#ifndef	lint
static char rcs_id[] = "$Header: time.c,v 1.3 88/05/09 16:02:59 ecc Exp $";
#endif	not lint

/*
 * time.c
 *
 * $Source: /usr0/ecc/nectar/src/cab/threads/RCS/time.c,v $
 *
 * Time routines.
 */


#include <nectar_sys.h>
#include <thread_time.h>

#undef	_TIME_
#include <sys/time.h>

/*
 * Store the current time in the result Time_val.
 */
EXPORT void
Time_Now(result)
	Time_val_t result;
    BEGIN(Time_Now)
	IMPORT gettimeofday();
	(void) gettimeofday(result, ((struct timezone *) 0));
	RET;
    END(Time_Now)


/*
 * Compare two Time_val structures.
 * The current time of day is used
 * in place of t1 or t2 if it is NO_TIME_VAL.
 * Result is <, ==, or > 0, according to whether t1 is <, ==, or > t2.
 */
EXPORT int
Time_Compare(t1, t2)
	Time_val_t t1, t2;
    BEGIN(Time_Compare)
	struct Time_val now;

	if (t1 == NO_TIME_VAL || t2 == NO_TIME_VAL) {
		Time_Now(&now);
		if (t1 == NO_TIME_VAL)
			t1 = &now;
		if (t2 == NO_TIME_VAL)
			t2 = &now;
	}
	RETURN(TIME_COMPARE(t1, t2));
    END(Time_Compare)

/*
 * result := t1 + t2
 * where t1 and t2 are struct Time_val pointers.
 * The current time of day is used
 * in place of t1 or t2 if it is NO_TIME_VAL.
 * t1 or t2 can also be used as the result.
 */
EXPORT void
Time_Plus(t1, t2, result)
	Time_val_t t1, t2;
	OUT Time_val_t result;
    BEGIN(Time_Plus)
	struct Time_val now, r;

	if (t1 == NO_TIME_VAL || t2 == NO_TIME_VAL) {
		Time_Now(&now);
		if (t1 == NO_TIME_VAL)
			t1 = &now;
		if (t2 == NO_TIME_VAL)
			t2 = &now;
	}
	r.seconds = t1->seconds + t2->seconds;
	r.microseconds = t1->microseconds + t2->microseconds;
	if (r.microseconds >= 1000000) {
		r.microseconds -= 1000000;
		r.seconds += 1;
	}
	*result = r;
	RET;
    END(Time_Plus)

/*
 * result := t1 - t2
 * where t1 and t2 are struct Time_val pointers.
 * The current time of day is used
 * in place of t1 or t2 if it is NO_TIME_VAL.
 * t1 or t2 can also be used as the result.
 */
EXPORT void
Time_Diff(t1, t2, result)
	Time_val_t t1, t2;
	OUT Time_val_t result;
    BEGIN(Time_Diff)
	struct Time_val now, r;

	if (t1 == NO_TIME_VAL || t2 == NO_TIME_VAL) {
		Time_Now(&now);
		if (t1 == NO_TIME_VAL)
			t1 = &now;
		if (t2 == NO_TIME_VAL)
			t2 = &now;
	}
	r.seconds = t1->seconds - t2->seconds;
	r.microseconds = t1->microseconds - t2->microseconds;
	if (r.microseconds < 0) {
		r.microseconds += 1000000;
		r.seconds -= 1;
	}
	*result = r;
	RET;
    END(Time_Diff)
