clear all; close all;

addpath ../../Toolboxes/Palamedes

%% Define what to analyse

% Which subjects?
subjects = [1:34];

% Which data?
whichdata = 'clean';  % alternative: 'raw'

if whichdata == 'clean'
    load('P:/3018029.09/data_clean.mat')
    folder_str = 'Clean data';
elseif whichdata == 'raw'
    load('P:/3018029.09/data.mat')
    folder_str = 'Raw data';
end

% Which plots?
plots_sanity_check = true;

%% ========= Sanity checks ========== %%

for iSubject = 1:length(subjects)
    
    %% Select the subject's data
    
    subject_data = data(data.subject == subjects(iSubject), :);
    
    stim_levels_all = table2array(unique(subject_data(:,'relativeCoherence')));
    stim_levels     = unique(abs(stim_levels_all));
    
    for iStimulus = 1:length(stim_levels)
        
        % Select data for stimulus levels
        subject_data_stim = subject_data(subject_data.relativeCoherenceAbs == stim_levels(iStimulus), :);
        
        % Percentage correct answers per stimulus level
        correct_percentage(iSubject, iStimulus) = ...
            100* sum(subject_data_stim.correct == 1) ... 
            / size(subject_data_stim.relativeCoherenceAbs,1);
        
        % Percentage correct answers and mean RT per stimulus level per confidence
        % level
        for iConfidence = 1:4
            correct_percentage_per_evid_conf{iStimulus}(iSubject,iConfidence) = ...
                100* sum(subject_data_stim.correct == 1 & subject_data_stim.confidence == iConfidence) ... 
                / sum(subject_data_stim.confidence == iConfidence);
            responsetime_per_evid_conf{iStimulus}(iSubject,iConfidence) = ...
                1000* nanmean(subject_data_stim.rt(subject_data_stim.confidence == iConfidence));   
        end
       
        % Mean response time per stimulus level    
        responsetime(iSubject,iStimulus) = ...
            1000* nanmean(subject_data_stim.rt(~isnan(subject_data_stim.responseKey)));   

        % Mean confidence per stimulus level
        confidence(iSubject,iStimulus) = nanmean(subject_data_stim.confidence);     
        
        % Mean RT and confidence split for incorrect (i=1)/correct (i=2) trials
        for i = 1:2 
            responsetime_corr_split{i}(iSubject,iStimulus) = ...
                1000* nanmean(subject_data_stim.rt(~isnan(subject_data_stim.responseKey) & subject_data_stim.correct == i-1)); 
            confidence_corr_split{i}(iSubject,iStimulus) = ...
                nanmean(subject_data_stim.confidence(subject_data_stim.correct == i-1));  
        end        
        
    end
    
    for iConfidence = 1:4

        subject_data_conf = subject_data(subject_data.confidence == iConfidence, :);

        % Mean correct per confidence level
        correct_percentage_conf(iSubject,iConfidence) = ...
            100* sum(subject_data_conf.correct == 1) ... 
            / size(subject_data_conf.confidence,1);

        % Mean reaction time per confidence level
        responsetime_conf(iSubject,iConfidence) = ...
            1000* nanmean(subject_data_conf.rt);
        
    end
  
end

% Group mean and se
correct_percentage_mean     = mean(correct_percentage);
    correct_percentage_se   = std(correct_percentage)/sqrt(length(correct_percentage));
responsetime_mean           = mean(responsetime);
    responsetime_se         = std(responsetime)/sqrt(length(responsetime));
confidence_mean             = mean(confidence);
    confidence_se           = std(confidence)/sqrt(length(confidence));
    
    % also for split incorrect (i=1)/correct (i=2) trials
    for i = 1:2
        responsetime_corr_split_mean(i,:)   = nanmean(responsetime_corr_split{i});
            responsetime_corr_split_se(i,:) = nanstd(responsetime_corr_split{i})/sqrt(length(responsetime_corr_split{i}(~isnan(responsetime_corr_split{i}))));
        confidence_corr_split_mean(i,:)     = nanmean(confidence_corr_split{i});
            confidence_corr_split_se(i,:)   = nanstd(confidence_corr_split{i}/sqrt(length(confidence_corr_split{i}(~isnan(confidence_corr_split{i})))));
    end
    
correct_percentage_conf_mean    = mean(correct_percentage_conf);
    correct_percentage_conf_se  = std(correct_percentage_conf)/sqrt(length(correct_percentage_conf));
responsetime_conf_mean          = mean(responsetime_conf);
    responsetime_conf_se        = std(responsetime_conf)/sqrt(length(responsetime_conf));
    
for iStimulus = 1:length(stim_levels)
    correct_percentage_per_evid_conf_mean{iStimulus}    = nanmean(correct_percentage_per_evid_conf{iStimulus});
        correct_percentage_per_evid_conf_se{iStimulus}  = nanstd(correct_percentage_per_evid_conf{iStimulus})./sqrt(sum(~isnan(correct_percentage_per_evid_conf{iStimulus})));
    responsetime_per_evid_conf_mean{iStimulus}          = nanmean(responsetime_per_evid_conf{iStimulus});
        responsetime_per_evid_conf_se{iStimulus}        = nanstd(responsetime_per_evid_conf{iStimulus})./sqrt(sum(~isnan(responsetime_per_evid_conf{iStimulus})));
end 
    
%% Plot the sanity check data if plots are enabled

