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