/*
 *------------------------------------------------------------------
 *
 * $Source: /afs/net.mit.edu/dev/project/techinfodev/src/srv_ti/RCS/web.c,v $
 * $Revision: 3.2 $
 * $Date: 93/02/03 11:24:17 $
 * $State: Exp $
 * $Author: thorne $
 * $Locker:  $
 *
 * $Log:	web.c,v $
 * Revision 3.2  93/02/03  11:24:17  thorne
 * new release
 * 
 * Revision 1.7  92/08/28  16:10:09  ark
 * Summer 1992 final version
 * 
 * Revision 1.6  92/08/27  17:11:47  ark
 * Retropatched error message file to allow old clients to work
 * 
 * Revision 1.5  92/08/24  15:47:42  ark
 * WAIS searching added to client & server (J command)
 * 
 * Revision 1.4  92/08/19  16:21:41  ark
 * New 'O' transaction replaces old 'o'
 * 
 * Revision 1.3  92/08/12  14:19:25  ark
 * New version of 'o' transaction tells what output format to use;
 * this is a hack to allow old (but broken) clients to still work.
 * 
 * Revision 1.2  92/08/04  16:28:40  ark
 * Test production version 8/4/92
 * 
 * Revision 1.1  92/07/22  11:09:49  ark
 * Saber loads quietly; ANSI use standardized; command line options; no behavioral changes
 * 
 * Revision 1.0  92/07/10  12:35:02  ark
 * Initial revision
 * 
 * Revision 1.2  91/07/18  09:50:58  thorne
 * fixes small bugs found by upenn etc (incorpoates diffs)
 * 
 * Revision 1.1  91/07/15  10:40:49  thorne
 * Initial revision
 * 
 *------------------------------------------------------------------
 */

#ifndef lint
#ifndef SABER
static char *rcsid_foo_c = "$Header: /afs/net.mit.edu/dev/project/techinfodev/src/srv_ti/RCS/web.c,v 3.2 93/02/03 11:24:17 thorne Exp $";
#endif SABER
#endif  lint
/*
 * web.c: 
 *
 * Calls for creating and manipulating an arbitrary web of nodes. 
 *
 * SMF 7-15-89 
 *
 */
/*
  Copyright (C) 1989 by the Massachusetts Institute of Technology

   Export of this software from the United States of America is assumed
   to require a specific license from the United States Government.
   It is the responsibility of any person or organization contemplating
   export to obtain such a license before exporting.

WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
distribute this software and its documentation for any purpose and
without fee is hereby granted, provided that the above copyright
notice appear in all copies and that both that copyright notice and
this permission notice appear in supporting documentation, and that
the name of M.I.T. not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.  M.I.T. makes no representations about the suitability of
this software for any purpose.  It is provided "as is" without express
or implied warranty.

*/


#include <stdio.h>
#include <strings.h>
#include "pdb.h"
#include "web.h"
#include "network.h"
#include "messages.h"

static NODE *addnode(void);
char *next_field(char **ptr);
static char    *initnode(char *line, NODE *n);
NODE           *web_rep_node(char *line);
static long    *make_link_block(char links[], short *linkcnt);
static void resolve_links(long *nid_block, short linkcnt);
void web_reorder_links(NODE *n, char *linkstr);
static NODE    *make_new_node(char *line);
int web_add_links(NODE *parent, char *linkstr);
void web_del_link(NODE * parent, NODE * child);
void web_del_node(NODE * n);
NODE           *web_node(long nid);
char           *web_short_node_str(NODE *n);
char           *web_short_node_str_old(NODE *n);
char           *web_node_str(NODE *n);
char           *web_node_str_old(NODE *n);
NODE           *find_prev_node(NODE *findprev);
void web_allnodes(void (*func) (NODE *n) );
/* int web_allnodes2(void (*func) (NODE *n) (int x)); */
void web_find_topic(char *topic, void (*func) (NODE *n, u_short x), NODE *node);
static void ensure_children(NODE * n);
static void ensure_parents(NODE * n);
static void traverse_up(NODE *n, u_short curdepth);
static void traverse_dn(NODE *n, u_short curdepth);
void web_traverse(int tflags, NODE *startnode, 
		  void (*func) (NODE *n, u_short depth), u_short maxdepth);
