clear all;
clc
close all;
%% load data
datafiles_rt=dir('*_emo_output*');
output_data=[];
output_data_pic=[];
stand=2;
for subj=1:size(datafiles_rt,1)    
    % preprocessing
    infile=[datafiles_rt(subj).name];
    [subject,gender,age,name,trial,rt,correct,cueori,tarpos,emo,picno,validity]=textread(infile,'%f%s%f%s%f%f%f%f%f%f%f%f','emptyvalue', NaN,'headerlines',1) ;
    subid=repmat(str2double(infile(1:2)),240,1);
    gender=strcmp(gender{1},'female')+1;
    validity(cueori(:,1)==tarpos(:,1),:)=1;
    validity(cueori(:,1)~=tarpos(:,1),:)=0;
    sortdata=[subid,age,trial,rt,correct,cueori,tarpos,emo,picno,validity];
    %calculate correct rate
    data_correct=sortdata(sortdata(:,5)==1);
    cr=size(data_correct,1)/size(sortdata,1);
    % sort data    
    subdata=sortdata(sortdata(:,4)>0.15&sortdata(:,4)<1.5,:);
    RT=subdata(:,4);
    RT_m=mean(subdata(:,4));
    RT_sd=std(subdata(:,4));
    subdata=subdata(RT< RT_m+stand*RT_sd&RT>RT_m-stand*RT_sd,:);
    lefttrials(subj,:)=[sortdata(1),size(subdata,1)];
    
    %calculate data
    for taremo=1:3%1-neg,2-neu,3-pos
        data=subdata(subdata(:,8)==taremo,:);
        con=1;%congruent
        RT_new(taremo,con)=mean(data(data(:,5)==1&data(:,10)==1,4));%Correct*CongruentRT        
        con=2;%incongruent
        RT_new(taremo,con)=mean(data(data(:,5)==1&data(:,10)==0,4));%Correct*IncongruentRT        
    end
    
   
    output_data=[sortdata(1),age(1),gender,1000*[RT_new(1,:),RT_new(2,:),RT_new(3,:)], (RT_new(1,2)-RT_new(1,1))/(RT_new(1,2)+RT_new(1,1)),(RT_new(2,2)-RT_new(2,1))/(RT_new(2,2)+RT_new(2,1)),(RT_new(3,2)-RT_new(3,1))/(RT_new(3,2)+RT_new(3,1)),cr ;output_data];
end

outputdata=sortrows(output_data);
outputdata=[{'SubID','Age','Gender','SadConRT','SadInConRT','NeuConRT','NeuInConRT','HappyConRT','HappyInConRT',...
   'SadCE','NeuCE','HappyCE','CorrectRate'};...
    num2cell(outputdata)];
cell2csv('Data.csv',outputdata);