/***********************************************************************
     "input.o": basic INPUT functions.
***********************************************************************/

/***********************************
  (C) Copyright 1992-1993; dit/upm
   Distributed under the conditions stated in the
   TOPO General Public License (see file LICENSE)
 ***********************************
 $Log: input.c,v $
 * Revision 1.1  1993/03/18  11:14:24  lotos
 * Initial revision
 *
 ***********************************/

#ifndef lint
static char rcsid[]= "$Id: input.c,v 1.1 1993/03/18 11:14:24 lotos Exp $";
#endif

#define input_IMP

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "glad.hh"
#include "input.hh"


#define ILB	_ILB	/* input line buffer abbreviation */
#define ILB_INC	BUFSIZ	/* input line buffer increment unit */

PUBLIC void
ILBinit (fp)
  FILE *fp;
{
  abort_if(ILB.stat != IBGN &&
	   ILB.stat != ICLR &&
	   ILB.stat != IEND)
  abort_if(fp == NULL)
  ILB.fp= fp;
  ILB.stop= '\0';
  ILB.stat= IBGN;
}

PUBLIC void
ILBclear ()
{
  abort_if(ILB.stat != IRUN)
  tfree(ILB.chr);
  ILB.chr= NULL;
  ILB.ndx= 0;
  ILB.size= 0;
  ILB.level= 0;
  ILB.stat= ICLR;
}

PUBLIC int
ILBfill ()
{
  int last_level;
  char *p;
  
  abort_if(ILB.stat != IBGN &&
	   ILB.stat != IRUN &&
	   ILB.stat != ICLR)
  if (ILB.stat == IBGN ||
      ILB.stat == ICLR)
  { ILB.size= ILB_INC;
    talloc(ILB.chr, ILB_INC);
    ILB.stat= IRUN;
  }
  abort_if(ILB.stat != IRUN)
  last_level= ILB.level;
  for (p= fgets(ILB.chr + ILB.level, ILB.size - ILB.level, ILB.fp);
       p != NULL;
       p= fgets(ILB.chr + ILB.level, ILB_INC + 1, ILB.fp))
  { ILB.level+= strlen(ILB.chr + ILB.level);
    if (ILB.level == ILB.size - 1 &&
        ILB.chr[ILB.level - 1] != '\n')
    { ILB.size+= ILB_INC;
      trealloc(ILB.chr, ILB.size);
    }
    else
      break;
  }
  if (ILB.level == last_level)
    if (last_level == 0)
    { ILBclear();
      ILB.stat= IEND;
      return FALSE;
    }
    else
      return FALSE;
  if (ILB.chr[ILB.level - 1] != '\n')
  { ILB.chr[ILB.level]= '\n';
    ILB.chr[++ILB.level]= '\0';
  }
  return TRUE;
}
