#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <unix.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h> // IO Control of socket.
#include "System.h"
#include "Syslog.h"
#include "AtsDriver.h"

//
////////////////////////////////////////////////////////////////////////////////
//
// PURPOSE:  To start up the AtsDriver task.
// AUTHOR:   Rich Henthorn
// DATE:     06/07/07
// COMMENTS: 
//
////////////////////////////////////////////////////////////////////////////////
//
//

void signalHandler(int signalNo);
void cleanup();

AtsDriver *atsdriver = 0;

int main( int argc, char **argv )
{

  signal(SIGINT,  signalHandler);
  signal(SIGTERM, signalHandler);
  signal(SIGQUIT, signalHandler);
  atexit(cleanup);
  // Set task priority
  if (System::setTaskPriority(NonCriticalDriverPriority) == -1)
    return 1;

  int port = -1;
  Boolean verbose = False;
  for (int i = 1; i < argc; i++) {
    if (!strcmp(argv[i], "-v")) 
      verbose = True;
    else
      port = atoi(argv[i]);
  }
  
  if (port != -1) printf("Using port %d\n", port);
  try {
    if (port != -1) atsdriver = new AtsDriver(port);
    else            atsdriver = new AtsDriver();
    
    atsdriver->setVerbose(verbose);
    if (0 == atsdriver->init())
    {
      atsdriver->run();
    }
    else
      exit(0);
  }
  catch (Exception e) {
    Syslog::write("%s - caught Exception: %s\n", argv[0], e.msg);
  }
  catch (...) {
    Syslog::write("%s - caught unknown exception\n", argv[0]);
  }

  delete atsdriver;

  return 0;

}


void signalHandler(int signalNo)
{

  //  cleanup();
  exit(0);
}

void cleanup()
{
  delete atsdriver;
}
