#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <X11/Xlib.h>
#include <locale.h>

Display *d;
Window w;
Screen s;

char *font = "-misc-fixed-medium-r-normal--20-*-iso10646-1";
int x = 200;
int y = 200;

static void usage(void)
{
   fprintf(stderr, "usage: xtext [-f font] [-x xoff] [-y yoff] text\n");
   exit(1);
}

int main(int argc, char **argv)
{
   XEvent evt;
   XFontStruct *fontInfo;
   GC gc;
   XSetWindowAttributes attr;
   char c, *str;

   setlocale(LC_ALL, "");

   while ((c = getopt(argc, argv, ":f:x:y:")) != -1) {
       switch (c) {
           case 'f':
               font = (char *)malloc(strlen(optarg) + 1);
               strcpy(font, optarg);
               break;
           case 'x':
               x = atoi(optarg);
               break;
           case 'y':
               y = atoi(optarg);
               break;
           case '?':
           case ':':
           default:
               usage();
       }
   }

   if ((argc - optind) < 1)
       usage();

   str = (char *)malloc(strlen(argv[optind]) + 1);
   strcpy(str, argv[optind]);

   d = XOpenDisplay(NULL);

   w = XCreateSimpleWindow(d, DefaultRootWindow(d), 0, 0,
       1024, 768, 0, BlackPixel(d, 0), WhitePixel(d, 0));

   if (! w) {
       printf("Error creating window!\n");
       exit(1);
   }

   attr.event_mask = KeyPressMask;
   XChangeWindowAttributes(d, w, CWEventMask, &attr);
   XStoreName(d, w, "XText");

   XMapWindow(d, w);
   XMoveWindow(d, w, 0, 0);

   fontInfo = XLoadQueryFont(d, font);
   if (! fontInfo) {
       fprintf(stderr, "Error loading font!\n");
       exit(1);
   }

/*
   printf("min_byte1: %d\n", fontInfo->min_byte1);
   printf("max_byte1: %d\n", fontInfo->max_byte1);
   printf("min_char_or_byte2: %d\n", fontInfo->min_char_or_byte2);
   printf("max_char_or_byte2: %d\n", fontInfo->max_char_or_byte2);
*/

   gc = XCreateGC(d, w, 0, NULL);

   XSetForeground(d, gc, BlackPixel(d, 0));
   XSetBackground(d, gc, WhitePixel(d, 0));
   XSetFont(d, gc, fontInfo->fid);

   XDrawString(d, w, gc, x, y, str, strlen(str));

   while(1) {
       while(XPending(d)) {
           XNextEvent(d, &evt);
           if (evt.type == KeyPress)
               goto end;
       }
       usleep(1000);
   }

end:
   XDestroyWindow(d, w);
   XCloseDisplay(d);
   return 0;
}