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

XL_SEXP * xl_Launch();


void
init_Launch(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"Launch"),
		get_func_prim(xl_Launch,FO_APPLICATIVE,0,2,2));
}

XL_SEXP *
xl_Launch(XLISP_ENV * env,XL_SEXP * s)
{
XL_SEXP * arg;
XL_SEXP * iid;
int _iid;
XL_INTERPRETER * xli;
STREAM * _st[2];
char cf[2];
char * _arg;
char ** argv;
char * str;
char * ptr, * p;
int cnt,i;
int pid;
	arg = get_el(s,1);
	iid = get_el(s,2);
	switch ( get_type(arg) ) {
	case XLT_ERROR:
		return arg;
	case XLT_STRING:
		_arg = copy_str(n_string(std_cm,arg->string.data));
		break;
	default:
		goto type_missmatch;
	}
	switch ( get_type(iid) ) {
	case XLT_ERROR:
		return iid;
	case XLT_INTEGER:
		_iid = iid->integer.data;
		if ( _iid >= 0 ) {
			xli = search_xli_id(_iid);
			if ( xli == 0 )
				goto param_error;
			if ( xli->a_type != XLA_CONNECT )
				goto param_error;
			_st[0] = xli->inp;
			_st[1] = 0;
		}
		else {
			_st[0] = 0;
		}
		break;
	case XLT_NULL:
		_iid = -1;
		_st[0] = 0;
		break;
	case XLT_FLOAT:
		_iid = iid->floating.data;
		break;
	default:
		goto type_missmatch;
	}
	for ( ptr = _arg ; ; ptr ++ ) {
		switch ( *ptr ) {
		case ' ':
		case '\t':
			*ptr = 0;
			continue;
		case 0:
			break;
		default:
			continue;
		}
		break;
	}
	cnt = 0;
	for ( p = _arg ; p != ptr && *p == 0 ; p ++ );
	if ( p == ptr )
		goto param_error;
	cnt ++;
	str = p;
	for ( ; ; ) {
		for ( ; *p ; p ++ );
		for ( ; p != ptr && *p == 0 ; p ++ );
		if ( p == ptr )
			break;
		cnt ++;
	}
	argv = d_alloc(sizeof(char*)*cnt,161);
	p = str;
	i = 0;
	for ( ; ; ) {
		argv[i++] = p;
		for ( ; *p ; p ++ );
		for ( ; p != ptr && *p == 0 ; p ++ );
		if ( p == ptr )
			break;
	}
	argv[i] = 0;
	cf[0] = 1;
	cf[1] = 0;
	pid = launch_proc(str,argv,_st,cf,0,0);
	d_f_ree(argv);
	if ( pid < 0 )
		return get_error(
			s->h.file,
			s->h.line,
			XLE_PROTO_LAUNCH,
			l_string(std_cm,"Launch"),
			n_get_string("cannot launch"));
	return get_integer(pid,0);
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"Launch"),
		n_get_string("type missmatch"));
param_error:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_INV_PARAM,
		l_string(std_cm,"Launch"),
		n_get_string("parameter error"));
}



