/*
 * Copyright 2003 Sun Microsystems Inc.
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * Authors: Karl Park <karl.park@sun.com>
 */

#include <stdio.h>
#include <assert.h>
#include "util.h"
#include <string.h>

#define SAFEBUF_SIZE 5

char *
safe_getline (FILE *fp)
{
  char *buf, *buf2, *ret;
  const size_t bufsize = SAFEBUF_SIZE;
  int n = 1;
  
  assert (fp != NULL);
  if (!fp){
    /* TO DO: log error */
    return NULL;
  }

  if (feof (fp) || ferror (fp)){
    /* TO DO: log error */
    return NULL;
  }

  buf = (char *) calloc (bufsize, sizeof (char));
  buf2 = buf;
  while ((ret = fgets (buf2, bufsize, fp)) != NULL &&
	 buf2[strlen (buf2) - 1] != '\n'){
    buf = (char *) realloc (buf, bufsize * ++n);
    buf2 = buf + strlen (buf);
  }
  if (ret == NULL){
    /* TO DO: log error */
    return NULL;
  }
  return buf;
}

#if 0
int
main (int argc, char **argv)
{
  FILE *fp;
  char *s;


  if (argc != 2){
    fprintf (stderr, "provide file name\n");
    return 0;
  }
  fp = fopen (argv [1], "r");
  while (s = safe_getline (fp)){
    printf ("%d byte : %s", strlen (s), s);
  }
  return 0;
}
#endif



