/*
 *                   XSPAWN
 *                Version 1.33
 *  (C) Copyright 1990 Whitney Software, Inc.
 *             All Rights Reserved
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include "xspawnp.h"

int xspawnvpe( modeflag, path, argv, envp )
int modeflag;                    /* execution mode for parent process */
char *path;                      /* file to be executed */
char *argv[];                    /* array of pointers to arguments */
char *envp[];                    /* array of pointers to environment strings */
{
    register char *e;
    register char *p;
    char buf[ 80 ];
    int rc;

    if (( rc = xspawnve( modeflag, path, argv, envp )) != -1 ||
        errno != ENOENT || *path == '\\' || *path == '/' ||
        *path && *( path + 1 ) == ':' || ( e = getenv( "PATH" )) == NULL )
    {
        return( rc );
    }

    for ( ;; e++ )
    {
        if (( p = strchr( e, ';' )) != NULL )
        {
            if ( p - e > 66 )
            {
                e = p;
                continue;
            }
        }
        else if ( strlen( e ) > 66 )
            return( -1 );
        p = buf;
        while ( *e && *e != ';' )
            *p++ = *e++;
        if ( p > buf )
        {
            if ( *( p - 1 ) != '\\' && *( p - 1 ) != '/' )
                *p++ = '\\';
            strcpy( p, path );

            if (( rc = xspawnve( modeflag, buf, argv, envp )) != -1 ||
                errno != ENOENT )
            {
                return( rc );
            }
        }
        if ( *e == '\0' )
            return( -1 );
    }
}
