/* This is not working , I am keeping it for kb_hit example */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>

int kb_hit(void)
{
	fd_set rfds;
	struct timeval tv;
	int ret;

	/* Watch stdin (fd 0) to see when it has input. */
	FD_ZERO(&rfds);
	FD_SET(0, &rfds);

	/* Wait a millisecond */
	tv.tv_sec = 0;
	tv.tv_usec = 1000;

	ret = select(1, &rfds, NULL, NULL, &tv);

	if (ret == -1) {
		perror("Error! select()");
		exit(EXIT_FAILURE);
	}
	if (FD_ISSET(0, &rfds)) {
		/* key was hit and data is available now */
		return 1;
	}
	/* No key press within a millisecond */
	return 0;
}

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

	if (kb_hit() == 1) {
		fflush(stdout);
		printf("RED ");
		fflush(stdout);
	} else {
		fflush(stdout);
		printf("NO ");
		fflush(stdout);
	}

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

	return *buf;
}

void show_buffer(unsigned char *buf, int len)
{
	int i, j;
	char str[17];

	fflush(stdout);
	printf("BUF ");
	fflush(stdout);
	str[16] = 0;
	printf("\n");
	for (i = 0; i < len; i += 16) {
		fflush(stdout);
		fprintf(stdout, "   ");
		for (j = 0; j < 16 && i + j < len; j++) {
			fflush(stdout);
			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++) {
			fflush(stdout);
			fprintf(stdout, "   ", buf[i + j]);
			str[j] = ' ';
		}
		fflush(stdout);
		printf("   |   %s   |\n", str);
	}
	fflush(stdout);
}

int main()
{
	int i, ch, len, factor;
	unsigned char *buf;

	ch = get_char();
	while (ch != EOF) {

		/* Read packet length */
		factor = 10000;
		len = 0;
		for (i = 0; i < 5 && ch != EOF; i++) {
			ch = (unsigned char)ch - 48;
			len += (ch * factor);
			factor /= 10;
			ch = get_char();
			if (ch == EOF)
				break;
		}

		buf = (unsigned char *)malloc(len);
		memset(buf, 0, len);

		/* Read packet data */
		for (i = 0; i < len && ch != EOF; i++) {
			buf[i] = ch;
			ch = get_char();
			if (ch == EOF)
				break;

			fflush(stdout);
			printf("GOT %d", i);
			fflush(stdout);
		}
		fflush(stdout);
		printf("BUF2 ");
		fflush(stdout);

		int i, j;
		char str[17];

		str[16] = 0;
		printf("\n");
		for (i = 0; i <= len; i += 16) {
			fflush(stdout);
			fprintf(stdout, "   ");
			for (j = 0; j < 16 && i + j < len; j++) {
				fflush(stdout);
				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++) {
				fflush(stdout);
				fprintf(stdout, "   ", buf[i + j]);
				str[j] = ' ';
			}
			fflush(stdout);
			printf("   |   %s   |\n", str);
		}
		fflush(stdout);

		// show_buffer(buf, len);

		free(buf);
	}

	return (EXIT_SUCCESS);
}