#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>

char *P[5] = { "Child, where are you?  Are you reading quotes?",
	      "What are you doing?",
	      "Well, why don't you tell me one?",
	      "Don't take too long...",
	      "You should learn better ones, like this:" };
char *C[5] = {"I'm here, mom.",
	      "I know all these quotes now!",
	      "Okay, mom.  Lemme look...",
	      "Here's one:",
	      "Okay, I'll look around some more" };

char *clear = "                                                              ";

main()
{
  FILE *fp;
  int sockets[2], child, i=0, j;
  char buf[80];

  j = getpid()%139;
  srandom(j);                /* Randomizer */

  if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0) {
   perror("opening stream socket pair");
    exit(1);
  }
  if ((fp = fopen("/mit/wchuang/.private/quotes", "r")) == NULL)
    perror("fopening file");
  strcpy(buf, clear);
  
  if ((child = fork()) == -1)
    {
      perror("fork");
      exit(1);
    }
  else if (child)                   /* This is the parent. */
    {
      close(sockets[0]);

      for (j=0; j<3; j++)
	{
	  if (write(sockets[1], P[j], strlen(P[j])) < 0)
	    perror("writing stream message");
	  if (read(sockets[1], buf, 80, 0) < 0)
	    perror("reading stream message");
	  printf(" child -->  %s\n", buf);
	  strcpy(buf, clear);
	  sleep(1);
	}
      
      do
	{
	  if (read(sockets[1], buf, 80, 0) < 0)
	    perror("while reading 'done'");
	} while (strncmp(buf, "done", 4) != 0);
      j = (int) (random()%99);
      i = 10;
      while (i < j)
	{
	  fgets(buf, 80, fp);
	  if (strcmp(buf, "---\n") == 0)
	    i++;
	}
      fgets(buf, 80, fp);
      printf(" \nparent -->  Get a real quote, like this:\n");
      do
	{
	  printf("%s", buf);
	  fgets(buf, 80, fp);
	} while (strcmp(buf, "---\n") != 0);
      printf("\nparent -->  Now go to sleep!\n");
      if (write(sockets[1], "done", strlen("done")) < 0)
        perror("writing stream message");
      close(sockets[1]);
    }
  else                              /* This is the child. */
    {
      close(sockets[1]);

      for (j=0; j<3; j++)
	{
	  if (read(sockets[0], buf, 80, 0) < 0)
	    perror("reading stream message");
	  printf("parent -->  %s\n", buf);
	  sleep(1);
	  strcpy(buf, clear);
	  if (write(sockets[0], C[j], strlen(C[j])) < 0)
	    perror("writing stream message");
	}
      
      j = (int) (random()%100);
      i = 0;
      while (i < j)
	{
	  fgets(buf, 80, fp);
	  if (strcmp(buf, "---\n") == 0)
	    i++;
	}
      fgets(buf, 80, fp);
      printf(" \nchild -->  Here's one:\n");
      do
	{
	  printf("%s", buf);
	  fgets(buf, 80, fp);
	} while (strcmp(buf, "---\n") != 0);
      if (write(sockets[0], "done", strlen("done")) < 0)
	perror("writing 'done'");
      do
        {
          if (read(sockets[0], buf, 80, 0) < 0)
            perror("while reading 'done'");
        } while (strncmp(buf, "done", 4) != 0);
      close(sockets[0]);
    }
  fclose(fp);
}
