%% Conversion into BIDS - Variability of Infant Directed Actions project

%% Section 1: specification of folders

clear;

user = getenv('USER');
if isempty(user)
    user = getenv('UserName');
end

switch user
    
    case 'U567154'
        scripts     = '\Documents\Donders\S_MotioneseEEG\Paper\Additional_Info\Data2bids-Scripts\Variability Infant Directed Actions';
        sourcedata  = '\Documents\Donders\S_MotioneseEEG\Paper\Additional_Info\sourcedata';
        bidsroot    = 'BIDS';
    otherwise
        error('you have top specify the local directories of the data and this code');
end

addpath(scripts);
cd(sourcedata)

% Delete the current BIDS folder if it already exists
if exist(bidsroot, 'dir')
    rmdir(bidsroot, 's');
end

%% Section 2: subject information

sub = {'P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8', 'P9', 'P10', 'P12', 'P13', 'P14', 'P15', 'P16', 'P17', 'P18', 'P19', 'P20', 'P21', 'P22', 'P23', 'P24', 'P25', 'P26', 'P27', 'P28', 'P29', 'P30',...
    'P31', 'P32', 'P33', 'P35', 'P36', 'P37', 'P38', 'P40', 'P41', 'P42', 'P43', 'P44', 'P45', 'P46', 'P47'};

age = [480, nan, nan, nan, nan, nan, 486, nan, 486, 484, nan, nan, 479, 482, nan, 491, nan, nan, nan,...
    nan, 483, 500, 484, nan, 475, nan, 473, 485, 474, nan, 474, nan, 483, 502, nan, nan, 493,...
    487, 477, nan, 504, 503, 489, nan];

sex = {'m' '' '' '' '' '' 'm' '' 'm' 'm' '' '' 'm' 'm' '' 'f' '' '' ''...
    '' 'f' 'm' 'm' '' 'f' '' 'f' 'm' 'f' '' 'm' '' 'f' 'f' '' '' 'm'...
    'f' 'f' '' 'f' 'm' 'm' ''};

incl = {'yes' 'no' 'no' 'no' 'no' 'no' 'yes' 'no' 'yes' 'yes' 'no' 'no' 'yes' 'yes' 'no' 'yes' 'no' 'no' 'no'...
    'no' 'yes' 'yes' 'yes' 'no' 'yes' 'no' 'yes' 'yes' 'yes' 'no' 'yes' 'no' 'yes' 'yes' 'no' 'no' 'yes'...
    'yes' 'yes' 'no' 'yes' 'yes' 'yes' 'no'};


%% Section 3: General information for the data2bids function

