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