/*
 *------------------------------------------------------------------
 *
 * $Source: /afs/net.mit.edu/dev/project/techinfodev/src/srv_ti/RCS/nlist_c.c,v $
 * $Revision: 3.2 $
 * $Date: 93/02/03 11:21:41 $
 * $State: Exp $
 * $Author: thorne $
 * $Locker:  $
 *
 * $Log:	nlist_c.c,v $
 * Revision 3.2  93/02/03  11:21:41  thorne
 * new release
 * 
 * Revision 1.4  92/08/25  17:09:36  ark
 * Saber & WAIS cleanup
 * 
 * 
 * Revision 1.3  92/08/24  15:47:00  ark
 * WAIS searching added to client & server (J command)
 * 
 * Revision 1.2  92/08/20  17:47:17  ark
 * WAIS search command added; used #defines instead of hard-coded command
 * abbreviations.
 * 
 * Revision 1.1  92/08/11  13:44:32  ark
 * Bug fixes: 'n' transaction leaving file descriptors open;
 *            'b' transaction now disallows searches on empty strings.
 * 
 * Revision 1.0  92/07/10  12:32:38  ark
 * Initial revision
 * 
 * Revision 1.2  91/07/18  09:50:30  thorne
 * fixes small bugs found by upenn etc (incorpoates diffs)
 * 
 * Revision 1.1  91/07/15  10:40:32  thorne
 * Initial revision
 * 
 *------------------------------------------------------------------
 */

#ifndef lint
#ifndef SABER
static char *rcsid_foo_c = "$Header: /afs/net.mit.edu/dev/project/techinfodev/src/srv_ti/RCS/nlist_c.c,v 3.2 93/02/03 11:21:41 thorne Exp $";
#endif SABER
#endif  lint


/*
 * nlist_c.c 
 * client node list routines S. Thorne 8/12/90
 *
 */
/*
  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>
#ifndef AIX
#include <sys/time.h>
#else
#include <time.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include "pdb.h"
#include "network.h"
#include "nlist_c.h"
#include "messages.h"
#include <errno.h>
#include <netdb.h>
#include <fcntl.h>
#include <unistd.h>

extern int      SERVER;
extern int      menu;
extern int      disptype,sock;
extern char *pips_server_host,*pips_server_port;

static NODE	*nlist[NLIST_MAX_LEN];
static TI_CONN  est_conn[MAX_SERVERS];
static u_short      numnode;
static u_short      curdepth;
static num_servers = 0;


static char	sbuf[SBUFLEN];
int sock;
#define	terminator(str)	(!strncmp(str, EOM, EOM_LEN))
void
log_aline(line)		    /* write  to a  file - for debugging */
	char           *line;
{
	int dfd;
	if ((dfd = open("/tmp/junk", O_APPEND | O_CREAT | O_WRONLY, 0644)) == 0)
		printf("error logging transaction\n");
	write(dfd, line, strlen(line));
	close(dfd);
	return;
}

nwrite(int thesock, char *str, int strlen)
{   /* common write routine, all client communication should go through here */
int rc;

  rc = write(thesock,str,strlen); 

  if (rc <= 0) { /* this never happens */
    perror("write failed");
    printf("lost contact with the server.");
    sleep(10);
    do_quit();
  }
}
  
static char *
get_msg()  /* common read rotine, uses global buffer */
{
	int	rc,cnt=0;
	long    len = 0;
	char junk[BUFSIZ];
 
	do {
		rc = read(sock, &sbuf[len], SBUFLEN - len);
		if (rc == 0)
		  cnt++;
		if (cnt > 50) /* don't keep reading nothing, somethings 
				  wrong, exit */
		  do_quit();
		if (rc < 0 )
		  do_quit(); /* perror("in read"); */
		else
		  len = rc + len;
	} while (len < SBUFLEN && !terminator(&sbuf[len - EOM_LEN]));

        if ( len >= SBUFLEN) {
	  /* too much for the buffer, so read until EOM found */
	  do {
	    if (rc == 0)
	      cnt++;
		if (cnt > 50)
		  do_quit();
	    rc = read(sock, junk , BUFSIZ);
	    if (rc < 0 ) {
	      perror("in read"); 
	      do_quit(); }
	  } while (!terminator(&junk[rc - EOM_LEN]));

	}
	else
	  len -= EOM_LEN;
    

	if (sbuf[len - 1] == LF)
	  len--;

	if (sbuf[len - 1] == CR)
	  len--;
	sbuf[len] = '\0';
	return sbuf;
}
int 
server_understood()
{     /* this routine is to detect if a server didn't understand a request,
	 usually due to its running an older version */
  
  /* Backwards compatibility for old servers -- gotta love it */
  if (strncmp(sbuf,"HUH?",4) && strncmp(sbuf,"13:Server did not",17)
      && (strncmp(sbuf,"99:There is no",14)))
      return TRUE;
  else
    {
      disp_setmsg("This server does not understand this request");
      return FALSE;
    }
}

