%% fMRI: Dare to approach experiment - practice script
% Run this script to initiate the experiment. Check input defaults!
% 02-03-2020, by Felix Klaassen

% Make sure you start fresh
clearvars;clc
rng('shuffle'); KbName('UnifyKeyNames');
delete(instrfind); ListenChar(0); RestrictKeysForKbCheck([]);

% Set global variables
global ButtonPhys ScannerShock %#ok<NUSED>

%% Set preferences
cfg.input = inputdlg({'Environment: Scanner(1), Dummy(2), Cubicle(3), Desk(4), Laptop(5)','Debug mode (0=No,1=Yes)'},...
    'Input',1,{'3','0'});

if isempty(cfg.input)
    return
end

cfg.environment = {'Scanner','Dummy','Cubicle','Desk','Laptop'};
cfg.environment = cfg.environment{str2double(cfg.input(1))};

if str2double(cfg.input(2)) == 1
    debugging = true;
else
    debugging = false;
end

if debugging || strcmp(cfg.environment, 'Laptop')
    Screen('Preference','SkipSyncTests',1);
end

addpath Tools Stimuli
setup_bitsi;

%% Create directories
cfg.date = clock;
dir.root = pwd;

%% Setup and open the screen
commandwindow;
if numel(Screen('Screens')) > 1
    screen.nr = 1;
else
    screen.nr = 0;
end
screen.resolution = Screen('Resolution',screen.nr);
if debugging
    [wd,rect] = Screen('OpenWindow',screen.nr,[40 40 40],[0 0 screen.resolution.width/2 screen.resolution.height/2]);
else
    [wd,rect] = Screen('OpenWindow',screen.nr,[40 40 40]);
    HideCursor;
end

% Make the presentation window the highest CPU priority
Priority(MaxPriority(wd));

screen.hz = Screen('Framerate', wd);
screen.x = rect(3);
screen.y = rect(4);
cfg.screen = screen;

%% Get all parameters
% Set text
ResetText(wd);

% Show loading screen...
DrawFormattedText(wd, 'Loading...','center', 'center',[255 255 255]);
Screen('Flip', wd);

run('Parameters.m');

%% Load practice counterbalancing matrix
% Read cb_mat columns as follows:
% 1) Trial Type                 (1 = Towards, 2 = Away)
% 2) Reward                     (1 - 5)
% 3) Shock                      (1 - 5)
% 4) Target Location Options    (1 = Left, 2 = Right)        
% 5) Cue to Stimulus Interval   (6*short, 6*medium, 50*long) 
% 6) Intertrial Interval        (8 - 10 seconds)             

% Load counterbalancing matrix for this participant and run
addpath Counterbalancing
load('Counterbalancing\cb_mat_practice.mat');

% Cut it in blocks
cfg.cb_mat = cell(1,cfg.nrPracticeBlocks);
for i = 1:cfg.nrPracticeBlocks
    cfg.cb_mat{i} = cb_mat_practice((i-1)*cfg.nrPracticeTrials+1:cfg.nrPracticeTrials*i,:);
end

doPractice = true;

%% Display instructions
Screen('TextFont', wd, 'Calibri');
Screen('TextStyle', wd, 0); % 0 = normal;1=bold;2=italic;4=underline
Screen('TextSize', wd, 16);

run('InstructionsPractice.m');
fprintf([datestr(now) ' Instructions started\n']);

