/************************************************************\
* bf2c.c                               timdoug -- 2008-02-02 *
* ------                                                     *
* Quick and dirty Brainfuck to C converter                   *
* spec courtesy of wikipedia                                 *
* licenced under GNU GPL                                     *
*                                                            *
* usage: gcc bf2c.c -o bf2c                                  *
*        ./bf2c [memsize] <primes.b >primes.c                *
*        gcc -O3 primes.c -o primes                          *
*                                                            *
* note: for huge programs (>50k instructions), you may need  *
*       to compile with -O0 to get reasonable compile times. *
*                                                            *
* this thing's a screamer:              (using gcc -O3)      *
* ~10x faster than the interpreter running primes.b (to 100) *
*  ~3x faster than the interpreter running hanoi.bf          *
* (although a _lot_ slower than wbf2c...)                    *
\************************************************************/

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

#define DEFAULT_MEM_SIZE 30000

int main(int argc, char *argv[])
{
	long mem = DEFAULT_MEM_SIZE;
	char c;
	
	if (argv[1])
		mem = atol(argv[1]);
	
	printf("#include <stdlib.h>\n#include <stdio.h>\n");
	printf("int main(void) {\nunsigned char* ptr;\n");
	printf("ptr = malloc(%ld);\n", mem);
	
	while ((c = getchar()) != EOF) {
		switch (c) {
			case '>': printf("ptr++;\n"); break;
			case '<': printf("ptr--;\n"); break;
			case '+': printf("(*ptr)++;\n"); break;
			case '-': printf("(*ptr)--;\n"); break;
			case '.': printf("putchar(*ptr);\n"); break;
			case ',': printf("*ptr = getchar();\n"); break;
			case '[': printf("while (*ptr) {\n"); break;
			case ']': printf("}\n"); break;
		}
	}
	
	printf("return 0;\n}");
	return 0;
}

