#include "mmix.h"

static bool init_done=0;
static struct termios told;
struct termios tnew;

void tty_mode_init(void) {
 init_done=1;

 if (tcgetattr(0, &told))
  mmix_error(ERR_TERM);

 tnew = told;
 tnew.c_lflag &= ~(ICANON|ECHO|ECHOE|ICRNL); /* we want it this way |ISIG*/
 tnew.c_cc[VMIN] = 1; /* return after 1 char */
 tnew.c_cc[VTIME] = 0;/* don't wait */

 if (tcsetattr(0, TCSANOW, &tnew))
  mmix_error(ERR_TERM);
 draw(T_INIT); tty_resize(0);
}

void tty_mode_restore(void) {
 if (init_done) {
  if (tcsetattr(0, TCSANOW, &told))
   mmix_error(ERR_TERM);
  draw(T_QUIT);
 }
 draw_flush();
}

void tty_resize(int unused) {
 set(U_ALL);
 draw_flush();
}

void tty_getsize(short *x, short *y) {
 volatile struct winsize ws;
 if (ioctl(1, TIOCGWINSZ, &ws)!=-1) {
  *x = ws.ws_col; *y = ws.ws_row; return;
 }
 mmix_error(ERR_TERM);
}
