#include "ds1307lib.h"

unsigned char data[8];

void setRTC(time now){
	if (now.seconds>59) now.seconds=59;
	if (now.minutes>59) now.minutes=59;
	if (now.hours>23) now.hours=23;
	if (now.dayOfWeek<MO) now.dayOfWeek=MO;
	if (now.dayOfWeek>SU) now.dayOfWeek=SU;
	if (now.day<1) now.day=1;
	if (now.day>31) now.day=31;
	if (now.month<1) now.month=1;
	if (now.month>12) now.month=12;
	if (now.year>2099) now.year=2099;
	if (now.year<2000) now.year=2000;
	now.year-=2000; 
	data[0] = 0x00;
	data[1] = ((now.seconds/10)<<4)|(now.seconds%10);
	data[2] = ((now.minutes/10)<<4)|(now.minutes%10);
	data[3] = ((now.hours/10)<<4)|(now.hours%10);
	data[4] = now.dayOfWeek;
	data[5] = ((now.day/10)<<4)|(now.day%10);
	data[6] = ((now.month/10)<<4)|(now.month%10);
	data[7] = ((now.year/10)<<4)|(now.year%10);
	
	IICTransmit(0b1101000,8,&data[0]);
}

time readRTC(void){
	int i;
	time now;
	data[0] = 0x00;
	IICTransmit(0b1101000,1,&data[0]);
	for(i=0;i<10000;i++);
	IICReceive(0b1101000,7,&data[0]);
	for(i=0;i<10000;i++);
	now.seconds = (((data[0]>>4)&0x0F)*10)+(data[0]&0x0F);
	now.minutes = (((data[1]>>4)&0x0F)*10)+(data[1]&0x0F);
	now.hours = (((data[2]>>4)&0x0F)*10)+(data[2]&0x0F);
	now.dayOfWeek = data[3];
	now.day = (((data[4]>>4)&0x0F)*10)+(data[4]&0x0F);
	now.month = (((data[5]>>4)&0x0F)*10)+(data[5]&0x0F);
	now.year = (((data[6]>>4)&0x0F)*10)+(data[6]&0x0F)+2000;
	return now;
}



void setSeconds(unsigned char seconds){
	if (seconds>59) seconds=59;
	data[0] = 0x00;
	data[1] = ((seconds/10)<<4)|(seconds%10);
	IICTransmit(0b1101000,2,&data[0]);
}

void setMinutes(unsigned char minutes){
	if (minutes>59) minutes=59;
	data[0] = 0x01;
	data[1] = ((minutes/10)<<4)|(minutes%10);
	IICTransmit(0b1101000,2,&data[0]);
}

void setHours(unsigned char hours){
	if (hours>23) hours=23;
	data[0] = 0x02;
	data[1] = ((hours/10)<<4)|(hours%10);
	IICTransmit(0b1101000,2,&data[0]);
}

void setDayOfWeek(unsigned char dayOfWeek){
	if (dayOfWeek<MO) dayOfWeek=MO;
	if (dayOfWeek>SU) dayOfWeek=SU;
	data[0] = 0x03;
	data[1] = dayOfWeek;
	IICTransmit(0b1101000,2,&data[0]);
}

void setDay(unsigned char day){
	if (day<1) day=1;
	if (day>31) day=31;
	data[0] = 0x04;
	data[1] = ((day/10)<<4)|(day%10);
	IICTransmit(0b1101000,2,&data[0]);
}

void setMonth(unsigned char month){
	if (month<1) month=1;
	if (month>12) month=12;
	data[0] = 0x05;
	data[1] = ((month/10)<<4)|(month%10);
	IICTransmit(0b1101000,2,&data[0]);
}

void setYear(unsigned int year){
	if (year>2099) year=2099;
	if (year<2000) year=2000;
	year-=2000;
	data[0] = 0x06;
	data[1] = ((year/10)<<4)|(year%10);
	IICTransmit(0b1101000,2,&data[0]);
}
