#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

#include "xex.h"

#ifndef VERSION
#define VERSION "???"
#endif

#define SELF "xexsplit"
#define OPTIONS "hvr"

char *usage =
	SELF " v" VERSION " by B. Watson (WTFPL)\n"
	"Split a multi-segment Atari binary load file into multiple files\n"
	"usage: " SELF " -[hv] [infile.xex] [outfile-prefix]\n"
	"  -r  Raw output (not xex).\n"
	"  -h  Print this help\n"
	"  -v  Verbose operation\n";

int main(int argc, char **argv) {
	xex_segment seg;
	char *infile = "-";
	FILE *in = stdin;
	char outfile[4096];
	unsigned char buffer[65536];
	FILE *out = NULL;
	int count = 1, outlen, c, raw_output = 0;

	strcpy(outfile, "xexsplit");

	while( (c = getopt(argc, argv, OPTIONS)) > 0) {
		switch(c) {
			case 'r':
				raw_output = 1;
				break;

			case 'h':
				printf(usage);
				exit(0);
				break;

			case 'v':
				xex_verbose = 1;
				break;

			default:
				fprintf(stderr, usage);
				exit(1);
		}
	}

	if(argc > optind) {
		infile = argv[optind];
		optind++;
	}

	if(argc > optind) {
		strcpy(outfile, argv[optind]);
		optind++;

		if(argc > optind)
			fprintf(stderr, SELF ": "
					"ignoring extra junk on command line: '%s'.\n", argv[optind]);
	} else if(strcmp(infile, "-") != 0) {
		strcpy(outfile, infile);
	}

	if(strcmp(outfile, "-") == 0) {
		fprintf(stderr, SELF ": can't write to standard output.\n");
		exit(1);
	}

	outlen = strlen(outfile);

	if( strcmp(infile, "-") != 0 && !(in = fopen(infile, "rb")) ) {
		fprintf(stderr, SELF ": %s: %s\n", infile, strerror(errno));
		exit(1);
	}

	seg.object = buffer;
	while(xex_fread_seg(&seg, in)) {
		if(count == 1 && !seg.has_ff_header) {
			fprintf(stderr, SELF ": warning: first segment lacks $FFFF header "
					"(bad XEX file?)\n");
		}

		seg.has_ff_header = 1;

		sprintf(outfile + outlen,
				".%03d.%04X.%04X.%s",
				count, seg.start_addr, seg.end_addr,
				(raw_output ? "bin" : "xex"));

		if( !(out = fopen(outfile, "wb")) ) {
			fprintf(stderr, SELF ": %s: %s\n", outfile, strerror(errno));
			fclose(in);
			exit(1);
		}

		if(raw_output) {
			if(fwrite(seg.object, seg.len, 1, out) < 1)
				break;
		} else {
			if(!xex_fwrite_seg(&seg, out))
				break;
		}

		fclose(out);
		out = NULL;

		fprintf(stderr, SELF ": Wrote file %s\n", outfile);

		count++;
	}

	fclose(in);
	if(out) fclose(out);

	if(xex_errno) {
		xex_perror(SELF);
		return 1;
	}

	if(count == 1) {
		fprintf(stderr, SELF ": input file was empty!\n");
		return 1;
	}

	return 0;
}
