/*
 * Copyright (C) 2008-2009 FAUmachine Team <info@faumachine.org>.
 * This program is free software. You can redistribute it and/or modify it
 * under the terms of the GNU General Public License, either version 2 of
 * the License, or (at your option) any later version. See COPYING.
 */

#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static const char *progname;
static unsigned int rom_width;
static unsigned int img_width;
static unsigned int rom_size;
static unsigned int img_size;
static const char *img;

static void
biossplit(void)
{
	unsigned char byte[1024*1024 + 1];
	unsigned int count;
	unsigned int pos;
	unsigned int r;
	unsigned int p;
	int fdin;
	int fdout[16];
	int ret;

	/*
	 * Read image.
	 */
	fdin = open(img, O_RDONLY);
	assert(0 <= fdin);

	ret = read(fdin, byte, sizeof(byte));
	assert(0 <= ret);
	assert(ret < sizeof(byte));

	img_size = ret;

	ret = close(fdin);
	assert(0 <= ret);

	/*
	 * Write image to several files.
	 */
	count = 0;

	for (pos = 0; pos < img_size; ) {
		/*
		 * Open ROM images.
		 */
		for (r = 0; r < img_width / rom_width; r++) {
			char name[1024];

			sprintf(name, "%s-%u", img, count++);

			fdout[r] = open(name, O_WRONLY | O_CREAT, 0666);
			assert(0 <= fdout[r]);
		}

		/*
		 * Write ROM images.
		 */
		for (p = 0; p < rom_size; p += rom_width) {
			for (r = 0; r < img_width / rom_width; r++) {
				ret = write(fdout[r], &byte[pos], rom_width);
				assert(ret == rom_width);

				pos += rom_width;
			}
		}

		/*
		 * Close ROM images.
		 */
		for (r = 0; r < img_width / rom_width; r++) {
			ret = close(fdout[r]);
			assert(0 <= ret);
		}
	}
}

static void __attribute__((__noreturn__))
usage(int retval)
{
	fprintf(stderr, "Usage: %s <romwidth> <imgwidth> <romsize> <img>\n",
			progname);
	exit(retval);
}

int
main(int argc, char **argv)
{
	int c;

	/*
	 * Get program name.
	 */
	progname = *argv;

	/*
	 * Get options.
	 */
	while ((c = getopt(argc, argv, "")) != -1) {
		switch (c) {
		default:
			usage(1);
		}
	}
	argc -= optind;
	argv += optind;

	/*
	 * Get arguments.
	 */
	if (argc == 0) {
		usage(1);
	}
	rom_width = atoi(*argv);
	argc--;
	argv++;

	if (argc == 0) {
		usage(1);
	}
	img_width = atoi(*argv);
	argc--;
	argv++;

	if (argc == 0) {
		usage(1);
	}
	rom_size = atoi(*argv);
	argc--;
	argv++;

	if (argc == 0) {
		usage(1);
	}
	img = *argv;
	argc--;
	argv++;

	if (argc != 0) {
		usage(1);
	}

	/*
	 * Check arguments.
	 */
	/* FIXME */

	biossplit();

	return 0;
}
