#include <stdarg.h>
#include "stdlib.h"
#include "dream.h"

// A blank atexit() function to let you call your main, main()
void atexit() { }

// Everything that follows is parts of various standard libraries and I'm
// fairly sure I don't need them, but I don't properly know how to set up
// my environment. >:(

/* vsprintf.c -- Lars Wirzenius & Linus Torvalds. */
/*
 * Wirzenius wrote this portably, Torvalds fucked it up :-)
 */
/* Then Mike "Tursi" Brent screwed around with it ;) */

#define tolower(c)  ( (c)-'A'+'a' )
#define toupper(c)  ( (c)-'a'+'A' )
#define is_digit(c)	((c) >= '0' && (c) <= '9')
#define isdigit(c)	((c) >= '0' && (c) <= '9')
#define isxdigit(c)	(isdigit(c) || ((toupper(c)>='A') && (toupper(c)<='F')))
#define islower(c)  ((c) >= 'a' && (c) <= 'z')

char return_hex_char (uint8 val);
uint32 return_1_byte (uint32 val, int position);
char return_hex_char_32 (uint32 val);

void free (void *){ }

void *malloc(unsigned int size) {
	/* starting a meg into ram */
	static void *ptr = (void *) (0x8c100000);
	void *tmp = ptr;
	
	(char *)ptr += size;
	if ( ((int)ptr) & 3 ) {
		(char *)ptr += 4 - (((int)ptr) & 3);
	}
	
	return tmp;
}

unsigned long simple_strtoul(const char *cp,char **endp,unsigned int base)
{
	unsigned long result = 0,value;

	if (!base) {
		base = 10;
		if (*cp == '0') {
			base = 8;
			cp++;
			if ((*cp == 'x') && isxdigit(cp[1])) {
				cp++;
				base = 16;
			}
		}
	}
	while (isxdigit(*cp) && (value = isdigit(*cp) ? *cp-'0' : (islower(*cp)
	    ? toupper(*cp) : *cp)-'A'+10) < base) {
		result = result*base + value;
		cp++;
	}
	if (endp)
		*endp = (char *)cp;
	return result;
}

static int skip_atoi(const char **s)
{
	int i=0;

	while (is_digit(**s))
		i = i*10 + *((*s)++) - '0';
	return i;
}

#define ZEROPAD	1		/* pad with zero */
#define SIGN	2		/* unsigned/signed long */
#define PLUS	4		/* show plus */
#define SPACE	8		/* space if plus */
#define LEFT	16		/* left justified */
#define SPECIAL	32		/* 0x */
#define LARGE	64		/* use 'ABCDEF' instead of 'abcdef' */

#define do_div(n,base) ({ int __res; __res = ((unsigned long) n) % (unsigned) base; n = ((unsigned long) n) / (unsigned) base; __res; })

static char * number(char * str, long num, int base, int size, int precision
	,int type)
{
	char c,sign,tmp[66];
	const char *digits="0123456789abcdefghijklmnopqrstuvwxyz";
	int i;

	if (type & LARGE)
		digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	if (type & LEFT)
		type &= ~ZEROPAD;
	if (base < 2 || base > 36)
		return 0;
	c = (type & ZEROPAD) ? '0' : ' ';
	sign = 0;
	if (type & SIGN) {
		if (num < 0) {
			sign = '-';
			num = -num;
			size--;
		} else if (type & PLUS) {
			sign = '+';
			size--;
		} else if (type & SPACE) {
			sign = ' ';
			size--;
		}
	}
	if (type & SPECIAL) {
		if (base == 16)
			size -= 2;
		else if (base == 8)
			size--;
	}
	i = 0;
	if (num == 0)
		tmp[i++]='0';
	else while (num != 0)
		tmp[i++] = digits[do_div(num,base)];
	if (i > precision)
		precision = i;
	size -= precision;
	if (!(type&(ZEROPAD+LEFT)))
		while(size-->0)
			*str++ = ' ';
	if (sign)
		*str++ = sign;
	if (type & SPECIAL)
		if (base==8)
			*str++ = '0';
		else if (base==16) {
			*str++ = '0';
			*str++ = digits[33];
		}
	if (!(type & LEFT))
		while (size-- > 0)
			*str++ = c;
	while (i < precision--)
		*str++ = '0';
	while (i-- > 0)
		*str++ = tmp[i];
	while (size-- > 0)
		*str++ = ' ';
	return str;
}

