%FIND_FILES return sorted files
%
% out = find_files(filebase, ext, start, ending, verbose)
%
%  filebase: string containing the base filename
%  ext     : extension
%  start   : first index to read
%  ending  : last index to read 
%  verbose : show diagnostic messages
%
% DEFAUTLS:
%  start  = 0 % start with the first found image
%  ending = 0 % read all found images
%  verbose  = 1

% (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
%
% Bernd Rieger, April 2004 (based on CL readstack)
% April 2004,     added support for empty extension (BR)
% May 2004,       added error if no files are found (BR)
% September 2004, support for dots in the file name (BR)
% September 2004, Fixed for use of '' as extension parameter, moved trimming of IN
%                 from READTIMESERIES to here; now we're able to read the 'imser?' series.
%                 Also correct use of 'ImageFilePath' preference & using FULLFILE. (CL)
% September 2004, fix Leica timeseries reading (BR)
% November 2004,  added Leica timeseries stuff (BR)
% June 2006,      changed global SupressOutput to parameter VERBOSE (CL)

function out=find_files(in,ext,st,ed,verbose)
if nargin < 5
   verbose = 1;
   if nargin < 4
      ed = 0;
      if nargin < 3
         st = 0;
         if nargin < 2
            ext = '';
         end
      end
   end
end

[pathstr,basename,extension] = fileparts(in);
if length(extension) > 4 %someone puts dots in the filename
   basename = [basename extension];
   extension = '';
end
if ~isempty(extension) & isempty(ext)
   ext = extension(2:end); % remove the dot
end
oldBase = basename;

%strange error if basename is only one character str2num returns imaginary
%here, Jan 2005 BR
while ~isnan(str2num(basename(end))) & isreal(str2num(basename(end)))
   basename(end) = []; %remove trailing numbers
end
if isempty(ext)
   fns = dir(fullfile(pathstr,[basename '*']));
   l_ext = 0;
else
   fns = dir(fullfile(pathstr,[basename '*.' ext]));
   l_ext = length(ext) + 1;
end
fns([fns.isdir]) = [];
if isempty(fns) & isempty(pathstr)
   p = convertpath(dipgetpref('imagefilepath'));
   for ii=1:length(p)
      if isempty(ext)
         fns = dir(fullfile(p{ii},[basename '*']));
      else
         fns = dir(fullfile(p{ii},[basename '*.' ext]));
      end
      fns([fns.isdir]) = [];
      if ~isempty(fns)
         pathstr = p{ii};
         break;
      end
   end
end
if isempty(fns)
   out = {};
   return;
end

if isempty(ext)
   [tmp1,tmp2,extension] = fileparts(fns(1).name);
   if ~isempty(extension)
      ext = extension(2:end);
      l_ext = length(ext) + 1;
   end
end
%fprintf('%s - %s - %s - %s\n',pathstr,fns(1).name,basename, ext);

Nout =  length(fns);
out = cell(1,Nout);
iout = zeros(1,Nout);

i = strfind(fns(1).name,'_ch0');
if ~isempty(i)
   %leica series
   if verbose
      disp(' Assuming Leica tiff series.');
   end
   if Nout <3
      %fprintf(' Trying ...\n');
      tmp = [in(1:end-12) '*' in(end-8:end)];     
      out=find_files(tmp,ext,st,ed);
      return;
   end
   
   l_ext = 8+1;%cris
   basename = basename(1:i-4);
end

for ii =1:Nout
   out{ii} = fns(ii).name;
   if strfind(lower(out{ii}),'ids')
      iout(ii) = -1;
   else
      iout(ii) = str2double(out{ii}(length(basename)+1:end-l_ext));
      if isnan(iout(ii))
      iout(ii) = str2double(out{ii}(length(basename)+2:end-l_ext));          
      end
   end
   out{ii} = fullfile(pathstr,out{ii});
   %fprintf('%s (%d)\n',out{ii},iout(ii));
end

I = iout >= st;
if ed ~=0
   I = I & iout <= ed;
end
out = out(I);
iout = iout(I);
[iout,I] = sort(iout);
out = out(I);

i = strfind(fns(1).name,'_ch0');
if ~isempty(i)
   %leica series
   ch = oldBase;
   ch = ch(end-4:end);
   id=zeros(Nout,1);
   for ii=1:Nout
      i = strfind(out{ii},ch);
      if ~isempty(i)
         id(ii) = 1;
      end
   end
   out = out(find(id));
end
