function [Objective, ConstraintViolations, ErrorConstraintViolation, ObjectiveEvaluationTime] = finishObjEval(this, Objective, ConstraintViolations, ErrorConstraintViolation, StartTic)
% Check constraint violation dimensions
%

%   Copyright 2016-2022 The MathWorks, Inc.

if numel(ConstraintViolations) ~= this.PrivOptions.NumCoupledConstraints
    bayesoptim.err('ObjectiveNumConstraintsWrong',...
        numel(ConstraintViolations), this.PrivOptions.NumCoupledConstraints);
end
% Set illegal Objective and ConstraintViolation to NaN
Objective = iNanIfBad(Objective);
ConstraintViolations = arrayfun(@iNanIfBad, ConstraintViolations);
if isnan(Objective)
    ErrorConstraintViolation = 1;
end
% Record runtime
ObjectiveEvaluationTime = toc(StartTic);
end

function val = iNanIfBad(val)
% Error if val is not a numeric scalar. If it's not a finite real, return
% NaN.
if ~(isnumeric(val) && isscalar(val))
    bayesoptim.err('ObjectiveFailed');
elseif ~(isfinite(val) && isreal(val))
    val = NaN;
end
end