/* cmdexists checks to see if a command exists and is executable.  This
   avoids the system crash that Execute(cmd,0,0) can cause when the command
   doesn't exist.
*/
#include <libraries/dosextens.h>

int cmdexists(char *cmd)
{
    struct CommandLineInterface *cli;
    struct Process *p;
    struct FileLock *oldlock;
    long s, l, *lp;
    char buf[256];

    p = (struct Process *)FindTask(0);
    if (!(cli = (struct CommandLineInterface *)((long)p->pr_CLI << 2)))
	return(0);

    if (s = LoadSeg(cmd)) {
	UnLoadSeg(s);
	return(1);
    }
    l = (long) cli->cli_CommandDir;
    while (l) {
	l <<= 2;
	lp = (long *)l;
	oldlock = (struct FileLock *)CurrentDir((struct FileLock *)*(lp + 1));
	s = LoadSeg(cmd);
	CurrentDir(oldlock);
	if (s) {
	    UnLoadSeg(s);
	    return(1);
	}
	l = *lp;
    }
    strcpy(buf, "c:");
    strcat(buf, cmd);
    if (s = LoadSeg(buf)) {
	UnLoadSeg(s);
	return(1);
    }    
    return(0);
}
