/*
** BYTEVAL -- Convert one of four formats to one of four formats
**	The formats: octal (0#), decimal (#), hex (0x#), or keyname ([A-G]...)
**
** Input may be arguments or stdin, one per line.
** If args, output will be a single line.
** If stdin, output will be one per line.
** Exit status will be 0 iff no errors & all values fit in a byte
**	psl 10/88
*/
#include <stdio.h>
#define	DECIMAL	1
#define	HEX	2
#define	HEX0X	3
#define	NAME	4
#define	OCTAL	5

int	Out	= HEX;
int	Errs	= 0;

main(argc,argv)
char *argv[];
{
	register int i, args = 0;
	char buf[128];

	for (i = 1; i < argc; i++) {
	    if (argv[i][0] == '-') {
		switch (argv[i][1]) {
		case 'd':			/* decimal output */
		    Out = DECIMAL;
		    break;
		case 'h':			/* naked hexadecimal output */
		    Out = HEX;
		    break;
		case 'x':			/* "0x" hexadecimal output */
		    Out = HEX0X;
		    break;
		case 'o':			/* octal output */
		    Out = OCTAL;
		    break;
		case 'k':			/* keyname output */
		case 'n':			/* ditto */
		    Out = NAME;
		    break;
		default:
		    fprintf(stderr, "Illegal output conversion: %s\n", argv[i]);
		    Errs++;
		}
	    } else {
		args++;
		print(cvt(argv[i]), " ");
	    }
	}
	if (args)
	    printf("\n");
	else
	    while (fgets(buf, sizeof buf, stdin))
		print(cvt(buf), "\n");
	if (!Errs)
	    exit(0);
syntax:
	fprintf(stderr, "Usage: %s [CONV] [args or stdin]\n", argv[0]);
	fprintf(stderr, "Legal output CONVersions are:\n");
	fprintf(stderr, "-d\tdecimal (e.g. 60)\n");
	fprintf(stderr, "-h\tnaked hexadecimal, the default (e.g. 3c)\n");
	fprintf(stderr, "-k or -n\tkey name (e.g. C4)\n");
	fprintf(stderr, "-o\toctal (e.g. 0074)\n");
	fprintf(stderr, "-x\t\"0x\" hexadecimal (e.g. 0x3c)\n");
	fprintf(stderr, "Input may be either from arguments or stdin,\n");
	fprintf(stderr, "and may be in any format EXCEPT \"naked hex\".\n");
	fprintf(stderr, "Exit status 0 iff no errors & all nums fit a byte.\n");
	exit(1);
}

cvt(arg)
char	*arg;
{
	int i;

	if ('A' <= *arg && *arg <= 'G')
	    i = name2key(arg);
	else
	    i = myatoi(arg);
	if (i < 0 || i > 0xff)
	    Errs++;
	return(i);
}

print(val, sep)
{
	if (Out == DECIMAL)
	    printf("%3d%s", val, sep);
	else if (Out == HEX)
	    printf("%02x%s", val, sep);
	else if (Out == HEX0X)
	    printf("0x%02x%s", val, sep);
	else if (Out == NAME)
	    printf("%s%s", key2name(val), sep);
	else
	    printf("0%03o%s", val, sep);
}
