/* xargs -- build and execute command lines from standard input
 Copyright (C) 2014, 2017 Ron Charlton
 Copyright (C) 1990, 91, 92, 93, 94 Free Software Foundation, Inc.

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>. */


/* Written by Mike Rendell <michael@cs.mun.ca>
and David MacKenzie <djm@gnu.ai.mit.edu>.  */

/* Modified 2014-01-28 by Ron Charlton (RonC) for Win32/Win64 with quoted file
names handled.  I eliminated all of the #if[n]def WIN32 tests and #ifndef WIN32
enclosed code.  Although some code remains that appears to allow
compiling for non-Win32/Win64 systems, it is not possible.  Now the only
target for this code is WIN32/WIN64. */

char version_string[] = "$Id: xargs.c 2.13 2017-11-19 17:06:59-05 Ron Exp $";

char copyright[] =  "Copyright (C) 2014, 2017 Ron Charlton.\n"
		"Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc.";

#include <string.h>
#include <process.h>
#include <ctype.h>
#include <string.h>

#ifdef isascii
#undef isascii
#endif

#ifdef isblank
#define ISBLANK(c) (isascii (c) && isblank (c))
#else
#define ISBLANK(c) ((c) == ' ' || (c) == '\t')
#endif

#define ISSPACE(c) (ISBLANK (c) || (c) == '\n' || (c) == '\r' \
|| (c) == '\f' || (c) == '\v')

#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <io.h>
#include <conio.h>

#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdlib.h>
#include <Windows.h> // for OpenProcess(), TerminateProcess()

// link with shell32 library for OpenProcess() and
// TerminateProcess() (is automatic by this)
#pragma comment(lib, "shell32.lib")

#include "xmalloc.h"

#include "error.h"
#include "getopt.h"
#include "getwords.h"
#include "StrchrCount.h"

