/* This is a simple program to take a 3MB disk image and arrange it into
 * a 4MB image suitable for programming into a 27c322 EPROM for a Classic II.
 *
 * Rob Braun <bbraun@synack.net> 2016
 */
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define ONEMB (1*1024*1024)
#define TWOMB (2*1024*1024)
#define THREEMB (3*1024*1024)
#define FOURMB (4*1024*1024)

int main(int argc, char *argv[]) {
	int fd;
	char *output = NULL;
	ssize_t r;
	
	output = calloc(1, FOURMB);

	fd = open(argv[1], O_RDONLY);
	// $40b00000 address space == $300000 in the EPROM
	r = read(fd, output+THREEMB, ONEMB);
	if (r < ONEMB) {
		perror("read 1");
		exit(1);
	}

	// $40c00000 address space == $0 in the EPROM
	lseek(fd, ONEMB, SEEK_SET);
	r = read(fd, output, TWOMB);
	if (r < TWOMB) {
		perror("read 2");
		exit(2);
	}
	close(fd);

	fd = open("c2-formatted.bin", O_WRONLY|O_CREAT|O_TRUNC, 0644);
	if (fd == -1) {
		perror("open output");
		exit(1);
	}
	write(fd, output, FOURMB);
	close(fd);
}