% Here we start looping over subjects
for ii = 1:length(sub)
    
    % The data is already in BrainVision format, we can simply copy the file
    cfg                                         = [];
    cfg.method                                  = 'copy';
    cfg.bidsroot                                = bidsroot;
    cfg.datatype                                = 'eeg';
    cfg.writejson                               = 'replace';
    
    %% Section 4: the dataset_description.json
    
    cfg.dataset_description.Name                = 'Variability in infant-directed actions';
    cfg.dataset_description.DatasetType         = 'raw';
    cfg.dataset_description.BIDSVersion         = '1.2.0';
    cfg.dataset_description.License             = 'ODC-ODbL-1.0';
    cfg.dataset_description.Authors             = {'Marlene Meyer', 'Johanna E. van Schaik', 'Francesco Poli', 'Sabine Hunnius'};
    
    
    %% Section 5: the participants tsv
    
    cfg.sub                               = sub{ii};
    cfg.participants.age                  = age(ii);
    cfg.participants.sex                  = sex{ii};
    cfg.participants.included             = incl{ii};
    
    %% Section 6: the data set
    
    cfg.dataset                           = ['EEG' filesep  cfg.sub '.vhdr'];
    if cfg.dataset
        hdr                                   = ft_read_header(cfg.dataset);
    end
    
    %% Section 7: the EEG json
    
    % Describing the task
    cfg.TaskName                                    = 'action_demonstration';
    cfg.TaskDescription                             = 'infants observed an avator perform actions such as stacking cups';
    cfg.Instructions                                = 'none';
    
    % Describing the recording setup
    cfg.InstitutionName                             = 'The Donders Institute for Brain, Cognition and Behaviour'; % The name of the institution in charge of the equipment that produced the composite instances.
    cfg.InstitutionAddress                          = 'Heyendaalseweg 135, 6525 AJ Nijmegen, the Netherlands';
    cfg.InstitutionalDepartmentName                 = 'Donders Centre for Cognition';
    
    cfg.Manufacturer                                = 'Brain Products GmbH'; % Manufacturer of the recording system
    cfg.ManufacturersModelName                      = 'BrainAmp Standard'; % Manufacturer's designation of the model
    cfg.eeg.CapManufacturer                         = 'Brain Products GmbH'; % name of the cap manufacturer
    cfg.eeg.CapManufacturersModelName               = 'actiCAP 32Ch'; % Manufacturer's designation of the EEG cap model
    cfg.eeg.EEGPlacementScheme                      = '10-20'; % Placement scheme of the EEG electrodes
    cfg.eeg.EEGReference                            = 'TP9'; % Description of the type of reference used
    cfg.eeg.EEGGround                               = 'AFz'; % Description of the location of the ground electrode
    
    cfg.eeg.SamplingFrequency                       = 500; % Sampling frequency (in Hz)
    % NOTE: the amplifier always samples at 5000 Hz in hardware, the data
    % is then downsampled to 500 Hz in software
    cfg.eeg.PowerLineFrequency                      = 50; % Frequency (in Hz) of the power grid where the EEG is installed (i.e. 50 or 60).
    cfg.eeg.HardwareFilters.LowCutoff.Frequency     = 0.1;
    cfg.eeg.HardwareFilters.HighCutoff.Frequency    = 1000;
    cfg.eeg.SoftwareFilters.LowCutoff.Frequency     = 0.1;
    cfg.eeg.SoftwareFilters.HighCutoff.Frequency    = 200; % List of temporal software filters applied or ideally  key:value pairs of pre-applied filters and their parameter values
    
    cfg.eeg.EEGChannelCount                         = 32; % Number of EEG channels
    % cfg.eeg.EOGChannelCount               = % None in these recordings
    % cfg.eeg.ECGChannelCount               = % None in these recordings
    % cfg.eeg.EMGChannelCount               = % None in these recordings
    % cfg.eeg.MiscChannelCount              = % Number of miscellaneous analog channels for auxiliary  signals
    % cfg.eeg.TriggerChannelCount           = % Number of channels for digital and analog triggers.
    
    % Describing the recording
    cfg.eeg.RecordingType                           = 'continuous';
    % cfg.eeg.RecordingDuration             = % Read automatically
    % cfg.eeg.EpochLength                   = % Read automatically
    
    % Possible additional info
    % cfg.eeg.HeadCircumference             = % Circumference of the participants head, not known for these recordings
    % cfg.eeg.SubjectArtefactDescription    = % Freeform description of the observed subject artefact and its possible cause (e.g. "Vagus Nerve Stimulator", "non-removable implant").
    
    
    %% Section 8: the events.tsv.
    
    % To do this, first create events using ft_define_trial
    cfg_trials                      = cfg;
    cfg_trials.trialdef.eventtype   = 'Stimulus';
    trl                             = trialfun_motionese(cfg_trials);
    cfg.events                      = trl;
    
    %% Section 9: the channels.tsv
    
    % Double info with eeg.tsv --> here only fill it out if it is channel specific
    
    cfg.channels.name               = hdr.label;
    cfg.channels.type               = repmat({'EEG'}, 32, 1);  % Type of channel
    cfg.channels.units              = repmat({'uV'}, 32, 1);% Physical unit of the data values recorded by this channel in SI
    cfg.channels.sampling_frequency = repmat(500, 32, 1); % Sampling rate of the channel in Hz.
    cfg.channels.low_cutoff         = repmat(0.1, 32, 1); % Frequencies used for the hardware high-pass filter applied to the channel in Hz
    cfg.channels.high_cutoff        = repmat(1000, 32, 1); % Frequencies used for the hardware low-pass filter applied to the channel in Hz.
    cfg.channels.notch              = nan(32, 1); % Frequencies used for the notch filter applied to the channel, in Hz. If no notch filter applied, use n/a.
    
    % cfg.channels.software_filters   = {' "Low Cutoff": 0.1', ' "High Cutoff": 125'}; % List of temporal and/or spatial software filters applied.
    % cfg.channels.description        = % OPTIONAL. Brief free-text description of the channel, or other information of interest. See examples below.
    % cfg.channels.status             = % OPTIONAL. Data quality observed on the channel (good/bad). A channel is considered bad if its data quality is compromised by excessive noise. Description of noise type SHOULD be provided in [status_description].
    % cfg.channels.status_description = % OPTIONAL. Freeform text description of noise or artifact affecting data quality on the channel. It is meant to explain why the channel was declared bad in [status].
    
    
    %% Call data2bids
    
    data2bids(cfg);
    
    %% Add behavioural data: demonstration phase
    
    % Find the corresponding excel file
    
    subject_number                                = sum(str2double(regexp(cell2mat(sub(ii)),'\d+','match')));
    str_subject                                   = ['_P' num2str(subject_number) '_'];
    filelist                                      = dir(fullfile(['VideoCoding' filesep 'ObservationPhase_Looking']));
    excel_obs ={};
    for ll = 1:size(filelist, 1)
        if ~isempty(strfind(filelist(ll).name, str_subject))
            excel_obs = ['VideoCoding' filesep 'ObservationPhase_Looking' filesep filelist(ll).name];
        end
    end
    
    if ~isempty(excel_obs) % if there is behavioral coding for this infant
        
        excel_observation                             = xlsread(excel_obs);      
        % Convert this info to a table
        tsv_obs                                       = read_excel_observation(excel_observation,cfg);
    
        % Add the correct folder
        foldername                                    = [bidsroot filesep 'sub-P' num2str(subject_number) filesep 'beh'];
        mkdir(foldername);
        filename                                      = [foldername filesep 'sub-P' num2str(subject_number) '_task-' cfg.TaskName '_events.tsv'];
        write_tsv(filename, tsv_obs);
        
        %% Add the behavioural events json, demonstration phase
        
        events_json                                 = [];
        events_json.onset.description               = 'Onset of the event in the EEG';
        events_json.onset.units                     = 'seconds';
        events_json.duration.description            = 'Duration of the event';
        events_json.duration.units                  = 'seconds';
        events_json.coded_period.description         = 'Period of annotation looking behaviour';
        events_json.coded_period.levels              = {'fixation cross: looking behaviour during entire fixation cross',...
            'intro: looking behaviour during entire introduction video',...
            'exp_phase1: from start stimulus video till the avator moves head down',...
            'exp_phase2: from head moves down till first hand movement',...
            'exp_phase3: during first action (start till stop hand movement)',...
            'exp_phase4: during second action (start till stop hand movement)',...
            'exp_phase5: during third action (start till stop hand movement)',...
            'exp_phase6: during fourth action (start till stop hand movement)',...
            'exp_phase7: during fifth action (start till stop hand movement)',...
            'exp_phase8: from last hand movement till head moves up',...
            'exp_phase9: from head moves up till end stimulus video',...
            'peek-a-boo_start: from start peek-a-boo video till moment avatar eyes fully covered)',...
            'peek-a-boo_hidden_[1-4]: hidden period per second',...
            'peek-a-boo_ende: first moment eyes visible again till end video'};
        
        events_json.annotation.description          = 'annotation of looking behaviour';
        events_json.annotation.levels               = {'1: child looked at the screen for the entire coded period', '0: child did not look at the screen for the entire coded period'};
        foldername                                  = [bidsroot filesep 'sub-P' num2str(subject_number) filesep 'beh'];
        filename                                    = [foldername filesep 'sub-P' num2str(subject_number) '_task-' cfg.TaskName '_events.json'];
        
        write_json(filename, events_json);
    end
    %% Behavioural data: exploration phase
    
    % Find the corresponding excel file
    
    subject_number                                = sum(str2double(regexp(cell2mat(sub(ii)),'\d+','match')));
    str_subject                                   = ['p' num2str(subject_number) '_'];
    filelist                                      = dir(fullfile(['VideoCoding' filesep 'ExplorationPhase_Behavior']));
    excel_expl ={};
    for ll = 1:size(filelist, 1)
        if ~isempty(strfind(filelist(ll).name, str_subject))
            excel_expl = ['VideoCoding' filesep 'ExplorationPhase_Behavior' filesep filelist(ll).name];
        end
    end
    if ~isempty(excel_expl)
        exploration_num                           = xlsread(excel_expl);        
        % Then convert info to a table
        
        coded_behaviour                            = {'A1_AllObjectsBase', 'A1_FirstObjectTouched', 'A1_PerformedTargetAction',...
            'A1_NumberTimesSuccesful', 'A1_NumberAttempts', 'A1_NumberAttemptsdWrongObject',...
            'A2_AllObjects', 'A2_FirstObjectTouched', 'A2_PerformedTargetAction',...
            'A2_NumberTimesSuccesful', 'A2_NumberAttempts', 'A2_NumberAttemptsdWrongObject',...
            'A3_AllObjects', 'A3_FirstObjectTouched', 'A3_PerformedTargetAction',...
            'A3_NumberTimesSuccesful', 'A3_NumberAttempts', 'A3_NumberAttemptsdWrongObject',...
            'T1_TargetObjectOnly', 'T1_PerformedTargetAction','T1_NumberTimesSuccesful', 'T1_NumberAttempts',...
            'T2_TargetObjectOnly', 'T2_PerformedTargetAction','T2_NumberTimesSuccesful', 'T2_NumberAttempts',...
            'T3_TargetObjectOnly', 'T3_PerformedTargetAction','T3_NumberTimesSuccesful', 'T3_NumberAttempts'}';
        annotation                                    = exploration_num(2:end);
        onset                                     = repmat({'ObjectsTouchTable'}, length(coded_behaviour), 1);
        duration                                  = repmat(60, length(coded_behaviour), 1);
        tsv_expl                                  = table(onset, duration, coded_behaviour, annotation);
        
        % Add it to the correct folder
        foldername                                    = [bidsroot filesep 'sub-P' num2str(subject_number) filesep 'beh'];
        filename                                      = [foldername filesep 'sub-P' num2str(subject_number) '_task-exploration_events.tsv'];
        write_tsv(filename, tsv_expl);
        %% Add the behavioural events json, exploration phase
        
        events_json                                 = [];
        events_json.onset.description               = 'Onset of the coded behaviour';
        events_json.duration.description            = 'Duration of the coded behaviour';
        events_json.duration.units                  = 'seconds';
        events_json.coded_behaviour.description      = 'Behaviour that was coded for 1 minute after objects were presented to the infant';
        events_json.coded_behaviour.levels.phase     = {'A(1-3)_AllObjectsBase: one goal base was presented together with 2 objects corresponding to each of three bases',...
            'T(1-3)_TargetObjectOnly: one goal base was presented together with 3 objects corresponding to the base '};
        events_json.coded_behaviour.levels.annotation    = {'A(1-3)_AllObjectsBase: goal base was associated with balls = 1, cups = 2 or rings = 3',...
            'T(1-3)_TargetObjectOnly: goal base was associated with balls = 1, cups = 2 or rings = 3',...
            'FirstObjectTouched: the first object the infant touched, ball = 1, cup = 2 or ring = 3',...
            'PerformedTargetAction: 1 = infant peformed target action on the base at least once, 0 = if not',...
            'NumberTimesSuccesful: number of times a succesful target action was performed',...
            'NumberAttempts: number of times the target action was attempted',...
            'NumberAttemptsdWrongObject: number of times the target action was attempted with the wrong object'};
        
        events_json.annotation.description             = 'annotation of behavioural coding';
        
        foldername                                  = [bidsroot filesep 'sub-P' num2str(subject_number) filesep 'beh'];
        filename                                    = [foldername filesep 'sub-P' num2str(subject_number) '_task-exploration_events.json'];
        
        write_json(filename, events_json);
    end
        
    
    %% Add the events json
    
    events_json                                 = [];
    events_json.onset.description               = 'Onset of the event';
    events_json.onset.units                     = 'seconds';
    events_json.duration.description            = 'Duration of the event';
    events_json.duration.units                  = 'seconds';
    events_json.begsample.description           = 'Sample where event begins (measured from start of recording)';
    events_json.begsample.units                 = 'sample number';
    events_json.endsample.description           = 'Sample where event ends (measured from start of recording)';
    events_json.endsample.units                 = 'sample number';
    events_json.offset.description              = 'Offset from begsample till start of the trial of interest';
    events_json.offset.units                    = 'sample number';
    events_json.marker.description              = 'Marker number corresponding to this event as indicated in the .vmrk file';
    events_json.stimulus.description            = 'Stimulus file presented to the infant (see Stimuli)';
    events_json.action_goal.description         = 'Action goal reached within an experimental video';
    events_json.action_goal.levels              = {'number of completed action goal (e.g. to place ring on peg) with a max of 5 actions in one video', 'n/a: not applicable for this trial type'};
    events_json.condition.description           = 'Condition';
    events_json.condition.levels                = {'normal: normal amplitude movement', 'high: high amplitude movement', 'variable: variable amplitude movement', 'n/a: not applicable for this trial type'};
    
    foldername                                  = [bidsroot filesep 'sub-P' num2str(subject_number) filesep 'eeg'];
    filename                                    = [foldername filesep 'sub-P' num2str(subject_number) '_task-' cfg.TaskName '_events.json'];
    
    write_json(filename, events_json);
    
