%_______________________________________________________________________
%
% Run random dot motion experiment defined in createDotInfo
%_______________________________________________________________________
%
% Input
%
% dotInfo | experiment configuration (struct)
%    subj | identifier of subject (string)
% condSet | conditions (cell array of strings)
%_______________________________________________________________________
%
function MAT_practice_170328(dotInfo, subj, test, 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(exist('condSet','var'))
%     error('Missing input: condSet')
%   elseif not(isempty(condSet)) && iscellstr(condSet) && min(cellfun(@length, condSet)) > 0
%     dotInfo.condSet = condSet;
%   else
%     error('Invalid input: condSet (requires cell array of non-empty strings)')
%   end

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

  %%
  %% for saving behavioural data
  %%
  sessionFile = ['dotsX_behav_' subj '_' datestr(now, 'dd-mm-yyyy_HH-MM')];
  sessionFile = [dotInfo.dataDir, sessionFile, '_PRACTICE.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

    % show intro only if not in debug mode
    if isfield(dotInfo, 'introNumTrial') &&  test == 1
      exitSession = dotsIntroduction(dotInfo, screenInfo);
    else
      exitSession = false;
    end

    if exitSession
      closeExperiment;
      return
    end

    sessStartTime = GetSecs;

    ResultMat = NaN(dotInfo.totalTrials,4);
    
    ExperimentProtocol = cell(0);

    ExperimentProtocol = [ExperimentProtocol; {'SessionOnset'}, {sessStartTime}, {[]}, {[]}, {[]},{NaN}];

    %% Intro slide

    DrawFormattedText(screenInfo.curWindow, '\nWillkommen bei der Multi-Attribut Aufgabe\n\nIm folgenden werden Sie Punktewolken sehen, die verschiedene Charakteristika aufweisen: \n\n Bewegungsrichtung \n Helligkeit \n Größe \n Farbe \n\n Im Folgenden sehen Sie ein (längeres) Beispiel', '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
    
    %% Show first 5 second example
    
    dotInfo.durCue = 0; % duration of cue
    dotInfo.durPres = 5; % duration of presentation
    dotInfo.durResp = 0; % duration of question
    
    dotInfo.MAT.percAtt1 = .65;
    dotInfo.MAT.percAtt2 =  1-dotInfo.MAT.percAtt1; % For each attribute, the relative amount of dots for each attribute option is the same.
    dotInfo.MAT.color = [255 255 255; 255 215 0]; % define dot color
    dotInfo.MAT.coherence = 1;  % define dot movement (coherence) [useless now!]
    dotInfo.MAT.direction = [180 0]; % left and right
    dotInfo.MAT.size = [5 8]; % define dot size
    dotInfo.MAT.luminance = [.4 .8]; % define dot luminance
    dotInfo.MAT.attNames = {'color'; 'direction'; 'size'; 'luminance'};
    
    TrialInitiation = GetSecs;
    ExperimentProtocol = [ExperimentProtocol; {'TrialInitiation'}, {TrialInitiation}, {[]}, {[]}, {[]}, {0}];
    % create fixation
    targets = makeDotTargets(screenInfo, dotInfo); % initialize targets
    showTargets(screenInfo, targets, 1);
    [~, dotInfo, ExperimentProtocol,ResultMat] = dotsX_JQK_MAT_170327(screenInfo, dotInfo, targets, 1, ExperimentProtocol,ResultMat);              

    %% Instruction
    
    DrawFormattedText(screenInfo.curWindow, 'Nun sehen Sie die Attribute einzeln und in der späteren Anzeigedauer. \n Bitte geben Sie an, von welcher der beiden Optionen mehr vorhanden ist.', 'center', 'center');
    Screen('Flip', screenInfo.curWindow);

    pause(1);
    
    % wait for experimenter to resume session
    while true
    [exitSession, resumeSession] = checkKeys(dotInfo);
    if resumeSession
      break
    elseif exitSession
      closeExperiment;
      return
    end
    end
    
    %% Instruction
    
    DrawFormattedText(screenInfo.curWindow, 'Wir beginnen mit der Farbe. \n\n Falls die weißen Punkte dominieren, drücken Sie die linke Taste. \n Falls die goldenen Punkte dominieren, dücken Sie die rechte Taste. \n\n Im Anschluss an Ihre Antwort erhalten Sie eine Rückmeldung.', 'center', 'center');
    Screen('Flip', screenInfo.curWindow);

    pause(1);
    
    % wait for experimenter to resume session
    while true
    [exitSession, resumeSession] = checkKeys(dotInfo);
    if resumeSession
      break
    elseif exitSession
      closeExperiment;
      return
    end
    end
    
    %% 1st dimension
    
    dotInfo = createDotInfo_TEST_Dim1_170327; dotInfo.deployed = true;
    dotInfo.feedback = 1;
    for indTrial = 1:dotInfo.totalTrials
        TrialInitiation = GetSecs;
        ExperimentProtocol = [ExperimentProtocol; {'TrialInitiation'}, {TrialInitiation}, {[]}, {[]}, {[]}, {1}];
        % create fixation
        targets = makeDotTargets(screenInfo, dotInfo); % initialize targets
        showTargets(screenInfo, targets, 1);
        [~, dotInfo, ExperimentProtocol,ResultMat] = dotsX_JQK_MAT_170327(screenInfo, dotInfo, targets, indTrial, ExperimentProtocol,ResultMat);              
    end
    
    Results{1,1} = dotInfo;
    Results{2,1} = ExperimentProtocol;
    Results{3,1} = ResultMat;
    
    %% Instruction
    
    DrawFormattedText(screenInfo.curWindow, 'Als nächstes die Bewegungsrichtung. \n\n Falls die Bewegung nach links dominiert, drücken Sie die linke Taste. \n Falls die Bewegung nach rechts dominiert, dücken Sie die rechte Taste.', 'center', 'center', [255 255 255]);
    Screen('Flip', screenInfo.curWindow);

    pause(1);
    
    % wait for experimenter to resume session
    while true
    [exitSession, resumeSession] = checkKeys(dotInfo);
    if resumeSession
      break
    elseif exitSession
      closeExperiment;
      return
    end
    end
    
    %% 2nd dimension
    
    dotInfo = createDotInfo_TEST_Dim2_170327; dotInfo.deployed = true;
    dotInfo.feedback = 1;
    for indTrial = 1:dotInfo.totalTrials
        TrialInitiation = GetSecs;
        ExperimentProtocol = [ExperimentProtocol; {'TrialInitiation'}, {TrialInitiation}, {[]}, {[]}, {[]}, {2}];
        % create fixation
        targets = makeDotTargets(screenInfo, dotInfo); % initialize targets
        showTargets(screenInfo, targets, 1);
        [~, dotInfo, ExperimentProtocol,ResultMat] = dotsX_JQK_MAT_170327(screenInfo, dotInfo, targets, indTrial, ExperimentProtocol,ResultMat);              
    end
    
    Results{1,2} = dotInfo;
    Results{2,2} = ExperimentProtocol;
    Results{3,2} = ResultMat;
    
    %% Instruction
    
    DrawFormattedText(screenInfo.curWindow, 'Als nächstes die Punktgröße. \n\n Falls die kleineren Punkte dominieren, drücken Sie die linke Taste. \n Falls die größeren Punkte dominieren, dücken Sie die rechte Taste.', 'center', 'center', [255 255 255]);
    Screen('Flip', screenInfo.curWindow);

    pause(1);
    
    % wait for experimenter to resume session
    while true
    [exitSession, resumeSession] = checkKeys(dotInfo);
    if resumeSession
      break
    elseif exitSession
      closeExperiment;
      return
    end
    end
    
    %% 3rd dimension
    
    dotInfo = createDotInfo_TEST_Dim3_170327; dotInfo.deployed = true;
    dotInfo.feedback = 1;
    for indTrial = 1:dotInfo.totalTrials
        TrialInitiation = GetSecs;
        ExperimentProtocol = [ExperimentProtocol; {'TrialInitiation'}, {TrialInitiation}, {[]}, {[]}, {[]}, {3}];
        % create fixation
        targets = makeDotTargets(screenInfo, dotInfo); % initialize targets
        showTargets(screenInfo, targets, 1);
        [~, dotInfo, ExperimentProtocol,ResultMat] = dotsX_JQK_MAT_170327(screenInfo, dotInfo, targets, indTrial, ExperimentProtocol,ResultMat);              
    end
    
    Results{1,3} = dotInfo;
    Results{2,3} = ExperimentProtocol;
    Results{3,3} = ResultMat;
    
    %% Instruction
    
    DrawFormattedText(screenInfo.curWindow, 'Als letztes die Punkthelligkeit. \n\n Falls die dunkleren Punkte dominieren, drücken Sie die linke Taste. \n Falls die helleren Punkte dominieren, dücken Sie die rechte Taste.', 'center', 'center', [255 255 255]);
    Screen('Flip', screenInfo.curWindow);

    pause(1);
    
    % wait for experimenter to resume session
    while true
    [exitSession, resumeSession] = checkKeys(dotInfo);
    if resumeSession
      break
    elseif exitSession
      closeExperiment;
      return
    end
    end
    
     %% 4th dimension
    
    dotInfo = createDotInfo_TEST_Dim4_170327; dotInfo.deployed = true;
    dotInfo.feedback = 1;
    for indTrial = 1:dotInfo.totalTrials
        TrialInitiation = GetSecs;
        ExperimentProtocol = [ExperimentProtocol; {'TrialInitiation'}, {TrialInitiation}, {[]}, {[]}, {[]}, {4}];
        % create fixation
        targets = makeDotTargets(screenInfo, dotInfo); % initialize targets
        showTargets(screenInfo, targets, 1);
        [~, dotInfo, ExperimentProtocol,ResultMat] = dotsX_JQK_MAT_170327(screenInfo, dotInfo, targets, indTrial, ExperimentProtocol,ResultMat);              
    end
    
    Results{1,4} = dotInfo;
    Results{2,4} = ExperimentProtocol;
    Results{3,4} = ResultMat;
    
    %% Instruction
    
    DrawFormattedText(screenInfo.curWindow, 'Nun kennen Sie alle Attribute. \n  Diese werden Ihnen im Folgenden gemeinsam präsentiert. \n Bitte geben Sie wie oben immer an, welche der beiden Optionen eines Attributs den Eindruck dominiert. \n Das gewünschte Attribut wird Ihnen dabei nach der Präsentation präsentiert.', 'center', 'center', [255 255 255]);
    Screen('Flip', screenInfo.curWindow);

    pause(1);
    
    % wait for experimenter to resume session
    while true
    [exitSession, resumeSession] = checkKeys(dotInfo);
    if resumeSession
      break
    elseif exitSession
      closeExperiment;
      return
    end
    end
    
    %% realistic without cue
    
    dotInfo = createDotInfo_JQK_170327; dotInfo.deployed = true;
    dotInfo.totalTrials = 10;
    dotInfo.durCue = 0; % duration of cue
    dotInfo.feedback = 1;

    for indTrial = 1:dotInfo.totalTrials
        TrialInitiation = GetSecs;
        ExperimentProtocol = [ExperimentProtocol; {'TrialInitiation'}, {TrialInitiation}, {[]}, {[]}, {[]}, {5}];
        % create fixation
        targets = makeDotTargets(screenInfo, dotInfo); % initialize targets
        showTargets(screenInfo, targets, 1);
        [~, dotInfo, ExperimentProtocol,ResultMat] = dotsX_JQK_MAT_170327(screenInfo, dotInfo, targets, indTrial, ExperimentProtocol,ResultMat);              
    end
    
    Results{1,5} = dotInfo;
    Results{2,5} = ExperimentProtocol;
    Results{3,5} = ResultMat;
    
    %% Instruction
    
    DrawFormattedText(screenInfo.curWindow, 'Während mancher Trials werden Sie vorher erfahren, welches Attribut abgefragt wird. \n Falls ein "?" erscheint, kann jedes Attribut abgefragt werden. \n Sie werden nun nicht mehr erfahren, ob Ihre Antworten korrekt waren.', 'center', 'center', [255 255 255]);
    Screen('Flip', screenInfo.curWindow);

    pause(1);
    
    % wait for experimenter to resume session
    while true
    [exitSession, resumeSession] = checkKeys(dotInfo);
    if resumeSession
      break
    elseif exitSession
      closeExperiment;
      return
    end
    end
    
    %% realistic with cue
    
    dotInfo = createDotInfo_JQK_170327; dotInfo.deployed = true;
    dotInfo.totalTrials = 10;

    for indTrial = 1:dotInfo.totalTrials
        TrialInitiation = GetSecs;
        ExperimentProtocol = [ExperimentProtocol; {'TrialInitiation'}, {TrialInitiation}, {[]}, {[]}, {[]}, {6}];
        % create fixation
        targets = makeDotTargets(screenInfo, dotInfo); % initialize targets
        showTargets(screenInfo, targets, 1);
        [~, dotInfo, ExperimentProtocol,ResultMat] = dotsX_JQK_MAT_170327(screenInfo, dotInfo, targets, indTrial, ExperimentProtocol,ResultMat);              
    end
    
    Results{1,6} = dotInfo;
    Results{2,6} = ExperimentProtocol;
    Results{3,6} = ResultMat;
    
    save(sessionFile, 'Results');
    
    %% inform the subject that the experiment is over
    
    DrawFormattedText(screenInfo.curWindow, 'Sie haben das Training erfolgreich beendet!', 'center', 'center', [255 255 255]);
    Screen('Flip', screenInfo.curWindow);

    pause(1);
    
    % 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
  end

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

end
