/*
 *    value.c
 *      =======
 *      - ohodnoceni pozice
 *              Martin Macok
 */

#include"data.h"

#define abs(x) (x>0 ? x : -x)
#define sign(x) (x==0 ? 0 : x / abs(x))

int Ohodnot(THra * H)
{				/* mat pat + matros */
	int p;
	TMG mg;
	p = MoveGen(H, mg, 1);
	/* urychleni by se ^^ melo dosahnout tim, ze negenerujeme vsechny tahy,
	   ale skoncime pri nalezeni prvniho ... */
	if (p == 0) {
		if (JeVSachu(H->natahu, H))	/* MAT */
			return -MATVAL;
		else
			return 0;	/* PAT */
	} else
		return OhodnotM(H);
}

int OhodnotM(THra * H)
{
	int i, v = 0,x,y, b2s = 0, c2s = 0;
	v += 2*(H->bily.rochada[0] - H->cerny.rochada[0]);
	v += H->bily.rochada[1] - H->cerny.rochada[1];
	v += H->bily.rochada[2] - H->cerny.rochada[2];
	v += 2*(sign(H->sachovnice[3][3]) + sign(H->sachovnice[3][4]) 
            + sign(H->sachovnice[4][3]) + sign(H->sachovnice[4][4]));
	v += sign(H->sachovnice[2][2]) + 
         sign(H->sachovnice[2][3]) + 
         sign(H->sachovnice[2][4]) + 
         sign(H->sachovnice[2][5]) + 
         sign(H->sachovnice[3][2]) + 
         sign(H->sachovnice[3][5]) + 
         sign(H->sachovnice[4][2]) + 
         sign(H->sachovnice[4][5]) + 
	     sign(H->sachovnice[5][2]) + 
         sign(H->sachovnice[5][3]) + 
         sign(H->sachovnice[5][4]) + 
         sign(H->sachovnice[5][5]);
	for (i = 1; i < 16; i++) {
		switch (H->bily.figury[i].fig) {
		case BPES:
			v += HPES;
            if (H->bily.figury[i].pos.x > 4) v++;
            if (H->bily.figury[i].pos.x > 5) v++;
			break;
		case BJEZ:
			v += HJEZ;
            x = H->bily.figury[i].pos.x;
            y = H->bily.figury[i].pos.y;
            if (x > 0 && y > 0 && x < 7 && y < 7) v++;
			break;
		case BSTR:
			v += HSTR;
            b2s++;
            if (b2s > 1) v++;
			break;
		case BVEZ:
			v += HVEZ;
			break;
		case BDAM:
			v += HDAM;
			break;
		}
		switch (H->cerny.figury[i].fig) {
		case CPES:
			v -= HPES;
            if (H->cerny.figury[i].pos.x < 3) v--;
            if (H->cerny.figury[i].pos.x < 2) v--;
			break;
		case CJEZ:
			v -= HJEZ;
            x = H->cerny.figury[i].pos.x;
            y = H->cerny.figury[i].pos.y;
            if (x > 0 && y > 0 && x < 7 && y < 7) v--;
			break;
		case CSTR:
			v -= HSTR;
            c2s++;
            if (c2s > 1) v--;
			break;
		case CVEZ:
			v -= HVEZ;
			break;
		case CDAM:
			v -= HDAM;
			break;
		}
	}
	if (H->natahu == BILYH)
		return v;
	else
		return -v;
}
