/*
Speak Freely 7.2
Copyright (C) 1997-2002 Brian C. Wiles.  All Rights Reserved.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

						   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 
