/* 
 * msx2dsk.c : converts .msx disk image to .dsk image
 * 
 * .msx files are a certain type of disk dumps. They always seem to be
 * double sided 720kB ones. There are no extra headers, but the order of
 * the sectors is all messed up. This little program should put that 
 * straight. :)
 *
 * The structure is as follows: the first 9 sectors (=0x1200 bytes) of the
 * first side, then the first 9 sectors of the other side, the next 9
 * sectors of the first site, the next 9 sectors of the other side.. etc.
 * 
 * These weird .msx files are found at: ftp://jazz.snu.ac.kr/pub/msx/
 */

#include <stdio.h>

char buffer[0x1200];        /* buffer for copying -- 9 sectors */

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

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

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

    /* check file size */
    fseek (fin, 0L, SEEK_END);
    if (737280L != ftell (fin) ) {
	fprintf (stderr, 
	    "%s: File not right size for .msx disk image\n", argv[1]);
	fclose (fin);
	return (2);
    }

    fseek (fin, 0L, SEEK_SET);

    i = 80; /* twice 9 sectors for every loop */

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

    n1=0; n2=80;
    while (i--) {
	fseek (fin, ((long)n1++)*0x1200L, SEEK_SET);

	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);
        }

        fseek (fin, ((long)n2++)*0x1200L, SEEK_SET);

        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);
}

