/*

    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

    22.7.1996 -- Added support for arbitrary device (such as gvpser.device) and units.
                 : Udo Schuermann <walrus@uga.umd.edu>

    22.7.1996 -- Redid that support to use ReadArgs and to save 7k - BM :)
*/

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

#define __USE_SYSBASE

#define IgnoreType (void *)

#define VERSIONTEXT "CheckCarrier V1.1 " __AMIGADATE__
const char Version[] = "$VER:" VERSIONTEXT;
#define TEMPLATE "D=Device/K,U=Unit/N"

int     SerialOpen;	
int     fail;

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

void    OpenAll(char *, long);
void    CloseAll( void );

int __saveds main(void)
{
  long 	result = 0;
  long   args[2];
  char  *Device;
  long   Unit;
  struct RDArgs *rdptr;
  
  struct DosLibrary *DOSBase = (struct DosLibrary *) OpenLibrary("dos.library", 0L);
  struct ExecBase *SysBase = (*((struct ExecBase **) 4));
  
  args[0] = 0;
  args[1] = 0;

  rdptr = ReadArgs(TEMPLATE, args, NULL);

  Device = args[0] ? (char *) args[0] : "serial.device";
  Unit = args[1] ? *((long *) args[1]) : 0;

  OpenAll(Device, Unit);

  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");

  FreeArgs(rdptr);
  CloseLibrary((struct Library *) DOSBase);
  CloseLibrary((struct Library *) SysBase);

  return ((result & (1 << 5)) ? 5 : 0);
}

void OpenAll(char *Device, long Unit)
{
  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;
}

