#! /bin/sh

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

# Bourne shell script: mtt_p2cc

# Pascal to .cc (for octave .oct files).
# P.J.Gawthrop Feb 2000
# Copyright (C) 2000 by Peter J. Gawthrop

    #$Id$	

## Extract the system and rep names.
sys=`mtt_sysname $1` 
rep=`mtt_repname $1` 
sys_rep=$sys"_"$rep

# Find system constants
Nx=`mtt_getsize $sys x` # States
Nu=`mtt_getsize $sys u` # Inputs 
Ny=`mtt_getsize $sys y` # Inputs 

# Create the representation code
mtt_p2C $sys $rep

# Inform user
echo Creating $sys_rep.cc

# Create the c++ code
# Heading
date=`date`

cat > $sys_rep.cc <<EOF
#include <octave/oct.h>

DEFUN_DLD ($sys_rep, args, ,
	   "Usage: $sys_rep(x,u,t,par)\n$sys_rep was generated by MTT on $date")
{
  ColumnVector mttx = args(0).vector_value ();
  ColumnVector mttu = args(1).vector_value ();
  double mttt = args(2).double_value ();
  ColumnVector mttpar = args(3).vector_value ();

EOF

case "$rep" in
    ode)
	echo "  ColumnVector mttdx ($Nx);" >> $sys_rep.cc
	;;
    odeo)
	echo "  ColumnVector mtty ($Ny);" >> $sys_rep.cc
	;;
    cse)
	echo "  ColumnVector mttdx ($Nx);" >> $sys_rep.cc
	;;
    cseo)
	echo "  ColumnVector mtty ($Ny);" >> $sys_rep.cc
	;;
    smx | smxa | smxax)
        Nxx=`echo "$Nx*$Nx" | bc`
	echo "  Matrix mtta ($Nx,$Nx);" >> $sys_rep.cc
	echo "  ColumnVector mttax ($Nx);" >> $sys_rep.cc
	;;
    *)
	
esac

#Extract Type info
echo '/* Types */'                >> $sys_rep.cc
grep typedef $sys_rep.C              >> $sys_rep.cc

#Extract the rep code converting [] to () and deleting mtt variables etc
#The awk part detects the begin and end of the relevant code.
echo "/* Representation $rep information */" >> $sys_rep.cc
gawk '{
  if ( (match($1,"}")==1)&&(NF>1)) writing=0;
  if ( (writing) && !(match($2,"mtt[a-z]")==1) ) print $0;
  if (match($1,"{")==1) writing=1;
}' <$sys_rep.C |\
sed 's/\[\([a-z0-9_]*\)\]\[\([a-z0-9_]*\)\]/(\1,\2)/g' |\
sed 's/\[\([a-z_0-9]*\)\]/(\1)/g' >> $sys_rep.cc

# Tail
cat >> $sys_rep.cc <<EOF

EOF

case "$rep" in
    ode)
        echo "return octave_value (mttdx);" >> $sys_rep.cc;
	;;
    odeo)
        echo "return octave_value (mtty); " >> $sys_rep.cc;
	;;
    cse)
        echo "return octave_value (mttdx);" >> $sys_rep.cc;
	;;
    cseo)
        echo "return octave_value (mtty); " >> $sys_rep.cc;
	;;
    smxa)
        echo "return octave_value (mtta); " >> $sys_rep.cc;
	;;
    smxax)
        echo "return octave_value (mttax); " >> $sys_rep.cc;
	;;
    *)
	
esac

# Terminating }
echo "}" >> $sys_rep.cc;

# Convert to octave loadable code
#echo Creating $sys_rep.oct
#mkoctfile $sys_rep.cc

