% Script 1: Defines LFP and EEG data into a structure-array that is compatible with 
%           Fieldtrip functions. We contrast two conditions: ntrl and emo
%           Please cite the JoVE publication if you make use of this
%           scripts and the anaylsis ideas.
%           


fs=512;            % Specify the sampling rate of data
bl=2;
stim_duration=4;   % Define Stimulus duration

lfp_r_ntrl=dlmread('Path_directory\Filename_LFP_right_condition_ntrl');
lfp_l_ntrl=dlmread('Path_directory\Filename_LFP_left_condition_ntrl');
eeg_dir='Path_directory\Filename_EEG_condition_ntrl';
t4_ntrl=dlmread([eeg_dir,'T4Cz.txt']);
t3_ntrl=dlmread([eeg_dir,'T3Cz.txt']);
pz_ntrl=dlmread([eeg_dir,'PzCz.txt']);
oz_ntrl=dlmread([eeg_dir,'OzPz.txt']);
fz_ntrl=dlmread([eeg_dir,'FzCz.txt']);

ntrl.label={'LFPR23','LFPL23','EEGT4Cz','EEGT3Cz','EEGPzCz','EEGOzPz','EEGFzCz'};
ntrl.fsample=512;
ntrl.time{1}=1:1/fs:(length(t4_ntrl)/fs);
ntrl.sampleinfo=[1 length(t4_ntrl)];
ntrl.trial{1}=[lfp_r_ntrl';lfp_l_ntrl';t4_ntrl';t3_ntrl';pz_ntrl';oz_ntrl';fz_ntrl'];

trl_ntrl=csvread('Path_directory\Filename_ntrl_Markers.txt');
trl_ntrl=trl_ntrl(:,1);
trl_ntrl=[trl_ntrl-round(bl*fs) trl_ntrl+round(stim_duration*fs) zeros(length(trl_ntrl),1)-round(bl*fs)];
trl_ntrl=trl_ntrl(2:end,:);

cfg=[];
cfg.trl=trl_ntrl;
ntrl=ft_redefinetrial(cfg,ntrl);

lfp_r_emo=dlmread('Path_directory\Filename_LFP_right_condition_emo.txt');
lfp_l_emo=dlmread('Path_directory\Filename_LFP_left_condition_emo.txt');
eeg_dir='Path_directory\Filename_EEG_condition_emo';
t4_emo=dlmread([eeg_dir,'T4Cz.txt']);
t3_emo=dlmread([eeg_dir,'T3Cz.txt']);
pz_emo=dlmread([eeg_dir,'PzCz_emo.txt']);
oz_emo=dlmread([eeg_dir,'OzPz_emo.txt']);
fz_emo=dlmread([eeg_dir,'FzCz_emo.txt']);

emo.label={'LFPR23','LFPL23','EEGT4Cz','EEGT3Cz','EEGPzCz','EEGOzPz','EEGFzCz'};
emo.fsample=512;
emo.time{1}=1:1/fs:(length(t4_emo)/fs);
emo.sampleinfo=[1 length(t4_emo)];
emo.trial{1}=[lfp_r_emo';lfp_l_emo';t4_emo';t3_emo';pz_emo';oz_emo';fz_emo'];

trl_emo=csvread('Path_directory\Filename_emo_Markers.txt');
trl_emo=trl_emo(:,1);
trl_emo=[trl_emo-round(bl*fs) trl_emo+round(stim_duration*fs) zeros(length(trl_emo),1)-round(bl*fs)];
trl_emo=trl_emo(2:end,:);

cfg=[];
cfg.trl=trl_emo;
emo=ft_redefinetrial(cfg,emo);

% In case artifact rejection needs to be performed Please uncomment the
% following lines:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% cfg=[];
% cfg.method='trial';
% cfg.eegscale=.25;
% dummy_ntrl=ft_rejectvisual(cfg,ntrl);
% dummy_emo=ft_rejectvisual(cfg,emo);

% emo=dummy_emo;
% ntrl=dummy_ntrl;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

save Path_directory\Filename.mat ntrl emo % Two structure variables (ntrl and emo) are saved into the specified file 