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

extern void gc_gb_sexp();
XL_SEXP * xl_svg_path();

void
init_svg_path(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"path"),
		get_func_prim(xl_svg_path,FO_APPLICATIVE,0,1,1));
}

char *
get_svg_token(char ** ptr)
{
char * p;
char * ret;
	for ( p = *ptr ; *p && (
		*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n');
		p ++ );
	if ( *p == 0 ) {
		ret = 0;
		goto end;
	}
	ret = p;
	for ( ; *p && *p != ' ' && *p != '\t' && *p != '\r' && *p != '\n';
		p ++);
	if ( *p == 0 )
		goto end;
	*p = 0;
	p ++;
	goto end;
end:
	*ptr = p;
	return ret;
}

XL_SEXP *
xl_svg_path(XLISP_ENV * env,XL_SEXP * s,
	XLISP_ENV * a,XL_SYM_FIELD * sf)
{
L_CHAR * data;
char * dt;
char * tk,tk1,tk2;
NAME_PTR ptr;
NM_VERTEX * prev_v,* v;
int type;

printf("path %i\r",s->h.line);
	data = 0;
	for ( ; sf ; sf = sf->next ) {
		if ( l_strcmp(sf->name,l_string(std_cm,"d")) == 0 ) {
			data = sf->data;
		}
	}
	if ( data == 0 ) {
		return get_error(
			s->h.file,
			s->h.line,
			XLE_PROTO_INV_PARAM,
			l_string(std_cm,"svg:path"),
			n_get_string("attr:d is required"));
	}
	if ( backup_fid >= 0 ) {
		type = BT_EDGE;
		write(backup_fid,&type,sizeof(type));
	}
	dt = n_string(std_cm,data);
	prev_v = 0;
	for ( ; *dt ; ) {
		tk = get_svg_token(&dt);
		if ( tk == 0 )
			break;
		if ( strcmp(tk,"M") == 0 ) {
			tk = get_svg_token(&dt);
			sscanf(tk,"%lf",&ptr.x);
			tk = get_svg_token(&dt);
			sscanf(tk,"%lf",&ptr.y);
			prev_v = new_vertex(&net_target[loading_target-1],
				&ptr,sizeof(ptr));
		}
		else if ( strcmp(tk,"L") == 0 ) {
			if ( prev_v == 0 ) {
				return get_error(
					s->h.file,
					s->h.line,
					XLE_PROTO_INV_PARAM,
					l_string(std_cm,"svg:path"),
					n_get_string("L command error"));
			}
			tk = get_svg_token(&dt);
			sscanf(tk,"%lf",&ptr.x);
			tk = get_svg_token(&dt);
			sscanf(tk,"%lf",&ptr.y);
			v = new_vertex(&net_target[loading_target-1],
				&ptr,sizeof(ptr));
			new_edge(&net_target[loading_target-1],prev_v,v);
			prev_v = v;
		}
		else {
			return get_error(
				s->h.file,
				s->h.line,
				XLE_PROTO_INV_PARAM,
				l_string(std_cm,"svg:path"),
				n_get_string("unsupport attr:d command"));
		}
		if ( backup_fid >= 0 ) {
			type = BT_VERTEX;
			write(backup_fid,&type,sizeof(type));
			write(backup_fid,&ptr,sizeof(ptr));
		}
	}
	return 0;
}


