function [L,THIS,S] = objfunc(P,THIS,S)
% OBJFUNC  [Not a public function] Evaluate objective function, usually minus log posterior.
%
% Backend IRIS function.
% No help provided.

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

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

P = P(:).';

L = 0;

if any(S.priorindex)
    % Evaluate minus log priors.
    for i = find(S.priorindex)
        L = L - S.prior{i}(P(i));
        if isinf(L)
            break
        end
    end
end

if ~isinf(L)
    THIS.Assign = S.assign;
    THIS.stdcorr = S.stdcorr;
    
    % Update model for new parameter values.
    [THIS,npath,sstatesuccess] = ...
        myupdatemodel(THIS,P,S.assignpos,S.stdcorrpos,S);
    
    if npath ~= 1 || ~sstatesuccess
        if strcmp(S.nosolution,'error')
            model.failed(THIS,npath,sstatesuccess,'estimate');
        else
            L = Inf;
        end
    else
        % Run minus log likelihood.
        % No extra output argument is required.
        K = S.minusloglik(THIS,S.data,[],S.loglikopt);
        % Sum up minus log priors and minus log likelihood.
        L = L + K;
    end
end

if isinf(L)
    % Although the imag part is zero (and hence causing no problems in
    % Optimization Toolbox or user-supplied optimisation procedure), this
    % will be still caught as a complex number in the posterior simulator
    % indicating that the draw is to be discarded.
    L = complex(1e10,0);
end

end