/*
 * web.c: 
 *
 * Calls for creating and manipulating an arbitrary web of nodes. 
 *
 * SMF 7-15-89 
 *
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <netinet/in.h>
#include <stdio.h>

#include "pdb.h"
#include "web.h"
#include "sweb.h"
#include "network.h"

char	WEB_BIN_FILE[] = "pips.web.b";

static NODE    *root_node = 0;
static NODE    *firstnode = 0;
static NODE    *lastnode = 0; 

static char empty_node_str[] =
"-1:8:<date>:<topic>:<title>,nid=######:<source>:<locker>:/dev/null::";

static int      web_debuglev;

#define	dbprintf(fmt)		if (web_debuglev) printf(fmt), flush()
#define	dbprintf1(fmt, a1)	if (web_debuglev) printf(fmt, a1), flush()
#define	dbprintf2(fmt, a1, a2)	if (web_debuglev) printf(fmt, a1, a2), flush()
#define	dbputs(str)		if (web_debuglev) puts(str), flush()

#define	ForParentPtrs(n, parent, i)	for (parent	= n_parent_ptrs(n), i=0; i < n_numparent(n); i++, parent++)
#define	ForParentIds(n, parent_id, i)	for (parent_id	= n_parent_ids(n),  i=0; i < n_numparent(n); i++, parent_id++)
#define	ForChildPtrs(n, child, i)	for (child	= n_child_ptrs(n),  i=0; i < n_numchild(n);   i++, child++)
#define	ForChildIds(n, child_id, i)	for (child_id	= n_child_ids(n),   i=0; i < n_numchild(n);   i++, child_id++)

int	CLIENT;
int	FilesLocal;	 /* We can get files ourselves, (via NFS, etc) */

/*
 * linknode:  and add the node to the head of the linked list of nodes.
 * (Calling this more than once on a single node will put loop(s)
 * in the linked list...)
 */

NODE *
linknode(NODE *n)
{
	if (n) { 
		n->nd_next = firstnode;
		firstnode = n;
	}
	return n;
}

/*
 * Allocate all the space needed for a node. (Fixed + variable length data)
 */

static NODE *
allocnode(int datalen, int numparent, int numchild)
{
	NODE	*n;
	int	nlen;

	nlen = sizeof(NODE) + datalen + (numparent + numchild) * sizeof(long);
	n = (NODE *) domalloc(nlen);

	n->nd_datalen = datalen;
	n->nd_numchild = numchild;
	n->nd_numparent = numparent;
	setflag(n, N_FREEABLE);

	return linknode(n);
}

static void
freenode(NODE *n)
{
	if (flagset(n, N_FREEABLE))
		free(n);

}

/*
 * Return pointer to start of next field (after it's starting colon) 
 * Replaces the : with '\0'
 */

static char    *
next_field(ptr)
	char          **ptr;
{
	register char  *cp = *ptr;

	while (*cp && *cp != DLM)
		cp++;
	*cp = '\0';
	return *ptr = ++cp;
}

NODE          *
web_rep_whole_node(char *nodestr,long nid)
/* completely replace a node, links and all */

{
int x,i;
NODE *oldnode,*prevnode,*nxtnode,*newnode;
NODE **parent,**child;

oldnode = web_node(nid);
newnode = web_make_new_node(nodestr);
resolve_links(n_parent_ids(newnode),n_numparent(newnode));
resolve_links(n_child_ids(newnode),n_numchild(newnode));
setflag(newnode, N_RESOLVED_UP|N_RESOLVED_DN);
printf("newnode = %ld\n",n_id(newnode));

prevnode = n_prev(oldnode); /* fix linked list.  */
nxtnode = n_next(oldnode);
if (prevnode)
  prevnode->nd_next = nxtnode;
/* newnode already linked in */

ForChildPtrs(oldnode,child,i)    /* fix the parent links of all children */
  if (TRUE) {      
    ForParentPtrs(*child,parent,x)
      if (TRUE){
	printf("parents of children = %ld\n",n_id(*parent));
	if (*parent == oldnode)  /* we found it */
	/*  n_parent_ptr(*child,x) = newnode; */
	*parent = newnode; 
      }

} /* end of for children */

ForParentPtrs(oldnode,parent,i) /* fix the child links of all parents */
  if (TRUE) {
    ForChildPtrs(*parent,child,x)
      if (TRUE) {

	if (*child == oldnode) /* we found it */
	  *child = newnode; 
	  /* n_child_ptr(*parent,x) = newnode; */
      } 
} /* end of for parents */

freenode(oldnode);       
return newnode;
}

