function [button] = readButtonbox( address, timeout )
%
% Scan Buttonbox connected to the LPT Status port specified by 'address'
% and wait until a 'button' is pressed (i.e., grounded).
%
% Returns with number of the button that was pressed or
% ZERO if no button within the number of msec specified by 'timeout'
%
%   Button-1 == Status-bit #4 == pin 15
%   Button-2 == Status-bit #5 == pin 13
%   Button-3 == Status-bit #6 == pin 12
%   Button-4 == Status-bit #7 == pin 10
%   Button-5 == Status-bit #8 == pin 11 (Inverted)
%
%dependencies: Cogent 2000 time() functiom
%              io32() port I/O extension must be active

%verify that io32() has been properly installed
global cogent;
if (cogent.io.status ~= 0)
    button = -1; %error exit
    return;
end

%initialize timeout threshold
timeout = time + timeout;

%scan buttonbox
button = 0; %default = no button pressed
loop = 1;
while( loop > 0 )
    %read specified input port (and convert to 8-bit integer format)
    response = uint8( inp(address) );
    %check for button #1
    if( bitget(response,4) == 0 )
        button = 1;
        loop = 0;
    end
    %check for button #2
    if( bitget(response,5) == 0 )
        button = 2;
        loop = 0;
    end
    %check for button #3
    if( bitget(response,6) == 0 )
        button = 3;
        loop = 0;
    end
    %check for button #4
    if( bitget(response,7) == 0 )
        button = 4;
        loop = 0;
    end
    %check for button #5 (inverted input logic; ground == 1)
    if( bitget(response,8) == 1 )
        button = 5;
        loop = 0;
    end
  
    %check for timeout condition
    if( time > timeout )
        loop = 0;
    end
end
