function StudySubject = find_brainstorm_structure(Fname);
%FIND_BRAINSTORM_STRUCTURE - Find all of the available files with a subject or study
% function StudySubject = find_brainstorm_structure(Fname);
% function StudySubject = find_brainstorm_structure(fname);
% fname must contain either "brainstormstudy.mat" or "brainstormsubject.mat"
% fname is assumed to be referentially qualified only, no fully qualified names allowed.
% If a study file, then program attempts to find the corresponding 
%  subject information as well, Study.BrainStormSubject
% Note that StudySubject.Data and StudySubject.Results are returned always as cell
%  arrays for possible multiple files.

%<autobegin> ---------------------- 09-Jul-2004 22:17:05 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Utility - General
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\get_user_directory.m
%   toolbox\load_brainstorm_file.m
%
% Subfunctions in this file, in order of occurrence in file:
%   k = findstrc(s1,c1);
%   [subdirs] = find_subdir(dirname);
%
% At Check-in: $Author: Mosher $  $Revision: 17 $  $Date: 7/09/04 8:42p $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 09-Jul-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> ------------------------ 09-Jul-2004 22:17:05 -----------------------

% 11/6/99 JCM adjust to handle referential filenames
% 12/2/99 JCM further adjusting
% 01-May-2002 JCM force everything lowercase for pattern matching

% keywords
SUBJECT = 'brainstormsubject.mat';
STUDY =   'brainstormstudy.mat';

% Fname is the original spelling of the name,
%  fname is the lower case version

fname = deblank((Fname)); % reduced sensitivity in pattern matching: removed because causes too many pbs under Linux  
SUBJECT = deblank((SUBJECT));
STUDY = deblank((STUDY));

% now figure out which keyword this is
iSuffix = findstr(fname,SUBJECT);
if(~isempty(iSuffix)), % found a subject match
   SUFFIX = SUBJECT;
else % not a match
   iSuffix = findstr(fname,STUDY);
   if(isempty(iSuffix)), % not a match either
      % don't know what this is
      msgbox(sprintf('FIND_BRAINSTORM_STRUCTURE: Invalid StudySubject File: %s',fname),'Error','modal');
      return
   end
   SUFFIX = STUDY;
end

User = get_user_directory; % the default user directories, remove from filenames for referential calls
%User.STUDIES = lower(User.STUDIES); % for case insensitivity
%User.SUBJECTS = lower(User.SUBJECTS);

% so now SUFFIX is set to SUBJECT or STUDY
PREFIX = fname(1:(iSuffix-1)); % the prefix before the keyword. Used to search for other names
% remove the database location,if already attached
PREFIX = strrep(PREFIX,(User.STUDIES),'');
PREFIX = strrep(PREFIX,(User.SUBJECTS),'');


% define the structure. Note that these are key names as well. The corresponding filename
%  must contain these names (filenames are assumed case insensitive. On unix, they should be lowercase).
StudySubject = struct(...
   'Subject',[],...
   'Study',[],...  
   'SubjectImage',[],...
   'SubjectTess',[],...
   'SubjectTriConn',[],...
   'SubjectVertConn',[],...
   'Channel',[],...
   'HeadModel',[],...
   'Data',[],...
   'Results',[]);

% now process according to which case

if(strcmp(SUFFIX,SUBJECT)),
   % this one is easy, since the info is loaded in the subject file
   % It's redundant to load into StudySubject, but it is handy.
   
   % load up some of the pre-determined information in the brainstormstudy file
   StudySubject.Subject = Fname;
   tempbsstudy = load_brainstorm_file(fullfile(User.SUBJECTS,Fname));
   if ~isfield(tempbsstudy,'Tesselation')
       tempbsstudy.Tesselation = [];
   end
   StudySubject.SubjectTess = tempbsstudy.Tesselation; % use the preset tesselation
   if ~isfield(tempbsstudy,'Anatomy')
       tempbsstudy.Anatomy = [];
   end
   StudySubject.SubjectImage = tempbsstudy.Anatomy; % FIX: What is anatomy vs SubjectImage?
   
   
