/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program is distributed in the hope that it will be 
	useful, but WITHOUT ANY WARRANTY; without even the 
	implied warranty of MERCHANTABILITY or FITNESS FOR A 
	PARTICULAR PURPOSE.

**********************************************************************/

#include <io.h>
#include <fcntl.h>
#include "utils.h"
#include "memory_debug.h"


char *
xlwhich(char * app)
{
char * path,* p1, * p2, * p3;
int path_len;
char * buf;
int fd;
	path = getenv("XLPATH");
	if ( path == 0 )
		return 0;
	path = copy_str(path);
	buf = d_alloc(strlen(path) + strlen(app) + 10,2);
	buf[0] = 0;
	for ( p1 = path ; p1 ; ) {
		p2 = p1;
		for ( ; *p2 && *p2 != ':' ; p2 ++ );
		switch ( *p2 ) {
		case 0:
			p3 = 0;
			break;
		case ':':
			p3 = p2+1;
			*p2 = 0;
			break;
		}
		strcpy(buf,p1);
		path_len = strlen(buf);
		if ( buf[path_len-1] != '/' ) {
			buf[path_len] = '/';
			path_len ++;
		}
		strcpy(&buf[path_len],app);
		fd = open(buf,O_RDONLY);
		if ( fd < 0 ) {
			p1 = p3;
			continue;
		}
		close(fd);
		buf[path_len] = 0;
		goto end;
	}
	d_f_ree(buf);
	buf = 0;
end:
	d_f_ree(path);
	return buf;
}
