function countDown2(display,startSecs,startScan,white,black,grey)
% function countDown2(display,startSecs,startScan,white,black,grey)
%
% startSecs is the (integer) number of seconds for the entire countdown sequence
% startScan is the (real) number of seconds remaining in the countdown when scanner
%   is to be started
%
% Purpose:  Counts down from secs to 1,
%           displaying the numbers on the
%           screen above the fixation point.
%
% Original author unknown
% 6/2/99 David Ress & Ben Backus: replaced timing loop with a time-based
%   loop instead of integer countdown, to allow use of real-valued scanner
%   starting times.
% 6/13/02 Rory Sayres: modified to work on its own, as countdown2.m.


if ~exist('startScan', 'var')
	startScan = -1;
end
if nargin < 6
	grey = 127;
	if nargin < 5
		black = 10;
		if nargin < 4
			white = 254;
		end
	end
end

loc = display.rect([3,4])/2;
win = display.windowPtr;
X = display.rect(3); Y = display.rect(4);
screen(win,'FillRect',grey);

% Loop to display countdown and start scanner
startSecs = round(startSecs);    % Force to integer
endTime = startSecs + getSecs;   % Time at which to end the countdown
scanStarted = 0;
currentDisplayNumber = startSecs;
timeRemaining = startSecs;
while timeRemaining > 0
	
	% Check whether to start scanner	
	if ~scanStarted
		if timeRemaining <= startScan
			trigScan;
% 			StartScan;
% 			dispStringInCenter(display,'Start Scan',0.6,'white');
% 			screen(win,'drawText','Start Scan',0.45*X,0.6*Y,black);
			scanStarted = 1;
		end
	end

	% Update countdown number, if it's time to do so
	if ceil(timeRemaining) <= currentDisplayNumber
% 		dispStringInCenter(display,num2str(currentDisplayNumber+1),0.5,'background');
% 		dispStringInCenter(display,num2str(currentDisplayNumber),0.5,'white');
		screen(win,'FillRect',grey,centerrect([0 0 80 80],display.rect));
		screen(win,'drawText',num2str(currentDisplayNumber),X/2,Y/2,white);
		currentDisplayNumber = currentDisplayNumber-1;
	end

	timeRemaining =  endTime - getSecs;
	
end


% Remove displayed elements
screen(win,'FillRect',grey);
SCREEN(display.windowPtr,'TextSize',12);