int vsprintf(char *buf, const char *fmt, va_list args)
{
	int len;
	unsigned long num;
	int i, base;
	char * str;
	const char *s;

	int flags;		/* flags to number() */

	int field_width;	/* width of output field */
	int precision;		/* min. # of digits for integers; max
				   number of chars for from string */
	int qualifier;		/* 'h', 'l', or 'L' for integer fields */

	for (str=buf ; *fmt ; ++fmt) {
		if (*fmt != '%') {
			*str++ = *fmt;
			continue;
		}
			
		/* process flags */
		flags = 0;
		repeat:
			++fmt;		/* this also skips first '%' */
			switch (*fmt) {
				case '-': flags |= LEFT; goto repeat;
				case '+': flags |= PLUS; goto repeat;
				case ' ': flags |= SPACE; goto repeat;
				case '#': flags |= SPECIAL; goto repeat;
				case '0': flags |= ZEROPAD; goto repeat;
				}
		
		/* get field width */
		field_width = -1;
		if (is_digit(*fmt))
			field_width = skip_atoi(&fmt);
		else if (*fmt == '*') {
			++fmt;
			/* it's the next argument */
			field_width = va_arg(args, int);
			if (field_width < 0) {
				field_width = -field_width;
				flags |= LEFT;
			}
		}

		/* get the precision */
		precision = -1;
		if (*fmt == '.') {
			++fmt;	
			if (is_digit(*fmt))
				precision = skip_atoi(&fmt);
			else if (*fmt == '*') {
				++fmt;
				/* it's the next argument */
				precision = va_arg(args, int);
			}
			if (precision < 0)
				precision = 0;
		}

		/* get the conversion qualifier */
		qualifier = -1;
		if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L') {
			qualifier = *fmt;
			++fmt;
		}

		/* default base */
		base = 10;

		switch (*fmt) {
		case 'c':
			if (!(flags & LEFT))
				while (--field_width > 0)
					*str++ = ' ';
			*str++ = (unsigned char) va_arg(args, int);
			while (--field_width > 0)
				*str++ = ' ';
			continue;

		case 's':
			s = va_arg(args, char *);
			if (!s)
				s = "<NULL>";

			len = strnlen(s, precision);

			if (!(flags & LEFT))
				while (len < field_width--)
					*str++ = ' ';
			for (i = 0; i < len; ++i)
				*str++ = *s++;
			while (len < field_width--)
				*str++ = ' ';
			continue;

		case 'p':
			if (field_width == -1) {
				field_width = 2*sizeof(void *);
				flags |= ZEROPAD;
			}
			str = number(str,
				(unsigned long) va_arg(args, void *), 16,
				field_width, precision, flags);
			continue;


		case 'n':
			if (qualifier == 'l') {
				long * ip = va_arg(args, long *);
				*ip = (str - buf);
			} else {
				int * ip = va_arg(args, int *);
				*ip = (str - buf);
			}
			continue;

		/* integer number formats - set up the flags and "break" */
		case 'o':
			base = 8;
			break;

		case 'X':
			flags |= LARGE;
		case 'x':
			base = 16;
			break;

		case 'd':
		case 'i':
			flags |= SIGN;
		case 'u':
			break;

		default:
			if (*fmt != '%')
				*str++ = '%';
			if (*fmt)
				*str++ = *fmt;
			else
				--fmt;
			continue;
		}
		if (qualifier == 'l')
			num = va_arg(args, unsigned long);
		else if (qualifier == 'h')
			if (flags & SIGN)
				num = va_arg(args, short);
			else
				num = va_arg(args, unsigned short);
		else if (flags & SIGN)
			num = va_arg(args, int);
		else
			num = va_arg(args, unsigned int);
		str = number(str, num, base, field_width, precision, flags);
	}
	*str = '\0';
	return str-buf;
}