static void test_traverse(NODE *n);
static void find_lost_nodes(int *orphans);

void web_remove_node(NODE *n);
void web_reload(void);
NODE *web_load(void);
char *get_server_name(int server_id);

extern void    nlist_add_srch  (NODE *node, u_short depth);
extern void    ensure_access(char file[], char attach_src[], int detach);
extern unsigned long     _allocated;
extern int     debug;
extern char    *msglist[];

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      Standalone;

/*
 * addnode:  allocate memory for a new node, and add the (uninitialized) node
 * to the linked list of nodes. 
 */

static NODE    *
addnode(void)
{
	NODE           *n = (NODE *) domalloc((unsigned int) sizeof(NODE));
        bzero(n,sizeof(NODE));
	if (!n)
		return (NODE *) 0;
	if (!firstnode)
		firstnode = n;
	else
		lastnode->nd_next = n;
	n->nd_next = 0;
	return lastnode = n;
}


/*
 * Return pointer to start of next field (after its starting colon) 
 */

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

	while (*cp != NULL && *cp != DLM)
		cp++;
	if (*cp == NULL)  /* end of the string */
	    return (*ptr = cp); 

	*cp = '\0';
	return (*ptr = ++cp);
}

/*
 * Initialize all of the non-link info for a node. Every new node created
 * must/will have had this called on it. 
 *   If debug mode is on, this procedure's behavior is different.
 *   See the comment preceding web_node for an explanation. ---ark
 */
static char    *
initnode(char *line, NODE *n)
{
	char           *topic, *title, *source, *locker, *file, *cp, *links;
	int             datalen;
	unsigned long            flags;

	n->nd_id = (long) atol(cp = line);
	/* flags = atol(next_field(&cp));  need to fix this=- ST 2/15/91 */
flags = strtoul(next_field(&cp),NULL,0);
	if (flagset(n, N_FAKE) && !debug)
		setflag(n, N_ONSTACK);
	n->nd_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);

	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);

	links = next_field(&cp);
	datalen = links - topic + 1;
        if (*links == NULL) 
	  datalen++; 
	n->nd_data = domalloc((unsigned int) datalen);
	memcpy(n->nd_data, topic, datalen);
	n->nd_flags =  flags; /****/
	if (flagset(n, N_FAKE) && !debug)
		setflag(n, N_ONSTACK); 
	return links;		/* return links data */
}


/*
 * Replace all non-link data for the given node-line. To do this, we simply
 * re-initialize it. 
 */
