1d27331fcf7bcad335ed48468e84754936d5ac88
[pspp] / src / language / stats / ctables.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2021 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <math.h>
20
21 #include "data/casereader.h"
22 #include "data/casewriter.h"
23 #include "data/dataset.h"
24 #include "data/dictionary.h"
25 #include "data/mrset.h"
26 #include "data/subcase.h"
27 #include "data/value-labels.h"
28 #include "language/command.h"
29 #include "language/lexer/format-parser.h"
30 #include "language/lexer/lexer.h"
31 #include "language/lexer/variable-parser.h"
32 #include "libpspp/array.h"
33 #include "libpspp/assertion.h"
34 #include "libpspp/hash-functions.h"
35 #include "libpspp/hmap.h"
36 #include "libpspp/i18n.h"
37 #include "libpspp/message.h"
38 #include "libpspp/string-array.h"
39 #include "math/mode.h"
40 #include "math/moments.h"
41 #include "math/percentiles.h"
42 #include "math/sort.h"
43 #include "output/pivot-table.h"
44
45 #include "gl/minmax.h"
46 #include "gl/xalloc.h"
47
48 #include "gettext.h"
49 #define _(msgid) gettext (msgid)
50 #define N_(msgid) (msgid)
51
52 enum ctables_vlabel
53   {
54     CTVL_NONE = SETTINGS_VALUE_SHOW_DEFAULT,
55     CTVL_NAME = SETTINGS_VALUE_SHOW_VALUE,
56     CTVL_LABEL = SETTINGS_VALUE_SHOW_LABEL,
57     CTVL_BOTH = SETTINGS_VALUE_SHOW_BOTH,
58   };
59
60 /* XXX:
61    - unweighted summaries (U*)
62    - lower confidence limits (*.LCL)
63    - upper confidence limits (*.UCL)
64    - standard error (*.SE)
65  */
66 #define SUMMARIES                                                       \
67     /* All variables. */                                                \
68     S(CTSF_COUNT, "COUNT", N_("Count"), CTF_COUNT, CTFA_ALL)            \
69     S(CTSF_ECOUNT, "ECOUNT", N_("Adjusted Count"), CTF_COUNT, CTFA_ALL) \
70     S(CTSF_ROWPCT_COUNT, "ROWPCT.COUNT", N_("Row %"), CTF_PERCENT, CTFA_ALL) \
71     S(CTSF_COLPCT_COUNT, "COLPCT.COUNT", N_("Column %"), CTF_PERCENT, CTFA_ALL) \
72     S(CTSF_TABLEPCT_COUNT, "TABLEPCT.COUNT", N_("Table %"), CTF_PERCENT, CTFA_ALL) \
73     S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT.COUNT", N_("Subtable %"), CTF_PERCENT, CTFA_ALL) \
74     S(CTSF_LAYERPCT_COUNT, "LAYERPCT.COUNT", N_("Layer %"), CTF_PERCENT, CTFA_ALL) \
75     S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT.COUNT", N_("Layer Row %"), CTF_PERCENT, CTFA_ALL) \
76     S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT.COUNT", N_("Layer Column %"), CTF_PERCENT, CTFA_ALL) \
77     S(CTSF_ROWPCT_VALIDN, "ROWPCT.VALIDN", N_("Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
78     S(CTSF_COLPCT_VALIDN, "COLPCT.VALIDN", N_("Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
79     S(CTSF_TABLEPCT_VALIDN, "TABLEPCT.VALIDN", N_("Table Valid N %"), CTF_PERCENT, CTFA_ALL) \
80     S(CTSF_SUBTABLEPCT_VALIDN, "SUBTABLEPCT.VALIDN", N_("Subtable Valid N %"), CTF_PERCENT, CTFA_ALL) \
81     S(CTSF_LAYERPCT_VALIDN, "LAYERPCT.VALIDN", N_("Layer Valid N %"), CTF_PERCENT, CTFA_ALL) \
82     S(CTSF_LAYERROWPCT_VALIDN, "LAYERROWPCT.VALIDN", N_("Layer Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
83     S(CTSF_LAYERCOLPCT_VALIDN, "LAYERCOLPCT.VALIDN", N_("Layer Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
84     S(CTSF_ROWPCT_TOTALN, "ROWPCT.TOTALN", N_("Row Total N %"), CTF_PERCENT, CTFA_ALL) \
85     S(CTSF_COLPCT_TOTALN, "COLPCT.TOTALN", N_("Column Total N %"), CTF_PERCENT, CTFA_ALL) \
86     S(CTSF_TABLEPCT_TOTALN, "TABLEPCT.TOTALN", N_("Table Total N %"), CTF_PERCENT, CTFA_ALL) \
87     S(CTSF_SUBTABLEPCT_TOTALN, "SUBTABLEPCT.TOTALN", N_("Subtable Total N %"), CTF_PERCENT, CTFA_ALL) \
88     S(CTSF_LAYERPCT_TOTALN, "LAYERPCT.TOTALN", N_("Layer Total N %"), CTF_PERCENT, CTFA_ALL) \
89     S(CTSF_LAYERROWPCT_TOTALN, "LAYERROWPCT.TOTALN", N_("Layer Row Total N %"), CTF_PERCENT, CTFA_ALL) \
90     S(CTSF_LAYERCOLPCT_TOTALN, "LAYERCOLPCT.TOTALN", N_("Layer Column Total N %"), CTF_PERCENT, CTFA_ALL) \
91                                                                         \
92     /* Scale variables, totals, and subtotals. */                       \
93     S(CTSF_MAXIMUM, "MAXIMUM", N_("Maximum"), CTF_GENERAL, CTFA_SCALE)  \
94     S(CTSF_MEAN, "MEAN", N_("Mean"), CTF_GENERAL, CTFA_SCALE)           \
95     S(CTSF_MEDIAN, "MEDIAN", N_("Median"), CTF_GENERAL, CTFA_SCALE)     \
96     S(CTSF_MINIMUM, "MINIMUM", N_("Minimum"), CTF_GENERAL, CTFA_SCALE)  \
97     S(CTSF_MISSING, "MISSING", N_("Missing"), CTF_GENERAL, CTFA_SCALE)  \
98     S(CTSF_MODE, "MODE", N_("Mode"), CTF_GENERAL, CTFA_SCALE)           \
99     S(CTSF_PTILE, "PTILE", N_("Percentile"), CTF_GENERAL, CTFA_SCALE)   \
100     S(CTSF_RANGE, "RANGE", N_("Range"), CTF_GENERAL, CTFA_SCALE)        \
101     S(CTSF_SEMEAN, "SEMEAN", N_("Std Error of Mean"), CTF_GENERAL, CTFA_SCALE) \
102     S(CTSF_STDDEV, "STDDEV", N_("Std Deviation"), CTF_GENERAL, CTFA_SCALE) \
103     S(CTSF_SUM, "SUM", N_("Sum"), CTF_GENERAL, CTFA_SCALE)              \
104     S(CSTF_TOTALN, "TOTALN", N_("Total N"), CTF_COUNT, CTFA_SCALE)      \
105     S(CTSF_ETOTALN, "ETOTALN", N_("Adjusted Total N"), CTF_COUNT, CTFA_SCALE) \
106     S(CTSF_VALIDN, "VALIDN", N_("Valid N"), CTF_COUNT, CTFA_SCALE)      \
107     S(CTSF_EVALIDN, "EVALIDN", N_("Adjusted Valid N"), CTF_COUNT, CTFA_SCALE) \
108     S(CTSF_VARIANCE, "VARIANCE", N_("Variance"), CTF_GENERAL, CTFA_SCALE) \
109     S(CTSF_ROWPCT_SUM, "ROWPCT.SUM", N_("Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
110     S(CTSF_COLPCT_SUM, "COLPCT.SUM", N_("Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
111     S(CTSF_TABLEPCT_SUM, "TABLEPCT.SUM", N_("Table Sum %"), CTF_PERCENT, CTFA_SCALE) \
112     S(CTSF_SUBTABLEPCT_SUM, "SUBTABLEPCT.SUM", N_("Subtable Sum %"), CTF_PERCENT, CTFA_SCALE) \
113     S(CTSF_LAYERPCT_SUM, "LAYERPCT.SUM", N_("Layer Sum %"), CTF_PERCENT, CTFA_SCALE) \
114     S(CTSF_LAYERROWPCT_SUM, "LAYERROWPCT.SUM", N_("Layer Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
115     S(CTSF_LAYERCOLPCT_SUM, "LAYERCOLPCT.SUM", N_("Layer Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
116                                                                         \
117     /* Multiple response sets. */                                       \
118   S(CTSF_RESPONSES, "RESPONSES", N_("Responses"), CTF_COUNT, CTFA_MRSETS) \
119     S(CTSF_ROWPCT_RESPONSES, "ROWPCT.RESPONSES", N_("Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
120     S(CTSF_COLPCT_RESPONSES, "COLPCT.RESPONSES", N_("Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
121     S(CTSF_TABLEPCT_RESPONSES, "TABLEPCT.RESPONSES", N_("Table Responses %"), CTF_PERCENT, CTFA_MRSETS) \
122     S(CTSF_SUBTABLEPCT_RESPONSES, "SUBTABLEPCT.RESPONSES", N_("Subtable Responses %"), CTF_PERCENT, CTFA_MRSETS) \
123     S(CTSF_LAYERPCT_RESPONSES, "LAYERPCT.RESPONSES", N_("Layer Responses %"), CTF_PERCENT, CTFA_MRSETS) \
124     S(CTSF_LAYERROWPCT_RESPONSES, "LAYERROWPCT.RESPONSES", N_("Layer Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
125     S(CTSF_LAYERCOLPCT_RESPONSES, "LAYERCOLPCT.RESPONSES", N_("Layer Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
126     S(CTSF_ROWPCT_RESPONSES_COUNT, "ROWPCT.RESPONSES.COUNT", N_("Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
127     S(CTSF_COLPCT_RESPONSES_COUNT, "COLPCT.RESPONSES.COUNT", N_("Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
128     S(CTSF_TABLEPCT_RESPONSES_COUNT, "TABLEPCT.RESPONSES.COUNT", N_("Table Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
129     S(CTSF_SUBTABLEPCT_RESPONSES_COUNT, "SUBTABLEPCT.RESPONSES.COUNT", N_("Subtable Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
130     S(CTSF_LAYERPCT_RESPONSES_COUNT, "LAYERPCT.RESPONSES.COUNT", N_("Layer Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
131     S(CTSF_LAYERROWPCT_RESPONSES_COUNT, "LAYERROWPCT.RESPONSES.COUNT", N_("Layer Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
132     S(CTSF_LAYERCOLPCT_RESPONSES_COUNT, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
133     S(CTSF_ROWPCT_COUNT_RESPONSES, "ROWPCT.COUNT.RESPONSES", N_("Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
134     S(CTSF_COLPCT_COUNT_RESPONSES, "COLPCT.COUNT.RESPONSES", N_("Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
135     S(CTSF_TABLEPCT_COUNT_RESPONSES, "TABLEPCT.COUNT.RESPONSES", N_("Table Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
136     S(CTSF_SUBTABLEPCT_COUNT_RESPONSES, "SUBTABLEPCT.COUNT.RESPONSES", N_("Subtable Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
137     S(CTSF_LAYERPCT_COUNT_RESPONSES, "LAYERPCT.COUNT.RESPONSES", N_("Layer Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
138     S(CTSF_LAYERROWPCT_COUNT_RESPONSES, "LAYERROWPCT.COUNT.RESPONSES", N_("Layer Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
139     S(CTSF_LAYERCOLPCT_COUNT_RESPONSES, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS)
140
141 enum ctables_summary_function
142   {
143 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) ENUM,
144     SUMMARIES
145 #undef S
146   };
147
148 enum {
149 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) +1
150   N_CTSF_FUNCTIONS = SUMMARIES
151 #undef S
152 };
153
154 enum ctables_domain_type
155   {
156     /* Within a section, where stacked variables divide one section from
157        another. */
158     CTDT_TABLE,                  /* All layers of a whole section. */
159     CTDT_LAYER,                  /* One layer within a section. */
160     CTDT_LAYERROW,               /* Row in one layer within a section. */
161     CTDT_LAYERCOL,               /* Column in one layer within a section. */
162
163     /* Within a subtable, where a subtable pairs an innermost row variable with
164        an innermost column variable within a single layer.  */
165     CTDT_SUBTABLE,               /* Whole subtable. */
166     CTDT_ROW,                    /* Row within a subtable. */
167     CTDT_COL,                    /* Column within a subtable. */
168 #define N_CTDTS 7
169   };
170
171 struct ctables_domain
172   {
173     struct hmap_node node;
174
175     const struct ctables_cell *example;
176
177     double d_valid;             /* Dictionary weight. */
178     double d_missing;
179     double e_valid;             /* Effective weight */
180     double e_missing;
181   };
182
183 enum ctables_summary_variant
184   {
185     CSV_CELL,
186     CSV_TOTAL
187 #define N_CSVS 2
188   };
189
190 struct ctables_cell
191   {
192     /* In struct ctables_section's 'cells' hmap.  Indexed by all the values in
193        all the axes (except the scalar variable, if any). */
194     struct hmap_node node;
195
196     /* The domains that contain this cell. */
197     bool contributes_to_domains;
198     struct ctables_domain *domains[N_CTDTS];
199
200     bool hide;
201     enum ctables_summary_variant sv;
202
203     struct ctables_cell_axis
204       {
205         struct ctables_cell_value
206           {
207             const struct ctables_category *category;
208             union value value;
209           }
210         *cvs;
211         int leaf;
212       }
213     axes[PIVOT_N_AXES];
214
215     union ctables_summary *summaries;
216   };
217
218 struct ctables
219   {
220     const struct dictionary *dict;
221     struct pivot_table_look *look;
222
223     /* If this is NULL, zeros are displayed using the normal print format.
224        Otherwise, this string is displayed. */
225     char *zero;
226
227     /* If this is NULL, missing values are displayed using the normal print
228        format.  Otherwise, this string is displayed. */
229     char *missing;
230
231     /* Indexed by variable dictionary index. */
232     enum ctables_vlabel *vlabels;
233
234     struct hmap postcomputes;   /* Contains "struct ctables_postcompute"s. */
235
236     bool mrsets_count_duplicates; /* MRSETS. */
237     bool smissing_listwise;       /* SMISSING. */
238     struct variable *e_weight;    /* WEIGHT. */
239     int hide_threshold;           /* HIDESMALLCOUNTS. */
240
241     struct ctables_table **tables;
242     size_t n_tables;
243   };
244
245 struct ctables_postcompute
246   {
247     struct hmap_node hmap_node; /* In struct ctables's 'pcompute' hmap. */
248     char *name;                 /* Name, without leading &. */
249
250     struct msg_location *location; /* Location of definition. */
251     struct ctables_pcexpr *expr;
252     char *label;
253     struct ctables_summary_spec_set *specs;
254     bool hide_source_cats;
255   };
256
257 struct ctables_pcexpr
258   {
259     /* Precedence table:
260
261        ()
262        **
263        -
264        * /
265        - +
266     */
267     enum ctables_postcompute_op
268       {
269         /* Terminals. */
270         CTPO_CONSTANT,          /* 5 */
271         CTPO_CAT_NUMBER,        /* [5] */
272         CTPO_CAT_STRING,        /* ["STRING"] */
273         CTPO_CAT_RANGE,         /* [LO THRU 5] */
274         CTPO_CAT_MISSING,       /* MISSING */
275         CTPO_CAT_OTHERNM,       /* OTHERNM */
276         CTPO_CAT_SUBTOTAL,      /* SUBTOTAL */
277         CTPO_CAT_TOTAL,         /* TOTAL */
278
279         /* Nonterminals. */
280         CTPO_ADD,
281         CTPO_SUB,
282         CTPO_MUL,
283         CTPO_DIV,
284         CTPO_POW,
285         CTPO_NEG,
286       }
287     op;
288
289     union
290       {
291         /* CTPO_CAT_NUMBER. */
292         double number;
293
294         /* CTPO_CAT_STRING. */
295         char *string;
296
297         /* CTPO_CAT_RANGE. */
298         double range[2];
299
300         /* CTPO_CAT_SUBTOTAL. */
301         size_t subtotal_index;
302
303         /* Two elements: CTPO_ADD, CTPO_SUB, CTPO_MUL, CTPO_DIV, CTPO_POW.
304            One element: CTPO_NEG. */
305         struct ctables_pcexpr *subs[2];
306       };
307
308     /* Source location. */
309     int ofs[2];
310     struct msg_location *location;
311   };
312
313 static void ctables_pcexpr_destroy (struct ctables_pcexpr *);
314 static struct ctables_pcexpr *ctables_pcexpr_allocate_binary (
315   enum ctables_postcompute_op, struct ctables_pcexpr *sub0,
316   struct ctables_pcexpr *sub1);
317
318 struct ctables_summary_spec_set
319   {
320     struct ctables_summary_spec *specs;
321     size_t n;
322     size_t allocated;
323
324     struct variable *var;
325   };
326
327 static void ctables_summary_spec_set_clone (struct ctables_summary_spec_set *,
328                                             const struct ctables_summary_spec_set *);
329 static void ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *);
330
331 /* A nested sequence of variables, e.g. a > b > c. */
332 struct ctables_nest
333   {
334     struct variable **vars;
335     size_t n;
336     size_t scale_idx;
337     size_t *domains[N_CTDTS];
338     size_t n_domains[N_CTDTS];
339
340     struct ctables_summary_spec_set specs[N_CSVS];
341   };
342
343 /* A stack of nestings, e.g. nest1 + nest2 + ... + nestN. */
344 struct ctables_stack
345   {
346     struct ctables_nest *nests;
347     size_t n;
348   };
349
350 struct ctables_value
351   {
352     struct hmap_node node;
353     union value value;
354     int leaf;
355   };
356
357 struct ctables_section_value
358   {
359     struct hmap_node node;
360     union value value;
361   };
362
363 struct ctables_section
364   {
365     struct ctables_table *table;
366     struct ctables_nest *nests[PIVOT_N_AXES];
367     struct hmap *occurrences[PIVOT_N_AXES];
368     struct hmap cells;            /* Contains "struct ctable_cell"s. */
369     struct hmap domains[N_CTDTS]; /* Contains "struct ctable_domain"s. */
370   };
371
372 struct ctables_table
373   {
374     struct ctables *ctables;
375     struct ctables_axis *axes[PIVOT_N_AXES];
376     struct ctables_stack stacks[PIVOT_N_AXES];
377     struct ctables_section *sections;
378     size_t n_sections;
379     enum pivot_axis_type summary_axis;
380     struct ctables_summary_spec_set summary_specs;
381
382     const struct variable *clabels_example;
383     struct hmap clabels_values_map;
384     struct ctables_value **clabels_values;
385     size_t n_clabels_values;
386
387     enum pivot_axis_type slabels_axis;
388     bool slabels_visible;
389
390     /* The innermost category labels for axis 'a' appear on axis label_axis[a].
391
392        Most commonly, label_axis[a] == a, and in particular we always have
393        label_axis{PIVOT_AXIS_LAYER] == PIVOT_AXIS_LAYER.
394
395        If ROWLABELS or COLLABELS is specified, then one of
396        label_axis[PIVOT_AXIS_ROW] or label_axis[PIVOT_AXIS_COLUMN] can be the
397        opposite axis or PIVOT_AXIS_LAYER.  Only one of them will differ.
398     */
399     enum pivot_axis_type label_axis[PIVOT_N_AXES];
400     enum pivot_axis_type clabels_from_axis;
401
402     /* Indexed by variable dictionary index. */
403     struct ctables_categories **categories;
404     size_t n_categories;
405
406     double cilevel;
407
408     char *caption;
409     char *corner;
410     char *title;
411
412     struct ctables_chisq *chisq;
413     struct ctables_pairwise *pairwise;
414   };
415
416 struct ctables_var
417   {
418     bool is_mrset;
419     union
420       {
421         struct variable *var;
422         const struct mrset *mrset;
423       };
424   };
425
426 static const struct fmt_spec *
427 ctables_var_get_print_format (const struct ctables_var *var)
428 {
429   return (var->is_mrset
430           ? var_get_print_format (var->mrset->vars[0])
431           : var_get_print_format (var->var));
432 }
433
434 static const char *
435 ctables_var_name (const struct ctables_var *var)
436 {
437   return var->is_mrset ? var->mrset->name : var_get_name (var->var);
438 }
439
440 struct ctables_categories
441   {
442     size_t n_refs;
443     struct ctables_category *cats;
444     size_t n_cats;
445     bool show_empty;
446   };
447
448 struct ctables_category
449   {
450     enum ctables_category_type
451       {
452         /* Explicit category lists. */
453         CCT_NUMBER,
454         CCT_STRING,
455         CCT_RANGE,
456         CCT_MISSING,
457         CCT_OTHERNM,
458
459         /* Totals and subtotals. */
460         CCT_SUBTOTAL,
461         CCT_HSUBTOTAL,
462         CCT_TOTAL,
463
464         /* Implicit category lists. */
465         CCT_VALUE,
466         CCT_LABEL,
467         CCT_FUNCTION,
468       }
469     type;
470
471     struct ctables_category *subtotal;
472
473     union
474       {
475         double number;          /* CCT_NUMBER. */
476         char *string;           /* CCT_STRING. */
477         double range[2];        /* CCT_RANGE. */
478         char *total_label;   /* CCT_SUBTOTAL, CCT_HSUBTOTAL, CCT_TOTAL. */
479
480         /* CCT_VALUE, CCT_LABEL, CCT_FUNCTION. */
481         struct
482           {
483             bool include_missing;
484             bool sort_ascending;
485
486             /* CCT_FUNCTION. */
487             enum ctables_summary_function sort_function;
488             struct variable *sort_var;
489             double percentile;
490           };
491       };
492   };
493
494 static void
495 ctables_category_uninit (struct ctables_category *cat)
496 {
497   if (!cat)
498     return;
499
500   switch (cat->type)
501     {
502     case CCT_NUMBER:
503     case CCT_RANGE:
504     case CCT_MISSING:
505     case CCT_OTHERNM:
506       break;
507
508     case CCT_STRING:
509       free (cat->string);
510       break;
511
512     case CCT_SUBTOTAL:
513     case CCT_HSUBTOTAL:
514     case CCT_TOTAL:
515       free (cat->total_label);
516       break;
517
518     case CCT_VALUE:
519     case CCT_LABEL:
520     case CCT_FUNCTION:
521       break;
522     }
523 }
524
525 static bool
526 ctables_category_equal (const struct ctables_category *a,
527                         const struct ctables_category *b)
528 {
529   if (a->type != b->type)
530     return false;
531
532   switch (a->type)
533     {
534     case CCT_NUMBER:
535       return a->number == b->number;
536
537     case CCT_STRING:
538       return strcmp (a->string, b->string);
539
540     case CCT_RANGE:
541       return a->range[0] == b->range[0] && a->range[1] == b->range[1];
542
543     case CCT_MISSING:
544     case CCT_OTHERNM:
545       return true;
546
547     case CCT_SUBTOTAL:
548     case CCT_HSUBTOTAL:
549     case CCT_TOTAL:
550       return !strcmp (a->total_label, b->total_label);
551
552     case CCT_VALUE:
553     case CCT_LABEL:
554     case CCT_FUNCTION:
555       return (a->include_missing == b->include_missing
556               && a->sort_ascending == b->sort_ascending
557               && a->sort_function == b->sort_function
558               && a->sort_var == b->sort_var
559               && a->percentile == b->percentile);
560     }
561
562   NOT_REACHED ();
563 }
564
565 static void
566 ctables_categories_unref (struct ctables_categories *c)
567 {
568   if (!c)
569     return;
570
571   assert (c->n_refs > 0);
572   if (--c->n_refs)
573     return;
574
575   for (size_t i = 0; i < c->n_cats; i++)
576     ctables_category_uninit (&c->cats[i]);
577   free (c->cats);
578   free (c);
579 }
580
581 static bool
582 ctables_categories_equal (const struct ctables_categories *a,
583                           const struct ctables_categories *b)
584 {
585   if (a->n_cats != b->n_cats || a->show_empty != b->show_empty)
586     return false;
587
588   for (size_t i = 0; i < a->n_cats; i++)
589     if (!ctables_category_equal (&a->cats[i], &b->cats[i]))
590       return false;
591
592   return true;
593 }
594
595 /* Chi-square test (SIGTEST). */
596 struct ctables_chisq
597   {
598     double alpha;
599     bool include_mrsets;
600     bool all_visible;
601   };
602
603 /* Pairwise comparison test (COMPARETEST). */
604 struct ctables_pairwise
605   {
606     enum { PROP, MEAN } type;
607     double alpha[2];
608     bool include_mrsets;
609     bool meansvariance_allcats;
610     bool all_visible;
611     enum { BONFERRONI = 1, BH } adjust;
612     bool merge;
613     bool apa_style;
614     bool show_sig;
615   };
616
617 struct ctables_axis
618   {
619     enum ctables_axis_op
620       {
621         /* Terminals. */
622         CTAO_VAR,
623
624         /* Nonterminals. */
625         CTAO_STACK,             /* + */
626         CTAO_NEST,              /* > */
627       }
628     op;
629
630     union
631       {
632         /* Terminals. */
633         struct
634           {
635             struct ctables_var var;
636             bool scale;
637             struct ctables_summary_spec_set specs[N_CSVS];
638           };
639
640         /* Nonterminals. */
641         struct ctables_axis *subs[2];
642       };
643
644     struct msg_location *loc;
645   };
646
647 static void ctables_axis_destroy (struct ctables_axis *);
648
649 enum ctables_format
650   {
651     CTF_COUNT,
652     CTF_PERCENT,
653     CTF_GENERAL
654   };
655
656 enum ctables_function_availability
657   {
658     CTFA_ALL,                /* Any variables. */
659     CTFA_SCALE,              /* Only scale variables, totals, and subtotals. */
660     CTFA_MRSETS,             /* Only multiple-response sets */
661   };
662
663 struct ctables_summary_spec
664   {
665     enum ctables_summary_function function;
666     double percentile;          /* CTSF_PTILE only. */
667     char *label;
668     struct fmt_spec format;     /* XXX extra CTABLES formats */
669     size_t axis_idx;
670   };
671
672 static void
673 ctables_summary_spec_clone (struct ctables_summary_spec *dst,
674                             const struct ctables_summary_spec *src)
675 {
676   *dst = *src;
677   dst->label = xstrdup (src->label);
678 }
679
680 static void
681 ctables_summary_spec_uninit (struct ctables_summary_spec *s)
682 {
683   if (s)
684     free (s->label);
685 }
686
687 static void
688 ctables_summary_spec_set_clone (struct ctables_summary_spec_set *dst,
689                                 const struct ctables_summary_spec_set *src)
690 {
691   struct ctables_summary_spec *specs = xnmalloc (src->n, sizeof *specs);
692   for (size_t i = 0; i < src->n; i++)
693     ctables_summary_spec_clone (&specs[i], &src->specs[i]);
694
695   *dst = (struct ctables_summary_spec_set) {
696     .specs = specs,
697     .n = src->n,
698     .allocated = src->n,
699     .var = src->var
700   };
701 }
702
703 static void
704 ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *set)
705 {
706   for (size_t i = 0; i < set->n; i++)
707     ctables_summary_spec_uninit (&set->specs[i]);
708   free (set->specs);
709 }
710
711 static bool
712 parse_col_width (struct lexer *lexer, const char *name, double *width)
713 {
714   lex_match (lexer, T_EQUALS);
715   if (lex_match_id (lexer, "DEFAULT"))
716     *width = SYSMIS;
717   else if (lex_force_num_range_closed (lexer, name, 0, DBL_MAX))
718     {
719       *width = lex_number (lexer);
720       lex_get (lexer);
721     }
722   else
723     return false;
724
725   return true;
726 }
727
728 static bool
729 parse_bool (struct lexer *lexer, bool *b)
730 {
731   if (lex_match_id (lexer, "NO"))
732     *b = false;
733   else if (lex_match_id (lexer, "YES"))
734     *b = true;
735   else
736     {
737       lex_error_expecting (lexer, "YES", "NO");
738       return false;
739     }
740   return true;
741 }
742
743 static enum ctables_function_availability
744 ctables_function_availability (enum ctables_summary_function f)
745 {
746   static enum ctables_function_availability availability[] = {
747 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = AVAILABILITY,
748     SUMMARIES
749 #undef S
750   };
751
752   return availability[f];
753 }
754
755 static bool
756 parse_ctables_summary_function (struct lexer *lexer,
757                                 enum ctables_summary_function *f)
758 {
759   struct pair
760     {
761       enum ctables_summary_function function;
762       struct substring name;
763     };
764   static struct pair names[] = {
765 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) \
766     { ENUM, SS_LITERAL_INITIALIZER (NAME) },
767     SUMMARIES
768
769     /* The .COUNT suffix may be omitted. */
770     S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _, _)
771     S(CTSF_COLPCT_COUNT, "COLPCT", _, _, _)
772     S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _, _)
773     S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _, _)
774     S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _, _)
775     S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _, _)
776     S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _, _)
777 #undef S
778   };
779
780   if (!lex_force_id (lexer))
781     return false;
782
783   for (size_t i = 0; i < sizeof names / sizeof *names; i++)
784     if (ss_equals_case (names[i].name, lex_tokss (lexer)))
785       {
786         *f = names[i].function;
787         lex_get (lexer);
788         return true;
789       }
790
791   lex_error (lexer, _("Expecting summary function name."));
792   return false;
793 }
794
795 static void
796 ctables_axis_destroy (struct ctables_axis *axis)
797 {
798   if (!axis)
799     return;
800
801   switch (axis->op)
802     {
803     case CTAO_VAR:
804       for (size_t i = 0; i < N_CSVS; i++)
805         ctables_summary_spec_set_uninit (&axis->specs[i]);
806       break;
807
808     case CTAO_STACK:
809     case CTAO_NEST:
810       ctables_axis_destroy (axis->subs[0]);
811       ctables_axis_destroy (axis->subs[1]);
812       break;
813     }
814   msg_location_destroy (axis->loc);
815   free (axis);
816 }
817
818 static struct ctables_axis *
819 ctables_axis_new_nonterminal (enum ctables_axis_op op,
820                               struct ctables_axis *sub0,
821                               struct ctables_axis *sub1,
822                               struct lexer *lexer, int start_ofs)
823 {
824   struct ctables_axis *axis = xmalloc (sizeof *axis);
825   *axis = (struct ctables_axis) {
826     .op = op,
827     .subs = { sub0, sub1 },
828     .loc = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
829   };
830   return axis;
831 }
832
833 struct ctables_axis_parse_ctx
834   {
835     struct lexer *lexer;
836     struct dictionary *dict;
837     struct ctables *ct;
838     struct ctables_table *t;
839   };
840
841 static struct fmt_spec
842 ctables_summary_default_format (enum ctables_summary_function function,
843                                 const struct ctables_var *var)
844 {
845   static const enum ctables_format default_formats[] = {
846 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
847     SUMMARIES
848 #undef S
849   };
850   switch (default_formats[function])
851     {
852     case CTF_COUNT:
853       return (struct fmt_spec) { .type = FMT_F, .w = 40 };
854
855     case CTF_PERCENT:
856       return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
857
858     case CTF_GENERAL:
859       return *ctables_var_get_print_format (var);
860
861     default:
862       NOT_REACHED ();
863     }
864 }
865
866 static char *
867 ctables_summary_default_label (enum ctables_summary_function function,
868                                double percentile)
869 {
870   static const char *default_labels[] = {
871 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = LABEL,
872     SUMMARIES
873 #undef S
874   };
875
876   return (function == CTSF_PTILE
877           ? xasprintf (_("Percentile %.2f"), percentile)
878           : xstrdup (gettext (default_labels[function])));
879 }
880
881 static const char *
882 ctables_summary_function_name (enum ctables_summary_function function)
883 {
884   static const char *names[] = {
885 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = NAME,
886     SUMMARIES
887 #undef S
888   };
889   return names[function];
890 }
891
892 static bool
893 add_summary_spec (struct ctables_axis *axis,
894                   enum ctables_summary_function function, double percentile,
895                   const char *label, const struct fmt_spec *format,
896                   const struct msg_location *loc, enum ctables_summary_variant sv)
897 {
898   if (axis->op == CTAO_VAR)
899     {
900       const char *function_name = ctables_summary_function_name (function);
901       const char *var_name = ctables_var_name (&axis->var);
902       switch (ctables_function_availability (function))
903         {
904         case CTFA_MRSETS:
905           if (!axis->var.is_mrset)
906             {
907               msg_at (SE, loc, _("Summary function %s applies only to multiple "
908                                  "response sets."), function_name);
909               msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
910                       var_name);
911               return false;
912             }
913           break;
914
915         case CTFA_SCALE:
916           if (!axis->scale)
917             {
918               msg_at (SE, loc,
919                       _("Summary function %s applies only to scale variables."),
920                       function_name);
921               msg_at (SN, axis->loc, _("'%s' is not a scale variable."),
922                       var_name);
923               return false;
924             }
925           break;
926
927         case CTFA_ALL:
928           break;
929         }
930
931       struct ctables_summary_spec_set *set = &axis->specs[sv];
932       if (set->n >= set->allocated)
933         set->specs = x2nrealloc (set->specs, &set->allocated,
934                                  sizeof *set->specs);
935
936       struct ctables_summary_spec *dst = &set->specs[set->n++];
937       *dst = (struct ctables_summary_spec) {
938         .function = function,
939         .percentile = percentile,
940         .label = xstrdup (label),
941         .format = (format ? *format
942                    : ctables_summary_default_format (function, &axis->var)),
943       };
944       return true;
945     }
946   else
947     {
948       for (size_t i = 0; i < 2; i++)
949         if (!add_summary_spec (axis->subs[i], function, percentile, label,
950                                format, loc, sv))
951           return false;
952       return true;
953     }
954 }
955
956 static struct ctables_axis *ctables_axis_parse_stack (
957   struct ctables_axis_parse_ctx *);
958
959 static bool
960 ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
961                    struct ctables_var *var)
962 {
963   if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
964     {
965       *var = (struct ctables_var) {
966         .is_mrset = true,
967         .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
968       };
969       if (!var->mrset)
970         {
971           lex_error (lexer, _("'%s' does not name a multiple-response set "
972                               "in the active file dictionary."),
973                      lex_tokcstr (lexer));
974           return false;
975         }
976       lex_get (lexer);
977       return true;
978     }
979   else
980     {
981       *var = (struct ctables_var) {
982         .is_mrset = false,
983         .var = parse_variable (lexer, dict),
984       };
985       return var->var != NULL;
986     }
987 }
988
989 static struct ctables_axis *
990 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
991 {
992   if (lex_match (ctx->lexer, T_LPAREN))
993     {
994       struct ctables_axis *sub = ctables_axis_parse_stack (ctx);
995       if (!sub || !lex_force_match (ctx->lexer, T_RPAREN))
996         {
997           ctables_axis_destroy (sub);
998           return NULL;
999         }
1000       return sub;
1001     }
1002
1003   if (!lex_force_id (ctx->lexer))
1004     return NULL;
1005
1006   int start_ofs = lex_ofs (ctx->lexer);
1007   struct ctables_var var;
1008   if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
1009     return NULL;
1010
1011   struct ctables_axis *axis = xmalloc (sizeof *axis);
1012   *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
1013
1014   /* XXX should figure out default measures by reading data */
1015   axis->scale = (var.is_mrset ? false
1016                  : lex_match_phrase (ctx->lexer, "[S]") ? true
1017                  : lex_match_phrase (ctx->lexer, "[C]") ? false
1018                  : var_get_measure (var.var) == MEASURE_SCALE);
1019   axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
1020                                 lex_ofs (ctx->lexer) - 1);
1021   return axis;
1022 }
1023
1024 static bool
1025 has_digit (const char *s)
1026 {
1027   return s[strcspn (s, "0123456789")] != '\0';
1028 }
1029
1030 static struct ctables_axis *
1031 ctables_axis_parse_postfix (struct ctables_axis_parse_ctx *ctx)
1032 {
1033   struct ctables_axis *sub = ctables_axis_parse_primary (ctx);
1034   if (!sub || !lex_match (ctx->lexer, T_LBRACK))
1035     return sub;
1036
1037   enum ctables_summary_variant sv = CSV_CELL;
1038   for (;;)
1039     {
1040       int start_ofs = lex_ofs (ctx->lexer);
1041
1042       /* Parse function. */
1043       enum ctables_summary_function function;
1044       if (!parse_ctables_summary_function (ctx->lexer, &function))
1045         goto error;
1046
1047       /* Parse percentile. */
1048       double percentile = 0;
1049       if (function == CTSF_PTILE)
1050         {
1051           if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
1052             goto error;
1053           percentile = lex_number (ctx->lexer);
1054           lex_get (ctx->lexer);
1055         }
1056
1057       /* Parse label. */
1058       char *label;
1059       if (lex_is_string (ctx->lexer))
1060         {
1061           label = ss_xstrdup (lex_tokss (ctx->lexer));
1062           lex_get (ctx->lexer);
1063         }
1064       else
1065         label = ctables_summary_default_label (function, percentile);
1066
1067       /* Parse format. */
1068       struct fmt_spec format;
1069       const struct fmt_spec *formatp;
1070       if (lex_token (ctx->lexer) == T_ID
1071           && has_digit (lex_tokcstr (ctx->lexer)))
1072         {
1073           if (!parse_format_specifier (ctx->lexer, &format)
1074               || !fmt_check_output (&format)
1075               || !fmt_check_type_compat (&format, VAL_NUMERIC))
1076             {
1077               free (label);
1078               goto error;
1079             }
1080           formatp = &format;
1081         }
1082       else
1083         formatp = NULL;
1084
1085       struct msg_location *loc = lex_ofs_location (ctx->lexer, start_ofs,
1086                                                    lex_ofs (ctx->lexer) - 1);
1087       add_summary_spec (sub, function, percentile, label, formatp, loc, sv);
1088       free (label);
1089       msg_location_destroy (loc);
1090
1091       lex_match (ctx->lexer, T_COMMA);
1092       if (sv == CSV_CELL && lex_match_id (ctx->lexer, "TOTALS"))
1093         {
1094           if (!lex_force_match (ctx->lexer, T_LBRACK))
1095             goto error;
1096           sv = CSV_TOTAL;
1097         }
1098       else if (lex_match (ctx->lexer, T_RBRACK))
1099         {
1100           if (sv == CSV_TOTAL && !lex_force_match (ctx->lexer, T_RBRACK))
1101             goto error;
1102           return sub;
1103         }
1104     }
1105
1106 error:
1107   ctables_axis_destroy (sub);
1108   return NULL;
1109 }
1110
1111 static const struct ctables_axis *
1112 find_scale (const struct ctables_axis *axis)
1113 {
1114   if (!axis)
1115     return NULL;
1116   else if (axis->op == CTAO_VAR)
1117     {
1118       if (axis->scale)
1119         {
1120           assert (!axis->var.is_mrset);
1121           return axis;
1122         }
1123       else
1124         return NULL;
1125     }
1126   else
1127     {
1128       for (size_t i = 0; i < 2; i++)
1129         {
1130           const struct ctables_axis *scale = find_scale (axis->subs[i]);
1131           if (scale)
1132             return scale;
1133         }
1134       return NULL;
1135     }
1136 }
1137
1138 static const struct ctables_axis *
1139 find_categorical_summary_spec (const struct ctables_axis *axis)
1140 {
1141   if (!axis)
1142     return NULL;
1143   else if (axis->op == CTAO_VAR)
1144     return !axis->scale && axis->specs[CSV_CELL].n ? axis : NULL;
1145   else
1146     {
1147       for (size_t i = 0; i < 2; i++)
1148         {
1149           const struct ctables_axis *sum
1150             = find_categorical_summary_spec (axis->subs[i]);
1151           if (sum)
1152             return sum;
1153         }
1154       return NULL;
1155     }
1156 }
1157
1158 static struct ctables_axis *
1159 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
1160 {
1161   int start_ofs = lex_ofs (ctx->lexer);
1162   struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
1163   if (!lhs)
1164     return NULL;
1165
1166   while (lex_match (ctx->lexer, T_GT))
1167     {
1168       struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
1169       if (!rhs)
1170         return NULL;
1171
1172       struct ctables_axis *nest = ctables_axis_new_nonterminal (
1173         CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
1174
1175       const struct ctables_axis *outer_scale = find_scale (lhs);
1176       const struct ctables_axis *inner_scale = find_scale (rhs);
1177       if (outer_scale && inner_scale)
1178         {
1179           msg_at (SE, nest->loc, _("Cannot nest scale variables."));
1180           msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
1181           msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
1182           ctables_axis_destroy (nest);
1183           return NULL;
1184         }
1185
1186       const struct ctables_axis *outer_sum = find_categorical_summary_spec (lhs);
1187       if (outer_sum)
1188         {
1189           msg_at (SE, nest->loc,
1190                   _("Summaries may only be requested for categorical variables "
1191                     "at the innermost nesting level."));
1192           msg_at (SN, outer_sum->loc,
1193                   _("This outer categorical variable has a summary."));
1194           ctables_axis_destroy (nest);
1195           return NULL;
1196         }
1197
1198       lhs = nest;
1199     }
1200
1201   return lhs;
1202 }
1203
1204 static struct ctables_axis *
1205 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
1206 {
1207   int start_ofs = lex_ofs (ctx->lexer);
1208   struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
1209   if (!lhs)
1210     return NULL;
1211
1212   while (lex_match (ctx->lexer, T_PLUS))
1213     {
1214       struct ctables_axis *rhs = ctables_axis_parse_nest (ctx);
1215       if (!rhs)
1216         return NULL;
1217
1218       lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
1219                                           ctx->lexer, start_ofs);
1220     }
1221
1222   return lhs;
1223 }
1224
1225 static bool
1226 ctables_axis_parse (struct lexer *lexer, struct dictionary *dict,
1227                     struct ctables *ct, struct ctables_table *t,
1228                     enum pivot_axis_type a)
1229 {
1230   if (lex_token (lexer) == T_BY
1231       || lex_token (lexer) == T_SLASH
1232       || lex_token (lexer) == T_ENDCMD)
1233     return true;
1234
1235   struct ctables_axis_parse_ctx ctx = {
1236     .lexer = lexer,
1237     .dict = dict,
1238     .ct = ct,
1239     .t = t
1240   };
1241   t->axes[a] = ctables_axis_parse_stack (&ctx);
1242   return t->axes[a] != NULL;
1243 }
1244
1245 static void
1246 ctables_chisq_destroy (struct ctables_chisq *chisq)
1247 {
1248   free (chisq);
1249 }
1250
1251 static void
1252 ctables_pairwise_destroy (struct ctables_pairwise *pairwise)
1253 {
1254   free (pairwise);
1255 }
1256
1257 static void
1258 ctables_table_destroy (struct ctables_table *t)
1259 {
1260   if (!t)
1261     return;
1262
1263   for (size_t i = 0; i < t->n_categories; i++)
1264     ctables_categories_unref (t->categories[i]);
1265   free (t->categories);
1266
1267   ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
1268   ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
1269   ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
1270   free (t->caption);
1271   free (t->corner);
1272   free (t->title);
1273   ctables_chisq_destroy (t->chisq);
1274   ctables_pairwise_destroy (t->pairwise);
1275   free (t);
1276 }
1277
1278 static void
1279 ctables_destroy (struct ctables *ct)
1280 {
1281   if (!ct)
1282     return;
1283
1284   pivot_table_look_unref (ct->look);
1285   free (ct->zero);
1286   free (ct->missing);
1287   free (ct->vlabels);
1288   for (size_t i = 0; i < ct->n_tables; i++)
1289     ctables_table_destroy (ct->tables[i]);
1290   free (ct->tables);
1291   free (ct);
1292 }
1293
1294 static struct ctables_category
1295 cct_range (double low, double high)
1296 {
1297   return (struct ctables_category) {
1298     .type = CCT_RANGE,
1299     .range = { low, high }
1300   };
1301 }
1302
1303 static bool
1304 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
1305                                 struct ctables_table *t)
1306 {
1307   if (!lex_match_id (lexer, "VARIABLES"))
1308     return false;
1309   lex_match (lexer, T_EQUALS);
1310
1311   struct variable **vars;
1312   size_t n_vars;
1313   if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
1314     return false;
1315
1316   struct ctables_categories *c = xmalloc (sizeof *c);
1317   *c = (struct ctables_categories) { .n_refs = n_vars, .show_empty = true };
1318   for (size_t i = 0; i < n_vars; i++)
1319     {
1320       struct ctables_categories **cp
1321         = &t->categories[var_get_dict_index (vars[i])];
1322       ctables_categories_unref (*cp);
1323       *cp = c;
1324     }
1325   free (vars);
1326
1327   size_t allocated_cats = 0;
1328   if (lex_match (lexer, T_LBRACK))
1329     {
1330       do
1331         {
1332           if (c->n_cats >= allocated_cats)
1333             c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1334
1335           struct ctables_category *cat = &c->cats[c->n_cats];
1336           if (lex_match_id (lexer, "OTHERNM"))
1337             cat->type = CCT_OTHERNM;
1338           else if (lex_match_id (lexer, "MISSING"))
1339             cat->type = CCT_MISSING;
1340           else if (lex_match_id (lexer, "SUBTOTAL"))
1341             *cat = (struct ctables_category)
1342               { .type = CCT_SUBTOTAL, .total_label = NULL };
1343           else if (lex_match_id (lexer, "HSUBTOTAL"))
1344             *cat = (struct ctables_category)
1345               { .type = CCT_HSUBTOTAL, .total_label = NULL };
1346           else if (lex_match_id (lexer, "LO"))
1347             {
1348               if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
1349                 return false;
1350               *cat = cct_range (-DBL_MAX, lex_number (lexer));
1351               lex_get (lexer);
1352             }
1353           else if (lex_is_number (lexer))
1354             {
1355               double number = lex_number (lexer);
1356               lex_get (lexer);
1357               if (lex_match_id (lexer, "THRU"))
1358                 {
1359                   if (lex_match_id (lexer, "HI"))
1360                     *cat = cct_range (number, DBL_MAX);
1361                   else
1362                     {
1363                       if (!lex_force_num (lexer))
1364                         return false;
1365                       *cat = cct_range (number, lex_number (lexer));
1366                       lex_get (lexer);
1367                     }
1368                 }
1369               else
1370                 *cat = (struct ctables_category) {
1371                   .type = CCT_NUMBER,
1372                   .number = number
1373                 };
1374             }
1375           else if (lex_is_string (lexer))
1376             {
1377               *cat = (struct ctables_category) {
1378                 .type = CCT_STRING,
1379                 .string = ss_xstrdup (lex_tokss (lexer)),
1380               };
1381               lex_get (lexer);
1382             }
1383           else
1384             {
1385               lex_error (lexer, NULL);
1386               return false;
1387             }
1388
1389           if (cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL)
1390             {
1391               if (lex_match (lexer, T_EQUALS))
1392                 {
1393                   if (!lex_force_string (lexer))
1394                     return false;
1395
1396                   cat->total_label = ss_xstrdup (lex_tokss (lexer));
1397                   lex_get (lexer);
1398                 }
1399               else
1400                 cat->total_label = xstrdup (_("Subtotal"));
1401             }
1402
1403           c->n_cats++;
1404           lex_match (lexer, T_COMMA);
1405         }
1406       while (!lex_match (lexer, T_RBRACK));
1407     }
1408
1409   struct ctables_category cat = {
1410     .type = CCT_VALUE,
1411     .include_missing = false,
1412     .sort_ascending = true,
1413   };
1414   bool show_totals = false;
1415   char *total_label = NULL;
1416   bool totals_before = false;
1417   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
1418     {
1419       if (!c->n_cats && lex_match_id (lexer, "ORDER"))
1420         {
1421           lex_match (lexer, T_EQUALS);
1422           if (lex_match_id (lexer, "A"))
1423             cat.sort_ascending = true;
1424           else if (lex_match_id (lexer, "D"))
1425             cat.sort_ascending = false;
1426           else
1427             {
1428               lex_error_expecting (lexer, "A", "D");
1429               return false;
1430             }
1431         }
1432       else if (!c->n_cats && lex_match_id (lexer, "KEY"))
1433         {
1434           lex_match (lexer, T_EQUALS);
1435           if (lex_match_id (lexer, "VALUE"))
1436             cat.type = CCT_VALUE;
1437           else if (lex_match_id (lexer, "LABEL"))
1438             cat.type = CCT_LABEL;
1439           else
1440             {
1441               cat.type = CCT_FUNCTION;
1442               if (!parse_ctables_summary_function (lexer, &cat.sort_function))
1443                 return false;
1444
1445               if (lex_match (lexer, T_LPAREN))
1446                 {
1447                   cat.sort_var = parse_variable (lexer, dict);
1448                   if (!cat.sort_var)
1449                     return false;
1450
1451                   if (cat.sort_function == CTSF_PTILE)
1452                     {
1453                       lex_match (lexer, T_COMMA);
1454                       if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
1455                         return false;
1456                       cat.percentile = lex_number (lexer);
1457                       lex_get (lexer);
1458                     }
1459
1460                   if (!lex_force_match (lexer, T_RPAREN))
1461                     return false;
1462                 }
1463               else if (ctables_function_availability (cat.sort_function)
1464                        == CTFA_SCALE)
1465                 {
1466                   bool UNUSED b = lex_force_match (lexer, T_LPAREN);
1467                   return false;
1468                 }
1469             }
1470         }
1471       else if (!c->n_cats && lex_match_id (lexer, "MISSING"))
1472         {
1473           lex_match (lexer, T_EQUALS);
1474           if (lex_match_id (lexer, "INCLUDE"))
1475             cat.include_missing = true;
1476           else if (lex_match_id (lexer, "EXCLUDE"))
1477             cat.include_missing = false;
1478           else
1479             {
1480               lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1481               return false;
1482             }
1483         }
1484       else if (lex_match_id (lexer, "TOTAL"))
1485         {
1486           lex_match (lexer, T_EQUALS);
1487           if (!parse_bool (lexer, &show_totals))
1488             return false;
1489         }
1490       else if (lex_match_id (lexer, "LABEL"))
1491         {
1492           lex_match (lexer, T_EQUALS);
1493           if (!lex_force_string (lexer))
1494             return false;
1495           free (total_label);
1496           total_label = ss_xstrdup (lex_tokss (lexer));
1497           lex_get (lexer);
1498         }
1499       else if (lex_match_id (lexer, "POSITION"))
1500         {
1501           lex_match (lexer, T_EQUALS);
1502           if (lex_match_id (lexer, "BEFORE"))
1503             totals_before = true;
1504           else if (lex_match_id (lexer, "AFTER"))
1505             totals_before = false;
1506           else
1507             {
1508               lex_error_expecting (lexer, "BEFORE", "AFTER");
1509               return false;
1510             }
1511         }
1512       else if (lex_match_id (lexer, "EMPTY"))
1513         {
1514           lex_match (lexer, T_EQUALS);
1515           if (lex_match_id (lexer, "INCLUDE"))
1516             c->show_empty = true;
1517           else if (lex_match_id (lexer, "EXCLUDE"))
1518             c->show_empty = false;
1519           else
1520             {
1521               lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1522               return false;
1523             }
1524         }
1525       else
1526         {
1527           if (!c->n_cats)
1528             lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
1529                                  "TOTAL", "LABEL", "POSITION", "EMPTY");
1530           else
1531             lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
1532           return false;
1533         }
1534     }
1535
1536   if (!c->n_cats)
1537     {
1538       if (c->n_cats >= allocated_cats)
1539         c->cats = x2nrealloc (c->cats, &allocated_cats,
1540                                 sizeof *c->cats);
1541       c->cats[c->n_cats++] = cat;
1542     }
1543
1544   if (show_totals)
1545     {
1546       if (c->n_cats >= allocated_cats)
1547         c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1548
1549       struct ctables_category *totals;
1550       if (totals_before)
1551         {
1552           insert_element (c->cats, c->n_cats, sizeof *c->cats, 0);
1553           totals = &c->cats[0];
1554         }
1555       else
1556         totals = &c->cats[c->n_cats];
1557       c->n_cats++;
1558
1559       *totals = (struct ctables_category) {
1560         .type = CCT_TOTAL,
1561         .total_label = total_label ? total_label : xstrdup (_("Total")),
1562       };
1563     }
1564
1565   struct ctables_category *subtotal = NULL;
1566   for (size_t i = totals_before ? 0 : c->n_cats;
1567        totals_before ? i < c->n_cats : i-- > 0;
1568        totals_before ? i++ : 0)
1569     {
1570       struct ctables_category *cat = &c->cats[i];
1571       switch (cat->type)
1572         {
1573         case CCT_NUMBER:
1574         case CCT_STRING:
1575         case CCT_RANGE:
1576         case CCT_MISSING:
1577         case CCT_OTHERNM:
1578           cat->subtotal = subtotal;
1579           break;
1580
1581         case CCT_SUBTOTAL:
1582         case CCT_HSUBTOTAL:
1583           subtotal = cat;
1584           break;
1585
1586         case CCT_TOTAL:
1587         case CCT_VALUE:
1588         case CCT_LABEL:
1589         case CCT_FUNCTION:
1590           break;
1591         }
1592     }
1593
1594   return true;
1595 }
1596
1597 static void
1598 ctables_nest_uninit (struct ctables_nest *nest)
1599 {
1600   if (nest)
1601     free (nest->vars);
1602 }
1603
1604 static void
1605 ctables_stack_uninit (struct ctables_stack *stack)
1606 {
1607   if (stack)
1608     {
1609       for (size_t i = 0; i < stack->n; i++)
1610         ctables_nest_uninit (&stack->nests[i]);
1611       free (stack->nests);
1612     }
1613 }
1614
1615 static struct ctables_stack
1616 nest_fts (struct ctables_stack s0, struct ctables_stack s1)
1617 {
1618   if (!s0.n)
1619     return s1;
1620   else if (!s1.n)
1621     return s0;
1622
1623   struct ctables_stack stack = { .nests = xnmalloc (s0.n, s1.n * sizeof *stack.nests) };
1624   for (size_t i = 0; i < s0.n; i++)
1625     for (size_t j = 0; j < s1.n; j++)
1626       {
1627         const struct ctables_nest *a = &s0.nests[i];
1628         const struct ctables_nest *b = &s1.nests[j];
1629
1630         size_t allocate = a->n + b->n;
1631         struct variable **vars = xnmalloc (allocate, sizeof *vars);
1632         enum pivot_axis_type *axes = xnmalloc (allocate, sizeof *axes);
1633         size_t n = 0;
1634         for (size_t k = 0; k < a->n; k++)
1635           vars[n++] = a->vars[k];
1636         for (size_t k = 0; k < b->n; k++)
1637           vars[n++] = b->vars[k];
1638         assert (n == allocate);
1639
1640         const struct ctables_nest *summary_src;
1641         if (!a->specs[CSV_CELL].var)
1642           summary_src = b;
1643         else if (!b->specs[CSV_CELL].var)
1644           summary_src = a;
1645         else
1646           NOT_REACHED ();
1647
1648         struct ctables_nest *new = &stack.nests[stack.n++];
1649         *new = (struct ctables_nest) {
1650           .vars = vars,
1651           .scale_idx = (a->scale_idx != SIZE_MAX ? a->scale_idx
1652                         : b->scale_idx != SIZE_MAX ? a->n + b->scale_idx
1653                         : SIZE_MAX),
1654           .n = n,
1655         };
1656         for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1657           ctables_summary_spec_set_clone (&new->specs[sv], &summary_src->specs[sv]);
1658       }
1659   ctables_stack_uninit (&s0);
1660   ctables_stack_uninit (&s1);
1661   return stack;
1662 }
1663
1664 static struct ctables_stack
1665 stack_fts (struct ctables_stack s0, struct ctables_stack s1)
1666 {
1667   struct ctables_stack stack = { .nests = xnmalloc (s0.n + s1.n, sizeof *stack.nests) };
1668   for (size_t i = 0; i < s0.n; i++)
1669     stack.nests[stack.n++] = s0.nests[i];
1670   for (size_t i = 0; i < s1.n; i++)
1671     stack.nests[stack.n++] = s1.nests[i];
1672   assert (stack.n == s0.n + s1.n);
1673   free (s0.nests);
1674   free (s1.nests);
1675   return stack;
1676 }
1677
1678 static struct ctables_stack
1679 enumerate_fts (enum pivot_axis_type axis_type, const struct ctables_axis *a)
1680 {
1681   if (!a)
1682     return (struct ctables_stack) { .n = 0 };
1683
1684   switch (a->op)
1685     {
1686     case CTAO_VAR:
1687       assert (!a->var.is_mrset);
1688
1689       struct variable **vars = xmalloc (sizeof *vars);
1690       *vars = a->var.var;
1691
1692       struct ctables_nest *nest = xmalloc (sizeof *nest);
1693       *nest = (struct ctables_nest) {
1694         .vars = vars,
1695         .n = 1,
1696         .scale_idx = a->scale ? 0 : SIZE_MAX,
1697       };
1698       if (a->specs[CSV_CELL].n || a->scale)
1699         for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1700           {
1701             ctables_summary_spec_set_clone (&nest->specs[sv], &a->specs[sv]);
1702             nest->specs[sv].var = a->var.var;
1703           }
1704       return (struct ctables_stack) { .nests = nest, .n = 1 };
1705
1706     case CTAO_STACK:
1707       return stack_fts (enumerate_fts (axis_type, a->subs[0]),
1708                         enumerate_fts (axis_type, a->subs[1]));
1709
1710     case CTAO_NEST:
1711       return nest_fts (enumerate_fts (axis_type, a->subs[0]),
1712                        enumerate_fts (axis_type, a->subs[1]));
1713     }
1714
1715   NOT_REACHED ();
1716 }
1717
1718 union ctables_summary
1719   {
1720     /* COUNT, VALIDN, TOTALN. */
1721     struct
1722       {
1723         double valid;
1724         double missing;
1725       };
1726
1727     /* MINIMUM, MAXIMUM, RANGE. */
1728     struct
1729       {
1730         double min;
1731         double max;
1732       };
1733
1734     /* MEAN, SEMEAN, STDDEV, SUM, VARIANCE, *.SUM. */
1735     struct moments1 *moments;
1736
1737     /* MEDIAN, MODE, PTILE. */
1738     struct
1739       {
1740         struct casewriter *writer;
1741         double ovalid;
1742         double ovalue;
1743       };
1744
1745     /* XXX multiple response */
1746   };
1747
1748 static void
1749 ctables_summary_init (union ctables_summary *s,
1750                       const struct ctables_summary_spec *ss)
1751 {
1752   switch (ss->function)
1753     {
1754     case CTSF_COUNT:
1755     case CTSF_ECOUNT:
1756     case CTSF_ROWPCT_COUNT:
1757     case CTSF_COLPCT_COUNT:
1758     case CTSF_TABLEPCT_COUNT:
1759     case CTSF_SUBTABLEPCT_COUNT:
1760     case CTSF_LAYERPCT_COUNT:
1761     case CTSF_LAYERROWPCT_COUNT:
1762     case CTSF_LAYERCOLPCT_COUNT:
1763     case CTSF_ROWPCT_VALIDN:
1764     case CTSF_COLPCT_VALIDN:
1765     case CTSF_TABLEPCT_VALIDN:
1766     case CTSF_SUBTABLEPCT_VALIDN:
1767     case CTSF_LAYERPCT_VALIDN:
1768     case CTSF_LAYERROWPCT_VALIDN:
1769     case CTSF_LAYERCOLPCT_VALIDN:
1770     case CTSF_ROWPCT_TOTALN:
1771     case CTSF_COLPCT_TOTALN:
1772     case CTSF_TABLEPCT_TOTALN:
1773     case CTSF_SUBTABLEPCT_TOTALN:
1774     case CTSF_LAYERPCT_TOTALN:
1775     case CTSF_LAYERROWPCT_TOTALN:
1776     case CTSF_LAYERCOLPCT_TOTALN:
1777     case CTSF_MISSING:
1778     case CSTF_TOTALN:
1779     case CTSF_ETOTALN:
1780     case CTSF_VALIDN:
1781     case CTSF_EVALIDN:
1782       s->missing = s->valid = 0;
1783       break;
1784
1785     case CTSF_MAXIMUM:
1786     case CTSF_MINIMUM:
1787     case CTSF_RANGE:
1788       s->min = s->max = SYSMIS;
1789       break;
1790
1791     case CTSF_MEAN:
1792     case CTSF_SEMEAN:
1793     case CTSF_STDDEV:
1794     case CTSF_SUM:
1795     case CTSF_VARIANCE:
1796     case CTSF_ROWPCT_SUM:
1797     case CTSF_COLPCT_SUM:
1798     case CTSF_TABLEPCT_SUM:
1799     case CTSF_SUBTABLEPCT_SUM:
1800     case CTSF_LAYERPCT_SUM:
1801     case CTSF_LAYERROWPCT_SUM:
1802     case CTSF_LAYERCOLPCT_SUM:
1803       s->moments = moments1_create (MOMENT_VARIANCE);
1804       break;
1805
1806     case CTSF_MEDIAN:
1807     case CTSF_MODE:
1808     case CTSF_PTILE:
1809       {
1810         struct caseproto *proto = caseproto_create ();
1811         proto = caseproto_add_width (proto, 0);
1812         proto = caseproto_add_width (proto, 0);
1813
1814         struct subcase ordering;
1815         subcase_init (&ordering, 0, 0, SC_ASCEND);
1816         s->writer = sort_create_writer (&ordering, proto);
1817         subcase_uninit (&ordering);
1818         caseproto_unref (proto);
1819
1820         s->ovalid = 0;
1821         s->ovalue = SYSMIS;
1822       }
1823       break;
1824
1825     case CTSF_RESPONSES:
1826     case CTSF_ROWPCT_RESPONSES:
1827     case CTSF_COLPCT_RESPONSES:
1828     case CTSF_TABLEPCT_RESPONSES:
1829     case CTSF_SUBTABLEPCT_RESPONSES:
1830     case CTSF_LAYERPCT_RESPONSES:
1831     case CTSF_LAYERROWPCT_RESPONSES:
1832     case CTSF_LAYERCOLPCT_RESPONSES:
1833     case CTSF_ROWPCT_RESPONSES_COUNT:
1834     case CTSF_COLPCT_RESPONSES_COUNT:
1835     case CTSF_TABLEPCT_RESPONSES_COUNT:
1836     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1837     case CTSF_LAYERPCT_RESPONSES_COUNT:
1838     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1839     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1840     case CTSF_ROWPCT_COUNT_RESPONSES:
1841     case CTSF_COLPCT_COUNT_RESPONSES:
1842     case CTSF_TABLEPCT_COUNT_RESPONSES:
1843     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1844     case CTSF_LAYERPCT_COUNT_RESPONSES:
1845     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1846     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1847       NOT_REACHED ();
1848     }
1849 }
1850
1851 static void UNUSED
1852 ctables_summary_uninit (union ctables_summary *s,
1853                         const struct ctables_summary_spec *ss)
1854 {
1855   switch (ss->function)
1856     {
1857     case CTSF_COUNT:
1858     case CTSF_ECOUNT:
1859     case CTSF_ROWPCT_COUNT:
1860     case CTSF_COLPCT_COUNT:
1861     case CTSF_TABLEPCT_COUNT:
1862     case CTSF_SUBTABLEPCT_COUNT:
1863     case CTSF_LAYERPCT_COUNT:
1864     case CTSF_LAYERROWPCT_COUNT:
1865     case CTSF_LAYERCOLPCT_COUNT:
1866     case CTSF_ROWPCT_VALIDN:
1867     case CTSF_COLPCT_VALIDN:
1868     case CTSF_TABLEPCT_VALIDN:
1869     case CTSF_SUBTABLEPCT_VALIDN:
1870     case CTSF_LAYERPCT_VALIDN:
1871     case CTSF_LAYERROWPCT_VALIDN:
1872     case CTSF_LAYERCOLPCT_VALIDN:
1873     case CTSF_ROWPCT_TOTALN:
1874     case CTSF_COLPCT_TOTALN:
1875     case CTSF_TABLEPCT_TOTALN:
1876     case CTSF_SUBTABLEPCT_TOTALN:
1877     case CTSF_LAYERPCT_TOTALN:
1878     case CTSF_LAYERROWPCT_TOTALN:
1879     case CTSF_LAYERCOLPCT_TOTALN:
1880     case CTSF_MISSING:
1881     case CSTF_TOTALN:
1882     case CTSF_ETOTALN:
1883     case CTSF_VALIDN:
1884     case CTSF_EVALIDN:
1885       break;
1886
1887     case CTSF_MAXIMUM:
1888     case CTSF_MINIMUM:
1889     case CTSF_RANGE:
1890       break;
1891
1892     case CTSF_MEAN:
1893     case CTSF_SEMEAN:
1894     case CTSF_STDDEV:
1895     case CTSF_SUM:
1896     case CTSF_VARIANCE:
1897     case CTSF_ROWPCT_SUM:
1898     case CTSF_COLPCT_SUM:
1899     case CTSF_TABLEPCT_SUM:
1900     case CTSF_SUBTABLEPCT_SUM:
1901     case CTSF_LAYERPCT_SUM:
1902     case CTSF_LAYERROWPCT_SUM:
1903     case CTSF_LAYERCOLPCT_SUM:
1904       moments1_destroy (s->moments);
1905       break;
1906
1907     case CTSF_MEDIAN:
1908     case CTSF_MODE:
1909     case CTSF_PTILE:
1910       casewriter_destroy (s->writer);
1911       break;
1912
1913     case CTSF_RESPONSES:
1914     case CTSF_ROWPCT_RESPONSES:
1915     case CTSF_COLPCT_RESPONSES:
1916     case CTSF_TABLEPCT_RESPONSES:
1917     case CTSF_SUBTABLEPCT_RESPONSES:
1918     case CTSF_LAYERPCT_RESPONSES:
1919     case CTSF_LAYERROWPCT_RESPONSES:
1920     case CTSF_LAYERCOLPCT_RESPONSES:
1921     case CTSF_ROWPCT_RESPONSES_COUNT:
1922     case CTSF_COLPCT_RESPONSES_COUNT:
1923     case CTSF_TABLEPCT_RESPONSES_COUNT:
1924     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1925     case CTSF_LAYERPCT_RESPONSES_COUNT:
1926     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1927     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1928     case CTSF_ROWPCT_COUNT_RESPONSES:
1929     case CTSF_COLPCT_COUNT_RESPONSES:
1930     case CTSF_TABLEPCT_COUNT_RESPONSES:
1931     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1932     case CTSF_LAYERPCT_COUNT_RESPONSES:
1933     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1934     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1935       NOT_REACHED ();
1936     }
1937 }
1938
1939 static void
1940 ctables_summary_add (union ctables_summary *s,
1941                      const struct ctables_summary_spec *ss,
1942                      const struct variable *var, const union value *value,
1943                      double d_weight, double e_weight)
1944 {
1945   switch (ss->function)
1946     {
1947     case CTSF_COUNT:
1948     case CSTF_TOTALN:
1949     case CTSF_VALIDN:
1950       if (var_is_value_missing (var, value))
1951         s->missing += d_weight;
1952       else
1953         s->valid += d_weight;
1954       break;
1955
1956     case CTSF_ECOUNT:
1957     case CTSF_ROWPCT_COUNT:
1958     case CTSF_COLPCT_COUNT:
1959     case CTSF_TABLEPCT_COUNT:
1960     case CTSF_SUBTABLEPCT_COUNT:
1961     case CTSF_LAYERPCT_COUNT:
1962     case CTSF_LAYERROWPCT_COUNT:
1963     case CTSF_LAYERCOLPCT_COUNT:
1964     case CTSF_ROWPCT_VALIDN:
1965     case CTSF_COLPCT_VALIDN:
1966     case CTSF_TABLEPCT_VALIDN:
1967     case CTSF_SUBTABLEPCT_VALIDN:
1968     case CTSF_LAYERPCT_VALIDN:
1969     case CTSF_LAYERROWPCT_VALIDN:
1970     case CTSF_LAYERCOLPCT_VALIDN:
1971     case CTSF_ROWPCT_TOTALN:
1972     case CTSF_COLPCT_TOTALN:
1973     case CTSF_TABLEPCT_TOTALN:
1974     case CTSF_SUBTABLEPCT_TOTALN:
1975     case CTSF_LAYERPCT_TOTALN:
1976     case CTSF_LAYERROWPCT_TOTALN:
1977     case CTSF_LAYERCOLPCT_TOTALN:
1978     case CTSF_MISSING:
1979     case CTSF_ETOTALN:
1980     case CTSF_EVALIDN:
1981       if (var_is_value_missing (var, value))
1982         s->missing += e_weight;
1983       else
1984         s->valid += e_weight;
1985       break;
1986
1987     case CTSF_MAXIMUM:
1988     case CTSF_MINIMUM:
1989     case CTSF_RANGE:
1990       if (!var_is_value_missing (var, value))
1991         {
1992           assert (!var_is_alpha (var)); /* XXX? */
1993           if (s->min == SYSMIS || value->f < s->min)
1994             s->min = value->f;
1995           if (s->max == SYSMIS || value->f > s->max)
1996             s->max = value->f;
1997         }
1998       break;
1999
2000     case CTSF_MEAN:
2001     case CTSF_SEMEAN:
2002     case CTSF_STDDEV:
2003     case CTSF_SUM:
2004     case CTSF_VARIANCE:
2005     case CTSF_ROWPCT_SUM:
2006     case CTSF_COLPCT_SUM:
2007     case CTSF_TABLEPCT_SUM:
2008     case CTSF_SUBTABLEPCT_SUM:
2009     case CTSF_LAYERPCT_SUM:
2010     case CTSF_LAYERROWPCT_SUM:
2011     case CTSF_LAYERCOLPCT_SUM:
2012       if (!var_is_value_missing (var, value))
2013         moments1_add (s->moments, value->f, e_weight);
2014       break;
2015
2016     case CTSF_MEDIAN:
2017     case CTSF_MODE:
2018     case CTSF_PTILE:
2019       if (var_is_value_missing (var, value))
2020         {
2021           s->ovalid += e_weight;
2022
2023           struct ccase *c = case_create (casewriter_get_proto (s->writer));
2024           *case_num_rw_idx (c, 0) = value->f;
2025           *case_num_rw_idx (c, 1) = e_weight;
2026           casewriter_write (s->writer, c);
2027         }
2028       break;
2029
2030     case CTSF_RESPONSES:
2031     case CTSF_ROWPCT_RESPONSES:
2032     case CTSF_COLPCT_RESPONSES:
2033     case CTSF_TABLEPCT_RESPONSES:
2034     case CTSF_SUBTABLEPCT_RESPONSES:
2035     case CTSF_LAYERPCT_RESPONSES:
2036     case CTSF_LAYERROWPCT_RESPONSES:
2037     case CTSF_LAYERCOLPCT_RESPONSES:
2038     case CTSF_ROWPCT_RESPONSES_COUNT:
2039     case CTSF_COLPCT_RESPONSES_COUNT:
2040     case CTSF_TABLEPCT_RESPONSES_COUNT:
2041     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2042     case CTSF_LAYERPCT_RESPONSES_COUNT:
2043     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2044     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2045     case CTSF_ROWPCT_COUNT_RESPONSES:
2046     case CTSF_COLPCT_COUNT_RESPONSES:
2047     case CTSF_TABLEPCT_COUNT_RESPONSES:
2048     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2049     case CTSF_LAYERPCT_COUNT_RESPONSES:
2050     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2051     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2052       NOT_REACHED ();
2053     }
2054 }
2055
2056 static enum ctables_domain_type
2057 ctables_function_domain (enum ctables_summary_function function)
2058 {
2059   switch (function)
2060     {
2061     case CTSF_COUNT:
2062     case CTSF_ECOUNT:
2063     case CTSF_MISSING:
2064     case CSTF_TOTALN:
2065     case CTSF_ETOTALN:
2066     case CTSF_VALIDN:
2067     case CTSF_EVALIDN:
2068     case CTSF_MAXIMUM:
2069     case CTSF_MINIMUM:
2070     case CTSF_RANGE:
2071     case CTSF_MEAN:
2072     case CTSF_SEMEAN:
2073     case CTSF_STDDEV:
2074     case CTSF_SUM:
2075     case CTSF_VARIANCE:
2076     case CTSF_MEDIAN:
2077     case CTSF_PTILE:
2078     case CTSF_MODE:
2079     case CTSF_RESPONSES:
2080       NOT_REACHED ();
2081
2082     case CTSF_COLPCT_COUNT:
2083     case CTSF_COLPCT_COUNT_RESPONSES:
2084     case CTSF_COLPCT_RESPONSES:
2085     case CTSF_COLPCT_RESPONSES_COUNT:
2086     case CTSF_COLPCT_SUM:
2087     case CTSF_COLPCT_TOTALN:
2088     case CTSF_COLPCT_VALIDN:
2089       return CTDT_COL;
2090
2091     case CTSF_LAYERCOLPCT_COUNT:
2092     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2093     case CTSF_LAYERCOLPCT_RESPONSES:
2094     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2095     case CTSF_LAYERCOLPCT_SUM:
2096     case CTSF_LAYERCOLPCT_TOTALN:
2097     case CTSF_LAYERCOLPCT_VALIDN:
2098       return CTDT_LAYERCOL;
2099
2100     case CTSF_LAYERPCT_COUNT:
2101     case CTSF_LAYERPCT_COUNT_RESPONSES:
2102     case CTSF_LAYERPCT_RESPONSES:
2103     case CTSF_LAYERPCT_RESPONSES_COUNT:
2104     case CTSF_LAYERPCT_SUM:
2105     case CTSF_LAYERPCT_TOTALN:
2106     case CTSF_LAYERPCT_VALIDN:
2107       return CTDT_LAYER;
2108
2109     case CTSF_LAYERROWPCT_COUNT:
2110     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2111     case CTSF_LAYERROWPCT_RESPONSES:
2112     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2113     case CTSF_LAYERROWPCT_SUM:
2114     case CTSF_LAYERROWPCT_TOTALN:
2115     case CTSF_LAYERROWPCT_VALIDN:
2116       return CTDT_LAYERROW;
2117
2118     case CTSF_ROWPCT_COUNT:
2119     case CTSF_ROWPCT_COUNT_RESPONSES:
2120     case CTSF_ROWPCT_RESPONSES:
2121     case CTSF_ROWPCT_RESPONSES_COUNT:
2122     case CTSF_ROWPCT_SUM:
2123     case CTSF_ROWPCT_TOTALN:
2124     case CTSF_ROWPCT_VALIDN:
2125       return CTDT_ROW;
2126
2127     case CTSF_SUBTABLEPCT_COUNT:
2128     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2129     case CTSF_SUBTABLEPCT_RESPONSES:
2130     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2131     case CTSF_SUBTABLEPCT_SUM:
2132     case CTSF_SUBTABLEPCT_TOTALN:
2133     case CTSF_SUBTABLEPCT_VALIDN:
2134       return CTDT_SUBTABLE;
2135
2136     case CTSF_TABLEPCT_COUNT:
2137     case CTSF_TABLEPCT_COUNT_RESPONSES:
2138     case CTSF_TABLEPCT_RESPONSES:
2139     case CTSF_TABLEPCT_RESPONSES_COUNT:
2140     case CTSF_TABLEPCT_SUM:
2141     case CTSF_TABLEPCT_TOTALN:
2142     case CTSF_TABLEPCT_VALIDN:
2143       return CTDT_TABLE;
2144     }
2145
2146   NOT_REACHED ();
2147 }
2148
2149 static double
2150 ctables_summary_value (const struct ctables_cell *cell,
2151                        union ctables_summary *s,
2152                        const struct ctables_summary_spec *ss)
2153 {
2154   switch (ss->function)
2155     {
2156     case CTSF_COUNT:
2157     case CTSF_ECOUNT:
2158       return s->valid;
2159
2160     case CTSF_ROWPCT_COUNT:
2161     case CTSF_COLPCT_COUNT:
2162     case CTSF_TABLEPCT_COUNT:
2163     case CTSF_SUBTABLEPCT_COUNT:
2164     case CTSF_LAYERPCT_COUNT:
2165     case CTSF_LAYERROWPCT_COUNT:
2166     case CTSF_LAYERCOLPCT_COUNT:
2167       {
2168         enum ctables_domain_type d = ctables_function_domain (ss->function);
2169         return (cell->domains[d]->e_valid
2170                 ? s->valid / cell->domains[d]->e_valid * 100
2171                 : SYSMIS);
2172       }
2173
2174     case CTSF_ROWPCT_VALIDN:
2175     case CTSF_COLPCT_VALIDN:
2176     case CTSF_TABLEPCT_VALIDN:
2177     case CTSF_SUBTABLEPCT_VALIDN:
2178     case CTSF_LAYERPCT_VALIDN:
2179     case CTSF_LAYERROWPCT_VALIDN:
2180     case CTSF_LAYERCOLPCT_VALIDN:
2181     case CTSF_ROWPCT_TOTALN:
2182     case CTSF_COLPCT_TOTALN:
2183     case CTSF_TABLEPCT_TOTALN:
2184     case CTSF_SUBTABLEPCT_TOTALN:
2185     case CTSF_LAYERPCT_TOTALN:
2186     case CTSF_LAYERROWPCT_TOTALN:
2187     case CTSF_LAYERCOLPCT_TOTALN:
2188       NOT_REACHED ();
2189
2190     case CTSF_MISSING:
2191       return s->missing;
2192
2193     case CSTF_TOTALN:
2194     case CTSF_ETOTALN:
2195       return s->valid + s->missing;
2196
2197     case CTSF_VALIDN:
2198     case CTSF_EVALIDN:
2199       return s->valid;
2200
2201     case CTSF_MAXIMUM:
2202       return s->max;
2203
2204     case CTSF_MINIMUM:
2205       return s->min;
2206
2207     case CTSF_RANGE:
2208       return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
2209
2210     case CTSF_MEAN:
2211       {
2212         double mean;
2213         moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
2214         return mean;
2215       }
2216
2217     case CTSF_SEMEAN:
2218       {
2219         double weight, variance;
2220         moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
2221         return calc_semean (variance, weight);
2222       }
2223
2224     case CTSF_STDDEV:
2225       {
2226         double variance;
2227         moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2228         return variance != SYSMIS ? sqrt (variance) : SYSMIS;
2229       }
2230
2231     case CTSF_SUM:
2232       {
2233         double weight, mean;
2234         moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
2235         return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
2236       }
2237
2238     case CTSF_VARIANCE:
2239       {
2240         double variance;
2241         moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2242         return variance;
2243       }
2244
2245     case CTSF_ROWPCT_SUM:
2246     case CTSF_COLPCT_SUM:
2247     case CTSF_TABLEPCT_SUM:
2248     case CTSF_SUBTABLEPCT_SUM:
2249     case CTSF_LAYERPCT_SUM:
2250     case CTSF_LAYERROWPCT_SUM:
2251     case CTSF_LAYERCOLPCT_SUM:
2252       NOT_REACHED ();
2253
2254     case CTSF_MEDIAN:
2255     case CTSF_PTILE:
2256       if (s->writer)
2257         {
2258           struct casereader *reader = casewriter_make_reader (s->writer);
2259           s->writer = NULL;
2260
2261           struct percentile *ptile = percentile_create (
2262             ss->function == CTSF_PTILE ? ss->percentile : 0.5, s->ovalid);
2263           struct order_stats *os = &ptile->parent;
2264           order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2265           s->ovalue = percentile_calculate (ptile, PC_HAVERAGE);
2266           statistic_destroy (&ptile->parent.parent);
2267         }
2268       return s->ovalue;
2269
2270     case CTSF_MODE:
2271       if (s->writer)
2272         {
2273           struct casereader *reader = casewriter_make_reader (s->writer);
2274           s->writer = NULL;
2275
2276           struct mode *mode = mode_create ();
2277           struct order_stats *os = &mode->parent;
2278           order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2279           s->ovalue = mode->mode;
2280           statistic_destroy (&mode->parent.parent);
2281         }
2282       return s->ovalue;
2283
2284     case CTSF_RESPONSES:
2285     case CTSF_ROWPCT_RESPONSES:
2286     case CTSF_COLPCT_RESPONSES:
2287     case CTSF_TABLEPCT_RESPONSES:
2288     case CTSF_SUBTABLEPCT_RESPONSES:
2289     case CTSF_LAYERPCT_RESPONSES:
2290     case CTSF_LAYERROWPCT_RESPONSES:
2291     case CTSF_LAYERCOLPCT_RESPONSES:
2292     case CTSF_ROWPCT_RESPONSES_COUNT:
2293     case CTSF_COLPCT_RESPONSES_COUNT:
2294     case CTSF_TABLEPCT_RESPONSES_COUNT:
2295     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2296     case CTSF_LAYERPCT_RESPONSES_COUNT:
2297     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2298     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2299     case CTSF_ROWPCT_COUNT_RESPONSES:
2300     case CTSF_COLPCT_COUNT_RESPONSES:
2301     case CTSF_TABLEPCT_COUNT_RESPONSES:
2302     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2303     case CTSF_LAYERPCT_COUNT_RESPONSES:
2304     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2305     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2306       NOT_REACHED ();
2307     }
2308
2309   NOT_REACHED ();
2310 }
2311
2312 struct ctables_cell_sort_aux
2313   {
2314     const struct ctables_nest *nest;
2315     enum pivot_axis_type a;
2316   };
2317
2318 static int
2319 ctables_cell_compare_3way (const void *a_, const void *b_, const void *aux_)
2320 {
2321   const struct ctables_cell_sort_aux *aux = aux_;
2322   struct ctables_cell *const *ap = a_;
2323   struct ctables_cell *const *bp = b_;
2324   const struct ctables_cell *a = *ap;
2325   const struct ctables_cell *b = *bp;
2326
2327   const struct ctables_nest *nest = aux->nest;
2328   for (size_t i = 0; i < nest->n; i++)
2329     if (i != nest->scale_idx)
2330       {
2331         const struct variable *var = nest->vars[i];
2332         const struct ctables_cell_value *a_cv = &a->axes[aux->a].cvs[i];
2333         const struct ctables_cell_value *b_cv = &b->axes[aux->a].cvs[i];
2334         if (a_cv->category != b_cv->category)
2335           return a_cv->category > b_cv->category ? 1 : -1;
2336
2337         const union value *a_val = &a_cv->value;
2338         const union value *b_val = &b_cv->value;
2339         switch (a_cv->category->type)
2340           {
2341           case CCT_NUMBER:
2342           case CCT_STRING:
2343           case CCT_SUBTOTAL:
2344           case CCT_HSUBTOTAL:
2345           case CCT_TOTAL:
2346             /* Must be equal. */
2347             continue;
2348
2349           case CCT_RANGE:
2350           case CCT_MISSING:
2351           case CCT_OTHERNM:
2352             {
2353               int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2354               if (cmp)
2355                 return cmp;
2356             }
2357             break;
2358
2359           case CCT_VALUE:
2360             {
2361               int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2362               if (cmp)
2363                 return a_cv->category->sort_ascending ? cmp : -cmp;
2364             }
2365             break;
2366
2367           case CCT_LABEL:
2368             {
2369               const char *a_label = var_lookup_value_label (var, a_val);
2370               const char *b_label = var_lookup_value_label (var, b_val);
2371               int cmp = (a_label
2372                          ? (b_label ? strcmp (a_label, b_label) : 1)
2373                          : (b_label ? -1 : value_compare_3way (
2374                               a_val, b_val, var_get_width (var))));
2375               if (cmp)
2376                 return a_cv->category->sort_ascending ? cmp : -cmp;
2377             }
2378             break;
2379
2380           case CCT_FUNCTION:
2381             NOT_REACHED ();
2382           }
2383       }
2384   return 0;
2385 }
2386
2387 /* Algorithm:
2388
2389    For each row:
2390        For each ctables_table:
2391            For each combination of row vars:
2392                For each combination of column vars:
2393                    For each combination of layer vars:
2394                        Add entry
2395    Make a table of row values:
2396        Sort entries by row values
2397        Assign a 0-based index to each actual value
2398        Construct a dimension
2399    Make a table of column values
2400    Make a table of layer values
2401    For each entry:
2402        Fill the table entry using the indexes from before.
2403  */
2404
2405 static struct ctables_domain *
2406 ctables_domain_insert (struct ctables_section *s, struct ctables_cell *cell,
2407                        enum ctables_domain_type domain)
2408 {
2409   size_t hash = 0;
2410   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2411     {
2412       const struct ctables_nest *nest = s->nests[a];
2413       for (size_t i = 0; i < nest->n_domains[domain]; i++)
2414         {
2415           size_t v_idx = nest->domains[domain][i];
2416           hash = value_hash (&cell->axes[a].cvs[v_idx].value,
2417                              var_get_width (nest->vars[v_idx]), hash);
2418         }
2419     }
2420
2421   struct ctables_domain *d;
2422   HMAP_FOR_EACH_WITH_HASH (d, struct ctables_domain, node, hash, &s->domains[domain])
2423     {
2424       const struct ctables_cell *df = d->example;
2425       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2426         {
2427           const struct ctables_nest *nest = s->nests[a];
2428           for (size_t i = 0; i < nest->n_domains[domain]; i++)
2429             {
2430               size_t v_idx = nest->domains[domain][i];
2431               if (!value_equal (&df->axes[a].cvs[v_idx].value,
2432                                 &cell->axes[a].cvs[v_idx].value,
2433                                 var_get_width (nest->vars[v_idx])))
2434                 goto not_equal;
2435             }
2436         }
2437       return d;
2438
2439     not_equal: ;
2440     }
2441
2442   d = xmalloc (sizeof *d);
2443   *d = (struct ctables_domain) { .example = cell };
2444   hmap_insert (&s->domains[domain], &d->node, hash);
2445   return d;
2446 }
2447
2448 static const struct ctables_category *
2449 ctables_categories_match (const struct ctables_categories *c,
2450                           const union value *v, const struct variable *var)
2451 {
2452   const struct ctables_category *othernm = NULL;
2453   for (size_t i = c->n_cats; i-- > 0; )
2454     {
2455       const struct ctables_category *cat = &c->cats[i];
2456       switch (cat->type)
2457         {
2458         case CCT_NUMBER:
2459           if (cat->number == v->f)
2460             return cat;
2461           break;
2462
2463         case CCT_STRING:
2464           NOT_REACHED ();
2465
2466         case CCT_RANGE:
2467           if ((cat->range[0] == -DBL_MAX || v->f >= cat->range[0])
2468               && (cat->range[1] == DBL_MAX || v->f <= cat->range[1]))
2469             return cat;
2470           break;
2471
2472         case CCT_MISSING:
2473           if (var_is_value_missing (var, v))
2474             return cat;
2475           break;
2476
2477         case CCT_OTHERNM:
2478           if (!othernm)
2479             othernm = cat;
2480           break;
2481
2482         case CCT_SUBTOTAL:
2483         case CCT_HSUBTOTAL:
2484         case CCT_TOTAL:
2485           break;
2486
2487         case CCT_VALUE:
2488         case CCT_LABEL:
2489         case CCT_FUNCTION:
2490           return (cat->include_missing || !var_is_value_missing (var, v) ? cat
2491                   : NULL);
2492         }
2493     }
2494
2495   return var_is_value_missing (var, v) ? NULL : othernm;
2496 }
2497
2498 static const struct ctables_category *
2499 ctables_categories_total (const struct ctables_categories *c)
2500 {
2501   const struct ctables_category *first = &c->cats[0];
2502   const struct ctables_category *last = &c->cats[c->n_cats - 1];
2503   return (first->type == CCT_TOTAL ? first
2504           : last->type == CCT_TOTAL ? last
2505           : NULL);
2506 }
2507
2508 static struct ctables_cell *
2509 ctables_cell_insert__ (struct ctables_section *s, const struct ccase *c,
2510                        const struct ctables_category *cats[PIVOT_N_AXES][10])
2511 {
2512   const struct ctables_nest *ss = s->nests[s->table->summary_axis];
2513
2514   size_t hash = 0;
2515   enum ctables_summary_variant sv = CSV_CELL;
2516   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2517     {
2518       const struct ctables_nest *nest = s->nests[a];
2519       for (size_t i = 0; i < nest->n; i++)
2520         if (i != nest->scale_idx)
2521           {
2522             hash = hash_pointer (cats[a][i], hash);
2523             if (cats[a][i]->type != CCT_TOTAL
2524                 && cats[a][i]->type != CCT_SUBTOTAL
2525                 && cats[a][i]->type != CCT_HSUBTOTAL)
2526               hash = value_hash (case_data (c, nest->vars[i]),
2527                                  var_get_width (nest->vars[i]), hash);
2528             else
2529               sv = CSV_TOTAL;
2530           }
2531     }
2532
2533   struct ctables_cell *cell;
2534   HMAP_FOR_EACH_WITH_HASH (cell, struct ctables_cell, node, hash, &s->cells)
2535     {
2536       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2537         {
2538           const struct ctables_nest *nest = s->nests[a];
2539           for (size_t i = 0; i < nest->n; i++)
2540             if (i != nest->scale_idx
2541                 && (cats[a][i] != cell->axes[a].cvs[i].category
2542                     || (cats[a][i]->type != CCT_TOTAL
2543                         && cats[a][i]->type != CCT_SUBTOTAL
2544                         && cats[a][i]->type != CCT_HSUBTOTAL
2545                         && !value_equal (case_data (c, nest->vars[i]),
2546                                          &cell->axes[a].cvs[i].value,
2547                                          var_get_width (nest->vars[i])))))
2548                 goto not_equal;
2549         }
2550
2551       return cell;
2552
2553     not_equal: ;
2554     }
2555
2556   cell = xmalloc (sizeof *cell);
2557   cell->hide = false;
2558   cell->sv = sv;
2559   cell->contributes_to_domains = true;
2560   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2561     {
2562       const struct ctables_nest *nest = s->nests[a];
2563       cell->axes[a].cvs = (nest->n
2564                         ? xnmalloc (nest->n, sizeof *cell->axes[a].cvs)
2565                         : NULL);
2566       for (size_t i = 0; i < nest->n; i++)
2567         {
2568           const struct ctables_category *cat = cats[a][i];
2569
2570           if (i != nest->scale_idx)
2571             {
2572               const struct ctables_category *subtotal = cat->subtotal;
2573               if (subtotal && subtotal->type == CCT_HSUBTOTAL)
2574                 cell->hide = true;
2575
2576               if (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL)
2577                 cell->contributes_to_domains = false;
2578             }
2579
2580           cell->axes[a].cvs[i].category = cat;
2581           value_clone (&cell->axes[a].cvs[i].value, case_data (c, nest->vars[i]),
2582                        var_get_width (nest->vars[i]));
2583         }
2584     }
2585
2586   const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2587   cell->summaries = xmalloc (specs->n * sizeof *cell->summaries);
2588   for (size_t i = 0; i < specs->n; i++)
2589     ctables_summary_init (&cell->summaries[i], &specs->specs[i]);
2590   for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2591     cell->domains[dt] = ctables_domain_insert (s, cell, dt);
2592   hmap_insert (&s->cells, &cell->node, hash);
2593   return cell;
2594 }
2595
2596 static void
2597 ctables_cell_add__ (struct ctables_section *s, const struct ccase *c,
2598                     const struct ctables_category *cats[PIVOT_N_AXES][10],
2599                     double d_weight, double e_weight)
2600 {
2601   struct ctables_cell *cell = ctables_cell_insert__ (s, c, cats);
2602   const struct ctables_nest *ss = s->nests[s->table->summary_axis];
2603
2604   const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2605   for (size_t i = 0; i < specs->n; i++)
2606     ctables_summary_add (&cell->summaries[i], &specs->specs[i], specs->var,
2607                          case_data (c, specs->var), d_weight, e_weight);
2608   if (cell->contributes_to_domains)
2609     {
2610       for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2611         {
2612           cell->domains[dt]->d_valid += d_weight;
2613           cell->domains[dt]->e_valid += e_weight;
2614         }
2615     }
2616 }
2617
2618 static void
2619 recurse_totals (struct ctables_section *s, const struct ccase *c,
2620                 const struct ctables_category *cats[PIVOT_N_AXES][10],
2621                 double d_weight, double e_weight,
2622                 enum pivot_axis_type start_axis, size_t start_nest)
2623 {
2624   for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2625     {
2626       const struct ctables_nest *nest = s->nests[a];
2627       for (size_t i = start_nest; i < nest->n; i++)
2628         {
2629           if (i == nest->scale_idx)
2630             continue;
2631
2632           const struct variable *var = nest->vars[i];
2633
2634           const struct ctables_category *total = ctables_categories_total (
2635             s->table->categories[var_get_dict_index (var)]);
2636           if (total)
2637             {
2638               const struct ctables_category *save = cats[a][i];
2639               cats[a][i] = total;
2640               ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2641               recurse_totals (s, c, cats, d_weight, e_weight, a, i + 1);
2642               cats[a][i] = save;
2643             }
2644         }
2645       start_nest = 0;
2646     }
2647 }
2648
2649 static void
2650 recurse_subtotals (struct ctables_section *s, const struct ccase *c,
2651                    const struct ctables_category *cats[PIVOT_N_AXES][10],
2652                    double d_weight, double e_weight,
2653                    enum pivot_axis_type start_axis, size_t start_nest)
2654 {
2655   for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2656     {
2657       const struct ctables_nest *nest = s->nests[a];
2658       for (size_t i = start_nest; i < nest->n; i++)
2659         {
2660           if (i == nest->scale_idx)
2661             continue;
2662
2663           const struct ctables_category *save = cats[a][i];
2664           if (save->subtotal)
2665             {
2666               cats[a][i] = save->subtotal;
2667               ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2668               recurse_subtotals (s, c, cats, d_weight, e_weight, a, i + 1);
2669               cats[a][i] = save;
2670             }
2671         }
2672       start_nest = 0;
2673     }
2674 }
2675
2676 static void
2677 ctables_add_occurrence (const struct variable *var,
2678                         const union value *value,
2679                         struct hmap *occurrences)
2680 {
2681   int width = var_get_width (var);
2682   unsigned int hash = value_hash (value, width, 0);
2683
2684   struct ctables_section_value *sv;
2685   HMAP_FOR_EACH_WITH_HASH (sv, struct ctables_section_value, node, hash,
2686                            occurrences)
2687     if (value_equal (value, &sv->value, width))
2688       return;
2689
2690   sv = xmalloc (sizeof *sv);
2691   value_clone (&sv->value, value, width);
2692   hmap_insert (occurrences, &sv->node, hash);
2693 }
2694
2695 static void
2696 ctables_cell_insert (struct ctables_section *s,
2697                      const struct ccase *c,
2698                      double d_weight, double e_weight)
2699 {
2700   const struct ctables_category *cats[PIVOT_N_AXES][10]; /* XXX */
2701   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2702     {
2703       const struct ctables_nest *nest = s->nests[a];
2704       for (size_t i = 0; i < nest->n; i++)
2705         {
2706           if (i == nest->scale_idx)
2707             continue;
2708
2709           const struct variable *var = nest->vars[i];
2710           const union value *value = case_data (c, var);
2711
2712           if (var_is_numeric (var) && value->f == SYSMIS)
2713             return;
2714
2715           cats[a][i] = ctables_categories_match (
2716             s->table->categories[var_get_dict_index (var)], value, var);
2717           if (!cats[a][i])
2718             return;
2719         }
2720     }
2721
2722   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2723     {
2724       const struct ctables_nest *nest = s->nests[a];
2725       for (size_t i = 0; i < nest->n; i++)
2726         if (i != nest->scale_idx)
2727           {
2728             const struct variable *var = nest->vars[i];
2729             const union value *value = case_data (c, var);
2730             ctables_add_occurrence (var, value, &s->occurrences[a][i]);
2731           }
2732     }
2733
2734   ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2735
2736   recurse_totals (s, c, cats, d_weight, e_weight, 0, 0);
2737   recurse_subtotals (s, c, cats, d_weight, e_weight, 0, 0);
2738 }
2739
2740 struct merge_item
2741   {
2742     const struct ctables_summary_spec_set *set;
2743     size_t ofs;
2744   };
2745
2746 static int
2747 merge_item_compare_3way (const struct merge_item *a, const struct merge_item *b)
2748 {
2749   const struct ctables_summary_spec *as = &a->set->specs[a->ofs];
2750   const struct ctables_summary_spec *bs = &b->set->specs[b->ofs];
2751   if (as->function != bs->function)
2752     return as->function > bs->function ? 1 : -1;
2753   else if (as->percentile != bs->percentile)
2754     return as->percentile < bs->percentile ? 1 : -1;
2755   return strcmp (as->label, bs->label);
2756 }
2757
2758 static struct pivot_value *
2759 ctables_category_create_label (const struct ctables_category *cat,
2760                                const struct variable *var,
2761                                const union value *value)
2762 {
2763   return (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL
2764           ? pivot_value_new_user_text (cat->total_label, SIZE_MAX)
2765           : pivot_value_new_var_value (var, value));
2766 }
2767
2768 static struct ctables_value *
2769 ctables_value_find__ (struct ctables_table *t, const union value *value,
2770                       int width, unsigned int hash)
2771 {
2772   struct ctables_value *clv;
2773   HMAP_FOR_EACH_WITH_HASH (clv, struct ctables_value, node,
2774                            hash, &t->clabels_values_map)
2775     if (value_equal (value, &clv->value, width))
2776       return clv;
2777   return NULL;
2778 }
2779
2780 static struct ctables_value *
2781 ctables_value_find (struct ctables_table *t,
2782                     const union value *value, int width)
2783 {
2784   return ctables_value_find__ (t, value, width,
2785                                value_hash (value, width, 0));
2786 }
2787
2788 static void
2789 ctables_table_add_section (struct ctables_table *t, enum pivot_axis_type a,
2790                            size_t ix[PIVOT_N_AXES])
2791 {
2792   if (a < PIVOT_N_AXES)
2793     {
2794       size_t limit = MAX (t->stacks[a].n, 1);
2795       for (ix[a] = 0; ix[a] < limit; ix[a]++)
2796         ctables_table_add_section (t, a + 1, ix);
2797     }
2798   else
2799     {
2800       struct ctables_section *s = &t->sections[t->n_sections++];
2801       *s = (struct ctables_section) {
2802         .table = t,
2803         .cells = HMAP_INITIALIZER (s->cells),
2804       };
2805       for (a = 0; a < PIVOT_N_AXES; a++)
2806         if (t->stacks[a].n)
2807           {
2808             struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2809             s->nests[a] = nest;
2810             s->occurrences[a] = xnmalloc (nest->n, sizeof *s->occurrences[a]);
2811             for (size_t i = 0; i < nest->n; i++)
2812               hmap_init (&s->occurrences[a][i]);
2813         }
2814       for (size_t i = 0; i < N_CTDTS; i++)
2815         hmap_init (&s->domains[i]);
2816     }
2817 }
2818
2819 static void
2820 ctables_table_output (struct ctables *ct, struct ctables_table *t)
2821 {
2822   struct pivot_table *pt = pivot_table_create__ (
2823     (t->title
2824      ? pivot_value_new_user_text (t->title, SIZE_MAX)
2825      : pivot_value_new_text (N_("Custom Tables"))),
2826     "Custom Tables");
2827   if (t->caption)
2828     pivot_table_set_caption (
2829       pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
2830   if (t->corner)
2831     pivot_table_set_caption (
2832       pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
2833
2834   bool summary_dimension = (t->summary_axis != t->slabels_axis
2835                             || (!t->slabels_visible
2836                                 && t->summary_specs.n > 1));
2837   if (summary_dimension)
2838     {
2839       struct pivot_dimension *d = pivot_dimension_create (
2840         pt, t->slabels_axis, N_("Statistics"));
2841       const struct ctables_summary_spec_set *specs = &t->summary_specs;
2842       if (!t->slabels_visible)
2843         d->hide_all_labels = true;
2844       for (size_t i = 0; i < specs->n; i++)
2845         pivot_category_create_leaf (
2846           d->root, pivot_value_new_text (specs->specs[i].label));
2847     }
2848
2849   bool categories_dimension = t->clabels_example != NULL;
2850   if (categories_dimension)
2851     {
2852       struct pivot_dimension *d = pivot_dimension_create (
2853         pt, t->label_axis[t->clabels_from_axis],
2854         t->clabels_from_axis == PIVOT_AXIS_ROW
2855         ? N_("Row Categories")
2856         : N_("Column Categories"));
2857       const struct variable *var = t->clabels_example;
2858       const struct ctables_categories *c = t->categories[var_get_dict_index (var)];
2859       for (size_t i = 0; i < t->n_clabels_values; i++)
2860         {
2861           const struct ctables_value *value = t->clabels_values[i];
2862           const struct ctables_category *cat = ctables_categories_match (c, &value->value, var);
2863           assert (cat != NULL);
2864           pivot_category_create_leaf (d->root, ctables_category_create_label (
2865                                         cat, t->clabels_example, &value->value));
2866         }
2867     }
2868
2869   pivot_table_set_look (pt, ct->look);
2870   struct pivot_dimension *d[PIVOT_N_AXES];
2871   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2872     {
2873       static const char *names[] = {
2874         [PIVOT_AXIS_ROW] = N_("Rows"),
2875         [PIVOT_AXIS_COLUMN] = N_("Columns"),
2876         [PIVOT_AXIS_LAYER] = N_("Layers"),
2877       };
2878       d[a] = (t->axes[a] || a == t->summary_axis
2879               ? pivot_dimension_create (pt, a, names[a])
2880               : NULL);
2881       if (!d[a])
2882         continue;
2883
2884       assert (t->axes[a]);
2885
2886       for (size_t i = 0; i < t->stacks[a].n; i++)
2887         {
2888           struct ctables_nest *nest = &t->stacks[a].nests[i];
2889           struct ctables_section **sections = xnmalloc (t->n_sections,
2890                                                         sizeof *sections);
2891           size_t n_sections = 0;
2892
2893           size_t n_total_cells = 0;
2894           size_t max_depth = 0;
2895           for (size_t j = 0; j < t->n_sections; j++)
2896             if (t->sections[j].nests[a] == nest)
2897               {
2898                 struct ctables_section *s = &t->sections[j];
2899                 sections[n_sections++] = s;
2900                 n_total_cells += s->cells.count;
2901
2902                 size_t depth = s->nests[a]->n;
2903                 max_depth = MAX (depth, max_depth);
2904               }
2905
2906           struct ctables_cell **sorted = xnmalloc (n_total_cells,
2907                                                    sizeof *sorted);
2908           size_t n_sorted = 0;
2909
2910           for (size_t j = 0; j < n_sections; j++)
2911             {
2912               struct ctables_section *s = sections[j];
2913
2914               struct ctables_cell *cell;
2915               HMAP_FOR_EACH (cell, struct ctables_cell, node, &s->cells)
2916                 if (!cell->hide)
2917                   sorted[n_sorted++] = cell;
2918               assert (n_sorted <= n_total_cells);
2919             }
2920
2921           struct ctables_cell_sort_aux aux = { .nest = nest, .a = a };
2922           sort (sorted, n_sorted, sizeof *sorted, ctables_cell_compare_3way, &aux);
2923
2924           struct ctables_level
2925             {
2926               enum ctables_level_type
2927                 {
2928                   CTL_VAR,          /* Variable label for nest->vars[var_idx]. */
2929                   CTL_CATEGORY,     /* Category for nest->vars[var_idx]. */
2930                   CTL_SUMMARY,      /* Summary functions. */
2931                 }
2932                 type;
2933
2934               size_t var_idx;
2935             };
2936           struct ctables_level *levels = xnmalloc (1 + 2 * max_depth, sizeof *levels);
2937           size_t n_levels = 0;
2938           for (size_t k = 0; k < nest->n; k++)
2939             {
2940               enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k])];
2941               if (vlabel != CTVL_NONE)
2942                 {
2943                   levels[n_levels++] = (struct ctables_level) {
2944                     .type = CTL_VAR,
2945                     .var_idx = k,
2946                   };
2947                 }
2948
2949               if (nest->scale_idx != k
2950                   && (k != nest->n - 1 || t->label_axis[a] == a))
2951                 {
2952                   levels[n_levels++] = (struct ctables_level) {
2953                     .type = CTL_CATEGORY,
2954                     .var_idx = k,
2955                   };
2956                 }
2957             }
2958
2959           if (!summary_dimension && a == t->slabels_axis)
2960             {
2961               levels[n_levels++] = (struct ctables_level) {
2962                 .type = CTL_SUMMARY,
2963                 .var_idx = SIZE_MAX,
2964               };
2965             }
2966
2967           /* Pivot categories:
2968
2969              - variable label for nest->vars[0], if vlabel != CTVL_NONE
2970              - category for nest->vars[0], if nest->scale_idx != 0
2971              - variable label for nest->vars[1], if vlabel != CTVL_NONE
2972              - category for nest->vars[1], if nest->scale_idx != 1
2973              ...
2974              - variable label for nest->vars[n - 1], if vlabel != CTVL_NONE
2975              - category for nest->vars[n - 1], if t->label_axis[a] == a && nest->scale_idx != n - 1.
2976              - summary function, if 'a == t->slabels_axis && a ==
2977              t->summary_axis'.
2978
2979              Additional dimensions:
2980
2981              - If 'a == t->slabels_axis && a != t->summary_axis', add a summary
2982              dimension.
2983              - If 't->label_axis[b] == a' for some 'b != a', add a category
2984              dimension to 'a'.
2985           */
2986
2987
2988           struct pivot_category **groups = xnmalloc (1 + 2 * max_depth, sizeof *groups);
2989           int prev_leaf = 0;
2990           for (size_t j = 0; j < n_sorted; j++)
2991             {
2992               struct ctables_cell *cell = sorted[j];
2993               struct ctables_cell *prev = j > 0 ? sorted[j - 1] : NULL;
2994
2995               size_t n_common = 0;
2996               if (j > 0)
2997                 {
2998                   for (; n_common < n_levels; n_common++)
2999                     {
3000                       const struct ctables_level *level = &levels[n_common];
3001                       if (level->type == CTL_CATEGORY)
3002                         {
3003                           size_t var_idx = level->var_idx;
3004                           const struct ctables_category *c = cell->axes[a].cvs[var_idx].category;
3005                           if (prev->axes[a].cvs[var_idx].category != c)
3006                             break;
3007                           else if (c->type != CCT_SUBTOTAL
3008                                    && c->type != CCT_HSUBTOTAL
3009                                    && c->type != CCT_TOTAL
3010                                    && !value_equal (&prev->axes[a].cvs[var_idx].value,
3011                                                     &cell->axes[a].cvs[var_idx].value,
3012                                                     var_get_type (nest->vars[var_idx])))
3013                             break;
3014                         }
3015                     }
3016                 }
3017
3018               for (size_t k = n_common; k < n_levels; k++)
3019                 {
3020                   const struct ctables_level *level = &levels[k];
3021                   struct pivot_category *parent = k ? groups[k - 1] : d[a]->root;
3022                   if (level->type == CTL_SUMMARY)
3023                     {
3024                       assert (k == n_levels - 1);
3025
3026                       const struct ctables_summary_spec_set *specs = &t->summary_specs;
3027                       for (size_t m = 0; m < specs->n; m++)
3028                         {
3029                           int leaf = pivot_category_create_leaf (
3030                             parent, pivot_value_new_text (specs->specs[m].label));
3031                           if (!m)
3032                             prev_leaf = leaf;
3033                         }
3034                     }
3035                   else
3036                     {
3037                       const struct variable *var = nest->vars[level->var_idx];
3038                       struct pivot_value *label;
3039                       if (level->type == CTL_VAR)
3040                         label = pivot_value_new_variable (var);
3041                       else if (level->type == CTL_CATEGORY)
3042                         {
3043                           const struct ctables_cell_value *cv = &cell->axes[a].cvs[level->var_idx];
3044                           label = ctables_category_create_label (cv->category,
3045                                                                  var, &cv->value);
3046                         }
3047                       else
3048                         NOT_REACHED ();
3049
3050                       if (k == n_levels - 1)
3051                         prev_leaf = pivot_category_create_leaf (parent, label);
3052                       else
3053                         groups[k] = pivot_category_create_group__ (parent, label);
3054                     }
3055                 }
3056
3057               cell->axes[a].leaf = prev_leaf;
3058             }
3059           free (sorted);
3060           free (groups);
3061         }
3062     }
3063
3064   for (size_t i = 0; i < t->n_sections; i++)
3065     {
3066       struct ctables_section *s = &t->sections[i];
3067
3068       struct ctables_cell *cell;
3069       HMAP_FOR_EACH (cell, struct ctables_cell, node, &s->cells)
3070         {
3071           if (cell->hide)
3072             continue;
3073
3074           const struct ctables_nest *specs_nest = s->nests[t->summary_axis];
3075           const struct ctables_summary_spec_set *specs = &specs_nest->specs[cell->sv];
3076           for (size_t j = 0; j < specs->n; j++)
3077             {
3078               size_t dindexes[5];
3079               size_t n_dindexes = 0;
3080
3081               if (summary_dimension)
3082                 dindexes[n_dindexes++] = specs->specs[j].axis_idx;
3083
3084               if (categories_dimension)
3085                 {
3086                   const struct ctables_nest *clabels_nest = s->nests[t->clabels_from_axis];
3087                   const struct variable *var = clabels_nest->vars[clabels_nest->n - 1];
3088                   const union value *value = &cell->axes[t->clabels_from_axis].cvs[clabels_nest->n - 1].value;
3089                   const struct ctables_value *ctv = ctables_value_find (t, value, var_get_width (var));
3090                   assert (ctv != NULL);
3091                   dindexes[n_dindexes++] = ctv->leaf;
3092                 }
3093
3094               for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3095                 if (d[a])
3096                   {
3097                     int leaf = cell->axes[a].leaf;
3098                     if (a == t->summary_axis && !summary_dimension)
3099                       leaf += j;
3100                     dindexes[n_dindexes++] = leaf;
3101                   }
3102
3103               double d = ctables_summary_value (cell, &cell->summaries[j], &specs->specs[j]);
3104               struct pivot_value *value = pivot_value_new_number (d);
3105               value->numeric.format = specs->specs[j].format;
3106               pivot_table_put (pt, dindexes, n_dindexes, value);
3107             }
3108         }
3109     }
3110
3111   pivot_table_submit (pt);
3112 }
3113
3114 static bool
3115 ctables_check_label_position (struct ctables_table *t, enum pivot_axis_type a)
3116 {
3117   enum pivot_axis_type label_pos = t->label_axis[a];
3118   if (label_pos == a)
3119     return true;
3120
3121   t->clabels_from_axis = a;
3122
3123   const char *subcommand_name = a == PIVOT_AXIS_ROW ? "ROWLABELS" : "COLLABELS";
3124   const char *pos_name = label_pos == PIVOT_AXIS_LAYER ? "LAYER" : "OPPOSITE";
3125
3126   const struct ctables_stack *stack = &t->stacks[a];
3127   if (!stack->n)
3128     return true;
3129
3130   const struct ctables_nest *n0 = &stack->nests[0];
3131   assert (n0->n > 0);
3132   const struct variable *v0 = n0->vars[n0->n - 1];
3133   struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
3134   t->clabels_example = v0;
3135
3136   for (size_t i = 0; i < c0->n_cats; i++)
3137     if (c0->cats[i].type == CCT_FUNCTION)
3138       {
3139         msg (SE, _("%s=%s is not allowed with sorting based "
3140                    "on a summary function."),
3141              subcommand_name, pos_name);
3142         return false;
3143       }
3144   if (n0->n - 1 == n0->scale_idx)
3145     {
3146       msg (SE, _("%s=%s requires the variables to be moved to be categorical, "
3147                  "but %s is a scale variable."),
3148            subcommand_name, pos_name, var_get_name (v0));
3149       return false;
3150     }
3151
3152   for (size_t i = 1; i < stack->n; i++)
3153     {
3154       const struct ctables_nest *ni = &stack->nests[i];
3155       assert (ni->n > 0);
3156       const struct variable *vi = ni->vars[ni->n - 1];
3157       struct ctables_categories *ci = t->categories[var_get_dict_index (vi)];
3158
3159       if (ni->n - 1 == ni->scale_idx)
3160         {
3161           msg (SE, _("%s=%s requires the variables to be moved to be "
3162                      "categorical, but %s is a scale variable."),
3163                subcommand_name, pos_name, var_get_name (vi));
3164           return false;
3165         }
3166       if (var_get_width (v0) != var_get_width (vi))
3167         {
3168           msg (SE, _("%s=%s requires the variables to be "
3169                      "moved to have the same width, but %s has "
3170                      "width %d and %s has width %d."),
3171                subcommand_name, pos_name,
3172                var_get_name (v0), var_get_width (v0),
3173                var_get_name (vi), var_get_width (vi));
3174           return false;
3175         }
3176       if (!val_labs_equal (var_get_value_labels (v0),
3177                            var_get_value_labels (vi)))
3178         {
3179           msg (SE, _("%s=%s requires the variables to be "
3180                      "moved to have the same value labels, but %s "
3181                      "and %s have different value labels."),
3182                subcommand_name, pos_name,
3183                var_get_name (v0), var_get_name (vi));
3184           return false;
3185         }
3186       if (!ctables_categories_equal (c0, ci))
3187         {
3188           msg (SE, _("%s=%s requires the variables to be "
3189                      "moved to have the same category "
3190                      "specifications, but %s and %s have different "
3191                      "category specifications."),
3192                subcommand_name, pos_name,
3193                var_get_name (v0), var_get_name (vi));
3194           return false;
3195         }
3196     }
3197
3198   return true;
3199 }
3200
3201 static bool
3202 ctables_prepare_table (struct ctables_table *t)
3203 {
3204   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3205     if (t->axes[a])
3206       {
3207         t->stacks[a] = enumerate_fts (a, t->axes[a]);
3208
3209         for (size_t j = 0; j < t->stacks[a].n; j++)
3210           {
3211             struct ctables_nest *nest = &t->stacks[a].nests[j];
3212             for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3213               {
3214                 nest->domains[dt] = xmalloc (nest->n * sizeof *nest->domains[dt]);
3215                 nest->n_domains[dt] = 0;
3216
3217                 for (size_t k = 0; k < nest->n; k++)
3218                   {
3219                     if (k == nest->scale_idx)
3220                       continue;
3221
3222                     switch (dt)
3223                       {
3224                       case CTDT_TABLE:
3225                         continue;
3226
3227                       case CTDT_LAYER:
3228                         if (a != PIVOT_AXIS_LAYER)
3229                           continue;
3230                         break;
3231
3232                       case CTDT_SUBTABLE:
3233                       case CTDT_ROW:
3234                       case CTDT_COL:
3235                         if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
3236                             : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
3237                             : a == PIVOT_AXIS_ROW)
3238                           {
3239                             if (k == nest->n - 1
3240                                 || (nest->scale_idx == nest->n - 1
3241                                     && k == nest->n - 2))
3242                               continue;
3243                           }
3244                         break;
3245
3246                       case CTDT_LAYERROW:
3247                         if (a == PIVOT_AXIS_COLUMN)
3248                           continue;
3249                         break;
3250
3251                       case CTDT_LAYERCOL:
3252                         if (a == PIVOT_AXIS_ROW)
3253                           continue;
3254                         break;
3255                       }
3256
3257                     nest->domains[dt][nest->n_domains[dt]++] = k;
3258                   }
3259               }
3260           }
3261       }
3262     else
3263       {
3264         struct ctables_nest *nest = xmalloc (sizeof *nest);
3265         *nest = (struct ctables_nest) { .n = 0 };
3266         t->stacks[a] = (struct ctables_stack) { .nests = nest, .n = 1 };
3267       }
3268
3269   struct ctables_stack *stack = &t->stacks[t->summary_axis];
3270   for (size_t i = 0; i < stack->n; i++)
3271     {
3272       struct ctables_nest *nest = &stack->nests[i];
3273       if (!nest->specs[CSV_CELL].n)
3274         {
3275           struct ctables_summary_spec_set *specs = &nest->specs[CSV_CELL];
3276           specs->specs = xmalloc (sizeof *specs->specs);
3277           specs->n = 1;
3278
3279           enum ctables_summary_function function
3280             = specs->var ? CTSF_MEAN : CTSF_COUNT;
3281           struct ctables_var var = { .is_mrset = false, .var = specs->var };
3282
3283           *specs->specs = (struct ctables_summary_spec) {
3284             .function = function,
3285             .format = ctables_summary_default_format (function, &var),
3286             .label = ctables_summary_default_label (function, 0),
3287           };
3288           if (!specs->var)
3289             specs->var = nest->vars[0];
3290
3291           ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3292                                           &nest->specs[CSV_CELL]);
3293         }
3294       else if (!nest->specs[CSV_TOTAL].n)
3295         ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3296                                         &nest->specs[CSV_CELL]);
3297     }
3298
3299   struct ctables_summary_spec_set *merged = &t->summary_specs;
3300   struct merge_item *items = xnmalloc (2 * stack->n, sizeof *items);
3301   size_t n_left = 0;
3302   for (size_t j = 0; j < stack->n; j++)
3303     {
3304       const struct ctables_nest *nest = &stack->nests[j];
3305       if (nest->n)
3306         for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3307           items[n_left++] = (struct merge_item) { .set = &nest->specs[sv] };
3308     }
3309
3310   while (n_left > 0)
3311     {
3312       struct merge_item min = items[0];
3313       for (size_t j = 1; j < n_left; j++)
3314         if (merge_item_compare_3way (&items[j], &min) < 0)
3315           min = items[j];
3316
3317       if (merged->n >= merged->allocated)
3318         merged->specs = x2nrealloc (merged->specs, &merged->allocated,
3319                                     sizeof *merged->specs);
3320       merged->specs[merged->n++] = min.set->specs[min.ofs];
3321
3322       for (size_t j = 0; j < n_left; )
3323         {
3324           if (merge_item_compare_3way (&items[j], &min) == 0)
3325             {
3326               struct merge_item *item = &items[j];
3327               item->set->specs[item->ofs].axis_idx = merged->n - 1;
3328               if (++item->ofs >= item->set->n)
3329                 {
3330                   items[j] = items[--n_left];
3331                   continue;
3332                 }
3333             }
3334           j++;
3335         }
3336     }
3337
3338 #if 0
3339   for (size_t j = 0; j < merged->n; j++)
3340     printf ("%s\n", ctables_summary_function_name (merged->specs[j].function));
3341
3342   for (size_t j = 0; j < stack->n; j++)
3343     {
3344       const struct ctables_nest *nest = &stack->nests[j];
3345       for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3346         {
3347           const struct ctables_summary_spec_set *specs = &nest->specs[sv];
3348           for (size_t k = 0; k < specs->n; k++)
3349             printf ("(%s, %zu) ", ctables_summary_function_name (specs->specs[k].function),
3350                     specs->specs[k].axis_idx);
3351           printf ("\n");
3352         }
3353     }
3354 #endif
3355
3356   return (ctables_check_label_position (t, PIVOT_AXIS_ROW)
3357           && ctables_check_label_position (t, PIVOT_AXIS_COLUMN));
3358 }
3359
3360 static void
3361 ctables_insert_clabels_values (struct ctables_table *t, const struct ccase *c,
3362                                enum pivot_axis_type a)
3363 {
3364   struct ctables_stack *stack = &t->stacks[a];
3365   for (size_t i = 0; i < stack->n; i++)
3366     {
3367       const struct ctables_nest *nest = &stack->nests[i];
3368       const struct variable *var = nest->vars[nest->n - 1];
3369       int width = var_get_width (var);
3370       const union value *value = case_data (c, var);
3371
3372       if (var_is_numeric (var) && value->f == SYSMIS)
3373         continue;
3374
3375       if (!ctables_categories_match (t->categories [var_get_dict_index (var)],
3376                                      value, var))
3377         continue;
3378
3379       unsigned int hash = value_hash (value, width, 0);
3380
3381       struct ctables_value *clv = ctables_value_find__ (t, value, width, hash);
3382       if (!clv)
3383         {
3384           clv = xmalloc (sizeof *clv);
3385           value_clone (&clv->value, value, width);
3386           hmap_insert (&t->clabels_values_map, &clv->node, hash);
3387         }
3388     }
3389 }
3390
3391 static int
3392 compare_clabels_values_3way (const void *a_, const void *b_, const void *width_)
3393 {
3394   const struct ctables_value *const *ap = a_;
3395   const struct ctables_value *const *bp = b_;
3396   const struct ctables_value *a = *ap;
3397   const struct ctables_value *b = *bp;
3398   const int *width = width_;
3399   return value_compare_3way (&a->value, &b->value, *width);
3400 }
3401
3402 static void
3403 ctables_sort_clabels_values (struct ctables_table *t)
3404 {
3405   int width = var_get_width (t->clabels_example);
3406
3407   size_t n = hmap_count (&t->clabels_values_map);
3408   t->clabels_values = xnmalloc (n, sizeof *t->clabels_values);
3409
3410   struct ctables_value *clv;
3411   size_t i = 0;
3412   HMAP_FOR_EACH (clv, struct ctables_value, node, &t->clabels_values_map)
3413     t->clabels_values[i++] = clv;
3414   t->n_clabels_values = n;
3415   assert (i == n);
3416
3417   sort (t->clabels_values, n, sizeof *t->clabels_values,
3418         compare_clabels_values_3way, &width);
3419
3420   for (size_t i = 0; i < n; i++)
3421     t->clabels_values[i]->leaf = i;
3422 }
3423
3424 static void
3425 ctables_add_category_occurrences (const struct variable *var,
3426                                   struct hmap *occurrences,
3427                                   const struct ctables_categories *cats)
3428 {
3429   const struct val_labs *val_labs = var_get_value_labels (var);
3430
3431   for (size_t i = 0; i < cats->n_cats; i++)
3432     {
3433       const struct ctables_category *c = &cats->cats[i];
3434       switch (c->type)
3435         {
3436         case CCT_NUMBER:
3437           ctables_add_occurrence (var, &(const union value) { .f = c->number },
3438                                   occurrences);
3439           break;
3440
3441         case CCT_STRING:
3442           abort ();             /* XXX */
3443
3444         case CCT_RANGE:
3445           assert (var_is_numeric (var));
3446           for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3447                vl = val_labs_next (val_labs, vl))
3448             if (vl->value.f >= c->range[0] && vl->value.f <= c->range[1])
3449               ctables_add_occurrence (var, &vl->value, occurrences);
3450           break;
3451
3452         case CCT_MISSING:
3453           for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3454                vl = val_labs_next (val_labs, vl))
3455             if (var_is_value_missing (var, &vl->value))
3456               ctables_add_occurrence (var, &vl->value, occurrences);
3457           break;
3458
3459         case CCT_OTHERNM:
3460           for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3461                vl = val_labs_next (val_labs, vl))
3462             ctables_add_occurrence (var, &vl->value, occurrences);
3463           break;
3464
3465         case CCT_SUBTOTAL:
3466         case CCT_HSUBTOTAL:
3467         case CCT_TOTAL:
3468           break;
3469
3470         case CCT_VALUE:
3471         case CCT_LABEL:
3472         case CCT_FUNCTION:
3473           for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3474                vl = val_labs_next (val_labs, vl))
3475             if (c->include_missing || !var_is_value_missing (var, &vl->value))
3476               ctables_add_occurrence (var, &vl->value, occurrences);
3477           break;
3478         }
3479     }
3480 }
3481
3482 static void
3483 ctables_section_recurse_add_empty_categories (
3484   struct ctables_section *s,
3485   const struct ctables_category *cats[PIVOT_N_AXES][10], struct ccase *c,
3486   enum pivot_axis_type a, size_t a_idx)
3487 {
3488   if (a >= PIVOT_N_AXES)
3489     ctables_cell_insert__ (s, c, cats);
3490   else if (!s->nests[a] || a_idx >= s->nests[a]->n)
3491     ctables_section_recurse_add_empty_categories (s, cats, c, a + 1, 0);
3492   else
3493     {
3494       const struct variable *var = s->nests[a]->vars[a_idx];
3495       int width = var_get_width (var);
3496       const struct hmap *occurrences = &s->occurrences[a][a_idx];
3497       const struct ctables_section_value *sv;
3498       HMAP_FOR_EACH (sv, struct ctables_section_value, node, occurrences)
3499         {
3500           union value *value = case_data_rw (c, var);
3501           value_destroy (value, width);
3502           value_clone (value, &sv->value, width);
3503           cats[a][a_idx] = ctables_categories_match (
3504             s->table->categories[var_get_dict_index (var)], value, var);
3505           assert (cats[a][a_idx] != NULL);
3506           ctables_section_recurse_add_empty_categories (s, cats, c, a, a_idx + 1);
3507         }
3508     }
3509 }
3510
3511 static void
3512 ctables_section_add_empty_categories (struct ctables_section *s)
3513 {
3514   bool show_empty = false;
3515   for (size_t a = 0; a < PIVOT_N_AXES; a++)
3516     if (s->nests[a])
3517       for (size_t k = 0; k < s->nests[a]->n; k++)
3518         if (k != s->nests[a]->scale_idx)
3519           {
3520             const struct variable *var = s->nests[a]->vars[k];
3521             const struct ctables_categories *cats = s->table->categories[
3522               var_get_dict_index (var)];
3523             if (cats->show_empty)
3524               {
3525                 show_empty = true;
3526                 ctables_add_category_occurrences (var, &s->occurrences[a][k], cats);
3527               }
3528           }
3529   if (!show_empty)
3530     return;
3531
3532   const struct ctables_category *cats[PIVOT_N_AXES][10]; /* XXX */
3533   struct ccase *c = case_create (dict_get_proto (s->table->ctables->dict));
3534   ctables_section_recurse_add_empty_categories (s, cats, c, 0, 0);
3535   case_unref (c);
3536 }
3537
3538 static bool
3539 ctables_execute (struct dataset *ds, struct ctables *ct)
3540 {
3541   for (size_t i = 0; i < ct->n_tables; i++)
3542     {
3543       struct ctables_table *t = ct->tables[i];
3544       t->sections = xnmalloc (MAX (1, t->stacks[PIVOT_AXIS_ROW].n) *
3545                               MAX (1, t->stacks[PIVOT_AXIS_COLUMN].n) *
3546                               MAX (1, t->stacks[PIVOT_AXIS_LAYER].n),
3547                               sizeof *t->sections);
3548       size_t ix[PIVOT_N_AXES];
3549       ctables_table_add_section (t, 0, ix);
3550     }
3551
3552   struct casereader *input = proc_open (ds);
3553   bool warn_on_invalid = true;
3554   for (struct ccase *c = casereader_read (input); c;
3555        case_unref (c), c = casereader_read (input))
3556     {
3557       double d_weight = dict_get_case_weight (dataset_dict (ds), c,
3558                                               &warn_on_invalid);
3559       double e_weight = (ct->e_weight
3560                          ? var_force_valid_weight (ct->e_weight,
3561                                                    case_num (c, ct->e_weight),
3562                                                    &warn_on_invalid)
3563                          : d_weight);
3564
3565       for (size_t i = 0; i < ct->n_tables; i++)
3566         {
3567           struct ctables_table *t = ct->tables[i];
3568
3569           for (size_t j = 0; j < t->n_sections; j++)
3570             ctables_cell_insert (&t->sections[j], c, d_weight, e_weight);
3571
3572           for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3573             if (t->label_axis[a] != a)
3574               ctables_insert_clabels_values (t, c, a);
3575         }
3576     }
3577   casereader_destroy (input);
3578
3579   for (size_t i = 0; i < ct->n_tables; i++)
3580     {
3581       struct ctables_table *t = ct->tables[i];
3582
3583       if (t->clabels_example)
3584         ctables_sort_clabels_values (t);
3585
3586       for (size_t j = 0; j < t->n_sections; j++)
3587         ctables_section_add_empty_categories (&t->sections[j]);
3588
3589       ctables_table_output (ct, ct->tables[i]);
3590     }
3591   return proc_commit (ds);
3592 }
3593 \f
3594 /* Postcomputes. */
3595
3596 typedef struct ctables_pcexpr *parse_recursively_func (struct lexer *);
3597
3598 static void
3599 ctables_pcexpr_destroy (struct ctables_pcexpr *e)
3600 {
3601   if (e)
3602     {
3603       switch (e->op)
3604         {
3605         case CTPO_CAT_STRING:
3606           free (e->string);
3607           break;
3608
3609         case CTPO_ADD:
3610         case CTPO_SUB:
3611         case CTPO_MUL:
3612         case CTPO_DIV:
3613         case CTPO_POW:
3614         case CTPO_NEG:
3615           for (size_t i = 0; i < 2; i++)
3616             ctables_pcexpr_destroy (e->subs[i]);
3617           break;
3618
3619         case CTPO_CONSTANT:
3620         case CTPO_CAT_NUMBER:
3621         case CTPO_CAT_RANGE:
3622         case CTPO_CAT_MISSING:
3623         case CTPO_CAT_OTHERNM:
3624         case CTPO_CAT_SUBTOTAL:
3625         case CTPO_CAT_TOTAL:
3626           break;
3627         }
3628
3629       msg_location_destroy (e->location);
3630       free (e);
3631     }
3632 }
3633
3634 static struct ctables_pcexpr *
3635 ctables_pcexpr_allocate_binary (enum ctables_postcompute_op op,
3636                                 struct ctables_pcexpr *sub0,
3637                                 struct ctables_pcexpr *sub1)
3638 {
3639   struct ctables_pcexpr *e = xmalloc (sizeof *e);
3640   *e = (struct ctables_pcexpr) {
3641     .op = op,
3642     .subs = { sub0, sub1 },
3643     .ofs = { sub0->ofs[0], sub1->ofs[1] }
3644   };
3645   return e;
3646 }
3647
3648 static struct msg_location *
3649 ctables_pcexpr_location (struct lexer *lexer, const struct ctables_pcexpr *e_)
3650 {
3651   if (!e_->location)
3652     {
3653       struct ctables_pcexpr *e = CONST_CAST (struct ctables_pcexpr *, e_);
3654       e->location = lex_ofs_location (lexer, e->ofs[0], e->ofs[1]);
3655     }
3656   return e_->location;
3657 }
3658
3659 /* How to parse an operator. */
3660 struct operator
3661   {
3662     enum token_type token;
3663     enum ctables_postcompute_op op;
3664   };
3665
3666 static const struct operator *
3667 match_operator (struct lexer *lexer, const struct operator ops[], size_t n_ops)
3668 {
3669   for (const struct operator *op = ops; op < ops + n_ops; op++)
3670     if (lex_token (lexer) == op->token)
3671       {
3672         if (op->token != T_NEG_NUM)
3673           lex_get (lexer);
3674
3675         return op;
3676       }
3677
3678   return NULL;
3679 }
3680
3681 static struct ctables_pcexpr *
3682 parse_binary_operators__ (struct lexer *lexer,
3683                           const struct operator ops[], size_t n_ops,
3684                           parse_recursively_func *parse_next_level,
3685                           const char *chain_warning,
3686                           struct ctables_pcexpr *lhs)
3687 {
3688   for (int op_count = 0; ; op_count++)
3689     {
3690       const struct operator *op = match_operator (lexer, ops, n_ops);
3691       if (!op)
3692         {
3693           if (op_count > 1 && chain_warning)
3694             msg_at (SW, ctables_pcexpr_location (lexer, lhs),
3695                     "%s", chain_warning);
3696
3697           return lhs;
3698         }
3699
3700       struct ctables_pcexpr *rhs = parse_next_level (lexer);
3701       if (!rhs)
3702         {
3703           ctables_pcexpr_destroy (lhs);
3704           return NULL;
3705         }
3706
3707       lhs = ctables_pcexpr_allocate_binary (op->op, lhs, rhs);
3708     }
3709 }
3710
3711 static struct ctables_pcexpr *
3712 parse_binary_operators (struct lexer *lexer,
3713                         const struct operator ops[], size_t n_ops,
3714                         parse_recursively_func *parse_next_level,
3715                         const char *chain_warning)
3716 {
3717   struct ctables_pcexpr *lhs = parse_next_level (lexer);
3718   if (!lhs)
3719     return NULL;
3720
3721   return parse_binary_operators__ (lexer, ops, n_ops, parse_next_level,
3722                                    chain_warning, lhs);
3723 }
3724
3725 static struct ctables_pcexpr *parse_add (struct lexer *);
3726
3727 static struct ctables_pcexpr
3728 ctpo_cat_range (double low, double high)
3729 {
3730   return (struct ctables_pcexpr) {
3731     .op = CTPO_CAT_RANGE,
3732     .range = { low, high },
3733   };
3734 }
3735
3736 static struct ctables_pcexpr *
3737 parse_primary (struct lexer *lexer)
3738 {
3739   int start_ofs = lex_ofs (lexer);
3740   struct ctables_pcexpr e;
3741   if (lex_is_number (lexer))
3742     {
3743       e = (struct ctables_pcexpr) { .op = CTPO_CONSTANT,
3744                                     .number = lex_number (lexer) };
3745       lex_get (lexer);
3746     }
3747   else if (lex_match_id (lexer, "MISSING"))
3748     e = (struct ctables_pcexpr) { .op = CTPO_CAT_MISSING };
3749   else if (lex_match_id (lexer, "OTHERNM"))
3750     e = (struct ctables_pcexpr) { .op = CTPO_CAT_OTHERNM };
3751   else if (lex_match_id (lexer, "TOTAL"))
3752     e = (struct ctables_pcexpr) { .op = CTPO_CAT_TOTAL };
3753   else if (lex_match_id (lexer, "SUBTOTAL"))
3754     {
3755       size_t subtotal_index = 0;
3756       if (lex_match (lexer, T_LBRACK))
3757         {
3758           if (!lex_force_int_range (lexer, "SUBTOTAL", 1, LONG_MAX))
3759             return NULL;
3760           subtotal_index = lex_integer (lexer);
3761           lex_get (lexer);
3762           if (!lex_force_match (lexer, T_RBRACK))
3763             return NULL;
3764         }
3765       e = (struct ctables_pcexpr) { .op = CTPO_CAT_SUBTOTAL,
3766                                     .subtotal_index = subtotal_index };
3767     }
3768   else if (lex_match (lexer, T_LBRACK))
3769     {
3770       if (lex_match_id (lexer, "LO"))
3771         {
3772           if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
3773             return false;
3774           e = ctpo_cat_range (-DBL_MAX, lex_number (lexer));
3775           lex_get (lexer);
3776         }
3777       else if (lex_is_number (lexer))
3778         {
3779           double number = lex_number (lexer);
3780           lex_get (lexer);
3781           if (lex_match_id (lexer, "THRU"))
3782             {
3783               if (lex_match_id (lexer, "HI"))
3784                 e = ctpo_cat_range (number, DBL_MAX);
3785               else
3786                 {
3787                   if (!lex_force_num (lexer))
3788                     return false;
3789                   e = ctpo_cat_range (number, lex_number (lexer));
3790                   lex_get (lexer);
3791                 }
3792             }
3793           else
3794             e = (struct ctables_pcexpr) { .op = CTPO_CAT_NUMBER,
3795                                           .number = number };
3796         }
3797       else if (lex_is_string (lexer))
3798         {
3799           e = (struct ctables_pcexpr) {
3800             .op = CTPO_CAT_STRING,
3801             .string = ss_xstrdup (lex_tokss (lexer)),
3802           };
3803           lex_get (lexer);
3804         }
3805       else
3806         {
3807           lex_error (lexer, NULL);
3808           return NULL;
3809         }
3810
3811       if (!lex_force_match (lexer, T_RBRACK))
3812         {
3813           if (e.op == CTPO_CAT_STRING)
3814             free (e.string);
3815           return NULL;
3816         }
3817     }
3818   else if (lex_match (lexer, T_LPAREN))
3819     {
3820       struct ctables_pcexpr *ep = parse_add (lexer);
3821       if (!ep)
3822         return NULL;
3823       if (!lex_force_match (lexer, T_RPAREN))
3824         {
3825           ctables_pcexpr_destroy (ep);
3826           return NULL;
3827         }
3828       return ep;
3829     }
3830   else
3831     {
3832       lex_error (lexer, NULL);
3833       return NULL;
3834     }
3835
3836   e.ofs[0] = start_ofs;
3837   e.ofs[1] = lex_ofs (lexer) - 1;
3838   return xmemdup (&e, sizeof e);
3839 }
3840
3841 static struct ctables_pcexpr *
3842 ctables_pcexpr_allocate_neg (struct ctables_pcexpr *sub,
3843                              struct lexer *lexer, int start_ofs)
3844 {
3845   struct ctables_pcexpr *e = xmalloc (sizeof *e);
3846   *e = (struct ctables_pcexpr) {
3847     .op = CTPO_NEG,
3848     .subs = { sub },
3849     .ofs = { start_ofs, lex_ofs (lexer) - 1 },
3850   };
3851   return e;
3852 }
3853
3854 static struct ctables_pcexpr *
3855 parse_exp (struct lexer *lexer)
3856 {
3857   static const struct operator op = { T_EXP, CTPO_POW };
3858
3859   const char *chain_warning =
3860     _("The exponentiation operator (`**') is left-associative: "
3861       "`a**b**c' equals `(a**b)**c', not `a**(b**c)'.  "
3862       "To disable this warning, insert parentheses.");
3863
3864   if (lex_token (lexer) != T_NEG_NUM || lex_next_token (lexer, 1) != T_EXP)
3865     return parse_binary_operators (lexer, &op, 1,
3866                                    parse_primary, chain_warning);
3867
3868   /* Special case for situations like "-5**6", which must be parsed as
3869      -(5**6). */
3870
3871   int start_ofs = lex_ofs (lexer);
3872   struct ctables_pcexpr *lhs = xmalloc (sizeof *lhs);
3873   *lhs = (struct ctables_pcexpr) {
3874     .op = CTPO_CONSTANT,
3875     .number = -lex_tokval (lexer),
3876     .ofs = { start_ofs, lex_ofs (lexer) },
3877   };
3878   lex_get (lexer);
3879
3880   struct ctables_pcexpr *node = parse_binary_operators__ (
3881     lexer, &op, 1, parse_primary, chain_warning, lhs);
3882   if (!node)
3883     return NULL;
3884
3885   return ctables_pcexpr_allocate_neg (node, lexer, start_ofs);
3886 }
3887
3888 /* Parses the unary minus level. */
3889 static struct ctables_pcexpr *
3890 parse_neg (struct lexer *lexer)
3891 {
3892   int start_ofs = lex_ofs (lexer);
3893   if (!lex_match (lexer, T_DASH))
3894     return parse_exp (lexer);
3895
3896   struct ctables_pcexpr *inner = parse_neg (lexer);
3897   if (!inner)
3898     return NULL;
3899
3900   return ctables_pcexpr_allocate_neg (inner, lexer, start_ofs);
3901 }
3902
3903 /* Parses the multiplication and division level. */
3904 static struct ctables_pcexpr *
3905 parse_mul (struct lexer *lexer)
3906 {
3907   static const struct operator ops[] =
3908     {
3909       { T_ASTERISK, CTPO_MUL },
3910       { T_SLASH, CTPO_DIV },
3911     };
3912
3913   return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
3914                                  parse_neg, NULL);
3915 }
3916
3917 /* Parses the addition and subtraction level. */
3918 static struct ctables_pcexpr *
3919 parse_add (struct lexer *lexer)
3920 {
3921   static const struct operator ops[] =
3922     {
3923       { T_PLUS, CTPO_ADD },
3924       { T_DASH, CTPO_SUB },
3925       { T_NEG_NUM, CTPO_ADD },
3926     };
3927
3928   return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
3929                                  parse_mul, NULL);
3930 }
3931
3932 static struct ctables_postcompute *
3933 ctables_find_postcompute (struct ctables *ct, const char *name)
3934 {
3935   struct ctables_postcompute *pc;
3936   HMAP_FOR_EACH_WITH_HASH (pc, struct ctables_postcompute, hmap_node,
3937                            utf8_hash_case_string (name, 0), &ct->postcomputes)
3938     if (!utf8_strcasecmp (pc->name, name))
3939       return pc;
3940   return NULL;
3941 }
3942
3943 static bool
3944 ctables_parse_pcompute (struct lexer *lexer, struct ctables *ct)
3945 {
3946   int start_ofs = lex_ofs (lexer) - 1;
3947
3948   if (!lex_force_match (lexer, T_AND) || !lex_force_id (lexer))
3949     return false;
3950
3951   char *name = ss_xstrdup (lex_tokss (lexer));
3952
3953   lex_get (lexer);
3954   if (!lex_force_match (lexer, T_EQUALS)
3955       || !lex_force_match_id (lexer, "EXPR")
3956       || !lex_force_match (lexer, T_LPAREN))
3957     {
3958       free (name);
3959       return false;
3960     }
3961
3962   struct ctables_pcexpr *expr = parse_add (lexer);
3963   if (!expr || !lex_force_match (lexer, T_RPAREN))
3964     {
3965       free (name);
3966       return false;
3967     }
3968
3969   struct msg_location *location = lex_ofs_location (lexer, start_ofs,
3970                                                     lex_ofs (lexer) - 1);
3971
3972   struct ctables_postcompute *pc = ctables_find_postcompute (ct, name);
3973   if (pc)
3974     {
3975       msg_at (SW, location, _("New definition of &%s will override the "
3976                               "previous definition."),
3977               pc->name);
3978       msg_at (SN, pc->location, _("This is the previous definition."));
3979
3980       ctables_pcexpr_destroy (pc->expr);
3981       msg_location_destroy (pc->location);
3982       free (name);
3983     }
3984   else
3985     {
3986       pc = xmalloc (sizeof *pc);
3987       *pc = (struct ctables_postcompute) { .name = name };
3988       hmap_insert (&ct->postcomputes, &pc->hmap_node,
3989                    utf8_hash_case_string (pc->name, 0));
3990     }
3991   pc->expr = expr;
3992   pc->location = location;
3993   return true;
3994 }
3995
3996 static bool
3997 ctables_parse_pproperties_format (struct lexer *lexer,
3998                                   struct ctables_summary_spec_set *sss)
3999 {
4000   *sss = (struct ctables_summary_spec_set) { .n = 0 };
4001
4002   while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH
4003          && !(lex_token (lexer) == T_ID
4004               && (lex_id_match (ss_cstr ("LABEL"), lex_tokss (lexer))
4005                   || lex_id_match (ss_cstr ("HIDESOURCECATS"),
4006                                    lex_tokss (lexer)))))
4007     {
4008       /* Parse function. */
4009       enum ctables_summary_function function;
4010       if (!parse_ctables_summary_function (lexer, &function))
4011         goto error;
4012
4013       /* Parse percentile. */
4014       double percentile = 0;
4015       if (function == CTSF_PTILE)
4016         {
4017           if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
4018             goto error;
4019           percentile = lex_number (lexer);
4020           lex_get (lexer);
4021         }
4022
4023       /* Parse format. */
4024       struct fmt_spec format;
4025       if (!parse_format_specifier (lexer, &format)
4026           || !fmt_check_output (&format)
4027           || !fmt_check_type_compat (&format, VAL_NUMERIC))
4028         goto error;
4029
4030       if (sss->n >= sss->allocated)
4031         sss->specs = x2nrealloc (sss->specs, &sss->allocated,
4032                                  sizeof *sss->specs);
4033       sss->specs[sss->n++] = (struct ctables_summary_spec) {
4034         .function = function,
4035         .percentile = percentile,
4036         .format = format,
4037       };
4038     }
4039   return true;
4040
4041 error:
4042   ctables_summary_spec_set_uninit (sss);
4043   return false;
4044 }
4045
4046 static bool
4047 ctables_parse_pproperties (struct lexer *lexer, struct ctables *ct)
4048 {
4049   struct ctables_postcompute **pcs = NULL;
4050   size_t n_pcs = 0;
4051   size_t allocated_pcs = 0;
4052
4053   while (lex_match (lexer, T_AND))
4054     {
4055       if (!lex_force_id (lexer))
4056         goto error;
4057       struct ctables_postcompute *pc
4058         = ctables_find_postcompute (ct, lex_tokcstr (lexer));
4059       if (!pc)
4060         {
4061           msg (SE, _("Unknown computed category &%s."), lex_tokcstr (lexer));
4062           goto error;
4063         }
4064
4065       if (n_pcs >= allocated_pcs)
4066         pcs = x2nrealloc (pcs, &allocated_pcs, sizeof *pcs);
4067       pcs[n_pcs++] = pc;
4068     }
4069
4070   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4071     {
4072       if (lex_match_id (lexer, "LABEL"))
4073         {
4074           lex_match (lexer, T_EQUALS);
4075           if (!lex_force_string (lexer))
4076             goto error;
4077
4078           for (size_t i = 0; i < n_pcs; i++)
4079             {
4080               free (pcs[i]->label);
4081               pcs[i]->label = ss_xstrdup (lex_tokss (lexer));
4082             }
4083
4084           lex_get (lexer);
4085         }
4086       else if (lex_match_id (lexer, "FORMAT"))
4087         {
4088           lex_match (lexer, T_EQUALS);
4089
4090           struct ctables_summary_spec_set sss;
4091           if (!ctables_parse_pproperties_format (lexer, &sss))
4092             goto error;
4093
4094           for (size_t i = 0; i < n_pcs; i++)
4095             {
4096               if (pcs[i]->specs)
4097                 ctables_summary_spec_set_uninit (pcs[i]->specs);
4098               else
4099                 pcs[i]->specs = xmalloc (sizeof *pcs[i]->specs);
4100               ctables_summary_spec_set_clone (pcs[i]->specs, &sss);
4101             }
4102           ctables_summary_spec_set_uninit (&sss);
4103         }
4104       else if (lex_match_id (lexer, "HIDESOURCECATS"))
4105         {
4106           lex_match (lexer, T_EQUALS);
4107           bool hide_source_cats;
4108           if (!parse_bool (lexer, &hide_source_cats))
4109             goto error;
4110           for (size_t i = 0; i < n_pcs; i++)
4111             pcs[i]->hide_source_cats = hide_source_cats;
4112         }
4113       else
4114         {
4115           lex_error_expecting (lexer, "LABEL", "FORMAT", "HIDESOURCECATS");
4116           goto error;
4117         }
4118     }
4119   free (pcs);
4120   return true;
4121
4122 error:
4123   free (pcs);
4124   return false;
4125 }
4126
4127 int
4128 cmd_ctables (struct lexer *lexer, struct dataset *ds)
4129 {
4130   size_t n_vars = dict_get_n_vars (dataset_dict (ds));
4131   enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
4132   enum settings_value_show tvars = settings_get_show_variables ();
4133   for (size_t i = 0; i < n_vars; i++)
4134     vlabels[i] = (enum ctables_vlabel) tvars;
4135
4136   struct ctables *ct = xmalloc (sizeof *ct);
4137   *ct = (struct ctables) {
4138     .dict = dataset_dict (ds),
4139     .look = pivot_table_look_unshare (pivot_table_look_ref (
4140                                         pivot_table_look_get_default ())),
4141     .vlabels = vlabels,
4142     .hide_threshold = 5,
4143   };
4144   ct->look->omit_empty = false;
4145
4146   if (!lex_force_match (lexer, T_SLASH))
4147     goto error;
4148
4149   while (!lex_match_id (lexer, "TABLE"))
4150     {
4151       if (lex_match_id (lexer, "FORMAT"))
4152         {
4153           double widths[2] = { SYSMIS, SYSMIS };
4154           double units_per_inch = 72.0;
4155
4156           while (lex_token (lexer) != T_SLASH)
4157             {
4158               if (lex_match_id (lexer, "MINCOLWIDTH"))
4159                 {
4160                   if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
4161                     goto error;
4162                 }
4163               else if (lex_match_id (lexer, "MAXCOLWIDTH"))
4164                 {
4165                   if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
4166                     goto error;
4167                 }
4168               else if (lex_match_id (lexer, "UNITS"))
4169                 {
4170                   lex_match (lexer, T_EQUALS);
4171                   if (lex_match_id (lexer, "POINTS"))
4172                     units_per_inch = 72.0;
4173                   else if (lex_match_id (lexer, "INCHES"))
4174                     units_per_inch = 1.0;
4175                   else if (lex_match_id (lexer, "CM"))
4176                     units_per_inch = 2.54;
4177                   else
4178                     {
4179                       lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
4180                       goto error;
4181                     }
4182                 }
4183               else if (lex_match_id (lexer, "EMPTY"))
4184                 {
4185                   free (ct->zero);
4186                   ct->zero = NULL;
4187
4188                   lex_match (lexer, T_EQUALS);
4189                   if (lex_match_id (lexer, "ZERO"))
4190                     {
4191                       /* Nothing to do. */
4192                     }
4193                   else if (lex_match_id (lexer, "BLANK"))
4194                     ct->zero = xstrdup ("");
4195                   else if (lex_force_string (lexer))
4196                     {
4197                       ct->zero = ss_xstrdup (lex_tokss (lexer));
4198                       lex_get (lexer);
4199                     }
4200                   else
4201                     goto error;
4202                 }
4203               else if (lex_match_id (lexer, "MISSING"))
4204                 {
4205                   lex_match (lexer, T_EQUALS);
4206                   if (!lex_force_string (lexer))
4207                     goto error;
4208
4209                   free (ct->missing);
4210                   ct->missing = (strcmp (lex_tokcstr (lexer), ".")
4211                                  ? ss_xstrdup (lex_tokss (lexer))
4212                                  : NULL);
4213                   lex_get (lexer);
4214                 }
4215               else
4216                 {
4217                   lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
4218                                        "UNITS", "EMPTY", "MISSING");
4219                   goto error;
4220                 }
4221             }
4222
4223           if (widths[0] != SYSMIS && widths[1] != SYSMIS
4224               && widths[0] > widths[1])
4225             {
4226               msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
4227               goto error;
4228             }
4229
4230           for (size_t i = 0; i < 2; i++)
4231             if (widths[i] != SYSMIS)
4232               {
4233                 int *wr = ct->look->width_ranges[TABLE_HORZ];
4234                 wr[i] = widths[i] / units_per_inch * 96.0;
4235                 if (wr[0] > wr[1])
4236                   wr[!i] = wr[i];
4237               }
4238         }
4239       else if (lex_match_id (lexer, "VLABELS"))
4240         {
4241           if (!lex_force_match_id (lexer, "VARIABLES"))
4242             goto error;
4243           lex_match (lexer, T_EQUALS);
4244
4245           struct variable **vars;
4246           size_t n_vars;
4247           if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
4248                                 PV_NO_SCRATCH))
4249             goto error;
4250
4251           if (!lex_force_match_id (lexer, "DISPLAY"))
4252             {
4253               free (vars);
4254               goto error;
4255             }
4256           lex_match (lexer, T_EQUALS);
4257
4258           enum ctables_vlabel vlabel;
4259           if (lex_match_id (lexer, "DEFAULT"))
4260             vlabel = (enum ctables_vlabel) settings_get_show_variables ();
4261           else if (lex_match_id (lexer, "NAME"))
4262             vlabel = CTVL_NAME;
4263           else if (lex_match_id (lexer, "LABEL"))
4264             vlabel = CTVL_LABEL;
4265           else if (lex_match_id (lexer, "BOTH"))
4266             vlabel = CTVL_BOTH;
4267           else if (lex_match_id (lexer, "NONE"))
4268             vlabel = CTVL_NONE;
4269           else
4270             {
4271               lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
4272                                    "BOTH", "NONE");
4273               free (vars);
4274               goto error;
4275             }
4276
4277           for (size_t i = 0; i < n_vars; i++)
4278             ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
4279           free (vars);
4280         }
4281       else if (lex_match_id (lexer, "MRSETS"))
4282         {
4283           if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
4284             goto error;
4285           lex_match (lexer, T_EQUALS);
4286           if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
4287             goto error;
4288         }
4289       else if (lex_match_id (lexer, "SMISSING"))
4290         {
4291           if (lex_match_id (lexer, "VARIABLE"))
4292             ct->smissing_listwise = false;
4293           else if (lex_match_id (lexer, "LISTWISE"))
4294             ct->smissing_listwise = true;
4295           else
4296             {
4297               lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
4298               goto error;
4299             }
4300         }
4301       else if (lex_match_id (lexer, "PCOMPUTE"))
4302         {
4303           if (!ctables_parse_pcompute (lexer, ct))
4304             goto error;
4305         }
4306       else if (lex_match_id (lexer, "PPROPERTIES"))
4307         {
4308           if (!ctables_parse_pproperties (lexer, ct))
4309             goto error;
4310         }
4311       else if (lex_match_id (lexer, "WEIGHT"))
4312         {
4313           if (!lex_force_match_id (lexer, "VARIABLE"))
4314             goto error;
4315           lex_match (lexer, T_EQUALS);
4316           ct->e_weight = parse_variable (lexer, dataset_dict (ds));
4317           if (!ct->e_weight)
4318             goto error;
4319         }
4320       else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
4321         {
4322           if (!lex_force_match_id (lexer, "COUNT"))
4323             goto error;
4324           lex_match (lexer, T_EQUALS);
4325           if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
4326             goto error;
4327           ct->hide_threshold = lex_integer (lexer);
4328           lex_get (lexer);
4329         }
4330       else
4331         {
4332           lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
4333                                "SMISSING", "PCOMPUTE", "PPROPERTIES",
4334                                "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
4335           goto error;
4336         }
4337
4338       if (!lex_force_match (lexer, T_SLASH))
4339         goto error;
4340     }
4341
4342   size_t allocated_tables = 0;
4343   do
4344     {
4345       if (ct->n_tables >= allocated_tables)
4346         ct->tables = x2nrealloc (ct->tables, &allocated_tables,
4347                                  sizeof *ct->tables);
4348
4349       struct ctables_category *cat = xmalloc (sizeof *cat);
4350       *cat = (struct ctables_category) {
4351         .type = CCT_VALUE,
4352         .include_missing = false,
4353         .sort_ascending = true,
4354       };
4355
4356       struct ctables_categories *c = xmalloc (sizeof *c);
4357       size_t n_vars = dict_get_n_vars (dataset_dict (ds));
4358       *c = (struct ctables_categories) {
4359         .n_refs = n_vars,
4360         .cats = cat,
4361         .n_cats = 1,
4362         .show_empty = true,
4363       };
4364
4365       struct ctables_categories **categories = xnmalloc (n_vars,
4366                                                          sizeof *categories);
4367       for (size_t i = 0; i < n_vars; i++)
4368         categories[i] = c;
4369
4370       struct ctables_table *t = xmalloc (sizeof *t);
4371       *t = (struct ctables_table) {
4372         .ctables = ct,
4373         .slabels_axis = PIVOT_AXIS_COLUMN,
4374         .slabels_visible = true,
4375         .clabels_values_map = HMAP_INITIALIZER (t->clabels_values_map),
4376         .label_axis = {
4377           [PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW,
4378           [PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN,
4379           [PIVOT_AXIS_LAYER] = PIVOT_AXIS_LAYER,
4380         },
4381         .clabels_from_axis = PIVOT_AXIS_LAYER, 
4382         .categories = categories,
4383         .n_categories = n_vars,
4384         .cilevel = 95,
4385       };
4386       ct->tables[ct->n_tables++] = t;
4387
4388       lex_match (lexer, T_EQUALS);
4389       if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
4390         goto error;
4391       if (lex_match (lexer, T_BY))
4392         {
4393           if (!ctables_axis_parse (lexer, dataset_dict (ds),
4394                                    ct, t, PIVOT_AXIS_COLUMN))
4395             goto error;
4396
4397           if (lex_match (lexer, T_BY))
4398             {
4399               if (!ctables_axis_parse (lexer, dataset_dict (ds),
4400                                        ct, t, PIVOT_AXIS_LAYER))
4401                 goto error;
4402             }
4403         }
4404
4405       if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
4406           && !t->axes[PIVOT_AXIS_LAYER])
4407         {
4408           lex_error (lexer, _("At least one variable must be specified."));
4409           goto error;
4410         }
4411
4412       const struct ctables_axis *scales[PIVOT_N_AXES];
4413       size_t n_scales = 0;
4414       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4415         {
4416           scales[a] = find_scale (t->axes[a]);
4417           if (scales[a])
4418             n_scales++;
4419         }
4420       if (n_scales > 1)
4421         {
4422           msg (SE, _("Scale variables may appear only on one axis."));
4423           if (scales[PIVOT_AXIS_ROW])
4424             msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
4425                     _("This scale variable appears on the rows axis."));
4426           if (scales[PIVOT_AXIS_COLUMN])
4427             msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
4428                     _("This scale variable appears on the columns axis."));
4429           if (scales[PIVOT_AXIS_LAYER])
4430             msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
4431                     _("This scale variable appears on the layer axis."));
4432           goto error;
4433         }
4434
4435       const struct ctables_axis *summaries[PIVOT_N_AXES];
4436       size_t n_summaries = 0;
4437       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4438         {
4439           summaries[a] = (scales[a]
4440                           ? scales[a]
4441                           : find_categorical_summary_spec (t->axes[a]));
4442           if (summaries[a])
4443             n_summaries++;
4444         }
4445       if (n_summaries > 1)
4446         {
4447           msg (SE, _("Summaries may appear only on one axis."));
4448           if (summaries[PIVOT_AXIS_ROW])
4449             msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
4450                     _("This variable on the rows axis has a summary."));
4451           if (summaries[PIVOT_AXIS_COLUMN])
4452             msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
4453                     _("This variable on the columns axis has a summary."));
4454           if (summaries[PIVOT_AXIS_LAYER])
4455             msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
4456                     _("This variable on the layers axis has a summary."));
4457           goto error;
4458         }
4459       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4460         if (n_summaries ? summaries[a] : t->axes[a])
4461           {
4462             t->summary_axis = a;
4463             break;
4464           }
4465
4466       if (lex_token (lexer) == T_ENDCMD)
4467         {
4468           if (!ctables_prepare_table (t))
4469             goto error;
4470           break;
4471         }
4472       if (!lex_force_match (lexer, T_SLASH))
4473         break;
4474
4475       while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
4476         {
4477           if (lex_match_id (lexer, "SLABELS"))
4478             {
4479               while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4480                 {
4481                   if (lex_match_id (lexer, "POSITION"))
4482                     {
4483                       lex_match (lexer, T_EQUALS);
4484                       if (lex_match_id (lexer, "COLUMN"))
4485                         t->slabels_axis = PIVOT_AXIS_COLUMN;
4486                       else if (lex_match_id (lexer, "ROW"))
4487                         t->slabels_axis = PIVOT_AXIS_ROW;
4488                       else if (lex_match_id (lexer, "LAYER"))
4489                         t->slabels_axis = PIVOT_AXIS_LAYER;
4490                       else
4491                         {
4492                           lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
4493                           goto error;
4494                         }
4495                     }
4496                   else if (lex_match_id (lexer, "VISIBLE"))
4497                     {
4498                       lex_match (lexer, T_EQUALS);
4499                       if (!parse_bool (lexer, &t->slabels_visible))
4500                         goto error;
4501                     }
4502                   else
4503                     {
4504                       lex_error_expecting (lexer, "POSITION", "VISIBLE");
4505                       goto error;
4506                     }
4507                 }
4508             }
4509           else if (lex_match_id (lexer, "CLABELS"))
4510             {
4511               while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4512                 {
4513                   if (lex_match_id (lexer, "AUTO"))
4514                     {
4515                       t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW;
4516                       t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN;
4517                     }
4518                   else if (lex_match_id (lexer, "ROWLABELS"))
4519                     {
4520                       lex_match (lexer, T_EQUALS);
4521                       if (lex_match_id (lexer, "OPPOSITE"))
4522                         t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_COLUMN;
4523                       else if (lex_match_id (lexer, "LAYER"))
4524                         t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_LAYER;
4525                       else
4526                         {
4527                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
4528                           goto error;
4529                         }
4530                     }
4531                   else if (lex_match_id (lexer, "COLLABELS"))
4532                     {
4533                       lex_match (lexer, T_EQUALS);
4534                       if (lex_match_id (lexer, "OPPOSITE"))
4535                         t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_ROW;
4536                       else if (lex_match_id (lexer, "LAYER"))
4537                         t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_LAYER;
4538                       else
4539                         {
4540                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
4541                           goto error;
4542                         }
4543                     }
4544                   else
4545                     {
4546                       lex_error_expecting (lexer, "AUTO", "ROWLABELS",
4547                                            "COLLABELS");
4548                       goto error;
4549                     }
4550                 }
4551             }
4552           else if (lex_match_id (lexer, "CRITERIA"))
4553             {
4554               if (!lex_force_match_id (lexer, "CILEVEL"))
4555                 goto error;
4556               lex_match (lexer, T_EQUALS);
4557
4558               if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
4559                 goto error;
4560               t->cilevel = lex_number (lexer);
4561               lex_get (lexer);
4562             }
4563           else if (lex_match_id (lexer, "CATEGORIES"))
4564             {
4565               if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
4566                 goto error;
4567             }
4568           else if (lex_match_id (lexer, "TITLES"))
4569             {
4570               do
4571                 {
4572                   char **textp;
4573                   if (lex_match_id (lexer, "CAPTION"))
4574                     textp = &t->caption;
4575                   else if (lex_match_id (lexer, "CORNER"))
4576                     textp = &t->corner;
4577                   else if (lex_match_id (lexer, "TITLE"))
4578                     textp = &t->title;
4579                   else
4580                     {
4581                       lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
4582                       goto error;
4583                     }
4584                   lex_match (lexer, T_EQUALS);
4585
4586                   struct string s = DS_EMPTY_INITIALIZER;
4587                   while (lex_is_string (lexer))
4588                     {
4589                       if (!ds_is_empty (&s))
4590                         ds_put_byte (&s, ' ');
4591                       ds_put_substring (&s, lex_tokss (lexer));
4592                       lex_get (lexer);
4593                     }
4594                   free (*textp);
4595                   *textp = ds_steal_cstr (&s);
4596                 }
4597               while (lex_token (lexer) != T_SLASH
4598                      && lex_token (lexer) != T_ENDCMD);
4599             }
4600           else if (lex_match_id (lexer, "SIGTEST"))
4601             {
4602               if (!t->chisq)
4603                 {
4604                   t->chisq = xmalloc (sizeof *t->chisq);
4605                   *t->chisq = (struct ctables_chisq) {
4606                     .alpha = .05,
4607                     .include_mrsets = true,
4608                     .all_visible = true,
4609                   };
4610                 }
4611
4612               do
4613                 {
4614                   if (lex_match_id (lexer, "TYPE"))
4615                     {
4616                       lex_match (lexer, T_EQUALS);
4617                       if (!lex_force_match_id (lexer, "CHISQUARE"))
4618                         goto error;
4619                     }
4620                   else if (lex_match_id (lexer, "ALPHA"))
4621                     {
4622                       lex_match (lexer, T_EQUALS);
4623                       if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
4624                         goto error;
4625                       t->chisq->alpha = lex_number (lexer);
4626                       lex_get (lexer);
4627                     }
4628                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
4629                     {
4630                       lex_match (lexer, T_EQUALS);
4631                       if (parse_bool (lexer, &t->chisq->include_mrsets))
4632                         goto error;
4633                     }
4634                   else if (lex_match_id (lexer, "CATEGORIES"))
4635                     {
4636                       lex_match (lexer, T_EQUALS);
4637                       if (lex_match_id (lexer, "ALLVISIBLE"))
4638                         t->chisq->all_visible = true;
4639                       else if (lex_match_id (lexer, "SUBTOTALS"))
4640                         t->chisq->all_visible = false;
4641                       else
4642                         {
4643                           lex_error_expecting (lexer,
4644                                                "ALLVISIBLE", "SUBTOTALS");
4645                           goto error;
4646                         }
4647                     }
4648                   else
4649                     {
4650                       lex_error_expecting (lexer, "TYPE", "ALPHA",
4651                                            "INCLUDEMRSETS", "CATEGORIES");
4652                       goto error;
4653                     }
4654                 }
4655               while (lex_token (lexer) != T_SLASH
4656                      && lex_token (lexer) != T_ENDCMD);
4657             }
4658           else if (lex_match_id (lexer, "COMPARETEST"))
4659             {
4660               if (!t->pairwise)
4661                 {
4662                   t->pairwise = xmalloc (sizeof *t->pairwise);
4663                   *t->pairwise = (struct ctables_pairwise) {
4664                     .type = PROP,
4665                     .alpha = { .05, .05 },
4666                     .adjust = BONFERRONI,
4667                     .include_mrsets = true,
4668                     .meansvariance_allcats = true,
4669                     .all_visible = true,
4670                     .merge = false,
4671                     .apa_style = true,
4672                     .show_sig = false,
4673                   };
4674                 }
4675
4676               do
4677                 {
4678                   if (lex_match_id (lexer, "TYPE"))
4679                     {
4680                       lex_match (lexer, T_EQUALS);
4681                       if (lex_match_id (lexer, "PROP"))
4682                         t->pairwise->type = PROP;
4683                       else if (lex_match_id (lexer, "MEAN"))
4684                         t->pairwise->type = MEAN;
4685                       else
4686                         {
4687                           lex_error_expecting (lexer, "PROP", "MEAN");
4688                           goto error;
4689                         }
4690                     }
4691                   else if (lex_match_id (lexer, "ALPHA"))
4692                     {
4693                       lex_match (lexer, T_EQUALS);
4694
4695                       if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
4696                         goto error;
4697                       double a0 = lex_number (lexer);
4698                       lex_get (lexer);
4699
4700                       lex_match (lexer, T_COMMA);
4701                       if (lex_is_number (lexer))
4702                         {
4703                           if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
4704                             goto error;
4705                           double a1 = lex_number (lexer);
4706                           lex_get (lexer);
4707
4708                           t->pairwise->alpha[0] = MIN (a0, a1);
4709                           t->pairwise->alpha[1] = MAX (a0, a1);
4710                         }
4711                       else
4712                         t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
4713                     }
4714                   else if (lex_match_id (lexer, "ADJUST"))
4715                     {
4716                       lex_match (lexer, T_EQUALS);
4717                       if (lex_match_id (lexer, "BONFERRONI"))
4718                         t->pairwise->adjust = BONFERRONI;
4719                       else if (lex_match_id (lexer, "BH"))
4720                         t->pairwise->adjust = BH;
4721                       else if (lex_match_id (lexer, "NONE"))
4722                         t->pairwise->adjust = 0;
4723                       else
4724                         {
4725                           lex_error_expecting (lexer, "BONFERRONI", "BH",
4726                                                "NONE");
4727                           goto error;
4728                         }
4729                     }
4730                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
4731                     {
4732                       lex_match (lexer, T_EQUALS);
4733                       if (!parse_bool (lexer, &t->pairwise->include_mrsets))
4734                         goto error;
4735                     }
4736                   else if (lex_match_id (lexer, "MEANSVARIANCE"))
4737                     {
4738                       lex_match (lexer, T_EQUALS);
4739                       if (lex_match_id (lexer, "ALLCATS"))
4740                         t->pairwise->meansvariance_allcats = true;
4741                       else if (lex_match_id (lexer, "TESTEDCATS"))
4742                         t->pairwise->meansvariance_allcats = false;
4743                       else
4744                         {
4745                           lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
4746                           goto error;
4747                         }
4748                     }
4749                   else if (lex_match_id (lexer, "CATEGORIES"))
4750                     {
4751                       lex_match (lexer, T_EQUALS);
4752                       if (lex_match_id (lexer, "ALLVISIBLE"))
4753                         t->pairwise->all_visible = true;
4754                       else if (lex_match_id (lexer, "SUBTOTALS"))
4755                         t->pairwise->all_visible = false;
4756                       else
4757                         {
4758                           lex_error_expecting (lexer, "ALLVISIBLE",
4759                                                "SUBTOTALS");
4760                           goto error;
4761                         }
4762                     }
4763                   else if (lex_match_id (lexer, "MERGE"))
4764                     {
4765                       lex_match (lexer, T_EQUALS);
4766                       if (!parse_bool (lexer, &t->pairwise->merge))
4767                         goto error;
4768                     }
4769                   else if (lex_match_id (lexer, "STYLE"))
4770                     {
4771                       lex_match (lexer, T_EQUALS);
4772                       if (lex_match_id (lexer, "APA"))
4773                         t->pairwise->apa_style = true;
4774                       else if (lex_match_id (lexer, "SIMPLE"))
4775                         t->pairwise->apa_style = false;
4776                       else
4777                         {
4778                           lex_error_expecting (lexer, "APA", "SIMPLE");
4779                           goto error;
4780                         }
4781                     }
4782                   else if (lex_match_id (lexer, "SHOWSIG"))
4783                     {
4784                       lex_match (lexer, T_EQUALS);
4785                       if (!parse_bool (lexer, &t->pairwise->show_sig))
4786                         goto error;
4787                     }
4788                   else
4789                     {
4790                       lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
4791                                            "INCLUDEMRSETS", "MEANSVARIANCE",
4792                                            "CATEGORIES", "MERGE", "STYLE",
4793                                            "SHOWSIG");
4794                       goto error;
4795                     }
4796                 }
4797               while (lex_token (lexer) != T_SLASH
4798                      && lex_token (lexer) != T_ENDCMD);
4799             }
4800           else
4801             {
4802               lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
4803                                    "CRITERIA", "CATEGORIES", "TITLES",
4804                                    "SIGTEST", "COMPARETEST");
4805               goto error;
4806             }
4807
4808           if (!lex_match (lexer, T_SLASH))
4809             break;
4810         }
4811
4812       if (t->label_axis[PIVOT_AXIS_ROW] != PIVOT_AXIS_ROW
4813           && t->label_axis[PIVOT_AXIS_COLUMN] != PIVOT_AXIS_COLUMN)
4814         {
4815           msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
4816           goto error;
4817         }
4818
4819       if (!ctables_prepare_table (t))
4820         goto error;
4821     }
4822   while (lex_token (lexer) != T_ENDCMD);
4823
4824   bool ok = ctables_execute (ds, ct);
4825   ctables_destroy (ct);
4826   return ok ? CMD_SUCCESS : CMD_FAILURE;
4827
4828 error:
4829   ctables_destroy (ct);
4830   return CMD_FAILURE;
4831 }
4832