/* 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[] ) {
	int sync_event, sync_error, n, i;
	Display *dpy;
	Window root;
	Atom vs;
	XSyncSystemCounter *sys_counter_list = NULL;
	XSyncCounter counter = None, c;
	XSyncValue v, v1;

	if((dpy = XOpenDisplay("")) == NULL) {
		fprintf(stderr, "error line %s: %d\n", __FILE__, __LINE__);
		exit(1);
	}
	root = RootWindow(dpy, DefaultScreen(dpy));
	if(!XSyncQueryExtension(dpy, &sync_event, &sync_error)) {
		fprintf(stderr, "error line %s: %d\n", __FILE__, __LINE__);
		exit(1);
	}
	sys_counter_list = XSyncListSystemCounters(dpy, &n);
	for(i = n-1; i >= 0; i--) {
		if(strcmp(sys_counter_list[i].name, "SERVERTIME")==0) {
			counter = sys_counter_list[i].counter;
			break;
		}
	}
	if(counter == None) {
		fprintf(stderr, "error line %s: %d\n", __FILE__, __LINE__);
		exit(1);
	}
	XSyncFreeSystemCounterList(sys_counter_list);
	XSyncQueryCounter(dpy, counter, &v);
//	fprintf(stderr, "SERVERTIME %d %u\n",XSyncValueHigh32(v),XSyncValueLow32(v));
	XSyncIntToValue(&v,1);
	c = XSyncCreateCounter(dpy,v);
	vs = XInternAtom(dpy,"_VSYNC_CRTC0",False);
	XChangeProperty(dpy, root, vs, XA_CARDINAL, 32, PropModeReplace, (void*)&c, 1);
	XSyncIntToValue(&v1,2);
//	XSynchronize(dpy, True);
	while(1) {
		usleep(1000000/60);
		XSyncChangeCounter(dpy,c,v1);
		XSyncQueryCounter(dpy,c,&v);
//		fprintf(stderr,"counter %d %u\n",XSyncValueHigh32(v),XSyncValueLow32(v));
	}
	XCloseDisplay(dpy);
	return 0;
}

