/* 
 * ddi2dsk.c : converts .ddi DiskDupe disk image to .dsk image
 * 
 * DiskDupe images are always double sided 720kB images (at least in the
 * MSX world). There is a hear of 0x1200 bytes (in the version known to the
 * MSX world; this is version is 5.12 -- and probably others). This format
 * is used by the CompuJunks MSX2 emulator (MSX2EMUL). 
 * 
 * The exact format of the header is unknown to me. However, this does not
 * seem to be important; the last 720kB is a complete continuous dump of
 * the disk.
 */

#include <stdio.h>

char buffer[0x4000];		/* 16kB buffer for copying */

int main(int argc, char *argv[])
{
    int		i;
    long	l;
    FILE	*fin, *fout;

    if (argc != 3) {
	fprintf (stderr, "%s: Missing file arguments or too many\n", argv[0]);
	fprintf (stderr, "Usage: `ddi2dsk SOURCE DESTINATION'\n"
	       "SOURCE is the .ddi file, DESTINATION the .dsk file.\n");
	return (2);
    }

    fin=fopen (argv[1],"rb");
    if (fin == NULL) {
	perror (argv[1]);
	return (1);
    }

    fseek (fin, 0L, SEEK_END);
    l = ftell (fin);

    if (l < 737280L) {
	fprintf (stderr, 
	    "%s: File not big enough to be a disk image\n", argv[1]);
	fclose (fin);
	return (2);
    }

    if (l != 741888L) {
	fprintf (stderr, "%s: Header size not consistent with .ddi files\n"
		"Trying to continue anyway\n", argv[1]);
    }

    fseek (fin, -737280L, SEEK_END);

    i = (int)(737280L / (long)sizeof (buffer));

    fout = fopen (argv[2], "wb");
    if (fout == NULL) {
	perror (argv[2]);
	fclose (fin);
	return (1);
    }

    while (i--) {
	if (sizeof (buffer) != fread (buffer, 1, sizeof (buffer), fin) ) {
	    perror (argv[1]);
	    fclose (fin); fclose (fout);
	    return (1);
	}

        if (sizeof (buffer) != fwrite (buffer, 1, sizeof (buffer), fout) ) {
	    perror (argv[2]);		
            fclose (fin); fclose (fout);
	    return (1);
        }
    }

    fclose (fin);
    fclose (fout);

    return (0);
}

