#include <azprolog.h>
#include <string.h>

extern pred P4_subatom();
extern pred P3_strtok();

initiate_subatom(){
	put_bltn("subatom",4,P4_subatom);
	put_bltn("strtok",3,P3_strtok);
}

pred P4_subatom(Env)
register Frame *Env;
{
	char atom[255];
	int	begin, len;

	Atom2Asciz(GetAtom(next_var_cell-4)	,atom);
	begin = GetInt(next_var_cell-3);
	len   = GetInt(next_var_cell-2);
	if (strlen(atom) < begin+len)
		YIELD(FAIL);		
	atom[begin+len] = 0;
	YIELD(UnifyAtom(next_var_cell-1, Asciz2Atom(Env, &atom[begin])));
}

pred	P3_strtok(Env)
Frame	*Env;
{
	BASECHAR	string1[256];
	BASECHAR	string2[256];
	BASECHAR	*token;
	TERM		*Arg, *wArg1, *wCar, *wCdr;
	
	Atom2Asciz(GetAtom(next_var_cell-3), string1);
	Atom2Asciz(GetAtom(next_var_cell-2), string2);
	Arg = next_var_cell - 1;
	MakeUndef(Env);
	wArg1 = next_var_cell - 1;
	if (!UnifyAtom(wArg1, ATOM_NIL))
		YIELD(FAIL);
	token = strtok(string1, string2);
	while (token != NULL)
	{
		MakeUndef(Env);
		MakeUndef(Env);
		wCar = next_var_cell - 2;
		wCdr = next_var_cell - 1;
		if (!UnifyAtom(wCar, PutAtom(Env, token)))
			YIELD(FAIL);
		if (!UnifyCons(Env, Arg, wCar, wCdr))
			YIELD(FAIL);
		Arg = wCdr;
		token = strtok(NULL, string2);
	}
	YIELD(Unify(Arg, wArg1));
}

/*
  HOW To Use

| ?-subatom(abcdefg,3,4,X).
X	= defg
yes
| ?-subatom(abcdefg,3,6,L).
no
| ?-subatom(abcdefg,7,3,L).
no
| ?-subatom(abcdefg,2,3,L).
L	= cde
yes

| ?-strtok('a,b,c,d',',',L).
L   = [a,b,c,d]
yes
| ?-strtok('a;b;c;d',';',L).
L   = [a,b,c,d]

*/

