First 'working' version of WolframAutomata for FreeBSD. Still has an XFreeGC() proble...
authorAaron Taylor <ataylor@subgeniuskitty.com>
Sat, 29 May 2021 00:28:42 +0000 (17:28 -0700)
committerAaron Taylor <ataylor@subgeniuskitty.com>
Sat, 29 May 2021 00:28:42 +0000 (17:28 -0700)
hacks/WolframAutomata/WolframAutomata.c

index c788f01..5e0b725 100644 (file)
 /* (c) 2021 Aaron Taylor <ataylor at subgeniuskitty dot com>   */
 /* See LICENSE.txt file for copyright and license details.     */
 
 /* (c) 2021 Aaron Taylor <ataylor at subgeniuskitty dot com>   */
 /* See LICENSE.txt file for copyright and license details.     */
 
-
-/* TODO: Write description explaining that this simulates all 1D NN CAs, and explain briefly what all those terms imply. */
-/* TODO: Explain things like the topology of the space. */
-/* TODO: Explain how the numbering for a CA expands to the actual rules. */
-/* TODO: Briefly explain the four different classes of behavior and their implications. */
-/* TODO: Include a link to Wikipedia. */
-/* TODO: I suppose a lot of this stuff goes in the README instead. */
-/* TODO: Explain the data structures in detail. */
-/* TODO: Explain all the options, like the various starting conditions. */
-/* TODO: Explain all the dependencies like libXpm. */
-/* TODO: Explain that the program is inherently double-buffered but if you don't have VSync turned on, all those alternating lines are going to look terrible when they scroll upward. */
-
-/* TODO: Add a #define for the hack version. */
-/* TODO: Check manpage for all functions I use and ensure my includes are correct. I don't want to depend on picking up includes via screenhack.h. */
-/* TODO: Verify everything in this file is C89. Get rid of things like '//' comments, pack all my declarations upfront, no stdint, etc. */
-
-#include <X11/Intrinsic.h>
 #include "screenhack.h"
 
 #include "screenhack.h"
 