int sprintf(char * buf, const char *fmt, ...)
{
	va_list args;
	int i;

	va_start(args, fmt);
	i=vsprintf(buf,fmt,args);
	va_end(args);
	return i;
}

// strings

char * ___strtok3 = (char *)NULL;

char * strcpy(char * dest,const char *src)
{
	char *tmp = dest;

	while ((*dest++ = *src++) != '\0')
		/* nothing */;
	return tmp;
}

char * strncpy(char * dest,const char *src,size_t count)
{
	char *tmp = dest;

	while (count-- && (*dest++ = *src++) != '\0')
		/* nothing */;

	return tmp;
}

char * strcat(char * dest, const char * src)
{
	char *tmp = dest;

	while (*dest)
		dest++;
	while ((*dest++ = *src++) != '\0')
		;

	return tmp;
}

char * strncat(char *dest, const char *src, size_t count)
{
	char *tmp = dest;

	if (count) {
		while (*dest)
			dest++;
		while ((*dest++ = *src++)) {
			if (--count == 0) {
				*dest = '\0';
				break;
			}
		}
	}

	return tmp;
}

int strcmp(const char * cs,const char * ct)
{
	register signed char __res;

	while (1) {
		if ((__res = *cs - *ct++) != 0 || !*cs++)
			break;
	}

	return __res;
}

int strncmp(const char * cs,const char * ct,size_t count)
{
	register signed char __res = 0;

	while (count) {
		if ((__res = *cs - *ct++) != 0 || !*cs++)
			break;
		count--;
	}

	return __res;
}

char * strchr(const char * s, int c)
{
	for(; *s != (char) c; ++s)
		if (*s == '\0')
			return (char *)NULL;
	return (char *) s;
}

char * strrchr(const char * s, int c)
{
       const char *p = s + strlen(s);
       do {
           if (*p == (char)c)
               return (char *)p;
       } while (--p >= s);
       return (char *)NULL;
}

size_t strlen(const char * s)
{
	const char *sc;

	for (sc = s; *sc != '\0'; ++sc)
		/* nothing */;
	return sc - s;
}

size_t strnlen(const char * s, size_t count)
{
	const char *sc;

	for (sc = s; count-- && *sc != '\0'; ++sc)
		/* nothing */;
	return sc - s;
}

size_t strspn(const char *s, const char *accept)
{
	const char *p;
	const char *a;
	size_t count = 0;

	for (p = s; *p != '\0'; ++p) {
		for (a = accept; *a != '\0'; ++a) {
			if (*p == *a)
				break;
		}
		if (*a == '\0')
			return count;
		++count;
	}

	return count;
}

char * strpbrk(const char * cs,const char * ct)
{
	const char *sc1,*sc2;

	for( sc1 = cs; *sc1 != '\0'; ++sc1) {
		for( sc2 = ct; *sc2 != '\0'; ++sc2) {
			if (*sc1 == *sc2)
				return (char *) sc1;
		}
	}
	return (char *)NULL;
}

char * strtok(char * s,const char * ct)
{
	char *sbegin, *send;

	sbegin  = s ? s : ___strtok3;
	if (!sbegin) {
		return (char *)NULL;
	}
	sbegin += strspn(sbegin,ct);
	if (*sbegin == '\0') {
		___strtok3 = (char *)NULL;
		return((char *)NULL );
	}
	send = strpbrk( sbegin, ct);
	if (send && *send != '\0')
		*send++ = '\0';
	___strtok3 = send;
	return (sbegin);
}

