
/* Placed in the public domain by the author David Kinzer */

#include "exec/types.h"
#include "exec/nodes.h"
#include "exec/lists.h"
#include "exec/ports.h"
#include "exec/libraries.h"
#include "exec/devices.h"
#include "exec/io.h"
#include "devices/serial.h"
#include "hardware/cia.h"

main(ac,av)
int ac;
char *av[];

{

unsigned char status = CIAF_COMCD;
unsigned char newstat;

   if (ac < 2) return;

   for (;;) {

      /* wait until the carrier detect bit makes a high to low */
      /* transition indicating new carrier detect.  */

      newstat = ciab.ciapra & CIAF_COMCD;
      if (newstat != status) {
         status = newstat;
         if (status) {
            /* ignore this, phone just hung up */
         } else {
            /* the carrier detect just came up */
            /* check serial device to see if anyone else is using */
            /* this.  If so, we ignore, else, we fire up the task */

            if (openamigaserial()) {
               /* it errored, someone else is using */
            } else {
               /* ours, close serial device, and start routine */
               closeamigaserial();
               Execute(av[1],0L,0L);
            }

         }
      }

      /* Delay a while, ain't multitasking easy? */
      Delay(150L);
   }
}


/* Standard Amiga Serial Port Routines */

static struct Port *mySerPort;
struct IOExtSer *mySerReq;

int openamigaserial()
{
int gotport = 0;
int gotextio = 0;
long error;
long OpenDevice();
VOID *CreateExtIO();
struct Port *CreatePort();


   mySerPort = CreatePort("mySerial",0L);
   if (mySerPort == NULL) 
      goto errorexit;
   gotport = 1;

   mySerReq = (struct IOExtSer *)CreateExtIO(mySerPort,
              (long)sizeof(struct IOExtSer));
   if (mySerReq == NULL) 
      goto errorexit;
   gotextio = 1;

   error = OpenDevice("serial.device",0L,mySerReq,0L);
   if (error) 
      goto errorexit;

   return 0;  /* return success */


errorexit:
   if (gotextio) 
      DeleteExtIO(mySerReq,sizeof(struct IOExtSer));
   if (gotport)
      DeletePort(mySerPort);

   return 1;  /* return error */

}

closeamigaserial()
{
   CloseDevice(mySerReq);
   DeleteExtIO(mySerReq,sizeof(struct IOExtSer));
   DeletePort(mySerPort);
}