-/*
- * We do a few manual manipulations of X resources in this hack, like picking
- * random colors. In order to ensure our manual manipulations always use the
- * same X resource specification as Xscreensaver, we pass HACKNAME to
- * Xscreensaver via the XSCREENSAVER_MODULE() line at the bottom of this file,
- * and then always use HACKNAME or MAKE_STRING(HACKNAME) as the base of the
- * resource specification when making manual manipulations.
- */
-#define HACKNAME WolframAutomata
-#define MAKE_STRING_X(s) #s
-#define MAKE_STRING(s) MAKE_STRING_X(s)
-
-// Command line options
-//        directory to output XBM files of each run (and call an external command to convert to PNGs?)
-//              -save-dir STRING
-//              (could use libXpm to save an XPM and then convert to PNG with ImageMagick) (this is a single function call to go from pixmap -> file)
-//              (since it depends on an external library, make this whole feature optional at build-time?)
-//        number of generations to simulate
-//              -random-generations
-//              -num-generations N
-//        delay time (speed of simulation)
-//              -random-delay
-//              -delay-usec N
-//        foreground and background color
-//              -random-colors (highest precedence)
-//              -foreground "COLORNAME"
-//              -background "COLORNAME"
-//              (default is black and white)
-//              (mention sample color combinations in manpage, and link to: https://en.wikipedia.org/wiki/X11_color_names)
-//              (note to the user that most color names they can naturally think of (e.g. red, purple, gray, pink, etc) are valid X11 color names for these CLI options.)
-//        display info overlay with CA number and start conditions?
-//              -overlay
-//        which ruleset number to use? Or random? Or random from small set of hand-selected interesting examples?
-//              In order of precedence:
-//                  -rule-random (select a random rule on each run)
-//                  -rule N (always simulate Rule N on each run)
-//                  (if neither of the above two are specified, then a random CURATED rule is selected on each run)
-//        which starting population to use, random or one bit? (for random: allow specifying a density)
-//              In order of precedence:
-//                  -population-single
-//                  -population-random DENSITY
-//                  (the two options above only apply to the simulation under the -rule-random or -rule N options. in curated mode, starting population is defined in the curation array)
-//                  TODO: In the future, add the option for user to pass list of cell IDs to turn ON.
-//        size of pixel square (e.g. 1x1, 2x2, 3x3, etc)
-//              -random-pixel-size
-//              -pixel-size N
-
 /* -------------------------------------------------------------------------- */
 /* Data Structures                                                            */
 /* -------------------------------------------------------------------------- */
 
 struct state {
 /* -------------------------------------------------------------------------- */
 /* Data Structures                                                            */
 /* -------------------------------------------------------------------------- */
 
 struct state {
-    /* Various X resources */
+    /* Various X resources                                                    */
     Display * dpy;
     Window    win;
     GC        gc;
 
     Display * dpy;
     Window    win;
     GC        gc;
 
-    // TODO: Explain that this holds the whole evolution of the CA and the actual displayed visualization is simply a snapshot into this pixmap.
-    Pixmap    evolution_history;
-
-    // TODO: Explain all of these.
+    /* These hold the pixel value of the foreground and background colors in  */
+    /* the same format as an XColor struct's "pixel" member.                  */
     unsigned long fg, bg;
     unsigned long fg, bg;
-    int xlim, ylim, ypos; // explain roughly how and where we use these. Note: I'm not thrilled xlim/ylim since they are actually the width of the display, not the limit of the index (off by one). Change those names.
-    Bool display_info;
 
 
-    Bool * current_generation;
+    /* This Pixmap will eventually hold the entire evolution of the CA. The   */
+    /* displayed portion of the CA's evolution is merely a viewport into this */
+    /* Pixmap.                                                                */
+    Pixmap    evolution_history;
 
 
-    // TODO: Describe these.
-    uint8_t rule_number;  // Note: This is not a CLI option. You're thinking of rule_requested.
-    uint8_t rule_requested; // Note: Repurposing Rule 0 as a null value.
-    Bool rule_random;
+    /* Together, these three values define the display viewport into the      */
+    /* 'evolution_history' Pixmap. The pair 'dpy_width' and 'dpy_height' are  */
+    /* simply the width and height of the display window. They remain         */
+    /* unchanged during normal operation. However, 'ypos' tracks the location */
+    /* of the viewport in the 'evolution_history'. It must always keep the    */
+    /* newest generation onscreen and display as much history as possible.    */
+    int dpy_width, dpy_height, ypos;
+
+    /* In the 'current_generation' array, the value True means a cell is      */
+    /* alive. We only need to track the current generation since our rulesets */
+    /* never consider older generations. Anything older can be rendered to    */
+    /* the 'evolution_history' Pixmap and subsequently ignored.               */
+    Bool * current_generation;
 
 
-    // TODO: Describe these.
+    /* When randomizing the seed generation, we can specify a population      */
+    /* density, or we can restrict to a single living cell.                   */
     int population_density;
     Bool population_single;
 
     int population_density;
     Bool population_single;
 
-    /* Misc Commandline Options */
-    int pixel_size; /* Size of CA cell in pixels (e.g. pixel_size=3 means 3x3 pixels per cell). */
-    int delay_microsec; /* Requested delay to screenhack framework before next call to WolframAutomata_draw(). */
-    int num_generations; /* Number of generations of the CA to simulate before restarting. */
+    /* For more information on the encoding used for rule_number and on the   */
+    /* method used to apply it: https://en.wikipedia.org/wiki/Wolfram_code    */
+    uint8_t rule_number;
 
 
-    /* Expository Variables - Not strictly necessary, but makes some code easier to read. */
+    /* At the end of the simulation, the user is given time to admire the     */
+    /* output. Delay is available to user as CLI option.                      */
+    Bool admiration_in_progress;
+    size_t admiration_delay; /* ...in microseconds.                           */
+
+    /* The following values correspond directly to independent CLI options.   */
+    Bool    rule_random;
+    uint8_t rule_requested;  /* Note: Repurposing Rule 0 as null value.       */
+    int     cell_size; /* If cell_size=N then draw NxN pixels per cell.       */
+    int     delay_microsec; /* ...between calls to WolframAutomata_draw().    */
+    int     num_generations; /* Reset simulation after this many generations. */
+
+    /* Not strictly necessary, but makes some code easier to read.            */
     size_t number_of_cells;
 };
 
     size_t number_of_cells;
 };
 
-// TODO: Decorations
 enum seed_population {
     random_cell,
     middle_cell,
     edge_cell
 };
 
 enum seed_population {
     random_cell,
     middle_cell,
     edge_cell
 };
 
-// TODO: Decorations
 struct curated_ruleset {
     uint8_t              rule;
     enum seed_population seed;
 };
 
 struct curated_ruleset {
     uint8_t              rule;
     enum seed_population seed;
 };
 