if plots_sanity_check == true

    % Percentage correct answers per stimulus level   
    figure; hold on;
        bar(correct_percentage_mean); 
        errorbar(correct_percentage_mean,correct_percentage_se,'.b'); 
        ylim([45 100]); 
        xlim([0.25 6.75]); 
        set(gca,'XTick',1:7,'XTickLabel',{'smallest','','','','','largest'});
        xlabel('Relative stimulus coherence')
        ylabel('Mean percentage correct per stimulus level')
        title('Performance');
        %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Group/Group_percentage correct per stimulus level.png'])

    % Percentage correct answers per stimulus level   
    figure; hold on;
        for iSubject = 1:length(subjects)
            plot(correct_percentage(iSubject,:))
        end
        ylim([45 100]); 
        xlim([0.25 6.75]); 
        set(gca,'XTick',1:7,'XTickLabel',{'smallest','','','','','largest'});
        xlabel('Relative stimulus coherence')
        ylabel('Mean percentage correct per stimulus level')
        title('Performance');
        %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Group/Group_percentage correct per stimulus level - individual lines.png'])

    % Percentage correct answers per stimulus level per confidence level
    figure; hold on;    
        for iStimulus = 1:6
            subplot(2,3,iStimulus);
            hold on;
            errorbar(correct_percentage_per_evid_conf_mean{iStimulus}, correct_percentage_per_evid_conf_se{iStimulus}, 'k');
            ylim([45 100]); 
            xlim([0.25 5.75]);         
            set(gca,'XTick',1:4,'XTickLabel',{'1','2','3','4'});
            xlabel('Confidence rating')
            ylabel('Performance (%)')
            title(['Coherence level ' num2str(iStimulus)]);
            hold off;
        end
        %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Group/Group_percentage correct per stimulus level per confidence level.png'])
     
    % Mean response time per stimulus level per confidence level
    figure; hold on;    
    for iStimulus = 1:6
        subplot(2,3,iStimulus);
        hold on;
        errorbar(responsetime_per_evid_conf_mean{iStimulus}, responsetime_per_evid_conf_se{iStimulus}, 'k');
        ylim([750 1600]); 
        xlim([0.25 4.75]);         
        set(gca,'XTick',1:4,'XTickLabel',{'1','2','3','4'});
        xlabel('Confidence rating')
        ylabel('RT (ms)')
        title(['Coherence level ' num2str(iStimulus)]);
        hold off;
    end
    saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Group/Group_mean RT per stimulus level per confidence level.png'])

   
    % Mean response time per stimulus level, with standard errors
    figure; hold on;
        bar(responsetime_mean);
        errorbar(responsetime_mean, responsetime_se, '.b')
        ylim([750 1500]); 
        xlim([0.25 6.75]); 
        set(gca,'XTick',1:6,'XTickLabel',{'smallest','','','','','largest'});
        xlabel('Relative stimulus coherence')
        ylabel('Response time (ms)')
        title('Mean response time per stimulus level');
        hold off;
        %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Group/Group_mean RT per stimulus level.png'])
        
    % split for incorrect/correct trials
    figure; hold on;
        plot(responsetime_corr_split_mean');
            errorbar(responsetime_corr_split_mean', responsetime_corr_split_se', '.k')
        legend('Incorrect responses', 'Correct responses')
        legend('Location','northwest')
        ylim([750 1500]); 
        xlim([0.25 6.75]); 
        set(gca,'XTick',1:6,'XTickLabel',{'smallest','','','','','largest'});
        xlabel('Relative stimulus coherence')
        ylabel('Response time (ms)')
        title('Mean response time per stimulus level');
        hold off;
        %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Group/Group_mean RT per stimulus level - corr split.png'])
        
    % Mean confidence per stimulus level 
    figure; hold on;
        bar(confidence_mean); 
        errorbar(confidence_mean, confidence_se, '.b')
        ylim([1 4]); 
        xlim([0.25 6.75]); 
        set(gca,'XTick',1:6,'XTickLabel',{'smallest','','','','','largest'});
        xlabel('Relative stimulus coherence')
        ylabel('Confidence (1-4)')
        title('Mean confidence per stimulus level');
        %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Group/Group_mean confidence per stimulus level.png'])

    % split for incorrect/correct trials
    figure; hold on;
        plot(confidence_corr_split_mean');
            errorbar(confidence_corr_split_mean', confidence_corr_split_se', '.k')
        legend('Incorrect responses', 'Correct responses')
        legend('Location','northwest')
        ylim([1 4]); 
        xlim([0.25 6.75]); 
        set(gca,'XTick',1:6,'XTickLabel',{'smallest','','','','','largest'});
        xlabel('Relative stimulus coherence')
        ylabel('Confidence (1-4)')
        title('Mean confidence per stimulus level');
        %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Group/Group_mean confidence per stimulus level - corr split.png'])
        
    % Percentage correct answers per confidence rating
    figure; hold on;
        bar(correct_percentage_conf_mean); 
        errorbar(correct_percentage_conf_mean,correct_percentage_conf_se,'k.');
        ylim([50 100]); 
        xlim([0.25 4.75]); 
        set(gca,'XTick',1:4,'XTickLabel',{'1','2','3','4'});
        xlabel('Confidence rating')
        ylabel('Percentage correct')
        title('Performance per confidence rating');
        %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Group/Group_percentage correct per confidence rating.png'])

    % Mean response time per confidence rating
    figure; hold on;
        bar(responsetime_conf_mean);
        errorbar(responsetime_conf_mean,responsetime_conf_se,'k.'); 
        ylim([500 2000]); 
        xlim([0.25 4.75]); 
        set(gca,'XTick',1:4,'XTickLabel',{'1','2','3','4'});
        xlabel('Confidence rating')
        ylabel('Direction response time (ms)')
        title('Mean response time per confidence rating'); 
        %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Group/Group_mean RT per condence rating.png'])     

end
