function varargout = data_manager(varargin)
%DATA_MANAGER - Edit/select database, subjects, studies, datasets, build headmodels, import data.
% function varargout = data_manager(varargin)
%    FIG = DATA_MANAGER launch data_manager GUI.
%    DATA_MANAGER('callback_name', ...) invoke the named callback.
%
% This GUI concentrates a lot of data management. The user can edit/select the
%  database. The information in any study or subject can be edited. Data from
%  the vendors and in ASCII format can be loaded.  Tesselation files can be
%  loaded through the subject editor. Headmodels for any study can be generated.
% 
% In addition to generating the appropriate Mat-files, a primary output of this
%  manager is the setting of the structures in the BrainStorm Taskbar, which
%  allows other routines to determine exactly what data the user wants in the
%  other routines. Use get_user_directory to retrieve this structure. This
%  structure is also mirrored in the BrainStorm Preferences, so that subsequent
%  sessions can begin at the last point, or batch routines can be run.

%<autobegin> ---------------------- 14-Jun-2004 17:10:24 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: GUI and Related
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\browse_study_folder.m
%   toolbox\bst_color_scheme.m
%   toolbox\bst_headmodeler.m
%   toolbox\bst_layout.m
%   toolbox\bst_message_window.m
%   toolbox\bst_static_taskbar.m
%   toolbox\bst_win_manager.m
%   toolbox\data_manager.m  NOTE: Routine calls itself explicitly
%   toolbox\database_manager.m
%   toolbox\dataplot_cb.m
%   toolbox\engstr.m
%   toolbox\find_brainstorm_files.m
%   toolbox\get_channel.m
%   toolbox\get_user_directory.m
%   toolbox\good_channel.m
%   toolbox\headmodeler_gui.m
%   toolbox\importdata.m
%   toolbox\make_default_database.m
%   toolbox\makeuswait.m
%   toolbox\mritool_cb.m
%   toolbox\save_fieldnames.m
%   toolbox\study_editor.m
%   toolbox\subject_editor.m
%
% Subfunctions in this file, in order of occurrence in file:
%   initialize_database(handles); % initialize the database portion
%   load_listbox_Study(handles);
%   varargout = popup_CurrentDatabase_Callback(h, eventdata, handles, varargin)
%   varargout = StudyFolder_Callback(h, eventdata, handles, varargin)
%   varargout = SubjectFolder_Callback(h, eventdata, handles, varargin)
%   varargout = listbox_Study_Callback(h, eventdata, handles, varargin)
%   varargout = listbox_Data_Callback(h, eventdata, handles, varargin)
%   varargout = LoadSelectedData_Callback(h, eventdata, handles, varargin)
%   varargout = menu_close_Callback(h, eventdata, handles, varargin)
%   varargout = menu_import_data_Callback(h, eventdata, handles, varargin)
%   varargout = menu_edit_subject_Callback(h, eventdata, handles, varargin)
%   varargout = menu_edit_study_Callback(h, eventdata, handles, varargin)
%   varargout = menu_edit_database_Callback(h, eventdata, handles, varargin)
%   varargout = menu_edit_rebuild_Callback(h, eventdata, handles, varargin)
%   varargout = menu_view_information_Callback(h, eventdata, handles, varargin)
%   varargout = menu_view_datafiles_Callback(h, eventdata, handles, varargin)
%   varargout = menu_view_results_Callback(h, eventdata, handles, varargin)
%   varargout = menu_pooled_define_Callback(h, eventdata, handles, varargin)
%   varargout = menu_pooled_allow_Callback(h, eventdata, handles, varargin)
%   varargout = ComputeDefaultHeadModel_Callback(h, eventdata, handles, varargin)
%   varargout = pushbutton_CoRegisterStudies_Callback(h, eventdata, handles, varargin)
%   varargout = DataInformation_Callback(h, eventdata, handles, varargin)
%   varargout = HeadModelAdvanced_Callback(h, eventdata, handles, varargin)
%   varargout = pushbutton_importdata_Callback(h, eventdata, handles, varargin)
%   varargout = RefreshHeadModelList_Callback(h, eventdata, handles, varargin)
%   varargout = Manage_DataBase_Callback(h, eventdata, handles, varargin)
%   varargout = ResultFiles_Callback(h, eventdata, handles, varargin)
%   varargout = DataFiles_Callback(h, eventdata, handles, varargin)
%   varargout = StudyBatch_Callback(h, eventdata, handles, varargin)
%   varargout = MRITool_Callback(h, eventdata, handles, varargin)
%   varargout = HeadModelList_Callback(h, eventdata, handles, varargin)
%   varargout = pushbutton_LoadView_Callback(h, eventdata, handles, varargin)
%   varargout = StudyFile_Callback(h, eventdata, handles, varargin)
%   varargout = SubjectFile_Callback(h, eventdata, handles, varargin)
%   varargout = Quit_Callback(h, eventdata, handles, varargin)
%   varargout = Refresh_Callback(h, eventdata, handles, varargin)
%
% Group : Preference data and their calls in this file:
%   'BrainStorm' : 'CurrentData'
%   'BrainStorm' : 'Studies'
%   'BrainStorm' : 'Subjects'
%   'BrainStorm' : 'UserDataBase'
%   'BrainStorm' : 'iUserDataBase'
%   
%   setpref('BrainStorm','CurrentData',CurrentData);
%   setpref('BrainStorm','CurrentData',Users.CurrentData);
%   setpref('BrainStorm','Studies', Studies);
%   setpref('BrainStorm','Subjects', Subjects);
%   setpref('BrainStorm','UserDataBase',UserDB)
%   setpref('BrainStorm','UserDataBase',UserDB);
%   setpref('BrainStorm','iUserDataBase',iDatabase);
%   
%   Layout = getpref('BrainStorm','Layout');
%   UserDB = getpref('BrainStorm','UserDataBase');
%   iDB = getpref('BrainStorm','iUserDataBase');
%   iUserDB = getpref('BrainStorm','iUserDataBase');
%
% Application data and their calls in this file:
%   'DataFiles'
%   'DataParam'
%   'FileList'
%   'TileType'
%   
%   Users.FILELIST = FileList; %setappdata(fig,'FileList',FileList);
%   setappdata(fig,'DataFiles',DataFiles);
%   setappdata(fig,'DataFiles',[]);
%   setappdata(fig,'DataParam',DataParam);
%   setappdata(fig,'DataParam',DataParamStr)
%   setappdata(fig,'FileList',FileList);
%   setappdata(fig,'TileType','T');
%   setappdata(h,'TileType','T');
%   
%   DataFiles = getappdata(fig,'DataFiles');
%   DataParam = getappdata(figs.DataManager,'DataParam');
%   DataParamStr = getappdata(fig,'DataParam');
%   FileList = Users.FILELIST; %getappdata(fig,'FileList');
%   char(getappdata(handles.DataParam,'HeadModelFunction'))}
%
% Figure Files opened by this function:
%   mfilename
%
%   Format of strings below: Type:Style:Tag, "String", CallBack Type and Call
%   <automatic> callback is <Tag>_Callback by Matlab default
%
% Callbacks by figure data_manager.fig
%   uicontrol:listbox:listbox_Data "Select a data folder in the list above" uses Callback for <automatic>
%   uicontrol:listbox:listbox_Study "Scanning Current Folder Tree..." uses Callback for <automatic>
%   uicontrol:popupmenu:popup_CurrentDatabase "Databases" uses Callback for <automatic>
%   uimenu::menu_close "" uses Callback for <automatic>
%   uimenu::menu_edit_database "" uses Callback for <automatic>
%   uimenu::menu_edit_rebuild "" uses Callback for <automatic>
%   uimenu::menu_edit_study "" uses Callback for <automatic>
%   uimenu::menu_edit_subject "" uses Callback for <automatic>
%   uimenu::menu_import_data "" uses Callback for <automatic>
%   uimenu::menu_pooled_allow "" uses Callback for <automatic>
%   uimenu::menu_pooled_define "" uses Callback for <automatic>
%   uimenu::menu_view_datafiles "" uses Callback for <automatic>
%   uimenu::menu_view_information "" uses Callback for <automatic>
%   uimenu::menu_view_results "" uses Callback for <automatic>
%
% At Check-in: $Author: Mosher $  $Revision: 71 $  $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:10:24 -----------------------


% Descriptions of Group: Preference data
%
% Group BrainStorm, Preferences:
%   'CurrentData' is a structure comprising fields:
%     StudyFile and SubjectFile,both referential filenames to the 
%       current *_brainstormstudy.mat and *_brainstormsujbect.mat files.
%     SubjectName, string giving current name
%     DataFile, referential name to the current data file in use
%     OtherDataFiles, list of additional data filenames to be processed identically
%      to the DataFile (CHEAT: Are they referential or absolute?)
%    
%   'UserDataBase' is the User structured array, User(i) comprising the fields
%     Comment, STUDIES,and SUBJECTS. Comment is a string AKA the database name,
%     STUDIES is the absolute path to the root of the studies folders, and 
%     SUBJECTS is the absolute path to the root of the subjects folders.
%
%   'iUserDataBase' is simply an integer, giving the index to the current User
%     structure in use. Since stored as a Preference, can be recalled at the
%     next startup of BST to return the user to the same database
%
% 
% Descriptions of Application Data
%
%   'BrainStormTaskbar', set in the root window 0, is retrieved only, as set in the 
%     startup of BST. Gives the handle to the Taskbar, as in 
%    TASKBAR = getappdata(0,'BrainStormTaskbar').
%  
%   'BrainStormDataBase', stored in the GUI TASKBAR, is the current database, i.e. in
%     Preference terms, UserDataBase(iUserDataBase). Called by get_user_directory
%     to determine the user's current database.
%
%   'FileList', stored in figure, 
%     begins in browse_study_folder as a "dir" structure, 
%       with the following features
%     name is referential to Users.STUDIES, 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
%     This application m-file also adds:
%     HeadModel is a cell array for each Study, that has subfields 
%       HeadModelName and GridName
%     Tesselation is a cell array of tesselation infor for each study
%
%   'DataFiles', stored in the figure, is a Mathworks structure resulting from
%     "dir", plus an additional field called "display". The "display" is used to
%     display a pretty print of filename in the data files listbox. If DataFiles
%     is of  length zero, then no data or results files are available in the
%     current study. 
%     JCM modified 6-Jun-2002 such that the field name is now also referential
%    
%   'HeadModelFunction'
%     JCM: I don't understand the utility of this, disabled some parts
%
%   'UserDB'
%     Identical to Preference UserDataBase, 
%       kept locally for convenience and older code


% /---Script Authors-------------------------------------\
% |  *** 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                                    |
% |  Los Alamos National Laboratory                      |
% |  Los Alamos, New Mexico, USA                         |
% |  mosher@lanl.gov                                     |
% \------------------------------------------------------/

