% standard opening commands
clc;
clear all;
close all;
rng('shuffle');

% you need to ask for the filename before you turn off keyboard input BUT
% after you clear everything!
filename = input('Enter a filename: ','s');

% Hide the cursor and "disable" keyboard
% Press ctl-c to bring it back
ListenChar(2);
HideCursor();

% define variables, the keys we want people to respond with (this is from the previous exercise)
% lets define out target keys, this also gets the ASCII or numeric index for they key
k1 = 'a';
k2 = 'l';
k3 = 'space';
keyOne = KbName(k1);
keyTwo = KbName(k2);
keyThree = KbName(k3);
% let's also define a background colour. when you open a window for drawing
% this is the preset background colour
background_colour = [255 255 255];

% open a drawing window
Screen('Preference', 'SkipSyncTests', 1); 
[window, window_size] = Screen('OpenWindow', 0, background_colour, [],32,2);

% figure out where the middle of the screen is
x_mid = window_size(3)/2;
y_mid = window_size(4)/2;

% define a the rectanges that will be draw. recall these just consist of
% four numbers, the top left x and y values and the bottom right x and y
% valuesa
stimulus_size = 50;
distance_from_middle = 200;
left_top_x = x_mid - distance_from_middle - stimulus_size;
left_top_y = y_mid - stimulus_size;
left_bottom_x = x_mid - distance_from_middle + stimulus_size;
left_bottom_y = y_mid + stimulus_size;
left_square = [left_top_x left_top_y left_bottom_x left_bottom_y];
right_top_x = x_mid + distance_from_middle - stimulus_size;
right_top_y = y_mid - stimulus_size;
right_bottom_x = x_mid + distance_from_middle + stimulus_size;
right_bottom_y = y_mid + stimulus_size;
right_square = [right_top_x right_top_y right_bottom_x right_bottom_y];
middle_top_x = x_mid - stimulus_size;
middle_top_y = y_mid - stimulus_size;
middle_bottom_x = x_mid + stimulus_size;
middle_bottom_y = y_mid + stimulus_size;
middle_square = [middle_top_x middle_top_y middle_bottom_x middle_bottom_y];
% do not panic, work through what these values are - they just refer to three squares

% set the number of blocks and trials
block_order = [1 1 2 2];
block_order = shuffle(block_order);
% you have to be careful here - the number of blocks has to be equal to the
% length of block order - think about why!
number_of_blocks = length(block_order);
number_of_trials = 5;

% assign a trial counter that keeps track of the actual trial you are on in
% total
actual_trial_counter = 1;

