#include "ctrl_set.h"
#include "console.h"
#include "utils.h"
#include "39vf160.h"
#include "DataType.h"


#define	DFT_DOWNLOAD_ADDR	0xc008000
#define	MAX_CMD_LEN	128
#define	MAX_ARGS	MAX_CMD_LEN/4

extern U32 MCLK;

int IP_ADDRESS = 0xc0a80064;
U32	SERIAL_BAUD	= 57600;
U32 download_addr;
U32 program_begin;

char table_begin[] = "/***************************************************************/\n";
#define prompt()	puts("\\>")

TIME_STRUC SysTime;
char *WeekDay[7] = {"SUN","MON", "TUES", "WED", "THURS","FRI", "SAT"}; 

/*********************************************************/
int GetParameter(char *str, int cnt)
{
	int i, key;
	
	
	i = 0;
	while(1)
	{
		if(kbhit())
		{
			key = getkey();
			if(key==BACK_KEY)
				i -= i?1:0;
			else
			if(key==ENTER_KEY)
			{
				str[i] = 0;
				return i;
			}
			else
			if(i<cnt)
			{	
				putch(key);
				str[i++] = key;
			}									
				
		}
	}
	
}

/*********************************************************/
int SysClock(int argc, char *argv[])
{
	printf("System is running @%dHz\n", MCLK);
	return 0;
}

int GetDate(int argc, char *argv[])
{
	int i, error = 0;
	char tmp[8];
	char *str;
	U32 year, month, day;
	
	RtcGetTime(&SysTime);
	printf("Current date is %d-%x-%x %s\n", SysTime.year, SysTime.month, SysTime.day, WeekDay[SysTime.weekday]);
	
	if(argc<2)
		return 0;	
		
	str = argv[1];	
	
	for(i=0; i<5; i++)	
		tmp[i] = str[i];
	if(tmp[4]!='-')
		error = 1;
	year = strtodec(str, 4);
	if(year<2000||error)
	{			
		puts("year error!\n");
		return 0;
	}		
				
	str += 5;
	i = 0;		
	if(str[++i]!='-')
		if(str[++i]!='-')
			error = 1;
	str[i] = 0;					
	month = strtobcd(str);
	if((month-1)>0x11||error)
	{				
		puts("month error!\n");
		return 0;
	}		
		
	str += i+1;		
	i = 0;
	if(str[++i]!=0)
		if(str[++i]!=0)
			error = 1;
	str[i] = 0;		
	day = strtobcd(str);
	if((day-1)>0x30||error)
	{		
		puts("day error!\n");
		return 0;
	}	
	
	SysTime.year  = year-2000;
	SysTime.month = month;
	SysTime.day   = day;		
	RtcSetDay(&SysTime);	
	
	printf("Set date %d-%x-%x %s\n", year, month, day, WeekDay[SysTime.weekday]);
	
	return 1;
}

int SetWeek(int argc, char *argv[])
{
	U32 i;
	int error = 0;	
	
	if(argc<2)
		error = 1;	
	
	i = strtodec(argv[1], 1);
	if((i-1)>5)
		error = 1;
	
	if(!error)
	{
		SysTime.weekday = i;
		RtcSetWeek(&SysTime);
		printf("Set to %s\n", WeekDay[i]);
	}
	else
	{
		puts("Please enter weekday\n");
		puts("0 : Sunday\n");
		puts("1 : Monday\n");
		puts("2 : Tuesday\n");
		puts("3 : Wednesday\n");
		puts("4 : Thursday\n");
		puts("5 : Friday\n");
		puts("6 : Satday\n");		
	}
	
	return 0;	
}

