[Master Index] [Index for Toolbox]

# dataplot_cb

## (Toolbox/dataplot_cb.m in BrainStorm 2.0 (Alpha))

### Function Synopsis

    varargout = dataplot_cb(action,varargin)

### Help Text

    DATAPLOT_CB - : Callback switchyard for the DATAViewer Tool
     function varargout = dataplot_cb(action,varargin)
     Callback function for the DATAVIEWER tool

### Cross-Reference Information

This function calls

    aviplayer                          C:\BrainStorm_2001\PublicToolbox\OtherTools\aviplayer.m
    brainstorm_filt                    C:\BrainStorm_2001\Toolbox\brainstorm_filt.m
    bst_color_scheme                   C:\BrainStorm_2001\Toolbox\bst_color_scheme.m
    bst_imaging_display                C:\BrainStorm_2001\Toolbox\bst_imaging_display.m
    bst_layout                         C:\BrainStorm_2001\Toolbox\bst_layout.m
    bst_message_window                 C:\BrainStorm_2001\Toolbox\bst_message_window.m
    bst_mriviewer                      C:\BrainStorm_2001\Toolbox\bst_mriviewer.m
    bst_static_taskbar                 C:\BrainStorm_2001\Toolbox\bst_static_taskbar.m
    bst_wavedata_display               C:\BrainStorm_2001\Toolbox\bst_wavedata_display.m
    bst_win_manager                    C:\BrainStorm_2001\Toolbox\bst_win_manager.m
    file_selection_win                 C:\BrainStorm_2001\Toolbox\file_selection_win.m
    filterGUI                          C:\BrainStorm_2001\Toolbox\filterGUI.m
    find_brainstorm_files              C:\BrainStorm_2001\Toolbox\find_brainstorm_files.m
    find_brainstorm_structure          C:\BrainStorm_2001\Toolbox\find_brainstorm_structure.m
    findclosest                        C:\BrainStorm_2001\Toolbox\findclosest.m
    get_channel                        C:\BrainStorm_2001\Toolbox\get_channel.m
    get_user_directory                 C:\BrainStorm_2001\Toolbox\get_user_directory.m
    good_channel                       C:\BrainStorm_2001\Toolbox\good_channel.m
    lcmvbf                             C:\BrainStorm_2001\Toolbox\lcmvbf.m
    load_brainstorm_file               C:\BrainStorm_2001\Toolbox\load_brainstorm_file.m
    makeuswait                         C:\BrainStorm_2001\Toolbox\makeuswait.m
    manage_corticalscouts              C:\BrainStorm_2001\Toolbox\manage_corticalscouts.m
    meg4read                           C:\BrainStorm_2001\Toolbox\meg4read.m
    mutincomp                          C:\BrainStorm_2001\Toolbox\mutincomp.m
    norcol                             C:\BrainStorm_2001\Toolbox\norcol.m
    parametric_estimation              C:\BrainStorm_2001\Toolbox\parametric_estimation.m
    rap_music_parameters               C:\BrainStorm_2001\Toolbox\rap_music_parameters.m
    save_fieldnames                    C:\BrainStorm_2001\Toolbox\save_fieldnames.m
    set_sourceviewing_parameters       C:\BrainStorm_2001\Toolbox\set_sourceviewing_parameters.m
    sourceimaging                      C:\BrainStorm_2001\Toolbox\sourceimaging.m
    togglebuttoncolor                  C:\BrainStorm_2001\Toolbox\togglebuttoncolor.m
    view3d                             C:\BrainStorm_2001\PublicToolbox\OtherTools\view3d.m
    windfind                           C:\BrainStorm_2001\Toolbox\windfind.m
    zscore_gui                         C:\BrainStorm_2001\Toolbox\zscore_gui.m

This function is called by

    bst_imaging_display                C:\BrainStorm_2001\Toolbox\bst_imaging_display.m
    bst_static_taskbar                 C:\BrainStorm_2001\Toolbox\bst_static_taskbar.m
    bst_wavedata_display               C:\BrainStorm_2001\Toolbox\bst_wavedata_display.m
    data_manager                       C:\BrainStorm_2001\Toolbox\data_manager.m
    manage_corticalscouts              C:\BrainStorm_2001\Toolbox\manage_corticalscouts.m
    parametric_estimation              C:\BrainStorm_2001\Toolbox\parametric_estimation.m
    rap_music_parameters               C:\BrainStorm_2001\Toolbox\rap_music_parameters.m
    results_time_series                C:\BrainStorm_2001\Toolbox\results_time_series.m
    sourceimaging                      C:\BrainStorm_2001\Toolbox\sourceimaging.m
    zscore_gui                         C:\BrainStorm_2001\Toolbox\zscore_gui.m

