/*
** makespace.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 makespace()
#else
int makespace()
#endif
{
  int i,j;

  if ((statlist = (DLENODE *)malloc(listsize * sizeof(DLENODE))) == NULL)
  {
    fprintf(stderr,
      "Unable to allocate space for cell list for that size maze\n");
    exit(1);
  }

  if ((cmaze = (char **)malloc(mazeheight * sizeof(char *))) == NULL)
  {
    fprintf(stderr,"%s%s",
      "Unable to allocate space for maze display pointer list for that",
      " size maze\n");
#ifdef __STDC__
    if (free(statlist) == -1)
      fprintf(stderr,"unable to free(statlist) on bailout\n");
#else
    free(statlist);
#endif

    exit(1);
  }

/*
** Thanks to  "GLENN E. HOST" <host@ccf4.nrl.navy.mil> for spotting a bug
** here that should have killed something during testing; I had mazewidth
** for mazeheight in the loop limit here.
*/

  for (i = 0; i < mazeheight; i++)
  {
    if ((cmaze[i] = (char *)malloc(mazewidth * sizeof(char))) == NULL)
    {
      fprintf(stderr,
      "Unable to allocate space for maze char array for that size maze\n");
#ifdef __STDC__
      for (j = 0; j < i; j++)
      {
        if (free(cmaze[j]) == -1)
        {
          fprintf(stderr,"unable to free(cmaze[%d]) on bailout\n",j);
          break;
        }
      }
      if (free(cmaze) == -1)
        fprintf(stderr,"unable to free(cmaze) on bailout\n");
      else
        if (free(statlist) == -1)
          fprintf(stderr,"unable to free(statlist) on bailout\n");
#else
      for (j = 0; j < i; j++) free(cmaze[j]);
      free(cmaze);
      free(statlist);
#endif
      exit(1);
    }
  }
  
  return;
}