NODE           *
web_rep_node(char *line)
{
	NODE           *n;

	n = web_node(atol(line));
	do_free(n->nd_data);	/* give back old string data */
	initnode(line, n);
	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. 
 */
static long    *
make_link_block(char links[], short *linkcnt)
{
	char           *cp;
	int             numlink, i, x, repeat;
	long            nid, *nid_block;

	numlink = *links ? strcnt(links, ',') + 1 : 0;

	nid_block = (long *) domalloc((unsigned int) numlink * sizeof(long));
	cp = links;

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

	*linkcnt = numlink;
	return nid_block;
}

/*
 * Turn links that are just node_ids into real pointers to nodes. 
 */
static void
resolve_links(long *nid_block, short linkcnt)
{
	int             i;

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

/* replace the children links of a node */
void
web_reorder_links(NODE *n, char *linkstr)
{
  short cnt = 0;
  long *blockptr;
  
  blockptr = make_link_block(linkstr,&cnt);
  if (!blockptr)
    printf("null blockptr\n");
  resolve_links(blockptr,cnt);
  memcpy(n->nd_child_ptrs,blockptr, cnt * sizeof(NODE *));
  if (!n->nd_child_ptrs)
    printf("null child link ptrs \n");
  do_free (blockptr);
}


/*
 * 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. 
 */
static NODE    *
make_new_node(char *line)
{
	NODE           *n = addnode();
	char           *links, *parent_links, *child_links;

	n->nd_numchild = 0;
	n->nd_numparent = 0;

	links = initnode(line, n);

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

	n->nd_parent_ids = make_link_block(parent_links, &n->nd_numparent);
	n->nd_child_ids = make_link_block(child_links, &n->nd_numchild);

	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. 
 */
int
web_add_links(NODE *parent, char *linkstr)
{
	NODE          **newlinks, *n;
	long           *addlinks;
	short           tryadd,	/* # of links we're trying to add */
	                numadd,	/* # we're really gonna add (less repeats) */
	                numcur,	/* # of child links in present parent */
	                numnew;	/* total # of new child links for parent */
	int             i, x, rc = TRUE;

	if (!flagset(parent, N_RESOLVED)) {
		puts("Can't add links to an unresolved parent!");
		return 1;
	}
	addlinks = make_link_block(linkstr, &tryadd);
	numcur = n_numchild(parent);

	resolve_links(addlinks, tryadd);

	numadd = tryadd;
	for (i = 0; i < numcur; i++) {	/* Eliminate repeats */
		n = n_child(parent, i);
		for (x = 0; x < tryadd; x++)
			if (n == (NODE *) addlinks[x]){ 
				addlinks[x] = -1L, numadd--;
				rc = FALSE; /* already linked here */
			      }
	}

	numnew = numcur + numadd;
	newlinks = (NODE **) domalloc((unsigned int) numnew * sizeof(NODE *));

	memcpy(newlinks, parent->nd_child_ids, numcur * sizeof(NODE *));

	for (i = 0; i < tryadd; i++)
		if (addlinks[i] != -1)
			newlinks[numcur++] = (NODE *) addlinks[i];
	
	do_free((char *) parent->nd_child_ptrs);
	parent->nd_numchild = numnew;
	parent->nd_child_ptrs = newlinks;
	/* add parent links to children */
	for (i = 0; i < tryadd; i++)
		if (addlinks[i] != -1) {
			n = (NODE *) addlinks[i];
			numcur = n_numparent(n);
			newlinks = (NODE **) domalloc((unsigned int) (numcur + 1) * sizeof(NODE *));
			memcpy(newlinks, n->nd_parent_ids, numcur * sizeof(NODE *));
			newlinks[numcur++] = (NODE *) parent;
			n->nd_numparent = numcur;
			do_free((char *) n->nd_parent_ptrs);
			n->nd_parent_ptrs = newlinks;
		}
	do_free((char *) addlinks);
	return rc;
}


/*
 * Completely delete the link between parent and child.  We don't bother to
 * free up the space for the two free pointers; it's not worth the effort. 
 */
void
web_del_link(NODE * parent, NODE * child)
{
	NODE           *n;
	int             i;
	int             numparent, numchild;

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

	n = parent;
	numchild = n_numchild(n);
	for (i = 0; i < numchild; i++)
		if (n_child(n, i) == child) {
			memcpy(&n->nd_child_ptrs[i], &n->nd_child_ptrs[i + 1],
			       ((numchild - i) - 1) * sizeof(long *));
			n->nd_numchild--;
			break;
		}
	/*
	 * remove parent from child's parent list 
	 */

	n = child;
	numparent = n_numparent(n);
	for (i = 0; i < numparent; i++)
		if (n_parent(n, i) == parent) {
			memcpy(&n->nd_parent_ptrs[i], &n->nd_parent_ptrs[i + 1],
			       ((numparent - i) - 1) * sizeof(long *));
			n->nd_numparent--;
			break;
		}
}

/*
 * Completely vaporize a node 
 */

void
web_del_node(NODE * n)
{

	/*
	 * remove links from children 
	 */
	while (0 < n_numchild(n))
	  web_del_link(n, n_child(n, 0));

	/*
	 * remove links from parents 
	 */

	while (0 < n_numparent(n))
	  web_del_link(n_parent(n, 0), n);

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

	do_free(n->nd_data);	/* deallocate memory */
	do_free(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. ---S. Thorne
 *
 * The old debug level checking has been removed; now debug mode is either
 * on or off.  New nodes are marked ONSTACK iff debug mode is off. ---ark
 * 
 */

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


	/* Special case -- assume that root node has id # 0 */
        if (!nid)
	  return root_node; 
	for (n = firstnode; n; n = n_next(n))
		if (n_id(n) == nid)
			return n;
	tmp_str =  domalloc((unsigned int) strlen(empty_node_str)+1);
	strcpy(tmp_str,empty_node_str);
	so_it_never_bombs = make_new_node(tmp_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];  /* Save 4K by making this external */
/*
 * Give us a node string without the link data, or rather, with empty link
 * data fields. 
 *   This is the NEW version--we DO send the flags.  (See network.h)
 */
char           *
web_short_node_str(NODE *n)
{
 char *name;

   if flagset(n,N_SERVER_NODE)
     /* replace server id with actual server name */
     name = get_server_name(atoi(n_locker(n)));
   else
     name = n_locker(n);

  sprintf(_node_buf, "%ld%c%u%c%d%c%s%c%s%c%s%c%s%c%s%c%c",
	  n_id(n), DLM,
	  /* eliminate internal flags */
	  n->nd_flags & ~N_NOSAVE, DLM,
	  n_date(n), DLM,
	  n_topic(n), DLM,
	  n_title(n), DLM,
	  n_source(n), DLM,
	  name, DLM,
	  n_file(n), DLM, DLM);
  if flagset(n,N_SERVER_NODE)
    free(name);
  return _node_buf;
}

/* This is the OLD version, for use with old clients--we zero out the 
   flags field. */
char *web_short_node_str_old(NODE *n)
{
  char *temp_line; 

  temp_line = web_short_node_str(n);
  /* Zero out the flags field */
  change_token(temp_line, 2, "0");

  return temp_line;
}

/*
 * Give the full text one-liner description of a node.  This generates the
 * line that goes in the pips.web file, etc. 
 *   This is the NEW version -- we DO send the flags.
 */
char           *
web_node_str(NODE *n)
{
  char           *cp;
  int             i;
  
  sprintf(_node_buf, "%ld%c%u%c%d%c%s%c%s%c%s%c%s%c%s%c",
	  n_id(n),DLM,
	  /* eliminate internal flags */
	  n->nd_flags & ~N_NOSAVE, 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 = _node_buf + strlen(_node_buf);
  
  for (i = 0; i < n_numparent(n); i++) {
    if (flagset(n, N_RESOLVED))
      sprintf(cp, "%ld,", n_id(n_parent(n, i)));
    else
      sprintf(cp, "%ld,", n_parent(n, i));
    cp += strlen(cp);
  }
  if (i)
    cp--;
  *cp = DLM;
  cp++;
  for (i = 0; i < n_numchild(n); i++) {
    if (flagset(n, N_RESOLVED))
      sprintf(cp, "%ld,", n_id(n_child(n, i)));
    else
      sprintf(cp, "%ld,", n_child(n, i));
    cp += strlen(cp);
  }
  if (i)
    cp--;
  *cp = '\0';
  return _node_buf;
}

/* This is the OLD version -- zero out the flags. */
char           *
web_node_str_old(NODE *n)
{
  char *temp_line;

  temp_line = web_node_str(n);
  /* Zero out the flags field */
  change_token(temp_line, 2, "0");

  return temp_line;
}


/*
 * Find the node previous to the given node in the linked list.  n_prev(n)
 * maps to this 
 */
NODE           *
find_prev_node(NODE *findprev)
{
	NODE           *n;

	for (n = firstnode; n; n = n_next(n))
		if (n_next(n) == findprev)
			return n;
	return lastnode;
}

/*
 * 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(void (*func) (NODE *n) )
{
  NODE           *n;
  
  for (n = firstnode; n; n = n_next(n))
    if (!flagset(n, N_FAKE))
      (*func) (n);
}
  /* pass a marker into the linkedlist so we can process a
	 chunk at a time */
/*
int
web_allnodes2(int (*func) (NODE *n) (int x )) */

typedef int (*ftype)(NODE *n, int x);

int
web_allnodes2(int (*func) (NODE *n,int x))
{
  NODE           *n;
  int             done = FALSE,x;
  
  for (n = firstnode,x = 0; n && !done; n = n_next(n), x++)
    if (!flagset(n, N_FAKE))
      done = (*func)(n, x);
return done; /* return 1 is finished chunk, or 0 if came to the end */  
}

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

void
web_find_topic(char *topic, void (*func) (NODE *n, u_short x), NODE *node)
{
        int            len;
        NODE           *n;
        char           *cp,*cpt;
	int            matched;

	for (cpt = topic; *cpt == ' '; cpt++); /* ignore leading spaces */
	if (node == NULL) 
	  { /* do complete search */
	    len = strlen(cpt);
	    for (n = firstnode; n; n = n_next(n)) 
	      {
		matched = 0;
		cp = n_topic(n);
		do 
		  {
		    for (; *cp == ' '; cp++); /* ignore leading spaces */
		    if (!strncasecmp(cp, cpt, len))
		      {
			matched = 1;
			(*func) (n, 0);
		      }
		    else 
		      {
			if (cp = index(cp,',')) cp++;
		      }
		  }
		while (!matched && cp);
	      }
	  }
        else /* do relative search */
          {
            srch_topic = cpt;
            web_traverse(TRAV_DOWN | TRAV_NOREPEAT, node, nlist_add_srch, 99u);
	  }
      }

/*
 * Make sure this parent's 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))
		return;
	resolve_links(n->nd_parent_ids, n_numparent(n));
	resolve_links(n->nd_child_ids, n_numchild(n));
	setflag(n, N_RESOLVED);
}

static void
ensure_parents(NODE * n)
{
  if (flagset(n, N_RESOLVED))
    return;
  resolve_links(n->nd_parent_ids, n_numparent(n));
  resolve_links(n->nd_child_ids, n_numchild(n));
  setflag(n, N_RESOLVED);
}

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

/* need to put in change to not clear flag for use with serarch commands only 
 * reset them all later using the nlist in this case */

/*
 * traverse_up: post-order recursive ascent thru parent links 
 *   Nodes marked as ONSTACK are ignored.
 * 
 * traverse up was changed to give the path command a more meaningful output
 * ST - 7/10/91 
 */

static void
traverse_up(NODE *n, u_short curdepth)
{
  int             i,depth;
  static	NODE            *node_stack[50];
  static  int     next = 0;	/* position of next available space on 
				   node_stack */

  if (flagset(n, N_ONSTACK))
    return;

  setflag(n, N_ONSTACK);
  node_stack[next] = n; next++;	/* put on stack */
  if (curdepth < trav_maxdepth) {
    if (!Standalone)
      ensure_parents(n); 

    if (n_numparent(n) == 0)  { /* at the top,so write stack out to nlist */
      depth = 0;
      for (i = (next - 1); i >= 0 ; i--,depth++)
	(*trav_function) (node_stack[i], (unsigned short) depth);
    }
    for (i = 0; i < n_numparent(n); i++)
      traverse_up(n_parent(n, i), curdepth + 1);
       
  }
  clrflag(n, N_ONSTACK);
  next--;			/* take off stack */
}

/*
 * traverse_dn: pre-order recursive descent thru child links 
 */
static void
traverse_dn(NODE *n, u_short curdepth)
{
  int             i;

  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 (!Standalone)
      ensure_children(n);
    for (i = 0; i < n_numchild(n); i++)
      traverse_dn(n_child(n, i), curdepth + 1);
  }
  clrflag(n, N_ONSTACK);
}

void
web_traverse(int tflags, NODE *startnode, 
	     void (*func) (NODE *n, u_short depth), u_short maxdepth)
/* (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;

    if (maxdepth > 0)
      for (i = 0; i < n_numchild(startnode); i++)
	traverse_dn(n_child(startnode, i), 1u);

  } 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;

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

  if (!n) {
    if (debug)
      puts("Traversal to null node...");
    return;
  }
  if (flagset(n, N_ONSTACK))
    return;
  setflag(n, N_ONSTACK);
  nodecnt++;
  linkcnt += n_numchild(n);

  for (i = 0; i < n_numchild(n); i++)
    test_traverse(n_child(n, i));
  clrflag(n, N_ONSTACK);
}

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

	NODE           *n;

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

void
web_remove_node(NODE *n) 
{
  do_free(n->nd_data);
  do_free(n->nd_parent_ids);
  do_free(n->nd_child_ids);
  do_free(n);
}

void
web_reload(void)
{
  printf("removing current nodes\n");
  web_allnodes(web_remove_node);
  lastnode = NULL;
  firstnode = NULL;
  printf("finished removing old nodes\n");
  web_load();  
}

/* Load the web, and resolve all node ids into pointers to nodes */
NODE           *
web_load(void)
{
	FILE           *web_file;
	char            line[NLINE_MAXLEN];
	NODE           *n;
	int             numlines = 0, orphans;

/* Unused argument standalone removed 7/17/92 ark.
   The line below, Standalone = FALSE, was actually here too.
	Standalone = standalone;
*/

	Standalone = FALSE;

	ensure_access(WEB_FILE, PIPS_LOCKER, 0); 
	
	printf("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 = make_new_node(line);
	}
	fclose(web_file);

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

	/*
	 * Now resolve all the links from node id's to pointers. 
	 */
	root_node = firstnode;  /* this is a kludge relying on the root being
				   the first node in the web file, look at 
				   web_node where there is a special root case */
	if (SERVER == TRUE)
		for (n = firstnode; n; n = n_next(n)) {
			resolve_links(n->nd_parent_ids, n_numparent(n));
			resolve_links(n->nd_child_ids, n_numchild(n));
			setflag(n, N_RESOLVED);
		}

	puts("Done"), flush();
	
	orphans = nodecnt = linkcnt = 0;
	printf("Parentless nodes: "), flush();
	find_lost_nodes(&orphans);
	if (orphans) {
	  printf("\n%d parentless nodes were found.", orphans);
	  printf("\n%d unreachable nodes were found.\n", nodecnt);
	} else puts("NONE");
	nodecnt = linkcnt = 0;
	test_traverse(root_node);
	if (debug)
	  {
	    printf("Web test: ");
	    printf("%d nodes were visited over %d links.\n", nodecnt, linkcnt);
	    flush();
	  }

	return root_node;
}

char *
get_server_name(int server_id)
{
  FILE           *fopen(), *srvfile;
  char           srvline[SRV_LN_SZ],*cp;
  
  srvfile = fopen(SERVER_FILE, "r");
  if (!srvfile) {
    perror(SERVER_FILE);
    send_msg(msglist[ CANT_FIND_SERVER_FILE ]);
    return (char *) NULL;
  }
  
  while (fgets(srvline, SRV_LN_SZ, srvfile) != '\0') {
    if (atoi(find_token(srvline,3)) == server_id) {
      cp = get_token(srvline,7);
      if (debug)
	printf("Found server name %s\n",cp);
      fclose(srvfile);
      return cp;
    }
  } 
  fclose(srvfile);
  return "";
}

