
/*  Provides the TTY functions for MS-ForTran  */
#include <dos.h>
#include <conio.h>

/*  call TTY  */
	void far fortran TTY()
	#define Vint 0x10
	{
	  union REGS inregs, outregs;

	  inregs.h.ah = 0;
	  inregs.h.al = 3;
	  int86( Vint, &inregs, &outregs );
	}


/*  if( ChrRdy(0) ) then ...  */
	char far fortran ChrRdy( dummy )
	  int *dummy;
	{
	  int result;

	  result = kbhit();
	  if( result == 0 ) return (0);
	  else return (-1);
	}


/*  call TTYO( ASCII code )  */
	far fortran TTYO( ascii_code )
	  int *ascii_code;
	{
	  char character;

	  character = *ascii_code; 
	  putch( character );
	}


/* global variables for TTYIW(), TTYset, and TTYrst routines */
	static int EchoOn = -1;

/* call TTYset  */
	void far fortran TTYset()
	{
	  EchoOn = 0;
	}
/* call TTYrst */
	void far fortran TTYrst()
	{
	  EchoOn = -1;
	}

/* call TTYIW( key ) */
	far fortran TTYIW( key )
	  int *key;
	{

	  struct my_register
	  {
	    unsigned int AL:8;
	    unsigned int AH:8;
	  };

	  union copies
	  {
	    struct my_register AX;
	    int result;
	  };

	  union REGS inregs, outregs;
	  union copies a;
	  int temp_store;
	  static char SaveIt;
	  static int Extended = 0;
	  #define IOCALL 0x16
	  #define CONTROL_C 0x23

	  if( Extended ) 
	  { Extended = 0;
	    *key = SaveIt;
	    return;
	  }

/* don't read keyboard until char is there */
	  while( ! kbhit() ) ;

	  inregs.h.ah = 0;
	  a.result = int86( IOCALL, &inregs, &outregs );

	  if( a.AX.AL == 0 )
	  { SaveIt = a.AX.AH;
	    Extended = -1;
	    *key = 0;
	    return;
	  }

	  if( a.AX.AL == 3 )
	  { temp_store = a.result;
	    a.result = int86( CONTROL_C, &inregs, &inregs );
	    return;
	    if( inregs.x.cflag ) abort();
	    else a.result = temp_store;
	  }

	  else
	   if( EchoOn ) putch( a.AX.AL );

	  if( (a.AX.AL > 42 && a.AX.AL < 58) &&
	    (a.AX.AH > 70 && a.AX.AH < 84) )
	    { inregs.h.ah = 2;
	      temp_store = a.result;
	      a.result = int86( IOCALL, &inregs, &outregs );
	      if( a.AX.AL != 0x20 )
	      { a.result = temp_store;
	        if( a.AX.AL < 0x80 ) a.AX.AH = 0;
	        else a.AX.AH = 0xFF;
	        a.result = a.result * -1;
	        *key = a.result;
	        return;
	      }
	      else a.result = temp_store;
	    }

	  *key = a.AX.AL;
	}