% Date of creation: January 1999 as bst_datamanager_gui
% ----------------------------- Script History ---------------------------------
% SB  18-Feb 2002 added coregistration of multiple studies (STILL UNDER DEVELOPMENT)
% JCM 23-Mar-2002 cosmetic changes to GUI
% JCM 25-Mar-2002 cosmetic changes to script
% SB  05-Apr-2002 cosmetic changes to GUI and script + initiated addition of 
%                  links to MRITool & HeadModeler
% SB  29-Apr-2002 added calls to HeadModeling routines + added reference to 
%                  TASKBAR's BrainStormWindows appdata for window management
% JCM  8-May-2002 shrinking GUI to XGA size, cleaning up comments and format of
% ............... this file, trying to understand Sylvain's opening sequence, 
%                 "fullfile" additions to handle referential names correctly
%
% ............... This GUI figure now has the following application data:
% ............... FileList, list of files as represented in the 
%                 Available Studies window
% ............... DataFiles, list of Data Sets as represented in the data list box
% ............... some (not all) of the GuiData = guidata(h) calls have 
%                 been updated for this new application data
% JCM 23-May-2002 major rewriting to make process flow clearer, snake out bugs
% JCM 24-May-2002 updated select_folder calls to be modal style, simple return
% JCM 24-May-2002 Changed to data_manager.m, updated all calls to it
% SB  27-May-2002 Changed display for tessellation file information according to
% ............... MMII conventions on TESS files (look for tess files in current folder).
% JCM 28-May-2002 Lots of changes to make the load routines less error prone, particularly for
%                 empty directories or older formats. Added buttons at end, so that now
%                 all callbacks in the GUI come first through this feval switchyard. 
%                 Used whos('-file') function to determine if variables were missing 
%                 before loading. Users.CurrentData.Database now Users.Comments.
% SB  30-May-2002 Still working at the link with HEADMODELER_GUI with new structures of Tessellation files
% ............... Upgraded and lightened StudyInformation display
% ............... Added the HeadModel and Tessellation fields to FileList for quicker access
% ............... to the related files in HEADMODELER_GUI
% JCM 4-Jun-2002  Added lots of comments above detailing the Preferences and 
%                 Application data, then carefully went through this code again
%                 updating its use to correspond to above description. Made all
%                 DataFiles.name to be referential instead of filename only.
%                 Disabled some code related to HeadModelFunction, since it
%                 appears to be unused and it relies on an old headmodel
%                 filename
% JCM 10-Jun-2002 Updated auto comments to include figure information. Fixed simple bug in
%                 DataFiles and ResultFiles toggles that caused them to reset studies 
%                 to the first one. Added new button to Load and View, and now the Load button
%                 only loads the selected trial into the User information. The Load and View
%                 brings up the dataplot_cb window.
% SB  22-Jul-2002 Fixed minor display bug for available headmodels 
%                 (when BsT2000 headmodel files are available)
% ............... Changed call to ImportData routine
% SB  23-Jul-2002 Added available Studies and Subjects to preferences 
%                 BrainStorm/Studies /Subjects respectively
% ............... StudyFile name is accessible through FileList(k).StudyFile 
%                 and not .name anymore 
% SB  29-Jul-2002 Fixed display bug when no tessellation file is available.
% SB  30-Jul-2002 As per our new convention for MMII, there should be only one 
%                 StudyFile and one SubjectFile
%                 per Study or Subject folder.
%                 This brings out two new things for data_manager
%                 1) Only the names of the StudyFolders are displayed in the Study Lisbox;
%                      Displaying the name of the brainstormstudy file is not relevant anymore.
%                 2) data_manager now operates some sanity checks on the Study and Subject files
%                      checking that there actually is only a single of those files per folder.
% SB 08-Aug-2002  Added a 'Watch' pointer when initializing databases.
% SB 10-Sep-2002  HeadModelFiles from older BrainStorm version are now automatically 
%                 re-written in appropriate format and older files are renamed as '.old' 
% JCM 30-Oct-2002 Comment editing, cleaning up to rely on preferences only for databasing.
%                 Accounting for empty preferences if no files in database.
% JCM 05-Nov-2002 Further ensurance that preferences are used, checking for defaults.
%                 Populating defaults if necessary. Now looks for *channel* file in Study.
%                 Disabled deprecated use of guidata for data storage, everything uses 
%                 Preferences now.
% SB  07-Nov-2002 Removed uiwait command during call to importdata.m
% SB  20-Nov-2002 Added automatic update of older channel files to newer format.
% JCM 20-Nov-2002 Fixed problem with automatic updating. Must test first to see if field
%                 exists. Here fixed mapping of old "Gcoef" data.
% SB  02-Dec-2002 Fixed issue when importing older channel structure 
% JCM 13-May-2003 Layout upgrade
% JCM 29-May-2003 Links into the new bst_static_taskbar. No deletions, just additional
%                 actions to make the new taskbar begin functioning.
% SB  03-Jun-2003 - Avoid systematic sifting through the entire data and subject roots.
% ...............   Unless the user hits the 'Refresh' button, file list from
%                   current Study root is recalled
%                   from new field of the Users structure called .FileList
%                 - Clicking on 'Information' displays full information about 
%                   selected data in separate quartertile
% SB  04-Jun-2003 Various minor fixes
% SB  12-Jun-2003 Use the 'Unique' option of bst_message_window to display data information
% SB  09-Jul-2003 Display an OK message when selected data set is ok for
%                 display/further processing
%                 Add a context menu to display selected study information
% JCM 19-Aug-2003 Rebuild case to also rebuild the Studies and Subjects pref
% JCM 09-Sep-2003 Disabling old taskbar
% JCM 11-Sep-2003 Adjusting "default" database cases to use the word "data"
%                 instead of "study". Note that programming code still refers to
%                 "study", we are only changing the apparent words for the user
%                 to say "data" to lessen the confusion.
% JCM 12-Sep-2003 Adjusting to new use of make_default_database for creating default data sets
%                 in both the brainstorm home area and the users present
%                 database. Startup will have created the BrainStorm default, if
%                 necessary. The 'Rebuild' command checks the present database
%                 and copies the BrainStorm default if necessary.
%                 make_default_database will have also confirmed the preference
%                 UserDataBase, so checking here is not necessary.
% JCM 17-Nov-2003 Moving buttons into menu items
% SB  15-Dec-2003 Minor display fixes
% SB  19-Jan-2004 Adding contextual menu to data listbox to load selected data set quickly using right-clicking over
%                 data listbox
% SB  16-Fev-2004 Fixed bug in creation of above-mentioned contextual menu
% JCM 11-May-2004 reinstated make_default_database(0) commands blocked by SB, which are
%                 necessary
% JCM 16-May-2004 Comments updating
% JCM 19-May-2004 Fixed problem around line 900, when DataFiles was empty, should
%                 not call listbox_Data_Callback.
% ----------------------------- Script History ---------------------------------

% Last Modified by GUIDE v2.0 17-Nov-2003 13:49:47