void * memset(void * s,int c,size_t count)
{
	char *xs = (char *) s;

	while (count--)
		*xs++ = c;

	return s;
}

void * memset16(void * s,uint16 c,size_t count)
{
	uint16 *xs = (uint16 *) s;

	while (count--)
		*xs++ = c;

	return s;
}

void * memset32(void * s,uint32 c,size_t count)
{
	uint32 *xs = (uint32 *) s;

	while (count--)
		*xs++ = c;

	return s;
}

char * bcopy(const char * src, char * dest, int count)
{
	char *tmp = dest;

	while (count--)
		*tmp++ = *src++;

	return dest;
}

void * memcpy(void * dest,const void *src,size_t count)
{
	char *tmp = (char *) dest, *s = (char *) src;

	while (count--)
		*tmp++ = *s++;

	return dest;
}

void * memmove(void * dest,const void *src,size_t count)
{
	char *tmp, *s;

	if (dest <= src) {
		tmp = (char *) dest;
		s = (char *) src;
		while (count--)
			*tmp++ = *s++;
		}
	else {
		tmp = (char *) dest + count;
		s = (char *) src + count;
		while (count--)
			*--tmp = *--s;
		}

	return dest;
}

int memcmp(const void * cs,const void * ct,size_t count)
{
	const unsigned char *su1, *su2;
	signed char res = 0;

	for( su1 = (const unsigned char *)cs, su2 = (const unsigned char *)ct; 0 < count; ++su1, ++su2, count--)
		if ((res = *su1 - *su2) != 0)
			break;
	return res;
}

/*
 * find the first occurrence of byte 'c', or 1 past the area if none
 */
void * memscan(void * addr, int c, size_t size)
{
	unsigned char * p = (unsigned char *) addr;

	while (size) {
		if (*p == c)
			return (void *) p;
		p++;
		size--;
	}
  	return (void *) p;
}

char * strstr(const char * s1,const char * s2)
{
	int l1, l2;

	l2 = strlen(s2);
	if (!l2)
		return (char *) s1;
	l1 = strlen(s1);
	while (l1 >= l2) {
		l1--;
		if (!memcmp(s1,s2,l2))
			return (char *) s1;
		s1++;
	}
	return (char *)NULL;
}

FILE* fopen (const char * filename, const char * mode) {
	// this currently only supports file reading, not writing
	return (FILE *)cd_open (filename, O_RDONLY);
}

size_t fwrite ( const void * buffer, size_t size, size_t count, FILE * stream ) {
	// currently unsupported
}

long int fseek ( FILE * stream , long offset , int origin ) {
	return cd_lseek (*stream, offset, origin);
}

int  fclose (FILE * stream) {
	return cd_close (*stream);
}

long int ftell ( FILE * stream ) {
	return cd_tell (*stream);
} 

int  fread (void * buffer, size_t size, size_t count, FILE * stream) {
	int total_size = size * count;
	return cd_read (*stream, buffer,total_size); 
}

void dc_print (char * stri) {
	vid_clear (0,0,0);
	draw_string (20, 20, 255, stri);
	//bfont_draw_str (vram_s + 320 * 20 + 20, 320, stri);
	timer_sleep (2000);
}

void dc_print_opcode (uint8 opcode) {
	vid_clear (0,0,0);
	char ops[6];
	uint8 op[2];
	uint8 opcode2 = opcode;
	uint8 opcode3 = opcode;
	uint8 opcode1;
	//op[0] = opcode;
	//op[1] = opcode;
	opcode1 = (opcode2 << 4);
	op[1] = (opcode1 >> 4);
	op[0] = (opcode3 >> 4);
	
	ops[0] = return_hex_char (op[0]);
	ops[1] = return_hex_char (op[1]);

	ops[2] = ' ';
	ops[3] = 'O';
	ops[4] = 'P';
	ops[5] = '\0';
	draw_string (20, 20, 255, ops);
	//bfont_draw_str (vram_s + 320 * 20 + 20, 320, stri);
	timer_sleep (750);
}

