#include <stdio.h>
#include <time.h>
#include <stdlib.h>

/*
 * Make a Tektronix 856x compatible floppy disk image with the sector payload from stdin
 * Side 0 Cyl 0 is 26 single density 128 byte sectors
 * Side 1 Cyl 0 and all other tracks are 26 double-density 256 byte sectors
 */
 
char sdsec[] = {0, 0, 0, 0x1a, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a};
char ddsec[] = {3, 0, 1, 0x1a, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a};

main(){
	struct tm time_s;
	struct timeval rawtime;
	char buf[100];
	int i,j;
	char cyl = 0;
	char side = 0;
	unsigned char c;
	
	gettimeofday(&rawtime);
	time_s = *gmtime(&rawtime.tv_sec);
	strftime(buf, sizeof(buf), "IMD 1.18: %m-%d/%m/%Y  %X \r\n", &time_s);
	
	printf("%s%c", buf,0x1a);
	//                         +- 0 = 500 FM, 3 = 500 MFM
	//                         |  - cyl 0-76
	//                         |  |  +- hd (0-1)
	//                         |  |  |  +- sec cnt
	//                         |  |  |  |  +- sec size 0 = 128, 1 = 256
	//                         |  |  |  |  |  +- sec numbering map
	//                         |  |  |  |  |  |
	// 26 128 byte SD sectors 00 00 00 1a 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a
        // data 01 {secsiz bytes}
	// data 02 {compressed value}
	//
	// 26 256 byte DD sectors 03 00 01 1a 01 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a
	// 76 x 2 256 byte DD sectors

	// first cyl side 0
	fwrite(sdsec,1,sizeof(sdsec),stdout);
	for(i = 1; i<27; i++){
	 putchar(1);
	 for(j=0; j<128; j++){
	 c = getchar();
	 if(feof(stdin))
	  putchar(0);
	 else
	  putchar(c);
	 }
	}
	// first cyl side 1
	fwrite(ddsec, 1,sizeof(ddsec),stdout);
	for(i = 1; i<27; i++){
	 putchar(1);
	 for(j=0; j<256; j++){
	 c = getchar();
	 if(feof(stdin))
	  putchar(0);
	 else
	  putchar(c);
	 }
	}
	
	// the rest of the cyls
	for(cyl = 1; cyl <77; cyl++){
	 // side 0
	 ddsec[1] = cyl;
	 ddsec[2] = 0;
	 fwrite(ddsec, 1,sizeof(ddsec),stdout);
	 for(i = 1; i<27; i++){
	  putchar(1);
	  for(j=0; j<256; j++){
	   c = getchar();
	   if(feof(stdin))
	    putchar(0);
	   else
	    putchar(c);
	  }
	 }
	 // side 1
	 ddsec[1] = cyl;
	 ddsec[2] = 1;
	 fwrite(ddsec, 1,sizeof(ddsec),stdout);
	 for(i = 1; i<27; i++){
	  putchar(1);
	  for(j=0; j<256; j++){
	   c = getchar();
	   if(feof(stdin))
	    putchar(0);
	   else
	    putchar(c);
	  }
	 }
	}
}