int
sweb_init(char *addr, char *portnum)
{    /* connect to a techinfo server */
  int ssock;
        ssock = inet_establish_connection(addr, portnum, TRUE);
  if (ssock < 0){
    printf("Could not connect to server. Call %s for help.\n",HELP_PHONE);
    sleep(5);
    return -1;
  }
  sock = ssock;
/*        printf("[%s]\n", get_msg()); */
  get_msg();
/* add the new format cmd, so we get the flags */
  nwrite(sock,"O:2\n",4);
  get_msg();
  return ssock;
}

/* make a connection to another server if needed, and change the 
      current server to this one */
nlist_est_conn(char *srv_name,char *port)
{  

  
  int i=0,oldsock;
  struct hostent		*hp;
  struct  in_addr hostaddr;

  oldsock =sock;
  /* get host addr */
  hp = gethostbyname(srv_name);

  /* Check to see if server is real */
  if (hp == NULL)
    return -1;
      
  bcopy(hp->h_addr, &hostaddr, hp->h_length);

  for (i = 0; i < num_servers; i++) 
    {
      if (!(bcmp(&hostaddr,&est_conn[i].addr,sizeof(hostaddr)))) 
	/* connection already there */
	{
	  log_aline("host already connectd\n");
	  sock = est_conn[i].sock;
	  /* test to see if the conn is still good ?? */
	  est_conn[i].ref_cnt++;
	  return sock;
	}
    }
  /* we must not have hade a connection here yet -- so do it*/
  est_conn[i].sock = sweb_init(srv_name,port);

  if (est_conn[i].sock > 0) {
    bcopy(&hostaddr,&est_conn[i].addr,sizeof(hostaddr));
    est_conn[i].srv_name = (char *) malloc(strlen(srv_name)+1);
    strncpy(est_conn[i].srv_name,srv_name,strlen(srv_name));
    sock = est_conn[i].sock;
    num_servers++;
    est_conn[i].ref_cnt = 0;
  }
  else{
    sock = oldsock;
    return -1;
  }
  return sock;
}

char *
nlist_get_srvname(int sock)
{
  int i;

  for (i = 0; i < num_servers; i++) 
    if (sock == est_conn[i].sock)
      return est_conn[i].srv_name;
  return NULL;
}


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

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

/* make a node from a delimited string */
NODE *
nlist_make_node(char *line)
{ 
  NODE *n;
  char *cp;
  unsigned  len;

  cp = line;
  n = (NODE *) domalloc((unsigned) sizeof(NODE));
  /* if (!n)
     log_aline("malloc failed\n");*/

  n->level = atoi(line);
  n->nd_id = atol(next_field(&cp));
  n->nd_flags = atoi(next_field(&cp));
  n->nd_date = atoi(next_field(&cp));
  n->topic = next_field(&cp);	/* only to null terminate last fld */
  len = (unsigned) strlen(cp);
  n->topic =  domalloc((unsigned) len + 1);
  bcopy(cp,n->topic,len+1);
  cp = n->topic;
  n->title = next_field(&cp);
  n->source = next_field(&cp);
  n->locker = next_field(&cp);
  n->file = next_field(&cp);
  cp = next_field(&cp);		/* only to null terminate last fld */
  return n;
}

free_node(NODE *n)
{
  do_free(n->topic);
  do_free(n); 
  return;
}

