/* Release 3.10 */
/*-------------------------------------------------------------------------*
*                                                                          *
*  CONIOSTR.CPP - console I/O stream class implementations.                *
*                                                                          *
*  COPYRIGHT (C) 1989..1992 Clarion Software Corporation.                  *
*  All Rights Reserved                                                     *
*                                                                          *
*--------------------------------------------------------------------------*/

#define _USE_CONIO
#include <clib.h>
#include <coniostr.hpp>


#pragma module(init_prio=>22)

extern "C" void _init_con(void) {

  conout.setf(ios::unitbuf);
}

static conbuf inbuf;
static conbuf outbuf;

istream conin(&inbuf);
ostream conout(&outbuf);

int conbuf::underflow() {

  #define CGETS_MAX_NR 255 /* new line */

  int nr, c;
  char *buf;

  nr=ebuf()-eback();
  if(nr == 1) {
    c=getche();
    if(c == EOF) {
      return EOF;
    }
    *eback()=c;
  }
  else {
    if (nr > CGETS_MAX_NR)  /* new line */
      nr = CGETS_MAX_NR;   /* new line */

    buf=new char[nr+3];
    buf[0]=nr;
    cgets(buf);
    nr=buf[1];
    memcpy(eback(), buf+2, nr);   /* corrected line */

    delete buf;
  }
  setg(eback(), eback(), eback()+nr);
  return *gptr();

  #undef CGETS_MAX_NR   /* new line */

}

int conbuf::pbackfail(int c) {

  return ungetch(c);
}

extern "C" unsigned _flush_init_magic;

int conbuf::overflow(int c) {

  char *pt;
  int nw;

  flush_magic=_flush_init_magic;
  if(unbuffered()) {
    if((c == EOF) || (putch(c) == EOF)) {
      return EOF;
    }
  }
  else {
    pt=pbase();
    nw=pptr()-pt;
    while(nw--) {
      if(putch(*pt) == EOF) {
        return EOF;
      }
      ++pt;
    }
  }
  setp(pbase(), epptr());
  if((c != EOF) && (!unbuffered()))
    sputc(c);
  return c;
}

int conbuf::sync() {

  overflow();
  setp(base(), ebuf());
  setg(base(), ebuf(), ebuf());
  return 0;
}

