/*
** Ulric Eriksson <ulric@siag.nu>
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>

#include <sdb.h>
#include <siod.h>

static LISP lsdb_init(void)
{
	sdb_init();
	return NIL;
}

static LISP lsdb_open(LISP url)
{
	char *p = sdb_open(get_c_string(url));
	if (p) return strcons(strlen(p), p);
	else return NIL;
}

static LISP lsdb_close(LISP id)
{
	sdb_close(get_c_string(id));
	return NIL;
}

static int my_cb(int n, char **p, void *closure)
{
	LISP mylist = NIL;
	LISP real_cb = (LISP)closure;
	LISP result;
	int i;

	for (i = n-1; i >= 0; i--) {
		if (p[i]) {
			mylist = cons(strcons(strlen(p[i]), p[i]), mylist);
		} else {
			mylist = cons(NIL, mylist);
		}
	}
	result = lapply(car(real_cb),
			cons(flocons(n),
			     cons(mylist,
				  cons(cdr(real_cb), NIL))));
	return get_c_long(result);
}

static LISP lsdb_query(LISP url, LISP query, LISP callback, LISP closure)
{
	int n = sdb_query(get_c_string(url),
			  get_c_string(query),
			  my_cb,
			  cons(callback, closure));
	return flocons(n);
}

void init_sdb(void)
{
	init_subr_0("sdb_init", lsdb_init);
	init_subr_1("sdb_open", lsdb_open);
	init_subr_1("sdb_close", lsdb_close);
	init_subr_4("sdb_query", lsdb_query);
}

