function BrainStormWindows = bst_win_manager(Fig,WinType);
%BST_WIN_MANAGER - GUI Window management for BrainStorm
% function BrainStormWindows = bst_win_manager(Fig,WinType);
% Utility routine for GUI window management in BrainStorm
% Updates the appdata from the Taskbar called 'BrainStormWindows'
% Fig is a figure handle corresponding to an active GUI 
% WinType is an optional tag that describes the type of GUI corresponding to figure Fig
% WinType may be any string of characters like one of the following
% which are conventional WinTypes for main BrainStorm windows/GUIs:
% - 'DataManager' : windows associated with the database manager
% - 'DataViewer'  : viewing data
% - 'MRIView'     : viewing MRI images and source localizations
% - 'Results'     : showing source estimation results
% - 'Source'      : setting-up for source estimation
% - 'Head'        : generating head models 
% - 'Message'     : Associated with some general message to the user
% - 'Other'       : windows not fitting above (Default type when WinType is not specified)
%
% Return BrainStormWindows, a structure with fields as described above with handles to all BsT's current GUI figures

%<autobegin> ---------------------- 26-May-2004 11:29:51 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: GUI and Related
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\brainstorm.m
%
% Application data and their calls in this file:
%   'BrainStormWindows'
%   
%   setappdata(TASKBAR,'BrainStormWindows',BrainStormWindows);
%   
%   BrainStormWindows = getappdata(TASKBAR,'BrainStormWindows');
%
% At Check-in: $Author: Mosher $  $Revision: 17 $  $Date: 5/26/04 9:59a $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 24-May-2004
% 
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
%    University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
%    Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
%    CNRS, Hopital de la Salpetriere, Paris, France
% 
% See BrainStorm website at http://neuroimage.usc.edu for further information.
% 
% Copyright (c) 2004 BrainStorm by the University of Southern California
% This software distributed  under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
% 
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 26-May-2004 11:29:51 -----------------------

% /--- 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                       |
% |                                                      |
% \------------------------------------------------------/
%  
% Date of creation: April 2002
% Script History ---------------------------------------------------------------
% SB  28-May-2002 Minor upgrade when nargin ==1
% SB  08-Aug-2002 Added feature so that any WinType is admissible.
% JCM 09-Sep-2003 Commenting, removing old taskbar
% JCM 11-May-2004 Removing old handles if figures no longer exist, old "if" test
%                 switch
% ------------------------------------------------------------------------------

% Get handle to BrainStorm's Taskbar
% JCM moved it to the new taskbar
TASKBAR = findobj(0,'Tag','static_taskbar');
BrainStormWindows = getappdata(TASKBAR,'BrainStormWindows'); % return empty if not defined

if isempty(BrainStormWindows) % Define the whole structure 
   BrainStormWindows  = struct('All',[],'DataManager',[],'DataViewer',[],'MRIView',[],...
      'Results',[],'Source',[],'Head',[],'Message',[],'Other',[]);
end

if nargin == 0
   Fig = [];
   WinType = 'Other';
else
   if ~ishandle(Fig)
      errordlg('Not a proper figure handle','bst_win_manager error')
      return
   end
end

if nargin == 1
   WinType = 'Other'; % Assign default window type
else
   BrainStormWindows.All = unique([BrainStormWindows.All(ishandle(BrainStormWindows.All)),Fig]);
end

switch(lower(WinType))
   case 'datamanager'
      BrainStormWindows.DataManager = Fig;
   case 'dataviewer'
      % The ishandle command ensure that all entries are valid and current figure handles
      BrainStormWindows.DataViewer = unique([BrainStormWindows.DataViewer(ishandle(BrainStormWindows.DataViewer)),Fig]);
   case 'mrriview'
      BrainStormWindows.MRIView = unique([BrainStormWindows.MRIView(ishandle(BrainStormWindows.MRIView)),Fig]); 
   case 'results'
      BrainStormWindows.Results = unique([BrainStorm.Results(ishandle(BrainStorm.Results)),Fig]);
   case 'source'
      BrainStormWindows.Source = Fig;
   case 'head'
      BrainStormWindows.Head = Fig;
   case 'message'
      BrainStormWindows.Message = unique([BrainStormWindows.Message(ishandle(BrainStormWindows.Message)),Fig]);
      
      %     case 'other'
      %         BrainStormWindows.Other = unique([BrainStormWindows.Other(ishandle(BrainStormWindows.Other)),Fig]);
      %         
   otherwise % Create a new type of window
      
      %errordlg(sprintf('Figure Window of unauthorized type %s',WinType),'Error from bst_win_manager')
      %return
      % Check if new type of window exists
      
      if ~isfield(BrainStormWindows,WinType) % If not : initialization to empty field.
         BrainStormWindows = setfield(BrainStormWindows,WinType,[]);
      end
      eval(sprintf('BrainStormWindows.%s = unique([BrainStormWindows.%s(ishandle(BrainStormWindows.%s)),Fig]);',WinType,WinType,WinType));
      
end

% final sanity check of all figures

NAMES = fieldnames(BrainStormWindows); % all of the fields

for i = 1:length(NAMES),
   % for each field name
   ndx = eval(['find(ishandle(BrainStormWindows.',NAMES{i},'));']); % valid figure handles  
   eval(['BrainStormWindows.',NAMES{i},' = BrainStormWindows.',NAMES{i},'(ndx);']); % keep only the good
end
   

setappdata(TASKBAR,'BrainStormWindows',BrainStormWindows);
