#include "h/p33FJ64GP802.h"
#include "h/rtc.h"

void initRTC(void)
{
	unsigned int u;
	u=OSCCON;
	u|=0x0002;					// enable LPOSCEN (bit 1 of OSCCON)
	__builtin_write_OSCCONL(u);	// unlock the OSCCON register for writing!
	RCFGCALbits.RTCOE=0;		// enable RTCC output on pin
	PADCFG1bits.RTSECSEL=1;		// select 1Hz output
	
	asm("disi #8");
	NVMKEY=0x55;
	NVMKEY=0xAA;
	RCFGCALbits.RTCWREN=1;		// allow writing
	RCFGCALbits.RTCEN=1;		// enable the RT Clock
	RCFGCALbits.RTCWREN=0;		// lock it.
}

TIMET getRTCTime(void)
{
	// get the current time
	unsigned int year, month_date, wday_hour, min_sec;
	TIMET	t;

	RCFGCALbits.RTCPTR=3;
	while(RCFGCALbits.RTCSYNC==1);
	year=RTCVAL;
	month_date=RTCVAL;
	wday_hour=RTCVAL;
	min_sec=RTCVAL;
	t.bcdyear=year;					// from 2000 in BCD
	t.bcdmonth=(month_date>>8);		
	t.bcdday=(month_date);
	t.bcdwday=(wday_hour>>8);
	t.bcdhours=(wday_hour);
	t.bcdminutes=(min_sec>>8);
	t.bcdseconds=(min_sec);
	return t;
}

void setRTCTime(TIMET t)
{
	unsigned int year, month_date, wday_hour, min_sec;

	year=t.bcdyear;
	month_date=(t.bcdmonth<<8)+(t.bcdday);
	wday_hour=(t.bcdwday<<8)+(t.bcdhours);
	min_sec=(t.bcdminutes<<8)+(t.bcdseconds);
	while(RCFGCALbits.RTCSYNC==1);
	asm("disi #8");
	NVMKEY=0x55;
	NVMKEY=0xAA;			// unlock
	RCFGCALbits.RTCWREN=1;	// enable writing
	RCFGCALbits.RTCEN=0;	// disable temporarily...
	RCFGCALbits.RTCPTR=3;	// set pointer
	RTCVAL=year;
	RTCVAL=month_date;
	RTCVAL=wday_hour;
	RTCVAL=min_sec;
	RCFGCALbits.RTCEN=1;	// enable again
	RCFGCALbits.RTCWREN=0;	// disable writes again
}


unsigned long BCD2Hex(unsigned int in)
{
	// convert a BCD coded usigned int to a hexadecimal number
	unsigned int i;
	unsigned int n;
	unsigned int result;

	result=0;
	n=1;
	for(i=0; i<4; i++)
	{
	result+=(n*(in & 0x0F));
	in=in>>4;
	n*=10;
	}
	return result;
}

TIMET	getTime(void)
{
	return currentTime;
}