-// TODO: Decorations
 static const struct curated_ruleset curated_ruleset_list[] = {
 static const struct curated_ruleset curated_ruleset_list[] = {
-    {18, middle_cell},
-    {30, middle_cell},
-    {45, middle_cell},
-    {54, middle_cell},
-    {57, middle_cell},
-    {73, middle_cell},
+    { 18, middle_cell},
+    { 30, middle_cell},
+    { 45, middle_cell},
+    { 54, middle_cell},
+    { 57, middle_cell},
+    { 73, middle_cell},
     {105, middle_cell},
     {109, middle_cell},
     {129, middle_cell},
     {133, middle_cell},
     {135, middle_cell},
     {150, middle_cell},
     {105, middle_cell},
     {109, middle_cell},
     {129, middle_cell},
     {133, middle_cell},
     {135, middle_cell},
     {150, middle_cell},
-    {30, edge_cell},
-    {45, edge_cell},
-    {57, edge_cell},
-    {60, edge_cell},
-    {75, edge_cell},
+    { 30, edge_cell},
+    { 45, edge_cell},
+    { 57, edge_cell},
+    { 60, edge_cell},
+    { 75, edge_cell},
     {107, edge_cell},
     {110, edge_cell},
     {133, edge_cell},
     {137, edge_cell},
     {169, edge_cell},
     {225, edge_cell},
     {107, edge_cell},
     {110, edge_cell},
     {133, edge_cell},
     {137, edge_cell},
     {169, edge_cell},
     {225, edge_cell},
-    {22, random_cell},
-    {30, random_cell},
-    {54, random_cell},
-    {62, random_cell},
-    {90, random_cell},
+    { 22, random_cell},
+    { 30, random_cell},
+    { 54, random_cell},
+    { 62, random_cell},
+    { 90, random_cell},
     {105, random_cell},
     {108, random_cell},
     {110, random_cell},
     {105, random_cell},
     {108, random_cell},
     {110, random_cell},
@@ -160,50 +113,70 @@ static const struct curated_ruleset curated_ruleset_list[] = {
     {240, random_cell}
 };
 
     {240, random_cell}
 };
 
-// TODO: Decorations
 struct color_pair {
 struct color_pair {
-    char * fg;
-    char * bg;
+    /* The type 'unsigned short' comes from the XColor struct definition,     */
+    /* reproduced below.                                                      */
+    /*                                                                        */
+    /*      typedef struct {                                                  */
+    /*          unsigned long pixel;                                          */
+    /*          unsigned short red, green, blue;                              */
+    /*          char flags;                                                   */
+    /*          char pad;                                                     */
+    /*      } XColor;                                                         */
+    /*                                                                        */
+    /* The red, green, and blue values are always in the range 0 to 65535     */
+    /* inclusive, independent of the number of bits actually used in the      */
+    /* display hardware. The server scales these values to the range used     */
+    /* by the hardware. Black is represented by (0,0,0), and white is         */
+    /* represented by (65535,65535,65535).                                    */
+    unsigned short fg_red, fg_green, fg_blue;
+    unsigned short bg_red, bg_green, bg_blue;
 };
 
 };
 
-// TODO: Decorations
 static const struct color_pair color_list[] = {
 static const struct color_pair color_list[] = {
-    {"red", "black"},
-    {"olive", "black"},
-    {"teal", "black"},
-    {"slateblue", "black"},
-    {"violet", "black"},
-    {"purple", "black"},
-    {"white", "black"},
-    {"white", "darkgreen"},
-    {"white", "darkmagenta"},
-    {"white", "darkred"},
-    {"white", "darkblue"},
-    {"darkslategray", "darkslategray1"},
-    {"lightsteelblue", "darkslategray"},
-    {"royalblue4", "royalblue"},
-    {"antiquewhite2", "antiquewhite4"},
-    {"darkolivegreen1", "darkolivegreen"},
-    {"darkseagreen1", "darkseagreen4"},
-    {"pink", "darkred"},
-    {"lightblue", "darkgreen"},
-    {"red", "blue"},
-    {"red", "darkgreen"},
-    {"aqua", "teal"},
-    {"darkblue", "teal"},
-    {"khaki", "seagreen"},
-    {"khaki", "darkolivegreen"},
-    {"lightslategray", "darkslategray"},
-    {"tomato", "darkslategray"},
-    {"tomato", "darkcyan"}
+    /* For mapping X11 color names to RGB values:                                           */
+    /*      https://www.ehdp.com/methods/x11-color-names-rgb-values.htm                     */
+    /* Remember that our values range from 0-65535 inclusive, so scale the                  */
+    /* usual 0-255 range accordingly.                                                       */
+    /*                                                                                      */
+    /* +---------------------------------------+                                            */
+    /* |   foreground    |   |    background   |                                            */
+    /* |  red,green,blue |   |  red,green,blue |                                            */
+       {65535,    0,    0,        0,    0,    0}, /* {"red",             "black"},          */
+       {32767,32767,    0,        0,    0,    0}, /* {"olive",           "black"},          */
+       {    0,32767,32767,        0,    0,    0}, /* {"teal",            "black"},          */
+       {27524,22937,52428,        0,    0,    0}, /* {"slateblue",       "black"},          */
+       {60947,33422,60947,        0,    0,    0}, /* {"violet",          "black"},          */
+       {41287, 8519,61602,        0,    0,    0}, /* {"purple",          "black"},          */
+       {65535,65535,65535,        0,    0,    0}, /* {"white",           "black"},          */
+       {65535,65535,65535,        0,25558,    0}, /* {"white",           "darkgreen"},      */
+       {65535,65535,65535,    36044,    0,36044}, /* {"white",           "darkmagenta"},    */
+       {65535,65535,65535,    36044,    0,    0}, /* {"white",           "darkred"},        */
+       {65535,65535,65535,        0,    0,36044}, /* {"white",           "darkblue"},       */
+       {11796,20315,20315,    36494,65535,65535}, /* {"darkslategray",   "darkslategray1"}, */
+       {45219,50461,57015,    11796,20315,20315}, /* {"lightsteelblue",  "darkslategray"},  */
+       {10023,16448,35723,    16383,26869,57670}, /* {"royalblue4",      "royalblue"},      */
+       {61166,57311,52428,    35723,33667,30840}, /* {"antiquewhite2",   "antiquewhite4"},  */
+       {51914,65535,28784,    21626,27524,11796}, /* {"darkolivegreen1", "darkolivegreen"}, */
+       {49601,65535,49601,    26985,35723,26985}, /* {"darkseagreen1",   "darkseagreen4"},  */
+       {65535,49151,52428,    36044,    0,    0}, /* {"pink",            "darkred"},        */
+       {44563,55704,58981,        0,25558,    0}, /* {"lightblue",       "darkgreen"},      */
+       {65535,    0,    0,        0,    0,65535}, /* {"red",             "blue"},           */
+       {65535,    0,    0,        0,25558,    0}, /* {"red",             "darkgreen"},      */
+       {    0,65535,65535,        0,32767,32767}, /* {"aqua",            "teal"},           */
+       {    0,    0,36044,        0,32767,32767}, /* {"darkblue",        "teal"},           */
+       {61602,58981,32767,    11796,36044,22281}, /* {"khaki",           "seagreen"},       */
+       {61602,58981,32767,    21626,27524,11796}, /* {"khaki",           "darkolivegreen"}, */
+       {30801,34733,39321,    11796,20315,20315}, /* {"lightslategray",  "darkslategray"},  */
+       {65535,25558,18349,    11796,20315,20315}, /* {"tomato",          "darkslategray"},  */
+       {65535,25558,18349,        0,36044,36044}  /* {"tomato",          "darkcyan"}        */
 };
 
 /* -------------------------------------------------------------------------- */
 /* Helper Functions                                                           */
 /* -------------------------------------------------------------------------- */
 
 };
 
 /* -------------------------------------------------------------------------- */
 /* Helper Functions                                                           */
 /* -------------------------------------------------------------------------- */
 
-// TODO: decorations? inline?
-void
+static void
 generate_random_seed(struct state * state)
 {
     int i;
 generate_random_seed(struct state * state)
 {
     int i;
@@ -212,9 +185,10 @@ generate_random_seed(struct state * state)
     }
 }
 
     }
 }
 
