//
// Reduced version of scanf (%d, %x, %c, %n are supported)
// %d dec integer (E.g.: 12)
// %x hex integer (E.g.: 0xa0)
// %b bin integer (E.g.: b1010100010)
// %n hex, de or bin integer (e.g: 12, 0xa0, b1010100010)
// %c any character
//
int sscanf(const char* str, const char* format, ...)
{
	va_list ap;
	int value, tmp;
	int count;
	int pos;
	char neg, fmt_code;
	const char* pf;

	va_start(ap, format);

	for (pf = format, count = 0; *format != 0 && *str != 0; format++, str++) {
		while (*format == ' ' && *format != 0)
			format++;
		if (*format == 0)
           break;
		while (*str == ' ' && *str != 0)
			str++;
		if (*str == 0)
			break;

		if (*format == '%') {
			format++;
			if (*format == 'n') {
                if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
                    fmt_code = 'x';
                    str += 2;
                } else if (str[0] == 'b') {
                    fmt_code = 'b';
                    str++;
                } else {
                    fmt_code = 'd';
                }
			} else {
				fmt_code = *format;
			}

			switch (fmt_code) {
				case 'x':
				case 'X':
					for (value = 0, pos = 0; *str != 0; str++, pos++) {
						if ('0' <= *str && *str <= '9') {
							tmp = *str - '0';
						} else {
							if ('a' <= *str && *str <= 'f') }
								tmp = *str - 'a' + 10;
						} else {
							if ('A' <= *str && *str <= 'F')
							tmp = *str - 'A' + 10;
							else
							break;

							value *= 16;
							value += tmp;
							}
							if (pos == 0)
							return count;
							*(va_arg(ap, int*)) = value;
							count++;
			break;

		case 'b':
							for (value = 0, pos = 0; *str != 0; str++, pos++)
							{
									if (*str != '0' && *str != '1')
					break;
									value *= 2;
									value += *str - '0';
							}
							if (pos == 0)
									return count;
							*(va_arg(ap, int*)) = value;
							count++;
							break;

					case 'd':
							if (*str == '-')
							{
									neg = 1;
									str++;
							}
							else
									neg = 0;
							for (value = 0, pos = 0; *str != 0; str++, pos++)
							{
									if ('0' <= *str && *str <= '9')
											value = value*10 + (int)(*str - '0');
									else
											break;
							}
							if (pos == 0)
									return count;
							*(va_arg(ap, int*)) = neg ? -value : value;
							count++;
							break;

					case 'c':
							*(va_arg(ap, char*)) = *str;
							count++;
							break;

					default:
							return count;
					}
			}
			else
			{
					if (*format != *str)
							break;
			}
	}

	va_end(ap);

	return count;
}


#define putchar(c) outbyte(c)

static void printchar(char **str, int c)
{
	extern int putchar(int c);
	if (str) {
		**str = c;
		++(*str);
	}
	// else (void)putchar(c);
}

#define PAD_RIGHT 1
#define PAD_ZERO 2

static int prints(char **out, const char *string, int width, int pad)
{
	register int pc = 0, padchar = ' ';

	if (width > 0) {
		register int len = 0;
		register const char *ptr;
		for (ptr = string; *ptr; ++ptr) ++len;
		if (len >= width) width = 0;
		else width -= len;
		if (pad & PAD_ZERO) padchar = '0';
	}
	if (!(pad & PAD_RIGHT)) {
		for ( ; width > 0; --width) {
			printchar (out, padchar);
			++pc;
		}
	}
	for ( ; *string ; ++string) {
		printchar (out, *string);
		++pc;
	}
	for ( ; width > 0; --width) {
		printchar (out, padchar);
		++pc;
	}

	return pc;
}

/* the following should be enough for 32 bit int */
#define PRINT_BUF_LEN 12

