#include <string.h>
#include "util.h"
#include "move.h"
#include "moveseq.h"
#include "null.h"


int MoveSeqValidate(board_t *board,moveseq_t *moveseq){
    int i;
    int move;
    board_t board_work[1];
    memcpy(board_work,board,sizeof(board_t));
    for(i=0;i<moveseq->gencnt;i++){
	move=moveseq->moves[i];
	if(!MoveIsPseudoLegal(board_work,move)){
	    return false;
	}
	if(board->xin_check){
	    return false;
	}
	MoveMake(board_work,move);
    }
    return true;
}


void MoveSeqToSAN(board_t *board, moveseq_t *moveseq, char *SAN){
    char SANmv[SANSZ];
    int i;
    int move;
    board_t board_work[1];
    SAN[0]='\0';
    memcpy(board_work,board,sizeof(board_t));
    for(i=0;i<moveseq->gencnt;i++){
	move=moveseq->moves[i];
	MoveToSAN(board_work,move,SANmv); 
	if(i!=0){
	    strcat(SAN," ");
	}
	strcat(SAN,SANmv);
	if(!(move & NULLMOVE)){
	    MoveMake(board_work,move);
	}else{
	    NullMoveMake(board_work);
	}
    }
    
}

void MoveSeqToLAN(moveseq_t *moveseq, char *LAN){
    char LANmv[SANSZ];
    int i;
    int move;
    LAN[0]='\0';;
    for(i=0;i<moveseq->gencnt;i++){
	move=moveseq->moves[i];
	MoveToLAN(moveseq->moves[i],LANmv);
	if(i!=0){
	    strcat(LAN," ");
	}
	strcat(LAN,LANmv);
    }
    
}

void MoveSeqShow(board_t *board, moveseq_t *moveseq){
    char SAN[MAXPLYDEPTH*(SANSZ+1)+1];
    MoveSeqToSAN(board,moveseq,SAN);
    Output("%s\n",SAN);
}

void MoveSeqShowLAN(moveseq_t *moveseq){
    char LAN[MAXPLYDEPTH*(SANSZ+1)+1];
    MoveSeqToLAN(moveseq,LAN);
    Output("%s\n",LAN);
}

void MoveSeqPrependMove(moveseq_t *dst, moveseq_t *src, int move){
  // XXX TO BUFFER OVERFLOW CHECK
  dst->moves[0]=move;
  memcpy((dst->moves)+1,src->moves,src->gencnt*sizeof(int));
  dst->gencnt=src->gencnt+1;
}

void MoveSeqShiftLeft(moveseq_t *dst, moveseq_t *src){
  // XXX TO BUFFER OVERFLOW CHECK
  memcpy(dst->moves,(src->moves)+1,(src->gencnt-1)*sizeof(int));
  dst->gencnt=src->gencnt-1;
}
