2-d subtotals work
[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 recurse_subtotals (struct ctables_table *t, const struct ccase *c,
2452                    size_t ix[PIVOT_N_AXES],
2453                    const struct ctables_category *cats[PIVOT_N_AXES][10],
2454                    double weight,
2455                    enum pivot_axis_type start_axis, size_t start_nest)
2456 {
2457   for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2458     {
2459       const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2460       for (size_t i = start_nest; i < nest->n; i++)
2461         {
2462           if (i == nest->scale_idx)
2463             continue;
2464
2465           const struct ctables_category *save = cats[a][i];
2466           if (save->subtotal)
2467             {
2468               cats[a][i] = save->subtotal;
2469               ctables_cell_add__ (t, c, ix, cats, weight);
2470               recurse_subtotals (t, c, ix, cats, weight, a, i + 1);
2471               cats[a][i] = save;
2472             }
2473         }
2474       start_nest = 0;
2475     }
2476 }
2477
2478 static void
2479 ctables_cell_insert (struct ctables_table *t,
2480                      const struct ccase *c,
2481                      size_t ir, size_t ic, size_t il,
2482                      double weight)
2483 {
2484   size_t ix[PIVOT_N_AXES] = {
2485     [PIVOT_AXIS_ROW] = ir,
2486     [PIVOT_AXIS_COLUMN] = ic,
2487     [PIVOT_AXIS_LAYER] = il,
2488   };
2489
2490   const struct ctables_category *cats[PIVOT_N_AXES][10];
2491   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2492     {
2493       const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2494       for (size_t i = 0; i < nest->n; i++)
2495         {
2496           if (i == nest->scale_idx)
2497             continue;
2498
2499           const struct variable *var = nest->vars[i];
2500           const union value *value = case_data (c, var);
2501
2502           if (var_is_numeric (var) && value->f == SYSMIS)
2503             return;
2504
2505           cats[a][i] = ctables_categories_match (
2506             t->categories[var_get_dict_index (var)], value, var);
2507           if (!cats[a][i])
2508             return;
2509         }
2510     }
2511
2512   ctables_cell_add__ (t, c, ix, cats, weight);
2513
2514   recurse_totals (t, c, ix, cats, weight, 0, 0);
2515   recurse_subtotals (t, c, ix, cats, weight, 0, 0);
2516 }
2517
2518 struct merge_item
2519   {
2520     const struct ctables_summary_spec_set *set;
2521     size_t ofs;
2522   };
2523
2524 static int
2525 merge_item_compare_3way (const struct merge_item *a, const struct merge_item *b)
2526 {
2527   const struct ctables_summary_spec *as = &a->set->specs[a->ofs];
2528   const struct ctables_summary_spec *bs = &b->set->specs[b->ofs];
2529   if (as->function != bs->function)
2530     return as->function > bs->function ? 1 : -1;
2531   else if (as->percentile != bs->percentile)
2532     return as->percentile < bs->percentile ? 1 : -1;
2533   return strcmp (as->label, bs->label);
2534 }
2535
2536 static struct pivot_value *
2537 ctables_category_create_label (const struct ctables_category *cat,
2538                                const struct variable *var,
2539                                const union value *value)
2540 {
2541   return (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL
2542           ? pivot_value_new_user_text (cat->total_label, SIZE_MAX)
2543           : pivot_value_new_var_value (var, value));
2544 }
2545
2546 static struct ctables_value *
2547 ctables_value_find__ (struct ctables_table *t, const union value *value,
2548                       int width, unsigned int hash)
2549 {
2550   struct ctables_value *clv;
2551   HMAP_FOR_EACH_WITH_HASH (clv, struct ctables_value, node,
2552                            hash, &t->clabels_values_map)
2553     if (value_equal (value, &clv->value, width))
2554       return clv;
2555   return NULL;
2556 }
2557
2558 static struct ctables_value *
2559 ctables_value_find (struct ctables_table *t,
2560                     const union value *value, int width)
2561 {
2562   return ctables_value_find__ (t, value, width,
2563                                value_hash (value, width, 0));
2564 }
2565
2566 static void
2567 ctables_table_output (struct ctables *ct, struct ctables_table *t)
2568 {
2569   struct pivot_table *pt = pivot_table_create__ (
2570     (t->title
2571      ? pivot_value_new_user_text (t->title, SIZE_MAX)
2572      : pivot_value_new_text (N_("Custom Tables"))),
2573     "Custom Tables");
2574   if (t->caption)
2575     pivot_table_set_caption (
2576       pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
2577   if (t->corner)
2578     pivot_table_set_caption (
2579       pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
2580
2581   bool summary_dimension = (t->summary_axis != t->slabels_axis
2582                             || (!t->slabels_visible
2583                                 && t->summary_specs.n > 1));
2584   if (summary_dimension)
2585     {
2586       struct pivot_dimension *d = pivot_dimension_create (
2587         pt, t->slabels_axis, N_("Statistics"));
2588       const struct ctables_summary_spec_set *specs = &t->summary_specs;
2589       if (!t->slabels_visible)
2590         d->hide_all_labels = true;
2591       for (size_t i = 0; i < specs->n; i++)
2592         pivot_category_create_leaf (
2593           d->root, pivot_value_new_text (specs->specs[i].label));
2594     }
2595
2596   bool categories_dimension = t->clabels_example != NULL;
2597   if (categories_dimension)
2598     {
2599       struct pivot_dimension *d = pivot_dimension_create (
2600         pt, t->label_axis[t->clabels_from_axis],
2601         t->clabels_from_axis == PIVOT_AXIS_ROW
2602         ? N_("Row Categories")
2603         : N_("Column Categories"));
2604       const struct variable *var = t->clabels_example;
2605       const struct ctables_categories *c = t->categories[var_get_dict_index (var)];
2606       for (size_t i = 0; i < t->n_clabels_values; i++)
2607         {
2608           const struct ctables_value *value = t->clabels_values[i];
2609           const struct ctables_category *cat = ctables_categories_match (c, &value->value, var);
2610           assert (cat != NULL);
2611           pivot_category_create_leaf (d->root, ctables_category_create_label (
2612                                         cat, t->clabels_example, &value->value));
2613         }
2614     }
2615
2616   pivot_table_set_look (pt, ct->look);
2617   struct pivot_dimension *d[PIVOT_N_AXES];
2618   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2619     {
2620       static const char *names[] = {
2621         [PIVOT_AXIS_ROW] = N_("Rows"),
2622         [PIVOT_AXIS_COLUMN] = N_("Columns"),
2623         [PIVOT_AXIS_LAYER] = N_("Layers"),
2624       };
2625       d[a] = (t->axes[a] || a == t->summary_axis
2626               ? pivot_dimension_create (pt, a, names[a])
2627               : NULL);
2628       if (!d[a])
2629         continue;
2630
2631       assert (t->axes[a]);
2632
2633       struct ctables_cell **sorted = xnmalloc (t->cells.count, sizeof *sorted);
2634       size_t n_sorted = 0;
2635
2636       struct ctables_cell *cell;
2637       HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2638         if (!cell->hide)
2639           sorted[n_sorted++] = cell;
2640       assert (n_sorted <= t->cells.count);
2641
2642       struct ctables_cell_sort_aux aux = { .t = t, .a = a };
2643       sort (sorted, n_sorted, sizeof *sorted, ctables_cell_compare_3way, &aux);
2644
2645       size_t max_depth = 0;
2646       for (size_t j = 0; j < t->stacks[a].n; j++)
2647         if (t->stacks[a].nests[j].n > max_depth)
2648           max_depth = t->stacks[a].nests[j].n;
2649
2650       /* Pivot categories:
2651
2652          - variable label for nest->vars[0], if vlabel != CTVL_NONE
2653          - category for nest->vars[0], if nest->scale_idx != 0
2654          - variable label for nest->vars[1], if vlabel != CTVL_NONE
2655          - category for nest->vars[1], if nest->scale_idx != 1
2656          ...
2657          - variable label for nest->vars[n - 1], if vlabel != CTVL_NONE
2658          - category for nest->vars[n - 1], if t->label_axis[a] == a && nest->scale_idx != n - 1.
2659          - summary function, if 'a == t->slabels_axis && a ==
2660          t->summary_axis'.
2661
2662          Additional dimensions:
2663
2664          - If 'a == t->slabels_axis && a != t->summary_axis', add a summary
2665          dimension.
2666          - If 't->label_axis[b] == a' for some 'b != a', add a category
2667          dimension to 'a'.
2668       */
2669
2670       struct ctables_level
2671         {
2672           enum ctables_level_type
2673             {
2674               CTL_VAR,          /* Variable label for nest->vars[var_idx]. */
2675               CTL_CATEGORY,     /* Category for nest->vars[var_idx]. */
2676               CTL_SUMMARY,      /* Summary functions. */
2677             }
2678           type;
2679
2680           size_t var_idx;
2681         };
2682       struct ctables_level *levels = xnmalloc (1 + 2 * max_depth, sizeof *levels);
2683       size_t n_levels = 0;
2684
2685       struct pivot_category **groups = xnmalloc (1 + 2 * max_depth, sizeof *groups);
2686       int prev_leaf = 0;
2687       for (size_t j = 0; j < n_sorted; j++)
2688         {
2689           struct ctables_cell *cell = sorted[j];
2690           struct ctables_cell *prev = j > 0 ? sorted[j - 1] : NULL;
2691           const struct ctables_nest *nest = &t->stacks[a].nests[cell->axes[a].nest_idx];
2692
2693           bool new_subtable = !prev || prev->axes[a].nest_idx != cell->axes[a].nest_idx;
2694           if (new_subtable)
2695             {
2696               n_levels = 0;
2697               for (size_t k = 0; k < nest->n; k++)
2698                 {
2699                   enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k])];
2700                   if (vlabel != CTVL_NONE)
2701                     {
2702                       levels[n_levels++] = (struct ctables_level) {
2703                         .type = CTL_VAR,
2704                         .var_idx = k,
2705                       };
2706                     }
2707
2708                   if (nest->scale_idx != k
2709                       && (k != nest->n - 1 || t->label_axis[a] == a))
2710                     {
2711                       levels[n_levels++] = (struct ctables_level) {
2712                         .type = CTL_CATEGORY,
2713                         .var_idx = k,
2714                       };
2715                     }
2716                 }
2717
2718               if (!summary_dimension && a == t->slabels_axis)
2719                 {
2720                   levels[n_levels++] = (struct ctables_level) {
2721                     .type = CTL_SUMMARY,
2722                     .var_idx = SIZE_MAX,
2723                   };
2724                 }
2725             }
2726
2727           size_t n_common = 0;
2728           if (!new_subtable)
2729             {
2730               for (; n_common < n_levels; n_common++)
2731                 {
2732                   const struct ctables_level *level = &levels[n_common];
2733                   if (level->type == CTL_CATEGORY)
2734                     {
2735                       size_t var_idx = level->var_idx;
2736                       const struct ctables_category *c = cell->axes[a].cvs[var_idx].category;
2737                       if (prev->axes[a].cvs[var_idx].category != c)
2738                         break;
2739                       else if (c->type != CCT_SUBTOTAL
2740                                && c->type != CCT_HSUBTOTAL
2741                                && c->type != CCT_TOTAL
2742                                && !value_equal (&prev->axes[a].cvs[var_idx].value,
2743                                                 &cell->axes[a].cvs[var_idx].value,
2744                                                 var_get_type (nest->vars[var_idx])))
2745                         break;
2746                     }
2747                 }
2748             }
2749
2750           for (size_t k = n_common; k < n_levels; k++)
2751             {
2752               const struct ctables_level *level = &levels[k];
2753               struct pivot_category *parent = k ? groups[k - 1] : d[a]->root;
2754               if (level->type == CTL_SUMMARY)
2755                 {
2756                   const struct ctables_summary_spec_set *specs = &t->summary_specs;
2757                   for (size_t m = 0; m < specs->n; m++)
2758                     {
2759                       int leaf = pivot_category_create_leaf (
2760                         parent, pivot_value_new_text (specs->specs[m].label));
2761                       if (!m)
2762                         prev_leaf = leaf;
2763                     }
2764                 }
2765               else
2766                 {
2767                   const struct variable *var = nest->vars[level->var_idx];
2768                   struct pivot_value *label;
2769                   if (level->type == CTL_VAR)
2770                     label = pivot_value_new_variable (var);
2771                   else if (level->type == CTL_CATEGORY)
2772                     {
2773                       const struct ctables_cell_value *cv = &cell->axes[a].cvs[level->var_idx];
2774                       label = ctables_category_create_label (cv->category,
2775                                                              var, &cv->value);
2776                     }
2777                   else
2778                     NOT_REACHED ();
2779
2780                   if (k == n_levels - 1)
2781                     prev_leaf = pivot_category_create_leaf (parent, label);
2782                   else
2783                     groups[k] = pivot_category_create_group__ (parent, label);
2784                 }
2785             }
2786
2787           cell->axes[a].leaf = prev_leaf;
2788         }
2789       free (sorted);
2790       free (groups);
2791     }
2792
2793   struct ctables_cell *cell;
2794   HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2795     {
2796       if (cell->hide)
2797         continue;
2798
2799       const struct ctables_nest *specs_nest = &t->stacks[t->summary_axis].nests[cell->axes[t->summary_axis].nest_idx];
2800       const struct ctables_summary_spec_set *specs = &specs_nest->specs[cell->sv];
2801       for (size_t j = 0; j < specs->n; j++)
2802         {
2803           size_t dindexes[5];
2804           size_t n_dindexes = 0;
2805
2806           if (summary_dimension)
2807             dindexes[n_dindexes++] = specs->specs[j].axis_idx;
2808
2809           if (categories_dimension)
2810             {
2811               const struct ctables_nest *clabels_nest = &t->stacks[t->clabels_from_axis].nests[cell->axes[t->clabels_from_axis].nest_idx];
2812               const struct variable *var = clabels_nest->vars[clabels_nest->n - 1];
2813               const union value *value = &cell->axes[t->clabels_from_axis].cvs[clabels_nest->n - 1].value;
2814               const struct ctables_value *ctv = ctables_value_find (t, value, var_get_width (var));
2815               assert (ctv != NULL);
2816               dindexes[n_dindexes++] = ctv->leaf;
2817             }
2818
2819           for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2820             if (d[a])
2821               {
2822                 int leaf = cell->axes[a].leaf;
2823                 if (a == t->summary_axis && !summary_dimension)
2824                   leaf += j;
2825                 dindexes[n_dindexes++] = leaf;
2826               }
2827
2828           double d = ctables_summary_value (cell, &cell->summaries[j], &specs->specs[j]);
2829           struct pivot_value *value = pivot_value_new_number (d);
2830           value->numeric.format = specs->specs[j].format;
2831           pivot_table_put (pt, dindexes, n_dindexes, value);
2832         }
2833     }
2834
2835   pivot_table_submit (pt);
2836 }
2837
2838 static bool
2839 ctables_check_label_position (struct ctables_table *t, enum pivot_axis_type a)
2840 {
2841   enum pivot_axis_type label_pos = t->label_axis[a];
2842   if (label_pos == a)
2843     return true;
2844
2845   t->clabels_from_axis = a;
2846
2847   const char *subcommand_name = a == PIVOT_AXIS_ROW ? "ROWLABELS" : "COLLABELS";
2848   const char *pos_name = label_pos == PIVOT_AXIS_LAYER ? "LAYER" : "OPPOSITE";
2849
2850   const struct ctables_stack *stack = &t->stacks[a];
2851   if (!stack->n)
2852     return true;
2853
2854   const struct ctables_nest *n0 = &stack->nests[0];
2855   assert (n0->n > 0);
2856   const struct variable *v0 = n0->vars[n0->n - 1];
2857   struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
2858   t->clabels_example = v0;
2859
2860   for (size_t i = 0; i < c0->n_cats; i++)
2861     if (c0->cats[i].type == CCT_FUNCTION)
2862       {
2863         msg (SE, _("%s=%s is not allowed with sorting based "
2864                    "on a summary function."),
2865              subcommand_name, pos_name);
2866         return false;
2867       }
2868   if (n0->n - 1 == n0->scale_idx)
2869     {
2870       msg (SE, _("%s=%s requires the variables to be moved to be categorical, "
2871                  "but %s is a scale variable."),
2872            subcommand_name, pos_name, var_get_name (v0));
2873       return false;
2874     }
2875
2876   for (size_t i = 1; i < stack->n; i++)
2877     {
2878       const struct ctables_nest *ni = &stack->nests[i];
2879       assert (ni->n > 0);
2880       const struct variable *vi = ni->vars[ni->n - 1];
2881       struct ctables_categories *ci = t->categories[var_get_dict_index (vi)];
2882
2883       if (ni->n - 1 == ni->scale_idx)
2884         {
2885           msg (SE, _("%s=%s requires the variables to be moved to be "
2886                      "categorical, but %s is a scale variable."),
2887                subcommand_name, pos_name, var_get_name (vi));
2888           return false;
2889         }
2890       if (var_get_width (v0) != var_get_width (vi))
2891         {
2892           msg (SE, _("%s=%s requires the variables to be "
2893                      "moved to have the same width, but %s has "
2894                      "width %d and %s has width %d."),
2895                subcommand_name, pos_name,
2896                var_get_name (v0), var_get_width (v0),
2897                var_get_name (vi), var_get_width (vi));
2898           return false;
2899         }
2900       if (!val_labs_equal (var_get_value_labels (v0),
2901                            var_get_value_labels (vi)))
2902         {
2903           msg (SE, _("%s=%s requires the variables to be "
2904                      "moved to have the same value labels, but %s "
2905                      "and %s have different value labels."),
2906                subcommand_name, pos_name,
2907                var_get_name (v0), var_get_name (vi));
2908           return false;
2909         }
2910       if (!ctables_categories_equal (c0, ci))
2911         {
2912           msg (SE, _("%s=%s requires the variables to be "
2913                      "moved to have the same category "
2914                      "specifications, but %s and %s have different "
2915                      "category specifications."),
2916                subcommand_name, pos_name,
2917                var_get_name (v0), var_get_name (vi));
2918           return false;
2919         }
2920     }
2921
2922   return true;
2923 }
2924
2925 static bool
2926 ctables_prepare_table (struct ctables_table *t)
2927 {
2928   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2929     if (t->axes[a])
2930       {
2931         t->stacks[a] = enumerate_fts (a, t->axes[a]);
2932
2933         for (size_t j = 0; j < t->stacks[a].n; j++)
2934           {
2935             struct ctables_nest *nest = &t->stacks[a].nests[j];
2936             for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2937               {
2938                 nest->domains[dt] = xmalloc (nest->n * sizeof *nest->domains[dt]);
2939                 nest->n_domains[dt] = 0;
2940
2941                 for (size_t k = 0; k < nest->n; k++)
2942                   {
2943                     if (k == nest->scale_idx)
2944                       continue;
2945
2946                     switch (dt)
2947                       {
2948                       case CTDT_TABLE:
2949                         continue;
2950
2951                       case CTDT_LAYER:
2952                         if (a != PIVOT_AXIS_LAYER)
2953                           continue;
2954                         break;
2955
2956                       case CTDT_SUBTABLE:
2957                       case CTDT_ROW:
2958                       case CTDT_COL:
2959                         if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
2960                             : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
2961                             : a == PIVOT_AXIS_ROW)
2962                           {
2963                             if (k == nest->n - 1
2964                                 || (nest->scale_idx == nest->n - 1
2965                                     && k == nest->n - 2))
2966                               continue;
2967                           }
2968                         break;
2969
2970                       case CTDT_LAYERROW:
2971                         if (a == PIVOT_AXIS_COLUMN)
2972                           continue;
2973                         break;
2974
2975                       case CTDT_LAYERCOL:
2976                         if (a == PIVOT_AXIS_ROW)
2977                           continue;
2978                         break;
2979                       }
2980
2981                     nest->domains[dt][nest->n_domains[dt]++] = k;
2982                   }
2983               }
2984           }
2985       }
2986     else
2987       {
2988         struct ctables_nest *nest = xmalloc (sizeof *nest);
2989         *nest = (struct ctables_nest) { .n = 0 };
2990         t->stacks[a] = (struct ctables_stack) { .nests = nest, .n = 1 };
2991       }
2992
2993   struct ctables_stack *stack = &t->stacks[t->summary_axis];
2994   for (size_t i = 0; i < stack->n; i++)
2995     {
2996       struct ctables_nest *nest = &stack->nests[i];
2997       if (!nest->specs[CSV_CELL].n)
2998         {
2999           struct ctables_summary_spec_set *specs = &nest->specs[CSV_CELL];
3000           specs->specs = xmalloc (sizeof *specs->specs);
3001           specs->n = 1;
3002
3003           enum ctables_summary_function function
3004             = specs->var ? CTSF_MEAN : CTSF_COUNT;
3005           struct ctables_var var = { .is_mrset = false, .var = specs->var };
3006
3007           *specs->specs = (struct ctables_summary_spec) {
3008             .function = function,
3009             .format = ctables_summary_default_format (function, &var),
3010             .label = ctables_summary_default_label (function, 0),
3011           };
3012           if (!specs->var)
3013             specs->var = nest->vars[0];
3014
3015           ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3016                                           &nest->specs[CSV_CELL]);
3017         }
3018       else if (!nest->specs[CSV_TOTAL].n)
3019         ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3020                                         &nest->specs[CSV_CELL]);
3021     }
3022
3023   struct ctables_summary_spec_set *merged = &t->summary_specs;
3024   struct merge_item *items = xnmalloc (2 * stack->n, sizeof *items);
3025   size_t n_left = 0;
3026   for (size_t j = 0; j < stack->n; j++)
3027     {
3028       const struct ctables_nest *nest = &stack->nests[j];
3029       if (nest->n)
3030         for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3031           items[n_left++] = (struct merge_item) { .set = &nest->specs[sv] };
3032     }
3033
3034   while (n_left > 0)
3035     {
3036       struct merge_item min = items[0];
3037       for (size_t j = 1; j < n_left; j++)
3038         if (merge_item_compare_3way (&items[j], &min) < 0)
3039           min = items[j];
3040
3041       if (merged->n >= merged->allocated)
3042         merged->specs = x2nrealloc (merged->specs, &merged->allocated,
3043                                     sizeof *merged->specs);
3044       merged->specs[merged->n++] = min.set->specs[min.ofs];
3045
3046       for (size_t j = 0; j < n_left; )
3047         {
3048           if (merge_item_compare_3way (&items[j], &min) == 0)
3049             {
3050               struct merge_item *item = &items[j];
3051               item->set->specs[item->ofs].axis_idx = merged->n - 1;
3052               if (++item->ofs >= item->set->n)
3053                 {
3054                   items[j] = items[--n_left];
3055                   continue;
3056                 }
3057             }
3058           j++;
3059         }
3060     }
3061
3062 #if 0
3063   for (size_t j = 0; j < merged->n; j++)
3064     printf ("%s\n", ctables_summary_function_name (merged->specs[j].function));
3065
3066   for (size_t j = 0; j < stack->n; j++)
3067     {
3068       const struct ctables_nest *nest = &stack->nests[j];
3069       for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3070         {
3071           const struct ctables_summary_spec_set *specs = &nest->specs[sv];
3072           for (size_t k = 0; k < specs->n; k++)
3073             printf ("(%s, %zu) ", ctables_summary_function_name (specs->specs[k].function),
3074                     specs->specs[k].axis_idx);
3075           printf ("\n");
3076         }
3077     }
3078 #endif
3079
3080   return (ctables_check_label_position (t, PIVOT_AXIS_ROW)
3081           && ctables_check_label_position (t, PIVOT_AXIS_COLUMN));
3082 }
3083
3084 static void
3085 ctables_insert_clabels_values (struct ctables_table *t, const struct ccase *c,
3086                                enum pivot_axis_type a)
3087 {
3088   struct ctables_stack *stack = &t->stacks[a];
3089   for (size_t i = 0; i < stack->n; i++)
3090     {
3091       const struct ctables_nest *nest = &stack->nests[i];
3092       const struct variable *var = nest->vars[nest->n - 1];
3093       int width = var_get_width (var);
3094       const union value *value = case_data (c, var);
3095
3096       if (var_is_numeric (var) && value->f == SYSMIS)
3097         continue;
3098
3099       if (!ctables_categories_match (t->categories [var_get_dict_index (var)],
3100                                      value, var))
3101         continue;
3102
3103       unsigned int hash = value_hash (value, width, 0);
3104
3105       struct ctables_value *clv = ctables_value_find__ (t, value, width, hash);
3106       if (!clv)
3107         {
3108           clv = xmalloc (sizeof *clv);
3109           value_clone (&clv->value, value, width);
3110           hmap_insert (&t->clabels_values_map, &clv->node, hash);
3111         }
3112     }
3113 }
3114
3115 static int
3116 compare_clabels_values_3way (const void *a_, const void *b_, const void *width_)
3117 {
3118   const struct ctables_value *const *ap = a_;
3119   const struct ctables_value *const *bp = b_;
3120   const struct ctables_value *a = *ap;
3121   const struct ctables_value *b = *bp;
3122   const int *width = width_;
3123   return value_compare_3way (&a->value, &b->value, *width);
3124 }
3125
3126 static void
3127 ctables_sort_clabels_values (struct ctables_table *t)
3128 {
3129   int width = var_get_width (t->clabels_example);
3130
3131   size_t n = hmap_count (&t->clabels_values_map);
3132   t->clabels_values = xnmalloc (n, sizeof *t->clabels_values);
3133
3134   struct ctables_value *clv;
3135   size_t i = 0;
3136   HMAP_FOR_EACH (clv, struct ctables_value, node, &t->clabels_values_map)
3137     t->clabels_values[i++] = clv;
3138   t->n_clabels_values = n;
3139   assert (i == n);
3140
3141   sort (t->clabels_values, n, sizeof *t->clabels_values,
3142         compare_clabels_values_3way, &width);
3143
3144   for (size_t i = 0; i < n; i++)
3145     t->clabels_values[i]->leaf = i;
3146 }
3147
3148 static bool
3149 ctables_execute (struct dataset *ds, struct ctables *ct)
3150 {
3151   struct casereader *input = casereader_create_filter_weight (proc_open (ds),
3152                                                               dataset_dict (ds),
3153                                                               NULL, NULL);
3154   bool warn_on_invalid = true;
3155   double total_weight = 0;
3156   for (struct ccase *c = casereader_read (input); c;
3157        case_unref (c), c = casereader_read (input))
3158     {
3159       double weight = dict_get_case_weight (dataset_dict (ds), c,
3160                                             &warn_on_invalid);
3161       total_weight += weight;
3162
3163       for (size_t i = 0; i < ct->n_tables; i++)
3164         {
3165           struct ctables_table *t = ct->tables[i];
3166
3167           for (size_t ir = 0; ir < t->stacks[PIVOT_AXIS_ROW].n; ir++)
3168             for (size_t ic = 0; ic < t->stacks[PIVOT_AXIS_COLUMN].n; ic++)
3169               for (size_t il = 0; il < t->stacks[PIVOT_AXIS_LAYER].n; il++)
3170                 ctables_cell_insert (t, c, ir, ic, il, weight);
3171
3172           for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3173             if (t->label_axis[a] != a)
3174               ctables_insert_clabels_values (t, c, a);
3175         }
3176     }
3177   casereader_destroy (input);
3178
3179   for (size_t i = 0; i < ct->n_tables; i++)
3180     {
3181       struct ctables_table *t = ct->tables[i];
3182
3183       if (t->clabels_example)
3184         ctables_sort_clabels_values (t);
3185
3186       ctables_table_output (ct, ct->tables[i]);
3187     }
3188   return proc_commit (ds);
3189 }
3190
3191 int
3192 cmd_ctables (struct lexer *lexer, struct dataset *ds)
3193 {
3194   size_t n_vars = dict_get_n_vars (dataset_dict (ds));
3195   enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
3196   enum settings_value_show tvars = settings_get_show_variables ();
3197   for (size_t i = 0; i < n_vars; i++)
3198     vlabels[i] = (enum ctables_vlabel) tvars;
3199
3200   struct ctables *ct = xmalloc (sizeof *ct);
3201   *ct = (struct ctables) {
3202     .look = pivot_table_look_unshare (pivot_table_look_ref (
3203                                         pivot_table_look_get_default ())),
3204     .vlabels = vlabels,
3205     .hide_threshold = 5,
3206   };
3207   ct->look->omit_empty = false;
3208
3209   if (!lex_force_match (lexer, T_SLASH))
3210     goto error;
3211
3212   while (!lex_match_id (lexer, "TABLE"))
3213     {
3214       if (lex_match_id (lexer, "FORMAT"))
3215         {
3216           double widths[2] = { SYSMIS, SYSMIS };
3217           double units_per_inch = 72.0;
3218
3219           while (lex_token (lexer) != T_SLASH)
3220             {
3221               if (lex_match_id (lexer, "MINCOLWIDTH"))
3222                 {
3223                   if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
3224                     goto error;
3225                 }
3226               else if (lex_match_id (lexer, "MAXCOLWIDTH"))
3227                 {
3228                   if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
3229                     goto error;
3230                 }
3231               else if (lex_match_id (lexer, "UNITS"))
3232                 {
3233                   lex_match (lexer, T_EQUALS);
3234                   if (lex_match_id (lexer, "POINTS"))
3235                     units_per_inch = 72.0;
3236                   else if (lex_match_id (lexer, "INCHES"))
3237                     units_per_inch = 1.0;
3238                   else if (lex_match_id (lexer, "CM"))
3239                     units_per_inch = 2.54;
3240                   else
3241                     {
3242                       lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
3243                       goto error;
3244                     }
3245                 }
3246               else if (lex_match_id (lexer, "EMPTY"))
3247                 {
3248                   free (ct->zero);
3249                   ct->zero = NULL;
3250
3251                   lex_match (lexer, T_EQUALS);
3252                   if (lex_match_id (lexer, "ZERO"))
3253                     {
3254                       /* Nothing to do. */
3255                     }
3256                   else if (lex_match_id (lexer, "BLANK"))
3257                     ct->zero = xstrdup ("");
3258                   else if (lex_force_string (lexer))
3259                     {
3260                       ct->zero = ss_xstrdup (lex_tokss (lexer));
3261                       lex_get (lexer);
3262                     }
3263                   else
3264                     goto error;
3265                 }
3266               else if (lex_match_id (lexer, "MISSING"))
3267                 {
3268                   lex_match (lexer, T_EQUALS);
3269                   if (!lex_force_string (lexer))
3270                     goto error;
3271
3272                   free (ct->missing);
3273                   ct->missing = (strcmp (lex_tokcstr (lexer), ".")
3274                                  ? ss_xstrdup (lex_tokss (lexer))
3275                                  : NULL);
3276                   lex_get (lexer);
3277                 }
3278               else
3279                 {
3280                   lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
3281                                        "UNITS", "EMPTY", "MISSING");
3282                   goto error;
3283                 }
3284             }
3285
3286           if (widths[0] != SYSMIS && widths[1] != SYSMIS
3287               && widths[0] > widths[1])
3288             {
3289               msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
3290               goto error;
3291             }
3292
3293           for (size_t i = 0; i < 2; i++)
3294             if (widths[i] != SYSMIS)
3295               {
3296                 int *wr = ct->look->width_ranges[TABLE_HORZ];
3297                 wr[i] = widths[i] / units_per_inch * 96.0;
3298                 if (wr[0] > wr[1])
3299                   wr[!i] = wr[i];
3300               }
3301         }
3302       else if (lex_match_id (lexer, "VLABELS"))
3303         {
3304           if (!lex_force_match_id (lexer, "VARIABLES"))
3305             goto error;
3306           lex_match (lexer, T_EQUALS);
3307
3308           struct variable **vars;
3309           size_t n_vars;
3310           if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
3311                                 PV_NO_SCRATCH))
3312             goto error;
3313
3314           if (!lex_force_match_id (lexer, "DISPLAY"))
3315             {
3316               free (vars);
3317               goto error;
3318             }
3319           lex_match (lexer, T_EQUALS);
3320
3321           enum ctables_vlabel vlabel;
3322           if (lex_match_id (lexer, "DEFAULT"))
3323             vlabel = (enum ctables_vlabel) settings_get_show_variables ();
3324           else if (lex_match_id (lexer, "NAME"))
3325             vlabel = CTVL_NAME;
3326           else if (lex_match_id (lexer, "LABEL"))
3327             vlabel = CTVL_LABEL;
3328           else if (lex_match_id (lexer, "BOTH"))
3329             vlabel = CTVL_BOTH;
3330           else if (lex_match_id (lexer, "NONE"))
3331             vlabel = CTVL_NONE;
3332           else
3333             {
3334               lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
3335                                    "BOTH", "NONE");
3336               free (vars);
3337               goto error;
3338             }
3339
3340           for (size_t i = 0; i < n_vars; i++)
3341             ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
3342           free (vars);
3343         }
3344       else if (lex_match_id (lexer, "MRSETS"))
3345         {
3346           if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
3347             goto error;
3348           lex_match (lexer, T_EQUALS);
3349           if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
3350             goto error;
3351         }
3352       else if (lex_match_id (lexer, "SMISSING"))
3353         {
3354           if (lex_match_id (lexer, "VARIABLE"))
3355             ct->smissing_listwise = false;
3356           else if (lex_match_id (lexer, "LISTWISE"))
3357             ct->smissing_listwise = true;
3358           else
3359             {
3360               lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
3361               goto error;
3362             }
3363         }
3364       /* XXX PCOMPUTE */
3365       else if (lex_match_id (lexer, "WEIGHT"))
3366         {
3367           if (!lex_force_match_id (lexer, "VARIABLE"))
3368             goto error;
3369           lex_match (lexer, T_EQUALS);
3370           ct->base_weight = parse_variable (lexer, dataset_dict (ds));
3371           if (!ct->base_weight)
3372             goto error;
3373         }
3374       else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
3375         {
3376           if (!lex_force_match_id (lexer, "COUNT"))
3377             goto error;
3378           lex_match (lexer, T_EQUALS);
3379           if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
3380             goto error;
3381           ct->hide_threshold = lex_integer (lexer);
3382           lex_get (lexer);
3383         }
3384       else
3385         {
3386           lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
3387                                "SMISSING", "PCOMPUTE", "PPROPERTIES",
3388                                "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
3389           goto error;
3390         }
3391
3392       if (!lex_force_match (lexer, T_SLASH))
3393         goto error;
3394     }
3395
3396   size_t allocated_tables = 0;
3397   do
3398     {
3399       if (ct->n_tables >= allocated_tables)
3400         ct->tables = x2nrealloc (ct->tables, &allocated_tables,
3401                                  sizeof *ct->tables);
3402
3403       struct ctables_category *cat = xmalloc (sizeof *cat);
3404       *cat = (struct ctables_category) {
3405         .type = CCT_VALUE,
3406         .include_missing = false,
3407         .sort_ascending = true,
3408       };
3409
3410       struct ctables_categories *c = xmalloc (sizeof *c);
3411       size_t n_vars = dict_get_n_vars (dataset_dict (ds));
3412       *c = (struct ctables_categories) {
3413         .n_refs = n_vars,
3414         .cats = cat,
3415         .n_cats = 1,
3416       };
3417
3418       struct ctables_categories **categories = xnmalloc (n_vars,
3419                                                          sizeof *categories);
3420       for (size_t i = 0; i < n_vars; i++)
3421         categories[i] = c;
3422
3423       struct ctables_table *t = xmalloc (sizeof *t);
3424       *t = (struct ctables_table) {
3425         .cells = HMAP_INITIALIZER (t->cells),
3426         .slabels_axis = PIVOT_AXIS_COLUMN,
3427         .slabels_visible = true,
3428         .clabels_values_map = HMAP_INITIALIZER (t->clabels_values_map),
3429         .label_axis = {
3430           [PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW,
3431           [PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN,
3432           [PIVOT_AXIS_LAYER] = PIVOT_AXIS_LAYER,
3433         },
3434         .clabels_from_axis = PIVOT_AXIS_LAYER, 
3435         .categories = categories,
3436         .n_categories = n_vars,
3437         .cilevel = 95,
3438       };
3439       for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3440         hmap_init (&t->domains[dt]);
3441       ct->tables[ct->n_tables++] = t;
3442
3443       lex_match (lexer, T_EQUALS);
3444       if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
3445         goto error;
3446       if (lex_match (lexer, T_BY))
3447         {
3448           if (!ctables_axis_parse (lexer, dataset_dict (ds),
3449                                    ct, t, PIVOT_AXIS_COLUMN))
3450             goto error;
3451
3452           if (lex_match (lexer, T_BY))
3453             {
3454               if (!ctables_axis_parse (lexer, dataset_dict (ds),
3455                                        ct, t, PIVOT_AXIS_LAYER))
3456                 goto error;
3457             }
3458         }
3459
3460       if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
3461           && !t->axes[PIVOT_AXIS_LAYER])
3462         {
3463           lex_error (lexer, _("At least one variable must be specified."));
3464           goto error;
3465         }
3466
3467       const struct ctables_axis *scales[PIVOT_N_AXES];
3468       size_t n_scales = 0;
3469       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3470         {
3471           scales[a] = find_scale (t->axes[a]);
3472           if (scales[a])
3473             n_scales++;
3474         }
3475       if (n_scales > 1)
3476         {
3477           msg (SE, _("Scale variables may appear only on one axis."));
3478           if (scales[PIVOT_AXIS_ROW])
3479             msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
3480                     _("This scale variable appears on the rows axis."));
3481           if (scales[PIVOT_AXIS_COLUMN])
3482             msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
3483                     _("This scale variable appears on the columns axis."));
3484           if (scales[PIVOT_AXIS_LAYER])
3485             msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
3486                     _("This scale variable appears on the layer axis."));
3487           goto error;
3488         }
3489
3490       const struct ctables_axis *summaries[PIVOT_N_AXES];
3491       size_t n_summaries = 0;
3492       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3493         {
3494           summaries[a] = (scales[a]
3495                           ? scales[a]
3496                           : find_categorical_summary_spec (t->axes[a]));
3497           if (summaries[a])
3498             n_summaries++;
3499         }
3500       if (n_summaries > 1)
3501         {
3502           msg (SE, _("Summaries may appear only on one axis."));
3503           if (summaries[PIVOT_AXIS_ROW])
3504             msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
3505                     _("This variable on the rows axis has a summary."));
3506           if (summaries[PIVOT_AXIS_COLUMN])
3507             msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
3508                     _("This variable on the columns axis has a summary."));
3509           if (summaries[PIVOT_AXIS_LAYER])
3510             msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
3511                     _("This variable on the layers axis has a summary."));
3512           goto error;
3513         }
3514       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3515         if (n_summaries ? summaries[a] : t->axes[a])
3516           {
3517             t->summary_axis = a;
3518             break;
3519           }
3520
3521       if (lex_token (lexer) == T_ENDCMD)
3522         {
3523           if (!ctables_prepare_table (t))
3524             goto error;
3525           break;
3526         }
3527       if (!lex_force_match (lexer, T_SLASH))
3528         break;
3529
3530       while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
3531         {
3532           if (lex_match_id (lexer, "SLABELS"))
3533             {
3534               while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3535                 {
3536                   if (lex_match_id (lexer, "POSITION"))
3537                     {
3538                       lex_match (lexer, T_EQUALS);
3539                       if (lex_match_id (lexer, "COLUMN"))
3540                         t->slabels_axis = PIVOT_AXIS_COLUMN;
3541                       else if (lex_match_id (lexer, "ROW"))
3542                         t->slabels_axis = PIVOT_AXIS_ROW;
3543                       else if (lex_match_id (lexer, "LAYER"))
3544                         t->slabels_axis = PIVOT_AXIS_LAYER;
3545                       else
3546                         {
3547                           lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
3548                           goto error;
3549                         }
3550                     }
3551                   else if (lex_match_id (lexer, "VISIBLE"))
3552                     {
3553                       lex_match (lexer, T_EQUALS);
3554                       if (!parse_bool (lexer, &t->slabels_visible))
3555                         goto error;
3556                     }
3557                   else
3558                     {
3559                       lex_error_expecting (lexer, "POSITION", "VISIBLE");
3560                       goto error;
3561                     }
3562                 }
3563             }
3564           else if (lex_match_id (lexer, "CLABELS"))
3565             {
3566               while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3567                 {
3568                   if (lex_match_id (lexer, "AUTO"))
3569                     {
3570                       t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW;
3571                       t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN;
3572                     }
3573                   else if (lex_match_id (lexer, "ROWLABELS"))
3574                     {
3575                       lex_match (lexer, T_EQUALS);
3576                       if (lex_match_id (lexer, "OPPOSITE"))
3577                         t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_COLUMN;
3578                       else if (lex_match_id (lexer, "LAYER"))
3579                         t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_LAYER;
3580                       else
3581                         {
3582                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3583                           goto error;
3584                         }
3585                     }
3586                   else if (lex_match_id (lexer, "COLLABELS"))
3587                     {
3588                       lex_match (lexer, T_EQUALS);
3589                       if (lex_match_id (lexer, "OPPOSITE"))
3590                         t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_ROW;
3591                       else if (lex_match_id (lexer, "LAYER"))
3592                         t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_LAYER;
3593                       else
3594                         {
3595                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3596                           goto error;
3597                         }
3598                     }
3599                   else
3600                     {
3601                       lex_error_expecting (lexer, "AUTO", "ROWLABELS",
3602                                            "COLLABELS");
3603                       goto error;
3604                     }
3605                 }
3606             }
3607           else if (lex_match_id (lexer, "CRITERIA"))
3608             {
3609               if (!lex_force_match_id (lexer, "CILEVEL"))
3610                 goto error;
3611               lex_match (lexer, T_EQUALS);
3612
3613               if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
3614                 goto error;
3615               t->cilevel = lex_number (lexer);
3616               lex_get (lexer);
3617             }
3618           else if (lex_match_id (lexer, "CATEGORIES"))
3619             {
3620               if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
3621                 goto error;
3622             }
3623           else if (lex_match_id (lexer, "TITLES"))
3624             {
3625               do
3626                 {
3627                   char **textp;
3628                   if (lex_match_id (lexer, "CAPTION"))
3629                     textp = &t->caption;
3630                   else if (lex_match_id (lexer, "CORNER"))
3631                     textp = &t->corner;
3632                   else if (lex_match_id (lexer, "TITLE"))
3633                     textp = &t->title;
3634                   else
3635                     {
3636                       lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
3637                       goto error;
3638                     }
3639                   lex_match (lexer, T_EQUALS);
3640
3641                   struct string s = DS_EMPTY_INITIALIZER;
3642                   while (lex_is_string (lexer))
3643                     {
3644                       if (!ds_is_empty (&s))
3645                         ds_put_byte (&s, ' ');
3646                       ds_put_substring (&s, lex_tokss (lexer));
3647                       lex_get (lexer);
3648                     }
3649                   free (*textp);
3650                   *textp = ds_steal_cstr (&s);
3651                 }
3652               while (lex_token (lexer) != T_SLASH
3653                      && lex_token (lexer) != T_ENDCMD);
3654             }
3655           else if (lex_match_id (lexer, "SIGTEST"))
3656             {
3657               if (!t->chisq)
3658                 {
3659                   t->chisq = xmalloc (sizeof *t->chisq);
3660                   *t->chisq = (struct ctables_chisq) {
3661                     .alpha = .05,
3662                     .include_mrsets = true,
3663                     .all_visible = true,
3664                   };
3665                 }
3666
3667               do
3668                 {
3669                   if (lex_match_id (lexer, "TYPE"))
3670                     {
3671                       lex_match (lexer, T_EQUALS);
3672                       if (!lex_force_match_id (lexer, "CHISQUARE"))
3673                         goto error;
3674                     }
3675                   else if (lex_match_id (lexer, "ALPHA"))
3676                     {
3677                       lex_match (lexer, T_EQUALS);
3678                       if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
3679                         goto error;
3680                       t->chisq->alpha = lex_number (lexer);
3681                       lex_get (lexer);
3682                     }
3683                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3684                     {
3685                       lex_match (lexer, T_EQUALS);
3686                       if (parse_bool (lexer, &t->chisq->include_mrsets))
3687                         goto error;
3688                     }
3689                   else if (lex_match_id (lexer, "CATEGORIES"))
3690                     {
3691                       lex_match (lexer, T_EQUALS);
3692                       if (lex_match_id (lexer, "ALLVISIBLE"))
3693                         t->chisq->all_visible = true;
3694                       else if (lex_match_id (lexer, "SUBTOTALS"))
3695                         t->chisq->all_visible = false;
3696                       else
3697                         {
3698                           lex_error_expecting (lexer,
3699                                                "ALLVISIBLE", "SUBTOTALS");
3700                           goto error;
3701                         }
3702                     }
3703                   else
3704                     {
3705                       lex_error_expecting (lexer, "TYPE", "ALPHA",
3706                                            "INCLUDEMRSETS", "CATEGORIES");
3707                       goto error;
3708                     }
3709                 }
3710               while (lex_token (lexer) != T_SLASH
3711                      && lex_token (lexer) != T_ENDCMD);
3712             }
3713           else if (lex_match_id (lexer, "COMPARETEST"))
3714             {
3715               if (!t->pairwise)
3716                 {
3717                   t->pairwise = xmalloc (sizeof *t->pairwise);
3718                   *t->pairwise = (struct ctables_pairwise) {
3719                     .type = PROP,
3720                     .alpha = { .05, .05 },
3721                     .adjust = BONFERRONI,
3722                     .include_mrsets = true,
3723                     .meansvariance_allcats = true,
3724                     .all_visible = true,
3725                     .merge = false,
3726                     .apa_style = true,
3727                     .show_sig = false,
3728                   };
3729                 }
3730
3731               do
3732                 {
3733                   if (lex_match_id (lexer, "TYPE"))
3734                     {
3735                       lex_match (lexer, T_EQUALS);
3736                       if (lex_match_id (lexer, "PROP"))
3737                         t->pairwise->type = PROP;
3738                       else if (lex_match_id (lexer, "MEAN"))
3739                         t->pairwise->type = MEAN;
3740                       else
3741                         {
3742                           lex_error_expecting (lexer, "PROP", "MEAN");
3743                           goto error;
3744                         }
3745                     }
3746                   else if (lex_match_id (lexer, "ALPHA"))
3747                     {
3748                       lex_match (lexer, T_EQUALS);
3749
3750                       if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3751                         goto error;
3752                       double a0 = lex_number (lexer);
3753                       lex_get (lexer);
3754
3755                       lex_match (lexer, T_COMMA);
3756                       if (lex_is_number (lexer))
3757                         {
3758                           if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3759                             goto error;
3760                           double a1 = lex_number (lexer);
3761                           lex_get (lexer);
3762
3763                           t->pairwise->alpha[0] = MIN (a0, a1);
3764                           t->pairwise->alpha[1] = MAX (a0, a1);
3765                         }
3766                       else
3767                         t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
3768                     }
3769                   else if (lex_match_id (lexer, "ADJUST"))
3770                     {
3771                       lex_match (lexer, T_EQUALS);
3772                       if (lex_match_id (lexer, "BONFERRONI"))
3773                         t->pairwise->adjust = BONFERRONI;
3774                       else if (lex_match_id (lexer, "BH"))
3775                         t->pairwise->adjust = BH;
3776                       else if (lex_match_id (lexer, "NONE"))
3777                         t->pairwise->adjust = 0;
3778                       else
3779                         {
3780                           lex_error_expecting (lexer, "BONFERRONI", "BH",
3781                                                "NONE");
3782                           goto error;
3783                         }
3784                     }
3785                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3786                     {
3787                       lex_match (lexer, T_EQUALS);
3788                       if (!parse_bool (lexer, &t->pairwise->include_mrsets))
3789                         goto error;
3790                     }
3791                   else if (lex_match_id (lexer, "MEANSVARIANCE"))
3792                     {
3793                       lex_match (lexer, T_EQUALS);
3794                       if (lex_match_id (lexer, "ALLCATS"))
3795                         t->pairwise->meansvariance_allcats = true;
3796                       else if (lex_match_id (lexer, "TESTEDCATS"))
3797                         t->pairwise->meansvariance_allcats = false;
3798                       else
3799                         {
3800                           lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
3801                           goto error;
3802                         }
3803                     }
3804                   else if (lex_match_id (lexer, "CATEGORIES"))
3805                     {
3806                       lex_match (lexer, T_EQUALS);
3807                       if (lex_match_id (lexer, "ALLVISIBLE"))
3808                         t->pairwise->all_visible = true;
3809                       else if (lex_match_id (lexer, "SUBTOTALS"))
3810                         t->pairwise->all_visible = false;
3811                       else
3812                         {
3813                           lex_error_expecting (lexer, "ALLVISIBLE",
3814                                                "SUBTOTALS");
3815                           goto error;
3816                         }
3817                     }
3818                   else if (lex_match_id (lexer, "MERGE"))
3819                     {
3820                       lex_match (lexer, T_EQUALS);
3821                       if (!parse_bool (lexer, &t->pairwise->merge))
3822                         goto error;
3823                     }
3824                   else if (lex_match_id (lexer, "STYLE"))
3825                     {
3826                       lex_match (lexer, T_EQUALS);
3827                       if (lex_match_id (lexer, "APA"))
3828                         t->pairwise->apa_style = true;
3829                       else if (lex_match_id (lexer, "SIMPLE"))
3830                         t->pairwise->apa_style = false;
3831                       else
3832                         {
3833                           lex_error_expecting (lexer, "APA", "SIMPLE");
3834                           goto error;
3835                         }
3836                     }
3837                   else if (lex_match_id (lexer, "SHOWSIG"))
3838                     {
3839                       lex_match (lexer, T_EQUALS);
3840                       if (!parse_bool (lexer, &t->pairwise->show_sig))
3841                         goto error;
3842                     }
3843                   else
3844                     {
3845                       lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
3846                                            "INCLUDEMRSETS", "MEANSVARIANCE",
3847                                            "CATEGORIES", "MERGE", "STYLE",
3848                                            "SHOWSIG");
3849                       goto error;
3850                     }
3851                 }
3852               while (lex_token (lexer) != T_SLASH
3853                      && lex_token (lexer) != T_ENDCMD);
3854             }
3855           else
3856             {
3857               lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
3858                                    "CRITERIA", "CATEGORIES", "TITLES",
3859                                    "SIGTEST", "COMPARETEST");
3860               goto error;
3861             }
3862
3863           if (!lex_match (lexer, T_SLASH))
3864             break;
3865         }
3866
3867       if (t->label_axis[PIVOT_AXIS_ROW] != PIVOT_AXIS_ROW
3868           && t->label_axis[PIVOT_AXIS_COLUMN] != PIVOT_AXIS_COLUMN)
3869         {
3870           msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
3871           goto error;
3872         }
3873
3874       if (!ctables_prepare_table (t))
3875         goto error;
3876     }
3877   while (lex_token (lexer) != T_ENDCMD);
3878
3879   bool ok = ctables_execute (ds, ct);
3880   ctables_destroy (ct);
3881   return ok ? CMD_SUCCESS : CMD_FAILURE;
3882
3883 error:
3884   ctables_destroy (ct);
3885   return CMD_FAILURE;
3886 }
3887