#!/bin/sh

     ###################################### 
     ##### Model Transformation Tools #####
     ######################################

# Bourne shell script: def2write.r
# Generates r code to write matrices
# Copyright (C) 2000 by Peter J. Gawthrop

###############################################################
## Version control history
###############################################################
## $Id$
## $Log$
## Revision 1.13  2002/07/10 17:43:05  geraint
## Added feature [ 562453 ] Optimisation of algebraic equations.
##
## Revision 1.12  2002/06/28 10:13:40  geraint
## Includes fix_c.r in ese2rdae and def2write_r to eliminate occurrances of x**y.
##
## Revision 1.11.2.1  2002/06/05 11:14:51  geraint
## ae.r now generated using def2write_r like cse?.r
## fix_c.r called at ese2rdae stage so that pow gets fixed in ae.r.
##
## Revision 1.11  2002/05/17 09:14:58  geraint
## Optimises each line in a separate session. Allows larger models to be built.
##
## Revision 1.10  2002/04/28 18:41:27  geraint
## Fixed [ 549658 ] awk should be gawk.
## Replaced calls to awk with call to gawk.
##
## Revision 1.9  2001/07/27 23:29:10  geraint
## Optimises only when requested (-opt).
##
## Revision 1.8  2001/07/13 04:54:04  geraint
## Branch merge: numerical-algebraic-solution back to main.
##
## Revision 1.7.2.1  2001/05/04 04:07:24  geraint
## Numerical solution of algebraic equations.
## sys_ae.cc written for unsolved inputs.
## Solution of equations using hybrd from MINPACK (as used by Octave fsolve).
##
## Revision 1.7  2001/04/11 09:44:26  gawthrop
## Fixed cc and c problems to do with pow(x,y) and integers
## mtt/lib/reduce/fix_c.r is included in rdae2dae and cse2smx_lang for
## -c, -cc and -oct options
##
## Revision 1.6  2000/11/29 20:48:53  peterg
## Zapped unnecessary Npar creation
##
## Revision 1.5  2000/11/09 10:12:24  peterg
## Removed debugging line
##
## Revision 1.4  2000/10/14 16:19:54  peterg
## Just optimize one line at a time ...
##
## Revision 1.3  2000/10/11 09:07:17  peterg
## Added csex rep (cse without E)
##
## Revision 1.2  2000/10/10 21:02:17  peterg
## Added cse reps
##
## Revision 1.1  2000/10/10 09:07:32  peterg
## Initial revision
##
###############################################################

optimise=''
while [ -n "`echo $1 | grep '^-'`" ]; do
    case $1 in
	-optimise)
	    opt='-optimise'
	    optimise_msg=' with optimisation' ;;
	-fixcc )
	    include=`echo 'in "'$MTT_LIB'/reduce/fix_c.r";'` ;;
	*)
	    echo "$1 is an invalid argument - ignoring" ;;
    esac
    shift
done

sys=$1 # System name
rep=$2 # System representation

# Inform User
echo Creating $1_$2_write.r $optimise_msg

# Find system constants
Nx=`mtt_getsize $sys x` # States
Nxx=`mtt_getsize $sys xx` # States x States
Nu=`mtt_getsize $sys u` # Inputs 
Ny=`mtt_getsize $sys y` # Outputs 
Nyz=`mtt_getsize $sys yz` # Zero outputs
#Npar=`wc -l $sys\_sympar.txt | gawk '{print $1}'`

# Set up representation-specific stuff
case $rep in
    ae)
	matrices='Yz'
	ns="$Nyz"
	ms="1"
	;;
    cse)
        matrices='EdX E'
        ns="$Nx $Nx"
        ms="1 $Nx"
	;;
    csex)
        matrices='EdX'
        ns="$Nx"
        ms="1"
	;;
    cseo)
        matrices='Y'
        ns="$Ny"
        ms="1"
	;;
    lde)
        matrices='L'
        ns="$Nyz"
        ms="1"
	;;
    ldeo)
        matrices='Y Yz'
        ns="$Ny $Nyz"
        ms="1 1"
	;;
    ode)
        matrices='dX'
        ns="$Nx"
        ms="1"
	;;
    odeo)
        matrices='Y'
        ns="$Ny"
        ms="1 1"
	;;
    sm)
        matrices='A B C D'
        ns="$Nx $Nx $Ny $Ny"
        ms="$Nx $Nu $Nx $Nu"
	;;
    *)
        echo def2write_r: representation $rep not recognised
        exit
esac


mtt_fix_integers ()
{
    gawk -F":=" -v RS="$" -v ORS="$\n" '
(NF == 1) {
	print $0
}
(NF > 1) {
	lhs=$1 ;
	rhs=$2" " ;
	rhs1 = gensub ( /([^A-Za-z_0-9\.\+])([0-9]+)([^\.0-9])/ , "\\1\\2.0\\3" , "g", rhs );
	rhs2 = gensub ( /([^e]\+)([0-9]+)([^\.0-9])/ , "\\1\\2.0\\3" , "g", rhs1 );
	rhs3 = gensub ( /([^A-Za-z_0-9\.\+])([0-9]+)e([0-9]+).0([^\.0-9])/ , "\\1\\2\\3\\4" , "g" , rhs)
	printf "%s:=%s$\n", lhs, rhs3 ;
    }'
}

mtt_optimise ()
{
    sys="$1"
    lhs="$2"
    rhs="$3"
    
    crr="${sys}_cr.r"
    dae="${sys}_dae.r"
    tmp="mtt_optimise.tmp"
    tmp2="mtt_optimise2.tmp"
    tmp3="mtt_optimise3.tmp"
    
    {
	cat <<EOF
off echo$
load scope$
on double$
on noconvert$
on rounded$
off int$
off nat$
$include

out "$tmp2"$
EOF
    } > $tmp
    
    echo "optimize" >> $tmp
    grep -i -e "^$lhs" $dae |\
	sed -e 's/;/\ INAME\ mtt_tmp/g' |\
	sed -e 's/:=/:=/g' >> $tmp
    {
	cat <<EOF

shut "$tmp2"$
EOF
    } >> $tmp
    echo "%%% $lhs %%%" >> def2write_r1.log
    ${SYMBOLIC:-reduce} < $tmp >> def2write_r1.log 2>> def2write_r2.log
    cat $tmp2 | gawk -v RS=';' '($2 == ":=") {print $0}' > $tmp3
    cat $tmp3 | mtt_fix_integers
    rm -f $tmp $tmp2 $tmp3
    return
}


# Remove log files
rm -f def2write_r1.log def2write_r2.log

# Write out the code
echo "" > $1_$2_write.r

if [ ${opt:-""} = "-optimise" ]; then
    echo 'off nat$'
#    echo 'on echo$'
else
    echo 'off echo$'
    echo 'load gentran$'
fi >> $1_$2_write.r

for matrix in $matrices; do
    n=`first "$ns"`; ns=`rest "$ns"` 
    m=`first "$ms"`; ms=`rest "$ms"`
    is=`n2m 1 $n`; 
    js=`n2m 1 $m`; 
    if [ $n -ge 1 ]; then
	for i in $is; do
	    for j in $js; do
		if [ ${opt:-""} = "-optimise" ]; then
		    name=`echo MTT$matrix'('$i','$j')'`
		    mtt_optimise $1 "$comma$name" "$name"
		    comma=''
		else
		    echo 'write'
		    name=`echo MTT$matrix'('$i','$j')'`
		    echo '  '$comma$name ':=' $name '$'
		fi >> $1_$2_write.r
	    done
	done
    fi
done
echo ';END;'                           >>$1_$2_write.r
