


#include <stdio.h>
#include <ctype.h>

#include "param.h"





export boolean loadParameters(char *file, ParamDesc *pd)
{
  FILE *fp;
  static char buff[1024];
  static char name[1024], type[1024];
  char *bp, *vp;
  int nchars;
  int entry;


  if ((fp = fopen(file, "r")) == NULL) {
    fprintf(stderr, "Can't open parameter file \"%s\"\n", file);
    return TRUE;
  }

  while (fgets(buff, 1023, fp) != NULL) {
    if ((bp = strchr(buff, '#')) != NULL) {
      *bp = (char) 0;
    }

    for (bp = buff + strlen(buff) - 1; bp >= buff && isspace(*bp); bp--) {
      *bp = (char) 0;
    }

    if (*buff == (char) 0) {
      continue;
    }
      
    if (sscanf(buff, "%s%*[ \t:]%s%*[ \t=]%n", name, type, &nchars) != 2) {
      fprintf(stderr, "Error parsing parameter line\n");
      return TRUE;
    }

    for (entry = 0; pd[entry].name && pd[entry].type != EndParam; entry++) {
      if (!strcmp(pd[entry].name, name)) {
        break;
      }
    }

    if (!pd[entry].name  ||  pd[entry].type == EndParam) {
      fprintf(stderr, "Parameter entry not found, \"%s\"\n", name);
      return TRUE;
    }

    bp = buff + nchars;
    if      (!strcasecmp(type, "int")) {
      if (pd[entry].type != IntParam)  goto TypeError;
      if (sscanf(bp, "%li", (long *) pd[entry].valp) != 1)  goto GetError;
    }
    else if (!strcasecmp(type, "char")) {
      if (pd[entry].type != CharParam)  goto TypeError;
      if (sscanf(bp, "\'%c\'", (char *) pd[entry].valp) != 1)  goto GetError;
    }
    else if (!strcasecmp(type, "uchar")) {
      if (pd[entry].type != UcharParam)  goto TypeError;
      if (sscanf(bp, "\'%c\'", (uchar *) pd[entry].valp) != 1)  goto GetError;
    }
    else if (!strcasecmp(type, "string")) {
      if (pd[entry].type != StringParam)  goto TypeError;
      if (*bp != '\"')  goto GetError;
      bp++;
      vp = (char *) pd[entry].valp;

      for ( ; *bp && *bp != '\"' && bp[-1] != '\\'; ) {
        *(vp++) = *(bp++);
      }
    }
    else if (!strcasecmp(type, "double")) {
      if (pd[entry].type != DoubleParam)  goto TypeError;
      if (sscanf(bp, "%lf", (double *) pd[entry].valp) != 1)  goto GetError;
    }
    else {
      fprintf(stderr, "Illegal parameter type, \"%s\"\n", type);
      return TRUE;
    }
  }

  return FALSE;
  
 TypeError:
  fprintf(stderr, "Parameter type mismatch\n");
  return TRUE;

 GetError:
  fprintf(stderr, "Error reading parameter value\n");
  return TRUE;
}
