#include <stdio.h>

#include "DATETIME.H"

int mLeapYear=0;
int mYear=0;
int mMonth=0;
int mDayOfMonth=0;
int mDayOfYear=0;
int mDayOfWeek=0;
int DaysOfMonths[]={31,28,31,30,31,30,31,31,30,31,30,31};

int cmpDTS (struct DTS * dts1,struct DTS * dts2)
{
	if ( dts1->Date < dts2->Date ) return(-1);
	if ( dts1->Date > dts2->Date ) return(1);
	if ( dts1->Hour < dts2->Hour ) return(-1);
	if ( dts1->Hour > dts2->Hour ) return(1);
	if ( dts1->Min < dts2->Min ) return(-1);
	if ( dts1->Min > dts2->Min ) return(1);
	return(0);
}
int getDOW(struct DTS * dts,int pSunMonFlag)
{
/* cpm date starts Sun, Jan 1, 1978 = 1*/
	if (dts->Date <= 0) return(0);
	mDayOfWeek = ((dts->Date-1) % 7) +1;
	if (pSunMonFlag!=0) mDayOfWeek++;
return( mDayOfWeek );
}


int IsLeapYear(int pYear)
{
return((pYear % 4) ==0) && ( ((pYear % 100) !=0) || ((pYear % 400) ==0) );
}

int conv2ymd(struct DTS * dts)
{
int tDate;
int DaysLeft;
int tYear;
int tMonth;

tDate=dts->Date;

for (tYear=1978; tYear<2067; tYear++)
	{
	DaysLeft=tDate;
	tDate-=365;
	if (mLeapYear=IsLeapYear(tYear)) tDate-- ;
	if (tDate <= 0) break;
	}
mYear=tYear;
mDayOfYear=tDate=DaysLeft;

for (tMonth=0; tMonth <12; tMonth++)
	{
	DaysLeft=tDate;
	tDate-=DaysOfMonths[tMonth];
	if (mLeapYear && (tMonth==1)) tDate-- ;
	if (tDate <= 0) break;
	}
mMonth=tMonth+1;
mDayOfMonth=DaysLeft;

return(0);
}

int time2str (struct DTS * dts, char * strTime)
{
int RTN;
RTN=sprintf( strTime,"%02x:%02x",  
		dts->Hour, 
		dts->Min);
return(RTN);
}

int date2str (struct DTS * dts, char * strDate)
{
int RTN;
conv2ymd(dts);
RTN=sprintf( strDate,"%02d/%02d/%02d", 
		mYear,mMonth,mDayOfMonth);
return(RTN);
}

int dts2str (struct DTS * dts, char * strDts)
{
int RTN;
conv2ymd(dts);
RTN=sprintf( strDts,"%02d/%02d/%02d %02x:%02x", 
		mYear,mMonth,mDayOfMonth, 
		dts->Hour, 
		dts->Min);
return(RTN);
}
