/* cookie.c -- The fortune cookie program */
/* Lars "ZAP" Hamre 29/08-1990            */

#include "stdio.h"
#include "stdlib.h"
#include "time.h"

#define SEEK_SET 0

long index, cookies, cnum;
FILE *fp1, *fp2;
char ch, lastch;
char str[100];

char *cookiefile  = "cookie.txt";
char *cookieindex = "cookie.idx";

long GetNum(long pos, FILE *);
int  random(int range);
void randomize();

void main(int argc, char **argv)
{
   if (argc>1 && argv[1][0]=='?')
   {
      printf("cookie -- Lars \"ZAP\" Hamre 1990\n");
      printf("The fortune cookie program.\n");
      printf("usage: cookie [number] [cookiefile]\n");
      exit(0);
   }

   if (argc==2)
      cnum = atoi(argv[1]);
   else
      cnum = 0;

   if (argc>2 && cnum==0)
   {
      cookiefile  = argv[1];
      cookieindex = argv[2];
   }

   fp1 = fopen(cookiefile,"rb");
   if (fp1==NULL)
   {
      printf("cookie: Can't open textfile '%s'!\n",cookiefile);
      exit(20);
   }

   fp2 = fopen(cookieindex,"rb");
   if (fp2==NULL)
   {
      printf("cookie: Can't open indexfile '%s'!\n",cookieindex);
      exit(20);
   }

   cookies = GetNum(0,fp2);

   if (cnum>cookies)
   {
      printf("cookie: Cookienumber too large (max. %lu)!\n",cookies);
      exit(10);
   }

   randomize();

   if (cnum==0) cnum = random(cookies)+1;
   index = GetNum(cnum,fp2);
   printf("(%ld)\n", cnum);
   fseek(fp1, index, SEEK_SET);

   fgets(str, 99, fp1);
   for(;;)
   {
      fgets(str, 99, fp1);
      if (feof(fp1)) break;
      if (str[0]=='%' && str[1]=='%') break;
      printf("%s",str);
   }

   fclose(fp1);
   fclose(fp2);
}


long GetNum(long pos, FILE *fp)
{
   fseek(fp, pos<<2, SEEK_SET);

   return ((long)getc(fp)<<24) +
          ((long)getc(fp)<<16) +
          ((long)getc(fp)<< 8) +
           (long)getc(fp);
}

/******** Chops off any character with a value less than space ********/
/******** at the end of a string.                              ********/

void CutEnd(char *str)
{
   int a = strlen(str);

   while (a>=0)
   {
      if (str[a] > ' ')
         break;
      else
         str[a--]='\0';
   }
}


/******** Returns random integer from 0 to range-1 ********/
int random(int range)
{
   return rand() % range;
}


/******** Set random number seed from vblank ********/
void randomize()
{
   long *ptr;
   ptr = (long *) 0x00dff004;

   srand(*ptr);
}

/* End of File */
