#include <tt8lib.h>
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
#include "izm.h"
#include "io_zmod.h"

extern jmp_buf  tohere;
extern ulong    modem_cts_ctr;

/****************************************************************************/
/* ZMODEM Systen Dependent I/O Primitives                                   */
/****************************************************************************/

/*
 *  Send a character to modem.  Small is beautiful.
 */
void sendline(register char c)
{
        register ulong  msTimeout;

        if( ModemIRQActive() == TRUE ){
          if( ModemCDActive() != TRUE )
            longjmp(tohere, RCDO);
          if( ModemCTSActive() == TRUE ){
            ++modem_cts_ctr;                      //keep track of CTS transitions
            msTimeout = (MilliSecs() + 30000L);   //set the timeout value in millisecs
            do{
              if(MilliSecs() > msTimeout)
                longjmp(tohere, CTSTIMEOUT);
              }while( ModemCTSActive() == TRUE );
            }
          }
        else
          SerPutByte(c);
}

void mputs(register char *s)
{
        while (*s)
          sendline(*s++);
}

/*
 * This version of readline is reasoably well suited for
 * reading many characters.
 *  (except, currently, for the Regulus version!)
 *
 * timeout is passed in tenths of seconds
 */

int readline(int timeout)
{
        long   msTimeout;
        short  d;
        msTimeout = (long) (timeout*100L);

        d=SerTimedGetByte(msTimeout);

        if(d == -1){                         //we got a timeout!
          if( ModemCDActive() != TRUE )      //are we still connected?
            longjmp(tohere, RCDO);
          else
            return( TIMEOUT );
          }

        return (d & 0377);
}


/*
 * Purge the device's input buffer for any characters
 */

int checkline(void)
{

        if( ModemIRQActive() == TRUE ){
          if( ModemCDActive() != TRUE )
            longjmp(tohere, RCDO);
           }
        else
          return (SerByteAvail());

}

/*
 * Purge the UART input buffer of all characters
 */

void purgeline(void)
{
        SerInFlush();
}




