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