/* ŽžŒvŠÖŒW */

#include "bootpack.h"
#include <stdio.h>

void loadtime(struct CLOCK *clock);

struct CLOCK checktime(void)
{
	struct CLOCK time[2];
	loadtime(&time[0]);
	loadtime(&time[1]);
	if( time[0].sec != time[1].sec || time[0].min != time[1].min ||
		time[0].hou != time[1].hou || time[0].day != time[1].day ||
		time[0].mon != time[1].mon ){ return checktime(); }
	else { return time[1]; }
}

void loadtime(struct CLOCK *clock)
{
	struct CLOCK *time = clock;
	io_out8(0x70, 0x00);
	time->sec = io_in8(0x71);
	io_out8(0x70, 0x02);
	time->min = io_in8(0x71);
	io_out8(0x70, 0x04);
	time->hou = io_in8(0x71);
	io_out8(0x70, 0x07);
	time->day = io_in8(0x71);
	io_out8(0x70, 0x08);
	time->mon = io_in8(0x71);
	io_out8(0x70, 0x09);
	time->year = io_in8(0x71);
	io_out8(0x70, 0x32);
	time->year |= io_in8(0x71) << 8;
	return;
};

void clock_task(struct SHEET *sht_back)
{
	struct BOOTINFO *binfo = (struct BOOTINFO *) ADR_BOOTINFO;
	struct TASK *task = task_now();
	struct CLOCK clock;
	char clocks[20];
	struct TIMER *timer;
	int i;

	timer = timer_alloc();
	timer_init(timer, &task->fifo, 65536);
	timer_settime(timer, 10);

	clock = checktime();
	sprintf(clocks, "%04X/%02X/%02X %02X:%02X:%02X",clock.year, clock.mon, clock.day, clock.hou, clock.min, clock.sec);
	putfonts8_asc_sht(sht_back, binfo->scrnx - 164, binfo->scrny - 21, COL8_FFFFFF, COL8_333333, clocks, 19);

	for(;;)
	{
		if (fifo32_status(&task->fifo) == 0) {
			task_sleep(task);
		} else {
			i = fifo32_get(&task->fifo);
			if(i == 65536) {
				timer_settime(timer, 10);
			}
			clock = checktime();
			sprintf(clocks, "%04X/%02X/%02X %02X:%02X:%02X",clock.year, clock.mon, clock.day, clock.hou, clock.min, clock.sec);
			putfonts8_asc_sht(sht_back, binfo->scrnx - 164, binfo->scrny - 21, COL8_FFFFFF, COL8_333333, clocks, 19);
		}
	}
}
