function H=subindex(method)
%SUBINDEX Label subplots with an index (e.g. a,b,c)
%  SUBINDEX labels subplots in the current figure with an index in
%  the top left corner.
%  
%  SUBINDEX(METHOD) labels subplots with an index defined by METHOD.
%  Options are:
%    METHOD = 'letter'   : a, b, c, etc.  (default)
%             'number'   : 1, 2, 3, etc.
%             'roman'    : i, ii, iii, etc.  
%
%  See also SUBPLOT.
  
% Author: David Lamper - david.lamper@gmail.com 
%
% v 1.0 - Mar 2006

  
% Default index method is letter
if nargin == 0
  method = 'letter';
end

% get axis handles
ax=get(gcf,'children');
ax = flipud(ax);
h = zeros(1,length(ax));

% only count up to 20 in roman numerals
if strcmpi(method,'roman')
  if length(ax) > 20
    warning('Roman numerals only supported for less than 20 axes.');
  end  
end

for i=1:length(ax)
  axes(ax(i));

  switch lower(method)
    case 'letter'
      string = [' ' 'a'+i-1 ')'];
    case 'number'
      string = [' ' '1'+i-1 ')'];
    case 'roman'
      string = [' ' rnum(i) ')'];
    otherwise
      error('Unknown method');
  end
  
  % determine if there is already a subindex label on the axis
  if length(getappdata(ax(i), 'subindexLabelHandle')>0)
    hold = getappdata(ax(i), 'subindexLabelHandle');
    delete(hold);
  end 
  
  h(i) = text(0,1,string,'units','normalized','verticalalignment','top');

  % set handle as application data
  setappdata(ax(i), 'subindexLabelHandle', h(i));
end

% return text handles
if nargout == 1
  H = h;
end

% ------------------------------------------------------------------------
function s=rnum(x)
% Convert x to roman numerals.  
% 
% Use a simple lookup table
 
roman = {'i','ii','iii','iv','v','vi','vii','viii','ix','x','xi', ...
         'xii','xiii','xiv','xv','xvi','xvii','xviii','xix','xx'};
nroman = 20;

% prevent error if x > length(roman)
s = roman{min(x,nroman)};
  
