#include <windows.h>
#include <stdio.h>
#include <sys/termio.h>
#include <sys/ioctl.h>
#include <sys/fcntl.h>
#include <signal.h>
static struct termio tmp1;
static struct termio tmp2;

void termcanon(){
   ioctl(fileno(stdin), TCSETAF, &tmp2);
   signal(SIGHUP, SIG_DFL);
   signal(SIGTERM, SIG_DFL);
   signal(SIGINT, SIG_DFL);
   signal(SIGPIPE, SIG_DFL);
}

void termraw(){
    /* set it up the way we want it */
    ioctl(fileno(stdin), TCGETA, &tmp1);
    ioctl(fileno(stdin), TCGETA, &tmp2);
    tmp1.c_iflag &= ~ICRNL;
    tmp1.c_iflag &= ~IXON;
    tmp1.c_lflag &= ~ISIG;
    tmp1.c_lflag &= ~ICANON;
    tmp1.c_lflag &= ~ECHO;
    tmp1.c_iflag &= ~IGNBRK;
    tmp1.c_iflag &= ~BRKINT;
    ioctl(fileno(stdin), TCSETAF, &tmp1);
    signal(SIGHUP, SIG_IGN);
    signal(SIGTERM, SIG_IGN);
    signal(SIGINT, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);
}

void settermout(void){
  setvbuf( stdout, NULL, _IONBF, 0 ); /* no buffering */
}

int main(void){
int n=0;
 settermout();
 termraw();
 printf("cygwin/gnu XFree86 key banger.\r\n");
 printf("Shows emitted characters for a keypress\r\n");
 printf("Press a key. Quit with q, Q or ctrl-c.\r\n");
 while(1){
  int x;
  x=getchar(); 
  if(x=='\033' || x == '\r'){if(n) printf("\r\n"); n=0;}
  if(isprint(x)) printf("%c",x); else printf("[0x%02x]",x);
  if(++n==10){ printf("\r\n"); n=0;}
  if(x=='q' | x=='Q') break;
 }
 printf("\r\n");
 termcanon();
 return 0;
}
