#! /bin/sh

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

# Bourne shell script: mtt_p2oct

# Pascal to .oct (octave loadable binary).
# P.J.Gawthrop Feb 2000
# Copyright (C) 2000 by Peter J. Gawthrop

    #$Id$	

# Find system constants
Nx=`mtt_getsize $1 x`
Nu=`mtt_getsize $1 u`

# Create numpar code
mtt_p2C $1 numpar

# Create input code
mtt_p2C $1 input

# Create the representation code
mtt_p2C $1 $2

# Inform user
echo Creating $1_$2.cc

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

cat > $1_$2.cc <<EOF
#include <octave/oct.h>
 
DEFUN_DLD ($1_$2, args, ,
	   "$1_$2 was generated by MTT on $date")
{
  ColumnVector mttdx ($Nx);
  ColumnVector mttu ($Nu);
  ColumnVector mttx = args(0).vector_value ();

EOF

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

#Extract any additional mtt_tmp variables
awk 'BEGIN{
  writing = 1;
}
{
  if (match($1,"mtt")==1) writing=0;  
  if ( (writing)&&(match($0,"mtt_t[0-9]")>0) ) print $0;
}' < $1_$2.C >> $1_$2.cc

#Extract the numpar code
echo '/* Numerical parameters */' >> $1_$2.cc
awk '{
  if ($1=="}") writing=0;
  if (writing) print $0;
  if ($1=="{") writing=1;
}' <$1_numpar.C >> $1_$2.cc

#Extract the input code converting [] to ()
echo "/* Input information */" >> $1_$2.cc
awk '{
  if ($1=="}") writing=0;
  if (match($1,"mtt")==1) writing=1;
  if (writing) print $0;
}' <$1_input.C |\
sed 's/\[\([0-9]*\)\]/(\1)/g' >> $1_$2.cc


#Extract the rep code converting [] to ()
echo "/* Representation $2 information */" >> $1_$2.cc
awk '{
  if ($1=="}") writing=0;
  if (match($1,"mtt")==1) writing=1;
  if (writing) print $0;
}' <$1_$2.C |\
sed 's/\[\([0-9]*\)\]/(\1)/g' >> $1_$2.cc

# Tail
cat >> $1_$2.cc <<EOF

  return octave_value (mttdx);
}
EOF

# Convert to octave loadable code
echo Creating $1_$2.oct
mkoctfile $1_$2.cc
