/*
 *========================================================================
 * $Id: xmlsysd_parse.c 77 2002-04-02 07:49:26Z rgb $
 *
 * See copyright in copyright.h and the accompanying file COPYING
 *========================================================================
 */

#include "xmlsysd.h"

/*
 * parse() is a reusable routine to break up a string into char[32]
 * fields.  Anything past 32 characters is truncated.
 */

int parse(inbuffer,outfields,maxfields,maxfieldlength)
char *inbuffer;
char **outfields;
int maxfieldlength;
int maxfields;
{

 char delim[7],*nextval;
 int i = 0;

 if((verbose == D_ALL) || (verbose == D_PARSE)){
   printf("D_PARSE: Starting parse().  Use -v %d to focus.\n",D_PARSE);
 }



/* 
 * Permit blank, tab, or comma separators anywhere we need to parse
 * a line.
 */
 delim[0] = ' ';                /* blanks */
 delim[1] = (char) 9;           /* tab */
 delim[2] = ',';                /* comma */
 delim[3] = (char) 10;		/* LF */
 delim[4] = (char) 13;		/* CR */
 delim[5] = ':';		/* : needed to parse /proc/net/dev or passwd */
 delim[6] = (char) NULL;        /* terminator */

 
 nextval = strtok(inbuffer,delim);
 if(nextval == (char *)NULL) return 0;
 strncpy(outfields[i++],nextval,maxfieldlength);
 if((verbose == D_ALL) || (verbose == D_WORK)){
   printf("D_PARSE: Parsed field[%d] = %s.\n",i-1,outfields[i-1]);
 }

 while(i < maxfields-1){
   nextval = strtok((char *) NULL, delim);
   if(nextval == (char *)NULL) break;
   strncpy(outfields[i++], nextval,maxfieldlength);
   if((verbose == D_ALL) || (verbose == D_WORK)){
     printf("D_PARSE: Parsed field[%d] = %s.\n",i-1,outfields[i-1]);
   }
 }

 /* Null the last field */
 bzero(outfields[i],maxfieldlength);
 if((verbose == D_ALL) || (verbose == D_WORK)){
   printf("D_PARSE: Terminated field[%d] = %s.\n",i,outfields[i]);
 }

 return i;

}

/*
 * parse_chips() is a special purpose routine required to parse the
 * return from /proc/sys/dev/sensors/chips (only).  The second field
 * MIGHT be isa or smbus and a unique identifier of a "good" sensor.
 */

int parse_chips(inbuffer,outfields,maxfields,maxfieldlength)
char *inbuffer;
char **outfields;
int maxfieldlength;
int maxfields;
{

 char delim[2],*nextval;
 int i = 0;
/* 
 * The delimiter in question is a "-", to parse e.g. "w83782d-isa-0290".
 */
 delim[0] = '-';                /* blanks */
 delim[1] = (char) NULL;        /* terminator */

 nextval = strtok(inbuffer,delim);
 strncpy(outfields[i++],nextval,maxfieldlength);

 while(i < maxfields-1){
   nextval = strtok((char *) NULL, delim);
   if(nextval == (char *)NULL) break;
   strncpy(outfields[i++], nextval,maxfieldlength);
 }

 /* Null the last field */
 bzero(outfields[i],maxfieldlength);

 return i;

}

