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