#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "irq.h"

#define	CPU_FREQ_HZ	100000000

#include "libsys.h"

char buffer[16384];
char * volatile pPtr_r;
char * volatile pPtr_w;

void handler0(void)
{
	printf("Interrupt 0\n");
	interrupt_clr(0);
}

void handler1(void)
{
	printf("Interrupt 1\n");
	interrupt_clr(1);
}

void handler2(void)
{
	printf("Interrupt 2\n");
}

void handler3(void)
{
	volatile UINT32 *pUART0_stat = (UINT32*)sys_uart0_stat;
	volatile UINT32 *pUART0_data = (UINT32*)sys_uart0_data;
	volatile UINT32 *pUART1_stat = (UINT32*)sys_uart1_stat;
	volatile UINT32 *pUART1_data = (UINT32*)sys_uart1_data;

	while(0x200 & *pUART0_stat)
	{
//		sputs("w: "); print_word((int)pPtr_w); sputs("\n");
		if (pPtr_w == &buffer[16383])
			pPtr_w = buffer;
		*(pPtr_w++) = *pUART0_data;
	}

	while(0x200 & *pUART1_stat)
	{
//		sputs("w: "); print_word((int)pPtr_w); sputs("\n");
		if (pPtr_w == &buffer[16383])
			pPtr_w = buffer;
		*(pPtr_w++) = *pUART1_data;
	}

}

void handler4(void)
{
	printf("Interrupt 4\n");
}

void handler5(void)
{
	printf("Interrupt 5\n");
}

void handler6(void)
{
	printf("Interrupt 6\n");
}

void handler7(void)
{
	printf("Interrupt 7\n");
}

int main(void)
{

	volatile UINT32 *pUART0_stat = (UINT32*)sys_uart0_stat;
	volatile UINT32 *pUART1_stat = (UINT32*)sys_uart1_stat;
	volatile UINT32 *pUART0_baud = (UINT32*)sys_uart0_baud;
	volatile UINT32 *pUART1_baud = (UINT32*)sys_uart1_baud;

	UART1_setbaud(460800);
	printf("Hello\n");
	memset(buffer, 0, sizeof(buffer));
	pPtr_r = buffer;
	pPtr_w = buffer;
	interrupt_register(0, handler0);
	interrupt_enable(0);

	interrupt_register(1, handler1);
	interrupt_enable(1);

	interrupt_register(2, handler2);
	interrupt_enable(2);

	printf("UART0 Status = 0x%8.8X\n", *pUART0_stat);
	printf("UART0 Baud   = 0x%8.8X\n", *pUART0_baud);
	printf("UART1 Status = 0x%8.8X\n", *pUART1_stat);
	printf("UART1 Baud   = 0x%8.8X\n", *pUART1_baud);

	// enable RX interrupt
	*pUART0_stat |= (1 << 6);
	*pUART1_stat |= (1 << 6);
	printf("UART0 Status = 0x%8.8X\n", *pUART0_stat);
	printf("UART1 Status = 0x%8.8X\n", *pUART1_stat);

	interrupt_register(3, handler3);
	interrupt_enable(3);

	interrupt_register(4, handler4);
//	interrupt_enable(4);

	interrupt_register(5, handler5);
	interrupt_enable(5);

	interrupt_register(6, handler6);
	interrupt_enable(6);

	interrupt_register(7, handler7);
	interrupt_enable(7);

	printf("Start:\n");

	interrupt_set(0);
	interrupt_set(1);
	interrupt_set(2);
	interrupt_set(3);
	interrupt_set(4);
	interrupt_set(5);
	interrupt_set(6);
	interrupt_set(7);

	sputs("r: "); print_word((int)pPtr_r); sputs("\n");
	sputs("w: "); print_word((int)pPtr_w); sputs("\n");

	// Print Status register
	sputs("Status  : ");
	print_word(CP0_SR_read());
	sputs("\n");

	while(1)
	{
		if(pPtr_w != pPtr_r)
		{
//			sputs("r: "); print_word((int)pPtr_r); sputs("\n");
			if (pPtr_r == &buffer[16383])
				pPtr_r = buffer;
			writechar(*(pPtr_r++));
		}
	}
	return 0;
}
