#ifdef	ournix
#include "ournix.h"
#endif
	char 
sccsID[] = "@(#) xd.c v1.2 Copyright Julian H. Stacey 1st October 1987.\n" ;
/* very slow on msdos, needs faster buffering */

#include	<stdio.h>
#include <stdlib.h>
#ifndef	minix	/* { */
#include	<fcntl.h>
#include	<sys/types.h>
#include	<sys/stat.h>
#else		/* } { */
#include	<stat.h>
#endif		/* } */
#include	<ctype.h>

#ifdef	minix	/* { */
extern FILE *fopen() ;
#endif		/* } */

#define to_hex(c)	((((c) > 9) ? (c) + 'A' -10 : (c) + '0'))

#ifdef unix	/* { */
#define BUF_LEN 80
#endif		/* } */
#ifdef MSDOS	/* { */
#define BUF_LEN 70
		/* when xd on msdos prints 80 chars, then \r \n via 
		ansi.sys to screen,
		an unwanted blank line appears
		not yet tried: this 70 cludge, or removing ansi.sys */
#endif		/* } */
char	buf_bytes[BUF_LEN+1]; char buf_hi[BUF_LEN+1], buf_lo[BUF_LEN+1] ;
char	*p_bytes, *p_hi, *p_lo;
char	more = 0 ;

int ARGC ; char **ARGV ; 

xd_flush()
	{
	*p_hi = *p_lo = *p_bytes = '\0' ;
	if (more) printf(
/* "--------------------------------------------------------------------------------\n" */
"----+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8\n"
		);
	printf( "%s\n%s\n%s\n" ,buf_bytes,buf_hi,buf_lo);
	}

main(argc,argv)
	int argc ; char **argv ; 
	{
	int	result = 0 ;	/* program returns how many files couldnt
					be opened */

	ARGV = argv ; ARGC = argc ;
#ifdef	VSL	/* { */
#include	"../../include/vsl.h"
#endif		/* } */

	if(argc-- == 1) return(display("\0"));
	else while(argc--)
		{
		if (**++argv == '-')
			switch(*++*argv)
				{
				case 'P':	/* print origin of program */
					printf("%s",sccsID) ;
					break;
				case '?':
				default:
					fprintf(stderr,
						"%s: Unknown flag %c\n",
						*ARGV, **argv);
					exit(1);
					break;
				}
			else result += display(*argv);
		}
	exit(result);
	}

	int 
display(name)
	char *name ;
	{
	int	ch;
	int	count = 1; /* char position on vdu-valid values: 1 to BUF_LEN */
	FILE	*file2 ;

	if (name[0] == '\0' ) file2 = stdin ;
	else if ((file2 = fopen(name,
#ifndef MSDOS	/* { */
					"r"
#else		/* } { */
					"rb"	/* read binary */
#endif		/* } */
					)) == NULL)
		{
		fprintf(stderr,"%s: Failed to open %s\n",*ARGV,name);
		return(1);
		}

	p_bytes = buf_bytes ; p_hi = buf_hi ; p_lo = buf_lo ; 
	while ((ch=getc(file2)) != EOF)
		{
		ch &=0xff ;
		if (count > BUF_LEN)
			{
			fprintf(stderr,"%s: Program error\n",*ARGV) ;
			exit(1);
			}
#define	ESC 0x1B
		*p_bytes++ = ((isprint(ch) || ( ch == ESC )) ? ch : '?' ) ;
		*p_lo++ = to_hex( ch & 0xF);
		*p_hi++ = to_hex( (ch & 0xF0) >> 4);
		count++ ;
		if ((ch == '\n') || ( count == BUF_LEN + 1 ) )
			{
			more = 1 ;
			count = 1;
			xd_flush();
			p_bytes = buf_bytes ; p_hi = buf_hi ; p_lo = buf_lo ;
			}
		}
		if (count > 1)
			{	/* flush remainder */
			xd_flush();
			}
	(void) fclose(file2);
	return(0);
	}