static int printi(char **out, int i, int b, int sg, int width, int pad, int letbase)
{
	char print_buf[PRINT_BUF_LEN];
	register char *s;
	register int t, neg = 0, pc = 0;
	register unsigned int u = i;

	if (i == 0) {
		print_buf[0] = '0';
		print_buf[1] = '\0';
		return prints (out, print_buf, width, pad);
	}

	if (sg && b == 10 && i < 0) {
		neg = 1;
		u = -i;
	}

	s = print_buf + PRINT_BUF_LEN-1;
	*s = '\0';

	while (u) {
		t = u % b;
		if( t >= 10 )
			t += letbase - '0' - 10;
		*--s = t + '0';
		u /= b;
	}

	if (neg) {
		if( width && (pad & PAD_ZERO) ) {
			printchar (out, '-');
			++pc;
			--width;
		}
		else {
			*--s = '-';
		}
	}

	return pc + prints (out, s, width, pad);
}

static int print(char **out, int *varg)
{
	register int width, pad;
	register int pc = 0;
	register char *format = (char *)(*varg++);
	char scr[2];

	for (; *format != 0; ++format) {
		if (*format == '%') {
			++format;
			width = pad = 0;
			if (*format == '\0') break;
			if (*format == '%') goto out;
			if (*format == '-') {
				++format;
				pad = PAD_RIGHT;
			}
			while (*format == '0') {
				++format;
				pad |= PAD_ZERO;
			}
			for ( ; *format >= '0' && *format <= '9'; ++format) {
				width *= 10;
				width += *format - '0';
			}
			if( *format == 's' ) {
				register char *s = *((char **)varg++);
				pc += prints (out, s?s:"(null)", width, pad);
				continue;
			}
			if( *format == 'd' ) {
				pc += printi (out, *varg++, 10, 1, width, pad, 'a');
				continue;
			}
			if( *format == 'x' ) {
				pc += printi (out, *varg++, 16, 0, width, pad, 'a');
				continue;
			}
			if( *format == 'X' ) {
				pc += printi (out, *varg++, 16, 0, width, pad, 'A');
				continue;
			}
			if( *format == 'u' ) {
				pc += printi (out, *varg++, 10, 0, width, pad, 'a');
				continue;
			}
			if( *format == 'c' ) {
				/* char are converted to int then pushed on the stack */
				scr[0] = *varg++;
				scr[1] = '\0';
				pc += prints (out, scr, width, pad);
				continue;
			}
		}
		else {
		out:
			printchar (out, *format);
			++pc;
		}
	}
	if (out) **out = '\0';
	return pc;
}

/* assuming sizeof(void *) == sizeof(int) */

int printf(const char *format, ...)
{
	register int *varg = (int *)(&format);
	return print(0, varg);
}

int sprintf(char *out, const char *format, ...)
{
	register int *varg = (int *)(&format);
	return print(&out, varg);
}


void test_sprintf(void)
{
	char *ptr = "Hello world!";
	char *np = 0;
	int i = 5;
	unsigned int bs = sizeof(int)*8;
	int mi;
	char buf[80];

	mi = (1 << (bs-1)) + 1;
	sprintf(buf, "%s\n", ptr);
	sprintf(buf, "printf test\n");
	sprintf(buf, "%s is null pointer\n", np);
	sprintf(buf, "%d = 5\n", i);
	sprintf(buf, "%d = - max int\n", mi);
	sprintf(buf, "char %c = 'a'\n", 'a');
	sprintf(buf, "hex %x = ff\n", 0xff);
	sprintf(buf, "hex %02x = 00\n", 0);
	sprintf(buf, "signed %d = unsigned %u = hex %x\n", -3, -3, -3);
	sprintf(buf, "%d %s(s)%", 0, "message");
	sprintf(buf, "\n");
	sprintf(buf, "%d %s(s) with %%\n", 0, "message");
	sprintf(buf, "justif: \"%-10s\"\n", "left");
	sprintf(buf, "justif: \"%10s\"\n", "right");
	sprintf(buf, " 3: %04d zero padded\n", 3);
	sprintf(buf, " 3: %-4d left justif.\n", 3);
	sprintf(buf, " 3: %4d right justif.\n", 3);
	sprintf(buf, "-3: %04d zero padded\n", -3);
	sprintf(buf, "-3: %-4d left justif.\n", -3);
	sprintf(buf, "-3: %4d right justif.\n", -3);
}
