/* 
hexd.c: a hex-dumper for muLinux 
------------------------------------
-code  : encode in hex + ascii
-decode: decode only hex rows. User can edit them.

*/

/*
 * Copyright (C) 1999
 *      Michele Andreoli, andreoli@pisoft.it - Public domain.
 */

#include <stdio.h>
#include <stdlib.h>

#define USAGE "hex code/decode: (C) by M. Andreoli 1999\n\
Usage hex [-h|-help] [-c|-code] [-d|-decode] (read/write from stdin/stdout)\n"

#define R 17 
#define COUNTER 6

/* functions */

/*
 *  code()
*/


int code()
{
unsigned char buf[R];
int j=0,i=0,n,c;

while (1)
{
	/* read the buffer */
        n=read(0, buf, R);
        if (n <= 0) break;  /* finish */

	/* row number */
	fprintf(stdout,"%0*d: ",COUNTER,i);

	/* write the buffer in HEX */

	for (j=0; j<n; j++ ) fprintf(stdout,"%02x ",buf[j]);
	for (j=n; j<R; j++ ) fprintf(stdout,"%2c ",' ');

	/* ascii version */
	fprintf(stdout,"[");
	for (j=0; j<n; j++ ) 
		{
		if ( isprint(buf[j]) ) c=buf[j]; else c='.';
		fprintf(stdout,"%c",c);
		}
	fprintf(stdout,"]\n");
	i+=R;

}


}

/*
 *  decode()
*/

int decode()
{
unsigned char buf[R];
int j=0,i=0,n,c;
int rc;
long x;

while (1)
{
        /* skip the counter */

	rc=read(0,buf,COUNTER+2);
	if (rc<=0 ) break;
	
	buf[0]=0;
	while (1 )
	{
	rc=read(0,buf,3);

	if ( 
	(buf[0]=='[') || (buf[0]==' ') \
	|| (buf[0]=='\n') \
	|| (buf[0]=='\t') \
	 ) /* skip ascii code */
		{
		while ( read(0,buf,1) && (buf[0]!='\n') );
		break;
		}
	else
		{	
		buf[2]=0;
		x=strtol( (const char*)(buf),0,16);
		printf("%c", x);
		} 
	}	
}

} /* end decode */

main(int argc, char** argv)
{
char op=0;

/* Parsing */

if ( argc==1)
	op=0;
else
	{
	if ( argv[1][0] == '-' )
	op=argv[1][1];
	}

switch ( op )
{
case 'h':{ 
	fprintf(stderr,"%s",USAGE); exit;
	break;
	}
case 'c':
	{ code(); break;}
case 'd':
	{ decode(); break;}
default: {fprintf(stderr,"%s",USAGE) ;exit(1);}
}


}
