#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void
usage(char *argv0)
{
	fprintf(stderr, "usage: %s [-rh] < FILE\n", argv0);
}

int
hex2int(int c)
{
	c = toupper(c);
	if (c >= '0' && c <= '9')
		return c - '0';
	if (c >= 'A' && c <= 'F')
		return c - 'A' + 10;
	return -1;
}

char *
tobin(char *in, char *out, size_t len)
{
        size_t i;

        for (i = 0; i < len; i++)
                out[i] = hex2int(in[i * 2]) << 4 | hex2int(in[i * 2 + 1]);
        return out;
}

char *
tohex(char *in, char *out, size_t len)
{
        size_t i, j;
        char hex[] = "0123456789abcdef";

        memset(out, 0, len*2 + 1);
        for (i=0, j=0; i<len; i++, j++) {
                out[j]   = hex[(unsigned char)in[i] >> 4];
                out[++j] = hex[(unsigned char)in[i] & 15];
        }

        return out;
}

int
main(int argc, char *argv[])
{
	int reverse = 0;
	char c;
	char h[3] = "";

	if (argc > 1 && argv[1][0] == '-') {
		switch (argv[1][1]) {
		case 'r':
			reverse = 1;
			break;
		default:
			usage(argv[0]);
			return -1;
		}
	}

	if (reverse) {
		while (read(0, &c, 1) > 0)
			printf("%s", tohex(&c, h, 1));
		putc('\n', stdout);
	} else {
		while (read(0, h, 2) > 1)
			printf("%c", *tobin(h, &c, 1));
	}

	return 0;
}
