#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/Xfixes.h>
#include <X11/extensions/XTest.h>

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define MAXW 1024 //10000
#define MAXH 768 //10000
#define SKIP 1
#define DELAY 50

unsigned long *idlist = NULL;
int idlength = 0;

int getID(unsigned long serial) {
    int i;

    for(i = 0; i < idlength; i++) {
	if(idlist[i] == serial) return i;
    }

    idlength++;
    idlist = (unsigned long *)realloc(idlist, sizeof(unsigned long) * idlength);
    idlist[idlength - 1] = serial;
    return idlength - 1;
}

int main(int argc,char **argv) {
        Display *display;
        char *display_name;
	XFixesCursorImage *res;
	unsigned long oldcurs = 0;

	unsigned long width, height;
	unsigned long x,y;

        if (! (display_name = getenv("DISPLAY")) ){
                fprintf(stderr,"environment variable DISPLAY must be set\n");
                exit(-1);
        }
        if (! (display = XOpenDisplay(display_name)) ){
                fprintf(stderr,"%s: Cannot open display %s\n", argv[0], 
                        display_name);
                exit(-1);
        }

	//FIXME: is this correct ?
	width = XDisplayWidth(display, 0);
	height = XDisplayHeight(display, 0);

	width = width > MAXW ? MAXW : width;
	height = height > MAXH ? MAXH : height;

	printf("P2\n%d %d\n", width/SKIP, height/SKIP);
	printf("%d\n", idlength - 1);

	for(y = 0; y < height; y+=SKIP) {
	    for(x = 0; x < width; x+=SKIP) {
		XTestFakeMotionEvent(display, -1, x, y, CurrentTime );
		usleep(DELAY);

		res = XFixesGetCursorImage(display);
		oldcurs = res->cursor_serial;
		printf("%d ", getID(oldcurs));
		XFree(res);
	    }

	    printf("\n");
	}

	fprintf(stderr, "maxid = %d\n", idlength - 1);

        return( 0 );


}

