function c = interpolateArray( v, cmap, crange )
%c = interpolateArray( v, cmap, crange )
%   C is the color produced by mapping V into the color map CMAP.
%   V can be a column vector of length N and C will be an N*3 matrix.

    if nargin < 3
        crange = [0 1];
    end
    ncolors = size(cmap,1);
    if ncolors==1
        c = ones(length(v,1))*cmap;
        return;
    end
    if crange(2) <= crange(1)
        c = ones(length(v),1)*cmap(1,:);
        return;
    end
    c = zeros(length(v),size(cmap,2));
    for i=1:length(v)
        v1 = v(i);
        if v1 <= crange(1)
            c(i,:) = cmap(1,:);
        elseif v1 >= crange(2)
            c(i,:) = cmap(ncolors,:);
        else
            lo = 1;
            hi = ncolors;
            vlo = crange(1);
            vhi = crange(2);
            iter = 0;
            while hi > lo+1
                iter = iter+1;
                mid = floor((lo+hi)/2.0);
                vmid = (vlo*(hi-mid) + vhi*(mid-lo))/(hi-lo);
              % fprintf( 1, '%d: [%d %d %d] [%.3f %.3f3 %.3f] [%.3f %.3f3 %.3f] [%.3f %.3f3 %.3f]\n', ...
              %     iter, lo, mid, hi, vlo, vmid, vhi, cmap(lo,:), cmap(hi,:) );
                if v1 <= vmid
                    hi = mid;
                    vhi = vmid;
                else
                    lo = mid;
                    vlo = vmid;
                end
            end
          % fprintf( 1, '%d: [%d %d %d] [%.3f %.3f3 %.3f] [%.3f %.3f3 %.3f] [%.3f %.3f3 %.3f]\n', ...
          %     iter, lo, mid, hi, vlo, vmid, vhi, cmap(lo,:), cmap(hi,:) );
            c(i,:) = (cmap(lo,:)*(vhi-v1) + cmap(hi,:)*(v1-vlo))/(vhi-vlo);
        end
    end
end
