%_______________________________________________________________________
%
% Run random dot motion introduction called from dotsExperiment
%_______________________________________________________________________
%
% A set of trials with descending coherence and immediate feedback are
% presented. The number of trials is defined in dotInfo.introNumTrial.
%_______________________________________________________________________
%
% Input
%
%    dotInfo | experiment configuration (struct)
% screenInfo | canvas configuration (struct)
%_______________________________________________________________________
%

function exitSession = dotsIntroduction(dotInfo, screenInfo)

  %%
  %% for saving behavioural data
  %%
  introFile = ['dotsX_intro_' dotInfo.subj '_' datestr(now, 'dd-mm-yyyy_HH-MM')];
  introFile = fullfile(dotInfo.dataDir, introFile);

  exitSession = false;
  trialData = struct(); % result structure
  baseDotInfo = dotInfo; % keep original dot info
  sessStartTime = GetSecs;
  count = 0;

  %%
  %% block start
  %%
  for m = 1:numel(dotInfo.introNumTrial)

    % have the subject get ready for the next introduction part
    DrawFormattedText(screenInfo.curWindow, 'ready?', 'center', 'center');
    Screen('Flip', screenInfo.curWindow);
    fprintf('> Introduction %i/%i\n', m, numel(dotInfo.introNumTrial))

    % wait for experimenter to resume session
    while true
      [exitSession, resumeSession] = checkKeys(dotInfo);
      if resumeSession
        % clear the screen
        Screen(screenInfo.curWindow, 'FillRect', screenInfo.bckgnd);
        Screen('Flip', screenInfo.curWindow);
        break
      elseif exitSession
        return
      end
    end

    blockStart = GetSecs;

    %%
    %% trial start
    %%
    for t = 1:dotInfo.introNumTrial(m)

      blockTime = GetSecs - blockStart;
      count = count + 1;
      fprintf('%i: %.2f', count, blockTime)

      [dotInfo] = randomIntroTrial(dotInfo, trialData, count);
      trialData(count).startTime = GetSecs - sessStartTime;
      trialData(count).fixTime = dotInfo.fixTime;
      trialData(count).corDir = find(dotInfo.dirSet == dotInfo.dir);
      trialData(count).coh = dotInfo.coh;
      trialData(count).dotDir = dotInfo.dir; % direction of dots
      trialData(count).rxtime = NaN; % reaction time
      trialData(count).movAccuracy = NaN; % moving average of accuracy
      trialData(count).winSize = NaN; % moving average window size            
      targets = makeDotTargets(screenInfo, dotInfo);
      trialStartTime = GetSecs;
      waitTime = dotInfo.fixTime;

      while true
        % exit wait loop when time delay is met
        if GetSecs - trialStartTime >= waitTime
          break
        end

        % stop experiment if exit key is pressed
        exitSession = checkKeys(dotInfo);
        if exitSession
          fprintf('\n')
          trialData(count) = [];
          return
        end
      end

      % in introduction only show fixation during trials
      showTargets(screenInfo, targets, 1);
      % show moving dots
      screenInfo.rseed = []; % to make different random dots for each trial
      % response: 1 = left, 2 = right
      [~, rseed, start_time, end_time, response, response_time] = dotsX(screenInfo, dotInfo, targets);
      trialData(count).rseed = rseed;
      keyPressed = ~isnan(response{3});
      keyDirection = response{3};

      if keyPressed && keyDirection > 0
        trialData(count).rxtime = response_time - start_time;
        if keyDirection == trialData(count).corDir;
          trialData(count).correct = 1;
          fprintf(' [ok]\n')
        else
          trialData(count).correct = 0;
          fprintf(' [err]\n')
        end
      else % no key was pressed
        trialData(count).correct = 0;
        fprintf(' [-]\n')
      end

      % exit experiment if trial was aborted
      if keyPressed && keyDirection == -1
        exitSession = true;
        return
      end

      if trialData(count).correct 
        trialFeedback = 'correct!';
      else
        trialFeedback = 'wrong';
      end

      % clear the screen and give a visual feedback to the subject
      if keyPressed
        Screen(screenInfo.curWindow, 'FillRect', screenInfo.bckgnd);
        DrawFormattedText(screenInfo.curWindow, trialFeedback, 'center', 'center');
        Screen('Flip', screenInfo.curWindow);
      end
      
    end % trials

    % wait a bit to avoid last feedback from immediately disappearing
    % TODO: this duplicate code should be factored out to a function
    fixStartTime = GetSecs;
    while true
      % exit wait loop when time delay is met
      if GetSecs - fixStartTime >= waitTime
        break
      end

      % stop experiment if exit key is pressed
      exitSession = checkKeys(dotInfo);
      if exitSession
        fprintf('\n')
        return
      end
    end

    % clear the screen
    Screen(screenInfo.curWindow, 'FillRect', screenInfo.bckgnd);
    Screen('Flip', screenInfo.curWindow);

    % wait some more to avoid next block from immediately appearing
    % TODO: this duplicate code should be factored out to a function
    fixStartTime = GetSecs;
    while true
      % exit wait loop when time delay is met
      if GetSecs - fixStartTime >= waitTime
        break
      end

      % stop experiment if exit key is pressed
      exitSession = checkKeys(dotInfo);
      if exitSession
        fprintf('\n')
        return
      end
    end

    dotInfo = baseDotInfo;

    save(introFile, 'trialData', 'dotInfo');

    fprintf('\n')

  end % blocks

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

end
