#! /bin/sh

  ###################################### 
  ##### Model Transformation Tools #####
  ######################################
  
  ###############################################################
  ## Version control history
  ###############################################################
  ## $Id$
  ## $Log$
  ## Revision 1.1  2003/03/13 15:44:53  gawthrop
  ## The main transformation for sorted elementary equations
  ##
  ## Revision 1.3  2003/03/13 09:00:22  peterg
  ## Revised for new mtt_component_eqn arg list
  ##
  ## Revision 1.2  2003/03/11 10:16:03  peterg
  ## Removed NAME argument
  ##
  ## Revision 1.1  2003/03/11 10:08:49  peterg
  ## Initial revision
  ##
  ##
  ###############################################################

## cbg2seqn_m2r: Converts causal bond graph into sorted equations
## Copyright (C) 2003 by Peter J. Gawthrop

while [ -n "`echo $1 | grep '^-'`" ]; do
  case $1 in
	-I )
                info=info;;

	*)
		echo "$1 is an invalid argument - ignoring" ;;
  esac
  shift
done

infofile='mtt_info.txt';
strucfile=$1_struc.txt
outfile=$1_sese.r
make=mtt_make_sese.m
CD='%%%% ====='
## Inform user
echo Creating ${outfile}

## Header
create_header() {
cat<<EOF    
$CD File ${outfile}
$CD Created by MTT on `date`

EOF
}

## Setup states etc
set_known() {
  gawk '{
  name["state"]="x";
  name["input"]="u";

  if ($1==which) {
   printf("MTT%s_%s := MTT%s(%s,1);\n", name[$1], $4, name[$1], $2);
   }
}'  which=$1 < ${strucfile}      
}

## Setup outputs, derivatives etc
set_out() {
  gawk '{
  name["state"]="dx";
  name["output"]="y";

  if ($1==which) {
   printf("MTT%s(%s,1) := MTT%s_%s;\n", name[$1], $2, name[$1], $4);
   }
}'  which=$1 < ${strucfile}      
}


## Create the octave commands for state, output etc
create_octave() {
gawk '{
  if ($1==which) {
     printf("printf(\"\\n%s The %s equation for %s\");\n", CD, $1, $4);
     printf("[known] = mtt_component_eqn\\\n");
     printf("(\"%s\",1,mtt_other_causality(\"%s\"),known,\"\",\"\");\n", $4, $6);
   }
}' "CD=${CD}" which=$1 < ${strucfile}         
}

create_octave_header() {
cat <<EOF
## Octave commands to generate sese file
## Created by mtt on `date`

known = "";

EOF
}

## Header
create_header > ${outfile}
cat >> ${outfile}<<EOF
${CD} Set up the state and input variables

EOF
which_list="state input"
for which in ${which_list}; do
    set_known ${which} >> ${outfile}
done


## Create a file of octave commands
create_octave_header > ${make}
which_list="state output"
for which in ${which_list}; do
    create_octave ${which} >> ${make}
done


## Execute the m file
octave -q < ${make} >> ${outfile}

## Tail
cat >> ${outfile}<<EOF

${CD} Set up the state derivative and output variables

EOF
which_list="state output"
for which in ${which_list}; do
    set_out ${which} >> ${outfile}
done

cat<<EOF >> ${outfile}
END;
EOF

## Print info

if [ "$info" = "info" ]; then
  cat $infofile
fi
