/* spawnvp, spawnlp: try to execute a program on the default system
   execution path. WARNING: the current directory is always searched
   first.

   Written by Eric R. Smith and placed in the public domain.
*/
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <stdarg.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

__EXTERN char *	findfile __PROTO((char *, char *, char **));

extern int _x_Bit_set_in_stat; /* in stat.c */

static char *extensions[] = { "ttp", "prg", "tos", NULL };

int
spawnvp(mode, name, argv)
	int mode;
	char *name;
	char **argv;
{
	char *execname;

	execname = findfile(name, getenv("PATH"), extensions);
	if (!execname) {
		errno = ENOENT;
		return -1;		/* file not found */
	}

	/* check to make sure that the file is executable. alas, this is not
	   foolproof, since .g and .sh files are marked as executable even though
	   they're not, really.
	 */
	if(mode < 0)
	{
	    int savex = _x_Bit_set_in_stat;

	    mode = (-mode);
	    _x_Bit_set_in_stat = 1;
	    if (access(execname, X_OK)) {
	        _x_Bit_set_in_stat = savex;
		errno = ENOENT;
		return -1;
	    }
	    _x_Bit_set_in_stat = savex;
	}

	return spawnve(mode, execname, argv, (char **)NULL);
}

#ifdef __STDC__
int spawnlp(int mode, char *name, ...)
#else
int spawnlp(mode, name)
	int	mode;
	char	*name;
#endif
{
	va_list args;

	va_start(args, name);
	return spawnvp(mode, name, (char **)args);
}
