#include "galaxy.h"


#ifdef __STDC__
void 
creategame (void)
#else
void 
creategame ()
#endif
{
   int             i, j, k;
   int             nplanets;
   double          x, y, dx, dy;
   double          tmp;
   player         *P;
   planet         *p;

   printf("Game name? ");
   gets(gamename);
   if (gamename[0] == 0)
      return;
   mkdir("data", 0700);
   sprintf(buf, "data/%s", gamename);
   if (mkdir(buf, 0700)) {
      printf("Can't create directory %s", buf);
      return;
   }
   printf("Name of players file? ");
   gets(buf);
   f = Fopen(buf, "r");
   printf("Total number of planets? ");
   gets(buf);
   nplanets = atoi(buf);
   printf("Size of galaxy? ");
   gets(buf);
   galaxysize = atof(buf);
   turn = 0;

   for (getbuf(), i = 1; buf[0] && buf[0] != (char)EOF; getbuf(), i++) {
      P = alloc(sizeof(player));
      memset(P, 0, sizeof(player));
      addlist(&players, P);
      nstrcpy(P->addr, buf, ADDRSIZE);
      sprintf(P->name, "Player %d", i);
      P->drive = 1;
      P->weapons = 1;
      P->shields = 1;
      P->cargo = 1;
      P->msize = galaxysize;
      P->namecase = 1;
      P->prodtable = 0;
      P->autounload = 0;
      P->sortgroups = 0;
      P->fleettables = 1;

      j = 0;
      do {
         k = 0;
         x = frand(galaxysize);
         y = frand(galaxysize);
         for (p = planets; p; p = p->next)
            if (p->owner) {
               dx = p->x - x;
               dy = p->y - y;
               if (dx * dx + dy * dy <= DRIVEMAGIC * DRIVEMAGIC) {
                  k = 1;
                  j++;
                  if (j == 100) {
                     printf("Can't space homeworlds at least %lf light years apart\n", DRIVEMAGIC);
                     printf("Please try again with a larger galaxy size\n");
                     fclose(f);
                     freegame();
                     return;
                  }
                  break;
               }
            }
      }
      while (k);
      p = addplanet();
      p->x = x;
      p->y = y;
      p->owner = P;
      p->size = MAXPOP;
      p->resources = 10;
      p->pop = MAXPOP;
      p->ind = MAXPOP;
   }
   fclose(f);

   for (; i != nplanets; i++) {
      p = addplanet();
      p->x = frand(galaxysize);
      p->y = frand(galaxysize);
      p->size = frand(MAXPOP);
      p->resources = pow(10.0, frand2());
   }

   reports();
   savegame(gamename);
   freegame();
}
