% Clear the workspace
clear;
close all;
sca;

% Setup PTB with some default values
PsychDefaultSetup(2);

% Seed the random number generator
rng('shuffle');

% Get the screen numbers
screens = Screen('Screens');

% Draw to the external screen if available
screenNumber = max(screens);

% Define black and gray
black = BlackIndex(screenNumber);
gray = GrayIndex(screenNumber);

% Open an on screen window and color it gray
[window, windowRect] = PsychImaging('OpenWindow', screenNumber, gray);

% Set the blend function for the screen
Screen('BlendFunction', window, 'GL_SRC_ALPHA', 'GL_ONE_MINUS_SRC_ALPHA');

% Get the size of the on screen window in pixels
[screenXpixels, screenYpixels] = Screen('WindowSize', window);

% Query the frame duration
ifi = Screen('GetFlipInterval', window);

% Set the text size
Screen('TextSize', window, 40);

% Setup the timing
stimDisplayTime = 2.5;
responseTime = 5;
nTrials = 370;
nBlocks = 2;
stimuli = generateStimuli(500); % Create your stimuli here

% Start the experiment
for block = 1:nBlocks
    disp(['Starting block ', num2str(block)]);
    Screen('TextSize', window, 24);
    DrawFormattedText(window, 'Press Space to begin.', 'center', 'center', black);
    Screen('Flip', window);
    KbWait([], 2);
    
    for trial = 1:nTrials
        % Display the stimulus
        stimulus = stimuli(randi(numel(stimuli))); % Randomly pick a stimulus
        DrawFormattedText(window, stimulus, 'center', 'center', black);
        tStart = Screen('Flip', window);
        
        % Wait for the display time
        WaitSecs(stimDisplayTime);
        
        % Clear the screen
        Screen('Flip', window);
        
        % Wait for a response or timeout
        response = 0;
        tResponse = tStart;
        while GetSecs - tResponse < responseTime
            [keyIsDown, ~, keyCode] = KbCheck;
            if keyIsDown
                if keyCode(KbName('n'))
                    response = 'novel';
                    break;
                elseif keyCode(KbName('r'))
                    response = 'repeated';
                    break;
                end
            end
        end
        
        % Log the response
        results(block, trial) = {stimulus, response};
        
        % Initiate the next trial
        KbWait([], 2);
    end
    
    % Break between blocks
    if block < nBlocks
        WaitSecs(1800); % 30 minutes break
    end
end

% Close the screen
sca;

function stimuli = generateStimuli(n)
    stimuli = cell(1, n);
    for i = 1:n
        stimuli{i} = ['Stimulus ', num2str(i)];
    end
end
