%% From recording to results
% Here we will create a set of dummy data and then see how to get final results from your raw data.
% In this virtual experiment, subject would do a target detecting task in each trial. The target would appear on ethier left or right side, and subject press key '1' or '2' to report their judgement as soon as they could. The reaction time is recorded as the most interested resutls. And there are two different conditions that we will compare.
%% Steps to final results
%
% Showing all trials is not always necessary for computing your final results, but it will help you check data, have first impression, go back checking later.
% Showing and checking individual results are also essential. Outliner, noise level, quick impression on individual variability (also for readers).
% Group results is more related to statistics and plotting, we won't go to that part here.
%
%% Gernerate the simulated data
% In this simulated dataset, we have 20 trials,

% clear all existed variables
clear

RT =        [1.44; 1.24; 1.63; 0.91; 1.35; 1.75; 1.53; 1.33; 1.48; 21.54; 1.20; 1.30; 1.64; 0.88; 0.98; 1.29; 1.64; 0.88; 0.98; 1.29; 1.64; 0.88; 0.98; 1.29];
condition = [6;    8;    6;    8;    8;    8;    6;    6;    6;    8;     6;    6;    8;    6;    8;    8;    8;    6;    8;    6;    8;    6;    8;    6];
targetside= {'l';  'r';  'l';  'r';  'l';  'r';  'l';  'r';  'l';  'r';  'l';   'r';  'l';  'r';  'l';  'r';  'l';  'r';  'l';  'r';  'l';  'r';  'l';  'r'};
response =  {'1';  '2';  '1';  '2';  '1';  '2';  '2';  '2';  '1';  '2';  '1';   '2';  '2';  '2';  '1';  '2';  '2';  '2';  '1';  '2';  '2';  '2';  '1';  '2'};
% ----------------------------------------------------------------------------- %
% creat and show a table "data" consists of all variables above


% ----------------------------------------------------------------------------- %

%
% Save this data and load it later.

filenname = 'TestData.mat';
save(filenname,"data");
data = [];
disp(data)

load(filenname);
disp(data)

%
%% Go through each trial and judge if the response is correct
%

% initialize variables
NTrials = height(data);
TrialCorrectOrNot = zeros(NTrials, 1);

% define the left and right key
leftkey = '1';
rightkey = '2';

% loop for all trials and judge if the correct key was pressed
for itrial = 1:NTrials
    iResponse = data.response(itrial);
    iTargetside = data.targetside(itrial);
    
    % ----------------------------------------------------------------------------- %
    % determine the value of TrialCorrectOrNot for this trial
    % 1: when the response is correct

    % 0: when the response is not correct

    % -1: when subject pressed other key
        
    % ----------------------------------------------------------------------------- %
end

% show the new variable
data.correctornot = TrialCorrectOrNot;
disp(data)

%%
%
%% Arrange results along different conditions
% Situation should be considered:
% 1) If the trial is valid:  Invalid means subject did not press the left nor right key.
% 2) If the trial is correct:  Incorrect means subject pressed the right key while target is on the left side, and vice versa
% 3) If the response time of the trial is outlier:  Exclueded trial means RT of this trial is outside the range of +- 3*std(RT)
%
%

% ----------------------------------------------------------------------------- %
% How many and which conditions you have
conditionList

NConditions
% ----------------------------------------------------------------------------- %

%% initialize variables for each condition
% number of trials
NumTrials = zeros(NConditions, 4);
% average response time
meanRT =  zeros(NConditions, 4);
% standard deviation of response time
stdRT = zeros(NConditions,4);
% standard error of response time
steRT =  zeros(NConditions, 4);

disp(NumTrials)

% --- Each row corresponds to different conditions
% --- Each column correponds to:
% 1) All trials,   2) Valid Trials,   3) Correct Trials,   4) Correct & Non-Outlier trials.
%