elseif(strcmp(SUFFIX,STUDY)),
   
   % this one is harder, we have to look for possibly lots of files
   Leader = deblank((fullfile(User.STUDIES,PREFIX))); % precedes all names
      
   switch computer
   case 'PCWIN'
      % find all Matlab .mat files in the same directory with the same prefix
      [s,files] = dos(sprintf('dir %s /s /b',sprintf('%s',[Leader,'*.mat'])));
      % files is a string array of fully qualified file names
   
      ndx = findstr(files,char(10)); 
      Files = cell(1,length(ndx));
      ndx = [0 ndx];  %prepend zero
      % scan through the string, parsing by EOL
      for i = 1:(length(ndx)-1),
         temp = files([(ndx(i)+1):(ndx(i+1)-1)]);
         %temp = lower(temp); % for case insensitivity
         % remove the user directory for portability
         temp = strrep((temp),(User.STUDIES),'');
         Files{i} = temp;
      end
   otherwise
      [path,name,ext,ver] = fileparts(Leader);
      filess = what(path);
      filess = filess.mat;
      i=0;
      for k = 1:length(filess)
         if findstr(filess{k},name)
            i = i+1;
            Files{i} = (fullfile(path,filess{k}));
            Files{i} = strrep(Files{i},(User.STUDIES),'');
         end
      end
   end % other cases were rejected above
   
   
   % So now Files is a cell array of all potential names with the same prefix
   % Match them up
   
   % the fieldnames contain the flag strings for the filenames
   Names = lower(fieldnames(StudySubject)); % get all of the names into a cell array
   oNames = (fieldnames(StudySubject)); % Field names are case-sensitive in BrainStorm
   for i = 1:length(Names),
      % use local function below
      k = findstrc(deblank((Names{i})),(Files)); % local function, any matches?
      if(any(k)), % we have a match
         
         switch deblank((Names{i}))
         case 'study'
            % do nothing, handled elsewhere
         case 'subject'
            % do nothing, handled elsewhere
         case 'data'
            % first remove any that have the word 'results' in them
            kndx = find(k); % valid data file
            k1 = findstrc('results',(Files(kndx)));
            k1ndx = find(k1==0); % subindex of names without 'results'
            % collect all applicable into cell structure
            StudySubject = setfield(StudySubject,'Data',Files(kndx(k1ndx)));
         case 'results'
            % collect all applicable into cell structure
            StudySubject = setfield(StudySubject,'Results',Files(find(k)));
         case {'tess' ,'image'}
            % do nothing, loaded in subject editor
         otherwise
            % collect first one into string
            StudySubject = setfield(StudySubject,oNames{i},Files{min(find(k))});
         end
         
      end
   end
   
   % now clean up 
   
   StudySubject.Study = Fname;
   % can we find the subject for this one?
   Study = load(fullfile(User.STUDIES,StudySubject.Study));
   StudySubject.Subject = Study.BrainStormSubject;
   if(~isempty(StudySubject.Subject)), % non-empty name
      if(exist(fullfile(User.SUBJECTS,StudySubject.Subject),'file')==2)
         % get the subject information with recursive call to this routine
         tempSubject = feval(mfilename,StudySubject.Subject);
         Names = fieldnames(tempSubject); % extract the names
         for i = 1:length(Names),
            temp = getfield(tempSubject,Names{i});
            if(~isempty(temp)),
               % information returned for subject, avoids overwriting study information
               StudySubject = setfield(StudySubject,Names{i},temp);
            end
         end
      else
         % FIX: doesn't appear to be a valid filename, help the user append a subject name
      end
   else
      % Subject name is empty, FIX: help the user
   end
   
end % "case switch" looking for subject or study data


return


%-----------------------------------------------------------------------
function k = findstrc(s1,c1);
% return vector k with 0 or 1 to indicate if string s1 is found in the strings of 
%  cell array c1

k = zeros(1,length(c1));

for i = 1:length(c1),
   if(~isempty(findstr(s1,c1{i}))),
      k(i) = 1;
   end
end

%-----------------------------------------------------------------------
function [subdirs] = find_subdir(dirname);
%function [subdirs] = find_subdir(dirname);
% Find all the subdirectories within dirname and
% return them is the cell array subdirs

cd(dirname)
D = dir(dirname);
for i = 1:length(D),
   if findstr(D(i).name,'..'),
      D(i).isdir = logical(0);  % don't want it
   end  
end
D = D([D.isdir]);

subdirs = {D.name};
if ~isempty(subdirs)
   for k = 1:length(subdirs)
      sub_subdirs{k} = fullfile(dirname,subdirs{k});
   end
   subdirs  = sub_subdirs;
else
   sub_subdirs = [];
end

for d = 1:length(D)
   sub_subdirs = find_subdir(fullfile(dirname,D(d).name));
   
   while 0%~isempty(sub_subdirs)
      subdirs = [subdirs,sub_subdirs];
      for k = 1:length(sub_subdirs)
         sub_subdirs = find_subdir(fullfile(dirname,sub_subdirs));
      end
   end
   
   subdirs = [subdirs,sub_subdirs];
   
end
disp('')
