function FileList = browse_study_folder(dir_name);
%BROWSE_STUDY_FOLDER - Find all *brainstormstudy.mat files in a directory tree
% function FileList = browse_study_folder(dir_name);
% Finds all studies in DIR_NAME and its subfolders
%  and stores the related information in FILELIST, a cell array of structures.
% dir_name must be an absolute directory name
% 
% FILELIST is a "dir" structure, plus the following features:
%  name is referential to include the dir_name, not just the name
%  Subject has subfields Name and SubjectFile, the namestring and the referential
%   filename for each study file
%  display is a prettyprint display of the name

%<autobegin> ---------------------- 14-Jun-2004 17:09:50 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Database Management
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\bst_message_window.m
%   toolbox\find_subdir.m
%   toolbox\get_user_directory.m
%
% At Check-in: $Author: Mosher $  $Revision: 20 $  $Date: 6/14/04 3:37p $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 14-Jun-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> ------------------------ 14-Jun-2004 17:09:50 -----------------------

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

% Script History
%
% JCM 25-Mar-2002 Cosmetic changes to strings, using %-s format
% SB  05-Apr-2002 Cosmetic changes to FileList.display for improved layout in listbox
% JCM 09-May-2002 handling filesep case at end of dir_name, adding n/a to keep deblank controlled
% JCM 04-Jun-2002 auto comments, cleaning, switched error message to bst_message_window
% SB  23-Jul-2002 Added StudyName field to FileList output and changed .name to .StudyFile
% SB  30-Jul-2002 Changed FileList.Display to display only the name of the Study folder and not
%                 the very name of the brainstormstudy file, asuuming there is only a single study file 
%                 per study folder.
% SB  01-Aug-2002 Sanity check on StudyName:
%                 Added ischar test on Name of Study. If ~ischar, Name is set to 'N/A' by default  
% -----------------------------------------------------

if(~strcmp(dir_name(end),filesep)), % doesn't end in a file separation 
   % since this is optional in windows, add it for a cleaner
   %  FileList name below that does not begin with a filesep
   dir_name(end+1) = filesep;
   % CHEAT: does this work in Unix too? A valid directory name in Windows
   %  optionally ends with a file separation parameter.
end

Users = get_user_directory;

if ~exist(dir_name,'dir')
    FileList = [];    
    bst_message_window('wrap',...
       [dir_name, ' is not a valid directory on this platform. ',...
          'Please reselect a valid database.']);
    return
end


% Looking for all subfolders within the study folder - recursive search
[subdirs] = find_subdir(dir_name); % alternative to genpath
% All names include the dir_name

% go first to the dir_name requested
cd(dir_name)

% Look for study files in current folder
FileList = dir('*brainstormstudy*.mat');

if length(FileList) > 1 % multiple studyfiles were found in this folder
    % Display warning
    errordlg(...
        {sprintf('Multiple BrainStormStudy files were found in %s.',dir_name),...
            sprintf('Please organize %s so that there is a single BrainStormStudyFile per Study folder.',...
            Users.STUDIES)...
        },'Problem with DataBase Organization')
    return
end

% Now browse every folder and look for study files
for k=1:length(subdirs)
    cd(subdirs{k})
    nFileList = dir('*brainstormstudy*.mat');
    subdirs{k} = strrep(subdirs{k},[dir_name],''); 
    if length(nFileList) > 1 % multiple studyfiles were found in this folder
        % Display warning
        errordlg(...
            {sprintf('Multiple BrainStormStudy files were found in %s.',subdirs{k}),...
                sprintf('Please organize %s so that there is a single BrainStormStudyFile per Study folder.',...
                Users.STUDIES)...
            },'Problem with DataBase Organization')
        return
    end
    % Make subdirs names relative to the study 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
end

% Change .name field to .StudyFile to make this more explicit
if(length(FileList)), % are there any files?
   for i = 1:length(FileList),
      FileList(i).StudyFile = FileList(i).name;
   end
   % remove old field
   FileList = rmfield(FileList,'name');
else
 % don't matter, there are no files
end

% back to where we started
cd(dir_name)

% make a pretty print line for each brainstormstudy
for k = 1:length(FileList)
    try        
        warnlevel = warning;
        warning off;       
        load(FileList(k).StudyFile,'Name','BrainStormSubject');
        warning(warnlevel);
        
        % Older study files with this variable not defined
        if ~exist('Name','var') % Older Study File
            Name = 'N/A';
        end
        FileList(k).StudyName = Name;
        
        Subj = load(fullfile(Users.SUBJECTS,BrainStormSubject),'Name');
        FileList(k).Subject.Name = Subj.Name;
        FileList(k).Subject.SubjectFile = BrainStormSubject;
    catch 
        FileList(k).Subject.Name = 'File not found';
        FileList(k).Subject.SubjectFile = '';
        Subj.Name ='N/A';
        Name = 'N/A';
    end
    
    [StudyDirName{k},file,ext] = fileparts(FileList(k).StudyFile);
    FileList(k).StudyFolder = StudyDirName{k};
    
    if ~isempty(Name)
        if ~ischar(Name)
            StudyName{k} = 'N/A';
        else
            StudyName{k} = Name;
        end
    else
        StudyName{k} = 'N/A'; % if all names blank, the deblank below causes crash
    end
    if ~isempty(Subj.Name)
        SubjectName{k} = Subj.Name;
    else
        SubjectName{k} = 'N/A';
    end
end

if(length(FileList)), % the list may have been empty
   % Now improve the layout of the final .display field
   StudyDirName = deblank(char(StudyDirName)); % Pad all names to same character length
   StudyName = deblank(char(StudyName));
   SubjectName = deblank(char(SubjectName));
   
   fmtstr = sprintf('%%-%ds | %%-%ds | %%-%ds',...
      size(StudyDirName,2),size(StudyName,2),size(SubjectName,2));
   
   for k = 1:length(FileList)
      FileList(k).display = sprintf(fmtstr,...
         strrep(StudyDirName(k,:),' ','.'),strrep(StudyName(k,:),' ','.'),strrep(SubjectName(k,:),' ','.'));
   end
end

