#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "basic.h"
#include "config.h"
#include "errnum.h"
#include "sensor.h"
#include "util.h"

// refer to the sensor and level codes in module outfmt
extern const char * sensorCode[];
extern const char * levelCode[];

void eatWhiteSpace(char **);
int grabArgument(char **, char *, int);
void clearString(char *, int);

static char keyword[16];
static char prefix[5];

int levparseSetLevels(char * cmdStr)
{
  int i;
  char * cp, * cp2;
  boolean prefixFound;
  double levelConv;

  // eat whitespace, grab the first arg and check to see if it's '$palevel'
  eatWhiteSpace(&cmdStr);
  grabArgument(&cmdStr, keyword, 16);

  if (strcmp(keyword, "$PALEVEL") != 0)
    return ERRNUM_INVALID_ARG;

  for (i=0;((i<(SENSOR_NUM_SENSORS<<1)) && (*cmdStr != '\0'));i++) {

    // potential <whitespace>,<whitespace>

    // find and skip over the comma
    while (*cmdStr != ',') cmdStr++; // find the comma
    cmdStr++; // skip over the comma
    eatWhiteSpace(&cmdStr); // eat whitespace up to the next param

    clearString(keyword,16);
    grabArgument(&cmdStr, keyword, 16); // doesn't include the next comma

    clearString(prefix,5);
    cp = prefix; cp2 = keyword;

    // within the argument, parse out the prefix
    // cp left pointing at the beginning of the fp arg
    while(isalpha((int)(*cp2)) != 0) {
      *cp++ = *cp2++;
    }
    *cp = '\0';

    // search our list of prefixes and get a levelId from index
    prefixFound = false;
    for(i=0; (i<(SENSOR_NUM_SENSORS << 1)); i++) {
      if (strcmp(prefix, levelCode[i]) == 0) {
	prefixFound = true;
	break;
      }
    }

    if (prefixFound == true) {
        levelConv = atof(cp2);
	sensorSetLevel(i, ((float)levelConv));
    } // if(prefixFound)
  } // for

  return 0;
}

#if 0
static void clearString(char *s, int len)
{
  int i;
  for (i=0;i<len;i++,s++) *s = '\0';
}

static void eatWhiteSpace(char **s) {
  while ( ((**s == ' ') || (**s == '\t')) && (**s != '\0')) (*s)++;
  }

static int grabArgument(char **srcStr, char *dstStr, int dstLen)
{
  int chCount = 0;
  
  if ((**srcStr == '\0') || (dstLen == 0))
    return -1;

  dstLen -= 1; // decrement dstLen to save room for '\0' at end

  while ( (**srcStr != ' ') && (**srcStr != ',') && 
	  (**srcStr != '\0') && (chCount < dstLen) ) {
    *dstStr++ = **srcStr;
    (*srcStr)++; chCount++;
    }
  
  *dstStr = '\0'; // add terminating NULL character
  
  return 0;
}
#endif



