function logLk=logLikKernel_MAI_VAR_SV(Y,A,Z,gs,sigmas)

%  Compute the log-likelihood kernel of the MAI-VAR-SV
%  
%  Specification is:
%
%  y_t     = A * Z_t     + u_t,  u_t i multnormal(0,Omega_t)
%
%  Y_t is nx1, A  is nxrp , Z_t is rpx1 , Omega_t is nxn
%
% Omega is triangularly decomposed, 
% and Omega_t=G_inv_t* diag(sigma_t)^2 *G_inv_t'
% where G_inv_t is the inverse of the triangular matrix with elements in g
% and ones in the diagonal
%
%  sample line:   logLk=logLikKernel_MAI_VAR_SV(Y,A,Z,gs,sigmas)
%
%  INPUTS:   Y is nxT ,  A is nxrp  , Z is rpxT,  
            %gs is mxT or mx1, sigmas is nxT
%
%  OUTPUTS: logLk
%  Author: Francesco Corsello, November 2015

[n,T]=size(Y);


u=Y-(A*Z);  %nxT

dom=zeros(1,T);
%ch_om=zeros(n,n,T);
u_star=zeros(n,T);

[Gs,Tg]=make_tril_A_pages(gs );

b_CV=Tg>1;
        
if not(b_CV)
    iGs=eye(n)/Gs;
end
    

% for t=1:T
% dom(t)=det(Omegas(:,:,t));
% %ch_om(:,:,t)=chol(Omegas(:,:,t),'lower');
% u_star(:,t)=chol(Omegas(:,:,t),'lower')\u(:,t);
% end

    for t=1:T
        if b_CV
            ch_om=  Gs(:,:,t) \diag( sigmas(:,t) )     ;
        else
            ch_om= iGs*diag(sigmas(:,t))     ;
        end
        dom(t)=prod(diag( ch_om ))^2;
        u_star(:,t)=ch_om\u(:,t);
    end


%ch_OM=spblkdiag(ch_om);
%U=vec(Y-(A*Z));

if any(dom<0)
    error('Some Covar Matrices have negative determinants!')
end



%old
%OMEGA= spblkdiag(Omegas);
%ch_OM=chol(OMEGA,'lower');



%U_star=ch_OM\U;
U_star=vec(u_star);

exp_arg=-0.5* (U_star'*U_star);
logLk=-0.5*    sum(log(dom))   + exp_arg;
   
 
 

 
 