int GetTime(int argc, char *argv[])
{
	int i, error = 0;
	char *str;
	U32 hour, min, sec;
	
	RtcGetTime(&SysTime);
	printf("Current time is %x:%x:%x\n", SysTime.hour, SysTime.min, SysTime.sec);
	
	if(argc>1)
	{
		str = argv[1];
		i = 0;
		if(str[++i]!=':')
			if(str[++i]!=':')
				error = 1;
		str[i] = 0;		
		hour = strtobcd(str);
		if(hour>0x23||error)
		{
			puts("hour error!\n");
			return error;
		}
		
		str	+= i+1;
		i = 0;		
		if(str[++i]!=':')
			if(str[++i]!=':')
				error = 1;
		str[i] = 0;		
		min = strtobcd(str);		
		if(min>0x59||error)
		{
			puts("minute error!\n");
			return error;
		}
		
		str	+= i+1;
		i = 0;		
		if(str[++i]!=0)
			if(str[++i]!=0)
				error = 1;
		str[i] = 0;		
		sec = strtobcd(str);		
		if(sec>0x59||error)
		{
			puts("second error!\n");
			return error;
		}
		
		SysTime.hour = hour;
		SysTime.min  = min;
		SysTime.sec = sec;		
		RtcSetTime(&SysTime);
		
		printf("Set time %x:%x:%x\n", hour, min, sec);								
	}	
	
	return error;
}

/*********************************************************/
int ChgSysMclk(int argc, char *argv[])
{
	int i, mdiv, pdiv, sdiv;
	char tmp[4];
	
	puts("This function is for adjust system running clock!!!\n");
	printf("Current clock is %dHz\n", MCLK);
	puts("Please enter the PLL parameter to use, mdiv[0-255], pdiv[0-63], sdiv[0-3]\n");
	
	puts("mdiv: ");	
	if((mdiv=strtodec(tmp, GetParameter(tmp, 3)))<0)		
	{
		puts("\nget mdiv Error!\n");
		return 0;
	}					
	
	puts("\npdiv: ");
	if((pdiv=strtodec(tmp, GetParameter(tmp, 3)))<0)		
	{
		puts("\nget pdiv Error!\n");
		return 0;
	}	
	
	puts("\nsdiv: ");
	
	if((sdiv=strtodec(tmp, GetParameter(tmp, 3)))<0)		
	{
		puts("\nget sdiv Error!\n");
		return 0;
	}		
	
	printf("\nYou set System clock mdiv = %d, pdiv = %d, sdiv = %d\n", mdiv, pdiv, sdiv);
	
	i = 8000;
	while(i--);
		
	ChangePllValue(mdiv, pdiv, sdiv);
	
	i = 8000;
	while(i--);	
	console_init(SERIAL_BAUD);
	printf("Current clock is %dHz\n", MCLK);	
	
	return 0;
}

int ChgBaudRate(int argc, char *argv[])
{
	int i;
	U32 BaudSet [6] = {4800, 9600, 19200, 38400, 57600, 115200};
	
	for(i=0; i<6; i++)
		printf("%d : %d\n", i, BaudSet[i]);
		
	puts("Please enter choice : ");
	
	while(1)
	{
		int ch = getch();
		
		if(ch<='6'||ch>='0')
		{
			SERIAL_BAUD = BaudSet[ch-'0'];
			printf("Baud rate set to : %d\nPress any key to continue\n", SERIAL_BAUD);
			i = 0x4000;
			while(i--);		//wait transmit end
			console_init(SERIAL_BAUD);
			getch();
			break;
		}
			
	}	

	return 0;
}

/*********************************************************/
int tftp_main(unsigned long ip, unsigned long addr, int method);

int LoadFile2Mem(int argc, char *argv[])
{
	
	if(argc<2)
	{
		download_addr = DFT_DOWNLOAD_ADDR;
		printf("No begin address for download, use default address 0x%x\n", download_addr);
	}
	else
		download_addr = strtoul(argv[1]);
	
	tftp_main(IP_ADDRESS, download_addr, 0);

	return 0;
}

