#include <stdio.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
    
extern char *getenv();    
extern char *malloc();
static char *path;
static char **pathVec;
static int pathVecSize;

/* Initialize stuff for PathLookup. */
PathInit ()
{
    int     i = 0;
    char   *p;

    p = getenv ("PATH");
    if (p == NULL)
	return;
    path = malloc ((u_int) strlen (p) + 1);
    strcpy (path, p);
    pathVecSize = 30;
    pathVec = (char **) malloc ((u_int) (pathVecSize * sizeof (char *)));
    /* p == path below handles null PATH as meaning current dir. */
    for (p = path; p != NULL && (p == path || *p != 0);) {
	if (i >= pathVecSize) {
	    pathVecSize *= 2;
	    pathVec = (char **) realloc ((char *) pathVec, (u_int) (pathVecSize * sizeof (char *)));
	}
	pathVec[i++] = p;
	p = index (p, ':');
	if (p != NULL && *p == ':')
	    *p++ = 0;
    }
    pathVec[i++] = NULL;
}

/* Lookup a command in the PATH. */
char *PathLookup (cmd)
    char *cmd;
{
    int     i;
    static char buf[MAXPATHLEN];
    struct stat s;

    if (cmd == NULL)
	return NULL;
    if (*cmd == '/')
	return cmd;
    for (i = 0; pathVec[i] != NULL; ++i) {
	strcpy (buf, pathVec[i]);
	strcat (buf, "/");
	strcat (buf, cmd);
	/* If it exists, is a normal file, and is executable, go for it. 
	 */
	if (stat (buf, &s) >= 0 && (s.st_mode & S_IFMT) == S_IFREG
		&& s.st_mode & 0111)
	    return buf;
    }
    return NULL;
}