/*
 * Replace all non-link data for the given node-line. To do this, we
 * have to trash the node and re-create it. what about the linked list?
 */

NODE           *
web_rep_node(line)
	char           *line;
{
	NODE           *n;
	char *linkstr,*basestr,*newline;
	int len;

/* need to test somewhere for that the right number of fields were sent */

	n = web_node(atol(line));
	linkstr = web_get_link_str(n);
	len = strlen(linkstr) + strlen(line) + 2;
	newline = (char *) malloc(len);
	sprintf(newline,"%s:%s",line,linkstr);
	printf("newstr = %s\n",newline);

	n =  web_rep_whole_node(newline,atol(line));


	return n;
}


/*
 * This takes a links string, and sets the link *ID's* up. That is, the links
 * are just node-id references, and have not been resolved to actual pointers
 * yet.  This will not allow a child to be repeated.
 */

void
make_link_block(char links[], int numlink, long *nid_block)
{
	char	*cp;
	int	i, x, repeat;
	long	nid;

	cp = links;
	for (i = 0; i < numlink; i++) {
		nid = atol(cp);
		for (repeat = 0, x = 0; x < i; x++)	/* no repeats */
			if (nid_block[i] == nid)
				repeat++;
		if (repeat)
			continue;
		nid_block[i] = nid;
		cp = index(cp, ',') + 1;
	}

}

/*
 * Turn links that are just node_ids into real pointers to nodes. 
 */

static void
resolve_links(nid_block, linkcnt)
	long           *nid_block;
	short           linkcnt;
{
	int             i;

	for (i = 0; i < linkcnt; i++)
		((NODE *) nid_block[i]) = web_node(nid_block[i]);
}

/*
 * Take a text line, parse up the node information, creat a new node for it,
 * and return that new node. This is what we call on each line from the web
 * file to create all the nodes. 
 */

NODE    *
web_make_new_node(char *line)
{
	NODE	*n;
	int	id, flags, date, datalen, numparent, numchild;
	char	*topic, *title, *source, *locker, *file, *cp, *links;
	char	*parent_links, *child_links;

	cp = line;
	
	id	= (long) atol(cp);
	flags	= atoi(next_field(&cp));
	date	= (short) atoi(next_field(&cp));

	topic	= next_field(&cp);
	title	= next_field(&cp);
	source	= next_field(&cp);
	locker	= next_field(&cp);
	file	= next_field(&cp);

	parent_links =	next_field(&cp);
	child_links =	next_field(&cp);

	datalen = parent_links - topic;
	numparent = *parent_links ? strcnt(parent_links, ',') + 1 : 0;
	numchild = *child_links ? strcnt(child_links, ',') + 1 : 0;

	n = allocnode(datalen, numparent, numchild);

	n->nd_id = id;
	n->nd_flags = flags;
	if (flagset(n, N_FAKE) && web_debuglev < 3)
		setflag(n, N_ONSTACK);
	n->nd_date = date;

	n->nd_off[0] = (u_char) (title - topic);
	n->nd_off[1] = (u_char) (source - topic);
	n->nd_off[2] = (u_char) (locker - topic);
	n->nd_off[3] = (u_char) (file - topic);

	memcpy(n->nd_end, topic, datalen);

	make_link_block(parent_links, numparent, n_parent_ids(n));
	make_link_block(child_links, numchild, n_child_ids(n));

	return n;
}

/*
 * Add the links listed in linkstr to the parent's list of children. Tests
 * are performed to make sure we dont indicate any link more than once. 
 */

