#include <bios.h>
#include "f2c.h"

int sale_(char *qlin, ftnlen qlin_len);

const unsigned int timeout   = 1 << 15;
const unsigned int xmtsempty = 1 << 14;
const unsigned int xmthempty = 1 << 13;
const unsigned int didbreak  = 1 << 12;
const unsigned int framerr   = 1 << 11;
const unsigned int parityerr = 1 << 10;
const unsigned int overrun   = 1 <<  9;
const unsigned int dataready = 1 <<  8;

const unsigned int datamask  = 0x7f;
const unsigned int receiverr = timeout + didbreak + framerr + parityerr + overrun;

void setcom_ (char* portch)
{
   unsigned int stat;
   const unsigned int timeout = 1 << 15;
   int port = portch - '1';
   if (port < 0 || port > 7)
      sale_("Serial port not in range 1..8", 29L);
   stat = 
      _bios_serialcom(_COM_INIT, port, (_COM_CHR8|_COM_STOP1|_COM_NOPARITY|_COM_1200));
   if (stat & timeout)
      sale_("Timed out waiting for response from serial port", 47L);
}

void getcom_ (char* portch, char* buf, ftnlen buf_len)
{
   buf*    = '\0';
   buf_len = 0;
   int port;
   port = portch - '1';
   unsigned int status;
   status = _bios_serialcom(_COM_STATUS, port, 0);
   char ch;
   ch = ' ';
   while (!(status & receiverr) && (ch != '\n')) {
      while (!(status & (dataready+receiverr))) {
         status = _bios_serialcom(_COM_STATUS, port, 0);
      }
      if (!(status & receiverr)) {
         status = _bios_serialcom(_COM_RECEIVE, port, 0);
         if (!(status & receiverr)) {
            ch = status & datamask;
            if (ch && (ch != '\n')) {
               (portch++)* = ch;
               portch* = 0;
               q16_len++;
            }
         }
      }
   }
   if (status & receiverr)
      sale_("Error reading COM port", 22L);
}
