/*
 * Copyright (C) 2007-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 <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "../lib/conv_cd.h"
#include "../lib/simsetup.h"

const char *progname;
const char *in;
const char *out;

const char *basedir = ".";
struct simsetup simsetup;

void time_stop(void) { }
void time_cont(void) { }

static void __attribute__((__noreturn__))
usage(int retval)
{
	fprintf(stderr, "Usage: %s [OPTIONS] <in> <out>\n", progname);
	fprintf(stderr, "\t-h: Show this help.\n");
	exit(retval);
}

int
main(int argc, char **argv)
{
	int c;
	void *conv;
	int out_fd;
	uint8_t buf[0x10000];
	unsigned long long pos;
	long long len;
	int ret;

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

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

	/*
	 * Get parameter.
	 */
	if (0 < argc) {
		in = *argv;
		argc--;
		argv++;
	} else {
		usage(1);
		/*NOTREACHED*/
	}
	if (0 < argc) {
		out = *argv;
		argc--;
		argv++;
	} else {
		usage(1);
		/*NOTREACHED*/
	}
	if (argc != 0) {
		usage(1);
		/*NOTREACHED*/
	}
	
	/*
	 * Do work.
	 */
	conv = conv_cd_from_iso_open(in, 1 + 60*75 + 60*75 + 360000);
	if (! conv) {
		fprintf(stderr, "ERROR: Can't open converter for \"%s\".\n",
				in);
		exit(1);
	}

	out_fd = open(out, O_WRONLY | O_CREAT, 0666);
	assert(0 <= out_fd);

	for (pos = 0ULL; ; pos += len) {
		len = conv_cd_from_iso_read(conv, buf, sizeof(buf), pos);
		if (len == 0) {
			break;
		}
		ret = write(out_fd, buf, len);
		assert(ret == len);
	}

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

	conv_cd_from_iso_close(conv);

	return 0;
}
