/* d2b.c: make a R.VAR file from a disk */
/* output file is 1 512-byte block :: 1 disk block */
#include <stdio.h>
#include <cx.h>
#include <qiofun.h>
#include <qioret.h>
#define EFN 6
#define LUN 6
#define BUFSIZ 512
extern int $$ferr;
extern int $dsw;
int		b[(BUFSIZ+1)/2];

helpless()
{printf("D2B DDn outputfile 1stblocknumber lastblocknumber\n");
 exit();
}

main(argc,argv)
int	argc;
char	**argv;
{
 FILE		*ioptr;		/* output file */
 long		first;		/* 1st lbn to suck */
 long		last;		/* last lbn to suck */
 long		lbn;		/* current logical block */
 char		dnam[3];	/* disk device name */
 int		dnum;		/* disk device number */
 int		dev;		/* disk device name */
 if	(argc<3)	helpless();
 first = 0;
 last = 1<<30;
 ioptr = stdout;
 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],"w")))	error("\7Can't open %s $$ferr=%oo\n",argv[2]);
	 if	(argc>3)
		{sscanf(argv[3],"%lu",&first);
		 if	(argc>4)
			{sscanf(argv[4],"%lu",&last);
			}
		 ;
		}
	 ;
	}
 ;
 for	(lbn=first; lbn<=last;	lbn++)
	{
	 rblk(LUN,BUFSIZ,b,EFN,lbn);
	 fput(b,BUFSIZ,ioptr);
	 if	(ferror(ioptr))	error("\7lbn=%ld. $$ferr=%oo\n",lbn,$$ferr);
	}
 ;
 fflush(ioptr);
 if	(fclose(ioptr))	error("Can't close\7\n");
}

	rblk(lun,bufsiz,buf,efn,blknum)
int	lun;
int	bufsiz;
char	*buf;
int	efn;
long	blknum;
{
 int	prl[6];
 int	qiow();
 int	isb[2];
 int	i;
 /* printf("blknum=%loo\n",blknum); */
 prl[0] = buf;
 prl[1] = bufsiz;
 prl[3] = blknum >> 16;
 prl[4] = blknum & 0xFFFF;
 qiow(IO_RLB,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 read disk block %u. isb[0]=%oo isb[1]=%oo $dsw=%oo\n\7",blknum,isb[0],isb[1],$dsw);
	}
 ;
}
