/*
**	$RCSfile: ExcptTest.c,v $
**	$Filename: ExcptTest.c $
**	$Revision: 1.0 $
**	$Date: 2000/08/01 15:25:03 $
**
**	sysmon.library silly Exception Test program (version 1.0)
**	
**	(C) Copyright 2000 by Etienne Vogt
*/

#define __USE_SYSBASE
#include <proto/exec.h>
#include <proto/dos.h>
#include <string.h>
#include <stdlib.h>
#include "sysmon.h"
#include "sysmon_protos.h"
#include "sysmon_pragmas.h"

struct SysmonBase *SysmonBase;

/* Global variables shared with exception code */
struct Process *myproc;
volatile BOOL done = FALSE;	/* Don't optimize this, please */
APTR oldexcept;

/* Prototypes */
int main(void);
static void cleanexit(int rc);
static ULONG __saveds __asm myexcept(register __d0 ULONG excptsigs, register __a1 APTR excptdata);

static UBYTE version[] = "$VER: ExcptTest 1.0 (2.8.2000)";

int main(void)
{ 
  SysmonBase = NULL;
  myproc = (struct Process *)FindTask(NULL);

  if ((SysmonBase = (struct SysmonBase *)OpenLibrary("sysmon.library",1)) == NULL)
  { PutStr("ExcptTest: Couldn't open sysmon.library V1\n");
    cleanexit(20);
  }

  smDisallowExcept();			/* Block exceptions for now */
  oldexcept = myproc->pr_Task.tc_ExceptCode;
  myproc->pr_Task.tc_ExceptCode = (APTR)myexcept;	/* Set our exception code */
  SetExcept(SIGBREAKF_CTRL_C|SIGBREAKF_CTRL_F, SIGBREAKF_CTRL_C|SIGBREAKF_CTRL_F); /* Activate CTRL_C and CTRL_F as exception signals */
  smAllowExcept();			/* Exceptions now allowed */

  PutStr("Sleeping, Type CTRL_C or CTRL_F to quit\n");

  while (!done) smHibernate();		/* Rrrrr... Pffffff.... */

  PutStr("Woken up by CTRL_F, exiting\n");

  smDisallowExcept();		/* Block exceptions again for cleanup */
  SetExcept(0, SIGBREAKF_CTRL_C|SIGBREAKF_CTRL_F);	/* Deactivate exception signals */
  myproc->pr_Task.tc_ExceptCode = oldexcept;	/* Restore old exception code */
  smAllowExcept();

  cleanexit(0);
}

static ULONG __saveds __asm myexcept(register __d0 ULONG excptsigs, register __a1 APTR excptdata)
{
  if (excptsigs & SIGBREAKF_CTRL_F)	/* CTRL_F received */
  { done = TRUE;	/* Tell the main code it's time to exit */
    smWakeUp((struct Task*)myproc);
  }
  if (excptsigs & SIGBREAKF_CTRL_C)	/* CTRL_C received */
  { PutStr("BREAK\n");
    smEndExcept(FALSE);		/* Prepare for exit, does an implicit smDisallowExcept() */
    SetExcept(0, SIGBREAKF_CTRL_C|SIGBREAKF_CTRL_F);	/* Deactivate exception signals */
    myproc->pr_Task.tc_ExceptCode = oldexcept;		/* Restore old exception code */
    smAllowExcept();		/* Don't forget this one */
    cleanexit(5);		/* byebye... */
  }

  return excptsigs;	/* for compatibility with exec */
}

static void cleanexit(int rc)
{
  if (SysmonBase) CloseLibrary((struct Library *)SysmonBase);
  exit(rc);
}
