#include 
#include 
#include 
#include 
#include 


#define nd 1
int main(){
  char buf[100];
  int fd,i,j,n,retval;
  struct mouse_state{
    int buttons;
    int dx;
    int dy;
  } state;

  fd_set rfds;
  struct timeval st;

  fd=open("/dev/psaux",O_RDONLY);
  if(fd<0){ 
        printf("mouse open error\n");
        return 1;
  } 

  for(i=0;i<1000;){
    for(j=0;j<3;j++){

      FD_ZERO(&rfds);
      FD_SET(fd, &rfds);
      st.tv_sec = 0;
      st.tv_usec = 50000;
      
      //      printf("Read from mouse\n");    
      retval = select(FD_SETSIZE, &rfds, NULL, NULL, &st);
      if(retval<=0) {
	//printf("Error: read time out.\n"); 
	break;
      }
      
      else{
	n=read(fd,buf+j,nd);
	printf("%02X ",(int)buf[j] & 0xff);
      }
    }
    if(j<2){
      if(j>0) printf("PS2 mouse read sequence error\n");
      continue;
    }
    printf("\n");
    i++;
    if(buf[0] & 0x08){
      state.buttons=buf[0]&0x7;
      if(buf[0] & 0x40) printf("X overflow ");
      if(buf[0] & 0x80) printf("Y overflow ");
      if(buf[0] & 0x10) state.dx=(int)(buf[1]|0xff00);
      else  state.dx=(int)(buf[1])&0xff;
      if(buf[0] & 0x20) state.dy=(int)(buf[2])|0xff00;
      else state.dy=(int)(buf[2])&0xff;
      printf(" buttons=%02X \tdx=%d \tdy=%d\n",state.buttons,state.dx,state.dy);
    }
    else {
      printf("Error data received from ps2 mouse.\n");
      break;
    }
  }
  close(fd);
  return 0;
}