% This function defines the system dynamics for "sfbdir_ex1"

function [y] = dir_nl1_dyn(t, x, flag, SysData, fcnflag)

n = SysData.n;
p = SysData.p;
kappa = SysData.kappa;
Gamma = SysData.Gamma;

theta = 1;
epsilon = 0.01;

% Strip out the plant states
xi = x(1:n); xi = xi(:);
dxi = zeros(n, 1);     % pre-allocate
hat_theta = x((n+1):(n+p)); hat_theta = hat_theta(:);
dhat_theta = zeros(p, 1);  % pre-allocate

% Define the reference trajectory
r = 0;

% Define the control input
e1 = xi(1) - r;
u = -kappa*e1 - epsilon*sign(e1) - hat_theta*xi(1);

dFdth = [xi(1)];
u = u - dFdth*hat_theta;

switch (fcnflag)
case 'deriv'

  % Define the plant dynamics
  dxi(1) = epsilon*xi(1)*xi(1) + theta*xi(1) + u;

  % Define the adaptive controller dynamics
  dhat_theta = -Gamma*xi(1)*e1;

  % this may be used when things go unstable
  if (abs(xi(1)) > 100)
    dxi(1) = 0;
    dhat_theta = 0;
  end

  y = [dxi; dhat_theta];

case 'output'
  
  y = [xi(1); u];
end

