function options = prepareOptionsForSolver(options, solverName)
%

%PREPAREOPTIONSFORSOLVER Prepare options for solver
%
%   OPTIONS = PREPAREOPTIONSFORSOLVER(OPTIONS,
%   SOLVERNAME) performs tasks to ensure the options are set up for use by
%   the solver. The following tasks are performed:-
%
%   * If a user has passed a SolverOptions object, first ensure that it is
%     a set of options for the solver. 
%
%   * If a user has passed a SolverOptions object, now extract the options
%     structure from the object.

%   Copyright 2012-2021 The MathWorks, Inc.

% If a user has passed a structure, we cannot tell whether a user wrote the
% code that passes the structure before or after 16a. In this case, we
% assume that the code was written before 16a and set TolFunValue to
% TolFun, if TolFunValue is not in options.  We also convert any string
% data types to character arrays.

if isstruct(options)
        
    fields = fieldnames(options);
    
    for i = 1:numel(fields)
        thisOpt = options.(fields{i});
        if isstring(thisOpt)
            if isscalar(thisOpt)
                options.(fields{i}) = char(thisOpt);
            else
                options.(fields{i}) = cellstr(thisOpt);
            end
        end
    end
    
    if isfield(options, 'TolFun') && ~isfield(options, 'TolFunValue')
        options.TolFunValue = options.TolFun;
    end 
    
end

% If a user has passed a SolverOptions object, first ensure that it is a
% set of options for the solver then extract the options structure from the
% object
if isa(options, 'optim.options.SolverOptions')
    options = convertForSolver(options, solverName);
    options = extractOptionsStructure(options);
end
