function c = translateToColors( v, crange, cmap )
%c = translateToColors( v, crange, cmap )
% Given a vector of values v, and range vrange = [lo,hi], and a list of
% colours, map every element of v to the corresponding colour.
% v is N*1, and c is N*3.

    numcolors = size(cmap,1);
    if numcolors==0
        c = ones( length(v), 3 );
    elseif crange(2) <= crange(1)
        c = repmat( cmap(1,:), length(v), 1 );
    else
        cfracscaled = 1 + (v-crange(1))*((numcolors-1)/(crange(2)-crange(1)));
        cindexlo = floor(cfracscaled);
        cremainder = cfracscaled - cindexlo;
        cindexhi = cindexlo+1;
        cindexlo = min(max(cindexlo,1),numcolors);
        cindexhi = min(max(cindexhi,1),numcolors);
        c = cmap(cindexlo,:).*repmat((1-cremainder),1,3) ...
            + cmap(cindexhi,:).*repmat(cremainder,1,3);
    end
end
