function [Objective, ConstraintViolations, UserData, ErrorConstraintViolation, ...
    ObjectiveEvaluationTime, ObjectiveNargout] = callObjFcn(this, X)
%

%   Copyright 2016-2022 The MathWorks, Inc.

if ~isempty(this.PrivOptions.ObjectiveNargout)
    % nargout is known. Call ObjectiveFcn normally.
    ObjectiveNargout = this.PrivOptions.ObjectiveNargout;
    [Objective, ConstraintViolations, UserData, ErrorConstraintViolation, ObjectiveEvaluationTime] ...
        = callObjNormally(this, X);
else
    % nargout is unknown. Try nargout=3:
    StartTic = tic;
    ErrorConstraintViolation = -1;
    try
        [Objective, ConstraintViolations, UserData] = this.ObjectiveFcn(conditionalizeX(this, X));
    catch msg
        % nargout may be < 3.
        % Set nargout based on NumCoupledConstraints:
        ObjectiveNargout = nargoutFromNumConstraints(this.PrivOptions.NumCoupledConstraints);
        this.PrivOptions.ObjectiveNargout = ObjectiveNargout;
        % nargout is now known. Call ObjectiveFcn normally.
        [Objective, ConstraintViolations, UserData, ErrorConstraintViolation, ObjectiveEvaluationTime] ...
            = callObjNormally(this, X);
        return;
    end
    % Calling with nargout=3 succeeded. Set nargout and finish up.
    ObjectiveNargout = 3;
    [Objective, ConstraintViolations, ErrorConstraintViolation, ObjectiveEvaluationTime] ...
        = finishObjEval(this, Objective, ConstraintViolations, -1, StartTic);
end
end

function ObjectiveNargout = nargoutFromNumConstraints(NumCoupledConstraints)
% We know nargout < 3
if NumCoupledConstraints > 0
    ObjectiveNargout = 2;
else
    ObjectiveNargout = 1;
end
end