function DATA = extract_ctf_markers(DS_FOLDER, MARKER_RANGE, CHANNELS, MarkerNames, MARKERPARAM, VERBOSE);
%EXTRACT_CTF_MARKERS - Extract signal block from a .ds CTF data set based on the Markers information in the Markerfile
% function DATA = extract_ctf_markers(DS_FOLDER, MARKER_RANGE, CHANNELS, MarkerNames, MARKERPARAM, VERBOSE);
%
% function DATA = extract_ctf_markers(DS_FOLDER, MARKER_RANGE, CHANNELS, MarkerNames, MARKERPARAM, VERBOSE);
% DS_FOLDER : String containing the name of the .ds folder (CTF data set format only)
% MARKER_RANGE : Time window of extraction (in seconds) about the listed markers.
% CHANNELS : Vector of channel indices to be extracted.
% MarkerNames : Cell array of strings of Marker NAMES to be read from the MarkerFile in corresponding DS_FOLDER.
%           Marker names need to correspond to marker names found in dataset's MarkerFile.
%           If left blank, all Markers from DS_FOLDER will be read.
% MARKERPARAM : Cell array of structure (one cell per Marker) containing Marker information with following fields:
%           .nsamples   :  Vector containing the number of occurences of each Marker in data set. 
%           .trial_time : Array Ntrials x 2 ; Ntrials is the number of trials where corresponding marker was found
%                         First column is the index of the trials where Marker was found
%                         Second column is the set of latencies from trial time 0 where Marker was found in given trial
% 
% VERBOSE : Verbose flag.

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

% /---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                    |
% |                                                      |
% \------------------------------------------------------/

% Script History --------------------------------------------------------
%
% Script Creation : March 2001 (bst_extractmarkersctf.m).
% SB  28-Jul-2002 : Renamed to currenty mfilename 
% ............... : Updated help header and file description
% ............... : MakerNames (was MarkerNames in bst_extract...) used to be a set of indices; it is now a cell array of strings (Marker names)

% NOTE : Some of the variables (e.g. ONLINE_AV) are used when function is used as a stand-alone script.
% SB : will leave it this way in first BsT MMII release.

ONLINE_AV = 0; % if set to 1, runs the online average of each trial and does not return the original data.
ONLINE_SW_AV = 0; % Same thing but for sample-weighted average 
% MarkerNames = [2]; % Array of markers to be read from the file - if empty, reads out all trials from all markers
% 
% VERBOSE = 1;
% [MARKERPARAM.names,MARKERPARAM.nsamples ,MARKERPARAM.trial_time] = readmarkerfile_ctf(DS_FOLDER);

% Original root folder
rootfolder = pwd;

% Name of MarkerFile
MarkerFile = fullfile(DS_FOLDER,'MarkerFile.mrk');
% Check if MarkerFile exists
if ~exist(MarkerFile,'file')
    error(...
        sprintf('MarkerFile $s was not found in %s.',MarkerFile,DS_FOLDER));
    return
end

% Read MarkerFile information
[MARKERPARAM.names,MARKERPARAM.nsamples ,MARKERPARAM.trial_time] = readmarkerfile_ctf(DS_FOLDER);
if isempty(MarkerNames) % Read all Markers in file
    MarkerNames = MARKERPARAM.names;
end

% Number of selected markers 
n_markers = length(MarkerNames);

% Find Markers indices in MarkerFile
iMarkers = []; % set of indices of selected Markers in MarkerFile
for kk = 1:length(MarkerNames)
    iMarkers = [iMarkers, find(strcmp(MARKERPARAM.names,MarkerNames{kk}))];
end

imark = 0;

for i = iMarkers
    
    imark = imark+1;
    
    % Are there several time from sync points for this marker ? 
    utime = unique(MARKERPARAM.trial_time{i}(:,2));
    if length(utime) == 1 % NO
        % Read all trials at once
        %F = ds2brainstorm(DS_FOLDER,VERBOSE,0,CHANNELS,MARKER_RANGE,MARKERPARAM.trial_time{i}(:,1)');
        F = ds2brainstorm(DS_FOLDER,VERBOSE,0,CHANNELS,MARKERPARAM.trial_time{i}(2)+MARKER_RANGE,MARKERPARAM.trial_time{i}(1));

        % F is a MARKERPARAM.trial_time{i}(:,1)-long cell array
        %        DATA{imark}  = zeros(length(CHANNELS),size(F{1},2),MARKERPARAM.nsamples(i)));
        for k = 1:length(MARKERPARAM.trial_time{i}(:,1))
            DATA{imark}(:,:,k) = F{k};
            F{k} = [];
        end
        clear F
        
    else % YES
        % Read trial by trial
        for k = 1:MARKERPARAM.nsamples(i)
            cd(rootfolder)
            F = ds2brainstorm(DS_FOLDER,VERBOSE,0,CHANNELS,MARKERPARAM.trial_time{i}(k,2)+MARKER_RANGE,MARKERPARAM.trial_time{i}(k,1));
            if k>1
                if size(F{1},2) < size(DATA{imark},2)
                    error('Please check the duration of MARKER_RANGE')
                else
                    F{1} = F{1}(:,1:size(DATA{imark},2));
                end
            else
                if ONLINE_AV == 0;
                    DATA{imark} = zeros(length(CHANNELS),size(F{1},2),MARKERPARAM.nsamples(i));
                else
                    DATA{imark} = zeros(length(CHANNELS),size(F{1},2));
                end
                
            end

            if ONLINE_AV == 0
                DATA{imark}(:,:,k) = F{1};
            else
                DATA{imark} = DATA{imark}+F{1}/MARKERPARAM.nsamples(i);
            end
            
            
            if VERBOSE
                fprintf('Trial %d\n',k);
            end
            
            clear F
        end
        
    end
    
end

% This part for averaging only

% 
% for i = 1:n_markers
%     data_av{i} = mean(DATA{imark},3);
%     figure, plot(MARKER_RANGE(1):1/SAMPLING_RATE:MARKER_RANGE(2),data_av{i}')
%     title(['Marker ',num2str(i)])
% end



