/***                  LISTING 8               ***/
/***                                          ***/
/***                   term.c                 ***/
/*** **************************************** ***/
/***              TERMINAL PROGRAM            ***/
/*** **************************************** ***/

#include <string.h>
#include <stdlib.h>
#include "serial.h"

#define ESC  0x1B
#define CR   0x0D
#define LF   0x0A

#define ASCII  0x007F
#define BINARY 0x00FF

void main(int argc, char *argv[])
{
 int comport;
 long baud;
 int parity;
 int databits;
 int stopbits;
 int done = 0;
 int Err  = 0;
 int flag = 0;
 int Char_Value;

 /* If NO parameters are passed list the syntax */

 if(argc == 1)
  {
   printf("\nSyntax  TERM [comport] [baud] [parity]"
	  " [databits] [stopbits] [P or I]\n\n");

   printf("      [comport]    = 1 - 4\n");
   printf("      [baud]       = 1 - 115200\n");
   printf("      [parity]     = N - None\n");
   printf("                   = E - Even\n");
   printf("                   = O - Odd\n");
   printf("      [databits]   = 5 - 8\n");
   printf("      [stopbits]   = 1 - 2\n");
   printf("      [P or I]     = P - Polled\n");
   printf("                   = I - Interrupt\n");
  }

 /*           Else RUN terminal program         */

 else
  {
   /*          Set parameter variables          */

   comport  = atoi(argv[1]) - 1;
   baud     = atol(argv[2]);
   databits = atoi(argv[4]);
   stopbits = atoi(argv[5]);


   if(strcmpi(argv[3],"N") == 0)
       parity = NO_PARITY;

   else if(strcmpi(argv[3],"E") == 0)
       parity = EVEN_PARITY;

   else if(strcmpi(argv[3],"O") == 0)
       parity = ODD_PARITY;

    /*** Flag for Interrupt I/O ***/

   if(strcmpi(argv[6],"I") == 0)
       flag = 1;

   Err = SetSerial(comport,baud,parity,databits,stopbits);

   if(!Err)
     {
      printf("Terminal established ..."
			   "  ESC to exit... \n");
      Assert(DTR);

      if(flag)
	 InitSerial(comport); /*** Interrupt I/O ***/

      do
       {
	if(kbhit())
	 {
	  Char_Value = getch();

	  if(Char_Value == ESC)
	   {
	    if(flag)         /*** Interrupt I/O ***/
	      CloseSerial(comport);
	    Assert_Off(DTR);
	    done = 1;
	   }

	  else
	   {
	    SerialOut(Char_Value);
	    putch(Char_Value);

	    if(Char_Value == CR)
	      {
	       SerialOut(LF);
	       putch(LF);
	      }
	   }
	}

      if(flag)   /*** Interrupt I/O ***/
	{
	if((Char_Value = IntSerialIn()) != -1)
	  putch(Char_Value & ASCII);
	}

       else      /***   Polled I/O   ***/
	{
	 if((Char_Value = SerialIn()) != -1)
	    putch(Char_Value & ASCII);
	}
      }
     while(!done);
    }

   else
    printf("Error setting up port\n");
  }
}
