move code around
[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_axis;
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       add_summary_spec (sub, function, percentile, label, formatp, loc, sv);
963       free (label);
964       msg_location_destroy (loc);
965
966       lex_match (ctx->lexer, T_COMMA);
967       if (sv == CSV_CELL && lex_match_id (ctx->lexer, "TOTALS"))
968         {
969           if (!lex_force_match (ctx->lexer, T_LBRACK))
970             goto error;
971           sv = CSV_TOTAL;
972         }
973       else if (lex_match (ctx->lexer, T_RBRACK))
974         {
975           if (sv == CSV_TOTAL && !lex_force_match (ctx->lexer, T_RBRACK))
976             goto error;
977           return sub;
978         }
979     }
980
981 error:
982   ctables_axis_destroy (sub);
983   return NULL;
984 }
985
986 static const struct ctables_axis *
987 find_scale (const struct ctables_axis *axis)
988 {
989   if (!axis)
990     return NULL;
991   else if (axis->op == CTAO_VAR)
992     {
993       if (axis->scale)
994         {
995           assert (!axis->var.is_mrset);
996           return axis;
997         }
998       else
999         return NULL;
1000     }
1001   else
1002     {
1003       for (size_t i = 0; i < 2; i++)
1004         {
1005           const struct ctables_axis *scale = find_scale (axis->subs[i]);
1006           if (scale)
1007             return scale;
1008         }
1009       return NULL;
1010     }
1011 }
1012
1013 static const struct ctables_axis *
1014 find_categorical_summary_spec (const struct ctables_axis *axis)
1015 {
1016   if (!axis)
1017     return NULL;
1018   else if (axis->op == CTAO_VAR)
1019     return !axis->scale && axis->specs[CSV_CELL].n ? axis : NULL;
1020   else
1021     {
1022       for (size_t i = 0; i < 2; i++)
1023         {
1024           const struct ctables_axis *sum
1025             = find_categorical_summary_spec (axis->subs[i]);
1026           if (sum)
1027             return sum;
1028         }
1029       return NULL;
1030     }
1031 }
1032
1033 static struct ctables_axis *
1034 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
1035 {
1036   int start_ofs = lex_ofs (ctx->lexer);
1037   struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
1038   if (!lhs)
1039     return NULL;
1040
1041   while (lex_match (ctx->lexer, T_GT))
1042     {
1043       struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
1044       if (!rhs)
1045         return NULL;
1046
1047       struct ctables_axis *nest = ctables_axis_new_nonterminal (
1048         CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
1049
1050       const struct ctables_axis *outer_scale = find_scale (lhs);
1051       const struct ctables_axis *inner_scale = find_scale (rhs);
1052       if (outer_scale && inner_scale)
1053         {
1054           msg_at (SE, nest->loc, _("Cannot nest scale variables."));
1055           msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
1056           msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
1057           ctables_axis_destroy (nest);
1058           return NULL;
1059         }
1060
1061       const struct ctables_axis *outer_sum = find_categorical_summary_spec (lhs);
1062       if (outer_sum)
1063         {
1064           msg_at (SE, nest->loc,
1065                   _("Summaries may only be requested for categorical variables "
1066                     "at the innermost nesting level."));
1067           msg_at (SN, outer_sum->loc,
1068                   _("This outer categorical variable has a summary."));
1069           ctables_axis_destroy (nest);
1070           return NULL;
1071         }
1072
1073       lhs = nest;
1074     }
1075
1076   return lhs;
1077 }
1078
1079 static struct ctables_axis *
1080 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
1081 {
1082   int start_ofs = lex_ofs (ctx->lexer);
1083   struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
1084   if (!lhs)
1085     return NULL;
1086
1087   while (lex_match (ctx->lexer, T_PLUS))
1088     {
1089       struct ctables_axis *rhs = ctables_axis_parse_nest (ctx);
1090       if (!rhs)
1091         return NULL;
1092
1093       lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
1094                                           ctx->lexer, start_ofs);
1095     }
1096
1097   return lhs;
1098 }
1099
1100 static bool
1101 ctables_axis_parse (struct lexer *lexer, struct dictionary *dict,
1102                     struct ctables *ct, struct ctables_table *t,
1103                     enum pivot_axis_type a)
1104 {
1105   if (lex_token (lexer) == T_BY
1106       || lex_token (lexer) == T_SLASH
1107       || lex_token (lexer) == T_ENDCMD)
1108     return true;
1109
1110   struct ctables_axis_parse_ctx ctx = {
1111     .lexer = lexer,
1112     .dict = dict,
1113     .ct = ct,
1114     .t = t
1115   };
1116   t->axes[a] = ctables_axis_parse_stack (&ctx);
1117   return t->axes[a] != NULL;
1118 }
1119
1120 static void
1121 ctables_chisq_destroy (struct ctables_chisq *chisq)
1122 {
1123   free (chisq);
1124 }
1125
1126 static void
1127 ctables_pairwise_destroy (struct ctables_pairwise *pairwise)
1128 {
1129   free (pairwise);
1130 }
1131
1132 static void
1133 ctables_table_destroy (struct ctables_table *t)
1134 {
1135   if (!t)
1136     return;
1137
1138   for (size_t i = 0; i < t->n_categories; i++)
1139     ctables_categories_unref (t->categories[i]);
1140   free (t->categories);
1141
1142   ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
1143   ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
1144   ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
1145   free (t->caption);
1146   free (t->corner);
1147   free (t->title);
1148   ctables_chisq_destroy (t->chisq);
1149   ctables_pairwise_destroy (t->pairwise);
1150   free (t);
1151 }
1152
1153 static void
1154 ctables_destroy (struct ctables *ct)
1155 {
1156   if (!ct)
1157     return;
1158
1159   pivot_table_look_unref (ct->look);
1160   free (ct->zero);
1161   free (ct->missing);
1162   free (ct->vlabels);
1163   for (size_t i = 0; i < ct->n_tables; i++)
1164     ctables_table_destroy (ct->tables[i]);
1165   free (ct->tables);
1166   free (ct);
1167 }
1168
1169 static struct ctables_category
1170 cct_range (double low, double high)
1171 {
1172   return (struct ctables_category) {
1173     .type = CCT_RANGE,
1174     .range = { low, high }
1175   };
1176 }
1177
1178 static bool
1179 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
1180                                 struct ctables_table *t)
1181 {
1182   if (!lex_match_id (lexer, "VARIABLES"))
1183     return false;
1184   lex_match (lexer, T_EQUALS);
1185
1186   struct variable **vars;
1187   size_t n_vars;
1188   if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
1189     return false;
1190
1191   struct ctables_categories *c = xmalloc (sizeof *c);
1192   *c = (struct ctables_categories) { .n_refs = n_vars };
1193   for (size_t i = 0; i < n_vars; i++)
1194     {
1195       struct ctables_categories **cp
1196         = &t->categories[var_get_dict_index (vars[i])];
1197       ctables_categories_unref (*cp);
1198       *cp = c;
1199     }
1200   free (vars);
1201
1202   size_t allocated_cats = 0;
1203   if (lex_match (lexer, T_LBRACK))
1204     {
1205       do
1206         {
1207           if (c->n_cats >= allocated_cats)
1208             c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1209
1210           struct ctables_category *cat = &c->cats[c->n_cats];
1211           if (lex_match_id (lexer, "OTHERNM"))
1212             cat->type = CCT_OTHERNM;
1213           else if (lex_match_id (lexer, "MISSING"))
1214             cat->type = CCT_MISSING;
1215           else if (lex_match_id (lexer, "SUBTOTAL"))
1216             *cat = (struct ctables_category)
1217               { .type = CCT_SUBTOTAL, .total_label = NULL };
1218           else if (lex_match_id (lexer, "HSUBTOTAL"))
1219             *cat = (struct ctables_category)
1220               { .type = CCT_HSUBTOTAL, .total_label = NULL };
1221           else if (lex_match_id (lexer, "LO"))
1222             {
1223               if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
1224                 return false;
1225               *cat = cct_range (-DBL_MAX, lex_number (lexer));
1226               lex_get (lexer);
1227             }
1228           else if (lex_is_number (lexer))
1229             {
1230               double number = lex_number (lexer);
1231               lex_get (lexer);
1232               if (lex_match_id (lexer, "THRU"))
1233                 {
1234                   cat->type = CCT_RANGE;
1235                   cat->range[0] = number;
1236                   if (lex_match_id (lexer, "HI"))
1237                     *cat = cct_range (number, DBL_MAX);
1238                   else
1239                     {
1240                       if (!lex_force_num (lexer))
1241                         return false;
1242                       *cat = cct_range (number, lex_number (lexer));
1243                       lex_get (lexer);
1244                     }
1245                 }
1246               else
1247                 *cat = (struct ctables_category) {
1248                   .type = CCT_NUMBER,
1249                   .number = number
1250                 };
1251             }
1252           else if (lex_is_string (lexer))
1253             {
1254               *cat = (struct ctables_category) {
1255                 .type = CCT_STRING,
1256                 .string = ss_xstrdup (lex_tokss (lexer)),
1257               };
1258               lex_get (lexer);
1259             }
1260           else
1261             {
1262               lex_error (lexer, NULL);
1263               return false;
1264             }
1265
1266           if (cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL)
1267             {
1268               if (lex_match (lexer, T_EQUALS))
1269                 {
1270                   if (!lex_force_string (lexer))
1271                     return false;
1272
1273                   cat->total_label = ss_xstrdup (lex_tokss (lexer));
1274                   lex_get (lexer);
1275                 }
1276               else
1277                 cat->total_label = xstrdup (_("Subtotal"));
1278             }
1279
1280           c->n_cats++;
1281           lex_match (lexer, T_COMMA);
1282         }
1283       while (!lex_match (lexer, T_RBRACK));
1284     }
1285
1286   struct ctables_category cat = {
1287     .type = CCT_VALUE,
1288     .include_missing = false,
1289     .sort_ascending = true,
1290   };
1291   bool show_totals = false;
1292   char *total_label = NULL;
1293   bool totals_before = false;
1294   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
1295     {
1296       if (!c->n_cats && lex_match_id (lexer, "ORDER"))
1297         {
1298           lex_match (lexer, T_EQUALS);
1299           if (lex_match_id (lexer, "A"))
1300             cat.sort_ascending = true;
1301           else if (lex_match_id (lexer, "D"))
1302             cat.sort_ascending = false;
1303           else
1304             {
1305               lex_error_expecting (lexer, "A", "D");
1306               return false;
1307             }
1308         }
1309       else if (!c->n_cats && lex_match_id (lexer, "KEY"))
1310         {
1311           lex_match (lexer, T_EQUALS);
1312           if (lex_match_id (lexer, "VALUE"))
1313             cat.type = CCT_VALUE;
1314           else if (lex_match_id (lexer, "LABEL"))
1315             cat.type = CCT_LABEL;
1316           else
1317             {
1318               cat.type = CCT_FUNCTION;
1319               if (!parse_ctables_summary_function (lexer, &cat.sort_function))
1320                 return false;
1321
1322               if (lex_match (lexer, T_LPAREN))
1323                 {
1324                   cat.sort_var = parse_variable (lexer, dict);
1325                   if (!cat.sort_var)
1326                     return false;
1327
1328                   if (cat.sort_function == CTSF_PTILE)
1329                     {
1330                       lex_match (lexer, T_COMMA);
1331                       if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
1332                         return false;
1333                       cat.percentile = lex_number (lexer);
1334                       lex_get (lexer);
1335                     }
1336
1337                   if (!lex_force_match (lexer, T_RPAREN))
1338                     return false;
1339                 }
1340               else if (ctables_function_availability (cat.sort_function)
1341                        == CTFA_SCALE)
1342                 {
1343                   bool UNUSED b = lex_force_match (lexer, T_LPAREN);
1344                   return false;
1345                 }
1346             }
1347         }
1348       else if (!c->n_cats && lex_match_id (lexer, "MISSING"))
1349         {
1350           lex_match (lexer, T_EQUALS);
1351           if (lex_match_id (lexer, "INCLUDE"))
1352             cat.include_missing = true;
1353           else if (lex_match_id (lexer, "EXCLUDE"))
1354             cat.include_missing = false;
1355           else
1356             {
1357               lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1358               return false;
1359             }
1360         }
1361       else if (lex_match_id (lexer, "TOTAL"))
1362         {
1363           lex_match (lexer, T_EQUALS);
1364           if (!parse_bool (lexer, &show_totals))
1365             return false;
1366         }
1367       else if (lex_match_id (lexer, "LABEL"))
1368         {
1369           lex_match (lexer, T_EQUALS);
1370           if (!lex_force_string (lexer))
1371             return false;
1372           free (total_label);
1373           total_label = ss_xstrdup (lex_tokss (lexer));
1374           lex_get (lexer);
1375         }
1376       else if (lex_match_id (lexer, "POSITION"))
1377         {
1378           lex_match (lexer, T_EQUALS);
1379           if (lex_match_id (lexer, "BEFORE"))
1380             totals_before = true;
1381           else if (lex_match_id (lexer, "AFTER"))
1382             totals_before = false;
1383           else
1384             {
1385               lex_error_expecting (lexer, "BEFORE", "AFTER");
1386               return false;
1387             }
1388         }
1389       else if (lex_match_id (lexer, "EMPTY"))
1390         {
1391           lex_match (lexer, T_EQUALS);
1392           if (lex_match_id (lexer, "INCLUDE"))
1393             c->show_empty = true;
1394           else if (lex_match_id (lexer, "EXCLUDE"))
1395             c->show_empty = false;
1396           else
1397             {
1398               lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1399               return false;
1400             }
1401         }
1402       else
1403         {
1404           if (!c->n_cats)
1405             lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
1406                                  "TOTAL", "LABEL", "POSITION", "EMPTY");
1407           else
1408             lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
1409           return false;
1410         }
1411     }
1412
1413   if (!c->n_cats)
1414     {
1415       if (c->n_cats >= allocated_cats)
1416         c->cats = x2nrealloc (c->cats, &allocated_cats,
1417                                 sizeof *c->cats);
1418       c->cats[c->n_cats++] = cat;
1419     }
1420
1421   if (show_totals)
1422     {
1423       if (c->n_cats >= allocated_cats)
1424         c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1425
1426       struct ctables_category *totals;
1427       if (totals_before)
1428         {
1429           insert_element (c->cats, c->n_cats, sizeof *c->cats, 0);
1430           totals = &c->cats[0];
1431         }
1432       else
1433         totals = &c->cats[c->n_cats];
1434       c->n_cats++;
1435
1436       *totals = (struct ctables_category) {
1437         .type = CCT_TOTAL,
1438         .total_label = total_label ? total_label : xstrdup (_("Total")),
1439       };
1440     }
1441
1442   struct ctables_category *subtotal = NULL;
1443   for (size_t i = totals_before ? 0 : c->n_cats;
1444        totals_before ? i < c->n_cats : i-- > 0;
1445        totals_before ? i++ : 0)
1446     {
1447       struct ctables_category *cat = &c->cats[i];
1448       switch (cat->type)
1449         {
1450         case CCT_NUMBER:
1451         case CCT_STRING:
1452         case CCT_RANGE:
1453         case CCT_MISSING:
1454         case CCT_OTHERNM:
1455           cat->subtotal = subtotal;
1456           break;
1457
1458         case CCT_SUBTOTAL:
1459         case CCT_HSUBTOTAL:
1460           subtotal = cat;
1461           break;
1462
1463         case CCT_TOTAL:
1464         case CCT_VALUE:
1465         case CCT_LABEL:
1466         case CCT_FUNCTION:
1467           break;
1468         }
1469     }
1470
1471   return true;
1472 }
1473
1474 static void
1475 ctables_nest_uninit (struct ctables_nest *nest)
1476 {
1477   if (nest)
1478     free (nest->vars);
1479 }
1480
1481 static void
1482 ctables_stack_uninit (struct ctables_stack *stack)
1483 {
1484   if (stack)
1485     {
1486       for (size_t i = 0; i < stack->n; i++)
1487         ctables_nest_uninit (&stack->nests[i]);
1488       free (stack->nests);
1489     }
1490 }
1491
1492 static struct ctables_stack
1493 nest_fts (struct ctables_stack s0, struct ctables_stack s1)
1494 {
1495   if (!s0.n)
1496     return s1;
1497   else if (!s1.n)
1498     return s0;
1499
1500   struct ctables_stack stack = { .nests = xnmalloc (s0.n, s1.n * sizeof *stack.nests) };
1501   for (size_t i = 0; i < s0.n; i++)
1502     for (size_t j = 0; j < s1.n; j++)
1503       {
1504         const struct ctables_nest *a = &s0.nests[i];
1505         const struct ctables_nest *b = &s1.nests[j];
1506
1507         size_t allocate = a->n + b->n;
1508         struct variable **vars = xnmalloc (allocate, sizeof *vars);
1509         enum pivot_axis_type *axes = xnmalloc (allocate, sizeof *axes);
1510         size_t n = 0;
1511         for (size_t k = 0; k < a->n; k++)
1512           vars[n++] = a->vars[k];
1513         for (size_t k = 0; k < b->n; k++)
1514           vars[n++] = b->vars[k];
1515         assert (n == allocate);
1516
1517         const struct ctables_nest *summary_src;
1518         if (!a->specs[CSV_CELL].var)
1519           summary_src = b;
1520         else if (!b->specs[CSV_CELL].var)
1521           summary_src = a;
1522         else
1523           NOT_REACHED ();
1524
1525         struct ctables_nest *new = &stack.nests[stack.n++];
1526         *new = (struct ctables_nest) {
1527           .vars = vars,
1528           .scale_idx = (a->scale_idx != SIZE_MAX ? a->scale_idx
1529                         : b->scale_idx != SIZE_MAX ? a->n + b->scale_idx
1530                         : SIZE_MAX),
1531           .n = n,
1532         };
1533         for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1534           ctables_summary_spec_set_clone (&new->specs[sv], &summary_src->specs[sv]);
1535       }
1536   ctables_stack_uninit (&s0);
1537   ctables_stack_uninit (&s1);
1538   return stack;
1539 }
1540
1541 static struct ctables_stack
1542 stack_fts (struct ctables_stack s0, struct ctables_stack s1)
1543 {
1544   struct ctables_stack stack = { .nests = xnmalloc (s0.n + s1.n, sizeof *stack.nests) };
1545   for (size_t i = 0; i < s0.n; i++)
1546     stack.nests[stack.n++] = s0.nests[i];
1547   for (size_t i = 0; i < s1.n; i++)
1548     stack.nests[stack.n++] = s1.nests[i];
1549   assert (stack.n == s0.n + s1.n);
1550   free (s0.nests);
1551   free (s1.nests);
1552   return stack;
1553 }
1554
1555 static struct ctables_stack
1556 enumerate_fts (enum pivot_axis_type axis_type, const struct ctables_axis *a)
1557 {
1558   if (!a)
1559     return (struct ctables_stack) { .n = 0 };
1560
1561   switch (a->op)
1562     {
1563     case CTAO_VAR:
1564       assert (!a->var.is_mrset);
1565
1566       struct variable **vars = xmalloc (sizeof *vars);
1567       *vars = a->var.var;
1568
1569       struct ctables_nest *nest = xmalloc (sizeof *nest);
1570       *nest = (struct ctables_nest) {
1571         .vars = vars,
1572         .n = 1,
1573         .scale_idx = a->scale ? 0 : SIZE_MAX,
1574       };
1575       if (a->specs[CSV_CELL].n || a->scale)
1576         for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1577           {
1578             ctables_summary_spec_set_clone (&nest->specs[sv], &a->specs[sv]);
1579             nest->specs[sv].var = a->var.var;
1580           }
1581       return (struct ctables_stack) { .nests = nest, .n = 1 };
1582
1583     case CTAO_STACK:
1584       return stack_fts (enumerate_fts (axis_type, a->subs[0]),
1585                         enumerate_fts (axis_type, a->subs[1]));
1586
1587     case CTAO_NEST:
1588       return nest_fts (enumerate_fts (axis_type, a->subs[0]),
1589                        enumerate_fts (axis_type, a->subs[1]));
1590     }
1591
1592   NOT_REACHED ();
1593 }
1594
1595 union ctables_summary
1596   {
1597     /* COUNT, VALIDN, TOTALN. */
1598     struct
1599       {
1600         double valid;
1601         double missing;
1602       };
1603
1604     /* MINIMUM, MAXIMUM, RANGE. */
1605     struct
1606       {
1607         double min;
1608         double max;
1609       };
1610
1611     /* MEAN, SEMEAN, STDDEV, SUM, VARIANCE, *.SUM. */
1612     struct moments1 *moments;
1613
1614     /* XXX percentiles, median, mode, multiple response */
1615   };
1616
1617 static void
1618 ctables_summary_init (union ctables_summary *s,
1619                       const struct ctables_summary_spec *ss)
1620 {
1621   switch (ss->function)
1622     {
1623     case CTSF_COUNT:
1624     case CTSF_ECOUNT:
1625     case CTSF_ROWPCT_COUNT:
1626     case CTSF_COLPCT_COUNT:
1627     case CTSF_TABLEPCT_COUNT:
1628     case CTSF_SUBTABLEPCT_COUNT:
1629     case CTSF_LAYERPCT_COUNT:
1630     case CTSF_LAYERROWPCT_COUNT:
1631     case CTSF_LAYERCOLPCT_COUNT:
1632     case CTSF_ROWPCT_VALIDN:
1633     case CTSF_COLPCT_VALIDN:
1634     case CTSF_TABLEPCT_VALIDN:
1635     case CTSF_SUBTABLEPCT_VALIDN:
1636     case CTSF_LAYERPCT_VALIDN:
1637     case CTSF_LAYERROWPCT_VALIDN:
1638     case CTSF_LAYERCOLPCT_VALIDN:
1639     case CTSF_ROWPCT_TOTALN:
1640     case CTSF_COLPCT_TOTALN:
1641     case CTSF_TABLEPCT_TOTALN:
1642     case CTSF_SUBTABLEPCT_TOTALN:
1643     case CTSF_LAYERPCT_TOTALN:
1644     case CTSF_LAYERROWPCT_TOTALN:
1645     case CTSF_LAYERCOLPCT_TOTALN:
1646     case CSTF_TOTALN:
1647     case CTSF_ETOTALN:
1648     case CTSF_VALIDN:
1649     case CTSF_EVALIDN:
1650       s->missing = s->valid = 0;
1651       break;
1652
1653     case CTSF_MAXIMUM:
1654     case CTSF_MINIMUM:
1655     case CTSF_RANGE:
1656       s->min = s->max = SYSMIS;
1657       break;
1658
1659     case CTSF_MEAN:
1660     case CTSF_SEMEAN:
1661     case CTSF_STDDEV:
1662     case CTSF_SUM:
1663     case CTSF_VARIANCE:
1664     case CTSF_ROWPCT_SUM:
1665     case CTSF_COLPCT_SUM:
1666     case CTSF_TABLEPCT_SUM:
1667     case CTSF_SUBTABLEPCT_SUM:
1668     case CTSF_LAYERPCT_SUM:
1669     case CTSF_LAYERROWPCT_SUM:
1670     case CTSF_LAYERCOLPCT_SUM:
1671       s->moments = moments1_create (MOMENT_VARIANCE);
1672       break;
1673
1674     case CTSF_MEDIAN:
1675     case CTSF_MISSING:
1676     case CTSF_MODE:
1677     case CTSF_PTILE:
1678       NOT_REACHED ();
1679
1680     case CTSF_RESPONSES:
1681     case CTSF_ROWPCT_RESPONSES:
1682     case CTSF_COLPCT_RESPONSES:
1683     case CTSF_TABLEPCT_RESPONSES:
1684     case CTSF_SUBTABLEPCT_RESPONSES:
1685     case CTSF_LAYERPCT_RESPONSES:
1686     case CTSF_LAYERROWPCT_RESPONSES:
1687     case CTSF_LAYERCOLPCT_RESPONSES:
1688     case CTSF_ROWPCT_RESPONSES_COUNT:
1689     case CTSF_COLPCT_RESPONSES_COUNT:
1690     case CTSF_TABLEPCT_RESPONSES_COUNT:
1691     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1692     case CTSF_LAYERPCT_RESPONSES_COUNT:
1693     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1694     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1695     case CTSF_ROWPCT_COUNT_RESPONSES:
1696     case CTSF_COLPCT_COUNT_RESPONSES:
1697     case CTSF_TABLEPCT_COUNT_RESPONSES:
1698     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1699     case CTSF_LAYERPCT_COUNT_RESPONSES:
1700     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1701     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1702       NOT_REACHED ();
1703     }
1704 }
1705
1706 static void UNUSED
1707 ctables_summary_uninit (union ctables_summary *s,
1708                         const struct ctables_summary_spec *ss)
1709 {
1710   switch (ss->function)
1711     {
1712     case CTSF_COUNT:
1713     case CTSF_ECOUNT:
1714     case CTSF_ROWPCT_COUNT:
1715     case CTSF_COLPCT_COUNT:
1716     case CTSF_TABLEPCT_COUNT:
1717     case CTSF_SUBTABLEPCT_COUNT:
1718     case CTSF_LAYERPCT_COUNT:
1719     case CTSF_LAYERROWPCT_COUNT:
1720     case CTSF_LAYERCOLPCT_COUNT:
1721     case CTSF_ROWPCT_VALIDN:
1722     case CTSF_COLPCT_VALIDN:
1723     case CTSF_TABLEPCT_VALIDN:
1724     case CTSF_SUBTABLEPCT_VALIDN:
1725     case CTSF_LAYERPCT_VALIDN:
1726     case CTSF_LAYERROWPCT_VALIDN:
1727     case CTSF_LAYERCOLPCT_VALIDN:
1728     case CTSF_ROWPCT_TOTALN:
1729     case CTSF_COLPCT_TOTALN:
1730     case CTSF_TABLEPCT_TOTALN:
1731     case CTSF_SUBTABLEPCT_TOTALN:
1732     case CTSF_LAYERPCT_TOTALN:
1733     case CTSF_LAYERROWPCT_TOTALN:
1734     case CTSF_LAYERCOLPCT_TOTALN:
1735     case CSTF_TOTALN:
1736     case CTSF_ETOTALN:
1737     case CTSF_VALIDN:
1738     case CTSF_EVALIDN:
1739       break;
1740
1741     case CTSF_MAXIMUM:
1742     case CTSF_MINIMUM:
1743     case CTSF_RANGE:
1744       break;
1745
1746     case CTSF_MEAN:
1747     case CTSF_SEMEAN:
1748     case CTSF_STDDEV:
1749     case CTSF_SUM:
1750     case CTSF_VARIANCE:
1751     case CTSF_ROWPCT_SUM:
1752     case CTSF_COLPCT_SUM:
1753     case CTSF_TABLEPCT_SUM:
1754     case CTSF_SUBTABLEPCT_SUM:
1755     case CTSF_LAYERPCT_SUM:
1756     case CTSF_LAYERROWPCT_SUM:
1757     case CTSF_LAYERCOLPCT_SUM:
1758       moments1_destroy (s->moments);
1759       break;
1760
1761     case CTSF_MEDIAN:
1762     case CTSF_MISSING:
1763     case CTSF_MODE:
1764     case CTSF_PTILE:
1765       NOT_REACHED ();
1766
1767     case CTSF_RESPONSES:
1768     case CTSF_ROWPCT_RESPONSES:
1769     case CTSF_COLPCT_RESPONSES:
1770     case CTSF_TABLEPCT_RESPONSES:
1771     case CTSF_SUBTABLEPCT_RESPONSES:
1772     case CTSF_LAYERPCT_RESPONSES:
1773     case CTSF_LAYERROWPCT_RESPONSES:
1774     case CTSF_LAYERCOLPCT_RESPONSES:
1775     case CTSF_ROWPCT_RESPONSES_COUNT:
1776     case CTSF_COLPCT_RESPONSES_COUNT:
1777     case CTSF_TABLEPCT_RESPONSES_COUNT:
1778     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1779     case CTSF_LAYERPCT_RESPONSES_COUNT:
1780     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1781     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1782     case CTSF_ROWPCT_COUNT_RESPONSES:
1783     case CTSF_COLPCT_COUNT_RESPONSES:
1784     case CTSF_TABLEPCT_COUNT_RESPONSES:
1785     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1786     case CTSF_LAYERPCT_COUNT_RESPONSES:
1787     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1788     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1789       NOT_REACHED ();
1790     }
1791 }
1792
1793 static void
1794 ctables_summary_add (union ctables_summary *s,
1795                      const struct ctables_summary_spec *ss,
1796                      const struct variable *var, const union value *value,
1797                      double weight)
1798 {
1799   switch (ss->function)
1800     {
1801     case CTSF_COUNT:
1802     case CTSF_ECOUNT:
1803     case CTSF_ROWPCT_COUNT:
1804     case CTSF_COLPCT_COUNT:
1805     case CTSF_TABLEPCT_COUNT:
1806     case CTSF_SUBTABLEPCT_COUNT:
1807     case CTSF_LAYERPCT_COUNT:
1808     case CTSF_LAYERROWPCT_COUNT:
1809     case CTSF_LAYERCOLPCT_COUNT:
1810     case CTSF_ROWPCT_VALIDN:
1811     case CTSF_COLPCT_VALIDN:
1812     case CTSF_TABLEPCT_VALIDN:
1813     case CTSF_SUBTABLEPCT_VALIDN:
1814     case CTSF_LAYERPCT_VALIDN:
1815     case CTSF_LAYERROWPCT_VALIDN:
1816     case CTSF_LAYERCOLPCT_VALIDN:
1817     case CTSF_ROWPCT_TOTALN:
1818     case CTSF_COLPCT_TOTALN:
1819     case CTSF_TABLEPCT_TOTALN:
1820     case CTSF_SUBTABLEPCT_TOTALN:
1821     case CTSF_LAYERPCT_TOTALN:
1822     case CTSF_LAYERROWPCT_TOTALN:
1823     case CTSF_LAYERCOLPCT_TOTALN:
1824     case CSTF_TOTALN:
1825     case CTSF_ETOTALN:
1826     case CTSF_VALIDN:
1827     case CTSF_EVALIDN:
1828       if (var_is_value_missing (var, value))
1829         s->missing += weight;
1830       else
1831         s->valid += weight;
1832       break;
1833
1834     case CTSF_MAXIMUM:
1835     case CTSF_MINIMUM:
1836     case CTSF_RANGE:
1837       if (!var_is_value_missing (var, value))
1838         {
1839           assert (!var_is_alpha (var)); /* XXX? */
1840           if (s->min == SYSMIS || value->f < s->min)
1841             s->min = value->f;
1842           if (s->max == SYSMIS || value->f > s->max)
1843             s->max = value->f;
1844         }
1845       break;
1846
1847     case CTSF_MEAN:
1848     case CTSF_SEMEAN:
1849     case CTSF_STDDEV:
1850     case CTSF_SUM:
1851     case CTSF_VARIANCE:
1852     case CTSF_ROWPCT_SUM:
1853     case CTSF_COLPCT_SUM:
1854     case CTSF_TABLEPCT_SUM:
1855     case CTSF_SUBTABLEPCT_SUM:
1856     case CTSF_LAYERPCT_SUM:
1857     case CTSF_LAYERROWPCT_SUM:
1858     case CTSF_LAYERCOLPCT_SUM:
1859       moments1_add (s->moments, value->f, weight);
1860       break;
1861
1862     case CTSF_MEDIAN:
1863     case CTSF_MISSING:
1864     case CTSF_MODE:
1865     case CTSF_PTILE:
1866       NOT_REACHED ();
1867
1868     case CTSF_RESPONSES:
1869     case CTSF_ROWPCT_RESPONSES:
1870     case CTSF_COLPCT_RESPONSES:
1871     case CTSF_TABLEPCT_RESPONSES:
1872     case CTSF_SUBTABLEPCT_RESPONSES:
1873     case CTSF_LAYERPCT_RESPONSES:
1874     case CTSF_LAYERROWPCT_RESPONSES:
1875     case CTSF_LAYERCOLPCT_RESPONSES:
1876     case CTSF_ROWPCT_RESPONSES_COUNT:
1877     case CTSF_COLPCT_RESPONSES_COUNT:
1878     case CTSF_TABLEPCT_RESPONSES_COUNT:
1879     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1880     case CTSF_LAYERPCT_RESPONSES_COUNT:
1881     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1882     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1883     case CTSF_ROWPCT_COUNT_RESPONSES:
1884     case CTSF_COLPCT_COUNT_RESPONSES:
1885     case CTSF_TABLEPCT_COUNT_RESPONSES:
1886     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1887     case CTSF_LAYERPCT_COUNT_RESPONSES:
1888     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1889     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1890       NOT_REACHED ();
1891     }
1892 }
1893
1894 static double
1895 ctables_summary_value (const struct ctables_cell *cell,
1896                        union ctables_summary *s,
1897                        const struct ctables_summary_spec *ss)
1898 {
1899   switch (ss->function)
1900     {
1901     case CTSF_COUNT:
1902     case CTSF_ECOUNT:
1903       return s->valid;
1904
1905     case CTSF_SUBTABLEPCT_COUNT:
1906       return cell->domains[CTDT_SUBTABLE]->valid ? s->valid / cell->domains[CTDT_SUBTABLE]->valid * 100 : SYSMIS;
1907
1908     case CTSF_ROWPCT_COUNT:
1909       return cell->domains[CTDT_ROW]->valid ? s->valid / cell->domains[CTDT_ROW]->valid * 100 : SYSMIS;
1910
1911     case CTSF_COLPCT_COUNT:
1912       return cell->domains[CTDT_COL]->valid ? s->valid / cell->domains[CTDT_COL]->valid * 100 : SYSMIS;
1913
1914     case CTSF_TABLEPCT_COUNT:
1915       return cell->domains[CTDT_TABLE]->valid ? s->valid / cell->domains[CTDT_TABLE]->valid * 100 : SYSMIS;
1916
1917     case CTSF_LAYERPCT_COUNT:
1918       return cell->domains[CTDT_LAYER]->valid ? s->valid / cell->domains[CTDT_LAYER]->valid * 100 : SYSMIS;
1919
1920     case CTSF_LAYERROWPCT_COUNT:
1921       return cell->domains[CTDT_LAYERROW]->valid ? s->valid / cell->domains[CTDT_LAYERROW]->valid * 100 : SYSMIS;
1922
1923     case CTSF_LAYERCOLPCT_COUNT:
1924       return cell->domains[CTDT_LAYERCOL]->valid ? s->valid / cell->domains[CTDT_LAYERCOL]->valid * 100 : SYSMIS;
1925
1926     case CTSF_ROWPCT_VALIDN:
1927     case CTSF_COLPCT_VALIDN:
1928     case CTSF_TABLEPCT_VALIDN:
1929     case CTSF_SUBTABLEPCT_VALIDN:
1930     case CTSF_LAYERPCT_VALIDN:
1931     case CTSF_LAYERROWPCT_VALIDN:
1932     case CTSF_LAYERCOLPCT_VALIDN:
1933     case CTSF_ROWPCT_TOTALN:
1934     case CTSF_COLPCT_TOTALN:
1935     case CTSF_TABLEPCT_TOTALN:
1936     case CTSF_SUBTABLEPCT_TOTALN:
1937     case CTSF_LAYERPCT_TOTALN:
1938     case CTSF_LAYERROWPCT_TOTALN:
1939     case CTSF_LAYERCOLPCT_TOTALN:
1940       NOT_REACHED ();
1941
1942     case CSTF_TOTALN:
1943     case CTSF_ETOTALN:
1944       return s->valid + s->missing;
1945
1946     case CTSF_VALIDN:
1947     case CTSF_EVALIDN:
1948       return s->valid;
1949
1950     case CTSF_MAXIMUM:
1951       return s->max;
1952
1953     case CTSF_MINIMUM:
1954       return s->min;
1955
1956     case CTSF_RANGE:
1957       return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
1958
1959     case CTSF_MEAN:
1960       {
1961         double mean;
1962         moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
1963         return mean;
1964       }
1965
1966     case CTSF_SEMEAN:
1967       {
1968         double weight, variance;
1969         moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
1970         return calc_semean (variance, weight);
1971       }
1972
1973     case CTSF_STDDEV:
1974       {
1975         double variance;
1976         moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
1977         return variance != SYSMIS ? sqrt (variance) : SYSMIS;
1978       }
1979
1980     case CTSF_SUM:
1981       {
1982         double weight, mean;
1983         moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
1984         return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
1985       }
1986
1987     case CTSF_VARIANCE:
1988       {
1989         double variance;
1990         moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
1991         return variance;
1992       }
1993
1994     case CTSF_ROWPCT_SUM:
1995     case CTSF_COLPCT_SUM:
1996     case CTSF_TABLEPCT_SUM:
1997     case CTSF_SUBTABLEPCT_SUM:
1998     case CTSF_LAYERPCT_SUM:
1999     case CTSF_LAYERROWPCT_SUM:
2000     case CTSF_LAYERCOLPCT_SUM:
2001       NOT_REACHED ();
2002
2003     case CTSF_MEDIAN:
2004     case CTSF_MISSING:
2005     case CTSF_MODE:
2006     case CTSF_PTILE:
2007       NOT_REACHED ();
2008
2009     case CTSF_RESPONSES:
2010     case CTSF_ROWPCT_RESPONSES:
2011     case CTSF_COLPCT_RESPONSES:
2012     case CTSF_TABLEPCT_RESPONSES:
2013     case CTSF_SUBTABLEPCT_RESPONSES:
2014     case CTSF_LAYERPCT_RESPONSES:
2015     case CTSF_LAYERROWPCT_RESPONSES:
2016     case CTSF_LAYERCOLPCT_RESPONSES:
2017     case CTSF_ROWPCT_RESPONSES_COUNT:
2018     case CTSF_COLPCT_RESPONSES_COUNT:
2019     case CTSF_TABLEPCT_RESPONSES_COUNT:
2020     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2021     case CTSF_LAYERPCT_RESPONSES_COUNT:
2022     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2023     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2024     case CTSF_ROWPCT_COUNT_RESPONSES:
2025     case CTSF_COLPCT_COUNT_RESPONSES:
2026     case CTSF_TABLEPCT_COUNT_RESPONSES:
2027     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2028     case CTSF_LAYERPCT_COUNT_RESPONSES:
2029     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2030     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2031       NOT_REACHED ();
2032     }
2033
2034   NOT_REACHED ();
2035 }
2036
2037 struct ctables_cell_sort_aux
2038   {
2039     const struct ctables_table *t;
2040     enum pivot_axis_type a;
2041   };
2042
2043 static int
2044 ctables_cell_compare_3way (const void *a_, const void *b_, const void *aux_)
2045 {
2046   const struct ctables_cell_sort_aux *aux = aux_;
2047   struct ctables_cell *const *ap = a_;
2048   struct ctables_cell *const *bp = b_;
2049   const struct ctables_cell *a = *ap;
2050   const struct ctables_cell *b = *bp;
2051
2052   size_t a_idx = a->axes[aux->a].stack_idx;
2053   size_t b_idx = b->axes[aux->a].stack_idx;
2054   if (a_idx != b_idx)
2055     return a_idx < b_idx ? -1 : 1;
2056
2057   const struct ctables_nest *nest = &aux->t->stacks[aux->a].nests[a_idx];
2058   for (size_t i = 0; i < nest->n; i++)
2059     if (i != nest->scale_idx)
2060       {
2061         const struct variable *var = nest->vars[i];
2062         const struct ctables_cell_value *a_cv = &a->axes[aux->a].cvs[i];
2063         const struct ctables_cell_value *b_cv = &b->axes[aux->a].cvs[i];
2064         if (a_cv->category != b_cv->category)
2065           return a_cv->category > b_cv->category ? 1 : -1;
2066
2067         const union value *a_val = &a_cv->value;
2068         const union value *b_val = &b_cv->value;
2069         switch (a_cv->category->type)
2070           {
2071           case CCT_NUMBER:
2072           case CCT_STRING:
2073           case CCT_SUBTOTAL:
2074           case CCT_HSUBTOTAL:
2075           case CCT_TOTAL:
2076             /* Must be equal. */
2077             continue;
2078
2079           case CCT_RANGE:
2080           case CCT_MISSING:
2081           case CCT_OTHERNM:
2082             {
2083               int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2084               if (cmp)
2085                 return cmp;
2086             }
2087             break;
2088
2089           case CCT_VALUE:
2090             {
2091               int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2092               if (cmp)
2093                 return a_cv->category->sort_ascending ? cmp : -cmp;
2094             }
2095             break;
2096
2097           case CCT_LABEL:
2098             {
2099               const char *a_label = var_lookup_value_label (var, a_val);
2100               const char *b_label = var_lookup_value_label (var, b_val);
2101               int cmp = (a_label
2102                          ? (b_label ? strcmp (a_label, b_label) : 1)
2103                          : (b_label ? -1 : value_compare_3way (
2104                               a_val, b_val, var_get_width (var))));
2105               if (cmp)
2106                 return a_cv->category->sort_ascending ? cmp : -cmp;
2107             }
2108             break;
2109
2110           case CCT_FUNCTION:
2111             NOT_REACHED ();
2112           }
2113       }
2114   return 0;
2115 }
2116
2117 /* Algorithm:
2118
2119    For each row:
2120        For each ctables_table:
2121            For each combination of row vars:
2122                For each combination of column vars:
2123                    For each combination of layer vars:
2124                        Add entry
2125    Make a table of row values:
2126        Sort entries by row values
2127        Assign a 0-based index to each actual value
2128        Construct a dimension
2129    Make a table of column values
2130    Make a table of layer values
2131    For each entry:
2132        Fill the table entry using the indexes from before.
2133  */
2134
2135 static struct ctables_domain *
2136 ctables_domain_insert (struct ctables_table *t, struct ctables_cell *cell,
2137                        enum ctables_domain_type domain)
2138 {
2139   size_t hash = 0;
2140   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2141     {
2142       size_t idx = cell->axes[a].stack_idx;
2143       const struct ctables_nest *nest = &t->stacks[a].nests[idx];
2144       hash = hash_int (idx, hash);
2145       for (size_t i = 0; i < nest->n_domains[domain]; i++)
2146         {
2147           size_t v_idx = nest->domains[domain][i];
2148           hash = value_hash (&cell->axes[a].cvs[v_idx].value,
2149                              var_get_width (nest->vars[v_idx]), hash);
2150         }
2151     }
2152
2153   struct ctables_domain *d;
2154   HMAP_FOR_EACH_WITH_HASH (d, struct ctables_domain, node, hash, &t->domains[domain])
2155     {
2156       const struct ctables_cell *df = d->example;
2157       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2158         {
2159           size_t idx = cell->axes[a].stack_idx;
2160           if (idx != df->axes[a].stack_idx)
2161             goto not_equal;
2162
2163           const struct ctables_nest *nest = &t->stacks[a].nests[idx];
2164           for (size_t i = 0; i < nest->n_domains[domain]; i++)
2165             {
2166               size_t v_idx = nest->domains[domain][i];
2167               if (!value_equal (&df->axes[a].cvs[v_idx].value,
2168                                 &cell->axes[a].cvs[v_idx].value,
2169                                 var_get_width (nest->vars[v_idx])))
2170                 goto not_equal;
2171             }
2172         }
2173       return d;
2174
2175     not_equal: ;
2176     }
2177
2178   d = xmalloc (sizeof *d);
2179   *d = (struct ctables_domain) { .example = cell };
2180   hmap_insert (&t->domains[domain], &d->node, hash);
2181   return d;
2182 }
2183
2184 static const struct ctables_category *
2185 ctables_categories_match (const struct ctables_categories *c,
2186                           const union value *v, const struct variable *var)
2187 {
2188   const struct ctables_category *othernm = NULL;
2189   for (size_t i = c->n_cats; i-- > 0; )
2190     {
2191       const struct ctables_category *cat = &c->cats[i];
2192       switch (cat->type)
2193         {
2194         case CCT_NUMBER:
2195           if (cat->number == v->f)
2196             return cat;
2197           break;
2198
2199         case CCT_STRING:
2200           NOT_REACHED ();
2201
2202         case CCT_RANGE:
2203           if ((cat->range[0] == -DBL_MAX || v->f >= cat->range[0])
2204               && (cat->range[1] == DBL_MAX || v->f <= cat->range[1]))
2205             return cat;
2206           break;
2207
2208         case CCT_MISSING:
2209           if (var_is_value_missing (var, v))
2210             return cat;
2211           break;
2212
2213         case CCT_OTHERNM:
2214           if (!othernm)
2215             othernm = cat;
2216           break;
2217
2218         case CCT_SUBTOTAL:
2219         case CCT_HSUBTOTAL:
2220         case CCT_TOTAL:
2221           break;
2222
2223         case CCT_VALUE:
2224         case CCT_LABEL:
2225         case CCT_FUNCTION:
2226           return (cat->include_missing || !var_is_value_missing (var, v) ? cat
2227                   : NULL);
2228         }
2229     }
2230
2231   return var_is_value_missing (var, v) ? NULL : othernm;
2232 }
2233
2234 static const struct ctables_category *
2235 ctables_categories_total (const struct ctables_categories *c)
2236 {
2237   const struct ctables_category *first = &c->cats[0];
2238   const struct ctables_category *last = &c->cats[c->n_cats - 1];
2239   return (first->type == CCT_TOTAL ? first
2240           : last->type == CCT_TOTAL ? last
2241           : NULL);
2242 }
2243
2244 static struct ctables_cell *
2245 ctables_cell_insert__ (struct ctables_table *t, const struct ccase *c,
2246                        size_t ix[PIVOT_N_AXES],
2247                        const struct ctables_category *cats[PIVOT_N_AXES][10])
2248 {
2249   const struct ctables_nest *ss = &t->stacks[t->summary_axis].nests[ix[t->summary_axis]];
2250
2251   size_t hash = 0;
2252   enum ctables_summary_variant sv = CSV_CELL;
2253   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2254     {
2255       const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2256       hash = hash_int (ix[a], hash);
2257       for (size_t i = 0; i < nest->n; i++)
2258         if (i != nest->scale_idx)
2259           {
2260             hash = hash_pointer (cats[a][i], hash);
2261             if (cats[a][i]->type != CCT_TOTAL
2262                 && cats[a][i]->type != CCT_SUBTOTAL
2263                 && cats[a][i]->type != CCT_HSUBTOTAL)
2264               hash = value_hash (case_data (c, nest->vars[i]),
2265                                  var_get_width (nest->vars[i]), hash);
2266             else
2267               sv = CSV_TOTAL;
2268           }
2269     }
2270
2271   struct ctables_cell *cell;
2272   HMAP_FOR_EACH_WITH_HASH (cell, struct ctables_cell, node, hash, &t->cells)
2273     {
2274       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2275         {
2276           const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2277           if (cell->axes[a].stack_idx != ix[a])
2278             goto not_equal;
2279           for (size_t i = 0; i < nest->n; i++)
2280             if (i != nest->scale_idx
2281                 && (cats[a][i] != cell->axes[a].cvs[i].category
2282                     || (cats[a][i]->type != CCT_TOTAL
2283                         && cats[a][i]->type != CCT_SUBTOTAL
2284                         && cats[a][i]->type != CCT_HSUBTOTAL
2285                         && !value_equal (case_data (c, nest->vars[i]),
2286                                          &cell->axes[a].cvs[i].value,
2287                                          var_get_width (nest->vars[i])))))
2288                 goto not_equal;
2289         }
2290
2291       return cell;
2292
2293     not_equal: ;
2294     }
2295
2296   cell = xmalloc (sizeof *cell);
2297   cell->hide = false;
2298   cell->sv = sv;
2299   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2300     {
2301       const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2302       cell->axes[a].stack_idx = ix[a];
2303       cell->axes[a].cvs = (nest->n
2304                         ? xnmalloc (nest->n, sizeof *cell->axes[a].cvs)
2305                         : NULL);
2306       for (size_t i = 0; i < nest->n; i++)
2307         {
2308           if (i != nest->scale_idx)
2309             {
2310               const struct ctables_category *subtotal = cats[a][i]->subtotal;
2311               if (subtotal && subtotal->type == CCT_HSUBTOTAL)
2312                 cell->hide = true;
2313             }
2314
2315           cell->axes[a].cvs[i].category = cats[a][i];
2316           value_clone (&cell->axes[a].cvs[i].value, case_data (c, nest->vars[i]),
2317                        var_get_width (nest->vars[i]));
2318         }
2319     }
2320
2321   const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2322   cell->summaries = xmalloc (specs->n * sizeof *cell->summaries);
2323   for (size_t i = 0; i < specs->n; i++)
2324     ctables_summary_init (&cell->summaries[i], &specs->specs[i]);
2325   for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2326     cell->domains[dt] = ctables_domain_insert (t, cell, dt);
2327   hmap_insert (&t->cells, &cell->node, hash);
2328   return cell;
2329 }
2330
2331 static void
2332 ctables_cell_add__ (struct ctables_table *t, const struct ccase *c,
2333                     size_t ix[PIVOT_N_AXES],
2334                     const struct ctables_category *cats[PIVOT_N_AXES][10],
2335                     double weight)
2336 {
2337   struct ctables_cell *cell = ctables_cell_insert__ (t, c, ix, cats);
2338   const struct ctables_nest *ss = &t->stacks[t->summary_axis].nests[ix[t->summary_axis]];
2339
2340   const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2341   for (size_t i = 0; i < specs->n; i++)
2342     ctables_summary_add (&cell->summaries[i], &specs->specs[i], specs->var,
2343                          case_data (c, specs->var), weight);
2344   for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2345     cell->domains[dt]->valid += weight;
2346 }
2347
2348 static void
2349 recurse_totals (struct ctables_table *t, const struct ccase *c,
2350                 size_t ix[PIVOT_N_AXES],
2351                 const struct ctables_category *cats[PIVOT_N_AXES][10],
2352                 double weight,
2353                 enum pivot_axis_type start_axis, size_t start_nest)
2354 {
2355   for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2356     {
2357       const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2358       for (size_t i = start_nest; i < nest->n; i++)
2359         {
2360           if (i == nest->scale_idx)
2361             continue;
2362
2363           const struct variable *var = nest->vars[i];
2364
2365           const struct ctables_category *total = ctables_categories_total (
2366             t->categories[var_get_dict_index (var)]);
2367           if (total)
2368             {
2369               const struct ctables_category *save = cats[a][i];
2370               cats[a][i] = total;
2371               ctables_cell_add__ (t, c, ix, cats, weight);
2372               recurse_totals (t, c, ix, cats, weight, a, i + 1);
2373               cats[a][i] = save;
2374             }
2375         }
2376       start_nest = 0;
2377     }
2378 }
2379
2380 static void
2381 ctables_cell_insert (struct ctables_table *t,
2382                      const struct ccase *c,
2383                      size_t ir, size_t ic, size_t il,
2384                      double weight)
2385 {
2386   size_t ix[PIVOT_N_AXES] = {
2387     [PIVOT_AXIS_ROW] = ir,
2388     [PIVOT_AXIS_COLUMN] = ic,
2389     [PIVOT_AXIS_LAYER] = il,
2390   };
2391
2392   const struct ctables_category *cats[PIVOT_N_AXES][10];
2393   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2394     {
2395       const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2396       for (size_t i = 0; i < nest->n; i++)
2397         {
2398           if (i == nest->scale_idx)
2399             continue;
2400
2401           const struct variable *var = nest->vars[i];
2402           const union value *value = case_data (c, var);
2403
2404           if (var_is_numeric (var) && value->f == SYSMIS)
2405             return;
2406
2407           cats[a][i] = ctables_categories_match (
2408             t->categories[var_get_dict_index (var)], value, var);
2409           if (!cats[a][i])
2410             return;
2411         }
2412     }
2413
2414   ctables_cell_add__ (t, c, ix, cats, weight);
2415
2416   recurse_totals (t, c, ix, cats, weight, 0, 0);
2417
2418   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2419     {
2420       const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2421       for (size_t i = 0; i < nest->n; i++)
2422         {
2423           if (i == nest->scale_idx)
2424             continue;
2425
2426           const struct ctables_category *save = cats[a][i];
2427           if (save->subtotal)
2428             {
2429               cats[a][i] = save->subtotal;
2430               ctables_cell_add__ (t, c, ix, cats, weight);
2431               cats[a][i] = save;
2432             }
2433         }
2434     }
2435 }
2436
2437 struct merge_item
2438   {
2439     const struct ctables_summary_spec_set *set;
2440     size_t ofs;
2441   };
2442
2443 static int
2444 merge_item_compare_3way (const struct merge_item *a, const struct merge_item *b)
2445 {
2446   const struct ctables_summary_spec *as = &a->set->specs[a->ofs];
2447   const struct ctables_summary_spec *bs = &b->set->specs[b->ofs];
2448   if (as->function != bs->function)
2449     return as->function > bs->function ? 1 : -1;
2450   else if (as->percentile != bs->percentile)
2451     return as->percentile < bs->percentile ? 1 : -1;
2452   return strcmp (as->label, bs->label);
2453 }
2454
2455 static void
2456 ctables_table_output_same_axis (struct ctables *ct, struct ctables_table *t)
2457 {
2458   struct pivot_table *pt = pivot_table_create__ (
2459     (t->title
2460      ? pivot_value_new_user_text (t->title, SIZE_MAX)
2461      : pivot_value_new_text (N_("Custom Tables"))),
2462     "Custom Tables");
2463   if (t->caption)
2464     pivot_table_set_caption (
2465       pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
2466   if (t->corner)
2467     pivot_table_set_caption (
2468       pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
2469
2470   pivot_table_set_look (pt, ct->look);
2471   struct pivot_dimension *d[PIVOT_N_AXES];
2472   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2473     {
2474       static const char *names[] = {
2475         [PIVOT_AXIS_ROW] = N_("Rows"),
2476         [PIVOT_AXIS_COLUMN] = N_("Columns"),
2477         [PIVOT_AXIS_LAYER] = N_("Layers"),
2478       };
2479       d[a] = (t->axes[a] || a == t->summary_axis
2480               ? pivot_dimension_create (pt, a, names[a])
2481               : NULL);
2482       if (!d[a])
2483         continue;
2484
2485       assert (t->axes[a]);
2486
2487       struct ctables_cell **sorted = xnmalloc (t->cells.count, sizeof *sorted);
2488
2489       struct ctables_cell *cell;
2490       size_t n = 0;
2491       HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2492         if (!cell->hide)
2493           sorted[n++] = cell;
2494       assert (n <= t->cells.count);
2495
2496       struct ctables_cell_sort_aux aux = { .t = t, .a = a };
2497       sort (sorted, n, sizeof *sorted, ctables_cell_compare_3way, &aux);
2498
2499       size_t max_depth = 0;
2500       for (size_t j = 0; j < t->stacks[a].n; j++)
2501         if (t->stacks[a].nests[j].n > max_depth)
2502           max_depth = t->stacks[a].nests[j].n;
2503
2504       struct pivot_category **groups = xnmalloc (max_depth, sizeof *groups);
2505       struct pivot_category *top = NULL;
2506       int prev_leaf = 0;
2507       for (size_t j = 0; j < n; j++)
2508         {
2509           struct ctables_cell *cell = sorted[j];
2510           const struct ctables_nest *nest = &t->stacks[a].nests[cell->axes[a].stack_idx];
2511
2512           size_t n_common = 0;
2513           bool new_subtable = false;
2514           if (j > 0)
2515             {
2516               struct ctables_cell *prev = sorted[j - 1];
2517               if (prev->axes[a].stack_idx == cell->axes[a].stack_idx)
2518                 {
2519                   for (; n_common < nest->n; n_common++)
2520                     if (n_common != nest->scale_idx
2521                         && (prev->axes[a].cvs[n_common].category
2522                             != cell->axes[a].cvs[n_common].category
2523                             || !value_equal (&prev->axes[a].cvs[n_common].value,
2524                                              &cell->axes[a].cvs[n_common].value,
2525                                              var_get_type (nest->vars[n_common]))))
2526                       break;
2527                 }
2528               else
2529                 new_subtable = true;
2530             }
2531           else
2532             new_subtable = true;
2533
2534           if (new_subtable)
2535             {
2536               enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[0])];
2537               top = d[a]->root;
2538               if (vlabel != CTVL_NONE)
2539                 top = pivot_category_create_group__ (
2540                   top, pivot_value_new_variable (nest->vars[0]));
2541             }
2542           if (n_common == nest->n)
2543             {
2544               cell->axes[a].leaf = prev_leaf;
2545               continue;
2546             }
2547
2548           for (size_t k = n_common; k < nest->n; k++)
2549             {
2550               struct pivot_category *parent = k > 0 ? groups[k - 1] : top;
2551
2552               struct pivot_value *label
2553                 = (k == nest->scale_idx ? NULL
2554                    : (cell->axes[a].cvs[k].category->type == CCT_TOTAL
2555                       || cell->axes[a].cvs[k].category->type == CCT_SUBTOTAL
2556                       || cell->axes[a].cvs[k].category->type == CCT_HSUBTOTAL)
2557                    ? pivot_value_new_user_text (cell->axes[a].cvs[k].category->total_label,
2558                                                 SIZE_MAX)
2559                    : pivot_value_new_var_value (nest->vars[k],
2560                                                 &cell->axes[a].cvs[k].value));
2561               if (k == nest->n - 1)
2562                 {
2563                   if (a == t->summary_axis)
2564                     {
2565                       if (label)
2566                         parent = pivot_category_create_group__ (parent, label);
2567                       const struct ctables_summary_spec_set *specs = &nest->specs[cell->sv];
2568                       for (size_t m = 0; m < specs->n; m++)
2569                         {
2570                           int leaf = pivot_category_create_leaf (
2571                             parent, pivot_value_new_text (specs->specs[m].label));
2572                           if (m == 0)
2573                             prev_leaf = leaf;
2574                         }
2575                     }
2576                   else
2577                     {
2578                       /* This assertion is true as long as the summary axis
2579                          is the axis where the summaries are displayed. */
2580                       assert (label);
2581
2582                       prev_leaf = pivot_category_create_leaf (parent, label);
2583                     }
2584                   break;
2585                 }
2586
2587               if (label)
2588                 parent = pivot_category_create_group__ (parent, label);
2589
2590               enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k + 1])];
2591               if (vlabel != CTVL_NONE)
2592                 parent = pivot_category_create_group__ (
2593                   parent, pivot_value_new_variable (nest->vars[k + 1]));
2594               groups[k] = parent;
2595             }
2596
2597           cell->axes[a].leaf = prev_leaf;
2598         }
2599       free (sorted);
2600       free (groups);
2601     }
2602   struct ctables_cell *cell;
2603   HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2604     {
2605       if (cell->hide)
2606         continue;
2607
2608       const struct ctables_nest *nest = &t->stacks[t->summary_axis].nests[cell->axes[t->summary_axis].stack_idx];
2609       const struct ctables_summary_spec_set *specs = &nest->specs[cell->sv];
2610       for (size_t j = 0; j < specs->n; j++)
2611         {
2612           size_t dindexes[3];
2613           size_t n_dindexes = 0;
2614
2615           for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2616             if (d[a])
2617               {
2618                 int leaf = cell->axes[a].leaf;
2619                 if (a == t->summary_axis)
2620                   leaf += j;
2621                 dindexes[n_dindexes++] = leaf;
2622               }
2623
2624           double d = ctables_summary_value (cell, &cell->summaries[j], &specs->specs[j]);
2625           struct pivot_value *value = pivot_value_new_number (d);
2626           value->numeric.format = specs->specs[j].format;
2627           pivot_table_put (pt, dindexes, n_dindexes, value);
2628         }
2629     }
2630
2631   pivot_table_submit (pt);
2632 }
2633
2634
2635 static void
2636 ctables_table_output_different_axis (struct ctables *ct, struct ctables_table *t)
2637 {
2638   struct pivot_table *pt = pivot_table_create__ (
2639     (t->title
2640      ? pivot_value_new_user_text (t->title, SIZE_MAX)
2641      : pivot_value_new_text (N_("Custom Tables"))),
2642     "Custom Tables");
2643   if (t->caption)
2644     pivot_table_set_caption (
2645       pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
2646   if (t->corner)
2647     pivot_table_set_caption (
2648       pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
2649
2650   pivot_table_set_look (pt, ct->look);
2651   struct pivot_dimension *d[PIVOT_N_AXES];
2652   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2653     {
2654       static const char *names[] = {
2655         [PIVOT_AXIS_ROW] = N_("Rows"),
2656         [PIVOT_AXIS_COLUMN] = N_("Columns"),
2657         [PIVOT_AXIS_LAYER] = N_("Layers"),
2658       };
2659       d[a] = (t->axes[a] || a == t->summary_axis
2660               ? pivot_dimension_create (pt, a, names[a])
2661               : NULL);
2662       if (!d[a])
2663         continue;
2664
2665       assert (t->axes[a]);
2666
2667       struct ctables_cell **sorted = xnmalloc (t->cells.count, sizeof *sorted);
2668
2669       struct ctables_cell *cell;
2670       size_t n = 0;
2671       HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2672         if (!cell->hide)
2673           sorted[n++] = cell;
2674       assert (n <= t->cells.count);
2675
2676       struct ctables_cell_sort_aux aux = { .t = t, .a = a };
2677       sort (sorted, n, sizeof *sorted, ctables_cell_compare_3way, &aux);
2678
2679       size_t max_depth = 0;
2680       for (size_t j = 0; j < t->stacks[a].n; j++)
2681         if (t->stacks[a].nests[j].n > max_depth)
2682           max_depth = t->stacks[a].nests[j].n;
2683
2684       struct pivot_category **groups = xnmalloc (max_depth, sizeof *groups);
2685       struct pivot_category *top = NULL;
2686       int prev_leaf = 0;
2687       for (size_t j = 0; j < n; j++)
2688         {
2689           struct ctables_cell *cell = sorted[j];
2690           const struct ctables_nest *nest = &t->stacks[a].nests[cell->axes[a].stack_idx];
2691
2692           size_t n_common = 0;
2693           bool new_subtable = false;
2694           if (j > 0)
2695             {
2696               struct ctables_cell *prev = sorted[j - 1];
2697               if (prev->axes[a].stack_idx == cell->axes[a].stack_idx)
2698                 {
2699                   for (; n_common < nest->n; n_common++)
2700                     if (n_common != nest->scale_idx
2701                         && (prev->axes[a].cvs[n_common].category
2702                             != cell->axes[a].cvs[n_common].category
2703                             || !value_equal (&prev->axes[a].cvs[n_common].value,
2704                                              &cell->axes[a].cvs[n_common].value,
2705                                              var_get_type (nest->vars[n_common]))))
2706                       break;
2707                 }
2708               else
2709                 new_subtable = true;
2710             }
2711           else
2712             new_subtable = true;
2713
2714           if (new_subtable)
2715             {
2716               enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[0])];
2717               top = d[a]->root;
2718               if (vlabel != CTVL_NONE)
2719                 top = pivot_category_create_group__ (
2720                   top, pivot_value_new_variable (nest->vars[0]));
2721             }
2722           if (n_common == nest->n)
2723             {
2724               cell->axes[a].leaf = prev_leaf;
2725               continue;
2726             }
2727
2728           for (size_t k = n_common; k < nest->n; k++)
2729             {
2730               struct pivot_category *parent = k > 0 ? groups[k - 1] : top;
2731
2732               struct pivot_value *label
2733                 = (k == nest->scale_idx ? NULL
2734                    : (cell->axes[a].cvs[k].category->type == CCT_TOTAL
2735                       || cell->axes[a].cvs[k].category->type == CCT_SUBTOTAL
2736                       || cell->axes[a].cvs[k].category->type == CCT_HSUBTOTAL)
2737                    ? pivot_value_new_user_text (cell->axes[a].cvs[k].category->total_label,
2738                                                 SIZE_MAX)
2739                    : pivot_value_new_var_value (nest->vars[k],
2740                                                 &cell->axes[a].cvs[k].value));
2741               if (k == nest->n - 1)
2742                 {
2743                   if (a == t->slabels_axis)
2744                     {
2745                       if (label)
2746                         parent = pivot_category_create_group__ (parent, label);
2747                       const struct ctables_summary_spec_set *specs = &t->summary_specs;
2748                       for (size_t m = 0; m < specs->n; m++)
2749                         {
2750                           int leaf = pivot_category_create_leaf (
2751                             parent, pivot_value_new_text (specs->specs[m].label));
2752                           if (m == 0)
2753                             prev_leaf = leaf;
2754                         }
2755                     }
2756                   else
2757                     {
2758                       prev_leaf = pivot_category_create_leaf (parent, label ? label : pivot_value_new_user_text ("text", SIZE_MAX));
2759                     }
2760                   break;
2761                 }
2762
2763               if (label)
2764                 parent = pivot_category_create_group__ (parent, label);
2765
2766               enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k + 1])];
2767               if (vlabel != CTVL_NONE)
2768                 parent = pivot_category_create_group__ (
2769                   parent, pivot_value_new_variable (nest->vars[k + 1]));
2770               groups[k] = parent;
2771             }
2772
2773           cell->axes[a].leaf = prev_leaf;
2774         }
2775       free (sorted);
2776       free (groups);
2777     }
2778   pivot_table_submit (pt);
2779 }
2780
2781
2782 static void
2783 ctables_prepare_table (struct ctables_table *t)
2784 {
2785   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2786     if (t->axes[a])
2787       {
2788         t->stacks[a] = enumerate_fts (a, t->axes[a]);
2789
2790         for (size_t j = 0; j < t->stacks[a].n; j++)
2791           {
2792             struct ctables_nest *nest = &t->stacks[a].nests[j];
2793             for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2794               {
2795                 nest->domains[dt] = xmalloc (nest->n * sizeof *nest->domains[dt]);
2796                 nest->n_domains[dt] = 0;
2797
2798                 for (size_t k = 0; k < nest->n; k++)
2799                   {
2800                     if (k == nest->scale_idx)
2801                       continue;
2802
2803                     switch (dt)
2804                       {
2805                       case CTDT_TABLE:
2806                         continue;
2807
2808                       case CTDT_LAYER:
2809                         if (a != PIVOT_AXIS_LAYER)
2810                           continue;
2811                         break;
2812
2813                       case CTDT_SUBTABLE:
2814                       case CTDT_ROW:
2815                       case CTDT_COL:
2816                         if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
2817                             : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
2818                             : a == PIVOT_AXIS_ROW)
2819                           {
2820                             if (k == nest->n - 1
2821                                 || (nest->scale_idx == nest->n - 1
2822                                     && k == nest->n - 2))
2823                               continue;
2824                           }
2825                         break;
2826
2827                       case CTDT_LAYERROW:
2828                         if (a == PIVOT_AXIS_COLUMN)
2829                           continue;
2830                         break;
2831
2832                       case CTDT_LAYERCOL:
2833                         if (a == PIVOT_AXIS_ROW)
2834                           continue;
2835                         break;
2836                       }
2837
2838                     nest->domains[dt][nest->n_domains[dt]++] = k;
2839                   }
2840               }
2841           }
2842       }
2843     else
2844       {
2845         struct ctables_nest *nest = xmalloc (sizeof *nest);
2846         *nest = (struct ctables_nest) { .n = 0 };
2847         t->stacks[a] = (struct ctables_stack) { .nests = nest, .n = 1 };
2848       }
2849
2850   struct ctables_stack *stack = &t->stacks[t->summary_axis];
2851   for (size_t i = 0; i < stack->n; i++)
2852     {
2853       struct ctables_nest *nest = &stack->nests[i];
2854       if (!nest->specs[CSV_CELL].n)
2855         {
2856           struct ctables_summary_spec_set *specs = &nest->specs[CSV_CELL];
2857           specs->specs = xmalloc (sizeof *specs->specs);
2858           specs->n = 1;
2859
2860           enum ctables_summary_function function
2861             = specs->var ? CTSF_MEAN : CTSF_COUNT;
2862           struct ctables_var var = { .is_mrset = false, .var = specs->var };
2863
2864           *specs->specs = (struct ctables_summary_spec) {
2865             .function = function,
2866             .format = ctables_summary_default_format (function, &var),
2867             .label = ctables_summary_default_label (function, 0),
2868           };
2869           if (!specs->var)
2870             specs->var = nest->vars[0];
2871
2872           ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
2873                                           &nest->specs[CSV_CELL]);
2874         }
2875       else if (!nest->specs[CSV_TOTAL].n)
2876         ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
2877                                         &nest->specs[CSV_CELL]);
2878     }
2879
2880   struct ctables_summary_spec_set *merged = &t->summary_specs;
2881   struct merge_item *items = xnmalloc (2 * stack->n, sizeof *items);
2882   size_t n_left = 0;
2883   for (size_t j = 0; j < stack->n; j++)
2884     {
2885       const struct ctables_nest *nest = &stack->nests[j];
2886       if (nest->n)
2887         for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
2888           items[n_left++] = (struct merge_item) { .set = &nest->specs[sv] };
2889     }
2890
2891   while (n_left > 0)
2892     {
2893       struct merge_item min = items[0];
2894       for (size_t j = 1; j < n_left; j++)
2895         if (merge_item_compare_3way (&items[j], &min) < 0)
2896           min = items[j];
2897
2898       if (merged->n >= merged->allocated)
2899         merged->specs = x2nrealloc (merged->specs, &merged->allocated,
2900                                     sizeof *merged->specs);
2901       merged->specs[merged->n++] = min.set->specs[min.ofs];
2902
2903       for (size_t j = 0; j < n_left; )
2904         {
2905           if (merge_item_compare_3way (&items[j], &min) == 0)
2906             {
2907               struct merge_item *item = &items[j];
2908               item->set->specs[item->ofs].axis_idx = merged->n - 1;
2909               if (++item->ofs >= item->set->n)
2910                 {
2911                   items[j] = items[--n_left];
2912                   continue;
2913                 }
2914             }
2915           j++;
2916         }
2917     }
2918
2919 #if 0
2920   for (size_t j = 0; j < merged->n; j++)
2921     printf ("%s\n", ctables_summary_function_name (merged->specs[j].function));
2922
2923   for (size_t j = 0; j < stack->n; j++)
2924     {
2925       const struct ctables_nest *nest = &stack->nests[j];
2926       for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
2927         {
2928           const struct ctables_summary_spec_set *specs = &nest->specs[sv];
2929           for (size_t k = 0; k < specs->n; k++)
2930             printf ("(%s, %zu) ", ctables_summary_function_name (specs->specs[k].function),
2931                     specs->specs[k].axis_idx);
2932           printf ("\n");
2933         }
2934     }
2935 #endif
2936 }
2937
2938 static bool
2939 ctables_execute (struct dataset *ds, struct ctables *ct)
2940 {
2941   struct casereader *input = casereader_create_filter_weight (proc_open (ds),
2942                                                               dataset_dict (ds),
2943                                                               NULL, NULL);
2944   bool warn_on_invalid = true;
2945   double total_weight = 0;
2946   for (struct ccase *c = casereader_read (input); c;
2947        case_unref (c), c = casereader_read (input))
2948     {
2949       double weight = dict_get_case_weight (dataset_dict (ds), c,
2950                                             &warn_on_invalid);
2951       total_weight += weight;
2952
2953       for (size_t i = 0; i < ct->n_tables; i++)
2954         {
2955           struct ctables_table *t = ct->tables[i];
2956
2957           for (size_t ir = 0; ir < t->stacks[PIVOT_AXIS_ROW].n; ir++)
2958             for (size_t ic = 0; ic < t->stacks[PIVOT_AXIS_COLUMN].n; ic++)
2959               for (size_t il = 0; il < t->stacks[PIVOT_AXIS_LAYER].n; il++)
2960                 ctables_cell_insert (t, c, ir, ic, il, weight);
2961         }
2962     }
2963   casereader_destroy (input);
2964
2965   for (size_t i = 0; i < ct->n_tables; i++)
2966     {
2967       struct ctables_table *t = ct->tables[i];
2968       if (t->summary_axis == t->slabels_axis)
2969         ctables_table_output_same_axis (ct, ct->tables[i]);
2970       else
2971         ctables_table_output_different_axis (ct, ct->tables[i]);
2972     }
2973   return proc_commit (ds);
2974 }
2975
2976 int
2977 cmd_ctables (struct lexer *lexer, struct dataset *ds)
2978 {
2979   size_t n_vars = dict_get_n_vars (dataset_dict (ds));
2980   enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
2981   enum settings_value_show tvars = settings_get_show_variables ();
2982   for (size_t i = 0; i < n_vars; i++)
2983     vlabels[i] = (enum ctables_vlabel) tvars;
2984
2985   struct ctables *ct = xmalloc (sizeof *ct);
2986   *ct = (struct ctables) {
2987     .look = pivot_table_look_unshare (pivot_table_look_ref (
2988                                         pivot_table_look_get_default ())),
2989     .vlabels = vlabels,
2990     .hide_threshold = 5,
2991   };
2992   ct->look->omit_empty = false;
2993
2994   if (!lex_force_match (lexer, T_SLASH))
2995     goto error;
2996
2997   while (!lex_match_id (lexer, "TABLE"))
2998     {
2999       if (lex_match_id (lexer, "FORMAT"))
3000         {
3001           double widths[2] = { SYSMIS, SYSMIS };
3002           double units_per_inch = 72.0;
3003
3004           while (lex_token (lexer) != T_SLASH)
3005             {
3006               if (lex_match_id (lexer, "MINCOLWIDTH"))
3007                 {
3008                   if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
3009                     goto error;
3010                 }
3011               else if (lex_match_id (lexer, "MAXCOLWIDTH"))
3012                 {
3013                   if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
3014                     goto error;
3015                 }
3016               else if (lex_match_id (lexer, "UNITS"))
3017                 {
3018                   lex_match (lexer, T_EQUALS);
3019                   if (lex_match_id (lexer, "POINTS"))
3020                     units_per_inch = 72.0;
3021                   else if (lex_match_id (lexer, "INCHES"))
3022                     units_per_inch = 1.0;
3023                   else if (lex_match_id (lexer, "CM"))
3024                     units_per_inch = 2.54;
3025                   else
3026                     {
3027                       lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
3028                       goto error;
3029                     }
3030                 }
3031               else if (lex_match_id (lexer, "EMPTY"))
3032                 {
3033                   free (ct->zero);
3034                   ct->zero = NULL;
3035
3036                   lex_match (lexer, T_EQUALS);
3037                   if (lex_match_id (lexer, "ZERO"))
3038                     {
3039                       /* Nothing to do. */
3040                     }
3041                   else if (lex_match_id (lexer, "BLANK"))
3042                     ct->zero = xstrdup ("");
3043                   else if (lex_force_string (lexer))
3044                     {
3045                       ct->zero = ss_xstrdup (lex_tokss (lexer));
3046                       lex_get (lexer);
3047                     }
3048                   else
3049                     goto error;
3050                 }
3051               else if (lex_match_id (lexer, "MISSING"))
3052                 {
3053                   lex_match (lexer, T_EQUALS);
3054                   if (!lex_force_string (lexer))
3055                     goto error;
3056
3057                   free (ct->missing);
3058                   ct->missing = (strcmp (lex_tokcstr (lexer), ".")
3059                                  ? ss_xstrdup (lex_tokss (lexer))
3060                                  : NULL);
3061                   lex_get (lexer);
3062                 }
3063               else
3064                 {
3065                   lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
3066                                        "UNITS", "EMPTY", "MISSING");
3067                   goto error;
3068                 }
3069             }
3070
3071           if (widths[0] != SYSMIS && widths[1] != SYSMIS
3072               && widths[0] > widths[1])
3073             {
3074               msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
3075               goto error;
3076             }
3077
3078           for (size_t i = 0; i < 2; i++)
3079             if (widths[i] != SYSMIS)
3080               {
3081                 int *wr = ct->look->width_ranges[TABLE_HORZ];
3082                 wr[i] = widths[i] / units_per_inch * 96.0;
3083                 if (wr[0] > wr[1])
3084                   wr[!i] = wr[i];
3085               }
3086         }
3087       else if (lex_match_id (lexer, "VLABELS"))
3088         {
3089           if (!lex_force_match_id (lexer, "VARIABLES"))
3090             goto error;
3091           lex_match (lexer, T_EQUALS);
3092
3093           struct variable **vars;
3094           size_t n_vars;
3095           if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
3096                                 PV_NO_SCRATCH))
3097             goto error;
3098
3099           if (!lex_force_match_id (lexer, "DISPLAY"))
3100             {
3101               free (vars);
3102               goto error;
3103             }
3104           lex_match (lexer, T_EQUALS);
3105
3106           enum ctables_vlabel vlabel;
3107           if (lex_match_id (lexer, "DEFAULT"))
3108             vlabel = (enum ctables_vlabel) settings_get_show_variables ();
3109           else if (lex_match_id (lexer, "NAME"))
3110             vlabel = CTVL_NAME;
3111           else if (lex_match_id (lexer, "LABEL"))
3112             vlabel = CTVL_LABEL;
3113           else if (lex_match_id (lexer, "BOTH"))
3114             vlabel = CTVL_BOTH;
3115           else if (lex_match_id (lexer, "NONE"))
3116             vlabel = CTVL_NONE;
3117           else
3118             {
3119               lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
3120                                    "BOTH", "NONE");
3121               free (vars);
3122               goto error;
3123             }
3124
3125           for (size_t i = 0; i < n_vars; i++)
3126             ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
3127           free (vars);
3128         }
3129       else if (lex_match_id (lexer, "MRSETS"))
3130         {
3131           if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
3132             goto error;
3133           lex_match (lexer, T_EQUALS);
3134           if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
3135             goto error;
3136         }
3137       else if (lex_match_id (lexer, "SMISSING"))
3138         {
3139           if (lex_match_id (lexer, "VARIABLE"))
3140             ct->smissing_listwise = false;
3141           else if (lex_match_id (lexer, "LISTWISE"))
3142             ct->smissing_listwise = true;
3143           else
3144             {
3145               lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
3146               goto error;
3147             }
3148         }
3149       /* XXX PCOMPUTE */
3150       else if (lex_match_id (lexer, "WEIGHT"))
3151         {
3152           if (!lex_force_match_id (lexer, "VARIABLE"))
3153             goto error;
3154           lex_match (lexer, T_EQUALS);
3155           ct->base_weight = parse_variable (lexer, dataset_dict (ds));
3156           if (!ct->base_weight)
3157             goto error;
3158         }
3159       else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
3160         {
3161           if (!lex_force_match_id (lexer, "COUNT"))
3162             goto error;
3163           lex_match (lexer, T_EQUALS);
3164           if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
3165             goto error;
3166           ct->hide_threshold = lex_integer (lexer);
3167           lex_get (lexer);
3168         }
3169       else
3170         {
3171           lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
3172                                "SMISSING", "PCOMPUTE", "PPROPERTIES",
3173                                "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
3174           goto error;
3175         }
3176
3177       if (!lex_force_match (lexer, T_SLASH))
3178         goto error;
3179     }
3180
3181   size_t allocated_tables = 0;
3182   do
3183     {
3184       if (ct->n_tables >= allocated_tables)
3185         ct->tables = x2nrealloc (ct->tables, &allocated_tables,
3186                                  sizeof *ct->tables);
3187
3188       struct ctables_category *cat = xmalloc (sizeof *cat);
3189       *cat = (struct ctables_category) {
3190         .type = CCT_VALUE,
3191         .include_missing = false,
3192         .sort_ascending = true,
3193       };
3194
3195       struct ctables_categories *c = xmalloc (sizeof *c);
3196       size_t n_vars = dict_get_n_vars (dataset_dict (ds));
3197       *c = (struct ctables_categories) {
3198         .n_refs = n_vars,
3199         .cats = cat,
3200         .n_cats = 1,
3201       };
3202
3203       struct ctables_categories **categories = xnmalloc (n_vars,
3204                                                          sizeof *categories);
3205       for (size_t i = 0; i < n_vars; i++)
3206         categories[i] = c;
3207
3208       struct ctables_table *t = xmalloc (sizeof *t);
3209       *t = (struct ctables_table) {
3210         .cells = HMAP_INITIALIZER (t->cells),
3211         .slabels_axis = PIVOT_AXIS_COLUMN,
3212         .slabels_visible = true,
3213         .row_labels = CTLP_NORMAL,
3214         .col_labels = CTLP_NORMAL,
3215         .categories = categories,
3216         .n_categories = n_vars,
3217         .cilevel = 95,
3218       };
3219       for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3220         hmap_init (&t->domains[dt]);
3221       ct->tables[ct->n_tables++] = t;
3222
3223       lex_match (lexer, T_EQUALS);
3224       if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
3225         goto error;
3226       if (lex_match (lexer, T_BY))
3227         {
3228           if (!ctables_axis_parse (lexer, dataset_dict (ds),
3229                                    ct, t, PIVOT_AXIS_COLUMN))
3230             goto error;
3231
3232           if (lex_match (lexer, T_BY))
3233             {
3234               if (!ctables_axis_parse (lexer, dataset_dict (ds),
3235                                        ct, t, PIVOT_AXIS_LAYER))
3236                 goto error;
3237             }
3238         }
3239
3240       if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
3241           && !t->axes[PIVOT_AXIS_LAYER])
3242         {
3243           lex_error (lexer, _("At least one variable must be specified."));
3244           goto error;
3245         }
3246
3247       const struct ctables_axis *scales[PIVOT_N_AXES];
3248       size_t n_scales = 0;
3249       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3250         {
3251           scales[a] = find_scale (t->axes[a]);
3252           if (scales[a])
3253             n_scales++;
3254         }
3255       if (n_scales > 1)
3256         {
3257           msg (SE, _("Scale variables may appear only on one axis."));
3258           if (scales[PIVOT_AXIS_ROW])
3259             msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
3260                     _("This scale variable appears on the rows axis."));
3261           if (scales[PIVOT_AXIS_COLUMN])
3262             msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
3263                     _("This scale variable appears on the columns axis."));
3264           if (scales[PIVOT_AXIS_LAYER])
3265             msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
3266                     _("This scale variable appears on the layer axis."));
3267           goto error;
3268         }
3269
3270       const struct ctables_axis *summaries[PIVOT_N_AXES];
3271       size_t n_summaries = 0;
3272       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3273         {
3274           summaries[a] = (scales[a]
3275                           ? scales[a]
3276                           : find_categorical_summary_spec (t->axes[a]));
3277           if (summaries[a])
3278             n_summaries++;
3279         }
3280       if (n_summaries > 1)
3281         {
3282           msg (SE, _("Summaries may appear only on one axis."));
3283           if (summaries[PIVOT_AXIS_ROW])
3284             msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
3285                     _("This variable on the rows axis has a summary."));
3286           if (summaries[PIVOT_AXIS_COLUMN])
3287             msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
3288                     _("This variable on the columns axis has a summary."));
3289           if (summaries[PIVOT_AXIS_LAYER])
3290             msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
3291                     _("This variable on the layers axis has a summary."));
3292           goto error;
3293         }
3294       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3295         if (n_summaries ? summaries[a] : t->axes[a])
3296           {
3297             t->summary_axis = a;
3298             break;
3299           }
3300
3301       if (lex_token (lexer) == T_ENDCMD)
3302         break;
3303       if (!lex_force_match (lexer, T_SLASH))
3304         break;
3305
3306       while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
3307         {
3308           if (lex_match_id (lexer, "SLABELS"))
3309             {
3310               while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3311                 {
3312                   if (lex_match_id (lexer, "POSITION"))
3313                     {
3314                       lex_match (lexer, T_EQUALS);
3315                       if (lex_match_id (lexer, "COLUMN"))
3316                         t->slabels_axis = PIVOT_AXIS_COLUMN;
3317                       else if (lex_match_id (lexer, "ROW"))
3318                         t->slabels_axis = PIVOT_AXIS_ROW;
3319                       else if (lex_match_id (lexer, "LAYER"))
3320                         t->slabels_axis = PIVOT_AXIS_LAYER;
3321                       else
3322                         {
3323                           lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
3324                           goto error;
3325                         }
3326                     }
3327                   else if (lex_match_id (lexer, "VISIBLE"))
3328                     {
3329                       lex_match (lexer, T_EQUALS);
3330                       if (!parse_bool (lexer, &t->slabels_visible))
3331                         goto error;
3332                     }
3333                   else
3334                     {
3335                       lex_error_expecting (lexer, "POSITION", "VISIBLE");
3336                       goto error;
3337                     }
3338                 }
3339             }
3340           else if (lex_match_id (lexer, "CLABELS"))
3341             {
3342               while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3343                 {
3344                   if (lex_match_id (lexer, "AUTO"))
3345                     t->row_labels = t->col_labels = CTLP_NORMAL;
3346                   else if (lex_match_id (lexer, "ROWLABELS"))
3347                     {
3348                       lex_match (lexer, T_EQUALS);
3349                       if (lex_match_id (lexer, "OPPOSITE"))
3350                         t->row_labels = CTLP_OPPOSITE;
3351                       else if (lex_match_id (lexer, "LAYER"))
3352                         t->row_labels = CTLP_LAYER;
3353                       else
3354                         {
3355                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3356                           goto error;
3357                         }
3358                     }
3359                   else if (lex_match_id (lexer, "COLLABELS"))
3360                     {
3361                       lex_match (lexer, T_EQUALS);
3362                       if (lex_match_id (lexer, "OPPOSITE"))
3363                         t->col_labels = CTLP_OPPOSITE;
3364                       else if (lex_match_id (lexer, "LAYER"))
3365                         t->col_labels = CTLP_LAYER;
3366                       else
3367                         {
3368                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3369                           goto error;
3370                         }
3371                     }
3372                   else
3373                     {
3374                       lex_error_expecting (lexer, "AUTO", "ROWLABELS",
3375                                            "COLLABELS");
3376                       goto error;
3377                     }
3378                 }
3379             }
3380           else if (lex_match_id (lexer, "CRITERIA"))
3381             {
3382               if (!lex_force_match_id (lexer, "CILEVEL"))
3383                 goto error;
3384               lex_match (lexer, T_EQUALS);
3385
3386               if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
3387                 goto error;
3388               t->cilevel = lex_number (lexer);
3389               lex_get (lexer);
3390             }
3391           else if (lex_match_id (lexer, "CATEGORIES"))
3392             {
3393               if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
3394                 goto error;
3395             }
3396           else if (lex_match_id (lexer, "TITLES"))
3397             {
3398               do
3399                 {
3400                   char **textp;
3401                   if (lex_match_id (lexer, "CAPTION"))
3402                     textp = &t->caption;
3403                   else if (lex_match_id (lexer, "CORNER"))
3404                     textp = &t->corner;
3405                   else if (lex_match_id (lexer, "TITLE"))
3406                     textp = &t->title;
3407                   else
3408                     {
3409                       lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
3410                       goto error;
3411                     }
3412                   lex_match (lexer, T_EQUALS);
3413
3414                   struct string s = DS_EMPTY_INITIALIZER;
3415                   while (lex_is_string (lexer))
3416                     {
3417                       if (!ds_is_empty (&s))
3418                         ds_put_byte (&s, ' ');
3419                       ds_put_substring (&s, lex_tokss (lexer));
3420                       lex_get (lexer);
3421                     }
3422                   free (*textp);
3423                   *textp = ds_steal_cstr (&s);
3424                 }
3425               while (lex_token (lexer) != T_SLASH
3426                      && lex_token (lexer) != T_ENDCMD);
3427             }
3428           else if (lex_match_id (lexer, "SIGTEST"))
3429             {
3430               if (!t->chisq)
3431                 {
3432                   t->chisq = xmalloc (sizeof *t->chisq);
3433                   *t->chisq = (struct ctables_chisq) {
3434                     .alpha = .05,
3435                     .include_mrsets = true,
3436                     .all_visible = true,
3437                   };
3438                 }
3439
3440               do
3441                 {
3442                   if (lex_match_id (lexer, "TYPE"))
3443                     {
3444                       lex_match (lexer, T_EQUALS);
3445                       if (!lex_force_match_id (lexer, "CHISQUARE"))
3446                         goto error;
3447                     }
3448                   else if (lex_match_id (lexer, "ALPHA"))
3449                     {
3450                       lex_match (lexer, T_EQUALS);
3451                       if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
3452                         goto error;
3453                       t->chisq->alpha = lex_number (lexer);
3454                       lex_get (lexer);
3455                     }
3456                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3457                     {
3458                       lex_match (lexer, T_EQUALS);
3459                       if (parse_bool (lexer, &t->chisq->include_mrsets))
3460                         goto error;
3461                     }
3462                   else if (lex_match_id (lexer, "CATEGORIES"))
3463                     {
3464                       lex_match (lexer, T_EQUALS);
3465                       if (lex_match_id (lexer, "ALLVISIBLE"))
3466                         t->chisq->all_visible = true;
3467                       else if (lex_match_id (lexer, "SUBTOTALS"))
3468                         t->chisq->all_visible = false;
3469                       else
3470                         {
3471                           lex_error_expecting (lexer,
3472                                                "ALLVISIBLE", "SUBTOTALS");
3473                           goto error;
3474                         }
3475                     }
3476                   else
3477                     {
3478                       lex_error_expecting (lexer, "TYPE", "ALPHA",
3479                                            "INCLUDEMRSETS", "CATEGORIES");
3480                       goto error;
3481                     }
3482                 }
3483               while (lex_token (lexer) != T_SLASH
3484                      && lex_token (lexer) != T_ENDCMD);
3485             }
3486           else if (lex_match_id (lexer, "COMPARETEST"))
3487             {
3488               if (!t->pairwise)
3489                 {
3490                   t->pairwise = xmalloc (sizeof *t->pairwise);
3491                   *t->pairwise = (struct ctables_pairwise) {
3492                     .type = PROP,
3493                     .alpha = { .05, .05 },
3494                     .adjust = BONFERRONI,
3495                     .include_mrsets = true,
3496                     .meansvariance_allcats = true,
3497                     .all_visible = true,
3498                     .merge = false,
3499                     .apa_style = true,
3500                     .show_sig = false,
3501                   };
3502                 }
3503
3504               do
3505                 {
3506                   if (lex_match_id (lexer, "TYPE"))
3507                     {
3508                       lex_match (lexer, T_EQUALS);
3509                       if (lex_match_id (lexer, "PROP"))
3510                         t->pairwise->type = PROP;
3511                       else if (lex_match_id (lexer, "MEAN"))
3512                         t->pairwise->type = MEAN;
3513                       else
3514                         {
3515                           lex_error_expecting (lexer, "PROP", "MEAN");
3516                           goto error;
3517                         }
3518                     }
3519                   else if (lex_match_id (lexer, "ALPHA"))
3520                     {
3521                       lex_match (lexer, T_EQUALS);
3522
3523                       if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3524                         goto error;
3525                       double a0 = lex_number (lexer);
3526                       lex_get (lexer);
3527
3528                       lex_match (lexer, T_COMMA);
3529                       if (lex_is_number (lexer))
3530                         {
3531                           if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3532                             goto error;
3533                           double a1 = lex_number (lexer);
3534                           lex_get (lexer);
3535
3536                           t->pairwise->alpha[0] = MIN (a0, a1);
3537                           t->pairwise->alpha[1] = MAX (a0, a1);
3538                         }
3539                       else
3540                         t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
3541                     }
3542                   else if (lex_match_id (lexer, "ADJUST"))
3543                     {
3544                       lex_match (lexer, T_EQUALS);
3545                       if (lex_match_id (lexer, "BONFERRONI"))
3546                         t->pairwise->adjust = BONFERRONI;
3547                       else if (lex_match_id (lexer, "BH"))
3548                         t->pairwise->adjust = BH;
3549                       else if (lex_match_id (lexer, "NONE"))
3550                         t->pairwise->adjust = 0;
3551                       else
3552                         {
3553                           lex_error_expecting (lexer, "BONFERRONI", "BH",
3554                                                "NONE");
3555                           goto error;
3556                         }
3557                     }
3558                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3559                     {
3560                       lex_match (lexer, T_EQUALS);
3561                       if (!parse_bool (lexer, &t->pairwise->include_mrsets))
3562                         goto error;
3563                     }
3564                   else if (lex_match_id (lexer, "MEANSVARIANCE"))
3565                     {
3566                       lex_match (lexer, T_EQUALS);
3567                       if (lex_match_id (lexer, "ALLCATS"))
3568                         t->pairwise->meansvariance_allcats = true;
3569                       else if (lex_match_id (lexer, "TESTEDCATS"))
3570                         t->pairwise->meansvariance_allcats = false;
3571                       else
3572                         {
3573                           lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
3574                           goto error;
3575                         }
3576                     }
3577                   else if (lex_match_id (lexer, "CATEGORIES"))
3578                     {
3579                       lex_match (lexer, T_EQUALS);
3580                       if (lex_match_id (lexer, "ALLVISIBLE"))
3581                         t->pairwise->all_visible = true;
3582                       else if (lex_match_id (lexer, "SUBTOTALS"))
3583                         t->pairwise->all_visible = false;
3584                       else
3585                         {
3586                           lex_error_expecting (lexer, "ALLVISIBLE",
3587                                                "SUBTOTALS");
3588                           goto error;
3589                         }
3590                     }
3591                   else if (lex_match_id (lexer, "MERGE"))
3592                     {
3593                       lex_match (lexer, T_EQUALS);
3594                       if (!parse_bool (lexer, &t->pairwise->merge))
3595                         goto error;
3596                     }
3597                   else if (lex_match_id (lexer, "STYLE"))
3598                     {
3599                       lex_match (lexer, T_EQUALS);
3600                       if (lex_match_id (lexer, "APA"))
3601                         t->pairwise->apa_style = true;
3602                       else if (lex_match_id (lexer, "SIMPLE"))
3603                         t->pairwise->apa_style = false;
3604                       else
3605                         {
3606                           lex_error_expecting (lexer, "APA", "SIMPLE");
3607                           goto error;
3608                         }
3609                     }
3610                   else if (lex_match_id (lexer, "SHOWSIG"))
3611                     {
3612                       lex_match (lexer, T_EQUALS);
3613                       if (!parse_bool (lexer, &t->pairwise->show_sig))
3614                         goto error;
3615                     }
3616                   else
3617                     {
3618                       lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
3619                                            "INCLUDEMRSETS", "MEANSVARIANCE",
3620                                            "CATEGORIES", "MERGE", "STYLE",
3621                                            "SHOWSIG");
3622                       goto error;
3623                     }
3624                 }
3625               while (lex_token (lexer) != T_SLASH
3626                      && lex_token (lexer) != T_ENDCMD);
3627             }
3628           else
3629             {
3630               lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
3631                                    "CRITERIA", "CATEGORIES", "TITLES",
3632                                    "SIGTEST", "COMPARETEST");
3633               goto error;
3634             }
3635
3636           if (!lex_match (lexer, T_SLASH))
3637             break;
3638         }
3639
3640       if (t->row_labels != CTLP_NORMAL && t->col_labels != CTLP_NORMAL)
3641         {
3642           msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
3643           goto error;
3644         }
3645
3646       ctables_prepare_table (t);
3647
3648       
3649     }
3650   while (lex_token (lexer) != T_ENDCMD);
3651
3652   bool ok = ctables_execute (ds, ct);
3653   ctables_destroy (ct);
3654   return ok ? CMD_SUCCESS : CMD_FAILURE;
3655
3656 error:
3657   ctables_destroy (ct);
3658   return CMD_FAILURE;
3659 }
3660