function Is = imscale(I)

% Is = imscale(I)
%
% DESC:
% scales the dynamic range of I according to its type:
%
%   uint8     -> uint8 in [0 255]
%   logical   -> uint8 in {0, 255}
%   uint16    -> uint16 in [0 65535]
%   single    -> single in [0 1]
%   double    -> double in [0 1]
%
% AUTHOR
% Marco Zuliani - zuliani@ece.ucsb.edu
%
% VERSION:
% 1.0.4
%
% INPUT:
% I                 = input image
%
% OUTPUT:
% Is                = output image

% HISTORY:
% 1.0.0             - ??/??/2007 initial version
% 1.0.1             - ??/??/2007 discard infs and nans
% 1.0.2             - 05/07/2007 handle different image types
% 1.0.3             - 06/05/2007 handle logical image type
% 1.0.4             - 11/03/2007 bug fix

% avoid infs and nans
flag = isfinite(I(:)) & ~isnan(I(:));
if ~all(flag)
    warning('inf and nan have been discarded')
end;

M = double(max(I(flag)));
m = double(min(I(flag)));

switch class(I)
    case {'uint8', 'logical'}
        A = 255;
    case 'unit16'
        A = 65535;
    case {'single', 'double'}
        A = 1;
end

if (M == m)
    Is = I;
else
    Is = immultiply( imsubtract( double(I), m ), A/(M-m));
end;

switch class(I)
    case 'uint8'
        Is = uint8(Is);
    case 'unit16'
        Is = uint16(Is);
    case 'single'
        Is = single(Is);
end

return