function hgsave(varargin)
% HGSAVE  Saves an HG object hierarchy to a MAT file
% 
% HGSAVE(H, 'Filename') saves the objects identified by handle array H
% to a file named 'Filename.'  If 'Filename' contains no extension,
% then the extension '.fig' is added.  If H is a vector, none of the
% handles in H may be ancestors or descendents of any other handles in
% H.
%
% HGSAVE('Filename') saves the current figure to a file named
% 'Filename.'
%
% HGSAVE(..., 'all') overrides the default behavior of excluding
% non-serializable objects from the file.  Items such as the default
% toolbars and default menus are marked as non-serializable, and are
% normally not saved in FIG-files, because they are loaded from
% separate files at figure creation time.  This allows the size of
% FIG-files to be reduced, and allows for revisioning of the default
% menus and toolbars without affecting existing FIG-files. Passing
% 'all' to HGSAVE insures non-serialzable objects are also saved.
% Note: the default behavior of HGLOAD is to ignore non- serializable
% objects in the file at load time, and that can be overridden using
% the 'all' flag with HGLOAD.
%
% See also HGLOAD
%

%   Copyright 1984-2000 The MathWorks, Inc. 
%   $Revision: 1.16 $  $Date: 2000/08/01 22:10:21 $
%   D. Foti  11/10/97

error(nargchk(1, inf, nargin));

% pull off handle + 'filename,' or just 'filename'
if(isstr(varargin{1}))
  h = gcf;
  filename = varargin{1};
  first_pass_through = 2;
else
  h = varargin{1};
  if any(~ishandle(h))
    error('Invalid handle');
  end
  filename = varargin{2};
  first_pass_through = 3;
end

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

% fileparts returns everything from the last . to the end of the
% string as the extention so the following test will catch
% an extention with 0, 1, or infinity dots.
% for example, all these filenames will have .fig added to the end:
%  foo.
%  foo..
%  foo.bar.
%  foo.bar...

if isempty(ext) | strcmp(ext, '.')
  filename = fullfile(path, [file , ext, '.fig']);
end

% Revision encoded as 2 digits for major revision,
% 2 digits for minor revision, and 2 digits for
% patch revision.  This is the minimum revision 
% required to fully support the file format.
% e.g. 050200 means 5.2.0

oldState = zeros(length(h));
for i = 1:length(h)
  if strcmp(get(h(i), 'type'), 'figure')
    oldState(i) = plotedit(h(i), 'isactive');
    if oldState(i)
      plotedit(h(i), 'off');
    end
  end
end

hgS_050200 = handle2struct(h, varargin{first_pass_through:end});

for i = 1:length(h)
  if oldState(i)
    plotedit(h(i), 'on');
  end
end

save(filename, 'hgS_050200');


