#include <termios.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#ifdef __CYGWIN__
#include <ncurses/term.h>
#else
#include <term.h>
#endif

#define ERR -1

struct termios gTtySave;

void minitscr()
{
    struct termios t;
    int x,y;
    int i, j;

    tcgetattr(STDIN_FILENO, &gTtySave);
    
    if(setupterm(NULL, STDOUT_FILENO, (int*) 0) == ERR) {
        fprintf(stderr, "invalid TERM setting");
        exit(1);
    }
    
    tcgetattr(STDIN_FILENO, &t);

#ifdef ECHOPRT
    t.c_lflag &= ~(ICANON | ISIG | ECHO | ECHOCTL | ECHOE| ECHOK | ECHOKE
                         | ECHONL | ECHOPRT);
#else
    t.c_lflag &= ~(ICANON | ISIG | ECHO | ECHOCTL | ECHOE | ECHOK | ECHOKE
                  | ECHONL);
#endif

    t.c_iflag |= IGNBRK;
    t.c_iflag &= ~(IXOFF|IXON);
    t.c_cc[VMIN] = 6;
    t.c_cc[VTIME] = 1;
    t.c_cc[VLNEXT] = 0;
    t.c_cc[VDISCARD] = 0;
    tcsetattr(STDIN_FILENO, TCSANOW, &t);
}

void mendwin()
{
    tcsetattr(STDIN_FILENO, TCSANOW, &gTtySave);
}

int main()
{
    minitscr();

    putp(tigetstr("clear"));
    printf("hit q to quit\n");
    fflush(stdout);
   
    char buf[128];
    memset(buf, 0, 128);
    int n;
    while(buf[0] != 'q') {
        do {
            if((n = read(0, buf, 10)) < 0) {
                perror("read");
                exit(1);
            }
        } while(n == 0);

        for(int i=0; i<n; i++) {
            printf("(%d)", buf[i]);
        }
        printf("\n");
        fflush(stdout);
   }
   
   mendwin();

   return 0;
}