int
nlist_recv() /* receive an nlist from the network, does not automatically
	      clear the nlist call nlist_reset for this */
{
  int line,num,cnt = 0;
  char *buf,*nextline;

  buf = get_msg();
  if (!server_understood())
    return numnode = 0;
  num = atoi(buf);
  if (num == 0)
    return numnode;
  buf = (char *) index(buf,'\n');
  buf++;
  for (line = numnode; line < (num + numnode); line++, cnt++) 
    {
      /* 
       * Prevent some crashes on very long node lists; still dies if
       *  list returned is exactly NLIST_MAXLEN long.   8/21/92  ark 
       */
      if (cnt == NLIST_MAX_LEN)
	break;

      nextline = (char *) index(buf,'\n');
      if (nextline) 
	{
	  *nextline = '\0'; 
	  nextline++;
	}
      nlist[line] = nlist_make_node(buf); 
      if (nextline) 
	buf = nextline;
      else
	break;			/* end of the buffer, but more nodes returned */   
      
    }
  
  if (num == cnt + 1)		/* changed to fix expand bug 8/11/92 THORNE */
    numnode = numnode + num; 
  else {
    numnode = numnode + cnt;	/* don't show incomplete last record */
    n_id(nlist[numnode-1]) = 0;	/* send them back to the beginning */
    n_file(nlist[numnode-1]) = "";   
    n_title(nlist[numnode-1]) = "This is an INCOMPLETE LIST, request too large";
  }
  return numnode;
}

NODE *
web_node(long n)
{
  char *buf;
  char str[50],nodestr[4000];

  sprintf(str,"%c:%05ld\n", T_SENDNODE, n);
  nwrite(sock,str,strlen(str));
  buf = get_msg();
  sprintf(nodestr,"0:%s",buf);	/* no level returned from an "s:" */
  return nlist_make_node(nodestr);
}


void
nlist_reset()
{				/* Empty out node list */
  int i;

  for (i = 0; i < numnode; i++)
    free_node(nlist[i]); 

  numnode = curdepth = 0;

}

short
nlist_numnode()
{
	return numnode;
}

nlist_set_numnode(int num)
{
	numnode = num;
}

NODE           *
nlist_node(int relative_id)
{
	if (relative_id >= numnode || relative_id < 0) {
		/* printf("Bad relative id#%d ", relative_id); */
		return (NODE *) 0;
	}
	return nlist[relative_id];
}

short
nlist_lev(int relative_id)
{
	if (relative_id > numnode)
		return 0;
	return nlist[relative_id]->level;
}

int
nlist_find_id(long nid, int list_len)
{
	 int             i;

	for (i = 0; i < list_len; i++) {
		if (nlist[i]->nd_id == nid)
			return i;
	}
	return -1;
}

nlist_add(long id,u_short lev) /* add a node to the nodelist */
{
  nlist[numnode] = web_node(id);
  nlist[numnode]->level = lev;
  if (lev > curdepth)
    curdepth = lev;
  numnode++;
}

void   /*******/
nlist_build(int dir, NODE * n, u_short levels)
{
  char str[50];

  if (levels > curdepth)
    curdepth = levels;
  sprintf(str,"%c:%d:%ld:%d\n", T_TRAVERSE, dir,n->nd_id,levels);
  nwrite(sock,str,strlen(str));
  numnode = nlist_recv();
}

void  /********/
nlist_help()
{
  char str[50];

  sprintf(str, "%c\n", T_HELP);
/*
  strcpy(str,"H\n");
*/
  nlist_reset();
  nwrite(sock,str,strlen(str));
  numnode = nlist_recv();
  return;
}

/* old
void
nlist_search(char *subject)
{
char str[50];

sprintf(str,"%c:%s\n", T_FIND, subject);
nwrite(sock,str,strlen(str));
numnode = nlist_recv();
}
*/

void
nlist_search(char *subject,NODE *node)
{
  char str[50];

  if (node)
    sprintf(str,"%c:%s:%ld\n", T_FIND, subject,n_id(node));
  else
    sprintf(str,"%c:%s\n", T_FIND, subject);
  nwrite(sock,str,strlen(str));
  numnode = nlist_recv();
}

