/* (C) Copyright International Business Machines Corporation 23 January */
/* 1990.  All Rights Reserved. */
/*  */
/* See the file USERAGREEMENT distributed with this software for full */
/* terms and conditions of use. */
/* SCCS Info: @(#)pathfind.c	1.7 3/21/90 */

#include <sys/types.h>
#include <sys/file.h>
#include <string.h>

#include "li.h"			/* arg... needed so that we don't choke on */
#include "storage.h"		/*  storage.h. */

#define BUFSIZE 255



char *
pathfind(path, file, mode)
char *path;
char *file;
{
    int colon;
    int filelen;
    char *found;
    char buf[BUFSIZE+1];


    filelen = strlen(file);

    while (*path isnt nil) {
	colon = strcspn(path, ":");
	if (colon + filelen + 1 < BUFSIZE) {
	    (void) strncpy(buf, path, colon);
	    buf[colon] = '/';
	    (void) strcpy(buf+colon+1, file);

	    if (access(buf, mode) is 0) { /* found -- return string */
	        found = (char *) getmain((counter) colon+filelen+2);
		if (found is nil)
		  return(nil);
		(void) strcpy(found, buf);
		return(found);
	    }
	}
	
	path = path + colon;	/* advance to next item in path */
	if (*path isnt nil)
	  path++;
    }

    return(nil);
}


#ifdef TESTPATH
static
testmain(argc, argv)
int argc;
char *argv[];
{
    char *pathfind();

    char *file;
    char *path = ".:/local/bin:/etc";
    int i;


    for (i = 1; i < argc; i++) {
	file = pathfind(path, argv[i], R_OK);
	(void) printf("Found %s in %s\n", argv[i], file);
    }
}
#endif
