function f = newfilename( filename )
%f = newfilename( filename )
%   Given a filename, find a filename similar to it for which a file does
%   not already exist, by inserting a 4-digit number before the extension,
%   starting from 0001 and counting upwards as far as necessary.

    if ~exist( filename, 'file' ),
        f = filename;
    end
    [path,name,ext] = fileparts( filename );
    startcount = 0;
    [a,b,c,d,e,f] = regexp( name, '-([0-9])+$|' );
    if ~isempty(e)
      % e
      % e{1}
      % e{1}{1}
        startcount = sscanf( e{1}{1}, '%d', 1 );
        name = name(1:(a-1));
    end
    i = startcount+1;
    while true
        tryname = sprintf( '%s-%04d%s', name, i, ext );
        fprintf( 1, 'newfilename: trying %s\n', tryname );
        f = fullfile( path, tryname );
        if ~exist( f, 'file' ), return; end
        i = i+1;
    end
end

