function retW = CalcOptCoxW(inEta,inCens,inRC)
%function retW = CalcOptCoxW(inEta,inCens,inRC)
% 
% Calculate the optimal weight matrix for Cox proportional hazards models.
%
% Input:
%   inEta: eta;
%   inCens: 0 if Y is not censored, 1 if censored;
%   inRC: ranks of observed failture times with ties the same rank;
%
% Output:
%   retW: nx1 weight vector for weight matrix W.
%
% Dabao Zhang
%
% Revised by:
%
% Copyright (c) 2013 by Dabao Zhang.


error(nargchk(3, 3, nargin));

% Compute the score: dL/dEta
bUnC = ~inCens;
expEta = exp(inEta);
%riskSum = flipud(cumsum(flipud(bUnC.*expEta)));
riskSum = flipud(cumsum(flipud(expEta)));
riskSum = riskSum(inRC(:,1));
invSum = cumsum(bUnC./riskSum);
invSum = invSum(inRC(:,2));
%tmpSc = bUnC - expEta.* InvSum;

% Compute the empirical Fisher Information: related to -d2L/dEta2
invSum2 = cumsum(bUnC./(riskSum.^2));
invSum2 = invSum2(inRC(:,2));
retW = expEta.*invSum-(expEta.^2).*invSum2;

% Any protection on retW?
retW(abs(retW)<eps) = eps;
retW = retW./sum(retW);
