/*
    STB Generator
    Copyright (C) 2006 Gian-Carlo Pascutto
   
    File: attacks.c
    Purpose: Attack calculation functions
*/

#include "global.h"

int is_attacked (state_s *s, int square, int color) {
    static const int rook_o[4] = {12, -12, 1, -1};
    static const int bishop_o[4] = {11, -11, 13, -13};
    static const int knight_o[8] = {10, -10, 14, -14, 23, -23, 25, -25};
    int ndir, a_sq;
    int basq, i;

    /* 
        white attacker: 
    */
    if (color == WHITE) {          
        for (i = 0; i < 4; i++) {
            ndir = bishop_o[i];
            a_sq = square + ndir;
            basq = s->board[a_sq];
      
            if (basq == wpawn && (i & 1)) {
                return TRUE;
            }
                  
            if (basq == wking) return TRUE;

            while (basq != frame) {
	        if (basq == wbishop || basq == wqueen) return TRUE;
	        if (basq != npiece) break;
	        a_sq += ndir;
	        basq = s->board[a_sq];
            }
        }

        for (i = 0; i < 8; i++) {
            if (s->board[square + knight_o[i]] == wknight) return TRUE;
        }
    
        for (i = 0; i < 4; i++) {
            ndir = rook_o[i];
            a_sq = square + ndir;
            basq = s->board[a_sq];
            
            if (basq == wking) return TRUE;
            
            while (basq != frame) {
	        if (basq == wrook || basq == wqueen) return TRUE;
	        if (basq != npiece) break;
	        a_sq += ndir;
	        basq = s->board[a_sq];
            }
        }        
    }  else {
        for (i = 0; i < 4; i++) {
            ndir = bishop_o[i];
            a_sq = square + ndir;
            basq = s->board[a_sq];
            
            if (basq == bpawn && !(i & 1)) return TRUE;
            
            if (basq == bking) return TRUE;
            while (basq != frame) {
	        if (basq == bbishop || basq == bqueen) return TRUE;
	        if (basq != npiece) break;
	        a_sq += ndir;
	        basq = s->board[a_sq];
            }
        }
    
        for (i = 0; i < 8; i++) {
            if (s->board[square + knight_o[i]] == bknight) return TRUE;
        }
        
        for (i = 0; i < 4; i++) {
            ndir = rook_o[i];
            a_sq = square + rook_o[i];
            basq = s->board[a_sq];
            
            if (basq == bking) return TRUE;
      
            while (basq != frame) {
	        if (basq == brook || basq == bqueen) return TRUE;
	        if (basq != npiece) break;
	        a_sq += ndir;
	        basq = s->board[a_sq];
            }
        }    
    }

    return FALSE;
}
