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

#define SELF "xex1to2"

FILE *open_file(const char *name, const char *mode) {
	FILE *f = fopen(name, mode);
	if(f) return f;

	fprintf(stderr, SELF ": %s: %s\n", name, strerror(errno));
	exit(1);
}

void invalid(void) {
	fprintf(stderr, SELF ": input is not a valid Atari DOS 1.0 executable.\n");
	exit(1);
}

void read_header(FILE *in) {
	int c;

	c = getc(in);
	if(c < 0 || c != 0x84) invalid();
	c = getc(in);
	if(c < 0 || c != 0x09) invalid();
}

int main(int argc, char **argv) {
	int c;
	FILE *in = stdin, *out = stdout;

	if(argc > 3) {
		fprintf(stderr, "Usage: " SELF " [dos1_input.xex] [dos2_output.xex]\n");
		exit(1);
	}

	if(argc > 1) in  = open_file(argv[1], "rb");
	if(argc > 2) out = open_file(argv[2], "wb");

	if(isatty(fileno(out))) {
		fprintf(stderr,
				SELF ": Standard output is a terminal; not writing binary data\n");
		exit(1);
	}

	read_header(in);
	fputc(0xff, out);
	fputc(0xff, out);

	while( (c = fgetc(in)) >= 0 )
		fputc(c, out);

	fclose(in);
	fclose(out);

	return 0;
}
