#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "ramjet.h"
#include "params.h"

// reset the parameters to their default values
void par_clear(PARAMS* par)
{
    par->time = MS_MAX;
    par->nodes = NC_MAX;
    par->depth = PAR_DEPTH_MAX;
    par->sm = SM_HALT;
}

// read the parameters from the UCI string
void par_scan_uci(char* uci, PARAMS* par, PLAYER pl)
{
    assert(!IS_PL_BAD(pl));

    char* token;

    // set the default values
    par_clear(par);

    // scan the UCI string in search for supported parameters
    for(token = grab_token(&uci); token[0] != '\0'; token = grab_token(&uci))

        // keep searching until further instructions
        if(!strcmp(token, "infinite") || !strcmp(token, "ponder")) {
            par->sm = SM_INF;

        // search for a fixed time
        } else if(!strcmp(token, "movetime")) {
            sscanf(grab_token(&uci), "%"MS_SCAN, &par->time);
            par->sm = SM_FIXED;

        // search a fixed number of nodes
        } else if(!strcmp(token, "nodes")) {
            sscanf(grab_token(&uci), "%"NC_SCAN, &par->nodes);
            par->sm = SM_FIXED;

        // search a fixed depth
        } else if(!strcmp(token, "depth")) {
            sscanf(grab_token(&uci), "%d", &par->depth);
            par->sm = SM_FIXED;

        // smart search given the remaining time
        } else if((pl == WHITE && !strcmp(token, "wtime")) ||
                  (pl == BLACK && !strcmp(token, "btime"))) {
            sscanf(grab_token(&uci), "%"MS_SCAN, &par->time);
            par->sm = SM_SMART;
        }

    // protection
    if(par->depth > PAR_DEPTH_MAX)
        par->depth = PAR_DEPTH_MAX;
}

// test the functions above
int par_test()
{
    char uci_1[] = "go ponder";
    char uci_2[] = "go wtime 5400 btime 17342";
    char uci_3[] = "go nodes 658321 depth 2 movetime 3428";
    PARAMS par;

    //"go movetime 53 really!? depth 8 nodes baaaah 123456 infinite"

    par_scan_uci(uci_1, &par, BLACK);
    if(par.sm != SM_INF)
        return 1;

    par_scan_uci(uci_2, &par, BLACK);
    if(par.sm != SM_SMART || par.time != 17342)
        return 2;

    par_scan_uci(uci_3, &par, BLACK);
    if(par.sm != SM_FIXED || par.time != 3428 || par.nodes != 658321 || par.depth != 2)
        return 3;

    return 0;
}