end

%% Add the participants json

participants_json.participant_id.description    = 'Subject identifier';
participants_json.age.description               = 'Age of each subject';
participants_json.age.units                     = 'days';
participants_json.sex.description               = 'Gender of each subject';
participants_json.sex.levels                    = {'f: female', 'm: male', 'n/a: not provided' };
participants_json.included.description          = 'Included in the final dataset for analysis';
participants_json.included.levels               = {'yes: included', 'no: not included' };

filename                                        = [bidsroot filesep 'participants.json'];

write_json(filename, participants_json);

%% Add the matlab code used to generate BIDS to a subfolder

destination                                     = [bidsroot filesep 'code'];
this_script                                     = [mfilename('fullpath') '.m'];
trialfun_script                                 = [fileparts(which(mfilename)) filesep 'trialfun_motionese.m'];

mkdir(destination);
copyfile(this_script, destination);
copyfile(trialfun_script, destination);

%% Create a sourcedata folder with the logfiles and the video's

% Create a folder for the logfiles
str                                             = [bidsroot filesep 'sourcedata' filesep 'logfiles'];
mkdir(str)

% And for the video files
strvideo                                        = [bidsroot filesep 'stimuli'];
mkdir(strvideo)

% Then copy the data there
logfiles                                        = [sourcedata filesep 'Logfiles'];
logfiles                                        = dir(logfiles);
videofile                                       = [sourcedata filesep 'Stimuli'];
videofile                                       = dir(videofile);