### Listing of function C:\BrainStorm_2001\Toolbox\dataplot_cb.m

    function varargout = dataplot_cb(action,varargin)
    %DATAPLOT_CB - : Callback switchyard for the DATAViewer Tool
    % function varargout = dataplot_cb(action,varargin)
    % Callback function for the DATAVIEWER tool

    %<autobegin> ---------------------- 12-Oct-2004 12:01:11 -----------------------
    % --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
    %
    % CATEGORY: GUI and Related
    %
    % Alphabetical list of external functions (non-Matlab):
    %   publictoolbox\othertools\aviplayer.m
    %   publictoolbox\othertools\view3d.m
    %   toolbox\brainstorm_filt.m
    %   toolbox\bst_color_scheme.m
    %   toolbox\bst_imaging_display.m
    %   toolbox\bst_layout.m
    %   toolbox\bst_message_window.m
    %   toolbox\bst_mriviewer.m
    %   toolbox\bst_static_taskbar.m
    %   toolbox\bst_wavedata_display.m
    %   toolbox\bst_win_manager.m
    %   toolbox\dataplot_cb.m  NOTE: Routine calls itself explicitly
    %   toolbox\file_selection_win.m
    %   toolbox\find_brainstorm_files.m
    %   toolbox\find_brainstorm_structure.m
    %   toolbox\findclosest.m
    %   toolbox\get_channel.m
    %   toolbox\get_user_directory.m
    %   toolbox\good_channel.m
    %   toolbox\load_brainstorm_file.m
    %   toolbox\makeuswait.m
    %   toolbox\manage_corticalscouts.m
    %   toolbox\meg4read.m
    %   toolbox\mutincomp.m
    %   toolbox\norcol.m
    %   toolbox\parametric_estimation.m
    %   toolbox\rap_music_parameters.m
    %   toolbox\save_fieldnames.m
    %   toolbox\set_sourceviewing_parameters.m
    %   toolbox\sourceimaging.m
    %   toolbox\togglebuttoncolor.m
    %   toolbox\windfind.m
    %   toolbox\zscore_gui.m
    %
    % Subfunctions in this file, in order of occurrence in file:
    %   initialize_SourceTimeViewing(handle)
    %   initialize_SourceSpatialViewing(handle)
    %   shorterfilename = shorter_filename(longfilename);
    %   slct_modal = get_selected_modalities;
    %
    % Group : Preference data and their calls in this file:
    %   'BrainStorm' : 'UserCurrentData'
    %
    %   setpref('BrainStorm','UserCurrentData',CurrentData);
    %
    %   CurrentData = getpref('BrainStorm','CurrentData');
    %   cd(fullfile(getpref('BrainStorm','brainstormHomeDir'),'Custom'))
    %
    % Application data and their calls in this file:
    %   'Methods'
    %   'RotateState'
    %   'TileType'
    %   'ZoomState'
    %
    %   setappdata(DATAPLOT,'RotateState',0);
    %   setappdata(DATAPLOT,'RotateState',1);
    %   setappdata(DATAPLOT,'TileType','D');
    %   setappdata(DATAPLOT,'ZoomState',0);
    %   setappdata(DATAPLOT,'ZoomState',1);
    %   setappdata(DataParam,'TileType','Tile')
    %   setappdata(chanwin,'TileType','Tile')
    %   setappdata(data.Measures.Display.Handles.Figures.ContactSheet,'TileType','T')
    %   setappdata(data.Results.Display.Handles.Figures.ContactSheet,'TileType','T')
    %   setappdata(data.Results.Display.Handles.Figures.Surfaces,'TileType','T')
    %   setappdata(data.Results.Display.Handles.Figures.TimeSeries,'TileType','T');
    %   setappdata(fig,'TileType','T')
    %   setappdata(figHandle,'TileType','T')
    %   setappdata(figcopy,'TileType','T')
    %   setappdata(h,'TileType','Tile')
    %   setappdata(handle,'Methods',Methods);
    %
    %   Method = getappdata(hDataplot.SourceViewingTimeDisplay,'Methods');
    %   Methods = getappdata(gcbo,'Methods');
    %   RotateState = getappdata(DATAPLOT,'RotateState');
    %   ZoomState = getappdata(DATAPLOT,'ZoomState');
    %
    % Figure Files opened by this function:
    %   'channel_select.fig'
    %   'dataplot.fig'
    %   'filterGUI.fig'
    %   'lcmvbf.fig'
    %   'listchan.fig'
    %   'set_dataviewing_parameters.fig'
    %   'sourceimaging.fig'
    %   'tessellation_select.fig'
    %   'tessellation_window.fig'
    %
    %   Format of strings below: Type:Style:Tag, "String", CallBack Type and Call
    %   <automatic> callback is <Tag>_Callback by Matlab default
    %
    % Callbacks by figure channel_select.fig
    %   uicontrol:popupmenu:pChannelSets "Channel Sets" uses Callback for dataplot_cb channel_switch
    %   uicontrol:pushbutton:OPushbutton1 "Done" uses Callback for dataplot_cb channel_select_done
    %   uicontrol:pushbutton:pAdd ">" uses Callback for dataplot_cb channel_switch
    %   uicontrol:pushbutton:pRemove "<" uses Callback for dataplot_cb channel_switch
    %   uicontrol:pushbutton:QPushbutton1 "Close" uses Callback for close gcbf
    %
    % Callbacks by figure dataplot.fig
    %   figure::DATAPLOT "" uses DeleteFcn for clear global data
    %   uicontrol:edit:current_time "0" uses Callback for dataplot_cb set_current_time
    %   uicontrol:edit:step "''" uses Callback for dataplot_cb set_time_step
    %   uicontrol:edit:time_max "" uses Callback for dataplot_cb set_time_max
    %   uicontrol:edit:time_min "" uses Callback for dataplot_cb set_time_min
    %   uicontrol:popupmenu:ChangeUnits "MKS" uses Callback for
    %     dataplot_cb('ChangeUnits','reset'),dataplot_cb ChangeUnits
    %   uicontrol:popupmenu:DataViewingDataType "Original Data" uses Callback for
    %     dataplot_cb DataViewingDataType
    %   uicontrol:popupmenu:DataViewingSpatialDisplay "<No Scalp Topography>" uses Callback for
    %     dataplot_cb('DataViewingSpatialDisplay', 'reset'), dataplot_cb DataViewingSpatialDisplay
    %   uicontrol:popupmenu:DataViewingTimeDisplay "<No Time Display>" uses Callback for
    %     dataplot_cb DataViewingTimeDisplay
    %   uicontrol:popupmenu:SourceEstimationMethod "-------- IMAGING " uses Callback for
    %     dataplot_cb SourceImaging
    %   uicontrol:popupmenu:SourceViewingSpatialDisplay "<No Spatial Topography>" uses Callback for
    %     dataplot_cb SourceViewingSpatialDisplay
    %   uicontrol:popupmenu:SourceViewingTimeDisplay "<No Time Display>" uses Callback for
    %     dataplot_cb SourceViewingTimeDisplay
    %   uicontrol:pushbutton:HPlot "Plot" uses Callback for dataplot_cb('Plot','Measures')
    %   uicontrol:pushbutton:HPlotTimeSeries "Plot" uses Callback for sourceimaging('View')
    %   uicontrol:pushbutton:HSetDataViewing "Set-up" uses Callback for dataplot_cb SetDataViewing
    %   uicontrol:pushbutton:HSetSourceViewing "Set-up" uses Callback for dataplot_cb SetSourceViewing
    %   uicontrol:pushbutton:MSIndexSwitch "ms/index" uses Callback for dataplot_cb MSIndexSwitch
    %   uicontrol:pushbutton:NoiseModel "Noise Model" uses Callback for dataplot_cb CallDataSelector
    %   uicontrol:pushbutton:pushbutton35 "Filter" uses Callback for dataplot_cb create_filter_window
    %   uicontrol:pushbutton:pushbutton36 "Average" uses Callback for dataplot_cb GenerateAverage
    %   uicontrol:pushbutton:SourceModel "Source Model" uses Callback for
    %     dummy_dynamic_viewer('pushbutton11_Callback',gcbo,[],guidata(gcbo))
    %   uicontrol:slider:TimeSlider "" uses Callback for dataplot_cb mapping_slider
    %
    % Callbacks by figure filterGUI.fig
    %   uicontrol:checkbox:toggleFilter "Filter is ON" uses Callback for dataplot_cb ToggleFilter
    %   uicontrol:pushbutton:cancel "Cancel" uses Callback for close(gcf)
    %   uicontrol:pushbutton:Hok "Done" uses Callback for dataplot_cb data_filter
    %
    % Callbacks by figure lcmvbf.fig
    %   uicontrol:checkbox:TikhonovRegularization "" uses Callback for
    %     sourceimaging Tikhonov_regularization
    %   uicontrol:edit:cAutomaticParameterSetUp "10" uses Callback for sourceimaging changeLambda
    %   uicontrol:edit:data_start "" uses Callback for sourceimaging data_start
    %   uicontrol:edit:data_stop "" uses Callback for sourceimaging data_stop
    %   uicontrol:edit:noise_start "" uses Callback for sourceimaging noise_start
    %   uicontrol:edit:noise_stop "" uses Callback for sourceimaging noise_stop
    %   uicontrol:pushbutton:Go "Go" uses Callback for sourceimaging Go
    %   uicontrol:pushbutton:Quit "Quit" uses Callback for sourceimaging Quit
    %   uicontrol:radiobutton:cBrainStorm "Filter Output" uses Callback for
    %     sourceimaging output_format_currDensity
    %   uicontrol:radiobutton:noiseNormalization "Neural Index" uses Callback for
    %     sourceimaging output_format_index
    %   uicontrol:radiobutton:normalizedOut "Normalized Output" uses Callback for
    %     sourceimaging output_format_normalizedOut
    %   uicontrol:radiobutton:sourcePower "Source Power" uses Callback for
    %     sourceimaging output_format_sourcePower
    %
    % Callbacks by figure listchan.fig
    %   uicontrol:listbox:available "" uses CreateFcn for movegui center
    %   uicontrol:listbox:removed "" uses CreateFcn for movegui center
    %   uicontrol:pushbutton:Pushbutton1 ">" uses CreateFcn for movegui center
    %   uicontrol:pushbutton:Pushbutton1 ">" uses Callback for dataplot_cb channel_plot_remove
    %   uicontrol:pushbutton:Pushbutton1 "<" uses CreateFcn for movegui center
    %   uicontrol:pushbutton:Pushbutton1 "<" uses Callback for dataplot_cb channel_plot_restore
    %   uicontrol:pushbutton:Pushbutton1 "Cancel" uses CreateFcn for movegui center
    %   uicontrol:pushbutton:Pushbutton1 "Cancel" uses Callback for close gcbf
    %   uicontrol:pushbutton:Pushbutton1 "Apply" uses CreateFcn for movegui center
    %   uicontrol:pushbutton:Pushbutton1 "Apply" uses Callback for dataplot_cb listchan_refresh
    %   uicontrol:pushbutton:pushbutton1 "Select All" uses CreateFcn for movegui center
    %   uicontrol:pushbutton:pushbutton1 "Select All" uses Callback for dataplot_cb listchan_SelectAll
    %   uicontrol:pushbutton:pushbutton2 "Remove All" uses CreateFcn for movegui center
    %   uicontrol:pushbutton:pushbutton2 "Remove All" uses Callback for dataplot_cb listchan_RemoveAll
    %   uicontrol:text:StaticText1 "Available" uses CreateFcn for movegui center
    %   uicontrol:text:StaticText1 "Selected" uses CreateFcn for movegui center
    %   uicontrol:text:text1 "Number of Columns" uses CreateFcn for movegui center
    %
    % Callbacks by figure set_dataviewing_parameters.fig
    %   uicontrol:checkbox:cAbsoluteColormap "Absolute" uses Callback for dataplot_cb AbsoluteColormap
    %   uicontrol:checkbox:cColorbar "Show colorbar" uses Callback for dataplot_cb Colorbar
    %   uicontrol:checkbox:cContours "On" uses Callback for dataplot_cb ShowContours
    %   uicontrol:checkbox:cSensorLabels "Labels" uses Callback for dataplot_cb SensorLabels
    %   uicontrol:checkbox:cSensorMarkers "Markers" uses Callback for dataplot_cb SensorMarkers
    %   uicontrol:edit:ColumnLayout "4" uses Callback for dataplot_cb ChangeColumnLayout
    %   uicontrol:edit:eGainValue "1" uses Callback for dataplot_cb ApplyGain
    %   uicontrol:pushbutton:pushbutton1 "Select" uses Callback for dataplot_cb selectchannels
    %   uicontrol:pushbutton:pushbutton10 "Load" uses Callback for dataplot_cb aviplayer
    %   uicontrol:pushbutton:pushbutton11 "-" uses Callback for dataplot_cb ChangeColumnLayout
    %   uicontrol:pushbutton:pushbutton12 "+" uses Callback for dataplot_cb ChangeColumnLayout
    %   uicontrol:pushbutton:pushbutton13 "Edit" uses Callback for dataplot_cb NewColormap
    %   uicontrol:pushbutton:pushbutton14 "Load" uses Callback for dataplot_cb loadColormap
    %   uicontrol:pushbutton:pushbutton15 "Save" uses Callback for dataplot_cb saveColormap
    %   uicontrol:pushbutton:pushbutton5 "-" uses Callback for dataplot_cb ChangeGain
    %   uicontrol:pushbutton:pushbutton6 "+" uses Callback for dataplot_cb ChangeGain
    %   uicontrol:pushbutton:pushbutton8 "Movie" uses Callback for dataplot_cb GenerateMovie
    %   uicontrol:pushbutton:pushbutton9 "Contact sheet" uses Callback for dataplot_cb GenerateSlides
    %   uicontrol:pushbutton:Qpushbutton7 "Close" uses Callback for close(gcbf)
    %
    % Callbacks by figure sourceimaging.fig
    %   uicontrol:checkbox:cBrainStorm "BrainStorm Format" uses Callback for
    %     sourceimaging mutincomp_kernel
    %   uicontrol:checkbox:cKernel "Kernel only" uses Callback for sourceimaging mutincomp_kernel
    %   uicontrol:checkbox:FFNormalization "" uses Callback for sourceimaging FFNormalization
    %   uicontrol:checkbox:noiseNormalization "" uses Callback for sourceimaging noiseNormalization
    %   uicontrol:checkbox:TikhonovRegularization "" uses Callback for
    %     sourceimaging Tikhonov_regularization
    %   uicontrol:edit:cAutomaticParameterSetUp "10" uses Callback for sourceimaging changeLambda
    %   uicontrol:edit:data_start "" uses Callback for sourceimaging  data_start
    %   uicontrol:edit:data_stop "" uses Callback for sourceimaging data_stop
    %   uicontrol:edit:noise_start "" uses Callback for sourceimaging noise_start
    %   uicontrol:edit:noise_stop "" uses Callback for sourceimaging noise_stop
    %   uicontrol:pushbutton:HGo "Go" uses Callback for sourceimaging Go
    %   uicontrol:pushbutton:Quit "Quit" uses Callback for sourceimaging Quit
    %
    % Callbacks by figure tessellation_select.fig
    %  Unable to open tessellation_select.fig
    %
    % Callbacks by figure tessellation_window.fig
    %   figure::tessellation_window "" uses CreateFcn for movegui northwest
    %
    % At Check-in: $Author: Mosher $  $Revision: 120 $  $Date: 10/12/04 10:23a $
    %
    % This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 12-Oct-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> ------------------------ 12-Oct-2004 12:01:11 -----------------------

    % /---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                     |
    % \------------------------------------------------------/
    %
    % Date of creation: January 1999
    %
    % Script History---------------------------------------------------------------------------------------------------------------------------
    % SB  2001-09     Revamping for compliancy with DataManager + major plastic surgery
    % SB  Oct 2001    Added Cortical Probes, Mapping of Curvature, Colormap Scaling of Activations
    % SB|DS Nov 2001 Multiple fixings; added 0ms adjustment  to data maximum peak (useful for epileptic data analysis about the maximum of the spike)
    % SB  10-May-2002 User.CurrentData.DataFile is now a referential file name
    % SB  28-May-2002 Call STUDY_EDITOR rather than STUDY_EDITOR_CB
    % JCM 28-May-2002 added bst_color_scheme, still needs lots of fixing, Users.Current.Database now
    %                  Users.Comment
    % SB  03-Mar-03   Starting major update. . .
    % JCM 09-Sep-2003 disabling old taskbar routines
    % SB  20-Oct-2003 lots of fixes at USC
    % SB  15-Dec 2003 Added visualisation of surface data on scalp tessellation
    %                 Fixed movie generation (provided uses has codec Indeo5
    %                 installed on computer)
    % JCM 17-Jun-2004 Adding Names to the time series figures
    % DP  28-Sep-2004 Fix a bug not to open many plot figures
    % DP  20-Sep-2004 Update the menu options for imaging methods
    % EK  1-Oct-2004  Visualization of results stored in kernel mode
    % EK  2-Oct-2004  Functionality to LCMV is given
    % EK  7-Oct-2004  Imaging methods that are NOT available are deleted from
    %                 the GUI (dataplot.fig) and code is changed according to the new list
    %                 Old list is available (commented) here for future
    %                 reference.
    % EK  7-Oct-2004  Minor change in result plotting. GUI file changed to call
    %                 sourceimaging('View') instead of dataplot_cb('Plot','RESULTS')
    %                 when PLOT button in Source Viewing section is pressed. Now the
    %                 Data Time Series window is also opened. Consistent with viewing the
    %                 results using an imaging method.
    % -----------------------------------------------------------------------------------------------------------------------------------------

    % SB - 01-Jul-2003 | Declare very-much used variables as global instead of storing things using guidata too much (make windows flicker under Matlab 6.1)
    global DATAPLOT hDataplot data DefaultCheckChar
    % DATAPLOT : handle to Viewer figure
    % hDataPlot : handles to all objects in Viewer GUI
    % data : large structure containing all display data and options
    % DefaultCheckChar : usualyy a '*' to check selected items in pulldown menus

    DefaultCheckChar = '*'; % SB 05-Jun-2003 | default character used for checked items in pulldown lists
    % Labels of modalities for surface measures
    % A cell array indicating to which modality the measures belong to :
    % {'MEG','EEG','OTHER'}.
    % This order is important as modalities are usually referred to by their index in ModalityLabel
    ModalityLabel = {'MEG','EEG','OTHER'};

    %-CALLBACK ACTION SWITCHYARD---------------------------------------------------------------------------------------------------------------

    switch action

    case 'create'

        clear global data

        Users = get_user_directory; % go and fetch information on current database

        % Check for data loaded from DataManager, if exists
        if ~isfield(Users,'CurrentData') % No data was loaded using DataManager - do nothing (old way)
            errordlg('No data file was loaded from DataManager.')
            return
        end

        % Warnings off to suppress the message:
        % Warning: Figure file created with a newer version (7.0.0)  of MATLAB
        warning off, DATAPLOT = openfig('dataplot.fig','reuse');, warning on
        BrainStormWindows = bst_win_manager(DATAPLOT,'DataViewer');
        bst_color_scheme(DATAPLOT);
        setappdata(DATAPLOT,'TileType','D');
        bst_layout('align',DATAPLOT)
        set(DATAPLOT,'Visible','on');

        hDataplot = guihandles(DATAPLOT);
        set([hDataplot.NoiseModelTag,hDataplot.tSourceModelTag],'String','default')

        % Look for datafiles in current study folder
        cd(Users.STUDIES);
        [studypath,file,ext] = fileparts(Users.CurrentData.StudyFile);
        cd(studypath)

        % Define Misc. Viewing parameters ---------------------------------------------------------------------

        % Load selected dataset from bst_static_taskbar
        tmp = bst_static_taskbar('GET','DATA');
        if ~isempty(tmp{1})
            dataplot_cb('loadfile',tmp);
        else
            errordlg('Please select first a data file from pulldown list','No data file selected')
            return
        end
        % Load selected result file from bst_static_taskbar
        tmp = bst_static_taskbar('GET','RESULTS');
        if ~isempty(tmp)
            dataplot_cb('loadfile',tmp);
        end

        if ~isappdata(hDataplot.SourceViewingTimeDisplay,'Methods');
            initialize_SourceTimeViewing(hDataplot.SourceViewingTimeDisplay); % Initialize pull-down menus
        end
        if ~isappdata(hDataplot.SourceViewingSpatialDisplay,'Methods');
            initialize_SourceSpatialViewing(hDataplot.SourceViewingSpatialDisplay); % Initialize pull-down menus
        end

        % CBB: need to do the same with all pulldown in DATAPLOT

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

    case 'FileDisplayType' % Toggle file display type in listbox (scalp data and/or result files)

        dataplot_cb('create') % refresh file list

        %----------------------------------------------------------------------------
    case 'GET' % Retrieve tag information

        TAG = varargin{1};
        switch(lower(TAG))

            % [TimeSet, TimeIndices] = dataplot_cb('GET','TIME')
            % Retrieve information about time window specified in the Viewer
            % TimeSet: [start, step, stop] time instants in seconds
            % TimeIndices: a subset of time indices from orginal data array

        case 'time' % retrieve time start|step|stop and corresponding time indices
            %         data.Display.Time(1) = str2num(get(hDataplot.time_min,'String'))/1000;
            %         data.Display.Time(end) = str2num(get(hDataplot.time_max,'String'))/1000;
            %         data.Display.SamplingRate = str2num(get(hDataplot.step,'String'))/1000;

            varargout{1} = [data.Display.Time(1) data.Display.SamplingRate data.Display.Time(end)];
          varargout{2} = data.Display.TimeSamples;

        case 'current_time' % retrieve current time in seconds

            timeValue = get(hDataplot.TimeSlider,'Value');
            timeVec =  [data.Display.Time(1):data.Display.SamplingRate:data.Display.Time(end)];
            timeValue = findclosest(timeValue,timeVec');
            varargout{1} = timeVec(timeValue);

        end

        %----------------------------------------------------------------------------
    case 'SET' % Set tag information

        TAG = varargin{1};
        switch(lower(TAG))

            % [TimeSet, TimeIndices] = dataplot_cb('GET','TIME')
            % Retrieve information about time window specified in the Viewer
            % TimeSet: [start, step, stop] time instants in seconds
            % TimeIndices: a subset of time indices from orginal data array

        case 'time' % set current time

            set(hDataplot.current_time,'string',num2str(1000*varargin{2},'%3.2f'));
            % update display
            dataplot_cb('set_current_time')

        end
        %----------------------------------------------------------------------------

    case 'loadfile' % Load either a data ro a result file

        makeuswait('start')

        Users = get_user_directory;
        datatype = 'mat'; % Assume we're loading only a BST matlab file with proper extension

        % Read Study File %
        cd(Users.STUDIES);

        if (0) % Deprecated code nargin == 1 % Manual load
            [studyfile,StudyPath] = uigetfile(['*brainstormstudy.',datatype], 'Enter file name for the study file');
            if (studyfile)==0, return, end
            cd(studypath)

            [datafile,datapath] = uigetfile(['*data*.',datatype], 'Enter file name for data set');
            if (datafile)==0, return, end
            disp('Loading data...')
            cd(datapath)

            [path,file,ext] = fileparts(studyfile);

            load(studyfile);
            if ~isempty(path)
                cd(path)
            end

        elseif nargin  == 2 % Data and Study files are specified as arguments

            datafile = varargin{1}{1};
            %fname =  varargin{1};

        end

        % Determine whether it is a surface data file or a result file
    %     if ~exist(datafile)
    %                 bst_message_window('wrap',...
    %             sprintf('Can''t find the datfile called %s . . .',datafile))
    %         data.Results.Filename = {[]};
    %         return
    %     end
        File_whos = whos('-file',fullfile(Users.STUDIES,datafile));
        if(strmatch('Fsynth',{File_whos.name})) % result file
            DataFlag = 0; % Just a flag: we're loading a result file
        elseif (strmatch('F',{File_whos.name})) % data file
            DataFlag = 1; % Just a flag: we're loading a data file
            % Check for time and data array size integrity
            if File_whos(strmatch('F',{File_whos.name})).size(2) ~= File_whos(strmatch('Time',{File_whos.name})).size(2)
                errordlg(sprintf(...
                    'Time and Data arrays have incompatible sizes in file %s.',datafile),...
                    'Cannot load this file : file is corrupted')
                makeuswait('stop')
                return
            end
        else
            errordlg('File does not follow BrainStorm file format.','Wrong file format')
            return
        end

        % Fill out all data or result parameters necessary  for subsequent viewing
        if DataFlag % MEG/EEG surface data file

            % Update display of type of data to plot
            dataplot_cb('DataViewingDataType','reset')
            set(hDataplot.DataViewingDataType,'enable','off','value',1)

            bst_message_window('wrap',...
                sprintf('Loading data file %s . . .',datafile))

            data.Measures = load(datafile,'Time','ChannelFlag'); % Load time samples (in seconds)
            data.Measures.Filename = {datafile};

            % Fill out basic entries with information about measures
            % -> Time Information
            data.Measures.SamplingRate = data.Measures.Time(2) - data.Measures.Time(1);
            data.Measures.NumberOfSamples = length(data.Measures.Time);
            data.Measures.Time = [data.Measures.Time(1), data.Measures.Time(end)];

            % Default time window for visualization if original data time window
            data.Display.Time = data.Measures.Time;
            data.Display.TimeSamples = [1:data.Measures.NumberOfSamples];
            data.Display.SamplingRate = data.Measures.SamplingRate;
            data.Display.NumberOfSamples = data.Measures.NumberOfSamples;

            % A set of strings for display of basic time information in GUI
            data.Measures.DataInfoString = {...
                    'Maximum time span',...
                    sprintf('From: %3.1f ms', 1000*data.Measures.Time(1)),...
                    sprintf('To: %3.1f ms', 1000*data.Measures.Time(end)),...
                    sprintf('%d samples',data.Measures.NumberOfSamples),...
                    sprintf('Sampling rate: %d Hz (%3.1f ms)',round(1/data.Measures.SamplingRate),data.Measures.SamplingRate*1000)...
                };

            % -> Time Information <- DONE

            % -> Channel Information
            % Fetch information about current study
            StudySubject = find_brainstorm_structure(Users.CurrentData.StudyFile);

            try
                Channel = load_brainstorm_file(StudySubject.Channel);
                data.Measures.Channel = Channel.Channel; clear Channel
            catch
                errordlg(...
                    sprintf('Please make sure that channel file is present and has proper name: %s',StudySubject.Channel),...
                    'Channel file not found'...
                    )
            end

            % Available channels in data file
            data.Measures.Display.SelectedChannels{1} = good_channel(data.Measures.Channel,data.Measures.ChannelFlag,'MEG');
            data.Measures.Display.SelectedChannels{2} = good_channel(data.Measures.Channel,data.Measures.ChannelFlag,'EEG');
            data.Measures.Display.SelectedChannels{3} = good_channel(data.Measures.Channel,data.Measures.ChannelFlag,'Other');

            % What does the user want to look at MEG? EEG? Both ? etc.
            % Get this information from checkboxes in Static Taskbar
            [val,enable,hMEG] = bst_static_taskbar('GET','MEG');
            [val,enable,hEEG] = bst_static_taskbar('GET','EEG');
            [val,enable,hOTHER] = bst_static_taskbar('GET','OTHER');

            % Check whether user's choice is compatible with available channels
            if isempty(data.Measures.Display.SelectedChannels{1})
                set(hMEG,'enable','off')
            else
                set(hMEG,'enable','on')
            end
            if isempty(data.Measures.Display.SelectedChannels{2})
                set(hEEG,'enable','off')
            else
                if ~isempty(data.Measures.Display.SelectedChannels{1})
                    set(hEEG,'enable','on') % Select MEG only by default
                else
                    set(hEEG,'enable','on')
                end
            end
            if isempty(data.Measures.Display.SelectedChannels{3})
                set(hOTHER,'enable','off')
            else
                set(hOTHER,'enable','on')
            end

            % Is any already checked ?
            chck = get_selected_modalities;
            if isempty(chck) % None selected, select first available by default
                tmpHandles = [hMEG,hEEG,hOTHER];
                enbl = get(tmpHandles,'enable');
                tmp = find(strcmp(enbl,'on'));
                set(tmpHandles(tmp(1)),'value',1)
            end

            % -> Channel Infomation <- DONE

            bst_message_window({'Loading data file -> DONE',' '})

        elseif DataFlag == 0 % Load a result file generated by some source analysis

            bst_message_window('wrap',...
                sprintf('Loading result file %s . . .',datafile))

            set(hDataplot.DataViewingDataType,'enable','on','value',1)
            dataplot_cb('DataViewingDataType','set',1,1); % Default visualization is Original Data

            % Results file name
            data.Results.Filename = {datafile};

            % -> Make time ranges of Measures and Results match for display purposes
            % Load original Time range of which source analysis was computed
            % This time range superseeds the original Measures time range for display
            tmpTimeSamples = load(datafile,'Time'); % load vector of subset sample indices from original data time range
            tmpTimeSamples = tmpTimeSamples.Time;
            origTime = linspace(data.Measures.Time(1),data.Measures.Time(end),data.Measures.NumberOfSamples);
            data.Results.Time = [origTime(tmpTimeSamples(1)),origTime(tmpTimeSamples(end))];
            data.Display.Time = data.Results.Time;
            data.Display.SamplingRate = origTime(tmpTimeSamples(2)) - origTime(tmpTimeSamples(1));
            data.Display.NumberOfSamples = length(tmpTimeSamples);
            clear tmpTimeSamples origTime

            % Apply Results time range to entire display, including Measures data
            set(hDataplot.time_min,'String',sprintf('%3.2f',1000*data.Display.Time(1)));
            set(hDataplot.time_max,'String',sprintf('%3.2f',1000*data.Display.Time(end)));
            set(hDataplot.step,'String',sprintf('%3.2f',1000*data.Display.SamplingRate));
            set(hDataplot.current_time,'String',data.Display.Time(1)*1000);

            % -> Make time ranges of Measures and Results match for display purposes <- DONE
            dataplot_cb('set_time_max')

            bst_message_window({'Loading result file -> DONE',' '})

        end

        % Update GUI objects in Viewer accordingly
        set(hDataplot.time_min,'String',sprintf('%3.2f',1000*data.Display.Time(1)));
        set(hDataplot.time_max,'String',sprintf('%3.2f',1000*data.Display.Time(end)));
        set(hDataplot.step,'String',sprintf('%3.2f',1000*data.Display.SamplingRate));
        set(hDataplot.TimeSlider,'Min',data.Display.Time(1),'Max',data.Display.Time(end),...
            'SliderStep',[data.Display.SamplingRate/(data.Display.Time(end)-data.Display.Time(1)),.1],'Value',data.Display.Time(1))
        set(hDataplot.current_time,'String',data.Display.Time(1)*1000);
        set(hDataplot.nTimeSamples,'String',sprintf('%d samples',data.Display.NumberOfSamples));

        makeuswait('stop')

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

    case 'LoadFromDataFileList' % Load from popup menu list in the DataViewer

        %     BrainStormWindows = bst_win_manager;
        %     DATAPLOT = BrainStormWindows.DataViewer;
        % % hDataplot = guihandles(DATAPLOT);

        iFile = get(hDataplot.DataFileList,'Value');
        FileNames = get(hDataplot.DataFileList,'String');

        dataplot_cb('loadfile',FileNames{iFile});

        %----------------------------------------------------------------------------
    case 'LoadPrevFile' % Load previous file in the popup menu list in the DataViewer

        % % hDataplot = guihandles(DATAPLOT);
        iFile = get(hDataplot.DataFileList,'Value');
        FileNames = get(hDataplot.DataFileList,'String');

        iFile = iFile - 1;
        if iFile < 1
            iFile = 1;
            return
        end

        set(hDataplot.DataFileList,'Value',iFile)
        CurrentData = getpref('BrainStorm','CurrentData');
        CurrentData.DataFile = fullfile(...
            fileparts(CurrentData.StudyFile),...
            FileNames{iFile});
        setpref('BrainStorm','UserCurrentData',CurrentData);

        dataplot_cb('loadfile',FileNames{iFile});

        %----------------------------------------------------------------------------
    case 'LoadNextFile' % Load previous file in the popup menu list in the DataViewer

        % % hDataplot = guihandles(DATAPLOT);
        iFile = get(hDataplot.DataFileList,'Value');
        FileNames = get(hDataplot.DataFileList,'String');

        iFile = iFile + 1;
        if iFile > length(FileNames)
            iFile = length(FileNames);
            return
        end

        set(hDataplot.DataFileList,'Value',iFile)

        CurrentData = getpref('BrainStorm','CurrentData');
        CurrentData.DataFile = fullfile(...
            fileparts(CurrentData.StudyFile),...
            FileNames{iFile});
        setpref('BrainStorm','UserCurrentData',CurrentData);

        dataplot_cb('loadfile',FileNames{iFile});

        %  dataplot_cb quicklook
        %----------------------------------------------------------------------------

    case 'SourceImaging' % Launch source imaging routines on seleceted data

        Val = get(hDataplot.SourceEstimationMethod,'Val'); % what is the popup set to
        %       OLD LIST
        %     -------- IMAGING
        %     Min. Norm Imaging (LMMS)
        %     (Recursive LMMS)
        %     ST-MAP
        %     Recursice Tiling
        %     LCMV
        %     Cortical MUSIC
        %
        %     -------- SCANNING
        %     LCMV
        %     RAP-MUSIC
        %     R-MUSIC
        %     SPTF
        %     --------

        %       NEW LIST
    %     -------- IMAGING
    %     Min. Norm Imaging (LMMS)
    %     Cortical LCMV Beamformer
    %     Cortical MUSIC
    %
    %     -------- SCANNING
    %     RAP-MUSIC
    %     --------

    %       CODE FOR OLD LIST
    %  --------------------------------------------
    %     switch Val
    %         case {1, 8, 9, 14}
    %             % do nothing, comment lines in the popup
    %             set(hDataplot.SourceEstimationMethod,'Val',1); % reset back to teaser
    %
    %         case {2} % min norm imaging
    %             % JCM 09-Sep-2003 moving taskbar function to here
    %             set(DATAPLOT,'Pointer','watch')
    %            set(hDataplot.SourceEstimationMethod,'Val',1); % reset back to teaser
    %             SrcImagingGUI = openfig('sourceimaging.fig','reuse');
    %             sourceimaging('create', SrcImagingGUI)
    %             set(DATAPLOT,'Pointer','arrow')
    %
    %         case {3}%Recursive LMMS
    %             bst_message_window(sprintf('Recursive LMMS not implemented yet'));
    %             set(hDataplot.SourceEstimationMethod,'Val',1); % reset back to teaser
    %
    %         case {4}%ST MAP
    %             bst_message_window(sprintf('ST MAP not implemented yet'));
    %             set(hDataplot.SourceEstimationMethod,'Val',1); % reset back to teaser
    %
    %         case {5}%recursive tiling
    %             bst_message_window(sprintf('Recursive tiling not implemented yet'));
    %             set(hDataplot.SourceEstimationMethod,'Val',1); % reset back to teaser
    %
    %         case{6}%Cortical LCMV Beamformer
    %             % EK 2-Oct-2004 Functionality to LCMV is given
    %        set(DATAPLOT,'Pointer','watch')
    %                    set(hDataplot.SourceEstimationMethod,'Val',1); % reset back to teaser
    %         SrcImagingGUI = openfig('lcmvbf.fig','reuse');
    %         sourceimaging('create', SrcImagingGUI)
    %         set(DATAPLOT,'Pointer','arrow')
    %
    %     case{7}%Cortical MUSIC
    %         bst_message_window(sprintf('Cortical MUSIC not implemented yet'));
    %         set(hDataplot.SourceEstimationMethod,'Val',1); % reset back to teaser
    %
    %     case 11 % RAP-MUSIC
    %
    %         if ~isfield(data.Measures,'F') % call data display
    %             tmp = bst_static_taskbar('GET','DATA');
    %             if ~isempty(tmp{1})
    %                 Users = get_user_directory;
    %                 dataplot_cb('loadfile',tmp); %Users.CurrentData.StudyFile
    %             end
    %             dataplot_cb('Plot','measures');
    %         end
    %
    %         if ~isfield(data.Measures,'NoiseModelParam') % Noise parameters were not defined - call data selector
    %             dataplot_cb('CallDataSelector')
    %             waitfor(findobj(0,'Name','Parametric Estimation Data Selector'))
    %         end
    %         hf = rap_music_parameters; % setup
    %         rap_music_parameters('load_parameters',hf,data.Measures.NoiseModelParam.StudySubject,data.Measures.NoiseModelParam);
    %
    %     case 13 % Least-squares
    %         % get the GUI parameters
    %         GUI = start_gui_structure(h,eventdata,handles,varargin);
    %         StudySubject = getappdata(fig,'StudySubject');
    %         hf = least_squares_parameters_cb; % setup
    %
    %         least_squares_parameters_cb(StudySubject,GUI,hf); %set up the popup
    %
    %     otherwise
    %         bst_message_window(sprintf('Unknown source estimation method'));
    %         set(hDataplot.SourceEstimationMethod,'Val',1); % reset back to teaser
    %     end
    %
    %     %----------------------------------------------------------------------------

    switch Val
        case {1, 5, 6, 8}
            % do nothing, comment lines in the popup
            set(hDataplot.SourceEstimationMethod,'Val',1); % reset back to teaser

        case {2} % min norm imaging
            % JCM 09-Sep-2003 moving taskbar function to here
            set(DATAPLOT,'Pointer','watch')
            set(hDataplot.SourceEstimationMethod,'Val',1); % reset back to teaser
            warning off, SrcImagingGUI = openfig('sourceimaging.fig','reuse');warning on
            sourceimaging('create', SrcImagingGUI)
            set(DATAPLOT,'Pointer','arrow')

        case{3}%Cortical LCMV Beamformer
            % EK 2-Oct-2004 Functionality to LCMV is given
            set(DATAPLOT,'Pointer','watch')
            set(hDataplot.SourceEstimationMethod,'Val',1); % reset back to teaser
            warning off, SrcImagingGUI = openfig('lcmvbf.fig','reuse');, warning on
            sourceimaging('create', SrcImagingGUI)
            set(DATAPLOT,'Pointer','arrow')

        case{4}%Cortical MUSIC
            bst_message_window(sprintf('Cortical MUSIC not implemented yet'));
            set(hDataplot.SourceEstimationMethod,'Val',1); % reset back to teaser

        case 7 % RAP-MUSIC

            set(hDataplot.SourceEstimationMethod,'Val',1); % reset back to teaser
            if ~isfield(data.Measures,'F') % call data display
                tmp = bst_static_taskbar('GET','DATA');
                if ~isempty(tmp{1})
                    Users = get_user_directory;
                    dataplot_cb('loadfile',tmp); %Users.CurrentData.StudyFile
                end
                dataplot_cb('Plot','measures');
            end

            if ~isfield(data.Measures,'NoiseModelParam') % Noise parameters were not defined - call data selector
                dataplot_cb('CallDataSelector')
                waitfor(findobj(0,'Name','Parametric Estimation Data Selector'))
            end
            hf = rap_music_parameters; % setup
            rap_music_parameters('load_parameters',hf,data.Measures.NoiseModelParam.StudySubject,data.Measures.NoiseModelParam);

        otherwise
            bst_message_window(sprintf('Unknown source estimation method'));
            set(hDataplot.SourceEstimationMethod,'Val',1); % reset back to teaser
    end

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

        case 'SelectChannelType' % Select MEG, EEG or Other Channels for display
            % hDataplot = guihandles(DATAPLOT);
            %data = guidata(DATAPLOT);

        if get(gcbo,'Value')
            flag = 1; % add channels to display
        else
            flag = 0; % remove channels from display
        end

        mod = strmatch(upper(get(gcbo,'Tag')),data.Label); % Which modalities were selected ?

        if flag
            data.Measures.Display.SelectedChannels{mod} = good_channel(data.Measures.Channel,[],data.Label{mod});
        else
            data.Measures.Display.SelectedChannels{mod} = [];
        end

        %----------------------------------------------------------------------------
    case 'ChangeColumnLayout' % Changle the number of column of disply layout
        handles = guihandles(gcbf);
        ViewParam = openfig('set_dataviewing_parameters.fig','reuse');
        hViewParam = guihandles(ViewParam);

        data.Measures.Display.DisplayTypes(2) = str2num(get(handles.ColumnLayout,'String'));

        switch(upper(get(gcbo,'String')))
        case '+'
            data.Measures.Display.DisplayTypes(2) = data.Measures.Display.DisplayTypes(2) + 1;
        case '-'
            data.Measures.Display.DisplayTypes(2) = max([data.Measures.Display.DisplayTypes(2)-1,1]);
        end

        set(hViewParam.ColumnLayout,'String',data.Measures.Display.DisplayTypes(2))

        %----------------------------------------------------------------------------
    case 'ChangeUnits' % Change display units of current waveforms

        switch(get(gcbo,'Value'))
        case 1
            %  Original time series units
        case 2
            % Move to Zscore time series
            zscore_gui('create')
        otherwise
            return % not implemented yet
        end

        %----------------------------------------------------------------------------
    case {'ChangeGain','ApplyGain'} % Change display gain of data

        % % hDataplot = guihandles(DATAPLOT);
        %%data = guidata(DATAPLOT);
        %Label = {'MEG','EEG','OTHER'};
        ViewParam = openfig('set_dataviewing_parameters.fig','reuse');
        hViewParam = guihandles(ViewParam);
        strr = get(hViewParam.GainDataType,'String');
        % Which modality was selected from pulldown?
        mod = get(hViewParam.GainDataType,'Value');

        switch(action)
        case 'ChangeGain'
            if ~isempty(findstr('+',get(gcbo,'String')))
                gain = 1.2; % increase display gain
            else
                gain = 0.8;
            end

            set(hViewParam.eGainValue,'String',num2str(gain))

        case 'ApplyGain'

            gain = str2num(get(hViewParam.eGainValue,'String'));

        end

        if data.Measures.Display.DisplayTypes(1) & mod <= length(data.Measures.Display.Handles.PlotOverlay)
            lineHandles = [data.Measures.Display.Handles.PlotOverlay(mod).lines{:}];
            lineHandles = lineHandles(:);
            ydata = get(lineHandles,'ydata');
            if isempty(ydata), return, end
            ytick = get(get(data.Measures.Display.Handles.PlotOverlay(mod).lines{1}(1),'Parent'),'Ytick');
            if length(ytick)>1
                ytick = ytick(mod);
            end
            ydata = reshape([ydata{:}],length(ydata{1}),length(ydata))';
            ydata = (ydata-ytick)* gain + ytick;
            for k=1:size(ydata,1)
                %set(data.Measures.Display.Handles.PlotOverlay(mod).lines(k),'ydata',ydata(k,:));
                set(lineHandles(k),'ydata',ydata(k,:));
            end
            if mod == 1 % MEG
                sstring = 'fT'; factor = 1e-15;
            elseif mod == 2 % EEG
                sstring  = 'uV'; factor = 1e-6;
            else
                sstring = 'a.u.'; factor = 1;
            end

            set(data.Measures.Display.Handles.PlotOverlay(mod).YScale.Label,'String',...
                sprintf('%3.1f %s',str2num(strrep(get(data.Measures.Display.Handles.PlotOverlay(mod).YScale.Label,'string'),sstring,''))/gain,sstring))
        end

        if data.Measures.Display.DisplayTypes(2) > 0
            colLines = [data.Measures.Display.Handles.PlotColumn(mod).lines{:}];
            ydata = get(colLines,'ydata');
            if isempty(ydata), return, end

            ydata = reshape([ydata{:}],length(ydata{1}),length(ydata))';
            ydata = ydata* gain + (1-gain)*data.Measures.Display.Handles.PlotColumn(mod).ytick'*ones(1,size(ydata,2));
            for k=1:size(ydata,1)
                set(colLines(k),'ydata',ydata(k,:));
            end
        end

        %----------------------------------------------------------------------------
    case {'ShowContours','SensorMarkers','SensorLabels','Colorbar','AbsoluteColormap'} % Update parameters for spatial display

        ViewParam = openfig('set_dataviewing_parameters.fig','reuse');
        hViewParam = guihandles(ViewParam);

        switch(action)
        case 'ShowContours'
            data.Measures.Display.Flags.ShowContours = get(hViewParam.cContours,'Value');
        case 'SensorMarkers'
            data.Measures.Display.Flags.SensorMarkers = get(hViewParam.cSensorMarkers,'Value');
        case 'SensorLabels'
            data.Measures.Display.Flags.SensorLabels = get(hViewParam.cSensorLabels,'Value');
        case 'AbsoluteColormap'
            data.Measures.Display.Flags.AbsoluteColormap = get(hViewParam.cAbsoluteColormap,'Value');
        case 'Colorbar'
            data.Measures.Display.Flags.Colorbar = get(hViewParam.cColorbar,'Value');
            if isfield(data,'Results')
                data.Results.Display.Flags.Colorbar = data.Measures.Display.Flags.Colorbar;
            end
        end

        % Update display
        set(gcbf,'pointer','watch')
        dataplot_cb('mapping_slider')
        set(gcbf,'pointer','arrow')
        %----------------------------------------------------------------------------
    case{'SourceViewingTimeDisplay'}

        Method = getappdata(hDataplot.SourceViewingTimeDisplay,'Methods');
        item = get(hDataplot.SourceViewingTimeDisplay,'Value');

        eval(Method(item).callback)

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

    case {'DataViewingDataType','set_SourceViewingTimeDisplay','DataViewingTimeDisplay','DataViewingSpatialDisplay','SourceViewingSpatialDisplay'} % Original / Modeled / Residual data and type of time series visualization

       switch(action)
        case 'DataViewingDataType'
            objtHandle = hDataplot.DataViewingDataType;
            flag = 1;
            reset = 0;
        case 'DataViewingTimeDisplay'
            objtHandle = hDataplot.DataViewingTimeDisplay;
            flag = 0;
            reset = 0;
        case 'set_SourceViewingTimeDisplay'
            objtHandle = hDataplot.SourceViewingTimeDisplay;
            flag = 0;
            reset = 0;
        case 'DataViewingSpatialDisplay'
            objtHandle = hDataplot.DataViewingSpatialDisplay;
            flag = 0;
            reset = 1;
        case 'SourceViewingSpatialDisplay'
            objtHandle = hDataplot.SourceViewingSpatialDisplay;
            flag = 0;
            reset = 1;
        otherwise
            error('Not a valid call.')
        end

        %if nargin == 1 % Reset selected items to 'unselected'
        if reset == 1 & nargin == 1
          dataplot_cb(action,'reset')
        end

        DataViewingTimeDisplay = get(objtHandle,'String'); % Available data types
        DisplayType = get(objtHandle,'Value');

        if nargin == 2
            if strmatch(lower(varargin{1}),'reset') % reset all items in pulldown menu
                for k = 1:length(DataViewingTimeDisplay)
                    DataViewingTimeDisplay{k} = strrep(DataViewingTimeDisplay{k},DefaultCheckChar,'');
                end
                set(objtHandle,'String',DataViewingTimeDisplay);
                return
            elseif strmatch(lower(varargin{1}),'get') % get values of checked items in pulldown menu
                items = zeros(length(DataViewingTimeDisplay),1);
                for k = 1:length(DataViewingTimeDisplay)
                    if ~isempty(findstr(DataViewingTimeDisplay{k},DefaultCheckChar))
                        items(k) = 1;
                    end
                end
                varargout{1} = items;
            end
        elseif nargin == 3 & strmatch(lower(varargin{1}),'set') % Set specified menu item
            nitem = varargin{2}; % item menu location
            value = varargin{3}; % 1 is check - 0 is uncheck
            DataViewingTimeDisplay{k} = strrep(DataViewingTimeDisplay{k},DefaultCheckChar,'');
            if value
                DataViewingTimeDisplay{DisplayType} = sprintf('%s%s',DataViewingTimeDisplay{DisplayType},DefaultCheckChar);
            end
            set(objtHandle,'String',DataViewingTimeDisplay);
            return
        end

        getFlag = 0; % Flag | see below
        if nargin == 2 % User request special function
            if strcmp(lower(varargin{1}),'get') % Get display properties without altering them
                getFlag = 1;
            end
        end

        if ~isempty(findstr(DataViewingTimeDisplay{DisplayType},DefaultCheckChar))% Unselect current display type
            if ~getFlag
                DataViewingTimeDisplay{DisplayType} = strrep(DataViewingTimeDisplay{DisplayType},DefaultCheckChar,'');
            end
        else
            if ~getFlag
                DataViewingTimeDisplay{DisplayType} = sprintf('%s%s',DataViewingTimeDisplay{DisplayType},DefaultCheckChar);
                if flag == 0 & DisplayType == 1
                    for k = 1:length(DataViewingTimeDisplay)
                        DataViewingTimeDisplay{k} = strrep(DataViewingTimeDisplay{k},DefaultCheckChar,'');
                    end
                end
            end
        end

        set(objtHandle,'String',DataViewingTimeDisplay);

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

    case 'Plot' % Look at Measures and/or Results in all possible ways

        makeuswait('start')

        if nargin == 1
            varargin{1}= 'measures'; % see surface data by default
        end

        % Zoom status of the window was previously stored as an application data
        if isappdata(DATAPLOT,'ZoomState')
            rmappdata(DATAPLOT,'ZoomState')   % Reset - zoom is turned off
        end

        % Create/Find display figure depending on type of display; i.e. data or results

        if strcmp(lower(varargin{1}),'measures') % Display surface measures (i.e. MEG, EEG, OTHER)

            DataFlag = 1; % Just a flag meaning we're looking at measures, not results.

            % Clean up previous figures
            if isfield(data.Measures.Display,'Handles')
                HandlesNames = fieldnames(data.Measures.Display.Handles);
                for k = 1:length(HandlesNames)
                    if ishandle(getfield(data.Measures.Display.Handles,HandlesNames{k}))
                        delete(getfield(data.Measures.Display.Handles,HandlesNames{k})) % Delete all previous figures
                    end
                end
                data.Measures.Display = rmfield(data.Measures.Display,'Handles');
            end

            % Create new figure
            %         figHandle = openfig('timeseries.fig','reuse'); % Handle to time series window
            %         set(0,'CurrentFigure',figHandle)
            %         clf
            %         set(figHandle,'MenuBar','figure')
            %         set(figHandle,'Visible','on')
            figHandle = findobj(0,'type', 'figure', 'tag','DataTimeSeries');
            if isempty(figHandle)
                figHandle = figure;
                set(figHandle,'Visible','off','tag','DataTimeSeries','Name',sprintf('Data Time Series Figure %.0f',figHandle));
                setappdata(figHandle,'TileType','T')
                bst_color_scheme(figHandle);
                set(figHandle,'menubar','figure');
                bst_layout('align',figHandle,2,1,1);
                set(figHandle,'Visible','on')
            end

            BrainStormWindows = bst_win_manager(figHandle,'DataTimeSeries');
            data.Measures.Display.Handles.Figures.TimeSeries = figHandle;
            clear figHandle

            % -> Fill out display parameters
            % What kind of displays are requested ?
            whichDisplay = dataplot_cb('DataViewingTimeDisplay','get'); % None | Overlay | Column ?
            data.Measures.Display.DisplayTypes(1) = whichDisplay(2); % Overlay
            if whichDisplay(3) == 0 % no Column
                data.Measures.Display.DisplayTypes(2) = 0;
            else % Column layout required
                if data.Measures.Display.DisplayTypes(2) > 1 % previous choice of number of columns somewhere
                    % use data.Measures.Display.DisplayTypes(2) ;
                else
                    data.Measures.Display.DisplayTypes(2) = 1;
                end
            end

            data.Measures.Display.DisplayTypes(3) = max([0,find(dataplot_cb('DataViewingSpatialDisplay','get'))]); % Spatial display

            % Now find what kind of datatype to display (Original | Modeled | Residuals)
            data.Measures.Display.TimeSeriesTypes = dataplot_cb('DataViewingDataType','get');
            %data.Display =  DisplayStruct;
            % -> Fill out display parameters <- DONE

            figHandle = data.Measures.Display.Handles.Figures.TimeSeries;
            figure(figHandle)
            %set(figHandle,'Pointer','watch')
            delete(findobj(figHandle,'type','axes'))
            set(figHandle,'Visible','on')

            %         % Remove all previous handles from Display substructure
            %         if isfield(data.Measures.Display,'Handles')
            %             data.Measures.Display = rmfield(data.Measures.Display,'Handles');
            %         end

            % -> Which modalities need to be displayed ?
            data.Measures.Display.Modality = get_selected_modalities;
            if isempty(data.Measures.Display.Modality)
                bst_message_window('wrap',...
                    {' ',...
                        'Please select either ''MEG'', ''EEG'' or ''Other'' for display in taskbar',...
                        ' '});

                errordlg(...
                    'Please select either ''MEG'', ''EEG'' or ''Other'' for display in Taskbar','No modality selected')
                return
            end
            % -> Which modalities need to be displayed ? <- DONE

            DisplayStruct = data.Measures.Display; %temporary structure to use shorter names in the following

            % -> Get data filename to create labels on displays
            fname = shorter_filename(data.Measures.Filename);
            % -> Get data filename to create labels on displays <- DONE

            % -> Fill out parameters before call to specific display subfunction
            DefaultLabels = {'MEG','EEG','OTHER'}; % Default modality labels
            OPTIONS = DisplayStruct;
            if isfield(OPTIONS,'Flags') % User has already altered viewing preferences
                flagNames = fieldnames(OPTIONS.Flags);
                for k = 1:length(flagNames)
                    OPTIONS = setfield(OPTIONS,flagNames{k},getfield(OPTIONS.Flags,flagNames{k}));
                end
            end

            OPTIONS.Modality = DisplayStruct.Modality;
            OPTIONS.ModalityLabel = DefaultLabels(DisplayStruct.Modality); clear DefaultLabels
            OPTIONS.SelectedChannels(OPTIONS.Modality) = data.Measures.Display.SelectedChannels(DisplayStruct.Modality);
            OPTIONS.Channel = data.Measures.Channel;
            tmpTime = linspace(data.Measures.Time(1),data.Measures.Time(end),data.Measures.NumberOfSamples); % Rebuild original time vector

            data.Display.NumberOfSamples = data.Measures.NumberOfSamples;
            data.Display.Time = data.Measures.Time;
            data.Display.SamplingRate = tmpTime(2)-tmpTime(1);

            % extract Display time samples in ms
            OPTIONS.Time = tmpTime(data.Display.TimeSamples); clear tmpTime
            OPTIONS.CurrentTime = dataplot_cb('GET','current_time');
            if 0,%isfield(data.Measures,'Fmax')
                OPTIONS.Fmax(:,OPTIONS.Modality) = data.Measures.Fmax;
            end

            %OPTIONS.DisplayTypes = data.Measures.Display.DisplayTypes;
            % <- DONE

            % Now specify data to display in specific cell arrays
            % -> Check if user wants to see modeled data or residuals when no results a re available yet
            if sum(data.Measures.Display.TimeSeriesTypes) > 1 & ~isfield(data,'Results')
                errordlg('Please selected a Results file from list in taskbar')
                return
            end
            % <- DONE

            % Fill out arrays containing Original | Modeled | Residuals
            % Make sure at least one of the above was selected
            if isempty(find(DisplayStruct.TimeSeriesTypes))
                % If not, selected Original timeseries by default
                DisplayStruct.TimeSeriesTypes(1) = 1;
                % Update pulldown menu by adding a 'checked' character
                dataplot_cb('DataViewingDataType','set',1,1)
            end

            % Initialize diplay variables
            OPTIONS.WaveLabel = cell(1);
            % Fill out these cell arrays
            if DisplayStruct.TimeSeriesTypes(1) == 1 % User wants to see Original data
                if (1)%~isfield(data.Measures,'F') % Data were not loaded yet
                    % Load them by calling subfunction that also checks for possible subsampling
                    tmp2 = dataplot_cb('set_time_min'); clear tmp2 % CHEAT - Need argout otherwise plot is re-drawn
                end
                OPTIONS.WaveLabel = fname;
            end

            % If results are available, and if user needs it, load Modeled data and Residuals
            if isfield(data,'Results') & ...
                    sum(data.Measures.Display.TimeSeriesTypes(2:3))>0
                % Load synthetized data
               Users = get_user_directory;
               cd(Users.STUDIES)
               Fsynth = load(data.Results.Filename{1},'Fsynth');
               data.Results.Fsynth = Fsynth.Fsynth; clear Fsynth

               % Is it MEG, EEG ?
                Label = {'MEG','EEG','OTHER'};
                DataFlag = load(data.Results.Filename{1},'OPTIONS'); %was DataFlag - CBB still is for RAP results file - see below
                if isempty(fieldnames(DataFlag)) % CBB - we're loading a rap results file
                    load(data.Results.Filename{1},'DataFlag');
                    DataFlag.OPTIONS.DataType = find(ismember(Label,DataFlag));
                end

                data.Results.DataFlag = Label{DataFlag.OPTIONS.DataType}; clear DataFlag
                if data.Measures.Display.TimeSeriesTypes(2) % User wants to see Modeled data
                    data.Measures.F{end+1} = zeros(length(data.Measures.Channel),length(data.Display.TimeSamples));
                    data.Measures.F{end}(good_channel(data.Measures.Channel,data.Measures.ChannelFlag,data.Results.DataFlag),:) = ...
                        data.Results.Fsynth; % CBB need to update plotselectedchannels accordingly
                    OPTIONS.WaveLabel{end+1} = ...
                        sprintf('Modeled Data; GOF = %3.1f%%',...
                        100*(1-mean(norcol(data.Measures.F{1}(good_channel(data.Measures.Channel,...
                        data.Measures.ChannelFlag,...
                        data.Results.DataFlag),:)...
                        - data.Results.Fsynth))/...
                        mean(norcol(data.Measures.F{1}(good_channel(data.Measures.Channel,data.Measures.ChannelFlag,data.Results.DataFlag),:))))); clear gof
                end

                [tmp,TimePlot] = dataplot_cb('GET','time'); % Get time samples
                clear tmp
                if data.Measures.Display.TimeSeriesTypes(3) == 1 % User wants to see residuals
                    data.Measures.F{end+1} = zeros(length(data.Measures.Channel),length(TimePlot));
                    data.Measures.F{end}(good_channel(data.Measures.Channel,data.Measures.ChannelFlag,data.Results.DataFlag),:) = data.Measures.F{1}(good_channel(data.Measures.Channel,data.Measures.ChannelFlag,data.Results.DataFlag),:)...
                        - data.Results.Fsynth; % CBB see above
                    OPTIONS.WaveLabel{end+1} = sprintf('Residual Data');
                end
            end

            % -> Now call diplay function
            %[PlotHandles,OPTIONS] = bst_wavedata_display('surface',data.Measures.F,OPTIONS); clear tmp;
            figs = data.Measures.Display.Handles.Figures;
            OPTIONS.DataType = 'surface';

            % Colormap
            if isfield(data.Measures.Display,'Colormap')
                OPTIONS.Colormap = data.Measures.Display.Colormap;
            end

            [data.Measures.Display.Handles,OPTIONS] = bst_wavedata_display(data.Measures.F,OPTIONS); clear tmp;
            if isempty(OPTIONS)  % Display type not available yet
                return
            end

            data.Measures.Display.Flags = struct('SensorMarkers',OPTIONS.SensorMarkers,...
                'SensorLabels',OPTIONS.SensorLabels, 'ShowContours', OPTIONS.ShowContours,...
                 'AbsoluteColormap',OPTIONS.AbsoluteColormap, 'Colorbar',OPTIONS.Colorbar);
             data.Measures.Display.Handles.Figures =  figs;
            % <- DONE

        elseif strcmp(lower(varargin{1}),'results') % Display results

            DataFlag = 0; % Just a flag, we're looking at Results, not Measures.

            if ~isempty(findobj(0,'Tag','set_sourceviewingparameters'))
                set_sourceviewing_parameters('create'); % Refresh viewing parameters
            end

            if ~isfield(data,'Results') % Nor results loaded
                errordlg('Please pick a Results file from taskbar.','No Results in memory')
                return
            end

            % Clean up previous figures
            if isfield(data.Results,'Display')
                if isfield(data.Results.Display,'Handles')
                    HandlesNames = fieldnames(data.Results.Display.Handles);
                    for k = 1:length(HandlesNames)
                        if ishandle(getfield(data.Results.Display.Handles,HandlesNames{k}))
                            delete(getfield(data.Results.Display.Handles,HandlesNames{k})) % Delete all previous figures
                        end
                    end
                    data.Results.Display = rmfield(data.Results.Display,'Handles');
                end

                DisplayStruct = data.Results.Display;

            end

            % -> Fill out display parameters
            % What kind of displays are requested ?
            whichDisplay = dataplot_cb('set_SourceViewingTimeDisplay','get'); % None | Overlay | Column ?
            DisplayStruct.DisplayTypes(1) = whichDisplay(2); % Overlay
            if whichDisplay(3) == 0 % no Column
                DisplayStruct.DisplayTypes(2) = 0;
            else % Column layout required
                if length(DisplayStruct.DisplayTypes) > 1 % previous choice of number of columns somewhere
                    % use data.Measures.Display.DisplayTypes(2) ;
                else
                    DisplayStruct.DisplayTypes(2) = 1;
                end
            end

            % Cortical envolope ? MRI ?
            DisplayStruct.DisplayTypes(3) = max([1,find(dataplot_cb('SourceViewingSpatialDisplay','get'))])-1; % Spatial display
            % Fill out display parameters --------------DONE-------------------------------------------------------------

            tmpLabel = {'MEG','EEG','Misc.'};
            % -> Which modalities need to be displayed ?
            data.Results.Display.Modality = get_selected_modalities;
            if isempty(data.Results.Display.Modality)
                bst_message_window('wrap',...
                    {' ',...
                        'Please select either ''MEG'', ''EEG'' or ''Other'' for display in DataPlot window',...
                        ' '});
                return
            end
            % -> Which modalities need to be displayed ? <- DONE

            % -> Get Results filename and edit it for display as a label
            fname = shorter_filename(data.Results.Filename);
            % <- DONE

            % We need to discriminate though between parametric source plots (a la MUSIC)
            % and cortical source imaging (distributed models)
            Users = get_user_directory;
            File_whos = whos('-file',fullfile(Users.STUDIES,data.Results.Filename{1}));
            if isempty(strmatch('TimeSeries',{File_whos.name})) % Does this file contain a variable named 'TimeSeries'
                TimeSeries = []; % No: this is an Imaging results file
            else
                load(fullfile(Users.STUDIES,data.Results.Filename{1}),'TimeSeries') % | CBB - just one Results file at a time
            end

            switch ~isempty(TimeSeries)
            case 1 % Parametric source results

                % Create new figure
                figHandle = findobj(0,'type','figure','tag','ResultsTimeSeries');
                if isempty(figHandle)
                    figHandle = figure; % Handle to time series window, integer handle by default
                    set(figHandle,'visible','off')
                    setappdata(figHandle,'TileType','T')
                    set(figHandle,'Name',sprintf('Data Time Series Figure %.0f',figHandle)); % integer handle by default
                    bst_color_scheme(figHandle);
                    set(figHandle,'MenuBar','figure')
                    bst_layout('align',figHandle,2,1,2);
                    data.Results.Display.Handles.Figures.TimeSeries = figHandle;
                    set(figHandle,'visible','on','tag','ResultsTimeSeries')
                end

                DataType = 'source';
                data.Results.TimeSeries = TimeSeries;
                TimeSeries = num2cell(TimeSeries',2);
                OPTIONS.Time = linspace(data.Display.Time(1),data.Display.Time(end),data.Display.NumberOfSamples);
                %tmp.Time = tmp.Time(data.Results.Time);

                for src = 1:length(TimeSeries)
                    SrcName{src} = sprintf('Source %d',src);
                end

                data.Results.DataFlag = load(fullfile(Users.STUDIES,data.Results.Filename{1}),'DataFlag'); % | CBB - just one Results file at a time
                data.Results.DataFlag = data.Results.DataFlag.DataFlag;

                OPTIONS.ModalityLabel = {data.Results.DataFlag};
                OPTIONS.WaveLabel = SrcName;
                OPTIONS.SelectedChannels = data.Measures.Display.SelectedChannels(data.Measures.Display.Modality);
                %OPTIONS.Channel = data.Measures.Channel;
                tmpLabel = {'MEG','EEG','Other'};
                tmpChannel = good_channel(data.Measures.Channel,[],tmpLabel{data.Measures.Display.Modality});
                [C,IA,IB] = intersect(tmpChannel,data.Measures.Display.SelectedChannels{data.Measures.Display.Modality});
                data.Results.IndepTopo = load(fullfile(Users.STUDIES,data.Results.Filename{1}),'IndepTopo'); % | CBB - just one Results file at a time
                data.Results.IndepTopo = data.Results.IndepTopo.IndepTopo;
                OPTIONS.IndepTopo = data.Results.IndepTopo(IA,:);
                OPTIONS.Channel = data.Measures.Channel(data.Measures.Display.SelectedChannels{data.Measures.Display.Modality});

                % CBB: We are opening yet another time series figure already opened
                % earlier. Redundant?
                data.Results.Display.Handles.Figures.TimeSeries = figure;
                setappdata(data.Results.Display.Handles.Figures.TimeSeries,'TileType','T');
                set(data.Results.Display.Handles.Figures.TimeSeries, 'Name',...
                   sprintf('Data Time Series Figure %.0f',data.Results.Display.Handles.Figures.TimeSeries))
                bst_color_scheme(data.Results.Display.Handles.Figures.TimeSeries);
                set(data.Results.Display.Handles.Figures.TimeSeries,'menubar','figure');
                bst_layout('align',data.Results.Display.Handles.Figures.TimeSeries,2,1,2)
                figure(data.Results.Display.Handles.Figures.TimeSeries)

                figs = data.Results.Display.Handles.Figures;
                OPTIONS.DataType = 'source';
                OPTIONS.DisplayTypes = data.Measures.Display.DisplayTypes;
                % Colormap
                if isfield(data.Measures.Display,'Colormap')
                    OPTIONS.Colormap = data.Measures.Display.Colormap;
                end

                [data.Results.Display.Handles,OPTIONS] = ...
                    bst_wavedata_display(TimeSeries,OPTIONS); clear tmp;

                data.Results.Display.Handles.Figures = figs; clear figs
                % See time series

                % And now spatial display, e.g. Glass Brain
                if DisplayStruct.DisplayTypes(3) == 3 % See parametric dipole models in brain
                    % Load selected tessellation file
                    [TessFile,h] = bst_static_taskbar('GET','TESS'); clear h

                    bst_message_window('wrap',{...
                            ' ',...
                            sprintf('Loading %s tessellation file',TessFile)});

                    load(fullfile(Users.SUBJECTS,TessFile),'Comment')

                    data.Results.ImageGrid.iGrid = 1;
                    if length(Comment)>1 % Several surfaces in this tessellation file
                        [data.Results.ImageGrid.iGrid,OK] = listdlg('PromptString','Select an envelope from list:',...
                            'SelectionMode','single',...
                            'ListString',Comment);
                        if OK == 0
                            return
                        end
                    end
                    clear Comment

                    data.Results.Display.Handles.Figures.Surfaces = figure; set(data.Results.Display.Handles.Figures.Surfaces,'visible','off' ); drawnow
                    setappdata(data.Results.Display.Handles.Figures.Surfaces,'TileType','T')
                    bst_color_scheme(data.Results.Display.Handles.Figures.Surfaces);
                    bst_layout('align',data.Results.Display.Handles.Figures.Surfaces,1,2,1);
                    bst_layout('align',data.Results.Display.Handles.Figures.TimeSeries,2,2,4);
                    bst_layout('align',data.Measures.Display.Handles.Figures.TimeSeries,2,2,2)

                    data.Results.ImageGrid.GridLoc = {TessFile};
                    load(fullfile(Users.STUDIES,data.Results.Filename{1}),'SourceLoc','SourceOrientation','TimeSeries'); % | CBB - just one Results file at a time
                    OPTIONS.Dipoles.SourceLoc = SourceLoc;
                    OPTIONS.Dipoles.Orientation = SourceOrientation;
                    OPTIONS.Dipoles.TimeSeries = TimeSeries;
                    OPTIONS.Dipoles.Color = data.Results.Display.Handles.LineColor;
                    OPTIONS.Time = 1;
                    OPTIONS.currDensityTransparency = 1;
                    OPTIONS.timeValue = dataplot_cb('GET','current_time');

                    figure(data.Results.Display.Handles.Figures.Surfaces)
                    [PlotHandles2,dOPTIONS] = bst_imaging_display(...
                        data.Results.Display.Handles.Figures.Surfaces,...
                        data.Results.ImageGrid,...
                        0,OPTIONS);
                    set(data.Results.Display.Handles.Figures.Surfaces,'visible','on' ); drawnow

                    data.Results.Display.Handles.hPatch = PlotHandles2.hPatch;
                    data.Results.Display.Handles.hLights = PlotHandles2.hLights;
                    data.Results.Display.OPTIONS = dOPTIONS;

                    dataplot_cb SetSourceViewing % Call GUI for setting of viewing parameters

                elseif DisplayStruct.DisplayTypes(3) == 2 % MRI
                    bst_mriviewer('LoadSourceMap_Callback','','','',data.Results.Filename{1});
                    bst_layout('align',data.Measures.Display.Handles.Figures.TimeSeries,2,2,2);
                    bst_layout('align',data.Results.Display.Handles.Figures.TimeSeries,2,2,4);
                end

            case 0  % Distributed cortical imaging

                %delete(data.Results.Display.Handles.Figures) % Screen layout will be a bit different for this kind of source display
                % dimitrios, avoid creating many figures
                if isfield(data.Results.Display,'SurfaceName')
                    h = windfind(data.Results.Display.SurfaceName);
                    close(h);
                end
                data.Results = rmfield(data.Results,'Display');
                data.Results.Display.Handles.Figures.Surfaces = figure;
                set(data.Results.Display.Handles.Figures.Surfaces,'visible','off' ); drawnow
                setappdata(data.Results.Display.Handles.Figures.Surfaces,'TileType','T')
                bst_layout('align',data.Results.Display.Handles.Figures.Surfaces,1,2,1);
                bst_layout('align',data.Measures.Display.Handles.Figures.TimeSeries,2,2,2)
                figHandle=data.Results.Display.Handles.Figures.Surfaces;
                bst_color_scheme(data.Results.Display.Handles.Figures.Surfaces);

                set( data.Results.Display.Handles.Figures.Surfaces,'CurrentAxes',findobj( data.Results.Display.Handles.Figures,'Tag','MainAxis'),...
                    'Color','k', 'Colormap',gray,'visible','off');

                view3d(data.Results.Display.Handles.Figures.Surfaces,'rot')

                % Tessellation information
                load(fullfile(Users.STUDIES,data.Results.Filename{1}),'HeadModelFile')
                try
                    data.Results.ImageGrid = load(HeadModelFile,'GridLoc','iGrid'); clear HeadModelFile
                catch
                    Users = get_user_directory;
                    try
                        data.Results.ImageGrid = load(fullfile(Users.STUDIES,data.Results.GUI.HeadModelFile),'GridLoc','iGrid');
                    catch
                        errordlg({'Result file has corrupted structure','Could not find GridLoc or iGrid information'})
                        delete(data.Results.Display.Handles.Figures.Surfaces)
                        return
                    end

                end

                OPTIONS.Time = 1; % time index to be displayed
                OPTIONS.timeValue = dataplot_cb('GET','current_time');
            end

            if DisplayStruct.DisplayTypes(3) == 1 % See distributed cortical models

                try
                    set(data.Results.Display.Handles.Figures.Surfaces,'Visible','on')
                catch
                    % do nothing
                end

                data.Results.ImageGridAmp = load(fullfile(Users.STUDIES,data.Results.Filename{1}),'ImageGridAmp');
                data.Results.ImageGridAmp = data.Results.ImageGridAmp.ImageGridAmp;
                % CBB time downsampling  & Kernel only
                if isempty(data.Results.ImageGridAmp)
                    try
                        data.Results.ImagingKernel = load(fullfile(Users.STUDIES,data.Results.Filename{1}),'ImagingKernel');
                        data.Results.ImagingKernel = data.Results.ImagingKernel.ImagingKernel;
                    catch
                        errordlg('Results file does not contain cortical soutce maps.','Non-compliant results file')
                        return
                    end

                    if isempty(data.Results.ImagingKernel)
                        errordlg('Results file does not contain cortical source maps.','Non-compliant results file')
                        return
                    else %ESEN - get the reconstruction from Kernel mode
                        DataType = {'MEG','EEG'};
                        goodChannels = good_channel(data.Measures.Channel,data.Measures.ChannelFlag,DataType{data.Measures.Display.Modality});
                        iKernel = data.Results.ImagingKernel;
                        f_good =  data.Measures.F{1};f_good= f_good(goodChannels, :);

                        tmp = load(fullfile(Users.STUDIES,data.Results.Filename{1}),'OPTIONS');

                        if(~tmp.OPTIONS.NNormalization) %if not noise normalization
                             data.Results.ImageGridAmp =double(iKernel) * f_good;
                         else

                             tmpdatafile = load(fullfile(Users.STUDIES,data.Results.Filename{1}),'DataFile');
                             tmpF = load(tmpdatafile.DataFile,'F'); tmpF = tmpF.F;
                             tmpF = tmpF(goodChannels, :);
                             tmpFbaseline = tmpF(:,tmp.OPTIONS.NoiseSegmentIndices);
                             mean_Baseline= mean(tmpFbaseline,2)*ones(1,size(f_good,2));
                             data.Results.ImageGridAmp =double(iKernel) * (f_good - mean_Baseline);

                         end
    %                     msgbox('Results visualization from results stored as linear kernel needs BrainStorm update'); % TBD !!!!
    %                     return
                    end
                end

                [PlotHandles,OPTIONS] = bst_imaging_display(data.Results.Display.Handles.Figures.Surfaces,...
                    data.Results.ImageGrid,...
                    data.Results.ImageGridAmp,OPTIONS);

                OPTIONS.hPatch = PlotHandles.hPatch;
                PlotHandles.OPTIONS = OPTIONS; clear OPTIONS % to save OPTIONS in data.Results.Display structure
                plotFieldNames = fieldnames(PlotHandles);
                for k = 1:length(plotFieldNames)
                    DisplayStruct = setfield(DisplayStruct,plotFieldNames{k},getfield(PlotHandles,plotFieldNames{k}));
                end
                % Clean up storage structures
                data.Results.Display = DisplayStruct;
                data.Results.Display.Handles.Figures.Surfaces = DisplayStruct.hFigure;
                data.Results.Display.Handles.hPatch  = DisplayStruct.hPatch;
                data.Results.Display.Handles.hLights = DisplayStruct.hLights;
                data.Results.Display = rmfield(data.Results.Display,{'hPatch','hLights','hFigure'});

                dataplot_cb SetSourceViewing  % Viewing parameters

            end

        end

        makeuswait('stop')

           %----------------------------------------------------------------------------
    case 'AddScalpSurface' % Add up Scalp surface display to cortical source visualization

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

        DisplayStruct = data.Measures.Display; %temporary structure to use shorter names in the following

        % -> Get data filename to create labels on displays
        %fname = shorter_filename(data.Measures.Filename);
        % -> Get data filename to create labels on displays <- DONE

        % -> Fill out parameters before call to specific display subfunction
        DefaultLabels = {'MEG','EEG','OTHER'}; % Default modality labels
        OPTIONS = DisplayStruct;

        OPTIONS.DisplayTypes = [0 0 4]; % Scalp surface display

        if isfield(OPTIONS,'Flags') % User has already altered viewing preferences
            flagNames = fieldnames(OPTIONS.Flags);
            for k = 1:length(flagNames)
                OPTIONS = setfield(OPTIONS,flagNames{k},getfield(OPTIONS.Flags,flagNames{k}));
            end
        end

        OPTIONS.Modality = DisplayStruct.Modality;
        OPTIONS.ModalityLabel = DefaultLabels(DisplayStruct.Modality); clear DefaultLabels
        OPTIONS.SelectedChannels = data.Measures.Display.SelectedChannels(DisplayStruct.Modality);
        OPTIONS.Channel = data.Measures.Channel;
        tmpTime = linspace(data.Measures.Time(1),data.Measures.Time(end),data.Measures.NumberOfSamples); % Rebuild original time vector
        % extract Display time samples in ms
        OPTIONS.Time = tmpTime(data.Display.TimeSamples); clear tmpTime
        OPTIONS.CurrentTime = dataplot_cb('GET','current_time');
        if isfield(data.Measures,'Fmax')
            OPTIONS.Fmax = data.Measures.Fmax;
        end

        % -> Now call diplay function
        figure(data.Results.Display.Handles.Figures.Surfaces); hold on
        OPTIONS.DataType = 'surface';

        [htmp,OPTIONS] = bst_wavedata_display(data.Measures.F,OPTIONS); clear tmp;

        data.Results.Display.Handles.TopoPlot = htmp.TopoPlot; clear tmp
        if isfield(data.Results.Display.Handles.TopoPlot(OPTIONS.Modality),'hsens')
            set(data.Results.Display.Handles.TopoPlot(OPTIONS.Modality).hsens{1},'Markeredgecolor',[.2 .2 .2]) % Figure color is 'white' - darken marker color
        end
        % Apply default transparency to scalp
        set(data.Results.Display.Handles.TopoPlot(OPTIONS.Modality).surf{1},'FaceAlpha',.5)
        set(data.Results.Display.Handles.TopoPlot(OPTIONS.Modality).timeText{1},'visible','off')

        %data.Measures.Display.Handles.Figures =  figs;
        % <- DONE

        set_sourceviewing_parameters('create'); % refresh pulldown list of surface patches

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

        %----------------------------------------------------------------------------
    case 'CorticalScouts' % Create/Manage cortical scouts

        manage_corticalscouts('create')

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

    case 'GetTimeWindowFromZoom' % Set viewing time window from zooming in/out of the overlay plot

        XXlim = xlim;

        if data.Measures.Display.DisplayTypes(1)
            for k=1:length(data.Measures.Display.Handles.PlotOverlay)
                set([data.Measures.Display.Handles.PlotOverlay(k).axes],'Xlim',XXlim,'buttondownfcn','dataplot_cb GetTimeWindowFromZoom')
                set(get([data.Measures.Display.Handles.PlotOverlay(k).axes],'Children'),'buttondownfcn','dataplot_cb GetTimeWindowFromZoom')
            end

        end

        if data.Measures.Display.DisplayTypes(2) > 1
            for k=1:length(data.Measures.Display.Handles.PlotColumn)
                set([data.Measures.Display.Handles.PlotColumn(k).axes],'Xlim',XXlim,'buttondownfcn','dataplot_cb GetTimeWindowFromZoom')
                tmp = get([data.Measures.Display.Handles.PlotColumn(k).axes],'Children');
                if iscell(tmp)
                    tmp = cat(1,tmp{:});
                end
                set(tmp,'buttondownfcn','dataplot_cb NameSelectedChannel')
                set(tmp,'buttondownfcn','dataplot_cb GetTimeWindowFromZoom')
            end
        end

        % Requested time window for display
        set(hDataplot.time_min,'String',1000*XXlim(1));
        set(hDataplot.time_max,'String',1000*XXlim(2));

        % Display global data
        data.Display.Time = XXlim;
        % Set current time in the middle of new window
        dataplot_cb('set_time_min');
        dataplot_cb('SET','time', mean(XXlim));

        % Check whether signal decomposition window is open
        DataSelectorFig = findobj(0,'Name','Parametric Estimation Data Selector');
        if isempty(DataSelectorFig), return, end
        % Set axes time limits to viewer's limits
        DShandles = guihandles(DataSelectorFig);
        set([DShandles.AxisSignalSubspace,DShandles.AxisNoiseSubspace],'Xlim',1000*XXlim);
        set([DShandles.EditMinTime],'string',sprintf('%3.2f ms',1000*XXlim(1)))
        set([DShandles.EditMaxTime],'string',sprintf('%3.2f ms',1000*XXlim(2)))

        %----------------------------------------------------------------------------
    case 'ToggleWindowFromZoom' % Toggle axes zoom status

        if ~isappdata(DATAPLOT,'ZoomState')
            setappdata(DATAPLOT,'ZoomState',0);
        end

        ZoomState = getappdata(DATAPLOT,'ZoomState');

        Axes = [];
        if data.Measures.Display.DisplayTypes(1)
            for k = 1:length(data.Measures.Display.Handles.PlotOverlay)
                Axes = [Axes,data.Measures.Display.Handles.PlotOverlay(k).axes];
            end
        end

        if data.Measures.Display.DisplayTypes(2) > 1
            for k = 1:length(data.Measures.Display.Handles.PlotColumn)
                data.Measures.Display.Handles.PlotColumn(k).axes = data.Measures.Display.Handles.PlotColumn(k).axes(data.Measures.Display.Handles.PlotColumn(k).axes~=0);
                Axes = [Axes,data.Measures.Display.Handles.PlotColumn(k).axes'];
            end
        end

        if ~ZoomState
            bst_message_window('wrap',{...
                    ' ',...
                    'Press and hold left mouse button to zoom in and out',...
                    'Press and hold middle mouse button to move the plot',...
                    'Double click to restore the original view'...
                })
                view3d zoom %zoom xon
                set(gcbo,'Checked','on')
            setappdata(DATAPLOT,'ZoomState',1);
            for k = 1:length(Axes)
                set(Axes(k),'buttondownfcn','dataplot_cb GetTimeWindowFromZoom','selected','on')
                set(setdiff(get(Axes(k),'Children'),data.Measures.Display.Handles.TimeCursor),'buttondownfcn','dataplot_cb GetTimeWindowFromZoom')
            end

        else
            view3d off %zoom off
            set(gcbo,'Checked','off')
            setappdata(DATAPLOT,'ZoomState',0);
            for k = 1:length(Axes)
                set(Axes(k),'buttondownfcn','','selected', 'off')
                set(setdiff(get(Axes(k),'Children'),data.Measures.Display.Handles.TimeCursor),'buttondownfcn','dataplot_cb NameSelectedChannel')
            end

        end
        %----------------------------------------------------------------------------

    case 'ToggleRotate3D' % Toggle rotate3d status

        if ~isappdata(DATAPLOT,'RotateState')
            setappdata(DATAPLOT,'RotateState',0);
        end

        RotateState = getappdata(DATAPLOT,'RotateState');

        %handles = guihandles(gcbf);
        try % to rotat eonly surface maps
            set(gcbf,'CurrentAxes',data.Measures.Display.Handles.TopoPlot.axes{:})
            if ~RotateState
                bst_message_window('wrap',{...
                        ' ',...
                        'Press and hold left mouse button to rotate about screen XY axis',...
                        'Press and hold middle mouse button to rotate about screen z axis',...
                        'Double click to restore the original view'...
                    })
                view3d rot%rotate3d on
                set(gcbo,'Checked','on')
                setappdata(DATAPLOT,'RotateState',1);
            else
                view3d off %rotate3d off
                set(gcbo,'Checked','off')
                setappdata(DATAPLOT,'RotateState',0);
            end
        catch
            % do nothing
        end

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

    case 'SetDataViewing' % set viewing parameters for data time and spatial displays

        DataParam = openfig('set_dataviewing_parameters.fig','reuse');
        setappdata(DataParam,'TileType','Tile')
        bst_color_scheme(DataParam);
        bst_layout('align',DataParam,2,2,4);

        hDataParam = guihandles(DataParam);
        % Number of columns
        if ~isfield(data.Measures.Display,'Flags')
            data.Measures.Display.DisplayTypes = dataplot_cb('DataViewingTimeDisplay','get'); % Time series
            data.Measures.Display.DisplayTypes = data.Measures.Display.DisplayTypes(2:end); % Discard first item which is N/A
            data.Measures.Display.DisplayTypes(3) = max([0,find(dataplot_cb('DataViewingSpatialDisplay','get'))]); % Spatial display
        end

        set(hDataParam.ColumnLayout,'String',data.Measures.Display.DisplayTypes(2));
        % Were basic viewing Flags defined before ?
        if ~isfield(data.Measures.Display,'Flags')
            data.Measures.Display.Flags = struct(...
                'Colorbar',1,'AbsoluteColormap',1,'SensorMarkers',1,'SensorLabels',0,'ShowContours',1);
        end

        set(hDataParam.cColorbar,'Value',data.Measures.Display.Flags.Colorbar);
        set(hDataParam.cAbsoluteColormap,'Value',data.Measures.Display.Flags.AbsoluteColormap);
        set(hDataParam.cSensorMarkers,'Value',data.Measures.Display.Flags.SensorMarkers);
        set(hDataParam.cSensorLabels,'Value',data.Measures.Display.Flags.SensorLabels);
        set(hDataParam.cContours,'Value',data.Measures.Display.Flags.ShowContours);

        set(DataParam,'Visible','on')

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

    case 'SetSourceViewing' % set viewing parameters for source displays

        set_sourceviewing_parameters('create')

        %----------------------------------------------------------------------------
    case 'MSIndexSwitch' % Switch between time expressed in milliseconds and indices of time samples

        %%%%% SB 12-Jun-2003 - CBB - STILL NOT FINISHED - wait until next version...

        switch(get(hDataplot.MsIndex,'String'))
        case 'ms' % Time is displaid in ms -> switch to time indices
            set(hDataplot.MsIndex,'String','time samples')

            return % CBB - need to finish this ?

            data.Indices = [1:data.NumberOfSamples];
            timesamples = findclosest([data.Display.Time(1),data.Display.Time(1)+data.Display.SamplingRate,data.Display.Time(end)], 1000*data.TimePlot');

            % Requested time window for display
            set(hDataplot.time_min,'String',timesamples(1));
            set(hDataplot.time_max,'String',timesamples(2));
            set(hDataplot.step,'String',timesamples(2)-timesamples(1));

            timesamples = findclosest([data.Display.Time(1),data.Display.Time(1)+data.Display.SamplingRate,data.Display.Time(end)], 1000*data.TimePlot');

        case 'time samples' % Time is displaid in samples  -> switch to milliseconds
            set(hDataplot.MsIndex,'String','ms')

            return % CBB - need to finish this ?
        end

        %----------------------------------------------------------------------------
    case {'set_time_min','set_time_step','set_time_max'} % Set parameters of time window for display

        Users = get_user_directory;

        % User has changed values from time-related objects in GUI: get new values
        % or a Results file has just been loaded and we need to restrict the Measures display
        % to the time window of analysis from which the results were obtained

        % Requested time window for display (range + step between samples)
        TIME_MIN = str2num(get(hDataplot.time_min,'String'));
        TIME_MAX = str2num(get(hDataplot.time_max,'String'));
        STEP = str2num(get(hDataplot.step,'String'));

        % -> Check whether these values stay within the original time window
        if TIME_MAX > data.Measures.Time(end) * 1000
            TIME_MAX = data.Measures.Time(end) * 1000;
            set(hDataplot.time_max,'String',num2str(TIME_MAX,5))
        end

        if TIME_MIN < data.Measures.Time(1) * 1000
            TIME_MIN = data.Measures.Time(1) * 1000;
            set(hDataplot.time_min,'String',num2str(TIME_MIN,5))
        end
        % -> Check whether these values stay within the original time window <- DONE

        % -> Subset of time samples for display
        % Rebuild original time window of measures
        tmp = linspace(data.Measures.Time(1),data.Measures.Time(2),data.Measures.NumberOfSamples);
        % Find original time samples closest to requested time window
        timesamples = findclosest([TIME_MIN,TIME_MIN+STEP,TIME_MAX], 1000*tmp');

        % New valid values for time range and samplerate from original Measures time window
        TIME_MIN = tmp(timesamples(1));
        STEP = tmp(timesamples(2))-tmp(timesamples(1));
        TIME_MAX = tmp(timesamples(end));
        data.Display.TimeSamples = [timesamples(1):timesamples(2)-timesamples(1):timesamples(end)];
        data.Display.Time =  tmp([timesamples(1),timesamples(end)]);
        data.Display.SamplingRate = STEP;
        data.Display.NumberOfSamples = length(data.Display.TimeSamples);

        clear tmp timesamples
        % -> Subset of time samples for display <- DONE

        % -> Update GUI objects accordingly
        set(hDataplot.step,'String',sprintf('%3.2f',1000*STEP))
        set(hDataplot.time_min,'String',sprintf('%3.2f',1000*data.Display.Time(1)))
        set(hDataplot.time_max,'String',sprintf('%3.2f',1000*data.Display.Time(end)))
        set(hDataplot.nTimeSamples,'String', sprintf('%d samples',length(data.Display.TimeSamples)))
        set(hDataplot.TimeSlider,'Min',data.Display.Time(1),'Max',data.Display.Time(end),...
            'Value',data.Display.Time(1),'SliderStep',[STEP/(data.Display.Time(end)-data.Display.Time(1)),.1])
        clear TIME_MIN TIME_MAX STEP
        % -> Update GUI objects accordingly <- DONE

        % -> Extract accordingly a subset of columns from original Measures array
        % for all selected data files
        [fname,h] = bst_static_taskbar('GET','DATA'); % Get data file
        if ~iscell(fname) % Single data set was selected
            fname = {fname};
        end

        data.Measures.F = cell(length(fname),1); % Spatio-temporal array of measures

        for ifname = 1:length(fname) % for each selected data filename

            load(fullfile(Users.STUDIES,fname{ifname}),'F')

            if ischar(F) % Data in native format
                data.Measures.F{ifname} = meg4read(F,1,data.Display.TimeSamples,1) % Trial is 1 here and Verbose is set to 1 too.
            else
                data.Measures.F{ifname} = F(:,data.Display.TimeSamples);
            end

            clear F

            for mod=1:3 % For each modality (MEG, EEG, OTHER), compute maximum across time and sensors
                % (useful for subsequent display)
                if ~isempty(data.Measures.Display.SelectedChannels{mod}) % Channels are available is this modality
                    data.Measures.Fmax(ifname,mod) = max(max(abs(...
                        data.Measures.F{ifname}(data.Measures.Display.SelectedChannels{mod},:))));
                else
                    data.Measures.Fmax(ifname,mod) = 0;
                end
            end

        end
        % -> Extract accordingly a subset of columns from original Measures array
        % for all selected data files <- DONE

        if nargout == 0
            dataplot_cb('Plot','measures'); % Update display of original data
        else
            varargout{1} = []; % trick to avoid plots to be redrawn | CBB (SB)
        end

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

    case 'NameSelectedChannel' % Display Channel Name of selected time series

        if ~strcmp(lower(get(gcbf,'SelectionType')),'normal') % Not a left-click button press - return
            return
        end

        hobj = gcbo;

        % Find which modality was selected
        nSets = length(data.Measures.F);
        iSelec = [];
        iChanSelec = [];
        for mod = data.Measures.Display.Modality % Explore all axes to find which was selected
            for iSet = 1:nSets

                if data.Measures.Display.DisplayTypes(1) % Overlay waveforms ?
                    Objects = [data.Measures.Display.Handles.PlotOverlay(mod).lines{iSet}];
                    iSelec = find(Objects == gcbo);
                    if ~isempty(iSelec)
                        modSelec = mod;
                        iSetSelec = iSet;
                        iChanSelec = iSelec;
                        break
                    end
                end
                if data.Measures.Display.DisplayTypes(2) > 1 % Column Layout
                    Objects = [data.Measures.Display.Handles.PlotColumn(mod).lines{iSet}];
                    iSelec = find(Objects == gcbo);
                    if ~isempty(iSelec)
                        modSelec = mod;
                        iSetSelec = iSet;
                        iChanSelec = iSelec;
                        break
                    end
                end

                if data.Measures.Display.DisplayTypes(3) > 1 % Surface plots
                    Objects = [data.Measures.Display.Handles.TopoPlot(mod).hsens{iSet}];
                    iSelec = find(Objects == gcbo);
                    if ~isempty(iSelec)
                        modSelec = mod;
                        iSetSelec = iSet;
                        iChanSelec = iSelec;
                        break
                    end
                end
            end
        end

        if isempty(iChanSelec), return, end
        iChan = data.Measures.Display.SelectedChannels{modSelec}(iChanSelec);

        % Was this channel selected before ?
        if ~isfield(data.Measures.Display.Handles,'MouseSelectedChannels')
            data.Measures.Display.Handles.MouseSelectedChannels = [];
        end

        if isempty(data.Measures.Display.Handles.MouseSelectedChannels) % this if series is to avoid warning signs in the command line...
            flag = 0;
        elseif ~isempty(find(data.Measures.Display.Handles.MouseSelectedChannels == iChan))
            flag = 1;
        else
            flag = 0;
        end

        if flag
            % Yes, remove it from selection
            data.Measures.Display.Handles.MouseSelectedChannels = setdiff(data.Measures.Display.Handles.MouseSelectedChannels,iChan);

            for iSet = 1:nSets
                if data.Measures.Display.DisplayTypes(1)
                    set(data.Measures.Display.Handles.PlotOverlay(modSelec).lines{iSet}(iChanSelec),'linewidth',1,...
                        'Color',data.Measures.Display.Handles.LineColor{iSetSelec})
                end
                if data.Measures.Display.DisplayTypes(2) > 1
                    set(data.Measures.Display.Handles.PlotColumn(modSelec).lines{iSet}(iChanSelec),'linewidth',1,...
                        'Color',data.Measures.Display.Handles.LineColor{iSetSelec})
                end
                if data.Measures.Display.DisplayTypes(3) > 1 & data.Measures.Display.Flags.SensorMarkers
                    set(data.Measures.Display.Handles.TopoPlot(modSelec).hsens{iSet}(iChanSelec),'MarkerFaceColor','none')
                end
            end

        else

            data.Measures.Display.Handles.MouseSelectedChannels = [data.Measures.Display.Handles.MouseSelectedChannels,iChan];

            for iSet = 1:nSets
                if data.Measures.Display.DisplayTypes(1)
                    set(data.Measures.Display.Handles.PlotOverlay(modSelec).lines{iSet}(iChanSelec),'linewidth',2)
                    if nSets == 1
                        set(data.Measures.Display.Handles.PlotOverlay(modSelec).lines{iSet}(iChanSelec),'Color','r')
                    end
                end
                if data.Measures.Display.DisplayTypes(2) > 1
                    set(data.Measures.Display.Handles.PlotColumn(modSelec).lines{iSet}(iChanSelec),'linewidth',2)
                    if nSets == 1
                        set(data.Measures.Display.Handles.PlotColumn(modSelec).lines{iSet}(iChanSelec),'Color','r')
                    end
                end
                if data.Measures.Display.DisplayTypes(3) > 1 & data.Measures.Display.Flags.SensorMarkers
                    set(data.Measures.Display.Handles.TopoPlot(modSelec).hsens{iSet}(iChanSelec),'MarkerFaceColor','g')
                end
            end
        end

        % Context Menu
        ChannelNames = uicontextmenu;
        uimenu(ChannelNames,'Label',char(data.Measures.Channel(iChan).Name))
        uimenu(ChannelNames,'Separator','on','Label','Display Selected Channel(s)','Callback','dataplot_cb DisplaySelectedChannels')
        uimenu(ChannelNames,'Separator','on','Label','Change Waveforms Color','Callback','dataplot_cb ChangeWaveformsColor')
        set(hobj,'UIcontextMenu',ChannelNames)

        data.SelectedChannel.iChan = iChanSelec;
        data.SelectedChannel.ModSelec = modSelec;
        data.SelectedChannel.iSetSelec = iSetSelec;

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

    case 'CopyCurrentPlot' % Make a copyobj command on selected axes to export current plot to some other tile

        % Create new figure
        set(gcf,'Pointer','Watch')

        figcopy = figure; % create new figure
        set(figcopy,'Visible','off')
        setappdata(figcopy,'TileType','T')
        bst_color_scheme(figcopy);
        bst_layout('align',figcopy,2,2,3);

        % Find what is current axes
        % (GCA command is not enough as we need extra information on colorbar and other stuff)
        copyColorbar = [];
        if data.Measures.Display.DisplayTypes(1)
            figAxes = [data.Measures.Display.Handles.PlotOverlay(:).axes];
            slctAxes = find(figAxes == gca);
            if isempty(slctAxes)
                if data.Measures.Display.DisplayTypes(2) > 1
                    figAxes = [data.Measures.Display.Handles.PlotColumn.axes(:)];
                    slctAxes = find(figAxes == gca);
                end
                if isempty(slctAxes) & data.Measures.Display.DisplayTypes(3) >1
                    figAxes = [];
                    for mod = data.Measures.Display.Modality
                        figAxes = [figAxes,data.Measures.Display.Handles.TopoPlot(mod).axes{:}];
                    end

                    slctAxes = find(figAxes == gca);

                    if data.Measures.Display.Flags.Colorbar
                        copyColorbar = [];
                        for mod = data.Measures.Display.Modality
                            copyColorbar = [copyColorbar,data.Measures.Display.Handles.TopoPlot(mod).Colorbar{:}];
                        end
                        copyColorbar = copyColorbar(slctAxes);
                    end
                end
            end
        end

        if isempty(slctAxes)
            delete(figcopy)
            set(gcf,'Pointer','Arrow')
            return
        end

        C = copyobj(figAxes(slctAxes),figcopy);
        set(C(1),'position',[0.1 0.1 0.8 0.8])
        if ~isempty(copyColorbar) % This is a surface topography plot

            newColorbar = colorbar('horiz','peer',C(1));
            posSurfAxes = get(C(1),'Position');
            posColBarAxes = get(newColorbar,'Position');

            set(get(newColorbar,'Children'),'XData',get(get(copyColorbar,'Children'),'XData'))
            set(newColorbar, 'XLim',get(copyColorbar,'XLim'),...
                'Position',[posColBarAxes(1)*1.00014,posColBarAxes(2),posSurfAxes(3),posColBarAxes(4)],...
                'YAxisLocation',get(copyColorbar,'YAxisLocation'),...
                'YLim',get(copyColorbar,'YLim'),...
                'Xtick',get(copyColorbar,'Xtick'),...
                'Ytick',get(copyColorbar,'Ytick'),...
                'XtickLabel',get(copyColorbar,'XtickLabel'),'YtickLabel',get(copyColorbar,'YtickLabel'))

        end
        if ~isfield(data.Measures.Display.Flags,'Colorbar')
            data.Measures.Display.Flags.Colorbar = 0;
        end

        set(figcopy,'visible','on',...
            'menubar','figure','NumberTitle','on','Name','Copy')

        if isfield(data.Measures.Display.Handles,'Colormap')
            set(figcopy,'visible','on','colormap',data.Measures.Display.Handles.Colormap,...
                'menubar','figure','NumberTitle','on','Name','Copy')
        end

        set(gcf,'Pointer','Arrow')

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

    case 'ChangeWaveformsColor' % Change line color of time series

        % Handles to all line objects in TimeSeries display window
        Lines = [];
        hsens = [];
        hobj = [];
        ncol = 0; nover = 0;

        if ~isempty(data.SelectedChannel.iChan)

            newcolor = uisetcolor('Pick a new color for selected waveform(s)');
            if ~newcolor
                return
            end

            % Now find the data set this time series belong to:

            if data.Measures.Display.DisplayTypes(2) > 1
                Lines = cat(1,data.Measures.Display.Handles.PlotColumn(data.SelectedChannel.ModSelec).lines{ data.SelectedChannel.iSetSelec });
            end

            if data.Measures.Display.DisplayTypes(1)
                Lines = [Lines;cat(1,data.Measures.Display.Handles.PlotOverlay(data.SelectedChannel.ModSelec).lines{ data.SelectedChannel.iSetSelec })];
            end

            set(Lines,'Color',newcolor)

            data.Measures.Display.Handles.LineColor{data.SelectedChannel.iSetSelec } = newcolor;

        end

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

    case 'DisplaySelectedChannels'
        % Display time series of selected channels using the above ''NameSelectedChannel' callback

        if ~isempty(data.Measures.Display.Handles.MouseSelectedChannels) % Channels were actually selected by user's mouse
            % Open new display figure
            h = figure;
            set(h,'visible','off')
            setappdata(h,'TileType','Tile')
            bst_color_scheme(h)
            figure(h), hold on

            for mod = data.Measures.Display.Modality
                if~isempty(data.Measures.Display.SelectedChannels{mod}==data.Measures.Display.Handles.MouseSelectedChannels(1))
                    modselected = mod;
                    break
                end
            end

            for iSet = 1:length(data.Measures.F)
                if data.Measures.Display.DisplayTypes(1)
                    LineColor =  get(data.Measures.Display.Handles.PlotOverlay(modselected).lines{iSet}(1),'color');
                elseif data.Measures.Display.DisplayTypes(2) > 1
                    LineColor =  get(data.Measures.Display.Handles.PlotColumn(modselected).lines{iSet}(1),'color');
                end
                tmpTime  = linspace(data.Display.Time(1),data.Display.Time(end),data.Display.NumberOfSamples);
                data.Measures.Display.Handles.PlotOverlaySelected.lines{iSet} = plot(tmpTime,...
                    data.Measures.F{iSet}(data.Measures.Display.Handles.MouseSelectedChannels,:)','color',LineColor);
            end

            data.Measures.Display.Handles.PlotOverlaySelected.axes = get(data.Measures.Display.Handles.PlotOverlaySelected.lines{1}(1),'Parent');

            set(data.Measures.Display.Handles.PlotOverlaySelected.axes,'ygrid','on','xgrid','on','Box','on',...
                'xColor',[.8 .8 .8], 'ycolor', [.8 .8 .8],'XMinorGrid','on',...
                'Xlim',[data.Display.Time(1),data.Display.Time(end)],...
                'ButtonDownFcn','dataplot_cb GetTimeWindowFromZoom',...
                'Visible','on')
            xlabel('Time (s)')

            % Display Legend
            [LEGH,OBJH,OUTH,OUTM] = legend(data.Measures.Channel(data.Measures.Display.Handles.MouseSelectedChannels).Name);
            LegendMenu = uicontextmenu;

            uimenu(LegendMenu,'Label','Hide/Show Legend','Callback','dataplot_cb HideShowMouseSelectedDisplayLegend')
            uimenu(LegendMenu,'checked','off','Label','Zoom ON','Callback','dataplot_cb ToggleWindowFromZoom')
            uimenu(LegendMenu,'checked','off','Label','Rotate','Callback','dataplot_cb ToggleRotate3D')
            uimenu(LegendMenu,'Separator','on','Label','Copy Current Plot','Callback','dataplot_cb CopyCurrentPlot')
            set([h;data.Measures.Display.Handles.PlotOverlaySelected.axes;LEGH;OBJH],'UIcontextMenu',LegendMenu)

            set(findobj(OBJH,'type','text'),'Fontsize',7,'fontunits','points')

            bst_layout('align',h,2,2,3)
            set(h,'visible','on')
        else
            bst_message_window('wrap',...
                'No channel selected - please click on overlay time series or sensor locations in scalp topography display')
        end

        %----------------------------------------------------------------------------
    case 'HideShowMouseSelectedDisplayLegend' % Hide/Show legend for plot of selected channel time series

        if ~isfield(data,'ShowMouseSelectedDisplayLegend') % Flag
            data.ShowMouseSelectedDisplayLegend = 1;
        end
        switch(data.ShowMouseSelectedDisplayLegend)
        case 1
            legend(gca,'hide') %data.Measures.Display.Handles.PlotOverlaySelected.axes
            data.ShowMouseSelectedDisplayLegend = 0;
        case 0
            legend(gca,'show')
            data.ShowMouseSelectedDisplayLegend = 1;
        end

        %----------------------------------------------------------------------------
    case 'MoveTimeCursor' % Move time cursor with mouse button pushed

        if ~exist('hDataplot','var') % Trick to make cursor move a bit faster
            global hDataplot data
            % % hDataplot = guihandles(DATAPLOT);
            %%data = guidata(DATAPLOT);
        end

        % Get handles from all text and time cursors (both Measures and Results plots)
        TimeCursorHandles = [];
        TextCursorHandles = [];
        if isfield(data.Measures.Display.Handles,'TimeCursor')
            TimeCursorHandles = data.Measures.Display.Handles.TimeCursor;%[data.Measures.Display.Handles.TimeCursor(ishandle(data.Measures.Display.Handles.TimeCursor)),data.Results.Display.TimeCursor(ishandle(data.Results.Display.TimeCursor))];
        end
        if isfield(data.Measures.Display.Handles,'TextCursor')
            TextCursorHandles = data.Measures.Display.Handles.TextCursor; %[data.Measures.Display.Handles.TimeCursor(ishandle(data.Measures.Display.Handles.TimeCursor)),data.Results.Display.TimeCursor(ishandle(data.Results.Display.TimeCursor))];
        end

        if isfield(data,'Results')
            if isfield(data.Results,'Display')
                if isfield(data.Results.Display.Handles,'TimeCursor')
                    TimeCursorHandles = [TimeCursorHandles,data.Results.Display.Handles.TimeCursor];
                end
                if isfield(data.Results.Display.Handles,'TextCursor')
                    TextCursorHandles = [TextCursorHandles ,data.Results.Display.Handles.TextCursor];
                end

                % Scout display
                if isfield(data.Results.Display,'Scouts')

                    if isfield(data.Results.Display.Scouts.Handles,'TimeCursor')
                        TimeCursorHandles = [TimeCursorHandles,data.Results.Display.Scouts.Handles.TimeCursor];
                    end

                    if isfield(data.Results.Display.Scouts.Handles,'TextCursor')
                        TextCursorHandles = [TextCursorHandles ,data.Results.Display.Scouts.Handles.TextCursor];
                    end

                end

            end

        end

        % House cleaning
        TimeCursorHandles = TimeCursorHandles(ishandle(TimeCursorHandles));
        TextCursorHandles = TextCursorHandles(ishandle(TextCursorHandles));

        switch varargin{1}
        case 'start',

            set(gcbf,'WindowButtonMotionFcn','dataplot_cb MoveTimeCursor move')
            set(gcbf,'WindowButtonUpFcn','dataplot_cb MoveTimeCursor stop')
            set(DATAPLOT,'pointer','fleur')

        case 'move'

            set(DATAPLOT,'pointer','fleur')

            set(TimeCursorHandles,'Selected','on')
            XData = get(TimeCursorHandles,'Xdata');

            X = get(gca,'CurrentPoint');
            X = X(1,1);

            % Check whether cursor is out of display time bounds
            if X < data.Display.Time(1)
                X = data.Display.Time(1);
            end
            if X > data.Display.Time(end)
                X = data.Display.Time(end);
            end

            set(TimeCursorHandles,'Xdata',[X X])

            postxt  = get(TextCursorHandles,'Position');
            if ~iscell(postxt)
                postxt = {postxt};
            end

            for curs = 1:length(postxt)
                if ~isempty(postxt{curs})
                    set(TextCursorHandles(curs),'Position',[X postxt{curs}(2)],'String',num2str(1000*X,'%3.1f'))
                end
            end

        case 'stop'

            set(gcbf,'WindowButtonMotionFcn','')
            set(gcbf,'WindowButtonUpFcn','')
            set(TimeCursorHandles,'selected','off')
            set(DATAPLOT,'pointer','arrow')
            X = get(data.Measures.Display.Handles.TimeCursor(1),'Xdata');
            set(hDataplot.current_time,'String',num2str(1000*X(1),'%3.2f'))
            set(hDataplot.TimeSlider,'Value',X(1));

            dataplot_cb mapping_slider

        end

        %----------------------------------------------------------------------------
    case 'mapping_slider' % Update of the current time sample using the slider or graphical timecursor

        ctime = dataplot_cb('GET','current_time');

        if isfield(data,'Results')
            if isfield(data.Results,'Display')
                setDisplayStruct = {data.Measures.Display,data.Results.Display};

                if isfield(data.Results.Display,'Scouts')
                    setDisplayStruct = {data.Measures.Display,data.Results.Display.Scouts,data.Results.Display};
                end

                noResults = 0; % Just a flag - 0: there are some results to display

            else
                setDisplayStruct = {data.Measures.Display};
                noResults = 1;
            end
        else
            setDisplayStruct = {data.Measures.Display};
            noResults = 1;
        end

        datatype = 0; % Flag : 1 is for surface data ; 2 is for result data
        for struuct = 1:length(setDisplayStruct)

            DisplayStruct = setDisplayStruct{struuct};
            DisplayStruct = DisplayStruct.Handles;
            datatype = datatype + 1;

            if ~isfield(DisplayStruct,'TimeCursor')
                break
            end

            if ~isempty(DisplayStruct.TimeCursor)
                if ~ishandle(DisplayStruct.TimeCursor), return, end
                set(DisplayStruct.TimeCursor,'Xdata',[ctime ctime])
            end

            if ~isfield(DisplayStruct,'TextCursor')
                DisplayStruct.TextCursor = [];
            end

            if (isempty(DisplayStruct.TextCursor) & ~isempty(DisplayStruct.TimeCursor)) | ~ishandle(DisplayStruct.TimeCursor) | ~ishandle(DisplayStruct.TextCursor)

                for k = 1%:length(data.Measures.Display.Handles.TimeCursor)
                    if k ==1  % Plot Overlay
                        DisplayStruct.TextCursor(k) = text(ctime,max(get(get(DisplayStruct.TimeCursor(k),'Parent'),'Ylim'))/1.1,num2str(1000*ctime,'%3.1f'),...
                            'Parent',get(DisplayStruct.TimeCursor(1),'Parent'));
                    else % Plot Columns
                        DisplayStruct.TextCursor(k) = text(ctime,txtpos(2),num2str(1000*ctime,'%3.1f'),'Units','Normal');
                    end
                end

                set(DisplayStruct.TextCursor ,'Horizontalalignment','right',...
                    'Fontweight','bold','color','k','fontsize',9,...
                    'Tag','data.TextCursor','erasemode','xor')

            elseif ~isempty(DisplayStruct.TextCursor)
                pos = get(DisplayStruct.TextCursor,'Position');
                set(DisplayStruct.TextCursor,'Position',[[ctime],pos(2)],...
                    'String',sprintf('%3.1f',1000*ctime))
            end

            % Current time index
            timeTmp = [data.Display.Time(1):data.Display.SamplingRate:data.Display.Time(end)]';
            tindx = findclosest(ctime,timeTmp);

            % Is there any spatial plot requested ?
            TopoType = data.Measures.Display.DisplayTypes;
            TopoType = TopoType(3);

            if TopoType > 1 % Spatial topography plot of scalp data is requested

                if datatype == 1
                    if data.Measures.Display.TimeSeriesTypes(1) == 1 % User wants to see original data
                        Disp.TimeSeries = data.Measures.F;
                    end
                    if 0%data.Measures.Display.TimeSeriesTypes(2) == 1 % User wants to see modeled data
                        Disp.TimeSeries{end+1} = zeros(length(data.Measures.Channel),length(data.Display.TimeSamples));
                        Disp.TimeSeries{end}(good_channel(data.Measures.Channel,...
                            data.Measures.ChannelFlag,data.Results.DataFlag),:) = data.Results.Fsynth; % CBB need to updat plotselectedchannels accordingly
                    end
                    if 0%data.Measures.Display.TimeSeriesTypes(3) == 1 % User wants to see residuals
                        Disp.TimeSeries{end+1} = zeros(length(data.Measures.Channel),length(data.Display.TimeSamples));
                        Disp.TimeSeries{end}(good_channel(data.Measures.Channel,...
                            data.Measures.ChannelFlag,data.Results.DataFlag),:) = ...
                            data.Measures.F{1}(good_channel(data.Measures.Channel,data.Measures.ChannelFlag,data.Results.DataFlag),:) ...
                            - data.Results.Fsynth;; % CBB see above
                    end

                    nSets = length(Disp.TimeSeries);

                elseif datatype == 2
                    nSets = size(data.Results.TimeSeries,2);
                end

                if ~isfield(setDisplayStruct{struuct},'Modality') & struuct > 1
                    setDisplayStruct{struuct}.Modality = setDisplayStruct{struuct-1}.Modality;
                elseif ~isfield(setDisplayStruct{struuct},'Modality') & struuct == 1
                    errordlg('Unvalid display structure.',mfilename)
                    return
                end

                for iSet = 1:nSets

                    for k = getfield(setDisplayStruct{struuct},'Modality')
                        switch(TopoType)
                        case 1 % Do nothing

                        case 2 % Spherical approximation of the scalp

                            if datatype == 1

                                CData = DisplayStruct.TopoPlot(k).Wmat{iSet} * Disp.TimeSeries{iSet}(data.Measures.Display.SelectedChannels{k},tindx);
                                CData = reshape(CData,sqrt(length(CData)),sqrt(length(CData)));
                                CData = CData * max(abs(Disp.TimeSeries{iSet}(data.Measures.Display.SelectedChannels{k},tindx)))/max(abs(CData(:))); % properly rescale to data amplitude

                            elseif datatype == 2

                                %F = zeros(length(data.Measures.Channel),size(data.Results.TimeSeries',2));
                                F = data.Results.IndepTopo(:,iSet)*data.Results.TimeSeries(tindx,iSet)';
                                CData = DisplayStruct.TopoPlot(k).Wmat{iSet} * F;
                                CData = reshape(CData,sqrt(length(CData)),sqrt(length(CData)));
                                CData = CData * max(abs(F))/max(abs(CData(:))); % properly rescale to data amplitude
                            end

                            set(DisplayStruct.TopoPlot(k).surf{iSet},'CData',CData);

                        case {3,6} % (2D) Sensor Cap

                            set(DisplayStruct.TopoPlot(k).surf{iSet},'FaceVertexCData', Disp.TimeSeries{iSet}(data.Measures.Display.SelectedChannels{k},tindx))

                        case 4 % Scalp surface interpolation

                            vertxcolor = DisplayStruct.TopoPlot(k).Wmat{iSet}*Disp.TimeSeries{iSet}(data.Measures.Display.SelectedChannels{k},tindx);
                            set(DisplayStruct.TopoPlot(k).surf{iSet},'FaceVertexCData',vertxcolor);

                        case 5 % 2D Disc

                            if datatype == 1
                                CData = DisplayStruct.TopoPlot(k).Wmat{iSet} * Disp.TimeSeries{iSet}(data.Measures.Display.SelectedChannels{k},tindx);
                                CData = reshape(CData,sqrt(length(CData)),sqrt(length(CData)));
                                CData = CData * max(abs(Disp.TimeSeries{iSet}(data.Measures.Display.SelectedChannels{k},tindx)))/max(abs(CData(:))); % properly rescale to data amplitude
                            elseif datatype == 2
                                F = data.Results.IndepTopo(:,iSet)*data.Results.TimeSeries(:,iSet)';
                                CData = DisplayStruct.TopoPlot(k).Wmat{iSet} * F(:,tindx);
                                CData = reshape(CData,sqrt(length(CData)),sqrt(length(CData)));
                                CData = CData * max(abs(F(:,tindx)))/max(abs(CData(:))); % properly rescale to data amplitude
                            end

                            set(DisplayStruct.TopoPlot(k).surf{iSet},'CData',CData)

                            if data.Measures.Display.Flags.ShowContours % Add contour plot
                                axes(DisplayStruct.TopoPlot(k).axes{iSet});
                                delete(DisplayStruct.TopoPlot(k).Contour{iSet}.H(ishandle(DisplayStruct.TopoPlot(k).Contour{iSet}.H))); % CBB - how is that I need to check for ishandle here ? (SB 15-Mar-2004)
                                [DisplayStruct.TopoPlot(k).Contour{iSet}.C,DisplayStruct.TopoPlot(k).Contour{iSet}.H] = contour(DisplayStruct.TopoPlot(k).Yo{iSet},DisplayStruct.TopoPlot(k).Xo{iSet},CData,'w-');
                            end

                        end

                        if iSet == 1
                            if datatype == 1
                                for kk = 1:length(Disp.TimeSeries)
                                    for kkk = 1:3
                                        if ~isempty(data.Measures.Display.SelectedChannels{kkk})
                                            tmp.Fmax(kk,kkk) = max(max(abs(Disp.TimeSeries{kk}(data.Measures.Display.SelectedChannels{kkk},:))));
                                        else
                                            tmp.Fmax(kk,kkk) = 0;
                                        end
                                    end
                                end
                                maxData(k) = max(tmp.Fmax(:,k));

                            elseif datatype == 2
                                if iSet == 1 %&~OPTIONS.AbsoluteColormap
                                    % Compute absolute maximum of surface topography for all sources
                                    Topo_maxx = max(max(abs(data.Results.IndepTopo*data.Results.TimeSeries')));
                                end
                                maxData(k) = Topo_maxx;
                            end

                        end

                        % Colormapping : Absolute | Relative ?
                        CData  = get(DisplayStruct.TopoPlot(k).surf{iSet},'CData');

                        if data.Measures.Display.Flags.AbsoluteColormap
                            tmp = max(abs(CData(:)));
                            set(DisplayStruct.TopoPlot(k).axes{iSet},'CLim',[-tmp tmp]); clear tmp
                        else
                            set(DisplayStruct.TopoPlot(k).axes{iSet},'CLim',[-maxData(k) maxData(k)]);
                        end

                        % Colorbar management
                        data.Measures.Display.Colormap = ...
                            get(data.Measures.Display.Handles.Figures.TimeSeries,'Colormap');

                        if ishandle(DisplayStruct.TopoPlot(k).Colorbar{iSet}) ...
                                & data.Measures.Display.Flags.Colorbar

                            % Store colormap and Clim (possibly edited using COLORMAPEDITOR)
                            tmp = get(DisplayStruct.TopoPlot(k).axes{iSet},'CLim');

                            if k == 1
                                tmp = tmp/1e-15; % fT
                            else
                                tmp = tmp/1e-6; % microV
                            end

                            m = num2str(tmp(2),2);
                            [m,e] = strtok(m,'e');
                            e = str2num(['1',e]);
                            m = str2num(m);

                            tmp2 = linspace(-m*e,m*e,3)';
                            tmp2(abs(tmp2)<0.001) = 0;
                            YtickLabel = num2str(tmp2,'%3.0f');

                            a = get(DisplayStruct.TopoPlot(k).Colorbar{iSet},'Children');
                            set(DisplayStruct.TopoPlot(k).Colorbar{iSet},'XTickLabel',YtickLabel,'Visible','on')

                        else

                            set(DisplayStruct.TopoPlot(k).Colorbar{iSet},'Visible','off');

                        end

                    end

                    % Is scalp surface superimposed to cortical surface ?
                    if isfield(data,'Results')
                        if isfield(data.Results,'Display')
                            if isfield(data.Results.Display.Handles,'TopoPlot')
                                if ishandle(data.Results.Display.Handles.TopoPlot(k).surf{iSet}) % If yes - then update facevertexcolor
                                    %vertxcolor = data.Results.Display.Handles.TopoPlot(k).Wmat{iSet}*Disp.TimeSeries{iSet}(data.Measures.Display.SelectedChannels{k},tindx);
                                    vertxcolor = data.Results.Display.Handles.TopoPlot(k).Wmat{iSet}*...
                                        data.Results.IndepTopo(:,iSet)*data.Results.TimeSeries(tindx,iSet)';
                                    switch(get(data.Results.Display.Handles.TopoPlot(k).surf{iSet},'Type'))
                                    case 'surface'
                                        vertxcolor = reshape(vertxcolor,sqrt(length(vertxcolor)),sqrt(length(vertxcolor)));
                                        set(data.Results.Display.Handles.TopoPlot(k).surf{iSet},'CData',vertxcolor);
                                    case 'patch'
                                        set(data.Results.Display.Handles.TopoPlot(k).surf{iSet},'FaceVertexCData',vertxcolor);
                                    end

                                end
                            end
                        end
                    end

                    % Update time display
                    set(DisplayStruct.TopoPlot(k).timeText{iSet},'string',sprintf('%3.1f ms',1000*timeTmp(tindx)))

                end % For each dataset

            end % if TopoType >1

            set(hDataplot.current_time,'String',sprintf('%3.2f',1000*timeTmp(tindx)))

            if datatype == 1
                data.Measures.Display.Handles = DisplayStruct;
                %rotate3d(data.Measures.Display.Handles.Figures.TimeSeries,'off')
                view3d(data.Measures.Display.Handles.Figures.TimeSeries,'off')
            elseif datatype == 2
                if struuct == 3 % Cortical display
                    data.Results.Display.Handles = DisplayStruct;
                    view3d(data.Results.Display.Handles.Figures.Surfaces,'rot')
                    %rotate3d(data.Results.Display.Handles.Figures.Surfaces,'on')
                elseif struuct == 2 % Scout time series
                    data.Results.Display.Scouts.Handles = DisplayStruct;
                    %rotate3d(data.Results.Display.Handles.Figures.TimeSeries,'off')
                    view3d(data.Results.Display.Handles.Figures.TimeSeries,'off')
                end
            end

        end % For data and maybe result display

        % Source Viewing Update
        if noResults
            % no results loaded yet
            return

        end
        if ~isfield(data.Results.Display.Handles,'hPatch') % No cortical map displayed yet
            return
        end

        if ishandle(data.Results.Display.Handles.hPatch) % surface handle for result display is valid
            if isempty(data.Results.ImageGridAmp), return, end % CBB - make dipole size change over time
            data.Results.Display.OPTIONS.Time = tindx;
            data.Results.Display.OPTIONS.timeValue = dataplot_cb('GET','current_time');
            data.Results.Display.OPTIONS.hPatch = data.Results.Display.Handles.hPatch;
            data.Results.Display.OPTIONS.hLights = data.Results.Display.Handles.hLights;
            [tmp,OPTIONS] = bst_imaging_display(data.Results.ImageGridAmp,data.Results.Display.OPTIONS); clear tmp
            view3d(data.Results.Display.Handles.Figures.Surfaces,'rot')         %rotate3d(data.Results.Display.Handles.Figures.Surfaces,'on')
        end

        % Source Viewing Update <- DONE

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

    case 'NewColormap'
        % Change properties of current colormap - from Matlab 6.5 only
        try
            colormapeditor;
        catch
            errordlg('Matlab 6.5 or greater is requested for colormap editing.','Older Matlab version')
            return
        end

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

    case 'saveColormap'
        % Save current colormap to disk

        % Move to Custom folder by default
        cd(fullfile(getpref('BrainStorm','brainstormHomeDir'),'Custom'))

        [FILENAME, PATHNAME, FILTERINDEX] = uiputfile('*.mat', 'Save colormap as...');
        if (FILENAME)==0, return, end
        Colormap = data.Measures.Display.Colormap;
        save(fullfile(PATHNAME,FILENAME),'Colormap')

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

    case 'loadColormap'
        % Save current colormap to disk

         % Move to Custom folder by default
         cd(fullfile(getpref('BrainStorm','brainstormHomeDir'),'Custom'))

        [FILENAME, PATHNAME, FILTERINDEX] = uigetfile('*.mat', 'Load colormap file ...');
         if (FILENAME) ==0, return, end
         load(fullfile(PATHNAME,FILENAME),'Colormap')
         if ~exist('Colormap','var'), errordlg('Not a valid BrainStorm colormap. Colormap arry needs to be saved under variable name : ''Colormap''.'), return, end
         data.Measures.Display.Colormap = Colormap;
         set(data.Measures.Display.Handles.Figures.TimeSeries,'Colormap',Colormap);

        %----------------------------------------------------------------------------
    case 'GenerateMovie' % Generate a movie of surface plots (Measures & Results) within specified time window

        % Where to store the AVI movie file ?
        Users = get_user_directory;
        datafile=bst_static_taskbar('GET','DATA');
        cd(fullfile(Users.STUDIES,fileparts(datafile{1})))

        [moviefile, moviepath] = uiputfile('*.avi', 'Save Movie File as...');
        if moviefile == 0, return, end
        cd(moviepath)

        % Is there a spatial Results display window opened ?
        if isfield(data,'Results')
            if ishandle(data.Results.Display.Handles.Figures.Surfaces) % Surface display
                % Set of results figures to get frames from
                resFigures = [data.Results.Display.Handles.Figures.Surfaces];
            end
        else
            resFigures = [];
        end

        % Movie parameters
        % Short input dialog
        prompt={'Frame(s) per second: ','Quality [0,100]: '};
        def={'1','100'};
        dlgTitle='Enter movie parameters';
        lineNo=1;
        answer=inputdlg(prompt,dlgTitle,lineNo,def);

        % Now generate movie
        Movie = avifile(moviefile,'FPS',max([1,round(answer{1})]),'QUALITY',round(answer{2}),'compression','None');
        if ~isempty(resFigures)
            resMovieFile = strrep(moviefile,'.avi','_surf.avi');
            resMovie = avifile(resMovieFile,'FPS',max([1,round(answer{1})]),'QUALITY',round(answer{2}),'compression','None');
            bst_message_window(...
                {'Cortical surface movie :',...
                    resMovieFile});
        end

        % Get time window
        timeWin = dataplot_cb('GET','time'); % [start,step,stop]
        timeWin = [data.Display.Time(1):data.Display.SamplingRate:data.Display.Time(2)];
        % Find time samples in original data array

        bst_message_window(...
            {'Starting shooting of movie . . .',...
            moviefile});

        % Loop on all time samples
        for n = timeWin
            % Update and set current time
            dataplot_cb('SET','time',n);
            drawnow
            if ishandle(data.Measures.Display.Handles.Figures.TimeSeries) % Measures display
                Frame = getframe(data.Measures.Display.Handles.Figures.TimeSeries);
                Movie = addframe(Movie,Frame);
            end
            if ~isempty(resFigures)
                if ishandle(data.Results.Display.Handles.Figures.Surfaces)
                    Frame = getframe(data.Results.Display.Handles.Figures.Surfaces);
                    resMovie = addframe(resMovie,Frame);
                end
            end

        end

        Movie = close(Movie);
        if exist('resMovie','var')
            resMovie = close(resMovie);
            % Play movie
            aviplayer(fullfile(moviepath,resMoviefile));
        end

        % Play movie
        aviplayer(fullfile(moviepath,moviefile));

        bst_message_window(...
            {'-> DONE ',...
                ' '});
        %----------------------------------------------------------------------------
    case 'aviplayer' % Load an .avi movie file and play it

        aviplayer % Call third-party routine in PublicToolbox
        %----------------------------------------------------------------------------

    case 'GenerateSlides' % Generate a contact sheet of surface plots (Measures & Results) within specified time window

        % Get selected time window
        timeWin = dataplot_cb('GET','time');
        timeWin = [timeWin(1):timeWin(2):timeWin(3)];

        % Number of columns and rows on contact sheet.
        ncol = ceil(sqrt(length(timeWin)));
        nrow = ncol;

        % Is there a spatial Results display window opened ?
        if isfield(data,'Results')
            if isfield(data.Results,'Display')
                if ishandle(data.Results.Display.Handles.Figures.Surfaces) % Surface display
                    % Set of results figures to get frames from
                    resFigures = [data.Results.Display.Handles.Figures.Surfaces];
                end
            end
        else
            resFigures = [];
        end

        bst_message_window(...
            {'Preparing contact sheet . . .'});

        % Loop on all time samples
        iplot = 0;
        for n = timeWin
            iplot = iplot+1;
            % Update and set current time
            dataplot_cb('SET','time',n);
            drawnow
            if ishandle(data.Measures.Display.Handles.Figures.TimeSeries) % Measures display

                if n == timeWin(1) % Create figure
                    data.Measures.Display.Handles.Figures.ContactSheet = figure;
                    setappdata(data.Measures.Display.Handles.Figures.ContactSheet,'TileType','T')
                    bst_color_scheme(data.Measures.Display.Handles.Figures.ContactSheet);
                    bst_layout('align',data.Measures.Display.Handles.Figures.ContactSheet,2,2,1)

                    figAxes = data.Measures.Display.Handles.TopoPlot(data.Measures.Display.Modality(1)).axes{1}; % CBB | only one dataset and one modality
                    set( data.Measures.Display.Handles.Figures.ContactSheet,'visible','on','colormap',data.Measures.Display.Handles.Colormap,...
                        'menubar','figure','NumberTitle','on','Name','Copy')

                end

                figure(data.Measures.Display.Handles.Figures.ContactSheet)
                cAxes =  subplot(ncol,nrow,iplot); % Current axes
                set(cAxes,'View',get(figAxes,'View'))
                axis equal, axis vis3d
                axis off
                C = copyobj(figAxes,data.Measures.Display.Handles.Figures.ContactSheet);
                child = get(C,'Children');
                set(child,'parent',cAxes),
                textObject = [];
                textObject(1) = findobj(child','string','MEG');
                textObject = [textObject,findobj(child','string','EEG')];
                linesObject = findobj(child','Type','line');
                delete(unique([textObject,linesObject'])) % CBB | pb is that it also deletes contour lines when present
                delete(C)

            end

            if ~isempty(resFigures)
                if ishandle(data.Results.Display.Handles.Figures.Surfaces)

                    if n == timeWin(1) % Create figure
                        data.Results.Display.Handles.Figures.ContactSheet = figure;
                        setappdata(data.Results.Display.Handles.Figures.ContactSheet,'TileType','T')
                        bst_color_scheme(data.Results.Display.Handles.Figures.ContactSheet);
                        bst_layout('align',data.Results.Display.Handles.Figures.ContactSheet,2,2,3)

                       resfigAxes = findobj(data.Results.Display.Handles.Figures.Surfaces,'Type','axes');
                        set( data.Results.Display.Handles.Figures.ContactSheet,'visible','on','colormap',data.Measures.Display.Handles.Colormap,...
                            'menubar','figure','NumberTitle','on','Name','Copy')

                    end
                    figure(data.Results.Display.Handles.Figures.ContactSheet)
                    cAxes =  subplot(ncol,nrow,iplot); % Current axes
                    set(cAxes,'View',get(resfigAxes,'View'))
                    axis equal, axis vis3d
                    axis off
                    C = copyobj(resfigAxes,data.Results.Display.Handles.Figures.ContactSheet);
                    child = get(C,'Children');
                    set(child,'parent',cAxes),
                    delete(C)
                    linesObject = findobj(child','Type','line');
                    delete(linesObject') % CBB | pb is that it also deletes contour lines when present
                end
            end

        end

        set( data.Measures.Display.Handles.Figures.ContactSheet,'visible','on','colormap',data.Measures.Display.Handles.Colormap,...
            'menubar','figure','NumberTitle','on','Name','Contact Sheet')

        bst_message_window(...
            {'-> DONE ',...
                ' '});

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

    case 'CallDataSelector' % just like it sounds....
        % Define noise model (covariance statistics and signal vs. source subspaces)

        figP = parametric_estimation;
        figP_handles = guihandles(figP);
        % decompose the data
        parametric_estimation('Pushbutton_decompose_Callback',...
            figP_handles.Pushbutton_decompose,[],figP_handles);

        %parametric_estimation % Call John's routine

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

    case 'set_current_time'

        ctime = str2num(get(hDataplot.current_time,'String'))/1000;

        set(hDataplot.TimeSlider,'Value',ctime);
        dataplot_cb mapping_slider

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

    case 'Residuals'
        Visu = get(DATAPLOT,'Userdata');

        tesselation_select_win = findobj(0,'Tag','tesselation_select');
        if isempty(tesselation_select_win)
            tesselation_select_win = open('tessellation_select.fig');
        end
        handles = guihandles(tesselation_select_win);

        ResFiles = get(handles.ResultFiles,'String');
        ResFile = ResFiles{get(handles.ResultFiles,'Value')};
        [path,file,ext] = fileparts(Users.CurrentData.StudyFile);
        ResFile = fullfile(Users.STUDIES,path,ResFile);
        load(ResFile,'Fsynth','OPTIONS','ImageGridTime');
        if ~exist('OPTIONS','var') % File is from older version (i.e. before MMII)
            load(ResFile,'GUI')
            OPTIONS = GUI; clear GUI
            OPTIONS.SegmentIndices = OPTIONS.Segment;
            OPTIONS = rmfield(OPTIONS,'Segment');
        end

        if ~isempty(find(Visu.Data.ChannelFlag == -1))%~isempty(find(Visu.Data.ChannelFlag == 0))
            goodchannels = good_channel(Visu.Channel,Visu.Data.ChannelFlag,DataType{current}); % Discard bad channels
            badchannels = setdiff(good_channel(Visu.Channel,ones(length(Visu.Channel),1),DataType{current}),goodchannels);
            %      goodchannels = setdiff(Visu.ChannelID{current},find(Visu.Data.ChannelFlag == -1)); % - min(Visu.ChannelID{current})+1; % Discard bad channels
            %badchannels = intersect(Visu.ChannelID{current},find(Visu.Data.ChannelFlag == -1));% - min(Visu.ChannelID{current})+1;
        else
            goodchannels = Visu.ChannelID{current};% - min(Visu.ChannelID{current})+1;
            badchannels = [];
        end

        %F = Visu.Data.F(goodchannels,[OPTIONS.SegmentIndices(1):OPTIONS.SegmentIndices(end)]); % Try next line instead
        F = Visu.Data.F(goodchannels,OPTIONS.SegmentIndices);
        Fsynth = Fsynth(goodchannels-goodchannels(1)+1,:);
        res = 100*sqrt(norcol(F-Fsynth)./norcol(F)); % NORCOL computes the square of the columns of matrix

        clear Results;
        mean_res = mean(res);
        std_res = std(res);
        min_res = min(res);
        max_res = max(res);

        figres = figure; % Overlay Residuals and normalized global field power plots
        %powF = norm(F,'fro');
        GFP = sqrt(norcol(F));
        GFP = 100*GFP/max(GFP);
        %[haxes, hline1,hline2] = plotyy(1000*ImageGridTime,res,1000*ImageGridTime,100*(norcol(F))/powF);
        [haxes, hline1,hline2] = plotyy(1000*ImageGridTime,res,1000*ImageGridTime,GFP);
        hold on
        axes(haxes(1))
        set(haxes(1),'Ycolor','r')
        set(hline1,'linewidth',2)
        xlabel('Time (ms)');
        ylabel('Residuals (%)');

        axes(haxes(2))
        set(haxes(2),'Ycolor','b')
        xlabel('Time (ms)');
        ylabel('GFP (normalized)');
        grid on
        set(hline1,'Color','r')
        set(hline2,'Color','b')
        grid on

        fprintf(...
            'Residuals\nAverage: %4.2f%%\nStd.:%4.2f%%\nMin.: %4.2f%%\nMax.: %4.2f%%\n',mean_res,std_res,min_res,max_res);

        set(figres,'Name','Residuals / GFP')
        set(get(figres,'CurrentAxes'),'XGrid','on','YGrid','on')

        %----------------------------------------------------------------------------
    case 'LoadResultFile' % Load selected Result File parameters for source visualization
        tesselation_select_win = findobj(0,'Tag','tesselation_select');

        if isempty(tesselation_select_win)
            tesselation_select_win = open('tessellation_select.fig');
        end
        handles = guihandles(tesselation_select_win);

        set(tesselation_select_win,'Pointer','watch'),drawnow

        set(handles.ZScore,'Value',0)
        togglebuttoncolor(handles.ZScore)

        if nargin == 1
            ResFiles = get(handles.ResultFiles,'String');
            ResFile = ResFiles{get(handles.ResultFiles,'Value')};
        else % A result file is specified
            ResFile = varargin{1};
        end

        [path,file,ext] = fileparts(Users.CurrentData.StudyFile);
        ResFile = fullfile(Users.STUDIES,path,ResFile);
        Results = load(ResFile);
        Results.ImageGridAmp = double(Results.ImageGridAmp); % Stored in single precision in MMII version
        % Convert older Results structure to MMII
        if isfield(Results,'GUI');
            Results = setfield(Results,'OPTIONS',Results.GUI);
            Results = rmfield(Results,'GUI');
        end
        set(handles.Refresh,'Userdata',ResFile)

        if isfield(Results,'ZScore')
            set(handles.Baseline,'Userdata',1) ; % Enforce Baseline application
            if get(handles.Baseline,'Userdata') == 0 % This if switch should therefore be optional from now on: need to check this when updating the next dataplot
                try
                    set(handles.Baseline,'String',num2str(1000*(Results.ZScore.BaselineTime),'%4.2f '));
                    if isfield(Results.ZScore,'BaselineFile')
                        disp(['ZScore available - baseline taken from file: ',strrep(Results.ZScore.BaselineFile,Users.STUDIES,'')])
                    else
                        disp(['ZScore available - baseline was set to: ', num2str(1000*Results.ZScore.BaselineTime,'%4,2f '),' ms'])
                    end

                catch
                    set(handles.Baseline,'String','File');
                end

            elseif (get(handles.Baseline,'Userdata')) == 1
                set(handles.Baseline,'String','File');
                if isfield(Results.ZScore,'BaselineFile')
                    disp(['ZScore available - baseline taken from file: ',Results.ZScore.BaselineFile])
                else
                    disp(['ZScore available - baseline was set to: ', num2str(1000*Results.ZScore.BaselineTime,'%4,2f '),' ms'])
                end
            end
        end

        %Load Associated Data File
        cd(fullfile(Users.STUDIES,path))
        ResFiletmp = strrep(ResFile,Users.STUDIES,'');
        ResFiletmp = strrep(ResFiletmp,'.mat','');
        Iunder = findstr(ResFiletmp,'_');
        DataFile= [ResFiletmp(1:Iunder(end-1)-1),'.mat'];

        if exist(DataFile,'file')
            dataplot_cb('loadfile',[DataFile]);
        end

        set(handles.ResultFiles,'Userdata',Results); % Save in GUI for future use
        nSources = length(Results.SourceLoc);
        if nSources == 0 | ischar(Results.SourceLoc) % Probably an ImageGrid file
            nSources  = size(Results.ImageGridAmp,1);
            BeginTime = Results.ImageGridTime(1)*1000;
            EndTime = Results.ImageGridTime(end)*1000;
            set(handles.CorticalMap,'enable','on') % Allo20w visualization of cortical current density maps
        else
            BeginTime = [];
            EndTime = [];
            set(handles.CorticalMap,'enable','off')
        end

        DATA = {'MEG','EEG'};

        if ~isfield(Results,'ZScore')
            ResultFileParamString= sprintf('%s\nNumber of Sources: %d\nTime window: %3.1f %3.1f msec',...
                Results.Comment,nSources,BeginTime,EndTime);
        else
            if ~isempty(Results.ZScore.BaselineFile)
                [tmp,tmpfile,ext] = fileparts(Results.ZScore.BaselineFile);
                BaselineTime = load(Results.ZScore.BaselineFile,'ImageGridTime');
                set(handles.LoadBaseline,'Userdata',Results.ZScore.BaselineFile)
                Results.ZScore.BaselineTime = [BaselineTime.ImageGridTime(1) BaselineTime.ImageGridTime(end)]; clear BaselineTime

                ResultFileParamString= sprintf(...
                    '%s-%s\nNumber of Sources: %d\nTime window: %3.1f %3.1f msec\nZScore done: baseline from file:\n%s\n%4.1f to %4.1f ms',...
                    Results.Comment,DATA{Results.OPTIONS.DataType},nSources,BeginTime,EndTime,tmpfile,1000*(Results.ZScore.BaselineTime));

            else
                ResultFileParamString= sprintf(...
                    '%s-%s\nNumber of Sources: %d\nTime window: %3.1f %3.1f msec\nZScore done: baseline set to\n%4.1f to %4.1f  ms',...
                    Results.Comment,DATA{Results.OPTIONS.DataType},nSources,BeginTime,EndTime,1000*(Results.ZScore.BaselineTime));
            end
        end

        set(handles.ResultFileParam,'String',ResultFileParamString)

        % Find the corresponding tessellated envelope in the list
        nsrc = size(Results.ImageGridAmp,1); % Number of cortical sources
        % Is there a cortical surface available qith the same number of sources ?
        Visu = get(DATAPLOT,'Userdata');
        try % MMII procedure

            load(Results.OPTIONS.GridLoc,'Vertices','Comment')
            nmesh = max(size(Vertices));
            Vals = [ones(nmesh,1),zeros(nmesh,7)];
            set(handles.removed,'Userdata',Vals)
            clear Vertices
            iCortex = Results.OPTIONS.iGrid;
            Visu.Tesselation = Results.OPTIONS.GridLoc;
            set(DATAPLOT,'UserData',Visu)

        catch % Older BsT Version

            try
                load(fullfile(Users.SUBJECTS,Visu.Tesselation),'Vertices','Comment')
            catch
                load(Visu.Tesselation,'Vertices','Comment')
            end
            for k = 1:length(Vertices)
                nverts(k) = size(Vertices{k},2);
            end
            iCortex = find(nverts == nsrc);
            if isempty(iCortex)
                errordlg('No corresponding cortical surface was found among the available tessellated surfaces')
                return
            elseif length(iCortex)>1
                msgbox('Several tessellated surfaces may be corresponding to this result file. Please select the proper one manually')
                return
            end

        end

        % Find the cortical surface is the list and mark it as selected

        set(handles.removed,'String',Comment{iCortex})
        set(handles.available,'String',Comment(setdiff(1:length(Comment),iCortex)))

        set(handles.CorticalMap,'Value',1);
        Green = [.66 1 .43];
        Dark = [.4 .4 .4];
        set(handles.CorticalMap,'Backgroundcolor',Green,'Foregroundcolor',Dark)

        set(tesselation_select_win,'Pointer','arrow')

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

    case 'mesh_props' % Indicate Mesh Surface Properties with Radiobuttons
        Visu = get(DATAPLOT,'Userdata');
        %   eval(['load ',Visu.Tesselation,' Comment'])
        cd(Users.SUBJECTS)
        load(Visu.Tesselation)

        nmesh = max(size(Comment));

        tesselation_select_win = findobj(0,'Tag','tesselation_select');
        available = findobj(tesselation_select_win,'Tag','available');
        removed =  findobj(tesselation_select_win,'Tag','removed');
        removeID = get(gcbo,'Value');
        IDs = get(gcbo,'String');
        mesh_names = IDs(removeID);
        %     current_surface = findobj(tesselation_select_win,'Tag','current_surface');
        %  set(current_surface,'String',mesh_names{1});

        OPAQUE = findobj(gcbf,'Tag','Opaque');
        TRANSPARENT = findobj(gcbf,'Tag','transparent');
        RIGHT = findobj(tesselation_select_win,'Tag','right');
        LEFT = findobj(tesselation_select_win,'Tag','left');
        FRONT = findobj(tesselation_select_win,'Tag','front');
        BACK = findobj(tesselation_select_win,'Tag','back');
        TOP = findobj(tesselation_select_win,'Tag','top');
        BOTTOM = findobj(tesselation_select_win,'Tag','bottom');

        if length(removeID)>1
            return
        end

        % Identification of the active mesh surfaces
        for i = 1:length(removeID)
            imesh(i) = find(strcmp(mesh_names{i},Comment));
        end

        if length(imesh)== 1
            set(findobj(gcbf,'Tag','faces'),'string',[int2str(size(Faces{imesh},1)),' Faces'])
            set(findobj(gcbf,'Tag','vertices'),'string',[int2str(size(Vertices{imesh},2)), ' Vertices'])
            if ~strcmp(get(gcbo,'Tag'),'removed'); return, end
        end

        Vals = get(removed,'Userdata');
        if isempty(Vals)
            Vals = [ones(nmesh,1),zeros(nmesh,7)];
        else
            HANDLES = [OPAQUE TRANSPARENT RIGHT LEFT FRONT BACK TOP BOTTOM];
            for k = 1:length(HANDLES)
                set(HANDLES(k),'Value',Vals(imesh,k));
            end
        end

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

    case 'mesh_vals' % Indicate Mesh Surface Properties with Radiobuttons
        Visu = get(DATAPLOT,'Userdata');
        try
            eval(['load ',Visu.Tesselation,' Comment'])
        catch
            cd(Users.SUBJECTS)
            eval(['load ',Visu.Tesselation,' Comment'])
        end

        nmesh = max(size(Comment));

        tesselation_select_win = findobj(0,'Tag','tesselation_select');
        available = findobj(tesselation_select_win,'Tag','available');
        removed =  findobj(tesselation_select_win,'Tag','removed');
        removeID = get(removed,'Value');
        IDs = get(removed,'String');
        if iscell(IDs)
            mesh_names = IDs(removeID);
        else
            mesh_names  = IDs;
        end

        current_surface = findobj(tesselation_select_win,'Tag','current_surface');
        %     set(current_surface,'String',mesh_names{1});

        OPAQUE = findobj(gcbf,'Tag','Opaque');
        TRANSPARENT = findobj(gcbf,'Tag','transparent');
        RIGHT = findobj(tesselation_select_win,'Tag','right');
        LEFT = findobj(tesselation_select_win,'Tag','left');
        FRONT = findobj(tesselation_select_win,'Tag','front');
        BACK = findobj(tesselation_select_win,'Tag','back');
        TOP = findobj(tesselation_select_win,'Tag','top');
        BOTTOM = findobj(tesselation_select_win,'Tag','bottom');

        % Identification of the active mesh surfaces
        if ~iscell(mesh_names)
            imesh = find(strcmp(mesh_names,Comment));
        else
            for i = 1:length(removeID)
                imesh(i) = find(strcmp(mesh_names{i},Comment));
            end
        end

        Vals = get(removed,'Userdata');
        if 0%isempty(Vals)
            Vals = [ones(nmesh,1),zeros(nmesh,7)];
        else
            HANDLES = [OPAQUE TRANSPARENT RIGHT LEFT FRONT BACK TOP BOTTOM];
            tmp = get(HANDLES,'Value');
            Vals(imesh,:) = [tmp{:}];
        end

        set(removed,'Userdata',Vals)

        %----------------------------------------------------------------------------
    case 'ConcatenateTess' % Concatenate 2 selected envelopes into 1
        tesselation_select_win = findobj(0,'Tag','tesselation_select');
        Visu = get(DATAPLOT,'Userdata');
        removed =  findobj(tesselation_select_win,'Tag','removed');
        removeID = get(removed,'Value');

        IDs = get(removed,'String');
        if isempty(IDs)
            return
        end

        mesh_names = IDs(removeID);
        eval(['load ',Visu.Tesselation,' Comment'])

        nmesh = max(size(Comment));

        % Identification of the active mesh surfaces
        for i = 1:length(removeID)
            imesh{i} = find(strcmp(mesh_names{i},Comment));
        end

        if length(imesh) >2
            errordlg('Cannot concatenate more than 2 envelopes yet') % CHEAT - need to generalize this
            return
        end

        load(Visu.Tesselation,'Faces','Vertices')
        Vertices{end+1} = [Vertices{imesh{1}},Vertices{imesh{2}}]  ;
        Faces{end+1} = [Faces{imesh{1}}; Faces{imesh{2}}+size(Vertices{imesh{1}},2)];
        Comment{end+1} = [Comment{imesh{1}},Comment{imesh{2}}]  ;

        save(Visu.Tesselation,'Faces','Vertices','Comment','-append')

        dataplot_cb mesh_rendering

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

    case 'SwapFaces' % Swap vertex ordering for face definition as some pacthes normal may happen to be oriented inwards and therefore look dark in 3d

        tesselation_select_win = findobj(0,'Tag','tesselation_select');
        Visu = get(DATAPLOT,'Userdata');
        removed =  findobj(tesselation_select_win,'Tag','removed');
        removeID = get(removed,'Value');

        IDs = get(removed,'String');
        if isempty(IDs)
            return
        end

        mesh_names = IDs(removeID);
        eval(['load ',Visu.Tesselation,' Comment'])

        nmesh = max(size(Comment));

        % Identification of the active mesh surfaces
        for i = 1:length(removeID)
            imesh{i} = find(strcmp(mesh_names{i},Comment));
        end

        if length(imesh) > 1
            errordlg('Cannot swap vertices of more than 1 envelope yet') % CHEAT - need to generalize this
            return
        end

        load(Visu.Tesselation,'Faces')

        Faces{imesh{1}} = Faces{imesh{1}}(:,[2 1 3]);

        save(Visu.Tesselation,'Faces','-append')

        dataplot_cb mesh_rendering

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

    case 'RenameTess' % Edit the Comment (ie label) of selected envelope

        tesselation_select_win = findobj(0,'Tag','tesselation_select');
        Visu = get(DATAPLOT,'Userdata');
        removed =  findobj(tesselation_select_win,'Tag','removed');
        removeID = get(removed,'Value');

        IDs = get(removed,'String');
        if isempty(IDs)
            return
        end

        mesh_names = IDs(removeID);
        eval(['load ',Visu.Tesselation,' Comment'])

        nmesh = max(size(Comment));

        % Identification of the active mesh surfaces
        for i = 1:length(removeID)
            imesh{i} = find(strcmp(mesh_names{i},Comment));
        end

        if length(imesh) > 1
            errordlg('Cannot rename more than 1 envelope yet') % CHEAT - need to generalize this
            return
        end

        newComment = inputdlg('Please enter a new label for the selected envelope');
        if isempty(newComment)
            return
        end

        Comment{imesh{1}} = newComment{:};

        save(Visu.Tesselation,'Comment','-append')

        dataplot_cb mesh_rendering

        %----------------------------------------------------------------------------
    case 'DownsizeTess'
        tesselation_select_win = findobj(0,'Tag','tesselation_select');
        Visu = get(DATAPLOT,'Userdata');
        removed =  findobj(tesselation_select_win,'Tag','removed');
        removeID = get(removed,'Value');

        IDs = get(removed,'String');
        if isempty(IDs)
            return
        end

        mesh_names = IDs(removeID);
        eval(['load ',Visu.Tesselation,' Comment'])

        nmesh = max(size(Comment));

        % Identification of the active mesh surfaces
        for i = 1:length(removeID)
            imesh{i} = find(strcmp(mesh_names{i},Comment));
        end

        if length(imesh) > 1
            errordlg('Cannot swap vertices of more than 1 envelope yet') % CHEAT - need to generalize this
            return
        end

        load(Visu.Tesselation,'Faces','Vertices')

        handles = guihandles(tesselation_select_win);
        nfv.faces = Faces{imesh{1}};
        nfv.vertices = Vertices{imesh{1}}';

        set(tesselation_select_win,'Pointer','watch')
        NFV = reducepatch(nfv, str2num(get(handles.DownsizeFactor,'String')));

        clear nfv
        Faces{end+1} = NFV.faces;
        Vertices{end+1} = NFV.vertices';
        clear NFV
        Comment{end+1} = [Comment{imesh{1}},'_',get(handles.DownsizeFactor,'String')];

        save(Visu.Tesselation,'Faces','Comment','Vertices', '-append')

        dataplot_cb mesh_rendering

        set(tesselation_select_win,'Pointer','arrow')
        %----------------------------------------------------------------------------
    case 'mesh_add' % Add a meshed surface to visualization
        Visu = get(DATAPLOT,'Userdata');
        load(Visu.Tesselation)
        nmesh = max(size(Vertices));

        tesselation_select_win = findobj(0,'Tag','tesselation_select');
        available = findobj(tesselation_select_win,'Tag','available');
        removed =  findobj(tesselation_select_win,'Tag','removed');
        removeID = get(available,'Value');

        %Check if it's a double-click
        old_available = get(available,'Userdata');
        if isempty(old_available) | old_available ~= removeID % Single Click
            set(available,'Userdata',removeID)
            return
        else
            set(available,'Userdata',[])
        end

        IDs = get(available,'String');
        if isempty(IDs), return, end
        chan = 1:length(get(available,'String'));

        set(available,'String', IDs(setdiff(chan,removeID)));
        if isempty(get(removed,'String'))
            set(removed,'String', IDs(removeID));
        else
            strtmp = (get(removed,'String'));
            strtmp(end+1:end+length(IDs)) = IDs(removeID) ;
            set(removed,'String', sort(unique(strtmp)));
        end
        set(available,'String', IDs(setdiff(chan,removeID)));
        set(available,'Value',1,'Max',length(get(available,'String')))
        set(removed,'Value',1,'Max',max([1,length(get(removed,'String'))]))

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

    case 'delete_tess'
        % Update the tessellation file (SubjectTess) by deleting the selected surface tessellation
        tesselation_select_win = findobj(0,'Tag','tesselation_select');
        available = findobj(tesselation_select_win,'Tag','available');
        removed =  findobj(tesselation_select_win,'Tag','removed');
        removeID = get(available,'Value');
        availableID = get(removed,'Value');
        IDs = get(removed,'String');
        if isempty(IDs)
            errordlg('Please select a Tessellation in the ''Active'' listbox')
            return
        end

        mesh_names = IDs(availableID);
        Visu = get(DATAPLOT,'Userdata');
        eval(['load ',Visu.Tesselation,' Comment'])
        nmesh = max(size(Comment));
        % Identification of the active mesh surfaces
        for i = 1:length(availableID)
            imesh{i} = find(strcmp(mesh_names{i},Comment));
        end
        ButtonName=questdlg(['Are you sure you want to delete permanently ',[Comment{[imesh{:}]}],' from the subject tessellation file ?'], ...
            'Warning', ...
            'Yes','No','No');
        switch ButtonName,
        case 'No',
            return
        end

        set(removed,'Value',1)
        set(removed,'String',setdiff(get(removed,'String'),char(Comment{[imesh{:}]})))

        load(Visu.Tesselation)
        tmp = 1:length(Comment);
        Comment = Comment(setdiff(tmp,[imesh{:}]));
        Vertices = Vertices(setdiff(tmp,[imesh{:}]));
        Faces= Faces(setdiff(tmp,[imesh{:}]));

        save(Visu.Tesselation,'Faces','Vertices','Comment','-append')

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

    case 'mesh_lighting_props' % Set lighting to Flat/Gouraud/Phong

        TessWin  = findobj(0,'Tag','tessellation_window'); % Handle to the 3D display
        SlidesWin = findobj(0,'Tag','subplot_tess_window'); % Handle to the Slides or Movie Window
        if ~isempty(SlidesWin)
            TessWin = SlidesWin;
        end

        if isempty(TessWin), return, end
        TessSelect = findobj(0,'Tag','tesselation_select');
        light_props = findobj(TessSelect,'Tag','light_props'); % Handle to the lighting properties pull-down menu
        tmp = get(light_props,'String');

        try
            set(findobj(TessWin,'type','patch'),'edgelighting',tmp{get(light_props,'Value')},...
                'facelighting',tmp{get(light_props,'Value')})

        catch
            if ~isempty(findstr(tmp{get(light_props,'Value')},'Flat'))
                set(findobj(TessWin,'type','patch'),...
                    'facecolor','flat')
            else
                set(findobj(TessWin,'type','patch'),...
                    'facecolor','interp')
            end

        end

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

    case 'mesh_remove' % Remove a mesh surface from visualization
        tesselation_select_win = findobj(0,'Tag','tesselation_select');
        available = findobj(tesselation_select_win,'Tag','available');
        removed =  findobj(tesselation_select_win,'Tag','removed');
        availableID = get(removed,'Value');
        Faces = findobj(tesselation_select_win,'Tag','faces');

        %Check if it's a double-click
        old_removed = get(Faces,'Userdata');
        if isempty(old_removed) | old_removed ~= availableID % Single Click
            set(Faces ,'Userdata',availableID)
            return
        else
            set(Faces ,'Userdata',[])
        end

        IDs = get(removed,'String');
        if isempty(IDs), return, end
        chan = [1:length(IDs)];

        set(removed,'Max',max([1,length(setdiff(chan,availableID))]))
        set(removed,'Value',1,'String',IDs(setdiff(chan,availableID)));

        if isempty(get(available,'String'))
            set(available,'String', [IDs(availableID)]);
        else
            strtmp = (get(available,'String'));
            strtmp(end+1:end+length(IDs)) = IDs(availableID) ;
            set(available,'String', sort(unique(strtmp)));
        end
        set(available,'Value',1,'Max',length(get(available,'String')))

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

    case 'change_color' % Changes the color of the current mesh surface
        Visu = get(DATAPLOT,'Userdata');
        eval(['load ',Visu.Tesselation,' Comment'])
        tesselation_select_win = findobj(0,'Tag','tesselation_select');
        available = findobj(tesselation_select_win,'Tag','available');
        removed =  findobj(tesselation_select_win,'Tag','removed');
        removeID = get(removed,'Value');
        IDs = get(removed,'String');
        mesh_names = IDs(removeID);

        for i = 1:length(removeID)
            imesh(i) = find(strcmp(mesh_names{i},Comment));
        end
        previous  = findobj(0,'Tag','tessellation_window');

        if isempty(previous), return, end

        for k = imesh
            h = findobj(previous,'Tag',Comment{k});
            corig = get(h,'Edgecolor');
            if ischar(corig) % Edgecolor 'none'
                corig = get(h,'FaceVertexCdata');
                iok = find(isfinite(corig(:,1)));
                corig = corig(iok,:);
                corig = corig(1,:);
            else
                iok = [];
            end
            c = uisetcolor(corig, [Comment{k}, ' Color Change']);
            if c == corig, return, end

            ctet = get(h,'vertices');
            vertexcolorh = get(h,'FaceVertexCData');
            siz = size(vertexcolorh,2);
            if size(vertexcolorh ,1) == 1
                vertexcolorh = ones(size(ctet,1),1)*vertexcolorh;
            end
            if 0%size(ctet,1)~=length(iok)
                vertexcolorh(tmp,:) = NaN * ones(length(tmp),siz);
            end

            vertexcolorh(iok,:) = ones(length(iok),1)*c ;
            set(h,'FaceVertexCData',vertexcolorh,'Userdata',c)
            if isempty(iok)
                set(h,'edgecolor',c)
            end

        end

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

    case 'saveas' % Save the new data set as...

        Users = get_user_directory;
        cd(Users.STUDIES)
        [FILENAME, PATHNAME] = uiputfile('*data*mat', 'New File Name');
        if FILENAME == 0, return, end
        cd(PATHNAME)
        Time = linspace(data.Display.Time(1),data.Display.Time(2),length(data.Display.TimeSamples));
        Device = load(data.Measures.Filename{1},'Device');
        [F,Device,ChannelFlag,Time,NoiseCov,SourceCov,Projector,Comment] = ...
            deal(data.Measures.F{1},Device.Device,data.Measures.ChannelFlag,Time,[],[],[],' ');

        save(FILENAME,'Device','ChannelFlag','F','Time','NoiseCov','SourceCov','Projector','Comment');

        I = findstr(FILENAME,['_data']);
        if isempty(I)
            error('File name should contain ''_data'' string ')
            return
        end

        %     channelfile = FILENAME(1:I-1);
        %     channelfile = [channelfile,'_channel'];
        %     Channel = data.Measures.Channel;
        %     save (channelfile,'Channel')

        %----------------------------------------------------------------------------
    case 'create_filter_window'

        fig = openfig('filterGUI.fig','reuse');
        bst_color_scheme(fig);
        setappdata(fig,'TileType','T')
        bst_layout('align',fig,2,2,3);

        BrainStormWindows = bst_win_manager(fig,'filterGUI');

        %----------------------------------------------------------------------------
    case 'ToggleFilter'
        % Toggle filter parameter GUI on/off
        handles = guihandles(gcbf);
        switch(get(gcbo,'Value'))
            case 1
                set([handles.lowpass, handles.highpass],'enable','on')
            case 0
                set([handles.lowpass, handles.highpass],'enable','off')
        end

        %----------------------------------------------------------------------------
    case 'data_filter' % Filter the data and update visualization

        makeuswait('start')

        filterGUI = findobj(0,'Tag','filterGUI');
        handles = guihandles(filterGUI);

           lpf = str2num(get(handles.lowpass,'string'));% Low Cut-off
        hpf = str2num(get(handles.highpass,'string'));% High Cut-off
        AVG = get(handles.avrgREF,'Value'); % Remove average

        current = get_selected_modalities;
        if isempty(current)
            errordlg('Please select either MEG, EEG or Other from taskbar.','No data type selected')
            makeuswait('stop')
            return
        end
        DataType = {'MEG','EEG','Other'};

        goodchannels = good_channel(data.Measures.Channel,data.Measures.ChannelFlag,DataType{current}); % Discard bad channels
        badchannels = setdiff(good_channel(data.Measures.Channel,'',DataType{current}),goodchannels);

        srate = 1/data.Measures.SamplingRate;
        new_waves  = data.Measures.F{1}; % CBB - only one dataset here.

        if get(handles.toggleFilter,'Value') % Filter is ON
            tmp = brainstorm_filt(data.Measures.F{1}(goodchannels,:),srate,hpf,lpf);
            new_waves(goodchannels,:) = tmp; clear tmp
        end

        if(1)
            if AVG & current == 2 % if EEG, Remove average
                new_waves(goodchannels,:) =  new_waves(goodchannels,:) - repmat(mean(new_waves(goodchannels,:)),length(goodchannels),1);
            end
        else
            if AVG == 1 % Remove average in time from each channel
                AVG_MAX = Visu.Data.Time(end)*1000; % milliseconds
                AVG_MIN = Visu.Data.Time(1)*1000;
                prompt={'Enter the starting time (ms)','Enter the ending time (ms)'};
                def={sprintf('%g',AVG_MIN),sprintf('%g',AVG_MAX)};
                dlgTitle='Input the times to use for average removal';
                answer = inputdlg(prompt,dlgTitle,1,def);
                if(isempty(answer)),
                    disp('Cancelled')
                    return
                else
                    AVG_MIN = sscanf(answer{1},'%g');
                    AVG_MAX = sscanf(answer{2},'%g');
                end
                AVG_MIN = min(find(Visu.Data.Time >= AVG_MIN/1000)); % convert to index
                AVG_MAX = max(find(Visu.Data.Time <= AVG_MAX/1000));
                if(isempty(AVG_MIN) | isempty(AVG_MAX)), % nothing
                    disp('Invalid time values')
                    return;
                end
                if(AVG_MAX < AVG_MIN), % bogus
                    disp('Inconsistent time values')
                    return;
                end

                tmp = mean(new_waves(goodchannels,AVG_MIN:AVG_MAX)')'; % mean in time for each channel
                new_waves(goodchannels,:) =  new_waves(goodchannels,:) - tmp(:,ones(1,size(new_waves,2)),:);
            end
        end

        data.Measures.F{1}(goodchannels,:) = new_waves(goodchannels,:);

        % Want to save data in file ?
        Users = get_user_directory;
        ButtonName=questdlg('Would you like to overwrite the orignal EEG segment in the current data file or save it under another name ?',...
            '','Overwrite','Save as a new file','Save as a new file');
        switch ButtonName
            case 'Overwrite'
                % Save it back to the original data set file

                % Get current data file
                [fname,h] = bst_static_taskbar('GET','DATA');
                fname = fname{1};% CBB - only one file selected
                cd(fullfile(Users.STUDIES,fileparts(fname)))
                [path,file,ext] = fileparts(fname);
                if file == 0, return, end

                % Get original field names of datafile
                oData = load(file);
                % Replace by filtered values
                oData.F = data.Measures.F{1};
                oData.Time = linspace(data.Display.Time(1),data.Display.Time(2),data.Display.NumberOfSamples);
                oData.ChannelFlag = data.Measures.ChannelFlag;

                save_fieldnames(oData,file)

                bst_message_window('wrap',...
                    sprintf('Overwrite original file %s -> done',file))

            case 'Save as a new file'

                % Save it to new datafile
                [fname,h] = bst_static_taskbar('GET','DATA');
                fname = fname{1};% CBB - only one file selected
                cd(fullfile(Users.STUDIES,fileparts(fname)))
                [path,file,ext] = fileparts(fname);
                if file == 0, return, end

                % Get original field names of datafile
                oData = load(file);

                file = sprintf('%s-f_L%dH%d',file,hpf,lpf);

                % Replace by filtered values
                oData.F = data.Measures.F{1};
                oData.Time = linspace(data.Display.Time(1),data.Display.Time(2),data.Display.NumberOfSamples);
                oData.ChannelFlag = data.Measures.ChannelFlag;

                save_fieldnames(oData,file)

                bst_message_window('wrap',...
                    sprintf('Filtered data saved in %s -> done',file))

                [DataDir,DataPopup,Leader] = find_brainstorm_files('data',pwd,[]);
                Users = get_user_directory;
                for k=1:length(DataDir)
                    DataDir{k} = fullfile(strrep(Leader,[Users.STUDIES,filesep],''),DataDir{k});
                end

                % Refresh data file display
                bst_static_taskbar('SET','DATA',DataDir);
                ifile = strmatch(file,cellstr(DataPopup)); % where's the new file ?

                % Find static taskbar
                static_taskbar = findobj(0,'Tag','static_taskbar');
                handles = guihandles(static_taskbar);
                set(handles.popupmenu_DATA,'Value',ifile)
                bst_static_taskbar('popupmenu_DATA_Callback',handles.popupmenu_DATA,[],guidata(handles.popupmenu_DATA))

            case 'Don''t save; just try it' % deprecated case
                % Do nothing
            case 'Cancel'
                return
            end

            makeuswait('stop')

            dataplot_cb('loadfile',{fullfile(path,file)})
            dataplot_cb('Plot')

            %----------------------------------------------------------------------------
    case 'show_fragment'
        Visu = get(DATAPLOT,'Userdata');
        tesselation_select_win = findobj(0,'Tag','tesselation_select');
        available = findobj(tesselation_select_win,'Tag','available');
        removed =  findobj(tesselation_select_win,'Tag','removed');
        availableID = get(removed,'Value');
        IDs = get(removed,'String');
        if isempty(IDs), return, end
        chan = [1:length(IDs)];

        load(Visu.Tesselation,'Clusters','Comment')

        if ~exist('Clusters','var') % No fragmentation available for this tessellation file
            return
        end

        % Identification of the active mesh surfaces
        for i = 1:length(IDs)
            imesh(i) = find(strcmp(IDs(i),Comment));
        end

        Vals = get(removed,'Userdata');
        if isempty(Vals)
            Vals = [ones(nmesh,1),zeros(nmesh,8)];
        end

        % Check for clusters for the current surface (highlighted surface name in the "selected text listbox")
        FragmentMenu = findobj(gcbf,'Tag','FragmentMenu');
        nsurf = imesh(availableID); % Selected surface

        dataplot_cb mesh_props

        if ~exist('Clusters','var') % Classes were not defined beforehand
            set(FragmentMenu,'String','No Fragmentation','Value',1);
            return
        end

        if isempty(Clusters{nsurf}) % No cluster available for surface 'nsurf'
            set(FragmentMenu,'String','No Fragmentation','Value',1);
            return
        else
            if isempty(Clusters{nsurf}.Seed)% No fragmentation availlable for this surface
                set(FragmentMenu,'String','No Fragmentation');
            else
                sstring = {'No Fragmentation'};
                for k = 1:length(Clusters{nsurf}.Seed)
                    sstring{k+1} = int2str(Clusters{nsurf}.Seed(k));
                end
                set(FragmentMenu,'String',sstring,'Value',2)
            end
        end

    case 'listchan_create' % Selection of channel names for n-plot visualization
        Visu = get(DATAPLOT,'Userdata');
        if isempty(Visu)
            errordlg('Please load a data set first')
            return
        end
        0
        str = {'MEG','EEG','OTHER'};

        LISTCHAN = findobj(0,'Tag','listchan');
        if isempty(LISTCHAN)
            LISTCHAN = open('listchan.fig');
        end

        goodchannels = good_channel(Visu.Channel,Visu.Data.ChannelFlag,DataType{current}); % Discard bad channels
        badchannels = setdiff(good_channel(Visu.Channel,ones(length(Visu.Channel),1),DataType{current}),goodchannels);
        %      goodchannels = setdiff(Visu.ChannelID{current},find(Visu.Data.ChannelFlag == -1))  - min(Visu.ChannelID{current})+1; % Discard bad channels
        % badchannels = intersect(Visu.ChannelID{current},find(Visu.Data.ChannelFlag == -1)) - min(Visu.ChannelID{current})+1;

        available = findobj(LISTCHAN,'Tag','available');
        removed =  findobj(LISTCHAN,'Tag','removed');

        set(available,'String', {Visu.Channel(goodchannels).Name});

        if ~isempty(badchannels)
            set(removed,'String', {Visu.Channel(badchannels).Name});
        else
            set(removed,'String', '');
        end

        set(available,'Value',1,'Max',length(get(available,'String')))
        set(removed,'Value',1,'Max',max([1,length(get(removed,'String'))]))

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

    case 'channel_plot_remove' % Remove Channels
        channel_select_win = findobj(0,'Tag','listchan');
        available = findobj(channel_select_win,'Tag','available');
        removed =  findobj(channel_select_win,'Tag','removed');
        removeID = get(available,'Value');
        IDs = get(available,'String');
        chan = [1:length(IDs)];

        set(available,'String', IDs(setdiff(chan,removeID)));
        if isempty(get(removed,'String'))
            set(removed,'String', [IDs(removeID)] );
        else
            strtmp = ([cellstr(get(removed,'String'));IDs(removeID)]);
            strtmp = sort(strtmp);
            set(removed,'String', cellstr(strtmp));
        end
        set(available,'Value',1,'Max',length(get(available,'String')))
        set(removed,'Value',1,'Max',max([1,length(get(removed,'String'))]))

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

    case 'channel_plot_restore' % Restore Channels - Make them become available again
        channel_select_win = findobj(0,'Tag','listchan');
        available = findobj(channel_select_win,'Tag','available');
        removed =  findobj(channel_select_win,'Tag','removed');
        availableID = get(removed,'Value');
        IDs = get(removed,'String');
        chan = [1:length(IDs)];

        set(removed,'Max',max([1,length(setdiff(chan,availableID))]))
        set(removed,'Value',1,'String',IDs(setdiff(chan,availableID)));

        if isempty(get(available,'String'))
            set(available,'String', [IDs(availableID)]);
        else
            strtmp = ([cellstr(get(available,'String'));IDs(availableID)]);
            strtmp = sort(strtmp);
            set(available,'String', cellstr(strtmp));
        end
        set(available,'Value',1,'Max',length(get(available,'String')))

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

    case 'listchan_SelectAll'

        channel_select_win = findobj(0,'Tag','listchan');
        available = findobj(channel_select_win,'Tag','available');
        set(available,'Value',[1:get(available,'Max')])
        dataplot_cb channel_plot_remove

        %----------------------------------------------------------------------------
    case 'listchan_RemoveAll'

        channel_select_win = findobj(0,'Tag','listchan');
        available = findobj(channel_select_win,'Tag','removed');
        set(available,'Value',[1:get(available,'Max')])
        dataplot_cb channel_plot_restore

        %----------------------------------------------------------------------------
    case 'listchan_refresh' % Update the channel information / plots

        Visu = get(DATAPLOT,'Userdata');
        str = {'MEG','EEG','OTHER'};

        channel_select_win = findobj(0,'Tag','listchan');
        removed =  findobj(channel_select_win,'Tag','removed');
        available =  findobj(channel_select_win,'Tag','available');
        handles = guihandles(channel_select_win);
        ncol = str2num(get(handles.NumberOfColumns,'String')); % Number of columns in the layout

        if isempty(get(removed,'String'))
            errordlg('Please Select Channels for the Plot first')
            return
        end

        [tmp,IDs] = intersect({Visu.Channel(Visu.ChannelID{current}).Name},get(removed,'String'));

        % Get time window
        data.Display.Time(1) = str2num(get(findobj(DATAPLOT,'Tag','time_min'),'String'));
        data.Display.Time(end) = str2num(get(findobj(DATAPLOT,'Tag','time_max'),'String'));

        if data.Display.Time(end) > Visu.Data.Time(end) * 1000
            data.Display.Time(end) = Visu.Data.Time(end) * 1000;
            set(findobj(DATAPLOT,'Tag','time_max'),'String',num2str(data.Display.Time(end),5))
        end

        if data.Display.Time(1) < Visu.Data.Time(1) * 1000
            data.Display.Time(1) = Visu.Data.Time(1) * 1000;
            set(findobj(DATAPLOT,'Tag','time_min'),'String',num2str(data.Display.Time(1),5))
        end

        delta_t = 1000*(Visu.Data.Time(2)-Visu.Data.Time(1));
        samples = round(([data.Display.Time(1):delta_t:data.Display.Time(end)]-Visu.Data.Time(1)*1000)/delta_t)+1;

        M = max(max(abs(Visu.Data.F(Visu.ChannelID{current}(IDs),samples))));

        fignplot = findobj(0,'Tag','nplot_win'); % Figure of overlaping plots for the current modality
        if isempty(fignplot)
            fig = figure;
            delete(findobj(fig,'type','axes'))
            movegui(fig,'center')
            set(fig,'Tag','nplot_win')
        else
            figure(fignplot)
            clf
        end

        % Visualization
        N = ceil(length(IDs)/ncol); % Maximum number of channels to visualize per column

        delta = .95/(N+1); % Space between plots (in normalized units)
        hold on
        for col = 1:ncol % For each column of the layout

            if col<ncol
                try
                    IDscol = IDs((col-1)*N+1 : N*col); % Labels of channels to plot in each column
                catch
                    errordlg('Please decrease the number of columns')
                    return
                end

            else
                IDscol = IDs((col-1)*N+1 : end); % Labels of channels to plot in each column
            end
            if col>1
                axes
            end

            i = 0;

            for k = IDscol
                i = i+1;
                plotwaves = plot([data.Display.Time(1):delta_t:data.Display.Time(end)],Visu.Data.F(Visu.ChannelID{current}(k),samples)+(2*M*i));
                hold on
            end

            set(gca,'units','normalized','ygrid','on','xgrid','on','Box','on',...
                'Position',[(col-1)*0.96/ncol + 0.039, 0.035, 0.80/ncol, 0.96],...
                'Yticklabel',{Visu.Channel(Visu.ChannelID{current}(IDscol)).Name},'Ytick',2*M*[1:length(IDscol)],...
                'FontName','Helvetica','FontSize',7,'FontUnits','Points','Fontweight','light',...
                'xColor',[.4 .4 .4], 'ycolor', [.05 .45 .80],'XMinorGrid','on',...
                'Xlim',[data.Display.Time(1),data.Display.Time(end)],'Ylim',[0 2*M*(N+1)])
            %         set(gca,'Fontunits','normal')
            liine = line([0 0],get(gca,'Ylim'),'linewidth',1);
            set(liine,'color','r','Tag','cursor')
        end

        hold off

        %--------------------------------------------------------------'--------------

    case 'selectchannels' % Selection of Good/Bad Channels

        chanwin = findobj(0,'type','figure','tag','channel_select');
        if isempty(chanwin)
            chanwin = openfig('channel_select.fig');
            bst_color_scheme(chanwin);
            setappdata(chanwin,'TileType','Tile')
            bst_layout('align',chanwin,2,2,3);

        end
        hchanwin = guihandles(chanwin);
        set(chanwin,'visible','on')

        % Visualization %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        imeg = good_channel(data.Measures.Channel,data.Measures.ChannelFlag,'MEG');
        ieeg = good_channel(data.Measures.Channel,data.Measures.ChannelFlag,'EEG');
        iother = good_channel(data.Measures.Channel,data.Measures.ChannelFlag,'Other');

        iall = [imeg,ieeg,iother];

        Label = {'All','MEG','EEG','Other'};
        set(hchanwin.pChannelSets,'String',Label,'Value',1);

        % Available Channels
        set(hchanwin.available,'String', {data.Measures.Channel(iall).Name});
        set(hchanwin.available,'Value',1,'Max',max([1,length(iall)]));

        % Bad or removed channels
        % Create dummy channelflag array to show all bad (-1) channels
        tmp.ChannelFlag = -ones(size(data.Measures.ChannelFlag));
        tmp.ChannelFlag(data.Measures.ChannelFlag == -1) = 1;
        ibad = [good_channel(data.Measures.Channel,tmp.ChannelFlag,'MEG'),...
                good_channel(data.Measures.Channel,tmp.ChannelFlag,'EEG'),...
                good_channel(data.Measures.Channel,tmp.ChannelFlag,'Other')];

        tmp = data.Measures.ChannelFlag(iall);
        iremoved = iall(tmp == 0);

        channels.removed = [ibad,iremoved];
        channels.available = [imeg,ieeg,iother];

        set(hchanwin.removed,'String', sort({data.Measures.Channel(channels.removed).Name}));
        set(hchanwin.removed,'Value',1,'Max',length(channels.removed));
        set(hchanwin.removed,'Value',1,'Max',max([1,length(channels.removed)]))

        % Store current selection of channels in channel_select GUI data
        guidata(chanwin,channels);

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

    case 'channel_switch' % Remove Channels

        chanwin = openfig('channel_select.fig','reuse');
        hchanwin = guihandles(chanwin);

        channels = guidata(chanwin);

        switch(get(gcbo,'Tag')) % Which action button was pressed ?
        case('pAdd')
            ActionFlag = 0;
            ChannelListFrom = hchanwin.removed;
            ChannelListTo = hchanwin.available;
        case('pRemove')
            ActionFlag = 0;
            ChannelListFrom = hchanwin.available;
            ChannelListTo = hchanwin.removed;
        case('pChannelSets') % Add some predefined channels set(s) to display
            ActionFlag = 1;

            ChannelListFrom = hchanwin.available;
            ChannelListTo = hchanwin.removed;

            % Visualization %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            imeg = good_channel(data.Measures.Channel,data.Measures.ChannelFlag,'MEG');
            ieeg = good_channel(data.Measures.Channel,data.Measures.ChannelFlag,'EEG');
            iother = good_channel(data.Measures.Channel,data.Measures.ChannelFlag,'Other');

            ChanSetType = get(gcbo,'Value'); % Type of preselected channel set;
            switch(ChanSetType)
            case 1 % All Channels
                ichans = [imeg,ieeg,iother];
            case 2 % MEG
                ichans = imeg;
            case 3 % EEG
                ichans = ieeg;
            case 4 % Other
                ichans = iother;
            end

        end

        if ActionFlag == 0  % Manual channel selection

            SelectedChannels = get(ChannelListFrom,'Value');
            ChanNames = get(ChannelListFrom,'String');

            if isempty(ChanNames)
                return
            end
            chan = [1:length(ChanNames)];

            set(ChannelListFrom,'String', ChanNames(setdiff(chan,SelectedChannels)));
            if isempty(get(ChannelListTo,'String'))
                set(ChannelListTo,'String', [ChanNames(SelectedChannels)] );
            else
                strtmp = ([cellstr(get(ChannelListTo,'String'));ChanNames(SelectedChannels)]);
                strtmp = sort(strtmp);
                set(ChannelListTo,'String', cellstr(strtmp));
            end
            set(ChannelListFrom,'Value',1,'Max',length(get(ChannelListFrom,'String')))
            set(ChannelListTo,'Value',1,'Max',max([1,length(get(ChannelListTo,'String'))]))

        elseif ActionFlag == 1 % Predefined display channel sets

            set(ChannelListFrom,'String', {data.Measures.Channel(ichans).Name},...
                'Value',1,'Max',max([1,length(ichans)]));
            set(ChannelListTo,'String', {data.Measures.Channel(setdiff([imeg,ieeg,iother],ichans)).Name},...
                'Value',1,'Max',max([1,length(setdiff([imeg,ieeg,iother],ichans))]));

        end

        [tmp,channels.removed] = intersect({data.Measures.Channel(:).Name},get(hchanwin.removed,'String'));
        [tmp,channels.available] = intersect({data.Measures.Channel(:).Name},get(hchanwin.available,'String'));

        guidata(chanwin,channels);

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

    case 'channel_select_done' % Update the channel information / plots

        makeuswait('start')
        Users = get_user_directory;

        chanwin = openfig('channel_select.fig','reuse');
        hchanwin = guihandles(chanwin);

        channels = guidata(chanwin);

        allchannels = [good_channel(data.Measures.Channel,[],'MEG'),...
                good_channel(data.Measures.Channel,[],'EEG'),...
                good_channel(data.Measures.Channel,[],'Other')];

        % Apply proper flags to channel 1: selected | 0: discarded | -1: bad channels for display
        if isempty(channels.removed)
            data.Measures.ChannelFlag(allchannels) = 1;%ones(1,length(allchannels)); %Restore to Good Channel
        else
            data.Measures.ChannelFlag(channels.available) = 1; % Reinitialize to 1 before update
            data.Measures.ChannelFlag(channels.removed) = -1; % CBB | Should be 0 instead
        end

        if get(hchanwin.ChannelSelectAllDataSets,'Value') % Apply this selection to all the data setsfrom this study
            bst_message_window('Updating all data files from current study . . .')

            cd(Users.STUDIES)
            [path,file,ext] = fileparts(Users.CurrentData.StudyFile);
            [DataDir,DataPopup,Leader] = find_brainstorm_files('data',fullfile(Users.STUDIES,path));
            ndatafiles = 0;
            clear ChannelFlag
            for file = DataDir
                cd(fullfile(Users.STUDIES,path))
                if isempty(findstr(file{:},'results'))
                    load(file{:},'ChannelFlag')
                end
                if exist('ChannelFlag','var') % Skip this file
                    ndatafiles = ndatafiles+1
                    ChannelFlag =  data.Measures.ChannelFlag;
                    save(file{:},'ChannelFlag','-append')
                    clear ChannelFlag
                end
            end
            bst_message_window('wrap',...
                {...
                    'Updating all data files from current study...-> DONE',...
                    sprintf('%d file(s) updated',ndatafiles)...
                })

        elseif get(hchanwin.ChannelSelectCurrentDataSet,'Value') % Apply this selection to current data file

            cd(Users.STUDIES)
            clear ChannelFlag
            dataFile = bst_static_taskbar('GET','DATA');
            dataFile = dataFile{1};        % CHEAT assume only first of selected file
            bst_message_window('wrap',...
                sprintf('Updating current data file: %s',dataFile))

            load(dataFile,'ChannelFlag')
            [path,file,ext] = fileparts(Users.CurrentData.StudyFile);
            cd(path)
            if exist('ChannelFlag','var') % Skip this file
                ChannelFlag =  data.Measures.ChannelFlag;
                save(dataFile,'ChannelFlag','-append')
                clear ChannelFlag
            end

            bst_message_window('-> DONE')

        end

        tmp = data.Measures.ChannelFlag;
        tmp(tmp==0) = -1;
        data.Measures.Display.SelectedChannels{1} = good_channel(data.Measures.Channel,tmp,'MEG');
        data.Measures.Display.SelectedChannels{2} = good_channel(data.Measures.Channel,tmp,'EEG');
        data.Measures.Display.SelectedChannels{3} = good_channel(data.Measures.Channel,tmp,'Other');

        dataplot_cb('Plot','measures')

        makeuswait('stop')

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

    case 'GenerateAverage' % Generate time-locked average of a selection of data files in current study folder

        % File selection
        % Current study folder
        [fname,h] = bst_static_taskbar('GET','DATA');
        fname = fname{1};
        Users = get_user_directory;
        path = fullfile(Users.STUDIES,fileparts(fname));
        % File selection window - call Pantazis's routine
        bst_message_window('Select files to be averaged from list')
        selectedFiles = file_selection_win({'data'},path); % Fully-qualified cell array of filenames

        if isempty(selectedFiles{1}),    makeuswait('stop'), return, end

        % Short input dialog about adjusting peak latency
        prompt={'Allow time jitter of (ms): '};
        def={'0'};
        dlgTitle='Adjust time-locking factor';
        lineNo = 1;
        answer=inputdlg(prompt,dlgTitle,lineNo,def);

        if isempty(answer), makeuswait('stop'), return ,    end

        makeuswait('start')

        bst_message_window('wrap',...
            sprintf('Time-locked averaging of %d selected data files...', length(selectedFiles)))

        ndatafiles = 0; % total number of files already read

        for file = selectedFiles

            if isempty(findstr(file{:},'results')) & isempty(findstr(file{:},'avr.mat'))
                % Don't include average files or mistakenly selected results
                % files

                ndatafiles = ndatafiles+1;

                bst_message_window('wrap',...
                    {...
                        sprintf('Step %d/%d -',ndatafiles,length(selectedFiles)),...
                        sprintf('Including %s into average', file{:})})

                load(file{:},'F','Time')
                [Channel,varargout] = get_channel(file{:}); % get Channel info

                TimeOrig = Time; % Store original time vector

                % Get selected modality
                slct_modal = get_selected_modalities;
                if length(slct_modal) > 1
                    errordlg('Only one modality needs to be selected in static taskbar for data averaging.')
                    return
                elseif isempty(slct_modal)
                    errordlg('Please select either MEG, EEG or OTHER data subset')
                    return
                end

                % Get all channels from current data setand seletec modality (i.e. including BAD channels)
                F = F(good_channel(Channel,[],ModalityLabel{slct_modal}),:);

                % Corresponding number of samples
                srate = Time(2)-Time(1); % Sampling rate of current file
                % Get value for time-jitter factor
                winPeak = str2num(answer{1});
                winPeak = ceil(winPeak/(1000*srate*2)); % Allow search of possible jitter in terms of number of samples

                % Find sample corresponding to time 0ms
                zeroLat = findclosest(0,Time);

                if winPeak > 0% Find maximum within jitter time window
                    % Extract data on the window of analysis:
                    tmpF = abs(F(:,zeroLat-winPeak:zeroLat+winPeak));
                    [mF ,mFindx] = max(tmpF);
                    [mF ,mFindx] = max(mF);
                    % New sample number for 0ms latency
                    zeroLat = zeroLat-winPeak+mFindx-1;
                end

                % Create new time vector
                Time(1) = sign(Time(1))*(zeroLat-1)*srate;
                Time = Time(1):srate:(Time(1)+(length(Time)-1)*srate);
                data.Display.Time = [Time(1), Time(end)];
                data.Display.SamplingRate = srate;

                set(hDataplot.time_min,'String',num2str(Time(1)*1000,'%3.2f'));
                set(hDataplot.time_max,'String',num2str(Time(end)*1000,'%3.2f'));
                set(hDataplot.step,'String',num2str(srate*1000,'%3.2f'));

                %Adjust time window
                if ndatafiles == 1
                    srate = data.Display.SamplingRate;
                    zeroLat = round(abs(Time(1))/srate)+1;
                    zeroLatOld = zeroLat;
                end

                % Average files all together
                if ndatafiles == 1
                    Fav = F;
                    iunder = findstr(file{:},'_'); % Generate average data file name
                    avFileName = file{:}(1:iunder(end));
                    avFileName = [avFileName,ModalityLabel{slct_modal},'avr.mat'];
                    Data = load(file{:});
                else
                    % Find sample corresponding to time 0ms
                    zeroLat = round(abs(Time(1))/srate)+1;
                    if zeroLat < zeroLatOld
                        Fav = Fav(:,zeroLatOld-zeroLat+1:end);
                        Fav = Fav(:,1:min([size(F,2),size(Fav,2)]));
                        F = F(:,1:min([size(F,2),size(Fav,2)]));
                        zeroLatOld = zeroLat;
                    else
                        F = F(:,zeroLat-zeroLatOld+1:end);
                        Fav = Fav(:,1:min([size(F,2),size(Fav,2)]));
                        F = F(:,1:min([size(F,2),size(Fav,2)]));
                        zeroLat = zeroLatOld;
                    end

                    Fav = Fav+F;

                end

                % Find maximum latency of this running average
                Time(1) = sign(Time(1))*(zeroLat-1)*srate;
                Time = Time(1):srate:(Time(1)+(size(Fav,2)-1)*srate);

                zeroLat = round(abs(Time(1))/srate)+1;
                zeroLatOld = zeroLat;

            end
        end

        srate = abs(TimeOrig(1)-TimeOrig(2));
        % New time vector
        Time(1) = sign(TimeOrig(1))*(zeroLat-1)*srate;
        Time = Time(1):srate:(Time(1)+(size(Fav,2)-1)*srate);

        % Save averaged data back to disk
        Data.F = zeros(length(Channel),length(Time));
        Data.F(good_channel(Channel,[],ModalityLabel{slct_modal}),:) = Fav/ndatafiles;
        Data.Time = Time;

        save_fieldnames(Data,avFileName);

        [DataDir,DataPopup,Leader] = find_brainstorm_files('data',pwd,[]);
        Users = get_user_directory;
        for k=1:length(DataDir)
            DataDir{k} = fullfile(strrep(Leader,[Users.STUDIES,filesep],''),DataDir{k});
        end

        % Refresh data file display
        bst_static_taskbar('SET','DATA',DataDir);
        ifile = strmatch(strrep(avFileName,[fileparts(avFileName),filesep],''),cellstr(DataPopup)); % where's the new file ?

        % Find static taskbar
        static_taskbar = findobj(0,'Tag','static_taskbar');
        handles = guihandles(static_taskbar);
        set(handles.popupmenu_DATA,'Value',ifile)
        bst_static_taskbar('popupmenu_DATA_Callback',handles.popupmenu_DATA,[],guidata(handles.popupmenu_DATA))

        bst_message_window('wrap',...
            {'Time-locked averaging -> DONE',...
                sprintf('%d files averaged',ndatafiles)}...
            )

        makeuswait('stop')

        dataplot_cb('loadfile',{strrep(avFileName,[Users.STUDIES,filesep],'')})
        dataplot_cb('Plot')

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

    case 'mapping_display_type' % Checkboxes Mutually incompatible
        DATAPLOT = findobj(0,'Tag','mapping');
        MEG = findobj(DATAPLOT,'Tag','single');
        EEG = findobj(DATAPLOT,'Tag','slides');
        OTHER = findobj(DATAPLOT,'Tag','movie');
        mutincomp([MEG,EEG,OTHER])
        h = findobj([MEG,EEG,OTHER],'Value',1);
        if length(h)>1
            set(h(2),'Value',0) % Just one modality at a time please !
        end

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

    case 'quit'
        close gcbf

        %----------------------------------------------------------------------------
    case 'see_sensors' % Visualize sensor locations using 3D spheres

        TessWin = findobj(0,'Tag','tesselation_select');
        hTessWin = guihandles(TessWin);

        %     mutincomp([hTessWin.Sensors3D,hTessWin.SensorsMarkers]);
        previous  = openfig('tessellation_window.fig','reuse');

        if get(hTessWin.Sensors3D,'Value') == 0
            if get(hTessWin.SensorsMarkers,'Value') == 1
                sph= findobj(previous,'Tag','SENSORS');
                delete(sph); set(previous,'Userdata',[])      % Redraw all sensors - to avoid mess with handles when resizing and coloring the sphere
                dataplot_cb see_sensors_markers
                return
            else
                sph= findobj(previous,'Tag','SENSORS');
                delete(sph); set(previous,'Userdata',[])      % Redraw all sensors - to avoid mess with handles when resizing and coloring the sphere
                return
            end
        end

        Visu = get(DATAPLOT,'Userdata');
        previous  = openfig('tessellation_window.fig','reuse');

        SIZE = sqrt(str2num(get(hTessWin.SensorSize,'String'))/10); % get sensor size
        if isempty(SIZE), SIZE = 1; end

        sph= findobj(previous,'Tag','SENSORS');
        delete(sph); set(previous,'Userdata',[])      % Redraw all sensors - to avoid mess with handles when resizing and coloring the sphere

        % Channels Locations:
        if ~isempty(find(Visu.Data.ChannelFlag == -1))
            goodchannels = good_channel(Visu.Channel,Visu.Data.ChannelFlag,DataType{current}); % Discard bad channels
            badchannels = setdiff(good_channel(Visu.Channel,ones(length(Visu.Channel),1),DataType{current}),goodchannels);
        else
            goodchannels = Visu.ChannelID{current};
            badchannels = [];
        end
        j = 0;
        chanloc = [Visu.Channel(goodchannels).Loc];
        chanloc = chanloc(:,1:2:end);
        for chan = goodchannels %Visu.ChannelID{current}
            j = j+1;
            figure(previous)
            hold on
            if j == 1
                maxx = max(abs(get(gca,'Xlim')/50))*SIZE;
                [X,Y,Z] = sphere;
            end
            sph(j) = surf(maxx*X+chanloc(1,j),maxx*Y+chanloc(2,j),maxx*Z+chanloc(3,j),'Visible','off');
        end

        set(sph,'Userdata',SIZE,'Visible','on','facelighting','Gouraud','edgelighting','Gouraud','Tag','SENSORS','facecolor',[.1 .1 .9],'Edgecolor','none')
        axis equal, axis vis3d
        varargout{1} = sph;

        %--------------------------------------------------------------------------------------------------------------------
    case 'see_sensors_markers' % Visualize sensor locations using regular markers

        TessWin = findobj(0,'Tag','tesselation_select');
        hTessWin = guihandles(TessWin);

        %     mutincomp([hTessWin.Sensors3D,hTessWin.SensorsMarkers]);
        previous  = openfig('tessellation_window.fig','reuse');

        if get(hTessWin.SensorsMarkers,'Value') == 0
            if get(hTessWin.Sensors3D,'Value') == 1
                sph= findobj(previous,'Tag','SENSORS');
                delete(sph); set(previous,'Userdata',[])      % Redraw all sensors - to avoid mess with handles when resizing and coloring the sphere
                dataplot_cb see_sensors
                return
            else
                sph= findobj(previous,'Tag','SENSORS');
                delete(sph); set(previous,'Userdata',[])      % Redraw all sensors - to avoid mess with handles when resizing and coloring the sphere
                return
            end
        end

        Visu = get(DATAPLOT,'Userdata');

        SIZE = sqrt(str2num(get(hTessWin.SensorSize,'String'))); % get sensor size
        if isempty(SIZE), SIZE = 1; end

        sph= findobj(previous,'Tag','SENSORS');
        delete(sph); set(previous,'Userdata',[])      % Redraw all sensors - to avoid mess with handles when resizing and coloring the sphere

        % Channels Locations:
        if ~isempty(find(Visu.Data.ChannelFlag == -1))
            goodchannels = good_channel(Visu.Channel,Visu.Data.ChannelFlag,DataType{current}); % Discard bad channels
            badchannels = setdiff(good_channel(Visu.Channel,ones(length(Visu.Channel),1),DataType{current}),goodchannels);
            %      %         goodchannels = setdiff(Visu.ChannelID{current},find(Visu.Data.ChannelFlag == -1));% - min(Visu.ChannelID{current})+1; % Discard bad channels
            %         badchannels = intersect(Visu.ChannelID{current},find(Visu.Data.ChannelFlag == -1));% - min(Visu.ChannelID{current})+1;
        else
            goodchannels = Visu.ChannelID{current};
            badchannels = [];
        end
        j = 0;
        chanloc = [Visu.Channel(goodchannels).Loc];
        chanloc = chanloc(:,1:2:end);
        hold on
        sph = scatter3(chanloc(1,:),chanloc(2,:),chanloc(3,:),'filled');

        set(sph,'Userdata',SIZE,'Visible','on','Tag','SENSORS',...
            'Markerfacecolor',[.1 .1 .9],'Markeredgecolor','k', 'MarkerSize',SIZE);
        axis equal, axis vis3d
        varargout{1} = sph;

        %--------------------------------------------------------------------------------------------------------------------
    case 'OrthoViews' % Toggle between visualization of selected envelopes along 4 orthogonal views and single-view mode

        TessSelect = findobj(0,'Tag','tesselation_select');
        hSelect = guihandles(TessSelect);
        TAG = get(hSelect.OrthoViews,'Value');

        TessWin = findobj(0,'Tag','tessellation_window');
        if isempty(TessWin), set(gcbo,'Value',0), return, end

        ha = findobj(TessWin,'Tag','MainAxes');
        hp = findobj(get(ha,'Children'),'Type','patch');
        haa(1) =  findobj(TessWin,'Tag','axsub1');
        haa(2) =  findobj(TessWin,'Tag','axsub2');
        haa(3) =  findobj(TessWin,'Tag','axsub3');
        haa(4) =  findobj(TessWin,'Tag','axsub4');

        haa_child = get(haa,'Children');
        if ~isempty(haa_child{1})
            hps{1} = findobj([haa_child{:}],'Type','patch');
        else
            hps{1} = [];
        end

        if isempty(TAG)|TAG == 1
            if isempty(hps{1})
                for k = 1:4
                    hps{k} =  copyobj([hp(:)]',[haa(k)]);
                end
                axes(haa(1)), view(-180, 90), axis vis3d, axis equal, axis off,
                copyobj(findobj(ha,'Type','light'),haa(1))
                axes(haa(2)), view(-180, 0), axis vis3d, axis equal, axis off,
                copyobj(findobj(ha,'Type','light'),haa(2))
                axes(haa(3)), view(-90, 0), axis vis3d, axis equal, axis off,
                copyobj(findobj(ha,'Type','light'),haa(3))
                axes(haa(4)), view(0, 0), axis vis3d, axis equal, axis off,
                copyobj(findobj(ha,'Type','light'),haa(4))

                set(haa, 'Clim',get(ha,'Clim'))

            else
                set([hps{:}],'visible','on')
            end
            set(hp,'visible','off')
        else
            set([hps{:}],'visible','off')
            set(hp,'visible','on')
            set(TessWin,'CurrentAxes',get(hp(1),'Parent'))
        end
        dataplot_cb mapping_slider % Refersh time sample
        %--------------------------------------------------------------------------------------------------------------------
    case 'FreezeColormap' %...so that Colormap is adjusted to

        TessWin = findobj(0,'Tag','tessellation_window');
        TessSelect = findobj(0,'Tag','tesselation_select');
        hSelect = guihandles(TessSelect);
        figure(TessWin);

        togglebuttoncolor(gcbo)

        % Check if loaded Results match this surface (ie number of sources = number of vertices of selected cortical surface)
        Results = get(hSelect.ResultFiles,'Userdata');
        if isempty(Results), return, end
        MAPPING = findobj(0,'Tag','mapping');
        hMAPPING = guihandles(MAPPING);
        srate = abs(Results.ImageGridTime(2)-Results.ImageGridTime(1));

        ctime = round((get(hMAPPING.hDataplot.TimeSlider,'Value')/1000- Results.ImageGridTime(1))/srate)+1;

        set(hSelect.FreezeColormap,'Userdata',ctime)
        if get(hSelect.FreezeColormap,'Value')
            set(hSelect.FreezeTime,'String',sprintf('Time: %4.1f ms',1000*Results.ImageGridTime(ctime)))
        else
            set(hSelect.FreezeTime,'String','')
        end

        if get(hSelect.FreezeColormap,'Value')
            set(hSelect.Normalize,'Value',0);
            set(TessSelect,'currentobject',hSelect.Normalize)
            dataplot_cb NormalizeColormap
        else
            dataplot_cb mapping_slider
        end

        %dataplot_cb mapping_slider
        %--------------------------------------------------------------------------------------------------------------------

    case 'NormalizeColormap' % ...so that Colormapping is automatic (data maxima reach the maximum of the colormap)

        TessWin = findobj(0,'Tag','tessellation_window');
        TessSelect = findobj(0,'Tag','tesselation_select');
        hSelect = guihandles(TessSelect);
        figure(TessWin);

        togglebuttoncolor(gcbo)

        if get(hSelect.Normalize,'Value')
            set(hSelect.FreezeColormap,'Value',0);
            set(TessSelect,'currentobject',hSelect.FreezeColormap)
            dataplot_cb FreezeColormap

        end
        dataplot_cb mapping_slider

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

    case 'ScaleColormap' % let the user adjust the color scaling for greater saturation

        hTessSelect = guihandles(gcbf);

        %ScaleFactor = inputdlg('Enter Caxis Scaling Factor','BrainStorm Movie Maker',[1 50],{'1'});
        %if isempty(ScaleFactor), return, end

        if get(hTessSelect.ZScoreThresholdApply,'Value') & get(hTessSelect.ZScore,'Value')
            ZScoreFlag = 1;
            ScaleFactor = 100*get(hTessSelect.ZScoreThreshold,'Userdata');
        else
            ScaleFactor = str2num(get(hTessSelect.TruncateFactor,'String'));
            ZScoreFlag = 0;
        end

        TessWin = findobj(0,'Tag','tessellation_window');
        if isempty(TessWin), return, end
        figure(TessWin)
        ColorMap = get(TessWin,'Colormap');

        ColorMapOld = get(hTessSelect.ScaleColormap,'Userdata');
        if isempty(ColorMapOld),
            ColorMapOld = ColorMap;
            set(hTessSelect.ScaleColormap,'Userdata',ColorMapOld);
        end
        ColorMap = ColorMapOld;

        if ScaleFactor > 0
            ColorMap(1:round(ScaleFactor*end/100),:) = ...
                repmat(min([.3,sum(ColorMap(round(ScaleFactor*end/100),:))])*[1 1 1],length(1:round(ScaleFactor*size(ColorMapOld,1)/100)),1);
        else
            ColorMap = ColorMapOld;
        end

        set(TessWin,'Colormap',ColorMap);
        set(hTessSelect.ColorMAP,'Userdata',ColorMap)

        dataplot_cb CorticalMap
        %--------------------------------------------------------------------------------------------------------------------

        %
        % case 'Colorbar' % Add colorbar to the Surface Viewer window
        %     handles = guihandles(gcbf);
        %     ViewColorbar = get(handles.Colorbar,'Value'); % Add or remove colorbar
        %     TessWin = findobj(0,'Tag','tessellation_window');
        %
        %     if isempty(TessWin), return, end
        %     if isempty(get(handles.Colorbar,'Userdata')) | (ViewColorbar == 1)
        %         figure(TessWin);
        %         Colorbar = colorbar('horiz');
        %         set(handles.Colorbar,'Userdata',Colorbar);
        %         set(Colorbar,'Xcolor',textcolor,'Ycolor',textcolor)
        %     elseif ~isempty(get(handles.Colorbar,'Userdata'))
        %         delete(get(handles.Colorbar,'Userdata'));
        %         set(handles.Colorbar,'Userdata',[])
        %     end
        %     figure(TessWin)
        %     view3d rot
        %     hTessSelect = guihandles(findobj(0,'Tag','tesselation_select'));
        %     if get(hTessSelect.Normalize,'Value') & ViewColorbar == 1% Normalized colorbar
        %         M=get(hTessSelect.Normalize,'Userdata');
        %         set(get(handles.Colorbar,'Userdata'),'XTickLabel',num2str(linspace(0,M,6)',1))
        %     end
        %
        %     %--------------------------------------------------------------------------------------------------------------------
        % case 'Colorbar_mapping' % Add colorbar to the Surface Viewer window
        %     handles = guihandles(gcbf);
        %     ViewColorbar = get(handles.Colorbar,'Value'); % Add or remove colorbar
        %     for k = 1:length(current)
        %         TessWin = findobj(0,'Tag',['map_single',int2str(current(k))]);
        %
        %         if isempty(TessWin), return, end
        %         if (ViewColorbar == 1)
        %             figure(TessWin);
        %             axes(get(TessWin,'CurrentAxes'));
        %             Colorbar{k} = colorbar('horiz');
        %             set(handles.Colorbar,'Userdata',Colorbar);
        %             set(Colorbar{k},'Xcolor',textcolor,'Ycolor',textcolor)
        %         elseif ~isempty(get(handles.Colorbar,'Userdata'))
        %             Colorbar = get(handles.Colorbar,'Userdata');
        %             if isempty(Colorbar)
        %                 return
        %             end
        %             delete([Colorbar{:}]);
        %             set(handles.Colorbar,'Userdata',[])
        %         end
        %     end
        %
        %--------------------------------------------------------------------------------------------------------------------
    case 'QuitTessSelect' % Bye
        delete(findobj(0,'tag','tesselation_select'));
        delete(findobj(0,'tag','tessellation_window'));

        %----------------------------------------------------------------------------
    case 'mutincomp_cmapping' % Mutually icompatible checkboxes
        mapping_win = findobj(0,'Tag','mapping');
        MEG = findobj(mapping_win ,'Tag','ABSOLUTE');
        EEG = findobj(mapping_win ,'Tag','RELATIVE');
        mutincomp([MEG,EEG])
        h = findobj([MEG,EEG],'Value',1);
        if length(h)>1
            set(h(2),'Value',0)
        end
        %----------------------------------------------------------------------------

    case 'mutincomp_colormap' % Mutually icompatible checkboxes
        mapping_win = findobj(0,'Tag','tesselation_select');
        MEG = findobj(mapping_win ,'Tag','Normalize');
        EEG = findobj(mapping_win ,'Tag','FreezeColormap');
        mutincomp([MEG,EEG])
        h = findobj([MEG,EEG],'Value',1);
        if length(h)>1
            set(h(2),'Value',0)
        end

        %----------------------------------------------------------------------------
    case 'mutincomp_meanmax' % Mutually icompatible checkboxes
        mapping_win = findobj(0,'Tag','tesselation_select');
        MEG = findobj(mapping_win ,'Tag','MeanCorticalArea');
        EEG = findobj(mapping_win ,'Tag','MaxCorticalArea');
        OTHER = findobj(mapping_win ,'Tag','AllCorticalArea');

        mutincomp([MEG,EEG,OTHER])
        h = findobj([MEG,EEG,OTHER],'Value',1);
        if length(h)>1
            set(h(2:end),'Value',0)
        end
        %----------------------------------------------------------------------------
    case 'mutincomp_opaque' % Mutually icompatible checkboxes
        MEG = findobj(gcbf,'Tag','Opaque');
        EEG = findobj(gcbf,'Tag','transparent');
        mutincomp([MEG,EEG])
        h = findobj([MEG,EEG],'Value',1);
        if length(h)>1
            set(h(2),'Value',0)
        end
        dataplot_cb mesh_vals

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

    case 'mapping_type' % Mutually icompatible checkboxes
        mapping_win = findobj(0,'Tag','mapping');
        MEG = findobj(mapping_win ,'Tag','raw');
        EEG = findobj(mapping_win ,'Tag','gradient');
        OTHER = findobj(mapping_win,'Tag','magnetic');
        mutincomp([MEG,EEG,OTHER])
        h = findobj([MEG,EEG,OTHER],'Value',1);
        if length(h)>1
            set(h(2),'Value',0)
        end
        %----------------------------------------------------------------------------

    case 'mapping_head_shape' % Mutually icompatible checkboxes
        mapping_win = findobj(0,'Tag','mapping');
        handles = guihandles(mapping_win);
        %     figure(mapping_win)
        mutincomp([handles.sphere,handles.fit,handles.scalp])
        h = findobj([handles.sphere,handles.fit,handles.scalp],'Value',1);
        if length(h)>1
            set(h(2),'Value',0)
        end

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

    case 'GetCallback' % Pick up callback associated to items in current pulldown menu

        Methods = getappdata(gcbo,'Methods'); % Callbacks were stored previously
        %if isempty(Methods), return, end

        iMethod = get(gcbo,'Value'); % Index of selected item in list

        eval(Methods(iMethod).callback) % Launch callback

    end  % Switch action

    % Subfunctions ------------------------------------------------------------------

    % ------------------------------------------------------------------------------
    function initialize_SourceTimeViewing(handle)

    % when first called, build the popups from here
    % Since we want to add functionality to these popups, particularly
    %  new viewing routines, we will explicitly build this popup and maintain it
    %  in the application data

    Methods = struct('display',[],'localfunction',[]); % initialize

    % build it here, imitating this format, rearrange as desired

    % the first line
    Methods(1).display = '<No Time Display>';
    Methods(1).callback = ''; % comment line

    % the remaining lines, use this format to allow easy rearranging.
    Methods(end+1).display = 'Overlay';
    Methods(end).callback = 'dataplot_cb set_SourceViewingTimeDisplay'; % local function in this m-file

    Methods(end+1).display = 'Column';
    Methods(end).callback = 'dataplot_cb set_SourceViewingTimeDisplay'; % local function in this m-file

    Methods(end+1).display = 'Cortical Scouts';
    Methods(end).callback = 'dataplot_cb CorticalScouts';

    % set the popup menu
    set(handle,'string',{Methods.display});

    % set application data in the popup
    setappdata(handle,'Methods',Methods);
    % thus retrieving this application data will yield the local function to
    %  be used for every method

    % ------------------------------------------------------------------------------
    function initialize_SourceSpatialViewing(handle)

    % when first called, build the popups from here
    % Since we want to add functionality to these popups, particularly
    %  new viewing routines, we will explicitly build this popup and maintain it
    %  in the application data

    Methods = struct('display',[],'callback',[]); % initialize

    % build it here, imitating this format, rearrange as desired

    % the first line
    Methods(1).display = '<No Spatial Display>';
    Methods(1).callback = ''; % comment line

    % the remaining lines, use this format to allow easy rearranging.
    Methods(end+1).display = 'Cortical Envelope';
    Methods(end).callback = 'dataplot_cb SourceViewingSpatialDisplay'; % local function in this m-file

    Methods(end+1).display = 'MRI';
    Methods(end).callback = 'dataplot_cb SourceViewingSpatialDisplay'; % local function in this m-file

    Methods(end+1).display = 'Glass Brain';
    Methods(end).callback = 'dataplot_cb SourceViewingSpatialDisplay';

    Methods(end+1).display = '------------';
    Methods(end).callback = '';

    Methods(end+1).display = 'Add Scalp Surface';
    Methods(end).callback = 'dataplot_cb AddScalpSurface';

    % set the popup menu
    set(handle,'string',{Methods.display});

    % set application data in the popup
    setappdata(handle,'Methods',Methods);
    % thus retrieving this application data will yield the local function to
    %  be used for every method

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

    function shorterfilename = shorter_filename(longfilename);
    % Shorten and edit the length of the relative filename file name LONGFILENAME
    % by removing path and underscores to avoid TEX interpretation of string.
    % Arguments are cell arrays of string.

    fname = longfilename; clear longfilename
    [PATHSTR,NAME,EXT,VERSN] = fileparts(fname{1}); % Make names shorter
    fname = strrep(fname,[PATHSTR,filesep],'');
    fname = strrep(fname,[EXT],'');
    fname = strrep(fname,'_','-'); % Avoid TEX interpretation of fname string
    shorterfilename = fname;

    % ------------------------------------------------------------------------------
    function slct_modal = get_selected_modalities;
    % Find selected modalities from static taskbar
    % Return a vector or a scalar with the following code
    % 1 is MEG
    % 2 is EEG
    % 3 is OTHER

    global data

    [val,enable,h] = bst_static_taskbar('GET','MEG'); % Go and fetch this information from static taskbar
    MEG = ~isempty(data.Measures.Display.SelectedChannels{1}) & val ;
    [val,enable,h] = bst_static_taskbar('GET','EEG');
    EEG = ~isempty(data.Measures.Display.SelectedChannels{2}) & val;
    [val,enable,h] = bst_static_taskbar('GET','OTHER');
    Other= ~isempty(data.Measures.Display.SelectedChannels{3}) & val;
    Test = [MEG,EEG,Other];
    slct_modal = find(Test); % Select modalities for display

Produced by color_mat2html, a customized BrainStorm 2.0 (Alpha) version of mat2html on Tue Oct 12 12:05:14 2004
Cross-Directory links are: ON