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

#include "chess.hpp"
#include "player.hpp"
#include "uplayer.hpp"
#include "cplayer.hpp"
#include "chessui.hpp"

void OutOfMemory(void)
  {
    ChessUI.outOfMemory();
    exit(1);
  }

// define a player based on a command line parameter.  player
// is allocated on heap.
LOCAL PLAYER *defPlayer(PIECECOLOR color, char *arg)
  {
    BOOL computer = TRUE;
    int lookAhead;
    PLAYER *player;

    if (stricmp(arg, "u") == 0)
      computer = FALSE;
    else if (stricmp(arg, "c1") == 0)
      lookAhead = 2;
    else if (stricmp(arg, "c2") == 0)
      lookAhead = 3;
    else if (stricmp(arg, "c3") == 0)
      lookAhead = 4;
    else
      exit(1);

    if (computer)
      player = new COMPUTERPLAYER(color, lookAhead);
    else
      player = new USERPLAYER(color);

    if (!player)
      OutOfMemory();

    return(player);
  }


// define the two players based on command line arguments (or
// defaults)
LOCAL void setupPlayers
  (
    int nArg,
    char **arg,
    PLAYER *&whitePlayer,
    PLAYER *&blackPlayer
  )
  {
    char *white = "u", *black = "c2";

    if (nArg > 1)
      white = arg[1];
    if (nArg > 2)
      black = arg[2];
    if (nArg > 3)
      exit(1);

    whitePlayer = defPlayer(WHITE, white);
    blackPlayer = defPlayer(BLACK, black);

    return;
  }

int main(int nArg, char **arg)
  {
    BOARD board;
    PLAYER *whitePlayer, *blackPlayer;

    setupPlayers(nArg, arg, whitePlayer, blackPlayer);

    ChessUI.init(board);

    for ( ; ; )
      {
	if (whitePlayer->play(board) == GAMEOVER)
	  break;
	if (blackPlayer->play(board) == GAMEOVER)
	  break;
      }

    delete whitePlayer;
    delete blackPlayer;

    return(0);
  }
