#include <sys/time.h>		/* for struct tm */

struct tm *mgtime();

main()
{
}

/*
 * This routine converts time as follows.
 * The epoch is 0000 Jan 1 1970 GMT.
 * The argument time is in seconds since then.
 * mgtime(t) returns a pointer to an structure containing
 *
 *	tm_sec		seconds (0-59)
 *	tm_min		minutes (0-59)
 *	tm_hour		hours (0-23)
 *	tm_mday		day of month (1-31)
 *	tm_mon		month (0-11)
 *	tm_year		year - 1900 (70- )
 *	tm_wday		weekday (0-6, Sun is 0)
 *	tm_yday		day of the year (0-364/5)
 *	tm_isdst	is daylight saving time in force? (always 0 = GMT)
 *
 * The routine does not work in Saudi Arabia which runs on Solar time.
 */

struct tm *
mgtime(tim)
long tim;
{
	register int d; /* workhorse variable */
	register int y = 0,m,a;
	static struct tm xtime;

	/*
	 *	This routine is good until year 2100.
	 */

	xtime.tm_sec = (d = tim % 86400)%60;
	xtime.tm_min = (d/=60) % 60;
	xtime.tm_hour = d/60;

	d = tim / 86400; /* no of days */

	/*
	 * d is the day number. Generate day of the week.
	 * The addend is 4 mod 7 (1/1/1970 was Thursday)
	 */

	xtime.tm_wday = (d+4)%7;

	/*
	 *	K=K+693902	days from 1st Mar 0000 to 1st Jan 1900
	 *	W=4*K-1
	 *	Y=W//146097	Reference:
	 *	K=W-146097*Y	Algorithm 1992 from "Collected Algorithms from ACM"
	 *	D=K//4		Volume 1  Published by the Association for
	 *	K=(4*D+3)//1461	Computing Machinery, 1980.
	 *	D=4*D+3-1461*K
	 *	D=(D+4)//4
	 *	M=(5*D-3)//153
	 *	D=5*D-3-153*M	When munging this, bear in mind that for calculation
	 *	D=(D+5)//5	the year starts on March the 1st (yday == 0)
	 *	Y=K
	 */

	/* deal with years 2000-2099 and the lack of 29th Feb 2000 */
	if ( d > 10957+58 /* 28 Feb 2000 */ ) { y = 100; d++; } else y=0;
	y += ( d = ( 4 * ( d + 693902+25567 ) - 1 ) % 146097 | 3 ) / 1461;
	a = ( d = ( d % 1461 ) / 4 + 1 ) - 307;
	m = ( ( d *= 5 ) - 3 ) / 153;
	xtime.tm_mday = ( d + 2 - 153 * m ) / 5;

	/* adjust for fact that day==0 is 1st Mar 0000 */
	if ((m += 2) > 11) { m -= 12; y++; }
	xtime.tm_yday = ( a >= 0 ? a : a+365 );
	if ( (y & 3) == 0 && a < 0) xtime.tm_yday++;
	xtime.tm_mon=m;
	xtime.tm_year=y;
	xtime.tm_isdst = 0;
	return(&xtime);
}
