/*
 * 4m v2.15 (print.c)
 * (C) Copyright 1990 by Carrick Sean Casey
 * (C) Copyright 1993 by Scott Chasin and Michaeljon Miller
 *
 * 3-24-93 See file COPYING for copyright information.
 *
 * Printing and graphical routines
 */

#include "4m.h"
#include "externs.h"

#include "../h/term.h"

extern FILE *logfp;
extern void (*t_scroll) ();

/* write to the screen, and maybe to the logfile and review buffer */


void pauseprompt ();
extern int fputs ();
extern int _flsbuf ();
extern int write ();
extern int fflush ();
extern int _filbuf ();


extern void pushback ();


extern void bufferadd ();

void putl(s, flags)
     char *s;
     int flags;
{
    char printbuf[1024];
    char *p = printbuf;
    char *t = s;

    if (!dumb && flags & PL_SCR) {
        hidecursor();
        cpos++;
    }
    if (continued) {
        linenumber = 0;
        continued = 0;
    }
    if (flags & PL_SCR) {
    /* if paging in effect, do paging */
        if (gv.pagesize && (++linenumber >= gv.pagesize)) {
            pauseprompt("[more]", 1, 0, 1, ' ');
            linenumber = 0;
        }
    /* write to the screen */
        while (*t != '\0')
            *p++ = *t++;

        *p++ = '\r';
        *p++ = '\n';

    }
 /* put line into session log */
    if ((flags & PL_LOG) && logfp != NULL) {
        fputs(s, logfp);
        putc('\n', logfp);
    }
 /* add to review buffer */
    if ((flags & PL_BUF) && gv.bufferlines)
        bufferadd(s);

    if (!dumb && t_scroll && (flags & PL_SCR)) {
        if (cpos > lines - 5) {
            t_scroll(1, lines - 4, 1);
            cpos = lines - 4;
        }
        gotoxy(ipos, lines - 2);
    }
    if (!dumb & flags & PL_SCR) {
        showcursor();
        gotoxy(0, cpos);
    }
    write(1, printbuf, p - printbuf);
    fflush(stdout);

    if (!dumb & flags & PL_SCR)
        gotoxy(ipos, lines - 2);

    return;
}


/* print a prompt, and wait for a character */
/* if erase is nonzero, the prompt is erased by backspacing */
/* if c is non-null, use must type c to continue */
/* if unget it set, user's character is pushed back into input buffer */

void pauseprompt(prompt, erase, c, unget, except)
     char *prompt;
     int erase;
     char c;
     int unget;
     char except;
{
    char uc, *p;

 /* print the prompt */

    setinverse();
    write(1, prompt, strlen(prompt));
    setnormal();
    if (c != '\0')
        while ((uc = getchar()) != c);
    else
        uc = getchar();

 /* erase the prompt if requested */
    if (erase) {
        char erasebuf[512];
        char *m = erasebuf;

        for (p = prompt; *p != '\0'; p++) {
            *m++ = '\b';
            *m++ = ' ';
            *m++ = '\b';
        }
        write(1, erasebuf, m - erasebuf);
    } else
        write(1, "\n", 1);

 /* push character back onto stream if requested */
    if (unget)
        if (except == '\0' || uc != except)
            pushback(uc);

    fflush(stdout);

    return;
}
