# include "dvoshell.h"

// identify the fields to be extracted (test for where, check syntax)
dbField *dbCmdlineFields (int argc, char **argv, int table, int *last, int *nfields) {

  int i, j, status, Nfields, NFIELDS;
  char *p, *q, *field;
  dbField *fields;

  *nfields = 0;
  Nfields = 0;
  NFIELDS = 10;
  ALLOCATE (fields, dbField, NFIELDS);
  dbInitField (&fields[0]);

  // examine each argv[i] entry until we reach a where 
  for (i = 1; (i < argc) && strcasecmp (argv[i], "where"); i++) {
    // split the word by ","
    p = argv[i];
    while (*p) {
      q = strchr (p, ',');
      if (q == NULL) {
	field = strcreate (p);
	p = p + strlen(p);
      } else {
	field = strncreate (p, q-p);
	p = q + 1;
      }
      // identify field for word
      // need to know which type of fields to look for...
      // xxx extend this more generally later
      if (table == DVO_TABLE_MEASURE) {
	status = ParseMeasureField (&fields[Nfields], field);
      } 
      if (table == DVO_TABLE_AVERAGE) {
	status = ParseAverageField (&fields[Nfields], field);
      } 
      if (!status) {
	gprint (GP_ERR, "unknown database field %s\n", field);
	free (field);
	dbFreeFields (fields, Nfields);
	return (NULL);
      }
      free (field);

      Nfields ++;
      CHECK_REALLOCATE (fields, dbField, NFIELDS, Nfields, 10);
      dbInitField (&fields[Nfields]);
    }
  }

  // require 'where' before boolean math
  if (i != argc) {
    if (strcasecmp(argv[i], "where")) {
      gprint (GP_ERR, "syntax error\n");
      free (fields);
      return (NULL);
    }
    if (i > argc - 2) {
      gprint (GP_ERR, "missing boolean expression\n");
      free (fields);
      return (NULL);
    }
    i++; // skip over the 'where'
  }

  *last = i;
  *nfields = Nfields;

  return (fields);
}
