function varargout = importdata(varargin);
%IMPORTDATA - Case Switchyard for importing data from major MEG and EEG systems
% function varargout = importdata(varargin);
% Import data from the 3 major MEG systems (Neuromag, CTF & BTi) + 
%  a selection of EEG systems and generic RAW format. 
% Routines are generally called by the importdata.fig GUI.
% Switchyard Cases in this file as of 16-April-2004, found manually with dos findstr
%    case 'create' % Starts importing data 
%    case 'RemoveDCOffset' % Remove DC offset from MEG channels
%    case 'checkDC' % Mutual incompatibility between checkboxes related to MEG DC removal
%    case 'MarkerInfo' 
%    case 'DisplayMarkerInfo' % Display extended information about selected data sets in message box.
%    case 'TrialSelection' % Selection of a subset of trials for data extraction
%    case 'MarkerTimeRange' % Are we extracting whole trials or chunks of data about marker(s) ?
%    case 'system_select' % Selects the data format to read from 
%    case 'SeqBlockRW' % Callbcak when cSeqBlockRW checkbox is clicked
%    case 'TNativeFormat' % Switch enable on/off for relevant checkboxes when choosing/dropping 
%    case 'ReadMarkerFile'
%    case 'AssignMarkerToDataSet'
%    case 'AssignSubjectToDataSet'
%    case 'fromRAW'
%    case 'OK' % Parameters are all set - import data NOW !
%    case 'mutincomp' % Raw/Average