int ProgFlash(int argc, char *argv[])
{
	unsigned int size = ~0;
	unsigned int data_begin = ~0;
	unsigned int prog_begin = ~0;
	int overwrite0 = 1;
	int modify_a0 = 0;
	unsigned int bios_load_addr;		 

	if(argc<4)
	{		
		puts("Arguments error!\n");
		puts("Usage:	prog a1 a2 size [-no0]\na1 = program begin address\na2 = data pointer to ram\nsize = program size(Bytes)\n-no0 = don't overwrite address 0\n");
		return -1;
	}	
		
	prog_begin = strtoul(argv[1]);			
	data_begin = strtoul(argv[2]);
	size       = strtoul(argv[3]);
	
	if(size==0)
	{
		puts("Write 0 Bytes!\n");
		return -1;
	}
	
	if(prog_begin==-1||data_begin==-1)		//
	{
		puts("Arguments error\n");
		return -1;
	}	
	
	printf("program flash begin @0x%x, from ram data @0x%x, size = %dBytes\nAre you sure? [y/n]", prog_begin, data_begin, size);
	while(1)
	{
		if(kbhit())
		{
			int key = getkey();
			if(key=='y'||key=='Y')
			{
				putch(key);
				next_line();
				break;
			}
			if(key=='n'||key=='N')
			{
				putch(key);
				next_line();
				return 0;
			}				
		}
			
	}		

#define	__ROM_SIZE	0x200000
#define	BIOS_BASE	(__ROM_SIZE-0x10000)
#define	BIOS_LOAD	(__ROM_SIZE-4)
	
	if(argc>4)
		if(strncmp(argv[4], "-no0", 4)==0)
			overwrite0 = 0;		
	
	if((prog_begin==0)&&overwrite0)
	{
		unsigned int ins;
		
		
		ins = *(unsigned int *)data_begin;				
		if((ins>>24)==0xea)			// instruction:	b	xxxx, now just support b instruction!!!			
			bios_load_addr = ((ins&0xffffff)<<2)+8;
		else
			bios_load_addr = 4;		// other instruction, jump to 4
													
		bios_load_addr = (bios_load_addr-BIOS_LOAD-8)/4;
		bios_load_addr = (bios_load_addr&0xffffff)|0xea000000;					
				
		*(unsigned int *)data_begin = 0xea000000+(BIOS_BASE-8)/4;				
		
		modify_a0 = 1;										
	}
			
	SectorProg(prog_begin, (unsigned short *)data_begin, size);
	
	if(modify_a0)
	{
		size = FlashSector(size-1)+SECTOR_SIZE;				
		
		FlashRead(FlashSector(BIOS_LOAD), (U16 *)(DFT_DOWNLOAD_ADDR+size), SECTOR_SIZE);			
		*(U32 *)(DFT_DOWNLOAD_ADDR+size+SECTOR_SIZE-4) = bios_load_addr;
		SectorProg(FlashSector(BIOS_LOAD), (U16 *)(DFT_DOWNLOAD_ADDR+size), SECTOR_SIZE);			
	}
		
	
	return 0;
}

int BootLoader(int argc, char *argv[])
{
	int key;		
	
	puts("boot from flash, are you sure? [y/n]");
	while(1)
	{
		if(kbhit())
		{
			key = getkey();
			if(key=='y'||key=='Y')
			{
				void (*fp)(void) =(void (*)(void))BIOS_LOAD;
				
				putch(key);
				next_line();
				(*fp)();							
			}
			if(key=='n'||key=='N')
			{
				putch(key);
				next_line();
				break;	
			}
		}			
	}
	
	return 0;
}

int AutoProgFlash(int argc, char *argv[])
{
	char ch_tmp[3][10];
	char *para_ptr[4];	
		
	ultostr(ch_tmp[0], 0);	
	ultostr(ch_tmp[1], DFT_DOWNLOAD_ADDR);	 	
	ultostr(ch_tmp[2], tftp_main(IP_ADDRESS, DFT_DOWNLOAD_ADDR, 1));		
	
	para_ptr[1] = ch_tmp[0];
	para_ptr[2] = ch_tmp[1];
	para_ptr[3] = ch_tmp[2];	
	
	ProgFlash(4, para_ptr);
	return	0;	
}

int CopyFlash(int argc, char *argv[])
{
	unsigned int src, dst, size;
	char tmp[10];
	
	if(argc<4)
	{
		puts("Usage : copy a1 a2 size\n");
		puts("a1 = src address, a2 = dst address, size = copy bytes (all in hex)\n");
		return -1;
	}
	
	src  = strtoul(argv[1]);
	dst  = strtoul(argv[2]);
	size = strtoul(argv[3]);
	if(src==-1||dst==-1||size==-1)
	{
		puts("give error address\n");
		return	-1;
	}	
	
	FlashRead(src, (unsigned short *)DFT_DOWNLOAD_ADDR, size);
	
	argv[1] = argv[2];
	argv[2] = tmp;
	ultostr(tmp, DFT_DOWNLOAD_ADDR);
	
	ProgFlash(4, argv);

	return 0;
}