for i_Counter = 1:NConditions
    iCond = conditionList(i_Counter);
    % be careful with the counter and condition code
    disp(['counter: ' num2str(i_Counter) ';   iCond: ' num2str(iCond)])
    
    % ----------------------------------------------------------------------------- %
    % Get sub part of data for trials under condition i
    iSelectedTrials
    % ----------------------------------------------------------------------------- %
    iSubData = data(iSelectedTrials,:);
    disp(iSubData)
    
    % Get RT and CorrectOrNot for trials under condition i
    iRTs = iSubData.RT;
    iCorrectOrNot = iSubData.correctornot;
    
    % number of all trials in condition i
    NumTrials(i_Counter, 1) = length(iRTs);
    % find valid and correct trials and count trial number
    iValidTrials = find(iCorrectOrNot~=-1);
    iCorrectTrials = find(iCorrectOrNot==1);
    NumTrials(i_Counter, 2) = length(iValidTrials);
    NumTrials(i_Counter, 3) = length(iCorrectTrials);
    
    % ----------------------------------------------------------------------------- %
    % compute mean, std and ste for all trials
    meanRT(i_Counter, 1)
    stdRT(i_Counter, 1)
    steRT(i_Counter, 1)
    % ----------------------------------------------------------------------------- %
    
    % mean, ste for valid trials and correct trials
    meanRT(i_Counter, 2) = mean(iRTs(iValidTrials));
    stdRT(i_Counter, 2) = std(iRTs(iValidTrials));
    steRT(i_Counter, 2)= stdRT(i_Counter, 2) / sqrt(length(iValidTrials));
    
    meanRT(i_Counter, 3) = mean(iRTs(iCorrectTrials));
    stdRT(i_Counter, 3) = std(iRTs(iCorrectTrials));
    steRT(i_Counter, 3) = stdRT(i_Counter, 3) / sqrt(length(iCorrectTrials));
    
    
    % number of trials, mean, std, ste for Non-outliner trials
    % ----------------------------------------------------------------------------- %
    % outliner is defined as: trial with RT outside the range of +- 3*std(RT)
    % vector with condition statements --> logic/ boolean vector
    iLogicVector_Correct_NonOutliner
    
    iCorrectnNonRTOutlierTrials = find(iLogicVector_Correct_NonOutliner);
    % ----------------------------------------------------------------------------- %
    
    NumTrials(i_Counter, 4) = length(iCorrectnNonRTOutlierTrials);
    meanRT(i_Counter, 4) = mean(iRTs(iCorrectnNonRTOutlierTrials)); 
    stdRT(i_Counter, 4) = std(iRTs(iCorrectnNonRTOutlierTrials));
    steRT(i_Counter, 4) = stdRT(i_Counter, 4) / sqrt(length(iCorrectnNonRTOutlierTrials));
    
    
    %% lets put non-outliner trial sequence back into the subdata table to visualize it.
    iSubData.validNonOutliner = iLogicVector_Correct_NonOutliner;
    disp(iSubData)
    
end

%
%% Show the resutls
% The fifth column: Correct & Non-Outlier trials (which we are most interested in)

disp('    mean RT   ste RT    #Trials   #Excluded Trials');
disp([squeeze(meanRT(:, 4)), squeeze(steRT(:, 4)), squeeze(NumTrials(:, 1)),  squeeze(NumTrials(:, 1) - NumTrials(:, 4))]);

%
%% Plot the results
% more about this part next week

% open a new figure window
figure;
% all a title
title('RT of correct and non-outliner trials');
% do not overlap
hold on;

y_mean = meanRT(:,4);
y_ste = steRT(:,4);

% plot bars and errorbars
bar(1:NConditions, y_mean, 0.2, 'FaceColor', [0.5 0.5 0.5]);
errorbar(1:NConditions, y_mean, y_ste, '.');

% beautify the figure
ylabel('Response Time')
xlabel('Condition')
set(gca,'XTick',1:NConditions);

set(gca,'XTickLabel',conditionList);
set(gca,'fontsize',16,'linewidth',2);
set(gca,'color','none');
set(gcf,'color','w')

%
%
%
%
%
%
%
%
%