% The independent variables:
% Col 1: trial number
% Col 2: related (1) or unrelated (2)
% Col 3: prime identifier (occurs twice in every session)
% Col 4: target identifier (occurs twice in every session, but combined with a different prime)
% Col 5: RT (in ms)
% Col 6: correct (1) or incorrect (2)
% Col 7: prime occurence, first (1) or second (2)
% Col 8: target occurence, first (1) or second (2)
% Col 9: target word length (integer)
% Col 10: session number (1 or 2)

subjindcs=[1:24];
meanRTdiffRUminusUR=zeros(length(subjindcs),1);
for subjind=subjindcs
    fn=['S',num2str(subjind),'_Priming_noFillers.mat'];
    
    load(fn);
    % we have D in memory now
    [ntrials,nivars,nsessions]=size(D);

    for session=2:2
        sessionD=squeeze(D(:,:,session));
        % remove trials with outlier RTs
        allRTs=sessionD(:,5);
        RTmean=mean(allRTs);
        RTsd=sqrt(var(allRTs));
        outlierselvec=allRTs>(RTmean+2*RTsd);
        sessionD=sessionD(~outlierselvec,:);
        % calculate the RT-differences between target presentations
        targetIDs=unique(squeeze(sessionD(:,4)));
        RTdiffRU=[];
        RTdiffUR=[];
        for tindx=1:length(targetIDs)
            thistargetID=targetIDs(tindx);
            thistargettrialnrs=find(sessionD(:,4)==thistargetID);
            if length(thistargettrialnrs)==2
                firstoccD=sessionD(thistargettrialnrs(1),:);
                secondoccD=sessionD(thistargettrialnrs(2),:);
                % select on the basis of correctness of both trials
                firstcorrect=firstoccD(6);
                secondcorrect=secondoccD(6);
                if all([firstcorrect,secondcorrect]==1)
                    RTdiff=firstoccD(5)-secondoccD(5);
                    firstoccRel=sessionD(thistargettrialnrs(1),2);
                    secondoccRel=sessionD(thistargettrialnrs(2),2);
                    if all([firstoccRel,secondoccRel]==[1,2])
                        RTdiffRU(end+1)=RTdiff;
                    elseif all([firstoccRel,secondoccRel]==[2,1])
                        RTdiffUR(end+1)=RTdiff;
                    end;
                end;
            end;
        end;
        meanRTdiffRUminusUR(subjind)=mean(RTdiffRU)-mean(RTdiffUR);
        [H,P,CI,STATS] = ttest2(RTdiffRU,RTdiffUR);
        disp(['Subject ',num2str(subjind),' p-value: ',num2str(P)]);
    end;
    % second level test
    [H,P,CI,STATS] = ttest(meanRTdiffRUminusUR);
    disp(['Across Subjects p-value and t-stat: ',num2str(P),', ',num2str(STATS.tstat)]);

end;