/* Copyright (c) 1991-2002 Doshita Lab. Speech Group, Kyoto University */
/* Copyright (c) 2000-2002 Speech and Acoustics Processing Lab., NAIST */
/*   All rights reserved   */

/* readfile.c --- input stream handling */

/* $Id: readfile.c,v 1.4 2002/09/11 22:01:50 ri Exp $ */

#include <sent/stddefs.h>
#ifdef HAVE_ZLIB
#include <zlib.h>
#endif


/* read in one line from fp */
/* blank line will be skipped */
/* return NULL on EOF or error */
char *
getl(char *buf, int maxlen, FILE *fp)
{
  int newline;

  while(
#ifdef HAVE_ZLIB
	gzgets((gzFile)fp, buf, maxlen) != Z_NULL
#else
	fgets(buf, maxlen, fp) != NULL
#endif
	) {
    newline = strlen(buf)-1;    /* chop newline */
    if (buf[newline] == '\n') buf[newline] = '\0';
    if (buf[0] == '\0') continue; /* if blank line, read next */
    return buf;
  }
  return NULL;
}

/* read in one line from fd */
/* blank line will be skipped */
/* return NULL on EOF or error */
char *
getl_fd(char *buf, int maxlen, int fd)
{
  int cnt;
  char *p;
  p = buf;
  while(1) {
    cnt = read(fd, p, 1);
    if (cnt <= 0) return NULL;		/* eof or error */
    if (*p == '\n' && p > buf) {
      *p = '\0';
      break;
    } else {
      if (++p >= buf + maxlen) {
	j_error("Error: getl_fd: line too long (> %d)\n", maxlen);
      }
    }
  }
  return buf;
}

/* return first token of a buffer, terminate if not found */
char *
first_token(char *buf)
{
  char *p;
  if ((p=strtok(buf, DELM)) == NULL) {
    j_error("data format error: corrupted data?\n");
  }
  return p;
}
/* return next token of a buffer, terminate if not found */
char *
next_token() {
  char *p;
  if ((p=strtok(NULL,DELM)) == NULL) {
    j_error("data format error: corrupted data?\n");
  }
  return p;
}
/* return next token of a buffer, return NULL if not found */
char *
next_token_if_any() {
  char *p;

  p=strtok(NULL,DELM);

  return p;
}
/* return the rest token(s) */
char *
rest_token() {
  char *p;
  if ((p=strtok(NULL, "\n")) == NULL) {
    j_error("data format error: corrupted data?\n");
  }
  return p;
}    

