/*
 * 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, j;
	char str[17];

	str[16] = 0;
	printf("\n");
	for (i = 0; i < len; i += 16) {
		fprintf(stdout, "   ");
		for (j = 0; j < 16 && i + j < len; j++) {
			fprintf(stdout, "%02x ", buf[i + j]);

			if (buf[i + j] > 32 && buf[i + j] < 127)
				str[j] = buf[i + j];
			else
				str[j] = '.';
		}
		for (; j < 16; j++) {
			fprintf(stdout, "   ", buf[i + j]);
			str[j] = ' ';
		}
		printf("   |   %s   |\n", str);
	}
	fflush(stdout);
}

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;
}

int get_len()
{
	int i, ch, factor, len;

	factor = 10000;
	len = 0;
	for (i = 0; i < 5; i++) {
		ch = get_char();
		ch = (unsigned char)ch - 48;
		len += (ch * factor);
		factor /= 10;
	}
	if (len < 0 || len > 65535) {
		printf("Packet length Error: %d", len);
		exit(EXIT_FAILURE);
	}

	return len;
}

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

	len = get_len();

	for (i = 0; i < len; i++)
		buf[i] = get_char();

	show_buffer(buf, len);
}

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