if nargin == 0  % LAUNCH GUI
   
   fig = openfig(mfilename,'reuse'); % there can be only one
   % JCM 24-May-2002 .fig is now set invisible
   
   % Generate a structure of handles to pass to callbacks, and store it. 
   handles = guihandles(fig);
   guidata(fig, handles); % Mathworks convention to store handles
   
   if nargout > 0
      varargout{1} = fig;
   end
   
   % customize window
   
   % movegui(fig,[5,-5]); % near top left
   bst_color_scheme(fig);
   setappdata(fig,'TileType','T');
   bst_layout('align',fig,1,1,1);
   
   if(0) % disabled cheat JCM 11 November 2003
      % cheat for the datamanager to get it to look like a dynamic
      %  taskbar on the right
      Layout = getpref('BrainStorm','Layout');
      pos = get(fig,'position'); % the tiled position
      pos(3) = pos(3) + Layout.winpos(3,3); % add the width of the dynamic bar
      set(fig,'position',pos);
   end
   set(fig,'visible','on'); % it's moved and colored, now show
   drawnow
   
   % Update the BrainStormWindows fields
   bst_win_manager(fig,'DataManager');
   
   set(fig, 'pointer', 'watch'), 
   drawnow
   initialize_database(handles); % initialize the database portion
   set(fig, 'pointer', 'arrow')
   
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK
   
   try
      [varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
   catch
      disp(lasterr);
   end
end




% -------------------------- Local Functions --------------------------------------------------------

function initialize_database(handles); % initialize the database portion
% GUI has just been built, populate the database section of the GUI

% JCM 30-Oct-2002, should use only preferences here, set by default in startup if needed
% JCM 12-Sep-2003, make_default_database will have already confirmed the UserDataBase

fig = handles.DataManager; % convenient shortcut

% Now browse the current Study and Subject folders and look for data...
% JCM 21-Mar-2002
% ask the taskbar switchyard to perform tasks on itself
% JCM 09-Sep-2003 disabling old taskbar
% taskbar('inactive'); % make the taskbar buttons inactive until valid database setup

% ensure we have a default database in the present working directory
if 1 % deprecated code | SB - default should exist because it's created at startup 
   UserDefault = make_default_database(0); % check only the present database
end

UserDB = getpref('BrainStorm','UserDataBase');
iUserDB = getpref('BrainStorm','iUserDataBase'); % what was the last one used

Current_User = UserDB(iUserDB); % most recent used

% load the popup with current values
if ~isfield(UserDB,'Comment')
   UserDB.Comment = 'Default Database';
   setpref('BrainStorm','UserDataBase',UserDB)
end

set(handles.popup_CurrentDatabase,'String',{UserDB.Comment},'Value',iUserDB);

% now continue as though the user just selected an item in the popup
popup_CurrentDatabase_Callback(handles.popup_CurrentDatabase,[],handles);




% ----------------- UPDATE THE LISTBOX OF STUDIES ---------------------
function load_listbox_Study(handles);
% The Study Folder has been changed, so update the listbox of studies

fig = handles.DataManager; % handy shortcut

if 1 % deprecated code | SB - default should exist because it's created at startup 
   UserDefault = make_default_database(0); % ensure a default exists 
end

Users = get_user_directory; % where are we?

% Avoid systematic sifting through the entire data branches of the study root
% Use listing structure stored in database 
FileList = Users.FILELIST; % make_default_database ensured this exists
if isempty(FileList)
   Users.FILELIST = browse_study_folder(Users.STUDIES);
   FileList = Users.FILELIST;
end

% we have a valid list of study files
% setup the Preferences for the list of Studies and Subjects in this database

listbox_display = {FileList.display}; % made by browse_study_folder
set(handles.listbox_Study,'enable','on');

% Store available Studies and Subjects BrainStorm Preferences for this user
Studies = rmfield(FileList,{'isdir','date','bytes','Subject','display'});

setpref('BrainStorm','Studies', Studies);

% now find list of subjects in the database
if(0), % JCM is altering SB's attempt here 20-August-2003
   %    issue is that an unassigned subject is not being seen in the study list
   % original SB section
   SubjectFile = find_brainstorm_files('subjects',Users.SUBJECTS); % CBB - should store subjects information in Users structure of users.mat file
   % [FileList(:).Subject]; % Contains Subject's Name and SubjectFile locations (as structure fields)
   % Find unique subjects
   Subjects = rmfield(FileList,{'isdir','date','bytes','StudyFile','StudyName','StudyFolder','display'});
   Subjects = [Subjects.Subject];
   %    for k = 1:length(SubjectFile) % Load Subject names
   %       load(fullfile(Users.SUBJECTS,SubjectFile{k}),'Name');
   %       Subjects(k).Name = Name;
   %       Subjects(k).SubjectFile = SubjectFile{k};
   %    end
   % make the list of subjects unique
   [tmp,iUnique] = unique(cellstr(char(Subjects.SubjectFile)));
   Subjects = Subjects(iUnique);
else
   % new JCM section, extrapolated from above.
   % get list of valid subjects in the current tree
   SubjectFile = find_brainstorm_files('subjects',Users.SUBJECTS);
   % we now have a list of valid "brainstormsubject" files, get their names
   
   [Subjects(1:length(SubjectFile))] = deal(struct('Name',[],'SubjectFile',[]));
   for k = 1:length(SubjectFile) % Load Subject names
      load(fullfile(Users.SUBJECTS,SubjectFile{k}),'Name');           
      Subjects(k).Name = Name;
      Subjects(k).SubjectFile = SubjectFile{k};
   end
   % make the list of subjects unique
   [tmp,iUnique] = unique(cellstr(char(Subjects.SubjectFile)));
   Subjects = Subjects(iUnique);
end

% Give the User a default subject to select. 
% Created and confirmed by the popup_CurrentDatabase_Callback
% Thus the user will always have a default subject if needed

setpref('BrainStorm','Subjects', Subjects);

% Preferences Studies and Subjects have now been loaded, or are empty
% JCM 12-Sep-2003, should never be empty anymore, since defaults always available

% load the listbox
set(handles.listbox_Study,'String',listbox_display,...
   'Value',1,'FontName','fixedwidth');

% if batch mode allowed, adjust the max
if 0, % old method with buttons
   if get(handles.StudyBatch,'Value')
      set(handles.listbox_Study,'Max',length(FileList))
   else
      set(handles.listbox_Study,'Max',1)
   end
else
   % new method of pull down menus
   switch get(handles.menu_pooled_allow,'Checked');
      case 'off'
         % not doing pooled, can only select one file
         set(handles.listbox_Study,'Max',1)
      case 'on'
         % allow selection of multiple files
         set(handles.listbox_Study,'Max',length(FileList))
   end
end

% initialize the data listbox
set(handles.listbox_Data,'Value',1)
set(handles.listbox_Data,'String','Select a study in the list above');
set(handles.listbox_Data,'Enable','inactive'); % not ready for action yet

% store the filelist
% deprecated code
if(0), % disabled, SB 03-Jun-2003, should be stored in a specific entry of the user database 
   setappdata(fig,'FileList',FileList);
end
setappdata(fig,'DataFiles',[]); % empty them out, not yet loaded

% deprecated code:
if(0), % disabled JCM 5-nov-2002, should be handled by above setappdata of FileList
   GuiData.FileList = FileList;
   guidata(fig,GuiData); % write the GuiData into the figure
end

% Display number of available studies in database
set(handles.BAvailableStudies,'String',sprintf('%d Data Folders in Current Database',length(FileList)))

% Mathworks convention 12.1 is to pass handles as guidata(gcbo)
% CHEAT should use a setappdata instead, but need to update
% all calls below

% with the Study Listbox loaded, now find data, possibly creating new DataFiles
if(strcmp('on',get(handles.listbox_Study,'enable'))),
   % it may be disabled for a lack of studies
   listbox_Study_Callback(fig, [], handles);
end




% ---------------------------- Button Callbacks --------------------------------


% --------------------- POPUP FOR CHANGING THE DATABASE ------------------------

function varargout = popup_CurrentDatabase_Callback(h, eventdata, handles, varargin)
% User changes the current database

% JCM 30-Oct-2002, enforcing use of preferences only
% JCM 05-Nov-2002, ensure that defaults exist
%  So this routine enforces that there be a Default_Subject and Default_Study
%  every time.
% JCM 12-Sep-2003 updating to use make_default_database

%  The Users structure is updated on disk

set(findobj(0,'type','figure'),'pointer','watch'); % we will be busy reloading listboxes
drawnow

handles = guihandles(h); % necessary because guidata may have been overwritten
fig = handles.DataManager; % handy shorthand

% 05-Nov-2002 TASKBAR no longer needed, use Preferences instead
% TASKBAR = getappdata(0,'BrainStormTaskbar'); % JCM 21-Mar-2002
% GuiData = guidata(h); % command not needed here


% which entry is the user centered on
iDatabase = get(handles.popup_CurrentDatabase,'Value'); % which popup selection

% save this index number as the most recent database pointer
setpref('BrainStorm','iUserDataBase',iDatabase);

% check it for existence and defaults
if 0 % deprecated code | SB - default should exist because it's created at startup 
   UserDefault = make_default_database(0); % check only this database
end

UserDB = getpref('BrainStorm','UserDataBase'); % current database
%iDatabase = getpref('BrainStorm','iUserDataBase'); % unlikely that it was updated

Users = UserDB(iDatabase); % select the one from the popup

% set the edit text fields, the other routines read these
set(handles.edit_StudyFolder,'String',Users.STUDIES);
set(handles.edit_SubjectFolder,'String',Users.SUBJECTS);

% ensure that popup strings are accurate
set(handles.popup_CurrentDatabase,'String',{UserDB.Comment});

load_listbox_Study(handles); % now load the listbox

set(findobj(0,'type','figure'),'pointer','arrow')
drawnow




% --------------------------------------------------------------------
function varargout = StudyFolder_Callback(h, eventdata, handles, varargin)
% activated by the edit window, but JCM 23-May-2002 made inactive to 
%  keep things simpler
% Keep as an inactive edit window for nice look, treat as a text window





% --------------------------------------------------------------------
function varargout = SubjectFolder_Callback(h, eventdata, handles, varargin)
% activated by the edit window, but JCM 23-May-2002 made inactive to 
%  keep things simpler
% Keep as an inactive edit window for nice look, treat as a text window





% ------------------- STUDIES LISTBOX CALLBACK -----------------
function varargout = listbox_Study_Callback(h, eventdata, handles, varargin)
% A study has changed in the listbox, update the associated data files

handles = guihandles(h); % reloads handles for insurance

% jcm disabled 05-Nov-2002
% GuiData = guidata(h); % deprecated,but may still be necessary

fig = handles.DataManager; % handy shortcut
%FileList = getappdata(fig,'FileList');

Users = get_user_directory; % the current database structure
FileList = Users.FILELIST;

if ~isfield(FileList,'StudyFile'), % Empty Study Folder
   return, 
end

% let user know something is happening
set(handles.DataManager,'pointer','watch'); 

% What was selected ?
Selection = get(handles.listbox_Study,'Value');

% Make the selected StudyFile current in the TASKBAR 
Users.CurrentData.StudyFile = FileList(Selection).StudyFile; % referential filename

% Does this studyfile have a BrainStormSubject?
% Deprecated code
if(0), % SB 03-Jun-2003 | all necessary information should now be stored in FileList
   StudyFile_whos = whos('-file',fullfile(Users.STUDIES,Users.CurrentData.StudyFile));
   if(strmatch('BrainStormSubject',{StudyFile_whos.name})),
      % BrainStormSubject exists in the desired studyfile
      % Make the selected SubjectFile current in the TASKBAR 
      load(fullfile(Users.STUDIES,Users.CurrentData.StudyFile),'BrainStormSubject')
      Users.CurrentData.SubjectFile = BrainStormSubject;
   else
      % Studyfile doesn't have one defined
      Users.CurrentData.SubjectFile = '';
   end
end
Users.CurrentData.SubjectFile = FileList(Selection).Subject.SubjectFile;

% update the preferences, used by get_user_directory
setpref('BrainStorm','CurrentData',Users.CurrentData);


% ------- NOW LOAD UP THE DATAFILES IN THIS STUDY ----------------------
% ------- AND IN THE FOLLOWING SECTION, UPDATE THE HEADMODEL INFO ------

refpath = fileparts(FileList(Selection).StudyFile);
% path is relative, cd to it
StudyPath = fullfile(Users.STUDIES,refpath);
cd(StudyPath);

% -------------------- DATAFILES -------------------
% now get all of the desired data or results files in that directory

% check status of toggle buttons
if 0,
   % old method of pulldowns
   DATA = get(handles.DataFiles,'Value'); % Are we looking for data files ?
   RESULTS = get(handles.ResultFiles,'Value'); % Are we looking for result files ?
else
   % new method of menu pulldowns
   switch get(handles.menu_view_datafiles,'Checked')
      case 'on'
         DATA = 1;
      case 'off'
         DATA = 0;
   end
   
   switch get(handles.menu_view_results,'Checked')
      case 'on'
         RESULTS = 1;
      case 'off'
         RESULTS = 0;
   end
end

% Create list of datafiles from this study directory
if ~DATA & RESULTS
   DataFiles = dir('*results*.mat');
elseif DATA & ~RESULTS
   TestFiles = dir('*data*.mat'); % tentative list
   DataFiles = TestFiles; % initialize array
   i = 0;
   for k = 1:length(TestFiles)
      if isempty(findstr(TestFiles(k).name,'results')), % remove the results files
         i = i+1;
         DataFiles(i) = TestFiles(k);
      end
   end
   DataFiles((i+1):end) = []; % remove the rest
else % both off
   % set DATA on
   set(handles.menu_view_datafiles,'Checked','on')
   DATA = 1;
   DataFiles = dir('*data*.mat'); % look for BsT files only - maybe consider .ds and .fiff ?
end

% we now have a list of DataFiles in the current Study folder
% It is possible that this list is empty

% Now also update the popup in the static taskbar
% set the results popup to default to the first file
if(~isempty(DataFiles)),
   DataRefNames = {DataFiles.name};
   for i = 1:length(DataRefNames),
      DataRefNames{i} = fullfile(refpath,DataRefNames{i}); % make referential
   end
   if(0)
      [ignore,tempname] = fileparts(DataFiles(1).name); % the first file, name only
      tempname = strrep(tempname,'data','results'); % leader with results substituted
      ResultsFiles = dir(sprintf('*%s*',tempname));
      if(~isempty(ResultsFiles)),
         ResultsFiles = {ResultsFiles.name};
         for i = 1:length(ResultsFiles),
            ResultsFiles{i} = fullfile(refpath,ResultsFiles{i});
         end
      else
         ResultsFiles = [];
      end
   end
   
   bst_static_taskbar('SET','DATA',DataRefNames);
   % bst_static_taskbar('SET','RESULTS',ResultsFiles);
   % now get the current setting
   if (0) % SB 18-Jun-2003 | deprecated code - the following calls duplicate the subsequent ones done in listbox_data_callback
      [fname,h] = bst_static_taskbar('GET','DATA');
      % and pretend to press the button
      bst_static_taskbar('popupmenu_DATA_Callback',h,[],guihandles(h));
   end
   
else
   bst_static_taskbar('SET','DATA',[]); %set to empty
   bst_static_taskbar('SET','RESULTS',[]);
end

% Fill text field in STATIC-TASKBAR with StudySubject information
sstring = sprintf('%s | %s', FileList(Selection).StudyName,FileList(Selection).Subject.Name);
ffig = findobj(get(0,'chil'),'flat','tag','static_taskbar');
figHandles = guihandles(ffig);
set(figHandles.Btext_STUDY,'String',sstring); clear sstring ffig figHandles

if isempty(DataFiles) % No Data files available
   
   listbox_display = {['No data files available for this study; ',...
            'consider importing a new data set']};
   set(handles.listbox_Data,'Enable','inactive');
   
else
   
   % let's make a nice listbox display by creating for each DataFiles a field
   %  called "display" that pretty prints the filename
   
   for k = 1:length(DataFiles)
      FileName{k} = strrep(DataFiles(k).name,'.mat','');
      FileSize{k} = engstr(DataFiles(k).bytes,1);
   end
   
   % Now make all of the filenames referential
   for k = 1:length(DataFiles),
      DataFiles(k).name = fullfile(refpath,DataFiles(k).name);
   end
   
   % Now improve the layout of the final .display field
   FileName = deblank(char(FileName)); % Pad all names to same character length
   FileSize = deblank(char(FileSize));
   
   fmtstr = sprintf('%%-%ds | %%-%dsbytes',size(FileName,2),size(FileSize,2));
   for k = 1:length(DataFiles)
      % also put in some "dots" to track across the blank spaces in the filename
      % jcm removed "." from file size 28-May-2002
      DataFiles(k).display = sprintf(fmtstr,...
         strrep(FileName(k,:),' ','.'),FileSize(k,:)); 
   end
   
   listbox_display = {DataFiles.display}; % create cell array of display names
   
   set(handles.listbox_Data,'Enable','on');
   
end

% at this point, DataFiles is either a "dir" structure, enhanced such that all
%  names are referential, and with the additional "display" field for 
%  pretty printing each filename,
% or DataFiles is of length 0 "dir" structure and tests as empty
% Enable is set accordingly in the above if statements

% load the listbox for Data
set(handles.listbox_Data,'string',listbox_display,'Value',1,'Max',length(listbox_display))

% load the banner text over this listbox
if DATA
   % viewing Data files
   if length(DataFiles) < 2
      set(handles.BDataSets,'String',sprintf('%d Data Set in Selected Data Folder',length(DataFiles)))
   else
      set(handles.BDataSets,'String',sprintf('%d Data Sets in Selected Data Folder',length(DataFiles)))
   end
elseif RESULTS
   % Results file
   if length(DataFiles) < 2
      set(handles.BDataSets,'String',sprintf('%d Result File in Selected Data Folder',length(DataFiles)))
   else
      set(handles.BDataSets,'String',sprintf('%d Results Files in Selected Data Folder',length(DataFiles)))
   end
   
else
   set(handles.BDataSets,'String',sprintf('(Mixed state of data and results)'))
end


% blank out the Study Information list box
% deprecated code
if 0 % SB - 03-Jun-2003 | .DataParam was removed. Now data information may be displayed in a specific quartile upon request
   set(handles.DataParam,'String',''); % the study information box
end

% save the DataFiles data
setappdata(fig,'DataFiles',DataFiles); % update

if(0), % JCM disabled 05-Nov-2002
   GuiData.DataFiles = DataFiles; % deprecated code
   guidata(h,GuiData); % deprecated
end


% With the listbox for Data now loaded, update the data listbox,
%  tesselation availability, and populate the study information list box

if isempty(DataFiles) % No Data files available
   
   listbox_display = {['No data files available for this study; ',...
            'consider importing a new data set']};
   set(handles.listbox_Data,'Enable','inactive');
   
else
   
   listbox_Data_Callback(handles.listbox_Data, [], handles);
   
end

% ------------------------ HEADMODELS ----------------------------------------

% the lisbox_Data_Callback will have added tesselation information
% Update FileList information about available tessellation files 

FileList = Users.FILELIST; %getappdata(fig,'FileList'); 

% Get DataParam string for upcoming update once headmodel files are listed
%DataParamStr = get(handles.DataParam,'String');
DataParamStr = getappdata(fig,'DataParam');

% any file in the current study folder with the keyword "headmodel"
[HeadModelFiles,DataPopup,Leader] = find_brainstorm_files('headmodel',StudyPath);

% Load the bst_static_taskbar

HEADMODELFILES = HeadModelFiles;
for i = 1:length(HeadModelFiles),
   HEADMODELFILES{i} = fullfile(refpath,HeadModelFiles{i}); % referential name
end

if(length(HeadModelFiles) > 0),
   bst_static_taskbar('SET','HEADMODEL',HEADMODELFILES);
else
   % empty
   bst_static_taskbar('SET','HEADMODEL',[]);
end    

% Load info from each headmodel file and append in the DataParam window

iokfile = 0;% Number of valid headmodel files

for k = 1:length(HeadModelFiles) % For all headmodel files in current studypath
   fileisold = 0; % Flag - 1 meaning file is writtent in older format
   
   % Go through each headmodel file
   %_____Test whether it's a valid BsT hdmodel file (older or newest format)
   %___________If older, update the file by creating new copies and move older file to a new file with extension .old  
   
   
   % Test for file validity
   cd(StudyPath)
   HeadModelWhos = whos('-file',HeadModelFiles{k}); % Look for variables in headmodel file
   
   % Valid headmodel file ?
   if (~isempty(strmatch('SearchGain',{HeadModelWhos.name})) | ...
         ~isempty(strmatch('ImageGain',{HeadModelWhos.name})) | ...
         ~isempty(strmatch('Gain',{HeadModelWhos.name}))) & ...
         ~isempty(strmatch('Param',{HeadModelWhos.name})) & ...
         ~isempty(strmatch('Function',{HeadModelWhos.name})) % Valid newest or older headmodel file 
      
      
      if ~isempty(strmatch('SearchGain',{HeadModelWhos.name}))   % Older SearchGrid file
         % HeadModel file is from older version of BrainStorm
         % Translate to newer version
         
         % VolumeSourceGrid is available
         
         bst_message_window('wrap',...
            sprintf('Updating (search grid): %s ...', HeadModelFiles{k}))
         
         [path,file,ext] = fileparts(HeadModelFiles{k}); % Original file name
         
         fileisold = 1; % Flag meaning file is old
         
         bst_message_window('wrap',{...
               sprintf('"%s" is from older version of BrainStorm',HeadModelFiles{k}),...
               sprintf('Automatically translating this file to newest file format...')...
            })
         
         
         % Load related material
         tmp = load(HeadModelFiles{k},'SearchGain','SearchGridLoc','SearchTess','Function','Param');
         
         
         for gain = 1:length(tmp.SearchGain) % Create a separate file for each cell in SearchGain
            
            % Now save VolumeSourceGrid headmodel(s) in separate files
            SaveHeadModel.HeadModelType = 'SearchGrid';
            SaveHeadModel.Param = tmp.Param;
            SaveHeadModel.Function = tmp.Function;
            % Headmodel name
            SaveHeadModel.HeadModelName = '';
            tmp.HDMName = deblank(cellstr(unique(char(SaveHeadModel.Function{:}),'rows')));
            for kk=1:length(tmp.HDMName) % Create HeadModelName entry - remove empty cells from tmp.HDMName
               if ~isempty(tmp.HDMName{kk})
                  SaveHeadModel.HeadModelName = sprintf('%s | %s',SaveHeadModel.HeadModelName,tmp.HDMName{kk});                  
               end
            end
            
            bemndx = findstr('bem', SaveHeadModel.HeadModelName); % Find whether bem was used for this headmodel file
            
            if isempty(bemndx) % Spherical models only
               if ~isempty(findstr('meg', SaveHeadModel.HeadModelName)) % MEG and Sphere
                  SaveHeadModel.MEGMethod = 'meg_sphere';
               end
               if ~isempty(findstr('eeg', SaveHeadModel.HeadModelName)) % EEG and Sphere
                  switch(tmp.Param(end).EEGType)
                     case 'EEG_BERG'
                        SaveHeadModel.EEGMethod = 'eeg_3sphereBerg' ;
                     case 'EEG_SINGLE'
                        SaveHeadModel.EEGMethod = 'eeg_sphere' ;                            
                     case 'EEG_3SHELL'
                        SaveHeadModel.EEGMethod = 'eeg_3sphere' ;                            
                  end
                  SaveHeadModel.EEGMethod = tmp.Param(end).EEGType;
               end
               
               if isempty(findstr('meg', SaveHeadModel.HeadModelName)) & isempty(findstr('eeg', SaveHeadModel.HeadModelName))
                  error(sprintf('Unvalid headmodel file: %s',HeadModelFiles{k}))
               end
               
            elseif length(bemndx) == 2 % Bem was used for EEG and MEG
               SaveHeadModel.MEGMethod = 'meg_bem';
               SaveHeadModel.EEGMethod = 'eeg_bem';
            end
            
            
            % Specify Source Model Name and Other Fields 
            switch gain 
               case 1
                  SourceOrderString = 'CD'; % Current Dipole
               case 2 
                  SourceOrderString = 'MD'; % Magnetic Dipole
               case 3
                  SourceOrderString = 'CME'; % Current Multipole
               case 4
                  SourceOrderString = 'CDpairs';
               case 5
                  SourceOrderString = 'MDpairs';
               case 6
                  SourceOrderString = 'CMEpairs';
            end
            
            % Source Order
            SaveHeadModel.SourceOrder = gain - 2;
            % Grid Gain Matrix
            SaveHeadModel.Gain{1} = single(tmp.SearchGain{gain});
            SaveHeadModel.GainCovar = {};
            SaveHeadModel.GainCovarName = '';
            SaveHeadModel.GridLoc = {tmp.SearchGridLoc{gain}};
            % Detailed grid name
            SaveHeadModel.GridName = {sprintf('%s Volumic Grid',SourceOrderString)};
            
            % now collect together and save
            SaveHeadModelFileOrig = strrep(HeadModelFiles{k},'headmodel',['headmodel',sprintf('VolGrid_%s',SourceOrderString)]);
            SaveHeadModelFileOrig = strrep(SaveHeadModelFileOrig,'.mat','');
            SaveHeadModelFile = SaveHeadModelFileOrig;
            
            ifile = 0;
            while exist([SaveHeadModelFile,'.mat'],'file') % Do not overwrite headmodel files
               ifile = ifile + 1;
               SaveHeadModelFile = [SaveHeadModelFileOrig,'_',int2str(ifile)];
            end
            
            bst_message_window('wrap',...
               sprintf('Writing HeadModel file in new BrainStorm format: %s ...', SaveHeadModelFile))
            
            save_fieldnames(SaveHeadModel, [SaveHeadModelFile,'.mat']);
            clear SaveHeadModel SourceOrderString
            
            bst_message_window(...
               {' -> DONE',' '}), 
            
         end % For each cell in SearchGain
         
         clear tmp
         
      end % SearchGrid
      
      if ~isempty(find(strcmp(cellstr(char(HeadModelWhos(:).name)),'ImageGain'))) 
         
         % ImageGrid is available
         fileisold = 1; % Flag meaning file is old
         
         bst_message_window('wrap',...
            sprintf('Updating (imaging grid): %s ...', HeadModelFiles{k}))
         
         SourceOrderString = 'CD'; % Only Current Dipole models for ImageGain in older BsT files
         
         
         % Load related material
         tmp = load(HeadModelFiles{k},'ImageGain','ImageGridLoc','ImageGainCovar','Function','Param');
         clear SearchTess % Obsolete
         
         for grid = 1: length(tmp.ImageGain)
            if ~isempty(tmp.ImageGain{grid})
               
               SaveHeadModel.HeadModelType = 'ImageGrid';
               
               % Now save VolumeSourceGrid headmodel(s) in separate files
               SaveHeadModel.Param = tmp.Param;
               SaveHeadModel.Function = tmp.Function;
               % Headmodel name
               SaveHeadModel.HeadModelName = '';
               tmp.HDMName = unique(SaveHeadModel.Function);
               for kk=1:length(tmp.HDMName) % Create HeadModelName entry - remove empty cells from tmp.HDMName
                  if ~isempty(tmp.HDMName{kk})
                     SaveHeadModel.HeadModelName = sprintf('%s | %s',SaveHeadModel.HeadModelName,tmp.HDMName{kk});             
                  end
               end
               
               bemndx = findstr('bem', SaveHeadModel.HeadModelName); % Find whether bem was used for this headmodel file
               
               if isempty(bemndx) % Spherical models only
                  if ~isempty(findstr('meg', SaveHeadModel.HeadModelName)) % MEG and Sphere
                     SaveHeadModel.MEGMethod = 'meg_sphere';
                  end
                  if ~isempty(findstr('eeg', SaveHeadModel.HeadModelName)) % EEG and Sphere
                     switch(tmp.Param(end).EEGType)
                        case 'EEG_BERG'
                           SaveHeadModel.EEGMethod = 'eeg_3sphereBerg' ;
                        case 'EEG_SINGLE'
                           SaveHeadModel.EEGMethod = 'eeg_sphere' ;                            
                        case 'EEG_3SHELL'
                           SaveHeadModel.EEGMethod = 'eeg_3sphere' ;                            
                     end
                  end
                  
                  if isempty(findstr('meg', SaveHeadModel.HeadModelName)) & isempty(findstr('eeg', SaveHeadModel.HeadModelName))
                     error(sprintf('Unvalid headmodel file: %s',HeadModelFiles{k}))
                  end
                  
               elseif length(bemndx) == 2 % Bem was used for EEG and MEG
                  SaveHeadModel.MEGMethod = 'meg_bem';
                  SaveHeadModel.EEGMethod = 'eeg_bem';
               end
               % Grid Gain Matrix
               SaveHeadModel.SourceOrder = -1; % Current dipoles only.
               SaveHeadModel.Gain = {tmp.ImageGain{grid}{1}};
               SaveHeadModel.GainCovar = {tmp.ImageGainCovar{grid}};
               SaveHeadModel.GainCovarName = '';
               tmp.SubjectFolder = fileparts(FileList(Selection).Subject.SubjectFile);
               tmp2 = load(fullfile(Users.SUBJECTS,FileList(Selection).Subject.SubjectFile),'Tesselation');
               if isempty(fieldnames(tmp2)) % No tessellation available
                  tmp.Tess.Tesselation = [];
               else
                  tmp.Tess.Tesselation = tmp2.Tesselation;
               end
               if isempty(tmp.Tess.Tesselation)
                  % Tessellation file not stored in Subject file (as in MMII file format):
                  % Ask user to point at tessellation file manually
                  hh = msgbox('Tessellation file was not found, please select from list.','File not found');
                  waitfor(hh)
                  cd(Users.SUBJECTS)
                  [filename, pathname] = uigetfile('*.mat', 'Pick a Tessellation file from list');
                  if isequal(filename,0) | isequal(pathname,0), return , end
                  tmp.Tess.Tesselation = fullfile(strrep(pathname,Users.SUBJECTS,''),filename);
                  cd(StudyPath)
               end
               
               %SaveHeadModel.GridLoc = {fullfile(tmp.SubjectFolder,tmp.Tess.Tesselation)};
               SaveHeadModel.GridLoc = {tmp.Tess.Tesselation};
               SaveHeadModel.iGrid = grid;
               
               if ~isempty(find(strcmp(cellstr(char(HeadModelWhos(:).name)),'ImageGain_RowNorm'))) % Complete with other available information in older file
                  load(HeadModelFiles{k},'ImageGain_RowNorm');
                  SaveHeadModel.Gain_RowNorm = {ImageGain_RowNorm{grid}};
               end
               
               if ~isempty(find(strcmp(cellstr(char(HeadModelWhos(:).name)),'ImageGainCovar_ColNormFus')))
                  load(HeadModelFiles{k},'ImageGainCovar_ColNormFus');
                  SaveHeadModel.GainCovar_ColNormFus = ImageGainCovar_ColNormFus{grid};
               end
               
               if ~isempty(find(strcmp(cellstr(char(HeadModelWhos(:).name)),'ImageGainCovar_ColNorm'))) 
                  load(HeadModelFiles{k},'ImageGainCovar_ColNorm');
                  SaveHeadModel.GainCovar_ColNorm = ImageGainCovar_ColNorm{grid};
               end
               
               % Detailed grid name
               try 
                  load(fullfile(Users.SUBJECTS,tmp.Tess.Tesselation),'Comment'); % Load surface names
               catch
                  load(tmp.Tess.Tesselation,'Comment'); % Load surface names
               end
               
               try 
                  Comment = Comment{grid};
               catch 
                  errordlg(sprintf(...
                     'Please check that the tessellation file contains as many envelopes (here %d) as the ones specified in the headmodel (here %d)', length(Comment),length(tmp.ImageGain)))
                  return
               end
               
               SaveHeadModel.GridName = {sprintf('%s Surface Grid : %s',SourceOrderString,Comment)};
               
               % now collect together and save
               SaveHeadModelFileOrig = strrep(HeadModelFiles{k},'headmodel',['headmodel',sprintf('SurfGrid_%s',SourceOrderString)]);
               SaveHeadModelFileOrig = strrep(SaveHeadModelFileOrig,'.mat','');
               SaveHeadModelFile = SaveHeadModelFileOrig;
               
               ifile = 0;
               while exist([SaveHeadModelFile,'.mat'],'file') % Do not overwrite headmodel files
                  ifile = ifile + 1;
                  SaveHeadModelFile = [SaveHeadModelFileOrig,'_',int2str(ifile)];
               end
               
               bst_message_window('wrap',...
                  sprintf('Writing HeadModel file in new BrainStorm format: %s ...', SaveHeadModelFile))
               
               save_fieldnames(SaveHeadModel, [SaveHeadModelFile,'.mat']);
               clear SaveHeadModel 
               bst_message_window(...
                  {' -> DONE',' '}), 
            end
            
         end % For each cell in ImageGain
         
      end % ImageGrid
      
      clear tmp
      
      if fileisold == 1 % HeadModelFiles{k} was an older file - store it as an .old file
         % Create name for each new headmodel file
         [path,file,ext]  = fileparts(HeadModelFiles{k});
         
         % Now move older file to new name with .old extension
         oldfile = [file,ext,'.old'];
         switch(upper(computer))
            case('PCWIN')
               dos(sprintf('move %s %s', [file,ext], oldfile));
            case ('UNIX')
               unix(sprintf('mv %s %s', [file,ext], oldfile));
         end
         
         % Reload study information
         listbox_Study_Callback(h, eventdata, handles, varargin)
         return
      end
      
      % GridName and HeadModelName exist, load them
      load(fullfile(StudyPath,HeadModelFiles{k}),'GridName','HeadModelName')
      if ~isempty(GridName)
         InfoStr{k} = {...
               sprintf('    HeadModel type: '),...
               sprintf('    --> %s',HeadModelName),...
               sprintf('    Source Grid:'),...
               sprintf('    --> %s',GridName{1})...
            };
      else 
         load(fullfile(StudyPath,HeadModelFiles{k}),'GridLoc')
         if ~isempty(GridLoc)
            InfoStr{k} = {...
                  sprintf('    HeadModel type: '),...
                  sprintf('    --> %s',HeadModelName),...
                  sprintf('    Source Grid:'),...
                  sprintf('    --> %s','Specific Grid Locations')...
               };
         else
            InfoStr{k} = {...
                  sprintf('    HeadModel type: '),...
                  sprintf('    --> %s',HeadModelName),...
                  sprintf('    Unrecognized format')...
               };
         end
      end
      
      iokfile = iokfile+1;
      % Update the Study FileList with HeadModel information
      FileList(Selection).HeadModel{iokfile}.HeadModelName = HeadModelName; 
      FileList(Selection).HeadModel{iokfile}.GridName = GridName; 
      
   else
      
      InfoStr{k} = {sprintf('%s is not a valid BrainStorm headmodel file',HeadModelFiles{k})};
      
   end % Valid (newest or older) file ?
   
   if k == 1, % initialize a header string
      DataParamStr = {DataParamStr{:},...
            ' ',...
            'available Head Model file(s) :',...
            ' '};
   end
   
   DataParamStr = {DataParamStr{:},...
         sprintf('*** %s',strrep(HeadModelFiles{k},'.mat','')),...
         InfoStr{k}{:},...
         ' '};
   
   
end % For each headmodel file

% update the banner text in the GUI
if length(HeadModelFiles) == 0,
   set(handles.AvailableHeadModels,...
      'String','0 Available Head Models','ForegroundColor','r');
elseif length(HeadModelFiles) == 1,
   set(handles.AvailableHeadModels,...
      'String',sprintf('%d Available Head Model',length(HeadModelFiles)),...
      'ForegroundColor','g');
else
   set(handles.AvailableHeadModels,...
      'String',sprintf('%d Available Head Models',length(HeadModelFiles)),...
      'ForegroundColor','g');
end

% update the Study Information listbox with the new data
setappdata(fig,'DataParam',DataParamStr)

% save the new filelist information
Users.FILELIST = FileList; % SB 03-Jun-2003 --- CBB this kind of FileList update should be done in a specific (sub)function
iDB = getpref('BrainStorm','iUserDataBase');
UserDB = getpref('BrainStorm','UserDataBase');
UserDB(iDB).FILELIST = Users.FILELIST;
setpref('BrainStorm','UserDataBase',UserDB);


% let the user know we are done.
makeuswait('stop')



% ------ CALLBACK FOR THE DATA LISTBOX --------------------------------------
function varargout = listbox_Data_Callback(h, eventdata, handles, varargin)
% Displays the parameters of a data set in the DataManager window

makeuswait('start')

handles = guihandles(h); % have to rebuild 
if(0), % disable 05-nov-2002
   GuiData = guidata(h); % deprecated
end

% JCM 09-Sep-2003 disabling old taskbar
% TASKBAR = getappdata(0,'BrainStormTaskbar');
% htaskbar = guihandles(TASKBAR); % to control the estimation enable
fig = handles.DataManager; % handy shortcut

DataFiles = getappdata(fig,'DataFiles');
%FileList = getappdata(fig,'FileList');

Users = get_user_directory; % current database
FileList = Users.FILELIST;

% JCM 09-Sep-2003 disabling old taskbar
% taskbar('inactive'); % set buttons inactive on the taskbar

% What was selected ?
StudySelection = get(handles.listbox_Study,'Value'); % Current Study
DataSelection = get(handles.listbox_Data,'Value');

% Look for data files in this folder
[refpath, file,ext] = fileparts(FileList(StudySelection).StudyFile);
StudyPath = fullfile(Users.STUDIES,refpath);  % fully qualified name

cd(Users.STUDIES) % names are referential from here

% -------------- CHANNEL FILE INFORMATION ------------------------
% Load associated channel file
% referential name

[Channel,ChannelFile] = get_channel(DataFiles(DataSelection).name);

% % change JCM 05-Nov-2002, only one channel file in a study folder
% if(0),
%    ChannelFile = strrep(FileList(StudySelection).StudyFile,'brainstormstudy','channel');
% else
%    % new search for a channel file
%    ChannelFile = dir(fullfile(StudyPath,'*channel*mat')); % any channel files
%    switch length(ChannelFile)
%    case 0
%       % no channel file!
%       DataParam = {...
%               ' ','DATABASE ERROR XXXXXX',...
%               ['A Channel file in',StudyPath],...
%               'is missing.',...
%               'Please consider importing',...
%               'the original data set again'};
%       
%       %set(handles.DataParam,'String',DataParam)
%       bst_message_window('wrap',DataParam)
%       %set(handles.LoadSelectedData,'Enable','off')
%       set(fig,'Pointer','arrow')
%       return
%       
%    case 1
%       % no problem, we found a single channel file
%    otherwise
%       % more than one channel file!
%       DataParam = {...
%               ' ','DATABASE ERROR XXXXXX',...
%               sprintf('More than one Channel file in: %s',StudyPath),...
%               'Please manually remove the extra Channel files.'};
%       
%       %set(handles.DataParam,'String',DataParam)
%       bst_message_window('wrap',DataParam)
%       %set(handles.LoadSelectedData,'Enable','off')
%       set(fig,'Pointer','arrow')
%       return
%       
%    end
%    ChannelFile = ChannelFile(1).name; % keep only the first as a string name
%    ChannelFile = fullfile(refpath,ChannelFile); % make referential
% end
% load(ChannelFile) % CBB : should load structure "Channel" into local workspace

% check whether this ChannelFile is from an older version of BrainStorm

% Check for EEG locations - should be 3x1 per electrode - not 3x2 anymore
ieeg = good_channel(Channel,[],'EEG');
Old = 0; % Flag
if ~isempty(ieeg)
   if size(Channel(ieeg(1)).Loc,2) == 2 % Old channel file format
      Old = 1; % Flag
   end
end

if isfield(Channel,'imegsens') | isfield(Channel,'ieegsens')  | Old
   
   
   bst_message_window('wrap',{...
         'WARNING! Old channel file detected',...
         sprintf('Backing up %s to %s.old. . .', ChannelFile,ChannelFile),...
         sprintf('Updating Channel structure. . .')...
      })
   
   % Back-up of all channel structure  
   save(fullfile(fileparts(DataFiles(DataSelection).name),[ChannelFile,'.old']), 'Channel','-mat');
   
   % Update channel structure
   imegsens = good_channel(Channel,[],'MEG');
   ieegsens = good_channel(Channel,[],'EEG');
   
   if ~isempty(imegsens)
      [Channel(imegsens).Comment] = deal('');
      if(isfield(Channel,'Gcoef')), % does the old Gcoef field exist
         if ~isempty(Channel(imegsens(1)).Gcoef), % and is it not empty
            Channel(imegsens(1)).Comment = Channel(imegsens(1)).Gcoef;
            Channel = rmfield(Channel,'Gcoef');
         end
      end       
   end
   
   if ~isempty(ieegsens)
      
      % Update .Loc field (now only a single column)
      for k = ieegsens
         Channel(k).Loc = Channel(k).Loc(:,1);
      end
      % Update EEG reference information
      refndx = strmatch(char(Channel(ieegsens).Comment),'EEG REF');
      if ~isempty(refndx) % Specific reference electrode is used
         Channel(ieegsens(refndx)).Comment = '';
         Channel(ieegsens(refndx)).Type = 'EEG REF';
         bst_message_window({...
               sprintf('EEG reference is %s',Channel(ieegsens(refndx)).Name)...
            })
      else % Average reference is assumed
         [Channel(ieegsens).Comment] = deal('AVERAGE REF');
         bst_message_window({...
               sprintf('EEG reference is AVERAGE')...
            })
      end
      
   end
   
   % now clean up old structures
   if(isfield(Channel,'imegsens')),
      Channel = rmfield(Channel,'imegsens');
   end
   
   if isfield(Channel,'RefChannel')
      Channel = rmfield(Channel,'RefChannel');
   end
   
   if isfield(Channel,'ieegsens')
      Channel = rmfield(Channel,'ieegsens');
   end
   
   if isfield(Channel,'irefsens')
      % Assign proper type to MEG reference channels
      [Channel(Channel(imegsens(1)).irefsens).Type] = deal('MEG REF'); 
      Channel = rmfield(Channel,'irefsens');
      irefsens = good_channel(Channel,[],'MEG REF');
      [Channel(irefsens).Comment] = deal('');
   end
   
   
   save(fullfile(fileparts(DataFiles(DataSelection).name),ChannelFile),'Channel')
   
   bst_message_window('wrap',...
      sprintf('Updated Channel structure saved in %s.', ChannelFile)...
      )
end

if ~exist('Channel','var')
   % something wrong with the load
   DataParam = {...
         ' ','DATABASE ERROR XXXXXX',...
         sprintf('Channel file %s wrong format.',ChannelFile),...
         'Please update the Study info',...
         'or consider importing the original data set into BrainStorn again.'};
   
   bst_message_window('wrap',DataParam)
   set(handles.LoadSelectedData,'Enable','off')
   set(h,'Pointer','arrow')
   return
end

ChannelFlag = ones(length(Channel),1);
MEGchan = good_channel(Channel,ChannelFlag,'MEG'); % MEG Channels
MEGRef = good_channel(Channel,ChannelFlag,'MEG REF'); % MEG Reference Channels
EEGchan = good_channel(Channel,ChannelFlag,'EEG'); % EEG channels
EEGRef = good_channel(Channel,ChannelFlag,'EEG REF'); % EEG REF, if empty : average reference
OTHERchan = good_channel(Channel,ChannelFlag,'OTHER'); % STIM, EOG, ECG...

% NOTE: If ChannelFlag exists already, will overwrite the above definition
% 6-Jun-2002 DataFiles.name is now referential to Users.STUDIES

load(DataFiles(DataSelection).name,'ChannelFlag','Comment','Device','Time')

if ~exist('Comment','var')
   Comment = 'No name defined';
end
DataComment = Comment; 
clear Comment

bst_static_taskbar('SET','STUDY',DataComment); % set the study name

% now set the checkboxes depending on the data detected
TEMPSTR = {'MEG','EEG','OTHER'};
for i = 1:length(TEMPSTR),
   eval(sprintf('tempchan = %schan;',TEMPSTR{i})); % which channel information
   if(length(tempchan)),
      bst_static_taskbar('SET',TEMPSTR{i},'on')%,'value',1);
   else
      bst_static_taskbar('SET',TEMPSTR{i},'off')%,'value',0);
   end