int SetIPAddr(int argc, char *argv[])
{
	int i, j, err = 0;
	char *str;
	int ip[4];
	char ch = '.';
	
	if(argc<2)
	{
		printf("IP address : %u.%u.%u.%u\n", (IP_ADDRESS>>24)&0xff, (IP_ADDRESS>>16)&0xff, (IP_ADDRESS>>8)&0xff, IP_ADDRESS&0xff);
		return 0;
	}
	
	str = argv[1];
	
	for(j=0; j<4; j++)
	{
		if(j==3)
			ch = 0;
		i = 0;
		if(str[++i]!=ch)
			if(str[++i]!=ch)
				if(str[++i]!=ch)
					err = 1;
		str[i] = 0;
		ip[j] = strtodec(str, i);
		if(ip[j]<0||ip[j]>254||err)
		{
			puts("IP address error\n");
			return -1;
		}			
		str += i+1;
	}
	
	printf("Set IP address : %u.%u.%u.%u\n", ip[0], ip[1], ip[2], ip[3]);					
	IP_ADDRESS = (ip[0]<<24)|(ip[1]<<16)|(ip[2]<<8)|ip[3];
	
	return 0;	
}

int LoadFromUart(int argc, char *argv[])
{
	int start, time_out;
	int load_addr = DFT_DOWNLOAD_ADDR;		
		
	if(argc>1)
	{
		start = strtoul(argv[1]);
		if(load_addr>0)
			load_addr = start;						
	}
	start = load_addr;
	
#define WAIT_TIME	0x300000	
	time_out = WAIT_TIME;	
	do{
		if(kbhit())
		{
			*((U8 *)load_addr++) = getkey();
			time_out = WAIT_TIME;
		}
	}while(--time_out);
	
	printf("Received 0x%x bytes from serial port.\n", load_addr-start);
	
	return 0;
#undef	WAIT_TIME	
}

int RunProgram(int argc, char *argv[])
{
	void (*fp)(void) = (void (*)(void))DFT_DOWNLOAD_ADDR;
	
	if(argc>1)
	{
		int	p = strtoul(argv[1]);
		if(p>0)
			fp = (void (*)(void))p;			
	}
	
	printf("Run program from 0x%x, are you aure? [y/n]", fp);
	
	while(1)
	{
		if(kbhit())
		{
			int key = getkey();
			if(key=='y'||key=='Y')
			{
				putch(key);
				next_line();
				break;
			}
			if(key=='n'||key=='N')
			{
				putch(key);
				next_line();
				return 0;
			}				
		}
	}
	
	(*fp)();
	
	return 0;		
}

int MoveFlashToRam(int argc, char *argv[])
{
	int rd_addr, wr_addr, size;
	
	if(argc<4)
	{
		puts("Please enter move a1 a2 size\na1 = flash addr, a2 = ram addr\n");
		return -1;		
	}
	
	rd_addr = strtoul(argv[1]);
	wr_addr = strtoul(argv[2]);
	size    = strtoul(argv[3]);
	if(rd_addr==-1||wr_addr==-1||size==-1)
	{
		puts("Parameter erroe\n");
		return -1;
	}
	
	FlashRead(rd_addr, (U16 *)wr_addr, size);
	
	return 0;
}
/*********************************************************/
int Help(int argc, char *argv[]);

typedef int (*cmdproc)(int argc, char *argv[]);
typedef struct {
	char *cmd;
	char *hlp;
	cmdproc proc;
}CMD_STRUC;

CMD_STRUC CMD_INNER[] =
				{ 	{"help", "show help", Help},
					{"?", "= help", Help},
					{"date", "show or set current date", GetDate},
					{"time", "show or set current time", GetTime},
					{"setweek", "set weekday", SetWeek},
					{"clock", "show system running clock", SysClock},
					{"setmclk", "set system running clock", ChgSysMclk},
					{"setbaud", "set baud rate", ChgBaudRate},
					{"load", "load file to memory", LoadFile2Mem},
					{"comload", "load file from serial port", LoadFromUart},
					{"prog", "program flash", ProgFlash},
					{"boot", "boot from flash", BootLoader},
					{"ap", "auto load image flie and program flash", AutoProgFlash},
					{"copy", "copy flash from src to dst address", CopyFlash},
					{"ipcfg", "show or set IP address", SetIPAddr},					
					{"run", "run from ram", RunProgram},
					{"move", "move data from flash to ram", MoveFlashToRam},
					{NULL, NULL, NULL}
				};

