#include "V.h"
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Split a string up into substrings, looking for any of the given  delimiters.
* Note  that  we modify the substring, and leave fldv[0] thru fldv[r] pointing
* at null-terminated substrings.  At most n args will be found, with the  last
* one  getting  the  entire tail end of the string.  All delimiters before the
* last field will be replaced by nulls.  The number of fields is returned.  We
* also set fldv[r] to null, if r<n.
*/
#ifndef CHARSETSIZE
#define CHARSETSIZE 256
#endif

split(string,delims,n,fldv)
	char* string;	/* The string to chop up */
	char* delims;	/* The delimiters to wipe out */
	int   n;		/* Size of fldv[] */
	char* fldv[];	/* Output: pointers to fields */
{	int   r=0;		/* Return value: number of fields */
	int   c;
	char* p;
	Flag  x[CHARSETSIZE];
	Fpush("split");
	if (!string || !delims)	/* Sanity check */
		Fail;
	Bzero(x,CHARSETSIZE);	/* Set up x[] to be 1 for delimiters, 0 otherwise */
	for (p=delims; *p; p++)
		x[*p] = 1;
	fldv[r=0] = string;
	for (p = string; (r < n) && (c = *p); p++) {
		if (x[c]) {		/* Delimiter? */
			V6 "Byte %d: delimiter '%c'",p-string,c D;
			*p = 0;
		} else {		/* Start of new field? */
			if (p == string || !p[-1]) {
				V6 "Byte %d: \"%s\"",p-string,p D;
				fldv[r++] = p;
			}
		}
	}
	if (r < n) fldv[r] = 0;	/* Null terminator */
fail:
	if (r < 0 || r > n)
		V2 "### Bad return value %d outside [0,%d]",r,n D;
	if (Vlvl > 4)
		for (n=0; n<r; n++)
			V5 "Field%2d=\"%s\"",n,fldv[n] D;
	Fpop;
	return r;
}
