#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>

#define ALGS 8
#define MAX_SIZE 32768

#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif


int main(int intc, char **argv){
	FILE *in;
	uint16_t a,b,c;
	size_t cur_wins = 0;
	size_t max_wins = 0;
	//size_t cur_fastest = 0;
	size_t cur_cycles = 0;

	uint16_t positions_alg[4] = {0,0,0,0};
	uint16_t positions_start[4] = {0,0,0,0};
	uint16_t positions_end[4] = {0,0,0,0};
	uint16_t positions_max[4] = {32764, 32765, 32766, 32767};

	uint16_t winning_starts[4] = {0,0,0,0};
	uint8_t winning_algs[4] = {0,0,0,0};
	uint32_t data[ALGS][MAX_SIZE];
	uint32_t fastest[MAX_SIZE];
	uint32_t read_buffer_size = 64;
	char *read_buffer = (char *)malloc(read_buffer_size + 1);
	(void)memset( (void *)read_buffer, '\0', read_buffer_size + 1);

	uint32_t test_max = atoi(argv[1]);


	for(a=0; a<ALGS; a++){
#ifdef IS32BIT
		if(a == 5)
			continue;
#endif
		(void)sprintf(read_buffer, "results/r%u.txt", a+1);
		in = fopen(read_buffer, "r");
		b = 0;
		(void)memset( (void *)read_buffer, '\0', read_buffer_size + 1);
		while( fgets(read_buffer, read_buffer_size, in) != NULL){
			if(b == MAX_SIZE)
				break;
			data[a][b] = atoi(read_buffer);
			b++;
		}
		fclose(in);
	}
	free(read_buffer);

	//put only the times of the fastest in new array
	for(a=0; a<MAX_SIZE; a++){
		cur_cycles = UINT32_MAX;
		for(c=0; c<ALGS; c++){
			if(data[c][a]<cur_cycles){
				//cur_fastest = c;
				cur_cycles = data[c][a];
			}
		}
		fastest[a] = cur_cycles;
	}


	positions_start[0] = 0;
	//positions_start[0] = positions_max[0];

	positions_max[0]=test_max-2;
	positions_max[1]=test_max-1;

	for(positions_end[0]=positions_max[0]; positions_end[0]>positions_start[0]; positions_end[0]--){
		//printf("%u/64\n", positions_end[0]);
		positions_start[1] = positions_end[0];
		for(positions_end[1]=positions_max[1]; positions_end[1]>positions_start[1]; positions_end[1]--){
			for(positions_alg[0]=0; positions_alg[0]<ALGS; positions_alg[0]++){
				for(positions_alg[1]=0; positions_alg[1]<ALGS; positions_alg[1]++){
					//for(positions_alg[2]=0; positions_alg[2]<ALGS; positions_alg[2]++){
					//	for(positions_alg[3]=0; positions_alg[3]<ALGS; positions_alg[3]++){
							cur_wins = 0;
							for(a=0; a<test_max; a++){
								if(a < positions_start[1]){
									b = positions_alg[0];
								}else{
									b = positions_alg[1];
								}
								if(fastest[a] == data[b][a])
									cur_wins++;
							}
							if(cur_wins < max_wins)
								continue;
							for(a=0; a<2; a++){
								winning_starts[a] = positions_start[a];
								winning_algs[a] = positions_alg[a];
							}
							max_wins = cur_wins;
							//}
						//}
					//}
				}
			}
		}
	}

	printf("config with most wins in first %u:\n", test_max);
	printf("winning_alg\tstart\n");
	for(a=0; a<2; a++){
		printf("\t%u\t\t%u\n", winning_algs[a], winning_starts[a]);
	}
	//printf("\n");
	//printf("\n");
	//printf("\n");

	return 0;
}