void
nlist_search_source(char *source,NODE *node)
{
  char str[50];

  if (node)
    sprintf(str,"%c:%s:%ld\n", T_SOURCE_SRCH,source,n_id(node));
  else
    sprintf(str,"%c:%s:0\n", T_SOURCE_SRCH, source);
  nwrite(sock,str,strlen(str));
  numnode = nlist_recv();
}


void
nlist_txtsrch(char *subject, NODE *node)
{
  char str[100];
  char *cp;

  /* If string is too long, quit */
  if (strlen(subject) > 90)
    {
      disp_msgnow("Search string is too long.");
      return;
    }
  
  while ((cp = (char *)strchr(subject, ':')) != NULL) {
    *cp = ' ';			/* put a space in place of the colon */
  }
  
  
  if (node)
    sprintf(str,"%c:%s:%ld\n", T_FULL_TXT_SEARCH, subject,n_id(node));
  else
    sprintf(str,"%c:%s\n", T_FULL_TXT_SEARCH, subject);
  nwrite(sock,str,strlen(str));
  numnode = nlist_recv();
}


void
nlist_newstuff(char *datestr,NODE *node)
{
  char str[50],*cp;
  

  cp = index(datestr,'/');
  if (cp)
    *cp = DLM;
  else
    return;
  cp = index(cp,'/');
  if (cp)
    *cp = DLM;
  else
    return;
  cp = index(cp,'/');
  if (cp)
    *cp = DLM;
if (node)
  sprintf(str,"%c:%ld:%s", T_CHGD_SINCE, n_id(node),datestr);
else
  sprintf(str,"%c::%s", T_CHGD_SINCE, datestr);
  nwrite(sock,str,strlen(str));
  numnode = nlist_recv();
}

void   /* expand a node list */
nlist_expand(u_short levels)
{
  NODE		*tmp_nlist[NLIST_MAX_LEN], *nl;
  unsigned int    tmp_blen;
  int             i, tmp_numnode;

  tmp_numnode = numnode;
  tmp_blen = sizeof(NODE *) * tmp_numnode;
  bcopy(nlist, tmp_nlist, tmp_blen);
  numnode = 0;
  /* nl = tmp_nlist[0]; */
  levels = levels + curdepth;
  for (i = 0; i < tmp_numnode; i++){
    nl = tmp_nlist[i];
    if (nl->level == 0)
      nlist_build(TRAV_DOWN,nl,levels);
    free_node(nl);
  }
  /* need to free tmplist strs (in for loop ?) */ 
}



void
nlist_fio(char *file, int op, int msgs)
{ 
  static char     _nliobuf[BUFSIZ];

  FILE           *fp;
  char           *home, *getenv();
  char            savefile[64];
  char           *openmode;
  int             i, pid;

  long            nid;
  u_short          nlev;
  char            buf[16];
	
  pid = getpid();
  if (!(home = getenv("HOME")))
    home = "/tmp";
  if (!file)
    sprintf(savefile,"%.50s/.pips.save.%d",home,pid); 
  else if (*file == '/')
    strncpy(savefile, file, 62);
  else
    sprintf(savefile, "%.50s/%s", home, file);

  openmode = (op == NL_SAVE ? "w+" : "r");

  if ((fp = fopen(savefile, openmode)) == 0) {
    perror(savefile);
    return;
  }
  setbuf(fp, _nliobuf);

  /* * *** NL_SAVE ***/ 


  if (op == NL_SAVE) {
    if (msgs)
      printf("Saving current list to [%s]...", savefile), flush();
    for (i = 0; i < numnode; i++)
      fprintf(fp, "%05ld %d\n", n_id(nlist[i]),
	      nlist_lev(i));
    fclose(fp);
    if (msgs)
      printf("%d items were saved to [%s]", --i, savefile), flush();
    return;
  }

  /* *** NL_RESTORE ***/ 

  if (op != NL_RESTORE && op != NL_RESTORE_OR && op != NL_RESTORE_AND) {
    printf("nlist_fio: op=?"), flush();
    return;
  }
  if (msgs)
    printf("Restoring list from [%s]...", savefile), flush();
/*
  int old_num = numnode;
*/
  if (op == NL_RESTORE)
    nlist_reset();
  i = 0;
  while (fgets(buf, 16, fp)) {
    nid = atol(buf);
    nlev = atoi(&buf[6]);
    nlist_add(nid, nlev);
    i++;
  }
  if (msgs)
    printf("%d items being restored from [%s]...", i, savefile), flush();
  fclose(fp);
  if (msgs)
    printf("%d items were restored from [%s]", i, savefile), flush();

/* Who knows what this did?

    if (op == NL_RESTORE_OR) {	
     
      for (i = old_num; i < numnode; i++) {
        if (nlist_find_id(n_id(nlist[i].n), i) != -1)
        nlist_del(n_id(nlist[i].n));
      }
    }
    if (op == NL_RESTORE_AND) {
      new_pos = 0;
      for (i = old_num; i < numnode; i++) {
        if (nlist_find_id(n_id(nlist[i].n), old_num) != -1) {
        nlist[new_pos].n = nlist[i].n;
        nlist[new_pos].lev = nlist[i].lev;
        new_pos++;
      }
    } 
*/

}

