function WaitScanner(keyOption)

%	function WaitScanner([keyOption])
%
%	WaitScanner is part of the VVRC Matlab interface to PST's system for
%	functional MRI.  WaitScanner polls the scanner sync. bit until it
%	goes high, then it exits, returning control to the calling script.  
%   Use it to synchronize the onset of your stimulus display with the
%	onset of an MRI scan.
%
%   If the optional KeyOption argument is true then waitScanner returns
%   when either a keyboard key is pressed, or when the scanner sync. 
%   bit goes high.
%   
%
%	Be sure to call the InitializeFMRI function once before using  
%	GetButtons. 
%
%	See Also: % See Also: KbName, InitializeFMRI, WaitScanner, GetButtons, ButtonName.
%
%	9/2/99 awi wrote it.
%   2/2/00 awi updated see also.

global GLOBAL_NI_DIO_SLOT_NUMBER;

if (nargin == 0)
	keyOption = 0;
end %if

gVariables = who('global');
if ~ismember('GLOBAL_NI_DIO_SLOT_NUMBER', gVariables);
	error('call function InitializeFMRI before using GetButtons');
end %if
if isempty(GLOBAL_NI_DIO_SLOT_NUMBER);
	error('call function InitializeFMRI before using GetButtons');
end 

if all('sim' == GLOBAL_NI_DIO_SLOT_NUMBER) %simulate scanner start with a keypress
	getChar;
else
	exitFunc = 1;
	exitFuncKey = 0;
	while exitFunc
		if keyOption
			exitFuncKey = kbCheck;
		end %if
		exitFuncSync = bitand(DIG_In_Port(GLOBAL_NI_DIO_SLOT_NUMBER, 1),128);
		exitFunc = ~(exitFuncKey | exitFuncSync);
	end %while
end %else

