//#include <stdio.h>
#include <stdlib.h>
//#include <string.h>

#define	NUM_ELEMENTS	100
#define	NUM_RUNS		1000

char sein(void)
{
	volatile char *pUART_stat = (char*)0x80000008;
	volatile char *pUART_data = (char*)0x80000004;

	while(!(0x10 & *pUART_stat));

	return *pUART_data;
}

void saus(char c)
{
	volatile char *pUART_stat = (char*)0x80000008;
	volatile char *pUART_data = (char*)0x80000004;

	while((0x02 & *pUART_stat) != 0);

	*pUART_data = c;
}

int sputs(char *pStr)
{
	char *start;
	start = pStr;

	while(*pStr)
		saus(*(pStr++));

	return pStr - start;
}

void print_byte(char byte)
{
	int i;
	unsigned char c, nibble;

	for (i=0; i < 2; i++)
	{
		nibble = (char)((byte >> 4) & 0xF);
		byte <<= 4;

		if (nibble < 10)
			c = nibble + '0';
		else
			c = nibble + 'A' - 10;

		saus(c);
	}
}

void print_word(int word)
{
	int i;
	unsigned char c, nibble;

	for (i=0; i < 4; i++)
	{
		c = (char) (word >> 24);
		print_byte(c);
		word <<= 8;
	}
}

int main (void)
{
	int cnt, i, j;
	int mix, *pReg = (int*)0x80000000;
	volatile char *pUART_data = (char*)0x80000004;
	volatile char *pUART_ctrl = (char*)0x80000008;
	volatile char *pUART_baud = (char*)0x80000009;
	char msg[] = "MIPS R3000 CPU\r\nMul/Div Test\r\n";
	int s1, s2, sp, st;

	div_t div_res;

	*pUART_baud = 0x35;
	*pUART_ctrl = 0x55;

	srand(0x19701031);

	sputs(msg);

	cnt = 0;
	while(1)
	{
		for (i=0; i < 1000; i++)
		{
			for (j=1; j < 1000; j++)
			{
				mix = (int)rand();
				mix = (mix << 8) ^ (mix << 16);
				s1 = (int)rand() ^ mix;
				mix = (int)rand();
				mix = (mix << 8) ^ (mix << 16);
				s2 = (int)rand() ^ mix;
	//			s1 = i;
	//			s2 = j;

				div_res = div(s1, s2);

	//			print_word(s1);
	//			sputs(" / ");
	//			print_word(s2);
	//			sputs(" = ");
	//			print_word(div_res.quot);
	//			sputs(" R: ");
	//			print_word(div_res.rem);
	//			sputs(" -- ");

				sp = s2*div_res.quot;
				st = div_res.rem + sp;
				if (st != s1)
				{
					sputs("Failed: ");
					sputs("d*quot = ");
					print_word(sp);
					sputs("\r\n");
					return -1;
				}
			}
		}
		sputs("Iteration ");
		print_word(cnt++);
		sputs(": Passed\r\n");
	}
}

