#ifndef lint
static char *RCSid = "$Header: /usr/brule/guest/empire/empire/emprcs/lib/gen/parse.c,v 2.1 1995/10/01 22:33:15 empire Exp $";
#endif

/*
 * parse.c
 *
 * parse empire command line, chop into argp
 * If values argpp and spacep passed, parse will use them.
 * otherwise, parse will use static space and global argp.
 * parse assumes that argpp is a char *buf[16], and that spacep
 * points to a buf of at least 256 bytes.
 *
 * from PSL Empire, 1985
 */

#include <ctype.h>
#include "misc.h"

int
parse(buf, argpp, condp, space, redir)
	register s_char *buf;
	s_char	**argpp;
	s_char	**condp;
	s_char	*space;
	s_char	**redir;
{
	register s_char *bp2;
	register s_char *bp1 = space;
	register s_char **arg = argpp;
	int	fs;
	int	argnum;

	if (space == 0)
		return -1;
	if (redir)
		*redir = 0;
	if (condp != 0)
		*condp = 0;
	for (argnum=0; *buf && argnum < 64; ) {
		arg[argnum] = bp1;
		argnum++;
		while (isspace(*buf))
			buf++;
		if (redir && (*buf == '>' || *buf == '|')) {
			*redir = buf;
			argnum--;
			arg[argnum] = 0;
			break;
		}
		fs = ' ';
		if (*buf == '"') {
			fs = '"';
			buf++;
		}
		for (bp2 = bp1; *buf; ) {
			if ((fs == ' ' && isspace(*buf)) || *buf == fs) {
				buf++;
				break;
			}
			/* allow for " inside condarg */
			if (*buf == '"'){
				fs = '"';
				buf++;
			}
			*bp1++ = *buf++;
		}
		*bp1++ = 0;
		if (*bp2 == '?' && condp != 0) {
			*condp = bp2 + 1;
			argnum--;
		}
	}
	for (fs = argnum; fs < 16; fs++)
		arg[fs] = 0;
	return argnum;
}
