%READIM   Read image from file
%
% SYNOPSIS:
%  [image_out, file_info] = readim(filename,format)
%
% OUTPUT:
%  image_out: the image
%  file_info: additional parameters of the image (if avaiable) returned as a struct,
%             see DIPIO_IMAGEFILEGETINFO for more information.
%
% PARAMETERS:
%  filename: string with name of file, optionally with path and extension.
%  format:   string with any of: 'ICS', 'LSM', 'TIFF', 'GIF', 'CSV' or 'PIC', or an
%            empty string, which will cause the function to search for the correct
%            type.
%
% DEFAULTS:
%  filename = 'erika.ics'
%  format = ''
%
% NOTES:
%  Color images will now automatically be read as color. The use of READCOLORIM is not
%  longer required. Use READGRAYIM for old functionality.
%
%  To get a current list of file formats, use the function DIPIO_GETIMAGEREADFORMATS,
%  which also gives a short description of each format.
%
%  For JPEG, BMP, PNG and other such files not recognized by dipIO, leave
%  FORMAT empty. This will allow READIM to call IMREAD (a MATLAB function)
%  that does recognize these files.
%
%  Some LSM files will not be read in properly. Use the function FIXLSMFILE
%  to fix a large class of these. For others - uh, well.
%
%  To read multi-page TIFF files use READTIMESERIES or the low-level function DIPIO_IMAGEREADTIFF.
%

% (C) Copyright 1999-2008               Pattern Recognition Group
%     All rights reserved               Faculty of Applied Physics
%                                       Delft University of Technology
%                                       Lorentzweg 1
%                                       2628 CJ Delft
%                                       The Netherlands
%
% Cris Luengo, June 2000.
% 17 December 2001: Using MATLAB's IMREAD if dipIO cannot read the file.
% February 2002: Removed static list of file formats.
% September 2006: Added second output argument,  output of dipio_imagefilegetinfo (BR)
% September 2006: Integrated readcolorim into readim (BR)
% December 2006: Fixed bug with colormap after calling IMREAD. (CL)
% February 2008: Adding pixel dimensions and units to dip_image. (BR)
% 5 March 2008: Bug fix in pixel dimension addition. (CL)

function varargout = readim(varargin)

frmts = [struct('name','','description','Any type'),dipio_getimagereadformats];

d = struct('menu','File I/O',...
           'display','Read image',...
           'inparams',struct('name',       {'filename',                'format'},...
                             'description',{'Name of the file to open','File format'},...
                             'type',       {'infile',                  'option'},...
                             'dim_check',  {0,                         0},...
                             'range_check',{'*.*',                     frmts},...
                             'required',   {0,                         0},...
                             'default',    {'erika.ics',               ''}...
                            ),...
           'outparams',struct('name',{'image_out',''},...
                              'description',{'Output image','Image Parameters'},...
                              'type',{'image','array'}...
                              )...
          );
if nargin == 1
   s = varargin{1};
   if ischar(s) & strcmp(s,'DIP_GetParamList')
      varargout{1} = d;
      return
   end
end
%%% aliases for elements in the 'format' list.
if nargin>=2 & ischar(varargin{2})
   if strcmpi(varargin{2},'tif')
      varargin{2} = 'tiff';
   end
end
%%%
try
   [filename,format] = getparams(d,varargin{:});
catch
   if ~isempty(paramerror)
      error(paramerror)
   else
      error(firsterr)
   end
end

foundfile = 0;
try
   [varargout{1}, photometric] = dipio_imagereadcolour(filename,format,1);
   fileInfo = dipio_imagefilegetinfo(filename,format,1);
catch
   status = dipio_filestatus(lasterr);
   if status == 0
      error(firsterr)
   end
   varargout{1} = [];
   if status == 1
      foundfile = 1;
   end
end
if isempty(varargout{1}) & isempty(fileparts(filename)) % The file name has no path.
   p = convertpath(dipgetpref('imagefilepath'));
   for ii=1:length(p)
      fname = fullfile(p{ii},filename);
      try
         [varargout{1}, photometric] = dipio_imagereadcolour(fname,format,1);
         fileInfo = dipio_imagefilegetinfo(fname,format,1);
      catch
         status = dipio_filestatus(lasterr);
         if status == 0
            error(firsterr)
         end
         varargout{1} = [];
         if status == 1
            foundfile = 1;
         end
      end
      if ~isempty(varargout{1})
         break;
      end
   end
end
if isempty(varargout{1})
   if ~foundfile
      error(['File "' filename  '" not found.'])
   end
   if ~isempty(format)
      error(['File type not recognized (leave ''format'' empty to allow IMREAD to be called).'])
   end
   try
      [varargout{1},map] = imread(filename);
   catch
      error('File type not recognized.')
   end
   if ~isempty(map)
      map = single(map*255);
      varargout{1} = lut(varargout{1},map);
   elseif ndims(varargout{1})==3
      if isa(varargout{1},'double')
         varargout{1} = varargout{1}*255;
      end
      varargout{1} = dip_image(varargout{1});
      varargout{1} = joinchannels('RGB',varargout{1});
   else
      varargout{1} = dip_image(varargout{1});
   end
else
   if ~strcmp(photometric,'gray')
      varargout{1} = joinchannels(photometric,varargout{1});
   end
end

if exist('fileInfo')
   n = ndims(varargout{1}{1}); % If it's a color image, physDims below usually contains one more element.
   varargout{1}.pixelsize = fileInfo.physDims.dimensions(1:n);
   varargout{1}.pixelunits = fileInfo.physDims.dimensionUnits(1:n);
   varargout{2} = fileInfo;
else
   varargout{2} = [];
end
