#include "ramjet.h"
#include "bitboard.h"
#include "quadboard.h"
#include "move.h"
#include "position.h"
#include "history.h"

// set all counters to zero
void history_clear(HISTORYTABLE* hy)
{
    PLAYER pl;
    PIECETYPE pt;
    SQUARE sq;

    for(pl = WHITE; pl <= BLACK; ++pl)
        for(pt = PAWN; pt <= KING; ++pt)
            for(sq = A8; sq <= H1; ++sq)
                hy->entry[pl][pt - 1][sq] = HE_NULL;
}

// divide all the counters by two
void history_halve(HISTORYTABLE* hy)
{
    PLAYER pl;
    PIECETYPE pt;
    SQUARE sq;

    for(pl = WHITE; pl <= BLACK; ++pl)
        for(pt = PAWN; pt <= KING; ++pt)
            for(sq = A8; sq <= H1; ++sq)
                hy->entry[pl][pt - 1][sq] /= 2;
}

// update the history counters
void history_update(HISTORYTABLE* hy, POSITION* pos, MOVE mv, int depth)
{
    BITBOARD bb_all = qb_get_bb_tot(&pos->qb);
    SQUARE to = MV_GET_TO(mv);

    // ignore a capture, promotion, enpassant or castle
    if((bb_all & BB_SQ(to)) || IS_MV_PROMO(mv) || IS_MV_SPECIAL(mv))
        return;

    SQUARE from = MV_GET_FROM(mv);
    PLAYER pl = ST_GET_PL(pos->st);
    PIECETYPE pt = qb_get_sq_pt(&pos->qb, from);

    // safety halving
    int i = HE_INC(depth);
    if(hy->entry[pl][pt - 1][to] > HE_MAX - i)
        history_halve(hy);

    // increment the (player, piece, to) entry
    hy->entry[pl][pt - 1][to] += i;
}
