#include <stdio.h>      
#include <sys/file.h>
#include <fcntl.h>
#include <ctype.h>
#include <errno.h>
#include "inet.h"

#define CR		'\015'
#define LF		'\012'
#define EOM             ".\r\n"
#define EOM_LEN         3
#define CRLF            "\015\012"
#define SOCKBUF		4096
#define FALSE           0
#define TRUE            1

char            outbuf[SOCKBUF];
char            inbuf[SOCKBUF];

char           *host, *port;
static int      ids[6], level, node, pipssock;
static char    *subj[6], *title, *line, *cp;


main()
{				/* parsing man items to add as docs
				 * to pips */

    FILE           *fopen(), *ifp, *ofp;
    char           *malloc();
    int             len, i;
    title = malloc(80);
    line = malloc(120);
    /* establish connect with pips */
    host = "hershey";
    port = "9000";

    pipssock = inet_establish_connection(host, port, 0);
    if (pipssock < 0) {
	puts("Fatal error: could not establish connection.");
	exit(1);
    }
    get_msg(pipssock, inbuf, SOCKBUF);
printf("banner=%s\n",inbuf);
bzero(inbuf,strlen(inbuf));
    send_msg(pipssock,"p:thorne",8); /* become a provider */
    get_msg(pipssock, inbuf, SOCKBUF);
printf("msg=<%s>\n",inbuf);
bzero(inbuf,strlen(inbuf));
    for (i = 0; i < 6; i++) {
	subj[i] = malloc(50);
	strcpy(subj[i], "");
	ids[i] = 0;
    }

    node = 0;
    ifp = fopen("cats", "r");
    while (fgets(line, 80, ifp) != 0) {
          len = strlen(line);
	  line[len-1] = '\0';
		add_subj();
    }
    fclose(ifp);
    close(pipssock);
}
add_subj()
{
    char            transline[120];
    char            linktrans[50];
    char            ret_msg[50];
    char            path[80];   

   bzero(transline,120);
   bzero(linktrans,50); 
    if (level > 1)
	sprintf(title, "%s.%s", title, subj[level]);
sprintf(transline,"a:9:4:9:%s:Unix Manual Pages:MAN::/usr/man/cat3/%s",line,line);
    printf("%s|%d\n", transline,strlen(transline));
 
    send_msg(pipssock,transline,strlen(transline));
    get_msg(pipssock,ret_msg,50);
    printf("ret msg <%s>\n",ret_msg);
    node = atoi(ret_msg);
    sprintf(linktrans,"l:20652:%d",node);
    printf("%s\n",linktrans); 
    bzero(ret_msg,50);
    send_msg(pipssock,linktrans,strlen(linktrans));
    get_msg(pipssock,ret_msg,50);
    printf("ret msg2 <%s>\n",ret_msg);
}

get_msg(sock, buff, buffsize)	/* read message off socket */
    int             sock;
    char           *buff;
    int             buffsize;
{
    int             red;
    char           *cp,tempbuff[256];

*buff = '\0';   
while ((red = read(sock, tempbuff, buffsize)) > 0) {
  if (!strncmp(&tempbuff[red - 3], EOM, EOM_LEN)) {
    tempbuff[red-4] = '\0';
    strcat(buff,tempbuff); 
    if (strlen(buff) > 0)   
      break; }
  strncat(buff,tempbuff,red);
}
}

send_msg(sock,str,len)
int sock;
char *str;
int len;
{
int wrote;
char msg[150];
sprintf(msg,"%s%s",str,CRLF);
wrote = write(sock,str,len + 2);
printf("wrote %d\n",wrote);
/* printf("wrote end %d\n",wrote); */
}