/*****************************************************************************/
/*****************************************************************************/
/*****************************************************************************/

 /* static */ int indent_per_lev = 2;
 /* static */ int topic_fld_len = 23;
 /* static */ int title_fld_len = 31;
#define	width_exactly(w)	(w), (w)	/* for -*.*s fields */
/*
 * This stuff prob should be reorganized somehow. It's also a nasty nasty
 * mess. 
 */


static char    *
node_pretty_fmt(n, lineno, depth)
	NODE           *n;
	int             lineno, depth;
{

	static char     buf[256];

	char           *fmt = "%4d  %-*.*s %-*.*s%-*.*s %-1.1s   %8.8s    %5.5s";
	int             indent, topic_space;
	char            nbuf[8], nid[10],theday[10];
	time_t            secs;
	struct tm       *thedate;

	indent = indent_per_lev * depth;
	if (indent > topic_fld_len)
		indent = topic_fld_len;
	topic_space = topic_fld_len - indent;
	if (topic_space < 0)
		topic_space = 0;
	if (flagset(n,N_IMAGE))
	  sprintf(nbuf, "I");
	else if (is_menu_node(n))
	  sprintf(nbuf, "S");
	else
	  sprintf(nbuf, "D");
	if (!is_menu_node(n))
	  {
	    secs = (time_t) (n_date(n) * 86400);
	    thedate = localtime(&secs);
	    sprintf(theday,"%2d/%2d/%2d",thedate->tm_mon +1,thedate->tm_mday, 
		    thedate->tm_year);
	  }
	else
	  sprintf(theday,"        ");
	sprintf(nid, "%5.5d", n_id(n));

	sprintf(buf, fmt,
		lineno + 1,
		width_exactly(title_fld_len),
		n_title(n),
		width_exactly(indent), "| | | | | | | | | | | | | | |",
		width_exactly(topic_space),
		n_topic(n),
		nbuf,theday,
		nid);

	return buf;
}
static char    *
node_pretty_fmt2(n, lineno, depth)	/* stripped down disp */
	NODE           *n;
	int             lineno, depth;
{

	static char     buf[256];

	char           *fmt2 = "%19d  %*.*s %-s";
	int             indent;

	indent = indent_per_lev * depth;
	sprintf(buf, fmt2,
		lineno + 1, width_exactly(indent), " | | | | | | | | | |",
		n_title(n));
	return buf;
}
static char    *
node_pretty_fmt3(n, lineno, depth)	/* stripped down disp */
	NODE           *n;
	int             lineno, depth;
{
	static char     buf[256];

	char           *fmt2 = "%4d       %*.*s %-*.*s %*.*s %-*.*s   %-*.*s";
/* %4d  %-*.*s %-*.*s%-*.*s %-1.1s   %8.8s    %5.5s"; */
	int             indent,pad;
	time_t thetime;
	struct   tm *thedate;
	char theday[20];
	if (!is_menu_node(n)) {
	  thetime = (time_t) n_date(n)*86400;
          thedate = localtime(&thetime);
          sprintf(theday,"%2d/%2d/%2d",thedate->tm_mon +1,thedate->tm_mday, 
		  thedate->tm_year);
	}
	else
	  sprintf(theday,"        ");
	indent = indent_per_lev * depth;
	pad = 10 - indent;
	sprintf(buf, fmt2,
		lineno + 1, width_exactly(indent), " | | | | | | | | | |",
		width_exactly(title_fld_len),n_title(n),width_exactly(pad),
		"                 ",
		width_exactly(8),theday,
		width_exactly(10),n_source(n));
	return buf;
      }

