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

% Clear memory
clear all

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


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


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


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

% define the case-studies
cs(1).param = 'blank';
cs(1).value = 0;
cs(1).fign = 1;    % run the default in the first window
cs(1).lnsty = '-';

cs(2).param = 'kappa';
cs(2).value = 50;
cs(2).fign = 2;    % the next two go in figure 2
cs(2).lnsty = '-';

cs(3).param = 'Gamma';
cs(3).value = 50*eye(p);
cs(3).fign = 2;
cs(3).lnsty = '-.';


% Clear the figures
figure(1); clf
figure(2); clf

% Loop over the case studies
for j=1:ns

  % define default system/controller parameters
  xi0 = [0; 0];
  th0 = zeros(p, 1);
  kappa = 10;
  eta = 1;
  sigma = 0.1;
  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, 'eta', eta);
  SysData = setfield(SysData, 'sigma', sigma);
  SysData = setfield(SysData, 'Gamma', Gamma);
  SysData = setfield(SysData, 'step_mag', 1); % step magnitude
  SysData = setfield(SysData, 'step_t', 1);   % step period

  % 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), 5);  % 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 = plot(t, y(:,1), cs(j).lnsty); hold on;
  set(h, 'LineWidth', 1.5);

end

% Finish plotting Figure 1
figure(1);
indx = 1:(length(t) - 1);  % dont plot the final step @ 4 seconds
h = plot(t(indx), y(indx,3), '--');
set(h, 'LineWidth', 1.5);
xlabel('t');
% print out the results
eval(sprintf('print -deps %s_a\n', exname));


% Finish plotting Figure 2
figure(2);
h = plot(t(indx), y(indx,3), '--');
set(h, 'LineWidth', 1.5);
xlabel('t');

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