-// TODO: function decorations?
-// TODO: Explain why this santizes the index for accessing current_generation (i.e. it creates a circular topology).
-size_t
+/* This function sanitizes the index used to access cells in a generation.    */
+/* Specifically, it wraps the index, creating a circular universe for the     */
+/* cells and ensuring every cell has two neighbors.                           */
+static size_t
 sindex(struct state * state, int index)
 {
     while (index < 0) {
 sindex(struct state * state, int index)
 {
     while (index < 0) {
@@ -226,9 +200,9 @@ sindex(struct state * state, int index)
     return (size_t) index;
 }
 
     return (size_t) index;
 }
 
-// TODO: function decorations?
-// TODO: At least give a one-sentence explanation of the algorithm since this function is the core of the simulation.
-Bool
+/* For more information on the encoding used for state->rule_number and on    */
+/* the method used to apply it: https://en.wikipedia.org/wiki/Wolfram_code    */
+static Bool
 calculate_cell(struct state * state, int cell_id)
 {
     uint8_t cell_pattern = 0;
 calculate_cell(struct state * state, int cell_id)
 {
     uint8_t cell_pattern = 0;
@@ -246,17 +220,16 @@ calculate_cell(struct state * state, int cell_id)
     }
 }
 
     }
 }
 
-// TODO: function decorations?
-void
+static void
 render_current_generation(struct state * state)
 {
     size_t xpos;
     for (xpos = 0; xpos < state->number_of_cells; xpos++) {
         if (state->current_generation[xpos] == True) {
 render_current_generation(struct state * state)
 {
     size_t xpos;
     for (xpos = 0; xpos < state->number_of_cells; xpos++) {
         if (state->current_generation[xpos] == True) {
-            XFillRectangle(state->dpy, state->evolution_history, state->gc, xpos*state->pixel_size, state->ypos, state->pixel_size, state->pixel_size);
+            XFillRectangle(state->dpy, state->evolution_history, state->gc, xpos*state->cell_size, state->ypos, state->cell_size, state->cell_size);
         } else {
             XSetForeground(state->dpy, state->gc, state->bg);
         } else {
             XSetForeground(state->dpy, state->gc, state->bg);
-            XFillRectangle(state->dpy, state->evolution_history, state->gc, xpos*state->pixel_size, state->ypos, state->pixel_size, state->pixel_size);
+            XFillRectangle(state->dpy, state->evolution_history, state->gc, xpos*state->cell_size, state->ypos, state->cell_size, state->cell_size);
             XSetForeground(state->dpy, state->gc, state->fg);
         }
     }
             XSetForeground(state->dpy, state->gc, state->fg);
         }
     }
@@ -299,36 +272,53 @@ WolframAutomata_init(Display * dpy, Window win)
     state->win = win;
 
     XGetWindowAttributes(state->dpy, state->win, &xgwa);
     state->win = win;
 
     XGetWindowAttributes(state->dpy, state->win, &xgwa);
-    state->xlim = xgwa.width;
-    state->ylim = xgwa.height;
-    state->ypos = 0; // TODO: Explain why.
+    state->dpy_width = xgwa.width;
+    state->dpy_height = xgwa.height;
+    state->ypos = 0;
+
+    state->admiration_delay = 5000000;
+    state->admiration_in_progress = False;
 
     if (get_boolean_resource(state->dpy, "random-colors", "Boolean")) {
 
     if (get_boolean_resource(state->dpy, "random-colors", "Boolean")) {
-        XrmDatabase db = XtDatabase(state->dpy);
+        XColor fg, bg;
         size_t rand_i = random() % sizeof(color_list)/sizeof(color_list[0]);
         size_t rand_i = random() % sizeof(color_list)/sizeof(color_list[0]);
-        XrmPutStringResource(&db, MAKE_STRING(HACKNAME) ".background", color_list[rand_i].bg);
-        XrmPutStringResource(&db, MAKE_STRING(HACKNAME) ".foreground", color_list[rand_i].fg);
+        fg.red   = color_list[rand_i].fg_red;
+        fg.green = color_list[rand_i].fg_green;
+        fg.blue  = color_list[rand_i].fg_blue;
+        bg.red   = color_list[rand_i].bg_red;
+        bg.green = color_list[rand_i].bg_green;
+        bg.blue  = color_list[rand_i].bg_blue;
+        /* TODO: Since I 'alloc', presumably I must also 'free' these colors  */
+        /* at some point. Where/how? I don't want to eventually crash my      */
+        /* X server after months of use.                                      */
+        XAllocColor(state->dpy, xgwa.colormap, &fg);
+        XAllocColor(state->dpy, xgwa.colormap, &bg);
+        state->fg = gcv.foreground = fg.pixel;
+        state->bg = gcv.background = bg.pixel;
+    } else {
+        state->fg = gcv.foreground = get_pixel_resource(state->dpy, xgwa.colormap, "foreground", "Foreground");
+        state->bg = gcv.background = get_pixel_resource(state->dpy, xgwa.colormap, "background", "Background");
     }
 
     }
 
-    state->fg = gcv.foreground = get_pixel_resource(state->dpy, xgwa.colormap, "foreground", "Foreground");
-    state->bg = gcv.background = get_pixel_resource(state->dpy, xgwa.colormap, "background", "Background");
     state->gc = XCreateGC(state->dpy, state->win, GCForeground, &gcv);
 
     state->gc = XCreateGC(state->dpy, state->win, GCForeground, &gcv);
 
-    /* Set the size of each simulated cell as NxN pixels for pixel_size=N.    */
+    /* Set the size of each simulated cell to NxN pixels for cell_size=N.     */
     if (get_boolean_resource(state->dpy, "random-pixel-size", "Boolean")) {
         /* Although we are choosing the pixel size 'randomly', a truly random */
         /* selection would bias toward large numbers since there are more of  */
         /* them. To avoid this, we select a random number for a bit shift,    */
         /* resulting in a pixel size of 1, 2, 4, 8, 16 or 32, equally likely. */
     if (get_boolean_resource(state->dpy, "random-pixel-size", "Boolean")) {
         /* Although we are choosing the pixel size 'randomly', a truly random */
         /* selection would bias toward large numbers since there are more of  */
         /* them. To avoid this, we select a random number for a bit shift,    */
         /* resulting in a pixel size of 1, 2, 4, 8, 16 or 32, equally likely. */
-        state->pixel_size = 1 << (random() % 6);
+        state->cell_size = 1 << (random() % 6);
     } else {
     } else {
-        state->pixel_size = get_integer_resource(state->dpy, "pixel-size", "Integer");
+        state->cell_size = get_integer_resource(state->dpy, "pixel-size", "Integer");
     }
     }
-    if (state->pixel_size < 1) state->pixel_size = 1;
-    if (state->pixel_size > state->xlim) state->pixel_size = state->xlim;
+    if (state->cell_size < 1) state->cell_size = 1;
+    if (state->cell_size > state->dpy_width) state->cell_size = state->dpy_width;
 
 
-    state->number_of_cells = state->xlim / state->pixel_size;
-    // TODO: Do we want to enforce that number_of_cells > 0?
+    /* Larger cell sizes won't always evenly divide the number of pixels in   */
+    /* our window. In order to avoid a black stripe down the edge, '+1' here  */
+    /* to ensure we are slightly oversize rather than undersize.              */
+    state->number_of_cells = (state->dpy_width / state->cell_size) + 1;
 
     /* Set the delay (in microseconds) between simulation of each generation  */
     /* of the simulation, also known as the delay between calls to            */
 
     /* Set the delay (in microseconds) between simulation of each generation  */
     /* of the simulation, also known as the delay between calls to            */
@@ -340,17 +330,17 @@ WolframAutomata_init(Display * dpy, Window win)
         /* human. By empirical observation, we note that for 1x1 up to 4x4    */
         /* pixel cell sizes, values for state->delay_microsec between         */
         /* 2048 (2^11) and 16556 (2^14) produce pleasant scroll rates. To     */
         /* human. By empirical observation, we note that for 1x1 up to 4x4    */
         /* pixel cell sizes, values for state->delay_microsec between         */
         /* 2048 (2^11) and 16556 (2^14) produce pleasant scroll rates. To     */
-        /* maintain this appearance, we bitshift state->pixel_size down until */
+        /* maintain this appearance, we bitshift state->cell_size down until  */
         /* it is a maximum of 4x4 pixels in size, record how many bitshifts   */
         /* took place, and then shift our valid window for                    */
         /* state->delay_microsec up by an equal number of bitshifts. For      */
         /* it is a maximum of 4x4 pixels in size, record how many bitshifts   */
         /* took place, and then shift our valid window for                    */
         /* state->delay_microsec up by an equal number of bitshifts. For      */
-        /* example, if state->pixel_size=9, then it takes one right shift to  */
-        /* reach state->pixel_size=4. Thus, the valid window for              */
+        /* example, if state->cell_size=9, then it takes one right shift to   */
+        /* reach state->cell_size=4. Thus, the valid window for               */
         /* state->delay_microsec becomes 4096 (2^12) up to 32768 (2^15).      */
         size_t pixel_shift_range = 1;
         /* state->delay_microsec becomes 4096 (2^12) up to 32768 (2^15).      */
         size_t pixel_shift_range = 1;
-        size_t pixel_size_temp = state->pixel_size;
-        while (pixel_size_temp > 4) {
-            pixel_size_temp >>= 1;
+        size_t cell_size_temp = state->cell_size;
+        while (cell_size_temp > 4) {
+            cell_size_temp >>= 1;
             pixel_shift_range++;
         }
         /* In the below line, '3' represents the total range, namely '14-11'  */
             pixel_shift_range++;
         }
         /* In the below line, '3' represents the total range, namely '14-11'  */
@@ -367,15 +357,15 @@ WolframAutomata_init(Display * dpy, Window win)
     /* and re-running with new settings.                                      */
     if (get_boolean_resource(state->dpy, "random-num-generations", "Boolean")) {
         /* By empirical observation, keep the product                         */
     /* and re-running with new settings.                                      */
     if (get_boolean_resource(state->dpy, "random-num-generations", "Boolean")) {
         /* By empirical observation, keep the product                         */
-        /*      state->num_generations * state->pixel_size                    */
+        /*      state->num_generations * state->cell_size                     */
         /* below 10,000 to avoid BadAlloc errors from the X server due to     */
         /* requesting an enormous pixmap. This value works on both a 12 core  */
         /* Xeon with 108 GiB of RAM and a Sun Ultra 2 with 2 GiB of RAM.      */
         /* below 10,000 to avoid BadAlloc errors from the X server due to     */
         /* requesting an enormous pixmap. This value works on both a 12 core  */
         /* Xeon with 108 GiB of RAM and a Sun Ultra 2 with 2 GiB of RAM.      */
-        state->num_generations = random() % (10000 / state->pixel_size);
+        state->num_generations = random() % (10000 / state->cell_size);
         /* Ensure selected value is large enough to at least fill the screen. */
         /* Cast to avoid overflow.                                            */
         /* Ensure selected value is large enough to at least fill the screen. */
         /* Cast to avoid overflow.                                            */
-        if ((long)state->num_generations * (long)state->pixel_size < state->ylim) {
-            state->num_generations = (state->ylim / state->pixel_size) + 1;
+        if ((long)state->num_generations * (long)state->cell_size < state->dpy_height) {
+            state->num_generations = (state->dpy_height / state->cell_size) + 1;
         }
     } else {
         state->num_generations = get_integer_resource(state->dpy, "num-generations", "Integer");
         }
     } else {
         state->num_generations = get_integer_resource(state->dpy, "num-generations", "Integer");
@@ -385,11 +375,11 @@ WolframAutomata_init(Display * dpy, Window win)
     /* WolframAutomata_draw(), which is where we check whether or not we've   */
     /* reached the end of the pixmap.                                         */
     if (state->num_generations < 0) state->num_generations = 2;
     /* WolframAutomata_draw(), which is where we check whether or not we've   */
     /* reached the end of the pixmap.                                         */
     if (state->num_generations < 0) state->num_generations = 2;
-    /* The maximum number of generations is pixel_size dependent. This is a   */
+    /* The maximum number of generations is cell_size dependent. This is a    */
     /* soft limit and may be increased if you have plenty of RAM (and a       */
     /* cooperative X server). The value 10,000 was determined empirically.    */
     /* soft limit and may be increased if you have plenty of RAM (and a       */
     /* cooperative X server). The value 10,000 was determined empirically.    */
-    if ((long)state->num_generations * (long)state->pixel_size > 10000) {
-        state->num_generations = 10000 / state->pixel_size;
+    if ((long)state->num_generations * (long)state->cell_size > 10000) {
+        state->num_generations = 10000 / state->cell_size;
     }
 
     /* Time to figure out which rule to use for this simulation.              */
     }
 
     /* Time to figure out which rule to use for this simulation.              */
@@ -445,19 +435,16 @@ WolframAutomata_init(Display * dpy, Window win)
         }
     }
 
         }
     }
 
