%_______________________________________________________________________
%
% Allow the experimenter to advance or exit the presentation
%_______________________________________________________________________
%
% In testing or development mode the presentation can be advanced by
% pressing dotInfo.keyReturn and exited by pressing dotInfo.keyEscape.
% In deployed mode the keys must be pressed in combination with a
% modifier stored in dotInfo.keyModifier to prevent accidental key presses
% of the subject advancing or exiting the experiment.
%_______________________________________________________________________
%
% Input
%
% dotInfo | experiment configuration generated by createDotInfo (struct)
%_______________________________________________________________________
%
% Output
%
%   exitKeyPressed | dotInfo.keyEscape was pressed (logical)
% resumeKeyPressed | dotInfo.keyReturn was pressed (logical)
%        keyIsDown | if any key, including modifiers is down (logical)
%             secs | time of keypress as returned by GetSecs (numeric)
%          keyCode | represents the pressed keys (array of logicals)
%_______________________________________________________________________
%
function [exitKeyPressed, resumeKeyPressed, keyIsDown, secs, keyCode] = checkKeys(dotInfo);

  resumeKeyPressed = false;
  exitKeyPressed = false;
  deployed = dotInfo.deployed;
  [keyIsDown, secs, keyCode] = KbCheck;

  %%
  %% Key codes for german/swiss-german(?) keyboard on Windows
  %% LeftAlt = [18 164]
  %% AltGr = [17 18 162 165]
  %% LeftControl  = [17 162]
  %% RightControl = [17 163]
  %%
  %% Key codes for german/swiss-german(?) keyboard on OS X
  %% LeftCmd = [227]
  %% RightCmd = [231]
  %%
  %% On Windows Psychtoolbox returns two key codes for modifier keys.
  %% For the left control key it returns 17 which is the generic key
  %% code for control key and also 162 which the key code specific
  %% for the left control key.
  %%
  %% On OS X Psychtoolbox returns a single key code for modifier keys.
  %%
  %% As a workaround for this inconsistency we remove the generic
  %% modifier key codes for shift (16), alt (17) and control (18).
  %%
  if ispc
    keyCodeGenMod = [16 17 18];
    keyCode(keyCodeGenMod) = 0;
    % if we had integer key codes, but kbcheck returns a binary key code
    % keyCode = keyCode(not(ismember(keyCode,keyCodeGenMod)));
  end

  if keyIsDown
    
    if deployed
      keyModIsDown = any(keyCode(dotInfo.keyModifier));
    else
      keyModIsDown = true;
    end
    
    if any(keyCode(dotInfo.keyReturn))
      resumeKeyPressed = true;
    end
    
    if keyModIsDown && keyCode(dotInfo.keyEscape)
      exitKeyPressed = true;
    end
    
  end
  
end
