#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>

#include <stdio.h>

Display *display;
int screen_num;
Window root;
int depth;

char *getenv(char *);

void main(int argc, char **argv)
{
  Window foo, bar;
  XSetWindowAttributes attrib;
  XWMHints wm_hints;
  XClassHint class_hints;
  XSizeHints size_hints;
  char *winName, *iconName;
  XTextProperty winname, iconname;
  XEvent event;
  Window this, that;
  XWindowChanges cw;

  display = XOpenDisplay(getenv("DISPLAY"));
  screen_num = DefaultScreen(display);
  root = RootWindow(display, screen_num);

  winName = iconName = "foo";
  XStringListToTextProperty(&winName, 1, &winname);
  XStringListToTextProperty(&iconName, 1, &iconname);
  wm_hints.initial_state = NormalState;
  wm_hints.input = True;
  wm_hints.flags = StateHint | InputHint;
  class_hints.res_name = "winplay";
  class_hints.res_class = "foobar";
  size_hints.flags = PPosition | PSize;
  size_hints.x = 100;
  size_hints.y = 100;
  size_hints.width = 100;
  size_hints.height = 100;
  attrib.event_mask = KeyPressMask;
  attrib.background_pixel = BlackPixel(display, screen_num);
  foo = XCreateWindow(display, root, 100, 100, 100, 100, CopyFromParent,
		      CopyFromParent, CopyFromParent, CopyFromParent,
		      (CWBackPixel | CWEventMask),
		      &attrib);
  XSetWMProperties(display, foo, &winname, &iconname, argv, argc,
		   &size_hints, &wm_hints, &class_hints);
  winName = iconName = "bar";
  XStringListToTextProperty(&winName, 1, &winname);
  XStringListToTextProperty(&iconName, 1, &iconname);
  class_hints.res_class = "foobar";
  attrib.background_pixel = WhitePixel(display, screen_num);
  bar = XCreateWindow(display, root, 100, 100, 100, 100, CopyFromParent,
		      CopyFromParent, CopyFromParent, CopyFromParent,
		      (CWBackPixel | CWEventMask),
		      &attrib);
  XSetWMProperties(display, bar, &winname, &iconname, argv, argc,
		   &size_hints, &wm_hints, &class_hints);

  XMapWindow(display, foo);
  XMapWindow(display, bar);
  XFlush(display);
  for (;;)
    {
      XNextEvent(display, &event);
      if (event.type == KeyPress)
	{
	  if (event.xkey.window == foo)
	    {
	      this = foo;
	      that = bar;
	    }
	  else
	    {
	      this = bar;
	      that = foo;
	    }
	  cw.sibling = that;
	  cw.stack_mode = Below;
	  XReconfigureWMWindow(display, this, screen_num,
			       (CWSibling | CWStackMode), &cw);
	  fprintf(stderr, "Game over!\n");
	}
    }
}
