#include <stdio.h>
#include <exec/memory.h>

/* #include <ctype.h> */

#define PATH_EXEC "YOW:"

/* zippy.c
 *
 * Print a quotation from Zippy the Pinhead.
 * Qux <Kaufman-David@Yale> March 6, 1986
 *
 * Compiled for AmigaDOS by Joseph Hillenburg (jph@gnu.ai.mit.edu,
 *                          dolmen!anaconda!jph@iuvax.cs.indiana.edu)
 *
 * Amiga Port History
 *
 * 1.00     May 11      Very first release...very weak...
 * 1.01     May 11      :) Cleaned up source a little...
 *
 * I plan to add...
 *  An Intutition version?
 *
 */

#define BUFSIZE  2000
#define SEP      '\0'
#define YOW_FILE "yow.lines"

static char *VersTag = "\0$VER: AmigaYow (Joseph Hillenburg) 1.01 (05/11/92)";

main (argc, argv)
     int argc;
     char *argv[];
{
  FILE *fp;
  char file[BUFSIZ];
  void yow();
/*ULONG seconds;
  ULONG micros;*/

/*  CurrentTime(seconds,micros); */

  if (argc > 1 && (!strcmp (argv[1], "-h") || !strcmp (argv[1], "-H") || !strcmp (argv[1], "-?")))
    {
    printf("yow [-v] [-h] [-?] [-f <filename>]\n");
    exit(1);
    }

  if (argc > 1 && !strcmp (argv[1], "-v"))
    {
    printf("AmigaYow 1.01 by Joseph Hillenburg, May 11 1992\n");
    printf("                 (jph@gnu.ai.mit.edu)\n");
    printf("                 (dolmen!anaconda!jph@iuvax.cs.indiana.edu)\n");
    exit(1);
    }

  if (argc > 2 && !strcmp (argv[1], "-f"))
    strcpy (file, argv[2]);
  else
    sprintf (file, "%s%s", PATH_EXEC, YOW_FILE);

  if ((fp = fopen(file, "r")) == NULL) {
    perror(file);
    exit(1);
  }

  /* initialize random seed -- used to use time + getpid()*/
  srand((int) (((long *) time(0)) + AvailMem()/* + micros*/));

  yow(fp);
  fclose(fp);
  exit(0);
}

void
yow (fp)
     FILE *fp;
{
  static long len = -1;
  long offset;
  int c, i = 0;
  char buf[BUFSIZE];

  /* Get length of file, go to a random place in it */
  if (len == -1) {
    if (fseek(fp, 0, 2) == -1) {
      perror("fseek 1");
      exit(1);
    }
    len = ftell(fp);
  }
  offset = rand() % len;
  if (fseek(fp, offset, 0) == -1) {
    perror("fseek 2");
    exit(1);
  }

  /* Read until SEP, read next line, print it.
     (Note that we will never print anything before the first seperator.)
     If we hit EOF looking for the first SEP, just recurse. */
  while ((c = getc(fp)) != SEP)
    if (c == EOF) {
      yow(fp);
      return;
    }

  /* Skip leading whitespace, then read in a quotation.
     If we hit EOF before we find a non-whitespace char, recurse. */
  while (isspace(c = getc(fp)))
    ;
  if (c == EOF) {
    yow(fp);
    return;
  }
  buf[i++] = c;
  while ((c = getc(fp)) != SEP && c != EOF) {
    buf[i++] = c;

    if (i == BUFSIZ-1)
      /* Yow! Is this quotation too long yet? */
      break;
  }
  buf[i++] = 0;
  printf("%s\n", buf);
}

