#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>

#include "streamrecode.h"

int main(int argc, char *argv[]) {
	recode_Packet *packet;
	struct sockaddr_in your_addr;
	struct timeval tv;
	size_t packetlen;
	int sockfd;

	memset(&tv, 0, sizeof(tv));

	if ((sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
		fprintf(stderr, "%s: Couldn't create socket: %s\n", argv[0], 
				strerror(errno));
		exit(1);
	}

	your_addr.sin_family = AF_INET;
	your_addr.sin_port   = htons(2003);
	your_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
	if (connect(sockfd, (const struct sockaddr*)&your_addr, sizeof(your_addr))
			== -1) {
		fprintf(stderr, "%s: Couldn't connect: %s\n", argv[0], strerror(errno));
		exit(1);
	}

	packetlen = sizeof(recode_Packet) + MAX_PACKET_SIZE;
	packet = (recode_Packet*)new char[packetlen];

	packet->recode_Type   = RECODE_DATA;
	packet->recode_Length = packetlen;

	while (1) {
		fd_set rfds;
		
		FD_ZERO(&rfds);
		FD_SET(sockfd, &rfds);

		send_recode_command(sockfd, "skip 10");
		send_recode_packet(sockfd, packet);
		
		while (select(sockfd + 1, &rfds, 0, 0, &tv) > 0) {
			recode_Packet *p;
			p = recv_recode_packet(sockfd);
			if (p) {
				if (p->recode_Type != RECODE_DATA)
					fprintf(stderr, "%s: Wrong type!!!\n", argv[0]);
			} else {
				fprintf(stderr, "%s: This shouldn't happen!\n", argv[0]);
				exit(1);
			}

			delete p;
		}
		usleep(1000);
	}
}
