#include <stdio.h>
#include <string>

using namespace std;

int main(int argc, char **argv)
{
	if (argc != 4) {
		fprintf(stderr, "Usage: bin2h INFILE BASENAME OUTFILE\n");
		return 1;
	}

	string basename = argv[2];
	for (char &ch : basename) {
		if (!isalpha(ch) && !isdigit(ch)) {
			ch = '_';
		}
	}

	FILE *infp = fopen(argv[1], "rb");
	if (infp == nullptr) {
		perror(argv[1]);
		abort();
	}

	FILE *outfp = fopen(argv[3], "w");
	if (outfp == nullptr) {
		perror(argv[3]);
		abort();
	}

	fprintf(outfp, "// Generated by bin2h.cpp from %s. Do not edit by hand.\n", argv[1]);
	fprintf(outfp, "#include <stddef.h>\n");
	fprintf(outfp, "unsigned char _binary_%s[] = {", basename.c_str());

	size_t num_bytes = 0;
	while (!feof(infp)) {
		if (num_bytes++ % 16 == 0) {
			fprintf(outfp, "\n\t");
		}
		int ch = getc(infp);
		if (ch == -1) {
			break;
		}
		fprintf(outfp, "0x%02x, ", ch);
	}
	fprintf(outfp, "\n};\n");
	fprintf(outfp, "unsigned char *_binary_%s_data = _binary_%s;\n", basename.c_str(), basename.c_str());
	fprintf(outfp, "size_t _binary_%s_size = sizeof(_binary_%s);\n", basename.c_str(), basename.c_str());
	return 0;
}
