#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
const int verbose = 1;

int
convert_grob_to_xbm(FILE* fGrob, FILE* fXbm, const char* xbm_name)
{
    int width, height;
    int byte;
    int first = 1;
    if (fscanf(fGrob, "GROB %d %d", &width, &height) != 2) {
	fputs("Error: input file is not an HP48 grob image\n", stderr);
	return -1;
    }
    fprintf(fXbm, "#define %s_width %d\n", xbm_name, width);
    fprintf(fXbm, "#define %s_height %d\n", xbm_name, height);
    fprintf(fXbm, "static char %s_bits[] = {\n", xbm_name);

    while ((byte = getc(fGrob)) == ' ')
	/* NOP */ ;
    if (ungetc(byte, fGrob) == EOF) {
	perror("Error: could'nt ungetc");
	return -1;
    }
    while (! feof(fGrob) && ! ferror(fGrob)) {
	char byte[2];
	if (fread(byte, 1, 2, fGrob) != 2) {
	    if (! feof(fGrob)) {
		perror("Error: can't read input file");
		return -1;
	    } else
		break;
	}
	assert(isxdigit(byte[0]));
	assert(isxdigit(byte[1]));
	if (! first)
	    fputs(", ", fXbm);
	else
	    first = !first;
	fprintf(fXbm, "0x%c%c", byte[1], byte[0]);
    }

    fputs("\n};\n", fXbm);
    return 0;
}

int
main(int argc, char** argv)
{
    int res = convert_grob_to_xbm(stdin, stdout, "my_xbm");
    if (res < 0 && verbose)
	fputs("Error while converting\n", stderr);
    return res < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}
