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