#! /bin/sh

# script uses Reduce + Scope to optimise an entire vector

system=$1
representation=$2

# error codes
E_REP_NOT_SUPPORTED=-19
E_FILE_NOT_EXIST=-20

case $representation in
    ae)
	matrix=yz ;
	nmatrix=`mtt_getsize $system yz` ;;
    ode)
	matrix=dx ;
	nmatrix=`mtt_getsize $system x` ;;
    cseo | odeo)
	matrix=y ;
	nmatrix=`mtt_getsize $system y` ;;
    *)
	exit $E_REP_NOT_SUPPORTED;;
esac

# Generate a command of the form
# optimise mtt?(1,1) :=: mtt?(1,1), mtt?(2,1) :=: mtt?(2,1), ..., INAME mtt_tmp$
command="optimize"
counter=1
while [ $counter -le $nmatrix ]; do
    command="$command mtt$matrix($counter,1) :=: mtt$matrix($counter,1),"
    counter=`expr $counter + 1`
done
command="$command INAME mtt_tmp$"

logfile=${system}_${representation}_global_optimisation.log
tmpfile=${system}_${representation}_global_optimisation.tmp
outfile=${system}_${representation}.r

if [ ! -f $outfile ]; then
    exit $E_FILE_NOT_EXIST
fi

# Use Reduce to perform the optimisation
${SYMBOLIC:-reduce} <<EOF > $logfile 2>&1
off nat$
in "${system}_def.r"$
matrix mtt$matrix($nmatrix,1)$
in "$outfile"$
load scope$
out "$tmpfile"$
$command
shut "$tmpfile"$
$end$
EOF

cp $outfile $outfile.unoptimised
cp $tmpfile $outfile.tmp
cat $tmpfile | mtt_fix_integers > $outfile
#cp $tmpfile $outfile
echo ";end;" >> $outfile

mtt_error_r $logfile
