/**
 * bytedump.c - simple hex dump utility.
 *
 * This program is free software. See files in ../legal/* for info.
 **/
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#ifdef MSDOS
#	include <io.h>
#endif
#include <fcntl.h>

#ifndef O_BINARY
#	define O_BINARY 0
#endif


void
usage(char *progname)
{
	fprintf(stderr, "Usage: %s filename\n", progname);
	fprintf(stderr, " This will dump the file in hex format\n");
	exit(0);
}


void
HexLine(char *buf, int size, long addrnow)
{
	register index;

	printf("%08x\t", addrnow);
	for(index = 0; index < size; index++)
		printf(" %02.2x", *(buf+index) & 0xFF);
	printf("\n");
}

main(int argc, char *argv[])
{
	int fd;
	char buf1[16];
	char buf2[16];
	char *bufptr, *prevbuf;
	long addrnow, rdnum, sameaddr;
	int samecount;

	if (argc < 2)
		usage(argv[0]);
	fd = open(argv[1], O_BINARY | O_RDONLY);
	if ( fd == -1 )
	{
		fprintf(stderr, "Could not open file %s\n", argv[1]);
		usage(argv[0]);
	}
	memset(buf1, 0, 16);
	memset(buf2, 0, 16);
	bufptr = buf1;
	prevbuf = buf2;
	samecount = 0;
	addrnow = 0;
	sameaddr = 0;
	for(addrnow = 0;;)
	{
		rdnum = read(fd, bufptr, 16);
		if (rdnum < 16)
		{
			if (samecount > 0)
			{
				HexLine(prevbuf, 16, sameaddr);
				printf("*\n");
			}
			if (rdnum <= 0)
				break;
			HexLine(bufptr, rdnum, addrnow);
			break;
		}
		if (addrnow && (memcmp(prevbuf, bufptr, 16) == 0))
		{
			if ( !samecount )
				sameaddr = addrnow;
			samecount++;
		}
		else
		{
			if (samecount > 0)
				printf("*\n");
			samecount = 0;
			sameaddr = 0;
			HexLine(bufptr, 16, addrnow);
		}
		addrnow += 16;
		if (bufptr == buf1)
		{
			bufptr = buf2;
			prevbuf = buf1;
		}
		else
		{
			bufptr = buf1;
			prevbuf = buf2;
		}
	}
	close(fd);
	return(0);
}
