/*
 * Copyright(C) Paul und Scherer (mct.de/mct.net)
 *
 * This example demonstrates how to...
 *
 *  ... measure reaction time.
 */

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <target.h>

#define LED		0x10000			// LED =P0.16

/*
 * Initialize Timer1 to count milliseconds
 *
 * Return millisecond count.
 */
static long
ms(void)
{
	static int done;			// skip if already done

	if (!done) {
		done = 1;
		Intern_t1tcr = 2;		// stop, reset
		Intern_t1pr  = _PCLK/1000-1;	// inc every ms
		Intern_t1tcr = 1;		// go...
	}
	return Intern_t1tc;
}

/*
 * When any key is hit, the LED lights for a random time between
 * two and 7 seconds. Hit again any key, after the LED is turned
 * off. The time between the turning off of the LED and your key
 * press is measured and displayed.
 *
 * If you use 'h' to start the game, the program tells you, when
 * the LED wil be turned off and an additional beep signals this
 * event.
 */
int
main(void)
{
	while (1) {
		long start, stop;		// start/stop
		int delay;			// stop delay
		int help;			// make it easier flag

	 retry:	Intern_iodir &= ~LED;		// LED off

		puts("Hit any key when ready ('h' for help)...");
		help = getch() == 'h';
		start = ms();			// ms count now
		delay = 2000+rand()%5000;	// delay 2000.. 7000ms

		Intern_iodir |= LED;		// LED on
		puts("START");
		if (help) printf("Stop in %dms\n", delay);

		while (ms()-start < delay) {
			if (kbhit()) {
				getch();	// remove pending char
				puts("TILT!");
				goto retry;
			}
		}
		Intern_iodir &= ~LED;		// LED off
		puts("STOP");
		if (help) putchar(7);

		start = ms();			// ms count now
		while (!kbhit()) {
			if (ms()-start > 5000) {
				puts("TIMEOUT!");
				goto retry;
			}
		}
		stop = ms();			// ms count at key hit
		getch();			// remove pending char

		printf("%lums\n\n", (stop-start));
	}
}
