/*************************************************************************
 ***                        io.c                         (JJB TEMPLAR) ***
 *** Date modifications begun: 7/8/89.                                 ***
 *** Last modified: 8/8/89.                                            ***
 *************************************************************************/
/*** Used to be MicroEMACS AmigaDOS (V31) terminal I/O. Hmmm.          ***
 *************************************************************************/

#include <exec/types.h>

#include "win.h"

#define   NOBUF   512      /* Not too big for 750/730.   */

int     tty;
char    obuf[NOBUF];    /* Output buffer */
int     nobuf;          /* # of bytes in above */

void    ttopen();
void    ttclose();
void    ttputc(int);
void    ttflush();
void    ttputs(char *);
void    tputs(char *);

void    ttopen() /*======================================================*/
{                /* Open terminal channel.                               */
    if (tty) return;    /* Already open. */
    nobuf = 0;
    tOpen();            /* Will die appropriately if failure occurs. */
}

void    ttclose() /*=====================================================*/
{
    if (tty) {
        ttflush();
        tClose();       /* Error resistant. Also sets tty to NULL. */
    }
}

void    ttputc(c) /*=====================================================*/
int     c;        /* Write char to display.                              */
{
    if (nobuf >= NOBUF) ttflush();  /* Out of buffer, flush. */
    obuf[nobuf++] = c;              /* Else just put in buffer. */
}

void    ttflush() /*=====================================================*/
{                 /* Output buffer, reset counter.                       */
    if (nobuf > 0) {
        tWrite(obuf,nobuf);   /* Go! */
        nobuf = 0;
    }
}

void    ttputs(s) /*=====================================================*/
register char *s; /* Output a string to the terminal.                    */
{
    while (*s) ttputc(*s++);
    ttflush();
}

void    tputs(s) /*======================================================*/
char *s;
{
    if (!tty) ttopen();
    flush();
    ttputs(s);  /* Pass it on... */
}
