Example #1
0
void test_pawn_divide(int depth)
{
  int i,move_count;
  move_t ms[MOVE_STACK];
  uint64 nodes = 0;
  uint64 total_nodes = 0;
  int legal_moves = 0;
  
  if(!depth) return;
  pawnhits = 0;
  pawncollisions = 0;
  pht_init();
  depth -= 1;
  timer_start();
  move_count = move_gen(&ms[0]);
  for(i = 0; i < move_count; i++)
  {
    if(!move_make(ms[i])) continue;
    nodes = perft(depth);
    print_move(ms[i].p);
    legal_moves++;
    printf("%I64u",nodes);
    printf("\n");
    move_undo();
    total_nodes += nodes;
  }
  printf("\nNodes: %I64u",total_nodes);
  printf("\nMoves: %d",legal_moves);
  printf("\nPawnHits: %d",pawnhits);
  printf("\nPawnCollisions: %d",pawncollisions);
  printf("\n\n");
  timer_stop();
  pht_free();
}
Example #2
0
BOOL test_perft960() {

	BOOL ok = TRUE;
	int i;
	t_nodes n = 0;

	if (!uci.engine_initialized)
		init_engine(position);

	//--Position 1
	//for (i = 0; i <= 1; i++) {
	//	set_fen(position, "R3rkrR/8/8/8/8/8/8/r3RKRr w EGeg - 0 1");
	//	n = perft(position, 5);
	//	ok &= (n == 12667098);
	//	global_nodes += n;
	//	flip_board(position);
	//}

	//--Position 2
	//for (i = 0; i <= 1; i++) {
		set_fen(position, "qr1kbb1r/1pp2ppp/3npn2/3pN3/1p3P2/4PN2/P1PP2PP/QR1KBB1R w HBhb -");
		n = perft(position, 6);
		ok &= (n == 3206947488);
	//	global_nodes += n;
	//	flip_board(position);
	//}

	if (ok)
		printf("Everything seems Fine - all PERFT 960 scores are correct\n");
	else
		printf("**ERROR** with PERFT 960 scores\n");

	return ok;
}
Example #3
0
unsigned long long perft(Board *board, int depth) {
    if (is_illegal(board)) {
        return 0L;
    }
    if (depth == 0) {
        return 1L;
    }
    int index = board->hash & MASK;
    Entry *entry = &TABLE[index];
    if (entry->key == board->hash && entry->depth == depth) {
        hits += entry->value;
        return entry->value;
    }
    unsigned long long result = 0;
    Undo undo;
    Move moves[MAX_MOVES];
    int count = gen_moves(board, moves);
    for (int i = 0; i < count; i++) {
        do_move(board, &moves[i], &undo);
        result += perft(board, depth - 1);
        undo_move(board, &moves[i], &undo);
    }
    entry->key = board->hash;
    entry->value = result;
    entry->depth = depth;
    return result;
}
Example #4
0
bool test_epd(char *filename)
{
  FILE *f;
  char c,*p;
  char line[255];
  char buff[255];
  uint64 nodes,result;
  int x,depth,position,errors,sum;

  f = fopen(filename, "r");
  if(f == NULL) return false;
  pht_init();
  timer_start();
  sum = 0;position = 0;result = 0;
  while(fgets(&line[0], sizeof(line), f))
  {				
    x = 0; p = &line[0];
    while(*p != ';'){	
      buff[x] = *p;
      p++; x++;
    }
    buff[x] = '\0';
    position++;
      
    if(!board_from_fen(&buff[0])){
      printf ("position %d - FEN error!\n\n", position);
      continue;
    }
    printf("\nposition %d\n",position);
    printf("----------------------\n");
    printf("%s\n",&buff[0]);
    printf("----------------------\n");
    
    depth = 0; errors = 0;
    while((*p != '\n') && (*p != 0))
    {
      if(*p == 'D'){
        depth++;
        sscanf(p,"%s %I64u",&c,&result);
        printf("depth %d: ",depth);
        nodes = perft(depth);
        if(nodes != result){
          printf("error\n");
          errors++;
        }
        else printf("done\n");
      }
      p++;
    }
    printf("----------------------\n");
    printf("unmatched: %d \n\n", errors);
    sum+=errors;
  }
  printf("----------------------\nend_of_file.\n");
  printf("total mismatched depths: %d\n",sum);
  timer_stop();
  fclose(f);
  pht_free();
  return true;
}
//perft
int64_t SimplePVSearch::perft(Board& board, int depth, int ply) {
	if (depth == 0) {
		return 1;
	}
	int64_t time=0;
	if (ply==1) {
		prepareToSearch();
		time=getTickCount();
	}
	int64_t nodes=0;
	int64_t partialNodes=0;
	MoveIterator moves = MoveIterator();
	MoveIterator::Move move;
	board.setInCheck(board.getSideToMove());
	while (true)  {
		move = selectMove<false>(board, moves, emptyMove, ply, depth);
		if (moves.end()) {
			break;
		}
		MoveBackup backup;
		board.doMove(move,backup);
		partialNodes = perft(board, depth-1, ply+1);
		nodes += partialNodes;
		if (ply == 1) std::cout << move.toString() << ": " << partialNodes << std::endl;
		board.undoMove(backup);
	}
	if (ply==1 && isUpdateUci()) {
		std::cout << "Node count: " << nodes << std::endl;
		std::cout << "Time: " << (getTickCount()-time) << std::endl;
	}
	return nodes;
}
Example #6
0
int main(void)
{
	brd_t brd[1], chld_brd[1];
	mv_slct_t slct[1];

	init();

	parse_fen(brd,"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
	//"3r4/p6k/4p1rp/1pp1Pp2/2pN3R/4PQ1R/P2K2PP/1q6 b - - 0 1");
	display_board(brd);

	slct->hash_mv = 0;

	printf("sq(28)="SQ_FMT"\n",SQ_ARGS(28));
	/* Move loop. */
#define MV_SLCT_FN(mv) \
		printf("got move: m=%o f="SQ_FMT" t="SQ_FMT" m=%i c=%i p=%i\n", mv,\
				SQ_ARGS(MV_GET_F(mv)), \
				SQ_ARGS(MV_GET_T(mv)),\
				MV_GET_M(mv),\
				MV_GET_C(mv),\
				MV_GET_P(mv));\

#include "mv_slct.c"

#undef MV_SLCT_FN

	int x;
	for (x = 1; x < 5; x++)
		printf("p[%i]=%i\n", x, perft(brd, x));
}
Example #7
0
void testMoveGen()
{
    puts("Some hard positions for the moves generator.");
    puts("");
    puts(" A worthy test position by Albert Bertilsson for a *true* move generator \n testing!");//Belka: Albert Bertilsson's test position
    puts(" 8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - -  \n");
    puts(" Running Perft the following nodes are true: ");
    puts(" depth=1,  nodes=         14");
    puts(" depth=2,  nodes=        191");
    puts(" depth=3,  nodes=      2,812");
    puts(" depth=4,  nodes=     43,238");
    puts(" depth=5,  nodes=    674,624");
    puts(" depth=6,  nodes= 11,030,083");
    puts(" depth=7,  nodes=178,633,661 \n");

    setBoard("8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - -");

    hdp = 0;
    fifty = 0;
    hashKeyPosition(); /* hash of the initial position */

    int i;
    for (i=1; i<7; ++i)
        printf("Perft %d: %d\n", i, perft(i));

    puts("");
    puts(" The famous test position by Peter McKenzie for a *true* move generator testing!");//Belka: Albert Bertilsson's test position
    puts(" r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -  \n");
    puts(" Running Perft the following nodes are true: ");
    puts(" depth=1,  nodes=           48");
    puts(" depth=2,  nodes=        2,039");
    puts(" depth=3,  nodes=       97,862");
    puts(" depth=4,  nodes=    4,085,603");
    puts(" depth=5,  nodes=  193,690,690");
    puts(" depth=6,  nodes=8,031,647,685");

    setBoard("r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R wKQkq -");

    hdp = 0;
    fifty = 0;
    hashKeyPosition(); /* hash of the initial position */

    for (i=1; i<7; ++i)
        printf("Perft %d: %d\n", i, perft(i));
}
Example #8
0
void ConsoleGame::handleDivide(std::istringstream & iss) const
{
  uint perftLevel = readLevel(iss);
  if (perftLevel == 0)
    return;

  Perft perft(mBoard.get());
  perft.divide(perftLevel);
}
Example #9
0
void ConsoleGame::doPerft(int perftLevel) const
{
  Perft perft(mBoard.get());

  Stopwatch stopWatch(true);
  ulonglong totalNodes = perft.execute(perftLevel);
  std::string timeString = stopWatch.timeElapsedString();
  std::cout << "Total Nodes: " << totalNodes << " Time: " << timeString << "\n";
}
Example #10
0
void ConsoleGame::handleTestMoveGen() const
{
  std::string fileName("data/perftsuite.epd");
  std::ifstream inputStream(fileName.c_str());
  if (inputStream.fail()) {
    std::cout << "Could not locate perft test file " << fileName << "\n";
    return;
  }

  while (true) {
    std::string inputLine;
    std::getline(inputStream, inputLine);
    if (inputStream.fail())
      break;

    std::vector<std::string> tokens;
    util::split(tokens, inputLine, ';');
    if (tokens.size() < 1)
      continue;

    std::string fenString = tokens.at(0);
    if (tokens.size() > 1) {
      std::cout << "fen: " << fenString << "\n";
      mBoard->setPosition(fenString);
    }

    for (uint i = 1; i < tokens.size(); i++) {
      std::string perftDepthString = tokens.at(i);

      std::vector<std::string> perftTokens;
      util::split(perftTokens, perftDepthString, ' ');
      if (perftTokens.size() < 2)
        continue;

      std::string depthString = perftTokens.at(0);
      std::string nodesString = perftTokens.at(1);

      uint depthLevel = atoi(depthString.substr(1).c_str());
      uint numNodes = atoi(nodesString.c_str());

      Stopwatch stopWatch;
      Perft perft(mBoard.get());

      stopWatch.start();
      ulonglong totalNodes = perft.execute(depthLevel);
      std::string timeString = stopWatch.timeElapsedString();

      bool success = (totalNodes == numNodes);
      std::cout << "Perft (" << depthLevel << "): " << totalNodes << " nodes, ";
      std::cout << "Time: " << timeString << " s, [" << numNodes << "], ";
      std::cout << (success ? "OK" : "FAIL") << "\n";

      if (!success)
        return;
    }
  }
}
Example #11
0
File: test.c Project: Glank/chess
int runPerftTest(const char* start, int perft3){
    ChessBoard* board = ChessBoard_new(start);
    ChessMoveGenerator* gen = ChessMoveGenerator_new(board);
    int p = perft(board, gen, 3);
    int ret = p!=perft3;
    if(ret) printf("%d - ", p);
    ChessMoveGenerator_delete(gen);
    ChessBoard_delete(board);
    return ret;
}
Example #12
0
static void
cmd_perfts(void)
{
    unsigned depth;

    depth = get_uint(1, 1024);
    for (unsigned i = 1; i <= depth; ++i) {
        uintmax_t n = perft(current_position(), i);
        printf("%s%u : %" PRIuMAX "\n", (i < 10) ? " " : "", i, n);
    }
}
Example #13
0
void PERFT (typePOS* POSITION, int d)
{
  int i;
  Mobility (POSITION);
  for (i = 0; i < 64; i++)
    CNT[i] = 0;
  perft (POSITION, d, 1);
  for (i = d; i >= 2; i--)
    printf ("%lld/", CNT[i]);
  printf ("%lld\n", CNT[1]);
}
Example #14
0
//perft with timing & logging
static uint64 timeperft(int depth) {
    Timer timer;
    timer.start();
    uint64 n = perft(depth);
    timer.stop();
    double tickspo = timer.ticks()/double(n);
    double seconds = timer.seconds();
    double mnps    = n/(seconds*1000000); //meganodes/second
    printf("perft %i %14.0f %10.2fs %8.1f mnps %6.1f ticks/move\n", depth, double(n), seconds, mnps, tickspo);

    return n;
}
Example #15
0
void test_divide(int depth)
{
  int i,move_count;
  move_t ms[MOVE_STACK];
  uint64 nodes;
  uint64 total_nodes;
  int legal_moves;
  #ifdef EVASIONS
  char strbuff[256];
  move_t ms_test[MOVE_STACK];
  #endif
  
  if(!depth) return;
  nodes = 0;
  total_nodes = 0;
  legal_moves = 0;
  
  pht_init();
  depth -= 1;
  timer_start();
    
  #ifdef EVASIONS
  if(is_in_check(board->side))
  { move_count = move_gen_evasions(&ms[0]);
    if(move_count != move_gen_legal(&ms_test[0]))
    { board_to_fen(&strbuff[0]);
      printf("error: \n %s \n",strbuff);
    }
  }
  else
  { move_count = move_gen(&ms[0]);
  }
  #else
  move_count = move_gen(&ms[0]);
  #endif
    
  for(i = 0; i < move_count; i++)
  { if(!move_make(ms[i])) continue;
    nodes = perft(depth);
    print_move(ms[i].p);
    legal_moves++;
    printf("%I64u",nodes);
    printf("\n");
    move_undo();
    total_nodes += nodes;
  }
  printf("\nNodes: %I64u",total_nodes);
  printf("\nMoves: %d",legal_moves);
  printf("\n\n");
  timer_stop();
  pht_free();
}
Example #16
0
//slow non-bulk version: all moves are made and undone
static uint64 perft(int depth) {
    Move moves[MaxMoves];
    Move *last = _board.genmoves(moves);
    uint64 n=0;
    Undo undo = _board.save();
    for (Move *m=moves; m<last; m++) {
        _board.move(*m);
//      if (depth<2) n++; else n+=perft(depth-1);
        n+=(depth<2)?1:perft(depth-1);
        _board.undo(*m, undo);
    }

    return n;
}
Example #17
0
void perft_test(char *fen, unsigned long long *expected, int count) {
    Board board;
    board_load_fen(&board, fen);
    board_print(&board);
    double start = now();
    for (int depth = 0; depth < count; depth++) {
        hits = 0;
        unsigned long long actual = perft(&board, depth);
        char *result = actual == expected[depth] ? "PASS" : "FAIL";
        double elapsed = now() - start;
        printf("%s: depth = %2d, time = %.3f, expected = %12llu, actual = %12llu, hits = %g%%\n",
            result, depth, elapsed, expected[depth], actual, 100.0 * hits / actual);
    }
    printf("\n");
}
Example #18
0
//faster perft: like bulk, but does not generate (all) moves at the last ply
static uint64 perft(int depth) {
    Move moves[MaxMoves];
    if (depth<=1) return _board.countmoves(moves);

    Move *last = _board.genmoves(moves);
    uint64 n=0;
    Undo undo = _board.save();
    for (Move *m=moves; m<last; m++) {
        _board.move(*m);
        n += perft(depth-1);
        _board.undo(*m, undo);
    }

    return n;
}
Example #19
0
int main(int argc, char* argv[]) {
  try {
    if (argc == 2) {
      std::string token(argv[1]);
      if (token == "perft") {
        std::unique_ptr<pulse::Perft> perft(new pulse::Perft());
        perft->run();
      }
    } else {
      std::unique_ptr<pulse::Pulse> pulse(new pulse::Pulse());
      pulse->run();
    }
  } catch (std::exception& e) {
    std::cout << "Exiting Pulse due to an exception: " << e.what() << std::endl;
    return 1;
  }
}
Example #20
0
//------------------------------------------------------------------------------
void repl_perft(char *arg) {
    int depth = arg ? atoi(arg) : 5;
    if (depth <= 0) {
        depth = 5;
    }

    Timestamp checkpoint = now();
    new_game();
    int64 nodes = perft(start(), depth);
    uint64 elapsed = since(checkpoint);
    uint64 nps = nodes * 1000000 / elapsed; // Elapsed is in microseconds.

    printf("  Depth: %d\n", depth);
    printf("  Nodes: %lld\n", nodes);
    printf("Elapsed: %llu.%06llus\n", elapsed / 1000000, elapsed % 1000000);
    printf("Nodes/s: %lldK\n\n", nps / 1000);
}
Example #21
0
U64 perft(int depth)
{
    Move movelist[256];
    int n;
    U64 result = 0;
    
    if(depth == 0) return 1;
    
    n = generate_moves(movelist);
    for(int i = 0; i < n; i += 1)
    {
        Move i_move = movelist[i];
        make_move(i_move);
        result += perft(depth - 1);
        unmake_move(i_move);
    }
    return result;
}
Example #22
0
//unrolled perft: performs a perft(depth-1) for each move
//useful for debugging
static void divide(int depth) {
    Move moves[MaxMoves];
    Move *last = _board.genmoves(moves);
    char tmp[16];
    uint64 total=0;
    Undo undo = _board.save();
    MoveParser parser(_board);
    for (Move *m=moves; m<last; m++) {
        _board.move(*m);
        uint64 n = depth>1?perft(depth-1):1;
        total+= n;
        _board.undo(*m, undo);
        _parser.format(tmp, *m);
        printf("%-8s %10.0f\n", tmp, double(n));
    }
    printf("-------------------\n");
    printf("total    %10.0f\n", double(total));
}
Example #23
0
unsigned long long Engine::perft(int depth)
{
	if (depth == 0) return 1;
	vector<Move> vec;
	vec.reserve(128);
	pos.generateMoves(vec);
	unsigned long long count = 0;
	for (int i = 0;i < vec.size();i++)
	{
		Move m = vec.at(i);
		if (pos.makeMove(m))
		{
			count += perft(depth - 1);
			pos.unmakeMove(m);
		}
	}
	return count;
}
Example #24
0
File: perft.cpp Project: pd/benthos
void
test(position_t *pos, char *name, int max_depth)
{
	char *fen = NULL;
	uint64 *expected = NULL;
	clock_t start_time, end_time;
	double time_used;
	int depth = iterate ? 1 : max_depth;
	int i;

	for (i = 0; i < KNOWN_POSITIONS; i++)
		if (!strcmp(names[i], name)) {
			fen = positions[i];
			expected = expected_results[i];
			break;
		}

	if (fen == NULL) {
		cout << "Unknown position: " << name << endl;
		usage();
	}

	position_from_fen(pos, fen);
	cout << "'" << name << "' test: " << fen << endl;

	for (; depth <= max_depth; depth++) {
		start_time = clock();
		perft(pos, depth);
		end_time = clock();
		time_used = ((double)end_time - (double)start_time) / 1000;

		// if we have something to match again, see if we were right
		printf("depth %d: %12llu [%6.2f secs - %8.0f nps]", depth, total_moves,
				time_used, (total_moves / time_used));
		if (depth <= depths[i][1]) {
			if (expected[depth - 1] == total_moves)
				printf(" [correct]\n");
			else
				printf(" [incorrect: expected %llu]\n", expected[depth - 1]);
		} else
			printf(" [unknown validity]\n");
	}
}
Example #25
0
void test_perft(int depth)
{//itterative perft calling and output:
  int i;
  uint64 nodes;
    
  pht_init();		
  printf("\n");
  printf("-----------------------\n");
  printf(" depth   nodes \n");
  printf("-----------------------\n");
  depth += 1;
  for(i = 1; i < depth; i++)
  { nodes = perft(i);
    printf("%6d   %I64u", i,nodes);
    printf("\n");
  }
  printf("-----------------------\n");
  pht_free();
}
Example #26
0
static void perft(const board_t * board, int depth) {

   int me;
   list_t list[1];
   int i, move;
   board_t new_board[1];

   ASSERT(board_is_ok(board));
   ASSERT(depth_is_ok(depth));

   ASSERT(!is_in_check(board,colour_opp(board->turn)));

   // init

   NodeNb++;

   // leaf

   if (depth == 0) {
      LeafNb++;
      return;
   }

   // more init

   me = board->turn;

   // move loop

   gen_moves(list,board);

   for (i = 0; i < list_size(list); i++) {

      move = list_move(list,i);

      board_copy(new_board,board);
      move_do(new_board,move);

      if (!is_in_check(new_board,me)) perft(new_board,depth-1);
   }
}
Example #27
0
File: test.c Project: Glank/chess
unsigned long perft(ChessBoard* start, ChessMoveGenerator* gen, 
    int depth){
    move_t *next = NULL;
    int nextCount = 0;
    if(depth==0){
        if(ChessBoard_testForCheck(start)){
            //printf("\n");
            //ChessBoard_print(start);
            checks++;
            ChessMoveGenerator_generateMoves(gen, 1, NULL);
            if(gen->nextCount==0)
                checkmates++;
        }
        return 1;
    }

    int i;
    unsigned long nodes = 0;
    ChessMoveGenerator_generateMoves(gen, 
        ChessBoard_testForCheck(start), NULL);
    ChessMoveGenerator_copyMoves(gen,
        &next, &nextCount);
    for (i = 0; i < nextCount; i++){
        ChessBoard_makeMove(start, next[i]);
        if(depth==1){
            if(next[i]&CAPTURE_MOVE_FLAG)
                captures++;
            if(next[i]&PROMOTION_MOVE_FLAG)
                promotions++;
            if(GET_META(next[i])==EN_PASSANT_MOVE)
                ep++;
        }
        nodes += perft(start, gen, depth-1);
        ChessBoard_unmakeMove(start);
    }
    free(next);
    return nodes;
}
Example #28
0
void search_perft(const board_t * board, int depth_max) {

   int depth;
   my_timer_t timer[1];
   double time, speed;

   ASSERT(board_is_ok(board));
   ASSERT(depth_max>=1&&depth_max<DepthMax);

   // init

   board_disp(board);

   // iterative deepening

   for (depth = 1; depth <= depth_max; depth++) {

      // init

      NodeNb = 0;
      LeafNb = 0;

      my_timer_reset(timer);

      my_timer_start(timer);
      perft(board,depth);
      my_timer_stop(timer);

      time = my_timer_elapsed_cpu(timer);
      speed = (time < 0.01) ? 0.0 : double(NodeNb) / time;

      printf("%2d %10lld %10lld %7.2f %7.0f\n",depth,NodeNb,LeafNb,time,speed);
   }

   printf("\n");
}
Example #29
0
static void perft (typePOS* POSITION, int d, int h)
{
  typeMoveList LM[256], *lm;
  int i;
  if (IN_CHECK)
    lm = EvasionMoves (POSITION, LM, 0xffffffffffffffff);
  else
    {
      lm = CaptureMoves (POSITION, LM, POSITION->OccupiedBW);
      lm = OrdinaryMoves (POSITION, lm);
    }
  for (i = 0; i < lm - LM; i++)
    {
      Make (POSITION, LM[i].move);
      Mobility (POSITION);
      if (!ILLEGAL)
	{
	  CNT[h]++;
	  if (d > 1)
	    perft (POSITION, d - 1, h + 1);
	}
      Undo (POSITION, LM[i].move);
    }
}
Example #30
0
void loop(char *input, render_callback render_board){
	
	/* case where it's the computer's turn to move: */
	if (!is_edit_mode && (comp_color == white_to_move || automode) 
		&& !force_mode && !must_sit && !result) {
		
		/* whatever happens, never allow pondering in normal search */
		is_pondering = FALSE_C;
		
		cpu_start = clock ();
		comp_move = think ();
		cpu_end = clock();
		
		ply = 0;
		
		/* must_sit can be changed by search */
		if (!must_sit || must_go != 0)
		{
			/* check for a game end: */
			if ((
				 ((Variant == Losers || Variant == Suicide)
				  && 
				  ((result != white_is_mated) && (result != black_is_mated)))
				 || 
				 ((Variant == Normal || Variant == Crazyhouse || Variant == Bughouse)
				  && ((comp_color == 1 && result != white_is_mated) 
					  ||
					  (comp_color == 0 && result != black_is_mated)
					  ))) 
				&& result != stalemate 
				&& result != draw_by_fifty 
				&& result != draw_by_rep) 
			{
				
				comp_to_coord (comp_move, output);
				
				hash_history[move_number] = hash;
				
				game_history[move_number] = comp_move;
				make (&comp_move, 0);
				
				/* saves state info */
				game_history_x[move_number++] = path_x[0];
				
				userealholdings = 0;
				must_go--;
				
				/* check to see if we draw by rep/fifty after our move: */
				if (is_draw ()) {
					result = draw_by_rep;
				}
				else if (fifty > 100) {
					result = draw_by_fifty;
				}
				
				root_to_move ^= 1;
				
				reset_piece_square ();
				
				if (book_ply < 40) {
					if (!book_ply) {
						strcpy(opening_history, output);
					}
					else {
						strcat(opening_history, output);
					}
				}
				
				book_ply++;
				
				printf ("\nNodes: %d (%0.2f%% qnodes)\n", nodes,
						(float) ((float) qnodes / (float) nodes * 100.0));
				
				elapsed = (cpu_end-cpu_start)/(double) CLOCKS_PER_SEC;
				nps = (float) nodes/(float) elapsed;
				
				if (!elapsed)
					printf ("NPS: N/A\n");
				else
					printf ("NPS: %d\n", (int32_t) nps);
				
				printf("ECacheProbes : %d   ECacheHits : %d   HitRate : %f%%\n", 
					   ECacheProbes, ECacheHits, 
					   ((float)ECacheHits/((float)ECacheProbes+1)) * 100);
				
				printf("TTStores : %d TTProbes : %d   TTHits : %d   HitRate : %f%%\n", 
					   TTStores, TTProbes, TTHits, 
					   ((float)TTHits/((float)TTProbes+1)) * 100);
				
				printf("NTries : %d  NCuts : %d  CutRate : %f%%  TExt: %d\n", 
					   NTries, NCuts, (((float)NCuts*100)/((float)NTries+1)), TExt);
				
				printf("Check extensions: %d  Razor drops : %d  Razor Material : %d\n", ext_check, razor_drop, razor_material);
				
				printf("EGTB Hits: %d  EGTB Probes: %d  Efficiency: %3.1f%%\n", EGTBHits, EGTBProbes,
					   (((float)EGTBHits*100)/(float)(EGTBProbes+1)));
				
				printf("Move ordering : %f%%\n", (((float)FHF*100)/(float)(FH+1)));
				
				printf("Material score: %d   Eval : %d  White hand: %d  Black hand : %d\n", 
					   Material, (int)eval(), white_hand_eval, black_hand_eval);
				
				printf("Hash : %X  HoldHash : %X\n", (unsigned)hash, (unsigned)hold_hash);
				
				/* check to see if we mate our opponent with our current move: */
				if (!result) {
					if (xb_mode) {
						
						/* safety in place here */
						if (comp_move.from != dummy.from || comp_move.target != dummy.target)
							printf ("move %s\n", output);
						
						if (Variant == Bughouse)
						{
							CheckBadFlow(FALSE_C);
						}	
					}
					else {
						if (comp_move.from != dummy.from || comp_move.target != dummy.target)
							printf ("\n%s\n", output);
					}
				}
				else {
					if (xb_mode) {
						if (comp_move.from != dummy.from || comp_move.target != dummy.target)
							printf ("move %s\n", output);
					}
					else {
						if (comp_move.from != dummy.from || comp_move.target != dummy.target)
							printf ("\n%s\n", output);
					}
					if (result == white_is_mated) {
						printf ("0-1 {Black Mates}\n");
					}
					else if (result == black_is_mated) {
						printf ("1-0 {White Mates}\n");
					}
					else if (result == draw_by_fifty) {
						printf ("1/2-1/2 {Fifty move rule}\n");
					}
					else if (result == draw_by_rep) {
						printf ("1/2-1/2 {3 fold repetition}\n");
					}
					else {
						printf ("1/2-1/2 {Draw}\n");
					}
					automode = 0;
				}
			}
			/* we have been mated or stalemated: */
			else {
				if (result == white_is_mated) {
					printf ("0-1 {Black Mates}\n");
				}
				else if (result == black_is_mated) {
					printf ("1-0 {White Mates}\n");
				}
				else if (result == draw_by_fifty) {
					printf ("1/2-1/2 {Fifty move rule}\n");
				}
				else if (result == draw_by_rep) {
					printf ("1/2-1/2 {3 fold repetition}\n");
				}
				else {
					printf ("1/2-1/2 {Draw}\n");
				}
				automode = 0;
			}
		}
	}
	
	/* get our input: */
	if (!xb_mode) {
		if (show_board) {
			printf ("\n");
			display_board (stdout, 1-comp_color);
			render_board(1-comp_color);
		}
		if (!automode)
		{
			printf ("Sjeng: ");
			//readStr(input, STR_BUFF);
			//			rinput (input, STR_BUFF, stdin);
		}
	}
	else {
		/* start pondering */
		
		if ((must_sit || (allow_pondering && !is_edit_mode && !force_mode &&
						  move_number != 0) || is_analyzing) && !result && !automode)
		{
			is_pondering = TRUE_C;
			think();
			is_pondering = FALSE_C;
			
			ply = 0;
		}
		if (!automode)
		{
			//rinput (input, STR_BUFF, stdin);
		}
	}
	
	/* check to see if we have a move.  If it's legal, play it. */
	if (!is_edit_mode && is_move (&input[0])) {
		if (verify_coord (input, &human_move)) {
			
			if (confirm_moves) printf ("Legal move: %s\n", input);
			
			game_history[move_number] = human_move;
			hash_history[move_number] = hash;
			
			make (&human_move, 0);
			game_history_x[move_number++] = path_x[0];
			
			reset_piece_square ();
			
			root_to_move ^= 1;
			
			if (book_ply < 40) {
				if (!book_ply) {
					strcpy(opening_history, input);
				}
				else {
					strcat(opening_history, input);
				}
			}
			
			book_ply++;
			
			if (show_board) {
				printf ("\n");
				display_board (stdout, 1-comp_color);
				render_board(1-comp_color);
			}
		}
		else {
			printf ("Illegal move: %s\n", input);
		}
	}
	else {
		
		/* make everything lower case for convenience: */
		/* GCP: except for setboard, which is case sensitive */
		if (!strstr(input, "setboard")){
			for (p = input; *p; p++) {
				*p = tolower (*p);
			}
		}
		
		/* command parsing: */
		if (!strcmp (input, "quit") || (!input[0] && feof(stdin))) {
			safe_fclose(lrn_standard);
			safe_fclose(lrn_zh);
			safe_fclose(lrn_suicide);
			safe_fclose(lrn_losers);
			free_hash();
			free_ecache();
			exit (EXIT_SUCCESS);
		}
		else if (!strcmp (input, "exit"))
		{
			if (is_analyzing)
			{
				is_analyzing = FALSE_C;
				is_pondering = FALSE_C;
				time_for_move = 0;
			}
			else
			{
				safe_fclose(lrn_standard);
				safe_fclose(lrn_zh);
				safe_fclose(lrn_suicide);
				safe_fclose(lrn_losers);
				free_hash();
				free_ecache();
				exit (EXIT_SUCCESS);
			}
		}
		else if (!strcmp (input, "diagram") || !strcmp (input, "d")) {
			toggle_bool_c (&show_board);
		}
		else if (!strncmp (input, "perft", 5)) {
			sscanf (input+6, "%d", &depth);
			raw_nodes = 0;
			xstart_time = rtime();
			perft (depth);
			printf ("Raw nodes for depth %d: %d\n", depth, raw_nodes);
			printf("Time : %.2f\n", (float)rdifftime(rtime(), xstart_time)/100.);
		}
		else if (!strcmp (input, "confirm_moves")) {
			confirm_moves = TRUE_C;
			printf("Will now confirm moves.\n");
		}
		else if (!strcmp (input, "new")) {
			
			if (xb_mode)
			{
				printf("tellics set 1 Sjeng " VERSION " (2001-9-28/%s)\n", setcode);
			}
			
			if (!is_analyzing)
			{	
				memcpy(material, std_material, sizeof(std_material));
				Variant = Normal;
				
				// memcpy(material, zh_material, sizeof(zh_material));
				//Variant = Crazyhouse;
				
				init_game ();
				initialize_hash();
				
				if (!braindeadinterface)
				{
					clear_tt();
					init_book();
					reset_ecache();
				}
				
				force_mode = FALSE_C;
				must_sit = FALSE_C;
				go_fast = FALSE_C;
				piecedead = FALSE_C;
				partnerdead = FALSE_C;
				kibitzed = FALSE_C;
				fixed_time = FALSE_C;
				
				root_to_move = WHITE;
				
				comp_color = 0;
				move_number = 0;
				hash_history[move_number] = 0;
				bookidx = 0;
				my_rating = opp_rating = 2000;
				must_go = 0;
				tradefreely = 1;
				automode = 0;
				
				CheckBadFlow(TRUE_C);
				ResetHandValue();
			}
			else
			{
				init_game ();
				move_number = 0;
			}
			
		}
		else if (!strcmp (input, "xboard")) {
			xb_mode = TRUE_C;
			toggle_bool_c (&show_board);
			signal (SIGINT, SIG_IGN);
			printf ("\n");
			
			/* Reset f5 in case we left with partner */
			printf("tellics set f5 1=1\n");
			
			BegForPartner();
		}
		else if (!strcmp (input, "nodes")) {
			printf ("Number of nodes: %d (%0.2f%% qnodes)\n", nodes,
					(float) ((float) qnodes / (float) nodes * 100.0));
		}
		else if (!strcmp (input, "nps")) {
			elapsed = (cpu_end-cpu_start)/(double) CLOCKS_PER_SEC;
			nps = (float) nodes/(float) elapsed;
			if (!elapsed)
				printf ("NPS: N/A\n");
			else
				printf ("NPS: %d\n", (int32_t) nps);
		}
		else if (!strcmp (input, "post")) {
			toggle_bool_c (&post);
			if (xb_mode)
				post = TRUE_C;
		}
		else if (!strcmp (input, "nopost")) {
			post = FALSE_C;
		}
		else if (!strcmp (input, "random")) {
			return;
		}
		else if (!strcmp (input, "hard")) {
			
			allow_pondering = TRUE_C;
			
			return;
		}
		else if (!strcmp (input, "easy")) {
			
			allow_pondering = FALSE_C;
			
			return;
		}
		else if (!strcmp (input, "?")) {
			return;
		}
		else if (!strcmp (input, "white")) {
			white_to_move = 1;
			root_to_move = WHITE;
			comp_color = 0;
		}
		else if (!strcmp (input, "black")) {
			white_to_move = 0;
			root_to_move = BLACK;
			comp_color = 1;
		}
		else if (!strcmp (input, "force")) {
			force_mode = TRUE_C;
		}
		else if (!strcmp (input, "eval")) {
			check_phase();
			printf("Eval: %d\n", (int)eval());
		}
		else if (!strcmp (input, "go")) {
			comp_color = white_to_move;
			force_mode = FALSE_C;
		}
		else if (!strncmp (input, "time", 4)) {
			sscanf (input+5, "%d", &time_left);
		}
		else if (!strncmp (input, "otim", 4)) {
			sscanf (input+5, "%d", &opp_time);
		}
		else if (!strncmp (input, "level", 5)) {
			if (strstr(input+6, ":"))
			{
				/* time command with seconds */
				sscanf (input+6, "%d %d:%d %d", &moves_to_tc, &min_per_game, 
						&sec_per_game, &inc);
				time_left = (min_per_game*6000) + (sec_per_game * 100);
				opp_time = time_left;
			}
			else
			{
				/* extract the time controls: */
				sscanf (input+6, "%d %d %d", &moves_to_tc, &min_per_game, &inc);
				time_left = min_per_game*6000;
				opp_time = time_left;
			}
			fixed_time = FALSE_C;
			time_cushion = 0; 
		}
		else if (!strncmp (input, "rating", 6)) {
			sscanf (input+7, "%d %d", &my_rating, &opp_rating);
			if (my_rating == 0) my_rating = 2000;
			if (opp_rating == 0) opp_rating = 2000;
		}
		else if (!strncmp (input, "holding", 7)) {
			ProcessHoldings(input);     
		}
		else if (!strncmp (input, "variant", 7)) {
			if (strstr(input, "normal"))
			{
				Variant = Normal;
				memcpy(material, std_material, sizeof(std_material));
				init_book();
			}
			else if (strstr(input, "crazyhouse"))
			{
				Variant = Crazyhouse;
				memcpy(material, zh_material, sizeof(zh_material));
				init_book();
			}
			else if (strstr(input, "bughouse"))
			{
				Variant = Bughouse;
				memcpy(material, zh_material, sizeof(zh_material));
				init_book();
			}
			else if (strstr(input, "suicide"))
			{
				Variant = Suicide;
				Giveaway = FALSE_C;
				memcpy(material, suicide_material, sizeof(suicide_material));
				init_book();
			}
			else if (strstr(input, "giveaway"))
			{
				Variant = Suicide;
				Giveaway = TRUE_C;
				memcpy(material, suicide_material, sizeof(suicide_material));
				init_book();
			}
			else if (strstr(input, "losers"))
			{
				Variant = Losers;
				memcpy(material, losers_material, sizeof(losers_material));
				init_book();
			}
			
			initialize_hash();
			clear_tt();
			reset_ecache();
			
		}
		else if (!strncmp (input, "analyze", 7)) {
			is_analyzing = TRUE_C;
			is_pondering = TRUE_C;
			think();
			ply = 0;
		}
		else if (!strncmp (input, "undo", 4)) {
			printf("Move number : %d\n", move_number);
			if (move_number > 0)
			{
				path_x[0] = game_history_x[--move_number];
				unmake(&game_history[move_number], 0);
				reset_piece_square();
				root_to_move ^= 1;
			}
			result = 0;
		}
		else if (!strncmp (input, "remove", 5)) {
			if (move_number > 1)
			{
				path_x[0] = game_history_x[--move_number];
				unmake(&game_history[move_number], 0);
				reset_piece_square();
				
				path_x[0] = game_history_x[--move_number];
				unmake(&game_history[move_number], 0);
				reset_piece_square();
			}
			result = 0;
		}
		else if (!strncmp (input, "edit", 4)) {
			is_edit_mode = TRUE_C;
			edit_color = WHITE;
		}
		else if (!strncmp (input, ".", 1) && is_edit_mode) {
			is_edit_mode = FALSE_C;
			if (wking_loc == 30) white_castled = no_castle;
			if (bking_loc == 114) black_castled = no_castle;
			book_ply = 50;
			ep_square = 0;
			move_number = 0;
			memset(opening_history, 0, sizeof(opening_history));
			clear_tt();
			initialize_hash();
			reset_piece_square();
		}
		else if (is_edit_mode && !strncmp (input, "c", 1)) {
			if (edit_color == WHITE) edit_color = BLACK; else edit_color = WHITE;
		}
		else if (is_edit_mode && !strncmp (input, "#", 1)) {
			reset_board();
			move_number = 0;
		}
		else if (is_edit_mode 
				 && isalpha(input[0]) 
				 && isalpha(input[1]) 
				 && isdigit(input[2])) {
			PutPiece(edit_color, input[0], input[1], input[2]);
		}
		else if (!strncmp (input, "partner", 7)) {
			HandlePartner(input+7);
		}
		else if (!strncmp (input, "$partner", 8)) {
			HandlePartner(input+8);
		}
		else if (!strncmp (input, "ptell", 5)) {
			HandlePtell(input);
		}
		else if (!strncmp (input, "test", 4)) {
			run_epd_testsuite();
		}
		else if (!strncmp (input, "st", 2)) {
			sscanf(input+3, "%d", &fixed_time);
			fixed_time = fixed_time * 100;
		}
		else if (!strncmp (input, "book", 4)) {
			build_book();
		}
		else if (!strncmp (input, "speed",  5)) {
			speed_test();
		}
		else if (!strncmp (input, "result", 6)) {
			if (cfg_booklearn)
			{
				if (strstr (input+7, "1-0"))
				{
					if (comp_color == 1)
						book_learning(WIN);
					else
						book_learning(LOSS);
				}
				else if (strstr(input+7, "0-1"))
				{
					if (comp_color == 1)
						book_learning(LOSS);
					else
						book_learning(WIN);
				}
				else if (strstr(input+7, "1/2-1/2"))
				{
					book_learning(DRAW);
				};
			}
		}
		else if (!strncmp (input, "prove", 5)) {
			printf("\nMax time to search (s): ");
			start_time = rtime();
			rinput(readbuff, STR_BUFF, stdin);
			pn_time = atoi(readbuff) * 100;
			printf("\n");
			proofnumbersearch();      
		}
		else if (!strncmp (input, "ping", 4)) {
			sscanf (input+5, "%d", &pingnum);
			printf("pong %d\n", pingnum);
		}
		else if (!strncmp (input, "fritz", 5)) {
			braindeadinterface = TRUE_C;
		}
		else if (!strncmp (input, "reset", 5)) {
			
			memcpy(material, std_material, sizeof(std_material));
			Variant = Normal;
			
			init_game ();
			initialize_hash();
			
			clear_tt();
			init_book();
			reset_ecache();       
			
			force_mode = FALSE_C;
			fixed_time = FALSE_C;
			
			root_to_move = WHITE;
			
			comp_color = 0;
			move_number = 0;
			bookidx = 0;
			my_rating = opp_rating = 2000;
		}
		else if (!strncmp (input, "setboard", 8)) {
			setup_epd_line(input+9);
		}
		else if (!strncmp (input, "buildegtb", 9)) {
			Variant = Suicide;
			gen_all_tables();
		}
		else if (!strncmp (input, "lookup", 6)) {
			Variant = Suicide;
			printf("Value : %d\n", egtb(white_to_move));
		}
		else if (!strncmp (input, ".", 1)) {
			/* periodic updating and were not searching */
			/* most likely due to proven mate */
			return;
		}
		else if (!strncmp (input, "sd", 2)) {
			sscanf(input+3, "%d", &maxdepth);
			printf("New max depth set to: %d\n", maxdepth);
			return;
		}
		else if (!strncmp (input, "auto", 4)) {
			automode = 1;
			return;
		}
		else if (!strncmp (input, "protover", 8)) {
			printf("feature ping=1 setboard=1 playother=0 san=0 usermove=0 time=1\n");
			printf("feature draw=0 sigint=0 sigterm=0 reuse=1 analyze=1\n");
			printf("feature myname=\"Sjeng " VERSION "\"\n");
			printf("feature variants=\"normal,bughouse,crazyhouse,suicide,giveaway,losers\"\n");
			printf("feature colors=1 ics=0 name=0 pause=0 done=1\n");
			xb_mode = 2;
		}
		else if (!strncmp (input, "accepted", 8)) {
			/* do nothing as of yet */
		}
		else if (!strncmp (input, "rejected", 8)) {
			printf("Interface does not support a required feature...expect trouble.\n");
		}
		else if (!strncmp (input, "warranty", 8)) {
			printf("\n  BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\n"
				   "FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\n"
				   "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\n"
				   "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\n"
				   "OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n"
				   "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\n"
				   "TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\n"
				   "PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\n"
				   "REPAIR OR CORRECTION.\n"
				   "\n");
			printf("  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\n"
				   "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\n"
				   "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\n"
				   "INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\n"
				   "OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\n"
				   "TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\n"
				   "YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\n"
				   "PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\n"
				   "POSSIBILITY OF SUCH DAMAGES.\n\n");
			
		}
		else if (!strncmp (input, "distribution", 12)) {
			printf("\n  You may copy and distribute verbatim copies of the Program's\n"
				   "source code as you receive it, in any medium, provided that you\n"
				   "conspicuously and appropriately publish on each copy an appropriate\n"
				   "copyright notice and disclaimer of warranty; keep intact all the\n"
				   "notices that refer to this License and to the absence of any warranty;\n"
				   "and give any other recipients of the Program a copy of this License\n"
				   "along with the Program.\n"
				   "\n"
				   "You may charge a fee for the physical act of transferring a copy, and\n"
				   "you may at your option offer warranty protection in exchange for a fee.\n\n");
			
		}
		else if (!strcmp (input, "help")) {
			printf ("\n%s\n\n", divider);
			printf ("diagram/d:       toggle diagram display\n");
			printf ("exit/quit:       terminate Sjeng\n");
			printf ("go:              make Sjeng play the side to move\n");
			printf ("new:             start a new game\n");
			printf ("level <x>:       the xboard style command to set time\n");
			printf ("  <x> should be in the form: <a> <b> <c> where:\n");
			printf ("  a -> moves to TC (0 if using an ICS style TC)\n");
			printf ("  b -> minutes per game\n");
			printf ("  c -> increment in seconds\n");
			printf ("nodes:           outputs the number of nodes searched\n");
			printf ("nps:             outputs Sjeng's NPS in search\n");
			printf ("perft <x>:       compute raw nodes to depth x\n");
			printf ("post:            toggles thinking output\n");
			printf ("xboard:          put Sjeng into xboard mode\n");
			printf ("test:            run an EPD testsuite\n");
			printf ("speed:           test movegen and evaluation speed\n");
			printf ("warranty:        show warranty details\n");
			printf ("distribution:    show distribution details\n");
			printf( "proof:           try to prove or disprove the current pos\n");
			printf( "sd <x>:          limit thinking to depth x\n");
			printf( "st <x>:          limit thinking to x centiseconds\n");
			printf( "setboard <FEN>:  set board to a specified FEN string\n");
			printf( "undo:            back up a half move\n");
			printf( "remove:          back up a full move\n");
			printf( "force:           disable computer moving\n");
			printf( "auto:            computer plays both sides\n");
			printf ("\n%s\n\n", divider);
			
			show_board = 0;
		}
		else if (!xb_mode) {
			printf ("Illegal move: %s\n", input);
		}
		
	}
	
}