function [out,beta_tt]=...
    draw_data5_P(dataid0,beta0,P00,F,Q,EXO,mid)
%Carter and Kohn algorithm to draw the factor
T=rows(dataid0);
N=cols(dataid0);
ns=cols(P00);
beta_tt=zeros(T,ns);          %will hold the filtered state variable
ptt=zeros(T,ns,ns);    % will hold its variance
% %%%%%%%%%%%Step 6a run Kalman Filter
beta11=beta0;
p11=P00;
for i=1:T
      
nanid1=mid(i,1); %checks if data on G is missing
nanid2=mid(i,2);


 H=eye(N,ns);
 rr=zeros(1,N);
if nanid1==1 %missing m_1
 H(1,:)=0;
 rr(1)=1e10;  %big variance so missing data ignored
end

if nanid2==1 %missing m_2
 H(2,:)=0;
 rr(2)=1e10;  %big variance so missing data ignored
end

 R=diag(rr);
   
x=H;
MUx=zeros(1,ns);
MUx(1:N)=EXO(i,:);
    %Prediction
beta10=MUx+beta11*F';
p10=F*p11*F'+Q;
yhat=(x*(beta10)')';                                               
eta=dataid0(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
% Backward recursion to calculate the mean and variance of the distribution of the state
%vector
beta2 = zeros(T,ns);   %this will hold the draw of the state variable
bm2=beta2;
jv=1:N; %index of non singular block
jv1=(1:2); %state variables to draw, 3, 5 are lagged states
i=T;  %period t
p00=squeeze(ptt(i,jv1,jv1)); 
beta2(i,:)=beta_tt(i,:);
beta2(i,jv1)=mvnrnd(beta_tt(i:i,jv1),p00,1);%beta_tt(i:i,jv1)+(wa(i:i,jv1)*cholx(p00));   %draw for beta in period t from N(beta_tt,ptt)
f=F(jv,:);
%periods t-1..to .1
for i=T-1:-1:1
MUx=zeros(1,ns);
MUx(1:N)=EXO(i+1,:); 
mu=MUx(jv);
q=Q(jv,jv);
pt=squeeze(ptt(i,:,:));
ifptfq=invpd(f*pt*f'+q);
bm=beta_tt(i:i,:)+(pt*f'*ifptfq*(beta2(i+1:i+1,jv)-mu-beta_tt(i,:)*f')')';  
pm=pt-pt*f'*ifptfq*f*pt;  
beta2(i,:)=bm;
beta2(i:i,jv1)=mvnrndx(bm(jv1),pm(jv1,jv1),1);     %bm(jv1)+(wa(i:i,jv1)*cholx(pm(jv1,jv1)));  
bm2(i,:)=bm;
end

out=beta2(:,jv1); %draw of Qrtly data