function [m,ok] = leaf_recomputestages( m, varargin )
%m = leaf_recomputestages( m, ... )
%   Recompute a set of stages of the project, starting from the current
%   state of m.  If this is after any of the stages specified, those stages
%   will not be recomputed.
%
%   Options:
%       'stages'    A list of the stages to be recomputed as an array of
%                   numerical times.  The actual times of the saved stages
%                   will be the closest possible to those specified, given
%                   the starting time and the time step.  If this option is
%                   omitted, it will default to the set of stage times
%                   currently stored in m, which can be set by
%                   leaf_requeststages.
%
%   See also: leaf_requeststages
%
%   Topics: Simulation.

    if isempty(m), return; end
    [s,ok] = safemakestruct( mfilename(), varargin );
    if ~ok, return; end
    s = defaultfields( s, 'stages', m.stagetimes, 'plot', 1, 'handles', [] );
    ok = checkcommandargs( mfilename(), s, 'exact', ...
        'stages', 'plot', 'handles' );
    if ~ok, return; end
    if isempty( s.stages ), return; end
    
    stages = s.stages;
    s = rmfield( s, 'stages' );
    m.stagetimes = addStages( m.stagetimes, stages );
    saveStaticPart( m );
    
    startTime = m.globalDynamicProps.currenttime;
    stages = unique( stages( stages > startTime ) );
    stageindex = 1;
    args = cellFromStruct( s );
    while stageindex <= length(stages)
        atstage = m.globalDynamicProps.currenttime - stages(stageindex) > -m.globalProps.timestep/2;
        if atstage
            [m,ok] = leaf_savemodel( m, m.globalProps.modelname, m.globalProps.projectdir );
            if ok
                if isinteractive(m)
                    hh = guidata( m.pictures(1) );
                    remakeStageMenu( hh );
                end
            else
                fprintf( 1, 'Problem saving stage %f.\n', ...
                    mfilename(), ...
                    m.globalDynamicProps.currenttime );
                break;
            end
            if stageindex >= length(stages)
                return;
            end
            stageindex = stageindex+1;
        end
        [m,ok] = leaf_iterate( m, 1, args{:} );
        if ~ok
            fprintf( 1, 'Recompute stages stopped prematurely at time %f.\n', ...
                mfilename(), ...
                m.globalDynamicProps.currenttime );
            break;
        end
    end
end
