/*
   Open and configure the serial port
   If successful return the file descriptor, otherwsie -1
*/
int OpenSerial(port)
char *port;
{
   int fd;
   struct termios opts;

   /* Attempt to open the serial port */
   if ((fd = open(port,O_RDWR | O_NOCTTY | O_NDELAY)) == -1)
      return(-1);

   tcgetattr(fd,&opts);
   opts.c_lflag &= ~(ICANON | ECHO | ISIG);
   opts.c_cflag |= (CLOCAL | CREAD);
   cfsetispeed(&opts,B38400);
   opts.c_cflag &= ~CNEW_RTSCTS;
   opts.c_iflag |= (INPCK | ISTRIP);
   opts.c_iflag |= (IXON | IXOFF | IXANY);
   opts.c_cflag &= ~CSIZE;
   opts.c_cflag |= CS8;
   opts.c_oflag &= ~OPOST;
   opts.c_cc[VMIN] = 1;
   opts.c_cc[VTIME] = 0;
   tcsetattr(fd,TCSANOW,&opts);

   return(fd);
}

/*
   Close the serial port
*/
void CloseSerial(fd)
int fd;
{
   close(fd);
}

/*
   Write to the serial port
   Return TRUE or FALSE depending on success.
*/
int SerialSend(fd,s)
int fd;
char *s;
{
   int i;
   int status;

   if ((status = write(fd,s,strlen(s))) != strlen(s))
      return(FALSE);
   return(TRUE);
}

/*
   Wait for dt seconds for a string s from the serial port
*/
int SerialWaitFor(fd,s,dt)
int fd;
char *s;
int dt;
{
   int i = 0,found = FALSE;
   time_t starttime,nowtime;
   char c[8],buffer[1024];

   buffer[0] = '\0';
   starttime = time(NULL);
   nowtime = starttime;
   while (nowtime - starttime < dt && i < 1000) {
      nowtime = time(NULL);
      if (read(fd,c,1) > 0) {
         if (c[0] == 0)
            c[0] = ' ';
         buffer[i++] = c[0];
         buffer[i] = '\0';
         if (strstr(buffer,s) != NULL) {
            found = TRUE;
            break;
         }
      }
   }

   return(found);
}

/*
   Clear all the stuff current in the serial input buffer
*/
void SerialClear(fd)
int fd;
{
   int i = 0;
   char c[8],buffer[1024];

   buffer[0] = '\0';
   while (read(fd,c,1) > 0 && i < 1000) {
      if (c[0] == 0)
         c[0] = ' ';
      buffer[i++] = c[0];
      buffer[i] = '\0';
   }
}

/*
   Attempt to force a hungup on the modem
*/
void HangUp(fd)
int fd;
{
   sleep(2);
   SerialSend(fd,"+++ATH0\r");
   /*sleep(2);
   SerialSend(fd,"ATH0\r");*/
   sleep(2);
   SerialClear(fd);
}


