#! /bin/sh

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

# Bourne shell script: cse_r2m
# Reduce constrained-state to simulab  constrained-state equations  
# P.J.Gawthrop 14 June 1991, 12 Jan 1994, April 1994.
# Copyright (c) P.J.Gawthrop 1991, 1994.

# Output must be filtered by matlab_tidy.

#Inform user
echo Creating $1_cse.m

# Remove the old log file
rm -f cse_r2m.log

# Use reduce to accomplish the transformation
reduce >cse_r2m.log << EOF

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

%Read the reduce  constrained-state equations   file
in "$1_cse.r";

%Read the reduce  substitution file
in "$1_subs.r";

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

%Read the parameter file
%%in "$1_sympar.r";


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

ON NERO;        % Suppress zero elements

OUT "$1_cse.m";

%Headings - Simulab style
%(Note. The ;; are deleted by for2mat)

write "function [sys,x0] = $1_cse(t,x,u,flag,xInitial);";

IF MTTNvar>0 THEN
BEGIN
  write "% Read in the parameters";
  write "global ...;;";
  FOR i := 1:MTTNvar DO
  BEGIN
     IF i<MTTNvar THEN write MTTVar(i,1), " ..."
                  ELSE write MTTVar(i,1), ";"
  END;
END;


write "%Constrained-state eqns in Simulab form for system $1;;";
write "%File $1_cse.m;;";
write "%Generated by MTT;;";


write "if nargin<4; flag=0; end;";	
write "if (abs(flag) == 1) | (abs(flag) == 3)";	
write "% Set up the State variables";
FOR i := 1:MTTNx DO
BEGIN
  write "MTTx", i, " = x(", i, ");";
END;

write "% Set up the Input variables";
IF MTTNu>0 THEN
FOR i := 1:MTTNu DO
BEGIN
  write "MTTu", i, " = u(", i, ");";
END;
write "end;";

%Fortran switches - one line expressions
OFF echo;
ON fort$
cardno!* := 1$
fortwidth!* := 100$
OFF period$

write "if abs(flag) == 1	%State derivative";

write "MTTE = zeros(", MTTNx, ",", MTTNx, ");";
MTTE := MTTE;
MTTEdx := MTTEdx;
write "sys = MTTE\MTTEdx;";

write "elseif abs(flag) == 3	%Outputs";
MTTy := MTTy;
write "sys = MTTy;";

write "elseif abs(flag) == 0	%Structure";
write "	sys = [", MTTNx, ",0,", MTTNy, ",", MTTNu, ",0,0]";
write "	if nargin<5; xInitial = zeros(", MTTNx, ",1); end;";
write "	x0  = xInitial;";
write "end;";
SHUT "$1_cse.m";

