/*

			Hex dump utility

*/

#include "netfone.h"

#ifndef NDEBUG

#define EOS     '\0'

static int bytesperline = 16, doublechar = 0,
		   dflen = 2;
static unsigned long fileaddr;
static unsigned char lineecho[32];

/*	OUTLINE  --  Edit a line of binary data into the selected output
				 format.  */

static void outline(LPBYTE dat, int len)
{
	char oline[132];
	int i;

	sprintf(oline, "%6X", fileaddr);
    strcat(oline, ":");
	for (i = 0; i < len; i++) {
		char outedit[80];

		sprintf(outedit, "%02X", dat[i]);
        strcat(oline, (i == (bytesperline / 2)) ? "  " : " ");
		strcat(oline, outedit);
	}

	if (doublechar) {
		char oc[2];
		int shortfall = ((bytesperline - len) * (dflen + 1)) +
						(len <= (bytesperline / 2) ? 1 : 0);

		while (shortfall-- > 0) {
            strcat(oline, " ");
		}
		oc[1] = EOS;
        strcat(oline, " | ");
		for (i = 0; i < len; i++) {
			int b = dat[i];

            /* Map non-printing characters to "." according to the
			   definitions for ISO 8859/1 Latin-1. */

            if (b < ' ' || (b > '~' && b < 145)
						|| (b > 146 && b < 160)) {
                b = '.';
			}
			oc[0] = b;
			strcat(oline, oc);
		}
	}
    strcat(oline, "\r\n");
	OutputDebugString(oline);
}

/*	XD	--	Dump a buffer.

			xd(buf, bufl, dochar);

			buf 	Address of buffer to dump.
			bufl	Buffer length in bytes.
			dochar	If nonzero, show ASCII/ISO characters
					as well as hexadecimal.

*/

void xd(void *mem, int bufl, int dochar)
{
	int b, bp;
	LPBYTE buf = (LPBYTE) mem;

	bp = 0;
	fileaddr = 0;
	doublechar = dochar;

	while (bufl-- > 0) {
		b = *buf++;
		if (bp >= bytesperline) {
			outline(lineecho, bp);
			bp = 0;
			fileaddr += bytesperline;
		}
		lineecho[bp++] = b;
	}

	if (bp > 0) {
		outline(lineecho, bp);
	}
}
#endif 
