data filled in
[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 #if 0
1410 static void
1411 ctables_summary_init (union ctables_summary *s,
1412                       const struct ctables_summary_spec *ss)
1413 {
1414   switch (ss->function)
1415     {
1416     case CTSF_COUNT:
1417     case CTSF_ECOUNT:
1418     case CTSF_ROWPCT_COUNT:
1419     case CTSF_COLPCT_COUNT:
1420     case CTSF_TABLEPCT_COUNT:
1421     case CTSF_SUBTABLEPCT_COUNT:
1422     case CTSF_LAYERPCT_COUNT:
1423     case CTSF_LAYERROWPCT_COUNT:
1424     case CTSF_LAYERCOLPCT_COUNT:
1425     case CTSF_ROWPCT_VALIDN:
1426     case CTSF_COLPCT_VALIDN:
1427     case CTSF_TABLEPCT_VALIDN:
1428     case CTSF_SUBTABLEPCT_VALIDN:
1429     case CTSF_LAYERPCT_VALIDN:
1430     case CTSF_LAYERROWPCT_VALIDN:
1431     case CTSF_LAYERCOLPCT_VALIDN:
1432     case CTSF_ROWPCT_TOTALN:
1433     case CTSF_COLPCT_TOTALN:
1434     case CTSF_TABLEPCT_TOTALN:
1435     case CTSF_SUBTABLEPCT_TOTALN:
1436     case CTSF_LAYERPCT_TOTALN:
1437     case CTSF_LAYERROWPCT_TOTALN:
1438     case CTSF_LAYERCOLPCT_TOTALN:
1439     case CSTF_TOTALN:
1440     case CTSF_ETOTALN:
1441     case CTSF_VALIDN:
1442     case CTSF_EVALIDN:
1443       s->missing = s->valid = 0;
1444       break;
1445
1446     case CTSF_MAXIMUM:
1447     case CTSF_MINIMUM:
1448     case CTSF_RANGE:
1449       s->min = s->max = SYSMIS;
1450       break;
1451
1452     case CTSF_MEAN:
1453     case CTSF_SEMEAN:
1454     case CTSF_STDDEV:
1455     case CTSF_SUM:
1456     case CTSF_VARIANCE:
1457     case CTSF_ROWPCT_SUM:
1458     case CTSF_COLPCT_SUM:
1459     case CTSF_TABLEPCT_SUM:
1460     case CTSF_SUBTABLEPCT_SUM:
1461     case CTSF_LAYERPCT_SUM:
1462     case CTSF_LAYERROWPCT_SUM:
1463     case CTSF_LAYERCOLPCT_SUM:
1464       s->moments = moments1_create (MOMENT_VARIANCE);
1465       break;
1466
1467     case CTSF_MEDIAN:
1468     case CTSF_MISSING:
1469     case CTSF_MODE:
1470     case CTSF_PTILE:
1471       NOT_REACHED ();
1472
1473     case CTSF_RESPONSES:
1474     case CTSF_ROWPCT_RESPONSES:
1475     case CTSF_COLPCT_RESPONSES:
1476     case CTSF_TABLEPCT_RESPONSES:
1477     case CTSF_SUBTABLEPCT_RESPONSES:
1478     case CTSF_LAYERPCT_RESPONSES:
1479     case CTSF_LAYERROWPCT_RESPONSES:
1480     case CTSF_LAYERCOLPCT_RESPONSES:
1481     case CTSF_ROWPCT_RESPONSES_COUNT:
1482     case CTSF_COLPCT_RESPONSES_COUNT:
1483     case CTSF_TABLEPCT_RESPONSES_COUNT:
1484     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1485     case CTSF_LAYERPCT_RESPONSES_COUNT:
1486     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1487     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1488     case CTSF_ROWPCT_COUNT_RESPONSES:
1489     case CTSF_COLPCT_COUNT_RESPONSES:
1490     case CTSF_TABLEPCT_COUNT_RESPONSES:
1491     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1492     case CTSF_LAYERPCT_COUNT_RESPONSES:
1493     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1494     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1495       NOT_REACHED ();
1496     }
1497 }
1498
1499 static void
1500 ctables_summary_uninit (union ctables_summary *s,
1501                         const struct ctables_summary_spec *ss)
1502 {
1503   switch (ss->function)
1504     {
1505     case CTSF_COUNT:
1506     case CTSF_ECOUNT:
1507     case CTSF_ROWPCT_COUNT:
1508     case CTSF_COLPCT_COUNT:
1509     case CTSF_TABLEPCT_COUNT:
1510     case CTSF_SUBTABLEPCT_COUNT:
1511     case CTSF_LAYERPCT_COUNT:
1512     case CTSF_LAYERROWPCT_COUNT:
1513     case CTSF_LAYERCOLPCT_COUNT:
1514     case CTSF_ROWPCT_VALIDN:
1515     case CTSF_COLPCT_VALIDN:
1516     case CTSF_TABLEPCT_VALIDN:
1517     case CTSF_SUBTABLEPCT_VALIDN:
1518     case CTSF_LAYERPCT_VALIDN:
1519     case CTSF_LAYERROWPCT_VALIDN:
1520     case CTSF_LAYERCOLPCT_VALIDN:
1521     case CTSF_ROWPCT_TOTALN:
1522     case CTSF_COLPCT_TOTALN:
1523     case CTSF_TABLEPCT_TOTALN:
1524     case CTSF_SUBTABLEPCT_TOTALN:
1525     case CTSF_LAYERPCT_TOTALN:
1526     case CTSF_LAYERROWPCT_TOTALN:
1527     case CTSF_LAYERCOLPCT_TOTALN:
1528     case CSTF_TOTALN:
1529     case CTSF_ETOTALN:
1530     case CTSF_VALIDN:
1531     case CTSF_EVALIDN:
1532       break;
1533
1534     case CTSF_MAXIMUM:
1535     case CTSF_MINIMUM:
1536     case CTSF_RANGE:
1537       break;
1538
1539     case CTSF_MEAN:
1540     case CTSF_SEMEAN:
1541     case CTSF_STDDEV:
1542     case CTSF_SUM:
1543     case CTSF_VARIANCE:
1544     case CTSF_ROWPCT_SUM:
1545     case CTSF_COLPCT_SUM:
1546     case CTSF_TABLEPCT_SUM:
1547     case CTSF_SUBTABLEPCT_SUM:
1548     case CTSF_LAYERPCT_SUM:
1549     case CTSF_LAYERROWPCT_SUM:
1550     case CTSF_LAYERCOLPCT_SUM:
1551       moments1_destroy (s->moments);
1552       break;
1553
1554     case CTSF_MEDIAN:
1555     case CTSF_MISSING:
1556     case CTSF_MODE:
1557     case CTSF_PTILE:
1558       NOT_REACHED ();
1559
1560     case CTSF_RESPONSES:
1561     case CTSF_ROWPCT_RESPONSES:
1562     case CTSF_COLPCT_RESPONSES:
1563     case CTSF_TABLEPCT_RESPONSES:
1564     case CTSF_SUBTABLEPCT_RESPONSES:
1565     case CTSF_LAYERPCT_RESPONSES:
1566     case CTSF_LAYERROWPCT_RESPONSES:
1567     case CTSF_LAYERCOLPCT_RESPONSES:
1568     case CTSF_ROWPCT_RESPONSES_COUNT:
1569     case CTSF_COLPCT_RESPONSES_COUNT:
1570     case CTSF_TABLEPCT_RESPONSES_COUNT:
1571     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1572     case CTSF_LAYERPCT_RESPONSES_COUNT:
1573     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1574     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1575     case CTSF_ROWPCT_COUNT_RESPONSES:
1576     case CTSF_COLPCT_COUNT_RESPONSES:
1577     case CTSF_TABLEPCT_COUNT_RESPONSES:
1578     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1579     case CTSF_LAYERPCT_COUNT_RESPONSES:
1580     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1581     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1582       NOT_REACHED ();
1583     }
1584 }
1585
1586 static void
1587 ctables_summary_add (union ctables_summary *s,
1588                      const struct ctables_summary_spec *ss,
1589                      const struct variable *var, const union value *value,
1590                      double weight)
1591 {
1592   switch (ss->function)
1593     {
1594     case CTSF_COUNT:
1595     case CTSF_ECOUNT:
1596     case CTSF_ROWPCT_COUNT:
1597     case CTSF_COLPCT_COUNT:
1598     case CTSF_TABLEPCT_COUNT:
1599     case CTSF_SUBTABLEPCT_COUNT:
1600     case CTSF_LAYERPCT_COUNT:
1601     case CTSF_LAYERROWPCT_COUNT:
1602     case CTSF_LAYERCOLPCT_COUNT:
1603     case CTSF_ROWPCT_VALIDN:
1604     case CTSF_COLPCT_VALIDN:
1605     case CTSF_TABLEPCT_VALIDN:
1606     case CTSF_SUBTABLEPCT_VALIDN:
1607     case CTSF_LAYERPCT_VALIDN:
1608     case CTSF_LAYERROWPCT_VALIDN:
1609     case CTSF_LAYERCOLPCT_VALIDN:
1610     case CTSF_ROWPCT_TOTALN:
1611     case CTSF_COLPCT_TOTALN:
1612     case CTSF_TABLEPCT_TOTALN:
1613     case CTSF_SUBTABLEPCT_TOTALN:
1614     case CTSF_LAYERPCT_TOTALN:
1615     case CTSF_LAYERROWPCT_TOTALN:
1616     case CTSF_LAYERCOLPCT_TOTALN:
1617     case CSTF_TOTALN:
1618     case CTSF_ETOTALN:
1619     case CTSF_VALIDN:
1620     case CTSF_EVALIDN:
1621       if (var_is_value_missing (var, value))
1622         s->missing += weight;
1623       else
1624         s->valid += weight;
1625       break;
1626
1627     case CTSF_MAXIMUM:
1628     case CTSF_MINIMUM:
1629     case CTSF_RANGE:
1630       if (!var_is_value_missing (var, value))
1631         {
1632           assert (!var_is_alpha (var)); /* XXX? */
1633           if (s->min == SYSMIS || value->f < s->min)
1634             s->min = value->f;
1635           if (s->max == SYSMIS || value->f > s->max)
1636             s->max = value->f;
1637         }
1638       break;
1639
1640     case CTSF_MEAN:
1641     case CTSF_SEMEAN:
1642     case CTSF_STDDEV:
1643     case CTSF_SUM:
1644     case CTSF_VARIANCE:
1645     case CTSF_ROWPCT_SUM:
1646     case CTSF_COLPCT_SUM:
1647     case CTSF_TABLEPCT_SUM:
1648     case CTSF_SUBTABLEPCT_SUM:
1649     case CTSF_LAYERPCT_SUM:
1650     case CTSF_LAYERROWPCT_SUM:
1651     case CTSF_LAYERCOLPCT_SUM:
1652       moments1_add (s->moments, value->f, weight);
1653       break;
1654
1655     case CTSF_MEDIAN:
1656     case CTSF_MISSING:
1657     case CTSF_MODE:
1658     case CTSF_PTILE:
1659       NOT_REACHED ();
1660
1661     case CTSF_RESPONSES:
1662     case CTSF_ROWPCT_RESPONSES:
1663     case CTSF_COLPCT_RESPONSES:
1664     case CTSF_TABLEPCT_RESPONSES:
1665     case CTSF_SUBTABLEPCT_RESPONSES:
1666     case CTSF_LAYERPCT_RESPONSES:
1667     case CTSF_LAYERROWPCT_RESPONSES:
1668     case CTSF_LAYERCOLPCT_RESPONSES:
1669     case CTSF_ROWPCT_RESPONSES_COUNT:
1670     case CTSF_COLPCT_RESPONSES_COUNT:
1671     case CTSF_TABLEPCT_RESPONSES_COUNT:
1672     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1673     case CTSF_LAYERPCT_RESPONSES_COUNT:
1674     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1675     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1676     case CTSF_ROWPCT_COUNT_RESPONSES:
1677     case CTSF_COLPCT_COUNT_RESPONSES:
1678     case CTSF_TABLEPCT_COUNT_RESPONSES:
1679     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1680     case CTSF_LAYERPCT_COUNT_RESPONSES:
1681     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1682     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1683       NOT_REACHED ();
1684     }
1685 }
1686
1687 static double
1688 ctables_summary_value (union ctables_summary *s,
1689                        const struct ctables_summary_spec *ss)
1690 {
1691   switch (ss->function)
1692     {
1693     case CTSF_COUNT:
1694     case CTSF_ECOUNT:
1695       return s->valid;
1696
1697     case CTSF_ROWPCT_COUNT:
1698     case CTSF_COLPCT_COUNT:
1699     case CTSF_TABLEPCT_COUNT:
1700     case CTSF_SUBTABLEPCT_COUNT:
1701     case CTSF_LAYERPCT_COUNT:
1702     case CTSF_LAYERROWPCT_COUNT:
1703     case CTSF_LAYERCOLPCT_COUNT:
1704     case CTSF_ROWPCT_VALIDN:
1705     case CTSF_COLPCT_VALIDN:
1706     case CTSF_TABLEPCT_VALIDN:
1707     case CTSF_SUBTABLEPCT_VALIDN:
1708     case CTSF_LAYERPCT_VALIDN:
1709     case CTSF_LAYERROWPCT_VALIDN:
1710     case CTSF_LAYERCOLPCT_VALIDN:
1711     case CTSF_ROWPCT_TOTALN:
1712     case CTSF_COLPCT_TOTALN:
1713     case CTSF_TABLEPCT_TOTALN:
1714     case CTSF_SUBTABLEPCT_TOTALN:
1715     case CTSF_LAYERPCT_TOTALN:
1716     case CTSF_LAYERROWPCT_TOTALN:
1717     case CTSF_LAYERCOLPCT_TOTALN:
1718       NOT_REACHED ();
1719
1720     case CSTF_TOTALN:
1721     case CTSF_ETOTALN:
1722       return s->valid + s->missing;
1723
1724     case CTSF_VALIDN:
1725     case CTSF_EVALIDN:
1726       return s->valid;
1727
1728     case CTSF_MAXIMUM:
1729       return s->max;
1730
1731     case CTSF_MINIMUM:
1732       return s->min;
1733
1734     case CTSF_RANGE:
1735       return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
1736
1737     case CTSF_MEAN:
1738       {
1739         double mean;
1740         moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
1741         return mean;
1742       }
1743
1744     case CTSF_SEMEAN:
1745       {
1746         double weight, variance;
1747         moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
1748         return calc_semean (variance, weight);
1749       }
1750
1751     case CTSF_STDDEV:
1752       {
1753         double variance;
1754         moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
1755         return variance != SYSMIS ? sqrt (variance) : SYSMIS;
1756       }
1757
1758     case CTSF_SUM:
1759       {
1760         double weight, mean;
1761         moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
1762         return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
1763       }
1764
1765     case CTSF_VARIANCE:
1766       {
1767         double variance;
1768         moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
1769         return variance;
1770       }
1771
1772     case CTSF_ROWPCT_SUM:
1773     case CTSF_COLPCT_SUM:
1774     case CTSF_TABLEPCT_SUM:
1775     case CTSF_SUBTABLEPCT_SUM:
1776     case CTSF_LAYERPCT_SUM:
1777     case CTSF_LAYERROWPCT_SUM:
1778     case CTSF_LAYERCOLPCT_SUM:
1779       NOT_REACHED ();
1780
1781     case CTSF_MEDIAN:
1782     case CTSF_MISSING:
1783     case CTSF_MODE:
1784     case CTSF_PTILE:
1785       NOT_REACHED ();
1786
1787     case CTSF_RESPONSES:
1788     case CTSF_ROWPCT_RESPONSES:
1789     case CTSF_COLPCT_RESPONSES:
1790     case CTSF_TABLEPCT_RESPONSES:
1791     case CTSF_SUBTABLEPCT_RESPONSES:
1792     case CTSF_LAYERPCT_RESPONSES:
1793     case CTSF_LAYERROWPCT_RESPONSES:
1794     case CTSF_LAYERCOLPCT_RESPONSES:
1795     case CTSF_ROWPCT_RESPONSES_COUNT:
1796     case CTSF_COLPCT_RESPONSES_COUNT:
1797     case CTSF_TABLEPCT_RESPONSES_COUNT:
1798     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1799     case CTSF_LAYERPCT_RESPONSES_COUNT:
1800     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1801     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1802     case CTSF_ROWPCT_COUNT_RESPONSES:
1803     case CTSF_COLPCT_COUNT_RESPONSES:
1804     case CTSF_TABLEPCT_COUNT_RESPONSES:
1805     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1806     case CTSF_LAYERPCT_COUNT_RESPONSES:
1807     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1808     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1809       NOT_REACHED ();
1810     }
1811
1812   NOT_REACHED ();
1813 }
1814 #endif
1815
1816 struct ctables_freq
1817   {
1818     struct hmap_node node;      /* Element in hash table. */
1819
1820     struct
1821       {
1822         size_t vaa_idx;
1823         union value *values;
1824         int leaf;
1825       }
1826     axes[PIVOT_N_AXES];
1827
1828     //union ctables_summary *summaries;
1829     double count;
1830   };
1831
1832 #if 0
1833 static struct ctables_freq *
1834 ctables_freq_create (struct ctables_freqtab *ft)
1835 {
1836   struct ctables_freq *f = xmalloc (sizeof *f + ft->vars.n * sizeof *f->values);
1837   f->summaries = xmalloc (ft->n_summaries * sizeof *f->summaries);
1838   for (size_t i = 0; i < ft->n_summaries; i++)
1839     ctables_summary_init (&f->summaries[i], &ft->summaries[i]);
1840   return f;
1841 }
1842
1843 static void
1844 ctables_freq_add (struct ctables_freqtab *ft, struct ctables_freq *f,
1845                   const struct variable *var, const union value *value,
1846                   double weight)
1847 {
1848   for (size_t i = 0; i < ft->n_summaries; i++)
1849     ctables_summary_add (&f->summaries[i], &ft->summaries[i],
1850                          var, value, weight);
1851 }
1852 #endif
1853
1854 struct ctables_freq_sort_aux
1855   {
1856     const struct ctables_table *t;
1857     enum pivot_axis_type a;
1858   };
1859
1860 static int
1861 ctables_freq_compare_3way (const void *a_, const void *b_, const void *aux_)
1862 {
1863   const struct ctables_freq_sort_aux *aux = aux_;
1864   struct ctables_freq *const *ap = a_;
1865   struct ctables_freq *const *bp = b_;
1866   const struct ctables_freq *a = *ap;
1867   const struct ctables_freq *b = *bp;
1868
1869   size_t a_idx = a->axes[aux->a].vaa_idx;
1870   size_t b_idx = b->axes[aux->a].vaa_idx;
1871   if (a_idx != b_idx)
1872     return a_idx < b_idx ? -1 : 1;
1873
1874   const struct var_array *va = &aux->t->vaas[aux->a].vas[a_idx];
1875   for (size_t i = 0; i < va->n; i++)
1876     {
1877       int cmp = value_compare_3way (&a->axes[aux->a].values[i],
1878                                     &b->axes[aux->a].values[i],
1879                                     var_get_width (va->vars[i]));
1880       if (cmp)
1881         return cmp;
1882     }
1883   return 0;
1884 }
1885
1886 /* Algorithm:
1887
1888    For each row:
1889        For each ctables_table:
1890            For each combination of row vars:
1891                For each combination of column vars:
1892                    For each combination of layer vars:
1893                        Add entry
1894    Make a table of row values:
1895        Sort entries by row values
1896        Assign a 0-based index to each actual value
1897        Construct a dimension
1898    Make a table of column values
1899    Make a table of layer values
1900    For each entry:
1901        Fill the table entry using the indexes from before.
1902  */
1903
1904 static void
1905 ctables_freqtab_insert (struct ctables_table *t,
1906                         const struct ccase *c,
1907                         size_t ir, size_t ic, size_t il,
1908                         double weight)
1909 {
1910   size_t ix[PIVOT_N_AXES] = {
1911     [PIVOT_AXIS_ROW] = ir,
1912     [PIVOT_AXIS_COLUMN] = ic,
1913     [PIVOT_AXIS_LAYER] = il,
1914   };
1915
1916   size_t hash = 0;
1917   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
1918     {
1919       const struct var_array *va = &t->vaas[a].vas[ix[a]];
1920       hash = hash_int (ix[a], hash);
1921       for (size_t i = 0; i < va->n; i++)
1922         hash = value_hash (case_data (c, va->vars[i]),
1923                            var_get_width (va->vars[i]), hash);
1924     }
1925
1926   struct ctables_freq *f;
1927   HMAP_FOR_EACH_WITH_HASH (f, struct ctables_freq, node, hash, &t->ft)
1928     {
1929       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
1930         {
1931           const struct var_array *va = &t->vaas[a].vas[ix[a]];
1932           if (f->axes[a].vaa_idx != ix[a])
1933             goto not_equal;
1934           for (size_t i = 0; i < va->n; i++)
1935             if (!value_equal (case_data (c, va->vars[i]),
1936                               &f->axes[a].values[i],
1937                               var_get_width (va->vars[i])))
1938               goto not_equal;
1939         }
1940
1941       f->count += weight;
1942       return;
1943
1944     not_equal: ;
1945     }
1946
1947   f = xmalloc (sizeof *f);
1948   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
1949     {
1950       const struct var_array *va = &t->vaas[a].vas[ix[a]];
1951       f->axes[a].vaa_idx = ix[a];
1952       f->axes[a].values = (va->n
1953                            ? xnmalloc (va->n, sizeof *f->axes[a].values)
1954                            : NULL);
1955       for (size_t i = 0; i < va->n; i++)
1956         value_clone (&f->axes[a].values[i], case_data (c, va->vars[i]),
1957                      var_get_width (va->vars[i]));
1958     }
1959   f->count = weight;
1960   hmap_insert (&t->ft, &f->node, hash);
1961 }
1962
1963 static bool
1964 ctables_execute (struct dataset *ds, struct ctables *ct)
1965 {
1966   for (size_t i = 0; i < ct->n_tables; i++)
1967     {
1968       struct ctables_table *t = ct->tables[i];
1969       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
1970         if (t->axes[a])
1971           t->vaas[a] = enumerate_fts (a, t->axes[a]);
1972         else
1973           {
1974             struct var_array *va = xmalloc (sizeof *va);
1975             *va = (struct var_array) { .n = 0 };
1976             t->vaas[a] = (struct var_array2) { .vas = va, .n = 1 };
1977           }
1978
1979       for (size_t i = 0; i < t->vaas[t->summary_axis].n; i++)
1980         {
1981           struct var_array *va = &t->vaas[t->summary_axis].vas[i];
1982           if (!va->n_summaries)
1983             {
1984               va->summaries = xmalloc (sizeof *va->summaries);
1985               va->n_summaries = 1;
1986
1987               enum ctables_summary_function function
1988                 = va->summary_var ? CTSF_MEAN : CTSF_COUNT;
1989               struct ctables_var var = { .is_mrset = false, .var = va->summary_var };
1990
1991               *va->summaries = (struct ctables_summary_spec) {
1992                 .function = function,
1993                 .format = ctables_summary_default_format (function, &var),
1994                 .label = ctables_summary_default_label (function, 0),
1995               };
1996               if (!va->summary_var)
1997                 va->summary_var = va->vars[0];
1998             }
1999         }
2000     }
2001
2002   struct casereader *input = casereader_create_filter_weight (proc_open (ds),
2003                                                               dataset_dict (ds),
2004                                                               NULL, NULL);
2005   bool warn_on_invalid = true;
2006   for (struct ccase *c = casereader_read (input); c;
2007        case_unref (c), c = casereader_read (input))
2008     {
2009       double weight = dict_get_case_weight (dataset_dict (ds), c,
2010                                             &warn_on_invalid);
2011
2012       for (size_t i = 0; i < ct->n_tables; i++)
2013         {
2014           struct ctables_table *t = ct->tables[i];
2015
2016           for (size_t ir = 0; ir < t->vaas[PIVOT_AXIS_ROW].n; ir++)
2017             for (size_t ic = 0; ic < t->vaas[PIVOT_AXIS_COLUMN].n; ic++)
2018               for (size_t il = 0; il < t->vaas[PIVOT_AXIS_LAYER].n; il++)
2019                 ctables_freqtab_insert (t, c, ir, ic, il, weight);
2020         }
2021     }
2022   casereader_destroy (input);
2023
2024   for (size_t i = 0; i < ct->n_tables; i++)
2025     {
2026       struct ctables_table *t = ct->tables[i];
2027
2028       struct pivot_table *pt = pivot_table_create (N_("Custom Tables"));
2029       pivot_table_set_look (pt, ct->look);
2030       struct pivot_dimension *d[PIVOT_N_AXES];
2031       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2032         {
2033           static const char *names[] = {
2034             [PIVOT_AXIS_ROW] = N_("Rows"),
2035             [PIVOT_AXIS_COLUMN] = N_("Columns"),
2036             [PIVOT_AXIS_LAYER] = N_("Layers"),
2037           };
2038           d[a] = (t->axes[a] || a == t->summary_axis
2039                   ? pivot_dimension_create (pt, a, names[a])
2040                   : NULL);
2041           if (!d[a])
2042             continue;
2043
2044           assert (t->axes[a]);
2045
2046           struct ctables_freq **sorted = xnmalloc (t->ft.count, sizeof *sorted);
2047
2048           struct ctables_freq *f;
2049           size_t n = 0;
2050           HMAP_FOR_EACH (f, struct ctables_freq, node, &t->ft)
2051             sorted[n++] = f;
2052           assert (n == t->ft.count);
2053
2054           struct ctables_freq_sort_aux aux = { .t = t, .a = a };
2055           sort (sorted, n, sizeof *sorted, ctables_freq_compare_3way, &aux);
2056
2057           size_t max_depth = 0;
2058           for (size_t j = 0; j < t->vaas[a].n; j++)
2059             if (t->vaas[a].vas[j].n > max_depth)
2060               max_depth = t->vaas[a].vas[j].n;
2061
2062           struct pivot_category **groups = xnmalloc (max_depth, sizeof *groups);
2063           struct pivot_category *top = NULL;
2064           int prev_leaf = 0;
2065           for (size_t j = 0; j < n; j++)
2066             {
2067               struct ctables_freq *f = sorted[j];
2068               const struct var_array *va = &t->vaas[a].vas[f->axes[a].vaa_idx];
2069
2070               size_t n_common = 0;
2071               bool new_subtable = false;
2072               if (j > 0)
2073                 {
2074                   struct ctables_freq *prev = sorted[j - 1];
2075                   if (prev->axes[a].vaa_idx == f->axes[a].vaa_idx)
2076                     {
2077                       for (; n_common < va->n; n_common++)
2078                         if (!value_equal (&prev->axes[a].values[n_common],
2079                                           &f->axes[a].values[n_common],
2080                                           var_get_type (va->vars[n_common])))
2081                           break;
2082                     }
2083                   else
2084                     new_subtable = true;
2085                 }
2086               else
2087                 new_subtable = true;
2088
2089               if (new_subtable)
2090                 {
2091                   enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (va->vars[0])];
2092                   top = d[a]->root;
2093                   if (vlabel != CTVL_NONE)
2094                     top = pivot_category_create_group__ (
2095                       top, pivot_value_new_variable (va->vars[0]));
2096                 }
2097               if (n_common == va->n)
2098                 {
2099                   f->axes[a].leaf = prev_leaf;
2100                   continue;
2101                 }
2102
2103               for (size_t k = n_common; k < va->n; k++)
2104                 {
2105                   struct pivot_category *parent = k > 0 ? groups[k - 1] : top;
2106
2107                   struct pivot_value *label = pivot_value_new_var_value (
2108                     va->vars[k], &f->axes[a].values[k]);
2109
2110                   if (k == va->n - 1)
2111                     {
2112                       if (a == t->summary_axis)
2113                         {
2114                           parent = pivot_category_create_group__ (parent, label);
2115                           for (size_t m = 0; m < va->n_summaries; m++)
2116                             {
2117                               int leaf = pivot_category_create_leaf (
2118                                 parent, pivot_value_new_text (va->summaries[m].label));
2119                               if (m == 0)
2120                                 prev_leaf = leaf;
2121                             }
2122                         }
2123                       else
2124                         prev_leaf = pivot_category_create_leaf (parent, label);
2125                       break;
2126                     }
2127
2128                   parent = pivot_category_create_group__ (parent, label);
2129
2130                   enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (va->vars[k + 1])];
2131                   if (vlabel != CTVL_NONE)
2132                     parent = pivot_category_create_group__ (
2133                       parent, pivot_value_new_variable (va->vars[k + 1]));
2134                   groups[k] = parent;
2135                 }
2136
2137               f->axes[a].leaf = prev_leaf;
2138             }
2139           free (sorted);
2140           free (groups);
2141         }
2142       struct ctables_freq *f;
2143       HMAP_FOR_EACH (f, struct ctables_freq, node, &t->ft)
2144         {
2145           size_t dindexes[3];
2146           size_t n_dindexes = 0;
2147
2148           for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2149             if (d[a])
2150               dindexes[n_dindexes++] = f->axes[a].leaf;
2151           pivot_table_put (pt, dindexes, n_dindexes,
2152                            pivot_value_new_number (f->count));
2153         }
2154
2155       pivot_table_submit (pt);
2156     }
2157
2158 #if 0
2159   for (size_t i = 0; i < ct->n_tables; i++)
2160     {
2161       struct ctables_table *t = ct->tables[i];
2162
2163       for (size_t j = 0; j < t->n_fts; j++)
2164         {
2165           struct ctables_freqtab *ft = t->fts[j];
2166           struct ctables_freq *f, *next;
2167           HMAP_FOR_EACH_SAFE (f, next, struct ctables_freq, node, &ft->data)
2168             {
2169               hmap_delete (&ft->data, &f->node);
2170               for (size_t k = 0; k < ft->n_summaries; k++)
2171                 ctables_summary_uninit (&f->summaries[k], &ft->summaries[k]);
2172               free (f->summaries);
2173               for (size_t k = 0; k < ft->vars.n; k++)
2174                 {
2175                   const struct variable *var = ft->vars.vars[k];
2176                   value_destroy (&f->values[k], var_get_width (var));
2177                 }
2178               free (f);
2179             }
2180           hmap_destroy (&ft->data);
2181           var_array_uninit (&ft->vars);
2182           free (ft);
2183         }
2184       free (t->fts);
2185     }
2186 #endif
2187   
2188   return proc_commit (ds);
2189 }
2190
2191 int
2192 cmd_ctables (struct lexer *lexer, struct dataset *ds)
2193 {
2194   size_t n_vars = dict_get_n_vars (dataset_dict (ds));
2195   enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
2196   enum settings_value_show tvars = settings_get_show_variables ();
2197   for (size_t i = 0; i < n_vars; i++)
2198     vlabels[i] = (enum ctables_vlabel) tvars;
2199
2200   struct ctables *ct = xmalloc (sizeof *ct);
2201   *ct = (struct ctables) {
2202     .look = pivot_table_look_unshare (pivot_table_look_ref (
2203                                         pivot_table_look_get_default ())),
2204     .vlabels = vlabels,
2205     .hide_threshold = 5,
2206   };
2207   ct->look->omit_empty = false;
2208
2209   if (!lex_force_match (lexer, T_SLASH))
2210     goto error;
2211
2212   while (!lex_match_id (lexer, "TABLE"))
2213     {
2214       if (lex_match_id (lexer, "FORMAT"))
2215         {
2216           double widths[2] = { SYSMIS, SYSMIS };
2217           double units_per_inch = 72.0;
2218
2219           while (lex_token (lexer) != T_SLASH)
2220             {
2221               if (lex_match_id (lexer, "MINCOLWIDTH"))
2222                 {
2223                   if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
2224                     goto error;
2225                 }
2226               else if (lex_match_id (lexer, "MAXCOLWIDTH"))
2227                 {
2228                   if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
2229                     goto error;
2230                 }
2231               else if (lex_match_id (lexer, "UNITS"))
2232                 {
2233                   lex_match (lexer, T_EQUALS);
2234                   if (lex_match_id (lexer, "POINTS"))
2235                     units_per_inch = 72.0;
2236                   else if (lex_match_id (lexer, "INCHES"))
2237                     units_per_inch = 1.0;
2238                   else if (lex_match_id (lexer, "CM"))
2239                     units_per_inch = 2.54;
2240                   else
2241                     {
2242                       lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
2243                       goto error;
2244                     }
2245                 }
2246               else if (lex_match_id (lexer, "EMPTY"))
2247                 {
2248                   free (ct->zero);
2249                   ct->zero = NULL;
2250
2251                   lex_match (lexer, T_EQUALS);
2252                   if (lex_match_id (lexer, "ZERO"))
2253                     {
2254                       /* Nothing to do. */
2255                     }
2256                   else if (lex_match_id (lexer, "BLANK"))
2257                     ct->zero = xstrdup ("");
2258                   else if (lex_force_string (lexer))
2259                     {
2260                       ct->zero = ss_xstrdup (lex_tokss (lexer));
2261                       lex_get (lexer);
2262                     }
2263                   else
2264                     goto error;
2265                 }
2266               else if (lex_match_id (lexer, "MISSING"))
2267                 {
2268                   lex_match (lexer, T_EQUALS);
2269                   if (!lex_force_string (lexer))
2270                     goto error;
2271
2272                   free (ct->missing);
2273                   ct->missing = (strcmp (lex_tokcstr (lexer), ".")
2274                                  ? ss_xstrdup (lex_tokss (lexer))
2275                                  : NULL);
2276                   lex_get (lexer);
2277                 }
2278               else
2279                 {
2280                   lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
2281                                        "UNITS", "EMPTY", "MISSING");
2282                   goto error;
2283                 }
2284             }
2285
2286           if (widths[0] != SYSMIS && widths[1] != SYSMIS
2287               && widths[0] > widths[1])
2288             {
2289               msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
2290               goto error;
2291             }
2292
2293           for (size_t i = 0; i < 2; i++)
2294             if (widths[i] != SYSMIS)
2295               {
2296                 int *wr = ct->look->width_ranges[TABLE_HORZ];
2297                 wr[i] = widths[i] / units_per_inch * 96.0;
2298                 if (wr[0] > wr[1])
2299                   wr[!i] = wr[i];
2300               }
2301         }
2302       else if (lex_match_id (lexer, "VLABELS"))
2303         {
2304           if (!lex_force_match_id (lexer, "VARIABLES"))
2305             goto error;
2306           lex_match (lexer, T_EQUALS);
2307
2308           struct variable **vars;
2309           size_t n_vars;
2310           if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
2311                                 PV_NO_SCRATCH))
2312             goto error;
2313
2314           if (!lex_force_match_id (lexer, "DISPLAY"))
2315             {
2316               free (vars);
2317               goto error;
2318             }
2319           lex_match (lexer, T_EQUALS);
2320
2321           enum ctables_vlabel vlabel;
2322           if (lex_match_id (lexer, "DEFAULT"))
2323             vlabel = (enum ctables_vlabel) settings_get_show_variables ();
2324           else if (lex_match_id (lexer, "NAME"))
2325             vlabel = CTVL_NAME;
2326           else if (lex_match_id (lexer, "LABEL"))
2327             vlabel = CTVL_LABEL;
2328           else if (lex_match_id (lexer, "BOTH"))
2329             vlabel = CTVL_BOTH;
2330           else if (lex_match_id (lexer, "NONE"))
2331             vlabel = CTVL_NONE;
2332           else
2333             {
2334               lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
2335                                    "BOTH", "NONE");
2336               free (vars);
2337               goto error;
2338             }
2339
2340           for (size_t i = 0; i < n_vars; i++)
2341             ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
2342           free (vars);
2343         }
2344       else if (lex_match_id (lexer, "MRSETS"))
2345         {
2346           if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
2347             goto error;
2348           lex_match (lexer, T_EQUALS);
2349           if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
2350             goto error;
2351         }
2352       else if (lex_match_id (lexer, "SMISSING"))
2353         {
2354           if (lex_match_id (lexer, "VARIABLE"))
2355             ct->smissing_listwise = false;
2356           else if (lex_match_id (lexer, "LISTWISE"))
2357             ct->smissing_listwise = true;
2358           else
2359             {
2360               lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
2361               goto error;
2362             }
2363         }
2364       /* XXX PCOMPUTE */
2365       else if (lex_match_id (lexer, "WEIGHT"))
2366         {
2367           if (!lex_force_match_id (lexer, "VARIABLE"))
2368             goto error;
2369           lex_match (lexer, T_EQUALS);
2370           ct->base_weight = parse_variable (lexer, dataset_dict (ds));
2371           if (!ct->base_weight)
2372             goto error;
2373         }
2374       else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
2375         {
2376           if (!lex_force_match_id (lexer, "COUNT"))
2377             goto error;
2378           lex_match (lexer, T_EQUALS);
2379           if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
2380             goto error;
2381           ct->hide_threshold = lex_integer (lexer);
2382           lex_get (lexer);
2383         }
2384       else
2385         {
2386           lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
2387                                "SMISSING", "PCOMPUTE", "PPROPERTIES",
2388                                "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
2389           goto error;
2390         }
2391
2392       if (!lex_force_match (lexer, T_SLASH))
2393         goto error;
2394     }
2395
2396   size_t allocated_tables = 0;
2397   do
2398     {
2399       if (ct->n_tables >= allocated_tables)
2400         ct->tables = x2nrealloc (ct->tables, &allocated_tables,
2401                                  sizeof *ct->tables);
2402
2403       struct ctables_table *t = xmalloc (sizeof *t);
2404       *t = (struct ctables_table) {
2405         .ft = HMAP_INITIALIZER (t->ft),
2406         .slabels_position = PIVOT_AXIS_COLUMN,
2407         .slabels_visible = true,
2408         .row_labels = CTLP_NORMAL,
2409         .col_labels = CTLP_NORMAL,
2410         .categories = xcalloc (dict_get_n_vars (dataset_dict (ds)),
2411                                sizeof *t->categories),
2412         .n_categories = dict_get_n_vars (dataset_dict (ds)),
2413         .cilevel = 95,
2414       };
2415       ct->tables[ct->n_tables++] = t;
2416
2417       lex_match (lexer, T_EQUALS);
2418       if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
2419         goto error;
2420       if (lex_match (lexer, T_BY))
2421         {
2422           if (!ctables_axis_parse (lexer, dataset_dict (ds),
2423                                    ct, t, PIVOT_AXIS_COLUMN))
2424             goto error;
2425
2426           if (lex_match (lexer, T_BY))
2427             {
2428               if (!ctables_axis_parse (lexer, dataset_dict (ds),
2429                                        ct, t, PIVOT_AXIS_LAYER))
2430                 goto error;
2431             }
2432         }
2433
2434       if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
2435           && !t->axes[PIVOT_AXIS_LAYER])
2436         {
2437           lex_error (lexer, _("At least one variable must be specified."));
2438           goto error;
2439         }
2440
2441       const struct ctables_axis *scales[PIVOT_N_AXES];
2442       size_t n_scales = 0;
2443       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2444         {
2445           scales[a] = find_scale (t->axes[a]);
2446           if (scales[a])
2447             n_scales++;
2448         }
2449       if (n_scales > 1)
2450         {
2451           msg (SE, _("Scale variables may appear only on one axis."));
2452           if (scales[PIVOT_AXIS_ROW])
2453             msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
2454                     _("This scale variable appears on the rows axis."));
2455           if (scales[PIVOT_AXIS_COLUMN])
2456             msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
2457                     _("This scale variable appears on the columns axis."));
2458           if (scales[PIVOT_AXIS_LAYER])
2459             msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
2460                     _("This scale variable appears on the layer axis."));
2461           goto error;
2462         }
2463
2464       const struct ctables_axis *summaries[PIVOT_N_AXES];
2465       size_t n_summaries = 0;
2466       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2467         {
2468           summaries[a] = (scales[a]
2469                           ? scales[a]
2470                           : find_categorical_summary_spec (t->axes[a]));
2471           if (summaries[a])
2472             n_summaries++;
2473         }
2474       if (n_summaries > 1)
2475         {
2476           msg (SE, _("Summaries may appear only on one axis."));
2477           if (summaries[PIVOT_AXIS_ROW])
2478             msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
2479                     _("This variable on the rows axis has a summary."));
2480           if (summaries[PIVOT_AXIS_COLUMN])
2481             msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
2482                     _("This variable on the columns axis has a summary."));
2483           if (summaries[PIVOT_AXIS_LAYER])
2484             msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
2485                     _("This variable on the layers axis has a summary."));
2486           goto error;
2487         }
2488       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2489         if (n_summaries ? summaries[a] : t->axes[a])
2490           {
2491             t->summary_axis = a;
2492             break;
2493           }
2494
2495       if (lex_token (lexer) == T_ENDCMD)
2496         break;
2497       if (!lex_force_match (lexer, T_SLASH))
2498         break;
2499
2500       while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
2501         {
2502           if (lex_match_id (lexer, "SLABELS"))
2503             {
2504               while (lex_token (lexer) != T_SLASH)
2505                 {
2506                   if (lex_match_id (lexer, "POSITION"))
2507                     {
2508                       lex_match (lexer, T_EQUALS);
2509                       if (lex_match_id (lexer, "COLUMN"))
2510                         t->slabels_position = PIVOT_AXIS_COLUMN;
2511                       else if (lex_match_id (lexer, "ROW"))
2512                         t->slabels_position = PIVOT_AXIS_ROW;
2513                       else if (lex_match_id (lexer, "LAYER"))
2514                         t->slabels_position = PIVOT_AXIS_LAYER;
2515                       else
2516                         {
2517                           lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
2518                           goto error;
2519                         }
2520                     }
2521                   else if (lex_match_id (lexer, "VISIBLE"))
2522                     {
2523                       lex_match (lexer, T_EQUALS);
2524                       if (!parse_bool (lexer, &t->slabels_visible))
2525                         goto error;
2526                     }
2527                   else
2528                     {
2529                       lex_error_expecting (lexer, "POSITION", "VISIBLE");
2530                       goto error;
2531                     }
2532                 }
2533             }
2534           else if (lex_match_id (lexer, "CLABELS"))
2535             {
2536               while (lex_token (lexer) != T_SLASH)
2537                 {
2538                   if (lex_match_id (lexer, "AUTO"))
2539                     t->row_labels = t->col_labels = CTLP_NORMAL;
2540                   else if (lex_match_id (lexer, "ROWLABELS"))
2541                     {
2542                       lex_match (lexer, T_EQUALS);
2543                       if (lex_match_id (lexer, "OPPOSITE"))
2544                         t->row_labels = CTLP_OPPOSITE;
2545                       else if (lex_match_id (lexer, "LAYER"))
2546                         t->row_labels = CTLP_LAYER;
2547                       else
2548                         {
2549                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
2550                           goto error;
2551                         }
2552                     }
2553                   else if (lex_match_id (lexer, "COLLABELS"))
2554                     {
2555                       lex_match (lexer, T_EQUALS);
2556                       if (lex_match_id (lexer, "OPPOSITE"))
2557                         t->col_labels = CTLP_OPPOSITE;
2558                       else if (lex_match_id (lexer, "LAYER"))
2559                         t->col_labels = CTLP_LAYER;
2560                       else
2561                         {
2562                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
2563                           goto error;
2564                         }
2565                     }
2566                   else
2567                     {
2568                       lex_error_expecting (lexer, "AUTO", "ROWLABELS",
2569                                            "COLLABELS");
2570                       goto error;
2571                     }
2572                 }
2573             }
2574           else if (lex_match_id (lexer, "CRITERIA"))
2575             {
2576               if (!lex_force_match_id (lexer, "CILEVEL"))
2577                 goto error;
2578               lex_match (lexer, T_EQUALS);
2579
2580               if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
2581                 goto error;
2582               t->cilevel = lex_number (lexer);
2583               lex_get (lexer);
2584             }
2585           else if (lex_match_id (lexer, "CATEGORIES"))
2586             {
2587               if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
2588                 goto error;
2589             }
2590           else if (lex_match_id (lexer, "TITLES"))
2591             {
2592               do
2593                 {
2594                   char **textp;
2595                   if (lex_match_id (lexer, "CAPTION"))
2596                     textp = &t->caption;
2597                   else if (lex_match_id (lexer, "CORNER"))
2598                     textp = &t->corner;
2599                   else if (lex_match_id (lexer, "TITLE"))
2600                     textp = &t->title;
2601                   else
2602                     {
2603                       lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
2604                       goto error;
2605                     }
2606                   lex_match (lexer, T_EQUALS);
2607
2608                   struct string s = DS_EMPTY_INITIALIZER;
2609                   while (lex_is_string (lexer))
2610                     {
2611                       if (!ds_is_empty (&s))
2612                         ds_put_byte (&s, ' ');
2613                       ds_put_substring (&s, lex_tokss (lexer));
2614                       lex_get (lexer);
2615                     }
2616                   free (*textp);
2617                   *textp = ds_steal_cstr (&s);
2618                 }
2619               while (lex_token (lexer) != T_SLASH
2620                      && lex_token (lexer) != T_ENDCMD);
2621             }
2622           else if (lex_match_id (lexer, "SIGTEST"))
2623             {
2624               if (!t->chisq)
2625                 {
2626                   t->chisq = xmalloc (sizeof *t->chisq);
2627                   *t->chisq = (struct ctables_chisq) {
2628                     .alpha = .05,
2629                     .include_mrsets = true,
2630                     .all_visible = true,
2631                   };
2632                 }
2633
2634               do
2635                 {
2636                   if (lex_match_id (lexer, "TYPE"))
2637                     {
2638                       lex_match (lexer, T_EQUALS);
2639                       if (!lex_force_match_id (lexer, "CHISQUARE"))
2640                         goto error;
2641                     }
2642                   else if (lex_match_id (lexer, "ALPHA"))
2643                     {
2644                       lex_match (lexer, T_EQUALS);
2645                       if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
2646                         goto error;
2647                       t->chisq->alpha = lex_number (lexer);
2648                       lex_get (lexer);
2649                     }
2650                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
2651                     {
2652                       lex_match (lexer, T_EQUALS);
2653                       if (parse_bool (lexer, &t->chisq->include_mrsets))
2654                         goto error;
2655                     }
2656                   else if (lex_match_id (lexer, "CATEGORIES"))
2657                     {
2658                       lex_match (lexer, T_EQUALS);
2659                       if (lex_match_id (lexer, "ALLVISIBLE"))
2660                         t->chisq->all_visible = true;
2661                       else if (lex_match_id (lexer, "SUBTOTALS"))
2662                         t->chisq->all_visible = false;
2663                       else
2664                         {
2665                           lex_error_expecting (lexer,
2666                                                "ALLVISIBLE", "SUBTOTALS");
2667                           goto error;
2668                         }
2669                     }
2670                   else
2671                     {
2672                       lex_error_expecting (lexer, "TYPE", "ALPHA",
2673                                            "INCLUDEMRSETS", "CATEGORIES");
2674                       goto error;
2675                     }
2676                 }
2677               while (lex_token (lexer) != T_SLASH
2678                      && lex_token (lexer) != T_ENDCMD);
2679             }
2680           else if (lex_match_id (lexer, "COMPARETEST"))
2681             {
2682               if (!t->pairwise)
2683                 {
2684                   t->pairwise = xmalloc (sizeof *t->pairwise);
2685                   *t->pairwise = (struct ctables_pairwise) {
2686                     .type = PROP,
2687                     .alpha = { .05, .05 },
2688                     .adjust = BONFERRONI,
2689                     .include_mrsets = true,
2690                     .meansvariance_allcats = true,
2691                     .all_visible = true,
2692                     .merge = false,
2693                     .apa_style = true,
2694                     .show_sig = false,
2695                   };
2696                 }
2697
2698               do
2699                 {
2700                   if (lex_match_id (lexer, "TYPE"))
2701                     {
2702                       lex_match (lexer, T_EQUALS);
2703                       if (lex_match_id (lexer, "PROP"))
2704                         t->pairwise->type = PROP;
2705                       else if (lex_match_id (lexer, "MEAN"))
2706                         t->pairwise->type = MEAN;
2707                       else
2708                         {
2709                           lex_error_expecting (lexer, "PROP", "MEAN");
2710                           goto error;
2711                         }
2712                     }
2713                   else if (lex_match_id (lexer, "ALPHA"))
2714                     {
2715                       lex_match (lexer, T_EQUALS);
2716
2717                       if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
2718                         goto error;
2719                       double a0 = lex_number (lexer);
2720                       lex_get (lexer);
2721
2722                       lex_match (lexer, T_COMMA);
2723                       if (lex_is_number (lexer))
2724                         {
2725                           if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
2726                             goto error;
2727                           double a1 = lex_number (lexer);
2728                           lex_get (lexer);
2729
2730                           t->pairwise->alpha[0] = MIN (a0, a1);
2731                           t->pairwise->alpha[1] = MAX (a0, a1);
2732                         }
2733                       else
2734                         t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
2735                     }
2736                   else if (lex_match_id (lexer, "ADJUST"))
2737                     {
2738                       lex_match (lexer, T_EQUALS);
2739                       if (lex_match_id (lexer, "BONFERRONI"))
2740                         t->pairwise->adjust = BONFERRONI;
2741                       else if (lex_match_id (lexer, "BH"))
2742                         t->pairwise->adjust = BH;
2743                       else if (lex_match_id (lexer, "NONE"))
2744                         t->pairwise->adjust = 0;
2745                       else
2746                         {
2747                           lex_error_expecting (lexer, "BONFERRONI", "BH",
2748                                                "NONE");
2749                           goto error;
2750                         }
2751                     }
2752                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
2753                     {
2754                       lex_match (lexer, T_EQUALS);
2755                       if (!parse_bool (lexer, &t->pairwise->include_mrsets))
2756                         goto error;
2757                     }
2758                   else if (lex_match_id (lexer, "MEANSVARIANCE"))
2759                     {
2760                       lex_match (lexer, T_EQUALS);
2761                       if (lex_match_id (lexer, "ALLCATS"))
2762                         t->pairwise->meansvariance_allcats = true;
2763                       else if (lex_match_id (lexer, "TESTEDCATS"))
2764                         t->pairwise->meansvariance_allcats = false;
2765                       else
2766                         {
2767                           lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
2768                           goto error;
2769                         }
2770                     }
2771                   else if (lex_match_id (lexer, "CATEGORIES"))
2772                     {
2773                       lex_match (lexer, T_EQUALS);
2774                       if (lex_match_id (lexer, "ALLVISIBLE"))
2775                         t->pairwise->all_visible = true;
2776                       else if (lex_match_id (lexer, "SUBTOTALS"))
2777                         t->pairwise->all_visible = false;
2778                       else
2779                         {
2780                           lex_error_expecting (lexer, "ALLVISIBLE",
2781                                                "SUBTOTALS");
2782                           goto error;
2783                         }
2784                     }
2785                   else if (lex_match_id (lexer, "MERGE"))
2786                     {
2787                       lex_match (lexer, T_EQUALS);
2788                       if (!parse_bool (lexer, &t->pairwise->merge))
2789                         goto error;
2790                     }
2791                   else if (lex_match_id (lexer, "STYLE"))
2792                     {
2793                       lex_match (lexer, T_EQUALS);
2794                       if (lex_match_id (lexer, "APA"))
2795                         t->pairwise->apa_style = true;
2796                       else if (lex_match_id (lexer, "SIMPLE"))
2797                         t->pairwise->apa_style = false;
2798                       else
2799                         {
2800                           lex_error_expecting (lexer, "APA", "SIMPLE");
2801                           goto error;
2802                         }
2803                     }
2804                   else if (lex_match_id (lexer, "SHOWSIG"))
2805                     {
2806                       lex_match (lexer, T_EQUALS);
2807                       if (!parse_bool (lexer, &t->pairwise->show_sig))
2808                         goto error;
2809                     }
2810                   else
2811                     {
2812                       lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
2813                                            "INCLUDEMRSETS", "MEANSVARIANCE",
2814                                            "CATEGORIES", "MERGE", "STYLE",
2815                                            "SHOWSIG");
2816                       goto error;
2817                     }
2818                 }
2819               while (lex_token (lexer) != T_SLASH
2820                      && lex_token (lexer) != T_ENDCMD);
2821             }
2822           else
2823             {
2824               lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
2825                                    "CRITERIA", "CATEGORIES", "TITLES",
2826                                    "SIGTEST", "COMPARETEST");
2827               goto error;
2828             }
2829         }
2830
2831       if (t->row_labels != CTLP_NORMAL && t->col_labels != CTLP_NORMAL)
2832         {
2833           msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
2834           goto error;
2835         }
2836
2837     }
2838   while (lex_token (lexer) != T_ENDCMD);
2839
2840   bool ok = ctables_execute (ds, ct);
2841   ctables_destroy (ct);
2842   return ok ? CMD_SUCCESS : CMD_FAILURE;
2843
2844 error:
2845   ctables_destroy (ct);
2846   return CMD_FAILURE;
2847 }
2848