-    // TODO: These should be command-line options, but I need to learn how the get_integer_resource() and similar functions work first.
-    state->display_info = True;
-
-    state->evolution_history = XCreatePixmap(state->dpy, state->win, state->xlim, state->num_generations*state->pixel_size, xgwa.depth);
-    // Pixmap contents are undefined after creation. Explicitly set a black
-    // background by drawing a black rectangle over the entire pixmap.
+    state->evolution_history = XCreatePixmap(state->dpy, state->win, state->dpy_width, state->num_generations*state->cell_size, xgwa.depth);
+    /* Pixmap contents are undefined after creation. Explicitly set a black   */
+    /* background by drawing a black rectangle over the entire pixmap.        */
     XColor blackx, blacks;
     XAllocNamedColor(state->dpy, DefaultColormapOfScreen(DefaultScreenOfDisplay(state->dpy)), "black", &blacks, &blackx);
     XSetForeground(state->dpy, state->gc, blacks.pixel);
     XColor blackx, blacks;
     XAllocNamedColor(state->dpy, DefaultColormapOfScreen(DefaultScreenOfDisplay(state->dpy)), "black", &blacks, &blackx);
     XSetForeground(state->dpy, state->gc, blacks.pixel);
-    XFillRectangle(state->dpy, state->evolution_history, state->gc, 0, 0, state->xlim, state->num_generations*state->pixel_size);
+    XFillRectangle(state->dpy, state->evolution_history, state->gc, 0, 0, state->dpy_width, state->num_generations*state->cell_size);
     XSetForeground(state->dpy, state->gc, state->fg);
     render_current_generation(state);
     XSetForeground(state->dpy, state->gc, state->fg);
     render_current_generation(state);
