/*
** makegates.c  Copyright 1991 Kent Paul Dolan,
**              Mountain View, CA, USA 94039-0755
**
** Written to satisfy an inquiry on USENet's rec.games.programmer newsgroup.
** May be freely used or modified in any non-commercial work.  Copyrighted
** only to prevent patenting by someone else.
*/

#include <stdio.h>
#include "townmaze.h"
#include "townproto.h"

#ifdef __STDC__
void makegates()
#else
int makegates()
#endif
{

  int gatewalls;
  int chosenwall;
  int chosencell;
  int stdir;
  int tries;
  int i;

/*
** Pepper gates around the outer wall; avoid gates at corners for
** esthetic reasons.
*/

#if PROGRESS
  fprintf(stderr,"Gates ");
#endif

  gatewalls = 2 * (mazeheight/2 + mazewidth/2);

  for (i = 0; i < mazegates; i++)
  {

/*  fprintf(stderr,"Gate %d\n",i); */

/*
** Protect against infinite looping.
*/
    tries = 0;
/*
** Keep looking until a candidate cell is found for this ith gate.
*/
    do
    {
      /* not perfectly fair, but good enough for moderate sized mazes. */
      chosenwall = RANDOM()%gatewalls;
                                       
/*    fprintf(stderr,"  chosenwall %d\n",chosenwall); */
      if (chosenwall < (mazewidth/2))
      {
        chosencell = chosenwall;
        stdir = 2;
/*      fprintf(stderr,"    top chosencell %d\n",chosencell); */
      }
      else
        if (chosenwall < ((mazewidth/2) + (mazeheight/2)))
        {
          chosencell = ((chosenwall - (mazewidth/2) + 1) 
                                      * (mazewidth/2) - 1);
          stdir = 3;
/*        fprintf(stderr,"      right chosencell %d\n",chosencell); */
        }
        else
          if (chosenwall < (mazewidth - 1 + (mazeheight/2)))
          {
            chosencell = (listsize - chosenwall + (mazewidth/2) 
                          + (mazeheight/2) - 1);
            stdir = 0;
/*          fprintf(stderr,"        bottom chosencell %d\n",chosencell); */
          }
          else
          {
            chosencell = (mazewidth - 1 + mazeheight - 1 - chosenwall - 1)
                         * (mazewidth/2);
            stdir = 1;
/*          fprintf(stderr,"          left chosencell %d\n",chosencell); */

          }
      tries++;
    } while (   (tries <= MAXTRIES)
             && (   (statlist[chosencell].status != ISOLATED)
                 || (   nhbrexists(chosencell,0)
                     && (statlist[nhbris(chosencell,0)].status != ISOLATED) )
                 || (   nhbrexists(chosencell,1)
                     && (statlist[nhbris(chosencell,1)].status != ISOLATED) )
                 || (   nhbrexists(chosencell,2)
                     && (statlist[nhbris(chosencell,2)].status != ISOLATED) )
                 || (   nhbrexists(chosencell,3)
                     && (statlist[nhbris(chosencell,3)].status != ISOLATED) )
                )
            );

    if (tries <= MAXTRIES) makestreet(chosencell,streetnumct++,stdir);
  }
  return;
}
