function m = leaf_load( m, varargin )
%m = leaf_load( m, filename, ... )
%   Load a leaf from a file.  If no filename is given, a dialog will be
%   opened to choose one.
%   The expected format depends on the extension of the filename:
%       .MAT    The leaf is contained in the file as a Matlab object called
%               m.
%       .M      The file contains Matlab commands to create or modify a
%               leaf.  These commands will be executed.
%       .OBJ    Contains only nodes and triangles, in OBJ format.  All
%               other properties of the mesh will be set to their default
%               values.
%   If no filename is given, a dialog will be opened to choose one.
%   If the filename consists of just an extension (including the initial
%   "."), a dialog will be opened showing only files with that extension.
%
%   All of these formats can be generated by leaf_save.
%   In the case of .MAT and .OBJ files, the existing leaf will be
%   discarded.  A .M file will discard the current leaf only if it contains
%   a command to create a new leaf; otherwise, it will apply its commands
%   to the current leaf.
%
%   Equivalent GUI operation: the "Load..." button.
%
%   Topics: Files, Mesh editing.

    extensions = { 'mat', 'm', 'obj' };

    filename = '';
    if ~isempty(varargin)
        [ok, filename, args] = getTypedArg( mfilename(), 'char', varargin );
        if ~ok, return; end
        if ~isempty( args )
            fprintf( 1, '%s: %d extra arguments ignored.\n', ...
                mfilename(), length(args) );
        end
    end
    
    askForFile = 0;
    if isempty(filename)
        askForFile = 1;
        filterspec = inputFilterspec( extensions );
    else
        for i=1:length(extensions)
            if strcmpi( varargin{1}, ['.' extensions{i}] )
                askForFile = 1;
                filterspec = inputFilterspec( { extensions{i} } );
                break;
            end
        end
    end

    if askForFile
        [filename,filepath] = uigetfile( filterspec, 'Load a leaf file' );
        if filename==0, return; end
    else
        [filepath,filename,fileext] = fileparts( filename );
        filename = [filename,fileext];
    end
    
    fullname = fullfile( filepath, filename );
    replaceM = isempty(m);
    m = loadmesh_anyfile( m, fullname );
    if ~isempty(m)
        m = recordcommand( m, replaceM, 'load', fullname );
    end
end