void
web_add_links(parent, child) /* changed to only add one - st */
	NODE           *parent;
	NODE           *child;
{
char *basestr,*linkstr,*newstr,*cp,*childlinks;
NODE *newnode;

/* add parent's child link */

basestr = web_get_base_str(parent);
linkstr = web_get_link_str(parent);
newstr = (char *) malloc(strlen(basestr) + strlen(linkstr) + 20);
if (n_numchild(parent) == 0)
  sprintf(newstr, "%s:%s%ld",basestr,linkstr,n_id(child));
else
  sprintf(newstr, "%s:%s,%ld",basestr,linkstr,n_id(child));
  printf("new parent line = %s\n",newstr);
newnode = web_rep_whole_node(newstr,n_id(parent));

/* add child's parent links */

basestr = web_get_base_str(child);
linkstr = web_get_link_str(child);
newstr = (char *) malloc(strlen(basestr) + strlen(linkstr) + 20);

if (n_numparent(child) == 0)
  sprintf(newstr,"%s:%ld%s",basestr,n_id(newnode),linkstr);
else  {
  cp =  (char *) rindex(linkstr,DLM);
  *cp = '\0'; 
  childlinks = cp++; 
  sprintf(newstr,"%s:%s,%ld:%s",basestr,linkstr,n_id(newnode),childlinks);
 }


  printf("new child line = %s\n",newstr);
newnode = web_rep_whole_node(newstr,n_id(child));
}


/*
 * Completely delete the link between parent and child.  We don't bother to
 * free up the space for the two free pointers, its not worth the effort. 
 */

void
web_del_link(NODE * p_node, NODE * c_node)
{
	NODE           *n;
	NODE **child;
	NODE **parent;

	char           *cp;
	int             i;
	char		nbuf[4096];

	/*
	 * remove child from parent's child list 
	 */


	sprintf(nbuf, "%ld%c%d%c%d%c%s%c%s%c%s%c%s%c%s%c",
		n_id(p_node),			DLM,
		p_node->nd_flags & N_FLAGS_SAVED,	DLM,
		n_date(p_node),			DLM,
		n_topic(p_node),	DLM,
		n_title(p_node),	DLM,
		n_source(p_node),			DLM,
		n_locker(p_node),			DLM,
		n_file(p_node),			DLM);

	cp = nbuf + strlen(nbuf);
	ForParentPtrs(p_node,parent,i)
	  sprintf(cp,"%ld",n_id(*parent),cp += strlen(cp));
	   if (i)
	     cp --;
	*cp = DLM;
	ForChildPtrs(p_node, child, i)
	    if (n_id(*child) != n_id(c_node))
	        sprintf(cp, "%ld,", n_id(*child), cp += strlen(cp));
	if (i)
	  cp--;
	*cp = '\0';

	web_rep_whole_node(nbuf,n_id(p_node));

	/*
	 * remove parent from child's parent list 
	 */

	sprintf(nbuf, "%ld%c%d%c%d%c%s%c%s%c%s%c%s%c%s%c",
		n_id(c_node),			DLM,
		c_node->nd_flags & N_FLAGS_SAVED,	DLM,
		n_date(c_node),			DLM,
		n_topic(c_node),	DLM,
		n_title(c_node),	DLM,
		n_source(c_node),			DLM,
		n_locker(c_node),			DLM,
		n_file(c_node),			DLM);

	cp = nbuf + strlen(nbuf);

	ForParentPtrs(c_node,parent,i)
	  if (n_id(*parent) != n_id(p_node))
	    sprintf(cp,"%ld",n_id(*parent),cp += strlen(cp));
	  if (i)
	     cp --;
	*cp = DLM;
	 ForChildPtrs(c_node, child, i)
	     sprintf(cp, "%ld,", n_id(*child), cp += strlen(cp));
	if (i)
	  cp--;
	*cp = '\0';
	web_rep_whole_node(nbuf,n_id(p_node));

}


/*
 * Completely vaporize a node 
 */

void
web_del_node(NODE * n)
{
	int             i;

	if (CLIENT && !sweb_del_node(n)) {

		/* server didn't/wouldn't/couldn't do it */

		return;
	}
	/*
	 * remove links from children 
	 */

	for (i = 0; i < n_numchild(n); i++)
		web_del_link(n, n_child_ptr(n, i));

	/*
	 * remove links from parents 
	 */

	for (i = 0; i < n_numparent(n); i++)
		web_del_link(n_parent_ptr(n, i), n);

	if (lastnode == n)
	  lastnode = n_prev(n);
	n_prev(n)->nd_next = n_next(n);	/* Take out of linked list */

	freenode(n);
}


