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