/********************************************************************
   pointers - generate pointers file for cookie prog.
     input : s:cookie.dat - cookie file
     output : s:cookie.ptr - pointers file

   © S.E.Mitchell 5/6/90
*********************************************************************/

#include <stdio.h>
#include <string.h>
#include <exec/types.h>
#include <exec/memory.h>
#include <libraries/dos.h>
#include <libraries/dosextens.h>
#include <proto/dos.h>
#include <proto/exec.h>

#define BUF_SIZE    256 	/* size of read buffer */
#define SEPERATOR   0x0c	/* char that seperates fortunes */

void _main()
{
  int c=1,i,t,count,len,*p,*base;
  BPTR in,out;
  char buffer[BUF_SIZE];

  if((in=Open("s:cookie.dat",MODE_OLDFILE))==NULL) {
    Write(Output(),"Cannot open in file\n",20);
    Exit(1);
  }
  if((out=Open("s:cookie.ptr",MODE_NEWFILE))==NULL) {
    Write(Output(),"Cannot open out file\n",21);
    Close(in);
    Exit(1);
  }

  /* find number of fortunes */

  while((count=Read(in,buffer,BUF_SIZE))>0) {
    for(i=0;i<count;i++)
      if(buffer[i]==SEPERATOR)
	c++;
  };

  /* first longword contains number cookies ... */

  Write(out,(UBYTE *)&c,4);

  /* and back to the beginning */

  Seek(in,0,OFFSET_BEGINNING);

  /* allocate sufficient memory to hold pointers to all cookies */

  len=c<<2;
  base=(int *)AllocMem(len,MEMF_PUBLIC);
  if(base==NULL) {
    Write(Output(),"Out of memory\n",14);
    Close(in);
    Close(out);
    Exit(1);
  };

  p=base;
  *p++=0;	    /* first cookie at 0 ... no ^L here ... */

  /* run through cookies again, this time noting down pointers */

  i=1;
  while((count=Read(in,buffer,BUF_SIZE))>0) {
    for(t=0;t<count;t++,i++)
      if(buffer[t]==SEPERATOR)
	*p++=i;
  };

  /* blam it out to file */

  Write(out,(UBYTE *)base,len);

  /* close up and exit */

  Close(in);
  Close(out);
  FreeMem(base,len);
  Exit(0);
}