/*
 * Look up the node with the given node-id.  If one doesn't exist, we CREATE
 * IT, thus, this call NEVER FAILS (unless we're out of memory or something
 * to that effect).  We do mark the created nodes as FAKE tho, so we can know
 * that it is if we choose to. 
 *
 * Having this call never fail (and return 0 or something) is a very useful
 * debugging time-saver, things don't crash if they ask for a node with bogus
 * id.  Also, unless debug mode is at it's highest (3 or more), we sneakily
 * mark the nodes as ONSTACK, so that the traverse routines ignore them
 * (thinking there's a traverse call on the stack already that is dealing
 * with that node), and we never see them. 
 */

NODE           *
web_node(nid)
	long            nid;
{
	NODE           *n;
	NODE           *so_it_never_bombs;

	for (n = firstnode; n; n = n_next(n))
		if (n_id(n) == nid)
			return n;

	if (CLIENT && (n = sweb_find_node(nid)))
		return n;
	so_it_never_bombs = web_make_new_node(empty_node_str);
	so_it_never_bombs->nd_id = nid;
	sprintf(index(n_title(so_it_never_bombs), '=') + 1, "%06ld", nid);
	return so_it_never_bombs;
}

static char     _node_buf[NLINE_MAXLEN];

/* get just the node string without any links */
char            *
web_get_base_str(n) 
     NODE          *n;
{
  char *cp,*p;

  cp = web_short_node_str(n);
  p = cp;
  cp = (char *) rindex(cp,DLM);
  cp--;
  *cp = '\0';
  return p;
}

 /* get just the link string of a node */
char            *
web_get_link_str(n)
     NODE      *n;
{
char *cp;
int i;

cp = web_node_str(n);
 /* the # (8) will need to be changed if the node str changes */
for (i = 0; i < 8; i++) {
  cp = (char *) index(cp,DLM);
  if (cp)
    cp++;
}
return cp;
}

/*
 * Give us a node string without the link data, or rather, with empty link
 * data fields. 
 */

char           *
web_short_node_str(n)
	NODE           *n;
{
	sprintf(_node_buf, "%ld:%d:%d:%s:%s:%s:%s:%s::",
		n_id(n),
		n->nd_flags & N_FLAGS_SAVED,
		n_date(n),
		n_topic(n),
		n_title(n),
		n_source(n),
		n_locker(n),
		n_file(n));

	return _node_buf;
}

/*
 * Give the full text one-liner description of a node.  This generates the
 * line that in the pips.web file, etc. 
 */

char           *
web_node_str(n)
	NODE           *n;
{
	char           *cp;
	int             i;
	static char		xnbuf[4096];

	sprintf(xnbuf, "%ld%c%d%c%d%c%s%c%s%c%s%c%s%c%s%c",
		n_id(n),			DLM,
		n->nd_flags & N_FLAGS_SAVED,	DLM,
		n_date(n),			DLM,
		n_topic(n),	DLM,
		n_title(n),	DLM,
		n_source(n),			DLM,
		n_locker(n),			DLM,
		n_file(n),			DLM);

	cp = xnbuf + strlen(xnbuf);

	if (flagset(n, N_RESOLVED_UP)) {
		NODE	**parent;

		ForParentPtrs(n, parent, i)
			sprintf(cp, "%ld,", n_id(*parent)), cp += strlen(cp);
	} else {
		long	*parent_id;

		ForParentIds(n, parent_id, i)
			sprintf(cp, "%ld,", *parent_id), cp += strlen(cp);
	}
	if (i)
		cp--;
	*cp = DLM;
	cp++;
	if (flagset(n, N_RESOLVED_DN)) {
		NODE	**child;

		ForChildPtrs(n, child, i)
			sprintf(cp, "%ld,", n_id(*child)), cp += strlen(cp);
	} else {
		long	*child_id;

		ForChildIds(n, child_id, i)	
			sprintf(cp, "%ld,", *child_id), cp += strlen(cp);
	}
	if (i)
		cp--;
	*cp = '\0';
	return xnbuf;
}


