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 CONTORM or CONTOR3M.
%
%  CLEGENDM(...,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
%
%  See also CLABELM, CONTORM, CONTOR3M

%  Copyright 1996-2000 Systems Planning and Analysis, Inc. and The MathWorks, Inc.
% $Revision: 1.9 $
%  Written by:  E. Byrns, E. Brown



if nargin == 1
     legend(varargin{1})
elseif nargin < 2
     error('Incorrect number of arguments')
elseif nargin == 2
     c = varargin{1};    h = varargin{2};   Pos = 0;
else
     c = varargin{1};    h = varargin{2};   Pos = varargin{3};
end

%  Test that a map axes is present

if ~ismap;   error('Map axes are not current');    end
axishndl = gca;  %  Save current axes handle.  Legend creates a new axes

%  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

%  Add a legend to the current plot

legend(h,num2str(level),Pos)
set(get(axishndl,'Parent'),'CurrentAxes',axishndl)  %  Reset current axes

%  Assign the SCRIBE callbacks to the legend objects

legndhndl = findobj(gcf,'Type','axes','Tag','legend');
children = get(legndhndl,'Children');
set(children,'ButtonDownFcn','uimaptbx')
