#!/bin/sh -f

# set -x; # Enable debugging

ncibin=@NCIHOME@/bin
ncisolib=@NCIHOME@/solib
if [ x$LD_LIBRARY_PATH  = x"" ]
    then LD_LIBRARY_PATH=$ncisolib
else
    LD_LIBRARY_PATH=$ncisolib:$LD_LIBRARY_PATH
fi

usage() {
   echo "Usage: $0 [-o outputfile] [-keep]"
   echo "       [-v] [-ast astfile] file.strl"
   echo "  Create a suif file from the input Esterel file."
   echo "  -ast dumps a textual representation of the AST to the given file,"
   echo "       or stdout if file is \"-\"."
   exit 1;
}

keep=0

prog=program
outputfile=""
pipeline=""
require=""
default_ext=.suif

defines=""

tmpfile=$$.drv
verbose=0

while [ ! -z "$1" ];
  do case x"$1" in 
    x-v)  verbose=1
      shift ;;
    x-keep) keep=1
      shift ;;
    x-o) shift
      if [ -z "$1" ]
        then usage; fi
      outputfile="$1"
      shift ;;
    x-ast) shift
      if [ -z "$1" ]
        then usage; fi
      strl2suifoptions="$strl2suifoptions -ast $1"
      shift ;;
    x-*) 
      echo "Bad option $1"; 
      usage ;;
    *) break ;;
  esac
done

if [ -z "$1" ] 
    then usage; fi
if [ $# -ne 1 ]
    then echo "Error: Too many files in the input line"
    usage
fi

base=`basename $1 .strl`
if [ `basename $1` != $base.strl ]
    then echo "Error: Input file '$1' does not have the .strl suffix"
    usage
fi

base=`basename $1 .strl`

if [ x$outputfile = x"" ]
    then outputfile="$base"$default_ext
fi

rm -f $outputfile ${base}.cil ${base}.spre

cat <<EOF > $tmpfile
${require}
import basicnodes suifnodes
import strl2suif
strl2suif $strl2suifoptions $1
save $outputfile
EOF

if [ $verbose = 1 ]
    then echo $ncibin/suifdriver -f $tmpfile
fi
$ncibin/suifdriver -f $tmpfile 2>&1
if [ $? != 0 ]
   then echo "FAILED: $ncibin/suifdriver -f $tmpfile"
   exit 1
fi
if [ $keep -eq 0 ]
  then if [ $verbose = 1 ]
    then echo rm -f $base.spre $tmpfile
  fi
  rm -f $base.spre $tmpfile
fi