/*
 * Make a node suitable for transport over the internet, or
 * saveable to a file.  (Node must be resolved or this will bomb...)
 */

void
make_net_node(NODE *n)
{
	long	*tn, *endlinks;

	endlinks = n_end(n);
	for (tn = n_linkinfo(n); tn < endlinks; tn++)
		*tn = htonl(n_id(* (NODE **) tn));

	makenl(n->nd_id);
	n->nd_flags &= N_FLAGS_SAVED;
	makens(n->nd_flags);
	makens(n->nd_date);
	makens(n->nd_datalen);
	makens(n->nd_numchild);
	makens(n->nd_numparent);
}

/*
 * Make sure a node is in host byte order.
 */

void
make_host_node(NODE *n)
{
	long	*tn, *endlinks;

	makehl(n->nd_id);
	makehs(n->nd_flags);
	makehs(n->nd_date);
	makehs(n->nd_datalen);
	makehs(n->nd_numchild);
	makehs(n->nd_numparent);

	endlinks = n_end(n);
	for (tn = n_linkinfo(n); tn < endlinks; tn++)
		makehl(*tn);
}

/*
 * Copy a node to the tmp _node_buf, and make sure the bytes are in network
 * order, then return the the tmp network order node.  At this point, since
 * the nodes are interally already set up in the new format, we really could
 * get by with calling make_net_node & n_size instead of this, but this
 * keeps things a bit more changeable.
 */

NODE *
web_binary_node(NODE *sn, u_short *len)
{
	NODE	*n;
	int	i;
	short	dlen;

	n = (NODE *) _node_buf;
	bcopy(sn, n, n_size(sn));

	make_net_node(n);

	*len = n_size(sn);
	return n;
}


/*
 * Find the node previous to the given node in the linked list.  n_prev(n)
 * maps to this 
 */

NODE           *
find_prev_node(findprev)
	NODE           *findprev;
{
	NODE           *n;

	for (n = firstnode; n; n = n_next(n))
		if (n_next(n) == findprev)
			return n;
	return (NODE *) 0;
}

/*
 * Call the given function on ALL the nodes in the linked list, except the
 * FAKE ones (created by web_node call with bogus nid). 
 */

void
web_allnodes(func)
	void            (*func) (NODE * n);
{
	NODE           *n;

	for (n = firstnode; n; n = n_next(n))
		if (!flagset(n, N_FAKE))
			(*func) (n);
}

/*
 * Call the given function on all the nodes who's topic is prefixed with the
 * given string. 
 */

void
web_find_topic(topic, func)
	char           *topic;
	void            (*func) (NODE * n, short);
{

	int             len;
	NODE           *n;

	/* if (CLIENT) {  */

	/*
	 * This is an intensive operation for the server, and ties it up. 
	 * May want to make finds by default only scan what we've got so far,
	 * and make a "full" find another command or something. 
	 */

	sweb_find_topic(topic, func);


	/* } else {  */
	len = strlower(topic);
	for (n = firstnode; n; n = n_next(n))
		if (!strncasecmp(n_topic(n), topic, len))
			(*func) (n, 0);
	/* }  */
}


/*
 * Make sure this parents children are all loaded in.  If the links are
 * unresolved, they must not be, and we've gotta get them from the server. 
 */

static void
ensure_children(NODE * n)
{
	if (flagset(n, N_RESOLVED_DN))
		return;
	if (CLIENT) {
		sweb_get_children(n);
		return;
	}
	resolve_links(n_child_ids(n), n_numchild(n));
	setflag(n, N_RESOLVED_DN);
}

static void
ensure_parents(NODE * n) /* doesnt seem to work */
{
printf("in ensure parents\n");
	if (flagset(n, N_RESOLVED_UP))
		return;
	if (CLIENT)
		sweb_get_parents(n);
	resolve_links(n_parent_ids(n), n_numparent(n));
printf("end ensure parents\n");
	setflag(n, N_RESOLVED_UP);
}

