/**********************************************************************
 
	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	<fcntl.h>
#include	"memory_debug.h"
#include	"utils.h"


L_CHAR * script_path;

L_CHAR *
get_script(L_CHAR * script)
{
L_CHAR * buf;
int len1,len2,len3;
STREAM * st;
char * path;

	len2 = l_strlen(script);

	/* if script exist? */

	st = s_open_file(n_string(std_cm,script),O_RDONLY);
	if ( st ) {
		s_close(st);
		return ll_copy_str(script,123);
	}

	if ( script[0] == '/' )
		return 0;

	/* if script_path exist? */

	if ( script_path ) {
		len1 = l_strlen(script_path);
		buf = d_alloc((len1+len2+1)*sizeof(L_CHAR),123);
		memcpy(buf,script_path,len1*sizeof(L_CHAR));
		memcpy(&buf[len1],script,len2*sizeof(L_CHAR));
		buf[len1+len2] = 0;
		st = s_open_file(n_string(std_cm,buf),O_RDONLY);
		if ( st ) {
			s_close(st);
			return buf;
		}
	}

	/* if xlpath exist? */


	path = xlwhich(n_string(std_cm,script));
	if ( path == 0 )
		return 0;
	buf = nl_copy_str(std_cm,path);
	len3 = l_strlen(buf);
	buf = d_re_alloc(buf,(len3+len2+1)*sizeof(L_CHAR));
	l_strcpy(&buf[len3],script);
	d_f_ree(path);
	return buf;
}

void
set_script_path(L_CHAR * script)
{
L_CHAR * path;
int len;
int i;
	path = ll_copy_str(script,1234);
	len = l_strlen(path);
	for ( i = len-1 ; i >= 0 ; i -- ) {
		if ( path[i] == '/' )
			break;
	}
	if ( script_path )
		d_f_ree(script_path);
	if ( i == -1 ) {
		script_path = nl_copy_str(std_cm,"./");
		d_f_ree(path);
	}
	else {
		path[i+1] = 0;
		script_path = path;
	}
}
