function [DataDir,DataPopup,Leader] = find_brainstorm_files(Type,DirPath,hf);
%FIND_BRAINSTORM_FILES - Find BrainStorm subjects or study files, create Menu
% function [DataDir,DataPopup,Leader] = find_brainstorm_files(Type,DirPath,hf);
% Type is either 
%  "studies"
%  "subjects"
%  "tri" or "tess" for tessellation files
%  "data"
%  "results"
%  "anatomy" (subjectimage files)
%  "headmodel"
%  "ctf"
%  "neuromag"
%  "besa"
%  "neuroscan"
%  "gis image"
% If no DirPath is given or is null, searches the 
%  folders located in Users.STUDIES or Users.SUBJECTS; 
%  otherwise searches subfolders of DirPath.
% Returns cell array DataDir of referentially qualified directory names.
% Returns character array DataPopup with '|' separators needed for 
%  the uicontrol popup.
% Leader is such that fullfile(Leader,DataDir{i}) gives fully qualified name.
%
% If hf is given, and type is 'studies' or 'subjects', then a menubar is created
%  in the given figure.
%
% If Type is not 'studies' or 'subjects', then Type is assumed to be a specific
%  filename. The Users.STUDIES and Users.SUBJECTS are searched for exactly this
%  name, and the fully qualified filename is returned.
% 
% Run find_brainstorm_structure to get all files associated with name

%<autobegin> ---------------------- 12-Oct-2004 01:11:14 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Utility - General
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\find_subdir.m
%   toolbox\get_user_directory.m
%
% At Check-in: $Author: Mosher $  $Revision: 29 $  $Date: 10/11/04 11:32p $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 23-Sep-2004
% 
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
%    University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
%    Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
%    CNRS, Hopital de la Salpetriere, Paris, France
% 
% See BrainStorm website at http://neuroimage.usc.edu for further information.
% 
% Copyright (c) 2004 BrainStorm by the University of Southern California
% This software distributed  under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
% 
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 12-Oct-2004 01:11:14 -----------------------


% /---Script Authors--------------------------------------\
% |  *** John C. Mosher, Ph.D.                            |
% |  Biophysics Group                                    |
% |                                                       |
% |  *** Sylvain Baillet, Ph.D.                           |
% |  Cognitive Neuroscience & Brain Imaging Laboratory    |
% |  CNRS UPR640 - LENA                                   | 
% |  Hopital de la Salpetriere, Paris, France             |
% |  sylvain.baillet@chups.jussieu.fr                     |
% \-------------------------------------------------------/

% Date of creation: January 1999
%
% Script History -------------------------------------------------------------------------------------
% 06-Jun-1999     upgraded to bring out prefixes of the flagfiles
% 16-Jun-1999     modified to handle null returns on find files
% 26-Oct-1999     modified to handle specific filenames.
% 06-Nov-1999     modified to give REFERENTIAL file names, referenced to 
% ...........     Users.STUDIES or .SUBJECTS.  Used local variable Leader to distinguish
% 08-Apr-2002 SB  added 'headmodel' file type
% 16-Apr-2002 SB  gathered all file types in a shorter switchyard to keep file search general.
% ...........     and removed all reference to platform dependency.
% 29-Apr-2002 SB  Fixed typo in Header.
% ...........     Fixed search for general type of files (see 'otherwise' case on Type below).
% 24-May-2002 SB  Added 'tess' file type.
% ........... SB  Secured subdir search.
% ........... SB  Come back to original folder rather than stay in last visited folder  
% 27-May-2002 SB  Search for TESS files does not return associated VERTCONN and TRICONN files anymore
% 11-Jun-2002 JCM If DirPath is empty, set it to '.' (the current directory), also minor comments
%                 fixes.
% 09-Jul-2002 SB  Updated comments with all available file types
% 23-Jul-2002 SB  Added Neuromag and CTF file types (find_*_data.m are now obsolete and are deleted from Toolbox)
% 02-Sep-2002 SB  Return to original folder when no file was found.
% 31-Oct-2002 JCM referential names should not begin with \, so ensured DirPath ends in a filesep
% 03-Jun-2003 SB  Added the 'results' file type 
% 15-May-2004 JCM Added Pantazis "dsgl" modification for file type extension
% 17-May-2004 JCM Added Pantazis "dfs" modification
% 20-Jul-2004 DB  Added GIS and MESH formats
% 08-Oct-2004 DP  Changed EGI format
% ---------------------------------------------------------------------------------------------------

OrigFolder = pwd;

