function clegendm(varargin)
%CLEGENDM	Add a legend labels to a map contour plot.
%
%  CLEGENDM(CS,H) adds a legend specifying the contour line heights to the
%  current map contour plot.  CS and H are the contour matrix output and
%  object handle outputs from CONTOURM or CONTOUR3M.
%
%  CLEGENDM(CS,H,Pos) places the legend in the specified location:
%        0 = Automatic placement (default)
%        1 = Upper right-hand corner
%        2 = Upper left-hand corner
%        3 = Lower left-hand corner
%        4 = Lower right-hand corner
%       -1 = To the right of the plot
%
%  CLEGENDM(...,UNITSTR) appends the character string UNITSTR to each entry
%  in the legend.
%
%  CLEGENDM(...,STR) uses the strings specified in cell array STR.  STR
%  must have same number of entries as H.
%
%  Examples:
%
%    % Load topographic data measured in meters                                 
%    load topo;                                                                 
%    figure; axesm robinson; framem                                                     
%    [cs,h] = contourm(topo,topolegend,3);                                       
%    % Create Legend in Upper Right Hand Corner (Elevation in meters)
%    clegendm(cs,h,2);                                                          
%
%    % Load topographic data measured in meters                                 
%    load topo;                                                                 
%    figure; axesm robinson; framem                                                     
%    [cs,h] = contourm(topo,topolegend,3); 
%    % Create Legend with units in Upper Right Hand Corner (Elevation in meters)
%    clegendm(cs,h,2,' m');  
%
%    % Load topographic data measured in meters                                 
%    load topo;                                                                 
%    figure; axesm robinson; framem                                                     
%    [cs,h] = contourm(topo,topolegend,3); 
%    % Create Legend with user specified string
%    str = {'low altitude','medium altitude','high altitude'}
%    clegendm(cs,h,2,str);  
%
%  See also CLABELM, CONTOURM, CONTOUR3M.

%  Copyright 1996-2004 The MathWorks, Inc.
%  $Revision: 1.12.4.2 $ $Date: 2004/08/27 15:15:51 $

checknargin(1,4,nargin,mfilename);

%  Test that a map axes is present
if ~ismap
   eid = sprintf('%s:%s:invalidMapAxes', getcomp, mfilename);
   error(eid,'%s','Map axes are not current');
end

% Obtain inputs
if nargin == 1
   legend(varargin{1})
   return
elseif nargin == 2
   c = varargin{1};    
   h = varargin{2};  
   Pos = 0;            
   Str = {};
elseif nargin == 3
   c = varargin{1};   
   h = varargin{2};  
   Pos = varargin{3}; 
   Str = {};
else
   c = varargin{1};    
   h = varargin{2};   
   Pos = varargin{3};
   Str = varargin{4};
end
if isempty(Pos)
   Pos = 0;
end

%  Save current axes handle.  Legend creates a new axes
axishndl = gca;

% Get the level names for the legend
[levelNames,h] = getLevelNames(c,h,Str);

% Create the legend and return its handle
legndhndl = createLegend(h,levelNames,Pos);

% Reset current axes
set(get(axishndl,'Parent'),'CurrentAxes',axishndl)  

% Assign the SCRIBE callbacks to the legend objects
if ~isequal(get(h,'type'),'hggroup')
   children = get(legndhndl,'Children');
   set(children,'ButtonDownFcn','uimaptbx')
end

%--------------------------------------------------------------------------
function legendhndl = createLegend(h, names, position)
% CREATELEGEND Create a legend and return its handle
%
% Inputs: 
%   H        - handle of the graphics
%   NAMES    - names of the legend labels
%   POSITION - postion for the legend axis
%
% Output:
%    LEGENDHNDL - handle of the legend axis
%

if isequal(get(h(1),'type'),'hggroup')
   % Using a contour group:
   %  construct an invisible line for each contour level
   %  and pass these line handles to legend, then delete them
   levels = get(h(1),'LevelList');
   hLine = zeros(1,numel(levels));
   for i=1:numel(levels)
      color = getColorValue(levels(i));
      hLine(i)=line([0 1],[0 1],'color',color,'visible','off');
   end
   legendhndl = legend(hLine, names, position);
   delete(hLine);
else  
   legendhndl = legend(h, names, position);
end

%--------------------------------------------------------------------------
function [levelNames,h] = getLevelNames(c,h,Str)
% GETLEVELNAMES Return each level string names 
% Inputs: 
%    C    - contour matrix
%    H    - handle to contours
%    STR  - a unit string or empty cell
%
% Outputs:
%    LEVELNAMES - cell array of the level names
%    H          - the updated output handle

if ~isequal(get(h,'type'),'hggroup')
   if iscell(Str) == 0

      % character string entered, expand into cell array of strings
      % Get the contour line data values.
      values = char(get(h,'Tag'));

      % Construct a string matrix consisting of the units value.
      unitsStr = repmat(Str,size(values,1),1);

      % Concatenate the data and units string matrices and convert
      % the resulting string matrix to a cell array of strings.
      levelNames = cellstr(strcat(values,unitsStr));

   elseif ~isempty(Str)
      levelNames = Str;
      
   else

      %  Get the levels for each contour line drawn
      level = zeros(size(h));    startpt = 1;
      for i = 1:length(h)
         level(i) = c(1,startpt);
         startpt = startpt + c(2,startpt) + 1;
      end

      %  Sort the contour levels and corresponding handles
      [level,indx] = sort(level);
      h = h(indx);

      %  Determine if any contour levels are duplicated
      difflevels = diff(level);
      indx = find(difflevels == 0);
      if ~isempty(indx)
         level(indx+1)=[];
         h(indx+1) = [];
      end
      levelNames = cellstr(num2str(level));
   end

else
   % The handle is a contour group
   levelNames = num2str(get(h,'LevelList')');
   if iscell(Str) == 0
      unitsStr = repmat(Str,size(levelNames,1),1);
      levelNames = cellstr(strcat(levelNames,unitsStr));
   elseif ~isempty(Str)
      levelNames = Str;
   end
end

%--------------------------------------------------------------------------
function cValue = getColorValue(value)
% GETCOLORVALUE Return color triplet from a value 
cmap = colormap;
[cmin cmax] = caxis;
sz = size(cmap,1);
index = fix((value-cmin)/(cmax-cmin)*sz)+1;
cValue = cmap(min(index,sz),:);

