try
    screens = Screen('Screens');
    whichscreen = max(screens);
    [myscreen,rect]=Screen('OpenWindow',whichscreen);
    DrawFormattedText(myscreen, 'PRESS ANY KEY TO PROCEED', 'center', ...
    'center');
    Screen('Flip', myscreen);
    KbWait;
    g = KbName('g');
    r = KbName('r');
    ntrials = 6;
    colorsequence = [1, 2, 2, 2, 1, 1];
    rt = zeros(ntrials, 1);
    response = zeros(ntrials, 1);
    stimulus_duration = zeros(ntrials, 1);
    for i=1:ntrials
        WaitSecs(1);
        Screen('FrameOval', myscreen, 0, CenterRect([0, 0, 10, 10], rect));
        onset_fixation = Screen('Flip', myscreen);
        if colorsequence(i) == 1
            stimuluscolor = [255, 0, 0];
        else
            stimuluscolor = [0, 255, 0];
        end
        Screen('FillRect', myscreen, stimuluscolor, CenterRect([0, 0, 50, ...
            50], rect));
        random_delay = rand+0.5;
        onset_stimulus = Screen('Flip', myscreen, onset_fixation + ...
        random_delay);
        t0 = GetSecs;
        [keyIsDown, secs, keyCode] = KbCheck;
        while keyCode(g)==0 && keyCode(r)==0
            [keyIsDown, secs, keyCode] = KbCheck;
        end
        rt(i) = secs - t0;
        response(i) = find(keyCode==1);
        stimulus_offsettime = Screen('Flip', myscreen);
        stimulus_duration(i) = stimulus_offsettime - t0;
    end
    screen('CloseAll');
catch
    Screen('CloseAll')
    rethrow(lasterror)
end