function axhandle = contourflegend(conts,h)

% Put a legend on a contourf plot.
% CONTOURFLEGEND(C,H) where C is the contour matrix as described in CONTOURC
% and used by CLABEL, and H is column vector of patch handles output by
% contourf.

% Andrew Knight, March 1998

indleft = 1;
indright = 0;
ind = [];
levels = [];
while indright<length(conts)
   indleft = indleft + length(ind) + 1;
   indright = indright + conts(2,indright+1) + 1;
   ind = indleft:indright;
   levels = [levels conts(1,indleft - 1)];

end
levels = unique(levels);
levels(length(levels)) = [];

%Get colours from the list of patch handles:
cindeces = zeros(1,length(h));
for i=1:length(h)
  cindeces(i) = get(h(i),'cdata');
end
cindeces = round(range(unique(cindeces),1,length(colormap)));
map = colormap;
colours = map(cindeces,:);


contpos = get(gca,'pos');
contax = gca;
dlevels = levels(2) - levels(1);
levels = [levels(1)-dlevels levels levels(length(levels))+dlevels];
%legpos(1) = contpos(1) + contpos(3) +contpos(3)/50;
legpos(1) = contpos(1) + contpos(3) + contpos(3)/200;
legpos(2) = contpos(2) + contpos(4)/2;
legpos(3) = contpos(3)/30;
legpos(4) = contpos(4)/2;
hcbar = axes('pos',legpos,...
    'yax','right',...
    'xtick',[],...
    'YLim',[levels(1) levels(length(levels))],...
    'YTick',levels,...
    'tickdir','out');
hold on
%Draw little rectangles for each colour used in the contour plot:
for i=1:length(levels)-1
  x = [0 1 1 0];
  y = levels([i i i+1 i+1]);
  patch(x,y,colours(i,:))
end

set(gcf,'CurrentAxes',contax)

if nargout>0
  axhandle = hcbar;
end