end

% update the filename to the next one in the list
[fname,hDATA] = bst_static_taskbar('GET','DATA');
gDATA = guihandles(hDATA); % the handles 
% first unselect the one we were looking at in the task bar
bst_static_taskbar('select_deselect_file',hDATA,gDATA,'CLEAR');

% now set the popup to our new selection
set(hDATA,'val',DataSelection);

% activate the popup on the taskbar
bst_static_taskbar('popupmenu_DATA_Callback',hDATA,[],gDATA);

% and ensure that we have actually set this file
bst_static_taskbar('select_deselect_file',hDATA,gDATA,'SET');


% -------------- TESSELATION INFORMATION ----------------------------
% Check if Tessellation is available
% We are still referential at the Users.STUDIES

load(FileList(StudySelection).StudyFile,'BrainStormSubject');

if exist('BrainStormSubject','var') 
   % That may not be the case for older file names
   % go to the subjects folders
   cd(Users.SUBJECTS);
   if ~exist(BrainStormSubject,'file') % Study file is obsolete - let the user update its database
      if isempty(BrainStormSubject)
         DataParam = {...
               ' ','DATABASE ERROR XXXXXX',...
               'No subject was assigned to this study.',...
               'Please run Study Editor to update.',...
            };
      else
         DataParam = {...
               ' ','DATABASE ERROR XXXXXX',...
               sprintf('Subject file %s',BrainStormSubject),...
               'was not found.',...
               'Please update the Study info',...
               'with the new location of the Subject file'};
      end
      
      %set(handles.DataParam,'String',(DataParam))
      bst_message_window('wrap',DataParam)
      set(fig,'Pointer','Arrow')
      %deprecated code
      %set(handles.LoadSelectedData,'Enable','on') % SB | 03-Jun-2003 button's removed
      return
   end  
   
   % Find tessellation files for this subject
   TessPath = fileparts(BrainStormSubject); % referential
   TessPath = fullfile(Users.SUBJECTS,TessPath); % absolute
   [Tess,DataPopup,Leader] = find_brainstorm_files('tess',TessPath);
   
   % also find the MRI files at this point, for convenience and loading of the
   % bst_static_taskbar
   
   MRIFILES = find_brainstorm_files('anatomy',TessPath);
   
   if isempty(Tess) % No Tessellation file availble for this subject
      %bst_message_window('No Tessellation file specified for this subject');
      Tess = [];%'N/A';
      DispComment = {''};
   else
      cd(TessPath)
      for k = 1:length(Tess) % Explore Tess files and read Comments
         TessWhos = whos('-file',Tess{k});
         if ~isempty(strmatch('Comment',{TessWhos.name})) 
            load(Tess{k},'Comment');
            DispComment{k} = char(Comment{:});
         else
            DispComment{k} = 'Not a valid tessellation file (Comment missing in file)';
         end
      end
   end
