function [data,expt,aborted] = AfterTouchNoTrial(data,expt,trial)
% I will use this in both the colour and texture trials, irrespective of fg
% shape, so may as well put it all in the same file so that any changes
% only have to be made once.
% This is for experiments where we are using the touchscreen to inidcate
% where the colour was. AfterYesNoTrial.m is the analogous file for trials
% where the child is to use the buttons to answer "yes" or "no".

% Specify key presses which will abort expt:
abort=expt.key_abort;
aborted = 0;
% If the child refuses to respond, the experimenter can press this key to finish the trial:
expterpress=expt.key_touchpad;
% If the cue needs to be repeated, the experiment can press  expt.key_repeatcue to
% have it repeated


% Possible outcomes of this trial:
NORESPONSEYET = 0; % no response yet
ABORTED = 1001; % expt was aborted.
EXPTERPRESSED = 1002; % experimenter moved to next trial.
CHILDTOUCHEDSTIM = 1003; % the child pressed somewhere in the valid area of the screen (either correctly or not).
CHILDTOUCHEDNOBUTTON = 1004; % the child touched the "not present" button.

output{ABORTED} = 'Experiment was aborted';
output{EXPTERPRESSED} = 'Experimenter moved on to next trial';
output{CHILDTOUCHEDSTIM} = 'Child pressed somewhere in stimulus';
output{CHILDTOUCHEDNOBUTTON} = 'Child pressed "not present" button';

jtrial = length(data)+1;

% Before displaying stimulus, check head is back on the headrest,
aborted=CheckHeadRest(expt);

if ~aborted
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % If cue is visual, then first flash up the target:
    if strcmp(expt.cuemode,'Visual')
        DisplayVisualCue(expt,trial);
    end
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Now present the desired experimental stimulus
    DrawStimulus(expt,trial);
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    tflip = GetSecs;
    
    if expt.eyetracking
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % Specify format of IVX data'
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        sendstr = 'ET_FRM "%TS %SX %SY"'
        IVXsend(sendstr,expt.ivx);
        
        % Start recording data on the eye-tracker
        IVXsend('ET_REC',expt.ivx);
        tmp = IVXreceive(expt.ivx);
        
        % Start streaming data from eye-tracker
        IVXsend('ET_STR',expt.ivx);
        % Record image on the screen
        im = Screen('GetImage',expt.PTBwin);
        data(jtrial).eyetracking = [];
    end
    
    if strcmp(expt.cuemode,'Sound')
        % Look up the sound file to play:
        soundfile = [ '..' filesep 'sounds' filesep expt.stimulusnames{trial.tgtcolindex} '.wav'];
        [yy, freq, nbits] = wavread(soundfile);
        auditcue = yy(:,1:expt.soundNchannels)'; % just keep first channel
        
        % Play sound indicating which colour/texture to seek.
        PsychPortAudio('FillBuffer', expt.soundhandle, auditcue);
        PsychPortAudio('Start', expt.soundhandle);
    end
    
    % Also write up target colour on matlab window:
    fprintf('Trial %d: target is %s\n',jtrial,expt.stimulusnames{trial.tgtcolindex});
    
    % Wait for child to release mouse and/or Ablenet buttons (which are mapped to keyboard)
    [x,y,buttons] = GetMouse(expt.screenID);
    [keyisdown,tmp,keycode] = KbCheck;
    keycode(expt.key_headrest)=0;% For this purpose, ignore the headrest key - that is meant to be pressed!
    while any(buttons) || any(keycode) % if already down, wait for release
        [x,y,buttons] = GetMouse(expt.screenID);
        [keyisdown,tmp,keycode] = KbCheck;
        keycode(expt.key_headrest)=0;% For this purpose, ignore the headrest key - that is meant to be pressed!
    end
    keycode = zeros(1,256);
    
    % For sound intervals to repeat cue at:
    t1=tflip;    interval = expt.repeatcueeveryNsecs * (0.9 + 0.2*rand(1));
    x=0;y=0;
    'waiting for child to press screen, or NO button, or for experimenter to press touchpad, or for abort signal'
end % end checking whetehr trial was aborted during CheckHeadRest

