function saveasmfig(h, filename)
%SAVEASMFIG Save figure to fig file and generate m file to load.
%
% SAVEASMFIG(H, 'Filename') Use SAVEASFIG to write figure to file
% then generate m file which loads the figure.

%   Copyright 1984-2002 The MathWorks, Inc. 
%   $Revision: 1.11 $  $Date: 2002/04/10 17:04:49 $
%   D. Foti  11/10/97

[path, name, ext] = fileparts(filename);

if ~isempty(find(name == '.'))
    error(['Invalid m-file name: ' filename ', . (dot) is not valid filename character.']);
end

mFncnName = name;
mFileName = fullfile(path, [name '.m']);
fFileName = fullfile(path, [name '.fig']);

% try to save figure as fig - this may error out on bad input
% args

saveasfig(h, fFileName)

% saveasfig was ok, generate a m file to load the fig

fid = fopen(mFileName ,'wb');

if (fid < 0)
    error([ 'Can''t create m-file: ', mFileName])
end

fprintf(fid, [ ...
'function h = %s\n', ...
'%% This function was created by saveas(...,''mfig''), or print -dmfile.\n', ...
'%% It loads an HG object saved in binary format in the FIG-file of the\n', ...
'%% same name.  NOTE: if you want to see the old-style M code\n', ...
'%% representation of a saved object, previously created by print -dmfile,\n', ...
'%% you can obtain this by using saveas(...,''mmat''). But be advised that the\n', ...
'%% M-file/MAT-file format does not preserve some important information due\n', ...
'%% to limitations in that format, including ApplicationData stored using\n', ...
'%% setappdata.  Also, references to handles stored in UserData or Application-\n', ...
'%% Data will no longer be valid if saved in the M-file/MAT-file format.\n', ...
'%% ApplicationData and stored handles (excluding integer figure handles)\n', ...
'%% are both correctly saved in FIG-files.\n', ...
'%%\n', ...
'%%load the saved object\n', ...
'[path, name] = fileparts(which(mfilename));\n', ...
'figname = fullfile(path, [name ''.fig'']);\n', ...
'if (exist(figname,''file'')), open(figname), else open([name ''.fig'']), end\n', ...
'if nargout > 0, h = gcf; end\n'], mFncnName);

% all done
fclose(fid);