else
   Tess = []%;'N/A';
   MRIFILES = [];
   DispComment = {''};
end

% load the static taskbar

refpath = strrep(TessPath,[Users.SUBJECTS,filesep],''); % referential path to tessfiles and MRIfiles
TESSFILES = Tess;
for i = 1:length(Tess),
   TESSFILES{i} = fullfile(refpath,Tess{i}); % referential filename
end
if(length(Tess) > 0),
   bst_static_taskbar('SET','TESS',TESSFILES);
else
   % empty
   bst_static_taskbar('SET','TESS',[]);
end

for i = 1:length(MRIFILES),
   MRIFILES{i} = fullfile(refpath,MRIFILES{i});
end
if(length(MRIFILES) > 0),
   bst_static_taskbar('SET','MRI',MRIFILES);
else
   bst_static_taskbar('SET','MRI',[]);
end



% this was loaded above the deprecated section
if ~exist('Device','var') % That's the case of older file names
   Device = 'Undefined';
end

% ditto, attempted load above the deprecated section
if ~exist('ChannelFlag','var') % That's the case of older file names
   DataParam = {...
         ' ','DATABASE ERROR XXXXXX',...
         'Old or altered version of data file detected.',...
         'Please consider importing the original data set into BrainStorm'...
      };
else
   % Bad Channels
   %try 
   if ~isempty(MEGchan)
      bc_MEG = find(ChannelFlag(MEGchan)==0);
   else
      bc_MEG = 0;
   end
   if ~isempty(EEGchan)
      bc_EEG = find(ChannelFlag(EEGchan)==0);
   else
      bc_EEG = 0;
   end
   if ~isempty(OTHERchan)
      bc_OTHER = find(ChannelFlag(OTHERchan)==0);
   else
      bc_OTHER = 0;
   end
   
   % Build cell array for display of available tessellation files and corresponding envelopes
   TessDisp = {            '_______________',...
         ' ',...
         sprintf('%d Tessellation File(s)',length(Tess)),...
         'Available for this Subject'};
   
   for k = 1:length(Tess)
      TessDisp{end+1} =  sprintf('      --> %s',strrep(Tess{k},'.mat',''));
      % Add Tessellation Information to FileList.
      FileList(StudySelection).Tessellation{k} = Tess{k}; 
   end
   
   if length(Tess) > 1
      TessDisp = {TessDisp{:},...
            'Run Subject Info for more details',...
            'about each envelope',...
            '_______________',...
         };
   end
   
   % EEG ref display
   if isempty(MEGRef) % No MEG reference channel
      MEGRef = 0;
   end
   % EEG ref display
   if isempty(EEGRef) % EEG is average-reference
      EEGRefDisp = 'Average Ref';
   else
      EEGRefDisp = Channel(EEGRef).Name;
   end
   
   
   DataParam = {...
         DataComment,...
         ' ',...
         sprintf('Device Type: %s',Device),...
         sprintf('Time Range: %3.2f to %3.2f ms',1000 * Time(1), 1000*Time(end)),...
         '',...
         '_______________',...
         '',...
         'Channel Count :',...
         sprintf('MEG   : %3d (%3d bad channel(s))',length(MEGchan), length(bc_MEG)),...
         sprintf('-> MEG REF : %3d',length(MEGRef)),...
         sprintf('EEG   : %3d (%3d bad channel(s))',length(EEGchan), length(bc_EEG)),...
         sprintf('-> EEG REF : %s',EEGRefDisp),...
         sprintf('OTHER : %3d (%3d bad channel(s))',length(OTHERchan), length(bc_OTHER)),...
         '_______________',...
         '',...
         char(TessDisp),...            
      };
   
   
   bst_message_window('wrap',...
      'Right-click for full information on current data set')
   
   
   InformationMenu = uicontextmenu; set(InformationMenu,'Parent',get(handles.listbox_Study,'parent'));
   uimenu(InformationMenu,'Label','See Study Information','Callback','data_manager(''DataInformation_Callback'',gcbo,[],guidata(gcbo))')
   set(handles.listbox_Study,'UIcontextMenu',InformationMenu)
   
   bst_message_window('wrap',...
      {' ',...
         'OK -> Ready for Visualization/Processing',...
         ' '})
