function [IMout, cmapout] = image_value_table_shift( IM, cmap, intable, totable )
% IMout = image_value_table_shift( IM, cmap intable, totable )
% 
% Takes a matrix M and changes its content using intable and totable. The
% latter two vectors contain all unique values in M, intable, contains what
% they are and totable what they should be changed to.



if (length( intable ) ~= length( totable )),
    error('intable and totable have different size')
end

IMout = nan( size(IM));

cmapout = zeros( max(totable), 3);


deltato = 0;
deltain = 0;
if min( intable) <1,
    deltain = 1 - min( intable );
end

if min( totable) <1,
    deltato = 1 - min( totable );
end


for idx = 1: length( intable),
    IMout( IM == intable(idx ) ) = totable(idx);
    cmapout( totable(idx) + deltato , :) = cmap( intable(idx) + deltain,:);
end

IMout = uint8(IMout);
