function Stop = plotMinObjective(bo, State)
%plotMinObjective     PlotFcn for plotting the minimum observed
%Objective versus the number of function evaluations.
%   Stop = plotMinObjective(bo, State) plots the minimum
%   observed Objective versus the number of function
%   evaluations.
%
% See also: BAYESOPT, BAYESIANOPTIMIZATION
%

%   Copyright 2016-2022 The MathWorks, Inc.

persistent Axes1 Curves1;
narginchk(2,2);
[Title1, XLabel1, YLabel] = textInMinObjectivePlot(bo.PrivOptions.BayesOptPrint, bo);

Stop = false;
set(0, 'defaultfigureunits', 'pixels');     % Make sure units are pixels
switch State
    case 'initial'
        f = figure('Tag','bayesopt.MinObjective');
        Axes1 = axes(f);
        title(Axes1, Title1);
        xlabel(Axes1, XLabel1);
        ylabel(Axes1, YLabel);
        Axes1.YAxisLocation='right';
        Curves1 = {};
    case {'iteration', 'done'}
        cellfun(@delete, Curves1);
        Curves1 = plotMinObjective(bo.PrivOptions.BayesOptPrint, bo, Axes1, Curves1);
    case 'standalone'
        f = figure('Tag','bayesopt.MinObjective');
        SAxes1 = axes(f);
        title(SAxes1, Title1);
        xlabel(SAxes1, XLabel1);
        ylabel(SAxes1, YLabel);
        SAxes1.YAxisLocation='right';
        plotCurve(1:numel(bo.ObjectiveMinimumTrace), bo.ObjectiveMinimumTrace, SAxes1, 'b');
        if all(isnan(bo.EstimatedObjectiveMinimumTrace))
            legend(SAxes1, {bayesoptim.infoString('MinObsObj')}, 'Location', 'best');
        else
            plotCurve(1:numel(bo.ObjectiveMinimumTrace), bo.EstimatedObjectiveMinimumTrace, SAxes1, 'g');
            legend(SAxes1, {bayesoptim.infoString('MinObsObj'), bayesoptim.infoString('EstMinObj')},...
                'Location', 'best');
        end
end

    function Curve = plotCurve(X, TraceToPlot, Axes, color)
        HoldOff = bayesoptim.holdOn(Axes);
        Curve = plot(Axes, X, TraceToPlot, ['-' color 'o'], 'MarkerSize', 2);
    end

end
