// gcc -std=gnu99 -o fake-trigger fake-trigger.c -lX11

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#ifndef TRUE
#define TRUE (0==0)
#endif

int main(int argc, char *argv[]);

int main(int argc, char *argv[]) {
  if (argc!=4) {
    fprintf(stderr, "usage: %s <trs> <tr> <slices_per_tr>\n", argv[0]);
    exit(EXIT_FAILURE);
  }
  unsigned int trs = atoi(argv[1]);
  double tr;
  if (sscanf(argv[2], "%lf", &tr)!=1) {
    fprintf(stderr, "usage: %s <trs> <tr> <slices_per_tr>\n", argv[0]);
    exit(EXIT_FAILURE);
  }
  unsigned int slices_per_tr = atoi(argv[3]);
  Display *display = XOpenDisplay("");
  Window root = DefaultRootWindow(display);
  XEvent event;
  int keycode = XKeysymToKeycode(display, XK_5);
  for (unsigned int i = 0; i<trs*slices_per_tr; i++) {
    // This isn't correct because each iteration takes time, particularly the
    // XSendEvent and XFlush.
    usleep(1000000*tr/slices_per_tr);
    event.type = KeyPress;
    // serial
    event.xkey.send_event = True;
    event.xkey.display = display;
    event.xkey.root = root;
    event.xkey.subwindow = None;
    event.xkey.time = CurrentTime;
    event.xkey.x = 1;
    event.xkey.y = 1;
    event.xkey.x_root = 1;
    event.xkey.y_root = 1;
    event.xkey.state = 0;
    event.xkey.keycode = keycode;
    event.xkey.same_screen = True;
    event.xkey.window = root;
    XSendEvent(display, root, True, KeyPressMask, &event);
    XFlush(display);
  }
  return EXIT_SUCCESS;
}
