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