/* bincmp.c - hack to do binary compare */
/* replaces doing DMP then CMP */

#include <stdio.h>
#include <algol68.h>

#define	BLKSIZ	(512)

FILE *	f1;		/* file handle					*/
FILE *	f2;		/* file handle					*/
long	f1size; 	/* file size bytes				*/
long	f2size;		/* file size bytes				*/
char	string[100];	/*						*/
long	blklim;		/* max block number to read + 1; BLocK LIMit	*/
char	buf1[BLKSIZ];	/* block from file 1				*/
char	buf2[BLKSIZ];	/* block from file 2				*/
BOOL	ok1;		/* no errors yet reading file 1			*/
BOOL	ok2;		/* no errors yet reading file 2			*/
int	got;		/* how many bytes we got on last read		*/
BOOL	blkunk;		/* block number unannounced			*/
char *	p1;		/* scans block from file 1			*/
char *	p2;		/* scans block from file 2			*/
long	blknum;		/* block number we are sniffing. 1-org for FCS	*/
char *	buf1lim;	/* 1 past last char in buf 1			*/

extern	long	fsize();

helpless(gripe)
char * gripe;
BEGIN
	fprintf(stderr,"\7BINCMP -F- %s\n",gripe);
	fprintf(stderr,"Command format is BINCMP filespec1 filespec2\n");
	exit();
END

main(argc,argv)
int	argc;
char **	argv;
BEGIN
	IF	(argc!=3)
	THEN	helpless("I expect exactly 3 arguments");
	FI
	IF	( ! (f1=fopenr(argv[1],BLKSIZ)) )
	THEN	fprintf(stderr,"$$ferr=%oo file=\"%s\"\n",$$ferr,argv[1]);
		helpless("Can't open 1st file");
	FI
	IF	( ! (f2=fopenr(argv[2],BLKSIZ)) )
	THEN	fprintf(stderr,"$$ferr=%oo file=\"%s\"\n",$$ferr,argv[2]);
		helpless("Can't open 2nd file");
	FI
	printf("+ file1=\"%s\" has %ld. bytes\n",fgetname(f1,string),f1size=fsize(f1));
	printf("+ file2=\"%s\" has %ld. bytes\n",fgetname(f2,string),f2size=fsize(f2));
	blklim = ( (f1size>f2size ? f1size : f2size) + (BLKSIZ-1) ) / BLKSIZ + 1;
	FOR	(blknum=1,ok1=ok2=TRUE;  blknum<blklim && ok1 && ok2;  blknum++)
	DO
		IF	( frget(buf1,BLKSIZ,f1,blknum) )
		THEN	ok1 = FALSE;
			printf("- read fail file1 $$ferr=%oo blknum=%ld.\n",$$ferr,blknum);
		FI
		IF	( frget(buf2,BLKSIZ,f2,blknum) )
		THEN	ok2 = FALSE;
			printf("- read fail file2 $$ferr=%oo blknum=%ld.\n",$$ferr,blknum);
		FI
		IF	(ok1 && ok2)
		THEN	blkunk = TRUE;
			FOR	(p1=buf1,p2=buf2,buf1lim=buf1+BLKSIZ;  p1<buf1lim;  p1++,p2++)
			DO	IF	(*p1!=*p2)
				THEN	IF	(blkunk)
					THEN	printf("= block number %ld.\n",blknum);
						blkunk = FALSE;
					FI
					printf("!     %7oo %4o %4o\n",p1-buf1,*p1&0xFF,*p2&0xFF);
				FI
			OD
		OD
	OD
END

/* end: bincom.c */
