#include <stdio.h>
#include <stdlib.h>

int main( int argc, char *argv[] ){
    int c;
    char *code[256];
    int length;
    FILE *fp;

    if( argc < 2 ){
        fprintf(stderr,"Usage: %s sourcefile\n", argv[0] );
        return EXIT_FAILURE;
    }
    if( (fp = fopen( argv[1], "r" )) == NULL ){
        fprintf(stderr,"Error: %s cannot opened\n", argv[1] );
        return EXIT_FAILURE;
    }
    if( !argv[2] || (length = atoi( argv[2] )) <= 0 ){
        length = 256;
    }

    for (c = 0; c < 256; c++) code[c] = NULL;
    code['>'] = "sp++;";
    code['<'] = "sp--;";
    code['+'] = "(*sp)++;";
    code['-'] = "(*sp)--;";
    code['.'] = "putchar(*sp);";
    code[','] = "*sp = getchar();";
    code['['] = "while(*sp){";
    code[']'] = "}";

    puts("#include <stdio.h>");
    puts("#include <stdlib.h>");
    printf("#define DATA_LEN %d\n", length);
    puts("char code[DATA_LEN];");
    puts("int main (void){");
    puts("   char *sp = code;");
    while( (c=fgetc( fp )) != EOF ) if (code[c]) printf("%s\n", code[c]); 
    puts("   return EXIT_SUCCESS;");
    puts("}");
    fclose(fp);
    return EXIT_SUCCESS;
}