i = 1;
while i <= length(instructions)
    draw_centered_text(wd, instructions{i}, cfg.color.text, cfg.screen.x/2, cfg.screen.y/2, cfg.wrapat, cfg.vSpacing);
    if i == 2
        Screen('FillOval',wd,cfg.color.target,cfg.stim.targetinstr);
        Screen('FillRect',wd,[cfg.color.self' cfg.color.plholder'],[cfg.stim.selfinstr' cfg.stim.plholderinstr']);
        Screen('DrawText',wd,'<- Target', cfg.stim.targetinstr(3)+10, cfg.stim.targetinstr(2)+5,cfg.color.text);
        Screen('DrawText',wd,'<- You', cfg.stim.selfinstr(3)+10, cfg.stim.selfinstr(2)+5,cfg.color.text);
        Screen('DrawText',wd,'<- Placeholder', cfg.stim.plholderinstr(3)+10,cfg.stim.plholderinstr(2)-10,cfg.color.text);
        
    elseif i == 3
        Screen('FillOval',wd,cfg.color.target,cfg.stim.targetinstr);
        Screen('FillRect',wd,[cfg.color.self' cfg.color.plholder'],[cfg.stim.selfinstr' cfg.stim.plholderinstr']);
        
        Screen('DrawTextures', wd, [cfg.stim.LeftArrow.img,cfg.stim.RightArrow.img,cfg.stim.DownArrow.img],...
            [],[cfg.stim.LeftArrow.rect',cfg.stim.RightArrow.rect',cfg.stim.DownArrow.rect']);
        Screen('DrawText',wd,'<- Placeholder', cfg.stim.plholderinstr(3)+10,cfg.stim.plholderinstr(2)-10,cfg.color.text);
        
    elseif i == 4
        Screen('FillOval', wd, cfg.color.target, cfg.stim.targetlocations{1}{1}(1,:));
        Screen('FillRect', wd, [cfg.color.plholder',cfg.color.plholder',cfg.color.self'], ...
            [cfg.stim.placeholderlocations(1,:)',cfg.stim.placeholderlocations(3,:)',...
            cfg.stim.selflocations(3,:)']);
        
    elseif i == 5
        Screen('DrawTextures', wd, cfg.stim.RewardCue.img,[],cfg.stim.RewardCue.draw{3});
        Screen('DrawTextures', wd, cfg.stim.ShockCue.img,[],cfg.stim.ShockCue.draw{5});
        Screen('DrawTextures', wd, cfg.stim.ApproachProbs.img,[],cfg.stim.ApproachProbs.rect);
        Screen('DrawTextures', wd, cfg.stim.AvoidProbs.img,[],cfg.stim.AvoidProbs.rect);
        
    elseif i == 7
        Screen('DrawTextures', wd, cfg.stim.RewardCue.img,[],cfg.stim.RewardCue.draw{3});
        Screen('DrawTextures', wd, cfg.stim.ShockCue.img,[],cfg.stim.ShockCue.draw{5});
        Screen('FillOval', wd, cfg.color.target, cfg.stim.targetlocations{1}{1}(1,:));
        Screen('FillRect', wd, [cfg.color.plholder',cfg.color.plholder',cfg.color.self'], ...
            [cfg.stim.placeholderlocations(1,:)',cfg.stim.placeholderlocations(3,:)',...
            cfg.stim.selflocations(3,:)']);
        
    elseif i == 8
        Screen('DrawTextures', wd, cfg.stim.ApproachProbs.img,[],cfg.stim.ApproachProbs.rect);
        Screen('DrawTextures', wd, cfg.stim.AvoidProbs.img,[],cfg.stim.AvoidProbs.rect);
        
    end
    Screen('Flip', wd);
    ButtonPhys.clearResponses();
    resp = ButtonPhys.getResponse(inf, true);
    if i > 1 && resp == cfg.button1
        i = i-1;
    elseif resp == cfg.button2
        i = i+1;
  elseif resp == KbName('q')
        doPractice = false;
        doMain = false;
        break
    end
    WaitSecs(0.2);
end
ResetText(wd);

%% Run Practice blocks
fprintf([datestr(now) ' Start of practice rounds!\n']);

practiceCycle = 1;
while doPractice
    ResetText(wd);
    cfg = runPracticeBlock(cfg,wd,practiceCycle);
    
    %% Intermediate screen
    ListenChar(0); RestrictKeysForKbCheck([]);
    Screen('TextFont', wd, 'Calibri');
    Screen('TextStyle', wd, 0); % 0 = normal;1=bold;2=italic;4=underline
    Screen('TextSize', wd, 16);
    
    draw_centered_text(wd, 'End of the practice rounds.\n\nDo you have any questions? If so, please ask them now.\n\n',...
        cfg.color.text, cfg.screen.x/2, cfg.screen.y/2, cfg.wrapat, cfg.vSpacing);
    Screen('Flip',wd);
    
    WaitSecs(2);
    RestrictKeysForKbCheck([KbName('y') KbName('p')]);
    [~,keyResponse,~] = KbWait;
    if keyResponse(KbName('y')) == 1 % Finish practice rounds
        doPractice = false;
    elseif keyResponse(KbName('p')) == 1 % Repeat practice
        practiceCycle = practiceCycle+1;
        if practiceCycle == 4
            practiceCycle = 1;
        end
    end
end

ListenChar(0); RestrictKeysForKbCheck([]);
ResetText(wd);

%% Close off
clearvars -except cfg dir

Screen('CloseAll')