-    state->ypos += state->pixel_size;
+    state->ypos += state->cell_size;
 
     return state;
 }
 
     return state;
 }
@@ -465,19 +452,12 @@ WolframAutomata_init(Display * dpy, Window win)
 static unsigned long
 WolframAutomata_draw(Display * dpy, Window win, void * closure)
 {
 static unsigned long
 WolframAutomata_draw(Display * dpy, Window win, void * closure)
 {
-// TODO: Mark these basic sections of the function
-//draw()
-//    calculate (and store) new generation
-//    draw new generation as line of pixels on pixmap
-//    calculate current 'viewport' into pixmap
-//    display on screen
-//  check for termination condition
-
     struct state * state = closure;
     int xpos;
     int window_y_offset;
 
     struct state * state = closure;
     int xpos;
     int window_y_offset;
 
-    Bool new_generation[state->xlim];
+    /* Calculate and record new generation.                                   */
+    Bool new_generation[state->dpy_width];
     for (xpos = 0; xpos < state->number_of_cells; xpos++) {
         new_generation[xpos] = calculate_cell(state, xpos);
     }
     for (xpos = 0; xpos < state->number_of_cells; xpos++) {
         new_generation[xpos] = calculate_cell(state, xpos);
     }
@@ -486,78 +466,80 @@ WolframAutomata_draw(Display * dpy, Window win, void * closure)
     }
     render_current_generation(state);
 
     }
     render_current_generation(state);
 