int Help(int argc, char *argv[])
{
	int i;	
	
	for(i=0; CMD_INNER[i].cmd!=NULL; i++)
	{
		if(CMD_INNER[i].hlp!=NULL)
		{
			puts(CMD_INNER[i].cmd);
			puts("	------	");
			puts(CMD_INNER[i].hlp);
			putch('\n');
		}
	}
	
	return 0;
}

/*********************************************************/
static void ParseArgs(char *cmdline, int *argc, char **argv)
{
#define STATE_WHITESPACE	0
#define STATE_WORD			1

	char *c;
	int state = STATE_WHITESPACE;
	int i;

	*argc = 0;

	if(strlen(cmdline) == 0)
		return;

	/* convert all tabs into single spaces */
	c = cmdline;
	while(*c != '\0')
	{
		if(*c == '\t')
			*c = ' ';
		c++;
	}
	
	c = cmdline;
	i = 0;

	/* now find all words on the command line */
	while(*c != '\0')
	{
		if(state == STATE_WHITESPACE)
		{
			if(*c != ' ')
			{
				argv[i] = c;		//将argv[i]指向c
				i++;
				state = STATE_WORD;
			}
		}
		else
		{ /* state == STATE_WORD */
			if(*c == ' ')
			{
				*c = '\0';
				state = STATE_WHITESPACE;
			}
		}
		c++;
	}
	
	*argc = i;
#undef STATE_WHITESPACE
#undef STATE_WORD
}

static int GetCmdMatche(char *cmdline)
{
	int i;	
	
	for(i=0; CMD_INNER[i].cmd!=NULL; i++)
	{
		if(strncmp(CMD_INNER[i].cmd, cmdline, strlen(CMD_INNER[i].cmd))==0)
			return i;
	}
	
	return -1;
}

static int ParseCmd(char *cmdline, int cmd_len)
{
	int argc, num_commands;
	char *argv[MAX_ARGS];

	ParseArgs(cmdline, &argc, argv);

	/* only whitespace */
	if(argc == 0) 
		return 0;
	
	num_commands = GetCmdMatche(argv[0]);
	if(num_commands<0)
		return -1;
		
	if(CMD_INNER[num_commands].proc!=NULL)	
		CMD_INNER[num_commands].proc(argc, argv);
				
	return 0;			
}

/*********************************************************/
int main()
{
	int i, key;
	char command[MAX_CMD_LEN];		
	
	ChangePllValue(88, 6, 1);	//修改系统主频为6倍频
	PortInit();
	console_init(SERIAL_BAUD);
	
	next_line();
	puts(table_begin);	

	puts("              欢迎您，这里是 ARM7 S3C44B0X 开发引导系统 1.0\n");
	puts("                    感谢您使用华兴智能的电子产品 \n");
	puts("                            www.hxmcu.com \n");
	SysClock(0, NULL);	
	printf("Serial Baud rate is %d\n", SERIAL_BAUD);
	puts("Build date:");
	puts(__DATE__);
	putch('-');
	puts(__TIME__);
	next_line();
	puts(table_begin);
	
	SysTime.year    = 3;
	SysTime.month   = 8;
	SysTime.day     = 18;
	SysTime.weekday = 3;
	SysTime.hour    = 0x17;
	SysTime.min     = 0x09;
	SysTime.sec     = 0;
	
	RtcSetDay(&SysTime);
	RtcSetTime(&SysTime);
	
	GetDate(0, NULL);
	GetTime(0, NULL);	
	
/*************************************/
	printf("Flash ID is : %x\n", GetFlashID());

	prompt();		
	
	i = 0;
	for(;;)
	{
		if(kbhit())
		{
			key = getkey();
			if(key == BACK_KEY)
			{			
				i -= i?1:0;
				putch(key);
			}
			else
			if(key == ENTER_KEY)
			{
				int tmp;
				command[i] = 0;
				putch('\n');
				tmp = ParseCmd(command, i);
				if(tmp<0)
					puts("Bad command\n");
				prompt();
				
				i = 0;
			}
			else
			{
				if(i<MAX_CMD_LEN-1)
				{
					command[i++] = key;
					putch(key);
				}
			}				
		}
	}
}

/*********************************************************/
int pIrqStart = 0;
int pIrqHandler = 0;
int pIrqFinish = 0;