/* New for v2.0: readline support -- daw */

/*
 * this is a reimplementation of the standard tickcounter, *without* alarm()!
 * god i hate alarm() -- it screws everything up, and isn't portable,
 * and tintin was calling alarm() every second!  blech.
 */

#include "tintin.h"

extern int time0, tick_size;
extern struct session *sessionlist;

extern void tintin_puts();

int timetilltick( /* void */ )
{
	int now, ttt;

	ttt = (time(0) - time0) % tick_size;
	ttt = (tick_size - ttt) % tick_size;
	return (ttt);
}

/*
 * returns how long before the next event, in seconds.
 * (i.e. if we're 13 seconds till tick in some session,
 * we return 3, because in 3 seconds we'll need to warn
 * the user that they are 10 seconds short of the tick.)
 * 
 * also prints the tick warnings, by the way. :-)
 * 
 * bug: if you suspend tintin++ for a few minutes, then
 * bring it back, you get lots of tick warnings.  is this
 * the desired behavior?
 */
int checktick( /* void */ )
{
	static int last = -1, ttt = -1;		/* ttt = time to tick */
	int now;
	struct session *s;

	if (time0 <= 0)
		return (100);	/* big number */
	now = time(0);

	if (last > 0)
		while (last <= now) {
			ttt = (++last - time0) % tick_size;
			ttt = (tick_size - ttt) % tick_size;
			if (ttt != 0 && ttt != 10)
				continue;
			for (s = sessionlist; s; s = s->next)
				if (s->tickstatus)
					tintin_puts((ttt == 0) ? "#TICK!!!"
					     : "#10 SECONDS TO TICK!!!", s);
		}
	else {
		last = now + 1;
		ttt = (now - time0) % tick_size;
		ttt = (tick_size - ttt) % tick_size;
	}

	if (ttt > 10)
		return (ttt - 10);
	else if (ttt > 0)
		return (ttt);
	else
		return (tick_size);
}