char           *
nlist_fmt_line(int lineno)
{
	int             num, depth;

	 if ((lineno+menu) >= nlist_numnode())
		return ""; 

	num = lineno;
	depth = nlist[lineno]->level;
	 if (menu) {		/* Menu kludge  */
		depth = 0;
		lineno++;
	} 

	if (disptype == FULL)
	  return node_pretty_fmt(nlist[lineno], num, depth);
	else if (disptype == SIMPLE)
	  return node_pretty_fmt2(nlist[lineno], num, depth);
	else
	  return node_pretty_fmt3(nlist[lineno], num, depth);
}
#ifndef GETFILES
extern char *text_buf;

int
get_text(NODE *n) /* get text from the server */
{
  char firstline[200],*cp,str[50];
  int rc,len,totalread;

  /* make the request */
  sprintf(str,"%c:%ld:0:%d\n", T_SENDFILE, n_id(n),MAXDOCCHARS);
  nwrite(sock,str,strlen(str));

  for (cp = firstline; *(cp-1) != LF; cp++)
    {
      rc = read(sock,cp,1);
      if (rc < 0){
	perror("reading firstline");
	return 0;
      }
    }
  *(cp - 1) = '\0';
if (isalpha(firstline[0])) /* must be an error msg */
  disp_errmsg(firstline);

  cp = (char *) index(firstline,DLM); 
  if (!cp) {			/* if the delimiter is not found read everything until the end */
    get_msg();			/* ?? ST 7/16/91 */
    return 0;			/* shouldn't I exit? */
  }
  cp++;

  len = atol(cp);

  if (len <= 4) 
    return 0;
  len++;			/* need to read one extra. why ? check into this */
  text_buf = domalloc((unsigned) len);
  totalread = 0;
  while (totalread < len) {
    rc = read(sock,text_buf + totalread,len - totalread);

    if (rc < 0){
      perror("in read");
      return 0;
    }
    totalread = totalread + rc;
  }

  len = len - 4;
  return len;
} 
#endif

ASERVER server_list[100];

load_servers() /* get the list of servers */ 
{ char *buf,*cp; 
  int i,numservers;

    nwrite(sock,"m\n",2);
    buf = get_msg();
    if (!server_understood())
      return 0;
    numservers = atoi(buf);
    cp = buf;

    for (i = 0 ; i < numservers; i++) {
      cp = (char *) index(cp,'\n');
      if (cp) {
	cp++;
	server_list[i].contact = get_token(cp,4);
	server_list[i].email = get_token(cp,5);
	server_list[i].name = get_token(cp,6);
	server_list[i].addr = get_token(cp,7);
	server_list[i].comment = get_token(cp,8);

	server_list[i].portnum = get_token(cp,2);
	/*    server_list[i].idnum = atoi(get_token(cp,3));
	      if (server_list[i].idnum == 0)
	      server_list[i].sock = sock;  Do this in conn table instead
	      else
	      server_list[i].sock = -1; */
      }
    }
    return numservers;
  }

char *
get_source(long nid)
{
  char line[100],*buf;

  sprintf(line,"%c:%ld\n", T_SRC_INFO, nid);
  nwrite(sock,line,strlen(line));
  buf = get_msg();
  if (!server_understood())
    return 0;
  return buf;
}

int
check_version()
{
  char ver_str[100],*buf;

  sprintf(ver_str,"%c:%s\n", T_VERSION, TI_VERSION);
  nwrite(sock,ver_str,strlen(TI_VERSION)+3);
  buf = get_msg();
  return atoi(buf);
}

