/*
 *    search.c
 *
 *      alfa-beta vyhledavaci funkce
 *
 */

#include"data.h"

int SAlfaBeta(THra *, int, int, int, int);	/* silent alfa-beta */

extern int IQ, SIQ;

int AlfaBeta(THra * H, int depth, int alpha, int beta)
{
	THra temp;
	TMG mg;
	int best, p, i = 0, value;
	char c[5];

	if (depth <= 0) {
		if (SIQ < 0)
			return SAlfaBeta(H, depth, alpha, beta, 0);
		else
			return Ohodnot(H);
	}
	p = MoveGen(H, mg, 0);

	if (p == 0)
		return Ohodnot(H);

	best = -MATVAL;
	while (i < p && best < beta) {
		temp = *H;
		Num2Not(mg[i].odkud, &c[0]);
		Num2Not(mg[i].kam, &c[2]);
		ZpracujTah(c, &temp);
		if (best > alpha)
			alpha = best;
		value = -AlfaBeta(&temp, depth - 1, -beta, -alpha);
		if (value > best)
			best = value;
		i++;
	}

	return best;
}

int SAlfaBeta(THra * H, int depth, int alpha, int beta, int nt)
{
	THra temp;
	TMG mg;
	int best, p, i = 0, value;
	char c[5];

	if (depth <= SIQ) {
		if (depth < 0)
			return OhodnotM(H);
		else
			return Ohodnot(H);
	}
	p = SMoveGen(H, mg);

	best = -MATVAL;
	while (i < p && best < beta) {
		temp = *H;
		Num2Not(mg[i].odkud, &c[0]);
		Num2Not(mg[i].kam, &c[2]);
		ZpracujTah(c, &temp);
		if (best > alpha)
			alpha = best;
		value = -SAlfaBeta(&temp, depth - 1, -beta, -alpha, 0);
		if (value > best)
			best = value;
		i++;
	}
	/* vygenerovat take NULL tah */
	/* jinak bude napriklad nucen delat nevyhodne
	   braci tahy */
	if (nt == 0) {
		temp = *H;
		if (H->natahu == BILYH)
			temp.natahu = CERNYH;
		else
			temp.natahu = BILYH;
		temp.enpas = -1;	/* no enpassant while NULL move */
		value = -SAlfaBeta(&temp, depth - 1, -beta, -alpha, 1);
		if (value > best)
			best = value;
	} else if (nt == 1 && p == 0)
		return OhodnotM(H);

	return best;
}
