function varargout = study_editor(action,varargin);
%STUDY_EDITOR - GUI to edit the BrainStorm Study information, case switchyard
% function varargout = study_editor(action,varargin);
% Initiate with study_editor('create');
% Need that DataManager window be open
%
% Creates/Edits a brainstormstudy.mat file
% [FIG,HANDLES] = STUDY_EDITOR(action) returns figure handle

%<autobegin> ---------------------- 09-Jul-2004 22:17:21 -----------------------
% --------- 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_layout.m
%   toolbox\bst_message_window.m
%   toolbox\bst_win_manager.m
%   toolbox\get_user_directory.m
%   toolbox\makeuswait.m
%   toolbox\save_fieldnames.m
%
% Group : Preference data and their calls in this file:
%   'BrainStorm' : 'UserDataBase'
%   
%   setpref('BrainStorm','UserDataBase',UserDB);
%   
%   Studies = getpref('BrainStorm','Studies',[]);
%   Subjects = getpref('BrainStorm','Subjects',[]);
%   UserDB = getpref('BrainStorm','UserDataBase');
%   iDB = getpref('BrainStorm','iUserDataBase');
%
% Application data and their calls in this file:
%   'StudySubjectTable'
%   'TileType'
%   
%   setappdata(fig,'StudySubjectTable',StudySubject)
%   setappdata(fig,'StudySubjectTable',StudySubject);
%   setappdata(fig,'TileType','T')
%   
%   StudySubject = getappdata(fig,'StudySubjectTable');
%   TASKBAR = getappdata(0,'BrainStormTaskbar');
%
% 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 study_editor.fig
%   uicontrol:edit:DOM "" uses Callback for study_editor UpdateStudyFields
%   uicontrol:edit:DOS "" uses Callback for study_editor UpdateStudyFields
%   uicontrol:edit:eSession "" uses Callback for study_editor UpdateStudyFields
%   uicontrol:edit:LStudyName "" uses Callback for study_editor UpdateStudyFields
%   uicontrol:listbox:LStudies "Sifting through current DataBase..." uses Callback for
%     study_editor StudyListbox
%   uicontrol:listbox:LSubjects "..." uses Callback for study_editor SubjectListbox
%   uicontrol:pushbutton:Pushbutton1 "Browse" uses Callback for study_editor subj_loadfile
%   uicontrol:pushbutton:Pushbutton2 "Load" uses Callback for study_editor loadfile
%   uicontrol:pushbutton:pushbutton3 "Save" uses Callback for study_editor save
%   uicontrol:pushbutton:Pushbutton4 "Save as" uses Callback for study_editor saveas
%   uicontrol:pushbutton:Quit "Done" uses Callback for study_editor quit
%
% At Check-in: $Author: Mosher $  $Revision: 30 $  $Date: 7/09/04 8:42p $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 09-Jul-2004
% 
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
%    University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
%    Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
%    CNRS, Hopital de la Salpetriere, Paris, France
% 
% See BrainStorm website at http://neuroimage.usc.edu for further information.
% 
% Copyright (c) 2004 BrainStorm by the University of Southern California
% This software distributed  under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
% 
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 09-Jul-2004 22:17:21 -----------------------


