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