clear all
close all

cd('/Users/leonieoostwoudwijdenes/surfdrive/Experiments/Donders/ManualReflex/RDM/experiment2');

% experimental settings
n_subj = 13;
pp=[1:4 6:14]; %pp5 did not finish experiment due to dizziness
start_exp = repmat(4000,1,n_subj);
start_exp([3 7]) = [8000 8000];

n_trials = 576; %pp1 did 575 trials
t_total = n_subj*n_trials;
ix = 0;
sf = 250; %Hz
max_t = 6*sf; %sec
margin = 500; %margin for trial cutting
pdcrit = 0.4; %voltage criterium 
pdmin = 0.2; %photodiode minimum

% predefine variables
subject=[]; trial=[]; sled_final_pos=[]; sled_start_next=[]; jump_timing=[]; target_final_pos_x=[]; hit=[]; diode=[];
hand_pos = NaN([t_total,max_t,3]);
sled_pos = NaN([t_total,max_t,3]);
check_trials = NaN(n_subj,1);

for s = 1:n_subj
    fprintf('%d...\n',s);
    
    % file names
    if pp(s)<10
        opto_file = ['sub-0' num2str(pp(s)) '/pp' num2str(pp(s)) '_001'];
        settings = ['sub-0' num2str(pp(s)) '/pp' num2str(pp(s)) '_log.txt'];
    else
        opto_file = ['sub-' num2str(pp(s)) '/pp' num2str(pp(s)) '_001'];
        settings = ['sub-' num2str(pp(s)) '/pp' num2str(pp(s)) '_log.txt'];
    end
    
    %% read txt files
    fd = fopen(settings,'r');
    d = textscan(fd, '%s','delimiter','\n','commentStyle','%','whitespace','');
    d = d{1};
    filelength = size(d,1); % number of lines in the file
    row = 2; % start reading at second row
    for r = row:filelength
        r_content = d{r};
        content = str2num(r_content);
        trial = [trial; content(1)+1];
        sled_final_pos = [sled_final_pos; content(2)];
        sled_start_next = [sled_start_next; content(3)];
        jump_timing = [jump_timing; content(4)];
        target_final_pos_x = [target_final_pos_x; content(5)];
        hit = [hit; content(6)];
        if pp(s)==1 && r==filelength %because last trial for pp1 is missing
            trial = [trial; NaN];
            sled_final_pos = [sled_final_pos; NaN];
            sled_start_next = [sled_start_next; NaN];
            jump_timing = [jump_timing; NaN];
            target_final_pos_x = [target_final_pos_x; NaN];
            hit = [hit; NaN];
        end
    end

    %% read optotrak files
    % ->first save xls file as xlsx
    % diode 1 = start sled motion + present target; 2 = target jump (if present); 3 = sled at end position
    
    opto = xlsread([opto_file '_3d.xlsx']);
    odau = xlsread([opto_file '_Odau_1.xlsx']);
    opto_axis = 1:size(opto,1);
    odau_axis = 1:size(odau,1);
    
    h = find(diff(odau(start_exp(s):end,2))>0.2 | diff(odau(start_exp(s):end,2))<-3)+(start_exp(s)-1); %find new trial initiation: length k should be equal to n_trials
    k = [h(diff(h)~=1); h(end)]; %remove two consecutive instances of trial start
      
    check_trials(s) = length(k)==n_trials;
    subject = [subject; repmat(s,n_trials,1)];
    for i = 1:length(k) %n_trials        
        if i==length(k)
            m = find(diff(odau(k(i):k(i)+max_t,3))>pdcrit)+k(i)-1; %find photodiode activation within trial
        else
            m = find(diff(odau(k(i):k(i+1),3))>pdcrit)+k(i)-1; %find photodiode activation within trial
        end
        
        if pp(s)==6 && i==522 %because one trial is missing due to a gap in optotrak collection (exp lasted >1 hour)
            diode = [diode; NaN(1,3)];
            ix = ix+1;
            hand_pos(ix,1:size(t_ix,2),:) = NaN(1,1500,3);
            sled_pos(ix,1:size(t_ix,2),:) = NaN(1,1500,3);
        else
            n = [1; diff(m)~=1]; %remove two consecutive samples
            m = m(n==1);
            if size(m,1)>3 && sum(odau(m-1,3)<pdmin)>3 %if there are two trials in one photodiode activation
                m1 = m(1:find(diff(m)>700));
                m2 = m(find(diff(m)>700)+1:end);
                
                p1 = odau(m1-1,3)<pdmin; p2 = odau(m2-1,3)<pdmin;
                diode = [diode; m1(p1==1)', NaN(1,3-(sum(p1))); m2(p2==1)', NaN(1,3-(sum(p2)))];
                %first trial
                t_stamp = m1(p1==1);
                ix = ix+1;
                t_ix = t_stamp(1)-margin:t_stamp(1)+999;
                hand_pos(ix,1:size(t_ix,2),:) = opto(t_ix,2:4); %cut trial: 2 sec (margin) before sled starts moving until 4 sec later
                sled_pos(ix,1:size(t_ix,2),:) = opto(t_ix,5:7);
                %second trial
                t_stamp = m2(p2==1);
                ix = ix+1;
                t_ix = t_stamp(1)-margin:t_stamp(1)+999;
                hand_pos(ix,1:size(t_ix,2),:) = opto(t_ix,2:4); %cut trial
                sled_pos(ix,1:size(t_ix,2),:) = opto(t_ix,5:7);
            else
                p = odau(m-1,3)<pdmin;
                diode = [diode; m(p==1)', NaN(1,3-(sum(p)))];
                t_stamp = m(p==1);
                ix = ix+1;
                t_ix = t_stamp(1)-margin:t_stamp(1)+999;
                hand_pos(ix,1:size(t_ix,2),:) = opto(t_ix,2:4); %cut trial
                sled_pos(ix,1:size(t_ix,2),:) = opto(t_ix,5:7);
            end
            if pp(s)==1 && ix==575  %because last trial for pp1 is missing
                diode = [diode; NaN(1,3)];
                ix = ix+1;
            end
        end
    end
    clear k opto odau
end
% figure;plot(diff(odau(:,2)));hold on;plot(odau(:,2));plot(k,2,'*');plot(odau(:,3));plot(m,0.2,'*')

check_diode = sum(isnan(diode(:,3)))==sum(jump_timing==0);
sled_dist = repmat([0.2; -0.3],(n_trials*n_subj)/2,1)-sled_final_pos;
sled_dist(sled_dist~=0) = 0.25; sled_dist(sled_dist==0) = 0.5;

save('/Users/leonieoostwoudwijdenes/surfdrive/Experiments/Donders/ManualReflex/RDM/derivatives/Experiment2Data', 'n_subj','n_trials','t_total','max_t','margin','sf','subject','trial','sled_start_next','sled_final_pos','sled_dist','jump_timing','target_final_pos_x','hit','diode','hand_pos','sled_pos');