/* koth.c: replacement for koth.bat 
   Copyright (c) 1998, 2001 Philip Kendall
             (c) 2001 Stefan Foerster

   $Id: koth.c,v 1.3 2002/02/19 21:44:45 pak21 Exp $

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

   Author contact information:

   E-mail: Philip Kendall <pak21-corewar@srcf.ucam.org>
   Postal address: 15 Crescent Road, Wokingham, Berks, RG40 2DB, England

*/

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

#ifdef __MSDOS__

const char *configFile="kothrc";

#else			/* #ifdef MSDOS */

const char *configFile=".kothrc";

#endif			/* #ifdef MSDOS */

#ifdef __DJGPP__

/* Disable filename globbing and loading of the environment file
   (To make executable smaller)					 */

char ** __crt0_glob_function(char *_argument)         { return 0; }
void    __crt0_load_environment_file(char *_app_name) { return;   }

#endif			/* #ifdef __DJGPP__ */

struct warrior {

  char *name;
  struct warrior *next;

};

typedef struct warrior warrior;

struct suite {

  char *id;
  char *options;
  warrior *warrior1;
  struct suite *next;

};

typedef struct suite suite;

int readConfig(char *buffer,suite **suiteListPtr);
void usage(void);

int main(int argc,char **argv)
{

  char prefix[128],buffer[1024],tempFile[10];
  int error,num,win,loss,tie,totalWin,totalTie,totalLoss,
      warriorsFought,rounds;
  float score,totalScore;
  FILE *f;
  suite *suiteList,*currentSuite;
  warrior *currentWarrior;

  if(argc<4)
    {
      usage();
      return 1;
    }

  if ( (error=readConfig(buffer,&suiteList)) ) return error;

  currentSuite=suiteList;

  while(currentSuite)
    {
      if( strcmp(argv[3],currentSuite->id) == 0 ) break;
      currentSuite=currentSuite->next;
    }

  if(!currentSuite)
    {
      fprintf(stderr,"Unknown suite `%s' specified\n",argv[3]);
      return 2;
    }

  rounds=atoi(argv[2]);

  if(rounds<1)
    {
      fprintf(stderr,"Invalid number of rounds: `%s'\n",argv[2]);
      return 5;
    }

  sprintf(prefix,"%s -r %s %s ",buffer,argv[2],currentSuite->options);

  currentWarrior=currentSuite->warrior1;

  totalWin=totalTie=totalLoss=0;
  totalScore=0;
  warriorsFought=0;

  printf( "%s\n%s\n- - - - - - - - - - - - - - -  W   L   T     Score\n",
	  argv[1], prefix);

  while(currentWarrior)
    {
      sprintf( buffer, "%s %s %s", prefix, argv[1], currentWarrior->name );

      fflush(stdin); fflush(stdout);
      
      f = popen( buffer, "r" );
      if( !f ) {
        perror("Error: ");
        return 6;
      }

      while ( (num=fscanf(f,"%*[^0-9] %d %d %d",&win,&loss,&tie)) != EOF
	      && (num != 3)
	    ) {
        if(num==0) fgetc(f);
      }

      pclose(f);
      fflush(stdin);
      fflush(stdout);

      if(num!=3)
	{
	  fprintf(stderr,"Couldn't get results\n");
	  return 4;
	}

      score=(100.0*(3*win+tie))/rounds;

      strncpy(buffer,currentWarrior->name,28); buffer[28]='\0';

      printf( "%-28s: %3d %3d %3d     %3.0f\n", buffer, win, loss, tie, score);

      totalWin+=win;
      totalLoss+=loss;
      totalTie+=tie;
      totalScore+=score;

      currentWarrior=currentWarrior->next; warriorsFought++;

    }

  totalScore/=warriorsFought;

  printf("- - - - - - - - - - - - - - - - - - - - - - - - -\n"
	 "Total wins   =  %d\n"
	 "Total losses =  %d\n"
	 "Total ties   =  %d\n"
	 "Overall score is %f\n",
	 totalWin,totalLoss,totalTie,totalScore);

  return 0;

}

int readConfig(char *buffer,suite **suiteListPtr)
{

  char buffer2[1024],*ptr,*ptr2=buffer2;
  int i;
  FILE *f;
  suite *currentSuite=0;
  warrior *currentWarrior;

  if ( (f=fopen(configFile,"rt")) == NULL )
    {
      fprintf(stderr,"Error opening `%s' for input\n",configFile);
      return 7;
    }

  ptr=buffer;
  while( (i=fgetc(f)) != EOF && (i !='\n') ) *ptr++=i; *ptr=0;

  while (!feof(f))
    {
      
      if(currentSuite)
	{
	  currentSuite->next=(suite*)malloc(sizeof(suite));
	  currentSuite=currentSuite->next;
	}
      else
	{
	  *suiteListPtr=(suite*)malloc(sizeof(suite));
	  currentSuite=*suiteListPtr;
	}

      currentSuite->options=0;
      currentSuite->warrior1=currentWarrior=0;
      currentSuite->next=0;

      /* Read in the next suite */

      ptr=ptr2;
      while( (i=fgetc(f)) != EOF && (i != '\n') ) *ptr++=i; *ptr=0;

      /* Scan to the first comma (end of id) */

      ptr=ptr2;
      while( *ptr && *ptr!=',' ) ptr++;

      i=ptr-ptr2;
      currentSuite->id=
        (char*)malloc( (i+1) * sizeof(char) );
      strncpy(currentSuite->id,ptr2,i);
      currentSuite->id[i]=0;
      ptr++;			/* skip the comma */

      /* Scan to second comma (end of options) */

      ptr2=ptr;
      while( *ptr && *ptr!=',' ) ptr++;

      i=ptr-ptr2;
      currentSuite->options=
        (char*)malloc( (i+1) * sizeof(char) );
      strncpy(currentSuite->options,ptr2,i);
      currentSuite->options[i]=0;

      ptr++;		/* skip the comma */

      while(*ptr)
	{

	  ptr2=ptr;
	  while( *ptr && *ptr!=',' ) ptr++;

	  if(currentWarrior)
	    {
	      currentWarrior->next=(warrior*)malloc(sizeof(warrior));
	      currentWarrior=currentWarrior->next;
	    }
	  else
	    {
	      currentSuite->warrior1=(warrior*)malloc(sizeof(warrior));
	      currentWarrior=currentSuite->warrior1;
	    }
	  
	  currentWarrior->name=0;
	  currentWarrior->next=0;
	  
	  i=ptr-ptr2;
	  currentWarrior->name=
	    (char*)malloc( (i+1) * sizeof(char) );
	  strncpy(currentWarrior->name,ptr2,i);
	  currentWarrior->name[i]=0;
          if(*ptr==0) break;
	  ptr++;	/* skip the comma */

	}
	      
    }

  fclose(f);

  return 0;

}
   
void usage(void)
{
  fprintf(stderr,"Usage: koth warrior rounds suite\n");
}
