function UserDefault = make_default_database(isAll, NameOnly);
%MAKE_DEFAULT_DATABASE - Confirm or Create a default database, default study, default subject
% function UserDefault = make_default_database(isAll, NameOnly);
% Call this routine to get the correct convention on default data used in BrainStorm.
% Confirm or create a default database exists in the BrainStorm home directory.
% Confirm or create a default data folder and default subject folder in the
%  default database.
% Confirm or create a default data folder and default subject folder in every
%  database of the user. When creating a new study or subject in a database, simply copy
%  the example in the default database.
% isAll and NameOnly are logicals, {0,1}.
% If isAll (optional, default 0, i.e. not all),
%  then apply to all directories in the database,
% else just apply to the current database.
%
% If NameOnly (optional, default 0), the confirm the default names only, do not create.
%
%
% Returns the structure UserDefault with fields
%  .Comment the name of the default user database, e.g. "Default Database"
%  .STUDIES the full path of the default study in the default database
%  .SUBJECTS the full path of the default subject in the default database
%  .FILELIST the list of files in the STUDIES, in browse_study_folder format
% and this structure is augmented by the following fields for convenience
%  .StudyName the default name of the study folder, e.g. 'default_study' without the
%             directory path prepended.
%  .SubjectName the default name of the subject folder
%
% See also MAKE_DEFAULT_SUBJECT, MAKE_DEFAULT_STUDY

%<autobegin> ---------------------- 26-May-2004 11:30:52 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Database Management
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\browse_study_folder.m
%   toolbox\bst_message_window.m
%   toolbox\make_default_study.m
%   toolbox\make_default_subject.m
%
% Group : Preference data and their calls in this file:
%   'BrainStorm' : 'UserDataBase'
%   'BrainStorm' : 'iUserDataBase'
%   
%   setpref('BrainStorm','UserDataBase',UserDB);
%   setpref('BrainStorm','iUserDataBase',i);
%   setpref('BrainStorm','iUserDataBase',iDefault);
%   setpref('BrainStorm','iUserDataBase',iUserDB);
%   setpref('BrainStorm',{'UserDataBase','iUserDataBase'},{UserDB,1});
%   setpref('BrainStorm',{'UserDataBase','iUserDataBase'},{UserDB,iDefault});
%   setpref('BrainStorm',{'UserDataBase','iUserDataBase'},{UserDB,iUserDB});
%   
%   UserDB = getpref('BrainStorm','UserDataBase');
%   UserDB = getpref('BrainStorm','UserDataBase',[]);
%   brainstormHomeDir = getpref('BrainStorm','brainstormHomeDir');
%   iUserDB = getpref('BrainStorm','iUserDataBase',1);
%
% At Check-in: $Author: Mosher $  $Revision: 26 $  $Date: 5/26/04 9:59a $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 24-May-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> ------------------------ 26-May-2004 11:30:52 -----------------------

% ----------------------- History -----------------
% JCM 15-AUG-2003  First design
% JCM  5-SEP-2003  Changed "Study" to "Data" in the folder name
%                  only. Internally, we will still call the data folder
%                  a "study folder" 
% JCM 11-Sep-2003  Concentrate all "default" activity through here, so that we remain 
%                  consistent on our use of defaults. Added output structure. Search
%                  the database making sure all is okay with the default structure.
%                  Create a default database in the BrainStorm home area, if needed.
%                  When making new defaults in the user's areas, simply copy the files
%                  kept in the BrainStorm home default database.
% SB 17-Oct-2003   Uses brainstormHomeDir preference
% SB 16-Feb-2004   SETPREF is a pretty time-greedy function - made tiny changes with less calls
%                  See also CBB about what should be considered as a default database
% -------------------------------------------------


% In routine use, this function should go quickly, simply confirming the existence
%  of default directories. In reset cases, will rebuild the defaults.


