#include "mergeSort.h"

#include <stdlib.h>
#include <assert.h>
#include <pthread.h>

void* merge_sort(void* args) {
	mrg_t* f = (mrg_t*) args;
	if(f->slice.start < f->slice.final) {
		int middle = (f->slice.start + f->slice.final) / 2;

		mrg_t args1 = {f->array, f->_depth+1, {f->slice.start, middle}};
		mrg_t args2 = {f->array, f->_depth+1, { middle+1, f->slice.final}};

		if(f->_depth * f->_depth < THREADS){
			pthread_t t1, t2;
			assert(!pthread_create(&t1, NULL, merge_sort,  (void*) &args1));
			assert(!pthread_create(&t2, NULL, merge_sort,  (void*) &args2));
			assert(!pthread_join(t1, NULL));
			assert(!pthread_join(t2, NULL));
		}else{
			merge_sort((void*) &args1);
			merge_sort((void*) &args2);
		}
		merge(f->array, f->slice.start, middle, f->slice.final);
	}
	return NULL;
}

void merge(int array[], uint8_t start, uint8_t middle, uint8_t final) {

	uint8_t countL = middle - start + 1;
	int *arrayL = malloc(countL * sizeof(int));
	for(uint8_t currentL = 0; currentL < countL; currentL ++)
		arrayL[currentL] = array[start + currentL ];

	uint8_t countR = final - middle;
	int* arrayR = malloc(countR * sizeof(int));
	for(uint8_t currentR = 0; currentR < countR; currentR ++)
		arrayR[currentR] = array[middle + 1 + currentR ];

	uint8_t currentL, currentR, current;
	for(currentL = 0, currentR = 0, current = start;
		 	current <= final && currentL < countL && currentR < countR;
		   	current ++) 
		if(arrayL[currentL] <= arrayR[currentR])
			array[current] = arrayL[currentL++];
		else
			array[current] = arrayR[currentR++];

	while(currentR < countR)
		array[current++] = arrayR[currentR++];
	while(currentL < countL)
		array[current++] = arrayL[currentL++];

	free(arrayL);
	free(arrayR);
}
