function [ cdata ] = imagescX ( img, cmap, clim )
% imagesc_fixed Plot image independent of colormap used in figure
% Usage:
%     imagesc_fixed ( img, cmap, clim )
% INPUT:
%     img = 2D matrix of image
%     cmap = colormap, defaults to 'jet'
% OUTPUT:
%     [] = plot the image to current axes
%     cdata = RGB matrix
%
% Development status: Partially functional
% Copyleft (c) Xiaohu Mo
% Version: 0.7

if nargin < 2
    cmap = jet(256);
end

img = squeeze(img);
if ndims(img) > 2
    cdata = [];
    return;
end

if isinteger(img)
    img = single(img);
end

cmap_len = size(cmap, 1);

if nargin < 3
    cmin = min(img(:));
    cmax = max(img(:));
else
    cmin = clim(1);
    cmax = clim(2);
end

% calculate color
% TODO cmap_len - 1 or not? See doc caxis
img_indexed = fix((img-cmin)/(cmax-cmin)*(cmap_len-1)) + 1;
img_indexed(img_indexed < 1) = 1;
img_indexed(img_indexed > cmap_len) = cmap_len;
img_indexed(isnan(img_indexed)) = 1; % TODO when cmax == cmin

cdata = zeros(size(img,1), size(img,2), 3);
cdata(:,:,1) = reshape(cmap(img_indexed, 1), size(img));
cdata(:,:,2) = reshape(cmap(img_indexed, 2), size(img));
cdata(:,:,3) = reshape(cmap(img_indexed, 3), size(img));

if nargout == 0
    image('CData', cdata);
end
