
// VB ROM-image Padder
// (c) 2003 Amos "RunnerPack" Bieler.  All rights reserved.

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

#define HEADER_SIZE 544

int main(int argc, char *argv[])
{
	FILE *fin, *fout;		// File pointers
	char t[13] = "temptemp.tmp";	// Temporary filename (if output name isn't specified)
	long size, new_size;		// Current and desired sizes of the file.
	long i;				// Miscellaneous iterator

	// If there aren't enough arguments, tell the user how to use.
	if (argc < 3) {
		printf("----------------------\nVB ROM-image Padder\n(c) 2003 Amos \"RunnerPack\" Bieler\n----------------------\n");
		printf("Usage: padromvb.exe infile n [outfile]\n\n");
		printf("The size of \"outfile\" becomes 2 raised to the power of (n+1).\n\n");
		printf("    The rule of thumb is: \"n\" should be set to the number of\n");
		printf("    address lines on each of your cart's ROM chips.\n");
		printf("    e.g. a 29F040 has 19 address lines.  Thus, \"n\" would be set to 19.\n\n");

		return 1;		// 1 is the "Something went wrong" signal.
	}

	// Open ROM file for binary reading
	fin = fopen(argv[1], "rb");

	if (argc > 3)
		fout = fopen(argv[3], "wb");	// If an output file is specified, open it for binary writing
	else
		fout = fopen(t, "wb");		// Otherwise, open "temptemp.tmp" for binary writing

	// Self-explanatory...
	if ((fin == NULL) || (fout == NULL)) {
		printf("Unknown error while opening file(s)\n");
		return 1;
	}

	// Calculate new filesize from size argument
	new_size = 1 << (atol(argv[2]) + 1);

	// Get current filesize
	fseek(fin, 0, SEEK_END);
	size = ftell(fin);
	fseek(fin, 0, SEEK_SET);

	// Check file size
	if (size < HEADER_SIZE) {
		printf("\nThis file isn't even big enough to be a VB ROM header!  Try an actual ROM...\n");
		return 1;
	}

	if (new_size < size) {
		printf("\nIt's already bigger than that!\n");
		return 1;
	}

	if (new_size == size) {
		printf("\nI guess you already padded it. *shrug*\n");
		return 1;
	}

	// Copy the infile to the outfile.
	for (i=0; i < size; i++) {
		putc(getc(fin), fout);
	}

	// Output "0xFF's" to the outfile, until we come to the new header location.
	for (; i < (new_size - HEADER_SIZE); i++) {
		putc(0xFF, fout);
	}

	// Seek back to the beginning of the header.
	fseek(fin, -HEADER_SIZE, SEEK_END);
	// Write the header from the infile.
	for (; i < new_size; i++) {
		putc(getc(fin), fout);
	}

	// We're done!  Shut 'em down!
	fclose(fin);
	fclose(fout);

	// If no output file, delete the original, and rename the temp file.
	if (argc < 4) {
		remove(argv[1]);
		rename(t, argv[1]);
	}

	// 0 is the "Everything went as planned" signal.
	return 0;
}