for block_counter = 1:number_of_blocks
    
    % determine block type - think about how this works given block_order
    block_type = block_order(block_counter);
    
    % stick up some instructions
    if block_type == 1
        instructions1a = 'In this block you are doing simple reaction time.'
        instructions1b = 'Press the space bar when you see a square.'
    else
        instructions1a = 'In this block you are doing choice reaction time.'
        instructions1b = 'Press the "a" for a square on the left, the "l" key for a square on the right.';
    end
    Screen(window,'TextFont','Arial');
    Screen(window,'TextSize',20);
    DrawFormattedText(window, instructions1a,'center', y_mid-50, [0 0 0],[],[],[],2);
    DrawFormattedText(window, instructions1b,'center', y_mid+50, [0 0 0],[],[],[],2);
    DrawFormattedText(window, 'Press Any Key To Continue','center', y_mid+200, [0 0 0],[],[],[],2);
    % never forget to flip!
    Screen('Flip',window);

    % handy command, waits for any key to be pressed
    KbPressWait;
    
    % draw an instruction
    Screen(window,'TextFont','Arial');
    Screen(window,'TextSize',20);
    DrawFormattedText(window, ['Get ready!'],'center', 'center', [0 0 0],[],[],[],2);
    % never forget to flip!
    Screen('Flip',window);

    % wait for three seconds
    WaitSecs(3);

    for trial_counter = 1:number_of_trials

        % figure out where we are drawing the square, if block_type == 1
        % then the middle, if block_type == 2 then randomly pick the left
        % or right square
        if block_type == 1
            stimulus_side = 0;
            drawn_square = middle_square;
        else
            % note cleaned this up a bit to make it easier to read use
            % randi instead of rand
            stimulus_side = randi([1 2],1);
            if stimulus_side == 1
                drawn_square = left_square;
            else
                drawn_square = right_square;
            end
        end

        % I am going to use Formatted Text to draw the fixation + sign
        Screen(window,'TextFont','Arial');
        Screen(window,'TextSize',40);
        DrawFormattedText(window, ['+'],'center', 'center', [0 0 0],[],[],[],2);
        % never forget to flip!
        Screen('Flip',window);

        % wait for some amount of time, between 400 and 700 ms
        random_delay = 0.4 + rand(1)*0.3;
        WaitSecs(random_delay);
        
        % makes sure no keys are down
        KbReleaseWait;

        % start a reaction time clock
        tic;

        % draw the target square
        Screen('FillRect', window , [0 0 0], drawn_square);
        % redraw the fixation cross, the flip command erases all previously drawn
        % items
        DrawFormattedText(window, ['+'],'center', 'center', [0 0 0],[],[],[],2);
        % never forget to flip!
        Screen('Flip',window);

        % wait for the response
        while 1

            % read the current status of the keyboard
            [keyIsDown, secs, keyCode] = KbCheck;
            % this returns some key information
            % keyIsDown is a variable that is a 1 if a key is pressed and 0 if no key is pressed
            % secs is the time of the key press
            % keyCode is a vector for each key, a 1 will appear in the vector for the key that has been pressed

            % this is a logic test, if the value of keyCode corresponding
            % to 'a' is pressed.
            % you will not here that any response key is valid in any
            % block.
            if keyCode(keyThree) == 1
                response_type = 0;
                reaction_time = toc;
                break;
            end
            if keyCode(keyOne) == 1
                response_type = 1;
                reaction_time = toc;
                break;
            end
            if keyCode(keyTwo) == 1
                response_type = 2;
                reaction_time = toc;
                break;
            end

        end
        
        % assume they are wrong
        response_correct = 0;
        % change this to a 1 if they are right
        if block_type == 1 & stimulus_side == 0 & response_type == 0
            response_correct = 1;
        end
        if block_type == 2 & stimulus_side == 1 & response_type == 1
            response_correct = 1;
        end
        if block_type == 2 & stimulus_side == 2 & response_type == 2
            response_correct = 1;
        end
        
        % store some data for analysis
        student_data(actual_trial_counter,1) = block_counter;
        student_data(actual_trial_counter,2) = block_type;
        student_data(actual_trial_counter,3) = trial_counter;
        student_data(actual_trial_counter,4) = stimulus_side;
        student_data(actual_trial_counter,5) = response_type;
        student_data(actual_trial_counter,6) = reaction_time;
        student_data(actual_trial_counter,7) = response_correct;
        
        % increment this by 1
        actual_trial_counter = actual_trial_counter + 1;
        
        % blank the screen for one second
        Screen('Flip',window);
        WaitSecs(1);

    end
    
end

% draw an instruction
Screen(window,'TextFont','Arial');
Screen(window,'TextSize',20);
DrawFormattedText(window, ['You are now done the experiment. Thank you.'],'center', 'center', [0 0 0],[],[],[],2);
% never forget to flip!
Screen('Flip',window);

% wait for three seconds
WaitSecs(3);

% close the drawing window
Screen('CloseAll');
% Hide the cursor and "disable" keyboard
% Press ctl-c to bring it back
ListenChar(0);
ShowCursor();

save(filename,'student_data');

clc;

% covert student data to a table
analysis_data = array2table(student_data);
analysis_data.Properties.VariableNames = {'BlockCounter' 'BlockType' 'TrialCounter' 'StimulusSide' 'ResponseType' 'RT' 'Accuracy'};

mean_RT1 = mean(analysis_data.RT(analysis_data.BlockType == 1));
mean_RT2 = mean(analysis_data.RT(analysis_data.BlockType == 2));

mean_ACC1 = mean(analysis_data.Accuracy(analysis_data.BlockType == 1));
mean_ACC2 = mean(analysis_data.Accuracy(analysis_data.BlockType == 2));

subplot(1,2,1);
RTs = [mean_RT1 mean_RT2];
% covert to ms
RTs = RTs * 1000;
% draw a bar graph
bar(RTs);
title('Reaction Time');

subplot(1,2,2);
ACCs = [mean_ACC1 mean_ACC2];
% covert to percent
ACCs = ACCs * 100;
% draw a bar graph
bar(ACCs);
title('Reaction Time');