end

% set(handles.DataParam,'String',(DataParam));
setappdata(fig,'DataParam',DataParam);

% deprecated, not needed
% setappdata(handles.DataParam,'HeadModelFunction',HeadModelFunction)
% set(handles.LoadSelectedData,'Enable','on')

% if exist('HeadModelName','var') & exist('GridName','var')
%     set(handles.HeadModelInfo,'String',{HeadModelName,GridName})
% end

Users.FILELIST = FileList; %setappdata(fig,'FileList',FileList); % updated with tesselation information
iDB = getpref('BrainStorm','iUserDataBase');
UserDB = getpref('BrainStorm','UserDataBase');
UserDB(iDB).FILELIST = Users.FILELIST;
setpref('BrainStorm','UserDataBase',UserDB);

% JCM 09-Sep-2003 disabling old taskbar
% taskbar('active'); % activate all buttons

% Adding contextual menu to load selected data set quickly

LoadDataMenu = uicontextmenu('Parent',fig);
uimenu(LoadDataMenu,'Label','See Study Information','Callback','data_manager(''DataInformation_Callback'',gcbo,[],guidata(gcbo))')
uimenu(LoadDataMenu,'Label','Load Selected','Callback','bst_static_taskbar(''menu_viewer_Callback'',gcbo,[],guidata(gcbo))','separator','on')
set(handles.listbox_Study,'UIcontextMenu',InformationMenu)
set(handles.listbox_Data,'UiContextMenu',LoadDataMenu)


