#include <sys/types.h>
#include <sys/time.h>

/*
 * In the MiNT library, gettimeofday has a granularity of two seconds --
 * which is pretty useless for ping.
 * We use clock() instead, which measures real time instead of process
 * time in the MiNT library. (clock() has 5 ms granularity).
 */

static int first = 1;
static struct timeval the_time;
static clock_t oticks;

static void
tvadd (tv1, tv2)
	struct timeval *tv1, *tv2;
{
	tv1->tv_usec += tv2->tv_usec;
	if ((unsigned long)tv1->tv_usec > 1000000L) {
		tv1->tv_usec -= 1000000L;
		tv1->tv_sec++;
	}
	tv1->tv_sec += tv2->tv_sec;
}

int
__5ms_gettimeofday (tv, tz)
	struct timeval *tv;
	struct timezone *tz;
{
	clock_t diff, ticks = clock ();

	if (first) {
		first = 0;
		oticks = ticks;
		gettimeofday (&the_time, 0);
	}
	diff = ticks - oticks;
	oticks = ticks;

	tv->tv_sec  = diff / CLK_TCK;
	tv->tv_usec = ((diff % CLK_TCK)*1000000L) / CLK_TCK;
	tvadd (&the_time, tv);
	*tv = the_time;
	return 0;
}

int
__5ms_settimeofday (tv, tz)
	struct timeval *tv;
	struct timezone *tz;
{
	int r;

	r = settimeofday (tv, tz);
	if (r == 0) {
		the_time = *tv;
		oticks = clock ();
	}
	return r;
}
