% This is a macro used to create the plots for Example 7.1

% Clear memory
clear all

% Define the input file names
exname = 'sfbdir_ex1';    % the name of this macro
sysname = [exname, 'sys'];


% The simulation time (and step size for plotting)
t0 = 0;
tf = 1;
nits = 200;   % used for plotting not simulation step size
t = t0:(tf-t0)/nits:tf;

% Define the system size
n = 1;  % number of plant states
p = 1;  % number of approximator (controller) states


% This is what to vary for each case-study
ns = 4;
study = struct('param', 'name', 'value', 0, 'fign', 0, 'lnsty', '-');
cs(ns) = study;

% define the case-studies
cs(1).param = 'th0';
cs(1).value = 0;
cs(1).fign = 1;
cs(1).lnsty = '-';

cs(2).param = 'th0';
cs(2).value = -2;
cs(2).fign = 1;
cs(2).lnsty = ':';

cs(3).param = 'th0';
cs(3).value = -4;
cs(3).fign = 1;
cs(3).lnsty = '-.';

cs(4).param = 'th0';
cs(4).value = -6;
cs(4).fign = 1;
cs(4).lnsty = '--';


% Clear the figures
figure(1); clf

% Loop over the case studies
h = [];
for j=1:ns

  % Reset values according to the current case-study
  eval(sprintf('SysData.%s = cs(j).value;', cs(j).param));
  % define default system/controller parameters
  xi0 = [0.5];
  th0 = zeros(p, 1);
  kappa = 10;
  Gamma = 10*eye(p);

  % used to easily pass simulation data
  SysData = struct('n', n, 'p', p);
  SysData = setfield(SysData, 'xi0', xi0);
  SysData = setfield(SysData, 'th0', th0);
  SysData = setfield(SysData, 'kappa', kappa);
  SysData = setfield(SysData, 'Gamma', Gamma);

  % Reset values according to the current case-study
  eval(sprintf('SysData.%s = cs(j).value;', cs(j).param));

  % Define the system initial conditions
  x0 = [SysData.xi0; SysData.th0];

  % Run the simulation
  opts = '';
  fprintf('Running case-study #%d\n', j);
  [t, x] = ode23(sysname, t, x0, opts, SysData, 'deriv');

  % Define the system outputs
  y = zeros(length(t), 2);  % needs to be the size of the output vector
  for i=1:length(t);
    tmp = feval(sysname, t(i), x(i,:), '', SysData, 'output');
    tmp = tmp(:);  % make sure it fits
    y(i, :) = tmp';  
  end

  % Plot the results
  figure(cs(j).fign);
  h = [h; plot(t, y(:,1), cs(j).lnsty)]; hold on;
  
end


figure(1);
axis([0, 1, 0, 2]);
set(h, 'LineWidth', 2);
xlabel('t');
h = ylabel('x');
set(h, 'Rotation', 0);  % dont rotate variable name

% print out the results
eval(sprintf('print -deps %s_a\n', exname));
