/**********************************************************************
 
	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.

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



#ifdef VA2
#include	<varargs.h>
#else
#include	<stdarg.h>
#endif
#include	"xl.h"
#include	"memory_debug.h"


typedef struct ge_by_sym {
	struct ge_by_sym * next;
	L_CHAR * 	attr;
	L_CHAR *	data;
} GE_BY_SYM;

XL_SEXP *
get_el(XL_SEXP * s,int pos)
{
	for ( ; ; ) {
		if ( get_type(s) == XLT_PAIR ) {
			if ( pos == 0 )
				return car(s);
			s = cdr(s);
			pos --;
			continue;
		}
		else {
			return 0;
		}
	}
}

XL_SEXP *
v_get_el_by_symbol(
	XL_SEXP * s,
	L_CHAR * sym,
	GE_BY_SYM * cond)
{
XL_SEXP * el,* tag;
XL_SYM_FIELD * sf;
L_CHAR * data;
GE_BY_SYM * c;
	for ( ; get_type(s) == XLT_PAIR ; s = cdr(s) ) {
		el = car(s);
		if ( get_type(el) != XLT_PAIR )
			continue;
		tag = car(el);
		if ( get_type(tag) != XLT_SYMBOL )
			continue;
		if ( l_strcmp(tag->symbol.data,sym) )
			continue;
		sf = tag->symbol.field;
		for ( c = cond ; c ; c = c->next ) {
			data = get_sf_attribute(sf,c->attr);
			if ( data == 0 )
				goto not_hit;
			if ( l_strcmp(data,c->data) )
				goto not_hit;
		}
		return el;
	not_hit:
		{}
	}
	return 0;
}

XL_SEXP *
get_el_by_symbol(
	XL_SEXP * s,
	L_CHAR * sym,
	...)
{
GE_BY_SYM * cond, * c;
va_list p;
L_CHAR * attr, * data;
XL_SEXP * ret;

#ifdef VA2
	va_start(p);
#else
	va_start(p,sym);
#endif
	cond = 0;
	for ( ; ; ) {
		attr = va_arg(p,L_CHAR *);
		if ( attr == 0 )
			break;
		data = va_arg(p,L_CHAR *);
		c = d_alloc(sizeof(*c));
		c->attr = attr;
		c->data = data;
		c->next = cond;
		cond = c;
	}
	va_end(p);
	ret = v_get_el_by_symbol(s,sym,cond);
	for ( ; cond ; ) {
		c = cond->next;
		d_f_ree(cond);
		cond = c;
	}
	return ret;
}