static u_short  trav_maxdepth;
static u_short  trav_repeatok;
static void     (*trav_function) (NODE *, u_short);

/*
 * traverse_up: post-order recursive ascent thru parent links 
 */

static void
traverse_up(n, curdepth)
	NODE           *n;
	u_short         curdepth;
{
	int             i;
	if (flagset(n, N_ONSTACK))
		return;

	setflag(n, N_ONSTACK);
	if (curdepth < trav_maxdepth) {
	/*        if (!SERVER)  */
			ensure_parents(n);
		for (i = 0; i < n_numparent(n); i++)
			traverse_up(n_parent_ptr(n, i), curdepth + 1);
	}
	clrflag(n, N_ONSTACK);

	if (trav_repeatok)
		(*trav_function) (n, curdepth);
	else if (!flagset(n, N_CALLEDON))
		(*trav_function) (n, curdepth), setflag(n, N_CALLEDON);

}

/*
 * traverse_dn: pre-order recursive descent thru child links 
 */

static void
traverse_dn(n, curdepth)
	NODE           *n;
	u_short         curdepth;
{
	int             i;
	NODE		**child;

	if (flagset(n, N_ONSTACK))
		return;

	if (trav_repeatok)
		(*trav_function) (n, curdepth);
	else if (!flagset(n, N_CALLEDON))
		(*trav_function) (n, curdepth), setflag(n, N_CALLEDON);
	else
		return;

	setflag(n, N_ONSTACK);
	if (curdepth < trav_maxdepth) {
	/*	if (!SERVER) */
			ensure_children(n);
		ForChildPtrs(n, child, i)
			traverse_dn(*child, curdepth + 1);
	}
	clrflag(n, N_ONSTACK);
}

void
web_traverse(tflags, startnode, func, maxdepth)
	int             tflags;
	NODE           *startnode;
	void            (*func) (NODE * n, u_short depth);
	u_short         maxdepth;
{
	if (!func)
		return;

	if (!startnode)
		startnode = root_node;

	trav_function = func;
	trav_maxdepth = maxdepth;
	trav_repeatok = !(tflags & TRAV_NOREPEAT);

	if (tflags & TRAV_UP)
		traverse_up(startnode, 0);

	if ((tflags & TRAV_OUT) == TRAV_OUT) {
		int	i;
		NODE	**child;

		if (maxdepth > 0)
			ForChildPtrs(startnode, child, i)
				traverse_dn(*child, 1);

	} else if (tflags & TRAV_DOWN)
		traverse_dn(startnode, 0);


	if (!trav_repeatok) {
		NODE           *n;

		for (n = firstnode; n; n = n_next(n))
			clrflag(n, N_CALLEDON);
	}
}



/*
 * recursive descent search of tree, child (downward) traverse only used for
 * initial web test and accounting 
 */

static int      nodecnt, linkcnt, orphans;

static void
test_traverse(n, diagnostic)
	NODE           *n;
	int             diagnostic;
{
	int             i;

	if (!n) {
		if (diagnostic)
			puts("Traversal to null node...");
		return;
	}
	if (flagset(n, N_ONSTACK))
		return;
	setflag(n, N_ONSTACK);
	nodecnt++;
	linkcnt += n_numchild(n);
/*	if (diagnostic)
		puts(web_node_str(n));
*/	for (i = 0; i < n_numchild(n); i++)
		test_traverse(n_child_ptr(n, i), diagnostic);
	clrflag(n, N_ONSTACK);
}

static void
find_lost_nodes()
{
	/*
	 * NOTE:  Nodes only reachable by passing up from a child are
	 * considerd lost.  test_traverse travels downward only. 
	 */

	NODE           *n;
	int             i;

	for (n = firstnode; n; n = n_next(n)) {
		if (!n_numparent(n) && n != root_node) {
			puts(web_node_str(n));
			orphans++;
			test_traverse(n, TRUE);
		}
	}
}

static NODE    *
find_root()
{
	NODE           *root = 0, *n;
	int             cnt;

	for (cnt = 0, n = firstnode; n; n = n_next(n))
		if (!n_id(n))
			cnt++, root = n;
	if (cnt != 1)
		printf("%d id-zero nodes were found!\n", cnt);

	return root;
}

