function fig = openfig(filename, policy)
% OPENFIG Open new copy or raise existing copy of saved figure.
%    OPENFIG('NAME.FIG', 'new') opens figure contained in .fig file,
%    NAME.FIG, and ensures it is completely on screen.  Specifying the
%    .fig extension is optional. Specifying the full path is optional
%    as long as the .fig file is on the MATLAB path.
%
%    If the .fig file contains an invisible figure, OPENFIG returns
%    its handle and leaves it invisible.  The caller should make the
%    figure visible when appropriate.
%
%    OPENFIG('NAME.FIG', 'reuse') opens figure contained in .fig file
%    only if a copy is not currently open, otherwise ensures existing
%    copy is still completely on screen.  If the existing copy is
%    visible, it is also raised above all other windows.
%
%    OPENFIG('NAME.FIG') is the same as OPENFIG('NAME.FIG', 'new').
%
%    F = OPENFIG(...) returns the handle to the figure.
%
%    See also: OPEN, MOVEGUI, GUIDE, GUIHANDLES, SAVE, SAVEAS.

%   Damian T. Packer 6-8-2000
%   Copyright (c) 1984-2000 The MathWorks, Inc. All Rights Reserved.
%   $Revision: 1.14 $  $Date: 2000/08/25 22:34:35 $

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

if nargin == 1
  policy = 'new';
end

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

if isempty(ext)
  ext = '.fig';
elseif ~isequal(ext, '.fig')
  error('Argument must be a .fig file');
end

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

% We will use this token, based on the base name of the file
% (without path or extension) to track open instances of figure.
TOKEN = [name '_SINGLETON_handle'];
TOKEN = TOKEN(1:min(end, 31));

% get the existing list of figures, and prune out stale handles.
figs = getappdata(0, TOKEN);
figs = figs(ishandle(figs));

switch policy
 
 case 'new'
  % create another one, unconditionally
  fig = hgload(filename);
  figs(end + 1) = fig;
 
 case 'reuse'
  % create one only if there are no others
  if isempty(figs)
    figs = hgload(filename);
  end
  % reuse the one at the end of the list:
  fig = figs(end);
  
 otherwise
  error('Second input argument must be ''new'' or ''reuse''.');
  
end

% remember all instances of this figure.
setappdata(0, TOKEN, figs);

% ensure the figure is completely on the screen:
movegui(fig, 'onscreen');

% raise it, if it is visible:
if isequal(get(fig,'visible'), 'on')
  figure(fig);
end