/*
    STB Generator
    Copyright (C) 2006 Gian-Carlo Pascutto
   
    File: utils.c
    Purpose: Utility functions
*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "global.h"

void convert_string_to_sig(char *str, matsig_s *matsig) {
    int i, len, piece, val, rank;
    int color;

    len = (int)strlen(str);

    if (len < 3 || str[0] != 'k') {
        printf("Malformed signature.\n");
        exit(EXIT_FAILURE);
    }

    memset(matsig, 0, sizeof(matsig_s));

    color = WHITE;

    for (i = 1; i < len; i++) {  
        rank = 0;      
        
        switch(tolower(str[i])) {
            case 'k': color = BLACK;  break;
            case 'p': piece = pawn;   
                if (i + 1 < len && isdigit(str[i + 1])) {
                    rank = atoi(&str[i + 1]);
                    i++;
                } else {
                    rank = 2;
                }
                break;
            case 'n': piece = knight; break;
            case 'b': piece = bishop; break;
            case 'r': piece = rook;   break;
            case 'q': piece = queen;  break;            
            default: 
                printf("Malformed signature.\n");
                exit(EXIT_FAILURE);
                break;
        }
        
        if (tolower(str[i]) != 'k') {
            val = piece * 2 - !color;            
            
            if (rank != 0) {
                matsig->pawnrank[color][matsig->npieces[val]] = rank;
            }
            
            matsig->npieces[val]++;
        }
    }
}

void convert_sig_to_string(matsig_s *matsig, char *str) {     
    static const int wpcs[] = {wqueen, wrook, wbishop, wknight, wpawn};
    static const int bpcs[] = {bqueen, brook, bbishop, bknight, bpawn};
    static const char* pcs[] = {"q", "r", "b", "n", "p"};
    static const char* cnt[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8"};
    int i, j, inc, num;   

    str[0] = 0;

    for (inc = 0; inc < 2; inc++) {
        strcat(str, "k");
            
        for (j = 0; j < 5; j++) {            
            num = matsig->npieces[wpcs[j] + inc];
            
            for (i = 0; i < num; i++) {
                strcat(str, pcs[j]);
                /* 
                    add rank to pawns
                */
                if (j == 4) {
                    strcat(str, cnt[matsig->pawnrank[inc][i]]);
                }
            }                
        }    
    }
}

void print_sig(matsig_s *sig) {
    char buff[256];

    convert_sig_to_string(sig, buff);

    printf("%s", buff);    
}