/* Tilem ROM Make v1.0
 * Copyright (C) 2001 Solignac Julien <x1cygnus@xcalc.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

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

void updatedisp(char z) {
	printf("[0x%02X]", z);
	fflush(stdout);
	if ((z % 8) == 7)
		printf("\n");
}

int main (int argc, char *argv[])
{
	FILE *tib, *rom;
	char xline[76], tmpx[3] = {0x00, 0x00, 0x00};
	unsigned char z, k, j;
	int i;

	puts("Tilem Rom Make v1.0 - (C) 2000 Solignac Julien");
	puts("THIS PROGRAM COMES WITH ABSOLUTLY NO WARRANTY");
	puts("PLEASE READ THE DOCUMENTATION FOR DETAILS");
	if (argc != 2) {
		puts("Usage: tcc file");
		exit(0);
	}

	if ((!(tib = fopen(argv[1], "r"))) || (!(rom = fopen("rom.bin", "w")))) {
		fprintf(stderr, "File IO Error\n");
		exit(-1);
	}
	puts("Writing ROM pages:");

	for (z = 0x00; z <= 0x1F; z++) {

		fread(xline, 1, 16, tib);
		if (xline[15] == 0x0D) fgetc(tib);
		xline[13] = '\0';
		k = strtol(xline + 11, NULL, 16);

		while (z < k) {
			updatedisp(z);

			for (i = 0; i < 0x4000; i++)
				putc(0xFF, rom);
			z++;
		}

		updatedisp(z);
		for (i = 0; i < 0x200; i++) {
			fread(xline, 1, 76, tib);
			if (xline[75] == 0x0D) fgetc(tib);

			for (j = 0; j < 32; j++) {
				tmpx[0] = xline[2 * j + 9];
				tmpx[1]	= xline[2 * j + 9 + 1];
				putc(strtol(tmpx, NULL, 16), rom);
			}
		}
	}

	puts("Done");

	fclose(rom);
	fclose(tib);

	return(0);
}
