clear all; close all;

%% Define what to analyse

% Which subjects and sessions?
subjects = [1:34];
sessions = 2;
blocksPerSession = 15;

%% =================== LOAD & SORT THE DATA =================== %%

%% Load the data 

data = [];
    
for iSubject = 1:length(subjects)
    
    clear tmp
               
    for iSession = 2:3

        filename = dir(['P:/3018029.09/Behavioral data/subj-' num2str(subjects(iSubject)) '/data_subj-' num2str(subjects(iSubject)) '_ses-' num2str(iSession) '_*.mat']);
        filename = {filename.name};
        load(['P:/3018029.09/Behavioral data/subj-' num2str(subjects(iSubject)) '/' filename{1}]);

        %% transform data to table
        variableNames = {'subject','session','block','trial','relativeCoherence','relativeCoherenceAbs','responseDir','responseKey','correct','rt','confidence','confidenceRt','stimLevel','motionDir'};

        subject                 = repmat(subjects(iSubject),numel(trialMatrix.relative_coherence),1);
        session                 = repmat(iSession,numel(trialMatrix.relative_coherence),1);
        block                   = [];
        for i = 1:blocksPerSession
            block               = [block ; i * ones(length(trialMatrix.relative_coherence),1)];
        end
        trial                   = repmat(1:length(trialMatrix.relative_coherence), 1, blocksPerSession)';
        relativeCoherence       = reshape(trialMatrix.relative_coherence',numel(trialMatrix.relative_coherence),1);
        relativeCoherenceAbs    = abs(relativeCoherence);
        responseDir             = reshape(results.responseDir',numel(results.responseDir),1);
        responseKey             = reshape(results.responseKey',numel(results.responseKey),1);
        correct                 = reshape(results.responseCorrect',numel(results.responseCorrect),1);
        rt                      = reshape(results.responseTime',numel(results.responseTime),1);
        confidence              = reshape(results.confidence',numel(results.confidence),1);
        confidenceRt            = reshape(results.confidenceTime',numel(results.confidenceTime),1);
        motionDir               = reshape(trialMatrix.direction',numel(trialMatrix.direction),1);
        
            % calculate a stim level value independent to difficulty of task
            stim_levels_all = unique(relativeCoherence);
            tmp2 = zeros(length(relativeCoherence),1);

            for i = 1:length(relativeCoherence)
                for j = 1:length(stim_levels_all)
                   if relativeCoherence(i) == stim_levels_all(j)
                       tmp2(i,1) = j;
                   else
                   end
                end
            end

            stimLevel = tmp2;
            clear tmp2

        tmp{iSession} = table(subject,session,block,trial,relativeCoherence,relativeCoherenceAbs,responseDir,responseKey,correct,rt,confidence,confidenceRt,stimLevel,motionDir);

        tmp{iSession}.responseDir(tmp{iSession}.responseDir == -1) = 0;

        data = [data; tmp{iSession}];    
           
    end
    
end

tmp = [];

%% Save table into file
save('P:/3018029.09/data.mat', 'data')

%% Sort data for serial dependence analysis

for i = 2:size(data,1)

    if ~isnan(data.responseKey(i)) && ~isnan(data.responseKey(i-1)) && ...
       data.subject(i)==data.subject(i-1) && data.session(i)==data.session(i-1) && data.block(i)==data.block(i-1)

        tmp = [tmp; ...
            data.subject(i), ...                % 1: Subject
            data.session(i), ...                % 2: Session
            data.block(i), ...                  % 3: Block
            data.relativeCoherence(i-1), ...    % 4: Previous stimulus coherence
            data.relativeCoherence(i), ...      % 5: Current stimulus coherence
            data.relativeCoherenceAbs(i-1), ... % 6: Previous absolute stimulus coherence
            data.relativeCoherenceAbs(i), ...   % 7: Current absolute stimulus coherence
            data.responseDir(i-1), ...          % 8: Previous response direction
            data.responseDir(i), ...            % 9: Current response direction
            data.correct(i-1), ...              % 10: Correctness of previous response
            data.correct(i), ...                % 11: Correctness of current response
            data.rt(i-1), ...                   % 12: Previous response time
            data.rt(i), ...                     % 13: Current response time
            data.confidence(i-1), ...           % 14: Previous confidence
            data.confidence(i), ...             % 15: Current confidence
            data.confidenceRt(i-1), ...         % 16: Previous confidence response time
            data.confidenceRt(i), ...           % 17: Current confidence response time
            data.stimLevel(i-1), ...            % 18: Previous stim level nr
            data.stimLevel(i), ...              % 19: Current stim level nr
            data.motionDir(i-1), ...            % 20: Previous motion direction
            data.motionDir(i)];                 % 21: Current motion direction
        
    end
    
end

% DATA_SD TRIAL MATRIX CREATION
variableNames = {'subject','session','block','prevRelativeCoherence','currRelativeCoherence','prevRelativeCoherenceAbs','currRelativeCoherenceAbs','prevResponseDir','currResponseDir','prevCorrect','currCorrect','prevRt','currRt','prevConfidence','currConfidence','prevConfidenceRt','currConfidenceRt','prevStimLevel','currStimLevel','prevMotionDir','currMotionDir'};

subject                     = tmp(:,1);
session                     = tmp(:,2);
block                       = tmp(:,3);
prevRelativeCoherence       = tmp(:,4);
currRelativeCoherence       = tmp(:,5);
prevRelativeCoherenceAbs    = tmp(:,6);
currRelativeCoherenceAbs    = tmp(:,7);
prevResponseDir             = tmp(:,8);
currResponseDir             = tmp(:,9);
prevCorrect                 = tmp(:,10);
currCorrect                 = tmp(:,11);
prevRt                      = tmp(:,12);
currRt                      = tmp(:,13);
prevConfidence              = tmp(:,14); 
currConfidence              = tmp(:,15);
prevConfidenceRt            = tmp(:,16);
currConfidenceRt            = tmp(:,17);
prevStimLevel               = tmp(:,18);
currStimLevel               = tmp(:,19);
prevMotionDir               = tmp(:,20);
currMotionDir               = tmp(:,21);

data_sd = table(subject,session,block,prevRelativeCoherence,currRelativeCoherence,prevRelativeCoherenceAbs,currRelativeCoherenceAbs,prevResponseDir,currResponseDir,prevCorrect,currCorrect,prevRt,currRt,prevConfidence,currConfidence,prevConfidenceRt,currConfidenceRt,prevStimLevel,currStimLevel,prevMotionDir,currMotionDir);

clear tmp

%% Save table into file
save('P:/3018029.09/data_sd.mat', 'data_sd')
