function [button,varargout] = RESPONSEPixx_GetLastButtonPressed
% Reads all button-presses currently in RESPONSEPixx buffer (since last
% flush or read). Ignore button releases; return the identity of the last
% button pressed. If no button has been pressed, this returns an empty variable.
% Calling this function wipes the buffer, so if you call it twice in a row,
% the second time will be empty.
% The optional second argument gives the time at which the button-press was
% made, in "Datapixx units". If you want this in seconds since stimulus
% onset, for example, then you need to do something like
% Datapixx('RegWrRd');t0=Datapixx('GetTime')
% [button,t1] = RESPONSEPixx_GetLastButtonPressed;
% reactiontime = t1-t0;
%
% NB This function assumes DATAPixx is Open and generally initialised
% correctly.
%
% Jenny Read, July 2010

% Define user-friendly variable names:
RESPONSEPixxCodes

Datapixx('RegWrRd');
buttonLogStatus = Datapixx('GetDinStatus');
button = []; % Default is to return empty. Now see if any buttons have been pressed.
timepressed = [];

% Every time a button is pressed, buttonLogStatus.newLogFrames goes up
% by two, once for button-press onset, once for offset.
if (buttonLogStatus.newLogFrames > 0)
    [buttonpresses timestamps] = Datapixx('ReadDinLog');
   % Remove button release events; I only want presses
   jkeep=[buttonpresses~=RPix_ButtonRelease];
   buttonpresses = buttonpresses(jkeep);
   timestamps = timestamps(jkeep);
   if ~isempty(buttonpresses)
       % Only record last press (i.e., user can change their mind)
       button = buttonpresses(end);
	   timepressed = timestamps(end);
   end
end
if nargout==2
	varargout{1}=timepressed;
end
     