-    // Was this the final generation of this particular simulation? If so, give
-    // the user a moment to bask in the glory of our output and then start a
-    // new simulation.
-    if (state->ypos/state->pixel_size < state->num_generations-1) {
-        state->ypos += state->pixel_size;
+    /* Check for end of simulation.                                           */
+    if (state->ypos/state->cell_size < state->num_generations-1) {
+        /* Life continues.                                                    */
+        state->ypos += state->cell_size;
     } else {
     } else {
-        // TODO: Wait for a second or two, clear the screen and do a new iteration with suitably changed settings.
-        // Note: Since we can't actually loop or sleep here, we need to add a flag to the state struct to indicate that we're in an 'admiration timewindow' (and indicate when it should end)
-        WolframAutomata_free(dpy, win, state);
-        closure = WolframAutomata_init(dpy, win);
+        /* We have reached the end of this simulation. Give the user a moment */
+        /* to bask in the glory of our output, then reset.                    */
+        if (state->admiration_in_progress) {
+            WolframAutomata_free(dpy, win, state);
+            closure = WolframAutomata_init(dpy, win);
+        } else {
+            state->admiration_in_progress = True;
+            return state->admiration_delay;
+        }
     }
 
     }
 
-    // Calculate the vertical offset of the current 'window' into the history
-    // of the CA. After the CA's evolution extends past what we can display, have
-    // the window track the current generation and most recent history.
-    if (state->ypos < state->ylim) {
+    /* Calculate vertical offset of current 'window' into the CA's history.   */
+    /* After the CA evolution exceeds our display extents, make window track  */
+    /* current generation, scrolling display to follow newest generation.     */
+    if (state->ypos < state->dpy_height) {
         window_y_offset = 0;
     } else {
         window_y_offset = 0;
     } else {
-        window_y_offset = state->ypos - (state->ylim - 1);
+        window_y_offset = state->ypos - (state->dpy_height - 1);
     }
 
     }
 
