function countDown(win,startSecs,startScan,white,grey);
% countDown(win,startSecs,[startScan,white,grey])
%
% win: pointer to the window on which you want to show the countdown.
% startSecs: (integer) number of seconds for the entire countdown sequence
% startScan: (integer) number of seconds remaining in the countdown when scanner
%   is to be started (optional; default = -1, don't trigger to start).
% white: (integer) value in lookup table for text (default = 225).
% grey: (integer) value in lookup table for background (default = 127).
%
%
% 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 ~exist('white', 'var')		white = 225; 	end
if ~exist('black', 'var')		black = 0; 	end
if ~exist('grey', 'var')		grey = 128; 	end
display.rect = screen(win,'Rect');
display.windowPtr = win;

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
% 			StartScan;
			trigScan;
% 			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
		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);
