/*
 *
 * (c) Copyright 1990 by William R. Pringle
 *
 *				**** SPLIT FLDS ****
 *
 * This routine splits a string into fields based on a delimeter
 * The string and an array of strings are passed by the caller.
 * This routine modifies the string by inserting EOS characters ('\0')
 * The array of strings is set to each field that is found in string.
 * The number of fields found is returned as the function value, a
 *	zero value indicates an error (e.g., the string pointer was NULL)
 *
 */

#include <stdio.h>

#ifndef EOS
#define	EOS	'\0'
#endif

split_flds(str,flds,delim,skip,maxflds)
char	*str;				/* input string to parse */
char	**flds;				/* output array of strings */
char	delim;				/* field delimeter character */
int		skip;				/* skip multiple delimeters */
int		maxflds;			/* maximum number of fields */
{
	char	*p, *q;			/* temporary pointers for parsing */
	int		nflds;			/* number of fields found */

	nflds = 0;				/* nothing found yet */

	if ((p = str) == NULL) return nflds;

	while (*p != EOS && nflds < maxflds)
	{
		for (q = p; *p != EOS && *p != delim; p++);	/* find delimeter */
		flds[nflds++] = q;	/* record beginning of field */
		if (*p != EOS)
		{		/* still more to parse in line */
			*p++ = EOS;	/* terminate intermediate field */
				/* skip multiple delimeters or treat each as a field? */
			if (skip) while (*p != EOS && *p == delim) p++;
			if (*p == EOS)
			{		/* last field missing */
				flds[nflds++] = p;
			}
		}
	}

	return nflds;
}

/*
 * NOTE:
 *
 * The following driver is compiled when -DEBUG option is used.
 *	(this defining a variable called EBUG)
 *
 */

#ifdef EBUG

#ifndef MAXFLDS
#define	MAXFLDS	99
#endif

main(argc,argv)
int	argc;
char	**argv;
{
	char buf[BUFSIZ];		/* input buffer */
	char	delim;			/* delimeter */
	char	*flds[MAXFLDS];	/* output table */
	int		nflds;			/* number of fields returned */
	int		skip;			/* skip multiple delimeters */
	int		i;				/* I always need i */

	printf("Enter delimeter character: ");
	gets(buf);				/* first character is delimeter */
	delim = *buf;			/* save it */
	printf("Skip multiple delimeters? (y or n): ");
	gets(buf);
	skip = (*buf == 'y' || *buf == 'Y') ? 1 : 0;

	while (*buf != EOS)
	{
		printf("Enter string to parse, or RETURN to quit\n>");
		gets(buf);			/* get string to parse */
		nflds = split_flds(buf,flds,delim,skip,MAXFLDS);
		printf("%d fields found:\n", nflds);

		for (i=0; i < nflds; i++) printf("%d: >>%s<<\n", i, flds[i]);
	}
}
#endif
