/*
 * This code is GPL.
 * 2012-11-17 (1391-08-27)
 */

#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

/* packet data (65535) + packet length (5) + safety(1) */
#define BUFSIZE 65541

void show_buffer(unsigned char *buf, int len)
{
	int i;

	/* Show packet length at first 5 characters */
	fprintf(stdout, "%05d", len);

	/* Show packet payload */
	for (i = 0; i < len; i++) {
		fprintf(stdout, "%c", buf[i]);
		fflush(stdout);
	}
	fflush(stdout);
}

unsigned char hex2dec(unsigned char hex)
{
	unsigned char ch;
	ch = hex - 48;
	if (ch > 9)
		ch -= 39;
	return ch;
}

void decode(unsigned char *buf, int len)
{
	int i, j;
	unsigned char *bin;
	unsigned char dec, ch;

	bin = (char *)malloc(len / 3);

	for (i = 0, j = 0; i < len; i += 3, j++) {
		// fprintf(stdout, "%c", buf[i]);
		bin[j] = hex2dec(buf[i + 1]) * 16 + hex2dec(buf[i + 2]);
		//fprintf(stdout, "%d ", bin[j]);
	}
	show_buffer(bin, len / 3);
}

int get_char()
{
	int buf[1];
	ssize_t ret;

	ret = read(0, (void *)buf, 1);
	if (ret == -1) {
		perror("Error! read()");
		exit(EXIT_FAILURE);
	}
	if (ret == 0) {
		return EOF;
	}

	return *buf;
}

void get_data()
{
	int i, ch;
	unsigned char buf[BUFSIZE] = { 0 };

	for (i = 0; i < BUFSIZE - 1; i++) {
		buf[i] = get_char();
		if (buf[i] == 10) {
			buf[i] = 0;
			break;
		}
	}

	decode(buf, i);
}

int main(void)
{
	while (1)
		get_data();
	return 0;
}