function u = im2uint16(img, typestr)
%IM2UINT16 Convert image to sixteen-bit unsigned integers.
%   IM2UINT16 takes an image as input, and returns an image of
%   class uint16.  If the input image is of class uint16, the
%   output image is identical to it.  If the input image is of
%   class double or uint8, IM2UINT16 returns the equivalent
%   image of class uint16, rescaling or offsetting the data as
%   necessary.
%
%   I2 = IM2UINT16(I1) converts the intensity image I1 to uint16,
%   rescaling the data if necessary.
%
%   RGB2 = IM2UINT16(RGB1) converts the truecolor image RGB1 to
%   uint16, rescaling the data if necessary.
%
%   X2 = IM2UINT16(X1,'indexed') converts the indexed image X1 to
%   uint16, offsetting the data if necessary.  If X1 is double,
%   then the maximum value of X1 must be 65536 or less.
%
%   See also DOUBLE, IM2DOUBLE, IM2UINT8, UINT8, UINT16.

%   Copyright 1993-1998 The MathWorks, Inc.  All Rights Reserved.
%   $Revision: 1.3 $  $Date: 1998/07/20 19:54:13 $

if isa(img, 'uint16')
    u = img; 
   
elseif isa(img, 'double') | isa(img, 'uint8')
    if nargin==1
        if islogical(img)      
            % 16-bit binary images not supported
            warning('Converting binary input image to grayscale');
            u = +uint16(img~=0);
            u(u~=0) = 65535;
        else
            % intensity image; call MEX-file
            u = grayto16(img);
        end
        
    elseif nargin==2
    
        if ~ischar(typestr) | (typestr(1) ~= 'i')
            error('Invalid input arguments');
        else 
            if (isa(img, 'uint8'))
                u = uint16(img);
                
            else
                % img is double
                if max(img(:))>=65537 
                    error('Too many colors for 16-bit integer storage.');
                elseif min(img(:))<1
                    error('Invalid indexed image: an index was less than 1.');
                else
                    u = uint16(img-1);
                end
            end
        end
    else
        error('Invalid input arguments.');
    end
else
    error('Unsupported input class.');
end
