
% Expression for Loglikelihood

function [NegSumLnPdf] = QRnegSumloglike(delta,y,x,beta,p)
%
% This function was earlier named as QRloglikelihood, when working in
% Rahman(2016).
% Output
%--------------------------------------------------------------------------
% NegSumLnPdf : Negative sum of the log-likelihood
% Input
% delta     : cut-points, a column vector
% y         : observed dicrete values, a column vector
% x         : covariate matrix including a column of ones
% beta      : Gibbs draw of beta, a column vector
% p         : quantile value
%--------------------------------------------------------------------------

J          = size(unique(y),1);           % number of outcomes
n          = size(y,1);
lnpdf      = zeros(n,1);

% Check function
if J<4
   error('Number of outcomes need to be ge 4 ');
end

expdelta   = exp(delta);                    % for J=4, expdelta is 2x1
gammaCp    = zeros(size(delta,1)+1,1);      % for J=4, gamma =[0 g1 g2]';
% Do not use gamma, its a function in Matlab

for j = 2:J-1
    gammaCp(j)  = sum(expdelta(1:j-1,1));
end
allgammaCp      = [-Inf; gammaCp; Inf];
mu              = x*beta;

% Using the AL distribution, alcdf(x,mu,sigma,p)
%--------------------------------------------------------------------------
for i = 1:n
    meani = mu(i);
    if y(i)==1
        lnpdf(i) = log( alcdf(0,meani,1,p));
    elseif y(i)==J
        lnpdf(i) = log(1 - alcdf(allgammaCp(J),meani,1,p));
    else
        lnpdf(i) = log( alcdf( allgammaCp(y(i)+1), meani,1,p) - ...
                        alcdf( allgammaCp(y(i)), meani,1,p)    );
    end
end
        
% % Using the Standard AL distribution
% for i = 1:n
%     if y(i) == 1
%         z1       = -mu(i);
%         lnpdf(i) = log(alcdfStd(z1,p));
%         
%     elseif y(i) == J
%         z2       = allgammaCp(J)-mu(i);
%         lnpdf(i) = log(1-alcdfStd(z2,p));
%     else
%         z3       = allgammaCp(y(i)+1)  - mu(i);
%         z4       = allgammaCp(y(i))    - mu(i);
%         lnpdf(i) = log(alcdfStd(z3,p)  - alcdfStd(z4,p));
%     end
% end

NegSumLnPdf  = -sum(lnpdf);

end
        
        
        