% This is a macro used to create the plots for Example 8.5
% - strict feedback system

% Clear memory
clear all

global tnext;  % used to help display the current time

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


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

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

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

cs(2).param = 'static';
cs(2).value = 0;
cs(2).fign = 1;
cs(2).lnsty = ':';

% Clear the figures
figure(1); clf

% Loop over the case studies
h = [];
for j=1:ns
  tnext = 0;   % used to dispay the current time

  % define default system/controller parameters
  x0 = [1; 0];
  th0 = zeros(1, 1);
  W = 0.1;
  theta = 2;
  eta = 1;
  sigma = 0.01;
  kappa = 1;
  Gamma = 2;
  d = sigma*theta*theta/2 + W*W/4/eta
  
  be = sqrt(d/2/kappa);
  bth = sqrt(2*d/sigma);
  Vr = 0.5*be*be + 0.5*bth*bth/Gamma
  errmax = sqrt(2*Vr)

  % used to easily pass simulation data
  SysData = struct('sys', 'sfb');
  SysData = setfield(SysData, 'x0', x0);
  SysData = setfield(SysData, 'th0', th0);
  SysData = setfield(SysData, 'kappa', kappa);
  SysData = setfield(SysData, 'eta', eta);
  SysData = setfield(SysData, 'Gamma', Gamma);
  SysData = setfield(SysData, 'sigma', sigma);
  SysData = setfield(SysData, 'theta', theta);
  SysData = setfield(SysData, 'update', cs(j).param);

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

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

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

  % Define the system outputs
  y = zeros(length(t), 3);  % 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); hold on;
  h = plot(t, y(:,1), cs(j).lnsty);
  set(h, 'LineWidth', 1.5);

end

% without adaptation
figure(1);
axis([0, tf, 0, 2]);
xlabel('t');
ylabel('x_1');
eval(sprintf('print -deps %s_a\n', exname));  % print out the results
