function m = leaf_purgeproject( m, varargin )
% m = leaf_purgeproject( m )
%   Purge the project directory of generated files.
%   The movies directory and its entire contents will be deleted.
%   The snapshots directory and its entire contents will be deleted.
%   All stage files will be deleted.
%   No other files will be affected.
%
%   Options:
%       'recycle'    A boolean.  If true (the default) then deleted files
%                    are sent to the wastebin.  If false, they are
%                    irrevocably deleted immediately.
%       'confirm'    A boolean.  If true (the default is false), the user
%                    will be asked to confirm the operation.

    if isempty(m)
        return;
    end
    [s,ok] = safemakestruct( mfilename(), varargin );
    if ~ok, return; end
    s = defaultfields( s, 'recycle', true, 'confirm', false );
    ok = checkcommandargs( mfilename(), s, 'exact', 'recycle', 'confirm' );
    if ~ok, return; end
    
    modeldir = getModelDir( m );

    if isempty( modeldir )
        return;
    end
    if ~exist( modeldir, 'dir' )
        return;
    end
    
    if s.confirm
        result = queryDialog( {'Purge', 'Cancel'}, 'Purge project', ...
            'Are you sure?  This will delete the movies directory, the snapshots directory, and all stage files from the project.' );
        if result ~= 1
            fprintf( 1, 'Purge operation cancelled by user.\n' );
            return;
        end
    end

    oldrecycle = recycle();
    if s.recycle
        recycle( 'on' );
    else
        recycle( 'off' );
    end
    
    somethingDeleted = false;
    
    moviesdir = fullfile( modeldir, 'movies' );
    if exist( moviesdir, 'dir' )
        somethingDeleted = true;
        fprintf( 1, 'Deleting %s and all its contents.\n', moviesdir );
        try
            rmdir( moviesdir, 's' );
        catch
        end
    end
    
    snapshotsdir = fullfile( modeldir, 'snapshots' );
    if exist( snapshotsdir, 'dir' )
        somethingDeleted = true;
        fprintf( 1, 'Deleting %s and all its contents.\n', snapshotsdir );
        try
            rmdir( snapshotsdir, 's' );
        catch
        end
    end
    
    stagepattern = fullfile( modeldir, [m.globalProps.modelname, '_s*.mat'] );
    stagelist = dir( stagepattern );
    announced = false;
    for i=1:length(stagelist)
        stagename = fullfile( modeldir, stagelist(i).name );
        if regexp( stagename, '_s[0-9]+(d[0-9]*)?\.mat$' )
            if ~announced
                fprintf( 1, 'Deleting stage files.\n' );
                announced = true;
                somethingDeleted = true;
            end
            fprintf( 1, 'Deleting %s\n', stagename );
            try
                delete( stagename );
            catch
            end
        end
    end
    
    if ~somethingDeleted
        fprintf( 1, '%s: No files to delete.\n', mfilename() );
    end
    
    recycle( oldrecycle );
end
