/*
 *	read -- reads a line of input and puts each word into variables
 *
 *	SYNTAX
 *		read <var-list>
 *
 *	DESCRIPTION
 *		Reads one line from stdin and puts each word encountered into
 *		successive variables from the list provided on the command line.
 *		Word delimiters are any whitespace characters.  Both single and
 *		double quotes may surround a string of characters to indicate
 *		that they should be considered one word, thus preventing the
 *		whitespace from being interpreted.
 */

#include <stdio.h>
#include <stdarg.h>
#include <exec/types.h>
#include <dos/var.h>
#include <pragma/dos.h>

void usage(int ier, char *fmt, ...)
{
	if (fmt && *fmt) {
		va_list args;

		va_start(args, fmt);
		vprintf(fmt, args);
		va_end(args);
	}
	puts("Usage: read <var-list>");
	exit( ier );
	/* NOTREACHED */
}

#define iseol(x)	((x) == '\n')

int main(int argc, char **argv)
{
	static char buff[BUFSIZ];
	char *bp, *start, delim;

	if (argc < 2)
		usage(20, NULL);

	fgets(buff, sizeof(buff), stdin);
	for (bp = buff; isspace(*bp); bp++)
		;
	start = bp, delim = '\0';

	while (*bp) {
		if (*bp == delim || (!delim && isspace(*bp))) {
			if (argc-- > 2 || *bp == delim)
				*bp++ = '\0';
			if (!SetVar(*++argv, start, -1L, LV_VAR | GVF_GLOBAL_ONLY))
				usage(20, "Couldn't set variable `%s'!\n", *argv);
			if (argc == 1)
				break;
			while (isspace(*bp))
				bp++;
			delim = '\0';
			start = bp;
		} else if (bp == start && (*bp == '"' || *bp == '\'')) {
			delim = *bp++;
			start = bp;
		} else
			bp++;
	}
	return( feof(stdin) ? 5 : 0 );
}
