function [bdraw,log_lik] = carter_kohn_online(y,Z,Ht,Qt,m,p,t,B0,V0)
% Carter and Kohn (1994), On Gibbs sampling for state space models.

% Kalman Filter
bp = B0;
Vp = V0;
log_lik = 0;
bdraw = zeros(t,m);
for i=1:t
    R = Ht((i-1)*p+1:i*p,:);
    H = Z((i-1)*p+1:i*p,:);
    cfe = y(i,:)' - H*bp;   % conditional forecast error
    f = H*Vp*H' + R;    % variance of the conditional forecast error
    inv_f = inv(f);
    %log_lik = log_lik + log(det(f)) + cfe'*inv_f*cfe;
    btt = bp + Vp*H'*inv_f*cfe;
    Vtt = Vp - Vp*H'*inv_f*H*Vp;
    if i < t
        bp = btt;
        Vp = Vtt + Qt;
    end
    %bdraw(i,:) = mvnrnd(btt,Vtt,1);
    bdraw(i,:) = btt;
end

