#! /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?

# 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

mtt_matrix := MTTYY;
mtt_matrix_n := MTTNY*(MTTGPCNy+1);
mtt_matrix_m := 1;
mtt_matrix_name := Y;
in"$MTTPATH/trans/matlab_matrix.r";

OUT "$1_obs.m1";

write "function Y = $1_obs(x,u)";
write "%GPC O function in matlab form for system $1;;";
write "%File $1_obs.m;;";
write "%Generated by MTT;;";

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

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);";


SHUT "$1_obs.m1";

GENTRANOUT "$1_obs.m3";
write "%"; 
write "% Translate the expression for Y";
matlab_matrix(); 
GENTRANSHUT "$1_obs.m3";

EOF

# Create the globals
sympar2global_txt2m $1> $1_obs.m2

# Change name
echo 'Y = mtt_matrix;' > $1_obs.m4
# Put together the pieces
cat   $1_obs.m? >$1_obs.m

rm -f $1_obs.m?