makeuswait('stop')



% ---------------ROUTINE TO LOAD THE DATA (was pushbutton) --------------------
function varargout = LoadSelectedData_Callback(h, eventdata, handles, varargin)
% Load selected data, update the taskbar information, application data, BrainStorm Preferences

handles = guihandles(h); % ensure we have the handles (mop up of legacy coding)
% GuiData = guidata(h); % obsolete 05-Nov-2002

% JCM 09-Sep-2003 disabling old taskbar
% TASKBAR = getappdata(0,'BrainStormTaskbar'); % JCM 21-Mar-2002
% htaskbar = guihandles(TASKBAR);

fig = handles.DataManager; % handy shortcut

Users = get_user_directory;
FileList = Users.FILELIST; %getappdata(fig,'FileList');

DataFiles = getappdata(fig,'DataFiles');

cd(get(handles.edit_StudyFolder,'String')) % goto current study

UserDB = getpref('BrainStorm','UserDataBase'); % all of the databases
iDB = get(handles.popup_CurrentDatabase,'Val'); % selected
Users = UserDB(iDB);

CurrentData = struct('StudyFile',[],'SubjectFile',[]);

% what study and subject are selected
StudySelection = get(handles.listbox_Study,'Value');
SubjectSelection = get(handles.listbox_Data,'Value');

CurrentData.StudyFile = FileList(StudySelection).StudyFile;
CurrentData.SubjectName = FileList(StudySelection).Subject.Name;
CurrentData.SubjectFile = FileList(StudySelection).Subject.SubjectFile;

load(fullfile(Users.STUDIES,CurrentData.StudyFile),'Name')

[StudyPath, file, path] = fileparts(CurrentData.StudyFile);

if length(SubjectSelection) == 1 % Only one file selected
   CurrentData.DataFile = DataFiles(SubjectSelection).name; % referential name
   
   % deprecated, info for the old taskbar window
   if(0), % disabled 5-sep-2003 by jcm
      set(htaskbar.Sedit_CurrentData,'String',...
         { ['Study: ',Name],...
            ['Subject: ', CurrentData.SubjectName],...
            ['Data File: ',CurrentData.DataFile],...
            ['Database: ',Users.Comment]...
         });
   end
   
else % Mutliple data sets are selected
   
   CurrentData.DataFile =  DataFiles(SubjectSelection(1)).name;
   
   CurrentData.OtherDataFiles = {DataFiles(SubjectSelection(2:end)).name};
   
   % deprecated, info for the old taskbar window
   if(0), % disabled 5-sep-2003 by jcm
      set(htaskbar.Sedit_CurrentData,'String',...
         sprintf('Study: %s\nSubject: %s\n\n%d DATA SETS SELECTED\n\nFirst Data File: %s\nDatabase: %s',...
         Name, CurrentData.SubjectName,length(SubjectSelection),...
         CurrentData.DataFile,Users.Comment))
   end
end

Users.CurrentData = CurrentData;

if(0), % JCM 09-Sep-2003 disabling old taskbar
   if(0) % disable, JCM 21-Mar-2002
      set(findobj(TASKBAR,'tag','DataPlot'),'enable','on');
      set(findobj(TASKBAR,'tag','MRITool'),'enable','on');
      set(findobj(TASKBAR,'tag','Visualization'),'enable','on');
      set(findobj(TASKBAR,'tag','head_modeler'),'enable','on');
   else % JCM 21-Mar-2002
      % JCM 09-Sep-2003 disabling old taskbar
      % taskbar('active'); % set the buttons active
   end
end

% JCM 09-Sep-2003 disabling old taskbar
% setappdata(TASKBAR,'BrainStormDataBase',Users);

setpref('BrainStorm','CurrentData',CurrentData); % permanent storage
% Database information itself did not change

% NOTE: JCM 10-JUN-2002, moved dataplot_cb to another pushbutton, Load and View
% dataplot_cb('create')








% ---------------------- MENU CALLBACKS ------------------------------
% ---------------------- FILE MENU -----------------------------------
% --------------------------------------------------------------------
function varargout = menu_close_Callback(h, eventdata, handles, varargin)
close(handles.DataManager); % close this figure



% --------------------------------------------------------------------
function varargout = menu_import_data_Callback(h, eventdata, handles, varargin)

fig = importdata('create');



% ---------------------- EDIT MENU -----------------------------------
% --------------------------------------------------------------------
function varargout = menu_edit_subject_Callback(h, eventdata, handles, varargin)
% Edit the Subject File
handles = guihandles(h); % rebuild

% Which study was selected ?
Selection = get(handles.listbox_Study,'Value');

fig = subject_editor('create');
uiwait(fig);

% then reinitialize
initialize_database(handles);

% and finally back to selected study 
set(handles.listbox_Study,'Value',Selection);
listbox_Study_Callback(h, eventdata, handles, varargin)





% --------------------------------------------------------------------
function varargout = menu_edit_study_Callback(h, eventdata, handles, varargin)

% Call the Study File editor.
handles = guihandles(h); % rebuild

% Which study was selected ?
Selection = get(handles.listbox_Study,'Value');

fig = study_editor('create');
uiwait(fig);

% then rebuild database
data_manager % initialize_database(handles);

% and finally back to selected study 
set(handles.listbox_Study,'Value',Selection);
listbox_Study_Callback(h, eventdata, handles, varargin)






% --------------------------------------------------------------------
function varargout = menu_edit_database_Callback(h, eventdata, handles, varargin)

User = database_manager;
if(isempty(User)),
   % cancelled
   return
end

initialize_database(handles); % now reinitialize the database with the new database





% --------------------------------------------------------------------
function varargout = menu_edit_rebuild_Callback(h, eventdata, handles, varargin)

set(findobj(0,'type','figure'),'pointer','watch')

bst_message_window('wrap',...
   'Rebuilding database. . .')

iDB = getpref('BrainStorm','iUserDataBase');
UserDB = getpref('BrainStorm','UserDataBase');
UserDB(iDB).FILELIST = browse_study_folder(UserDB(iDB).STUDIES); % Update file list in current study folder
setpref('BrainStorm','UserDataBase',UserDB);

load_listbox_Study(handles); %rebuild Studies and Subjects list as well

data_manager % why the recursive call? 19-Aug-2003. apparently should rebuild, but doesn't sometimes

bst_message_window('wrap',...
   'Rebuilding database -> DONE')

set(findobj(0,'type','figure'),'pointer','arrow')



% ---------------------- VIEW MENU -----------------------------------
% --------------------------------------------------------------------
function varargout = menu_view_information_Callback(h, eventdata, handles, varargin)

figs = bst_win_manager;
DataParam = getappdata(figs.DataManager,'DataParam'); % Fetch Display Information 
h = bst_message_window('unique',DataParam); % SB - 12-jun-2003 | Use the new feature from bst_message_window instead of creating and altering a message box.

set(h,'visible','off');
bst_color_scheme(h); 
setappdata(h,'TileType','T');
bst_layout('align',h,1,2,2);

set(h,'Visible','on')




% --------------------------------------------------------------------
function varargout = menu_view_datafiles_Callback(h, eventdata, handles, varargin)

