function[K1,K2,S]=doublex8(A,C,D,E,Q,sig)
%function[K1,K2,S]=doublex8(A,C,D,E,Q,sig)
%  Solves the robust filtering problem for the state space system
%
%   x' = A x + B u + D w
%   y  = C x       + E w
%   z  = H x + G u
% 
%   Q is H'H
%   Formulas assume D'E =0  (no cross products between state and
%   observer noises) 
%   sig < 0 indicates preference for robustness
%
%  The optimal filter is of the form
%  
%  \check x' = A \check x + B u + K1*(y-C*\check x) + K2* \check x
%
%  returns K1, K2, and the state covariance S
%
% Uses doubling algorithm as described in Anderson, et. al.
%
% Initializes with po=I.  The version is designed to find the optimal
% stable work solution in, for example,  
% `permanent income' models that don't satisfy the detectability condition.
%  See AHMS (Computational economics) for details.  The program
%  adapts the algorithm to the risk-sensitive specicfication of
%  Hansen-Sargent (IEEE, May, 1995)  
%
N=E*E';

ss=max(size(A));
v=eye(ss);
po=v;

J=C'*(N\C)+sig*Q;

t=v+J*po;
a0=t\(A');
b0=t\J;
g0=D*D'-po+A*po*a0;

tol=1e-15;
dd=1;

while dd>tol

a1=a0*((v+b0*g0)\a0);
b1=b0+a0*((v+b0*g0)\(b0*a0'));
g1=g0+a0'*g0*((v+b0*g0)\a0);



dd=norm(g1-g0)/norm(g0);

a0=a1;
b0=b1;
g0=g1;
end

gg1=g1+po;   %  gg1=g1+po % (changed from  paper)

S=gg1;     %  the steady state covariance matrix

K1 = (A*S/(v+J*S))*(C'/N); 
K2 = -sig*(A*S/(v+J*S))*Q; 
% ST=g1t;  %  this is the distorted value function of HS and Whittle
