function m = leaf_deletestages( m, varargin )
%m = leaf_deletestages( m )
%   Delete all the stage files for m, and optionally, the stage times.
%   Deleted files are gone at once, not put in the wastebasket.
%
%   Options:
%   'times'     Boolean.  Default false.
%   'stages'    Boolean.  Default true.
%
%   If 'stages' and 'times' are both true, then all stage files and stage
%   times will be deleted.
%
%   If 'stages' is true and 'times' is false, then the stage files will be
%   deleted, but all stage times will be retained.
%
%   If 'stages' is false and 'times' is true, then the stage files will be
%   preserved, and all times will be deleted for which there is no stage
%   file.
%
%   If 'stages' and 'times' are both false, nothing happens.
%
%   Equivalent GUI operation: the "Delete All Stages..." and "Delete Stages
%   and Times" commands on the Stages menu.
%
%   Topics: Project management.

    if isempty(m), return; end
    setGlobals();
    global gMISC_GLOBALS

    [s,ok] = safemakestruct( mfilename(), varargin );
    if ~ok, return; end
    s = defaultfields( s, 'times', false, 'stages', true );
    ok = checkcommandargs( mfilename(), s, 'exact', ...
            'times', 'stages' );
    if ~ok, return; end

    if (~s.stages) && (~s.times)
        % Nothing to do.
        return;
    end
    if isempty( m.globalProps.projectdir )
        % Not a project.
        return;
    end

    modeldir = getModelDir( m );
    if s.stages
        fprintf( 1, 'Deleting files from %s:\n', modeldir );
        filepattern = fullfile( modeldir, ...
                          [ m.globalProps.modelname gMISC_GLOBALS.stageprefix '*.mat' ] );
        filepattern2 = fullfile( modeldir, ...
                          'snapshots', ...
                          [ 'Stage' gMISC_GLOBALS.stageprefix '*.png' ] );
        filepattern3 = fullfile( modeldir, ...
                          'snapshots', ...
                          [ 'Stage' gMISC_GLOBALS.stageprefix '*.txt' ] );
        filenames = dirnames(filepattern);
        if isempty( filenames )
            fprintf( 1, 'No files found.\n' );
        else
            for i=1:length(filenames)
                if isempty( regexp( filenames{i}, '_static\.mat$' ) )
                    filetodelete = fullfile( modeldir, filenames{i} );
                    fprintf( 1, '%s\n', filenames{i} );
                    delete( filetodelete );
                end
            end
            % delete( filepattern );
        end
        delete( filepattern2 );
        delete( filepattern3 );
        if s.times
            m.stagetimes = [];
        end
        m.globalProps.savedrunname = '';
        m.globalProps.savedrundesc = '';
    else
        m.stagetimes = savedStages( m );
    end
    saveStaticPart( m );
end