% NB the child has to touch somewhere in the visible area of the screen for
% it to be counted as a "present" response, or in the "frowny face" for it
% to be counted as a "not present" response. Touching the blank, upper area
% of the screen is not recognised as a response
NORESPONSEYET = 0; % no response yet
ABORTED = 1001; % expt was aborted.
EXPTERPRESSED = 1002; % experimenter moved to next trial.
CHILDTOUCHEDSTIM = 1003; % the child pressed somewhere in the valid area of the screen (either correctly or not).
CHILDTOUCHEDNOBUTTON = 1004; % the child touched the "not present" button.

output{ABORTED} = 'Experiment was aborted';
output{EXPTERPRESSED} = 'Experimenter moved to next trial before child responded';
output{CHILDTOUCHEDSTIM} = 'Child touched somewhere in the stimulus area';
output{CHILDTOUCHEDNOBUTTON} = 'Child touched the "target not present" button';

% Read in sound file ready to say "thank you"
[yy, Fs, nbits] = wavread(['..' filesep 'sounds' filesep 'thankyou.wav']);
thankyou = yy(:,1:expt.soundNchannels)';

if aborted % If the experiment was aborted during CheckHeadRest
    responsetype=ABORTED;
else
    responsetype = NORESPONSEYET;
end
while (responsetype== NORESPONSEYET);
    [x,y,buttons] = GetMouse(expt.screenID);
    [a,b,keycode] = KbCheck;
    
    % Repeat cue if necessary:
    % Sound cue is repeated at intervals or when experimenter presses the
    % repeat button:
    if strcmp(expt.cuemode,'Sound') ...
            && ( (GetSecs-t1>interval) || any(keycode(expt.key_repeatcue)) )
        status=PsychPortAudio('GetStatus',expt.soundhandle);
        % Only repeat the cue if we are not already playing a sound;
        if ~status.Active
            PsychPortAudio('Start', expt.soundhandle);
            t1=GetSecs;
            interval = expt.repeatcueeveryNsecs * (0.8 + 0.4*rand(1));
        end        
    end
    % Visual cue is repeated only when experimenter presses the repeat button:
    if strcmp(expt.cuemode,'Visual') && any(keycode(expt.key_repeatcue))
        DisplayVisualCue(expt,trial);
        DrawStimulus(expt,trial);
    end
    
    % Test to see if a valid response (or abort) was obtained.
    % 1. Did they abort?
    if any(keycode(abort))
        % Experimenter aborted
        responsetype = ABORTED;
    end
    if any(keycode(expterpress))
        responsetype = EXPTERPRESSED;
    end
    if any(keycode(expt.key_nobutton))
        responsetype = CHILDTOUCHEDNOBUTTON;
    end
    if buttons(1) % left button = touchscreen, at location (x,y)
        fprintf('screen touched at (x,y) = (%d, %d)',x,y)
        % So, screen was touched somewhere - figure out if it was in the
        % valid stimulus:
        if (x>=expt.visstimscreenrect(1) && x<=expt.visstimscreenrect(3) && y>=expt.visstimscreenrect(2) && y<=expt.visstimscreenrect(4))
            responsetype =  CHILDTOUCHEDSTIM;
            % or maybe it was in the "not present" image?
        elseif (x>=expt.nobuttonrect(1) && x<=expt.nobuttonrect(3) && y>=expt.nobuttonrect(2) && y<=expt.nobuttonrect(4))
            responsetype = CHILDTOUCHEDNOBUTTON;
        end
    end
    
end
tpress=GetSecs;
output{responsetype}


if expt.eyetracking
    % Stop streaming data from eye-tracker
    IVXsend('ET_EST',expt.ivx);
    tmp = IVXreceive(expt.ivx);
    % Stop recording
    IVXsend('ET_STP',expt.ivx);
    tmp = IVXreceive(expt.ivx);
    
    % Save the data that was recorded
    [tmp,IVXfilename,tmp] = fileparts(expt.filename);
    IVXfilename = sprintf('data\\%s_%d.idf',IVXfilename,jtrial);
    sendstr = ['ET_SAV ' IVXfilename]
    IVXsend(sendstr,expt.ivx);
    tmp=IVXreceive(expt.ivx)
end

