fix one bug with clabels
[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       moments1_add (s->moments, value->f, weight);
1929       break;
1930
1931     case CTSF_MEDIAN:
1932     case CTSF_MISSING:
1933     case CTSF_MODE:
1934     case CTSF_PTILE:
1935       NOT_REACHED ();
1936
1937     case CTSF_RESPONSES:
1938     case CTSF_ROWPCT_RESPONSES:
1939     case CTSF_COLPCT_RESPONSES:
1940     case CTSF_TABLEPCT_RESPONSES:
1941     case CTSF_SUBTABLEPCT_RESPONSES:
1942     case CTSF_LAYERPCT_RESPONSES:
1943     case CTSF_LAYERROWPCT_RESPONSES:
1944     case CTSF_LAYERCOLPCT_RESPONSES:
1945     case CTSF_ROWPCT_RESPONSES_COUNT:
1946     case CTSF_COLPCT_RESPONSES_COUNT:
1947     case CTSF_TABLEPCT_RESPONSES_COUNT:
1948     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1949     case CTSF_LAYERPCT_RESPONSES_COUNT:
1950     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1951     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1952     case CTSF_ROWPCT_COUNT_RESPONSES:
1953     case CTSF_COLPCT_COUNT_RESPONSES:
1954     case CTSF_TABLEPCT_COUNT_RESPONSES:
1955     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1956     case CTSF_LAYERPCT_COUNT_RESPONSES:
1957     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1958     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1959       NOT_REACHED ();
1960     }
1961 }
1962
1963 static double
1964 ctables_summary_value (const struct ctables_cell *cell,
1965                        union ctables_summary *s,
1966                        const struct ctables_summary_spec *ss)
1967 {
1968   switch (ss->function)
1969     {
1970     case CTSF_COUNT:
1971     case CTSF_ECOUNT:
1972       return s->valid;
1973
1974     case CTSF_SUBTABLEPCT_COUNT:
1975       return cell->domains[CTDT_SUBTABLE]->valid ? s->valid / cell->domains[CTDT_SUBTABLE]->valid * 100 : SYSMIS;
1976
1977     case CTSF_ROWPCT_COUNT:
1978       return cell->domains[CTDT_ROW]->valid ? s->valid / cell->domains[CTDT_ROW]->valid * 100 : SYSMIS;
1979
1980     case CTSF_COLPCT_COUNT:
1981       return cell->domains[CTDT_COL]->valid ? s->valid / cell->domains[CTDT_COL]->valid * 100 : SYSMIS;
1982
1983     case CTSF_TABLEPCT_COUNT:
1984       return cell->domains[CTDT_TABLE]->valid ? s->valid / cell->domains[CTDT_TABLE]->valid * 100 : SYSMIS;
1985
1986     case CTSF_LAYERPCT_COUNT:
1987       return cell->domains[CTDT_LAYER]->valid ? s->valid / cell->domains[CTDT_LAYER]->valid * 100 : SYSMIS;
1988
1989     case CTSF_LAYERROWPCT_COUNT:
1990       return cell->domains[CTDT_LAYERROW]->valid ? s->valid / cell->domains[CTDT_LAYERROW]->valid * 100 : SYSMIS;
1991
1992     case CTSF_LAYERCOLPCT_COUNT:
1993       return cell->domains[CTDT_LAYERCOL]->valid ? s->valid / cell->domains[CTDT_LAYERCOL]->valid * 100 : SYSMIS;
1994
1995     case CTSF_ROWPCT_VALIDN:
1996     case CTSF_COLPCT_VALIDN:
1997     case CTSF_TABLEPCT_VALIDN:
1998     case CTSF_SUBTABLEPCT_VALIDN:
1999     case CTSF_LAYERPCT_VALIDN:
2000     case CTSF_LAYERROWPCT_VALIDN:
2001     case CTSF_LAYERCOLPCT_VALIDN:
2002     case CTSF_ROWPCT_TOTALN:
2003     case CTSF_COLPCT_TOTALN:
2004     case CTSF_TABLEPCT_TOTALN:
2005     case CTSF_SUBTABLEPCT_TOTALN:
2006     case CTSF_LAYERPCT_TOTALN:
2007     case CTSF_LAYERROWPCT_TOTALN:
2008     case CTSF_LAYERCOLPCT_TOTALN:
2009       NOT_REACHED ();
2010
2011     case CSTF_TOTALN:
2012     case CTSF_ETOTALN:
2013       return s->valid + s->missing;
2014
2015     case CTSF_VALIDN:
2016     case CTSF_EVALIDN:
2017       return s->valid;
2018
2019     case CTSF_MAXIMUM:
2020       return s->max;
2021
2022     case CTSF_MINIMUM:
2023       return s->min;
2024
2025     case CTSF_RANGE:
2026       return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
2027
2028     case CTSF_MEAN:
2029       {
2030         double mean;
2031         moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
2032         return mean;
2033       }
2034
2035     case CTSF_SEMEAN:
2036       {
2037         double weight, variance;
2038         moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
2039         return calc_semean (variance, weight);
2040       }
2041
2042     case CTSF_STDDEV:
2043       {
2044         double variance;
2045         moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2046         return variance != SYSMIS ? sqrt (variance) : SYSMIS;
2047       }
2048
2049     case CTSF_SUM:
2050       {
2051         double weight, mean;
2052         moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
2053         return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
2054       }
2055
2056     case CTSF_VARIANCE:
2057       {
2058         double variance;
2059         moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2060         return variance;
2061       }
2062
2063     case CTSF_ROWPCT_SUM:
2064     case CTSF_COLPCT_SUM:
2065     case CTSF_TABLEPCT_SUM:
2066     case CTSF_SUBTABLEPCT_SUM:
2067     case CTSF_LAYERPCT_SUM:
2068     case CTSF_LAYERROWPCT_SUM:
2069     case CTSF_LAYERCOLPCT_SUM:
2070       NOT_REACHED ();
2071
2072     case CTSF_MEDIAN:
2073     case CTSF_MISSING:
2074     case CTSF_MODE:
2075     case CTSF_PTILE:
2076       NOT_REACHED ();
2077
2078     case CTSF_RESPONSES:
2079     case CTSF_ROWPCT_RESPONSES:
2080     case CTSF_COLPCT_RESPONSES:
2081     case CTSF_TABLEPCT_RESPONSES:
2082     case CTSF_SUBTABLEPCT_RESPONSES:
2083     case CTSF_LAYERPCT_RESPONSES:
2084     case CTSF_LAYERROWPCT_RESPONSES:
2085     case CTSF_LAYERCOLPCT_RESPONSES:
2086     case CTSF_ROWPCT_RESPONSES_COUNT:
2087     case CTSF_COLPCT_RESPONSES_COUNT:
2088     case CTSF_TABLEPCT_RESPONSES_COUNT:
2089     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2090     case CTSF_LAYERPCT_RESPONSES_COUNT:
2091     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2092     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2093     case CTSF_ROWPCT_COUNT_RESPONSES:
2094     case CTSF_COLPCT_COUNT_RESPONSES:
2095     case CTSF_TABLEPCT_COUNT_RESPONSES:
2096     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2097     case CTSF_LAYERPCT_COUNT_RESPONSES:
2098     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2099     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2100       NOT_REACHED ();
2101     }
2102
2103   NOT_REACHED ();
2104 }
2105
2106 struct ctables_cell_sort_aux
2107   {
2108     const struct ctables_table *t;
2109     enum pivot_axis_type a;
2110   };
2111
2112 static int
2113 ctables_cell_compare_3way (const void *a_, const void *b_, const void *aux_)
2114 {
2115   const struct ctables_cell_sort_aux *aux = aux_;
2116   struct ctables_cell *const *ap = a_;
2117   struct ctables_cell *const *bp = b_;
2118   const struct ctables_cell *a = *ap;
2119   const struct ctables_cell *b = *bp;
2120
2121   size_t a_idx = a->axes[aux->a].nest_idx;
2122   size_t b_idx = b->axes[aux->a].nest_idx;
2123   if (a_idx != b_idx)
2124     return a_idx < b_idx ? -1 : 1;
2125
2126   const struct ctables_nest *nest = &aux->t->stacks[aux->a].nests[a_idx];
2127   for (size_t i = 0; i < nest->n; i++)
2128     if (i != nest->scale_idx)
2129       {
2130         const struct variable *var = nest->vars[i];
2131         const struct ctables_cell_value *a_cv = &a->axes[aux->a].cvs[i];
2132         const struct ctables_cell_value *b_cv = &b->axes[aux->a].cvs[i];
2133         if (a_cv->category != b_cv->category)
2134           return a_cv->category > b_cv->category ? 1 : -1;
2135
2136         const union value *a_val = &a_cv->value;
2137         const union value *b_val = &b_cv->value;
2138         switch (a_cv->category->type)
2139           {
2140           case CCT_NUMBER:
2141           case CCT_STRING:
2142           case CCT_SUBTOTAL:
2143           case CCT_HSUBTOTAL:
2144           case CCT_TOTAL:
2145             /* Must be equal. */
2146             continue;
2147
2148           case CCT_RANGE:
2149           case CCT_MISSING:
2150           case CCT_OTHERNM:
2151             {
2152               int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2153               if (cmp)
2154                 return cmp;
2155             }
2156             break;
2157
2158           case CCT_VALUE:
2159             {
2160               int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2161               if (cmp)
2162                 return a_cv->category->sort_ascending ? cmp : -cmp;
2163             }
2164             break;
2165
2166           case CCT_LABEL:
2167             {
2168               const char *a_label = var_lookup_value_label (var, a_val);
2169               const char *b_label = var_lookup_value_label (var, b_val);
2170               int cmp = (a_label
2171                          ? (b_label ? strcmp (a_label, b_label) : 1)
2172                          : (b_label ? -1 : value_compare_3way (
2173                               a_val, b_val, var_get_width (var))));
2174               if (cmp)
2175                 return a_cv->category->sort_ascending ? cmp : -cmp;
2176             }
2177             break;
2178
2179           case CCT_FUNCTION:
2180             NOT_REACHED ();
2181           }
2182       }
2183   return 0;
2184 }
2185
2186 /* Algorithm:
2187
2188    For each row:
2189        For each ctables_table:
2190            For each combination of row vars:
2191                For each combination of column vars:
2192                    For each combination of layer vars:
2193                        Add entry
2194    Make a table of row values:
2195        Sort entries by row values
2196        Assign a 0-based index to each actual value
2197        Construct a dimension
2198    Make a table of column values
2199    Make a table of layer values
2200    For each entry:
2201        Fill the table entry using the indexes from before.
2202  */
2203
2204 static struct ctables_domain *
2205 ctables_domain_insert (struct ctables_table *t, struct ctables_cell *cell,
2206                        enum ctables_domain_type domain)
2207 {
2208   size_t hash = 0;
2209   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2210     {
2211       size_t idx = cell->axes[a].nest_idx;
2212       const struct ctables_nest *nest = &t->stacks[a].nests[idx];
2213       hash = hash_int (idx, hash);
2214       for (size_t i = 0; i < nest->n_domains[domain]; i++)
2215         {
2216           size_t v_idx = nest->domains[domain][i];
2217           hash = value_hash (&cell->axes[a].cvs[v_idx].value,
2218                              var_get_width (nest->vars[v_idx]), hash);
2219         }
2220     }
2221
2222   struct ctables_domain *d;
2223   HMAP_FOR_EACH_WITH_HASH (d, struct ctables_domain, node, hash, &t->domains[domain])
2224     {
2225       const struct ctables_cell *df = d->example;
2226       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2227         {
2228           size_t idx = cell->axes[a].nest_idx;
2229           if (idx != df->axes[a].nest_idx)
2230             goto not_equal;
2231
2232           const struct ctables_nest *nest = &t->stacks[a].nests[idx];
2233           for (size_t i = 0; i < nest->n_domains[domain]; i++)
2234             {
2235               size_t v_idx = nest->domains[domain][i];
2236               if (!value_equal (&df->axes[a].cvs[v_idx].value,
2237                                 &cell->axes[a].cvs[v_idx].value,
2238                                 var_get_width (nest->vars[v_idx])))
2239                 goto not_equal;
2240             }
2241         }
2242       return d;
2243
2244     not_equal: ;
2245     }
2246
2247   d = xmalloc (sizeof *d);
2248   *d = (struct ctables_domain) { .example = cell };
2249   hmap_insert (&t->domains[domain], &d->node, hash);
2250   return d;
2251 }
2252
2253 static const struct ctables_category *
2254 ctables_categories_match (const struct ctables_categories *c,
2255                           const union value *v, const struct variable *var)
2256 {
2257   const struct ctables_category *othernm = NULL;
2258   for (size_t i = c->n_cats; i-- > 0; )
2259     {
2260       const struct ctables_category *cat = &c->cats[i];
2261       switch (cat->type)
2262         {
2263         case CCT_NUMBER:
2264           if (cat->number == v->f)
2265             return cat;
2266           break;
2267
2268         case CCT_STRING:
2269           NOT_REACHED ();
2270
2271         case CCT_RANGE:
2272           if ((cat->range[0] == -DBL_MAX || v->f >= cat->range[0])
2273               && (cat->range[1] == DBL_MAX || v->f <= cat->range[1]))
2274             return cat;
2275           break;
2276
2277         case CCT_MISSING:
2278           if (var_is_value_missing (var, v))
2279             return cat;
2280           break;
2281
2282         case CCT_OTHERNM:
2283           if (!othernm)
2284             othernm = cat;
2285           break;
2286
2287         case CCT_SUBTOTAL:
2288         case CCT_HSUBTOTAL:
2289         case CCT_TOTAL:
2290           break;
2291
2292         case CCT_VALUE:
2293         case CCT_LABEL:
2294         case CCT_FUNCTION:
2295           return (cat->include_missing || !var_is_value_missing (var, v) ? cat
2296                   : NULL);
2297         }
2298     }
2299
2300   return var_is_value_missing (var, v) ? NULL : othernm;
2301 }
2302
2303 static const struct ctables_category *
2304 ctables_categories_total (const struct ctables_categories *c)
2305 {
2306   const struct ctables_category *first = &c->cats[0];
2307   const struct ctables_category *last = &c->cats[c->n_cats - 1];
2308   return (first->type == CCT_TOTAL ? first
2309           : last->type == CCT_TOTAL ? last
2310           : NULL);
2311 }
2312
2313 static struct ctables_cell *
2314 ctables_cell_insert__ (struct ctables_table *t, const struct ccase *c,
2315                        size_t ix[PIVOT_N_AXES],
2316                        const struct ctables_category *cats[PIVOT_N_AXES][10])
2317 {
2318   const struct ctables_nest *ss = &t->stacks[t->summary_axis].nests[ix[t->summary_axis]];
2319
2320   size_t hash = 0;
2321   enum ctables_summary_variant sv = CSV_CELL;
2322   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2323     {
2324       const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2325       hash = hash_int (ix[a], hash);
2326       for (size_t i = 0; i < nest->n; i++)
2327         if (i != nest->scale_idx)
2328           {
2329             hash = hash_pointer (cats[a][i], hash);
2330             if (cats[a][i]->type != CCT_TOTAL
2331                 && cats[a][i]->type != CCT_SUBTOTAL
2332                 && cats[a][i]->type != CCT_HSUBTOTAL)
2333               hash = value_hash (case_data (c, nest->vars[i]),
2334                                  var_get_width (nest->vars[i]), hash);
2335             else
2336               sv = CSV_TOTAL;
2337           }
2338     }
2339
2340   struct ctables_cell *cell;
2341   HMAP_FOR_EACH_WITH_HASH (cell, struct ctables_cell, node, hash, &t->cells)
2342     {
2343       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2344         {
2345           const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2346           if (cell->axes[a].nest_idx != ix[a])
2347             goto not_equal;
2348           for (size_t i = 0; i < nest->n; i++)
2349             if (i != nest->scale_idx
2350                 && (cats[a][i] != cell->axes[a].cvs[i].category
2351                     || (cats[a][i]->type != CCT_TOTAL
2352                         && cats[a][i]->type != CCT_SUBTOTAL
2353                         && cats[a][i]->type != CCT_HSUBTOTAL
2354                         && !value_equal (case_data (c, nest->vars[i]),
2355                                          &cell->axes[a].cvs[i].value,
2356                                          var_get_width (nest->vars[i])))))
2357                 goto not_equal;
2358         }
2359
2360       return cell;
2361
2362     not_equal: ;
2363     }
2364
2365   cell = xmalloc (sizeof *cell);
2366   cell->hide = false;
2367   cell->sv = sv;
2368   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2369     {
2370       const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2371       cell->axes[a].nest_idx = ix[a];
2372       cell->axes[a].cvs = (nest->n
2373                         ? xnmalloc (nest->n, sizeof *cell->axes[a].cvs)
2374                         : NULL);
2375       for (size_t i = 0; i < nest->n; i++)
2376         {
2377           if (i != nest->scale_idx)
2378             {
2379               const struct ctables_category *subtotal = cats[a][i]->subtotal;
2380               if (subtotal && subtotal->type == CCT_HSUBTOTAL)
2381                 cell->hide = true;
2382             }
2383
2384           cell->axes[a].cvs[i].category = cats[a][i];
2385           value_clone (&cell->axes[a].cvs[i].value, case_data (c, nest->vars[i]),
2386                        var_get_width (nest->vars[i]));
2387         }
2388     }
2389
2390   const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2391   cell->summaries = xmalloc (specs->n * sizeof *cell->summaries);
2392   for (size_t i = 0; i < specs->n; i++)
2393     ctables_summary_init (&cell->summaries[i], &specs->specs[i]);
2394   for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2395     cell->domains[dt] = ctables_domain_insert (t, cell, dt);
2396   hmap_insert (&t->cells, &cell->node, hash);
2397   return cell;
2398 }
2399
2400 static void
2401 ctables_cell_add__ (struct ctables_table *t, const struct ccase *c,
2402                     size_t ix[PIVOT_N_AXES],
2403                     const struct ctables_category *cats[PIVOT_N_AXES][10],
2404                     double weight)
2405 {
2406   struct ctables_cell *cell = ctables_cell_insert__ (t, c, ix, cats);
2407   const struct ctables_nest *ss = &t->stacks[t->summary_axis].nests[ix[t->summary_axis]];
2408
2409   const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2410   for (size_t i = 0; i < specs->n; i++)
2411     ctables_summary_add (&cell->summaries[i], &specs->specs[i], specs->var,
2412                          case_data (c, specs->var), weight);
2413   for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2414     cell->domains[dt]->valid += weight;
2415 }
2416
2417 static void
2418 recurse_totals (struct ctables_table *t, const struct ccase *c,
2419                 size_t ix[PIVOT_N_AXES],
2420                 const struct ctables_category *cats[PIVOT_N_AXES][10],
2421                 double weight,
2422                 enum pivot_axis_type start_axis, size_t start_nest)
2423 {
2424   for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2425     {
2426       const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2427       for (size_t i = start_nest; i < nest->n; i++)
2428         {
2429           if (i == nest->scale_idx)
2430             continue;
2431
2432           const struct variable *var = nest->vars[i];
2433
2434           const struct ctables_category *total = ctables_categories_total (
2435             t->categories[var_get_dict_index (var)]);
2436           if (total)
2437             {
2438               const struct ctables_category *save = cats[a][i];
2439               cats[a][i] = total;
2440               ctables_cell_add__ (t, c, ix, cats, weight);
2441               recurse_totals (t, c, ix, cats, weight, a, i + 1);
2442               cats[a][i] = save;
2443             }
2444         }
2445       start_nest = 0;
2446     }
2447 }
2448
2449 static void
2450 ctables_cell_insert (struct ctables_table *t,
2451                      const struct ccase *c,
2452                      size_t ir, size_t ic, size_t il,
2453                      double weight)
2454 {
2455   size_t ix[PIVOT_N_AXES] = {
2456     [PIVOT_AXIS_ROW] = ir,
2457     [PIVOT_AXIS_COLUMN] = ic,
2458     [PIVOT_AXIS_LAYER] = il,
2459   };
2460
2461   const struct ctables_category *cats[PIVOT_N_AXES][10];
2462   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2463     {
2464       const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2465       for (size_t i = 0; i < nest->n; i++)
2466         {
2467           if (i == nest->scale_idx)
2468             continue;
2469
2470           const struct variable *var = nest->vars[i];
2471           const union value *value = case_data (c, var);
2472
2473           if (var_is_numeric (var) && value->f == SYSMIS)
2474             return;
2475
2476           cats[a][i] = ctables_categories_match (
2477             t->categories[var_get_dict_index (var)], value, var);
2478           if (!cats[a][i])
2479             return;
2480         }
2481     }
2482
2483   ctables_cell_add__ (t, c, ix, cats, weight);
2484
2485   recurse_totals (t, c, ix, cats, weight, 0, 0);
2486
2487   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2488     {
2489       const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2490       for (size_t i = 0; i < nest->n; i++)
2491         {
2492           if (i == nest->scale_idx)
2493             continue;
2494
2495           const struct ctables_category *save = cats[a][i];
2496           if (save->subtotal)
2497             {
2498               cats[a][i] = save->subtotal;
2499               ctables_cell_add__ (t, c, ix, cats, weight);
2500               cats[a][i] = save;
2501             }
2502         }
2503     }
2504 }
2505
2506 struct merge_item
2507   {
2508     const struct ctables_summary_spec_set *set;
2509     size_t ofs;
2510   };
2511
2512 static int
2513 merge_item_compare_3way (const struct merge_item *a, const struct merge_item *b)
2514 {
2515   const struct ctables_summary_spec *as = &a->set->specs[a->ofs];
2516   const struct ctables_summary_spec *bs = &b->set->specs[b->ofs];
2517   if (as->function != bs->function)
2518     return as->function > bs->function ? 1 : -1;
2519   else if (as->percentile != bs->percentile)
2520     return as->percentile < bs->percentile ? 1 : -1;
2521   return strcmp (as->label, bs->label);
2522 }
2523
2524 static struct pivot_value *
2525 ctables_category_create_label (const struct ctables_category *cat,
2526                                const struct variable *var,
2527                                const union value *value)
2528 {
2529   return (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL
2530           ? pivot_value_new_user_text (cat->total_label, SIZE_MAX)
2531           : pivot_value_new_var_value (var, value));
2532 }
2533
2534 static struct ctables_value *
2535 ctables_value_find__ (struct ctables_table *t, const union value *value,
2536                       int width, unsigned int hash)
2537 {
2538   struct ctables_value *clv;
2539   HMAP_FOR_EACH_WITH_HASH (clv, struct ctables_value, node,
2540                            hash, &t->clabels_values_map)
2541     if (value_equal (value, &clv->value, width))
2542       return clv;
2543   return NULL;
2544 }
2545
2546 static struct ctables_value *
2547 ctables_value_find (struct ctables_table *t,
2548                     const union value *value, int width)
2549 {
2550   return ctables_value_find__ (t, value, width,
2551                                value_hash (value, width, 0));
2552 }
2553
2554 static void
2555 ctables_table_output (struct ctables *ct, struct ctables_table *t)
2556 {
2557   struct pivot_table *pt = pivot_table_create__ (
2558     (t->title
2559      ? pivot_value_new_user_text (t->title, SIZE_MAX)
2560      : pivot_value_new_text (N_("Custom Tables"))),
2561     "Custom Tables");
2562   if (t->caption)
2563     pivot_table_set_caption (
2564       pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
2565   if (t->corner)
2566     pivot_table_set_caption (
2567       pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
2568
2569   bool summary_dimension = t->summary_axis != t->slabels_axis;
2570   if (summary_dimension)
2571     {
2572       struct pivot_dimension *d = pivot_dimension_create (
2573         pt, t->slabels_axis, N_("Summaries"));
2574       const struct ctables_summary_spec_set *specs = &t->summary_specs;
2575       for (size_t i = 0; i < specs->n; i++)
2576         pivot_category_create_leaf (
2577           d->root, pivot_value_new_text (specs->specs[i].label));
2578     }
2579
2580   bool categories_dimension = t->clabels_example != NULL;
2581   if (categories_dimension)
2582     {
2583       struct pivot_dimension *d = pivot_dimension_create (
2584         pt, t->label_axis[t->clabels_from_axis],
2585         t->clabels_from_axis == PIVOT_AXIS_ROW
2586         ? N_("Row Categories")
2587         : N_("Column Categories"));
2588       const struct variable *var = t->clabels_example;
2589       const struct ctables_categories *c = t->categories[var_get_dict_index (var)];
2590       for (size_t i = 0; i < t->n_clabels_values; i++)
2591         {
2592           const struct ctables_value *value = t->clabels_values[i];
2593           const struct ctables_category *cat = ctables_categories_match (c, &value->value, var);
2594           assert (cat != NULL);
2595           pivot_category_create_leaf (d->root, ctables_category_create_label (
2596                                         cat, t->clabels_example, &value->value));
2597         }
2598     }
2599
2600   pivot_table_set_look (pt, ct->look);
2601   struct pivot_dimension *d[PIVOT_N_AXES];
2602   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2603     {
2604       static const char *names[] = {
2605         [PIVOT_AXIS_ROW] = N_("Rows"),
2606         [PIVOT_AXIS_COLUMN] = N_("Columns"),
2607         [PIVOT_AXIS_LAYER] = N_("Layers"),
2608       };
2609       d[a] = (t->axes[a] || a == t->summary_axis
2610               ? pivot_dimension_create (pt, a, names[a])
2611               : NULL);
2612       if (!d[a])
2613         continue;
2614
2615       assert (t->axes[a]);
2616
2617       struct ctables_cell **sorted = xnmalloc (t->cells.count, sizeof *sorted);
2618       size_t n_sorted = 0;
2619
2620       struct ctables_cell *cell;
2621       HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2622         if (!cell->hide)
2623           sorted[n_sorted++] = cell;
2624       assert (n_sorted <= t->cells.count);
2625
2626       struct ctables_cell_sort_aux aux = { .t = t, .a = a };
2627       sort (sorted, n_sorted, sizeof *sorted, ctables_cell_compare_3way, &aux);
2628
2629       size_t max_depth = 0;
2630       for (size_t j = 0; j < t->stacks[a].n; j++)
2631         if (t->stacks[a].nests[j].n > max_depth)
2632           max_depth = t->stacks[a].nests[j].n;
2633
2634       /* Pivot categories:
2635
2636          - variable label for nest->vars[0], if vlabel != CTVL_NONE
2637          - category for nest->vars[0], if nest->scale_idx != 0
2638          - variable label for nest->vars[1], if vlabel != CTVL_NONE
2639          - category for nest->vars[1], if nest->scale_idx != 1
2640          ...
2641          - variable label for nest->vars[n - 1], if vlabel != CTVL_NONE
2642          - category for nest->vars[n - 1], if t->label_axis[a] == a && nest->scale_idx != n - 1.
2643          - summary function, if 'a == t->slabels_axis && a ==
2644          t->summary_axis'.
2645
2646          Additional dimensions:
2647
2648          - If 'a == t->slabels_axis && a != t->summary_axis', add a summary
2649          dimension.
2650          - If 't->label_axis[b] == a' for some 'b != a', add a category
2651          dimension to 'a'.
2652       */
2653
2654       struct ctables_level
2655         {
2656           enum ctables_level_type
2657             {
2658               CTL_VAR,          /* Variable label for nest->vars[var_idx]. */
2659               CTL_CATEGORY,     /* Category for nest->vars[var_idx]. */
2660               CTL_SUMMARY,      /* Summary functions. */
2661             }
2662           type;
2663
2664           size_t var_idx;
2665         };
2666       struct ctables_level *levels = xnmalloc (1 + 2 * max_depth, sizeof *levels);
2667       size_t n_levels = 0;
2668
2669       struct pivot_category **groups = xnmalloc (1 + 2 * max_depth, sizeof *groups);
2670       int prev_leaf = 0;
2671       for (size_t j = 0; j < n_sorted; j++)
2672         {
2673           struct ctables_cell *cell = sorted[j];
2674           struct ctables_cell *prev = j > 0 ? sorted[j - 1] : NULL;
2675           const struct ctables_nest *nest = &t->stacks[a].nests[cell->axes[a].nest_idx];
2676
2677           bool new_subtable = !prev || prev->axes[a].nest_idx != cell->axes[a].nest_idx;
2678           if (new_subtable)
2679             {
2680               n_levels = 0;
2681               printf ("%s levels:", pivot_axis_type_to_string (a));
2682               for (size_t k = 0; k < nest->n; k++)
2683                 {
2684                   enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k])];
2685                   if (vlabel != CTVL_NONE)
2686                     {
2687                       printf (" var(%s)", var_get_name (nest->vars[k]));
2688                       levels[n_levels++] = (struct ctables_level) {
2689                         .type = CTL_VAR,
2690                         .var_idx = k,
2691                       };
2692                     }
2693
2694                   if (nest->scale_idx != k
2695                       && (k != nest->n - 1 || t->label_axis[a] == a))
2696                     {
2697                       printf (" category(%s)", var_get_name (nest->vars[k]));
2698                       levels[n_levels++] = (struct ctables_level) {
2699                         .type = CTL_CATEGORY,
2700                         .var_idx = k,
2701                       };
2702                     }
2703                 }
2704
2705               if (a == t->slabels_axis && a == t->summary_axis)
2706                 {
2707                   printf (" summary");
2708                   levels[n_levels++] = (struct ctables_level) {
2709                     .type = CTL_SUMMARY,
2710                     .var_idx = SIZE_MAX,
2711                   };
2712                 }
2713               printf ("\n");
2714             }
2715
2716           size_t n_common = 0;
2717           if (!new_subtable)
2718             {
2719               for (; n_common < n_levels; n_common++)
2720                 {
2721                   const struct ctables_level *level = &levels[n_common];
2722                   if (level->type == CTL_CATEGORY)
2723                     {
2724                       size_t var_idx = level->var_idx;
2725                       if (prev->axes[a].cvs[var_idx].category
2726                           != cell->axes[a].cvs[var_idx].category)
2727                         {
2728                           break;
2729                         }
2730                       else if (!value_equal (&prev->axes[a].cvs[var_idx].value,
2731                                            &cell->axes[a].cvs[var_idx].value,
2732                                              var_get_type (nest->vars[var_idx])))
2733                         {
2734                           break;
2735                         }
2736                     }
2737                 }
2738             }
2739
2740           for (size_t k = n_common; k < n_levels; k++)
2741             {
2742               const struct ctables_level *level = &levels[k];
2743               struct pivot_category *parent = k ? groups[k - 1] : d[a]->root;
2744               if (level->type == CTL_SUMMARY)
2745                 {
2746                   const struct ctables_summary_spec_set *specs = &t->summary_specs;
2747                   for (size_t m = 0; m < specs->n; m++)
2748                     {
2749                       int leaf = pivot_category_create_leaf (
2750                         parent, pivot_value_new_text (specs->specs[m].label));
2751                       if (!m)
2752                         prev_leaf = leaf;
2753                     }
2754                 }
2755               else
2756                 {
2757                   const struct variable *var = nest->vars[level->var_idx];
2758                   struct pivot_value *label;
2759                   if (level->type == CTL_VAR)
2760                     label = pivot_value_new_variable (var);
2761                   else if (level->type == CTL_CATEGORY)
2762                     {
2763                       const struct ctables_cell_value *cv = &cell->axes[a].cvs[level->var_idx];
2764                       label = ctables_category_create_label (cv->category,
2765                                                              var, &cv->value);
2766                     }
2767                   else
2768                     NOT_REACHED ();
2769
2770                   if (k == n_levels - 1)
2771                     prev_leaf = pivot_category_create_leaf (parent, label);
2772                   else
2773                     groups[k] = pivot_category_create_group__ (parent, label);
2774                 }
2775             }
2776
2777           cell->axes[a].leaf = prev_leaf;
2778         }
2779       free (sorted);
2780       free (groups);
2781     }
2782
2783   struct ctables_cell *cell;
2784   HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2785     {
2786       if (cell->hide)
2787         continue;
2788
2789       const struct ctables_nest *specs_nest = &t->stacks[t->summary_axis].nests[cell->axes[t->summary_axis].nest_idx];
2790       const struct ctables_summary_spec_set *specs = &specs_nest->specs[cell->sv];
2791       for (size_t j = 0; j < specs->n; j++)
2792         {
2793           size_t dindexes[5];
2794           size_t n_dindexes = 0;
2795
2796           if (summary_dimension)
2797             dindexes[n_dindexes++] = specs->specs[j].axis_idx;
2798
2799           if (categories_dimension)
2800             {
2801               const struct ctables_nest *clabels_nest = &t->stacks[t->clabels_from_axis].nests[cell->axes[t->clabels_from_axis].nest_idx];
2802               const struct variable *var = clabels_nest->vars[clabels_nest->n - 1];
2803               const union value *value = &cell->axes[t->clabels_from_axis].cvs[clabels_nest->n - 1].value;
2804               const struct ctables_value *ctv = ctables_value_find (t, value, var_get_width (var));
2805               assert (ctv != NULL);
2806               dindexes[n_dindexes++] = ctv->leaf;
2807             }
2808
2809           for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2810             if (d[a])
2811               {
2812                 int leaf = cell->axes[a].leaf;
2813                 if (a == t->summary_axis && !summary_dimension)
2814                   leaf += j;
2815                 dindexes[n_dindexes++] = leaf;
2816               }
2817
2818           double d = ctables_summary_value (cell, &cell->summaries[j], &specs->specs[j]);
2819           struct pivot_value *value = pivot_value_new_number (d);
2820           value->numeric.format = specs->specs[j].format;
2821           pivot_table_put (pt, dindexes, n_dindexes, value);
2822         }
2823     }
2824
2825   pivot_table_submit (pt);
2826 }
2827
2828 static bool
2829 ctables_check_label_position (struct ctables_table *t, enum pivot_axis_type a)
2830 {
2831   enum pivot_axis_type label_pos = t->label_axis[a];
2832   if (label_pos == a)
2833     return true;
2834
2835   t->clabels_from_axis = a;
2836
2837   const char *subcommand_name = a == PIVOT_AXIS_ROW ? "ROWLABELS" : "COLLABELS";
2838   const char *pos_name = label_pos == PIVOT_AXIS_LAYER ? "LAYER" : "OPPOSITE";
2839
2840   const struct ctables_stack *stack = &t->stacks[a];
2841   if (!stack->n)
2842     return true;
2843
2844   const struct ctables_nest *n0 = &stack->nests[0];
2845   assert (n0->n > 0);
2846   const struct variable *v0 = n0->vars[n0->n - 1];
2847   struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
2848   t->clabels_example = v0;
2849
2850   for (size_t i = 0; i < c0->n_cats; i++)
2851     if (c0->cats[i].type == CCT_FUNCTION)
2852       {
2853         msg (SE, _("%s=%s is not allowed with sorting based "
2854                    "on a summary function."),
2855              subcommand_name, pos_name);
2856         return false;
2857       }
2858   if (n0->n - 1 == n0->scale_idx)
2859     {
2860       msg (SE, _("%s=%s requires the variables to be moved to be categorical, "
2861                  "but %s is a scale variable."),
2862            subcommand_name, pos_name, var_get_name (v0));
2863       return false;
2864     }
2865
2866   for (size_t i = 1; i < stack->n; i++)
2867     {
2868       const struct ctables_nest *ni = &stack->nests[i];
2869       assert (ni->n > 0);
2870       const struct variable *vi = ni->vars[ni->n - 1];
2871       struct ctables_categories *ci = t->categories[var_get_dict_index (vi)];
2872
2873       if (ni->n - 1 == ni->scale_idx)
2874         {
2875           msg (SE, _("%s=%s requires the variables to be moved to be "
2876                      "categorical, but %s is a scale variable."),
2877                subcommand_name, pos_name, var_get_name (vi));
2878           return false;
2879         }
2880       if (var_get_width (v0) != var_get_width (vi))
2881         {
2882           msg (SE, _("%s=%s requires the variables to be "
2883                      "moved to have the same width, but %s has "
2884                      "width %d and %s has width %d."),
2885                subcommand_name, pos_name,
2886                var_get_name (v0), var_get_width (v0),
2887                var_get_name (vi), var_get_width (vi));
2888           return false;
2889         }
2890       if (!val_labs_equal (var_get_value_labels (v0),
2891                            var_get_value_labels (vi)))
2892         {
2893           msg (SE, _("%s=%s requires the variables to be "
2894                      "moved to have the same value labels, but %s "
2895                      "and %s have different value labels."),
2896                subcommand_name, pos_name,
2897                var_get_name (v0), var_get_name (vi));
2898           return false;
2899         }
2900       if (!ctables_categories_equal (c0, ci))
2901         {
2902           msg (SE, _("%s=%s requires the variables to be "
2903                      "moved to have the same category "
2904                      "specifications, but %s and %s have different "
2905                      "category specifications."),
2906                subcommand_name, pos_name,
2907                var_get_name (v0), var_get_name (vi));
2908           return false;
2909         }
2910     }
2911
2912   return true;
2913 }
2914
2915 static bool
2916 ctables_prepare_table (struct ctables_table *t)
2917 {
2918   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2919     if (t->axes[a])
2920       {
2921         t->stacks[a] = enumerate_fts (a, t->axes[a]);
2922
2923         for (size_t j = 0; j < t->stacks[a].n; j++)
2924           {
2925             struct ctables_nest *nest = &t->stacks[a].nests[j];
2926             for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2927               {
2928                 nest->domains[dt] = xmalloc (nest->n * sizeof *nest->domains[dt]);
2929                 nest->n_domains[dt] = 0;
2930
2931                 for (size_t k = 0; k < nest->n; k++)
2932                   {
2933                     if (k == nest->scale_idx)
2934                       continue;
2935
2936                     switch (dt)
2937                       {
2938                       case CTDT_TABLE:
2939                         continue;
2940
2941                       case CTDT_LAYER:
2942                         if (a != PIVOT_AXIS_LAYER)
2943                           continue;
2944                         break;
2945
2946                       case CTDT_SUBTABLE:
2947                       case CTDT_ROW:
2948                       case CTDT_COL:
2949                         if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
2950                             : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
2951                             : a == PIVOT_AXIS_ROW)
2952                           {
2953                             if (k == nest->n - 1
2954                                 || (nest->scale_idx == nest->n - 1
2955                                     && k == nest->n - 2))
2956                               continue;
2957                           }
2958                         break;
2959
2960                       case CTDT_LAYERROW:
2961                         if (a == PIVOT_AXIS_COLUMN)
2962                           continue;
2963                         break;
2964
2965                       case CTDT_LAYERCOL:
2966                         if (a == PIVOT_AXIS_ROW)
2967                           continue;
2968                         break;
2969                       }
2970
2971                     nest->domains[dt][nest->n_domains[dt]++] = k;
2972                   }
2973               }
2974           }
2975       }
2976     else
2977       {
2978         struct ctables_nest *nest = xmalloc (sizeof *nest);
2979         *nest = (struct ctables_nest) { .n = 0 };
2980         t->stacks[a] = (struct ctables_stack) { .nests = nest, .n = 1 };
2981       }
2982
2983   struct ctables_stack *stack = &t->stacks[t->summary_axis];
2984   for (size_t i = 0; i < stack->n; i++)
2985     {
2986       struct ctables_nest *nest = &stack->nests[i];
2987       if (!nest->specs[CSV_CELL].n)
2988         {
2989           struct ctables_summary_spec_set *specs = &nest->specs[CSV_CELL];
2990           specs->specs = xmalloc (sizeof *specs->specs);
2991           specs->n = 1;
2992
2993           enum ctables_summary_function function
2994             = specs->var ? CTSF_MEAN : CTSF_COUNT;
2995           struct ctables_var var = { .is_mrset = false, .var = specs->var };
2996
2997           *specs->specs = (struct ctables_summary_spec) {
2998             .function = function,
2999             .format = ctables_summary_default_format (function, &var),
3000             .label = ctables_summary_default_label (function, 0),
3001           };
3002           if (!specs->var)
3003             specs->var = nest->vars[0];
3004
3005           ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3006                                           &nest->specs[CSV_CELL]);
3007         }
3008       else if (!nest->specs[CSV_TOTAL].n)
3009         ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3010                                         &nest->specs[CSV_CELL]);
3011     }
3012
3013   struct ctables_summary_spec_set *merged = &t->summary_specs;
3014   struct merge_item *items = xnmalloc (2 * stack->n, sizeof *items);
3015   size_t n_left = 0;
3016   for (size_t j = 0; j < stack->n; j++)
3017     {
3018       const struct ctables_nest *nest = &stack->nests[j];
3019       if (nest->n)
3020         for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3021           items[n_left++] = (struct merge_item) { .set = &nest->specs[sv] };
3022     }
3023
3024   while (n_left > 0)
3025     {
3026       struct merge_item min = items[0];
3027       for (size_t j = 1; j < n_left; j++)
3028         if (merge_item_compare_3way (&items[j], &min) < 0)
3029           min = items[j];
3030
3031       if (merged->n >= merged->allocated)
3032         merged->specs = x2nrealloc (merged->specs, &merged->allocated,
3033                                     sizeof *merged->specs);
3034       merged->specs[merged->n++] = min.set->specs[min.ofs];
3035
3036       for (size_t j = 0; j < n_left; )
3037         {
3038           if (merge_item_compare_3way (&items[j], &min) == 0)
3039             {
3040               struct merge_item *item = &items[j];
3041               item->set->specs[item->ofs].axis_idx = merged->n - 1;
3042               if (++item->ofs >= item->set->n)
3043                 {
3044                   items[j] = items[--n_left];
3045                   continue;
3046                 }
3047             }
3048           j++;
3049         }
3050     }
3051
3052 #if 0
3053   for (size_t j = 0; j < merged->n; j++)
3054     printf ("%s\n", ctables_summary_function_name (merged->specs[j].function));
3055
3056   for (size_t j = 0; j < stack->n; j++)
3057     {
3058       const struct ctables_nest *nest = &stack->nests[j];
3059       for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3060         {
3061           const struct ctables_summary_spec_set *specs = &nest->specs[sv];
3062           for (size_t k = 0; k < specs->n; k++)
3063             printf ("(%s, %zu) ", ctables_summary_function_name (specs->specs[k].function),
3064                     specs->specs[k].axis_idx);
3065           printf ("\n");
3066         }
3067     }
3068 #endif
3069
3070   return (ctables_check_label_position (t, PIVOT_AXIS_ROW)
3071           && ctables_check_label_position (t, PIVOT_AXIS_COLUMN));
3072 }
3073
3074 static void
3075 ctables_insert_clabels_values (struct ctables_table *t, const struct ccase *c,
3076                                enum pivot_axis_type a)
3077 {
3078   struct ctables_stack *stack = &t->stacks[a];
3079   for (size_t i = 0; i < stack->n; i++)
3080     {
3081       const struct ctables_nest *nest = &stack->nests[i];
3082       const struct variable *var = nest->vars[nest->n - 1];
3083       int width = var_get_width (var);
3084       const union value *value = case_data (c, var);
3085
3086       if (var_is_numeric (var) && value->f == SYSMIS)
3087         continue;
3088
3089       if (!ctables_categories_match (t->categories [var_get_dict_index (var)],
3090                                      value, var))
3091         continue;
3092
3093       unsigned int hash = value_hash (value, width, 0);
3094
3095       struct ctables_value *clv = ctables_value_find__ (t, value, width, hash);
3096       if (!clv)
3097         {
3098           clv = xmalloc (sizeof *clv);
3099           value_clone (&clv->value, value, width);
3100           hmap_insert (&t->clabels_values_map, &clv->node, hash);
3101         }
3102     }
3103 }
3104
3105 static int
3106 compare_clabels_values_3way (const void *a_, const void *b_, const void *width_)
3107 {
3108   const struct ctables_value *const *ap = a_;
3109   const struct ctables_value *const *bp = b_;
3110   const struct ctables_value *a = *ap;
3111   const struct ctables_value *b = *bp;
3112   const int *width = width_;
3113   return value_compare_3way (&a->value, &b->value, *width);
3114 }
3115
3116 static void
3117 ctables_sort_clabels_values (struct ctables_table *t)
3118 {
3119   int width = var_get_width (t->clabels_example);
3120
3121   size_t n = hmap_count (&t->clabels_values_map);
3122   t->clabels_values = xnmalloc (n, sizeof *t->clabels_values);
3123
3124   struct ctables_value *clv;
3125   size_t i = 0;
3126   HMAP_FOR_EACH (clv, struct ctables_value, node, &t->clabels_values_map)
3127     t->clabels_values[i++] = clv;
3128   t->n_clabels_values = n;
3129   assert (i == n);
3130
3131   sort (t->clabels_values, n, sizeof *t->clabels_values,
3132         compare_clabels_values_3way, &width);
3133
3134   for (size_t i = 0; i < n; i++)
3135     t->clabels_values[i]->leaf = i;
3136 }
3137
3138 static bool
3139 ctables_execute (struct dataset *ds, struct ctables *ct)
3140 {
3141   struct casereader *input = casereader_create_filter_weight (proc_open (ds),
3142                                                               dataset_dict (ds),
3143                                                               NULL, NULL);
3144   bool warn_on_invalid = true;
3145   double total_weight = 0;
3146   for (struct ccase *c = casereader_read (input); c;
3147        case_unref (c), c = casereader_read (input))
3148     {
3149       double weight = dict_get_case_weight (dataset_dict (ds), c,
3150                                             &warn_on_invalid);
3151       total_weight += weight;
3152
3153       for (size_t i = 0; i < ct->n_tables; i++)
3154         {
3155           struct ctables_table *t = ct->tables[i];
3156
3157           for (size_t ir = 0; ir < t->stacks[PIVOT_AXIS_ROW].n; ir++)
3158             for (size_t ic = 0; ic < t->stacks[PIVOT_AXIS_COLUMN].n; ic++)
3159               for (size_t il = 0; il < t->stacks[PIVOT_AXIS_LAYER].n; il++)
3160                 ctables_cell_insert (t, c, ir, ic, il, weight);
3161
3162           for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3163             if (t->label_axis[a] != a)
3164               ctables_insert_clabels_values (t, c, a);
3165         }
3166     }
3167   casereader_destroy (input);
3168
3169   for (size_t i = 0; i < ct->n_tables; i++)
3170     {
3171       struct ctables_table *t = ct->tables[i];
3172
3173       if (t->clabels_example)
3174         ctables_sort_clabels_values (t);
3175
3176       ctables_table_output (ct, ct->tables[i]);
3177     }
3178   return proc_commit (ds);
3179 }
3180
3181 int
3182 cmd_ctables (struct lexer *lexer, struct dataset *ds)
3183 {
3184   size_t n_vars = dict_get_n_vars (dataset_dict (ds));
3185   enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
3186   enum settings_value_show tvars = settings_get_show_variables ();
3187   for (size_t i = 0; i < n_vars; i++)
3188     vlabels[i] = (enum ctables_vlabel) tvars;
3189
3190   struct ctables *ct = xmalloc (sizeof *ct);
3191   *ct = (struct ctables) {
3192     .look = pivot_table_look_unshare (pivot_table_look_ref (
3193                                         pivot_table_look_get_default ())),
3194     .vlabels = vlabels,
3195     .hide_threshold = 5,
3196   };
3197   ct->look->omit_empty = false;
3198
3199   if (!lex_force_match (lexer, T_SLASH))
3200     goto error;
3201
3202   while (!lex_match_id (lexer, "TABLE"))
3203     {
3204       if (lex_match_id (lexer, "FORMAT"))
3205         {
3206           double widths[2] = { SYSMIS, SYSMIS };
3207           double units_per_inch = 72.0;
3208
3209           while (lex_token (lexer) != T_SLASH)
3210             {
3211               if (lex_match_id (lexer, "MINCOLWIDTH"))
3212                 {
3213                   if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
3214                     goto error;
3215                 }
3216               else if (lex_match_id (lexer, "MAXCOLWIDTH"))
3217                 {
3218                   if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
3219                     goto error;
3220                 }
3221               else if (lex_match_id (lexer, "UNITS"))
3222                 {
3223                   lex_match (lexer, T_EQUALS);
3224                   if (lex_match_id (lexer, "POINTS"))
3225                     units_per_inch = 72.0;
3226                   else if (lex_match_id (lexer, "INCHES"))
3227                     units_per_inch = 1.0;
3228                   else if (lex_match_id (lexer, "CM"))
3229                     units_per_inch = 2.54;
3230                   else
3231                     {
3232                       lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
3233                       goto error;
3234                     }
3235                 }
3236               else if (lex_match_id (lexer, "EMPTY"))
3237                 {
3238                   free (ct->zero);
3239                   ct->zero = NULL;
3240
3241                   lex_match (lexer, T_EQUALS);
3242                   if (lex_match_id (lexer, "ZERO"))
3243                     {
3244                       /* Nothing to do. */
3245                     }
3246                   else if (lex_match_id (lexer, "BLANK"))
3247                     ct->zero = xstrdup ("");
3248                   else if (lex_force_string (lexer))
3249                     {
3250                       ct->zero = ss_xstrdup (lex_tokss (lexer));
3251                       lex_get (lexer);
3252                     }
3253                   else
3254                     goto error;
3255                 }
3256               else if (lex_match_id (lexer, "MISSING"))
3257                 {
3258                   lex_match (lexer, T_EQUALS);
3259                   if (!lex_force_string (lexer))
3260                     goto error;
3261
3262                   free (ct->missing);
3263                   ct->missing = (strcmp (lex_tokcstr (lexer), ".")
3264                                  ? ss_xstrdup (lex_tokss (lexer))
3265                                  : NULL);
3266                   lex_get (lexer);
3267                 }
3268               else
3269                 {
3270                   lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
3271                                        "UNITS", "EMPTY", "MISSING");
3272                   goto error;
3273                 }
3274             }
3275
3276           if (widths[0] != SYSMIS && widths[1] != SYSMIS
3277               && widths[0] > widths[1])
3278             {
3279               msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
3280               goto error;
3281             }
3282
3283           for (size_t i = 0; i < 2; i++)
3284             if (widths[i] != SYSMIS)
3285               {
3286                 int *wr = ct->look->width_ranges[TABLE_HORZ];
3287                 wr[i] = widths[i] / units_per_inch * 96.0;
3288                 if (wr[0] > wr[1])
3289                   wr[!i] = wr[i];
3290               }
3291         }
3292       else if (lex_match_id (lexer, "VLABELS"))
3293         {
3294           if (!lex_force_match_id (lexer, "VARIABLES"))
3295             goto error;
3296           lex_match (lexer, T_EQUALS);
3297
3298           struct variable **vars;
3299           size_t n_vars;
3300           if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
3301                                 PV_NO_SCRATCH))
3302             goto error;
3303
3304           if (!lex_force_match_id (lexer, "DISPLAY"))
3305             {
3306               free (vars);
3307               goto error;
3308             }
3309           lex_match (lexer, T_EQUALS);
3310
3311           enum ctables_vlabel vlabel;
3312           if (lex_match_id (lexer, "DEFAULT"))
3313             vlabel = (enum ctables_vlabel) settings_get_show_variables ();
3314           else if (lex_match_id (lexer, "NAME"))
3315             vlabel = CTVL_NAME;
3316           else if (lex_match_id (lexer, "LABEL"))
3317             vlabel = CTVL_LABEL;
3318           else if (lex_match_id (lexer, "BOTH"))
3319             vlabel = CTVL_BOTH;
3320           else if (lex_match_id (lexer, "NONE"))
3321             vlabel = CTVL_NONE;
3322           else
3323             {
3324               lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
3325                                    "BOTH", "NONE");
3326               free (vars);
3327               goto error;
3328             }
3329
3330           for (size_t i = 0; i < n_vars; i++)
3331             ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
3332           free (vars);
3333         }
3334       else if (lex_match_id (lexer, "MRSETS"))
3335         {
3336           if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
3337             goto error;
3338           lex_match (lexer, T_EQUALS);
3339           if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
3340             goto error;
3341         }
3342       else if (lex_match_id (lexer, "SMISSING"))
3343         {
3344           if (lex_match_id (lexer, "VARIABLE"))
3345             ct->smissing_listwise = false;
3346           else if (lex_match_id (lexer, "LISTWISE"))
3347             ct->smissing_listwise = true;
3348           else
3349             {
3350               lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
3351               goto error;
3352             }
3353         }
3354       /* XXX PCOMPUTE */
3355       else if (lex_match_id (lexer, "WEIGHT"))
3356         {
3357           if (!lex_force_match_id (lexer, "VARIABLE"))
3358             goto error;
3359           lex_match (lexer, T_EQUALS);
3360           ct->base_weight = parse_variable (lexer, dataset_dict (ds));
3361           if (!ct->base_weight)
3362             goto error;
3363         }
3364       else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
3365         {
3366           if (!lex_force_match_id (lexer, "COUNT"))
3367             goto error;
3368           lex_match (lexer, T_EQUALS);
3369           if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
3370             goto error;
3371           ct->hide_threshold = lex_integer (lexer);
3372           lex_get (lexer);
3373         }
3374       else
3375         {
3376           lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
3377                                "SMISSING", "PCOMPUTE", "PPROPERTIES",
3378                                "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
3379           goto error;
3380         }
3381
3382       if (!lex_force_match (lexer, T_SLASH))
3383         goto error;
3384     }
3385
3386   size_t allocated_tables = 0;
3387   do
3388     {
3389       if (ct->n_tables >= allocated_tables)
3390         ct->tables = x2nrealloc (ct->tables, &allocated_tables,
3391                                  sizeof *ct->tables);
3392
3393       struct ctables_category *cat = xmalloc (sizeof *cat);
3394       *cat = (struct ctables_category) {
3395         .type = CCT_VALUE,
3396         .include_missing = false,
3397         .sort_ascending = true,
3398       };
3399
3400       struct ctables_categories *c = xmalloc (sizeof *c);
3401       size_t n_vars = dict_get_n_vars (dataset_dict (ds));
3402       *c = (struct ctables_categories) {
3403         .n_refs = n_vars,
3404         .cats = cat,
3405         .n_cats = 1,
3406       };
3407
3408       struct ctables_categories **categories = xnmalloc (n_vars,
3409                                                          sizeof *categories);
3410       for (size_t i = 0; i < n_vars; i++)
3411         categories[i] = c;
3412
3413       struct ctables_table *t = xmalloc (sizeof *t);
3414       *t = (struct ctables_table) {
3415         .cells = HMAP_INITIALIZER (t->cells),
3416         .slabels_axis = PIVOT_AXIS_COLUMN,
3417         .slabels_visible = true,
3418         .clabels_values_map = HMAP_INITIALIZER (t->clabels_values_map),
3419         .label_axis = {
3420           [PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW,
3421           [PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN,
3422           [PIVOT_AXIS_LAYER] = PIVOT_AXIS_LAYER,
3423         },
3424         .clabels_from_axis = PIVOT_AXIS_LAYER, 
3425         .categories = categories,
3426         .n_categories = n_vars,
3427         .cilevel = 95,
3428       };
3429       for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3430         hmap_init (&t->domains[dt]);
3431       ct->tables[ct->n_tables++] = t;
3432
3433       lex_match (lexer, T_EQUALS);
3434       if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
3435         goto error;
3436       if (lex_match (lexer, T_BY))
3437         {
3438           if (!ctables_axis_parse (lexer, dataset_dict (ds),
3439                                    ct, t, PIVOT_AXIS_COLUMN))
3440             goto error;
3441
3442           if (lex_match (lexer, T_BY))
3443             {
3444               if (!ctables_axis_parse (lexer, dataset_dict (ds),
3445                                        ct, t, PIVOT_AXIS_LAYER))
3446                 goto error;
3447             }
3448         }
3449
3450       if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
3451           && !t->axes[PIVOT_AXIS_LAYER])
3452         {
3453           lex_error (lexer, _("At least one variable must be specified."));
3454           goto error;
3455         }
3456
3457       const struct ctables_axis *scales[PIVOT_N_AXES];
3458       size_t n_scales = 0;
3459       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3460         {
3461           scales[a] = find_scale (t->axes[a]);
3462           if (scales[a])
3463             n_scales++;
3464         }
3465       if (n_scales > 1)
3466         {
3467           msg (SE, _("Scale variables may appear only on one axis."));
3468           if (scales[PIVOT_AXIS_ROW])
3469             msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
3470                     _("This scale variable appears on the rows axis."));
3471           if (scales[PIVOT_AXIS_COLUMN])
3472             msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
3473                     _("This scale variable appears on the columns axis."));
3474           if (scales[PIVOT_AXIS_LAYER])
3475             msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
3476                     _("This scale variable appears on the layer axis."));
3477           goto error;
3478         }
3479
3480       const struct ctables_axis *summaries[PIVOT_N_AXES];
3481       size_t n_summaries = 0;
3482       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3483         {
3484           summaries[a] = (scales[a]
3485                           ? scales[a]
3486                           : find_categorical_summary_spec (t->axes[a]));
3487           if (summaries[a])
3488             n_summaries++;
3489         }
3490       if (n_summaries > 1)
3491         {
3492           msg (SE, _("Summaries may appear only on one axis."));
3493           if (summaries[PIVOT_AXIS_ROW])
3494             msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
3495                     _("This variable on the rows axis has a summary."));
3496           if (summaries[PIVOT_AXIS_COLUMN])
3497             msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
3498                     _("This variable on the columns axis has a summary."));
3499           if (summaries[PIVOT_AXIS_LAYER])
3500             msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
3501                     _("This variable on the layers axis has a summary."));
3502           goto error;
3503         }
3504       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3505         if (n_summaries ? summaries[a] : t->axes[a])
3506           {
3507             t->summary_axis = a;
3508             break;
3509           }
3510
3511       if (lex_token (lexer) == T_ENDCMD)
3512         {
3513           if (!ctables_prepare_table (t))
3514             goto error;
3515           break;
3516         }
3517       if (!lex_force_match (lexer, T_SLASH))
3518         break;
3519
3520       while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
3521         {
3522           if (lex_match_id (lexer, "SLABELS"))
3523             {
3524               while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3525                 {
3526                   if (lex_match_id (lexer, "POSITION"))
3527                     {
3528                       lex_match (lexer, T_EQUALS);
3529                       if (lex_match_id (lexer, "COLUMN"))
3530                         t->slabels_axis = PIVOT_AXIS_COLUMN;
3531                       else if (lex_match_id (lexer, "ROW"))
3532                         t->slabels_axis = PIVOT_AXIS_ROW;
3533                       else if (lex_match_id (lexer, "LAYER"))
3534                         t->slabels_axis = PIVOT_AXIS_LAYER;
3535                       else
3536                         {
3537                           lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
3538                           goto error;
3539                         }
3540                     }
3541                   else if (lex_match_id (lexer, "VISIBLE"))
3542                     {
3543                       lex_match (lexer, T_EQUALS);
3544                       if (!parse_bool (lexer, &t->slabels_visible))
3545                         goto error;
3546                     }
3547                   else
3548                     {
3549                       lex_error_expecting (lexer, "POSITION", "VISIBLE");
3550                       goto error;
3551                     }
3552                 }
3553             }
3554           else if (lex_match_id (lexer, "CLABELS"))
3555             {
3556               while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3557                 {
3558                   if (lex_match_id (lexer, "AUTO"))
3559                     {
3560                       t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW;
3561                       t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN;
3562                     }
3563                   else if (lex_match_id (lexer, "ROWLABELS"))
3564                     {
3565                       lex_match (lexer, T_EQUALS);
3566                       if (lex_match_id (lexer, "OPPOSITE"))
3567                         t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_COLUMN;
3568                       else if (lex_match_id (lexer, "LAYER"))
3569                         t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_LAYER;
3570                       else
3571                         {
3572                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3573                           goto error;
3574                         }
3575                     }
3576                   else if (lex_match_id (lexer, "COLLABELS"))
3577                     {
3578                       lex_match (lexer, T_EQUALS);
3579                       if (lex_match_id (lexer, "OPPOSITE"))
3580                         t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_ROW;
3581                       else if (lex_match_id (lexer, "LAYER"))
3582                         t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_LAYER;
3583                       else
3584                         {
3585                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3586                           goto error;
3587                         }
3588                     }
3589                   else
3590                     {
3591                       lex_error_expecting (lexer, "AUTO", "ROWLABELS",
3592                                            "COLLABELS");
3593                       goto error;
3594                     }
3595                 }
3596             }
3597           else if (lex_match_id (lexer, "CRITERIA"))
3598             {
3599               if (!lex_force_match_id (lexer, "CILEVEL"))
3600                 goto error;
3601               lex_match (lexer, T_EQUALS);
3602
3603               if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
3604                 goto error;
3605               t->cilevel = lex_number (lexer);
3606               lex_get (lexer);
3607             }
3608           else if (lex_match_id (lexer, "CATEGORIES"))
3609             {
3610               if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
3611                 goto error;
3612             }
3613           else if (lex_match_id (lexer, "TITLES"))
3614             {
3615               do
3616                 {
3617                   char **textp;
3618                   if (lex_match_id (lexer, "CAPTION"))
3619                     textp = &t->caption;
3620                   else if (lex_match_id (lexer, "CORNER"))
3621                     textp = &t->corner;
3622                   else if (lex_match_id (lexer, "TITLE"))
3623                     textp = &t->title;
3624                   else
3625                     {
3626                       lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
3627                       goto error;
3628                     }
3629                   lex_match (lexer, T_EQUALS);
3630
3631                   struct string s = DS_EMPTY_INITIALIZER;
3632                   while (lex_is_string (lexer))
3633                     {
3634                       if (!ds_is_empty (&s))
3635                         ds_put_byte (&s, ' ');
3636                       ds_put_substring (&s, lex_tokss (lexer));
3637                       lex_get (lexer);
3638                     }
3639                   free (*textp);
3640                   *textp = ds_steal_cstr (&s);
3641                 }
3642               while (lex_token (lexer) != T_SLASH
3643                      && lex_token (lexer) != T_ENDCMD);
3644             }
3645           else if (lex_match_id (lexer, "SIGTEST"))
3646             {
3647               if (!t->chisq)
3648                 {
3649                   t->chisq = xmalloc (sizeof *t->chisq);
3650                   *t->chisq = (struct ctables_chisq) {
3651                     .alpha = .05,
3652                     .include_mrsets = true,
3653                     .all_visible = true,
3654                   };
3655                 }
3656
3657               do
3658                 {
3659                   if (lex_match_id (lexer, "TYPE"))
3660                     {
3661                       lex_match (lexer, T_EQUALS);
3662                       if (!lex_force_match_id (lexer, "CHISQUARE"))
3663                         goto error;
3664                     }
3665                   else if (lex_match_id (lexer, "ALPHA"))
3666                     {
3667                       lex_match (lexer, T_EQUALS);
3668                       if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
3669                         goto error;
3670                       t->chisq->alpha = lex_number (lexer);
3671                       lex_get (lexer);
3672                     }
3673                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3674                     {
3675                       lex_match (lexer, T_EQUALS);
3676                       if (parse_bool (lexer, &t->chisq->include_mrsets))
3677                         goto error;
3678                     }
3679                   else if (lex_match_id (lexer, "CATEGORIES"))
3680                     {
3681                       lex_match (lexer, T_EQUALS);
3682                       if (lex_match_id (lexer, "ALLVISIBLE"))
3683                         t->chisq->all_visible = true;
3684                       else if (lex_match_id (lexer, "SUBTOTALS"))
3685                         t->chisq->all_visible = false;
3686                       else
3687                         {
3688                           lex_error_expecting (lexer,
3689                                                "ALLVISIBLE", "SUBTOTALS");
3690                           goto error;
3691                         }
3692                     }
3693                   else
3694                     {
3695                       lex_error_expecting (lexer, "TYPE", "ALPHA",
3696                                            "INCLUDEMRSETS", "CATEGORIES");
3697                       goto error;
3698                     }
3699                 }
3700               while (lex_token (lexer) != T_SLASH
3701                      && lex_token (lexer) != T_ENDCMD);
3702             }
3703           else if (lex_match_id (lexer, "COMPARETEST"))
3704             {
3705               if (!t->pairwise)
3706                 {
3707                   t->pairwise = xmalloc (sizeof *t->pairwise);
3708                   *t->pairwise = (struct ctables_pairwise) {
3709                     .type = PROP,
3710                     .alpha = { .05, .05 },
3711                     .adjust = BONFERRONI,
3712                     .include_mrsets = true,
3713                     .meansvariance_allcats = true,
3714                     .all_visible = true,
3715                     .merge = false,
3716                     .apa_style = true,
3717                     .show_sig = false,
3718                   };
3719                 }
3720
3721               do
3722                 {
3723                   if (lex_match_id (lexer, "TYPE"))
3724                     {
3725                       lex_match (lexer, T_EQUALS);
3726                       if (lex_match_id (lexer, "PROP"))
3727                         t->pairwise->type = PROP;
3728                       else if (lex_match_id (lexer, "MEAN"))
3729                         t->pairwise->type = MEAN;
3730                       else
3731                         {
3732                           lex_error_expecting (lexer, "PROP", "MEAN");
3733                           goto error;
3734                         }
3735                     }
3736                   else if (lex_match_id (lexer, "ALPHA"))
3737                     {
3738                       lex_match (lexer, T_EQUALS);
3739
3740                       if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3741                         goto error;
3742                       double a0 = lex_number (lexer);
3743                       lex_get (lexer);
3744
3745                       lex_match (lexer, T_COMMA);
3746                       if (lex_is_number (lexer))
3747                         {
3748                           if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3749                             goto error;
3750                           double a1 = lex_number (lexer);
3751                           lex_get (lexer);
3752
3753                           t->pairwise->alpha[0] = MIN (a0, a1);
3754                           t->pairwise->alpha[1] = MAX (a0, a1);
3755                         }
3756                       else
3757                         t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
3758                     }
3759                   else if (lex_match_id (lexer, "ADJUST"))
3760                     {
3761                       lex_match (lexer, T_EQUALS);
3762                       if (lex_match_id (lexer, "BONFERRONI"))
3763                         t->pairwise->adjust = BONFERRONI;
3764                       else if (lex_match_id (lexer, "BH"))
3765                         t->pairwise->adjust = BH;
3766                       else if (lex_match_id (lexer, "NONE"))
3767                         t->pairwise->adjust = 0;
3768                       else
3769                         {
3770                           lex_error_expecting (lexer, "BONFERRONI", "BH",
3771                                                "NONE");
3772                           goto error;
3773                         }
3774                     }
3775                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3776                     {
3777                       lex_match (lexer, T_EQUALS);
3778                       if (!parse_bool (lexer, &t->pairwise->include_mrsets))
3779                         goto error;
3780                     }
3781                   else if (lex_match_id (lexer, "MEANSVARIANCE"))
3782                     {
3783                       lex_match (lexer, T_EQUALS);
3784                       if (lex_match_id (lexer, "ALLCATS"))
3785                         t->pairwise->meansvariance_allcats = true;
3786                       else if (lex_match_id (lexer, "TESTEDCATS"))
3787                         t->pairwise->meansvariance_allcats = false;
3788                       else
3789                         {
3790                           lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
3791                           goto error;
3792                         }
3793                     }
3794                   else if (lex_match_id (lexer, "CATEGORIES"))
3795                     {
3796                       lex_match (lexer, T_EQUALS);
3797                       if (lex_match_id (lexer, "ALLVISIBLE"))
3798                         t->pairwise->all_visible = true;
3799                       else if (lex_match_id (lexer, "SUBTOTALS"))
3800                         t->pairwise->all_visible = false;
3801                       else
3802                         {
3803                           lex_error_expecting (lexer, "ALLVISIBLE",
3804                                                "SUBTOTALS");
3805                           goto error;
3806                         }
3807                     }
3808                   else if (lex_match_id (lexer, "MERGE"))
3809                     {
3810                       lex_match (lexer, T_EQUALS);
3811                       if (!parse_bool (lexer, &t->pairwise->merge))
3812                         goto error;
3813                     }
3814                   else if (lex_match_id (lexer, "STYLE"))
3815                     {
3816                       lex_match (lexer, T_EQUALS);
3817                       if (lex_match_id (lexer, "APA"))
3818                         t->pairwise->apa_style = true;
3819                       else if (lex_match_id (lexer, "SIMPLE"))
3820                         t->pairwise->apa_style = false;
3821                       else
3822                         {
3823                           lex_error_expecting (lexer, "APA", "SIMPLE");
3824                           goto error;
3825                         }
3826                     }
3827                   else if (lex_match_id (lexer, "SHOWSIG"))
3828                     {
3829                       lex_match (lexer, T_EQUALS);
3830                       if (!parse_bool (lexer, &t->pairwise->show_sig))
3831                         goto error;
3832                     }
3833                   else
3834                     {
3835                       lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
3836                                            "INCLUDEMRSETS", "MEANSVARIANCE",
3837                                            "CATEGORIES", "MERGE", "STYLE",
3838                                            "SHOWSIG");
3839                       goto error;
3840                     }
3841                 }
3842               while (lex_token (lexer) != T_SLASH
3843                      && lex_token (lexer) != T_ENDCMD);
3844             }
3845           else
3846             {
3847               lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
3848                                    "CRITERIA", "CATEGORIES", "TITLES",
3849                                    "SIGTEST", "COMPARETEST");
3850               goto error;
3851             }
3852
3853           if (!lex_match (lexer, T_SLASH))
3854             break;
3855         }
3856
3857       if (t->label_axis[PIVOT_AXIS_ROW] != PIVOT_AXIS_ROW
3858           && t->label_axis[PIVOT_AXIS_COLUMN] != PIVOT_AXIS_COLUMN)
3859         {
3860           msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
3861           goto error;
3862         }
3863
3864       if (!ctables_prepare_table (t))
3865         goto error;
3866     }
3867   while (lex_token (lexer) != T_ENDCMD);
3868
3869   bool ok = ctables_execute (ds, ct);
3870   ctables_destroy (ct);
3871   return ok ? CMD_SUCCESS : CMD_FAILURE;
3872
3873 error:
3874   ctables_destroy (ct);
3875   return CMD_FAILURE;
3876 }
3877