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