/* B2F.c: output a R.VAR file to a diskette */
/* input file is 1 256-byte record :: 1 disk sector */
#include <stdio.h>
#include <cx.h>
#include <qiofun.h>
#include <qioret.h>
#define EFN 6
#define LUN 6
#define BUFSIZ 256
extern int $$ferr;
extern int $dsw;
int		b[(BUFSIZ+1)/2];

helpless()
{printf("B2F DDn inputfile 1stphysicalblocknumber lastphysicalblocknumber increment\n");
 exit();
}

main(argc,argv)
int	argc;
char	**argv;
{
 FILE		*ioptr;		/* input file */
 int		first;		/* 1st pbn to blow */
 int		last;		/* last pbn to blow */
 int		pbn;		/* current physical block */
 char		dnam[3];	/* disk device name */
 int		dnum;		/* disk device number */
 int		dev;		/* disk device name */
 int		inc;		/* */
 int		got;
 if	(argc<3)	helpless();
 first = 0;
 last = 1<<15;
 ioptr = stdout;
 inc = 1;
 if	(strlen(argv[1])!=3 || !isdigit(argv[1][2]))
	{puts("\7First Argument must be EXACTLY ddn");
	 helpless();
	}
 ;
 copy(dnam,argv[1],2);
 dnum = argv[1][2] - '0';
 dev = toupper(dnam[1])<<8 | toupper(dnam[0]);
 if	(alun(LUN,dev,dnum)!=IS_SUC)	error("\7Can't attach to %s $dsw=%oo\n",argv[1],$dsw);
 if	(argc>2)
	{if	(!(ioptr=fopen(argv[2],"ru")))	error("\7Can't open %s $$ferr=%oo\n",argv[2]);
	 if	(argc>3)
		{sscanf(argv[3],"%u",&first);
		 if	(argc>4)
			{sscanf(argv[4],"%u",&last);
			 if	(argc>5)
				{sscanf(argv[5],"%u",&inc);
				}
			 ;
			}
		 ;
		}
	 ;
	}
 ;
 for	(pbn=first; pbn<=last;	pbn+=inc)
	{
	 if	(feof(ioptr))	break;
	 got = fget(b,BUFSIZ,ioptr);
	 if	(ferror(ioptr))	error("\7pbn=%d. $$ferr=%oo\n",pbn,$$ferr);
	 if	(got)	wblk(LUN,got,b,EFN,pbn);
	}
 ;
 if	(fclose(ioptr))	error("Can't close\7\n");
}

	wblk(lun,bufsiz,buf,efn,blknum)
int	lun;
int	bufsiz;
char	*buf;
int	efn;
int	blknum;
{
 int	prl[6];
 int	qiow();
 int	isb[2];
 int	i;
 /* printf("blknum=%oo\n",blknum); */
 prl[0] = buf;
 prl[1] = bufsiz;
 prl[3] = 0;
 prl[4] = blknum;
 qiow(IO_WPB,lun,efn,isb,0,prl);
 if	(isb[0]!=IS_SUC)
	{for	(i=0; i<6; i++)	printf("prl[%d]=%oo\n",i,prl[i]);
	 error("Can't write disk block %u. isb[0]=%oo isb[1]=%oo $dsw=%oo\n\7",blknum,isb[0],isb[1],$dsw);
	}
 ;
}
