26837f1b93c61fae51bd946c5f2c6b4b7238e242
[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 struct ctables
148   {
149     struct pivot_table_look *look;
150
151     /* If this is NULL, zeros are displayed using the normal print format.
152        Otherwise, this string is displayed. */
153     char *zero;
154
155     /* If this is NULL, missing values are displayed using the normal print
156        format.  Otherwise, this string is displayed. */
157     char *missing;
158
159     /* Indexed by variable dictionary index. */
160     enum ctables_vlabel *vlabels;
161
162     bool mrsets_count_duplicates; /* MRSETS. */
163     bool smissing_listwise;       /* SMISSING. */
164     struct variable *base_weight; /* WEIGHT. */
165     int hide_threshold;           /* HIDESMALLCOUNTS. */
166
167     struct ctables_table **tables;
168     size_t n_tables;
169   };
170
171 struct ctables_postcompute
172   {
173     struct hmap_node hmap_node; /* In struct ctables's 'pcompute' hmap. */
174     const char *name;           /* Name, without leading &. */
175
176     struct ctables_postcompute_expr *expr;
177     char *label;
178     /* XXX FORMAT */
179     bool hide_source_cats;
180   };
181
182 struct ctables_postcompute_expr
183   {
184     enum ctables_postcompute_op
185       {
186         /* Terminals. */
187         CTPO_CAT_NUMBER,
188         CTPO_CAT_STRING,
189         CTPO_CAT_RANGE,
190         CTPO_CAT_MISSING,
191         /* XXX OTHERNM */
192         /* XXX SUBTOTAL and HSUBTOTAL */
193
194         /* Nonterminals. */
195         CTPO_ADD,
196         CTPO_SUB,
197         CTPO_MUL,
198         CTPO_DIV,
199         CTPO_POW,
200       }
201     op;
202
203     union
204       {
205         /* CTPO_CAT_NUMBER, CTPO_NUMBER. */
206         double number;
207
208         /* CTPO_CAT_RANGE.
209
210            XXX what about string ranges? */
211         double range[2];
212
213         /* CTPO_ADD, CTPO_SUB, CTPO_MUL, CTPO_DIV, CTPO_POW. */
214         struct ctables_postcompute_expr *subs[2];
215       };
216   };
217
218 enum ctables_label_position
219   {
220     CTLP_NORMAL,
221     CTLP_OPPOSITE,
222     CTLP_LAYER,
223   };
224
225 struct var_array
226   {
227     struct variable **vars;
228     size_t n;
229
230     struct ctables_summary_spec *summaries;
231     size_t n_summaries;
232     struct variable *summary_var;
233   };
234
235 struct var_array2
236   {
237     struct var_array *vas;
238     size_t n;
239   };
240
241 struct ctables_table
242   {
243     struct ctables_axis *axes[PIVOT_N_AXES];
244     struct var_array2 vaas[PIVOT_N_AXES];
245     enum pivot_axis_type summary_axis;
246     struct hmap ft;
247
248     enum pivot_axis_type slabels_position;
249     bool slabels_visible;
250
251     enum ctables_label_position row_labels;
252     enum ctables_label_position col_labels;
253
254     /* Indexed by variable dictionary index. */
255     struct ctables_categories **categories;
256     size_t n_categories;
257
258     double cilevel;
259
260     char *caption;
261     char *corner;
262     char *title;
263
264     struct ctables_chisq *chisq;
265     struct ctables_pairwise *pairwise;
266
267   };
268
269 struct ctables_var
270   {
271     bool is_mrset;
272     union
273       {
274         struct variable *var;
275         const struct mrset *mrset;
276       };
277   };
278
279 static const struct fmt_spec *
280 ctables_var_get_print_format (const struct ctables_var *var)
281 {
282   return (var->is_mrset
283           ? var_get_print_format (var->mrset->vars[0])
284           : var_get_print_format (var->var));
285 }
286
287 static const char *
288 ctables_var_name (const struct ctables_var *var)
289 {
290   return var->is_mrset ? var->mrset->name : var_get_name (var->var);
291 }
292
293 struct ctables_categories
294   {
295     size_t n_refs;
296
297     /* Explicit categories. */
298     struct ctables_cat_value *values;
299     size_t n_values;
300
301     /* Implicit categories. */
302     bool sort_ascending;
303     bool include_missing;
304     enum { CTCS_VALUE, CTCS_LABEL, CTCS_FUNCTION } key;
305     enum ctables_summary_function sort_func;
306     struct variable *sort_func_var;
307     double percentile;
308
309     /* Totals. */
310     bool show_totals;
311     bool totals_before;
312     char *total_label;
313
314     /* Empty categories. */
315     bool show_empty;
316   };
317
318 struct ctables_cat_value
319   {
320     enum ctables_cat_value_type
321       {
322         CCVT_NUMBER,
323         CCVT_STRING,
324         CCVT_RANGE,
325         CCVT_MISSING,
326         CCVT_OTHERNM,
327         CCVT_SUBTOTAL,
328         CCVT_HSUBTOTAL,
329       }
330     type;
331
332     union
333       {
334         double number;          /* CCVT_NUMBER. */
335         char *string;           /* CCVT_STRING. */
336         double range[2];        /* CCVT_RANGE. */
337         char *subtotal_label;   /* CCVT_SUBTOTAL, CCVT_HSUBTOTAL. */
338       };
339   };
340
341 static void
342 ctables_cat_value_uninit (struct ctables_cat_value *cv)
343 {
344   if (!cv)
345     return;
346
347   switch (cv->type)
348     {
349     case CCVT_NUMBER:
350     case CCVT_RANGE:
351     case CCVT_MISSING:
352     case CCVT_OTHERNM:
353       break;
354
355     case CCVT_STRING:
356       free (cv->string);
357       break;
358
359     case CCVT_SUBTOTAL:
360     case CCVT_HSUBTOTAL:
361       free (cv->subtotal_label);
362     }
363 }
364
365 static void
366 ctables_categories_unref (struct ctables_categories *c)
367 {
368   if (!c)
369     return;
370
371   assert (c->n_refs > 0);
372   if (--c->n_refs)
373     return;
374
375   for (size_t i = 0; i < c->n_values; i++)
376     ctables_cat_value_uninit (&c->values[i]);
377   free (c->values);
378   free (c->total_label);
379   free (c);
380 }
381
382 /* Chi-square test (SIGTEST). */
383 struct ctables_chisq
384   {
385     double alpha;
386     bool include_mrsets;
387     bool all_visible;
388   };
389
390 /* Pairwise comparison test (COMPARETEST). */
391 struct ctables_pairwise
392   {
393     enum { PROP, MEAN } type;
394     double alpha[2];
395     bool include_mrsets;
396     bool meansvariance_allcats;
397     bool all_visible;
398     enum { BONFERRONI = 1, BH } adjust;
399     bool merge;
400     bool apa_style;
401     bool show_sig;
402   };
403
404 struct ctables_axis
405   {
406     enum ctables_axis_op
407       {
408         /* Terminals. */
409         CTAO_VAR,
410
411         /* Nonterminals. */
412         CTAO_STACK,             /* + */
413         CTAO_NEST,              /* > */
414       }
415     op;
416
417     union
418       {
419         /* Terminals. */
420         struct
421           {
422             struct ctables_var var;
423             bool scale;
424             struct ctables_summary_spec *summaries;
425             size_t n_summaries;
426             size_t allocated_summaries;
427           };
428
429         /* Nonterminals. */
430         struct ctables_axis *subs[2];
431       };
432
433     struct msg_location *loc;
434   };
435
436 static void ctables_axis_destroy (struct ctables_axis *);
437
438 enum ctables_format
439   {
440     CTF_COUNT,
441     CTF_PERCENT,
442     CTF_GENERAL
443   };
444
445 enum ctables_function_availability
446   {
447     CTFA_ALL,                /* Any variables. */
448     CTFA_SCALE,              /* Only scale variables, totals, and subtotals. */
449     CTFA_MRSETS,             /* Only multiple-response sets */
450   };
451
452 struct ctables_summary_spec
453   {
454     enum ctables_summary_function function;
455     double percentile;          /* CTSF_PTILE only. */
456     char *label;
457     struct fmt_spec format;     /* XXX extra CTABLES formats */
458   };
459
460 static void
461 ctables_summary_spec_uninit (struct ctables_summary_spec *s)
462 {
463   if (s)
464     free (s->label);
465 }
466
467 static bool
468 parse_col_width (struct lexer *lexer, const char *name, double *width)
469 {
470   lex_match (lexer, T_EQUALS);
471   if (lex_match_id (lexer, "DEFAULT"))
472     *width = SYSMIS;
473   else if (lex_force_num_range_closed (lexer, name, 0, DBL_MAX))
474     {
475       *width = lex_number (lexer);
476       lex_get (lexer);
477     }
478   else
479     return false;
480
481   return true;
482 }
483
484 static bool
485 parse_bool (struct lexer *lexer, bool *b)
486 {
487   if (lex_match_id (lexer, "NO"))
488     *b = false;
489   else if (lex_match_id (lexer, "YES"))
490     *b = true;
491   else
492     {
493       lex_error_expecting (lexer, "YES", "NO");
494       return false;
495     }
496   return true;
497 }
498
499 static enum ctables_function_availability
500 ctables_function_availability (enum ctables_summary_function f)
501 {
502   static enum ctables_function_availability availability[] = {
503 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = AVAILABILITY,
504     SUMMARIES
505 #undef S
506   };
507
508   return availability[f];
509 }
510
511 static bool
512 parse_ctables_summary_function (struct lexer *lexer,
513                                 enum ctables_summary_function *f)
514 {
515   struct pair
516     {
517       enum ctables_summary_function function;
518       struct substring name;
519     };
520   static struct pair names[] = {
521 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) \
522     { ENUM, SS_LITERAL_INITIALIZER (NAME) },
523     SUMMARIES
524
525     /* The .COUNT suffix may be omitted. */
526     S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _, _)
527     S(CTSF_COLPCT_COUNT, "COLPCT", _, _, _)
528     S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _, _)
529     S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _, _)
530     S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _, _)
531     S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _, _)
532     S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _, _)
533 #undef S
534   };
535
536   if (!lex_force_id (lexer))
537     return false;
538
539   for (size_t i = 0; i < sizeof names / sizeof *names; i++)
540     if (ss_equals_case (names[i].name, lex_tokss (lexer)))
541       {
542         *f = names[i].function;
543         lex_get (lexer);
544         return true;
545       }
546
547   lex_error (lexer, _("Expecting summary function name."));
548   return false;
549 }
550
551 static void
552 ctables_axis_destroy (struct ctables_axis *axis)
553 {
554   if (!axis)
555     return;
556
557   switch (axis->op)
558     {
559     case CTAO_VAR:
560       for (size_t i = 0; i < axis->n_summaries; i++)
561         ctables_summary_spec_uninit (&axis->summaries[i]);
562       free (axis->summaries);
563       break;
564
565     case CTAO_STACK:
566     case CTAO_NEST:
567       ctables_axis_destroy (axis->subs[0]);
568       ctables_axis_destroy (axis->subs[1]);
569       break;
570     }
571   msg_location_destroy (axis->loc);
572   free (axis);
573 }
574
575 static struct ctables_axis *
576 ctables_axis_new_nonterminal (enum ctables_axis_op op,
577                               struct ctables_axis *sub0,
578                               struct ctables_axis *sub1,
579                               struct lexer *lexer, int start_ofs)
580 {
581   struct ctables_axis *axis = xmalloc (sizeof *axis);
582   *axis = (struct ctables_axis) {
583     .op = op,
584     .subs = { sub0, sub1 },
585     .loc = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
586   };
587   return axis;
588 }
589
590 struct ctables_axis_parse_ctx
591   {
592     struct lexer *lexer;
593     struct dictionary *dict;
594     struct ctables *ct;
595     struct ctables_table *t;
596   };
597
598 static struct fmt_spec
599 ctables_summary_default_format (enum ctables_summary_function function,
600                                 const struct ctables_var *var)
601 {
602   static const enum ctables_format default_formats[] = {
603 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
604     SUMMARIES
605 #undef S
606   };
607   switch (default_formats[function])
608     {
609     case CTF_COUNT:
610       return (struct fmt_spec) { .type = FMT_F, .w = 40 };
611
612     case CTF_PERCENT:
613       return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
614
615     case CTF_GENERAL:
616       return *ctables_var_get_print_format (var);
617
618     default:
619       NOT_REACHED ();
620     }
621 }
622
623 static char *
624 ctables_summary_default_label (enum ctables_summary_function function,
625                                double percentile)
626 {
627   static const char *default_labels[] = {
628 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = LABEL,
629     SUMMARIES
630 #undef S
631   };
632
633   return (function == CTSF_PTILE
634           ? xasprintf (_("Percentile %.2f"), percentile)
635           : xstrdup (gettext (default_labels[function])));
636 }
637
638 static const char *
639 ctables_summary_function_name (enum ctables_summary_function function)
640 {
641   static const char *names[] = {
642 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = NAME,
643     SUMMARIES
644 #undef S
645   };
646   return names[function];
647 }
648
649 static bool
650 add_summary_spec (struct ctables_axis *axis,
651                   enum ctables_summary_function function, double percentile,
652                   const char *label, const struct fmt_spec *format,
653                   const struct msg_location *loc)
654 {
655   if (axis->op == CTAO_VAR)
656     {
657       if (axis->n_summaries >= axis->allocated_summaries)
658         axis->summaries = x2nrealloc (axis->summaries,
659                                       &axis->allocated_summaries,
660                                       sizeof *axis->summaries);
661
662       const char *function_name = ctables_summary_function_name (function);
663       const char *var_name = ctables_var_name (&axis->var);
664       switch (ctables_function_availability (function))
665         {
666         case CTFA_MRSETS:
667           if (!axis->var.is_mrset)
668             {
669               msg_at (SE, loc, _("Summary function %s applies only to multiple "
670                                  "response sets."), function_name);
671               msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
672                       var_name);
673               return false;
674             }
675           break;
676
677         case CTFA_SCALE:
678           if (!axis->scale)
679             {
680               msg_at (SE, loc,
681                       _("Summary function %s applies only to scale variables."),
682                       function_name);
683               msg_at (SN, axis->loc, _("'%s' is not a scale variable."),
684                       var_name);
685               return false;
686             }
687           break;
688
689         case CTFA_ALL:
690           break;
691         }
692
693       struct ctables_summary_spec *dst = &axis->summaries[axis->n_summaries++];
694       *dst = (struct ctables_summary_spec) {
695         .function = function,
696         .percentile = percentile,
697         .label = xstrdup (label),
698         .format = (format ? *format
699                    : ctables_summary_default_format (function, &axis->var)),
700       };
701       return true;
702     }
703   else
704     {
705       for (size_t i = 0; i < 2; i++)
706         if (!add_summary_spec (axis->subs[i], function, percentile, label,
707                                format, loc))
708           return false;
709       return true;
710     }
711 }
712
713 static struct ctables_axis *ctables_axis_parse_stack (
714   struct ctables_axis_parse_ctx *);
715
716 static bool
717 ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
718                    struct ctables_var *var)
719 {
720   if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
721     {
722       *var = (struct ctables_var) {
723         .is_mrset = true,
724         .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
725       };
726       if (!var->mrset)
727         {
728           lex_error (lexer, _("'%s' does not name a multiple-response set "
729                               "in the active file dictionary."),
730                      lex_tokcstr (lexer));
731           return false;
732         }
733       lex_get (lexer);
734       return true;
735     }
736   else
737     {
738       *var = (struct ctables_var) {
739         .is_mrset = false,
740         .var = parse_variable (lexer, dict),
741       };
742       return var->var != NULL;
743     }
744 }
745
746 static struct ctables_axis *
747 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
748 {
749   if (lex_match (ctx->lexer, T_LPAREN))
750     {
751       struct ctables_axis *sub = ctables_axis_parse_stack (ctx);
752       if (!sub || !lex_force_match (ctx->lexer, T_RPAREN))
753         {
754           ctables_axis_destroy (sub);
755           return NULL;
756         }
757       return sub;
758     }
759
760   if (!lex_force_id (ctx->lexer))
761     return NULL;
762
763   int start_ofs = lex_ofs (ctx->lexer);
764   struct ctables_var var;
765   if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
766     return NULL;
767
768   struct ctables_axis *axis = xmalloc (sizeof *axis);
769   *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
770
771   /* XXX should figure out default measures by reading data */
772   axis->scale = (var.is_mrset ? false
773                  : lex_match_phrase (ctx->lexer, "[S]") ? true
774                  : lex_match_phrase (ctx->lexer, "[C]") ? false
775                  : var_get_measure (var.var) == MEASURE_SCALE);
776   axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
777                                 lex_ofs (ctx->lexer) - 1);
778   return axis;
779 }
780
781 static struct ctables_axis *
782 ctables_axis_parse_postfix (struct ctables_axis_parse_ctx *ctx)
783 {
784   struct ctables_axis *sub = ctables_axis_parse_primary (ctx);
785   if (!sub || !lex_match (ctx->lexer, T_LBRACK))
786     return sub;
787
788   do
789     {
790       int start_ofs = lex_ofs (ctx->lexer);
791
792       /* Parse function. */
793       enum ctables_summary_function function;
794       if (!parse_ctables_summary_function (ctx->lexer, &function))
795         goto error;
796
797       /* Parse percentile. */
798       double percentile = 0;
799       if (function == CTSF_PTILE)
800         {
801           if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
802             goto error;
803           percentile = lex_number (ctx->lexer);
804           lex_get (ctx->lexer);
805         }
806
807       /* Parse label. */
808       char *label;
809       if (lex_is_string (ctx->lexer))
810         {
811           label = ss_xstrdup (lex_tokss (ctx->lexer));
812           lex_get (ctx->lexer);
813         }
814       else
815         label = ctables_summary_default_label (function, percentile);
816
817       /* Parse format. */
818       struct fmt_spec format;
819       const struct fmt_spec *formatp;
820       if (lex_token (ctx->lexer) == T_ID)
821         {
822           if (!parse_format_specifier (ctx->lexer, &format)
823               || !fmt_check_output (&format)
824               || !fmt_check_type_compat (&format, VAL_NUMERIC))
825             {
826               free (label);
827               goto error;
828             }
829           formatp = &format;
830         }
831       else
832         formatp = NULL;
833
834       struct msg_location *loc = lex_ofs_location (ctx->lexer, start_ofs,
835                                                    lex_ofs (ctx->lexer) - 1);
836       add_summary_spec (sub, function, percentile, label, formatp, loc);
837       free (label);
838       msg_location_destroy (loc);
839
840       lex_match (ctx->lexer, T_COMMA);
841     }
842   while (!lex_match (ctx->lexer, T_RBRACK));
843
844   return sub;
845
846 error:
847   ctables_axis_destroy (sub);
848   return NULL;
849 }
850
851 static const struct ctables_axis *
852 find_scale (const struct ctables_axis *axis)
853 {
854   if (!axis)
855     return NULL;
856   else if (axis->op == CTAO_VAR)
857     {
858       if (axis->scale)
859         {
860           assert (!axis->var.is_mrset);
861           return axis;
862         }
863       else
864         return NULL;
865     }
866   else
867     {
868       for (size_t i = 0; i < 2; i++)
869         {
870           const struct ctables_axis *scale = find_scale (axis->subs[i]);
871           if (scale)
872             return scale;
873         }
874       return NULL;
875     }
876 }
877
878 static const struct ctables_axis *
879 find_categorical_summary_spec (const struct ctables_axis *axis)
880 {
881   if (!axis)
882     return NULL;
883   else if (axis->op == CTAO_VAR)
884     return !axis->scale && axis->n_summaries ? axis : NULL;
885   else
886     {
887       for (size_t i = 0; i < 2; i++)
888         {
889           const struct ctables_axis *sum
890             = find_categorical_summary_spec (axis->subs[i]);
891           if (sum)
892             return sum;
893         }
894       return NULL;
895     }
896 }
897
898 static struct ctables_axis *
899 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
900 {
901   int start_ofs = lex_ofs (ctx->lexer);
902   struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
903   if (!lhs)
904     return NULL;
905
906   while (lex_match (ctx->lexer, T_GT))
907     {
908       struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
909       if (!rhs)
910         return NULL;
911
912       struct ctables_axis *nest = ctables_axis_new_nonterminal (
913         CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
914
915       const struct ctables_axis *outer_scale = find_scale (lhs);
916       const struct ctables_axis *inner_scale = find_scale (rhs);
917       if (outer_scale && inner_scale)
918         {
919           msg_at (SE, nest->loc, _("Cannot nest scale variables."));
920           msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
921           msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
922           ctables_axis_destroy (nest);
923           return NULL;
924         }
925
926       const struct ctables_axis *outer_sum = find_categorical_summary_spec (lhs);
927       if (outer_sum)
928         {
929           msg_at (SE, nest->loc,
930                   _("Summaries may only be requested for categorical variables "
931                     "at the innermost nesting level."));
932           msg_at (SN, outer_sum->loc,
933                   _("This outer categorical variable has a summary."));
934           ctables_axis_destroy (nest);
935           return NULL;
936         }
937
938       lhs = nest;
939     }
940
941   return lhs;
942 }
943
944 static struct ctables_axis *
945 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
946 {
947   int start_ofs = lex_ofs (ctx->lexer);
948   struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
949   if (!lhs)
950     return NULL;
951
952   while (lex_match (ctx->lexer, T_PLUS))
953     {
954       struct ctables_axis *rhs = ctables_axis_parse_nest (ctx);
955       if (!rhs)
956         return NULL;
957
958       lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
959                                           ctx->lexer, start_ofs);
960     }
961
962   return lhs;
963 }
964
965 static bool
966 ctables_axis_parse (struct lexer *lexer, struct dictionary *dict,
967                     struct ctables *ct, struct ctables_table *t,
968                     enum pivot_axis_type a)
969 {
970   if (lex_token (lexer) == T_BY
971       || lex_token (lexer) == T_SLASH
972       || lex_token (lexer) == T_ENDCMD)
973     return true;
974
975   struct ctables_axis_parse_ctx ctx = {
976     .lexer = lexer,
977     .dict = dict,
978     .ct = ct,
979     .t = t
980   };
981   t->axes[a] = ctables_axis_parse_stack (&ctx);
982   return t->axes[a] != NULL;
983 }
984
985 static void
986 ctables_chisq_destroy (struct ctables_chisq *chisq)
987 {
988   free (chisq);
989 }
990
991 static void
992 ctables_pairwise_destroy (struct ctables_pairwise *pairwise)
993 {
994   free (pairwise);
995 }
996
997 static void
998 ctables_table_destroy (struct ctables_table *t)
999 {
1000   if (!t)
1001     return;
1002
1003   for (size_t i = 0; i < t->n_categories; i++)
1004     ctables_categories_unref (t->categories[i]);
1005   free (t->categories);
1006
1007   ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
1008   ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
1009   ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
1010   free (t->caption);
1011   free (t->corner);
1012   free (t->title);
1013   ctables_chisq_destroy (t->chisq);
1014   ctables_pairwise_destroy (t->pairwise);
1015   free (t);
1016 }
1017
1018 static void
1019 ctables_destroy (struct ctables *ct)
1020 {
1021   if (!ct)
1022     return;
1023
1024   pivot_table_look_unref (ct->look);
1025   free (ct->zero);
1026   free (ct->missing);
1027   free (ct->vlabels);
1028   for (size_t i = 0; i < ct->n_tables; i++)
1029     ctables_table_destroy (ct->tables[i]);
1030   free (ct->tables);
1031   free (ct);
1032 }
1033
1034 static struct ctables_cat_value
1035 ccvt_range (double low, double high)
1036 {
1037   return (struct ctables_cat_value) {
1038     .type = CCVT_RANGE,
1039     .range = { low, high }
1040   };
1041 }
1042
1043 static bool
1044 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
1045                                 struct ctables_table *t)
1046 {
1047   if (!lex_match_id (lexer, "VARIABLES"))
1048     return false;
1049   lex_match (lexer, T_EQUALS);
1050
1051   struct variable **vars;
1052   size_t n_vars;
1053   if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
1054     return false;
1055
1056   struct ctables_categories *c = xmalloc (sizeof *c);
1057   *c = (struct ctables_categories) { .n_refs = n_vars };
1058   for (size_t i = 0; i < n_vars; i++)
1059     {
1060       struct ctables_categories **cp
1061         = &t->categories[var_get_dict_index (vars[i])];
1062       ctables_categories_unref (*cp);
1063       *cp = c;
1064     }
1065   free (vars);
1066
1067   if (lex_match (lexer, T_LBRACK))
1068     {
1069       size_t allocated_values = 0;
1070       do
1071         {
1072           if (c->n_values >= allocated_values)
1073             c->values = x2nrealloc (c->values, &allocated_values,
1074                                     sizeof *c->values);
1075
1076           struct ctables_cat_value *v = &c->values[c->n_values];
1077           if (lex_match_id (lexer, "OTHERNM"))
1078             v->type = CCVT_OTHERNM;
1079           else if (lex_match_id (lexer, "MISSING"))
1080             v->type = CCVT_MISSING;
1081           else if (lex_match_id (lexer, "SUBTOTAL"))
1082             *v = (struct ctables_cat_value)
1083               { .type = CCVT_SUBTOTAL, .subtotal_label = NULL };
1084           else if (lex_match_id (lexer, "HSUBTOTAL"))
1085             *v = (struct ctables_cat_value)
1086               { .type = CCVT_HSUBTOTAL, .subtotal_label = NULL };
1087           else if (lex_match_id (lexer, "LO"))
1088             {
1089               if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
1090                 return false;
1091               *v = ccvt_range (-DBL_MAX, lex_number (lexer));
1092               lex_get (lexer);
1093             }
1094           else if (lex_is_number (lexer))
1095             {
1096               double number = lex_number (lexer);
1097               lex_get (lexer);
1098               if (lex_match_id (lexer, "THRU"))
1099                 {
1100                   v->type = CCVT_RANGE;
1101                   v->range[0] = number;
1102                   if (lex_match_id (lexer, "HI"))
1103                     *v = ccvt_range (number, DBL_MAX);
1104                   else
1105                     {
1106                       if (!lex_force_num (lexer))
1107                         return false;
1108                       *v = ccvt_range (number, lex_number (lexer));
1109                       lex_get (lexer);
1110                     }
1111                 }
1112               else
1113                 *v = (struct ctables_cat_value) {
1114                   .type = CCVT_NUMBER,
1115                   .number = number
1116                 };
1117             }
1118           else if (lex_is_string (lexer))
1119             {
1120               *v = (struct ctables_cat_value) {
1121                 .type = CCVT_STRING,
1122                 .string = ss_xstrdup (lex_tokss (lexer)),
1123               };
1124               lex_get (lexer);
1125             }
1126           else
1127             {
1128               lex_error (lexer, NULL);
1129               return false;
1130             }
1131
1132           if ((v->type == CCVT_SUBTOTAL || v->type == CCVT_HSUBTOTAL)
1133               && lex_match (lexer, T_EQUALS))
1134             {
1135               if (!lex_force_string (lexer))
1136                 return false;
1137
1138               v->subtotal_label = ss_xstrdup (lex_tokss (lexer));
1139               lex_get (lexer);
1140             }
1141
1142           c->n_values++;
1143           lex_match (lexer, T_COMMA);
1144         }
1145       while (!lex_match (lexer, T_RBRACK));
1146     }
1147
1148   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
1149     {
1150       if (!c->n_values && lex_match_id (lexer, "ORDER"))
1151         {
1152           lex_match (lexer, T_EQUALS);
1153           if (lex_match_id (lexer, "A"))
1154             c->sort_ascending = true;
1155           else if (lex_match_id (lexer, "D"))
1156             c->sort_ascending = false;
1157           else
1158             {
1159               lex_error_expecting (lexer, "A", "D");
1160               return false;
1161             }
1162         }
1163       else if (!c->n_values && lex_match_id (lexer, "KEY"))
1164         {
1165           lex_match (lexer, T_EQUALS);
1166           if (lex_match_id (lexer, "VALUE"))
1167             c->key = CTCS_VALUE;
1168           else if (lex_match_id (lexer, "LABEL"))
1169             c->key = CTCS_LABEL;
1170           else
1171             {
1172               c->key = CTCS_FUNCTION;
1173               if (!parse_ctables_summary_function (lexer, &c->sort_func))
1174                 return false;
1175
1176               if (lex_match (lexer, T_LPAREN))
1177                 {
1178                   c->sort_func_var = parse_variable (lexer, dict);
1179                   if (!c->sort_func_var)
1180                     return false;
1181
1182                   if (c->sort_func == CTSF_PTILE)
1183                     {
1184                       lex_match (lexer, T_COMMA);
1185                       if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
1186                         return false;
1187                       c->percentile = lex_number (lexer);
1188                       lex_get (lexer);
1189                     }
1190
1191                   if (!lex_force_match (lexer, T_RPAREN))
1192                     return false;
1193                 }
1194               else if (ctables_function_availability (c->sort_func)
1195                        == CTFA_SCALE)
1196                 {
1197                   bool UNUSED b = lex_force_match (lexer, T_LPAREN);
1198                   return false;
1199                 }
1200             }
1201         }
1202       else if (!c->n_values && lex_match_id (lexer, "MISSING"))
1203         {
1204           lex_match (lexer, T_EQUALS);
1205           if (lex_match_id (lexer, "INCLUDE"))
1206             c->include_missing = true;
1207           else if (lex_match_id (lexer, "EXCLUDE"))
1208             c->include_missing = false;
1209           else
1210             {
1211               lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1212               return false;
1213             }
1214         }
1215       else if (lex_match_id (lexer, "TOTAL"))
1216         {
1217           lex_match (lexer, T_EQUALS);
1218           if (!parse_bool (lexer, &c->show_totals))
1219             return false;
1220         }
1221       else if (lex_match_id (lexer, "LABEL"))
1222         {
1223           lex_match (lexer, T_EQUALS);
1224           if (!lex_force_string (lexer))
1225             return false;
1226           free (c->total_label);
1227           c->total_label = ss_xstrdup (lex_tokss (lexer));
1228           lex_get (lexer);
1229         }
1230       else if (lex_match_id (lexer, "POSITION"))
1231         {
1232           lex_match (lexer, T_EQUALS);
1233           if (lex_match_id (lexer, "BEFORE"))
1234             c->totals_before = true;
1235           else if (lex_match_id (lexer, "AFTER"))
1236             c->totals_before = false;
1237           else
1238             {
1239               lex_error_expecting (lexer, "BEFORE", "AFTER");
1240               return false;
1241             }
1242         }
1243       else if (lex_match_id (lexer, "EMPTY"))
1244         {
1245           lex_match (lexer, T_EQUALS);
1246           if (lex_match_id (lexer, "INCLUDE"))
1247             c->show_empty = true;
1248           else if (lex_match_id (lexer, "EXCLUDE"))
1249             c->show_empty = false;
1250           else
1251             {
1252               lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1253               return false;
1254             }
1255         }
1256       else
1257         {
1258           if (!c->n_values)
1259             lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
1260                                  "TOTAL", "LABEL", "POSITION", "EMPTY");
1261           else
1262             lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
1263           return false;
1264         }
1265     }
1266   return true;
1267 }
1268
1269 static void
1270 var_array_uninit (struct var_array *va)
1271 {
1272   if (va)
1273     free (va->vars);
1274 }
1275
1276 static void
1277 var_array2_uninit (struct var_array2 *vaa)
1278 {
1279   if (vaa)
1280     {
1281       for (size_t i = 0; i < vaa->n; i++)
1282         var_array_uninit (&vaa->vas[i]);
1283       free (vaa->vas);
1284     }
1285 }
1286
1287 static struct var_array2
1288 nest_fts (struct var_array2 va0, struct var_array2 va1)
1289 {
1290   if (!va0.n)
1291     return va1;
1292   else if (!va1.n)
1293     return va0;
1294
1295   struct var_array2 vaa = { .vas = xnmalloc (va0.n, va1.n * sizeof *vaa.vas) };
1296   for (size_t i = 0; i < va0.n; i++)
1297     for (size_t j = 0; j < va1.n; j++)
1298       {
1299         const struct var_array *a = &va0.vas[i];
1300         const struct var_array *b = &va1.vas[j];
1301
1302         size_t allocate = a->n + b->n;
1303         struct variable **vars = xnmalloc (allocate, sizeof *vars);
1304         enum pivot_axis_type *axes = xnmalloc (allocate, sizeof *axes);
1305         size_t n = 0;
1306         for (size_t k = 0; k < a->n; k++)
1307           vars[n++] = a->vars[k];
1308         for (size_t k = 0; k < b->n; k++)
1309           vars[n++] = b->vars[k];
1310         assert (n == allocate);
1311
1312         const struct var_array *summary_src;
1313         if (!a->summary_var)
1314           summary_src = b;
1315         else if (!b->summary_var)
1316           summary_src = a;
1317         else
1318           NOT_REACHED ();
1319         vaa.vas[vaa.n++] = (struct var_array) {
1320           .vars = vars,
1321           .n = n,
1322           .summaries = summary_src->summaries,
1323           .n_summaries = summary_src->n_summaries,
1324           .summary_var = summary_src->summary_var,
1325         };
1326       }
1327   var_array2_uninit (&va0);
1328   var_array2_uninit (&va1);
1329   return vaa;
1330 }
1331
1332 static struct var_array2
1333 stack_fts (struct var_array2 va0, struct var_array2 va1)
1334 {
1335   struct var_array2 vaa = { .vas = xnmalloc (va0.n + va1.n, sizeof *vaa.vas) };
1336   for (size_t i = 0; i < va0.n; i++)
1337     vaa.vas[vaa.n++] = va0.vas[i];
1338   for (size_t i = 0; i < va1.n; i++)
1339     vaa.vas[vaa.n++] = va1.vas[i];
1340   assert (vaa.n == va0.n + va1.n);
1341   free (va0.vas);
1342   free (va1.vas);
1343   return vaa;
1344 }
1345
1346 static struct var_array2
1347 enumerate_fts (enum pivot_axis_type axis_type, const struct ctables_axis *a)
1348 {
1349   if (!a)
1350     return (struct var_array2) { .n = 0 };
1351
1352   switch (a->op)
1353     {
1354     case CTAO_VAR:
1355       assert (!a->var.is_mrset);
1356       struct var_array *va = xmalloc (sizeof *va);
1357       if (a->scale)
1358         *va = (struct var_array) { .n = 0 };
1359       else
1360         {
1361           struct variable **vars = xmalloc (sizeof *vars);
1362           *vars = a->var.var;
1363           enum pivot_axis_type *axes = xmalloc (sizeof *axes);
1364           *axes = axis_type;
1365           *va = (struct var_array) { .vars = vars, .n = 1 };
1366         }
1367       if (a->n_summaries || a->scale)
1368         {
1369           va->summaries = a->summaries;
1370           va->n_summaries = a->n_summaries;
1371           va->summary_var = a->var.var;
1372         }
1373       return (struct var_array2) { .vas = va, .n = 1 };
1374
1375     case CTAO_STACK:
1376       return stack_fts (enumerate_fts (axis_type, a->subs[0]),
1377                         enumerate_fts (axis_type, a->subs[1]));
1378
1379     case CTAO_NEST:
1380       return nest_fts (enumerate_fts (axis_type, a->subs[0]),
1381                        enumerate_fts (axis_type, a->subs[1]));
1382     }
1383
1384   NOT_REACHED ();
1385 }
1386
1387 union ctables_summary
1388   {
1389     /* COUNT, VALIDN, TOTALN. */
1390     struct
1391       {
1392         double valid;
1393         double missing;
1394       };
1395
1396     /* MINIMUM, MAXIMUM, RANGE. */
1397     struct
1398       {
1399         double min;
1400         double max;
1401       };
1402
1403     /* MEAN, SEMEAN, STDDEV, SUM, VARIANCE, *.SUM. */
1404     struct moments1 *moments;
1405
1406     /* XXX percentiles, median, mode, multiple response */
1407   };
1408
1409 static void
1410 ctables_summary_init (union ctables_summary *s,
1411                       const struct ctables_summary_spec *ss)
1412 {
1413   switch (ss->function)
1414     {
1415     case CTSF_COUNT:
1416     case CTSF_ECOUNT:
1417     case CTSF_ROWPCT_COUNT:
1418     case CTSF_COLPCT_COUNT:
1419     case CTSF_TABLEPCT_COUNT:
1420     case CTSF_SUBTABLEPCT_COUNT:
1421     case CTSF_LAYERPCT_COUNT:
1422     case CTSF_LAYERROWPCT_COUNT:
1423     case CTSF_LAYERCOLPCT_COUNT:
1424     case CTSF_ROWPCT_VALIDN:
1425     case CTSF_COLPCT_VALIDN:
1426     case CTSF_TABLEPCT_VALIDN:
1427     case CTSF_SUBTABLEPCT_VALIDN:
1428     case CTSF_LAYERPCT_VALIDN:
1429     case CTSF_LAYERROWPCT_VALIDN:
1430     case CTSF_LAYERCOLPCT_VALIDN:
1431     case CTSF_ROWPCT_TOTALN:
1432     case CTSF_COLPCT_TOTALN:
1433     case CTSF_TABLEPCT_TOTALN:
1434     case CTSF_SUBTABLEPCT_TOTALN:
1435     case CTSF_LAYERPCT_TOTALN:
1436     case CTSF_LAYERROWPCT_TOTALN:
1437     case CTSF_LAYERCOLPCT_TOTALN:
1438     case CSTF_TOTALN:
1439     case CTSF_ETOTALN:
1440     case CTSF_VALIDN:
1441     case CTSF_EVALIDN:
1442       s->missing = s->valid = 0;
1443       break;
1444
1445     case CTSF_MAXIMUM:
1446     case CTSF_MINIMUM:
1447     case CTSF_RANGE:
1448       s->min = s->max = SYSMIS;
1449       break;
1450
1451     case CTSF_MEAN:
1452     case CTSF_SEMEAN:
1453     case CTSF_STDDEV:
1454     case CTSF_SUM:
1455     case CTSF_VARIANCE:
1456     case CTSF_ROWPCT_SUM:
1457     case CTSF_COLPCT_SUM:
1458     case CTSF_TABLEPCT_SUM:
1459     case CTSF_SUBTABLEPCT_SUM:
1460     case CTSF_LAYERPCT_SUM:
1461     case CTSF_LAYERROWPCT_SUM:
1462     case CTSF_LAYERCOLPCT_SUM:
1463       s->moments = moments1_create (MOMENT_VARIANCE);
1464       break;
1465
1466     case CTSF_MEDIAN:
1467     case CTSF_MISSING:
1468     case CTSF_MODE:
1469     case CTSF_PTILE:
1470       NOT_REACHED ();
1471
1472     case CTSF_RESPONSES:
1473     case CTSF_ROWPCT_RESPONSES:
1474     case CTSF_COLPCT_RESPONSES:
1475     case CTSF_TABLEPCT_RESPONSES:
1476     case CTSF_SUBTABLEPCT_RESPONSES:
1477     case CTSF_LAYERPCT_RESPONSES:
1478     case CTSF_LAYERROWPCT_RESPONSES:
1479     case CTSF_LAYERCOLPCT_RESPONSES:
1480     case CTSF_ROWPCT_RESPONSES_COUNT:
1481     case CTSF_COLPCT_RESPONSES_COUNT:
1482     case CTSF_TABLEPCT_RESPONSES_COUNT:
1483     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1484     case CTSF_LAYERPCT_RESPONSES_COUNT:
1485     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1486     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1487     case CTSF_ROWPCT_COUNT_RESPONSES:
1488     case CTSF_COLPCT_COUNT_RESPONSES:
1489     case CTSF_TABLEPCT_COUNT_RESPONSES:
1490     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1491     case CTSF_LAYERPCT_COUNT_RESPONSES:
1492     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1493     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1494       NOT_REACHED ();
1495     }
1496 }
1497
1498 static void UNUSED
1499 ctables_summary_uninit (union ctables_summary *s,
1500                         const struct ctables_summary_spec *ss)
1501 {
1502   switch (ss->function)
1503     {
1504     case CTSF_COUNT:
1505     case CTSF_ECOUNT:
1506     case CTSF_ROWPCT_COUNT:
1507     case CTSF_COLPCT_COUNT:
1508     case CTSF_TABLEPCT_COUNT:
1509     case CTSF_SUBTABLEPCT_COUNT:
1510     case CTSF_LAYERPCT_COUNT:
1511     case CTSF_LAYERROWPCT_COUNT:
1512     case CTSF_LAYERCOLPCT_COUNT:
1513     case CTSF_ROWPCT_VALIDN:
1514     case CTSF_COLPCT_VALIDN:
1515     case CTSF_TABLEPCT_VALIDN:
1516     case CTSF_SUBTABLEPCT_VALIDN:
1517     case CTSF_LAYERPCT_VALIDN:
1518     case CTSF_LAYERROWPCT_VALIDN:
1519     case CTSF_LAYERCOLPCT_VALIDN:
1520     case CTSF_ROWPCT_TOTALN:
1521     case CTSF_COLPCT_TOTALN:
1522     case CTSF_TABLEPCT_TOTALN:
1523     case CTSF_SUBTABLEPCT_TOTALN:
1524     case CTSF_LAYERPCT_TOTALN:
1525     case CTSF_LAYERROWPCT_TOTALN:
1526     case CTSF_LAYERCOLPCT_TOTALN:
1527     case CSTF_TOTALN:
1528     case CTSF_ETOTALN:
1529     case CTSF_VALIDN:
1530     case CTSF_EVALIDN:
1531       break;
1532
1533     case CTSF_MAXIMUM:
1534     case CTSF_MINIMUM:
1535     case CTSF_RANGE:
1536       break;
1537
1538     case CTSF_MEAN:
1539     case CTSF_SEMEAN:
1540     case CTSF_STDDEV:
1541     case CTSF_SUM:
1542     case CTSF_VARIANCE:
1543     case CTSF_ROWPCT_SUM:
1544     case CTSF_COLPCT_SUM:
1545     case CTSF_TABLEPCT_SUM:
1546     case CTSF_SUBTABLEPCT_SUM:
1547     case CTSF_LAYERPCT_SUM:
1548     case CTSF_LAYERROWPCT_SUM:
1549     case CTSF_LAYERCOLPCT_SUM:
1550       moments1_destroy (s->moments);
1551       break;
1552
1553     case CTSF_MEDIAN:
1554     case CTSF_MISSING:
1555     case CTSF_MODE:
1556     case CTSF_PTILE:
1557       NOT_REACHED ();
1558
1559     case CTSF_RESPONSES:
1560     case CTSF_ROWPCT_RESPONSES:
1561     case CTSF_COLPCT_RESPONSES:
1562     case CTSF_TABLEPCT_RESPONSES:
1563     case CTSF_SUBTABLEPCT_RESPONSES:
1564     case CTSF_LAYERPCT_RESPONSES:
1565     case CTSF_LAYERROWPCT_RESPONSES:
1566     case CTSF_LAYERCOLPCT_RESPONSES:
1567     case CTSF_ROWPCT_RESPONSES_COUNT:
1568     case CTSF_COLPCT_RESPONSES_COUNT:
1569     case CTSF_TABLEPCT_RESPONSES_COUNT:
1570     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1571     case CTSF_LAYERPCT_RESPONSES_COUNT:
1572     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1573     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1574     case CTSF_ROWPCT_COUNT_RESPONSES:
1575     case CTSF_COLPCT_COUNT_RESPONSES:
1576     case CTSF_TABLEPCT_COUNT_RESPONSES:
1577     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1578     case CTSF_LAYERPCT_COUNT_RESPONSES:
1579     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1580     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1581       NOT_REACHED ();
1582     }
1583 }
1584
1585 static void
1586 ctables_summary_add (union ctables_summary *s,
1587                      const struct ctables_summary_spec *ss,
1588                      const struct variable *var, const union value *value,
1589                      double weight)
1590 {
1591   switch (ss->function)
1592     {
1593     case CTSF_COUNT:
1594     case CTSF_ECOUNT:
1595     case CTSF_ROWPCT_COUNT:
1596     case CTSF_COLPCT_COUNT:
1597     case CTSF_TABLEPCT_COUNT:
1598     case CTSF_SUBTABLEPCT_COUNT:
1599     case CTSF_LAYERPCT_COUNT:
1600     case CTSF_LAYERROWPCT_COUNT:
1601     case CTSF_LAYERCOLPCT_COUNT:
1602     case CTSF_ROWPCT_VALIDN:
1603     case CTSF_COLPCT_VALIDN:
1604     case CTSF_TABLEPCT_VALIDN:
1605     case CTSF_SUBTABLEPCT_VALIDN:
1606     case CTSF_LAYERPCT_VALIDN:
1607     case CTSF_LAYERROWPCT_VALIDN:
1608     case CTSF_LAYERCOLPCT_VALIDN:
1609     case CTSF_ROWPCT_TOTALN:
1610     case CTSF_COLPCT_TOTALN:
1611     case CTSF_TABLEPCT_TOTALN:
1612     case CTSF_SUBTABLEPCT_TOTALN:
1613     case CTSF_LAYERPCT_TOTALN:
1614     case CTSF_LAYERROWPCT_TOTALN:
1615     case CTSF_LAYERCOLPCT_TOTALN:
1616     case CSTF_TOTALN:
1617     case CTSF_ETOTALN:
1618     case CTSF_VALIDN:
1619     case CTSF_EVALIDN:
1620       if (var_is_value_missing (var, value))
1621         s->missing += weight;
1622       else
1623         s->valid += weight;
1624       break;
1625
1626     case CTSF_MAXIMUM:
1627     case CTSF_MINIMUM:
1628     case CTSF_RANGE:
1629       if (!var_is_value_missing (var, value))
1630         {
1631           assert (!var_is_alpha (var)); /* XXX? */
1632           if (s->min == SYSMIS || value->f < s->min)
1633             s->min = value->f;
1634           if (s->max == SYSMIS || value->f > s->max)
1635             s->max = value->f;
1636         }
1637       break;
1638
1639     case CTSF_MEAN:
1640     case CTSF_SEMEAN:
1641     case CTSF_STDDEV:
1642     case CTSF_SUM:
1643     case CTSF_VARIANCE:
1644     case CTSF_ROWPCT_SUM:
1645     case CTSF_COLPCT_SUM:
1646     case CTSF_TABLEPCT_SUM:
1647     case CTSF_SUBTABLEPCT_SUM:
1648     case CTSF_LAYERPCT_SUM:
1649     case CTSF_LAYERROWPCT_SUM:
1650     case CTSF_LAYERCOLPCT_SUM:
1651       moments1_add (s->moments, value->f, weight);
1652       break;
1653
1654     case CTSF_MEDIAN:
1655     case CTSF_MISSING:
1656     case CTSF_MODE:
1657     case CTSF_PTILE:
1658       NOT_REACHED ();
1659
1660     case CTSF_RESPONSES:
1661     case CTSF_ROWPCT_RESPONSES:
1662     case CTSF_COLPCT_RESPONSES:
1663     case CTSF_TABLEPCT_RESPONSES:
1664     case CTSF_SUBTABLEPCT_RESPONSES:
1665     case CTSF_LAYERPCT_RESPONSES:
1666     case CTSF_LAYERROWPCT_RESPONSES:
1667     case CTSF_LAYERCOLPCT_RESPONSES:
1668     case CTSF_ROWPCT_RESPONSES_COUNT:
1669     case CTSF_COLPCT_RESPONSES_COUNT:
1670     case CTSF_TABLEPCT_RESPONSES_COUNT:
1671     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1672     case CTSF_LAYERPCT_RESPONSES_COUNT:
1673     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1674     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1675     case CTSF_ROWPCT_COUNT_RESPONSES:
1676     case CTSF_COLPCT_COUNT_RESPONSES:
1677     case CTSF_TABLEPCT_COUNT_RESPONSES:
1678     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1679     case CTSF_LAYERPCT_COUNT_RESPONSES:
1680     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1681     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1682       NOT_REACHED ();
1683     }
1684 }
1685
1686 static double
1687 ctables_summary_value (union ctables_summary *s,
1688                        const struct ctables_summary_spec *ss)
1689 {
1690   switch (ss->function)
1691     {
1692     case CTSF_COUNT:
1693     case CTSF_ECOUNT:
1694       return s->valid;
1695
1696     case CTSF_ROWPCT_COUNT:
1697     case CTSF_COLPCT_COUNT:
1698     case CTSF_TABLEPCT_COUNT:
1699     case CTSF_SUBTABLEPCT_COUNT:
1700     case CTSF_LAYERPCT_COUNT:
1701     case CTSF_LAYERROWPCT_COUNT:
1702     case CTSF_LAYERCOLPCT_COUNT:
1703     case CTSF_ROWPCT_VALIDN:
1704     case CTSF_COLPCT_VALIDN:
1705     case CTSF_TABLEPCT_VALIDN:
1706     case CTSF_SUBTABLEPCT_VALIDN:
1707     case CTSF_LAYERPCT_VALIDN:
1708     case CTSF_LAYERROWPCT_VALIDN:
1709     case CTSF_LAYERCOLPCT_VALIDN:
1710     case CTSF_ROWPCT_TOTALN:
1711     case CTSF_COLPCT_TOTALN:
1712     case CTSF_TABLEPCT_TOTALN:
1713     case CTSF_SUBTABLEPCT_TOTALN:
1714     case CTSF_LAYERPCT_TOTALN:
1715     case CTSF_LAYERROWPCT_TOTALN:
1716     case CTSF_LAYERCOLPCT_TOTALN:
1717       NOT_REACHED ();
1718
1719     case CSTF_TOTALN:
1720     case CTSF_ETOTALN:
1721       return s->valid + s->missing;
1722
1723     case CTSF_VALIDN:
1724     case CTSF_EVALIDN:
1725       return s->valid;
1726
1727     case CTSF_MAXIMUM:
1728       return s->max;
1729
1730     case CTSF_MINIMUM:
1731       return s->min;
1732
1733     case CTSF_RANGE:
1734       return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
1735
1736     case CTSF_MEAN:
1737       {
1738         double mean;
1739         moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
1740         return mean;
1741       }
1742
1743     case CTSF_SEMEAN:
1744       {
1745         double weight, variance;
1746         moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
1747         return calc_semean (variance, weight);
1748       }
1749
1750     case CTSF_STDDEV:
1751       {
1752         double variance;
1753         moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
1754         return variance != SYSMIS ? sqrt (variance) : SYSMIS;
1755       }
1756
1757     case CTSF_SUM:
1758       {
1759         double weight, mean;
1760         moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
1761         return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
1762       }
1763
1764     case CTSF_VARIANCE:
1765       {
1766         double variance;
1767         moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
1768         return variance;
1769       }
1770
1771     case CTSF_ROWPCT_SUM:
1772     case CTSF_COLPCT_SUM:
1773     case CTSF_TABLEPCT_SUM:
1774     case CTSF_SUBTABLEPCT_SUM:
1775     case CTSF_LAYERPCT_SUM:
1776     case CTSF_LAYERROWPCT_SUM:
1777     case CTSF_LAYERCOLPCT_SUM:
1778       NOT_REACHED ();
1779
1780     case CTSF_MEDIAN:
1781     case CTSF_MISSING:
1782     case CTSF_MODE:
1783     case CTSF_PTILE:
1784       NOT_REACHED ();
1785
1786     case CTSF_RESPONSES:
1787     case CTSF_ROWPCT_RESPONSES:
1788     case CTSF_COLPCT_RESPONSES:
1789     case CTSF_TABLEPCT_RESPONSES:
1790     case CTSF_SUBTABLEPCT_RESPONSES:
1791     case CTSF_LAYERPCT_RESPONSES:
1792     case CTSF_LAYERROWPCT_RESPONSES:
1793     case CTSF_LAYERCOLPCT_RESPONSES:
1794     case CTSF_ROWPCT_RESPONSES_COUNT:
1795     case CTSF_COLPCT_RESPONSES_COUNT:
1796     case CTSF_TABLEPCT_RESPONSES_COUNT:
1797     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1798     case CTSF_LAYERPCT_RESPONSES_COUNT:
1799     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1800     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1801     case CTSF_ROWPCT_COUNT_RESPONSES:
1802     case CTSF_COLPCT_COUNT_RESPONSES:
1803     case CTSF_TABLEPCT_COUNT_RESPONSES:
1804     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1805     case CTSF_LAYERPCT_COUNT_RESPONSES:
1806     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1807     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1808       NOT_REACHED ();
1809     }
1810
1811   NOT_REACHED ();
1812 }
1813
1814 struct ctables_freq
1815   {
1816     struct hmap_node node;      /* Element in hash table. */
1817
1818     struct
1819       {
1820         size_t vaa_idx;
1821         union value *values;
1822         int leaf;
1823       }
1824     axes[PIVOT_N_AXES];
1825
1826     union ctables_summary *summaries;
1827   };
1828
1829 #if 0
1830 static struct ctables_freq *
1831 ctables_freq_create (struct ctables_freqtab *ft)
1832 {
1833   struct ctables_freq *f = xmalloc (sizeof *f + ft->vars.n * sizeof *f->values);
1834   f->summaries = xmalloc (ft->n_summaries * sizeof *f->summaries);
1835   for (size_t i = 0; i < ft->n_summaries; i++)
1836     ctables_summary_init (&f->summaries[i], &ft->summaries[i]);
1837   return f;
1838 }
1839
1840 static void
1841 ctables_freq_add (struct ctables_freqtab *ft, struct ctables_freq *f,
1842                   const struct variable *var, const union value *value,
1843                   double weight)
1844 {
1845   for (size_t i = 0; i < ft->n_summaries; i++)
1846     ctables_summary_add (&f->summaries[i], &ft->summaries[i],
1847                          var, value, weight);
1848 }
1849 #endif
1850
1851 struct ctables_freq_sort_aux
1852   {
1853     const struct ctables_table *t;
1854     enum pivot_axis_type a;
1855   };
1856
1857 static int
1858 ctables_freq_compare_3way (const void *a_, const void *b_, const void *aux_)
1859 {
1860   const struct ctables_freq_sort_aux *aux = aux_;
1861   struct ctables_freq *const *ap = a_;
1862   struct ctables_freq *const *bp = b_;
1863   const struct ctables_freq *a = *ap;
1864   const struct ctables_freq *b = *bp;
1865
1866   size_t a_idx = a->axes[aux->a].vaa_idx;
1867   size_t b_idx = b->axes[aux->a].vaa_idx;
1868   if (a_idx != b_idx)
1869     return a_idx < b_idx ? -1 : 1;
1870
1871   const struct var_array *va = &aux->t->vaas[aux->a].vas[a_idx];
1872   for (size_t i = 0; i < va->n; i++)
1873     {
1874       int cmp = value_compare_3way (&a->axes[aux->a].values[i],
1875                                     &b->axes[aux->a].values[i],
1876                                     var_get_width (va->vars[i]));
1877       if (cmp)
1878         return cmp;
1879     }
1880   return 0;
1881 }
1882
1883 /* Algorithm:
1884
1885    For each row:
1886        For each ctables_table:
1887            For each combination of row vars:
1888                For each combination of column vars:
1889                    For each combination of layer vars:
1890                        Add entry
1891    Make a table of row values:
1892        Sort entries by row values
1893        Assign a 0-based index to each actual value
1894        Construct a dimension
1895    Make a table of column values
1896    Make a table of layer values
1897    For each entry:
1898        Fill the table entry using the indexes from before.
1899  */
1900
1901 static void
1902 ctables_freqtab_insert (struct ctables_table *t,
1903                         const struct ccase *c,
1904                         size_t ir, size_t ic, size_t il,
1905                         double weight)
1906 {
1907   size_t ix[PIVOT_N_AXES] = {
1908     [PIVOT_AXIS_ROW] = ir,
1909     [PIVOT_AXIS_COLUMN] = ic,
1910     [PIVOT_AXIS_LAYER] = il,
1911   };
1912   const struct var_array *ss = &t->vaas[t->summary_axis].vas[ix[t->summary_axis]];
1913
1914   size_t hash = 0;
1915   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
1916     {
1917       const struct var_array *va = &t->vaas[a].vas[ix[a]];
1918       hash = hash_int (ix[a], hash);
1919       for (size_t i = 0; i < va->n; i++)
1920         hash = value_hash (case_data (c, va->vars[i]),
1921                            var_get_width (va->vars[i]), hash);
1922     }
1923
1924   struct ctables_freq *f;
1925   HMAP_FOR_EACH_WITH_HASH (f, struct ctables_freq, node, hash, &t->ft)
1926     {
1927       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
1928         {
1929           const struct var_array *va = &t->vaas[a].vas[ix[a]];
1930           if (f->axes[a].vaa_idx != ix[a])
1931             goto not_equal;
1932           for (size_t i = 0; i < va->n; i++)
1933             if (!value_equal (case_data (c, va->vars[i]),
1934                               &f->axes[a].values[i],
1935                               var_get_width (va->vars[i])))
1936               goto not_equal;
1937         }
1938
1939       goto summarize;
1940
1941     not_equal: ;
1942     }
1943
1944   f = xmalloc (sizeof *f);
1945   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
1946     {
1947       const struct var_array *va = &t->vaas[a].vas[ix[a]];
1948       f->axes[a].vaa_idx = ix[a];
1949       f->axes[a].values = (va->n
1950                            ? xnmalloc (va->n, sizeof *f->axes[a].values)
1951                            : NULL);
1952       for (size_t i = 0; i < va->n; i++)
1953         value_clone (&f->axes[a].values[i], case_data (c, va->vars[i]),
1954                      var_get_width (va->vars[i]));
1955     }
1956   f->summaries = xmalloc (ss->n_summaries * sizeof *f->summaries);
1957   for (size_t i = 0; i < ss->n_summaries; i++)
1958     ctables_summary_init (&f->summaries[i], &ss->summaries[i]);
1959   hmap_insert (&t->ft, &f->node, hash);
1960
1961 summarize:
1962   for (size_t i = 0; i < ss->n_summaries; i++)
1963     ctables_summary_add (&f->summaries[i], &ss->summaries[i], ss->summary_var,
1964                          case_data (c, ss->summary_var), weight);
1965 }
1966
1967 static bool
1968 ctables_execute (struct dataset *ds, struct ctables *ct)
1969 {
1970   for (size_t i = 0; i < ct->n_tables; i++)
1971     {
1972       struct ctables_table *t = ct->tables[i];
1973       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
1974         if (t->axes[a])
1975           t->vaas[a] = enumerate_fts (a, t->axes[a]);
1976         else
1977           {
1978             struct var_array *va = xmalloc (sizeof *va);
1979             *va = (struct var_array) { .n = 0 };
1980             t->vaas[a] = (struct var_array2) { .vas = va, .n = 1 };
1981           }
1982
1983       for (size_t i = 0; i < t->vaas[t->summary_axis].n; i++)
1984         {
1985           struct var_array *va = &t->vaas[t->summary_axis].vas[i];
1986           if (!va->n_summaries)
1987             {
1988               va->summaries = xmalloc (sizeof *va->summaries);
1989               va->n_summaries = 1;
1990
1991               enum ctables_summary_function function
1992                 = va->summary_var ? CTSF_MEAN : CTSF_COUNT;
1993               struct ctables_var var = { .is_mrset = false, .var = va->summary_var };
1994
1995               *va->summaries = (struct ctables_summary_spec) {
1996                 .function = function,
1997                 .format = ctables_summary_default_format (function, &var),
1998                 .label = ctables_summary_default_label (function, 0),
1999               };
2000               if (!va->summary_var)
2001                 va->summary_var = va->vars[0];
2002             }
2003         }
2004     }
2005
2006   struct casereader *input = casereader_create_filter_weight (proc_open (ds),
2007                                                               dataset_dict (ds),
2008                                                               NULL, NULL);
2009   bool warn_on_invalid = true;
2010   for (struct ccase *c = casereader_read (input); c;
2011        case_unref (c), c = casereader_read (input))
2012     {
2013       double weight = dict_get_case_weight (dataset_dict (ds), c,
2014                                             &warn_on_invalid);
2015
2016       for (size_t i = 0; i < ct->n_tables; i++)
2017         {
2018           struct ctables_table *t = ct->tables[i];
2019
2020           for (size_t ir = 0; ir < t->vaas[PIVOT_AXIS_ROW].n; ir++)
2021             for (size_t ic = 0; ic < t->vaas[PIVOT_AXIS_COLUMN].n; ic++)
2022               for (size_t il = 0; il < t->vaas[PIVOT_AXIS_LAYER].n; il++)
2023                 ctables_freqtab_insert (t, c, ir, ic, il, weight);
2024         }
2025     }
2026   casereader_destroy (input);
2027
2028   for (size_t i = 0; i < ct->n_tables; i++)
2029     {
2030       struct ctables_table *t = ct->tables[i];
2031
2032       struct pivot_table *pt = pivot_table_create (N_("Custom Tables"));
2033       pivot_table_set_look (pt, ct->look);
2034       struct pivot_dimension *d[PIVOT_N_AXES];
2035       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2036         {
2037           static const char *names[] = {
2038             [PIVOT_AXIS_ROW] = N_("Rows"),
2039             [PIVOT_AXIS_COLUMN] = N_("Columns"),
2040             [PIVOT_AXIS_LAYER] = N_("Layers"),
2041           };
2042           d[a] = (t->axes[a] || a == t->summary_axis
2043                   ? pivot_dimension_create (pt, a, names[a])
2044                   : NULL);
2045           if (!d[a])
2046             continue;
2047
2048           assert (t->axes[a]);
2049
2050           struct ctables_freq **sorted = xnmalloc (t->ft.count, sizeof *sorted);
2051
2052           struct ctables_freq *f;
2053           size_t n = 0;
2054           HMAP_FOR_EACH (f, struct ctables_freq, node, &t->ft)
2055             sorted[n++] = f;
2056           assert (n == t->ft.count);
2057
2058           struct ctables_freq_sort_aux aux = { .t = t, .a = a };
2059           sort (sorted, n, sizeof *sorted, ctables_freq_compare_3way, &aux);
2060
2061           size_t max_depth = 0;
2062           for (size_t j = 0; j < t->vaas[a].n; j++)
2063             if (t->vaas[a].vas[j].n > max_depth)
2064               max_depth = t->vaas[a].vas[j].n;
2065
2066           struct pivot_category **groups = xnmalloc (max_depth, sizeof *groups);
2067           struct pivot_category *top = NULL;
2068           int prev_leaf = 0;
2069           for (size_t j = 0; j < n; j++)
2070             {
2071               struct ctables_freq *f = sorted[j];
2072               const struct var_array *va = &t->vaas[a].vas[f->axes[a].vaa_idx];
2073
2074               size_t n_common = 0;
2075               bool new_subtable = false;
2076               if (j > 0)
2077                 {
2078                   struct ctables_freq *prev = sorted[j - 1];
2079                   if (prev->axes[a].vaa_idx == f->axes[a].vaa_idx)
2080                     {
2081                       for (; n_common < va->n; n_common++)
2082                         if (!value_equal (&prev->axes[a].values[n_common],
2083                                           &f->axes[a].values[n_common],
2084                                           var_get_type (va->vars[n_common])))
2085                           break;
2086                     }
2087                   else
2088                     new_subtable = true;
2089                 }
2090               else
2091                 new_subtable = true;
2092
2093               if (new_subtable)
2094                 {
2095                   enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (va->vars[0])];
2096                   top = d[a]->root;
2097                   if (vlabel != CTVL_NONE)
2098                     top = pivot_category_create_group__ (
2099                       top, pivot_value_new_variable (va->vars[0]));
2100                 }
2101               if (n_common == va->n)
2102                 {
2103                   f->axes[a].leaf = prev_leaf;
2104                   continue;
2105                 }
2106
2107               for (size_t k = n_common; k < va->n; k++)
2108                 {
2109                   struct pivot_category *parent = k > 0 ? groups[k - 1] : top;
2110
2111                   struct pivot_value *label = pivot_value_new_var_value (
2112                     va->vars[k], &f->axes[a].values[k]);
2113
2114                   if (k == va->n - 1)
2115                     {
2116                       if (a == t->summary_axis)
2117                         {
2118                           parent = pivot_category_create_group__ (parent, label);
2119                           for (size_t m = 0; m < va->n_summaries; m++)
2120                             {
2121                               int leaf = pivot_category_create_leaf (
2122                                 parent, pivot_value_new_text (va->summaries[m].label));
2123                               if (m == 0)
2124                                 prev_leaf = leaf;
2125                             }
2126                         }
2127                       else
2128                         prev_leaf = pivot_category_create_leaf (parent, label);
2129                       break;
2130                     }
2131
2132                   parent = pivot_category_create_group__ (parent, label);
2133
2134                   enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (va->vars[k + 1])];
2135                   if (vlabel != CTVL_NONE)
2136                     parent = pivot_category_create_group__ (
2137                       parent, pivot_value_new_variable (va->vars[k + 1]));
2138                   groups[k] = parent;
2139                 }
2140
2141               f->axes[a].leaf = prev_leaf;
2142             }
2143           free (sorted);
2144           free (groups);
2145         }
2146       struct ctables_freq *f;
2147       HMAP_FOR_EACH (f, struct ctables_freq, node, &t->ft)
2148         {
2149           const struct var_array *ss = &t->vaas[t->summary_axis].vas[f->axes[t->summary_axis].vaa_idx];
2150           for (size_t j = 0; j < ss->n_summaries; j++)
2151             {
2152               size_t dindexes[3];
2153               size_t n_dindexes = 0;
2154
2155               for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2156                 if (d[a])
2157                   {
2158                     int leaf = f->axes[a].leaf;
2159                     if (a == t->summary_axis)
2160                       leaf += j;
2161                     dindexes[n_dindexes++] = leaf;
2162                   }
2163
2164               double value = ctables_summary_value (&f->summaries[j], &ss->summaries[j]);
2165               pivot_table_put (pt, dindexes, n_dindexes,
2166                                pivot_value_new_number (value));
2167             }
2168         }
2169
2170       pivot_table_submit (pt);
2171     }
2172
2173 #if 0
2174   for (size_t i = 0; i < ct->n_tables; i++)
2175     {
2176       struct ctables_table *t = ct->tables[i];
2177
2178       for (size_t j = 0; j < t->n_fts; j++)
2179         {
2180           struct ctables_freqtab *ft = t->fts[j];
2181           struct ctables_freq *f, *next;
2182           HMAP_FOR_EACH_SAFE (f, next, struct ctables_freq, node, &ft->data)
2183             {
2184               hmap_delete (&ft->data, &f->node);
2185               for (size_t k = 0; k < ft->n_summaries; k++)
2186                 ctables_summary_uninit (&f->summaries[k], &ft->summaries[k]);
2187               free (f->summaries);
2188               for (size_t k = 0; k < ft->vars.n; k++)
2189                 {
2190                   const struct variable *var = ft->vars.vars[k];
2191                   value_destroy (&f->values[k], var_get_width (var));
2192                 }
2193               free (f);
2194             }
2195           hmap_destroy (&ft->data);
2196           var_array_uninit (&ft->vars);
2197           free (ft);
2198         }
2199       free (t->fts);
2200     }
2201 #endif
2202   
2203   return proc_commit (ds);
2204 }
2205
2206 int
2207 cmd_ctables (struct lexer *lexer, struct dataset *ds)
2208 {
2209   size_t n_vars = dict_get_n_vars (dataset_dict (ds));
2210   enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
2211   enum settings_value_show tvars = settings_get_show_variables ();
2212   for (size_t i = 0; i < n_vars; i++)
2213     vlabels[i] = (enum ctables_vlabel) tvars;
2214
2215   struct ctables *ct = xmalloc (sizeof *ct);
2216   *ct = (struct ctables) {
2217     .look = pivot_table_look_unshare (pivot_table_look_ref (
2218                                         pivot_table_look_get_default ())),
2219     .vlabels = vlabels,
2220     .hide_threshold = 5,
2221   };
2222   ct->look->omit_empty = false;
2223
2224   if (!lex_force_match (lexer, T_SLASH))
2225     goto error;
2226
2227   while (!lex_match_id (lexer, "TABLE"))
2228     {
2229       if (lex_match_id (lexer, "FORMAT"))
2230         {
2231           double widths[2] = { SYSMIS, SYSMIS };
2232           double units_per_inch = 72.0;
2233
2234           while (lex_token (lexer) != T_SLASH)
2235             {
2236               if (lex_match_id (lexer, "MINCOLWIDTH"))
2237                 {
2238                   if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
2239                     goto error;
2240                 }
2241               else if (lex_match_id (lexer, "MAXCOLWIDTH"))
2242                 {
2243                   if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
2244                     goto error;
2245                 }
2246               else if (lex_match_id (lexer, "UNITS"))
2247                 {
2248                   lex_match (lexer, T_EQUALS);
2249                   if (lex_match_id (lexer, "POINTS"))
2250                     units_per_inch = 72.0;
2251                   else if (lex_match_id (lexer, "INCHES"))
2252                     units_per_inch = 1.0;
2253                   else if (lex_match_id (lexer, "CM"))
2254                     units_per_inch = 2.54;
2255                   else
2256                     {
2257                       lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
2258                       goto error;
2259                     }
2260                 }
2261               else if (lex_match_id (lexer, "EMPTY"))
2262                 {
2263                   free (ct->zero);
2264                   ct->zero = NULL;
2265
2266                   lex_match (lexer, T_EQUALS);
2267                   if (lex_match_id (lexer, "ZERO"))
2268                     {
2269                       /* Nothing to do. */
2270                     }
2271                   else if (lex_match_id (lexer, "BLANK"))
2272                     ct->zero = xstrdup ("");
2273                   else if (lex_force_string (lexer))
2274                     {
2275                       ct->zero = ss_xstrdup (lex_tokss (lexer));
2276                       lex_get (lexer);
2277                     }
2278                   else
2279                     goto error;
2280                 }
2281               else if (lex_match_id (lexer, "MISSING"))
2282                 {
2283                   lex_match (lexer, T_EQUALS);
2284                   if (!lex_force_string (lexer))
2285                     goto error;
2286
2287                   free (ct->missing);
2288                   ct->missing = (strcmp (lex_tokcstr (lexer), ".")
2289                                  ? ss_xstrdup (lex_tokss (lexer))
2290                                  : NULL);
2291                   lex_get (lexer);
2292                 }
2293               else
2294                 {
2295                   lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
2296                                        "UNITS", "EMPTY", "MISSING");
2297                   goto error;
2298                 }
2299             }
2300
2301           if (widths[0] != SYSMIS && widths[1] != SYSMIS
2302               && widths[0] > widths[1])
2303             {
2304               msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
2305               goto error;
2306             }
2307
2308           for (size_t i = 0; i < 2; i++)
2309             if (widths[i] != SYSMIS)
2310               {
2311                 int *wr = ct->look->width_ranges[TABLE_HORZ];
2312                 wr[i] = widths[i] / units_per_inch * 96.0;
2313                 if (wr[0] > wr[1])
2314                   wr[!i] = wr[i];
2315               }
2316         }
2317       else if (lex_match_id (lexer, "VLABELS"))
2318         {
2319           if (!lex_force_match_id (lexer, "VARIABLES"))
2320             goto error;
2321           lex_match (lexer, T_EQUALS);
2322
2323           struct variable **vars;
2324           size_t n_vars;
2325           if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
2326                                 PV_NO_SCRATCH))
2327             goto error;
2328
2329           if (!lex_force_match_id (lexer, "DISPLAY"))
2330             {
2331               free (vars);
2332               goto error;
2333             }
2334           lex_match (lexer, T_EQUALS);
2335
2336           enum ctables_vlabel vlabel;
2337           if (lex_match_id (lexer, "DEFAULT"))
2338             vlabel = (enum ctables_vlabel) settings_get_show_variables ();
2339           else if (lex_match_id (lexer, "NAME"))
2340             vlabel = CTVL_NAME;
2341           else if (lex_match_id (lexer, "LABEL"))
2342             vlabel = CTVL_LABEL;
2343           else if (lex_match_id (lexer, "BOTH"))
2344             vlabel = CTVL_BOTH;
2345           else if (lex_match_id (lexer, "NONE"))
2346             vlabel = CTVL_NONE;
2347           else
2348             {
2349               lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
2350                                    "BOTH", "NONE");
2351               free (vars);
2352               goto error;
2353             }
2354
2355           for (size_t i = 0; i < n_vars; i++)
2356             ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
2357           free (vars);
2358         }
2359       else if (lex_match_id (lexer, "MRSETS"))
2360         {
2361           if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
2362             goto error;
2363           lex_match (lexer, T_EQUALS);
2364           if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
2365             goto error;
2366         }
2367       else if (lex_match_id (lexer, "SMISSING"))
2368         {
2369           if (lex_match_id (lexer, "VARIABLE"))
2370             ct->smissing_listwise = false;
2371           else if (lex_match_id (lexer, "LISTWISE"))
2372             ct->smissing_listwise = true;
2373           else
2374             {
2375               lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
2376               goto error;
2377             }
2378         }
2379       /* XXX PCOMPUTE */
2380       else if (lex_match_id (lexer, "WEIGHT"))
2381         {
2382           if (!lex_force_match_id (lexer, "VARIABLE"))
2383             goto error;
2384           lex_match (lexer, T_EQUALS);
2385           ct->base_weight = parse_variable (lexer, dataset_dict (ds));
2386           if (!ct->base_weight)
2387             goto error;
2388         }
2389       else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
2390         {
2391           if (!lex_force_match_id (lexer, "COUNT"))
2392             goto error;
2393           lex_match (lexer, T_EQUALS);
2394           if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
2395             goto error;
2396           ct->hide_threshold = lex_integer (lexer);
2397           lex_get (lexer);
2398         }
2399       else
2400         {
2401           lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
2402                                "SMISSING", "PCOMPUTE", "PPROPERTIES",
2403                                "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
2404           goto error;
2405         }
2406
2407       if (!lex_force_match (lexer, T_SLASH))
2408         goto error;
2409     }
2410
2411   size_t allocated_tables = 0;
2412   do
2413     {
2414       if (ct->n_tables >= allocated_tables)
2415         ct->tables = x2nrealloc (ct->tables, &allocated_tables,
2416                                  sizeof *ct->tables);
2417
2418       struct ctables_table *t = xmalloc (sizeof *t);
2419       *t = (struct ctables_table) {
2420         .ft = HMAP_INITIALIZER (t->ft),
2421         .slabels_position = PIVOT_AXIS_COLUMN,
2422         .slabels_visible = true,
2423         .row_labels = CTLP_NORMAL,
2424         .col_labels = CTLP_NORMAL,
2425         .categories = xcalloc (dict_get_n_vars (dataset_dict (ds)),
2426                                sizeof *t->categories),
2427         .n_categories = dict_get_n_vars (dataset_dict (ds)),
2428         .cilevel = 95,
2429       };
2430       ct->tables[ct->n_tables++] = t;
2431
2432       lex_match (lexer, T_EQUALS);
2433       if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
2434         goto error;
2435       if (lex_match (lexer, T_BY))
2436         {
2437           if (!ctables_axis_parse (lexer, dataset_dict (ds),
2438                                    ct, t, PIVOT_AXIS_COLUMN))
2439             goto error;
2440
2441           if (lex_match (lexer, T_BY))
2442             {
2443               if (!ctables_axis_parse (lexer, dataset_dict (ds),
2444                                        ct, t, PIVOT_AXIS_LAYER))
2445                 goto error;
2446             }
2447         }
2448
2449       if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
2450           && !t->axes[PIVOT_AXIS_LAYER])
2451         {
2452           lex_error (lexer, _("At least one variable must be specified."));
2453           goto error;
2454         }
2455
2456       const struct ctables_axis *scales[PIVOT_N_AXES];
2457       size_t n_scales = 0;
2458       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2459         {
2460           scales[a] = find_scale (t->axes[a]);
2461           if (scales[a])
2462             n_scales++;
2463         }
2464       if (n_scales > 1)
2465         {
2466           msg (SE, _("Scale variables may appear only on one axis."));
2467           if (scales[PIVOT_AXIS_ROW])
2468             msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
2469                     _("This scale variable appears on the rows axis."));
2470           if (scales[PIVOT_AXIS_COLUMN])
2471             msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
2472                     _("This scale variable appears on the columns axis."));
2473           if (scales[PIVOT_AXIS_LAYER])
2474             msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
2475                     _("This scale variable appears on the layer axis."));
2476           goto error;
2477         }
2478
2479       const struct ctables_axis *summaries[PIVOT_N_AXES];
2480       size_t n_summaries = 0;
2481       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2482         {
2483           summaries[a] = (scales[a]
2484                           ? scales[a]
2485                           : find_categorical_summary_spec (t->axes[a]));
2486           if (summaries[a])
2487             n_summaries++;
2488         }
2489       if (n_summaries > 1)
2490         {
2491           msg (SE, _("Summaries may appear only on one axis."));
2492           if (summaries[PIVOT_AXIS_ROW])
2493             msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
2494                     _("This variable on the rows axis has a summary."));
2495           if (summaries[PIVOT_AXIS_COLUMN])
2496             msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
2497                     _("This variable on the columns axis has a summary."));
2498           if (summaries[PIVOT_AXIS_LAYER])
2499             msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
2500                     _("This variable on the layers axis has a summary."));
2501           goto error;
2502         }
2503       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2504         if (n_summaries ? summaries[a] : t->axes[a])
2505           {
2506             t->summary_axis = a;
2507             break;
2508           }
2509
2510       if (lex_token (lexer) == T_ENDCMD)
2511         break;
2512       if (!lex_force_match (lexer, T_SLASH))
2513         break;
2514
2515       while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
2516         {
2517           if (lex_match_id (lexer, "SLABELS"))
2518             {
2519               while (lex_token (lexer) != T_SLASH)
2520                 {
2521                   if (lex_match_id (lexer, "POSITION"))
2522                     {
2523                       lex_match (lexer, T_EQUALS);
2524                       if (lex_match_id (lexer, "COLUMN"))
2525                         t->slabels_position = PIVOT_AXIS_COLUMN;
2526                       else if (lex_match_id (lexer, "ROW"))
2527                         t->slabels_position = PIVOT_AXIS_ROW;
2528                       else if (lex_match_id (lexer, "LAYER"))
2529                         t->slabels_position = PIVOT_AXIS_LAYER;
2530                       else
2531                         {
2532                           lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
2533                           goto error;
2534                         }
2535                     }
2536                   else if (lex_match_id (lexer, "VISIBLE"))
2537                     {
2538                       lex_match (lexer, T_EQUALS);
2539                       if (!parse_bool (lexer, &t->slabels_visible))
2540                         goto error;
2541                     }
2542                   else
2543                     {
2544                       lex_error_expecting (lexer, "POSITION", "VISIBLE");
2545                       goto error;
2546                     }
2547                 }
2548             }
2549           else if (lex_match_id (lexer, "CLABELS"))
2550             {
2551               while (lex_token (lexer) != T_SLASH)
2552                 {
2553                   if (lex_match_id (lexer, "AUTO"))
2554                     t->row_labels = t->col_labels = CTLP_NORMAL;
2555                   else if (lex_match_id (lexer, "ROWLABELS"))
2556                     {
2557                       lex_match (lexer, T_EQUALS);
2558                       if (lex_match_id (lexer, "OPPOSITE"))
2559                         t->row_labels = CTLP_OPPOSITE;
2560                       else if (lex_match_id (lexer, "LAYER"))
2561                         t->row_labels = CTLP_LAYER;
2562                       else
2563                         {
2564                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
2565                           goto error;
2566                         }
2567                     }
2568                   else if (lex_match_id (lexer, "COLLABELS"))
2569                     {
2570                       lex_match (lexer, T_EQUALS);
2571                       if (lex_match_id (lexer, "OPPOSITE"))
2572                         t->col_labels = CTLP_OPPOSITE;
2573                       else if (lex_match_id (lexer, "LAYER"))
2574                         t->col_labels = CTLP_LAYER;
2575                       else
2576                         {
2577                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
2578                           goto error;
2579                         }
2580                     }
2581                   else
2582                     {
2583                       lex_error_expecting (lexer, "AUTO", "ROWLABELS",
2584                                            "COLLABELS");
2585                       goto error;
2586                     }
2587                 }
2588             }
2589           else if (lex_match_id (lexer, "CRITERIA"))
2590             {
2591               if (!lex_force_match_id (lexer, "CILEVEL"))
2592                 goto error;
2593               lex_match (lexer, T_EQUALS);
2594
2595               if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
2596                 goto error;
2597               t->cilevel = lex_number (lexer);
2598               lex_get (lexer);
2599             }
2600           else if (lex_match_id (lexer, "CATEGORIES"))
2601             {
2602               if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
2603                 goto error;
2604             }
2605           else if (lex_match_id (lexer, "TITLES"))
2606             {
2607               do
2608                 {
2609                   char **textp;
2610                   if (lex_match_id (lexer, "CAPTION"))
2611                     textp = &t->caption;
2612                   else if (lex_match_id (lexer, "CORNER"))
2613                     textp = &t->corner;
2614                   else if (lex_match_id (lexer, "TITLE"))
2615                     textp = &t->title;
2616                   else
2617                     {
2618                       lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
2619                       goto error;
2620                     }
2621                   lex_match (lexer, T_EQUALS);
2622
2623                   struct string s = DS_EMPTY_INITIALIZER;
2624                   while (lex_is_string (lexer))
2625                     {
2626                       if (!ds_is_empty (&s))
2627                         ds_put_byte (&s, ' ');
2628                       ds_put_substring (&s, lex_tokss (lexer));
2629                       lex_get (lexer);
2630                     }
2631                   free (*textp);
2632                   *textp = ds_steal_cstr (&s);
2633                 }
2634               while (lex_token (lexer) != T_SLASH
2635                      && lex_token (lexer) != T_ENDCMD);
2636             }
2637           else if (lex_match_id (lexer, "SIGTEST"))
2638             {
2639               if (!t->chisq)
2640                 {
2641                   t->chisq = xmalloc (sizeof *t->chisq);
2642                   *t->chisq = (struct ctables_chisq) {
2643                     .alpha = .05,
2644                     .include_mrsets = true,
2645                     .all_visible = true,
2646                   };
2647                 }
2648
2649               do
2650                 {
2651                   if (lex_match_id (lexer, "TYPE"))
2652                     {
2653                       lex_match (lexer, T_EQUALS);
2654                       if (!lex_force_match_id (lexer, "CHISQUARE"))
2655                         goto error;
2656                     }
2657                   else if (lex_match_id (lexer, "ALPHA"))
2658                     {
2659                       lex_match (lexer, T_EQUALS);
2660                       if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
2661                         goto error;
2662                       t->chisq->alpha = lex_number (lexer);
2663                       lex_get (lexer);
2664                     }
2665                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
2666                     {
2667                       lex_match (lexer, T_EQUALS);
2668                       if (parse_bool (lexer, &t->chisq->include_mrsets))
2669                         goto error;
2670                     }
2671                   else if (lex_match_id (lexer, "CATEGORIES"))
2672                     {
2673                       lex_match (lexer, T_EQUALS);
2674                       if (lex_match_id (lexer, "ALLVISIBLE"))
2675                         t->chisq->all_visible = true;
2676                       else if (lex_match_id (lexer, "SUBTOTALS"))
2677                         t->chisq->all_visible = false;
2678                       else
2679                         {
2680                           lex_error_expecting (lexer,
2681                                                "ALLVISIBLE", "SUBTOTALS");
2682                           goto error;
2683                         }
2684                     }
2685                   else
2686                     {
2687                       lex_error_expecting (lexer, "TYPE", "ALPHA",
2688                                            "INCLUDEMRSETS", "CATEGORIES");
2689                       goto error;
2690                     }
2691                 }
2692               while (lex_token (lexer) != T_SLASH
2693                      && lex_token (lexer) != T_ENDCMD);
2694             }
2695           else if (lex_match_id (lexer, "COMPARETEST"))
2696             {
2697               if (!t->pairwise)
2698                 {
2699                   t->pairwise = xmalloc (sizeof *t->pairwise);
2700                   *t->pairwise = (struct ctables_pairwise) {
2701                     .type = PROP,
2702                     .alpha = { .05, .05 },
2703                     .adjust = BONFERRONI,
2704                     .include_mrsets = true,
2705                     .meansvariance_allcats = true,
2706                     .all_visible = true,
2707                     .merge = false,
2708                     .apa_style = true,
2709                     .show_sig = false,
2710                   };
2711                 }
2712
2713               do
2714                 {
2715                   if (lex_match_id (lexer, "TYPE"))
2716                     {
2717                       lex_match (lexer, T_EQUALS);
2718                       if (lex_match_id (lexer, "PROP"))
2719                         t->pairwise->type = PROP;
2720                       else if (lex_match_id (lexer, "MEAN"))
2721                         t->pairwise->type = MEAN;
2722                       else
2723                         {
2724                           lex_error_expecting (lexer, "PROP", "MEAN");
2725                           goto error;
2726                         }
2727                     }
2728                   else if (lex_match_id (lexer, "ALPHA"))
2729                     {
2730                       lex_match (lexer, T_EQUALS);
2731
2732                       if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
2733                         goto error;
2734                       double a0 = lex_number (lexer);
2735                       lex_get (lexer);
2736
2737                       lex_match (lexer, T_COMMA);
2738                       if (lex_is_number (lexer))
2739                         {
2740                           if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
2741                             goto error;
2742                           double a1 = lex_number (lexer);
2743                           lex_get (lexer);
2744
2745                           t->pairwise->alpha[0] = MIN (a0, a1);
2746                           t->pairwise->alpha[1] = MAX (a0, a1);
2747                         }
2748                       else
2749                         t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
2750                     }
2751                   else if (lex_match_id (lexer, "ADJUST"))
2752                     {
2753                       lex_match (lexer, T_EQUALS);
2754                       if (lex_match_id (lexer, "BONFERRONI"))
2755                         t->pairwise->adjust = BONFERRONI;
2756                       else if (lex_match_id (lexer, "BH"))
2757                         t->pairwise->adjust = BH;
2758                       else if (lex_match_id (lexer, "NONE"))
2759                         t->pairwise->adjust = 0;
2760                       else
2761                         {
2762                           lex_error_expecting (lexer, "BONFERRONI", "BH",
2763                                                "NONE");
2764                           goto error;
2765                         }
2766                     }
2767                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
2768                     {
2769                       lex_match (lexer, T_EQUALS);
2770                       if (!parse_bool (lexer, &t->pairwise->include_mrsets))
2771                         goto error;
2772                     }
2773                   else if (lex_match_id (lexer, "MEANSVARIANCE"))
2774                     {
2775                       lex_match (lexer, T_EQUALS);
2776                       if (lex_match_id (lexer, "ALLCATS"))
2777                         t->pairwise->meansvariance_allcats = true;
2778                       else if (lex_match_id (lexer, "TESTEDCATS"))
2779                         t->pairwise->meansvariance_allcats = false;
2780                       else
2781                         {
2782                           lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
2783                           goto error;
2784                         }
2785                     }
2786                   else if (lex_match_id (lexer, "CATEGORIES"))
2787                     {
2788                       lex_match (lexer, T_EQUALS);
2789                       if (lex_match_id (lexer, "ALLVISIBLE"))
2790                         t->pairwise->all_visible = true;
2791                       else if (lex_match_id (lexer, "SUBTOTALS"))
2792                         t->pairwise->all_visible = false;
2793                       else
2794                         {
2795                           lex_error_expecting (lexer, "ALLVISIBLE",
2796                                                "SUBTOTALS");
2797                           goto error;
2798                         }
2799                     }
2800                   else if (lex_match_id (lexer, "MERGE"))
2801                     {
2802                       lex_match (lexer, T_EQUALS);
2803                       if (!parse_bool (lexer, &t->pairwise->merge))
2804                         goto error;
2805                     }
2806                   else if (lex_match_id (lexer, "STYLE"))
2807                     {
2808                       lex_match (lexer, T_EQUALS);
2809                       if (lex_match_id (lexer, "APA"))
2810                         t->pairwise->apa_style = true;
2811                       else if (lex_match_id (lexer, "SIMPLE"))
2812                         t->pairwise->apa_style = false;
2813                       else
2814                         {
2815                           lex_error_expecting (lexer, "APA", "SIMPLE");
2816                           goto error;
2817                         }
2818                     }
2819                   else if (lex_match_id (lexer, "SHOWSIG"))
2820                     {
2821                       lex_match (lexer, T_EQUALS);
2822                       if (!parse_bool (lexer, &t->pairwise->show_sig))
2823                         goto error;
2824                     }
2825                   else
2826                     {
2827                       lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
2828                                            "INCLUDEMRSETS", "MEANSVARIANCE",
2829                                            "CATEGORIES", "MERGE", "STYLE",
2830                                            "SHOWSIG");
2831                       goto error;
2832                     }
2833                 }
2834               while (lex_token (lexer) != T_SLASH
2835                      && lex_token (lexer) != T_ENDCMD);
2836             }
2837           else
2838             {
2839               lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
2840                                    "CRITERIA", "CATEGORIES", "TITLES",
2841                                    "SIGTEST", "COMPARETEST");
2842               goto error;
2843             }
2844         }
2845
2846       if (t->row_labels != CTLP_NORMAL && t->col_labels != CTLP_NORMAL)
2847         {
2848           msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
2849           goto error;
2850         }
2851
2852     }
2853   while (lex_token (lexer) != T_ENDCMD);
2854
2855   bool ok = ctables_execute (ds, ct);
2856   ctables_destroy (ct);
2857   return ok ? CMD_SUCCESS : CMD_FAILURE;
2858
2859 error:
2860   ctables_destroy (ct);
2861   return CMD_FAILURE;
2862 }
2863