function cf_index(h, clev, irange)
%  function cf_index(h, clev, irange)
%
%  ContourF INDEX
%     Change contourf patch objects from scaled to direct
%     color mapping.
%
%     h        vector of handles to patch objects created by contourf
%     clev     vector of contour levels used in the call to contourf
%     irange   [i0 i_end] index range in the colormap to which clev
%              is to be mapped.
%
%  Example:
%     clev = [-6000:500:500];
%     map1 = brighten(jet(length(clev) +1),0.5);
%     map2 = jet(64);
%     colormap([map1 ; map2]);
%     m_proj('merc', 'lon', [-30 16], 'lat', [56 62]);
%     [cmat, htopo] = m_tbase('contourf', clev);
%     cf_index(htopo, clev, [1 size(map1,1)]);
%     % Colorbar:
%     h_dcb = dcolbar( clev/1000, 'vert', 'Depth (km)');
%     h_dcbp = findobj(h_dcb,'Type','patch');
%     cf_index(h_dcbp, clev/1000, [1 size(map1,1)]);
%     % Now superimpose something else, mapped to the map2 segment
%     % of the colormap.  For that, use
%     %     irange = size(map1,1) + [1 size(map2,1)];
%
%  Note: A colormap segment for use by contourf in this way needs
%  to be no larger than 1 + length(clev); this is actually the ideal
%  length, causing an even and unique mapping of clev to colors.

%  Eric Firing
%
%  modified 2001/05/24 to accept scalar or vector h

lev = get(h,'CData');
% lev is a cell array
ilev = c_index(lev, clev, irange);
if length(h) > 1,
   set(h, {'CData'}, ilev);
      set(h, {'CData'}, ilev);
else
   set(h, 'CData', ilev);
end
set(h,'CDataMapping','direct');

ilevtest = c_index(clev, clev, irange);
if length(unique(ilevtest)) ~= length(clev),
   disp('Warning: Some clev values are sharing the same index')
   disp('into the colormap.')
   disp('You may want to change the size of the colormap.')
   disp('Making it, e.g., jet(1 + length(clev))  ensures uniqueness.')
end