% --------------- Set the parameters of this script ---------------------------
% note that for considerations of mixed-case operating systems, folders should be lower case
% The following names are the same in the user's BrainStorm folder and all of his databases
DB_COMMENT = 'Default Database'; % the name of the default database
DEFAULT_DATABASE = 'default_database'; % name of folder in the home directory
STUDY_NAME = 'default_data'; % the name of the default data folder in the root folder
SUBJECT_NAME = 'default_subject'; % the name of the default subject folder in the root folder
% note that user can shove other datasets into the default_database as well

% check input parameter
if ~exist('isAll','var') | isempty(isAll),
    isAll = 0; % only confirm the current database for defaults
end

if ~exist('NameOnly','var') | isempty(NameOnly),
    NameOnly = 0; % assume want creation as well as confirmation
end


% ----------------- Confirm/Create the default database -----------------------
% setup the directories in the BrainStorm directory
% the following command line may return other startup files that are sitting in e.g. the PublicToolbox folder
% need a more systematic way of finding BrainStorm home directory.
%brainstormHomeDir = fileparts(which('startup.m')); % user's brainstorm directory
try
    brainstormHomeDir = getpref('BrainStorm','brainstormHomeDir');
catch
    brainstormHomeDir = fileparts(which('startup.m')); % user's brainstorm directory
end

% go there
cd(brainstormHomeDir)

% build the full filenames of the defaults in the home directory
defaultDatabase = fullfile(brainstormHomeDir,DEFAULT_DATABASE);
defaultStudy = fullfile(brainstormHomeDir,DEFAULT_DATABASE,STUDY_NAME);
defaultSubject = fullfile(brainstormHomeDir,DEFAULT_DATABASE,SUBJECT_NAME);


% ------------ Confirm the existence of a user database ---------------
UserDB = getpref('BrainStorm','UserDataBase',[]); % creates and returns empty if none
iUserDB = getpref('BrainStorm','iUserDataBase',1); % which database are we pointing at now, default 1

% initialize
isUserDataBase = logical(0); % no user database
isDefaultDataBase = logical(0); % no default data base
iDefault = NaN; % no default database index

if(~isempty(UserDB)),
    
    % there is an existing database
    isUserDataBase = logical(1);
    % Is there a default database?
    tmp = strcmp(DB_COMMENT,{UserDB.Comment}); % lookfor the default comment
    
    if any(tmp),
        % There is a default database
        % we only want one, take the first one
        tmpndx = find(tmp); % the default databases
        if length(tmpndx) > 1,
            UserDB(tmpndx(2:end)) = []; % remove them
            iUserDB = tmpndx(1); % set to the first
            
            % save the reduced database
            setpref('BrainStorm',{'UserDataBase','iUserDataBase'},{UserDB,iUserDB}); 
        end
        tmpndx = tmpndx(1); % trim the reset
        
        % the remaining one, is it valid?
        if strcmp(UserDB(tmpndx).STUDIES,defaultDatabase) & strcmp(UserDB(tmpndx).SUBJECTS,defaultDatabase)
            if exist(defaultStudy,'dir') & exist(defaultSubject,'dir')
                isDefaultDataBase = logical(1);
                iDefault = tmpndx;
            end
            
        else
            % SB Comment | CBB - it's a bit too drastic here. A database is valid as long as directories exist
            % default database should be the one created when no database is found when brainstorm starts
            
            % it has invalid entries
            UserDB(tmpndx) = []; % remove it
            % save the reduced database
            setpref('BrainStorm',{'UserDataBase','iUserDataBase'},{UserDB,1}); 
            
            if isempty(UserDB),
                % we wiped out the database
                isUserDataBase = logical(0);
            end
        end
    end
end

% setup a temporary default structure with an empty filelist.
% Want to avoid creating filelist for the default everytime.
UserDefault(1) = struct('Comment',DB_COMMENT,...
   'STUDIES',defaultDatabase,'SUBJECTS',defaultDatabase,'FILELIST',[]);

if NameOnly,
   % we just wanted the names, no action
   return   
end

