more work
[pspp] / src / language / stats / ctables.c
index 585753664a549703c1acf09b93b6c3bc3f9d6872..624331ba5d108429fcd220aca672eef66de6be65 100644 (file)
@@ -58,6 +58,100 @@ ctables_vlabel_unique (enum ctables_vlabel vlabel)
     }
 }
 
+/* XXX:
+   - unweighted summaries (U*)
+   - lower confidence limits (*.LCL)
+   - upper confidence limits (*.UCL)
+   - standard error (*.SE)
+ */
+#define SUMMARIES                                                       \
+    /* All variables. */                                                \
+    S(CTSF_COUNT, "COUNT", N_("Count"), CTF_COUNT, CTFA_ALL)            \
+    S(CTSF_ECOUNT, "ECOUNT", N_("Adjusted Count"), CTF_COUNT, CTFA_ALL) \
+    S(CTSF_ROWPCT_COUNT, "ROWPCT.COUNT", N_("Row %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_COLPCT_COUNT, "COLPCT.COUNT", N_("Column %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_TABLEPCT_COUNT, "TABLEPCT.COUNT", N_("Table %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT.COUNT", N_("Subtable %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_LAYERPCT_COUNT, "LAYERPCT.COUNT", N_("Layer %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT.COUNT", N_("Layer Row %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT.COUNT", N_("Layer Column %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_ROWPCT_VALIDN, "ROWPCT.VALIDN", N_("Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_COLPCT_VALIDN, "COLPCT.VALIDN", N_("Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_TABLEPCT_VALIDN, "TABLEPCT.VALIDN", N_("Table Valid N %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_SUBTABLEPCT_VALIDN, "SUBTABLEPCT.VALIDN", N_("Subtable Valid N %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_LAYERPCT_VALIDN, "LAYERPCT.VALIDN", N_("Layer Valid N %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_LAYERROWPCT_VALIDN, "LAYERROWPCT.VALIDN", N_("Layer Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_LAYERCOLPCT_VALIDN, "LAYERCOLPCT.VALIDN", N_("Layer Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_ROWPCT_TOTALN, "ROWPCT.TOTALN", N_("Row Total N %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_COLPCT_TOTALN, "COLPCT.TOTALN", N_("Column Total N %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_TABLEPCT_TOTALN, "TABLEPCT.TOTALN", N_("Table Total N %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_SUBTABLEPCT_TOTALN, "SUBTABLEPCT.TOTALN", N_("Subtable Total N %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_LAYERPCT_TOTALN, "LAYERPCT.TOTALN", N_("Layer Total N %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_LAYERROWPCT_TOTALN, "LAYERROWPCT.TOTALN", N_("Layer Row Total N %"), CTF_PERCENT, CTFA_ALL) \
+    S(CTSF_LAYERCOLPCT_TOTALN, "LAYERCOLPCT.TOTALN", N_("Layer Column Total N %"), CTF_PERCENT, CTFA_ALL) \
+                                                                        \
+    /* Scale variables, totals, and subtotals. */                       \
+    S(CTSF_MAXIMUM, "MAXIMUM", N_("Maximum"), CTF_GENERAL, CTFA_SCALE)  \
+    S(CTSF_MEAN, "MEAN", N_("Mean"), CTF_GENERAL, CTFA_SCALE)           \
+    S(CTSF_MEDIAN, "MEDIAN", N_("Median"), CTF_GENERAL, CTFA_SCALE)     \
+    S(CTSF_MINIMUM, "MINIMUM", N_("Minimum"), CTF_GENERAL, CTFA_SCALE)  \
+    S(CTSF_MISSING, "MISSING", N_("Missing"), CTF_GENERAL, CTFA_SCALE)  \
+    S(CTSF_MODE, "MODE", N_("Mode"), CTF_GENERAL, CTFA_SCALE)           \
+    S(CTSF_PTILE, "PTILE", N_("Percentile"), CTF_GENERAL, CTFA_SCALE)   \
+    S(CTSF_RANGE, "RANGE", N_("Range"), CTF_GENERAL, CTFA_SCALE)        \
+    S(CTSF_SEMEAN, "SEMEAN", N_("Std Error of Mean"), CTF_GENERAL, CTFA_SCALE) \
+    S(CTSF_STDDEV, "STDDEV", N_("Std Deviation"), CTF_GENERAL, CTFA_SCALE) \
+    S(CTSF_SUM, "SUM", N_("Sum"), CTF_GENERAL, CTFA_SCALE)              \
+    S(CSTF_TOTALN, "TOTALN", N_("Total N"), CTF_COUNT, CTFA_SCALE)      \
+    S(CTSF_ETOTALN, "ETOTALN", N_("Adjusted Total N"), CTF_COUNT, CTFA_SCALE) \
+    S(CTSF_VALIDN, "VALIDN", N_("Valid N"), CTF_COUNT, CTFA_SCALE)      \
+    S(CTSF_EVALIDN, "EVALIDN", N_("Adjusted Valid N"), CTF_COUNT, CTFA_SCALE) \
+    S(CTSF_VARIANCE, "VARIANCE", N_("Variance"), CTF_GENERAL, CTFA_SCALE) \
+    S(CTSF_ROWPCT_SUM, "ROWPCT.SUM", N_("Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
+    S(CTSF_COLPCT_SUM, "COLPCT.SUM", N_("Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
+    S(CTSF_TABLEPCT_SUM, "TABLEPCT.SUM", N_("Table Sum %"), CTF_PERCENT, CTFA_SCALE) \
+    S(CTSF_SUBTABLEPCT_SUM, "SUBTABLEPCT.SUM", N_("Subtable Sum %"), CTF_PERCENT, CTFA_SCALE) \
+    S(CTSF_LAYERPCT_SUM, "LAYERPCT.SUM", N_("Layer Sum %"), CTF_PERCENT, CTFA_SCALE) \
+    S(CTSF_LAYERROWPCT_SUM, "LAYERROWPCT.SUM", N_("Layer Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
+    S(CTSF_LAYERCOLPCT_SUM, "LAYERCOLPCT.SUM", N_("Layer Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
+                                                                        \
+    /* Multiple response sets. */                                       \
+  S(CTSF_RESPONSES, "RESPONSES", N_("Responses"), CTF_COUNT, CTFA_MRSETS) \
+    S(CTSF_ROWPCT_RESPONSES, "ROWPCT.RESPONSES", N_("Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_COLPCT_RESPONSES, "COLPCT.RESPONSES", N_("Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_TABLEPCT_RESPONSES, "TABLEPCT.RESPONSES", N_("Table Responses %"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_SUBTABLEPCT_RESPONSES, "SUBTABLEPCT.RESPONSES", N_("Subtable Responses %"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_LAYERPCT_RESPONSES, "LAYERPCT.RESPONSES", N_("Layer Responses %"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_LAYERROWPCT_RESPONSES, "LAYERROWPCT.RESPONSES", N_("Layer Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_LAYERCOLPCT_RESPONSES, "LAYERCOLPCT.RESPONSES", N_("Layer Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_ROWPCT_RESPONSES_COUNT, "ROWPCT.RESPONSES.COUNT", N_("Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_COLPCT_RESPONSES_COUNT, "COLPCT.RESPONSES.COUNT", N_("Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_TABLEPCT_RESPONSES_COUNT, "TABLEPCT.RESPONSES.COUNT", N_("Table Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_SUBTABLEPCT_RESPONSES_COUNT, "SUBTABLEPCT.RESPONSES.COUNT", N_("Subtable Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_LAYERPCT_RESPONSES_COUNT, "LAYERPCT.RESPONSES.COUNT", N_("Layer Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_LAYERROWPCT_RESPONSES_COUNT, "LAYERROWPCT.RESPONSES.COUNT", N_("Layer Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_LAYERCOLPCT_RESPONSES_COUNT, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_ROWPCT_COUNT_RESPONSES, "ROWPCT.COUNT.RESPONSES", N_("Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_COLPCT_COUNT_RESPONSES, "COLPCT.COUNT.RESPONSES", N_("Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_TABLEPCT_COUNT_RESPONSES, "TABLEPCT.COUNT.RESPONSES", N_("Table Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_SUBTABLEPCT_COUNT_RESPONSES, "SUBTABLEPCT.COUNT.RESPONSES", N_("Subtable Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_LAYERPCT_COUNT_RESPONSES, "LAYERPCT.COUNT.RESPONSES", N_("Layer Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_LAYERROWPCT_COUNT_RESPONSES, "LAYERROWPCT.COUNT.RESPONSES", N_("Layer Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
+    S(CTSF_LAYERCOLPCT_COUNT_RESPONSES, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS)
+
+enum ctables_summary_function
+  {
+#define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) ENUM,
+    SUMMARIES
+#undef S
+  };
+
+enum {
+#define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) +1
+  N_CTSF_FUNCTIONS = SUMMARIES
+#undef S
+};
+
 struct ctables
   {
     struct pivot_table_look *look;
@@ -122,12 +216,7 @@ struct ctables_postcompute_expr
         /* CTPO_CAT_RANGE.
 
            XXX what about string ranges? */
-        struct
-          {
-            double low;         /* -DBL_MAX for LO. */
-            double high;        /* DBL_MAX for HIGH. */
-          }
-        range;
+        double range[2];
 
         /* CTPO_ADD, CTPO_SUB, CTPO_MUL, CTPO_DIV, CTPO_POW. */
         struct ctables_postcompute_expr *subs[2];
@@ -151,7 +240,9 @@ struct ctables_table
     enum ctables_label_position row_labels;
     enum ctables_label_position col_labels;
 
-    /* XXX CATEGORIES */
+    /* Indexed by variable dictionary index. */
+    struct ctables_categories **categories;
+    size_t n_categories;
 
     double cilevel;
 
@@ -163,6 +254,119 @@ struct ctables_table
     struct ctables_pairwise *pairwise;
   };
 
+struct ctables_var
+  {
+    bool is_mrset;
+    union
+      {
+        struct variable *var;
+        const struct mrset *mrset;
+      };
+  };
+
+static const struct fmt_spec *
+ctables_var_get_print_format (const struct ctables_var *var)
+{
+  return (var->is_mrset
+          ? var_get_print_format (var->mrset->vars[0])
+          : var_get_print_format (var->var));
+}
+
+static const char *
+ctables_var_name (const struct ctables_var *var)
+{
+  return var->is_mrset ? var->mrset->name : var_get_name (var->var);
+}
+
+struct ctables_categories
+  {
+    size_t n_refs;
+
+    /* Explicit categories. */
+    struct ctables_cat_value *values;
+    size_t n_values;
+
+    /* Implicit categories. */
+    bool sort_ascending;
+    bool include_missing;
+    enum { CTCS_VALUE, CTCS_LABEL, CTCS_FUNCTION } key;
+    enum ctables_summary_function sort_func;
+    struct variable *sort_func_var;
+    double percentile;
+
+    /* Totals. */
+    bool show_totals;
+    bool totals_before;
+    char *total_label;
+
+    /* Empty categories. */
+    bool show_empty;
+  };
+
+struct ctables_cat_value
+  {
+    enum ctables_cat_value_type
+      {
+        CCVT_NUMBER,
+        CCVT_STRING,
+        CCVT_RANGE,
+        CCVT_MISSING,
+        CCVT_OTHERNM,
+        CCVT_SUBTOTAL,
+        CCVT_HSUBTOTAL,
+      }
+    type;
+
+    union
+      {
+        double number;          /* CCVT_NUMBER. */
+        char *string;           /* CCVT_STRING. */
+        double range[2];        /* CCVT_RANGE. */
+        char *subtotal_label;   /* CCVT_SUBTOTAL, CCVT_HSUBTOTAL. */
+      };
+  };
+
+static void
+ctables_cat_value_uninit (struct ctables_cat_value *cv)
+{
+  if (!cv)
+    return;
+
+  switch (cv->type)
+    {
+    case CCVT_NUMBER:
+    case CCVT_RANGE:
+    case CCVT_MISSING:
+    case CCVT_OTHERNM:
+      break;
+
+    case CCVT_STRING:
+      free (cv->string);
+      break;
+
+    case CCVT_SUBTOTAL:
+    case CCVT_HSUBTOTAL:
+      free (cv->subtotal_label);
+    }
+}
+
+static void
+ctables_categories_unref (struct ctables_categories *c)
+{
+  if (!c)
+    return;
+
+  assert (c->n_refs > 0);
+  if (--c->n_refs)
+    return;
+
+  for (size_t i = 0; i < c->n_values; i++)
+    ctables_cat_value_uninit (&c->values[i]);
+  free (c->values);
+  free (c->total_label);
+  free (c);
+}
+
 /* Chi-square test (SIGTEST). */
 struct ctables_chisq
   {
@@ -191,7 +395,6 @@ struct ctables_axis
       {
         /* Terminals. */
         CTAO_VAR,
-        CTAO_MRSET,
 
         /* Nonterminals. */
         CTAO_STACK,             /* + */
@@ -204,20 +407,18 @@ struct ctables_axis
         /* Terminals. */
         struct
           {
-            union
-              {
-                struct variable *var;
-                const struct mrset *mrset;
-              };
-
+            struct ctables_var var;
             bool scale;
             struct ctables_summary *summaries;
             size_t n_summaries;
+            size_t allocated_summaries;
           };
 
         /* Nonterminals. */
         struct ctables_axis *subs[2];
       };
+
+    struct msg_location *loc;
   };
 
 static void ctables_axis_destroy (struct ctables_axis *);
@@ -229,94 +430,13 @@ enum ctables_format
     CTF_GENERAL
   };
 
-#define SUMMARIES                                                       \
-    /* All variables. */                                                \
-    S(CTSF_COUNT, "COUNT", N_("Count"), CTF_COUNT)                      \
-    S(CTSF_ECOUNT, "ECOUNT", N_("Adjusted Count"), CTF_COUNT)           \
-    S(CTSF_ROWPCT_COUNT, "ROWPCT.COUNT", N_("Row %"), CTF_PERCENT)      \
-    S(CTSF_COLPCT_COUNT, "COLPCT.COUNT", N_("Column %"), CTF_PERCENT)   \
-    S(CTSF_TABLEPCT_COUNT, "TABLEPCT.COUNT", N_("Table %"), CTF_PERCENT) \
-    S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT.COUNT", N_("Subtable %"), CTF_PERCENT) \
-    S(CTSF_LAYERPCT_COUNT, "LAYERPCT.COUNT", N_("Layer %"), CTF_PERCENT) \
-    S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT.COUNT", N_("Layer Row %"), CTF_PERCENT) \
-    S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT.COUNT", N_("Layer Column %"), CTF_PERCENT) \
-    S(CTSF_ROWPCT_VALIDN, "ROWPCT.VALIDN", N_("Row Valid N %"), CTF_PERCENT) \
-    S(CTSF_COLPCT_VALIDN, "COLPCT.VALIDN", N_("Column Valid N %"), CTF_PERCENT) \
-    S(CTSF_TABLEPCT_VALIDN, "TABLEPCT.VALIDN", N_("Table Valid N %"), CTF_PERCENT) \
-    S(CTSF_SUBTABLEPCT_VALIDN, "SUBTABLEPCT.VALIDN", N_("Subtable Valid N %"), CTF_PERCENT) \
-    S(CTSF_LAYERPCT_VALIDN, "LAYERPCT.VALIDN", N_("Layer Valid N %"), CTF_PERCENT) \
-    S(CTSF_LAYERROWPCT_VALIDN, "LAYERROWPCT.VALIDN", N_("Layer Row Valid N %"), CTF_PERCENT) \
-    S(CTSF_LAYERCOLPCT_VALIDN, "LAYERCOLPCT.VALIDN", N_("Layer Column Valid N %"), CTF_PERCENT) \
-    S(CTSF_ROWPCT_TOTALN, "ROWPCT.TOTALN", N_("Row Total N %"), CTF_PERCENT) \
-    S(CTSF_COLPCT_TOTALN, "COLPCT.TOTALN", N_("Column Total N %"), CTF_PERCENT) \
-    S(CTSF_TABLEPCT_TOTALN, "TABLEPCT.TOTALN", N_("Table Total N %"), CTF_PERCENT) \
-    S(CTSF_SUBTABLEPCT_TOTALN, "SUBTABLEPCT.TOTALN", N_("Subtable Total N %"), CTF_PERCENT) \
-    S(CTSF_LAYERPCT_TOTALN, "LAYERPCT.TOTALN", N_("Layer Total N %"), CTF_PERCENT) \
-    S(CTSF_LAYERROWPCT_TOTALN, "LAYERROWPCT.TOTALN", N_("Layer Row Total N %"), CTF_PERCENT) \
-    S(CTSF_LAYERCOLPCT_TOTALN, "LAYERCOLPCT.TOTALN", N_("Layer Column Total N %"), CTF_PERCENT) \
-                                                                        \
-    /* Scale variables, totals, and subtotals. */                       \
-    S(CTSF_MAXIMUM, "MAXIMUM", N_("Maximum"), CTF_GENERAL)              \
-    S(CTSF_MEAN, "MEAN", N_("Mean"), CTF_GENERAL)                       \
-    S(CTSF_MEDIAN, "MEDIAN", N_("Median"), CTF_GENERAL)                 \
-    S(CTSF_MINIMUM, "MINIMUM", N_("Minimum"), CTF_GENERAL)              \
-    S(CTSF_MISSING, "MISSING", N_("Missing"), CTF_GENERAL)              \
-    S(CTSF_MODE, "MODE", N_("Mode"), CTF_GENERAL)                       \
-    S(CTSF_PTILE, "PTILE", N_("Percentile"), CTF_GENERAL)               \
-    S(CTSF_RANGE, "RANGE", N_("Range"), CTF_GENERAL)                    \
-    S(CTSF_SEMEAN, "SEMEAN", N_("Std Error of Mean"), CTF_GENERAL)      \
-    S(CTSF_STDDEV, "STDDEV", N_("Std Deviation"), CTF_GENERAL)          \
-    S(CTSF_SUM, "SUM", N_("Sum"), CTF_GENERAL)                          \
-    S(CSTF_TOTALN, "TOTALN", N_("Total N"), CTF_COUNT)                  \
-    S(CTSF_ETOTALN, "ETOTALN", N_("Adjusted Total N"), CTF_COUNT)       \
-    S(CTSF_VALIDN, "VALIDN", N_("Valid N"), CTF_COUNT)                  \
-    S(CTSF_EVALIDN, "EVALIDN", N_("Adjusted Valid N"), CTF_COUNT)       \
-    S(CTSF_VARIANCE, "VARIANCE", N_("Variance"), CTF_GENERAL)           \
-    S(CTSF_ROWPCT_SUM, "ROWPCT.SUM", N_("Row Sum %"), CTF_PERCENT)      \
-    S(CTSF_COLPCT_SUM, "COLPCT.SUM", N_("Column Sum %"), CTF_PERCENT)   \
-    S(CTSF_TABLEPCT_SUM, "TABLEPCT.SUM", N_("Table Sum %"), CTF_PERCENT) \
-    S(CTSF_SUBTABLEPCT_SUM, "SUBTABLEPCT.SUM", N_("Subtable Sum %"), CTF_PERCENT) \
-    S(CTSF_LAYERPCT_SUM, "LAYERPCT.SUM", N_("Layer Sum %"), CTF_PERCENT) \
-    S(CTSF_LAYERROWPCT_SUM, "LAYERROWPCT.SUM", N_("Layer Row Sum %"), CTF_PERCENT) \
-    S(CTSF_LAYERCOLPCT_SUM, "LAYERCOLPCT.SUM", N_("Layer Column Sum %"), CTF_PERCENT) \
-                                                                        \
-    /* Multiple response sets. */                                       \
-    S(CTSF_RESPONSES, "RESPONSES", N_("Responses"), CTF_COUNT)           \
-    S(CTSF_ROWPCT_RESPONSES, "ROWPCT.RESPONSES", N_("Row Responses %"), CTF_PERCENT) \
-    S(CTSF_COLPCT_RESPONSES, "COLPCT.RESPONSES", N_("Column Responses %"), CTF_PERCENT) \
-    S(CTSF_TABLEPCT_RESPONSES, "TABLEPCT.RESPONSES", N_("Table Responses %"), CTF_PERCENT) \
-    S(CTSF_SUBTABLEPCT_RESPONSES, "SUBTABLEPCT.RESPONSES", N_("Subtable Responses %"), CTF_PERCENT) \
-    S(CTSF_LAYERPCT_RESPONSES, "LAYERPCT.RESPONSES", N_("Layer Responses %"), CTF_PERCENT) \
-    S(CTSF_LAYERROWPCT_RESPONSES, "LAYERROWPCT.RESPONSES", N_("Layer Row Responses %"), CTF_PERCENT) \
-    S(CTSF_LAYERCOLPCT_RESPONSES, "LAYERCOLPCT.RESPONSES", N_("Layer Column Responses %"), CTF_PERCENT) \
-    S(CTSF_ROWPCT_RESPONSES_COUNT, "ROWPCT.RESPONSES.COUNT", N_("Row Responses % (Base: Count)"), CTF_PERCENT) \
-    S(CTSF_COLPCT_RESPONSES_COUNT, "COLPCT.RESPONSES.COUNT", N_("Column Responses % (Base: Count)"), CTF_PERCENT) \
-    S(CTSF_TABLEPCT_RESPONSES_COUNT, "TABLEPCT.RESPONSES.COUNT", N_("Table Responses % (Base: Count)"), CTF_PERCENT) \
-    S(CTSF_SUBTABLEPCT_RESPONSES_COUNT, "SUBTABLEPCT.RESPONSES.COUNT", N_("Subtable Responses % (Base: Count)"), CTF_PERCENT) \
-    S(CTSF_LAYERPCT_RESPONSES_COUNT, "LAYERPCT.RESPONSES.COUNT", N_("Layer Responses % (Base: Count)"), CTF_PERCENT) \
-    S(CTSF_LAYERROWPCT_RESPONSES_COUNT, "LAYERROWPCT.RESPONSES.COUNT", N_("Layer Row Responses % (Base: Count)"), CTF_PERCENT) \
-    S(CTSF_LAYERCOLPCT_RESPONSES_COUNT, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Responses % (Base: Count)"), CTF_PERCENT) \
-    S(CTSF_ROWPCT_COUNT_RESPONSES, "ROWPCT.COUNT.RESPONSES", N_("Row Count % (Base: Responses)"), CTF_PERCENT) \
-    S(CTSF_COLPCT_COUNT_RESPONSES, "COLPCT.COUNT.RESPONSES", N_("Column Count % (Base: Responses)"), CTF_PERCENT) \
-    S(CTSF_TABLEPCT_COUNT_RESPONSES, "TABLEPCT.COUNT.RESPONSES", N_("Table Count % (Base: Responses)"), CTF_PERCENT) \
-    S(CTSF_SUBTABLEPCT_COUNT_RESPONSES, "SUBTABLEPCT.COUNT.RESPONSES", N_("Subtable Count % (Base: Responses)"), CTF_PERCENT) \
-    S(CTSF_LAYERPCT_COUNT_RESPONSES, "LAYERPCT.COUNT.RESPONSES", N_("Layer Count % (Base: Responses)"), CTF_PERCENT) \
-    S(CTSF_LAYERROWPCT_COUNT_RESPONSES, "LAYERROWPCT.COUNT.RESPONSES", N_("Layer Row Count % (Base: Responses)"), CTF_PERCENT) \
-    S(CTSF_LAYERCOLPCT_COUNT_RESPONSES, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Count % (Base: Responses)"), CTF_PERCENT)
-
-enum ctables_summary_function
+enum ctables_function_availability
   {
-#define S(ENUM, NAME, LABEL, FORMAT) ENUM,
-    SUMMARIES
-#undef S
+    CTFA_ALL,                /* Any variables. */
+    CTFA_SCALE,              /* Only scale variables, totals, and subtotals. */
+    CTFA_MRSETS,             /* Only multiple-response sets */
   };
 
-enum {
-#define S(ENUM, NAME, LABEL, FORMAT) +1
-  N_CTSF_FUNCTIONS = SUMMARIES
-#undef S
-};
-
 struct ctables_summary
   {
     enum ctables_summary_function function;
@@ -364,6 +484,18 @@ parse_bool (struct lexer *lexer, bool *b)
   return true;
 }
 
+static enum ctables_function_availability
+ctables_function_availability (enum ctables_summary_function f)
+{
+  static enum ctables_function_availability availability[] = {
+#define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = AVAILABILITY,
+    SUMMARIES
+#undef S
+  };
+
+  return availability[f];
+}
+
 static bool
 parse_ctables_summary_function (struct lexer *lexer,
                                 enum ctables_summary_function *f)
@@ -374,17 +506,18 @@ parse_ctables_summary_function (struct lexer *lexer,
       struct substring name;
     };
   static struct pair names[] = {
-#define S(ENUM, NAME, LABEL, FORMAT) { ENUM, SS_LITERAL_INITIALIZER (NAME) },
+#define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) \
+    { ENUM, SS_LITERAL_INITIALIZER (NAME) },
     SUMMARIES
 
     /* The .COUNT suffix may be omitted. */
-    S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _)
-    S(CTSF_COLPCT_COUNT, "COLPCT", _, _)
-    S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _)
-    S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _)
-    S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _)
-    S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _)
-    S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _)
+    S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _, _)
+    S(CTSF_COLPCT_COUNT, "COLPCT", _, _, _)
+    S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _, _)
+    S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _, _)
+    S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _, _)
+    S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _, _)
+    S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _, _)
 #undef S
   };
 
@@ -395,6 +528,7 @@ parse_ctables_summary_function (struct lexer *lexer,
     if (ss_equals_case (names[i].name, lex_tokss (lexer)))
       {
         *f = names[i].function;
+        lex_get (lexer);
         return true;
       }
 
@@ -411,7 +545,6 @@ ctables_axis_destroy (struct ctables_axis *axis)
   switch (axis->op)
     {
     case CTAO_VAR:
-    case CTAO_MRSET:
       for (size_t i = 0; i < axis->n_summaries; i++)
         ctables_summary_uninit (&axis->summaries[i]);
       free (axis->summaries);
@@ -423,16 +556,22 @@ ctables_axis_destroy (struct ctables_axis *axis)
       ctables_axis_destroy (axis->subs[1]);
       break;
     }
+  msg_location_destroy (axis->loc);
   free (axis);
 }
 
 static struct ctables_axis *
 ctables_axis_new_nonterminal (enum ctables_axis_op op,
                               struct ctables_axis *sub0,
-                              struct ctables_axis *sub1)
+                              struct ctables_axis *sub1,
+                              struct lexer *lexer, int start_ofs)
 {
   struct ctables_axis *axis = xmalloc (sizeof *axis);
-  *axis = (struct ctables_axis) { .op = op, .subs = { sub0, sub1 } };
+  *axis = (struct ctables_axis) {
+    .op = op,
+    .subs = { sub0, sub1 },
+    .loc = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
+  };
   return axis;
 }
 
@@ -444,62 +583,139 @@ struct ctables_axis_parse_ctx
     struct ctables_table *t;
   };
 
-static struct ctables_summary *
-add_summary (struct ctables_axis *axis, enum ctables_summary_function function,
-             double percentile, size_t *allocated_summaries)
+static struct fmt_spec
+ctables_summary_default_format (enum ctables_summary_function function,
+                                const struct ctables_var *var)
 {
-  if (axis->n_summaries >= *allocated_summaries)
-    axis->summaries = x2nrealloc (axis->summaries, allocated_summaries,
-                                  sizeof *axis->summaries);
-
-  static const char *default_labels[] = {
-#define S(ENUM, NAME, LABEL, FORMAT) [ENUM] = LABEL,
-    SUMMARIES
-#undef S
-  };
-  char *label = (function == CTSF_PTILE
-                 ? xasprintf (_("Percentile %.2f"), percentile)
-                 : xstrdup (gettext (default_labels[function])));
-
   static const enum ctables_format default_formats[] = {
-#define S(ENUM, NAME, LABEL, FORMAT) [ENUM] = FORMAT,
+#define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
     SUMMARIES
 #undef S
   };
-  struct fmt_spec format;
   switch (default_formats[function])
     {
     case CTF_COUNT:
-      format = (struct fmt_spec) { .type = FMT_F, .w = 40 };
-      break;
+      return (struct fmt_spec) { .type = FMT_F, .w = 40 };
 
     case CTF_PERCENT:
-      format = (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
-      break;
+      return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
 
     case CTF_GENERAL:
-      format = *(axis->op == CTAO_VAR
-                 ? var_get_print_format (axis->var)
-                 : var_get_print_format (axis->mrset->vars[0]));
-      break;
+      return *ctables_var_get_print_format (var);
 
     default:
       NOT_REACHED ();
     }
+}
 
-  struct ctables_summary *s = &axis->summaries[axis->n_summaries++];
-  *s = (struct ctables_summary) {
-    .function = function,
-    .percentile = percentile,
-    .label = label,
-    .format = format,
+static const char *
+ctables_summary_function_name (enum ctables_summary_function function)
+{
+  static const char *names[] = {
+#define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = NAME,
+    SUMMARIES
+#undef S
   };
-  return s;
+  return names[function];
+}
+
+static bool
+add_summary (struct ctables_axis *axis,
+             enum ctables_summary_function function, double percentile,
+             const char *label, const struct fmt_spec *format,
+             const struct msg_location *loc)
+{
+  if (axis->op == CTAO_VAR)
+    {
+      if (axis->n_summaries >= axis->allocated_summaries)
+        axis->summaries = x2nrealloc (axis->summaries,
+                                      &axis->allocated_summaries,
+                                      sizeof *axis->summaries);
+
+      const char *function_name = ctables_summary_function_name (function);
+      const char *var_name = ctables_var_name (&axis->var);
+      switch (ctables_function_availability (function))
+        {
+        case CTFA_MRSETS:
+          if (!axis->var.is_mrset)
+            {
+              msg_at (SE, loc, _("Summary function %s applies only to multiple "
+                                 "response sets."), function_name);
+              msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
+                      var_name);
+              return false;
+            }
+          break;
+
+        case CTFA_SCALE:
+          if (!axis->scale)
+            {
+              msg_at (SE, loc,
+                      _("Summary function %s applies only to scale variables."),
+                      function_name);
+              msg_at (SN, axis->loc, _("'%s' is not a scale variable."),
+                      var_name);
+              return false;
+            }
+          break;
+
+        case CTFA_ALL:
+          break;
+        }
+
+      struct ctables_summary *dst = &axis->summaries[axis->n_summaries++];
+      *dst = (struct ctables_summary) {
+        .function = function,
+        .percentile = percentile,
+        .label = xstrdup (label),
+        .format = (format ? *format
+                   : ctables_summary_default_format (function, &axis->var)),
+      };
+      return true;
+    }
+  else
+    {
+      for (size_t i = 0; i < 2; i++)
+        if (!add_summary (axis->subs[i], function, percentile, label, format,
+                          loc))
+          return false;
+      return true;
+    }
 }
 
 static struct ctables_axis *ctables_axis_parse_stack (
   struct ctables_axis_parse_ctx *);
 
+static bool
+ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
+                   struct ctables_var *var)
+{
+  if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
+    {
+      *var = (struct ctables_var) {
+        .is_mrset = true,
+        .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
+      };
+      if (!var->mrset)
+        {
+          lex_error (lexer, _("'%s' does not name a multiple-response set "
+                              "in the active file dictionary."),
+                     lex_tokcstr (lexer));
+          return false;
+        }
+      lex_get (lexer);
+      return true;
+    }
+  else
+    {
+      *var = (struct ctables_var) {
+        .is_mrset = false,
+        .var = parse_variable (lexer, dict),
+      };
+      return var->var != NULL;
+    }
+}
+
 static struct ctables_axis *
 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
 {
@@ -517,101 +733,191 @@ ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
   if (!lex_force_id (ctx->lexer))
     return NULL;
 
-  const struct mrset *mrset = NULL;
-  struct variable *var = NULL;
-  if (ss_starts_with (lex_tokss (ctx->lexer), ss_cstr ("$")))
-    {
-      mrset = dict_lookup_mrset (ctx->dict, lex_tokcstr (ctx->lexer));
-      if (!mrset)
-        {
-          lex_error (ctx->lexer, _("'%s' is not the name of a "
-                                   "multiple-response set in the active file "
-                                   "dictionary."),
-                     lex_tokcstr (ctx->lexer));
-          return NULL;
-        }
-      lex_get (ctx->lexer);
-    }
-  else
-    {
-      var = parse_variable (ctx->lexer, ctx->dict);
-      if (!var)
-        return NULL;
-    }
+  int start_ofs = lex_ofs (ctx->lexer);
+  struct ctables_var var;
+  if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
+    return NULL;
 
   struct ctables_axis *axis = xmalloc (sizeof *axis);
-  if (mrset)
-    *axis = (struct ctables_axis) { .op = CTAO_MRSET, .mrset = mrset };
-  else
-    *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
+  *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
 
   /* XXX should figure out default measures by reading data */
-  axis->scale = (mrset ? false
+  axis->scale = (var.is_mrset ? false
                  : lex_match_phrase (ctx->lexer, "[S]") ? true
                  : lex_match_phrase (ctx->lexer, "[C]") ? false
-                 : var_get_measure (var) == MEASURE_SCALE);
+                 : var_get_measure (var.var) == MEASURE_SCALE);
+  axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
+                                lex_ofs (ctx->lexer) - 1);
+  return axis;
+}
 
-  size_t allocated_summaries = 0;
-  if (lex_match (ctx->lexer, T_LBRACK))
+static struct ctables_axis *
+ctables_axis_parse_postfix (struct ctables_axis_parse_ctx *ctx)
+{
+  struct ctables_axis *sub = ctables_axis_parse_primary (ctx);
+  if (!sub || !lex_match (ctx->lexer, T_LBRACK))
+    return sub;
+
+  do
     {
-      do
+      int start_ofs = lex_ofs (ctx->lexer);
+
+      /* Parse function. */
+      enum ctables_summary_function function;
+      if (!parse_ctables_summary_function (ctx->lexer, &function))
+        goto error;
+
+      /* Parse percentile. */
+      double percentile = 0;
+      if (function == CTSF_PTILE)
         {
-          enum ctables_summary_function function;
-          if (!parse_ctables_summary_function (ctx->lexer, &function))
+          if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
             goto error;
+          percentile = lex_number (ctx->lexer);
+          lex_get (ctx->lexer);
+        }
 
-          double percentile = 0;
-          if (function == CTSF_PTILE)
-            {
-              if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
-                goto error;
-              percentile = lex_number (ctx->lexer);
-              lex_get (ctx->lexer);
-            }
+      /* Parse label. */
+      char *label;
+      if (lex_is_string (ctx->lexer))
+        {
+          label = ss_xstrdup (lex_tokss (ctx->lexer));
+          lex_get (ctx->lexer);
+        }
+      else if (function == CTSF_PTILE)
+        label = xasprintf (_("Percentile %.2f"), percentile);
+      else
+        {
+          static const char *default_labels[] = {
+#define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = LABEL,
+            SUMMARIES
+#undef S
+          };
+          label = xstrdup (gettext (default_labels[function]));
+        }
 
-          struct ctables_summary *s = add_summary (axis, function, percentile,
-                                                   &allocated_summaries);
-          if (lex_is_string (ctx->lexer))
-            {
-              free (s->label);
-              s->label = ss_xstrdup (lex_tokss (ctx->lexer));
-              lex_get (ctx->lexer);
-            }
-          if (lex_token (ctx->lexer) == T_ID)
+      /* Parse format. */
+      struct fmt_spec format;
+      const struct fmt_spec *formatp;
+      if (lex_token (ctx->lexer) == T_ID)
+        {
+          if (!parse_format_specifier (ctx->lexer, &format)
+              || !fmt_check_output (&format)
+              || !fmt_check_type_compat (&format, VAL_NUMERIC))
             {
-              if (!parse_format_specifier (ctx->lexer, &s->format)
-                  || !fmt_check_output (&s->format)
-                  || !fmt_check_type_compat (&s->format, VAL_NUMERIC))
-                goto error;
+              free (label);
+              goto error;
             }
-          lex_match (ctx->lexer, T_COMMA);
+          formatp = &format;
         }
-      while (!lex_match (ctx->lexer, T_RBRACK));
+      else
+        formatp = NULL;
+
+      struct msg_location *loc = lex_ofs_location (ctx->lexer, start_ofs,
+                                                   lex_ofs (ctx->lexer) - 1);
+      add_summary (sub, function, percentile, label, formatp, loc);
+      free (label);
+      msg_location_destroy (loc);
+
+      lex_match (ctx->lexer, T_COMMA);
     }
-  else
-    add_summary (axis, axis->scale ? CTSF_MEAN : CTSF_COUNT, 0,
-                 &allocated_summaries);
-  return axis;
+  while (!lex_match (ctx->lexer, T_RBRACK));
+
+  return sub;
 
 error:
-  ctables_axis_destroy (axis);
+  ctables_axis_destroy (sub);
   return NULL;
 }
 
+static const struct ctables_axis *
+find_scale (const struct ctables_axis *axis)
+{
+  if (!axis)
+    return NULL;
+  else if (axis->op == CTAO_VAR)
+    {
+      if (axis->scale)
+        {
+          assert (!axis->var.is_mrset);
+          return axis;
+        }
+      else
+        return NULL;
+    }
+  else
+    {
+      for (size_t i = 0; i < 2; i++)
+        {
+          const struct ctables_axis *scale = find_scale (axis->subs[i]);
+          if (scale)
+            return scale;
+        }
+      return NULL;
+    }
+}
+
+static const struct ctables_axis *
+find_categorical_summary (const struct ctables_axis *axis)
+{
+  if (!axis)
+    return NULL;
+  else if (axis->op == CTAO_VAR)
+    return !axis->scale && axis->n_summaries ? axis : NULL;
+  else
+    {
+      for (size_t i = 0; i < 2; i++)
+        {
+          const struct ctables_axis *sum
+            = find_categorical_summary (axis->subs[i]);
+          if (sum)
+            return sum;
+        }
+      return NULL;
+    }
+}
+
 static struct ctables_axis *
 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
 {
-  struct ctables_axis *lhs = ctables_axis_parse_primary (ctx);
+  int start_ofs = lex_ofs (ctx->lexer);
+  struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
   if (!lhs)
     return NULL;
 
   while (lex_match (ctx->lexer, T_GT))
     {
-      struct ctables_axis *rhs = ctables_axis_parse_primary (ctx);
+      struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
       if (!rhs)
         return NULL;
 
-      lhs = ctables_axis_new_nonterminal (CTAO_NEST, lhs, rhs);
+      struct ctables_axis *nest = ctables_axis_new_nonterminal (
+        CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
+
+      const struct ctables_axis *outer_scale = find_scale (lhs);
+      const struct ctables_axis *inner_scale = find_scale (rhs);
+      if (outer_scale && inner_scale)
+        {
+          msg_at (SE, nest->loc, _("Cannot nest scale variables."));
+          msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
+          msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
+          ctables_axis_destroy (nest);
+          return NULL;
+        }
+
+      const struct ctables_axis *outer_sum = find_categorical_summary (lhs);
+      if (outer_sum)
+        {
+          msg_at (SE, nest->loc,
+                  _("Summaries may only be requested for categorical variables "
+                    "at the innermost nesting level."));
+          msg_at (SN, outer_sum->loc,
+                  _("This outer categorical variable has a summary."));
+          ctables_axis_destroy (nest);
+          return NULL;
+        }
+
+      lhs = nest;
     }
 
   return lhs;
@@ -620,6 +926,7 @@ ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
 static struct ctables_axis *
 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
 {
+  int start_ofs = lex_ofs (ctx->lexer);
   struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
   if (!lhs)
     return NULL;
@@ -630,7 +937,8 @@ ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
       if (!rhs)
         return NULL;
 
-      lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs);
+      lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
+                                          ctx->lexer, start_ofs);
     }
 
   return lhs;
@@ -674,6 +982,10 @@ ctables_table_uninit (struct ctables_table *t)
   if (!t)
     return;
 
+  for (size_t i = 0; i < t->n_categories; i++)
+    ctables_categories_unref (t->categories[i]);
+  free (t->categories);
+
   ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
   ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
   ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
@@ -700,6 +1012,241 @@ ctables_destroy (struct ctables *ct)
   free (ct);
 }
 
+static struct ctables_cat_value
+ccvt_range (double low, double high)
+{
+  return (struct ctables_cat_value) {
+    .type = CCVT_RANGE,
+    .range = { low, high }
+  };
+}
+
+static bool
+ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
+                                struct ctables_table *t)
+{
+  if (!lex_match_id (lexer, "VARIABLES"))
+    return false;
+  lex_match (lexer, T_EQUALS);
+
+  struct variable **vars;
+  size_t n_vars;
+  if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
+    return false;
+
+  struct ctables_categories *c = xmalloc (sizeof *c);
+  *c = (struct ctables_categories) { .n_refs = n_vars };
+  for (size_t i = 0; i < n_vars; i++)
+    {
+      struct ctables_categories **cp
+        = &t->categories[var_get_dict_index (vars[i])];
+      ctables_categories_unref (*cp);
+      *cp = c;
+    }
+  free (vars);
+
+  if (lex_match (lexer, T_LBRACK))
+    {
+      size_t allocated_values = 0;
+      do
+        {
+          if (c->n_values >= allocated_values)
+            c->values = x2nrealloc (c->values, &allocated_values,
+                                    sizeof *c->values);
+
+          struct ctables_cat_value *v = &c->values[c->n_values];
+          if (lex_match_id (lexer, "OTHERNM"))
+            v->type = CCVT_OTHERNM;
+          else if (lex_match_id (lexer, "MISSING"))
+            v->type = CCVT_MISSING;
+          else if (lex_match_id (lexer, "SUBTOTAL"))
+            *v = (struct ctables_cat_value)
+              { .type = CCVT_SUBTOTAL, .subtotal_label = NULL };
+          else if (lex_match_id (lexer, "HSUBTOTAL"))
+            *v = (struct ctables_cat_value)
+              { .type = CCVT_HSUBTOTAL, .subtotal_label = NULL };
+          else if (lex_match_id (lexer, "LO"))
+            {
+              if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
+                return false;
+              *v = ccvt_range (-DBL_MAX, lex_number (lexer));
+              lex_get (lexer);
+            }
+          else if (lex_is_number (lexer))
+            {
+              double number = lex_number (lexer);
+              lex_get (lexer);
+              if (lex_match_id (lexer, "THRU"))
+                {
+                  v->type = CCVT_RANGE;
+                  v->range[0] = number;
+                  if (lex_match_id (lexer, "HI"))
+                    *v = ccvt_range (number, DBL_MAX);
+                  else
+                    {
+                      if (!lex_force_num (lexer))
+                        return false;
+                      *v = ccvt_range (number, lex_number (lexer));
+                      lex_get (lexer);
+                    }
+                }
+              else
+                *v = (struct ctables_cat_value) {
+                  .type = CCVT_NUMBER,
+                  .number = number
+                };
+            }
+          else if (lex_is_string (lexer))
+            {
+              *v = (struct ctables_cat_value) {
+                .type = CCVT_STRING,
+                .string = ss_xstrdup (lex_tokss (lexer)),
+              };
+              lex_get (lexer);
+            }
+          else
+            {
+              lex_error (lexer, NULL);
+              return false;
+            }
+
+          if ((v->type == CCVT_SUBTOTAL || v->type == CCVT_HSUBTOTAL)
+              && lex_match (lexer, T_EQUALS))
+            {
+              if (!lex_force_string (lexer))
+                return false;
+
+              v->subtotal_label = ss_xstrdup (lex_tokss (lexer));
+              lex_get (lexer);
+            }
+
+          c->n_values++;
+          lex_match (lexer, T_COMMA);
+        }
+      while (!lex_match (lexer, T_RBRACK));
+    }
+
+  while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
+    {
+      if (!c->n_values && lex_match_id (lexer, "ORDER"))
+        {
+          lex_match (lexer, T_EQUALS);
+          if (lex_match_id (lexer, "A"))
+            c->sort_ascending = true;
+          else if (lex_match_id (lexer, "D"))
+            c->sort_ascending = false;
+          else
+            {
+              lex_error_expecting (lexer, "A", "D");
+              return false;
+            }
+        }
+      else if (!c->n_values && lex_match_id (lexer, "KEY"))
+        {
+          lex_match (lexer, T_EQUALS);
+          if (lex_match_id (lexer, "VALUE"))
+            c->key = CTCS_VALUE;
+          else if (lex_match_id (lexer, "LABEL"))
+            c->key = CTCS_LABEL;
+          else
+            {
+              c->key = CTCS_FUNCTION;
+              if (!parse_ctables_summary_function (lexer, &c->sort_func))
+                return false;
+
+              if (lex_match (lexer, T_LPAREN))
+                {
+                  c->sort_func_var = parse_variable (lexer, dict);
+                  if (!c->sort_func_var)
+                    return false;
+
+                  if (c->sort_func == CTSF_PTILE)
+                    {
+                      lex_match (lexer, T_COMMA);
+                      if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
+                        return false;
+                      c->percentile = lex_number (lexer);
+                      lex_get (lexer);
+                    }
+
+                  if (!lex_force_match (lexer, T_RPAREN))
+                    return false;
+                }
+              else if (ctables_function_availability (c->sort_func)
+                       == CTFA_SCALE)
+                {
+                  bool UNUSED b = lex_force_match (lexer, T_LPAREN);
+                  return false;
+                }
+            }
+        }
+      else if (!c->n_values && lex_match_id (lexer, "MISSING"))
+        {
+          lex_match (lexer, T_EQUALS);
+          if (lex_match_id (lexer, "INCLUDE"))
+            c->include_missing = true;
+          else if (lex_match_id (lexer, "EXCLUDE"))
+            c->include_missing = false;
+          else
+            {
+              lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
+              return false;
+            }
+        }
+      else if (lex_match_id (lexer, "TOTAL"))
+        {
+          lex_match (lexer, T_EQUALS);
+          if (!parse_bool (lexer, &c->show_totals))
+            return false;
+        }
+      else if (lex_match_id (lexer, "LABEL"))
+        {
+          lex_match (lexer, T_EQUALS);
+          if (!lex_force_string (lexer))
+            return false;
+          free (c->total_label);
+          c->total_label = ss_xstrdup (lex_tokss (lexer));
+          lex_get (lexer);
+        }
+      else if (lex_match_id (lexer, "POSITION"))
+        {
+          lex_match (lexer, T_EQUALS);
+          if (lex_match_id (lexer, "BEFORE"))
+            c->totals_before = true;
+          else if (lex_match_id (lexer, "AFTER"))
+            c->totals_before = false;
+          else
+            {
+              lex_error_expecting (lexer, "BEFORE", "AFTER");
+              return false;
+            }
+        }
+      else if (lex_match_id (lexer, "EMPTY"))
+        {
+          lex_match (lexer, T_EQUALS);
+          if (lex_match_id (lexer, "INCLUDE"))
+            c->show_empty = true;
+          else if (lex_match_id (lexer, "EXCLUDE"))
+            c->show_empty = false;
+          else
+            {
+              lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
+              return false;
+            }
+        }
+      else
+        {
+          if (!c->n_values)
+            lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
+                                 "TOTAL", "LABEL", "POSITION", "EMPTY");
+          else
+            lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
+          return false;
+        }
+    }
+  return true;
+}
+
 int
 cmd_ctables (struct lexer *lexer, struct dataset *ds)
 {
@@ -916,13 +1463,15 @@ cmd_ctables (struct lexer *lexer, struct dataset *ds)
         .slabels_visible = true,
         .row_labels = CTLP_NORMAL,
         .col_labels = CTLP_NORMAL,
+        .categories = xcalloc (dict_get_n_vars (dataset_dict (ds)),
+                               sizeof *t->categories),
+        .n_categories = dict_get_n_vars (dataset_dict (ds)),
         .cilevel = 95,
       };
 
       lex_match (lexer, T_EQUALS);
       if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
         goto error;
-
       if (lex_match (lexer, T_BY))
         {
           if (!ctables_axis_parse (lexer, dataset_dict (ds),
@@ -936,12 +1485,42 @@ cmd_ctables (struct lexer *lexer, struct dataset *ds)
                 goto error;
             }
         }
+
+      if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
+          && !t->axes[PIVOT_AXIS_LAYER])
+        {
+          lex_error (lexer, _("At least one variable must be specified."));
+          goto error;
+        }
+
+      const struct ctables_axis *scales[PIVOT_N_AXES];
+      size_t n_scales = 0;
+      for (size_t i = 0; i < 3; i++)
+        {
+          scales[i] = find_scale (t->axes[i]);
+          if (scales[i])
+            n_scales++;
+        }
+      if (n_scales > 1)
+        {
+          msg (SE, _("Scale variables may appear only on one dimension."));
+          if (scales[PIVOT_AXIS_ROW])
+            msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
+                    _("This scale variable appears in the rows dimension."));
+          if (scales[PIVOT_AXIS_COLUMN])
+            msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
+                    _("This scale variable appears in the columns dimension."));
+          if (scales[PIVOT_AXIS_LAYER])
+            msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
+                    _("This scale variable appears in the layer dimension."));
+          goto error;
+        }
+
       if (lex_token (lexer) == T_ENDCMD)
         break;
       if (!lex_force_match (lexer, T_SLASH))
         break;
 
-      /* XXX Validate axes. */
       while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
         {
           if (lex_match_id (lexer, "SLABELS"))
@@ -959,8 +1538,7 @@ cmd_ctables (struct lexer *lexer, struct dataset *ds)
                         t->slabels_position = PIVOT_AXIS_LAYER;
                       else
                         {
-                          lex_error_expecting (lexer, "COLUMN", "ROW",
-                                               "LAYER");
+                          lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
                           goto error;
                         }
                     }
@@ -1028,6 +1606,11 @@ cmd_ctables (struct lexer *lexer, struct dataset *ds)
               t->cilevel = lex_number (lexer);
               lex_get (lexer);
             }
+          else if (lex_match_id (lexer, "CATEGORIES"))
+            {
+              if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
+                goto error;
+            }
           else if (lex_match_id (lexer, "TITLES"))
             {
               do
@@ -1268,6 +1851,13 @@ cmd_ctables (struct lexer *lexer, struct dataset *ds)
               goto error;
             }
         }
+
+      if (t->row_labels != CTLP_NORMAL && t->col_labels != CTLP_NORMAL)
+        {
+          msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
+          goto error;
+        }
+
     }
   while (lex_token (lexer) != T_ENDCMD);
   ctables_destroy (ct);