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';
    violin = false;
elseif whichdata == 'raw'
    load('P:/3018029.09/data.mat')
    folder_str = 'Raw data';
    violin = true;
end

% 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     = stim_levels_all((size(stim_levels_all)/2+1):size(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), :);
        subject_data_stim_session2  = subject_data_stim(subject_data_stim.session == 2, :);
        subject_data_stim_session3  = subject_data_stim(subject_data_stim.session == 3, :);

        % Number of missed responses per stimulus level
        missed{iSubject}(iStimulus) = ...
            100* sum(isnan(subject_data_stim.responseKey)) ...  
            / size(subject_data_stim.relativeCoherenceAbs,1);

        % Percentage correct answers per stimulus level
        correct_percentage{iSubject}(iStimulus) = ...
            100* sum(subject_data_stim.correct == 1) ... 
            / size(subject_data_stim.relativeCoherenceAbs,1);

            % Split first and second half
            correct_percentage_session2{iSubject}(iStimulus) = ...
                100* sum(subject_data_stim_session2.correct == 1) ... 
                / size(subject_data_stim_session2.relativeCoherenceAbs,1);
            correct_percentage_session3{iSubject}(iStimulus) = ...
                100* sum(subject_data_stim_session3.correct == 1) ... 
                / size(subject_data_stim_session3.relativeCoherenceAbs,1);

        if violin == true
        % Response times ordered per stimulus level
        responsetimes_per_stim_level{iSubject}(iStimulus) = subject_data_stim.rt*1000;
        end
        
        % Mean response time per stimulus level    
        responsetime{iSubject}(iStimulus) = ...
            1000* nanmean(subject_data_stim.rt(~isnan(subject_data_stim.responseKey)));

        % Standard error of response time per stimulus level
        responsetime_se{iSubject}(iStimulus) = ...
            1000* std(subject_data_stim.rt(~isnan(subject_data_stim.responseKey))) ...
            / sqrt(length(subject_data_stim.rt(~isnan(subject_data_stim.responseKey))));

        % Mean confidence response time per stimulus level    
        responsetime_confidence{iSubject}(iStimulus) = ...
            1000* nanmean(subject_data_stim.confidenceRt(~isnan(subject_data_stim.confidence)));

        % Standard error of confidence response time per stimulus level
        responsetime_confidence_se{iSubject}(iStimulus) = ...
            1000* std(subject_data_stim.confidenceRt(~isnan(subject_data_stim.confidence))) ...
            / sqrt(length(subject_data_stim.confidenceRt(~isnan(subject_data_stim.confidence))));

        % Mean confidence per stimulus level
        confidence_mean{iSubject}(iStimulus) = ...
            nanmean(subject_data_stim.confidence);

            % Split first and second half
            confidence_mean_session2{iSubject}(iStimulus) = ...
                nanmean(subject_data_stim_session2.confidence);
            confidence_mean_session3{iSubject}(iStimulus) = ...
                nanmean(subject_data_stim_session3.confidence);

        % Confidence ratings per stimulus level
        for i = 1:4
            confidence_count{iSubject}{iStimulus}(i) = ...
                100* sum(subject_data_stim.confidence == i) ...
                / size(subject_data_stim.confidence,1);
        end
        confidence_count{iSubject}{iStimulus}(5) = ...
            100* sum(isnan(subject_data_stim.confidence)) ...
            / size(subject_data_stim.confidence,1);

        % Number correct per confidence rating per stimulus level
        for i = 1:4
            for j = [0 1]
                confidence_corr{iSubject}{iStimulus}(i, j+1) = ...
                   sum(subject_data_stim.confidence == i & ...
                   subject_data_stim.correct == j);
            end
        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);

        % Standard error of response time per confidence level
        responsetime_conf_se{iSubject}(iConfidence) = ...
            1000* std(subject_data_conf.rt) ...
            / sqrt(length(subject_data_conf.rt));

    end
    
    % Plot the sanity check data if plots are enabled

    if plots_sanity_check == true

        % Number of missed responses per stimulus level
        figure; bar(missed{iSubject}); 
            ylim([0 20]); 
            xlim([0.25 6.75]); 
            set(gca,'XTick',1:6,'XTickLabel',{'smallest','','','','','largest'});
            xlabel('Relative stimulus coherence')
            ylabel('Percentage trials missed')
            title(['Subject ' num2str(subjects(iSubject))]);
            %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Subject/S' num2str(subjects(iSubject)) '_missed responses per stimulus level.png'])

        % Percentage correct answers per stimulus level   
        figure; bar(correct_percentage{iSubject}); 
            ylim([0 100]); 
            xlim([0.25 6.75]); 
            set(gca,'XTick',1:7,'XTickLabel',{'smallest','','','','','largest'});
            xlabel('Relative stimulus coherence')
            ylabel('Percentage correct')
            title(['Subject ' num2str(subjects(iSubject))]);
            %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Subject/S' num2str(subjects(iSubject)) '_percentage correct per stimulus level.png'])

            % Split second and third session
            figure; suptitle(['Subject ' num2str(subjects(iSubject))]);
            hold on;
            for iPlot = 1:2
                subplot(1,2,iPlot);
                if iPlot == 1
                    bar(correct_percentage_session2{iSubject});
                    title('Session 2')
                else
                    bar(correct_percentage_session3{iSubject}); 
                    title('Session 3')
                end
            ylim([0 100]); 
            xlim([0.25 6.75]); 
            set(gca,'XTick',1:7,'XTickLabel',{'smallest','','','','','largest'});
            xlabel('Relative stimulus coherence')
            ylabel('Percentage correct')
            end      
            %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Subject/S' num2str(subjects(iSubject)) '_percentage correct responses per stimulus level - session split.png'])

        if violin == true
            % Response times per stimulus level in violin plot
            figure; hold on;
                for iStimulus = 1:6
                    violinplot(responsetimes_per_stim_level{iSubject});
                end
                ylim([0 4500]); 
                xlim([0.25 6.75]); 
                set(gca,'XTick',1:6,'XTickLabel',{'smallest','','','','','largest'});
                xlabel('Relative stimulus coherence')
                ylabel('Response time (ms)')
                title(['Subject ' num2str(subjects(iSubject))]);
                hold off;
                %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Subject/S' num2str(subjects(iSubject)) '_RT per stimulus level violin plot.png'])
        end

        % Mean response time per stimulus level, with standard errors
        figure; hold on;
            bar(responsetime{iSubject});
            errorbar(responsetime{iSubject}, responsetime_se{iSubject}, '.')
            ylim([0 2500]); 
            xlim([0.25 6.75]); 
            set(gca,'XTick',1:6,'XTickLabel',{'smallest','','','','','largest'});
            xlabel('Relative stimulus coherence')
            ylabel('Response time (ms)')
            title(['Subject ' num2str(subjects(iSubject))]);
            hold off;
            %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Subject/S' num2str(subjects(iSubject)) '_mean RT per stimulus level.png'])
    
        % Mean confidence response time per stimulus level, with standard errors
        figure; hold on;
            bar(responsetime_confidence{iSubject});
            errorbar(responsetime_confidence{iSubject},responsetime_confidence_se{iSubject},'.'); 
            ylim([0 2500]); 
            xlim([0.25 6.75]); 
            set(gca,'XTick',1:6,'XTickLabel',{'smallest','','','','','largest'});
            xlabel('Relative stimulus coherence')
            ylabel('Confidence response time (ms)')
            title(['Subject ' num2str(subjects(iSubject))]);
            hold off;
            %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Subject/S' num2str(subjects(iSubject)) '_mean confidence RT per stimulus level.png'])

        % Mean confidence per stimulus level 
        figure; bar(confidence_mean{iSubject}); 
            ylim([0 4]); 
            xlim([0.25 6.75]); 
            set(gca,'XTick',1:6,'XTickLabel',{'smallest','','','','','largest'});
            xlabel('Relative stimulus coherence')
            ylabel('Confidence (1-4)')
            title(['Subject ' num2str(subjects(iSubject))]);
            %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Subject/S' num2str(subjects(iSubject)) '_mean confidence per stimulus level.png'])

            % Split first and second half
            figure; suptitle(['Subject ' num2str(subjects(iSubject))]);
            hold on;
            for iPlot = 1:2
                subplot(1,2,iPlot);
                if iPlot == 1
                    bar(confidence_mean_session2{iSubject}); 
                    title('Session 2')
                else
                    bar(confidence_mean_session3{iSubject}); 
                    title ('Session 3')
                end
            ylim([0 4]); 
            xlim([0.25 6.75]); 
            set(gca,'XTick',1:6,'XTickLabel',{'smallest','','','','','largest'});
            xlabel('Stimulus orientation')
            ylabel('Confidence')
            end     
            %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Subject/S' num2str(subjects(iSubject)) '_mean confidence per stimulus level - session split.png'])

        % Confidence ratings per stimulus level
        figure; suptitle(['Subject ' num2str(subjects(iSubject))]);
        hold on;
        for iStimulus = 1:6
            subplot(2,3,iStimulus);
            bar(confidence_count{iSubject}{iStimulus});
            ylim([0 100]); 
            xlim([0.25 5.75]);                  
            set(gca,'XTick',1:6,'XTickLabel',{'1','2','3','4','NaN'});
            xlabel('Confidence rating')
            ylabel('Percentage')
            title(['Coherence level ' num2str(stim_levels(iStimulus))]);
            hold off;
        end
        %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Subject/S' num2str(subjects(iSubject)) '_confidence ratings per stimulus level.png'])

        % Correct and incorrect per confidence rating per stimulus level
        figure; suptitle(['Subject ' num2str(subjects(iSubject))]);
        hold on;
        for iStimulus = 1:6
            subplot(2,3,iStimulus);
            st = bar(confidence_corr{iSubject}{iStimulus},'stacked');
            st(1).FaceColor = 'r';
            st(2).FaceColor = 'g';
            ylim([0 100]); 
            xlim([0.25 5.75]);                  
            set(gca,'XTick',1:6,'XTickLabel',{'1','2','3','4','NaN'});
            xlabel('Confidence rating')
            ylabel('Percentage')
            title(['Coherence level ' num2str(stim_levels(iStimulus))]);
            hold off;
        end
        %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Subject/S' num2str(subjects(iSubject)) '_number correct per confidence rating per stimulus level.png'])

        % Percentage correct answers per confidence rating
        figure; bar(correct_percentage_conf{iSubject}); 
            ylim([0 100]); 
            xlim([0.25 4.75]); 
            set(gca,'XTick',1:7,'XTickLabel',{'1','2','3','4'});
            xlabel('Confidence rating')
            ylabel('Percentage correct')
            title(['Subject ' num2str(subjects(iSubject))]);
            %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Subject/S' num2str(subjects(iSubject)) '_percentage correct per confidence rating.png'])

        % Mean response time per condence rating, with standard errors
        figure; hold on;
            bar(responsetime_conf{iSubject});
            errorbar(responsetime_conf{iSubject},responsetime_conf_se{iSubject},'.'); 
            ylim([0 3000]); 
            xlim([0.25 4.75]); 
            set(gca,'XTick',1:6,'XTickLabel',{'1','2','3','4'});
            xlabel('Confidence rating')
            ylabel('Direction response time (ms)')
            title(['Subject ' num2str(subjects(iSubject))]); 
            %saveas(gcf,['P:/3018029.09/Graphs/Sanity checks/' folder_str '/Subject/S' num2str(subjects(iSubject)) '_mean RT per condence rating.png'])
         
        close all
        
    end
    
end



%{
•	reaction time histogram (Floris addition)
•	difficulty x reaction time
•	difficulty x subjective confidence
•	reaction time x subjective confidence
    o	which one on x-axis is clearer?
    o	Spearman’s correlation (ordinal x continuous)
•	Psychometric curves
%}