function [LIK, lik] = diffuse_kalman_filter(T,R,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol,riccati_tol)
% Computes the diffuse likelihood of a state space model.
%
% INPUTS
% T [double] mm*mm transition matrix
% R [double] mm*rr matrix
% Q [double] rr*rr covariance matrix of the structural innovations.
% H [double] pp*pp covariance matrix of the measurement errors (if H is equal to zero (scalar) there is no measurement error).
% Pinf [double] mm*mm matrix used to initialize the covariance matrix of the state vector.
% Pstar [double] mm*mm matrix used to initialize the covariance matrix of the state vector.
% Y [double] pp*smpl matrix of (detrended) data, where pp is the number of observed variables.
% start [integer] scalar, likelihood evaluation starts at 'start'.
% Z [double] pp*mm matrix, selection matrix or pp linear independant combinations of the state vector.
% kalman_tol [double] scalar, tolerance parameter (rcond).
% riccati_tol [double] scalar, tolerance parameter (riccati iteration).
%
% OUTPUTS
% LIK: likelihood
% lik: density vector in each period
%
% REFERENCES
% See "Filtering and Smoothing of State Vector for Diffuse State Space
% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
% Analysis, vol. 24(1), pp. 85-98).
% Copyright (C) 2004-2008 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
[pp,smpl] = size(Y);
mm = size(T,2);
a = zeros(mm,1);
dF = 1;
QQ = R*Q*transpose(R);
t = 0;
oldK = 0;
lik = zeros(smpl,1);
LIK = Inf;
% lik(smpl+1) = smpl*pp*log(2*pi);
notsteady = 1;
reste = 0;
while rank(Pinf,kalman_tol) && (t