#include <stdio.h>
#include "dbftable.h"

static char HELP[] =
  "\n"
  "  dbflist  <dbf filespecs>\n"
  "\n"
  "writes all records from the specified DBF table to the standard\n"
  "output in comma-delimited form, with spacing added as required\n"
  "so fields will be aligned vertically. The format for dates is\n"
  "YYYYMMDD. Quotation marks and control characters in character\n"
  "fields are replaced with spaces.\n"
  "If there is an asterisk (*) before the filespecs, the list\n"
  "will begin with the field names on the first line.\n";

int main(int argc, char **argv)
{
  if (argc < 2)
  {
    fputs(HELP, stderr);
    return 1;
  }
  bool field_names_on_first_line = false;
  const char *filespecs = argv[1];
  if (filespecs[0] == '*')
  {
    filespecs++;
    field_names_on_first_line = true;
  }
  dbf_table t;
  if (!t.open(filespecs, DBF_READ))
  {
    fprintf(stderr, "Can't open table %s\n", filespecs);
    return 1;
  }
  if (field_names_on_first_line)
  {
    int i = 0;
    for (int i = 0; ; i++)
    {
      const dbf_field_descriptor *p = t.field_info(i);
      if (p == NULL)
      {
        fputc('\n', stdout);
        break;
      }
      if (i != 0) fputs(", ", stdout);
      fputs(p->name, stdout);
    }
  }
  for (long i = 1L; i <= t.number_of_records; i++)
  {
    t.record_number = i;
    char buffer[500];
    if (!t.delimited(buffer, sizeof(buffer)))
    {
      fprintf(stderr, "error in record %ld\n", i);
      return 1;
    }
    puts(buffer);
  }
  t.close();
  return 0;
}

