/* f2b.c: make a R.VAR file from a diskette */
/* output 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("F2B DDn outputfile 1stphysicalblocknumber lastphysicalblocknumber increment\n");
 exit();
}

main(argc,argv)
int	argc;
char	**argv;
{
 FILE		*ioptr;		/* output file */
 int		first;		/* 1st pbn to suck */
 int		last;		/* last pbn to suck */
 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<<30;
 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],"wu")))	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)
	{
	 got = rblk(LUN,BUFSIZ,b,EFN,pbn);
	 fput(b,got,ioptr);
	 if	(ferror(ioptr))	error("\7pbn=%d. $$ferr=%oo\n",pbn,$$ferr);
	}
 ;
 fflush(ioptr);
 if	(fclose(ioptr))	error("Can't close\7\n");
}

int	rblk(lun,bufsiz,buf,efn,blknum)	/* return number of bytes read */
int	lun;
int	bufsiz;
char	*buf;
int	efn;
int	blknum;
{
 int	prl[6];
 int	qiow();
 int	isb[2];
 int	tries;
 int	i;
 /* printf("blknum=%oo\n",blknum); */
 isb[0] = IE_VER;
 tries = 10;
 while	(isb[0]!=IS_SUC && tries--)
	{prl[0] = buf;
	 prl[1] = bufsiz;
	 prl[3] = 0;
	 prl[4] = blknum;
	 qiow(IO_RPB,lun,efn,isb,0,prl);
	 if	(isb[0]!=IS_SUC)
		{for	(i=0; i<6; i++)	printf("prl[%d]=%oo ",i,prl[i]);
		 printf("\nCan't read disk block %u. isb[0]=%oo isb[1]=%oo $dsw=%oo\n\7",blknum,isb[0],isb[1],$dsw);
		}
	 ;
	}
 ;
 if	(isb[0]!=IS_SUC)	printf("\7bad block\7 - continuing\n");
 return(isb[1]);
}