static int
web_text_load()
{
	NODE	*n;
	FILE	*web_file;
	char	line[NLINE_MAXLEN];
	int	numlines = 0;

	dbprintf1("Loading the web from [%s]...", WEB_FILE), flush();

	if (!(web_file = fopen(WEB_FILE, "r"))) {
		perror(WEB_FILE);
		return 0;
	}

	/*
	 * read in the web file...
	 */

	while (fgets(line, NLINE_MAXLEN, web_file)) {
		if (*line == '#')
			continue;
		numlines++;
		line[strlen(line) - 1] = '\0';
		n = web_make_new_node(line);
	}
	fclose(web_file);

	if (web_debuglev > 1) {
		extern long     _allocated;

		printf("Done -- %d node descriptors were parsed\n", numlines);
		printf("Allocated %.1fK for the web.\n",
		       (float) _allocated / 1024.0),
			printf("Resolving links..."), flush();
	} else if (web_debuglev)
		putchar('.'), flush();

	/*
	 * Now resolve all the links from node id's to pointers. 
	 */

	if (SERVER) {
		for (n = firstnode; n; n = n_next(n)) {
			resolve_links(n_parent_ids(n), n_numparent(n));
			resolve_links(n_child_ids(n), n_numchild(n));
			setflag(n, N_RESOLVED_UP|N_RESOLVED_DN);
		}
	}
	dbprintf("Done\nLooking for the root node...");

	root_node = find_root();

	dbputs("Done");
	return 1;
}

static int	_bfd;
static long	_bytecnt, _nodecnt;

void
binary_dump_aux(n, depth)
NODE	*n;
u_short	depth;
{
	char	*cp;
	u_short	len;

	cp = (char *) web_binary_node(n, &len);
	write(_bfd, cp, len);
	_bytecnt += len;
	_nodecnt++;
}

web_binary_dump()
{
	_bfd = open(WEB_BIN_FILE, O_WRONLY | O_CREAT | O_TRUNC, 0664);
	if (!_bfd) {
		perror(WEB_BIN_FILE);
		return;
	}

	_bytecnt = _nodecnt = 0;

	lseek(_bfd, sizeof(long) * 2, L_SET);

	web_traverse(TRAV_DOWN|TRAV_NOREPEAT, 0, (void *) binary_dump_aux, -1);

	printf("Wrote %ld nodes in %ld bytes (%.1fK)\n",
	       _nodecnt, _bytecnt, (float) _bytecnt / 1024.0);

	lseek(_bfd, 0L, L_SET);
	makenl(_bytecnt), makenl(_nodecnt);
	write(_bfd, &_bytecnt, sizeof(long));
	write(_bfd, &_nodecnt, sizeof(long));
	close(_bfd);

}


/*
 * What we're doing here may not be immediately obvious.  This recursively
 * calls itself while passing over a just loaded binary web area.  It works
 * by knowing (expecting) the we file to have been written out in a
 * pre-order recursive traverse over the web.  First we set the node into
 * the linked list (somewhat redundant as all the nodes are contiguous at
 * first, but if any nodes need to be added...).  Then we make sure the
 * bytes are in host order.  Then we go about setting up the children
 * pointers, knowing the 1st child & it's children (etc) follow immediately.
 */

static NODE	*nextnode;

static NODE *
get_next_resolved_node(long nid, NODE *parent)
{
	static int	justfailed = 0;
	static NODE	*lastparent;

	int	datalen, i;
	char	*cp;
	NODE	*n;
	long	*nid_ptr;

	n = nextnode;
	if (!justfailed)
		make_host_node(n);
	else
		justfailed = NO;

	/*
	 * If the child in the next slot isn't the child with the id we're
	 * expecting, it must have been written out previously as someone
	 * elses child.  This means we need to go back from where we are
	 * and do a manual search to find and resolve the link.
	 */

	if (n_id(n) != nid) {
/*		printf("Was looking for %ld but found %ld.\n", nid, n_id(n)), flush(); */
		justfailed = YES;
		return web_node(nid);
	}

	linknode(n);
	nextnode = n_end(n);
/*
	if (n_numparent(n))
		n_parent_ptr(n, 0) = parent;
	else if (parent)
		printf("Orphan nid: %ld\n", n_id(n));
*/
	ForChildIds(n, nid_ptr, i)
		* (NODE **) nid_ptr = get_next_resolved_node(*nid_ptr, n);

	setflag(n, N_RESOLVED_DN);
	return n;
}

