#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <X11/Xmu/CurUtil.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *program_name;
Display *dpy;
int screen;
Window root;

#include <time.h>

void usage(void) {
    /* nuffin */
}

unsigned short colormod(unsigned long color) {
    color %= 131072;
    return color > 65535 ? 131071 - color : color;
}

int main(int argc, char **argv) {
    const struct timespec howlong  = { 0, 250 * 1000000 };
    char *display_name = NULL;
    unsigned long le_pixel;
    Colormap screen_colormap;
    XColor le_couleur;

    int i;
    program_name = argv[0];
    for (i = 1; i < argc; i++) {
        if (!strcmp ("-display", argv[i])) {
            if (++i >= argc) usage();
            display_name = argv[i];
            continue;
        }
        if (!strcmp("-help", argv[i])) {
            usage();
        }
    }

    dpy = XOpenDisplay(display_name);
    if (!dpy) {
        fprintf(stderr, "%s:  unable to open display '%s'\n",
                program_name, XDisplayName (display_name));
        exit (2);
    }

    screen = DefaultScreen(dpy);
    root = RootWindow(dpy, screen);
    le_pixel = WhitePixel (dpy, screen);
    
    screen_colormap = DefaultColormap(dpy, screen);

    {
        unsigned step = 0;
        unsigned long i;
        unsigned increment = 64;
        for (i = 0;; i += increment) {
            unsigned short cmod = colormod(i);
            
            if (cmod == 0) {
                ++step;
            }

            le_couleur.red =   step % 3 == 0 ? cmod : 0;
            le_couleur.green = step % 7 == 0 ? cmod : 0;
            le_couleur.blue =  step % 3 == 2 ? cmod : 0;

        
            {
                Status s = XAllocColor(dpy,
                                       screen_colormap,
                                       &le_couleur);
                /* make sure the allocation succeeded. */
                if (s == 0) {
                    fprintf(stderr,
                            "XAllocColor - allocation of color `X' failed.\n");
                }
            }
        
            XSetWindowBackground(dpy, root, le_couleur.pixel);
            XClearWindow(dpy, root);
            XFlush(dpy);
            nanosleep(&howlong, NULL);
        }
    }

    return 0;
}