% do these folders exist in the home directory?
% if not, create them
if ~exist(defaultDatabase),
% CBB, would check the status of the creation.
   [status, message] = mkdir(brainstormHomeDir,DEFAULT_DATABASE);
end

% now make the folders inside this database
if ~exist(defaultStudy,'dir'),
% CBB, would check the status of the creation.
   [status, message] = mkdir(defaultDatabase,STUDY_NAME);
end

if(~exist(defaultSubject,'dir')),
% CBB, would check the status of the creation.
   [status, message] = mkdir(defaultDatabase,SUBJECT_NAME);
end

% we will populate these folders below



% -------- Now ensure that UserDataBase points to the default

if ~isUserDataBase,
   % no present database preferences
   
   UserDB = UserDefault;
   iDefault = 1;
   iUserDB = 1;
   
else
   % there is an existing database
   
   if ~isDefaultDataBase,
      % no default database
      UserDB = [UserDefault UserDB]; % make it the first
      iDefault = 1;
      iUserDB = iUserDB + 1; % current database item gets bumped up one
   end
   
end

% now set these preferences to the default
if 0 % deprecated code | SB 16-Feb-2004
    setpref('BrainStorm','UserDataBase',UserDB);
    setpref('BrainStorm','iUserDataBase',iDefault);
else
    setpref('BrainStorm',{'UserDataBase','iUserDataBase'},{UserDB,iDefault}); % Speeds up the execution
end



% with the UserDataBase pointing at the default, see if any default data are needed
cd(defaultSubject)
tmp = dir('*.mat'); % any mat files in here?
if isempty(tmp)
   % we had to make a new default subject folder. Populate it
   make_default_subject(SUBJECT_NAME);
end

% similarly
cd(defaultStudy)
tmp = dir('*.mat'); % any mat files in here?
if isempty(tmp)
   make_default_study(STUDY_NAME,SUBJECT_NAME);
   % find all of the new files now in the folder
   FILELIST = browse_study_folder(UserDB(iDefault).STUDIES); %update
   UserDB(iDefault).FILELIST = FILELIST;
   setpref('BrainStorm','UserDataBase',UserDB); % rewrite   
end



% ----------- Now confirm/create the defaults in the full user database ---------

UserDB = getpref('BrainStorm','UserDataBase'); % retrieve again for insurance
% locate again the default database
tmp = strcmp(DB_COMMENT,{UserDB.Comment}); % lookfor the default comment
iDefault = min(find(tmp)); % first instance of the default database

% get all the files in these default directories
DefaultStudyFiles = dir(fullfile(defaultStudy,'*.mat'));
DefaultSubjectFiles = dir(fullfile(defaultSubject,'*.mat'));

% reduce to just the filenames
DefaultStudyFiles = {DefaultStudyFiles.name};
DefaultSubjectFiles ={DefaultSubjectFiles.name};

% and now convert to full filenames
for i = 1:length(DefaultStudyFiles),
   DefaultStudyFiles{i} = fullfile(defaultStudy,DefaultStudyFiles{i});
end
for i = 1:length(DefaultSubjectFiles),
   DefaultSubjectFiles{i} = fullfile(defaultSubject,DefaultSubjectFiles{i});
end

% we will use this list of filenames to copy to any new defaults created below


% Are all of the existing databases valid disk locations?
% Do all of the existing databases have a default study and subject?
inValid = zeros(1,length(UserDB)); % we may find invalid directories

if isAll, % input parameter
   ndx = 1:length(UserDB); % update all databases
else
   ndx = iUserDB; % only update the current
end