-    // Render everything to the display.
-    XCopyArea(state->dpy, state->evolution_history, state->win, state->gc, 0, window_y_offset, state->xlim, state->ylim, 0, 0);
-    // TODO: Print info on screen if display_info is true. Will need fonts/etc. Do I want to create a separate pixmap for this during the init() function and then just copy the pixmap each time we draw the screen in draw()?
+    /* Render a window into the CA history.                                   */
+    XCopyArea(state->dpy, state->evolution_history, state->win, state->gc, 0, window_y_offset, state->dpy_width, state->dpy_height, 0, 0);
 
     return state->delay_microsec;
 }
 
 
     return state->delay_microsec;
 }
 
-// TODO: Fix formatting
 static const char * WolframAutomata_defaults[] = {
 static const char * WolframAutomata_defaults[] = {
-    ".background:    black",
-    ".foreground:    white",
-    "*random-colors: False",
-    "*delay-usec:    25000",
-    // TODO: Difference between dot and asterisk? Presumably the asterisk matches all resouces of attribute "pixelsize"? Apply answer to all new options.
-    "*pixel-size:    2",
+    "*delay-usec:         25000",
     "*num-generations:    5000",
     "*num-generations:    5000",
-    "*rule-requested:    0",
-    "*rule-random:    False",
-    "*population-density:    50",
-    "*population-single:    False",
-    "*random-delay:    False",
-    "*random-pixel-size:    False",
-    "*random-num-generations:    False",
+    "*pixel-size:         2",
+    "*population-density: 50",
+    "*population-single:  False",
+    "*random-cellsize:    False",
+    "*random-color:       False",
+    "*random-delay:       False",
+    "*random-length:      False",
+    "*random-rule:        False",
+    "*rule-requested:     0",
     0
 };
 
     0
 };
 
-// TODO: Fix formatting
 static XrmOptionDescRec WolframAutomata_options[] = {
 static XrmOptionDescRec WolframAutomata_options[] = {
-    { "-background",        ".background",    XrmoptionSepArg, 0},
-    { "-foreground",        ".foreground",    XrmoptionSepArg, 0},
-    { "-random-colors",        ".random-colors",    XrmoptionNoArg, "True"},
-    { "-delay-usec",        ".delay-usec",    XrmoptionSepArg, 0 },
-    { "-pixel-size",    ".pixel-size",    XrmoptionSepArg, 0 },
-    { "-num-generations",    ".num-generations",    XrmoptionSepArg, 0 },
-    { "-rule",    ".rule-requested",    XrmoptionSepArg, 0 },
-    { "-rule-random",    ".rule-random",    XrmoptionNoArg, "True" },
-    { "-population-density",    ".population-density",    XrmoptionSepArg, 0 },
-    { "-population-single",    ".population-single",    XrmoptionNoArg, "True" },
-    { "-random-delay", ".random-delay", XrmoptionNoArg, "True" },
-    { "-random-pixel-size", ".random-pixel-size", XrmoptionNoArg, "True" },
-    { "-random-num-generations", ".random-num-generations", XrmoptionNoArg, "True" },
-
+    { "-delay-usec",         ".delay-usec",             XrmoptionSepArg, 0      },
+    { "-num-generations",    ".num-generations",        XrmoptionSepArg, 0      },
+    { "-pixel-size",         ".pixel-size",             XrmoptionSepArg, 0      },
+    { "-population-density", ".population-density",     XrmoptionSepArg, 0      },
+    { "-population-single",  ".population-single",      XrmoptionNoArg,  "True" },
+    { "-random-cellsize",    ".random-pixel-size",      XrmoptionNoArg,  "True" },
+    { "-random-color",       ".random-colors",          XrmoptionNoArg,  "True" },
+    { "-random-delay",       ".random-delay",           XrmoptionNoArg,  "True" },
+    { "-random-length",      ".random-num-generations", XrmoptionNoArg,  "True" },
+    { "-random-rule",        ".rule-random",            XrmoptionNoArg,  "True" },
+    { "-rule",               ".rule-requested",         XrmoptionSepArg, 0      },
     { 0, 0, 0, 0 }
 };
 
 static void
 WolframAutomata_reshape(Display * dpy, Window win, void * closure, unsigned int w, unsigned int h)
 {
     { 0, 0, 0, 0 }
 };
 
 static void
 WolframAutomata_reshape(Display * dpy, Window win, void * closure, unsigned int w, unsigned int h)
 {
-    WolframAutomata_free(dpy, win, closure);
-    closure = WolframAutomata_init(dpy, win);
+    struct state * state = closure;
+    XWindowAttributes xgwa;
+    XGetWindowAttributes(state->dpy, state->win, &xgwa);
+
+    /* Only restart the simulation if the window changed size.                */
+    if (state->dpy_width != xgwa.width || state->dpy_height != xgwa.height) {
+        WolframAutomata_free(dpy, win, closure);
+        closure = WolframAutomata_init(dpy, win);
+    }
 }
 
 }
 
-XSCREENSAVER_MODULE ("1D Nearest-Neighbor Cellular Automata", HACKNAME)
+XSCREENSAVER_MODULE ("1D Nearest-Neighbor Cellular Automata", WolframAutomata)