#include <em_device.h>									// header for all micro registers
#include "hardware.h"									// custom headers
#include "uart.h"
#include "dogs_10x4.h"

const char days[][10] = {"", "Monday", "Tuesday", "Wednesday", "Thursday",
						"Friday", "Saturday", "Sunday"};
extern char response[];									// AMW037 response buffer
uint8_t computeDayOfWeek(uint16_t, uint8_t, uint8_t);
						
int main()
{
	CMU_setup();										// configure clock
	GPIO_setup();										// configure GPIO ports											
	I2C0_setup();
	USART_setup();
	LETIMER_setup();
	DOGS_setup();										// configure LCD
	
	do
	{
		Send_AMW037("get wl n s");						// wait for connection with AP
		Delay_ms(1000);
	} while (response[11] != '2');						// and getting IP address
	
	Send_AMW037("set sy c e 0");						// supress echo
	Send_AMW037("set ti z -5");							// set time zone relative to UTC
	Send_AMW037("get ti r utc");						// get time command

	DOGS_WriteRow(&response[13], 8, DOGS_FIRST_ROW);	// display time
	DOGS_WriteRow(&response[2], 10, DOGS_SECOND_ROW);	// display date
	uint8_t day = computeDayOfWeek(a2i(response, 2, 4),
		a2i(response, 7, 2), a2i(response, 10, 2));
	DOGS_WriteRow((char*)days[day], 10, DOGS_THIRD_ROW);// display day
	
	while(1)											// main application loop
	{	
		__WFI();										// enter sleep
	}	
}

uint8_t computeDayOfWeek(uint16_t y, uint8_t m, uint8_t d)
 {
    if (m <= 2)					// January and February are counted as			
    {							// months 13 and 14 of the previous year
       m += 12;
       y -= 1;
    }

    uint8_t j = y / 100;		// J = century
    uint8_t k = y % 100;		// K = year of the century

    //Compute H using Zeller's congruence
    uint16_t h = d + (26 * (m + 1) / 10) + k + (k / 4) + (5 * j) + (j / 4);
    return ((h + 5) % 7) + 1;	// return the day of the week
 }