static int
web_binary_load()
{
	struct stat	st;
	NODE		*n;
	char		*web_area;
	long		red, *child_ptr,*parent_ptr;
	int		i;

	_bfd = open(WEB_BIN_FILE, O_RDONLY);
	if (!_bfd) {
		perror(WEB_BIN_FILE);
		return 0;
	}
	fstat(_bfd, &st);
	dbprintf2("Size of web file: %ld bytes (%.1fK)\n",
		st.st_size, (float) st.st_size / 1024.0);
	read(_bfd, &_bytecnt, sizeof(long));
	read(_bfd, &_nodecnt, sizeof(long));
	makehl(_bytecnt), makehl(_nodecnt);
	dbprintf1("There are reportedly %ld nodes in the file.\n", _nodecnt);
	if (_bytecnt + sizeof(long) * 2 != st.st_size) {
		printf("WARNING: ");
		if (!_bytecnt)
			puts("Previous binary save did not complete.");
		else
			printf("Web file says it should be %ld bytes long!\n",
			       _bytecnt + sizeof(long) * 2);
	}
	dbprintf("Malloc...");
	st.st_size -= sizeof(long) * 2;
	web_area = domalloc(st.st_size);
	dbprintf("Done\nWhumping in...");
	red = read(_bfd, web_area, st.st_size);
	if (red != st.st_size) {
		perror("read");
		return 0;
	}
	close(_bfd);
	dbprintf("Done\nResolving binary links...");
	nextnode = (NODE *) web_area;
	root_node = get_next_resolved_node(0L, 0); /* resolves down */

/* resolving up */
	for (n = firstnode; n; n = n_next(n))
		if (!flagset(n, N_FAKE)) {
		  setflag(n,N_RESOLVED_UP);
			ForParentIds(n, child_ptr, i)
				/* if (i > 0) ??? */
					* (NODE **) child_ptr = web_node(*child_ptr); 
		      }

	dbputs("Done");

	/*
	 * This needs to deal with multiple & parent links!
	 */

	return 1;
}

NODE *
web_load(int debuglev)
{
	struct stat	st;
	time_t		text_mtime;
	int             rehash;

	web_debuglev = debuglev;

	FilesLocal = YES;
	if (!SERVER) {
		if (sweb_init()) {
			CLIENT = YES;
			FilesLocal = YES; /* needs to be a parameter? */
			return sweb_find_node(0);
		}
		puts("Couldn't contact server, running standalone.");
		CLIENT = NO;
	}

	stat(WEB_FILE, &st);
	text_mtime = st.st_mtime;
	stat(WEB_BIN_FILE, &st);
	rehash = (text_mtime >= st.st_mtime);

	/*
	 * ensure_access(WEB_FILE, PIPS_LOCKER, debuglev); 
	 */

	if (rehash) {
		if (!web_text_load())
			return 0;
		printf("Binary dump..."), flush();
		web_binary_dump();
		puts("Done"), flush();
	}

	dbprintf("Binary LOAD...");
	if (!web_binary_load())
		return 0; 
	dbputs("Done");

	/*
	 * This debugging stuff cause it crashes without the links
	 * resolved.
	 */

	if (debuglev > 1 && SERVER) {
		orphans = nodecnt = linkcnt = 0;

		printf("PARENTLESS NODES: "), flush();
		find_lost_nodes();
		if (orphans)
			printf("\n%d parentless nodes were found, causing a total of %d unreachable nodes.\n", orphans, nodecnt);
		else
			puts("None.");
		nodecnt = linkcnt = 0;
		printf("Web test: "), flush();
		test_traverse(root_node, FALSE);
		printf("%d nodes were visited over %d links.\n", nodecnt, linkcnt);
		flush();
	}
	return root_node;
}
