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

int main(int argc, char *argv[])
{
	FILE *fi, *fo;
	char buf[256];

	if (argc != 3) {
		printf("usage:\n%s <carthw.cfg> <carthw.c>\n", argv[0]);
		return 1;
	}

	fi = fopen(argv[1], "r");
	fo = fopen(argv[2], "w");
	if (fi == NULL || fo == NULL) {
		printf("fopen failed\n");
		return 1;
	}

	fprintf(fo, "/* generated by %s, do not modify */\n", argv[0]);
	fprintf(fo, "static const char builtin_carthw_cfg[] =\n");

	while ((fgets(buf, sizeof(buf), fi)))
	{
		char bufd[256];
		char *d = bufd, *p = buf;
		int quote = 0;

		while (*p && isspace(*p))
			p++;

		if (*p == 0 || *p == '#')
			continue;

		/* section names not needed */
		if (*p == '[')
			strcpy(p, "[]");

		for (; *p != 0; p++) {
			if (!quote && isspace(*p))
				continue;
			if (*p == '"') {
				quote = !quote;
				*d++ = '\\';
			}
			*d++ = *p;
		}
		*d = 0;


		fprintf(fo, "  \"%s\\n\"\n", bufd);
	}

	fprintf(fo, ";\n");

	fclose(fi);
	fclose(fo);

	return 0;
}
