
# include	"llist.h"

extern char *ll_freelist;

List_p
ll_insert(hp, atom, pos)
Head_p	hp;
char	*atom;
register int	pos;
{	register	List_p	lp;
	register	List_p	lp1;

	LIST_INCR(ll_insert);
	LL_HMAGIC(hp);
	lp = (List_p) vm_alloc(sizeof (List), &ll_freelist);
	LIST_INCR(lp_alloced);
	LIST_INCR(ll_alloc);
	lp->ll_magic = LL_LIST;
	lp->ll_next = lp->ll_prev = NULL;
	lp->ll_elem = atom;

	if (pos == 0 || hp->ll_next == NULL) {
		lp->ll_next = hp->ll_next;
		lp->ll_prev = hp;
		hp->ll_next = lp;
		if (lp->ll_next)
			lp->ll_next->ll_prev = lp;
		return lp;
		}

	for (lp1 = hp->ll_next; pos-- > 0 && lp1->ll_next; )
		lp1 = lp1->ll_next;

	lp->ll_next = lp1->ll_next;
	lp->ll_prev = lp1;

	lp1->ll_next = lp;
	if (lp->ll_next)
		lp->ll_next->ll_prev = lp;

	return lp;
}
