function [beta2,errors,problem]=carterkohn1(beta0,p00x,hlast,Q,Y,X)

%%Step 1 Set up matrices for the Kalman Filter
ns=cols(beta0);
t=rows(Y);
beta_tt=zeros(t,ns);          %will hold the filtered state variable

ptt=zeros(t,ns,ns);    % will hold its variance
mu=0;
F=eye(ns);
%initialise the state variable
beta11=beta0; 
p11=p00x;



for i=1:t
    x=X(i,:);
    R=hlast(i+1);
    %Prediction
beta10=beta11;
p10=p11+Q;
yhat=(x*(beta10)')';                                               
eta=Y(i,:)-yhat;
feta=(x*p10*x')+R;
%updating
K=(p10*x')*invpd(feta);
beta11=(beta10'+K*eta')';
p11=p10-K*(x*p10);

ptt(i,:,:)=p11;
beta_tt(i,:)=beta11;

end
%%%%%%%%%%%end of Kalman Filter%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


% Carter and Kohn Backward recursion to calculate the mean and variance of the distribution of the state
%vector
problem=0;
beta2 = zeros(t,ns);   %this will hold the draw of the state variable
wa=randn(t,ns);
errors=zeros(t,1);
problemc=0;

i=t;  %period t
p00=squeeze(ptt(i,:,:)); 
rc=rcond(p00);
if rc<1e-14 || isnan(rc)
  p00=p00x;
    problem=1;
end
beta2(i,:)=beta_tt(i:i,:)+(wa(i:i,:)*cholx(p00));   
errors(i,:)=Y(i,:)-X(i,:)*beta2(i,:)';
%periods t-1..to 1

for i=t-1:-1:1
pt=squeeze(ptt(i,:,:));

 iFptF=invpd(pt+Q);
% iFptF=invpd(F*pt*F'+Q);

bm=beta_tt(i:i,:)+(pt*iFptF*(beta2(i+1:i+1,:)-mu-beta_tt(i,:))')';  

pm=pt-pt*iFptF*pt; 

rc=rcond(pm);
if rc<1e-14 || isnan(rc)
    pm=p00x;
    problem=1;
end

beta2(i:i,:)=bm+(wa(i:i,:)*cholx(pm));  
errors(i,:)=Y(i,:)-X(i,:)*beta2(i,:)';

end
