/* vim */
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>
#include <X11/extensions/sync.h>

int main( int argc, char * argv[] ) {
	unsigned int white_pixel, black_pixel, width, height, count = 0;
	unsigned long nitems, leftover;
	int sync_event, sync_error, actual_format,*data;
	Display * dpy;
	Window root, win;
	XEvent event;
	XGCValues values;
	GC gc[2];
	XSyncCounter c;
	XSyncValue v, v1;
	Atom vs, actual_type;
	XSyncWaitCondition wc;
	Bool b=True;

	if((dpy = XOpenDisplay("")) == NULL) {
		fprintf(stderr, "error line %s: %d\n", __FILE__, __LINE__);
		exit(1);
	}
	if(!XSyncQueryExtension(dpy, &sync_event, &sync_error)) {
		fprintf(stderr, "error line %s: %d\n", __FILE__, __LINE__);
		exit(1);
	}
	root = RootWindow(dpy, DefaultScreen(dpy));
	white_pixel = WhitePixel(dpy, DefaultScreen(dpy));
	black_pixel = BlackPixel(dpy, DefaultScreen(dpy));
	width = DisplayWidth(dpy, DefaultScreen(dpy))/2;
	height = DisplayHeight(dpy, DefaultScreen(dpy))/2;
	win = XCreateSimpleWindow(dpy, root, 0, 0, width, height, 0, black_pixel, white_pixel);
	gc[0] = XCreateGC(dpy, win, 0, &values);
	XSetForeground(dpy, gc[0], black_pixel);
	gc[1] = XCreateGC(dpy, win, 0, &values);
	XSetForeground(dpy, gc[1], white_pixel);
	XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask | PointerMotionMask);
	XMapWindow(dpy, win);
	vs=XInternAtom(dpy,"_VSYNC_CRTC0",False);
	XGetWindowProperty(dpy, root, vs, 0, 1, False, XA_CARDINAL, &actual_type, &actual_format, &nitems, &leftover, (void*)&data);
	c=(int)*data;
	XSyncIntToValue(&v1,2);
	while(1) {
		if (XPending(dpy)) {
			XNextEvent(dpy, &event);
			switch(event.type) {
				case ButtonPress:
				case KeyPress:
					XFreeGC(dpy, gc[0]);
					XFreeGC(dpy, gc[1]);
					XCloseDisplay(dpy);
					exit(0);
					break;
			}
		}
		XFillRectangle(dpy, win, gc[count%2], 0, 0, width, height);
		count++;
		XSync(dpy, False);
		wc.trigger.counter = c;
		wc.trigger.value_type = XSyncAbsolute;
		wc.trigger.test_type = XSyncPositiveComparison;
		XSyncIntToValue(&wc.event_threshold, 0);
		XSyncQueryCounter(dpy, c, &v);
		XSyncValueAdd(&wc.trigger.wait_value, v, v1, &b);
		fprintf(stderr, "Wait for %u\n",XSyncValueLow32(wc.trigger.wait_value));
		XSyncAwait(dpy, &wc, 1);
	}
	return 0;
}
