#include <exec/exec.h>
#include <exec/types.h>
#include <exec/memory.h>
#include <dos/dos.h>
#include <dos/dosasl.h>
#include <dos/dostags.h>
#include <dos/notify.h>
#include <dos/rdargs.h>

#include <clib/exec_protos.h>
#include <clib/dos_protos.h>

extern struct ExecBase *SysBase;
static UBYTE   *VersTag = "\0$VER: SNoti 1.0 (28.05.96)";
struct Process *me;
struct CommandLineInterface *cli;
static char buffer[256];
ULONG storage = 0L;

main()
{

    struct RDArgs  *readargs;
    LONG            rargs[4];
    struct NotifyRequest *notifyrequest;
    UBYTE          *filename;
    ULONG           signr, signal;
    ULONG           initial;

 initial = 0L;
 rargs[2] = 0L;
 if (readargs = ReadArgs("Filename/A,Command/A,I=Initial/S,Taskname/K", rargs, NULL)) {
  filename = (UBYTE *) (rargs[0]);
  if((BOOL)rargs[2]!=FALSE) {
   initial = NRF_NOTIFY_INITIAL;
  }
  if(strlen(rargs[3])!=NULL) {
   me = (struct Process *)FindTask(NULL); /* Bad. But I KNOW this is a process. */

   buffer[0] = strlen(rargs[3]);
   if(buffer[0] > 30) {
    buffer[0] = 30;
   }
   strncpy(&buffer[1], rargs[3], 30);
   cli = BADDR( me->pr_CLI );
   storage = cli->cli_CommandName;
   cli->cli_CommandName = MKBADDR( buffer );
  }

  /* Allocate a NotifyRequest structure */
  if (notifyrequest = AllocMem(sizeof(struct NotifyRequest), MEMF_CLEAR)) {

   /* And allocate a signalbit */
   if ((signr = AllocSignal(-1L)) != -1) {

    /* Initialize notification request */
    notifyrequest->nr_Name = filename;
    notifyrequest->nr_Flags = NRF_SEND_SIGNAL | initial;

    /* Signal this task */
    notifyrequest->nr_stuff.nr_Signal.nr_Task =
        (struct Task *) FindTask(NULL);

    /* with this signal bit */
    notifyrequest->nr_stuff.nr_Signal.nr_SignalNum = signr;

    if ((StartNotify(notifyrequest)) == DOSTRUE) {

     /* Loop until Ctrl-C to exit */
     for (;;) {
      signal = Wait(1L << signr | SIGBREAKF_CTRL_C);
      if (signal & (1L << signr))
       SystemTags((char *)rargs[1],TAG_END);
       /*VFPrintf(Output(), "Notification signal!\n", NULL);*/
      if (signal & SIGBREAKF_CTRL_C) {
       EndNotify(notifyrequest);
       PrintFault(ERROR_BREAK, NULL);
       if(storage != NULL) {
        cli->cli_CommandName = storage;
       }
       break;
      }
     }
    } else PrintFault(ERROR_NOT_IMPLEMENTED, NULL);    /* most logical */
    FreeSignal(signr);
   }
   else VFPrintf(Output(), "No signal available\n", NULL);
   FreeMem(notifyrequest, sizeof(struct NotifyRequest));
  }
  else PrintFault(ERROR_NO_FREE_STORE, NULL);
  FreeArgs(readargs);
 } else {
  printf("Usage: SNoti Filename/A,Command/A,I=Initial/S,Taskname/K\n");
  exit(20);
 }
 exit(0);
}
