#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <time.h>
#include "../base.h"

#define PORT 23241

#define rand_max (double)RAND_MAX
#define r() ((rand()/rand_max)*2-1)

int main()
{
	int sockfd, newsockfd;
	int num_r, num_w;
	int errcode;
	socklen_t clilen=0;
	struct sockaddr_in cli_addr, serv_addr;
	char buff[BUFF_SIZE];
	struct timespec start[3], stop[3];
	double diff_time;

	srand(time(NULL));

	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd == -1) {
		system_error();
	}

	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	serv_addr.sin_port = htons(PORT);
	int optval = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));

	errcode = bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(struct sockaddr));
	if (errcode == -1) {
		system_error();
	}

	if (listen(sockfd, 5) == -1) {
		system_error();
	}

	while (1) {
		newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &clilen);
		if (newsockfd == -1) {
			system_error();
		}
		FILE *stream = fdopen(newsockfd, "r+");

		char direction;
		int times;
		int i, j;
		double out[16];
		fread(&direction, sizeof(char), 1, stream);
		fread(&times, sizeof(int), 1, stream);

		if (direction == 't') {
			for (i=0; i<times; i++) {
				fread(out, sizeof(double), 16, stream);

				if (i%100 == 0)
					printf("current %d\n", i);
			}
		}
		else if (direction == 'r') {
			for (int i=0; i<times; i++) {
				for (int j=0; j<16; j++)
					out[j] = r();
				fwrite(out, sizeof(double), 16, stream);

				if (i%100 == 0)
					printf("current %d\n", i);
			}
		}

		fclose(stream);
		close(newsockfd);

	}
	close(sockfd);

	return 0;
}

