%--------------------------------------------------------------
% This function calculates the DCC-MIDAS likelihood.
% Input: Parameters, Standard residuals for two data series 
% reshaped correlation matrix.
% Output: The likelihood function.
% % Author  Ai Jun Hou 
%------------------------------------------------------------
%%


function f=dccgarchXNV_20140222(T, z10,z20,cor,macro,ratio,flg)


 %if T(1)+T(2)<1 && T(1)>0 && T(2)>0  && T(3)>1

w1=1;       % w1 for beta weights
if flg=='CR' % DCC MIDAS S-RC-X
    R=T(3);
    w2c=T(4); 
    w2e=T(5);% w2 for beta weights
    m=T(6);
    thetaC=T(7);
    thetaE=T(8);
elseif flg=='C' %DCC MIDAS RC-X
    R=0;
    w2c=T(3); 
    w2e=T(4);% w2 for beta weights
    m=T(5);
    thetaC=T(6);
    thetaE=T(7);
elseif flg=='R'% DCC MIDAS-S-X
    R=T(3);
    w2c=1; 
    w2e=T(4);% w2 for beta weights
    m=T(5);
    thetaC=0;
    thetaE=T(6);
  elseif flg=='T'% DCC MIDAS-S-C
    R=0;
    w2c=T(3); 
    w2e=1;% w2 for beta weights
    m=T(4);
    thetaC=T(5);
    thetaE=0;  
    
else          % DCC MIDAS-X
    R=0;
    w2c=1; 
    w2e=T(3);% w2 for beta weights
    m=T(4);
    thetaC=0;
    thetaE=T(5);
end    
    

%Caculate sample variance of series z1, z2 and covariance of z1and z2 and correlation between z1 and z2


lag=size(macro,2);
be_values_c=beta_weights(lag,w1,w2c);  % a vector of weights assigned to the reshaped 
be_values_e=beta_weights(lag,w1,w2e);                                    % corr. matrix 


z1=z10;
z2=z20;
g12=m+thetaE*(macro*be_values_e)+thetaC*cor*be_values_c;

Rho_bar=(exp(2*g12)-1)./(exp(2*g12)+1);

n=length(z1);

var_z1t=var(z1).*ones(n,1);
var_z2t=var(z2).*ones(n,1);
cov_z1z2=cov(z1,z2);
cov_z1tz2t=cov_z1z2(1,2).*ones(n,1);
%corr12=corr(z1,z2);


for i=2:n;
    
% %specify var_z1t, var_z2t, cov_z1tz2t
 var_z1t(i)=(1-T(1)-T(2))+T(1)*(z1(i-1)^2)+T(2)*var_z1t(i-1);
 if isnan(var_z1t(i))==1 
     var_z1t(i)=1;
 end    
 var_z2t(i)=(1-T(1)-T(2))+T(1)*(z2(i-1)^2)+T(2)*var_z2t(i-1);
if isnan(var_z2t(i))==1 
     var_z2t(i)=1;
 end    
 
 cov_z1tz2t(i)=((1-T(1)-T(2)-R)*Rho_bar(i,1)...
     +T(1)*z1(i-1)*z2(i-1)+T(2)*cov_z1tz2t(i-1))...
     +R*ratio(i-1);
if isnan(cov_z1tz2t(i))==1 
     cov_z1tz2t(i)=1;
 end    
 
end

%rho12=(cov_z1tz2t./sqrt(abs(var_z1t.*var_z2t)))';
rho12=(cov_z1tz2t./sqrt(abs(var_z1t.*var_z2t)));

%defining the determinant of correlation matrix and determinant of Dt

detrRt=(1-(rho12.^2));
detrRt=abs(detrRt);

%define the log likelihood function
 
 % f=sum((1/2)*(log(2*pi)+log(detrRt)+((z1.^2+z2.^2-2*rho12.*z1.*z2)./detrRt)-z1.^2-z2.^2)) ;
   
 pen=sum((var_z1t<0))+sum((var_z2t<0));

 
   f=sum((1/2)*(log(2*pi)+log(detrRt)+(z1.^2+z2.^2-2*rho12.*z1.*z2)./detrRt)+z1.^2+z2.^2)+10*pen;
 

   
if isnan(f)==1 || isinf(f)==1 
     f=10000000;
end
% [T]
 
 %else
  %  f= 10000000;   % smaller value than infinity
 %end

