
/*
 * RUN.C
 *
 * (c)1986 Matthew Dillon     9 October 1986
 *
 *    RUN   handles running of external commands.
 *
 * Version 2.07M by Steve Drew 10-Sep-87
 *
 * Version 4.01A by Carlo Borreo & Cesare Dieni 17-Feb-90
 *
 */

char *FindIt();

do_run(str)
char *str;
{
int retcode;
char buf[200]; /* enough space for 100 char cmd name + path stuff */
char *path, *argline, *trueargline, *copy, *p = av[0];

while(*p++) *p &= 0x7F;      /* allow "com mand" */

argline=compile_av(av, 1, ac, ' ', 1);
trueargline= (*argline ? argline : "\n");

if (strlen(av[0]) > 100) { ierror(NULL,509); return -1; }

sprintf(buf,"res_%s",BaseName(av[0]));
if (Getenv(buf, buf+100, 90L) && loadres(av[0])) Setenv(buf,NULL);
retcode=SyncRun(av[0],trueargline,0L,0L);
if (retcode>=0) { free(argline); return retcode; }
if (path = FindIt(av[0],"",buf)) {
	retcode = SyncRun(path,trueargline,0L,0L);
	free(argline);
	return retcode;
	}
else free(argline);
if ((path = FindIt(av[0],".sh",buf)) == NULL) {
	fprintf(stderr,"Command Not Found %s\n",av[0]);
	return -1;
	}
av[1] = buf;
copy = malloc(strlen(str)+3);
sprintf(copy,"x %s",str);
retcode = do_source(copy);
free(copy);
return retcode;
}

char *dofind(cmd, ext, buf)
char *cmd, *ext, *buf;
{
char *ptr, *s;

sprintf(buf,"%s%s",cmd,ext);
if (exists(buf)) return buf;
if (BaseName(buf)==buf) {
	s = get_var(LEVEL_SET, v_path);
	while (*s) {
		for (ptr=buf; *s && *s!=','; ) *ptr++ = *s++;
		sprintf(ptr, "%s%s", cmd, ext);
		if (exists(buf)) return buf;
		if (*s) s++;
		}
	}
return NULL;
}

char *FindIt(cmd,ext,buf)
char *cmd, *ext, *buf;
{
char *response;

Myprocess->pr_WindowPtr = (APTR)(-1);
response=dofind(cmd,ext,buf);
Myprocess->pr_WindowPtr = NULL;
return response;
}
