function out = jacob_cloop(m,c,y_d,v)
%JACOB_CLOOP Compute the jacobian with respect to the
%    state for a closed loop
%    
%    OUT = JACOB_CLOOP(M,C,YD,V) 
%    
%    See also: ALSO 
%    
%    

%MAN_PAGE_BEGIN
%
%   @purpose	Compute the jacobian with respect to the state for a closed loop
%
%   @synopsis	out = jacob_cloop(m,c,yd,v)
%   @description  
%
%   @see also 
%
%MAN_PAGE_END

x_m = get(m,'state');
x_c = get(c,'state');

u = zeros(1,get(m,'n_in') - length(v));

r_m = [x_m v u];
y = eval(m,r_m);

r_c = [x_c y_d y];
u = eval(c,r_c);

r_m = [x_m v u];	%Update the regressor with the new values

% out = jacobian = [J1 J2;J3 J4]

for i=1:get(m,'n_state'),
	jms(i,:) = jacob_s_inputs(m,r_m,i);
end

for i=1:get(m,'n_out'),
	jmo(i,:) = jacob_inputs(m,r_m,i);
end

for i=1:get(c,'n_state'),
	jcs(i,:) = jacob_s_inputs(c,r_c,i);
end

for i=1:get(c,'n_out'),
	jco(i,:) = jacob_inputs(c,r_c,i);
end

J1 = statepart(m,jms) + inputpart(m,jms) * inputpart(c,jco) * statepart(m,jmo);
J2 = inputpart(m,jms) * statepart(c,jco);
J3 = inputpart(c,jcs) * statepart(m,jmo);
J4 = statepart(c,jcs);

out = [J1 J2; J3 J4];

function x = inputpart(m,r)

% By Antoine Duchateau. All Rights Reserved.
% Written: 11/05/99


x = r(:,1+m.n_state:end);

function x = statepart(m,r)

% By Antoine Duchateau. All Rights Reserved.
% Written: 11/05/99



x = r(:,1:m.n_state);
