#include <vgamouse.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <curses.h>
#include <sys/time.h>
#include <sys/times.h>
#include <sys/types.h>
#include <sys/stat.h>


static int mouse_fd;
static int keyboard_fd;


enum { NO_EVENT, KEYBOARD_EVENT, MOUSE_EVENT }; 


int get_event(int *val, int *x, int *y, int timeout)
{ 
  struct timeval tv;
  fd_set rfds;
  int f = ((mouse_fd > keyboard_fd) ? mouse_fd : keyboard_fd) + 1;

  FD_ZERO(&rfds);
  FD_SET(mouse_fd,&rfds);
  FD_SET(keyboard_fd,&rfds);
  tv.tv_usec = timeout;
  tv.tv_sec = 0;

  if (timeout == 0)
     select(f,&rfds,NULL,NULL,NULL);
  else
    if (select(f,&rfds,NULL,NULL,&tv) <= 0) return NO_EVENT;

  if (FD_ISSET(keyboard_fd,&rfds)) { 
    char c;
    read(keyboard_fd,&c,1);
    *val = c;
    return KEYBOARD_EVENT;
   }

  if (FD_ISSET(mouse_fd,&rfds)) { 
    mouse_waitforupdate();
    *x = mouse_getx();
    *y = mouse_gety();
    *val = mouse_getbutton();
    return MOUSE_EVENT;
   }

}




main()
{ 
  mouse_fd = mouse_init_return_fd("/dev/mouse",MOUSE_PS2,150);
/*
  keyboard_fd = open("/dev/console",O_RDONLY | O_NONBLOCK | O_CBREAK);
*/
  keyboard_fd = 0;
  cbreak();
  noecho();
/*
  if ( mouse_init("/dev/mouse",MOUSE_PS2,150) != 0 )
  { printf("\nCannot open mouse device ?)\n\n");
    exit(1);
   }
*/


  for(;;) 
  { int val,x,y;
    int k = get_event(&val,&x,&y,0);
    printf("k = %d  val = %d x = %d  y = %d\n",k,val,x,y);
    if (k == KEYBOARD_EVENT && val == 27) break;
  }


  nocbreak();
  echo();
  mouse_close();

  return 0;
}