State = get(h,'Checked'); % current state of on or off
switch State
   case 'on'
      set(h,'Checked','off');
      set(handles.menu_view_results,'Checked','on'); % mutual exclusive
   case 'off'
      set(h,'Checked','on');
      set(handles.menu_view_results,'Checked','off'); % mutual exclusive
end

% now update the datafiles again
listbox_Study_Callback(handles.listbox_Study,[],handles);





% --------------------------------------------------------------------
function varargout = menu_view_results_Callback(h, eventdata, handles, varargin)

State = get(h,'Checked'); % current state of on or off
switch State
   case 'on'
      set(h,'Checked','off');
      set(handles.menu_view_datafiles,'Checked','on'); % mutual exclusive
   case 'off'
      set(h,'Checked','on');
      set(handles.menu_view_datafiles,'Checked','off'); % mutual exclusive
end

% now update the datafiles again
listbox_Study_Callback(handles.listbox_Study,[],handles);



% ------------- MENU POOLED ANALYSIS -----------------------
% --------------------------------------------------------------------
function varargout = menu_pooled_define_Callback(h, eventdata, handles, varargin)
% do nothing for now

bst_message_window('not implemented')



% --------------------------------------------------------------------
function varargout = menu_pooled_allow_Callback(h, eventdata, handles, varargin)
% do nothing for now, leave off
set(h,'Checked','off')
bst_message_window('not implemented')




% ------------------------ OLD PUSHBUTTON ROUTINES ------------------------------
% --------------------------------------------------------------------
function varargout = ComputeDefaultHeadModel_Callback(h, eventdata, handles, varargin)
% Compute head model(s) of selected study(ies) with default 
%  parameters as described in bst_headmodeler;

handles = guihandles(h); % rebuild handles

% Fetch StudyFile
Users = get_user_directory;
GUIs = bst_win_manager;

set(GUIs.DataManager,'Pointer','Watch')

bst_message_window('wrap',{...
      'Computing head model for study: ',...
      strrep(Users.CurrentData.StudyFile,'.mat',''),...
      'with default parameters',...
   });

OPTIONS.HeadModelFile = 'Default';
bst_headmodeler(Users.CurrentData.StudyFile,OPTIONS);

bst_message_window('wrap',{...
      strrep(Users.CurrentData.StudyFile,'.mat',''),...
      '-> DONE',...
   });

% Refresh DM display

if(strcmp('on',get(handles.listbox_Study,'enable'))),
   % study listbox is on, update the data
   data_manager('listbox_Study_Callback',GUIs.DataManager);
end

set(GUIs.DataManager,'Pointer','Arrow')



% --------------------------------------------------------------------
function varargout = pushbutton_CoRegisterStudies_Callback(h, eventdata, handles, varargin)
% JCM 28-May-2002, added this buttons so that ALL callbacks MUST first come
% through the feval switchyard, for easier tracking

bst_RegisterStudies('Create');



% --------------------------------------------------------------------
function varargout = DataInformation_Callback(h, eventdata, handles, varargin)
% Display specific information about selected data set in a separate quatertile

figs = bst_win_manager;
DataParam = getappdata(figs.DataManager,'DataParam'); % Fetch Display Information 

% Create a Message ListBox --------------------- SB 04-Jun-2003 | CBB, could be a function call

% h = msgbox(DataParam,'Data Information','none'); % Create message boc
% set(h,'Visible','off')
% set(h,'resize','on'); % in case it is too big
% 
% child = findobj(h); % get all of the children
% set(child,'Units','normal');
% a = unique(findobj(child,'type','text'));
% set(a,'visible','off');
% b = uicontrol(h,'Style','listbox','units','normal','position',[0.04 0.08 0.92 0.92],...
%     'FontName','FixedWidth');
% set(b,'String',DataParam);
% 
% okbttn = findobj(child,'String','OK');
% set(okbttn,'Tag','H_OK')

h = bst_message_window('unique',DataParam); % SB - 12-jun-2003 | Use the new feature from bst_message_window instead of creating and altering a message box.


% Create a Message ListBox --------------------- DONE

bst_color_scheme(h); % looks too dark, need a special
setappdata(h,'TileType','T');
bst_layout('align',h,1,2,2);

set(h,'Visible','on')



% --------------------------------------------------------------------
function varargout = HeadModelAdvanced_Callback(h, eventdata, handles, varargin)

% Basic call - will change when new headmodelling routine will be available
%GuiData = guidata(h); % obsolete
Users = get_user_directory; 
headmodeler_gui('LoadStudy',Users.CurrentData.StudyFile)





% --------------------------------------------------------------------
function varargout = pushbutton_importdata_Callback(h, eventdata, handles, varargin)
% JCM 28-May-2002, added this buttons so that ALL callbacks MUST first come
% through the feval switchyard, for easier tracking
handles = guihandles(h); % rebuild handles

fig = importdata('create');
% uiwait(fig); % wait on the user to finish
% 
% % then try reloading the database again, to detect any new data
% 
% initialize_database(handles);




% --------------------------------------------------------------------
function varargout = RefreshHeadModelList_Callback(h, eventdata, handles, varargin)
% Refresh HeadModelList display with new files available 
% (useful after call to HeadModeler when new HeadModel files were created)





% --------------------------------------------------------------------
function varargout = Manage_DataBase_Callback(h, eventdata, handles, varargin)
% Refresh DataManager display with new files available

handles = guihandles(h); % rebuild handles

if(0), % deprecated code
   initialize_users('create'); % Let the user pick-up a new data base  
end

% new code 24-May-2002
User = database_manager;
if(isempty(User)),
   % cancelled
   return
end

initialize_database(handles); % now reinitialize the database with the new database





% --------------------------------------------------------------------
function varargout = ResultFiles_Callback(h, eventdata, handles, varargin)
handles = guihandles(h); % ensure handles
% GuiData = guidata(h); % obsolete

Green = [.66 1 .43];
Dark = [.4 .4 .4];
if get(handles.ResultFiles,'Value')
   set(handles.ResultFiles,'Backgroundcolor',Green,'Foregroundcolor',Dark)
else
   set(handles.ResultFiles,'Backgroundcolor',Dark,'Foregroundcolor','w')
end

% now update the datafiles again
listbox_Study_Callback(handles.listbox_Study,[],handles);




% --------------------------------------------------------------------
function varargout = DataFiles_Callback(h, eventdata, handles, varargin)

handles = guihandles(h); % ensure handles
% GuiData = guidata(h); % obsolete

Green = [.66 1 .43];
Dark = [.4 .4 .4];
if get(handles.DataFiles,'Value')
   set(handles.DataFiles,'Backgroundcolor',Green,'Foregroundcolor',Dark)
else
   set(handles.DataFiles,'Backgroundcolor',Dark,'Foregroundcolor','w')
end

% now update the datafiles again
listbox_Study_Callback(handles.listbox_Study,[],handles);




% --------------------------------------------------------------------
function varargout = StudyBatch_Callback(h, eventdata, handles, varargin)

data_manager




% --------------------------------------------------------------------
function varargout = MRITool_Callback(h, eventdata, handles, varargin)
% Basic call
% NOTE: Need to install Alex' new code instead

mritool_cb('create')




% --------------------------------------------------------------------
function varargout = HeadModelList_Callback(h, eventdata, handles, varargin)
% Display HeadModelName and GridName

GUI = bst_win_manager;
handles = guihandles(GUI.DataManager);
HeadModelPath = get(handles.HeadModelList,'Userdata'); % Full path to the headmodel files
if isempty(HeadModelPath), 
   return, 
end

HeadModelFiles = get(handles.HeadModelList,'String');
HeadModel = get(handles.HeadModelList,'Value');

HeadModel_whos = whos('-file',fullfile(StudyPath,HeadModelFiles{HeadModel}));  

% Load info from file
if(isempty(strmatch('GridName',{HeadModel_whos.name})) | ...
      isempty(strmatch('HeadModelName',{HeadModel_whos.name}))) % Not valid or older headmodel file 
   
   if isempty(strmatch('Function',{HeadModel_whos.name})),
      InfoStr = 'Not a valid HeadModel file';
   else
      % function does exist
      load(fullfile(HeadModelPath,HeadModelFiles{HeadModel}),'Function')
      InfoStr = {'File is from older version of BrainStorm', ...
            char(getappdata(handles.DataParam,'HeadModelFunction'))};
   end
   
else
   
   % valid file
   load(fullfile(HeadModelPath,[HeadModelFiles{HeadModel},'.mat']),'GridName','HeadModelName')
   InfoStr = {...
         sprintf('HeadModel type: '),...
         sprintf('\t%s',HeadModelName),...
         'GridName:',...
         sprintf('\t%s',GridName{1})...
      };
   
end

%set(handles.HeadModelInfo,'String',InfoStr)
varargout{1} = InfoStr;



% --------------------------------------------------------------------
function varargout = pushbutton_LoadView_Callback(h, eventdata, handles, varargin)

handles = guihandles(h); % we have to rebuild

% first load the selected data
LoadSelectedData_Callback(handles.LoadSelectedData,[],handles);

% now view it
dataplot_cb('create')




% --------------- EDIT THE STUDY FILES --------------------------------
function varargout = StudyFile_Callback(h, eventdata, handles, varargin)
% Call the Study File editor.
handles = guihandles(h); % rebuild

% Which study was selected ?
Selection = get(handles.listbox_Study,'Value');

fig = study_editor('create');
uiwait(fig);

% then rebuild database
data_manager % initialize_database(handles);

% and finally back to selected study 
set(handles.listbox_Study,'Value',Selection);
listbox_Study_Callback(h, eventdata, handles, varargin)




% --------------- EDIT THE SUBJECT FILES --------------------------------
function varargout = SubjectFile_Callback(h, eventdata, handles, varargin)

% Edit the Subject File
handles = guihandles(h); % rebuild

% Which study was selected ?
Selection = get(handles.listbox_Study,'Value');

fig = subject_editor('create');
uiwait(fig);

% then reinitialize
initialize_database(handles);

% and finally back to selected study 
set(handles.listbox_Study,'Value',Selection);
listbox_Study_Callback(h, eventdata, handles, varargin)


% --------------------------------------------------------------------
function varargout = Quit_Callback(h, eventdata, handles, varargin)
% Stub for Callback of the uicontrol handles.Quit.

delete(gcbf)



% --------------------------------------------------------------------
function varargout = Refresh_Callback(h, eventdata, handles, varargin)
% Refresh DataManager display with new files available

set(findobj(0,'type','figure'),'pointer','watch')

bst_message_window('wrap',...
   'Rebuilding database. . .')

iDB = getpref('BrainStorm','iUserDataBase');
UserDB = getpref('BrainStorm','UserDataBase');
UserDB(iDB).FILELIST = browse_study_folder(UserDB(iDB).STUDIES); % Update file list in current study folder
setpref('BrainStorm','UserDataBase',UserDB);

load_listbox_Study(handles); %rebuild Studies and Subjects list as well

data_manager % why the recursive call? 19-Aug-2003. apparently should rebuild, but doesn't sometimes

bst_message_window('wrap',...
   'Rebuilding database -> DONE')

set(findobj(0,'type','figure'),'pointer','arrow')