if  responsetype == ABORTED;
    % Remove this trial's data from the array
    data = data(1:(jtrial-1));
    aborted=1;
    return
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% KEY EVENT: A RESPONSE HAS BEEN MADE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now we go through and analyse what has happened.

data(jtrial).target = expt.stimulusnames{trial.tgtcolindex};
data(jtrial).tgtpresent = trial.tgtpresent;
data(jtrial).responsetype = output{responsetype};

tuntil = GetSecs + expt.timetoleaveupafteranswer;
if responsetype ~= EXPTERPRESSED;
    % If the child responded (i.e. not that the experimenter terminated the
    % trial), acknowledge the response by saying "thank you":
    % Fill the audio playback buffer with the audio data:
    PsychPortAudio('FillBuffer', expt.soundhandle, thankyou);
    % Start playback
    PsychPortAudio('Start', expt.soundhandle);
    
    data(jtrial).touch_xpix = x;
    data(jtrial).touch_ypix = y;
    
    % The child responded by pressing the stimulus region of the screen: display an animation at the
    % point where they pressed.
    tgtsize=100; % animation is in a 100x100 window
    rect = [ x-tgtsize/2 y-tgtsize/2 x+tgtsize/2 y+tgtsize/2];
    tgtsize=120; % animation is in a 100x100 window
    bigrect = [ x-tgtsize/2 y-tgtsize/2 x+tgtsize/2 y+tgtsize/2];
    % Read off what is already on the screen at this pont:
    stim = Screen('GetImage', expt.PTBwin,bigrect );
    savestim = Screen('MakeTexture',expt.PTBwin,stim);
    
    % Leave the stimulus up, with the animation playing, until the allotted time has elapsed:
    jframe=1;
    status=PsychPortAudio('GetStatus',expt.soundhandle);
    tuntil = GetSecs + expt.timetoleaveupafteranswer; % in case this all took a while
    while status.Active || (GetSecs < tuntil)
        % Redraw old stim
        Screen('DrawTexture', expt.PTBwin, savestim,[],bigrect);
        % Draw the next frame of the clown, tilting it a little bit back and forth as well:
        Screen('DrawTexture', expt.PTBwin, expt.animtex(jframe),[],rect,10*sind(360*jframe/6));
        jframe = jframe+1; if jframe>length(expt.animtex); jframe=1;end
        % Update display:
        Screen('Flip', expt.PTBwin,0,1);
        WaitSecs(0.05);
        status=PsychPortAudio('GetStatus',expt.soundhandle);
    end;
    Screen('Close',savestim)
    
end

timeofnexttrial = tuntil + expt.intertrialinterval;

% Display the inter-trial image, if provided, or blank the screen
Screen('FillRect', expt.PTBwin , expt.blankcol );
if isfield(expt,'intertrialtex')
    screenrect = Screen('Rect',expt.PTBwin);
    Screen('DrawTexture', expt.PTBwin, expt.intertrialtex);
end
Screen('Flip', expt.PTBwin);

if strcmp(expt.ExptType,'Squares')
    % then we are in the main FG/BG expt, and will need to know the index
    % of the background position:
    bgpos = expt.nFG+1;
end
% Did the experimenter press their button to terminate the trial, or
% did the child touch the screen?
if responsetype == EXPTERPRESSED;
    'Experimenter terminated trial'
    x = NaN;
    y = NaN;
    data(jtrial).iscorrect = 0;
    data(jtrial).pressed = 'Child did not respond; experimenter moved on.';
    jpospressed=NaN;
    data(jtrial).touch_xpix = NaN;
    data(jtrial).touch_ypix = NaN;
elseif  responsetype == CHILDTOUCHEDNOBUTTON;
    % The child pressed the "target not present" button
    jpospressed=NaN;
    data(jtrial).pressed='"target absent" button';
    data(jtrial).touch_xpix = NaN;
    data(jtrial).touch_ypix = NaN;
    if data(jtrial).tgtpresent % tgt was present
        data(jtrial).iscorrect = 0;
        data(jtrial).responsetype = 'miss';
    else % tgt was absent
        data(jtrial).iscorrect = 1; % they correctly answered that the tgt was absent
        data(jtrial).responsetype = 'correct rejection';
    end
    