% /---Script Author--------------------------------------\
% |                                                      |
% | *** Sylvain Baillet Ph.D.                            |
% | Cognitive Neuroscience & Brain Imaging Laboratory    |
% | CNRS UPR640 - LENA                                   | 
% | Hopital de la Salpetriere, Paris, France             |
% | sylvain.baillet@chups.jussieu.fr                     |
% |                                                      |
% |  *** John C. Mosher, Ph.D.                           |
% |  Biophysics Group                                    |
% \------------------------------------------------------/
%  
% Date of creation: January 1999
%
% Script History  :
% SB: 28-Mar-2002  : Systematic use of Users = getappdata 
%                     instead of Users = guidata or _directory.  
% SB: 17-Apr-2002  : Use the guihandles(.) command to access all 
%                     object handles  in figure study_editor.fig
% JCM 9-May-2002   : updated study_editor.fig file to fit XGA screen
% JCM 24-May-2002  : saved .fig as invisible, make visible here to 
%                    suppress flash also made routine more efficient, 
%                    since first lines were always being called,
%                    moved them to 'create', added comments. 
%                    Fixed bug between use of User. and Users.
% JCM 24-May-2002  : More edits. "path" is a keyword, use "pathname"
%                    improved saveas routine. Added returns of figure and handles
%                    to arguments out
% SB  28-May-2002  : Speed-up the load_listboxes process by communicating with the DataManager GUI
% ...............    Changed name to STUDY_EDITOR
% JCM  6-Jun-2002  : handling case of an empty folder to begin with
% JCM 20-Jun-2002  : Make "Save As" goto User.STUDIES first, change STUDYEDITOR to fig.
% SB  22-Jul-2002  : Make "Save" keep the current study current in listboxx display
% ...............    When "Save", update date of modification with today's date
% ...............    Directly display study 
% SB  28-Jul-2002  : Bug fixes when subject file is not found
% SB  01-Aug-2002  : Fixed issues in saving study file with edited fields
% SB  06-AUg-2002  : Fixed issues related to multiple studies selection and save.
% JCM 30-Oct-2002  : handled cases of getpref for empty Studies
% SB  03-Jun-2003  : Updated display in accordance with new GUI tiling.
% JCM 13-Sep-2003  : disabled a mandatory "waitfor" msgbox routine
%-----------------------------------------------------------------

%     CBB: strips and adds the suffix brainstormstudy. Instead put the real name into
%          application data and just show display data for convenience.
%          Make an feval switchyard

% old-fashioned case switchyard of R11, as opposed to newer feval 
% switchyards of R12.1

% These first lines are always called.

% First, recover the figure handle, or open a new window if none
fig = openfig(mfilename,'reuse');

% and recover all handles
handles = guihandles(fig);

% get common variables
TASKBAR = getappdata(0,'BrainStormTaskbar');
Users = get_user_directory;

if(nargout),
    varargout{1} = fig; % pass back the handles
    varargout{2} = handles;
end

switch(action)
    %---------------------------------------------------------------
case 'create'
    
    makeuswait ('start')
    
    bst_color_scheme(fig);
    %set(fig,'visible','off')
    setappdata(fig,'TileType','T')
    bst_layout('align',fig,2,1,1)
    
    bst_win_manager(fig,'Other');
    %drawnow % takes a long time to do the rest, let user see the figure
    
    
    % show locations in the static text
    set(handles.Btext_UserSTUDIES,'string',...
        ['Studies in ' Users.STUDIES]);
    
    set(handles.Btext_UserSUBJECTS,'string',...
        ['Subjects in ', Users.SUBJECTS]);
    
    feval(mfilename,'load_listboxes');
    set(fig,'visible','on');
    
    makeuswait ('stop')
    %---------------------------------------------------------------
case 'load_listboxes' % Load Study and Subject information to initialize display in GUI
    
    makeuswait ('start')
    
    figs = bst_win_manager; %Handles to BST GUIs
    
    % STUDIES ------------------------------------------------------
    % Get all information on studies in current DataBase
    Studies = getpref('BrainStorm','Studies',[]); % initialized by data_manager 
    
    if ~isempty(Studies) % Studies are available 
        % Display only StudyFolder name(s) - one brainstormstudy file per folder 
        % (this was checked by data_manager)
        % meaning there is one to one correspondence between Study folder and Study file
        % which filename has no importance after all.
        Display = cellstr(char(Studies(:).StudyFolder)); 
        Display = [{'Create New Study'};Display];
        set(handles.LStudies,'enable','on')
    else
        Display = sprintf('No study file found in %s',Users.STUDIES); 
        set(handles.LStudies,'enable','inactive');
    end
    
    set(handles.LStudies,'Value',1,'String',Display,'Max',length(Display)+1) ; % Allow multiple study selection
    
    % Create StudySubject assignment table
    % StudySubject table is a vector.
    % For each entry (i.e. each study), StudySubject
    % indicates the index of the subject file in the Subject's list (fig.LSubjects)
    [StudySubject(1:length(Studies)+1)] = deal(struct('Name',0,'Subject',0,'DOM',0,'Session',0,'DOS',0));
    % +1 because our first study will be 'Create New Study'
    setappdata(fig,'StudySubjectTable',StudySubject)
    
    % SUBJECTS ------------------------------------------------------
    % Fill the Subject listbox with available subject's file in current database
    Subjects = getpref('BrainStorm','Subjects',[]);
    
    if(~isempty(Subjects))
       % One subject at time : 'Max' set to 1
       set(handles.LSubjects,'String',cellstr(char(Subjects.Name)),'Value',1); 
    end
    
    %     % Find BrainStorm Default
    %     iDefault = strmatch(cellstr(char(Subject.Name)),'BrainStorm Default');
    %   
    
    % Now get selected study from DataManager window and display corresponding information 
    GUIs = bst_win_manager;
    DMhandles = guihandles(GUIs.DataManager); % Handles from DataManager GUI
    iStudy = get(DMhandles.listbox_Study,'Value'); % Current study
    set(handles.LStudies,'Value',iStudy+1) % Fisrt item is 'Create New Study'
        
    
    if ~isempty(Studies)
        feval(mfilename,'StudyListbox'); % now load the information on currenty; selected study in DataManager
    end 
    
    makeuswait ('stop')
    %---------------------------------------------------------------
    
