/* Lab. 10 - Es. 04 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>

typedef struct {
	pthread_t tid;
	int *v;
	int len;
} thread_merge_arg_t;

void *thread_f(void *arg) {
	thread_merge_arg_t* s = (thread_merge_arg_t *)arg;
	
	if (s->len <= 1) {
		return NULL;
	}
	
	thread_merge_arg_t args[2];
	
	args[0].v = s->v;
	args[0].len = s->len - (s->len >> 1);
	
	if (pthread_create(&args[0].tid, NULL, thread_f, (void *)&args[0]) != 0) {
		fprintf(stderr, "Error while creating thread.\n");
		exit(-1);
	}
	
	args[1].v = s->v + s->len - (s->len >> 1);
	args[1].len = s->len >> 1;
	
	if (pthread_create(&args[1].tid, NULL, thread_f, (void *)&args[1]) != 0) {
		fprintf(stderr, "Error while creating thread.\n");
		exit(-1);
	}
	
	pthread_join(args[0].tid, NULL);
	pthread_join(args[1].tid, NULL);
	
	/* MERGE */
	const int left = 0;
	const int center = s->len - (s->len >> 1);
	const int right = s->len;
	
	int i = left;
	int j = center;
	int k = 0;
	int* b = (int *)malloc(sizeof(int) * s->len);
	while (i < center && j < right) {
		if (s->v[i] <= s->v[j]) {
			b[k] = s->v[i];
			i++;
			k++;
		}else{
			b[k] = s->v[j];
			j++;
			k++;
		}
	}
	while (i < center) {
		b[k] = s->v[i];
		i++;
		k++;
	}
	while (j < right) {
		b[k] = s->v[j];
		j++;
		k++;
	}
	for (k = 0; k < right; k++) {
		s->v[k] = b[k];
	}
	free(b);
	
	return NULL;
}

int main(int argc, char **argv) {
	int i;
	size_t t;
	int len = 0;
	int *v = NULL;
	char *line = NULL;
	FILE *file = NULL;
	
	if (argc == 1) {
		/* random generation */
		srand(time(NULL));
		/* MAX 16 */
		len = rand() % 0x10;
		v = (int *)malloc(sizeof(int) * len);
		for (i = 0; i < len; i++) {
			v[i] = rand() % 0x100;
		}
	}else if (argc == 2) {
		/* from file */
		if ((file = fopen(argv[1], "r")) == NULL) {
			fprintf(stderr, "Error while opening '%s'.\n", argv[1]);
			return -1;
		}
		
		while (getline(&line, &t, file) != -1) {
			len++;
			free(line);
			line = NULL;
		}
		
		v = (int *)malloc(sizeof(int) * len);
		fseek(file, 0, SEEK_SET);
		
		i = 0;
		while (getline(&line, &t, file) != -1) {
			v[i] = atoi(line);
			free(line);
			line = NULL;
		}
		
		fclose(file);
	}else if (argc > 2) {
		/* from keyboard */
		len = argc - 1;
		v = (int *)malloc(sizeof(int) * len);
		for (i = 1; i < len; i++) {
			v[i - 1] = atoi(argv[i]);
		}
	}
	
	if (len == 0) {
		fprintf(stderr, "Vector was empty.\n");
		return -1;
	}
	
	/* PRINT ARRAY */
	for (i = 0; i < len; i++) {
	    printf("%d,",v[i]);
	}
	printf("\n");
	
	/* START */
	thread_merge_arg_t s;
	s.v = v;
	s.len = len;
	thread_f((void *)&s);
	
	for (i = 0; i < len; i++) {
	    printf("%d,",v[i]);
	}
	printf("\n");
	
	free(v);
	
	return 0;
}
