#include <X11/Xlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <X11/XKBlib.h>
#include <X11/cursorfont.h>

int main()
{
	Display* d;
	Window w;
	Window r;
	int s = 0;
	char msg[100];
	XEvent ev;
	int e;
	int win_ur_x, win_ur_y, win_width, win_height;
	int root_x, root_y, root_width, root_height;
	int blah = 0; // stuff we don't care about
	int ctr = 0;
	int ul_x = -1, ul_y = -1;
	int br_x = -1, br_y = -1;
	Cursor c;

	d = XOpenDisplay(":0.0");
	c = XCreateFontCursor(d, XC_arrow);
	XGetGeometry(d, RootWindow(d, s), &r, &root_x, &root_y, &root_width, &root_height, &blah, &blah);
	printf("root window is: %dx%d\n", root_width, root_height);
	XAllowEvents (d, AsyncBoth, CurrentTime);
	XGrabPointer(d, RootWindow(d, s), False, ButtonPress, GrabModeAsync, GrabModeAsync, None, c, CurrentTime);
	// get upper left coordinates
	printf("**********************************************\n");
	printf("* Click the upper left corner of your screen *\n");
	printf("**********************************************\n");
	while (ul_x == -1 && ul_y == -1) {
		while (! XPending(d)) {
			usleep(100000);
		}
		XNextEvent(d, &ev);
		if (ev.type != MotionNotify) {
			printf("got an event: ");
		}
		switch (ev.type) {
			case ButtonPress:
				printf("button press @ %dx%d\n", ev.xbutton.x_root, ev.xbutton.y_root);
				ul_x = ev.xbutton.x_root;
				ul_y = ev.xbutton.y_root;
				break;
			case MotionNotify:
				break;
			default:
				printf("unknown: %d\n", ev.type);
				break;
		}
		XAllowEvents (d, AsyncBoth, CurrentTime);
	}
	// get bottom right coordinates
	printf("************************************************\n");
	printf("* Click the bottom right corner of your screen *\n");
	printf("************************************************\n");
	while (br_x == -1 && br_y == -1) {
		while (! XPending(d)) {
			usleep(100000);
		}
		XNextEvent(d, &ev);
		if (ev.type != MotionNotify) {
			printf("got an event: ");
		}
		switch (ev.type) {
			case ButtonPress:
				printf("button press @ %dx%d\n", ev.xbutton.x_root, ev.xbutton.y_root);
				br_x = ev.xbutton.x_root;
				br_y = ev.xbutton.y_root;
				break;
			case MotionNotify:
				break;
			default:
				printf("unknown: %d\n", ev.type);
				break;
		}
		XAllowEvents (d, AsyncBoth, CurrentTime);
	}
	printf("Root Window Size: %dx%d\n", root_width, root_height);
	printf("Viewable Size: %dx%d\n", br_x - ul_x, br_y - ul_y);
	printf("Your screen is cut off by the following number of pixels:\n");
	printf("Left  : %d\n", ul_x);
	printf("Right : %d\n", root_width - br_x);
	printf("Top   : %d\n", ul_y);
	printf("Bottom: %d\n\n", root_height - br_y);

	return(0);
}

