function res = imrescale(im,tozero,toone)
% imrescale(im, tozero, toone)
% rescale a double image to the range 0-1
% sending a value <tozero> to 0 and <toone> to 1.
% This is useful for plotting doubles as images
% using imshow.
% If <tozero> and <toone> are unspecified,
% these are computed from the maximum and minimum
% values in the image.
[a,b,d] = size(im);
if strcmp(class(im),'uint8')
   im = double(im);
end

if nargin < 3
   if d > 1
      toone = max(max(max(im)));
   else
      toone = max(max(im));
   end
end

if nargin < 2
   if d > 1
      tozero = min(min(min(im)));
   else
      tozero = min(min(im));
   end
end

if toone == tozero
   res = zeros(a,b,d);
else
   res = (im -tozero)/(toone - tozero);
   res(res > 1) = 1;
   res(res < 0) = 0;
end
