function [cmap] = cmaplevel(levels, colors, cmin, cmax, num_colors)
%CMAPLEVEL Create colormap from specified levels and colors
%
% Description:
%   Pixel value within [Lv(k) Lv(k+1)) assigned to RGB color(k,:)
% Usage:
%   [cmap] = cmaplevel(levels, colors, cmin, cmax, num_colors)
% Input:
%   c = 1x3 float of RGB values between 
% Output:
%   str = html color code format, e.g. color(23, 47, 83)
%
% Xiaohu Mo

% TODO input checking
% TODO specify number of color levels

%%
if cmin > cmax
    cmap = [];
    return;
elseif cmin == cmax % clevels will be NaN
    [tilde, ind] = max(levels);
    cmap = repmat(colors(ind, :), [num_colors, 1]);
    return;
end

if ~isvector(levels)
    cmap = [];
    return;
end

%% sort the levels and colors
t = horzcat(levels(:), colors);
t = sortrows(t, 1);
levels = t(:, 1);
colors = t(:, 2:4);

%% indices of the absolute levels on colormap
clevels = fix((levels-cmin)/(cmax-cmin)*num_colors) + 1;

%% create cmap
cmap = zeros(num_colors, 3);

% add the last level below cmin if exist
indices = find(clevels < 1, 1, 'last');
% all useful levels
indices = [indices find(clevels >= 1 & clevels <= num_colors)];

% fill the colormap
for ind = indices:numel(levels)
    cmap(clevels(ind):num_colors, :) = repmat(colors(ind, :), [num_colors-clevels(ind)+1 1]);
end
