#define I_AM_MAIN

#include "global.h"

#include "net.h"
#include "mapdisplay.h"
#include "defs.h"

#ifdef USE_X11

# ifdef USE_XVIEW
#  include "XvScreen.h"
# else
#  ifdef USE_XM
#   include "XmScreen.h"
#  else
#   ifdef USE_XAW
#    include "XawScreen.h"
#   endif
#  endif
# endif

# include <unistd.h>
# include <stdlib.h>
# include <stdio.h>

// seems to be needed...
# ifdef _POSIX_SOURCE
#  include <getopt.h>
# endif

void optionhelp();

main(int argc, char **argv)
{
  distanceBetweenConts = defaultDistanceBetweenConts;
  contChunkSize = defaultContChunkSize;
  numberOfChunksPerCont = defaultNumberOfChunksPerCont;

  screen = NULL;
  WorldCreate = 0;
  
  numPlayers = 0;
  myName = NULL;
  opterr = 0;
  int opt;

  debugFlags = NULL;
  
  // FIXME: use standard Xt parsing mechanism ?
  while ((opt = getopt(argc, argv, "h?sD:w:")) != -1) {
    if ((opt == 'h') || (opt == '?')) optionhelp();
    if (opt == 'D') debugFlags = optarg;
    if (opt == 'w') {
      distanceBetweenConts = atoi(optarg);
      contChunkSize = atoi(argv[optind++]);
      numberOfChunksPerCont = atoi(argv[optind++]);
      printf("dist %d, chunk size %d, number of chunks %d\n",
	     distanceBetweenConts,
	     contChunkSize, numberOfChunksPerCont);
    }
    if (opt == 's') WorldCreate = WorldCreate | 0x02;
  }

# ifdef USE_XVIEW
  screen = new XvScreen(argc, argv);
# else
#  ifdef USE_XM
  screen = new XmScreen(argc, argv);
#  else
#   ifdef USE_XAW
  screen = new XawScreen(argc, argv);
#   endif
#  endif
# endif

  screen->StartUp();
  MainMap = screen->CreateMapDisplay();
  screen->MainLoop();
}

void optionhelp()
{
  printf("Multiplayer Civ v%s\n\n",VERSION);
  printf("\
Usage: civ [-h|?] [-s] [-D flags] [-w distance size number]\n\
\n\
	-h print this help text and exit\n\
	-? same as -h\n\
	-D set the debuging flags (see below)\n\
	-s set the whole world viewable\n\
	-w set the distance between continents, the size of a chunk\n\
	   and the number of chunks per continent. Defaults are respectively\n\
	   %d, %d and %d\n\n\
", defaultDistanceBetweenConts, defaultContChunkSize, defaultNumberOfChunksPerCont);

  // FIXME: these are just guesses; might not be accurate !!
  puts("\
 Debuging flags:\n\
	+ All debug messages\n\
	c City\n\
	F Settlers' actions\n\
	i Init\n\
	n Network\n\
	p Player\n\
	r Rules\n\
	s Saving/Restoring\n\
	u Unit\n\
	w World\n\
	x X11\n\
\n");

  exit(0);
}

#else  // !USE_X11

# include <fcntl.h>
# include <stdlib.h>
# include "WScreen.h"
# include "server.h"
# include "defs.h"

int PASCAL WinMain(HANDLE hInstance, HANDLE hPrevInstance, LPSTR lpszCmdLine,
  int nCmdShow)
{
  _fmode = O_BINARY;
  // registers class, displays civ window, asks for default server,
  // player name and num players
  screen = new WScreen(HandleKey, hInstance, hPrevInstance, nCmdShow);
  CivInit(savedGame ? RestoreSaveFile : StartNewGame, serverName);
  return screen->MainLoop();
}

#endif // !USE_X11
