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