// Copyright 1992-1997 by Jon Dart.  All Rights Reserved.

#include "stdafx.h"
#include "book.h"
#include "movegen.h"
#include "moveord.h"
#include "util.h"
extern "C"
{
#include <stdlib.h>
#include <time.h>
};

Book::Book()
{
    time_t t;
    srand((unsigned)time(&t));
    reader = new Book_Reader(MAIN_BOOK_NAME,MAIN_MAPPING_NAME);
    style_reader = new Book_Reader(STYLE_BOOK_NAME,STYLE_MAPPING_NAME);
}       

Book::~Book()
{
    delete reader;
    delete style_reader;
    Book_Entry::freeAll(TRUE);
}

Move Book::book_move( const Board &b, enum styles style )
{
     Book_Entry target(b.HashCode(),0,0,0);
     // First try to find a move matching the preferred style
     // in the style book.
     if ((style != Balanced) && style_reader->Is_Open())
     {
         uint16 indx = style_reader->Head(b, style);
         Move m = style_reader->pick(b, indx, target);
         if (!m.IsNull())
            return m;
     }
     // No style move, try to find a move in the regular opening
     // book.
     if (!reader->Is_Open())
     {
         return Move::NullMove();
     }
     else
     {
        uint16 indx = reader->Head(b,Balanced);
        return reader->pick(b, indx, target);
     }
     return Move::NullMove();
}

unsigned Book::book_moves( const Board &b, Move *moves, 
        const unsigned limit)
{
     if (!reader->Is_Open())
         return 0;
     return reader->book_moves(b,moves,limit);

}
