function A = showlegend(A, varargin)
%AXISOBJ/SHOWLEGEND
%   domethod(A,'showlegend')  toggles the legend for axisobj A
%   domethod(A,'showlegend','on')  creates or sets legend
%       visibility on for axisobj A
%   domethod(A,'showlegend','off')  sets legend does nothing or
%       visibility off for axisobj A
%   domethod(A,'showlegend','reset')  calls legend off
%       for axisobj A


%   Copyright 1984-2000 The MathWorks, Inc. 
%   $Revision: 1.6 $  $Date: 2000/06/01 02:52:25 $

HG = get(A,'MyHGHandle');
switch nargin
case 1
   newstate = '';  % toggle state
case 2
   newstate = varargin{1};
end

if strcmp(newstate,'reset')
   legend(HG,'off');
   return
end

legendHandle = legend(HG);
   
if ~isempty(legendHandle)
   % legend already exists
   children = get(legendHandle,'Children');
   if isempty(newstate) % showlegend(A)  toggle visibility
      if strcmp('on',get(legendHandle,'Visible'))
         newstate = 'off';
      else
         newstate = 'on';
      end
   end

   set([legendHandle; children],'Visible',newstate);

else % no legend exists for this axis
   if isempty(newstate)
      newstate = 'on';
   end
  
   if strcmp(newstate,'on')
      dataObjects = flipud(get(A,'Children'));
      if isempty(dataObjects)
         errordlg('Can not add a legend to an empty plot.');
      else
         for i = 1:length(dataObjects)
            tag = get(dataObjects(i),'Tag');
            if ~isempty(tag)
               dataNames{i} = tag;
            else
               dataNames{i} = ['data' num2str(i)];
            end
         end
         legend(HG,dataNames{:});
      end
   end
end


