/********************************
  netpuyo(server)
  main.c --- main
  (C) Sep 24, 1997 ROYALPANDA
*******************************/

#include<stdio.h>
#include<unistd.h>
#include<signal.h>
#include<time.h>

#include"server.h"
#include"protocol.h"

static int Port = 9000;
static int Auto_exit = 1;

static int Private = 0;

int Children = 0;

int Sock;

int M_time = 180;
int Rate = 70;

int Time_start;

int Dir_x[4] = { 0,1,0,-1 };
int Dir_y[4] = { -1,0,1,0 };

player_t P[2];

char *Myname = "netpuyos";

void child_dead( void )
{
  wait( NULL );
  if( Auto_exit && --Children == 0 ){
    close( Sock );
    exit(0);
  }
}


static void help( void )
{
  char **pp;

  static char *msg[] = {
    "netpuyos [options...]\n",
    "\t-noexit\t\t do not exit if all players log out.\n",
    "\t-private\t act as private server(a pair of players only).\n",
    "\t-port \"port\"\t describe port number(default:9000).\n",
    "\t-time \"second\"\t describe margin time(default:180).\n",
    "\t-rate \"rate\"\t describe ojama-puyo rate(default:70).\n",
    "\t-version\tshow version\n",
    "\t-help\t\t show this message.\n",
    NULL,
  };

  for( pp = msg ; *pp ; pp++ )
    fprintf(stderr,*pp);
}

static void version( void )
{
  static char str[] ="\n" 
    "-----------------------------------------------------\n\n"
      "N e t P u y o ( server )   version 0.6( Prototype )\n\n"
	"(c) 1997 ROYALPANDA\n\n"
	  "Please send bug report to: i11053@ced.cas.uec.ac.jp\n\n"
	    "-----------------------------------------------------\n";

  fprintf( stderr,str );
}


static void option( int argc,char **argv )
{
  int i;

  for( i = 1 ; i < argc ; i++ ){

    if( strcmp( argv[i],"-noexit" ) == 0 ){
      Auto_exit = 0;
      continue;
    }

    if( strcmp( argv[i],"-private" ) == 0 ){
      Private = 1;
      continue;
    }

    if( strcmp( argv[i],"-port" ) == 0 ){
      Port = atoi( argv[++i] );
      continue;
    }

    if( strcmp( argv[i],"-time" ) == 0 ){
      M_time = atoi( argv[++i] );
      continue;
    }

    if( strcmp( argv[i],"-rate" ) == 0 ){
      Rate = atoi( argv[++i] );
      if( Rate < 1 )
	Rate = 1;
      continue;
    }

    if( strcmp( argv[i],"-version" ) == 0 ){
      version();
      exit(0);
    }

    if( strcmp( argv[i],"-help" ) == 0 ){
      help();
      exit(0);
    }

    help();
    exit(1);
  }
}


int main( int argc, char ** argv )
{
  static char buf[0] = {0};
  int p;

  if( argv[0] != NULL )
    Myname = argv[0];

  option(argc,argv);

  if( init_network( Port ) < 0 )
    exit(1);

  if( !Private )
    signal( SIGCHLD,child_dead );

  srandom( time(NULL) );

  if( connection(Private,Auto_exit) < 0 )
    exit(1);
                 /* if !Private, only child process will be return */


  send_init( MSG_CNCT );
  send_msg(0);
  send_msg(1);

  for(;;){
    wait_start();
    game();
  }

  return -1;
}
