function cmap_new = stretch_colormap(cmap_old, weight_fn)
%   STRETCH_COLORMAP creates a new colormap by stretching an old one.
%
% function cmap_new = stretch_colormap(cmap_old, weight_fn)
%
% cmap_new is an nX3 colormap returned when stretch_colormap is passed
% cmap_old, an old nX3 colormap, and the vector weight_fn. weight_fn can be
% any monotonic increasing vector and it is used to interpolate between the
% rows of the colormap. Thus if weight_fn is linearly increasing then
% cmap_new will be identical to cmap_old to within a rounding error. If
% weight_fn increases quickly at the beginning then the colormap is
% compressed so that the most rapid changes in color occur at the lower range
% of the variable being mapped.
%
% Example usage:
%    nn = 1/3;                                       
%    cmap_new = stretch_colormap(jet, (0:.01:1).^nn);
%    colormap(cmap_new) 

% $Id: stretch_colormap.m,v 1.1 1998/09/01 01:47:01 mansbrid Exp $
% Copyright J. V. Mansbridge, CSIRO, Tue Sep  1 11:16:41 EST 1998

% Check input arguments

if nargin ~= 2
  error('nargin must be passed exactly 2 arguments')
end

if min(diff(weight_fn)) <= 0
  error('weight_fn must be a monotonic increasing vector')
end

% Create a normalised weight function the same length as the number of rows
% in the colormap and also fix up possible rounding error due to the
% interpolation.

[mc, nc] = size(cmap_old);
wt = (weight_fn - weight_fn(1))/(weight_fn(end) - weight_fn(1));
wt = wt(:)*(mc - 1) + 1;
xi = (0:(mc-1))*(length(wt)-1)/(mc-1) + 1;
wt_i = interp1(wt, xi(:));
wt_i(1) = 1;
wt_i(end) = mc;

cmap_new = interp1(cmap_old, wt_i);
