#include "search.h"
#include <time.h>

extern const char * Feature_name[nbFeatures];
extern int feature[2][nbFeatures];

void flip_board(void);

void runsuite(char * epd, int ms, int deep){
	FILE * ts;
	FILE * ws;
	FILE * results;
	char name[64] = {0};
	char namw[64] = {0};
	char fen[512];
	char mv[8];
	char dmv[8];
	uMOVE move[1];
	sMOVES * mi;
	char bm[8] = {0};
	char * score;
	int avoid = 0;
	long tnodes = 1;
	long elapsed = 1;
	long tscore = 0;
	long long begin;
	int p = 0;
	int n=0;//, m=0;
	int wa=0, ra=0;
	int b = 0;
	int i,s;

	float sumbf = 0.0f;
	float sumid = 0.0f;
	float sumsd = 0.0f;
	float sumqd = 0.0f;

	/*
	int results[nbFeatures];
	*/
	int sumstm[nbFeatures]={0};
	int sumsnm[nbFeatures]={0};
	
	time_t t;
	t = time(&t);

#ifdef _WIN32     
	strcpy(name, "../tests/");
	strcpy(namw, "../tests/w_");
#else
	strcpy(name, "./tests/");
	strcpy(namw, "./tests/w_");
#endif
	strcat(name, epd);
	strcat(name, ".epd");
	if(ms <= 0 || ms > 360000) ms = 360000;
	if ((ts = fopen(name, "r")) == NULL){
		printf("Read error occurred: could not open %s\n", name);
		return; 
	}
	strcat(namw, epd);
	strcat(namw, ".epd");
	if ((ws = fopen(namw, "w")) == NULL){
		printf("Read error occurred: could not open %s\n", namw);
		return; 
	}

	if ((results = fopen("results.txt", "a")) == NULL){
		printf("Read error occurred: could not open results.txt\n");
		return;
	}

	//fprintf(results, "%s @ %d ms\nopen    menace  outpost undermi BvN     Tony\n", name, ms);

#ifdef LOG
	fprintf(debuglog, "Time   Reserv Mo   Depth    Knodes evals FH1   BF   Extend   Checks   recap    etd    rtd     pawn     end   seekT   1reps   mate   dangT    null   delta  futile xfutile   razor    hist  reducT     res hash  hit  WW P BB P   move  score  delta     ?  ? fen\n");
#endif

	begin = _tick();

	while(fgets(fen, 512, ts) != NULL){
		if(fen[0] == '#' || fen[0] == '\0' || fen[0] == ' ');
		else if(fen[0] == '=') {
			if(wa)
				fprintf(results, "%d%%\t", 10*ra/(wa));
			fprintf(ws, "%s", fen);
			ra=wa=0;
		}
		else{
			
			if(strstr(fen, "bm")) {
				
				strncpy(bm, strstr(fen, "bm")+3, 7);
				
				avoid = 0;
			}
			else if(strstr(fen, "am")) {
				
				strncpy(bm, strstr(fen, "am")+3, 7);
				
				avoid = 1;
			}
			else printf("No Best Move!!!");
			
			setup(fen);
			
			
			
			
			{ 
			printf("%d %d %ld\n", p, b, tscore);
			
			printf("%s\n", fen); 
			//begin = _tick();

			if(deep > 1) {
				
				++wa;
				n = think(ms, 0, deep);
				
				move->asint = pv[1][1].asint;
				move2str(move, dmv); // original, in case EPD does NOT disambiguate
				move2str(move, mv);
				/* disambiguation  HACK */
				for (mi = last_move[0]; mi < last_move[1]; ++mi) {
					if(mi->move.data.piece == move->data.piece && mi->move.data.dest == move->data.dest && mi->move.asint != move->asint) {
					       if(FILE(mi->move.data.from) != FILE(move->data.from)) {
					       		for (i=6; i>0 ;i--) mv[i+1] = mv[i];
					 		mv[1] = 'a' + FILE(move->data.from);
					       }
			       			else if(RANK(mi->move.data.from) != RANK(move->data.from)) {
					       		for (i=6; i>0 ;i--) mv[i+1] = mv[i];
					 		mv[1] = '1' + RANK(move->data.from);
					       }
					}
				}				

				printf("%s\n", mv);
				
				
				
				if(avoid) {
					if(!strncmp(bm, mv, strlen(mv))) {
						//++wa;
						printf("WRONG???\n");
						fprintf(ws, "%s", fen);
					}
					else {
						ra += 10;
						printf("RIGHT!!!\n");
					}
				}
				else {
					//if(!strncmp(bm, mv, strlen(mv))) {
					if((score=strstr(fen, mv))) {
						//++ra;
						printf("RIGHT!!!\n");
						while(*score != '=') ++score;
						++score;
						sscanf(score, "%d", &s);
						ra += s;
					}
					else if((score=strstr(fen, dmv))) {
						//++ra;
						printf("RIGHT!!!\n");
						while(*score != '=') ++score;
						++score;
						sscanf(score, "%d", &s);
						ra += s;
					}
					else {
						//++wa;
						printf("WRONG???\n");
						fprintf(ws, "%s", fen);
					}
				}
				
				sumbf += bf;
				sumid += idepth;
				sumsd += sdepth;
				sumqd += qdepth;
			}
			else if(deep == 1)
				n = squies(-MATE,MATE);
			else{
				n = evaluate();
				
				//display();
				
				for (i=0; i<nbFeatures; ++i) {
					
					//printf("WHITE %s: %d\tBLACK %s: %d\n", Feature_name[i], feature[WHITE][i], Feature_name[i], feature[BLACK][i]);
					
					sumstm[i] += (feature[stm][i] /* - feature[stm^1][i] */);
					sumsnm[i] += feature[stm^1][i];
					
				}
				//getchar();
				
				/* sort templist 
				g = nbFeatures-1;
				do{
					f = 0;
					for(i = 0; i < g; ++i){
						if(templist[i] < templist[i+1]){
							t = templist[i+1];
							templist[i+1] = templist[i];
							templist[i] = t;
							f = 1;
						}
					}
					--g;
				}while(f);
				*/
				

#ifdef LOG
				//fprintf(debuglog, "%d  %s\n", n, fen); 
#endif
				
				/*
				flip_board();
				m = evaluate();
				
				if(n != m){
					printf("\a%d != %d\n", n, m);
					break;
				}
				//*/
				
			}

			//elapsed += (long)((_tick()-begin)/1000);
			tnodes += nodes;
			
			tscore += (stm)? n : -n;
			
			++p;
			b += ((stm<<1) - 1);
		}
		if(Bioskey()) break;
		
		}
	}

	elapsed += (long)((_tick()-begin)/1000);		

#ifdef LOG
	fprintf(debuglog, "%s %s\n", name, ctime(&t));
	fprintf(debuglog, "Total tree size = %ldK ", tnodes/1024);
	if(elapsed) {
		fprintf(debuglog, "KNPS = %ld ", tnodes/elapsed/1024);
	}
	fprintf(debuglog, "Avg Depth = %1.1f ", (float)(sumid/p));
	fprintf(debuglog, "Avg Selec = %1.1f ", (float)(sumsd/p));
	fprintf(debuglog, "Avg Quies = %1.1f ", (float)(sumqd/p));
	fprintf(debuglog, "SUM Score= %ld ", tscore);
	fprintf(debuglog, "Avg EBF = %1.1f\n", (float)(sumbf/p));
	
	if(wa) {
		fprintf(debuglog, "Correct : %d  out of %d (%d%%)\n", ra/10, wa, 10*ra/wa);
	}
#endif   
	printf("Avg Depth = %1.1f ", (float)(sumid/p));
	printf("Avg Selec = %1.1f ", (float)(sumsd/p));
	printf("Avg Quies = %1.1f ", (float)(sumqd/p));
	printf("Avg EBF = %1.1f\n", (float)(sumbf/p));
	printf("SUM = %ld\n\a\a", tscore);
	if(elapsed) {
		printf("KNPS = %ld ", tnodes/elapsed/1024);
	}
	if(wa) {
		printf("Correct : %d  out of %d (%d%%)\n", ra/10, wa, 10*ra/wa);
	}
	
	if(deep == 0) {
		n = 0;
		for (i=0; i<nbFeatures; ++i)
			n += abs(sumstm[i] - sumsnm[i]);
		for (i=0; i<nbFeatures; ++i) {
			printf("%s:  \t%d\t%d\t(%d)\t[%d%%]\n", Feature_name[i], sumstm[i], sumsnm[i], sumstm[i] - sumsnm[i], 100 * (sumstm[i] - sumsnm[i])/n);
		}
	}

	fprintf(results, "\n");
	fclose(ts);
	fclose(ws);
	fclose(results);
	return;
}
