%_______________________________________________________________________
%
% dotInfo = randomDotTrial(dotInfo, trialData)
%_______________________________________________________________________
%
% Generates the configuration for next trial
%_______________________________________________________________________
%
% Input
%
%   dotInfo | experiment configuration (struct)
% trialData | results of the session (struct)
%_______________________________________________________________________
%
% Output
%
%   dotInfo | experiment configuration (struct)
%_______________________________________________________________________
%
function dotInfo = randomDotTrial(dotInfo, trialData)

  % adjust coherence if accuracy is off target
  if not(isnan(dotInfo.movAccuracy)) && not(dotInfo.movAccuracy == dotInfo.targetAcc) && dotInfo.subjResponded
    dotInfo = updateCohMobs(dotInfo);
  end 
  
  % choose random direction
  dotInfo.dir = dotInfo.dirSet(ceil(rand*length(dotInfo.dirSet)));

  % limit number of consecutive trials with dots in same direction to three
  % caveat: current implementation only works for two directions
  if numel(trialData) > 2
    dir1 = trialData(end).dotDir;
    dir2 = trialData(end-1).dotDir;
    dir3 = trialData(end-2).dotDir;
    threeSameDir = all(dotInfo.dir == [dir1 dir2 dir3]);
    if threeSameDir
      otherDir = not(dotInfo.dirSet == dotInfo.dir);
      dotInfo.dir = dotInfo.dirSet(otherDir);
    end
  end

  % generate random fixation duration
  fixMin = dotInfo.fixMinTime; % minimum fixation
  fixMax = dotInfo.fixMaxTime; % maximum fixation 
  dotInfo.fixTime = (fixMax - fixMin) * rand + fixMin;

end

% update coherence using the MOBS heuristic
function dotInfo = updateCohMobs(dotInfo)

  % short-term accuracy for increasing/decreasing coherence
  if dotInfo.movAccuracy < dotInfo.targetAcc
    dotInfo.resp = 'no';
  else
    dotInfo.resp = 'yes';
  end

  % stable mid-term accuracy for deciding about regressions
  if not(isnan(dotInfo.longMovAccuracy))
    if dotInfo.longMovAccuracy < dotInfo.targetAcc
      dotInfo.longResp = 'no';
    else
      dotInfo.longResp = 'yes';
    end
  else
    dotInfo.longResp = '';
  end

  % ignore long-term accuracy if it contradicts short-term accuracy
  if not(strcmp(dotInfo.resp, dotInfo.longResp))
    dotInfo.longResp = '';
  end

  dotInfo = mobs(dotInfo);

end
