# include "dgd.h"
# include "str.h"
# include <sys/types.h>
# include <exec/types.h>
# include <exec/memory.h>
# include <exec/tasks.h>
# include <exec/interrupts.h>
# include <devices/timer.h>
# include <dos/dos.h>
# include <clib/alib_protos.h>
# include <clib/dos_protos.h>
# include <clib/exec_protos.h>
# include <stdio.h>
# include "alarm.h"

static bool timeout;  /* alarm timed out */

ULONG sys_signal_alarm = 0;   /* The signal mask allocated for alarm */
STKARGS void (*handler_alarm)(int);   /* The alarm handler */
STKARGS void (*handler_int)(int);     /* The ctrlc handler */

static struct timerequest *treq = NULL; /* the alarm()-timer */


/*
 * NAME:        start_timer
 * DESCRIPTION: start a timer on a given timerequest
 */
STKARGS int start_timer(struct timeval *tv, struct timerequest *tr) {
  if (!tr) {
    P_message("start_timer: no request structure\n");
    return 0;
  }

  if (tv->tv_secs == 0L && tv->tv_micro < 2L)
    tv->tv_micro = 2L; /* minimal delay */

  tr->tr_time = *tv;
  tr->tr_node.io_Command = TR_ADDREQUEST;

  SendIO ((struct IORequest *) tr);
  return 1;
}

/*
 * NAME:        setup_timer
 * DESCRIPTION: setup timerequest for later use
 */
STKARGS int setup_timer (LONG unit, struct timerequest **tr) {
  struct MsgPort *timerport;
  struct timerequest *req;

  if (*tr) return 1;

  if (!(timerport = (struct MsgPort *)CreatePort(0L, 0L))) {
    *tr = NULL;
    P_message("setup_timer: could not create port\n");
    return 0;
  }

  if (!(req = (struct timerequest *) CreateExtIO (timerport
                                                 , sizeof(struct timerequest))
     )) {
    DeletePort(timerport);
    *tr = NULL;
    printf("setup_timer: could not get request\n");
    return 0;
  }

  if (OpenDevice (TIMERNAME, unit, (struct IORequest *) req, 0L)) {
    CloseDevice( (struct IORequest *) req);
    DeleteExtIO( (struct IORequest *) req);
    DeletePort(timerport);
    P_message("setup_timer: could not open timer\n");
    *tr = NULL;
    return 0;
  }
  *tr = req;
  return 1;
}

/*
 * NAME:        cleanup_timer
 * DESCRIPTION: cleanup (after aborting) a timerequest
 */
STKARGS void cleanup_timer (struct timerequest **tr) {
  struct MsgPort *tp;
  struct timerequest *tmp;
  UBYTE pFlags;

  if (*tr) {
    tmp = *tr;
    tp = tmp->tr_node.io_Message.mn_ReplyPort;
    if (tp) {
        /* abort the current request */
      pFlags = tp->mp_Flags; /* still needed for DeletePort */
      tp->mp_Flags = PA_IGNORE;
      AbortIO( (struct IORequest *) tmp );
      WaitIO( (struct IORequest *) tmp );
      while(GetMsg(tp));
      Forbid();
      tp->mp_Flags = pFlags;
      DeletePort(tp);
      Permit();
    }
    CloseDevice( (struct IORequest *) tmp );
    DeleteExtIO( (struct IORequest *) tmp );
  }
  *tr = NULL;
}

/*
 * NAME:        cleanup_alarm
 * DESCRIPTION: cleanup the alarm timer on shutdown
 */
STKARGS void cleanup_alarm () {
  cleanup_timer(&treq);
}

/*
 * NAME:        alarm
 * DESCRIPTION: cause an alarm signal to occur after the given number of
 *              seconds
 */
static STKARGS unsigned int alarm (unsigned int seconds) {
  static struct timeval tv;
  static first = 1;

  if (!treq) {
    P_message("alarm: No handler installed !\n");
    return 0;
  }

  tv.tv_secs = seconds;
  tv.tv_micro = 0;

  if (seconds > 0) {
      /* first call of alarm() : WaitIO on unsent request ..... */
    if (!first) {
      treq->tr_node.io_Message.mn_ReplyPort->mp_Flags = PA_IGNORE;
      AbortIO( (struct IORequest *) treq);
      WaitIO( (struct IORequest *) treq);
      treq->tr_node.io_Message.mn_ReplyPort->mp_Flags = PA_SIGNAL;
    }
    first = 0;
    start_timer (&tv, treq);
  }
  else {
    /* if I don't use this code, AbortIO will generate a signal, which will
     * trigger catch_alarm. catch_alarm will then generate CTRL-E. This
     * can be resolved by preventing the signal to occur :-)
     */
    treq->tr_node.io_Message.mn_ReplyPort->mp_Flags = PA_IGNORE;
    AbortIO( (struct IORequest *) treq);
    WaitIO( (struct IORequest *) treq);
    cleanup_timer (&treq);
    first = 1;
  }
  return 0;
}

/*
 * NAME:        check_signals
 * DESCRIPTION: manually check if the OS signalled us
 */
STKARGS ULONG check_signals ( void )
{
  static int _ChkSignalLockout = 0;  /* simple semaphore */
  ULONG mask;

  if (_ChkSignalLockout) return 0L;
  ++_ChkSignalLockout;

  mask = ((struct Task *)FindTask(NULL))->tc_SigRecvd;

    /* Default Ctrl-C handling */
  if (mask & SIGBREAKF_CTRL_C) {
    write(2, "*** Break.\n", 11);
    (*handler_int)(0);
    SetSignal (0L, SIGBREAKF_CTRL_C);
  }

    /* Handle our special exceptions */
  if (mask & sys_signal_alarm) {
    (*handler_alarm)(0);
    SetSignal (0L, sys_signal_alarm);
  }
  --_ChkSignalLockout;
  return mask;
}

/*
 * NAME:        intr
 * DESCRIPTION: catch an alarm interrupt
 */
static STKARGS void intr(arg)
int arg;
{
    timeout = TRUE;
}

/*
 * NAME:        P->alarm()
 * DESCRIPTION: cause an alarm signal to occur after the given number of
 *              seconds
 */
STKARGS void P_alarm(delay)
unsigned int delay;
{
    if (!sys_signal_alarm) {
        ULONG sigalrm;
        if (!setup_timer (UNIT_VBLANK, &treq)) {
            P_message("P_alarm: Could not setup_timer\n");
        }
        else {
            sigalrm = 1L << (treq->tr_node.io_Message.mn_ReplyPort->mp_SigBit);

            ((struct Task *)FindTask(NULL))->tc_ExceptCode = (APTR) catch_exception;
            sys_signal_alarm = sigalrm;
            handler_alarm = intr;
            SetExcept (sigalrm, sigalrm);
        }
    }
    timeout = FALSE;
    alarm(delay);
}

/*
 * NAME:      P->timeout()
 * DESCRIPTION:       return the value of the timeout flag
 */
bool P_timeout()
{
    return timeout;
}

