function xp=fRic(t,x)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%       
% function xp=fRic(t,x)
% Right hand side to the "generalized"
% Riccati equations.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%

global ti tf 

global A B C Q0 Qref R S

% Fixing reverse time 

t=tf-(t-ti);


% The Cost functional

yref=(1-cos(1*pi*t/tf))*5;

Rinv=inv(R);

Q=C'*Qref*C;
f=(-yref'*Qref*C)';


% The Riccati variables

n=length(A);
[P,q,c]=XtoP(x,n);

% The Riccati equation

Pp=-Q-P*A-A'*P+ (B'*P+S')'*Rinv*(B'*P+S');
qp=-f+(B'*P+S')'*Rinv*B'*q-A'*q;
cp=q'*B*Rinv*B'*q;

xp=PtoX(Pp,qp,cp);


% Reversing flow to solve in reverse time
xp=-xp;