/*
** closegates.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 closegates()
#else
int closegates()
#endif
{
  int gatesleft;
  int chosengate;
  int foundgate;
  int gatewalk;
  int possiblegates;

  int mazei, mazej;

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

  if (mazegates <= leftgates) return;

  gatesleft = mazegates;

  possiblegates = (mazeheight-1) + (mazewidth-1);

/*
**  fprintf(stderr,
**    "\nmazegates %d leftgates %d gatesleft %d possiblegates %d\n",
**    mazegates,leftgates,gatesleft,possiblegates);
*/

  while (gatesleft > leftgates)
  {
    chosengate = RANDOM()%gatesleft;

    foundgate = 0;

    for (gatewalk = 0; gatewalk < possiblegates; gatewalk++)
    {
      if (gatewalk < (mazewidth-1)/2) /* Pick a side: top? */
      {
        mazei = 0;
        mazej = 2 * gatewalk + 1;
      }
      else
        if (gatewalk < ((mazewidth-1)/2 + (mazeheight-1)/2)) /* right? */
        {
          mazei = 2 * (gatewalk - (mazewidth-1)/2) + 1;
          mazej = mazewidth-1;
        }
        else
/*
**  Thanks to Stefan M. Linnemann <crissl@rulcvx.LeidenUniv.nl> for picking
**  up the two errors flagged beneath his user ID below, where I had "+ 1" and
**  needed the "- 1"'s shown.  Again, it dumped core on other machines, ran
**  OK on mine.  Sigh.  Stefan was kind enough to send the repair back as a
**  patch, and then to patiently explain to me in a second note _why_ what I
**  did was wrong.
*/
          if (gatewalk < ((mazewidth-1) + (mazeheight-1)/2)) /* bottom? */
          {
            mazei = mazeheight-1;
            mazej = 2 * (((mazewidth-1)/2)-                      /* crissl */
                    (gatewalk-((mazewidth-1)/2 + (mazeheight-1)/2))) - 1;
          }
          else  /* left! */
          {
            mazei = 2 * (((mazeheight-1)/2)-                      /* crissl */
                    (gatewalk-((mazewidth-1) + (mazeheight-1)/2))) - 1;
            mazej = 0;
          }

/*
**      fprintf(stderr,
**              "gatesleft %d chosengate %d foundgate %d gatewalk %d",
**              gatesleft,chosengate,foundgate,gatewalk);
**      fprintf(sdterr," mazei %d mazej %d %c\n",
**              mazei,mazej, cmaze[mazei][mazej]);
*/

      if ((cmaze[mazei][mazej] == VDOOR) || (cmaze[mazei][mazej] == HDOOR))
        if (foundgate < chosengate)
          foundgate++;
        else
        {
          cmaze[mazei][mazej] = WALL;
          gatesleft--;
          break;
        }
    }
  }
  return;
}
