/*  filo -- manipulate a `rolodex'-like database
 *  Copyright (C) 1994 David Deaven, Jennifer Corkill
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * $Id: read.c,v 1.3 1995/10/26 19:53:43 deaven Exp $
 */

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "dmd/memory.h"
#include "filo.h"

#define MAX_LINE_LENGTH	512	/* max chars in database file line */

static int line = -1;
static int buffersize = 0;
static char *buffer = NULL;

/* Read a file with address entries in it.
 * Return the next entry.
 * Return EOF when the file is exhausted.
 *
 * Each entry is separated by at least one blank line ("\n\n").
 * White space between these delimiting newlines is acceptable.
 */
char *read_filo(FILE *fin)
{
  char *s;
  int i, l, recsize=0;

  while(1)
  {
    if((i = recsize + MAX_LINE_LENGTH) > buffersize)
      buffer = myrealloc(buffer, buffersize = i); 

    s = buffer + recsize;
    if(fgets(s, MAX_LINE_LENGTH, fin) == NULL)
    {
      line = -1;
      return (recsize > 0 ? buffer : NULL);
    }

    if(line < 0) line = 1;
    else ++line;

    /* This is the end of a record if the line only contains a 
     * newline character as the first interesting character.
     * However, if we haven't read anything yet, we can skip
     * such a record, waiting for the next.
     */
    i=0; while(s[i]!='\n' && isspace(s[i]))++i;
    if(s[i]=='\n')
    {
      s[0]='\0';
      if(recsize > 0) return buffer;
    }
    else
    {
      l = strlen(s);
      s += l;
      recsize += l;
    }
  }
}

