/*
  decode_hex.c

  Hex dump, for debugging.
  
  Copyright (c) 2000 Dug Song <dugsong@monkey.org>
  
  $Id: decode_hex.c,v 1.2 2000/06/14 16:15:59 dugsong Exp $
*/

#include "config.h"

#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "decode.h"

/* adapted from OpenBSD tcpdump: dump the buffer in emacs-hexl format */

int
decode_hex(u_char *buf, int len)
{
	u_int i, j, jm;
	int c;

	Buf[0] = '\0';
	
	for (i = 0; i < len; i += 0x10) {
	        snprintf(Buf + strlen(Buf), sizeof(Buf) - strlen(Buf),
			 "  %04x: ", (u_int)(i));
		jm = len - i;
		jm = jm > 16 ? 16 : jm;
		
		for (j = 0; j < jm; j++) {
			if ((j % 2) == 1)
				snprintf(Buf + strlen(Buf),
					 sizeof(Buf) - strlen(Buf),
					 "%02x ", (u_int)buf[i+j]);
			else
				snprintf(Buf + strlen(Buf),
					 sizeof(Buf) - strlen(Buf),
					 "%02x", (u_int)buf[i+j]);
		}
		for (; j < 16; j++) {
			if ((j % 2) == 1)
				strlcat(Buf, "   ", sizeof(Buf));
			else
				strlcat(Buf, "  ", sizeof(Buf));
		}
		strlcat(Buf, " ", sizeof(Buf));
		
		for (j = 0; j < jm; j++) {
			c = buf[i+j];
			c = isprint(c) ? c : '.';
			snprintf(Buf + strlen(Buf), sizeof(Buf) - strlen(Buf),
				 "%c", c);
		}
		strlcat(Buf, "\n", sizeof(Buf));
	}
	return (strlen(Buf));
}