%<autobegin> ---------------------- 12-Oct-2004 01:11:22 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Data import
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\bst_color_scheme.m
%   toolbox\bst_layout.m
%   toolbox\bst_message_window.m
%   toolbox\bst_win_manager.m
%   toolbox\ds2brainstorm.m
%   toolbox\eeg2bs.m
%   toolbox\elpos2bs.m
%   toolbox\extract_ctf_markers.m
%   toolbox\find_brainstorm_files.m
%   toolbox\findclosest.m
%   toolbox\get_user_directory.m
%   toolbox\good_channel.m
%   toolbox\importdata.m  NOTE: Routine calls itself explicitly
%   toolbox\load_raw.m
%   toolbox\makeuswait.m
%   toolbox\mutincomp.m
%   toolbox\readmarkerfile_ctf.m
%   toolbox\save_fieldnames.m
%   toolbox\study_editor.m
%
% Subfunctions in this file, in order of occurrence in file:
%   save_sensor_locs(Channel)
%
% Group : Preference data and their calls in this file:
%   Subjects = getpref('BrainStorm','Subjects',[]);
%   tmp = getpref('BrainStorm','Subjects',[]);
%
% Application data and their calls in this file:
%   'DCOffset'
%   'DSFolders'
%   'DataFormats'
%   'DataInformationTable'
%   'DataMarkerFileTable'
%   'DataMarkerIntervalTable'
%   'DataMarkerTable'
%   'DataSubjectTable'
%   'DataTrialSelectionTable'
%   'Markers'
%   'System'
%   'TileType'
%   
%   setappdata(ImportGUI,'DCOffset',0);
%   setappdata(ImportGUI,'DCOffset',1);
%   setappdata(ImportGUI,'DCOffset',DCOffset);
%   setappdata(ImportGUI,'DataInformationTable',DataInformation);
%   setappdata(ImportGUI,'DataInformationTable',cell(length(get(handles.RawDataList,'String')),1));
%   setappdata(ImportGUI,'DataMarkerFileTable',DataMarkerFile);
%   setappdata(ImportGUI,'DataMarkerIntervalTable',DataMarkerInterval);
%   setappdata(ImportGUI,'DataMarkerIntervalTable',cell(length(get(handles.RawDataList,'String')),1));
%   setappdata(ImportGUI,'DataMarkerTable',DataMarker);
%   setappdata(ImportGUI,'DataSubjectTable',DataSubject);
%   setappdata(ImportGUI,'DataSubjectTable',cell(length(get(handles.RawDataList,'String')),1));
%   setappdata(ImportGUI,'DataTrialSelectionTable',DataTrialSelection);
%   setappdata(ImportGUI,'DataTrialSelectionTable',cell(length(get(handles.RawDataList,'String')),1));
%   setappdata(ImportGUI,'Markers',Marker);
%   setappdata(ImportGUI,'System',SYSTEM);
%   setappdata(ImportGUI,'TileType','T');
%   setappdata(handles.RawDataList,'DSFolders',DataDir);
%   setappdata(handles.popupDataFormats,'DataFormats',DataFormats);
%   
%   DCOffset = getappdata(ImportGUI,'DCOffset');
%   DataDir = getappdata(handles.RawDataList,'DSFolders');
%   DataFormats = getappdata(handles.popupDataFormats,'DataFormats');
%   DataInformation = getappdata(ImportGUI,'DataInformationTable');
%   DataMarker = getappdata(ImportGUI,'DataMarkerTable');
%   DataMarkerFile = getappdata(ImportGUI,'DataMarkerFileTable');
%   DataMarkerInterval = getappdata(ImportGUI,'DataMarkerIntervalTable');
%   DataSubject = getappdata(ImportGUI,'DataSubjectTable');
%   DataTrialSelection = getappdata(ImportGUI,'DataTrialSelectionTable');
%   Marker = getappdata(ImportGUI,'Markers');
%   SYSTEM = getappdata(ImportGUI,'System');
%   TASKBAR = getappdata(0,'BrainStormTaskbar');
%   switch upper(getappdata(ImportGUI,'System'))
%
% Figure Files opened by this function:
%   'generic_listbox_win.fig'
%   'importdata.fig'
%
%   Format of strings below: Type:Style:Tag, "String", CallBack Type and Call
%   <automatic> callback is <Tag>_Callback by Matlab default
%
% Callbacks by figure generic_listbox_win.fig
%   uicontrol:pushbutton:DONE "Done" uses Callback for subject_editor ImportTriDone
%
% Callbacks by figure importdata.fig
%   uicontextmenu::See more information  "" uses Callback for importdata DisplayMarkerInfo
%   uicontrol:checkbox:cAllMarkers "" uses Callback for importdata MarkerInfo
%   uicontrol:checkbox:cCommonMarkers "" uses Callback for importdata MarkerInfo
%   uicontrol:checkbox:checkDCPreTrig "Based on pretrigger" uses Callback for importdata checkDC
%   uicontrol:checkbox:checkDCWholeTrial "Based on whole trial" uses Callback for importdata checkDC
%   uicontrol:checkbox:checkRemoveDC "Remove DC offset" uses Callback for importdata RemoveDCOffset
%   uicontrol:checkbox:cMarkerTimeRange "" uses Callback for importdata MarkerTimeRange
%   uicontrol:checkbox:cReadWholeTrials "Read whole trial(s)" uses Callback for
%     importdata MarkerTimeRange
%   uicontrol:checkbox:cSeqBlockRW "Sequential Block Read/Write" uses Callback for
%     importdata SeqBlockRW
%   uicontrol:checkbox:cSplitTrials "Split trials in multiple data.mat files" uses Callback for
%     importdata MarkerTimeRange
%   uicontrol:checkbox:cUseMarkers "Do not use markers" uses Callback for importdata MarkerInfo
%   uicontrol:checkbox:TNativeFormat "Keep native format" uses Callback for importdata TNativeFormat
%   uicontrol:edit:eTimeRange """ uses Callback for importdata MarkerTimeRange
%   uicontrol:edit:eTrialSelection "''" uses Callback for importdata TrialSelection
%   uicontrol:listbox:LMarkerList "''" uses Callback for importdata AssignMarkerToDataSet
%   uicontrol:listbox:LSubjects "''" uses Callback for importdata AssignSubjectToDataSet
%   uicontrol:listbox:RawDataList "''" uses Callback for importdata MarkerInfo
%   uicontrol:popupmenu:popupDataFormats "Pick-up a data format. . ." uses Callback for
%     importdata system_select
%   uicontrol:popupmenu:popupEEGRef "Pick-up a reference for the EEG" uses Callback for
%     importdata SelectEEGReference
%   uicontrol:pushbutton:HOK "Import" uses Callback for importdata OK
%   uicontrol:pushbutton:QPushbutton1 "Close" uses Callback for delete(gcbf)
%   uicontrol:text:BTrialSelection "Trial Selection" uses Callback for importdata MarkerTimeRange
%   uicontrol:text:tAllMarkers "Use (all) marker(s) from" uses Callback for importdata MarkerInfo
%   uicontrol:text:tCommonMarkers "Use marker(s) common" uses Callback for importdata MarkerInfo
%   uicontrol:text:tMarkerTimeRange "Time Range" uses Callback for importdata MarkerTimeRange
%
% At Check-in: $Author: Mosher $  $Revision: 55 $  $Date: 10/11/04 11:33p $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 23-Sep-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 01:11:22 -----------------------




% /---Script Author--------------------------------------\
% |                                                      |
% | *** Sylvain Baillet, Ph.D.                           |
% | Cognitive Neuroscience & Brain Imaging Laboratory    |
% | CNRS UPR640 - LENA                                   | 
% | Hopital de la Salpetriere, Paris, France             |
% | sylvain.baillet@chups.jussieu.fr                     |
% |                                                      |
% |  *** John C. Mosher, Ph.D.                           |
% |  Biophysics Group                                    |
% |  Los Alamos National Laboratory                      |
% |  Los Alamos, New Mexico, USA                         |
% |  mosher@lanl.gov                                     |
% \------------------------------------------------------/
%  
% Date of creation: January 1999
%---------------------------------------------------------------------------------------------------------------------------

% SB  13-Nov-2001 added peak-detection facility about the marker 
% ............... (useful when importing epileptic spikes with a maximum at zero time) 
% JCM 28-May-2002 simplified create, added bst_color
% JCM 06-Jun-2002 returns varargout for create, so UIWAIT can be applied
% SB  22-Jul-2002 Major update
% JCM 30-Oct-2002 Handled getpref cases if Studies or Subjects are empty
% JCM 31-Oct-2002 creating default brainstorm folders had file separator bug, used "fullfile"
%                 to fix
% SB  07-Nov-2002 Follow up to 22-07-2002 major update:
%                 Enabled importation of Markers in CTF format
%                 Systematic use of bst_message_window
% SB  15-Nov-2002 Added choice for EEG reference from GUI
%                 Changed layout of GUI - updated callbacks accordingly
% JCM 20-Nov-2002 Problems with GUI, figure and objects were built in normalized units.
%                 Altered back to points, resaved, also but movegui function here. Made
%                 figure invisible at creation, make visible when ready.
% SB  23-Jan-2003 Now it's possible to keep CTF data in native format (disk space saving feature + 
%                 speeds-up access to data by replacing the F data array 
%                 in the data file by a string specifying the original name of the .ds folder 
%                 Other BrainStorm tools will recognize this format and access the data using appropriate means.
%                 Need to extend this feature to other accepted native data formats (so far, none but Neuromag - limited
%                 to Linux environment - untested).
% JCM 15-Dec-2003 Added "ispc" test around "mkdir" command, since linux user was encountering Status issue
% JCM 16-Apr-2004 Fixed and upgraded the ASCII load routines into "RAW" routines
%                 for both binary and ascii loading, upgraded the "Pick a
%                 format" to be more versatile and editable from within the
%                 m-file. See cases "create" and "system_select"
% JCM 28-Apr-2004 Continued building the ASCII importing routines
% Sb  04-Jun-2004 Replaced DISP calls by BST_MESSAGE_WINDOW
% JCM 14-Jun-2004 Upgraded raw importing in an attempt to make clearer.
% JCM 16-Jun-2004 Fixed bug related to 14-Jun with "DataType"
% DP  24-Sep-2004 Add landmarks support when importing BESA EEG data
% -----------------------------------------------------

if isempty(varargin), % no input, assume create
    varargin{1} = 'create';
end

Users = get_user_directory;

switch varargin{1}
    % --------------------------------------------------------------------------------
    case 'create' % Starts importing data 
        ImportGUI = openfig('importdata.fig'); % Window for datatype selection
        % note, GUI is invisible initially
        bst_color_scheme(ImportGUI);
        bst_win_manager(ImportGUI,'Other');
        
        setappdata(ImportGUI,'TileType','T');
        bst_layout('align',ImportGUI,1,1,1);
        
        % Initialize GUIs related to marker information
        handles = guihandles(ImportGUI);
        set([handles.LMarkerList,handles.eTimeRange,...
                handles.cSeqBlockRW,handles.cMarkerTimeRange,...
                handles.tMarkerTimeRange,handles.cReadWholeTrials],'Enable','on')
        set(handles.LMarkerList,'String',{'Read whole data file(s)','without marker information'})
        
        MarkerTimeInterval = 'Whole Trial';
        
        set(handles.eTimeRange,'String',MarkerTimeInterval)
        
        % Build the format popup:
        %   uicontrol:popupmenu:popupDataFormats "Pick-up a data format. . ." uses Callback for
        %     importdata system_select
        % Set the strings and systems for the popup. Systems are keywords:
        %  System belongs to (case insensitive)
        %  {'magnes','ctf','neuromag','neuroscan','egi','prn','raw'}
        
        DataFormats = struct('String',[],'System',[]);
        DataFormats(1).String = 'Pick-up a data format . . .';
        DataFormats(1).System = []; % comment line, no system
        
        % Now arrange as desired
        DataFormats(end+1).String = '---- MEG -----';
        DataFormats(end).System = []; % comment line, no system
        
        DataFormats(end+1).String = '  4-D / BTi (Magnes) <N/A in current version>';
        DataFormats(end).System = 'Magnes'; % keyword, case insensitive
        
        DataFormats(end+1).String = '  CTF';
        DataFormats(end).System = 'CTF';
        
        DataFormats(end+1).String = '  Neuromag <N/A in current version>';
        DataFormats(end).System = 'Neuromag';
        
        DataFormats(end+1).String = '------ EEG ----';
        DataFormats(end).System = [];
        
        DataFormats(end+1).String = ' BESA <ASCII>';
        DataFormats(end).System = 'BESA';
        
        DataFormats(end+1).String = ' EGI ';
        DataFormats(end).System = 'EGI';
        
        DataFormats(end+1).String = ' Neuroscan <binary>';
        DataFormats(end).System = 'Neuroscan';
        
        DataFormats(end+1).String = '-- RAW (ASCII and binary) --';
        DataFormats(end).System = [];
        
        DataFormats(end+1).String = ' Raw formats';
        DataFormats(end).System = 'RAW';
        
        % end of designing format popup, now load
        set(handles.popupDataFormats,'String',{DataFormats.String}); % Available data formats
        setappdata(handles.popupDataFormats,'DataFormats',DataFormats); % store in uicontrol
        
        set(ImportGUI,'Visible','on')
        
        if(nargout)
            varargout{1} = ImportGUI;
            varargout{2} = guihandles(ImportGUI);
        end
        
        % Fill the Subject listbox with available subject's file in current database
        tmp = getpref('BrainStorm','Subjects',[]); % default to empty if not there
        if(~isempty(tmp)),
            tmp = cellstr(char(tmp.Name));
            Subjects = cell(length(tmp)+2,1);
        else
            Subjects = cell(2,1);
        end
        
        Subjects([1,2]) = {'Default Subject','New Subject'}; %Add Default Subject as first choice in list 
        Subjects(3:end) = tmp; % works even if tmp is empty
        handles = guihandles(ImportGUI);
        set(handles.LSubjects,'String',Subjects,'Value',1,'Max',1); % One subject at time : 'Max' set to 1
        
        bst_message_window({...
                ' ',...
                '-> Please select a data native format',...
                ' '})
        
        set(ImportGUI,'Visible','On'); % show the user
        
        
        
        % --------------------------------------------------------------------------------
    case 'RemoveDCOffset' % Remove DC offset from MEG channels
        ImportGUI = openfig('importdata.fig','reuse'); % Window for datatype selection
        handles = guihandles(ImportGUI);
        
        
        switch(get(handles.checkRemoveDC,'Value'))
            case 1
                set(handles.checkDCWholeTrial,'Value',1,'enable','on')
                set(handles.checkDCPreTrig,'Value',0,'enable','on')
                setappdata(ImportGUI,'DCOffset',1); % Remove DCOffset based on entire trial length    
            case 0
                set([handles.checkDCWholeTrial,handles.checkDCPreTrig],'Value',0,'enable','off')
                setappdata(ImportGUI,'DCOffset',0); % Default is to not remove DCOffset from MEG data
        end
        
    case 'checkDC' % Mutual incompatibility between checkboxes related to MEG DC removal
        ImportGUI = openfig('importdata.fig','reuse'); % Window for datatype selection
        handles = guihandles(ImportGUI);
        mutincomp([handles.checkDCWholeTrial,handles.checkDCPreTrig]);
        
        if get(handles.checkDCWholeTrial,'Value') == 1
            DCOffset = 1;
        else
            DCOffset = 2;
        end
        
        setappdata(ImportGUI,'DCOffset',DCOffset);
        
        
        % --------------------------------------------------------------------------------
    case 'MarkerInfo' 
        % Two things are done here :
        % 1) Read data information from raw file and display
        % 2) what do we do with marker(s), if available ?
        
        ImportGUI = gcbf; % handle to import_dataselector.fig
        handles = guihandles(ImportGUI);
        
        % Marker management ---------------------------------------------
        
        % First manage mutual incompatibility between relevant checkboxes. 
        % Get checkboxes handles
        mutincomp([handles.cUseMarkers, handles.cAllMarkers, handles.cCommonMarkers])
        
        % Display data and subject information -----------------------------------------
        % if callback object is RawDataList only and if only one dataset is selected
        
        % Which dataset are selected ?
        iDataSet = get(handles.RawDataList,'Value');
        DataDir = getappdata(handles.RawDataList,'DSFolders');
        
        
        % Enable or disable objects associated with Marker info
        switch get(handles.cUseMarkers,'Value')
            case 1 % Do not take Marker info into account
                set([handles.LMarkerList,handles.eTimeRange,...
                        handles.cSeqBlockRW,handles.cMarkerTimeRange,...
                        handles.tMarkerTimeRange,handles.cReadWholeTrials],'Enable','on')
                set(handles.LMarkerList,'String',{'Read whole data file(s)','without marker information'},'Max',2,'Value',1)
                DataMarkerTemplate = struct('MarkerName','','MarkerIndex',[],'Param',[],'NoMarker',[]); 
                [DataMarker(iDataSet)] = deal(DataMarkerTemplate);
                [DataMarker(iDataSet).NoMarker] = deal(1); % Meaning we're importing without refering to any marker
                
                setappdata(ImportGUI,'DataMarkerTable',DataMarker);
                
            otherwise % use markers
                set([handles.LMarkerList,handles.eTimeRange,...
                        handles.cSeqBlockRW,handles.cMarkerTimeRange,...
                        handles.tMarkerTimeRange,handles.cReadWholeTrials],'Enable','on')
                importdata('ReadMarkerFile');    
        end
        
        
        if isappdata(ImportGUI,'DataSubjectTable')
            DataSubject = getappdata(ImportGUI,'DataSubjectTable');
            if ~isempty([DataSubject{iDataSet}]) % A subject was already assigned to this data set 
                set(handles.LSubjects,'Value',[DataSubject{iDataSet}]);
            else % assume default data set
                set(handles.LSubjects,'Value',1);
            end
        end
        
        if ~isappdata(ImportGUI,'DataInformationTable')
            % No appdata containing data information for displayed data sets is available
            setappdata(ImportGUI,'DataInformationTable',cell(length(get(handles.RawDataList,'String')),1));
        end
        % now get it
        DataInformation = getappdata(ImportGUI,'DataInformationTable');
        
        for k = 1:length(iDataSet) % Fill the information cell for each of the selected data sets
            if isempty(DataInformation{iDataSet(k)})
                % Read data information from .res4 file 
                % May take a while - ...
                makeuswait('start')
                bst_message_window({...
                        ' ',...
                        ' Reading original data information from selected file(s). . .'...
                    })
                SYSTEM = getappdata(ImportGUI,'System'); % Store it for later use 
                switch(SYSTEM)
                    case 'ctf'
                        % ds2brainstorm with READRES argument set to 2 (read data information only).
                        DataInformation{iDataSet(k)} = ds2brainstorm(fullfile(Users.STUDIES,DataDir{iDataSet(k)}),0,2);
                        makeusewait('stop')
                    otherwise % Cannot read more information about file: return <CBB>
                        makeuswait('stop')
                        return
                end
                
            end
            setappdata(ImportGUI,'DataInformationTable',DataInformation);
        end
        
        if length(get(handles.RawDataList,'Value'))>1 % Multiple data sets selection - need to pick just one
            set(handles.eTimeRange,'String', 'Multiple values')
            set(handles.eTrialSelection,'String', 'Multiple values')
            return
        end
        
        Data.no_channels = DataInformation{iDataSet}.gSetUp.no_channels;
        Data.sample_rate = DataInformation{iDataSet}.gSetUp.sample_rate;
        Data.no_samples = DataInformation{iDataSet}.gSetUp.no_samples;
        Data.no_trials = DataInformation{iDataSet}.gSetUp.no_trials;
        Data.no_trials_avrgd = DataInformation{iDataSet}.no_trials_avgd;
        Data.preTrigPts = DataInformation{iDataSet}.gSetUp.preTrigPts;
        Data.imegsens = DataInformation{iDataSet}.imegsens;
        Data.ieegsens = DataInformation{iDataSet}.ieegsens;
        
        % Enable / Disable GUI check boxes that are specific to either EEG or MEG
        if isempty(Data.imegsens)
            set(handles.checkRemoveDC,'enable','off')
        else
            set(handles.checkRemoveDC,'enable','on')
        end
        
        if isempty(Data.ieegsens)
            set(handles.popupEEGRef,'enable','off')
        else
            set(handles.popupEEGRef,'enable','on')
            set(handles.popupEEGRef,'String',{'Average Reference',DataInformation{iDataSet}.ChannelNames(Data.ieegsens,:)})
        end
        
        
        % Original time range
        Time = [-Data.preTrigPts Data.no_samples-Data.preTrigPts]/Data.sample_rate;
        
        % Update or create MarkerTimeInterval table
        if isappdata(ImportGUI,'DataMarkerIntervalTable') % Already defined
            DataMarkerInterval = getappdata(ImportGUI,'DataMarkerIntervalTable');
            if isempty(DataMarkerInterval{iDataSet})
                DataMarkerInterval{iDataSet} = num2str(Time);
            end
        else
            % Defined from our current reading of data information 
            setappdata(ImportGUI,'DataMarkerIntervalTable',cell(length(get(handles.RawDataList,'String')),1));
            DataMarkerInterval = getappdata(ImportGUI,'DataMarkerIntervalTable');    
            DataMarkerInterval{iDataSet} = num2str(Time);
        end
        set(handles.eTimeRange,'String', DataMarkerInterval{iDataSet})
        setappdata(ImportGUI,'DataMarkerIntervalTable',DataMarkerInterval);
        
        
        % Trial selection
        % Create a Data table 
        if isappdata(ImportGUI,'DataTrialSelectionTable') % Already defined
            DataTrialSelection = getappdata(ImportGUI,'DataTrialSelectionTable');
            if isempty(DataTrialSelection{iDataSet})
                DataTrialSelection{iDataSet} = sprintf('1:%d',Data.no_trials);
            end
        else
            % Defined from our current reading of data information 
            setappdata(ImportGUI,'DataTrialSelectionTable',cell(length(get(handles.RawDataList,'String')),1));
            DataTrialSelection = getappdata(ImportGUI,'DataTrialSelectionTable');    
            DataTrialSelection{iDataSet} = sprintf('1:%d',Data.no_trials);
        end
        set(handles.eTrialSelection,'String',DataTrialSelection{iDataSet})
        
        setappdata(ImportGUI,'DataTrialSelectionTable',DataTrialSelection);
        
        % --------------------------------------------------------------------------------
        
    case 'DisplayMarkerInfo' % Display extended information about selected data sets in message box.
        
        ImportGUI = gcbf; % handle to import_dataselector.fig
        handles = guihandles(ImportGUI);
        
        % Which dataset are selected ?
        iDataSet = get(handles.RawDataList,'Value');
        DataDir = getappdata(handles.RawDataList,'DSFolders');
        
        if isappdata(ImportGUI,'DataInformationTable')
            DataInformation = getappdata(ImportGUI,'DataInformationTable');
        else
            % No appdata containing data information for displayed data sets is available
            setappdata(ImportGUI,'DataInformationTable',cell(length(get(handles.RawDataList,'String')),1));
            DataInformation = getappdata(ImportGUI,'DataInformationTable');    
        end
        
        % Now set-up fancy display in handles.DataInformation textbox
        Subject = DataInformation{iDataSet}.nfSetUp.nf_subject_id;
        
        Study.Name = DataInformation{iDataSet}.nfSetUp.nf_run_title;
        Study.DateOfSession = DataInformation{iDataSet}.data_date;
        
        Data.no_channels = DataInformation{iDataSet}.gSetUp.no_channels;
        Data.sample_rate = DataInformation{iDataSet}.gSetUp.sample_rate;
        Data.no_samples = DataInformation{iDataSet}.gSetUp.no_samples;
        Data.no_trials = DataInformation{iDataSet}.gSetUp.no_trials;
        Data.no_trials_avrgd = DataInformation{iDataSet}.no_trials_avgd;
        Data.preTrigPts = DataInformation{iDataSet}.gSetUp.preTrigPts;
        Data.TrialDuration = DataInformation{iDataSet}.gSetUp.epoch_time/Data.no_trials ;
        Data.imegsens = DataInformation{iDataSet}.imegsens;
        Data.ieegsens = DataInformation{iDataSet}.ieegsens;
        Data.iothersens = DataInformation{iDataSet}.iothersens;
        
        Display = {...
                sprintf(' Name of session: %s', Study.Name),...
                sprintf(' Recorded on: %s', Study.DateOfSession),...
                ' -------------',....
                ' ',...
                sprintf(' Subject: %s',Subject),...
                ' -------------',....
                ' ',...
                sprintf(' Number of channels: '),...
                sprintf('        MEG   : %d',length(Data.imegsens)),...
                sprintf('        EEG   : %d ',length(Data.ieegsens)),...
                sprintf('        Other : %d ',length(Data.iothersens)),...
                ' -------------',....
                ' ',...
                sprintf(' %d trials from %d averaged raw trials',Data.no_trials,Data.no_trials_avrgd),...
                sprintf(' Trial duration: %gs / with %gs pretrigger',  Data.TrialDuration,Data.preTrigPts/Data.sample_rate)...
            };
        
        
        msgbox(Display);
        
        % --------------------------------------------------------------------------------
        
    case 'TrialSelection' % Selection of a subset of trials for data extraction
        ImportGUI = gcbf; % handle to import_dataselector.fig
        handles = guihandles(ImportGUI);
        
        iDataSet = get(handles.RawDataList,'Value'); % Selected data sets
        
        if get(handles.cAllMarkers,'Value') == 0 % Do not use markers
            % Trial selection
            % Use a Data table 
            if isappdata(ImportGUI,'DataTrialSelectionTable') % Already defined
                DataTrialSelection = getappdata(ImportGUI,'DataTrialSelectionTable');
            else % Create table
                setappdata(ImportGUI,'DataTrialSelectionTable',cell(length(get(handles.RawDataList,'String')),1));
                DataTrialSelection = getappdata(ImportGUI,'DataTrialSelectionTable');    
            end
            % Get Trial selection from editable textbox in GUI
            DataTrialSelection{iDataSet} = get(handles.eTrialSelection,'String');
            
            setappdata(ImportGUI,'DataTrialSelectionTable',DataTrialSelection);
            
        else % Use Markers - select a subset of marker events
            
            
            iMarker = get(handles.LMarkerList,'Value'); % What's the selected Marker ?
            if ~isempty(iMarker(iMarker == 1)) % No Marker Selected
                return 
            else
                iMarker = iMarker - 1;
                
                % Get the Marker information
                Marker = getappdata(ImportGUI,'Markers');
                
                %Which datasets are selected ?
                DataDir = getappdata(handles.RawDataList,'DSFolders');
                iDataSets = get(handles.RawDataList,'Value');
                
                
                % Now store all the extraction information in a table 
                % Get MarkerFile information for each dataset
                if length(iMarker) == 1 & length(iDataSets) == 1 % Display trial information
                    try
                        TrialSamples = str2num(get(handles.eTrialSelection,'String')); % Subset of selected trials for current Marker.    
                    catch
                        errordlg(sprintf('Unvalid String: %s', get(handles.eTrialSelection,'String')))
                    end
                    
                elseif length(iMarker) > 1 | length(iDataSets) > 1 % Multiple values
                    set(handles.eTrialSelection,'String','Multiple Values')
                    return
                end
                
                for imark = 1:length(iMarker)  % For each Marker, save sample information
                    for ids = iDataSets
                        idsInMarker = find(strcmp(cellstr(Marker(iMarker(imark)).ds),DataDir{ids})); % Index of ds file in Marker structure
                        if ~isempty(idsInMarker) 
                            % Store information only if current Marker can be found in selected ds
                            DataMarker(ids).NoMarker = 0;
                            DataMarker(ids).MarkerIndex(imark) = iMarker(imark);
                            DataMarker(ids).MarkerName{imark} = Marker(iMarker(imark)).name;
                            DataMarker(ids).Param(imark).trial_time =  Marker(iMarker(imark)).trial_time{idsInMarker}(TrialSamples,:);
                            DataMarker(ids).Param(imark).no_samples = size(DataMarker(ids).Param(imark).trial_time,1);
                        end
                    end
                end
            end
            
            setappdata(ImportGUI,'DataMarkerTable',DataMarker);
            
        end
        
        % --------------------------------------------------------------------------------
    case 'MarkerTimeRange' % Are we extracting whole trials or chunks of data about marker(s) ?
        ImportGUI = gcbf; % handle to import_dataselector.fig
        handles = guihandles(ImportGUI);
        
        % First manage mutual incompatibility between relevant checkboxes. 
        mutincomp([handles.cReadWholeTrials,handles.cMarkerTimeRange]);
        
        % Now assign Marker interval information to selected datasets for future importation
        if isappdata(ImportGUI,'DataMarkerIntervalTable')
            DataMarkerInterval = getappdata(ImportGUI,'DataMarkerIntervalTable');
        else
            setappdata(ImportGUI,'DataMarkerIntervalTable',cell(length(get(handles.RawDataList,'String')),1));
            DataMarkerInterval = getappdata(ImportGUI,'DataMarkerIntervalTable');    
        end
        
        %Which datasets are selected ?
        iDataSets = get(handles.RawDataList,'Value');
        
        [DataMarkerInterval(iDataSets)] = deal({get(handles.eTimeRange,'String')});
        
        setappdata(ImportGUI,'DataMarkerIntervalTable',DataMarkerInterval);
        
        
        % --------------------------------------------------------------------------------
    case 'system_select' % Selects the data format to read from 
        
        %   uicontrol:popupmenu:popupDataFormats "Pick-up a data format. . ." uses Callback for
        %     importdata system_select   
        
        ImportGUI = gcbf; % handle to import_dataselector.fig
        handles = guihandles(ImportGUI);
        
        
        % Initialize subjects and marker assignation
        if isappdata(ImportGUI,'DataMarkerTable')
            rmappdata(ImportGUI,'DataMarkerTable');
        end
        if isappdata(ImportGUI,'DataSubjectTable')
            rmappdata(ImportGUI,'DataSubjectTable');
        end
        
        % Get the system from the popup string
        % stored in uicontrol at time of creation
        DataFormats = getappdata(handles.popupDataFormats,'DataFormats'); 
        % Identification of system type by which popup selected
        SYSTEM = DataFormats(get(handles.popupDataFormats,'Value')).System;
        
        if isempty(SYSTEM),
            % a no-op comment line
            set(handles.popupDataFormats,'value',1); % back to the beginning
            return % done
        end
        
        % now handle the cases that are not ready yet
        switch lower(SYSTEM)
            % special case handling         
            case {'magnes','neuroscan'}
                set(handles.RawDataList,'String',...
                    {...
                        sprintf('No automatic loading of %s data sets yet.', SYSTEM) ,...
                        'Please export your data into "raw" formatted files.',...
                        'Check the BrainStorm web site for latest news',...
                        'about available formats.'...
                    })
                set(handles.popupDataFormats,'Value',1)
                return
            case 'raw'
                % special handling for now
                importdata('fromRAW')
                set(handles.popupDataFormats,'Value',1) % reset handle
                return
        end
        
        bst_message_window('wrap','Looking for data sets in native format in current database...')
        makeuswait('start')
        
        setappdata(ImportGUI,'System',SYSTEM); % Store it for later use
        % Look for data files from this system in current database
        % Look for CTF format in current study folder
        [DataDir,DataPopup,Leader] = find_brainstorm_files(SYSTEM,Users.STUDIES);
        if isempty(DataPopup) % If data sets in current study folder
            
            % Listbox display
            
            set(handles.RawDataList,'String',...
                {...
                    sprintf('No %s data sets in current study folder:',SYSTEM),...
                    sprintf('%s ', Users.STUDIES),...
                })
            set(handles.popupDataFormats,'Value',1)
            makeuswait('stop')
            return
            
        else
            
            set(handles.RawDataList,'String',cellstr(DataPopup),'Min',1,'Max',length(DataDir)+1) % Listbox display
            setappdata(handles.RawDataList,'DSFolders',DataDir); % Store for later usage
            importdata MarkerInfo % jcm 19 august 2003 update the automatic selection of the first element
            
        end
        
        switch get(handles.cUseMarkers,'Value')
            case 1 % Do not take Marker info into account
            otherwise
                % Find possible associated MarkerFile.
                importdata('ReadMarkerFile');    
        end
        
        makeuswait('Stop')
        
        bst_message_window('wrap',{...
                '-> Done',...
                'You may now select one or several data sets to import'...
            })
        
        %------------------------------------------------------------------------------------
    case 'SeqBlockRW' % Callbcak when cSeqBlockRW checkbox is clicked
        ImportGUI = gcbf; % handle to import_dataselector.fig
        handles = guihandles(ImportGUI);
        
        
        % if SeqBlockRW is requested
        % then splitrials in multiple files is enforced 
        % (consistent with the way trials are read sequentially and therefore saved likewise)
        
        if get(handles.cSeqBlockRW,'Value')
            set(handles.cSplitTrials,'Value',1,'Enable','off')
        else
            set(handles.cSplitTrials,'Value',1,'Enable','on')
        end
        
        %------------------------------------------------------------------------------------
    case 'TNativeFormat' % Switch enable on/off for relevant checkboxes when choosing/dropping 
        % native data file format.
        
        ImportGUI = gcbf; % handle to import_dataselector.fig
        handles = guihandles(ImportGUI);
        if get(handles.TNativeFormat,'Value')
            set([handles.cAllMarkers,handles.cCommonMarkers,handles.cUseMarkers],'Enable','off')
        else
            set([handles.cAllMarkers,handles.cCommonMarkers,handles.cUseMarkers],'Enable','off')
        end
        
        
        %------------------------------------------------------------------------------------
    case 'ReadMarkerFile'
        
        ImportGUI = gcbf; % handle to import_dataselector.fig
        handles = guihandles(ImportGUI);
        cd(Users.STUDIES);
        
        SYSTEM = getappdata(ImportGUI,'System');
        
        if isempty(SYSTEM), return, end % System still undefined, return
        
        switch(SYSTEM)
            
            case 'CTF'
                
                DataFiles = get(handles.RawDataList, 'Value');         % Which .ds has been selected ?
                DataDir = getappdata(handles.RawDataList,'DSFolders');
                set(handles.LMarkerList,'Value',1)
                set(handles.LSubjects,'Value',1)
                
                DataDir = DataDir(DataFiles); % Relative parth to selected data sets.
                
                % How many files were selected ?
                nfiles = length(DataDir);
                
                % Now fill-out the Marker structure array.
                % .name : name of the marker
                % .ds : a cell array of the DS folders where this marker was found
                % .trial_time : a cell array of trial_time arrays indicating for trial, the latency from trial time zero
                % where to find the marker; one cell per DS folder.
                % .nsamples : total number of occurences of this marker
                Marker = [];%struct('name','','ds','','trial_time',[],'nsamples',[]);
                DSMarker.names = [];
                
                for k = 1:nfiles
                    % Look for a Marker file in current .ds folder
                    [DSMarker.names,DSMarker.nsamples ,DSMarker.trial_time] = readmarkerfile_ctf(DataDir{k});
                    while isempty(DSMarker.names) & k < nfiles+1 % Look for a MarkerFile in either of the selected data sets 
                        k = k+1;
                        if k > nfiles
                            k = nfiles;
                            break
                        end
                        [DSMarker.names,DSMarker.nsamples ,DSMarker.trial_time] = readmarkerfile_ctf(DataDir{k});
                        
                    end
                    
                    % Store Marker information for each Dataset (for later use in data extraction : case 'OK')
                    if isappdata(ImportGUI,'DataMarkerFileTable')
                        DataMarkerFile = getappdata(ImportGUI,'DataMarkerFileTable');
                    else
                        DataMarkerFile = cell(length(get(handles.RawDataList,'String')),1);
                    end
                    DataMarkerFile{k} = DSMarker; 
                    setappdata(ImportGUI,'DataMarkerFileTable',DataMarkerFile);
                    % ----------------------------
                    
                    if isempty(DSMarker.names) % No markerfile found: get out of here !
                        break
                    end
                    
                    % DSMarker is a structure filled with Marker information from current data set DataDir{k}
                    
                    % Now fill out a few variables for future (nice) display of Marker information in GUI
                    MarkerNames{k} = deblank(char(DSMarker.names)); % Pad all names to same character length
                    MarkerNSamples{k} = deblank(char(int2str(DSMarker.nsamples)));
                    
                    % Start filling Marker structure
                    for kk = 1:length(DSMarker.names) % For each Marker found in first data set 
                        Marker(end+1).name = DSMarker.names{kk};
                        j = length(Marker);
                        Marker(j).ds = DataDir{k};
                        Marker(j).trial_time = DSMarker.trial_time{kk}; 
                        Marker(j).nsamples =  DSMarker.nsamples(kk);
                    end
                    % Now handles Marker with same names
                    % Keep all markers available - just detect duplicates in other .ds files
                    % and refresh the corresponding array entry of Marker
                    [UniqueMarkers iUniqueMarkers jUniqueMarkers]  ...
                        = unique(cellstr(char(Marker.name))) ;
                    tmp = Marker;
                    for kk = 1:length(UniqueMarkers) % Update Marker field values
                        
                        Marker(kk).name = UniqueMarkers{kk};
                        iMarkers = find(strcmp(cellstr(char(tmp.name)),UniqueMarkers{kk})); % Index of Markers with names UniqueMarkers{kk}
                        Marker(kk).nsamples = sum([tmp(iMarkers).nsamples]);
                        Marker(kk).ds = char(tmp(iMarkers).ds);
                        Marker(kk).trial_time = cell(1,length(iMarkers));
                        for imark = 1:length(iMarkers)
                            if ~iscell(tmp(iMarkers(imark)).trial_time)
                                Marker(kk).trial_time{imark} = tmp(iMarkers(imark)).trial_time;
                            else
                                Marker(kk).trial_time{imark} = tmp(iMarkers(imark)).trial_time{:}; % For first selected ds
                            end
                        end
                    end
                    
                    Marker = Marker(1:length(iUniqueMarkers));
                    
                end
                
                if isempty(Marker)
                    bst_message_window({...
                            ' ',...
                            'No MarkerFile found for selected data set(s)',...
                            (char(DataDir)),...
                            ' '...
                        });
                    return
                end
                iremove = [];
                if nfiles > 1 & get(handles.cCommonMarkers,'Value') % Only keep markers present in ALL data sets
                    for kk = 1:length(Marker)
                        if size(Marker(kk).ds,1) ~= nfiles
                            % This marker does not belong to all data sets - remove it from final selection
                            iremove = [iremove,kk];
                        end
                    end
                    if ~isempty(iremove)
                        Marker = Marker(setdiff(1:length(Marker),iremove));    
                    end
                    
                end
                
                if isempty(Marker)
                    bst_message_window({...
                            'No MarkerFile found for selected data set(s)',...
                            DataDir{k}...
                        });
                    return
                end
                
                
                fmtstr = sprintf('%%-%ds | %%-%ds trials',...
                    size(MarkerNames,2),size(MarkerNSamples,2)); % Template string
                
                % Now get prepared for fancy listbox display
                % first create proper character arrays fro Names and NSamples
                MarkerNames = char(Marker.name);
                MarkerNSamples = char(cellstr(int2str([Marker.nsamples]')));
                
                clear MarkerDisplay
                MarkerDisplay{1} = 'No Marker Selected'; % Default choice - useful when removing a data set from selection
                for k = 1:size(MarkerNames,1)
                    MarkerDisplay{k+1} = sprintf(fmtstr,...
                        strrep(MarkerNames(k,:),' ','.'),strrep(MarkerNSamples(k,:),' ','.'));
                end
                
                
                set(handles.LMarkerList,'String',MarkerDisplay,'enable','on','Max',length(MarkerDisplay));
                setappdata(ImportGUI,'Markers',Marker); % Store marker information
                
                % Update display corresponding to selected markers and subjects for the selected data sets
                if get(handles.cUseMarkers,'Value') == 0 & length(DataFiles) == 1 % Only one data set is selected
                    if isappdata(ImportGUI,'DataMarkerTable')
                        DataMarker = getappdata(ImportGUI,'DataMarkerTable');
                        try % if a Marker was selected 
                            if ~isempty(DataMarker(DataFiles).MarkerName) %~isempty([DataMarker{DataFiles}]) 
                                imark = [];
                                for kk = 1:length([DataMarker(DataFiles).MarkerName]) % Find listbox values of current marker display
                                    imark = [imark,find(strcmp( cellstr(char(Marker(:).name)), DataMarker(DataFiles).MarkerName{kk}))];
                                end
                                set(handles.LMarkerList,'Value',imark+1)
                            end
                        end
                    end
                end
                
            otherwise
                bst_message_window('Unsupported data type to read marker information')
                return
        end
        
        %------------------------------------------------------------------------------------
    case 'AssignMarkerToDataSet'
        % When marker information is taken into account
        % we assign here the markers we want to consider for importation
        % for the selected datasets.
        
        ImportGUI = gcbf; % handle to import_dataselector.fig
        handles = guihandles(ImportGUI);
        
        if get(handles.cUseMarkers,'Value') % Do not use markers: return
            return
        end
        
        
        %Which datasets are selected ?
        iDataSets = get(handles.RawDataList,'Value');
        
        % Get the table of correspondence 
        % between data sets and selected markers 
        % If does not exist, create one
        % Create pr Update the Data <-> Marker assignement table
        % An array of structures
        % Each structure will specify the Markers to be extracted and the associated information
        % Field description (for each marker):
        % .NoMarker    : set to 1 means that data importation is done with reference to trial onset, and not to any Marker
        % .MarkerIndex : Index of the selected Markers in .ds MarkerFile
        % .MarkerName   : Marker names foundin MarkerFile
        %%%%%%%%%%%%%%%%%%%%%% .TimeRange    : Time range of extraction about Marker latency
        % .Param(imark).trial_time   : Array of trial number x latencies for Marker imark 
        % .Param(imark).no_samples   : Number of occurences of Marker         "
        DataMarkerTemplate = struct('MarkerName','','MarkerIndex',[],'Param',[],'NoMarker',[]); 
        if isappdata(ImportGUI,'DataMarkerTable')
            DataMarker = getappdata(ImportGUI,'DataMarkerTable');
            % Reinitialize DataMarker for selected Datasets (Marker selection has porbably changed between tow calls to this
            % switch)
            %DataMarker(iDataSets) = [];
            DataMarker(iDataSets) = deal(DataMarkerTemplate);
        else
            [DataMarker(1:length(get(handles.RawDataList,'String')))] = deal(DataMarkerTemplate);
            setappdata(ImportGUI,'DataMarkerTable',DataMarker);
        end
        
        % Get the Marker information
        Marker = getappdata(ImportGUI,'Markers');
        
        % Which is the time range for data extraction about the selected markers
        if isappdata(ImportGUI,'DataMarkerIntervalTable')
            DataMarkerInterval = getappdata(ImportGUI,'DataMarkerIntervalTable');
        end
        
        DataDir = get(handles.RawDataList,'String');
        
        % Which is the current subject ?
        iMarker = get(handles.LMarkerList,'Value');
        if ~isempty(iMarker(iMarker == 1)) % No Marker Selected
            % Remove dataset from selection
            DataMarker(iDataSets) = deal(DataMarkerTemplate);
            set(handles.LMarkerList,'Value',1)
        else
            iMarker = iMarker - 1;
            
            % Now store all the extraction information in a table 
            % Get MarkerFile information for each dataset
            if length(iMarker) == 1 & length(iDataSets) == 1 % Display trial information
                set(handles.eTrialSelection,'String',sprintf('%d:%d',1,size( Marker(iMarker).trial_time{1},1)))    
            elseif length(iMarker) > 1 | length(iDataSets) > 1 % Multiple values
                set(handles.eTrialSelection,'String','Multiple Values')
            end
            
            for imark = 1:length(iMarker)  % For each Marker, save sample information
                for ids = iDataSets
                    idsInMarker = find(strcmp(cellstr(Marker(iMarker(imark)).ds),DataDir{ids})); % Index of ds file in Marker structure
                    if ~isempty(idsInMarker) 
                        % Store information only if current Marker can be found in selected ds
                        DataMarker(ids).NoMarker = 0;
                        DataMarker(ids).MarkerIndex(imark) = iMarker(imark);
                        DataMarker(ids).MarkerName{imark} = Marker(iMarker(imark)).name;
                        DataMarker(ids).Param(imark).trial_time =  Marker(iMarker(imark)).trial_time{idsInMarker};
                        DataMarker(ids).Param(imark).no_samples = size(DataMarker(ids).Param(imark).trial_time,1);
                    end
                end
            end
        end
        
        setappdata(ImportGUI,'DataMarkerTable',DataMarker);
        
        %------------------------------------------------------------------------------------
    case 'AssignSubjectToDataSet'
        % When importing data, a subject needs to be assigned to all imported data sets 
        % prior to be included in to the BrainStorm database.
        % This is achieved here by selecting datasets in the RawDataList and then assigning 
        % a subject to them by selecting a subject from the database in LSubjects.
        % Subject can either be an existing one in the database, Default (with assumed default anatomy)
        % or New, therefore creating automatically a new Subject folder and file in the SUBJECTS folder.
        
        ImportGUI = gcbf; % handle to import_dataselector.fig
        handles = guihandles(ImportGUI);
        
        % Get the table of correspondence 
        % between data sets and subjects 
        % If does not exist, create one
        if isappdata(ImportGUI,'DataSubjectTable')
            DataSubject = getappdata(ImportGUI,'DataSubjectTable');
        else
            setappdata(ImportGUI,'DataSubjectTable',cell(length(get(handles.RawDataList,'String')),1));
            DataSubject = getappdata(ImportGUI,'DataSubjectTable');
        end
        
        %Which datasets are selected ?
        iDataSets = get(handles.RawDataList,'Value');
        
        % Which is the current subject ?
        iSubject = get(handles.LSubjects,'Value');
        
        % First remove previous subject that was selected for these datasets. 
        %DataSubject(iDataSets) = deal({[]});
        DataSubject(iDataSets) = deal({iSubject});
        
        setappdata(ImportGUI,'DataSubjectTable',DataSubject);
        
        %------------------------------------------------------------------------------------
        
        % case 'fromNEUROMAG'
        %     open('importparam.fig');
        %     set(gcf,'Userdata','neuromag') 
        %     delete(gcbf)
        %     system_name = findobj(gcf,'tag','system_name');
        %     set(system_name,'String','Neuromag Data Format')
        %     handles = findobj(gcf,'callback','importdata mutincomp2');
        %     set(handles,'Visible','off')
        %     
        %     open('listbox_win.fig')
        %     LISTBOX_WIN = findobj(0,'Tag','listbox_win');
        %     listboxx = findobj(LISTBOX_WIN,'Tag','listbox');
        %     
        %     
        %     [DataDir,DataPopup] = find_neuromag_data;
        %     if isempty(DataPopup)
        %         errordlg('No Neuromag files found in the current studies directory')
        %         return
        %     end
        %     
        %     set(listboxx,'String',DataPopup,'Userdata',DataDir,'Min',1,'Max',length(DataPopup))
        %     
        %     
        
        
        % --------------- ROUTINE TO LOAD RAW CHANNEL and DATA -------------------
    case 'fromRAW'
        
        % -------------- ASSIGN A BRAINSTORM STUDY TO THIS LOAD ------------------
        
        User = get_user_directory;
        cd(User.STUDIES)
        
        [StudyFile,StudyPath] = uigetfile(['*_brainstormstudy.mat'], ...
            'Please select the related BrainStorm Study File (cancel to build)');
        if StudyFile == 0, 
            % Cancelled, let build a study first
            fig = study_editor('create');
            uiwait(fig);
            [StudyFile,StudyPath] = uigetfile(['*_brainstormstudy.mat'], ...
                'Please select the related BrainStorm Study File (cancel to quit)');
            if StudyFile == 0, 
                % user is still cancelling out
                return
            end
        end
        cd(StudyPath)
        
        
        StudyNameRoot = findstr(StudyFile,'brainstormstudy.mat');
        if isempty(StudyNameRoot)
            errordlg('Study file name should be of the form ''*brainstormstudy.mat''')
            return
        end
        StudyNameRoot = StudyFile(1:StudyNameRoot-1);
        if strcmp(StudyNameRoot(end),'_'), % still have an underscore at end
            StudyNameRoot(end) = [];
        end
        
        
        % ---------------- GET THE CHANNEL LOCATION FILE NAME --------------------
        [ChannelFile, ChannelPath] = uigetfile({'*.txt;*.raw', 'All RAW Files(*.txt, *.raw)'},...
            'File of Sensor Locations (x,y,z) in Subject Coordinate System');
        if ChannelFile == 0, % cancelled
            return, 
        end
        cd(ChannelPath) % move to that directory, assume other files are there too.
        
        
        ans = questdlg('Which Coordinate System Convention?', 'Subject Coordinate System',...
            'CTF / Magnes','Neuromag','CTF / Magnes');
        switch ans
            case 'CTF / Magnes'
                SYSTEM = 'CTF'; % keyword
            case 'Neuromag'
                SYSTEM = 'NEUROMAG'; % keyword
        end
        
        
        % ------------------ READ THE CHANNEL LOCATION DATA ----------------------
        Channels_read = load_raw(ChannelFile,ChannelPath);
        
        NUM_CHANNELS = size(Channels_read,1); % number of channels to process
        
        % --------------- What type data is this? ------------------
        % The data can be EEG, MEG, or mixed array as read from a file
        DataType = questdlg(...
            'Are all channels identical, or should we read a file of types?',...
            'Homogeneous or Mixed Array Type (See Help -> Generic Data Loading)','MEG only','EEG only','Mixed: Read File','EEG only');
        TypeRead = cell(NUM_CHANNELS,1); % initialize as column vector
        
        switch DataType
            case 'Mixed: Read File'
                % --------------- Read the Data Type File ------------------
                [TypeFile, TypePath] = uigetfile({'*.txt', 'All Text Files(*.txt)'},...
                    'File of Sensor Types (lines of ASCII)');
                if TypeFile == 0, % cancelled
                    return, 
                end
                cd(TypePath)
                fid = fopen(TypeFile,'rt');
                for i = 1:NUM_CHANNELS,
                    TypeRead{i} = fgetl(fid); % no error handling on read
                    % now ensure it is a valid keyword
                    switch TypeRead{i}
                        case {'MEG','EEG','MEG REF','EEG REF','OTHER'}
                            % fine
                        otherwise
                            bst_message_window(sprintf(...
                                'Converting sensor %.0f with string "%s" to "OTHER"',i,TypeRead{i}));
                            TypeRead{i} = 'OTHER';
                    end % switch
                end
                fclose(fid);
                
            case 'MEG only'
                % all one type of sensor
                [TypeRead{1:NUM_CHANNELS}] = deal('MEG'); % homogeneous array
            case 'EEG only'
                [TypeRead{1:NUM_CHANNELS}] = deal('EEG'); % homogeneous array
        end % switch Dataype
        
        
        
        % Now we have all channel locations initially read, and we know what each
        % channel type is. Continuing loading more information
        
        % ----------------- GET THE FILENAMES FROM THE USER --------------------
        % CBB: Auto detect the names, but for now we're much more manual
        
        % ---------------- GET CHANNEL ORIENTATION FILE NAME -------------------
        [OrientFile, OrientPath] = uigetfile({'*.txt;*.raw', 'All RAW Files(*.txt, *.raw)'},...
            'File of Sensor Orientations (cos x, cos y, cos z) ("Cancel" if none)');
        if OrientFile == 0, % cancelled
            OrientFile = []; % none
            OrientPath = [];
        end
        
        % ---------------- GET CHANNEL LABELS FILE NAME, IF ANY ----------------
        [LabelFile, LabelPath] = uigetfile({'*.txt', 'All Text Files(*.txt)'},...
            'Optional File of Sensor Labels (text strings) ("Cancel" for default labels)');
        if LabelFile == 0, % cancelled, therefore default labels
            LabelFile = [];
            LabelPath = [];
        end
        
        % ---------- GET REFERENCE CHANNEL WEIGHTS FILE NAME, IF ANY ---------
        [ReferenceFile, ReferencePath] = uigetfile({'*.txt;*.raw', 'All RAW Files(*.txt, *.raw)'},...
            'Optional File of Reference Weights ("Cancel" if none)');
        if ReferenceFile == 0, % cancelled, therefore default labels
            bst_message_window('No reference weights loaded');
            ReferenceFile = [];
            ReferencePath = [];
        end
        
        % ---------- GET DATA FILE NAME ---------------
        [DataFile, DataPath] = uigetfile({'*.txt;*.raw', 'All RAW Files(*.txt, *.raw)'},...
            'File of Spatio-temporal Data Matrix ("Cancel" to quit)');
        if DataFile == 0, 
            return, 
        end
        
        % -------- GET DATA TIME FILE NAME, IF ANY ---------
        [TimeFile, TimePath] = uigetfile({'*.txt;*.raw', 'All RAW Files(*.txt, *.raw)'},...
            'Optional File of Time Values ("Cancel" for default time assignment)');
        if TimeFile == 0, 
            bst_message_window('Will use default times of one millisecond per sample');
            TimeFile = [];
            TimePath = [];
        end
        
        
        % --------- NOW LOAD THESE DATA ---------------------
        % we have the filenames (user did not cancel out), now get data
        
        
        % ---------- READ THE CHANNEL ORIENTATION DATA ----------
        Orient_read = load_raw(OrientFile, OrientPath); % will return empty if no such data
        
        % convert the read in channels into our structure
        NUM_CHANNELS = size(Channels_read,1);
        
        % ----------- READ THE CHANNEL LABELS, IF ANY ----------------
        LabelsRead = cell(NUM_CHANNELS,1);
        if ~isempty(LabelFile),
            cd(LabelPath)
            fid = fopen(LabelFile,'rt');
            for i = 1:NUM_CHANNELS,
                LabelsRead{i} = fgetl(fid); % no error handling
            end
        else
            % user gave no channels, form defaults
            for i = 1:NUM_CHANNELS,
                LabelsRead{i} = sprintf('%s Channel #%03.0f',TypeRead{i},i);
            end
        end
        
        % --------------------- READ THE REFERENCE WEIGHTS, IF ANY ---------
        
        Reference_Weights = load_raw(ReferenceFile, ReferencePath); % may return empty
        
        
        % --------- LOAD THE SPATIO-TEMPORAL DATA  ------------------      
        
        Data = struct('F',[],'Time',[],'ChannelFlag',[],'NoiseCov',[],'SourceCov',[],...
            'Projector',[],'Comment',[]);
        
        Data.F = load_raw(DataFile,DataPath);
        
        % now figure out if it needs transposing
        % CBB, but if we make it automatic, how do we catch square matrices or
        % matrice where they forgot one or two channels.
        [mF,nF] = size(Data.F);
        bst_message_window('wrap',sprintf('You have loaded %.0f Sensor Channels, and you have loaded',NUM_CHANNELS))
        bst_message_window('wrap',sprintf('a data matrix that is %.0f rows by %.0f columns.', mF, nF));
        bst_message_window('wrap',sprintf('The number of rows in the data matrix must be equivalent to the number of channels.'));
        
        if mF == NUM_CHANNELS,
            % probably don't need to transpose
            FlipData = questdlg(sprintf('Do we need to transpose this %.0f by %.0f data matrix (probably NOT!)?',mF,nF),...
                sprintf('You have %.0f channels of data',NUM_CHANNELS),'Yes','No','No');
        else
            % probably do need to transpose
            FlipData = questdlg(sprintf('Do we need to transpose this %.0f by %.0f data matrix (probably YES!)?',mF,nF),...
                sprintf('You have %.0f channels of data',NUM_CHANNELS),'Yes','No','Yes');
        end
        
        switch FlipData
            case 'Yes'
                Data.F = Data.F';
            case 'No'
                % do nothing
        end
        [mF,nF] = size(Data.F); % final size, spatio x temporal
        
        Data.Time = load_raw(TimeFile,TimePath);
        
        if isempty(Data.Time),
            % user did not give a time series, will synthesize
            Data.Time = [0:(nF-1)]/(nF-1) * .001; % one millisecond data
        end
        
        
        % Could be better, CBB, but for now apply this simple test
        if NUM_CHANNELS ~= mF,
            bst_message_window('wrap',sprintf('You have loaded a total %.0f Sensor channels, including possible references, ',NUM_CHANNELS))
            bst_message_window('wrap',sprintf('BUT, you have loaded %.0f rows of data.',mF));
            bst_message_window('wrap','The number of rows in the spatial temporal data matrix must match the number of channels.');
            bst_message_window('wrap','Please add/subtract in rows in the data matrix, including reference data, even if it is a row of zeros.')
            bst_message_window('wrap','See also HELP_DATA_CHANNEL, HELP_DATA_RAW, HELP_DATA_DATA');
            return
        end
        
        
        % ------------------- BUILD THE CHANNEL STRUCTURE ----------------------
        [Channel(1:NUM_CHANNELS)] = deal(struct('Loc',[],'Orient',[],'Weight',[],'Type',[],...
            'Comment',[]));
        
        for i = 1:NUM_CHANNELS,
            
            % ignore any NaNs on each line
            ndx = find(~isnan(Channels_read(i,:))); % each column is a sensor
            
            Channel(i).Loc = reshape(Channels_read(i,ndx),3,length(ndx)/3);
            if isempty(Orient_read), % no orientation file, should be EEG data
                Channel(i).Orient = []; % EEG
            else
                Channel(i).Orient = reshape(Orient_read(i,ndx),3,length(ndx)/3);
            end
            
            switch length(ndx)/3
                case 0 
                    % all NaN
                    Channel(i).Weight = [];
                case 1
                    Channel(i).Weight = 1;
                case 2
                    Channel(i).Weight = [1 -1]; % first order gradiometer
                case 3
                    Channel(i).Weight = [1 -2 1]; % second order gradiometer
                otherwise
                    error('Sorry, cannot handle higher than second order at this time.')
            end
            
            Channel(i).Type = TypeRead{i}; % 'MEG', 'EEG'
            Channel(i).Comment = '';
            Channel(i).Name = LabelsRead{i};
            
        end % building channel structure
        
        
        % ---------------- HANDLE THE REFERENCE CHANNEL CASES --------------------
        
        % Initialize
        EEGndx = find(strcmp({Channel.Type},'EEG'));
        MEGndx = find(strcmp({Channel.Type},'MEG'));
        EEGRefndx = find(strcmp({Channel.Type},'EEG REF'));
        MEGRefndx = find(strcmp({Channel.Type},'MEG REF'));
        
        if ~isempty(EEGndx),
            % there are EEG sensors, so are there EEG references?
            bst_message_window('wrap',sprintf(...
                'You have loaded a total %.0f EEG channels with %.0f channels denoted as reference channels',...
                length(EEGndx),length(EEGRefndx)));
            
            if ~isempty(EEGRefndx),
                % we have EEG reference channels loaded
                if length(EEGRefndx) > 1,
                    bst_message_window('wrap',sprintf('You have loaded more than one EEG reference electrode.'));
                    bst_message_window('wrap','Please edit your input to have only one EEG reference electrode.');
                end   
            else
                % we have no EEG reference channels loaded
                [Channel(EEGndx).Comment] = deal('AVERAGE REF');
                bst_message_window('wrap','You loaded no reference channels. Assuming Average Reference and averaging your data')
                Data.F = Data.F - repmat( mean(Data.F),NUM_CHANNELS,1); 
            end
        end % if the are EEG sensors
        
        if ~isempty(MEGndx),
            % there are MEG sensors, are there any MEG reference channels?
            bst_message_window('wrap',sprintf(...
                'You have loaded a total %.0f MEG channels with %.0f channels denoted as reference channels',...
                length(MEGndx),length(MEGRefndx)));
            
            if ~isempty(MEGRefndx),
                % we have MEG reference channels loaded as well
                Channel(MEGndx(1)).Comment = Reference_Weights;
                
            else
                % no MEG reference channels have been loaded
            end
        end % if there are MEG sensors
        
        
        Data.ChannelFlag = ones(1,length(Channel)); % all channels assumed initially good
        
        
        % ---- NEED TO HANDLE REFERENCE CHANNELS LABELS --------
        
        Data.NoiseCov = []; % unused for now
        Data.SourceCov = []; % unused for now
        Data.Projector = []; % unused for now
        Data.Comment = 'Imported RAW Data';
        Data.Device = SYSTEM;
        Data.System = SYSTEM;
        
        
        % --------------------------- Save the data ------------------------------
        
        cd(StudyPath) % ensure we are in the right directory
        
        chan_bst_file = [StudyNameRoot,'_channel'];
        
        save(chan_bst_file,'Channel');
        
        bst_message_window(['Channel Information Saved in: ',fullfile(StudyPath,chan_bst_file)]);
        
        save_sensor_locs(Channel) % local subfunction
        bst_message_window([...
                'Sensor locations can be checked in the MRI Tool by loading the file: sensor_result.mat'])
        drawnow
        
        addon = [];
        bst_file = [StudyNameRoot,'_data',addon];
        
        save_fieldnames(Data,bst_file); 
        bst_message_window(['Data Saved in: ',fullfile(StudyPath,bst_file)]);
        drawnow
        
        
        
        % --------------------------------------------------------------------------------
        
    case 'OK' % Parameters are all set - import data NOW !
        
        ImportGUI = gcbf; % handle to import_dataselector.fig
        handles = guihandles(ImportGUI);
        TASKBAR = getappdata(0,'BrainStormTaskbar');
        
        VERBOSE = get(handles.TVerbose,'value');
        
        makeuswait('start')
        
        if VERBOSE 
            clockk = fix(clock);
            bst_message_window({...
                    'Starting data import. . .',...
                    sprintf('%s - %dH %dmin %ds',date,clockk(4:6))...
                })
            time0 = clock;
        end
        
        % Load parameters from GUI -----------------------
        SeqBlockRW = get(handles.cSeqBlockRW,'Value'); % Sequential extraction and save of data chunks - slower but memory-saver
        
        % Get the Data Tables
        DataInformation = getappdata(ImportGUI,'DataInformationTable');
        DataMarkerInterval = getappdata(ImportGUI,'DataMarkerIntervalTable');
        DataSubject = getappdata(ImportGUI,'DataSubjectTable');
        DataTrialSelection = getappdata(ImportGUI,'DataTrialSelectionTable');
        
        %         % What datasets will be imported ?
        %         switch(upper(getappdata(ImportGUI,'System'))) % 
        %             
        %             case 'CTF' % Get full information about file and data
        %                 
        if get(handles.cUseMarkers,'Value') % do not need markers, import the entire selected datasets
            
            iDataDir = get(handles.RawDataList,'Value');
            DataDir = getappdata(handles.RawDataList,'DSFolders');
            DataDir = DataDir(iDataDir);
            Marker = []; % No Marker I said
            DataInformation = DataInformation(iDataDir); % restricted to selected data sets
            try 
                DataTrialSelection = DataTrialSelection(iDataDir);
            catch
                DataTrialSelection = [];
            end
            
            try 
                DataSubject = DataSubject(iDataDir); % idem
            catch % no subject was associated to selected data sets
                DataSubject = cell(length(iDataDir),1);
                [DataSubject(:)] = deal({1}); % Assume default subject
            end
            
            try 
                DataMarkerInterval = DataMarkerInterval(iDataDir); % If time range was user-specified
            catch
                % Do nothing - time interval are empty cells
            end
            
            MarkerFile = 0; % Flag - meaning we're NOT using markers
            
        else % Use marker infomation
            % Bring back the assignement tables 
            DataMarker = getappdata(ImportGUI,'DataMarkerTable');
            %Marker = getappdata(ImportGUI,'Markers');
            DataDir = getappdata(handles.RawDataList,'DSFolders');
            
            % Find data sets that were selected for importation
            % these are the ones which marker information is not empty
            iDataDir = [];
            for k = 1:length(DataMarker);
                if ~isempty(DataMarker(k).MarkerName) 
                    if (DataMarker(k).NoMarker == 0) 
                        iDataDir = [iDataDir k];
                    end
                end
            end
            DataDir = DataDir(iDataDir);
            DataMarker = DataMarker(iDataDir);
            
            if isempty(iDataDir) % No markers were defined for selected data sets
                errordlg('Please select markers for each selected data sets')
                return
            end
            DataInformation = DataInformation(iDataDir); % restricted to selected data sets
            
            % Get MarkerFile information from current dataset
            DataMarkerFile = getappdata(ImportGUI,'DataMarkerFileTable');
            DataMarkerFile = DataMarkerFile(iDataDir);
            
            % Now check whether all data sets have corresponding subjects assigned
            try 
                DataSubject = DataSubject(iDataDir); % idem
            catch % no subject was associated to selected data sets
                DataSubject = cell(length(iDataDir),1);
                [DataSubject(:)] = deal({1}); % Assume default subject
                
                if VERBOSE
                    bst_message_window({...
                            'Assuming Default Subject for data set(s):',...
                            DataDir{:}...
                        });
                end
            end
            
            try 
                DataMarkerInterval = DataMarkerInterval(iDataDir); % If time range was user-specified
            catch
                % Do nothing - time interval are empty cells
            end
            
            MarkerFile = 1; % Flag - meaning we're using markers
        end
                
        %             otherwise % If SYSTEM ~= CTF
        %                 
        %                 % Do nothing
        %                 
        %         end % Switch (SYSTEM)
        %        
        cd(Users.STUDIES) % Raw data sets are located in the STUDIES folder - so let's go.
        
        
        % --------------------------------------
        % For each of the selected data folders
        
        for K = 1:length(DataDir) 
            
            
            % For clarity puroposes in database organization, 
            % and rather than exporting data directly into the original data folder,
            % create a BrainStorm folder in data fodler and store the BsT files in it.
            
            % Look for possibly existing BrainStorm folder in the .ds folder
            % we are already in Users.STUDIES, search from here
            if ~isdir(DataDir{K})
                homeDir = fileparts(DataDir{K});
            else
                homeDir = DataDir{K};
            end
                
            BsTFolders = dir(fullfile(homeDir,'*BrainStorm'));
            % Look for folders only
            if ~isempty(BsTFolders)
                BsTFolders = BsTFolders([BsTFolders.isdir] == 1);
            end
            
            if isempty(BsTFolders) % No BrainStorm folder found - create one 
                [SUCCESS,MESSAGE,MESSAGEID] = mkdir(fullfile(Users.STUDIES,homeDir),'BrainStorm');
                if ~SUCCESS % error while creating the directory
                    bst_message_window('wrap','Error creating the BrainStorm default directory:')
                    if ispc,
                        % accept that there really was an error
                        errordlg(MESSAGE);
                    else
                        % pc is the only non-unix platform. Problem with linux systems (sometimes)
                        %  returning bad status, as of 15 Dec 2003
                        % Does the BrainStorm directory exist?
                        if exist(fullfile(Users.STUDIES,DataDir{K},'BrainStorm'),'dir'),
                            bst_message_window('wrap',{...
                                    'You are running a non-PC operating system.',...
                                    'There may be no actual error, since your directory exists.',...
                                    MESSAGE,...
                                    'Proceeding as if there were no error'});
                        else
                            % no directory, there really is a problem
                            error(MESSAGE)
                        end
                    end
                end
            end
            
            % Deprecated code : SB - I'd rather create a study file anytime we're importing the data (if at multiple instances)
            % rather than manage several study files in same folder. This does not make too much sense for me anymore.
            % Oooooh things, they are changing .............
            
            %             [DataDir,DataPopup,Leader] = find_brainstorm_files('studies',DataDir{K});
            %             % Does not account for possibly multiple studies in one ds folder
            %             % Our convention so far is to have a single study file per .ds folder
            %             
            %if isempty(DataPopup) | isempty(findstr(DataPopup,'study')) % No Study File available
            % Create one
            
            [path, rooot,ext] = fileparts(DataDir{K});
            study_file = [rooot,'_brainstormstudy.mat']; % Take the name of the .ds folde as prefix to the BrainStorm Study file. 
            
            % Fill-out study fields
            Study.DateOfModification = date; % Default importation date
            Study.Session = []; % SB : Don't know what to do with this - of minor importance I think
            
            % Now we can assign or even create a Subject structure from the importation routine
            % What subject was selected for this study ?
            switch(DataSubject{K})
                case 1 % Default subject was assigned
                    SubjectFolder = fullfile(Users.SUBJECTS,'BrainStormDefault');
                    if ~exist(SubjectFolder,'dir') % No default subject folder in Subjects data base
                        % create one
                        cd(Users.SUBJECTS)
                        [SUCCESS,MESSAGE,MESSAGEID] = mkdir('BrainStormDefault');
                        if ~SUCCESS % error while creating the directory
                            error(MESSAGE);
                            return
                        end
                        Name = 'BrainStorm Default'; % Name of Default Subject
                        save(fullfile(SubjectFolder,'bstdefault_brainstormsubject.mat'),'Name')
                    end
                    
                    Study.BrainStormSubject = fullfile('Default','bstdefaut_brainstormsubject.mat');
                    %getpref('BrainStorm','DefaultSubject');
                    
                case 2 % Create new subject folder
                    SubjectFolder = strrep(DataDir{K},'.','_Subject'); % Build subject's folder name from data set prefix.
                    [SUCCESS,MESSAGE,MESSAGEID] = mkdir(Users.SUBJECTS,SubjectFolder);
                    if ~SUCCESS % error while creating the directory
                        error(MESSAGE);
                        return
                    end
                    % Create new SubjectFile
                    [path,File,ext]= fileparts(DataDir{K}); 
                    SubjectFile = [File,'_brainstormsubject.mat'];
                    Study.BrainStormSubject = fullfile(SubjectFolder,SubjectFile);
                    Name = [File, ' Subject'];
                    save(fullfile(Users.SUBJECTS,Study.BrainStormSubject),'Name')
                    
                otherwise % Get existing subject
                    Subjects = getpref('BrainStorm','Subjects',[]);
                    if(~isempty(Subjects)),
                        Study.BrainStormSubject = Subjects(DataSubject{K}-2).SubjectFile;
                    end
            end    
            
            if VERBOSE
                bst_message_window('wrap',{,...
                        sprintf('Subject was assigned to data set %s',DataDir{K}),...
                        sprintf('Subject File: %s',Study.BrainStormSubject),...
                    });
            end
            
            cd(Users.STUDIES)
            
            % Not too happy with the following - needs to be loaded from the .res4 file.
            System = ''; 
            Device = '';
            NoiseCov = [];
            SourceCov = [];
            Projector = [];
            addon = []  ;       
            F = [];
            
            %-- Switch to available data formats
            
            switch upper(getappdata(ImportGUI,'System')) % Type of data to be imported
                
                case 'RAW'
                    % our generic import routines, both ASCII and Binary
                    
                    importdata('fromRAW')
                    
                case {'BESA','NEUROSCAN','EGI'}
                    % Call F. Darvas import
                    % routines-------------------------------
                    
                    % save out Study file
                    Study.Name = deblank(DataDir{K});
                    Study.DateOfStudy = 'N/A'; % Acquisition date 
                    cd(fullfile(Users.STUDIES,fileparts(DataDir{K}),'BrainStorm'))    
                    save_fieldnames(Study, study_file);
                    % -> Done
                    
                    
                    % --------------------------- Get channel information
                    
                    % Pick a original channel file name
                    cd(fullfile(Users.STUDIES,fileparts(DataDir{K})))
                    [channelFile, pathname] = uigetfile( ...
                        {'*.elp';'*.mdl';'*.dat';'*.res';'*.sfp'}, ...
                        'Pick the original file containing informations about electrodes locations and labels');
                    if(~channelFile) %if no channelfile is choosen
                        bst_message_window('wrap',...
                            'Process canceled by user; no channel file was selected ');
                        return
                    end
                    
                    % Call Darvas routine
                    [tmp,tmp,channelType] = fileparts(channelFile); % Channel file type given by file extension
                    [Channel,Landmark] = elpos2bs(fullfile(pathname,channelFile),'',strrep(channelType,'.',''));
                    

                        
                        
                    
                    % Save channel information.
                    save(fullfile('BrainStorm',[rooot,'_channel.mat']),'Channel','Landmark','-mat');
                    
                    % Read data 
                    [tmp,tmp,dataType] = fileparts(DataDir{K}); % Data file type given by file extension
                    Data = eeg2bs(DataDir{K},'',strrep(dataType,'.',''), Channel);

                    %                     % Specify missing data fields
                    %                     Data.System = 'ctf'; 
                    %                     Data.Device = 'Ctf_Axial_151';

                    % Save in BrainStorm format
                    bst_file = fullfile(fileparts(DataDir{K}),'BrainStorm',[rooot,'_data']);
                    
                    save_fieldnames(Data,fullfile(Users.STUDIES,bst_file))
                    if VERBOSE
                        bst_message_window('wrap',...
                            ['Saving ',bst_file]);
                    end
                    
                    
                case 'CTF'
                    
                    DCOffset = getappdata(ImportGUI,'DCOffset'); % DCOffset flag
                    
                    % save out Study file
                    Study.Name = deblank(DataInformation{K}.nfSetUp.nf_run_title);
                    Study.DateOfStudy = deblank(DataInformation{K}.data_date); % Acquisition date 
                    cd(fullfile(Users.STUDIES,DataDir{K},'BrainStorm'))    
                    save_fieldnames(Study, study_file);
                    % -> Done
                    
                    % Specify missing data fields
                    System = 'ctf'; 
                    Device = 'Ctf_Axial_151';
                    
                    %-----------------------------------------------------------------------
                    res4_mat = fullfile(Users.STUDIES,DataDir{K},'BrainStorm',[rooot,'_res4.mat']);
                    
                    if MarkerFile == 0 % No markerfile is present - import the whole trials within a given time extraction window
                        
                        % Get time range specifications
                        if ~isempty(DataMarkerInterval{K})
                            DataMarker(K).TimeRange = str2num(DataMarkerInterval{K});
                        else
                            DataMarker(K).TimeRange = []; % Import whole trial
                        end
                        
                        % get Trial selection specifications
                        if ~isempty(DataTrialSelection{K})
                            try
                                Trials = str2num(DataTrialSelection{K});
                            catch
                                errordlg(sprintf('Unvalid numerical writing: %s', DataTrialSelection{K}))
                            end
                        else
                            Trials = []; % Import all trials
                        end
                        
                        % Keep data in native data file format ?
                        if get(handles.TNativeFormat,'Value')
                            READRES = 3; % Code for ds2brainstorm routine
                        else
                            READRES = 0; % Code for ds2brainstorm routine
                        end
                        
                        
                        [Ftmp,Channel,imegsens,ieegsens,iothersens,irefsens,grad_order_no,no_trials,filter,Time, Comment] = ...
                            ds2brainstorm(fullfile(Users.STUDIES,DataDir{K}),VERBOSE,READRES,[],DataMarker(K).TimeRange,Trials,DCOffset);
                        
                        % ------------------------------ DEFINE EEG REFERENCE
                        % When EEG data is available,
                        % check here if an EEG reference was defined.
                        % If not, ask for it and store it somewhere so that when the Channel.mat file is created, the EEG reference 
                        % is properly defined.
                        
                        if ~isempty(ieegsens) % EEG Data is available
                            
                            SameRefForAll = get(handles.checkSameRefForAll,'Value'); % Flag: 1 means "same EEG reference all selected data sets"
                            if SameRefForAll ~= 1 % Not the same EEG reference for all selected data sets - ask for a new reference then.
                                
                                % NOT IMPLEMENTED YET !
                                % At this time, user needs to select data sets with same EEG reference.
                                
                                % Open listbox figure and fill with EEG electrode names
                                TriList = openfig('generic_listbox_win.fig');
                                TriHandles = guihandles(TriList);
                                set(TriHandles.listbox,'String',char({'Average Reference',char(Channel(ieegsens).Name)}),...
                                    'ListboxTop',1,'Max',1)
                                set(TriList,'Name','Select EEG Reference')
                                set(TriHandles.DONE,'Callback',sprintf('%s EEGRefSelected', mfilename))
                            end
                            
                            % Update Channel structure    
                            EEGRef = get(handles.popupEEGRef,'Value');
                            if EEGRef == 1 % Average Reference
                                [Channel(ieegsens).Comment] = deal('AVERAGE REF'); % Average potentials reference.
                            else
                                Channel(ieegsens(EEGRef - 1)).Type = 'EEG REF'; % Specific channel for EEG reference.
                            end
                        end
                        % ------------------------------ DEFINE EEG REFERENCE - DONE
                        
                        save(fullfile('BrainStorm',[rooot,'_channel.mat']),'Channel','-mat');
                        
                        %Correct data in nth-order gradient if originaly saved in raw format 
                        if ~isempty(find(grad_order_no(imegsens)==0))
                            ButtonName = questdlg('Would you like to save the data sets with the 3rd-order gradient correction ?','Raw data detected','Yes','No','Yes');
                            switch(ButtonName)
                                case 'No'
                                    % Do nothing
                                    CorrectionFlag = 0;
                                case 'Yes'
                                    % Apply correction to all trials
                                    CorrectionFlag = 1;
                            end             
                        else
                            % Do nothing
                            CorrectionFlag = 0;
                        end
                        
                        if ~get(handles.TNativeFormat,'Value')
                            
                            for trial = 1:length(Ftmp) % For each trial
                                
                                % Are we splitting Trials into several BrainStorm data files ? 
                                switch get(handles.cSplitTrials,'Value')
                                    case 1 % YES
                                        
                                        F = Ftmp{trial};
                                        
                                        % Generate a new Time vector according to the TimeRange
                                        [time] = findclosest(DataMarker(K).TimeRange, Time');
                                        %                         [mm,time(1)] = min(abs(Time - DataMarker(K).TimeRange(1)));
                                        %                         [mm,time(2)] = min(abs(Time - DataMarker(K).TimeRange(2)));
                                        nSamples = min([size(F,2),time(2)-time(1)+1]);
                                        time(2) = time(1)+nSamples-1;
                                        Time = Time(time(1):time(2));
                                        
                                    case 0 % NO: concatenate in a single data file (.mat)
                                        ntrials = length(Ftmp); % Number of trials to concatenate in single file
                                        for trial = 1:ntrials
                                            F = [F,Ftmp{trial}];
                                        end          
                                        % Generate a new Time vector 
                                        % according to the TimeRange and number of concatenated trials
                                        [time] = findclosest(DataMarker(K).TimeRange, Time');
                                        %                         [mm,time(1)] = min(abs(Time - TimeRange(1)));
                                        %                         [mm,time(2)] = min(abs(Time - TimeRange(2)));
                                        nSamples = min([size(F,2),time(2)-time(1)+1]);
                                        time(2) = time(1)+nSamples-1;
                                        Time = Time(time(1):time(2)); % Time is the time vector for only one trial
                                        % Extend to ntrials
                                        Time = [Time(1):Time(2)-Time(1):ntrials*Time(end)];       
                                end
                                
                                if CorrectionFlag
                                    % Apply 3rd-order gradient correction if data originally stored as 1st-order gradc corrected
                                    fprintf('Applying Gradient Correction....')
                                    F(imegsens,:) = F(imegsens,:) - Channel(imegsens(1)).Comment*F(irefsens,:);               
                                    fprintf('Applying Gradient Correction....DONE')
                                end
                                
                                % Suffix to DataFile names
                                addon = ['_Trial',int2str(Trials(trial))];
                                bst_file = fullfile(DataDir{K},'BrainStorm',[rooot,'_data',addon]);
                                
                                if trial == 1 % Fill-out ChannelFlag
                                    
                                    ChannelFlag = ones(size(F,1),1); % By default
                                    
                                    % Look for a badchannel file if exists
                                    cd(Users.STUDIES)
                                    if exist(fullfile(DataDir{K},'BadChannels'),'file')
                                        badchan_name = textread(fullfile(DataDir{K},'BadChannels'),'%s');
                                        if ~isempty(badchan_name)
                                            bst_message_window(['Removing Bad Channels. . . - Trial',int2str(Trials(trial))])
                                            [tmp I] = intersect({Channel(:).Name},badchan_name);
                                            ChannelFlag(I) = -1; % set as bad
                                            bst_message_window('Removing Bad Channels. . .  - DONE')
                                        end
                                    end
                                end
                                
                                save(fullfile(Users.STUDIES,bst_file),'F','ChannelFlag','Device','Time','NoiseCov','SourceCov','Projector','Comment','System');
                                if VERBOSE
                                    bst_message_window('wrap',...
                                        ['Saving ',bst_file]);
                                end
                                
                            end  % For each trial
                            
                        else % Keep data in native file format
                            
                            F = Ftmp;
                            
                            % Data file name
                            addon = ['_NativeFormat'];
                            bst_file = fullfile(DataDir{K},'BrainStorm',[rooot,'_data',addon]);
                            
                            
                            ChannelFlag = ones(length(Channel),1); % By default
                            
                            % Look for a badchannel file if exists
                            cd(Users.STUDIES)
                            if exist(fullfile(DataDir{K},'BadChannels'),'file')
                                badchan_name = textread(fullfile(DataDir{K},'BadChannels'),'%s');
                                if ~isempty(badchan_name)
                                    bst_message_window(['Removing Bad Channels. . . - Trial',int2str(file)])
                                    [tmp I] = intersect({Channel(:).Name},badchan_name);
                                    ChannelFlag(I) = -1; % set as bad
                                    bst_message_window('Removing Bad Channels. . .  - DONE')
                                end
                            end
                            
                            save(fullfile(Users.STUDIES,bst_file),'F','ChannelFlag','Device','Time','NoiseCov','SourceCov','Projector','Comment','System');
                            if VERBOSE
                                bst_message_window('wrap',...
                                    ['Saving ',bst_file]);
                            end
                            
                        end
                        
                    else % Import data corresponding to selected marker
                        
                        if ~exist(res4_mat,'file') % Res4 file does not exist - create it
                            ds2brainstorm(fullfile(Users.STUDIES,DataDir{K}),VERBOSE);    % Read data information only
                        end
                        
                        load(res4_mat); % Now load all resources information
                        TimeOrig = Time; % Original trial time window
                        Comment = RunTitle;
                        
                        % ------------------------------ DEFINE EEG REFERENCE
                        % When EEG data is available,
                        % check here if an EEG reference was defined.
                        % If not, ask for it and store it somewhere so that when the Channel.mat file is created, the EEG reference 
                        % is properly defined.
                        
                        if ~isempty(ieegsens) % EEG Data is available
                            
                            SameRefForAll = get(handles.checkSameRefForAll,'Value'); % Flag: 1 means "same EEG reference all selected data sets"
                            if SameRefForAll ~= 1 % Not the same EEG reference for all selected data sets - ask for a new reference then.
                                
                                % NOT IMPLEMENTED YET !
                                % At this time, user needs to select data sets with same EEG reference.
                                
                                % Open listbox figure and fill with EEG electrode names
                                TriList = openfig('generic_listbox_win.fig');
                                TriHandles = guihandles(TriList);
                                set(TriHandles.listbox,'String',char({'Average Reference',char(Channel(ieegsens).Name)}),...
                                    'ListboxTop',1,'Max',1)
                                set(TriList,'Name','Select EEG Reference')
                                set(TriHandles.DONE,'Callback',sprintf('%s EEGRefSelected', mfilename))
                            end
                            
                            % Update Channel structure    
                            EEGRef = get(handles.popupEEGRef,'Value');
                            if EEGRef == 1 % Average Reference
                                [Channel(ieegsens).Comment] = deal('AVERAGE REF'); % Average potentials reference.
                            else
                                Channel(ieegsens(EEGRef - 1)).Type = 'EEG REF'; % Specific channel for EEG reference.
                            end
                        end
                        % ------------------------------ DEFINE EEG REFERENCE - DONE
                        
                        
                        save(fullfile(Users.STUDIES,DataDir{K},'BrainStorm',[rooot,'_channel.mat']),'Channel','-mat');
                        
                        %Correct data in nth-order gradient if originaly saved in raw format 
                        if ~isempty(find(grad_order_no(imegsens)==0))
                            ButtonName = questdlg('Would you like to save the data sets with the 3rd-order gradient correction ?','Raw data detected','Yes','No','Yes');
                            switch(ButtonName)
                                case 'No'
                                    % Do nothing
                                    CorrectionFlag = 0;
                                case 'Yes'
                                    % Apply correction to all trials
                                    CorrectionFlag = 1;
                            end             
                        else
                            % Do nothing
                            CorrectionFlag = 0;
                        end
                        
                        % Channels to be extracted
                        CHANNELS = [1:length(Channel)]; % CBB - needs to be more flexible; e.g. extract a subset of channels                    
                        
                        %save(fullfile(Users.STUDIES,DataDir{K},'BrainStorm',[rooot,'_channel.mat']),'Channel','-mat');
                        
                        % Time Range
                        try 
                            DataMarker(K).TimeRange = str2num(DataMarkerInterval{K});
                        catch
                            errordlg(sprintf('Unvalid numerical writing: %s', DataMarkerInterval{K}))
                        end
                        
                        cd(Users.STUDIES)
                        if VERBOSE
                            bst_message_window('wrap',{...
                                    ' ',...
                                    sprintf('-------- Processing dataset %s', DataDir{K})...
                                });
                        end
                        
                        if ~get(handles.TNativeFormat,'Value') % Don't keep data under native format
                            
                            % Now loop on each Markers for this dataset.
                            for mrk = 1:length(DataMarker(K).MarkerName)
                                
                                if VERBOSE
                                    bst_message_window('wrap',{...
                                            sprintf('Extracting marker ''%s'' data', DataMarker(K).MarkerName{mrk})...
                                        });
                                end
                                
                                if get(handles.cSeqBlockRW,'Value') == 0 % Read all trials from selected marker at once
                                    
                                    Ftmp = extract_ctf_markers(...
                                        DataDir{K}, DataMarker(K).TimeRange, CHANNELS, DataMarker(K).MarkerName,...
                                        DataMarker(K).Param, VERBOSE);
                                    Ftmp = Ftmp{1};
                                    
                                    for trial = 1:size(Ftmp,3) % For each trial
                                        
                                        % Are we splitting Trials into several BrainStorm data files ? 
                                        switch get(handles.cSplitTrials,'Value')
                                            case 1 % YES
                                                
                                                F = Ftmp(:,:,trial);
                                                
                                                if trial == 1% Generate a new Time vector according to the TimeRange
                                                    %[mm,time(1)] = min(abs(Time - DataMarker(K).TimeRange(1)));
                                                    %[mm,time(2)] = min(abs(Time - DataMarker(K).TimeRange(2)));
                                                    time = findclosest(DataMarker(K).TimeRange, Time');
                                                    nSamples = min([size(F,2),time(2)-time(1)+1]);
                                                    time(2) = time(1)+nSamples-1;
                                                    Time = Time(time(1):time(2));
                                                end
                                                
                                                % Suffix to DataFile names
                                                addon = ['_',deblank(strrep(DataMarker(K).MarkerName{mrk},' ','')),'_Sample',int2str(trial)];
                                                
                                            case 0 % NO: concatenate in a single data file (.mat)
                                                ntrials = length(Ftmp); % Number of trials to concatenate in single file
                                                for trial = 1:ntrials
                                                    F = [F,Ftmp(:,:,trial)];
                                                end          
                                                % Generate a new Time vector 
                                                % according to the TimeRange and number of concatenated trials
                                                %[mm,time(1)] = min(abs(Time - TimeRange(1)));
                                                %[mm,time(2)] = min(abs(Time - TimeRange(2)));
                                                time = findclosest(DataMarker(K).TimeRange, Time');
                                                nSamples = min([size(F,2),time(2)-time(1)+1]);
                                                time(2) = time(1)+nSamples-1;
                                                Time = Time(time(1):time(2)); % Time is the time vector for only one trial
                                                % Extend to ntrials
                                                Time = [Time(1):Time(2)-Time(1):ntrials*Time(end)];       
                                                
                                                % Suffix to DataFile names
                                                addon = ['_',deblank(strrep(DataMarker(K).MarkerName{mrk},' ','')),'_AllSamples'];
                                        end
                                        
                                        
                                        bst_file = fullfile(DataDir{K},'BrainStorm',[rooot,'_data',addon]);
                                        
                                        if trial == 1
                                            %Correct data in nth-order gradient if originaly saved in raw format 
                                            if ~isempty(find(grad_order_no(imegsens)==0))
                                                ButtonName = questdlg('Would you like to save the data sets with the 3rd-order gradient correction ?','Raw data detected','Yes','No','Yes');
                                                switch(ButtonName)
                                                    case 'No'
                                                        % Do nothing
                                                        CorrectionFlag = 0;
                                                    case 'Yes'
                                                        % Apply correction to all trials
                                                        CorrectionFlag = 1;
                                                end             
                                            else
                                                % Do nothing
                                                CorrectionFlag = 0;
                                            end
                                            
                                            ChannelFlag = ones(size(F,1),1); % By default
                                            % Look for a badchannel file if exists
                                            cd(Users.STUDIES)
                                            if exist(fullfile(DataDir{K},'BadChannels'),'file')
                                                badchan_name = textread(fullfile(DataDir{K},'BadChannels'),'%s');
                                                if ~isempty(badchan_name)
                                                    bst_message_window(['--------------------- Removing Bad Channels Trial',int2str(trial),' -----------------------'])
                                                    [tmp I] = intersect({Channel(:).Name},badchan_name);
                                                    ChannelFlag(I) = -1; % set as bad
                                                    bst_message_window('--------------------- Removing Bad Channels - DONE -------------------------------')
                                                end
                                            end
                                        end
                                        
                                        if CorrectionFlag
                                            % Apply 3rd-order gradient correction if data originally stored as 1st-order gradc corrected
                                            fprintf('Applying Gradient Correction....')
                                            F(imegsens,:) = F(imegsens,:) - Channel(imegsens(1)).Gcoef*F(irefsens,:);               
                                            fprintf('Applying Gradient Correction....DONE')
                                        end
                                        
                                        save(bst_file,'F','ChannelFlag','Device','Time','NoiseCov','SourceCov','Projector','Comment','System');
                                        
                                        if VERBOSE
                                            bst_message_window('wrap',...
                                                ['Saving ',bst_file]);
                                        end
                                    end  % For each trial
                                    
                                else % Lighter memory load: proceed by block-reading
                                    
                                    % Set nsamples to 1 and proceed iteratively
                                    DataMarker(K).Paramtmp.nsamples = 1;
                                    
                                    % Loop on each Marker occurence of current Marker
                                    for isample = 1:size(DataMarker(K).Param(mrk).trial_time,1)
                                        
                                        if VERBOSE
                                            bst_message_window('wrap',{...
                                                    sprintf('Marker sample : %d/%d', isample,DataMarker(K).Param(mrk).no_samples)...
                                                });
                                        end
                                        
                                        DataMarker(K).Paramtmp.trial_time = DataMarker(K).Param(mrk).trial_time(isample,:); % Latency for current sample
                                        F = ... 
                                            ds2brainstorm(fullfile(Users.STUDIES,DataDir{K}),VERBOSE,0,CHANNELS,...
                                            DataMarker(K).Param(mrk).trial_time(isample,2)+DataMarker(K).TimeRange,...
                                            DataMarker(K).Param(mrk).trial_time(isample,1),DCOffset);
                                        
                                        F = F{1};
                                        
                                        % Requested time window might be clipped
                                        % because marker could be too close from original
                                        % trial time window edges
                                        % Generate a new Time vector according to the TimeRange
                                        tmpTime = TimeOrig - DataMarker(K).Param(mrk).trial_time(isample,2); % Center trial time window around marker occurence
                                        tmp = findclosest(DataMarker(K).TimeRange,tmpTime);
                                        Time = tmpTime(tmp);
                                        Time = linspace(Time(1),Time(2),size(F,2));                           
                                        
                                        if CorrectionFlag
                                            % Apply 3rd-order gradient correction if data originally stored as 1st-order gradc corrected
                                            fprintf('Applying Gradient Correction....')
                                            F(imegsens,:) = F(imegsens,:) - Channel(imegsens(1)).Gcoef*F(irefsens,:);               
                                            fprintf('Applying Gradient Correction....DONE')
                                        end
                                        
                                        if isample == 1
                                            cd(Users.STUDIES)
                                            ChannelFlag = ones(size(F,1),1); % By default
                                        end
                                        
                                        addon = ['_',deblank(strrep(DataMarker(K).MarkerName{mrk},' ','')),'_Sample',num2str(isample)];
                                        bst_file = fullfile(DataDir{K},'BrainStorm',[rooot,'_data',addon]);
                                        
                                        % Look for a badchannel file if exists
                                        cd(Users.STUDIES)
                                        if exist(fullfile(DataDir{K},'BadChannels'),'file')
                                            badchan_name = textread(fullfile(DataDir{K},'BadChannels'),'%s');
                                            if ~isempty(badchan_name)
                                                bst_message_window('- Removing Bad Channels, Trial',int2str(isample))
                                                [tmp I] = intersect({Channel(:).Name},badchan_name);
                                                ChannelFlag(I) = -1; % set as bad
                                                bst_message_window('- Removing Bad Channels -> DONE')
                                            end
                                        end
                                        save(bst_file,'F','ChannelFlag','Device','Time','NoiseCov','SourceCov','Projector','Comment','System');
                                        if VERBOSE
                                            bst_message_window('wrap',...
                                                ['Saving ',bst_file]);
                                            
                                        end
                                        
                                    end % for each of current marker's sample
                                    
                                end % if sequential block RW
                                
                            end % For each Marker of selected dataset
                            
                        else % Keep data in Native format
                            
                            F = Ftmp;
                            
                            % Data file name
                            addon = ['_NativeFormat'];
                            bst_file = fullfile(DataDir{K},'BrainStorm',[rooot,'_data',addon]);
                            
                            ChannelFlag = ones(length(Channel),1); % By default
                            
                            % Look for a badchannel file if exists
                            cd(Users.STUDIES)
                            if exist(fullfile(DataDir{K},'BadChannels'),'file')
                                badchan_name = textread(fullfile(DataDir{K},'BadChannels'),'%s');
                                if ~isempty(badchan_name)
                                    bst_message_window(['Removing Bad Channels. . . - Trial',int2str(file)])
                                    [tmp I] = intersect({Channel(:).Name},badchan_name);
                                    ChannelFlag(I) = -1; % set as bad
                                    bst_message_window('Removing Bad Channels. . .  - DONE')
                                end
                            end
                            
                            save(fullfile(Users.STUDIES,bst_file),'F','ChannelFlag','Device','Time','NoiseCov','SourceCov','Projector','Comment','System');
                            if VERBOSE
                                bst_message_window('wrap',...
                                    ['Saving ',bst_file]);
                            end
                            
                        end
                        
                        
                    end % if MarkerFile
                                        
                    if VERBOSE
                        bst_message_window(sprintf('Done with %s', DataDir{K}));
                        bst_message_window('wrap',{...
                                ' ',...
                                sprintf('Done with %s', DataDir{K})...
                                'Bon appetit !',...
                                ' '...
                            });
                    end 
            
                case 'NEUROMAG' 
                    % Was working in  Helinski, Sept 2001
                    % Needs to be revisited though for importation of data projectors
                    %
                    % Necessitate the meg_1.2 routines + control that is actually running under any Linux plateform
                    % cf. http://boojum.hut.fi/~kuutela/meg-pd/
                    
                    DataFiles = DataDir(get(listboxx,'value'));
                    
                    % Coil coordinates in device coordinate system
                    Coil = cell(4001,1); % This cell array of structures contain the information on every type of coils that are used in the Neuromag/BTi systems
                    
                    Coil{2}.Description = 'Neuromag-122 planar gradiometer';
                    Coil{2}.n = 2; % Number of integration points
                    Coil{2}.xyz = [8.1 0 0 ; -8.1 0 0]'; % Locations of Integration points for the magnetic field (mm)
                    Coil{2}.weights = [1/16.2 -1/16.2]; % weights to be applied at each integration point          
                    
                    Coil{3012}.Description = 'VectorView type 1 planar gradiometer';
                    Coil{3012}.n = 2; % Number of integration points
                    Coil{3012}.xyz = [8.4 0 0.3 ; -8.4 0 0.3]'; % Locations of Integration points for the magnetic field (mm)
                    Coil{3012}.weights = [1/16.8 -1/16.8]; % weights to be applied at each integration point          
                    
                    Coil{3013}.Description = 'VectorView type 2 planar gradiometer';
                    Coil{3013}.n = 2; % Number of integration points
                    Coil{3013}.xyz = [8.4 0 0.3 ; -8.4 0 0.3]'; % Locations of Integration points for the magnetic field (mm)
                    Coil{3013}.weights = [1/16.8 -1/16.8]; % weights to be applied at each integration point          
                    
                    Coil{3022}.Description = 'VectorView type 1 magnetometer';
                    Coil{3022}.n = 4; % Number of integration points
                    Coil{3022}.xyz = [12.9 12.9 0.3 ;12.9 -12.9 0.3 ;...
                            -12.9 12.9 0.3; -12.9 -12.9 0.3]'; % Locations of Integration points for the magnetic field (mm)
                    Coil{3022}.weights = [1/4 1/4 1/4 1/4]; % weights to be applied at each integration point          
                    
                    Coil{3023}.Description = 'VectorView type 2 magnetometer';
                    Coil{3023}.n = 4; % Number of integration points
                    Coil{3023}.xyz = [12.9 12.9 0.3 ;12.9 -12.9 0.3 ;...
                            -12.9 12.9 0.3; -12.9 -12.9 0.3]'; % Locations of Integration points for the magnetic field (mm)
                    Coil{3023}.weights = [1/4 1/4 1/4 1/4]; % weights to be applied at each integration point          
                    
                    Coil{2000}.Description = 'Ideal point magnetometer';
                    Coil{2000}.n = 1; % Number of integration points
                    Coil{2000}.xyz = [0 0 0];
                    Coil{2000}.weights = [1]; % weights to be applied at each integration point          
                    
                    Coil{4001}.Description = 'Magnes WH magnetometer';
                    Coil{4001}.n = 4; % Number of integration points
                    Coil{4001}.xyz = [5.75 5.75 0; -5.75 5.75 0;...
                            -5.75 -5.75 0; 5.75 -5.75 0]';
                    Coil{4001}.weights = [1/4 1/4 1/4 1/4]; % weights to be applied at each integration point          
                    
                    
                    for K = 1:length(DataFiles)
                        
                        if VERBOSE
                            bst_message_window({...
                                    ' ',...
                                    '----------------------------------------------------------------------------------',...            
                                    ' Processing Channel Information ',...
                                    '----------------------------------------------------------------------------------',...            
                                    ' '...
                                })
                        end
                        
                        fifFile = DataFiles{K};
                        %             channel_file = [channel_fileo(1:min(findstr(channel_fileo,'.'))),'apos'];
                        
                        % Run megmodel to access channel information
                        megmodel([0 0 0], fifFile);
                        
                        if ~exist('chaninfo','file') % meg_1.2 routines not available on this machine
                            errordlg('meg_1.2 routines not available on this machine. Please check the following link: http://boojum.hut.fi/~kuutela/meg-pd/');
                            return
                        end
                        
                        [ChanType, ChanName,T] = chaninfo;
                        [GradPlan,Name] = chaninfo('type'); % GradPlan = 0 for magnetometers, 1 for gradiometers; Name indicates the system Neuromag_122 or Vectorview or Magnes
                        
                        % CHEAT - Discard Gradiometers
                        if VERBOSE
                            bst_message_window('Magnetometers were discarded from the importation' )
                            drawnow
                        end
                        iGrad = find(GradPlan);
                        ChanType = ChanType(iGrad);
                        ChanName = ChanName(iGrad,:);
                        GradPlan = GradPlan(iGrad);
                        Name = Name(iGrad);
                        T = T(iGrad);
                        
                        nchan= length(T); % Number of channels
                        ieeg = 0; imeg = 0; 
                        iother = 0; 
                        megID = [];
                        eegID = [];
                        otherID = [];
                        
                        
                        chaneeg = [];% Index of EEG channels 
                        chanmeg = [];chanother = [];
                        
                        [Channel(1:nchan)] = deal(struct('Loc',[],'Orient',[],'Comment',[],'Weight',[],'Type',[],'Name',''));
                        if VERBOSE
                            % hwait = waitbar(0,'Reading Channel Information...');
                            bst_message_window('Reading Channel Information');
                            bst_message_window(sprintf('Reading %.0f of %.0f . . .',1,nchan));
                        end
                        
                        for chan = 1:nchan
                            if VERBOSE
                                % waitbar(chan/nchan,hwait)
                                if(~rem(nchan,20)), % not every time
                                    bst_message_window('overwrite',...
                                        sprintf('Reading %.0f of %.0f . . .',chan,nchan));
                                end
                            end
                            
                            switch upper(strtok(ChanName(chan,:)))
                                case 'MEG'
                                    if nchan == 122 % A little cheat here as the channel type is not obtained explicitly from th ecurrent chaninfo routine
                                        % Check for channel type
                                        Device = 'Neuromag-122';
                                        switch GradPlan(chan)
                                            case 0 % Magnetometer - should not occur with the Neuromag 122
                                                CType = 2000;
                                            case 1 % Gradiometer
                                                CType = 2;
                                        end
                                        
                                    elseif nchan == 204%306
                                        Device = 'Vectoview-306';
                                        switch GradPlan(chan)
                                            case 0 % Magnetometer - 
                                                CType = 3022;
                                            case 1 % Gradiometer
                                                CType = 3012;
                                        end
                                        
                                    end % Otherwise, I don't know how to handle the Magnes channels
                                    
                                    Channel(chan).Loc = T{chan}*[Coil{CType}.xyz/1000;ones(1,Coil{CType}.n)];
                                    Channel(chan).Loc = Channel(chan).Loc(1:3,:);
                                    Channel(chan).Orient = T{chan}*[[0 0 1]' * ones(1,Coil{CType}.n);zeros(1,Coil{CType}.n)];
                                    Channel(chan).Orient = Channel(chan).Orient(1:3,:);
                                    
                                    %Channel(chan).Comment = setdiff(ChanName(chan,:),strtok(ChanName(chan,:)));
                                    Channel(chan).Comment = ChanName(chan,:);
                                    Channel(chan).Type = 'MEG';%upper(strtok(Label(chan,:)));
                                    chanmeg = [chanmeg,chan];
                                    Channel(chan).Weight = Coil{CType}.weights*1000 ;  
                                    imeg = imeg + 1;
                                    megID(imeg) = chan;   
                                    Channel(chan).Name = strrep(Channel(chan).Comment,'MEG ','');  
                                case 'EEG' % Should not be available from 4D data
                                    ieeg = ieeg + 1;
                                    eegID(ieeg) = chan;   
                                    if ~isempty(Extra)
                                        if ieeg < max(size(Extra))
                                            Channel(chan).Loc =[Extra(ieeg,:)',Extra(ieeg,:)'];
                                        else
                                            Channel(chan).Loc = [];
                                        end
                                        
                                        Channel(chan).Orient = [];
                                        Channel(chan).Type = 'EEG';%upper(strtok(Label(chan,:)));
                                        Channel(chan).Comment = [Label(chan,:),' ',int2str(ieeg)];
                                    end
                                    Channel(chan).Type = upper(strtok(Label(chan,:)));
                                    Channel(chan).Comment = [Label(chan,:),' ',int2str(ieeg)];
                                    Channel(chan).Weight = [];   
                                    chaneeg = [chaneeg,chan];
                                    Channel(chan).Name = int2str(ieeg) ;  
                                    
                                otherwise
                                    iother = iother+1;
                                    otherID(iother) = chan;   
                                    Channel(chan).Loc = [];
                                    Channel(chan).Orient = [];
                                    Channel(chan).Type = 'OTHER';
                                    Channel(chan).Comment = [Label(chan,:),' ',int2str(iother)];
                                    Channel(chan).Weight = [];   
                                    chanother = [chanother,chan];
                                    Channel(chan).Name = int2str(iother) ;  
                            end
                            
                        end % End load chaninfo
                        
                        
                        if VERBOSE
                            % close(hwait)
                        end
                        
                        
                        
                        %ChannelID = {megID,eegID,otherID};
                        Current = getfield(get(TASKBAR,'Userdata'),'Users');
                        cd(Current.STUDIES)
                        
                        [study_file,path] = uigetfile(['*_brainstormstudy.mat'], 'Please select the related BrainStorm Study File');
                        if study_file == 0, return, end
                        
                        cd(path)
                        save_sensor_locs(Channel) % local subfunction
                        bst_message_window(['Sensor locations can be checked in the MRI Tool by loading the file: sensor_result.mat'])
                        drawnow
                        
                        rooot = findstr(study_file,'brainstormstudy.mat');
                        if isempty(rooot)
                            errordlg('Study file name should be of the form ''*brainstormstudy.mat''')
                            return
                        end
                        rooot = study_file(1:rooot-2);
                        
                        chan_bst_file = [rooot,'_channel'];
                        
                        if VERBOSE
                            bst_message_window({...
                                    ' ',...
                                    '----------------------------------------------------------------------------------',...            
                                    ' Processing Channel Information -> DONE ',...
                                    '----------------------------------------------------------------------------------',...            
                                    ' '...
                                })
                        end
                        
                        % ------------------------------------------------------------------------------- Reading Data 
                        
                        if VERBOSE
                            bst_message_window({...
                                    '----------------------------------------------------------------------------------',...            
                                    ' ',...
                                    sprintf('BrainStorm -> Reading Data Information - %s',fifFile)...
                                });
                        end
                        
                        if VERBOSE
                            bst_message_window({...
                                    'BrainStorm -> Done',...
                                    '----------------------------------------------------------------------------------',...
                                    ' '...
                                })
                        end
                        
                        [N,comments]=loadfif(fifFile,'sets'); % How many data sets are there ?
                        
                        NoiseCov = [];
                        SourceCov = [];
                        Projector = [];
                        for subfile = 1:N
                            [F,sfreq,t0]=loadfif(fifFile,subfile-1);                      
                            
                            if size(F,1)>204 % There are magnetometers here
                                F = F(iGrad,:);
                            end
                            ChannelFlag = ones(size(F,1),1); % By default
                            
                            Time = t0+[0:1/sfreq:size(F,2)/sfreq-1/sfreq];  % in seconds
                            
                            Comment = comments{subfile};
                            bst_message_window(Comment)
                            drawnow
                            
                            addon = [];
                            Data = struct('datafile','','F',F,'ChannelFlag',ChannelFlag,'Time',Time,'NoiseCov',NoiseCov,...
                                'SourceCov',SourceCov,'Projector',Projector,'Comment',Comment,'addon',addon);
                            
                            Data = struct2cell(Data); 
                            [datafile, Fo,Channelo,Time,NoiseCov,SourceCov,Projector,Comment,addon] = deal(Data{:});
                            if N > 1
                                addon = ['_',num2str(subfile)];
                            end
                            id = findstr(lower(fifFile),'.fif');
                            rooot = strrep(fifFile(1:id-1),'.','_');
                            bst_file = [rooot,'_data',addon];
                            %Device = 'Neuromag_Planar_122';
                            
                            System = 'neuromag';
                            
                            save(bst_file,'F','ChannelFlag','System','Device','Time','NoiseCov','SourceCov','Projector','Comment');
                            
                        end
                        
                        
                        I = findstr(bst_file,['_data']);
                        if isempty(I)
                            error('Cannot find file for channel information')
                            return
                        end
                        
                        ChannelFile = bst_file(1:I-1);
                        ChannelFile = [ChannelFile,'_channel']; 
                        save(ChannelFile ,'Channel'); 
                        
                    end
                    
                    if VERBOSE
                        msgbox(['Data saved in BrainStorm format in ',bst_file(1:end),'.mat'],'BrainStorm Message');
                        %msgbox(['Channel information saved in ',ChannelFile,'.mat'],'BrainStorm Message');
                    end
                    
            end % switch(SYSTEM)
        
        end % for each file to import... for Datadir
        
        if VERBOSE 
            clockk = fix(clock);
            bst_message_window({...
                    'Finished data importation:',...
                    sprintf('%s - %dH %dmin %ds (took %3.2f seconds)',date,clockk(4:6), etime(clock,time0))...
                })
        end
        
        makeuswait('stop')
        
        % --------------------------------------------------------------------------------
    case 'mutincomp' % Raw/Average
        handles = findobj(gcbf,'callback','importdata mutincomp');
        mutincomp(handles) 
        
        
    end % end of major switchyard and this function   
    
    % --------------------------------------------------------------------------------
    function  save_sensor_locs(Channel)
    % Save Channel location in a pseudo-result file for visualization in the MRITool
    
    nchan = length(Channel);
    meg = good_channel(Channel,ones(nchan,1),'MEG');
    eeg = good_channel(Channel,ones(nchan,1),'EEG');
    
    nchan= length([meg,eeg]);
    SourceLoc = cell(1,nchan);
    
    i = 0;
    for k = [meg,eeg]
        i = i+1;
        SourceLoc{i} = Channel(k).Loc(:,1);
        SourceOrder(i) = -1;
        Comment = 'Sensor Locations';
    end   
    
    DataFlag = 'Sensors';
    save sensor_result SourceLoc SourceOrder DataFlag Comment
    
