#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <time.h>
#include "libsys.h"

#define BUF_SIZE	1024
char buffer[BUF_SIZE];
char rxbuf[BUF_SIZE];
char * volatile pPtr_r;
char * volatile pPtr_w;
UINT32 volatile timeout_cnt;

void handler3(void)
{
	volatile UINT32 *pUART_stat = (UINT32*)SYS_UART_STAT;
	volatile UINT32 *pUART_data = (UINT32*)SYS_UART_DATA;

	while((0x10 & *pUART_stat))
	{
///		sputs("w: "); print_word((int)pPtr_w); sputs("\n");
		if (pPtr_w == &buffer[BUF_SIZE-1])
			pPtr_w = buffer;
		*(pPtr_w++) = *pUART_data;
		timeout_cnt = 200;

	}

}

int main(int argc, char **argv)
{
	volatile UINT32 *pUART_stat = (UINT32*)SYS_UART_STAT;
	unsigned char *fileData;
	unsigned long file_len, state;

	pPtr_r = buffer;
	pPtr_w = buffer;
	interrupt_register(3, handler3);
	interrupt_enable(3);
	*pUART_stat |= (1 << 6);
	setbuf(stderr, NULL);

	state = 0;
	while(1)
	{
		fprintf(stdout,"Reading serial stream..\n");
		file_len = 0;
		timeout_cnt = 20000000;
		while(timeout_cnt--)
		{
			sleep(1);
		}
		while(pPtr_w != pPtr_r)
		{
//			sputs("r: "); print_word((int)pPtr_r); sputs("\n");
			if (pPtr_r == &buffer[BUF_SIZE-1])
				pPtr_r = buffer;
			rxbuf[file_len++] = *(pPtr_r++);
		}
		if (file_len)
		{
			PrintBuffer8(rxbuf, 16, file_len);
		}
		switch(state)
		{
			case 0:
			if (!memcmp(rxbuf, "CLIENT", file_len))
			{
				fprintf(stdout,"Send response\n");
				fprintf(stderr,"SERVER");
				state = 1;
			}
			break;
			default:
			break;
		}
	}

	return 0;
}
