%FILENAME = GETFILE(MASK,TITLE)
%    Asks the user for a filename using a dialog box.

% (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, May 2000.
% 29 March 2001:     Using a 'current directory' for images.
% 6 August 2001:     Catching error possibly caused by CD.
% 12 October 2004:   Removed DEFUALT parameter, which was not being used.
% 18 September 2007: Don't use '*.*' on UNIX machines!

function filename = getfile(mask,title)
if nargin ~= 2 | (~ischar(mask) | ~ischar(title))
   error('Invalid input.')
end

cp = [pwd,filesep];
defdir = dipgetpref('CurrentImageFileDir');
if ~isempty(defdir)
   % Go to 'current directory'.
   try
      cd(defdir);
   catch
      warning('Non-existing directory referenced.');
      dipsetpref('CurrentImageFileDir','');
   end
else
   % Go to first directory specified in path.
   defdir = convertpath(dipgetpref('imagefilepath'));
   if ~isempty(defdir) & ~isempty(defdir{1})
      try
         cd(defdir{1});
      catch
         warning('Non-existing directory referenced.');
      end
   end
end
if isempty(mask)
   mask = '*.*';
end
if isunix & strcmp(mask,'*.*')
   mask = '*';
end
[filename,p] = uigetfile(mask,title);
% Return to original directory.
cd(cp);
if ~ischar(filename)
   % uigetfile returns [0,0] when the user presses CANCEL.
   filename = '';
else
   % This part removes the path if it is equal to the current path.
   if ~isunix
      p = lower(p);
      cp = lower(cp);
   end
   if ~strcmp(p,cp)
      filename = [p,filename];
   end
   dipsetpref('CurrentImageFileDir',p);
end
