#include "globals.h"

void EvalPawns();
bool Pawns(int& s,const int file);
bool Pawns2(int& s,const int start);
/*  

Eval() is simple. Firstly it fetches the table scores which were updated whenever moves were
updated. 

It then looks up the pawn hash table. If the pawn position is not
already stored it evaluates the pawns and adds the scores to the pawn hash table.
It adds the pawn scores for each side.

It then adds a score for the king position depending on how much material the opponent has.
It adds a bonus for a pawn or piece in front of the King. (A very simple King defence score).

It turn returns the side to moves score minus the opponent's score.

There are plenty of things that could be added to the eval function.

 */
int Eval()
{
  int s0 = table_score[0];
  int s1 = table_score[1];
//
if(LookUpPawn()==0)
{
	EvalPawns();
}
s0 += GetHashPawn0();
s1 += GetHashPawn1();
//
  if(s1 < 1000)
    s0 += king_endgame[0][kingloc[0]];
  else
  {
	if(row[kingloc[0]] < 2 && color[kingloc[0]+8]==0)
		s0 += 10;
  }

  if(table_score[0] < 1000)
    s1 += king_endgame[1][kingloc[1]];
  else
  {
	if(row[kingloc[1]]>5 && color[kingloc[1]-8]==1)
		s1 += 10;
  }

  if(side==0)
	  return s0 - s1;
  else
	  return s1 - s0;
}
/*  

EvalPawns() evaluates each pawn and gives a bonus for passed pawns
and a minus for isolated pawns.
Total scores are stored in the pawn hash table.

 */
void EvalPawns()
{
int score[2];
score[0] = 0;
score[1] = 0;
int s, xs;
for(int x = A2;x < A8;x++)
{
	if(board[x] == P)
	{
		s = color[x];
		xs = 1-s;
		if( !Pawns2(xs,x) &&
			(col[x]==0 || !Pawns2(xs,x-1)) &&
			(col[x]==7 || !Pawns2(xs,x+1)) )
			{
				score[s] += passed[s][x];
			}
		if( (col[x]==0 || !Pawns(s,col[x]-1)) && (col[x]==7 || !Pawns(s,col[x]+1)) )
			score[s] -= 20;
	}
}
AddPawnHash(score[0],score[1]);
}
/*  

Pawns() searches for pawns on a file.
It is used to detect isolated pawns.

 */
bool Pawns(int& s,const int file)
{
for(int x = file + 8;x < A8; x += 8)
{
	if(board[x]==P && color[x]==s)
		return true;
}
return false;
}
/*  

Pawns2() searches for pawns on a file beyond a square.
It is used to detect passed pawns.

 */
bool Pawns2(int& s,const int start)
{
int pawns = 0;
int diff = 8;
if(s==0) diff = -8;
for(int x = start + diff;x < A8; x += diff)
{
	if(board[x]==P && color[x]==s)
		return true;
}
return false;
}