function [L,THIS,OPT,VSTAR] = objfunc(P,THIS,S,OPT)

if isempty(P)
    L = [];
    VSTAR = [];
    return
end

P = P(:).';
L = 0;
if S.isprior
    L = 0;
    for j = find(S.priorindex)
        L = L - S.prior{j}(P(j));
        if isinf(L)
            break
        end
    end
end
if isfinite(L)
    % Assign current parameters to the rhsmodel object. The data
    % array `X` gets updated inside `kalman`.
    THIS.Assign(1,S.passignpos) = P(1,~S.passignposnan);
    THIS.stdcorr(1,S.pstdcorrpos) = P(1,~S.pstdcorrposnan);
    [K,VSTAR] = kalman(THIS,S.A,S.X,S.sy,S.o,OPT);
    L = L + K;
else
    L = 1e10;
end

end