case 'StudyListbox' % Selection of one or multiple studies in LStudies listbox
    
    cd(Users.STUDIES);
    
    % Which studies are selected
    iStudy = get(handles.LStudies,'Value');
    
    % Studies database.
    Studies = getpref('BrainStorm','Studies',[]);
    % Subjects database.
    Subjects = getpref('BrainStorm','Subjects',[]);
    % Both were created by DATA_MANAGER
    
    %CHEAT: No handling here for empty Studies or Subjects!
    
    % Get Study-Subject assignment table
    StudySubject = getappdata(fig,'StudySubjectTable');
            
    if iStudy == 1
        % Create a new study
        
        % Study Information
        StudySubject(1).Name = 'New Study';
        StudySubject(1).DOS = 'N/A';
        StudySubject(1).DOM = date;
        StudySubject(1).Session = 'N/A';
        
        set(handles.DOS,'String',StudySubject(1).DOS)
        set(handles.DOM,'String',StudySubject(1).DOM)
        set(handles.eSession,'String',StudySubject(1).Session)
        set(handles.LStudyName,'String',StudySubject(1).Name)
        
        
        StudySubject(1).Subject = 1; % Assume Default Subject for any new study.
        % Now display Name of Subject and save assignement to table 
        set(handles.LSubjects,'Value',StudySubject(1).Subject); 
        set(handles.eSubjectName,'String', 'Default BrainStorm Subject');
        
    elseif length(iStudy) == 1 % Selection of a single existing study; display all information
        
        if StudySubject(iStudy).Name == 0 % Information was not edited by user
            set(handles.LStudyName,'String',Studies(iStudy-1).StudyName)
            StudySubject(iStudy).Name  = Studies(iStudy-1).StudyName;   
        else
            set(handles.LStudyName,'String',StudySubject(iStudy).Name)
        end
        
        if StudySubject(iStudy).DOS == 0 % Information was not edited by user
            load(Studies(iStudy-1).StudyFile); % Load rest of information
            if ~exist('DateOfStudy','var')
                DateOfStudy = 'N/A';
            end
            if isempty(DateOfStudy)
                DateOfStudy = 'N/A';
            end
            set(handles.DOS,'String',DateOfStudy)
            StudySubject(iStudy).DOS = DateOfStudy;
        else
            set(handles.DOS,'String',StudySubject(iStudy).DOS)
        end
        
        if StudySubject(iStudy).DOM == 0 % Information was not edited by user
            load(Studies(iStudy-1).StudyFile); % Load rest of information
            if ~exist('DateOfModification','var')
                DateOfModification = date; % Assign default date 
            end
            if isempty(DateOfModification)
                DateOfModification = date;
            end
            StudySubject(iStudy).DOM = DateOfModification;
            set(handles.DOM,'String',DateOfModification)
        else
            set(handles.DOM,'String',StudySubject(iStudy).DOM)
        end
        
        if StudySubject(iStudy).Session == 0 % Information was not edited by user
            load(Studies(iStudy-1).StudyFile); % Load rest of information
            if ~exist('Session','var')
                Session = 'N/A';
            end
            if isempty(Session)
                Session = 'N/A';
            end
            set(handles.eSession,'String',Session)
            StudySubject(iStudy).Session = Session;
        else
            set(handles.eSession,'String',StudySubject(iStudy).Session)
        end
        
                
        if StudySubject(iStudy).Subject == 0 % No subject was assigned to this study 
            % during this study_editor session
            
            if ~exist('BrainStormSubject','var') % Subject file was not defined for this study
                % Assume default subject
                StudySubject(iStudy).Subject = 1;
                
            elseif exist(fullfile(Users.SUBJECTS,BrainStormSubject),'file') ~= 2
               % Subject file was not found in database
               % exist for 'file' works for directories and files, 7 if directory , 2 if file
               % here we're looking for a file, hence ~= 2
               if ~isempty(BrainStormSubject)
                  % JCM 13-Sep-2003 disabled the mandatory waitbox feature
                  % h = msgbox({...
                  %     sprintf('Subject file %s was not found in', BrainStormSubject),...
                  %      sprintf('%s.',Users.SUBJECTS),...
                  %      'Please select a Subject from current database in the Subjects''s list.'},...
                  %  'Lost Subject File' );
                  
                  bst_message_window('wrap',{...
                        sprintf('Subject file %s was not found in', BrainStormSubject),...
                        sprintf('%s.',Users.SUBJECTS),...
                        'Please select a Subject from current database in the Subjects''s list.'})
                  
                  % waitfor(h)
               end
               return
               
                % SB = 06-Aug-2202
                % I'm commenting the lines below because users need to have all their subject information
                % in the DataBase; meaning that asking them for a brainstormsubject file might cause confusion
                % because the missing subject file might well be outside of the current Subject's data base.
                % Further, we'd better not ask for a specific brainstormsubject file because most users won't need
                % to create one (it will be automatically created and managed from the GUIs). Therefore, we should stick to 
                % asking for a subject name from the list.

                %                 cd(Users.SUBJECTS)
                %                 [BrainStormSubject,pathname] = uigetfile(['*brainstormsubject*.mat'], ...
                %                     'Pick a BrainStorm Subject File');
                %                 
                %                 % Check whether subject is in current database
                %                 while isempty(strmatch(Users.SUBJECTS,pathname))
                %                     hh = msgbox({...
                %                             sprintf('%s needs to be placed in',BrainStormSubject),...
                %                             sprintf('current SUBJECTS database :%s.',Users.SUBJECTS),...
                %                         }, 'DataBase Violation');
                %                     
                %                     waitfor(hh);
                %                     
                %                     [BrainStormSubject,pathname] = uigetfile(['*brainstormsubject*.mat'], ...
                %                         'Pick a BrainStorm Subject File');
                %                     
                %                     if BrainStormSubject == 0, 
                %                         % user cancelled
                %                         return, 
                %                     end
                %                 end
                %                 
                %                 cd(Users.STUDIES)
                %                 
                %                 BrainStormSubject = strrep(fullfile(pathname,BrainStormSubject),Users.SUBJECTS,'');
                %                 
                %                 save(Studies(iStudy-1).StudyFile,'BrainStormSubject','-append')
                %                 
            end
            
            % Now find subject in Subjects list:
            StudySubject(iStudy).Subject = strmatch(BrainStormSubject,char(Subjects.SubjectFile)); 
            % iSubject should not be empty as BrainStormSubject was checked to be in current 
            
        end
        
        % Now display Name of Subject and save assignement to table 
        set(handles.LSubjects,'Value',StudySubject(iStudy).Subject); 
       
        set(handles.eSubjectName,'String', Subjects(StudySubject(iStudy).Subject).Name); 
        
    else % If multiple studies are selected
       
        set([handles.LStudyName,handles.DOS,handles.DOM,handles.eSession],...
            'String','Multiple values')
        StudySubject = getappdata(fig,'StudySubjectTable');
        
        if ~isempty(find(iStudy == 1)) % Selected studies include 'New Study'
            % Force single selection
            set(handles.LStudies,'Value',1)
            feval(mfilename,'StudyListbox');
        end
        
            
        if length(unique([StudySubject(iStudy).Subject])) == 1
            % If all studies have same subject - highlight subject in listbox
            if StudySubject(iStudy(1)).Subject == 0; % Same subject but still unedited in this session 
                load(Studies(iStudy(1)-1).StudyFile,'BrainStormSubject'); % Load subject information            
                iSubject = strmatch(BrainStormSubject,char(Subjects.SubjectFile)); 
                set(handles.LSubjects,'Value',iSubject); 
                set(handles.eSubjectName,'String', Subjects(iSubject).Name); 
            else
                set(handles.LSubjects,'Value',StudySubject(iStudy(1)).Subject)
                set(handles.eSubjectName,'String', Subjects(StudySubject(iStudy(1)).Subject).Name)
            end
        else
            % Assume default subject
            set(handles.LSubjects,'Value',1)
            set(handles.eSubjectName,'String', 'Multiple Subjects')
        end
        
    end % if length(iStudy)
    
    % Store  StudySubject Table
    
    setappdata(fig,'StudySubjectTable',StudySubject);
    

