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