elseif  responsetype == CHILDTOUCHEDSTIM;
    % The child touched somewhere on the touchscreen
    if data(jtrial).tgtpresent==0 % tgt was absent, so this was a wrong response
        data(jtrial).iscorrect = 0; % they correctly answered that the tgt was absent
        data(jtrial).responsetype = 'false alarm';
    end
    
    % Figure out where on the screen they pressed:
    switch expt.ExptType
        case 'Squares'
            % See if they clicked inside a square:
            insquare = (abs(x-expt.sqxcens)<=expt.sqside/2 & abs(y-expt.sqycens)<=expt.sqside/2);
            % Find which square, if any, they pressed:
            jpospressed = find(insquare==1);
            if isempty(jpospressed)
                % if they didn't press a square, but the expter didn't terminate the trial, they must have pressed the background
                jpospressed = bgpos;
                data(jtrial).touch_object = 'Background';
            else
                data(jtrial).touch_object = sprintf('Square position %1d',jpospressed);
            end
            
        case 'Patchwork'
            % The child did touch the screen
            % Figure out where on the screen they pressed:
            jpospressed = NaN;
            data(jtrial).touch_object = 'None';
            for jsq=1:length(expt.squarepos)
                if expt.squarepos{jsq}(1)<x && x<expt.squarepos{jsq}(3) && expt.squarepos{jsq}(2)<y && y<expt.squarepos{jsq}(4)
                    jpospressed=jsq;
                    data(jtrial).touch_object = sprintf('Patch position %1d',jpospressed);
                end
            end
            
        case 'singletarget'
            % The child did touch the screen
            % Figure out whether they touched the single target or not:
            if trial.squarepos(1)<x && x<trial.squarepos(3) && trial.squarepos(2)<y && y<trial.squarepos(4)
                data(jtrial).touch_object = 'successfully touched target';
                data(jtrial).pressed = expt.stimulusnames{trial.tgtcolindex};
                data(jtrial).iscorrect = 1;
            else
                data(jtrial).touch_object = 'missed target';
                data(jtrial).iscorrect = 0;
                data(jtrial).pressed = 'blank background';
            end
    end
    
else
    'Should never get to here - some error in AfterTouchNoTrial!'
    stop
end

if sum(strcmp(expt.ExptType,{'Patchwork' 'Squares'})) && ~isnan(jpospressed)
    % Then the stimulus contained a variety of colours; Find the index of the colour they pressed:
    pressedcolindex = trial.colindices(jpospressed);
    data(jtrial).pressed = expt.stimulusnames{pressedcolindex};
    % and record whether this was correct
    if pressedcolindex==trial.tgtcolindex
        data(jtrial).iscorrect = 1;
        data(jtrial).responsetype = 'hit';
    else
        data(jtrial).iscorrect = 0;
        if trial.tgtpresent
            data(jtrial).responsetype = 'wrong location'; % the target was present but they hit the screen in the wrong location - could have been a mis-press
        end
        % if the target was absent, response type should already have been
        % set to "false alarm"
    end
    data(jtrial).touch_posindex = jpospressed;
end

data(jtrial).reactiontime = tpress-tflip;
data(jtrial).t_stimonset = tflip;
data(jtrial).t_screenpress = tpress;

% Data fields specific to main experiment, with foreground and background:
if strcmp(expt.ExptType,'Squares') 
    if trial.tgtposindex<bgpos
        data(jtrial).istgtinFG = 1;
    else
        data(jtrial).istgtinFG = 0;
    end
    data(jtrial).foreground = {expt.stimulusnames{trial.colindices(1:expt.nFG)}} ;
    data(jtrial).background = expt.stimulusnames{trial.colindices(end)};
elseif strcmp(expt.ExptType,'Patchwork')
    data(jtrial).patches = {expt.stimulusnames{trial.colindices}};
end
data(jtrial)


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Look at eye tracking data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if expt.eyetracking
    data(jtrial) = GazeData(expt,im,data(jtrial),jtrial,trial);     
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
save(expt.filename,'expt','data');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Wait any remaining time before initiating next trial
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while GetSecs<timeofnexttrial && ~any(keycode(abort))
    [a,b,keycode] = KbCheck;
end
if any(keycode(abort))
    aborted = 1;
end