/* gcc -g -Wall -o klicki klicki-0.1.c -L /usr/X11R6/lib/ -lX11 -lXtst */ 
/* written by Oliver Heins <olli@sopos.org> 2006 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <X11/extensions/XTest.h> 

static void usage() {
  fprintf(stderr, "%s", "usage: klicki [-t] [-v] 1 | 2 | 3\n");
  exit(1);
}

int main( int argc, char *argv[] ) { 
  static char version[] = "klicki 0.1";
  Display *dpy;
  short printAsText = 0;
  int i = 0;
  char *cmd;

  dpy = XOpenDisplay( NULL ); 
  if(!dpy) {
    fprintf(stderr, "%s", "klicki: cannot open display\n");
    exit(1);
  }

  /* command line args */
  if(argc < 2) {
    XCloseDisplay( dpy );
    usage();
  }

  for(i = 1; (i < argc) && (argv[i][0] == '-'); i++) {
    switch (argv[i][1]) {
    case 'v':
      fprintf(stdout, "%s\n", version);
      exit(0);
      break;
    case 't':
      printAsText = 1;
      break;
    default:
      XCloseDisplay( dpy );
      usage();
      break;
    }
  }
  cmd = argv[argc-1];

  XTestFakeKeyEvent( dpy, 50, False, CurrentTime );  // Shift_L
  XTestFakeKeyEvent( dpy, 62, False, CurrentTime );  // Shift_R
  XTestFakeKeyEvent( dpy, 64, False, CurrentTime );  // Alt
  XTestFakeKeyEvent( dpy, 115, False, CurrentTime ); // Win Start
  
  if(!strncmp(cmd, "1", 2)) { 
    XTestFakeButtonEvent( dpy, 1, True, CurrentTime ); 
    XTestFakeButtonEvent( dpy, 1, False, CurrentTime ); 
  } else if(!strncmp(cmd, "2", 2)) {
    if (printAsText) {
      printf("%s\n", "Not yet implemented.  Sorry.");
    } else {
      XTestFakeButtonEvent( dpy, 2, True, CurrentTime ); 
      XTestFakeButtonEvent( dpy, 2, False, CurrentTime ); 
    }
  } else if(!strncmp(cmd, "3", 2))  { 
    XTestFakeButtonEvent( dpy, 3, True, CurrentTime ); 
    XTestFakeButtonEvent( dpy, 3, False, CurrentTime ); 
  } else {
    XCloseDisplay( dpy );
    usage();
  }

  XCloseDisplay( dpy );
  return 0; 
} 