copyfile([sourcedata filesep 'Logfiles' filesep logfiles(1).name], str);
copyfile([sourcedata filesep 'Stimuli' filesep videofile(1).name], strvideo);

for cc = 1:length(videofile)
    if contains(videofile(cc).name, 'wave')
        delete([strvideo filesep videofile(cc).name])
    end
end


%% Exlude scans.tsv from bidsvalidator

destination = fullfile(bidsroot, '.bidsignore');
fileID = fopen(destination,'w');
fprintf(fileID,'*_scans.tsv\n');
fclose(fileID);

%% Make a README file as placeholders

destination = fullfile(bidsroot, 'README');
fileID = fopen(destination,'w');
fprintf(fileID,'\n\n\n');
fclose(fileID);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% SUBFUNCTION

function s = remove_empty(s)
if isempty(s)
    return
elseif isstruct(s)
    fn = fieldnames(s);
    fn = fn(structfun(@isempty, s));
    s = removefields(s, fn);
elseif istable(s)
    remove = false(1,size(s,2));
    for i=1:size(s,2)
        % find columns that are non-numeric and where all elements are []
        remove(i) = ~isnumeric(s{:,i}) && all(cellfun(@isempty, s{:,i}));
    end
    s = s(:,~remove);
end

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% SUBFUNCTION

