#include "cl.h"

// #pragma inline

static int access( char *file ) {
	FILE *fp = fopen( file, "rb" );

	if ( fp == NULL )
		return 0;
	fclose(fp);
	return 1;
}

static int found( char *buf, char *name ) {
	int len = strlen( buf );

	if ( len && buf[ len ] != '\\' ) {
		buf[ len++ ] = '\\';
		buf[ len ] = 0;
	}

	if (  access( strcat( buf, name ) )  )
		return 1;

	len = strlen( buf );

	if ( len && buf[len] != '.' ) {

		if (  access( strcat( buf, ".COM" ) )  )
			return 1;

		buf[len] = 0;

		if (  access( strcat( buf, ".EXE" ) )  )
			return 1;

		buf[len] = 0;

		if (  access( strcat( buf, ".BAT" ) )  )
			return 1;
	}
	return 0;
}


static void searchenv( char *name, char *env_var, char *buf ) {
	char *path = getenv( env_var );
	char *beg, *p = path;

	*buf = 0;

	if ( found( buf, name ) )
		return;

	for(;p; path = p+1 ) {

		p = strchr( path, ';' );

		if ( p == NULL )
			strcpy( buf, path );
		else {
			memcpy( buf, path, p - path );
			buf[ p - path ] = 0;
		}

		if ( found( buf, name ) )
			return;
	}

	*buf = 0;
}

char run_path[ STR_MAX ];

extern char *search( char *name ) {
	static char fpath[ STR_MAX ];

	fpath[0] = 0;
	if ( found( fpath, name ) )
		return fpath;

	strcpy( fpath, run_path );
	if ( found( fpath, name ) )
		return fpath;

	searchenv( name, "PATH", fpath );
	return fpath[0] ? fpath : name;
}