for i = ndx,
   
   % first check for the validity of the database folders
   if ~exist(UserDB(i).STUDIES,'dir') | ~exist(UserDB(i).SUBJECTS,'dir')
      % one of the directories does not exist!
      inValid(i) = 1; % it's invalid
      msg1 = [];
      msg2 = [];
      % build an error message to the user
      if ~exist(UserDB(i).STUDIES,'dir'),
         msg1 = sprintf(['Your Data root folder, %s,  does not exist ', ...
               'setting you to default'],UserDB(i).STUDIES);
      end
      if(~exist(UserDB(i).SUBJECTS,'dir')),
         msg2 = sprintf(['Your Subjects root folder, %s,  does not exist ', ...
               'setting you to default'],UserDB(i).SUBJECTS);
      end
      bst_message_window('wrap',{msg1,msg2,...
            sprintf('Recommend you Edit Database ''%s'' to correct',UserDB(i).Comment)});
      
   else
      % the directory locations test as valid.
   
      % Earlier versions, does this database have the "FILELIST" convention?
      if ~isfield(UserDB(i),'FILELIST') 
         % DB is too old - update by adding field FILELIST
         bst_message_window('Updating FILELIST structure. . .')
         UserDB(i).FILELIST = browse_study_folder(UserDB(k).STUDIES);
         % note that other database entries will be automatically updated to empty entries
         %  which can later be populated by the correct FILELIST. For speed considerations,
         %  only update the ith entry here.
         setpref('BrainStorm','UserDataBase',UserDB);
      end
      
      % build the full filenames of the defaults in the next directory
      thisDefaultStudy = fullfile(UserDB(i).STUDIES,STUDY_NAME);
      thisDefaultSubject = fullfile(UserDB(i).SUBJECTS,SUBJECT_NAME);
      setpref('BrainStorm','iUserDataBase',i); % set the database indexer to this database
      
      % do these default folders exist in this directory
      if ~exist(thisDefaultStudy,'dir'),
         
         bst_message_window('wrap',sprintf(...
            'Creating default data folder in %s.',UserDB(i).STUDIES));
         
         mkdir(UserDB(i).STUDIES,STUDY_NAME);
         
      end
      
      if ~exist(thisDefaultSubject,'dir'),
         
         bst_message_window('wrap',sprintf(...
            'Creating default subject folder in %s.',UserDB(i).SUBJECTS));
         
         mkdir(UserDB(i).SUBJECTS,SUBJECT_NAME);
         
      end
      
      % Are they empty? Then need a copy of the default database in here
      % Simply copy the existing default database files
      cd(thisDefaultStudy)
      tmp = dir('*.mat');
      if(isempty(tmp)),
         for jFile = 1:length(DefaultStudyFiles),
            copyfile(DefaultStudyFiles{jFile},thisDefaultStudy);
         end 
         bst_message_window('Updating FILELIST structure. . .')
         UserDB(i).FILELIST = browse_study_folder(UserDB(i).STUDIES); % update
      end
       
      cd(thisDefaultSubject)
      tmp = dir('*.mat');
      if(isempty(tmp)),
         % now simply copy the existing default database files
         for jFile = 1:length(DefaultSubjectFiles),
            copyfile(DefaultSubjectFiles{jFile},thisDefaultSubject);
         end 
      end
         
      
      % and finally, if the FILELIST is empty, repopulate it
      if isempty(UserDB(i).FILELIST),
         bst_message_window('Updating FILELIST structure. . .')
         UserDB(i).FILELIST = browse_study_folder(UserDB(i).STUDIES); % update
      end
      
      
   end % if the folders are valid disk locations
   
end % for each database found

% clean up
% now save to preferences the updated UserDB
if 0 % deprecated code | SB 16-Feb-2004
    setpref('BrainStorm','UserDataBase',UserDB);
    setpref('BrainStorm','iUserDataBase',iUserDB);
else
    setpref('BrainStorm',{'UserDataBase','iUserDataBase'},{UserDB,iUserDB}); % Speeds up the execution
end

    
% put us back in the original root data folder
if isdir(UserDB(iUserDB).STUDIES),
   cd(UserDB(iUserDB).STUDIES); 
end


% now finish building the output structure with some custom fields, convenient
UserDefault.StudyName = STUDY_NAME;
UserDefault.SubjectName = SUBJECT_NAME;
