# include "../lexgen1/ldefs.c"
# define NALTS 6


slide(a0,a1,a2)
{
char *cp;
if (a0>NST) error("%d states", NST);
switch(a1)
	{
	case 0:
		if (xslide[a0]) return(xslide[a0]);
		cp=xslide[a0]=calloc(a2,1);
		while(a2--)
			*cp++ = 0;
		return(xslide[a0]);
	case 1:
		return(xslide[a0]);
	case -1:
		if (xslide[a0])
			cfree(xslide[a0],2,1);
		xslide[a0] = 0;
	}
return(0);
}


addslide(i,j)
{
int *p, *q, leng, *tp, temp[NRULES];
if(i==j) return;
leng = 2*NALTS*sizeof(i);
q= p = slide(i,0,leng);
p++;
if (*q==0) *q = leng/sizeof(i);
while (*p)
	if (*p++ == j)
		return;
leng = *q;
if (p-q >= leng-1)
	{
	leng =* 2;
	tp = temp;
	while (*tp++ = *q++);
	slide(i,-1,0);
	q= p = slide(i, 0, leng*sizeof(p));
	tp=temp;
	while (*p = *tp++) p++;
	*q = leng;
	}
*p = j;
}


addmove(i,c,j)
{
int *p, *q, leng, *tp, temp[NRULES];
int **pp;
leng = NALTS*sizeof(i);
pp = move(i,c,0,leng);
if(*pp == 0)
	{
	*pp = j;
	return;
	}
p = *pp;
if (!ptr(p))
	{
	i = p;
	if(i==j) return;
	*pp = p = calloc(leng,1);
	p [0]= NALTS;
	p[1] = i;
	p[2] = 0;
	}
q=p;
p++;
while (*p)
	if (*p++ == j)
		return;
leng = *q;
if (p-q >= leng-1)
	{
	leng =* 2;
	tp = temp;
	while (*tp++ = *q++);
	cfree(*pp,  leng, 1);
	q = p = *pp = calloc(leng*sizeof(p), 1);
	tp=temp;
	while (*p = *tp++) p++;
	*q = leng;
	}
*p++ = j;
*p = 0;
}


addstop(i,j)
{
int *p, *q, v;
q= p = stops(i,0);
for (; v = *p; p++)
	if (v == j)
		return;
	else if (j > 0 && (v > j || v < 0 ))
		{ *p = j; j= v;}
if (p-q >= NALTS-1)
	error("too many stops state %d",i);
else
	*p = j;
}


stops(a0,a1)
{
char *cp; int a2;
if (a0>NST) error("%d states", NST);
switch(a1)
	{
	case 0:
		if (xstop[a0]) return(xstop[a0]);
		cp=xstop[a0]=calloc(a2=NALTS*sizeof(a2),1);
		while(a2--)
			*cp++ = 0;
		return(xstop[a0]);
	case 1:
		return(xstop[a0]);
	case -1:
		if (xstop[a0])
			cfree(xstop[a0],10,1);
		xstop[a0] = 0;
	}
return(0);
}


ptr(a)
{
if (a== -1) return (0);
if (a<0) return(1);
if (a<1024) return(0);
return(1);
}


new( ii, sz)
{
char *p;
if (ii>NST) error("new state overflow");
if (xnew[ii] != 0) return(xnew[ii]);
xnew[ii] = p = calloc(sz, 1);
while (sz--)
	*p++ = 0;
return(xnew[ii]);
}