void print_uint32 (uint32 val) {
	vid_clear (0,0,0);
	uint32 temp, temp2;
	char val_32[9];
	
	for (int i=0; i < 8; i++) {
		temp2 = val;
		temp = return_1_byte (temp2, i);
		val_32[7-i] = return_hex_char_32 (temp); 
	}
	val_32[8] = '\0';
	draw_string (20, 20, 255, val_32);
	timer_sleep (3000);
}

void print_num (uint32 val, uint32 xval, uint32 yval) {
	//vid_clear (0,0,0);
	uint32 temp, temp2;
	char val_32[9];
	
	for (int i=0; i < 8; i++) {
		temp2 = val;
		temp = return_1_byte (temp2, i);
		val_32[7-i] = return_hex_char_32 (temp); 
	}
	val_32[8] = '\0';
	draw_string (xval, yval, 255, val_32);
	//timer_sleep (3000);
}

void dc_sleep (uint32 time) {
	timer_sleep (time);
}

uint32 return_1_byte (uint32 val, int position) {
	uint32 temp;

	switch (position) {
		case 0: temp = (val << 28);
				temp = (temp >> 28);
				return temp;
				break;

		case 1:	temp = (val << 24);
				temp = (temp >> 28);
				return temp;
				break;

		case 2: temp = (val << 20);
				temp = (temp >> 28);
				return temp;
				break;

		case 3: temp = (val << 16);
				temp = (temp >> 28);
				return temp;
				break;

		case 4:	temp = (val << 12);
				temp = (temp >> 28);
				return temp;
				break;

		case 5: temp = (val << 8);
				temp = (temp >> 28);
				return temp;
				break;

		case 6: temp = (val << 4);
				temp = (temp >> 28);
				return temp;
				break;

		case 7:	temp = (val >> 28);
				return temp;
				break;
	}
	return (0xFFFFFFFF);

}

char return_hex_char (uint8 val) {
	switch (val) {
		case 0x00:
			return '0';
			break;
		case 0x01:
			return '1';
			break;
		case 0x02:
			return '2';
			break;
		case 0x03:
			return '3';
			break;
		case 0x04:
			return '4';
			break;
		case 0x05:
			return '5';
			break;
		case 0x06:
			return '6';
			break;
		case 0x07:
			return '7';
			break;
		case 0x08:
			return '8';
			break;
		case 0x09:
			return '9';
			break;
		case 0x0A:
			return 'A';
			break;
		case 0x0B:
			return 'B';
			break;
		case 0x0C:
			return 'C';
			break;
		case 0x0D:
			return 'D';
			break;
		case 0x0E:
			return 'E';
			break;
		case 0x0F:
			return 'F';
			break;
		}
		return 'Z';		
}


char return_hex_char_32 (uint32 val) {
	switch (val) {
		case 0x00000000:
			return '0';
			break;
		case 0x00000001:
			return '1';
			break;
		case 0x00000002:
			return '2';
			break;
		case 0x00000003:
			return '3';
			break;
		case 0x00000004:
			return '4';
			break;
		case 0x00000005:
			return '5';
			break;
		case 0x00000006:
			return '6';
			break;
		case 0x00000007:
			return '7';
			break;
		case 0x00000008:
			return '8';
			break;
		case 0x00000009:
			return '9';
			break;
		case 0x0000000A:
			return 'A';
			break;
		case 0x0000000B:
			return 'B';
			break;
		case 0x0000000C:
			return 'C';
			break;
		case 0x0000000D:
			return 'D';
			break;
		case 0x0000000E:
			return 'E';
			break;
		case 0x0000000F:
			return 'F';
			break;
		}
		return 'Z';		
}
