function PTBParams = InitPTB(homePath,varargin)
% function PTBParams = InitPTB(homePath,['DefaultSession',ssnid])
%
% Function for initializing parameters at the beginning of a session
%
% Inputs:
% - homePath: Path specifying directory for the study
% - 'DefaultSession'
% Author: Cendri Hutcherson
% Last Modified: 05-27-18

% \ Clear any open screens or figures \
close all;
Screen('CloseAll');

% \ Create participant directory and data file \
% This code will first prompt the user to specify a participant ID, as well
% as a session/task identifier. Default values are specified for ease of
% use, with the file taking the generic form "Data.[pID].[ssnID].mat.
% The code then checks to make sure that this datafile does not
% already exist. If it does, it issues a warning to the user that the file
% is about to be overwritten, and forces the user to indicate that
% overwriting is the desired behavior. The program will cycle through this
% loop as long as it takes for the user to indicate they are satisfied with
% the resulting file name. The file will be created, and a time-stamp saved
% indicating the date and time of creation.

cd(homePath);
checkPID = true;
while checkPID
    pID = input('Participant ID:  ', 's');
    ssnID = input('Session ID:  ', 's');

    % Set defaults for Pp and session IDs
    if isempty(pID)
        pID = '999';
    end

    if isempty(ssnID)
        if isempty(varargin) || ~any(strcmp(varargin,'DefaultSession'))
            ssnID = '1';
        else
            index = find(strcmp(varargin,'DefaultSession'));
            ssnID = varargin{index + 1};
        end
    end

    fprintf('\nSaving datafile as Data.%s.%s.mat\n\n',pID,ssnID)

    % Issue warning if a datafile with this identifier already exists and
    % move on only if command is given to overwrite
    checkPID = false;
    pFile = fullfile(homePath, 'SubjectData', pID, ['Data.' pID '.' ssnID '.mat']);
    if exist(pFile,'file')
        moveOn = input('WARNING: Datafile already exists!  Overwrite? (y/n)  ','s');
        if isempty(moveOn) || moveOn == 'n'
            checkPID = true;
        end
    end
end

% Create directory and initial data file
pFolder = fullfile(homePath, 'SubjectData', pID);
if ~exist(pFolder,'dir')
    mkdir(pFolder);
end


Data.pID = pID;
Data.ssnID = ssnID;
Data.startTime = datestr(now);

save(pFile,'Data');



% \ Initialize PsychToolbox Parameters and save in PTBParams struct \
% This code will hide the cursor, and open an on-screen PsychToolBox
% display window. This window can either be opened full-screen, or if
% debugging, in partial screen mode (for all subject numbers > 900). A
% structure named PTBParams is created that will store certain defaults
% including 1) the window identifier and the size of the window; 2) the
% color specification for white, black, and gray; 3) information about the
% keyboard input; and 4) set the default text size and color.

AssertOpenGL;
ListenChar(2); % don't print keypresses to screen
% Screen('Preference', 'SkipSyncTests', 1); % may have to use if VBL fails
Screen('Preference', 'VisualDebugLevel',3);

HideCursor;

screens = Screen('Screens');
screenNum = max(screens);
% determine whether to run in partial screen mode
if str2double(pID) > 900
    [w, rect] = Screen('OpenWindow',screenNum, [], [0 0 800 600]);
else
    [w, rect] = Screen('OpenWindow',screenNum);
end

ifi = Screen('GetFlipInterval', w);

% Create PTBParams structure (used for study parameters later)
PTBParams.win = w;
PTBParams.rect = rect;
PTBParams.ctr = [rect(3)/2, rect(4)/2];
PTBParams.white = WhiteIndex(w);
PTBParams.black = BlackIndex(w);
PTBParams.gray = (WhiteIndex(w) + BlackIndex(w))/2;
PTBParams.ifi = ifi;
PTBParams.datafile = pFile;
PTBParams.homepath = homePath;
PTBParams.subjid = str2double(pID);
PTBParams.ssnid = ssnID;
PTBParams.KbDevice = -1; % accept input from all keyboards
PTBParams.numKeys = {'1!' '2@' '3#' '4$' '5%' '6^' '7&' '8*' '9(' '0)'};

% save PTBParams structure
PTBfile = fullfile(homePath, 'SubjectData', pID, ['PTBParams.' PTBParams.ssnid '.mat']);
save(PTBfile,'PTBParams');

% set default text options
Screen(w,'TextSize',round(.1*PTBParams.ctr(2)));
Screen('TextFont',w,'Helvetica');
Screen('FillRect',w,PTBParams.black);

% used to initialize mouse cursor, otherwise the first time
% this is called elsewhere it can take up to 300ms, throwing off timing
GetMouse(w);

% \ Seed random number generator  \
% On various systems, it can be useful to 'seed' the random number
% generator so that it generates different random orders and values every
% time the script is run. Note that different versions of Matlab
% allow/deprecate different random number generators, so I've incorporated
% some flexibility here

[v, d] = version; % get Matlab version
if datenum(d) > datenum('April 8, 2011') % compare to first release of rng
    rng('shuffle')
else
    rand('twister',sum(100*clock));
end