#! /bin/sh

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

# Bourne shell script: obs_r2m
# Reduce GPC obs function to matlab
# P.J.Gawthrop 18 May 1991, 12 Jan 1994, April 1994, Dec 1994, July 1995
# Copyright (c) P.J.Gawthrop 1991, 1994.

# Inform user
echo Creating $1_obs.m

# Remove the old log file
rm -f obs_r2m.log
rm -f $1_obs.m?
rm -f $1_obsa.m

# Is the system affine (look in the _obs.r file
affine=`grep 'affine :=' $1_obs.r | gawk '{print $3}' | sed 's/;//'`


# Use reduce to accomplish the transformation
$SYMBOLIC >obs_r2m.log << EOF

%Read the reduce definitions file
in "$1_def.r";

%Set up the number of argument variables to zero in case the user has forgotten
MTTNVar := 0;

%Set default values - reset by obspar file.
MTTGPCNy := 2;
MTTGPCNu := 0;

%Read the parameters file
in "$1_obspar.r";

%Read the simplification file
in "$1_simp.r";

%Read the reduce state-space equations   file
in "$1_obs.r";


ON BigFloat, NumVal;
PRECISION 16; %Compatible with Matlab
OFF Nat;

ON NERO;        % Suppress zero elements

% Matrix output function
in"$MTTPATH/trans/matlab_matrix.r";

OUT "$1_obs.m2";

write "% Set up the State variables";
FOR i := 1:MTTNx DO
BEGIN
  write "mttx", i, " = x(", i, ");";
END;

IF affine=0 THEN 
BEGIN
write "%"; 
write "% Set up the inputs and input derivatives";
FOR i := 1:MTTNu DO
  BEGIN
    write "mttu", i, " = u(", i, ",1);";
    FOR j := 1:MTTGPCNu DO
    BEGIN
      write "mttu", i,j, " = u(", i, ",", j+1, ");";
    END;
  END;

%write "%"; 
%write "% Set up the Y matrix";
%write "Y = zeros(", mtt_matrix_n, ",1);";
END;


SHUT "$1_obs.m2";

IF affine=1 THEN 
BEGIN
  GENTRANOUT "$1_obs.m3";
  MTT_Matrix := MTTObs_o$ 
  MTT_Matrix_name := "MTTO_o"$
  MTT_Matrix_n := (MTTGPCNY+1)*MTTNy$
  MTT_Matrix_m := 1$
  matlab_Matrix()$
  GENTRAN O_o := mtt_matrix;

  MTT_Matrix := MTTObs_h$ 
  MTT_Matrix_name := "MTTO_h"$
  MTT_Matrix_n := (MTTGPCNy+1)*MTTNy$
  MTT_Matrix_m := (MTTGPCNu+1)*MTTNu$
  matlab_Matrix()$
  GENTRAN O_h := mtt_matrix;

  GENTRANSHUT "$1_obs.m3";
END
ELSE
BEGIN
  GENTRANOUT "$1_obs.m3";
  mtt_matrix := MTTYY$
  mtt_matrix_n := MTTNY*(MTTGPCNy+1)$
  mtt_matrix_m := 1$
  mtt_matrix_name := Y$
  matlab_matrix(); 
  GENTRAN YY := mtt_matrix;
  GENTRANSHUT "$1_obs.m3";
END;

EOF

if [ "$affine" = "1" ]; then
    lang_header $1 obs m x [o_o,o_h] > $1_obs.m1
else
    lang_header $1 obs m x,u yy > $1_obs.m1
fi

# Put together the pieces
matlab_tidy $1_obs.m2
matlab_tidy $1_obs.m3
cat   $1_obs.m? >$1_obs.m

rm -f $1_obs.m?







