/*TITLE date conversions */

/****keyword-flag*** "%v %f %n" */
/* "4 20-Mar-98,23:14:18 DATE.CPP" */

#include <malloc.h>
#include <dos.h>
#include <stdio.h>
#include <stdlib.h>
#include "date.h"

char *days_to_date_string(char *date_string, int days)
{
	int quad_year;
	int relative_year;
	int month_num;
	int i;
	int days_left;
	int month_days[12] = 
	{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};

	quad_year = days / 1461;
	relative_year = 4 * quad_year;
	days_left = days - quad_year * 1461;
	if (days_left < 366)
		{
		for (i = 2; i < 12; i ++)
			month_days[i] ++;
		}
	else if (days_left < 731)
		{
		relative_year ++;
		days_left -= 366;
		}
	else if (days_left < 1096)
		{
		relative_year += 2;
		days_left -= 731;
		}
	else
		{
		relative_year += 3;
		days_left -= 1096;
		}
		
	month_num = 11;
	for (i = 0; i < 12; i ++)
		if (month_days[i] > days_left)
			{
			month_num = i-1;
			break;
			}

	days_left -= month_days[month_num];

	sprintf(date_string,"%02d/%02d/%04d",month_num+1,days_left+1,
	relative_year+1980);

	return(date_string);

}


int date_string_to_days(char *date_string)
{
	struct tm datep;
	char *where;
	where = date_string;

	datep.tm_mon = atoi(where);
	where = strchr(where,'/')+1;

	datep.tm_mday = atoi(where);
	where = strchr(where,'/')+1;

	datep.tm_year = atoi(where);
	if (datep.tm_year < 1900)
		datep.tm_year += 1900;

	return(datep_to_days(datep));
}



struct tm days_to_datep(int days)
{
	char date_string[40];
	struct tm datep;
	char *where;

	days_to_date_string(date_string,days);
	where = date_string;

	datep.tm_mon = atoi(where);
	where = strchr(where,'/')+1;

	datep.tm_mday = atoi(where);
	where = strchr(where,'/')+1;

	datep.tm_year = atoi(where);

	return(datep);
}


datep_to_days(struct tm datep)
{
	int relative_year;
	int total_days;
	int year_days;
	int month_days[12] = 
	{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};

	relative_year = datep.tm_year - 1980;
	year_days = relative_year * 365 + (relative_year / 4);
	if (datep.tm_mon < 3 && relative_year % 4 == 0)
		year_days --;

	total_days = year_days + month_days[datep.tm_mon-1];

	total_days += datep.tm_mday;

	return(total_days);
}


int p_date()
{
    long ltime;
    struct tm* datep;
    struct tm dateq;

	time(&ltime);
    datep = localtime(&ltime);

    dateq = (*datep);

    return(datep_to_days(dateq));
}