#ifdef __cplusplus
extern "C" {
#endif

// nPid is used in signal_handler() and main()
static int nPid;		// holds child process' ID

/* a larger ARG_MAX than 1024 will result in errno E2BIG from _spawnvp()  */
//#define ARG_MAX 1024
// 5000 works on Windows 7 SP1 x64
#define ARG_MAX 5000

/* States for read_line. */
#define NORM 0
#define SPACE 1
#define QUOTE 2
#define BACKSLASH 3

/* Return nonzero if S is the EOF string.  */
#define EOF_STR(s) (eof_str && *eof_str == *s && !strcmp(eof_str, s))

/* Not char because of type promotion; NeXT gcc can't handle it.  */
typedef int myboolean;
#define		true    1
#define		false	0

/* This program's name.  */
char *progName = "xargs";

/* Buffer for reading arguments from stdin.  */
static char *linebuf;

/* Line number in stdin since the last command was executed.  */
static int lineno = 0;

/* If nonzero, then instead of putting the args from stdin at
the end of the command argument list, they are each stuck into the
initial args, replacing each occurrence of the `replace_pat' in the
initial args.  */
static char *replace_pat = NULL;

/* The length of `replace_pat'.  */
static size_t rplen = 0;

/* If nonzero, when this string is read on stdin it is treated as
end of file.
I don't like this - it should default to NULL.  RonC: Now it does. */
static char *eof_str = NULL;

/* If nonzero, the maximum number of nonblank lines from stdin to use
per command line.  */
static long lines_per_exec = 0;

/* The maximum number of arguments to use per command line.  */
static long args_per_exec = 1024;

/* If true, exit if lines_per_exec or args_per_exec is exceeded.  */
static myboolean exit_if_size_exceeded = false;

/* The maximum number of characters that can be used per command line.  */
static long arg_max;

/* Storage for elements of `cmd_argv'.  */
static char *argbuf;

/* The list of args being built.  */
static char **cmd_argv = NULL;

/* Number of elements allocated for `cmd_argv'.  */
static int cmd_argv_alloc = 0;

/* Number of valid elements in `cmd_argv'.  */
static int cmd_argc = 0;

/* Number of chars being used in `cmd_argv'.  */
static int cmd_argv_chars = 0;

/* Number of initial arguments given on the command line.  */
static int initial_argc = 0;

/* Number of chars in the initial args.  */
static int initial_argv_chars = 0;

/* true when building up initial arguments in `cmd_argv'.  */
static myboolean initial_args = true;

/* If nonzero, the maximum number of child processes that can be running
at once.  */
static int proc_max = 1;

/* Total number of child processes that have been executed.  */
static int procs_executed = 0;

/* If true, print each command on stderr before executing it.  */
static myboolean print_command = false;

/* If true, query the user before executing each command, and only
execute the command if the user responds affirmatively.  */
static myboolean query_before_executing = false;

/* if true, at least one invocation of command returned 1-125  */
static int command_exit_status_1_to_125 = false;

/* if true, command exited with status 255 (-1)  */
static int command_exit_status_255 = false;

static struct option const longopts[] = {
	{"null", no_argument, NULL, '0'},
	{"eof", optional_argument, NULL, 'e'},
	{"replace", optional_argument, NULL, 'i'},
	{"max-lines", optional_argument, NULL, 'l'},
	{"max-args", required_argument, NULL, 'n'},
	{"no-run-if-empty", no_argument, NULL, 'r'},
	{"max-chars", required_argument, NULL, 's'},
	{"verbose", no_argument, NULL, 't'},
	{"exit", no_argument, NULL, 'x'},
	{"query", no_argument, NULL, 'p'},
	{"version", no_argument, NULL, 'v'},
	{"help", no_argument, NULL, 'h'},
	{NULL, no_argument, NULL, 0}
};

/* prototypes */
static int read_line(void);
static int read_string(void);
static void do_insert(char *arg, size_t arglen, size_t lblen);
static void push_arg(char *arg, size_t len);
static void do_exec(void);
static long parse_num(char *s, int option, long min, long max);
static long env_size(char **envp);
static void usage(FILE * stream, int status);

static void print_args(char **args);
static char *dblQuoteString(const char *s);
static void freeQuotedArgs(char **args);
static char **dblQuoteArgs(int argc, const char *const argv[]);
static void signal_handler(int signal_value);
static int subExec(int argc, char **argv);


int
main(int argc, char **argv)
{
	int optc;
	int always_run_command = 1;
	static char *p[4] = { "", "", "???", "???" };
	long orig_arg_max;
	char *default_cmd = "echo";
	int (*read_args)(void) = read_line;

	orig_arg_max = ARG_MAX;
	arg_max = orig_arg_max;

	/* : -> required argument,   :: -> optional argument */
	while ((optc = getopt_long(argc, argv, "+0e::i::l::n:rs:txpvh",
							   longopts, (int *) 0)) != -1) {
		switch (optc) {
		case '0':
			read_args = read_string;
			(void)_setmode(_fileno(stdin), _O_BINARY);
			(void)_setmode(_fileno(stdout), _O_BINARY);
			break;

		case 'e':
			if (optarg)
				eof_str = optarg;
			else
				eof_str = 0;
			break;

		case 'h':
			usage(stdout, 0);
			break;

		case 'i':
			if (optarg)
				replace_pat = optarg;
			else
				replace_pat = "{}";
			/* -i excludes -n -l.  */
			args_per_exec = 0;
			lines_per_exec = 0;
			break;

		case 'l':
			if (optarg)
				lines_per_exec = parse_num(optarg, 'l', 1L, -1L);
			else
				lines_per_exec = 1;
			/* -l excludes -i -n.  */
			args_per_exec = 0;
			replace_pat = NULL;
			break;

		case 'n':
			args_per_exec = parse_num(optarg, 'n', 1L, -1L);
			/* -n excludes -i -l.  */
			lines_per_exec = 0;
			replace_pat = NULL;
			break;

		case 'p':
			query_before_executing = true;
			break;

		case 'r':
			always_run_command = 0;
			break;

		case 's':
			arg_max = parse_num(optarg, 's', 1L, orig_arg_max);
			break;

		case 't':
			print_command = true;
			break;

		case 'v':
			/* find the whitespaced-delimited "words" in version_string and
			 use the version number and date  */
			if (getwords(version_string, p, 4) == 4) {
				printf("GNU %s version %s (%s) for Windows.\n%s\n",
						progName, p[2], p[3], copyright);
				return 0;
			} else {
				error(1, 0, "Internal error; cannot get my version or date.");
			}
			/* Not reached */
			break;

		case 'x':
			exit_if_size_exceeded = true;
			break;

		default:
			usage(stderr, 1);
			break;
		}
	}

	if (replace_pat || lines_per_exec)
		exit_if_size_exceeded = true;

	if (optind == argc) {
		optind = 0;
		argc = 1;
		argv = &default_cmd;
	}

	linebuf = xmalloc(arg_max + 1);
	argbuf = xmalloc(arg_max + 1);

	// Call signal_handler() for every signal we can catch, so we can terminate
	// the child process if it is running.
	signal(SIGABRT, signal_handler);
	signal(SIGFPE,  signal_handler);
	signal(SIGILL,  signal_handler);
	signal(SIGINT,  signal_handler);
	signal(SIGSEGV, signal_handler);
	signal(SIGTERM, signal_handler);

	if (!replace_pat) {
		for (; optind < argc; optind++)
			push_arg(argv[optind], strlen(argv[optind]) + 1);
		initial_args = false;
		initial_argc = cmd_argc;
		initial_argv_chars = cmd_argv_chars;

		while ((*read_args)() != -1)
			if (lines_per_exec && lineno >= lines_per_exec) {
				do_exec();
				lineno = 0;
			}

		/* SYSV xargs seems to do at least one exec, even if the
		   input is empty.  */
		if (cmd_argc != initial_argc
			|| (always_run_command && procs_executed == 0))
			do_exec();
	} else {
		int i;
		size_t len;
		size_t *arglen = xmalloc(sizeof(*arglen) * argc);

		for (i = optind; i < argc; i++)
			arglen[i] = strlen(argv[i]);
		rplen = strlen(replace_pat);
		while ((len = (*read_args)()) != -1) {
			/* Don't do insert on the command name.  */
			push_arg(argv[optind], arglen[optind] + 1);
			len--;
			for (i = optind + 1; i < argc; i++)
				do_insert(argv[i], arglen[i], len);
			do_exec();
		}
	}

	return command_exit_status_255 ? 124 : (command_exit_status_1_to_125 ? 123 : 0);
}


/* Read a line of arguments from stdin and add them to the list of
arguments to pass to the command.  Ignore blank lines and initial blanks.
Double quotes quote metacharacters and blanks.
Return -1 if eof (either physical or logical) is reached,
otherwise the length of the last string read (including the null).  */

static int
read_line(void)
{
	static myboolean eof = false;
	/* Start out in mode SPACE to always strip leading spaces (even with -i).  */
	int state = SPACE;			/* The type of character we last read.  */
	int prevc;					/* The previous value of c.  */
	int quotc = 0;				/* The last quote character read.  */
	int c = EOF;
	myboolean first = true;		/* true if reading first arg on line.  */
	int len;
	char *p = linebuf;
	/* Including the NUL, the args must not grow past this point.  */
	char *endbuf = linebuf + arg_max - initial_argv_chars - 1;

	if (eof)
		return -1;
	while (1) {
		prevc = c;
		c = getc(stdin);
		if (c == EOF) {
			/* COMPAT: SYSV seems to ignore stuff on a line that
			   ends without a \n; we don't.  */
			eof = true;
			if (p == linebuf)
				return -1;
			*p++ = '\0';
			len = p - linebuf;
			/* FIXME we don't check for unterminated quotes here.  */
			if (first && EOF_STR(linebuf))
				return -1;
			if (!replace_pat)
				push_arg(linebuf, len);
			return len;
		}
		switch (state) {
		case SPACE:
			if (ISSPACE(c))
				continue;
			state = NORM;
			/* aaahhhh....  */

		case NORM:
			if (c == '\n') {
				if (!ISBLANK(prevc))
					lineno++;	/* For -l.  */
				if (p == linebuf) {
					/* Blank line.  */
					state = SPACE;
					continue;
				}
				*p++ = '\0';
				len = p - linebuf;
				if (EOF_STR(linebuf)) {
					eof = true;
					return first ? -1 : len;
				}
				if (!replace_pat)
					push_arg(linebuf, len);
				return len;
			}
			if (!replace_pat && ISSPACE(c)) {
				*p++ = '\0';
				len = p - linebuf;
				if (EOF_STR(linebuf)) {
					eof = true;
					return first ? -1 : len;
				}
				push_arg(linebuf, len);
				p = linebuf;
				state = SPACE;
				first = false;
				continue;
			}
			switch (c) {
			// case '\\':
				// state = BACKSLASH;
				// continue;

			//case '\'':
			case '"':
				state = QUOTE;
				quotc = c;
				continue;
			}
			break;

		case QUOTE:
			if (c == '\n')
				error(1, 0, "Unmatched %s quote in input.",
					  quotc == '"' ? "double" : "single");
			if (c == quotc) {
				state = NORM;
				continue;
			}
			break;

		// case BACKSLASH:
			// state = NORM;
			// break;
		}
		if (p >= endbuf)
			error(1, 0, "argument line too long");
		*p++ = c;
	}
}


/* Read a null-terminated string from stdin and add it to the list of
arguments to pass to the command.
Return -1 if eof (either physical or logical) is reached,
otherwise the length of the string read (including the null).  */

static int
read_string(void)
{
	static myboolean eof = false;
	int len;
	char *p = linebuf;
	/* Including the NUL, the args must not grow past this point.  */
	char *endbuf = linebuf + arg_max - initial_argv_chars - 1;

	if (eof)
		return -1;
	while (1) {
		int c = getc(stdin);
		if (c == EOF) {
			eof = true;
			if (p == linebuf)
				return -1;
			*p++ = '\0';
			len = p - linebuf;
			if (!replace_pat)
				push_arg(linebuf, len);
			return len;
		}
		if (c == '\0') {
			lineno++;			/* For -l.  */
			*p++ = '\0';
			len = p - linebuf;
			if (!replace_pat)
				push_arg(linebuf, len);
			return len;
		}
		if (p >= endbuf)
			error(1, 0, "argument line too long");
		*p++ = c;
	}
}


/* Replace all instances of `replace_pat' in ARG with `linebuf',
and add the resulting string to the list of arguments for the command
to execute.
ARGLEN is the length of ARG, not including the null.
LBLEN is the length of `linebuf', not including the null.

 COMPAT: insertions on the SYSV version are limited to 255 chars per line,
 and a max of 5 occurrences of replace_pat in the initial-arguments.
Those restrictions do not exist here.  */

static void
do_insert(char *arg, size_t arglen, size_t lblen)
{
	/* Temporary copy of each arg with the replace pattern replaced by the
	real arg.  */
	static char *insertbuf;
	char *p;
	int bytes_left = arg_max - 1;	/* Bytes left on the command line.  */

	if (!insertbuf)
		insertbuf = xmalloc(arg_max + 1);
	p = insertbuf;

	do {
		size_t len;				/* Length in ARG before `replace_pat'.  */
		char *s = strstr(arg, replace_pat);
		if (s)
			len = s - arg;
		else
			len = arglen;
		bytes_left -= len;
		if (bytes_left <= 0)
			break;

		strncpy(p, arg, len);
		p += len;
		arg += len;

		if (s) {
			bytes_left -= lblen;
			if (bytes_left <= 0)
				break;
			strcpy(p, linebuf);
			arg += rplen;
			p += lblen;
		}
	} while (*arg);
	if (*arg)
		error(1, 0, "command too long");
	*p++ = '\0';
	push_arg(insertbuf, p - insertbuf);
}


/* Add ARG to the end of the list of arguments `cmd_argv' to pass
to the command.
LEN is the length of ARG, including the terminating null.
If this brings the list up to its maximum size, execute the command.  */

static void
push_arg(char *arg, size_t len)
{
	if (arg) {
		if (cmd_argv_chars + len > arg_max) {
			if (initial_args || cmd_argc == initial_argc)
				error(1, 0,
					  "can not fit single argument within argument list size limit");
			if (replace_pat
				|| (exit_if_size_exceeded
					&& (lines_per_exec || args_per_exec)))
				error(1, 0, "argument list too long");
			do_exec();
		}
		if (!initial_args && args_per_exec &&
			cmd_argc - initial_argc == args_per_exec)
			do_exec();
	}

	if (cmd_argc >= cmd_argv_alloc) {
		if (!cmd_argv) {
			cmd_argv_alloc = 64;
			cmd_argv = xmalloc(sizeof(*cmd_argv) * cmd_argv_alloc);
		} else {
			cmd_argv_alloc *= 2;
			cmd_argv = xrealloc(cmd_argv, sizeof(*cmd_argv) * cmd_argv_alloc);
		}
	}

	if (!arg) {
		cmd_argv[cmd_argc++] = NULL;
	} else {
		cmd_argv[cmd_argc++] = argbuf + cmd_argv_chars;
		strcpy(argbuf + cmd_argv_chars, arg);
		cmd_argv_chars += len;
	}
}


/* Execute the command that has been built in `cmd_argv'.  */
static void
do_exec(void)
{
	int rc;
	push_arg((char *) NULL, 0);	/* Null terminate the arg list.  */

	if (cmd_argv == NULL || cmd_argv[0] == NULL || cmd_argv[0][0] == '\0') {
		error(0, 0, "ERROR: command is empty (\"\"?).");
		usage(stderr, 1);
	}

	/* Doublequote arguments with spaces or special characters,
	and execute the resulting command.  */
	rc = subExec(cmd_argc, cmd_argv);

	if (rc >= 1 && rc <= 125) {
		command_exit_status_1_to_125 = true;
	} else if (rc == 255) {
		command_exit_status_255 = true;
	}

	cmd_argc = initial_argc;
	cmd_argv_chars = initial_argv_chars;
}


/* Return the value of the number represented in STR.
OPTION is the command line option to which STR is the argument.
If the value does not fall within the boundaries MIN and MAX,
Print an error message mentioning OPTION and exit.  If MAX is < 0 then no
maximum value check is made.  */
static long
parse_num(char *s, int option, long min, long max)
{
	char *eptr;
	long val;

	val = strtol(s, &eptr, 10);
	if (eptr == s || *eptr) {
		fprintf(stderr, "%s: invalid number for -%c option\n",
				progName, option);
		usage(stderr, 1);
	} else if (val < min) {
		fprintf(stderr, "%s: value for -%c option must be >= %ld\n",
				progName, option, min);
		usage(stderr, 1);
	} else if (max >= 0 && val > max) {
		fprintf(stderr, "%s: value for -%c option must be < %ld\n",
				progName, option, max);
		usage(stderr, 1);
	}
	return val;
}


/* Return how much of ARG_MAX is used by the environment.  */
static long
env_size(char **envp)
{
	long len = 0;

	while (*envp)
		len += strlen(*envp++) + 1;

	return len;
}


static void
usage(FILE *stream, int status)
{
	fprintf(stream,
			"Usage: %s [-0hprtvx] [-e[eof-s]] [-i[replace-s]] [-l[max-lines]]\n"
			" [-n max-args] [-s max-chars] [--null] [--eof[=eof-s]]\n"
			" [--replace[=replace-s]] [--max-lines[=max-lines]]\n"
			" [--max-chars=max-chars] [--verbose] [--exit]\n"
			" [--max-args=max-args] [--no-run-if-empty] [--query] [--version] [--help]\n"
			" [command [initial-arguments]]\n", progName);
	exit(status);
}



// ------------------------[ Begin RonC code ]---------------------------------


// Handle all signals.  On signal, terminate the child process. Then raise
// the original signal.  OpenProcess(), TerminateProcess() & HANDLE are Windows-
// specific.
static void
signal_handler(int signal_value)
{
	signal(signal_value, SIG_IGN);

	if (nPid > 0) {
		// terminate the child
		HANDLE hdl = OpenProcess(PROCESS_TERMINATE, 0, nPid);
		if (hdl) {
			// unconditionally terminate a process after its pending I/O finishes
			TerminateProcess(hdl, EXIT_FAILURE);
			CloseHandle(hdl);
		}
	}

	signal(signal_value, SIG_DFL);
	raise(signal_value);
}


/* Print the command to execute. */
static void
print_args(char **args)
{
	if (args && *args) {
		fprintf(stderr, "%s", *args++);
		while (*args) {
			fprintf(stderr, " %s", *args++);
		}
		fputc('\n', stderr);
		fflush(stderr);
	}
}


/* This code was copied from RonTime.c. */

/* Return a duplicated string.  Enclose it in double quotes if s contains TAB
or SPACE, or if s contains cmd.exe special characters '''\t &|()\"<>[]{}^=;!'+,`~'''
Also, escape '"' characters with backslash.  Returns NULL if malloc()/strdup()
fails.  */
static char *
dblQuoteString(const char *s)
{
	char *result = NULL, *r;
	static char shellSpecialChars[] = "\t &|()\"<>[]{}^=;!'+,`~";
	static size_t sscLen = sizeof(shellSpecialChars) - 1;

	if (s) {
		size_t len = strlen(s);

		if ((strcspn(shellSpecialChars, s) == sscLen) && len) {
			/* no whitespace or special characters and not an empty string */
			result = strdup(s);

		} else {
			/* whitespace or special characters or empty */

			/* 3 for "" and '\0' */
			r = result = malloc(len + StrchrCount(s, '"') + 3);
			if (r) {
				*r++ = '"';
				while (*s) {
					if (*s == '"') {
						*r++ = '\\';
					}
					*r++ = *s++;
				}
				*r++ = '"';
				*r = '\0';
			}
		}
	}

	return result;
}


/* free all of the arguments created by dblQuoteArgs() */
static void
freeQuotedArgs(char **args)
{
	if (args) {
		char **p = args;

		while (*p) {
			free(*p);
			*p++ = NULL;
		}
		free(args);
	}
}


/* Return a pointer to a new argv-like array of string pointers with new strings
double quoted if they contain SPACE, TAB or cmd.exe special characters
\t &|()\"<>[]{}^=;!'+,`~  .  argv's pointers and strings are not changed.
Returns NULL if cannot malloc().  */
static char **
dblQuoteArgs(int argc, const char *const argv[])
{
	char **qArgs = NULL;

	/* *qArgs must be NULL-terminated even if argc == 0 */
	if (argc >= 0) {
		qArgs = malloc(sizeof(*qArgs) * (argc + 1));
		if (qArgs) {
			char **q = qArgs;

			while (*argv) {
				if ((*q++ = dblQuoteString(*argv++)) == NULL) {
					freeQuotedArgs(qArgs);	/* free already-allocated strings */
					return NULL;
				}
			}
			*q = NULL;			/* terminating NULL, like argv */
		}
	}

	return qArgs;
}


/* Execute the command (with its args).  It contains modified code from
RonTime.c  */
static int
subExec(int argc, char **argv)
{
	char *command_name, **quotedArgs;
	int terminationStatus = EXIT_FAILURE;// termination status for child process

	quotedArgs = dblQuoteArgs(argc, argv);

	if (quotedArgs) {
		command_name = argv[0];

		if (query_before_executing || print_command) {
			print_args(quotedArgs);
		}

		if (query_before_executing) {
			static char qbeBuf[100];
			size_t nread;
			
			*qbeBuf = '\0';		/* insurance policy */

			fprintf(stderr, "Execute? Yes/All/No/Quit (y/a/n/q): ");
			fflush(stderr);

			/* do{}while(); is to suppress multiple _cgets_s() returns when
			Enter key is pressed once, and to filter invalid responses */
			do {
				/* Microsoft Visual C 2012 (works from XP to Win8 at least):
				read a string from the console */
				if (_cgets_s(qbeBuf, sizeof(qbeBuf)-1, &nread) != 0) {
					/* If any _cgets_s() arg is bad, program crashes!!!,
					regardless of whether error() or exit(99) is called. */
					error(EXIT_FAILURE, errno, 
							"ERROR: Function _cgets_s() failed.  Reason");
				}
			} while (0 == nread || !strchr("YyAaNnQq", *qbeBuf));

			switch(*qbeBuf) {
			case 'q' :
			case 'Q' :
				freeQuotedArgs(quotedArgs);
				exit(0);
				break;

			case 'n' :
			case 'N' :
				freeQuotedArgs(quotedArgs);
				return 0;
				break;

			case 'a' :
			case 'A' :
				query_before_executing = false;
				break;

			case 'y' :
			case 'Y' :
				/* 'Y' or 'y' entered; proceed */
				break;

			default:
				error(EXIT_FAILURE, 0,
						"Internal error at line %d in file \"%s\".",
						__LINE__, __FILE__);
				/* not reached */
				break;
			}
		}

		/* v in _spawnvp means treat the third argument as an argument array;
		p in _spawnvp means search the path for 'command_name'.

		IMPORTANT: command_name must NOT be quoted; EVERY quotedArgs element,
		including the duplicated command name, MUST be double quoted IF it
		contains whitespace or cmd.exe special characters.  */
		nPid = _spawnvp(_P_NOWAIT, command_name, quotedArgs);
		if (nPid != -1) {
			_cwait(&terminationStatus, nPid, _WAIT_CHILD);
			nPid = 0;	// for signal_handler()

			freeQuotedArgs(quotedArgs);

		} else {
			/* spawnvp() error */
			if (ENOEXEC == errno) {
				/* _spawnvp() error */
				error(126, 0,
					  "ERROR: Cannot start \"%s\". Reason:\n"
					  "Specified file is not executable or has an invalid "
					  "executable-file format.", command_name);

			} else {
				int status = (ENOENT == errno) ? 127 : 126;

				/* spawnvp() error but not ENOEXEC */
				error(status, errno,
					  "ERROR: Cannot execute \"%s\" in path.  Reason",
					  command_name);
			}
		}

		return terminationStatus;

	} else {
		error(1, 0, "ERROR: cannot duplicate arguments: out of memory.");
		// not reached
		return 1;
	}
}

#ifdef __cplusplus
}
#endif