%---------------------------------------------------------------

case 'SubjectListbox' % Assign a new subject to selected studies
    
    % Indices of selected Studies
    iStudies = get(handles.LStudies,'Value');
    
    % Fetch StudySubject assignment table
    StudySubject = getappdata(fig,'StudySubjectTable');
    
    % Get Subject index and assign to selected studies
    iSubject = get(handles.LSubjects,'Value');
    [StudySubject(iStudies).Subject] = deal(iSubject);
    setappdata(fig,'StudySubjectTable',StudySubject);
    
    % And load Subject's name
    Subjects = getpref('BrainStorm','Subjects',[]);
    % CHEAT: No handling for empty Subjects
    load(fullfile(Users.SUBJECTS,Subjects(iSubject).SubjectFile),'Name') 
    
    if ~exist('Name','var')
        set(handles.eSubjectName,'String','Not available');
    else
        set(handles.eSubjectName,'String',Name);
    end
    
    %---------------------------------------------------------------
    
case {'save','saveas'}
    % Save altered study files according to 
    % the current StudySubject Assignment table 
    
    % Get Study-Subject assignment table
    StudySubject = getappdata(fig,'StudySubjectTable');
    % Get Studies and Subjects databases
    Studies = getpref('BrainStorm','Studies',[]);
    Subjects = getpref('BrainStorm','Subjects',[]);
    
    % CHEAT: No handling for empty Studies or Subjects!
    
    %     % Find Studies that have been changed during this call to STUDY_EDITOR
    %     iStudies = unique([find([StudySubject(:).Subject]),...
    %         find([StudySubject(:).DOS]),...
    %         find([StudySubject(:).DOM]),...
    %         find([StudySubject(:).Name]),...
    %         find([StudySubject(:).Session])]);
    %         
    
    iStudies = get(handles.LStudies,'Value'); % CBB - see above
    % CBB - see above
    % not only save selected studies but all studies that have been 
    % altered during this call to STUDY_EDITOR.
    
    
    for k = iStudies
        % No creation of a new Study
        % just update selected StudyFiles.
        if ~strcmp(StudySubject(k).DOM,'0')% Edited field
            Study.DateOfModification = StudySubject(k).DOM;
        end
        if ~strcmp(StudySubject(k).DOS,'0')
            Study.DateOfStudy = StudySubject(k).DOS;
        end
        if ~strcmp(StudySubject(k).Name,'0')
            Study.Name = StudySubject(k).Name;
        end
        if ~strcmp(StudySubject(k).Session,'0')
            Study.Session = StudySubject(k).Session;
        end
        % Now Subject's information
        iSubject = StudySubject(k).Subject;
        if iSubject == 0 % No Subject was specified
            % Assume default
            iSubject = 1;
        end
        Study.BrainStormSubject = Subjects(iSubject).SubjectFile;
        
        if k == 1 % Creation of a new StudyFile
            action = 'saveas'; % Force request for a new file name
        end
        
        switch(action)
        case 'save' % Replace older StudyFile
            
            save_fieldnames(Study,fullfile(Users.STUDIES,Studies(k-1).StudyFile),'-append');
            Users.FILELIST(k-1).Subject.Name = Subjects(iSubject).Name;
            Users.FILELIST(k-1).Subject.SubjectFile = Subjects(iSubject).SubjectFile;
            Users.FILELIST(k-1).StudyName = Study.Name;
            
            StudyDirName = char(Users.FILELIST(:).StudyFolder);
            StudyName = char(Users.FILELIST(:).StudyName);
            tmp = [Users.FILELIST(:).Subject];
            SubjectName = char(tmp.Name);
                        
            fmtstr = sprintf('%%-%ds | %%-%ds | %%-%ds',...
                size(StudyDirName,2),size(StudyName,2),size(SubjectName,2));
            
            for kk = 1:length(Users.FILELIST)
                Users.FILELIST(kk).display = sprintf(fmtstr,...
                    strrep(Users.FILELIST(kk).StudyFolder,' ','.'),strrep(Users.FILELIST(kk).StudyName,' ','.'),strrep(Users.FILELIST(kk).Subject.Name,' ','.'));
            end
            
            iDB = getpref('BrainStorm','iUserDataBase');
            UserDB = getpref('BrainStorm','UserDataBase');
            UserDB(iDB) = rmfield(Users,'CurrentData');
            setpref('BrainStorm','UserDataBase',UserDB);
            
         case 'saveas' % Ask for a new StudyFile name
            
             cd(Users.STUDIES)
             % Default studyfile name
             StudyFile = [Study.Name,'_brainstormstudy.mat'];
            [study_file,pathname] = uiputfile(StudyFile, ...
                'Save as a new BrainStorm study file');
            
            if isequal(study_file,0) | isequal(pathname,0)
                % user cancelled or error occurred
                return, 
            end
            
            save_fieldnames(Study,fullfile(pathname,study_file),'-append');
            
            % Rebuild database - CBB : just add a file to Users.FILELIST
            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);

        end
        
    end

    % refresh databases and database display 
    
    feval(mfilename,'UpdateStudyFields')
    feval(mfilename,'StudyListbox')
    
    %---------------------------------------------------------------
