function Stop = saveToFile(bo, State)
%saveToFile     OutputFcn for saving a Bayesian Optimization to
%a file.
%   Stop = saveToFile(bo, State) saves the BayesianOptimization
%   instance 'bo' to a file. The file name is obtained from
%   bo.Options.SaveFileName.
%
% See also: BAYESOPT, BAYESIANOPTIMIZATION
%

%   Copyright 2016-2022 The MathWorks, Inc.

narginchk(2,2);
% Remove things that will cause a parallel pool to be opened
% upon load
bo.FantasyModels = [];
bo.Parallel = [];
% Do the save
Stop = false;
SaveFilename = bo.PrivOptions.SaveFileName;
prevFilename = sprintf('%s.PREV', SaveFilename);
try
    if exist(['./' SaveFilename], 'file')
        if exist(['./' prevFilename], 'file')
            delete(prevFilename);
        end
        copyfile(SaveFilename, prevFilename);
    end
    BayesoptResults = bo;
    save(SaveFilename, 'BayesoptResults', '-v7.3');
catch me
    bayesoptim.warn('SaveToFileFailed', SaveFilename);
    disp(me);
end
end
