function HESS = diffprior(prior,p)
% DIFFPRIOR  [Not a public function] Contributions of priors to gradient and hessian.
%
% Backend IRIS function.
% No help provided.

% -IRIS Toolbox.
% -Copyright (c) 2007-2012 Jaromir Benes.

%**************************************************************************

npar = numel(prior);
HESS = zeros(1,npar);
priorindex = ~cellfun(@isempty,prior);
for i = find(priorindex)
    try
        HESS(i) = prior{i}(p,'info');
    catch %#ok<CTCH>
        HESS(i) = numdiff_();
    end
end
HESS = diag(HESS);

% Nested functions follow.

    % @ *******************************************************************
    function hess = numdiff_()
        p0 = p(i);
        step = max([abs(p0),1])*eps()^(1/3);
        pp = p0 + step;
        pm = p0 - step;
        L0 = -prior{i}(p0);
        Lp = -prior{i}(pp);
        Lm = -prior{i}(pm); 
        h = (pp - pm)/2;
        hess = (Lp - 2*L0 + Lm) ./ (h^2);
    end
    % @ numdiff_().
    
end
