#include <avr/io.h>
#include <util/delay.h>
#include "lcd.h"
#include "lcd.c"
#include <stdint.h>
#include <stdlib.h>
#include <avr/interrupt.h>
char csec[10],chour[10],cmin[10];
int tot_overflow;
char buffer[10], buffer2[10];
unsigned short int min,hour,sec;

ISR(TIMER0_OVF_vect)
{
	tot_overflow++;
}


void puturi(unsigned short int min, unsigned short int hour, unsigned short int sec)
{
	lcd_gotoxy(0,0);
	lcd_puts("Ceas:");
	char csec[10],chour[10],cmin[10];
	itoa(sec, csec, 10);
	itoa(min, cmin, 10);
	itoa(hour, chour, 10);
	if (hour <= 9)
	{
		lcd_gotoxy(0,1);
		lcd_puts("0");
		lcd_gotoxy(1,1);
		lcd_puts(chour);
		lcd_gotoxy(2,1);
		lcd_puts(":");
	}
	if (hour > 9)
	{
		lcd_gotoxy(0,1);
		lcd_puts(chour);
		lcd_gotoxy(2,1);
		lcd_puts(":");
	}
	if (min <= 9)
	{
		lcd_gotoxy(3,1);
		lcd_puts("0");
		lcd_gotoxy(4,1);
		lcd_puts(cmin);
		lcd_gotoxy(5,1);
		lcd_puts(":");
	}
	if (min > 9)
	{
		lcd_gotoxy(3,1);
		lcd_puts(cmin);
		lcd_gotoxy(5,1);
		lcd_puts(":");
	}
	if (sec <= 9)
	{
		lcd_gotoxy(6,1);
		lcd_puts("0");
		lcd_gotoxy(7,1);
		lcd_puts(csec);
	}
	if (sec > 9)
	{
		lcd_gotoxy(6,1);
		lcd_puts(csec);
	}
	
}


void timer0_init()

{
	TCCR0 |= (0 << CS02)|(0 << CS01)|(1 << CS00);
	TIMSK |= (1 << TOIE0);
	TCNT0 = 0;
	sei();
}


int main(void)
{
	timer0_init();
	DDRC = 0b00111000;
	lcd_init(LCD_DISP_ON);
	lcd_clrscr();
	int timer = 0;
	//	char buffer[10];
	min = sec = hour = 0;
	sec = 0;
	min = 59;
	hour = 19;
	while(1)
	{
		puturi(min,hour,sec);
		_delay_ms(100);
		lcd_clrscr();
		if (tot_overflow >=3906)
		{
			if (TCNT0 >= 64)
			{
				TCNT0 = 0;
				tot_overflow = 0;
				sec++;
				if (sec >= 60)
				{
					min++;
					sec = 0;
					if (min >= 60)
					{
						hour++;
						min = sec = 0;
						if (hour == 24)
						{
							min = hour = sec = 0;
						}
					}
				}
				
			}
		}
	}
}