function y = sort_fields(x)
fn = fieldnames(x);
fn = sort(fn);
y = struct();
for i=1:numel(fn)
    y.(fn{i}) = x.(fn{i});
end

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% SUBFUNCTION

function write_json(filename, json)

ft_info('writing ''%s''\n', filename);
json = remove_empty(json);
% json = sort_fields(json);
json = ft_struct2char(json); % convert strings into char-arrays
ft_hastoolbox('jsonlab', 1);
% see also the output_compatible helper function
% write nan as 'n/a'
% write boolean as True/False
str = savejson('', json, 'NaN', '"n/a"', 'ParseLogical', true);
% fid = fopen_or_error(filename, 'w');
fid = fopen(filename, 'w');
fwrite(fid, str);
fclose(fid);

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% SUBFUNCTION

function write_tsv(filename, tsv)
ft_info('writing ''%s''\n', filename);
fn = tsv.Properties.VariableNames;
for i=1:numel(fn)
    % write [] as 'n/a'
    % write nan as 'n/a'
    % write boolean as 'True' or 'False'
    tsv.(fn{i}) = output_compatible(tsv.(fn{i}));
end
writetable(tsv, filename, 'Delimiter', 'tab', 'FileType', 'text');
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% SUBFUNCTION

function val = output_compatible(val)
if istable(val)
    fn = val.Properties.VariableNames;
    for i=1:numel(fn)
        val.(fn{i}) = output_compatible(val.(fn{i}));
    end
