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