/* Util.cpp, do with this as you wish.  -Josh (jwright at willhackforsushi.com) */
#include <windows.h>
#include <stdio.h>

/* d is the data to print, dl is the length of the data */
void hdump(BYTE *d, ULONG dl) {
	ULONG i=0, j=0, padCalc=0;
	USHORT numShort=0;
	static const BYTE asciify[] = "................................ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~.................................................................................................................................";
	
	if (dl == 0) {
		return;
	}
	
	for(i=0; (i <= (dl-16)) && (dl >= 16); i+=16) {
		for(j=0; j < 16; j++) {
			if (j == 0) {
				printf("%04X:  %02X", i, *(d+j+i));
			} else {
				printf("%02X", *(d+j+i));
			}
			if (j % 2 == 1) {
				printf(" ");
			}
		}
		printf("    ");

		/* Print ascii'ified data */
		for(j=0; j < 16; j++) {
			printf("%c", asciify[*(d+j+i)]);
		}

		printf("\n");
	}

	/* Handle remaining data not evenly divisible by 16 */
	if (dl%16) {
		for(j=0; j < (dl%16); j++) {
			if (j == 0) {
				printf("%04X:  %02X", i, *(d+j+i));
			} else {
				printf("%02X", *(d+j+i));
			}
			if (j % 2 == 1) {
				printf(" ");
			}
		}

		/* Pad to align ascii dump */
		for(padCalc=0; padCalc < (16 - (dl%16)); padCalc++) {
			printf("  ");
		}

		if ((16 - (dl%16)) > 1) {
			numShort = ((16 - (dl%16))/2);
		}
		for (padCalc=0; padCalc < numShort; padCalc++) {
			printf(" ");
		}
		if ((dl%16)%2) {
			printf(" ");
		}

		printf("    ");

		/* Print ascii'ified data */
		for(j=0; j < (dl%16); j++) {
			printf("%c", asciify[*(d+j+i)]);
		}

		printf("\n");
	}

	return;
	
}

int __cdecl wmain(int argc, WCHAR* argv[])
{
	BYTE data[256];
	USHORT i;

	/* populate data array, dumping contents in hex */
	for (i=0 ; i < sizeof(data); i++) {
		data[i] = (BYTE)i;
		printf("Length: %d\n", (i+1));
		hdump(data, (USHORT)(i+1));
	}
	return 0;
}

