#! /bin/sh

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

# Bourne shell script: p2C

# Pascal to a c program - intermediate step for mtt_p2oct
# P.J.Gawthrop Feb 2000
# Copyright (C) 2000 by Peter J. Gawthrop

    #$Id$	


sys_rep="$1_$2"
begin="BEGIN{$sys_rep}"

# Inform user
# echo "Creating $1_$2.pas"

# Find system constants
Nx=`mtt_getsize $1 x`
Nxx=`mtt_getsize $1 xx`
Nu=`mtt_getsize $1 u`
Ny=`mtt_getsize $1 y`

Npar=`wc -l $1_sympar.txt | awk '{print $1}'`


echo "PROCEDURE $1_$2;" > $1_$2.pas
echo "TYPE"             >>$1_$2.pas
echo "    StateVector  = ARRAY[1..$Nx] OF REAL;"        >>$1_$2.pas
echo "    StateMatrix  = ARRAY[1..$Nx,1..$Nx] OF REAL;" >>$1_$2.pas
echo "    StateMatrixVector  = ARRAY[1..$Nxx] OF REAL;" >>$1_$2.pas
echo "    InputVector  = ARRAY[1..$Nu] OF REAL;"        >>$1_$2.pas
echo "    OutputVector  = ARRAY[1..$Ny] OF REAL;"       >>$1_$2.pas
echo "    ParameterVector  = ARRAY[1..$Npar] OF REAL;"  >>$1_$2.pas


# Create the predefined vars
echo "VAR"     >>$1_$2.pas
awk '{
       printf("%s,", $1)
     }
     END{print "JUNK : REAL;"}'< $1_sympar.txt     >>$1_$2.pas

if [ "$2" = "ode2odes" ]; then
    first='PROCEDURE'
    awk '
    {
    if (writing) print $0;
    if (i++==0) writing=1
    if (match($1,"PROCEDURE")==1) writing=0;
    }'  < $1_$2.p >>$1_$2.pas
else
    first='BEGIN'

 # Convert VAR format in the headings
    awk 'BEGIN{writing=1}
    {
    if (match($1,"BEGIN")==1) writing=0;
    if (writing) print $0;
    }'  < $1_$2.p | \
    sed \
	-e 's/PROCEDURE [a-zA-Z_0-9]*(VAR/VAR/' \
	-e 's/PROCEDURE [a-zA-Z_0-9]*;//' \
	-e 's/REAL);/REAL;/' \
	-e 's/OutputVector);/OutputVector;/' \
	-e 's/ParameterVector);/ParameterVector;/' \
	>>$1_$2.pas
fi

# Write out the actual code until the begining of the procedure
awk 'BEGIN{writing=0}
{
  if (match($1,first)==1) writing=1;
  if (writing) print $0;
  if (match($1,begin)==1) writing=0;

}' begin=$begin first=$first   < $1_$2.p  >>$1_$2.pas

# Write out the parameters
echo {Parameters}   >>$1_$2.pas
awk '{
       printf("  %s \t:= mttpar[%i];\n", $1, ++i);
     }'< $1_sympar.txt  >>$1_$2.pas

# Write out the actual code from the end of the procedure
awk 'BEGIN{writing=0}
{
  if (writing) print $0;
  if (match($1,begin)==1) writing=1;
}' begin=$begin   < $1_$2.p  >>$1_$2.pas

#echo "Creating $1_$2.C"
p2c -o $1_$2.C $1_$2.pas > mtt_p2C.log 2>> mtt_p2C.log


