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