%_______________________________________________________________________
%
% Run random dot motion experiment defined in createDotInfo
%_______________________________________________________________________
%
% Input
%
% dotInfo | experiment configuration (struct)
%    subj | identifier of subject (string)
% condSet | conditions (cell array of strings)
%_______________________________________________________________________
%

% adapted from dotsExperiment_JQK_170327
% 170704    | cleanup, adapted
% 170707    | removed saving for each trial; instead save in catch part
%           | now saves DisplayInfo

function MAT_experiment_170704(dotInfo, subj, DEBUG, opacity)

  %%
  %% sanitize function parameters
  %%
  if nargin == 0
    eval('help dotsExperiment')
    return
  end

  if not(exist('dotInfo','var'))
    error('Missing input: dotInfo')
  elseif isempty(dotInfo) || not(isstruct(dotInfo))
    error('Invalid input: dotInfo (requires non-empty struct)')
  end

  if not(exist('subj','var'))
    error('Missing input: subj')
  elseif not(isempty(subj)) && ischar(subj)
    dotInfo.subj = subj;
  else
    error('Invalid input: subj (requires non-empty string)')
  end

  if not(isfield(dotInfo,'deployed'))
    dotInfo.deployed = true;
  end

  %%
  %% for saving behavioural data
  %%
  
  sessionFile = [dotInfo.dataDir, subj '_' datestr(now, 'yymmdd_HHMM'), '.mat'];
    
  %%
  %% prepare presentation
  %%
  displayList = Screen('screens');
  displayIdx = displayList(1);
  KbName('UnifyKeyNames'); % use portable key naming scheme
  oldVerbosityLevel = Screen('Preference', 'Verbosity', 2); % show errors and warnings
  arrowKeys = [dotInfo.keyLeft dotInfo.keyRight];
  baseDotInfo = dotInfo; % keep for saving later
  
    if DEBUG == 1
        Screen('Preference', 'SkipSyncTests', 1);
        PsychDebugWindowConfiguration(0, opacity);
    else
        clear Screen; %PsychDebugWindowConfiguration([], 1);
    end;

  try

    %%
    %% prepare canvas
    %%
    screenInfo = openExperiment(50,50,displayIdx); clc; % open drawing canvas
    if numel(Screen('screens')) == 1 || dotInfo.deployed
      HideCursor(screenInfo.curWindow);
    end
    Screen('TextFont', screenInfo.curWindow, 'Helvetica');
    Screen('TextSize', screenInfo.curWindow, 20);
    Screen('TextStyle', screenInfo.curWindow, 0); % regular
    Screen('TextColor', screenInfo.curWindow, 255); % white

    sessStartTime = GetSecs;

    ResultMat = NaN(dotInfo.totalTrials,4);
    DisplayInfo = [];
    ExperimentProtocol = cell(0);
    ExperimentProtocol = [ExperimentProtocol; {'SessionOnset'}, {sessStartTime}, {[]}, {[]}, {[]},{NaN}, {[]}];
    
      %%
      %% block start
      %%
      
        % have the subject get ready for the next condition
        DrawFormattedText(screenInfo.curWindow, 'Bereit?', 'center', 'center');
        Screen('Flip', screenInfo.curWindow);

        % wait for experimenter to resume session
        while true
            [exitSession, resumeSession] = checkKeys(dotInfo);
        if resumeSession
            break
        elseif exitSession
            closeExperiment;
            return
        end
        end
      
      for indTrial = 1:dotInfo.totalTrials
            fprintf(' (%i)\n', indTrial)
            TrialInitiation = GetSecs;
            ExperimentProtocol = [ExperimentProtocol; {'TrialInitiation'}, {TrialInitiation}, {[]}, {[]}, {[]}, {indTrial}, {[]}];
            % create fixation
            targets = makeDotTargets(screenInfo, dotInfo); % initialize targets
            %showTargets(screenInfo, targets, 1);
            [~, dotInfo, ExperimentProtocol,ResultMat,DisplayInfo] = dotsX_JQK_MAT_170704(screenInfo, dotInfo, targets, indTrial, ExperimentProtocol,ResultMat,DisplayInfo);
            % take a break when specified
            if ismember(indTrial, dotInfo.PauseAfterTrials)
                PauseStart = GetSecs();
                ExperimentProtocol = [ExperimentProtocol; {'PauseStart'}, {PauseStart}, {[]}, {[]}, {[]}, {indTrial}, {[]}];
                while (GetSecs()-PauseStart) < dotInfo.breakTime
                    % have the subject get ready for the next condition
                    pause(.1);
                    remain = dotInfo.breakTime-round(GetSecs - PauseStart,0);
                    DrawFormattedText(screenInfo.curWindow, ['Pause: continue in ',num2str(remain),' s'], 'center', 'center');
                    Screen('Flip', screenInfo.curWindow);
                end
            end
      end % trial presentation
      
      sessEndTime = GetSecs;
      ExperimentProtocol = [ExperimentProtocol; {'SessionEnd'}, {sessEndTime}, {[]}, {[]}, {[]}, {indTrial}, {[]}];

      save(sessionFile, 'ExperimentProtocol', 'dotInfo', 'ResultMat', 'DisplayInfo');

    % inform the subject that the experiment is over
    DrawFormattedText(screenInfo.curWindow, 'task complete!', 'center', 'center');
    Screen('Flip', screenInfo.curWindow);

%     sessTime = GetSecs - sessStartTime;
%     meanFixTime = mean([trialData.fixTime]);
%     numCorrect = numel(find([trialData.correct]));
%     numTrial = numel([trialData.correct]);
%     numResponded = numel(find(~isnan([trialData.rxtime])));
%   
%     fprintf('\nTotal Time: %.2f\n', sessTime) % incl. block startup waits
%     fprintf('Average fixation: %.2fs\n', meanFixTime)
%     fprintf('Responded: %i/%i\n', numResponded, numTrial)
%     fprintf('Correct: %i/%i\n', numCorrect, numTrial)
%     fprintf('Accuracy: %.1f\n', 100*numCorrect/numResponded)

    % wait for experimenter to close screen
    while true
      [exitKeyPressed, resumeKeyPressed] = checkKeys(dotInfo);
      if exitKeyPressed || resumeKeyPressed
        break
      end
    end

  catch exception
    getReport(exception) % show stack trace
    save(sessionFile);
  end

  closeExperiment; % close drawing canvas
  Screen('Preference', 'Verbosity', oldVerbosityLevel); % restore verbosity

end
