/*

    CheckCarrier - Program to Query the serial port and check the status of
    the carrier detect bit.

    (C) 1996 Byron Montgomerie.

    bmontgom@morgan.ucs.mun.ca

*/

#include <exec/types.h>
#include <exec/execbase.h>
#include <proto/exec.h>
#include <proto/dos.h>
#include <devices/serial.h>
#include <string.h>

#define __USE_SYSBASE

#define IgnoreType (void *)

#define VERSIONTEXT "CheckCarrier V1.0 " __AMIGADATE__
const char Version[] = "$VER:" VERSIONTEXT;

char   *Device = "serial.device";
int     Unit = 0;

int     SerialOpen;	
int     fail;

struct MsgPort *SerialPort = NULL;	
struct IOExtSer *SerialIO = NULL;	
struct IOExtSer *CommandIO = NULL;

void    OpenAll( void );
void    CloseAll( void );

int __saveds main(void)
{
	long 	result = 0;

   struct DosLibrary *DOSBase = (struct DosLibrary *) OpenLibrary("dos.library", 0L);
   struct ExecBase *SysBase = (*((struct ExecBase **) 4));

	OpenAll();
   
   if (!fail)
   {
	   CommandIO->IOSer.io_Command = SDCMD_QUERY;
	   CommandIO->IOSer.io_Actual = 0;

	   if (DoIO(IgnoreType CommandIO) != NULL)
		   CloseAll();
      else
         result = CommandIO->io_Status;
   }

	CloseAll();

   PutStr((result & (1 << 5)) ? "No\n" : "Yes\n");

   CloseLibrary((struct Library *) DOSBase);
   CloseLibrary((struct Library *) SysBase);
}

void OpenAll(void)
{
   SerialOpen = FALSE;
   fail = FALSE;

	if ((SerialPort = (struct MsgPort *) CreateMsgPort()) != NULL &&
	    (SerialIO = (struct IOExtSer *) CreateExtIO(SerialPort, sizeof(struct IOExtSer))) != NULL &&
	    (CommandIO = (struct IOExtSer *) CreateExtIO(SerialPort, sizeof(struct IOExtSer))) != NULL &&
	    (SerialOpen = !OpenDevice(Device, (long) Unit, IgnoreType SerialIO, 0L)) == NULL)
      CloseAll();
   else
      memcpy(CommandIO, SerialIO, sizeof(struct IOExtSer));
}

void CloseAll()
{
   if (fail)
      return;

	 if (SerialOpen)
		CloseDevice(IgnoreType SerialIO);

	if (CommandIO)
		DeleteExtIO(IgnoreType CommandIO);

	if (SerialIO)
		DeleteExtIO(IgnoreType SerialIO);

	if (SerialPort)
		DeleteMsgPort(SerialPort);

   fail = TRUE;
}
