/*
 * CSV-reading C module
 *
 * Copyright (C) 2019 Mateusz Viste
 *
 */

/* reads a csv line from file. returns 0 on success, -1 on EOF or error. */
static int csvreadline(char *buf, unsigned short maxlinelen, char **ptrs, int maxptrs, FILE *fd) {
  int c;
  int i;
  int t;
  int blen = 0;
  /* read the line into buf */
  for (;;) {
    c = fgetc(fd);
    if ((c < 0) && (blen == 0)) return(-1);
    if ((c < 0) || (c == '\n')) break;
    if (c == '\r') continue;
    buf[blen++] = c;
    if (blen == maxlinelen) return(-1);
  }
  buf[blen] = 0;

  /* set up pointers and terminate fields */
  for (i = 0; i < maxptrs; i++) ptrs[i] = buf + blen; /* preinit to empty */
  ptrs[0] = buf;
  t = 1;
  for (i = 0;; i++) {
    switch (buf[i]) {
      case ',':
        buf[i] = 0;
        ptrs[t] = buf + i + 1;
        if ((t + 1) < maxptrs) t++;
        break;
      case '\r':
      case '\n':
      case 0:
        buf[i] = 0;
        return(0);
    }
  }
}
