function y = llk_ose(theta, Y, X2, istar, mats, rlb, dt, index)
% log-likelihood of srtsm combined with falling stars 
% istar: proxy of \tau
% X2:    First three PCs 
% 15 elements in theta:
%                   1    kinfQ
%                   2:4  dlamQ   d
%                   5:6  pbar
%                   7:8  gamma
%                   9:14 lower triangular of sigma     
%                   15   sigtau^2
T = size(Y,1);
J = mats/dt;
j = length(J);
N = 3;
% parameterization
pars = theta2pars_ose(theta);
kinfQ = pars.kinfQ;
lamQ =  pars.lamQ;
omega = pars.omega;
sigtau2 = pars.sigtau2;
gamma = [pars.a; 1-sum(pars.a)];
Xbar = [pars.p; -sum(pars.p)];
Sigma_tilde = omega - gamma*gamma'*sigtau2;

if invalidCovMat(Sigma_tilde)
    y = 1e8 ;
    return
end

loads = SRTSM_loadings2(kinfQ, diag(lamQ), omega, mats, dt) ;
aJ = loads.an;
bJ = loads.bn;
sigmasJ = loads.SigmaQ;

% Q-Likelihood
yields_m = Gsr(X2,aJ,bJ,sigmasJ,rlb);  % Txj
yields_error = Y - yields_m;  % Txj
yields_error_square = yields_error.^2;
% Compute sigma_e saure
sige2 = sum(yields_error_square,'all')/(T*(j-N));
llkQ = -0.5*(j-N)*log(2*pi*sige2) -0.5*sum(yields_error_square,2)/sige2; % Tx1
llkQ = llkQ(2:end);

% P-Likelihood
Xtilde = X2 - repmat(Xbar',T,1) - istar * gamma';  % Tx3
Mdl = varm(3,1);
Mdl.Constant = zeros(3,1);
var1 = estimate(Mdl, Xtilde);
Phi = cell2mat(var1.AR);
if max(abs(eig(Phi)))>0.999
    Phi = makestationary(Phi);
end
innovations = Xtilde(2:end,:)' - Phi * Xtilde(1:end-1,:)';  % 3x(T-1)
llkP1 = -0.5*N*log(2*pi) - 0.5* log(det(Sigma_tilde)) -0.5* sum(innovations.* (Sigma_tilde\innovations),1); % (T-1)x1
llkP2 = -0.5*log(2*pi*sigtau2) - 0.5 * diff(istar).^2/sigtau2;
llkP = llkP1' + llkP2 ;

llf = llkQ + llkP;

if index == 0
    y = -sum(llf(2:end));
else
    y = pars;
    y.gamma = gamma;
    y.Xbar = Xbar;
    y.Sigma_tilde = Sigma_tilde;
    y.sige2 = sige2;
    y.Phi = Phi;
    y.aJ = aJ;
    y.bJ = bJ;
    y.sigmasJ = sigmasJ;
    y.llkQ = llkQ;
    y.llkP = llkP;
    y.llk = sum(llf(2:end));
    y.yields_error = yields_error;
    
end
    



