#include <exec/types.h>
#include <exec/io.h>
#include <exec/exec.h>
#include <libraries/dos.h>
#include <libraries/dosextens.h>
#include <devices/console.h>
#include <devices/keymap.h>
#include <intuition/intuition.h>
#include <lattice/stdio.h>


struct NewWindow hw =
{
            0, 0, 640, 200, 3, 1, NULL, ACTIVATE,
            0, NULL,"Ogre Help",  NULL, NULL, 100, 45,
            640, 200, CUSTOMSCREEN
};

#define FULLPAGE  21
#define NUMCHAR   100

extern struct Screen *scrn;
struct IOStdReq *HelpMsg, *MoreMsg;
struct MsgPort *HelpPort, *MorePort;
struct Window *helpwin;

char fname[] = "Ogre:Instructions";

char buf[NUMCHAR];
UBYTE response;


/* Open a window and a console for printing game instructions, and
 * open the instructions file.  Note that the game volume name MUST
 * be "Ogre" for this to work.
 */

get_help()
{
   FILE *fp, *fopen();
   int error;

   /* read, write ports for the help window */
      /* Can't open it. Complain. */


   HelpPort = CreatePort("con2.write",0);
   if (HelpPort == NULL)
      return(-1);

   HelpMsg = CreateStdIO(HelpPort);
   if (HelpMsg == NULL)
      return(-1);

   MorePort = CreatePort("con2.read",0);
   if (MorePort == NULL)
      return(-2);

   MoreMsg = CreateStdIO(MorePort);
   if (MoreMsg == NULL)
      return(-2);

   hw.Screen = scrn;

   helpwin = (struct Window *) OpenWindow(&hw);
   if (helpwin == NULL)
      return(-1);

   error = OpenConsole(HelpMsg, MoreMsg, helpwin);
   if (error != 0)
   {
      end_help();
      return(-3);
   }

   QueueRead(MoreMsg, &response);

   /* open the instructions file */
    if (Lock(fname, ACCESS_READ) == NULL)
    {
         ConPutStr(HelpMsg,
           "\nCan't open Ogre:Instructions. Check your volume name.\n");
         Delay(250);
         error = end_help();
         return(-4);
    }

   fp = fopen(fname,"r");
   if (fp == NULL)
   {
      return(-4);
   }

   put_help(fp);
   error = end_help();
   close(fp);
   return(error);
}


/* cleanup and exit
 */

int end_help()
{
   int error;

   DeletePort(HelpPort);
   DeleteStdIO(HelpMsg);
   DeletePort(MorePort);
   DeleteStdIO(MoreMsg);
   error = CloseWindow(helpwin);
   return(error);
}

/* write help file to window and read for more */


put_help(fp)
FILE *fp;
{
   int nomore = 0, numlines = 0;

   while ((nomore = fgets(&buf[0], NUMCHAR, fp)) != NULL)
   {
      ConPutStr(HelpMsg, buf);
      numlines += 1;

      /* when a full page has been written, pause for a keystroke */

      if (numlines == FULLPAGE)
      {
         response = ConGetChar(MorePort, MoreMsg, &response);
         numlines = 0;
      }
   }
   /* get one last key to clear the remaining text from the screen */

   response = ConGetChar(MorePort, MoreMsg, &response);
}

