#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <curses.h>
#include <signal.h>

void initcurses(void) {
  // Initialize curses:
  initscr();
  // Make sure terminal is in 8 bit (CS8) mode:
  meta(stdscr,TRUE);
  // Disable line buffering and erase/kill character handling:
  cbreak();
  // Turn off keyboard echo:
  noecho();
  // Turn on colorization:
  start_color();
  // Initialize color-pairs:
  for(int i=0; i < 8; i++)
    for(int j=0; j < 8; j++)
      init_pair(i<<3|j, i, j);
  // Disable output flush on keyboard interrupt:
  intrflush(stdscr, FALSE);
  // Enable the keypad
  keypad(stdscr, TRUE);
  // Enable mouse events if the terminal supports them:
  mousemask(ALL_MOUSE_EVENTS|REPORT_MOUSE_POSITION, NULL);
  // Clear the screen:
  clear();
  // updates the screen to reflect changes made to the internal state:
  refresh();
}

void cleanup(int s) {
  echo();
  nocbreak();
  endwin();
}

int main(int argc, char *argv[])
{
  struct sigaction sa;
  WINDOW *top, *bot;
  int i, rows, ch;
  
  sa.sa_handler = cleanup;
  for(int i=1; i <= 32; i++) sigaction(i, &sa, NULL);

  initcurses();
  // LINES and COLS represent the current size of the terminal:
  rows = (LINES - LINES%2 -1)/2;
  // Create a new window at the top half of the screen:
  top = newwin(rows, COLS, 0, 0);
  // Turn scrolling on for the top window:
  scrollok(top, 1);
  // Add a row of ---'s across the middle of the screen:
  for(i=0; i < COLS; i++)
    mvaddch(rows+1, i, '-');
  // Create a bottom window:
  bot = newwin(rows, COLS, rows+2, 0);
  scrollok(bot, 1);
  // Update the screen:
  refresh();

  while ((ch = getch()) != EOF) {
    waddch(top, ch);
    wrefresh(top);
    waddch(bot, ch);
    wrefresh(bot);
  }
}