files = [];

if(~exist('Type')),
   DataDir = [];
   DataPopup = [];
   msgbox('FIND_BRAINSTORM_FILES, Must give Type of Studies or Subjects','Error','Modal');
   return
end

if(~exist('DirPath','var')), % user gave no input
   DirPath = []; % default
end

if(~exist('hf','var')), % user gave no figure
   hf = []; % set to empty
end

if(isempty(DirPath)),
   DirPath = '.'; % current directory
end

Users = get_user_directory;% the User directory information

Extension = '.mat'; % default extension, unless overridden below
switch lower(deblank(Type))
   case 'studies'
      FileString = 'brainstormstudy'; % File filter for the dir command
      %DirPath = Users.STUDIES; % Root directory for this file type.
   case 'subjects'
      FileString = 'brainstormsubject';
      %DirPath = Users.SUBJECTS;
   case 'tri'
      FileString = '';
      %DirPath = Users.SUBJECTS;
      Extension = '.tri';
   case 'mesh'
      FileString = '';
      %DirPath = Users.SUBJECTS;
      Extension = '.mesh';
   case 'dsgl'
      FileString = '';
      %DirPath = Users.SUBJECTS;
      Extension = '.dsgl';
   case 'dfs'
      FileString = '';
      %DirPath = Users.SUBJECTS;
      Extension = '.dfs';
   case 'tess'
      FileString = 'tess';
      FileStringFilter = {'vertconn','triconn'}; % don't return files with names that include both FileString and either of the FileStringFilter strings
   case 'results'
      FileString = 'results';
   case 'data'
      FileString = 'data';
      FileStringFilter = {'results'}; % don't return files with names that include both FileString and either of the FileStringFilter strings
   case 'anatomy'
      FileString = 'subjectimage';
      %DirPath = Users.STUDIES;
   case 'headmodel'
      FileString = 'headmodel';
      %DirPath = Users.STUDIES;
      
      % below are system files that we seek, where the type is a System name from
      %  {'magnes','ctf','neuromag','neuroscan','egi','prn','raw'}
      % See importdata routine and the "create" switchyard case for valid
      % Systems
      
   case 'magnes'
     % unknown at this time
      FileString = ''; % No specific string in file name
      Extension = '.magnes'; % extension is specific       
   case 'besa'
       % BESA ASCII file format
       FileString = ''; % No specific string in file name
       Extension = '.avr'; % extension is specific 
   case 'ctf'
      FileString = ''; % No specific string in file name
      Extension = '.ds'; % extension is specific 
   case 'neuromag'
      FileString = ''; % No specific string in file name
      Extension = '.fif';  % extension is specific       
   case 'neuroscan'
      % Neuroscan binary EEG format
      FileString = ''; % No specific string in file name
      Extension = '.avg'; % extension is specific 
   case 'egi'
      % unknown at this time
      FileString = ''; % No specific string in file name
      Extension = '.raw'; % extension is specific 
   case 'prn'
      % unknown at this time
      FileString = ''; % No specific string in file name
      Extension = '.prn'; % extension is specific 
   case 'raw'
      FileString = ''; % No specific string in file name
      Extension = '.raw'; % extension is specific 
  case 'gis image' % GIS MRI format -> see [http://brainvisa.info]
      FileString = ''; % No specific string in file name
      Extension = '.ima'; % extension is specific 
      
  otherwise % try handling as a default case
      FileString = Type;
      Extension = '';
end

% we need DirPath to end in a file separator, in order to cleanly remove
if(~strcmp(DirPath(end),filesep)),
   DirPath(end+1) = filesep;
end

Leader = DirPath; % prefix on the file names


FileList = dir(fullfile(DirPath,sprintf('*%s*%s',FileString,Extension)));
[subdirs] = find_subdir(DirPath); % Looking for all subfolders within current folder - recursive search

dirinit = pwd;
% Now browse every folder and look for files of requested type
for k=1:length(subdirs)
   cd(subdirs{k})
   nFileList = dir(fullfile(subdirs{k},sprintf('*%s*%s',FileString,Extension))); % New file list
   subdirs{k} = strrep(subdirs{k},[DirPath],''); % Make subdirs names relative to root folder
   for kk = 1:length(nFileList)
      nFileList(kk).name = fullfile(subdirs{k},nFileList(kk).name);
   end
   FileList(end+1:end+length(nFileList)) = nFileList; % Add study files to the list
   cd(dirinit)
end


if exist('FileStringFilter','var') % Filter out  some file names that contain string FileStringFilter.
   iok = []; % Indices of the filenames that does not contain FileStringFilter
   for k=1:length(FileList)    
      for filt = 1:length(FileStringFilter)
         if ~isempty(strfind(FileList(k).name,FileStringFilter{filt}))
            iFlag = 1;
         end
      end
      if ~exist('iFlag','var')
         iok = [iok,k]; % Keep this file
      end
      
      clear('iFlag')
      
   end
   
   FileList = FileList(iok);
   
end

try % Secured file search
   cd(DirPath)
catch
   try 
      cd(fullfile(Users.STUDIES,DirPath))
   catch
      cd(fullfile(Users.SUBJECTS,DirPath))
   end
end

if(isempty(FileList)), % there are no files to process   
   % there ain't nothing to process
   DataDir = [];
   DataPopup = [];   
   cd(OrigFolder) % Go back to original calling folder
   return   
else
   FileList = {FileList.name};
end

%Leader = deblank(lower(Leader)); % reduced sensitivity
if(~strcmp(Leader(end),filesep)),
   % does not end in a file separator, add one
   Leader(end+1) = filesep;
end

% 11/6/99 remove the Leader to make a referential list
filess = FileList;
%FileList = strrep(FileList,fullfile(Users.STUDIES,Leader),'');
FileList = strrep(FileList,Leader,'');

DataPopup = char(FileList{:});
DataDir = FileList;

% switch lower(deblank(computer))
% case 'pcwin'
%     %ndx = findstr(char(FileList),sprintf('\n')); 
%     ndx = strmatch(FileList,sprintf('\n')); 
%     % the popup button needs these separated by '|'.
%     DataPopup = FileList; % map the character array
%     if ~isempty(ndx)
%         DataPopup(ndx(1:(end-1))) = '|'; % replace all but the last linefeed
%         DataPopup(ndx(end)) = []; % remove the last linefeed
%         % need convenient cell array. string is already terminated with linefeed
%         DataDir = cell(1,length(ndx)); % null entries
%         ndx = [0 ndx];  %prepend zero
%         
%         % scan through the string, parsing by EOL
%         for i = 1:(length(ndx)-1),
%             temp = FileList([(ndx(i)+1):(ndx(i+1)-1)]);
%             DataDir{i} = temp;
%         end
%     else
%         DataDir = DataPopup;
%     end
%     
% otherwise
%     ndx = 1:length(FileList);
%     DataPopup = FileList; % map the character array
%     for k = 1:length(FileList)
%         %[path,name,ext,ver] = fileparts(filess{k});
%         %tmp = strrep(filess{k},path,'');
%         %DataDir{k} = strrep(tmp,FileList{k},'');
%         DataDir{k} = FileList{k};
%     end
% end


if(~isempty(hf)), % user wants pull down menu of files
   switch lower(deblank(Type))
      case 'studies'
         
         hu = findobj(hf,'Tag','UimenuBSTStudy');
         if(~isempty(hu)), % existing menu
            delete(hu);
         end
         hu = uimenu(hf,'Label','BrainStorm Study','Tag','UimenuBSTStudy');
         
         for i = 1:length(DataDir),
            uimenu(hu,'Label',DataDir{i},'Callback',...
               sprintf('taskbar_userdata(find_brainstorm_structure(''%s''));',DataDir{i}));
         end
         if(0), % 11/4/99 JCM we don't need this
            uimenu(hu,'Label','Refresh Studies','Callback',...
               sprintf('find_brainstorm_files(''studies'',[],%.0f);',hf),...
               'Separator','On','Position',length(DataDir)+1);
         end
         
      case 'subjects'
         
         hu = findobj(hf,'Tag','UimenuBSTSubject');
         if(~isempty(hu)), % no menu
            delete(hu);
         end
         hu = uimenu(hf,'Label','BrainStorm Subject','Tag','UimenuBSTSubject','Position',11);
         
         for i = 1:length(DataDir),
            uimenu(hu,'Label',DataDir{i},'Callback',...
               sprintf('taskbar_userdata(find_brainstorm_structure(''%s''));',DataDir{i}));
         end
         if(0), % 11/4/99 JCM we don't need this
            uimenu(hu,'Label','Refresh Subjects','Callback',...
               sprintf('find_brainstorm_files(''subjects'',[],%.0f);',hf),...
               'Separator','On','Position',length(DataDir)+1);
         end
         
      otherwise
         % do nothing, we were looking for a file
   end
end

cd(OrigFolder) % Go back to original calling folder