elseif iscell(val)
    % use recursion to make all elements compatible
    val = cellfun(@output_compatible, val, 'UniformOutput', false);
elseif isnumeric(val) && numel(val)>1 && any(isnan(val))
    % convert and use recursion to make all elements compatible
    val = num2cell(val);
    val = cellfun(@output_compatible, val, 'UniformOutput', false);
else
    % write [] as 'n/a'
    % write nan as 'n/a'
    % write boolean as 'True' or 'False'
    if isempty(val)
        val = 'n/a';
    elseif isnan(val)
        val = 'n/a';
    elseif islogical(val)
        if val
            val = 'True';
        else
            val = 'False';
        end
    end
end

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% SUBFUNCTION
function tsv_obs = read_excel_observation(excel_observation,cfg)

load(['VideoCoding' filesep 'ObservationPhase_Looking' filesep 'stim_videos_msec_info_resthands.mat']);
load(['VideoCoding' filesep 'ObservationPhase_Looking' filesep 'stim_videos_msec_info_headmove.mat']);
load(['VideoCoding' filesep 'ObservationPhase_Looking' filesep 'stim_videos_msec_info_peekaboo.mat']);

Fs = cfg.eeg.SamplingFrequency;
coded_period                                    = cell(length(excel_observation), 1);
cnt = 1;
rest_hand_idx = [5,7,9,11,13];
for ll = 1:length(excel_observation)
    if cnt <= size(cfg.events,1)
        curr_m = cfg.events{cnt,4};
        curr_m = curr_m{:};
        digits = num2str(excel_observation(ll,1)); % convert into string
        if excel_observation(ll, 1) == 95 && strcmp('S 95',curr_m)
            coded_period(ll, :) = {'fixation cross'};
            onset(ll,:) = (cfg.events{cnt,1}-1)/Fs; % locked to onset of the fixation cross video
            duration(ll,:) = 1; % duration of coding period in seconds
            cnt = cnt+1;
        elseif excel_observation(ll, 1)>100 && excel_observation(ll, 1)<200 && strcmp('1',curr_m(2))
            coded_period(ll, :) = {'intro'};
            onset(ll,:) = (cfg.events{cnt,1}-1)/Fs; % locked to onset of the fixation cross video
            duration(ll,:) = 1.917; % duration of coding period in seconds
            cnt = cnt+1;
        elseif excel_observation(ll, 1)>2000000 && excel_observation(ll, 1)<22000000
            % there are nine phases of this:
            phase = num2str(excel_observation(ll, 1));
            phase_str = ['exp_phase' phase(end)];
            coded_period(ll, :) = {phase_str};
            if str2num(digits(end))==1
                idx_stim = find(stim_videos_msec_info_headmove(:,1)==str2num(digits(1:3)));
                ts = stim_videos_msec_info_headmove(idx_stim,5);
                onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs);
                duration(ll,:) = ts;
            elseif str2num(digits(end))==2
                idx_stim = find(stim_videos_msec_info_headmove(:,1)==str2num(digits(1:3)));
                ts = stim_videos_msec_info_headmove(idx_stim,5);
                te = stim_videos_msec_info_resthands(idx_stim,5);
                onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts;
                duration(ll,:) = te-ts;
            elseif str2num(digits(end))>=3 && str2num(digits(end))<=7
                idx_stim = find(stim_videos_msec_info_resthands(:,1)==str2num(digits(1:3)));
                ts = stim_videos_msec_info_resthands(idx_stim,rest_hand_idx(str2num(digits(end))-2));
                te = stim_videos_msec_info_resthands(idx_stim,rest_hand_idx(str2num(digits(end))-2)+1);
                onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts; % locked to onset of the fixation cross video
                duration(ll,:) = te-ts; % duration of coding period in seconds
            elseif  str2num(digits(end))==9
                idx_stim = find(stim_videos_msec_info_headmove(:,1)==str2num(digits(1:3)));
                ts = stim_videos_msec_info_headmove(idx_stim,6);
                onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts;
                duration(ll,:) = 32-ts;
                cnt = cnt+1;
            else
                idx_stim = find(stim_videos_msec_info_headmove(:,1)==str2num(digits(1:3)));
                ts = stim_videos_msec_info_resthands(idx_stim,14);
                te = stim_videos_msec_info_headmove(idx_stim,6);
                onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts;
                duration(ll,:) = te-ts;
            end
            
        elseif excel_observation(ll, 1)>800000 && excel_observation(ll, 1)<900000 && strcmp('S 8',curr_m(1:3))
            phase = num2str(excel_observation(ll, 1));
            idx_stim = find(stim_videos_msec_info_peekaboo(:,1)==str2num(digits(1:2)));
            if str2num(curr_m(end))==1
                
                if str2num(phase(end))==1
                    %                 phase_str = ['peek-a-boo video - start' phase(end)];
                    phase_str = ['peek-a-boo_start'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,2);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs);
                    duration(ll,:) = ts;
                elseif str2num(phase(end))==2
                    phase_str = ['peek-a-boo_hidden_1'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,2);
                    te = stim_videos_msec_info_peekaboo(idx_stim,3);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts;
                    duration(ll,:) = te-ts;
                elseif str2num(phase(end))==3
                    phase_str = ['peek-a-boo_end'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,3);
                    te = stim_videos_msec_info_peekaboo(idx_stim,4);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts;
                    duration(ll,:) = te-ts;
                    cnt = cnt+1;
                end
            elseif str2num(curr_m(end))==2
                if str2num(phase(end))==1
                    %                 phase_str = ['peek-a-boo video - start' phase(end)];
                    phase_str = ['peek-a-boo_start'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,2);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs);
                    duration(ll,:) = ts;
                elseif str2num(phase(end))==2
                    phase_str = ['peek-a-boo_hidden_1'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,2);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts;
                    duration(ll,:) = 1;
                elseif str2num(phase(end))==3
                    phase_str = ['peek-a-boo_hidden_2'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,2);
                    te = stim_videos_msec_info_peekaboo(idx_stim,3);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts+1;
                    duration(ll,:) = te-(ts+1);
                elseif str2num(phase(end))==4
                    phase_str = ['peek-a-boo_end'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,3);
                    te = stim_videos_msec_info_peekaboo(idx_stim,4);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts+2;
                    duration(ll,:) = te-ts;
                    cnt = cnt+1;
                end
            elseif str2num(curr_m(end))==3
                if str2num(phase(end))==1
                    %                 phase_str = ['peek-a-boo video - start' phase(end)];
                    phase_str = ['peek-a-boo_start'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,2);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs);
                    duration(ll,:) = ts;
                elseif str2num(phase(end))==2
                    phase_str = ['peek-a-boo_hidden_1'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,2);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts;
                    duration(ll,:) = 1;
                elseif str2num(phase(end))==3
                    phase_str = ['peek-a-boo_hidden_2'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,2);
                    te = stim_videos_msec_info_peekaboo(idx_stim,3);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts+1;
                    duration(ll,:) = te-(ts+1);
                elseif str2num(phase(end))==4
                    phase_str = ['peek-a-boo_hidden_3'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,2);
                    te = stim_videos_msec_info_peekaboo(idx_stim,3);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts+2;
                    duration(ll,:) = te-(ts+2);
                elseif str2num(phase(end))==5
                    phase_str = ['peek-a-boo_end'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,3);
                    te = stim_videos_msec_info_peekaboo(idx_stim,4);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts+3;
                    duration(ll,:) = te-ts;
                    cnt = cnt+1;
                end
            elseif str2num(curr_m(end))==4
                if str2num(phase(end))==1
                    %                 phase_str = ['peek-a-boo video - start' phase(end)];
                    phase_str = ['peek-a-boo_start'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,2);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs);
                    duration(ll,:) = ts;
                elseif str2num(phase(end))==2
                    phase_str = ['peek-a-boo_hidden_1'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,2);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts;
                    duration(ll,:) = 1;
                elseif str2num(phase(end))==3
                    phase_str = ['peek-a-boo_hidden_2'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,2);
                    te = stim_videos_msec_info_peekaboo(idx_stim,3);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts+1;
                    duration(ll,:) = te-(ts+1);
                elseif str2num(phase(end))==4
                    phase_str = ['peek-a-boo_hidden_3'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,2);
                    te = stim_videos_msec_info_peekaboo(idx_stim,3);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts+2;
                    duration(ll,:) = te-(ts+2);
                elseif str2num(phase(end))==5
                    phase_str = ['peek-a-boo_hidden_4'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,2);
                    te = stim_videos_msec_info_peekaboo(idx_stim,3);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts+3;
                    duration(ll,:) = te-(ts+3);
                elseif str2num(phase(end))==6
                    phase_str = ['peek-a-boo_end'];
                    coded_period(ll, :) = {phase_str};
                    ts = stim_videos_msec_info_peekaboo(idx_stim,3);
                    te = stim_videos_msec_info_peekaboo(idx_stim,4);
                    onset(ll,:) = ((cfg.events{cnt,1}-1)/Fs)+ts+4;
                    duration(ll,:) = te-ts;
                    cnt = cnt+1;
                end
            end
            
        end
        if cnt < size(cfg.events,1)
            while strcmp('n/a',cfg.events{cnt,4})
                cnt = cnt+1;
                if cnt > size(cfg.events,1)
                    break
                end
            end
        end
    end
end
annotation                                    = excel_observation(:, 2);
tsv_obs                                       = table(onset, duration, coded_period, annotation);

end