/* mw -  write multiple diskettes from stdin data
      - mw [-f] device size(in 1K blocks)
          (-f forces a format for all diskettes, rather
          than the autodetect formatting)
 */
#include <stdio.h>
main(int argc, char **argv)
{
	FILE *fp,*tp;
	int i,n,size,disk=1,doformat=0,done=0;
	char c,*buf,cmd[128];

	if ((argc !=3) && (argc !=4)) {
		fprintf(stderr,"usage: mr [-f] device size\n");
		exit(1);
	}
	if (argc == 4) {
		if((argv[1][0] != '-')||(argv[1][1] != 'f')) {
			fprintf(stderr,"usage: mr [-f] device size\n");
			exit(1);
		}
		else
			doformat = 1;
	}
	size = atoi(argv[2+doformat]);
	if ((buf  = (char *)malloc(size/10*1024)) == NULL) {
		fprintf(stderr,"not enough memory\n");
		exit(1);
	}
	if ((tp = fopen("/dev/tty","r")) == NULL) {
		fprintf(stderr,"can't open tty\n");
		exit(1);
	}
	sprintf(cmd,"fdformat %s",argv[1+doformat]);
	while(!done) {
		fprintf(stderr,"Insert disk %d and press enter: ",disk++);
		fflush(stderr);
		c = getc(tp);
		if(doformat) 
			system(cmd);
		if((fp = fopen(argv[1+doformat],"r")) == NULL) {
			fprintf(stderr,"bad device\n");
			exit(1);
		}
		if((n = fread(buf,512,1,fp)) == 1) 
			fclose(fp);
		else{
			fprintf(stderr,"hmm... trying a format\n",n);
			fclose(fp);
			system(cmd);
		}
		if((fp = fopen(argv[1+doformat],"w")) == NULL) {
			fprintf(stderr,"bad device\n");
			exit(1);
		}
		for (i=0;i<10;i++) {
			bzero(buf,size/10*1024); 
			if (!done) {
			  if((n=fread(buf,1,size/10*1024,stdin))<size/10*1024)
				done=1;
			}
			if((n = fwrite(buf,1024,size/10,fp)) != size/10) {
				fprintf(stderr,"bad floppy wrote %d\n",n);
				exit(1);
			}
		}
		fclose(fp);
	}
}
