# include	"../hdr/defines.h"
# include	<sys/timeb.h>

SCCSID(@(#)date_ab	1.2);
/*
	Function to convert date in the form "yymmddhhmmss" to
	standard UNIX time (seconds since Jan. 1, 1970 GMT).
	Units left off of the right are replaced by their
	maximum possible values.

	The function corrects properly for leap year,
	daylight savings time, offset from Greenwich time, etc.

	Function returns -1 if bad time is given (i.e., "730229").
*/
char	*Datep;

date_ab(adt,bdt)
char *adt;
long *bdt;
	{
	int			year,month,day;
	int			hours,minutes,seconds;
	register int		i;
	long			time;
	struct timeb		tmb;
	extern struct tm	*localtime();

	Datep = adt;

	if ((year = get2()) < 0)
		year = 99;

	if (year < 70 || year > 99)
		return (-1);

	if ((month = get2()) < 0)
		month = 12;

	if (month < 1 || month > 12)
		return (-1);

	if ((day = get2()) < 0)
		day = monthsize(year,month);

	if (day < 1 || day > monthsize(year,month))
		return (-1);

	if ((hours = get2()) < 0)
		hours = 23;

	if (hours < 0 || hours > 23)
		return (-1);

	if ((minutes = get2()) < 0)
		minutes = 59;

	if (minutes < 0 || minutes > 59)
		return (-1);

	if ((seconds = get2()) < 0)
		seconds = 59;

	if (seconds < 0 || seconds > 59)
		return (-1);

	time = 0L;
	year += 1900;

	for (i = 1970; i < year; i++)
		time += yearsize(i);

	while (--month)
		time += monthsize(year,month);

	time += day - 1;
	time *= 24;
	time += hours;
	time *= 60;
	time += minutes;
	time *= 60;
	time += seconds;

	ftime(&tmb);
	time += tmb.timezone * 60;

	if (localtime(&time) -> tm_isdst)
		time += (-1 * 60 * 60);

	*bdt = time;

	return (0);
}

get2()
	{
	register char	*p;
	register int	c;

	p = Datep;

	while (*p && !numeric(*p))
		p++;

	if (!*p)
		return (-1);

	c = (*p++ - '0') * 10;

	if (*p)
		c += (*p++ - '0');

	Datep = p;

	return (c);
}

monthsize(y,m)
int	y,m;
	{
	static int	days[] =	{
		31,28,31,30,31,30,31,31,30,31,30,31
	};

	if (m == 2 && yearsize(y) == 366)
		return (29);
	else
		return (days[m - 1]);
}

yearsize(y)
int	y;
	{

	if (!(y % 4) && (y % 100))
		return (366);
	else
		return (365);
}