case 'UpdateStudyFields'
    % Update either of the StudyFile fields and store new info in 
    % StudySubject assignment table
        
    % Get Study-Subject assignment table
    StudySubject = getappdata(fig,'StudySubjectTable');
    
    % Find selected Studies 
    iStudies = get(handles.LStudies,'Value');
    
    for k = iStudies
        % No creation of a new Study
        % just update selected StudyFiles.
        StudySubject(k).DOM = get(handles.DOM,'String');
        if isempty(StudySubject(k).DOM) 
            StudySubject(k).DOM = date; % Assume default date
        end
        if strcmpi(StudySubject(k).DOM,'Multiple Values') % Do not update - multiple studies were selected
            StudySubject(k).DOM = 0;
        end
        StudySubject(k).DOS = get(handles.DOS,'String');
        if isempty(StudySubject(k).DOS)
            StudySubject(k).DOS = 0;
        end
        if strcmpi(StudySubject(k).DOS,'Multiple Values') % Do not update - multiple studies were selected
            StudySubject(k).DOS = 0;
        end
        StudySubject(k).Name = get(handles.LStudyName,'String');
        if isempty(StudySubject(k).Name)
            StudySubject(k).Name = 0;
        end
        if strcmpi(StudySubject(k).Name,'Multiple Values') % Do not update - multiple studies were selected
            StudySubject(k).Name = 0;
        end
        StudySubject(k).Session = get(handles.eSession,'String');
        if isempty(StudySubject(k).Session)
            StudySubject(k).Session = 0;
        end
        if strcmpi(StudySubject(k).Session,'Multiple Values') % Do not update - multiple studies were selected
            StudySubject(k).Session = 0;
        end
    
    end
    
    % Store updated information
    setappdata(fig,'StudySubjectTable',StudySubject);
    
    %---------------------------------------------------------------
    
case 'quit'
    close(fig)
    
    
    %--------------------- END OF ALL CASES -----------------------------
end
