563abdf7f1d99951db13b7522e1d65d9cb0f7b50
[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 "data/casereader.h"
20 #include "data/dataset.h"
21 #include "data/dictionary.h"
22 #include "data/mrset.h"
23 #include "language/command.h"
24 #include "language/lexer/format-parser.h"
25 #include "language/lexer/lexer.h"
26 #include "language/lexer/variable-parser.h"
27 #include "language/stats/freq.h"
28 #include "libpspp/assertion.h"
29 #include "libpspp/hmap.h"
30 #include "libpspp/message.h"
31 #include "libpspp/string-array.h"
32 #include "output/pivot-table.h"
33
34 #include "gl/minmax.h"
35 #include "gl/xalloc.h"
36
37 #include "gettext.h"
38 #define _(msgid) gettext (msgid)
39 #define N_(msgid) (msgid)
40
41 enum ctables_vlabel
42   {
43     CTVL_DEFAULT = SETTINGS_VALUE_SHOW_DEFAULT,
44     CTVL_NAME = SETTINGS_VALUE_SHOW_VALUE,
45     CTVL_LABEL = SETTINGS_VALUE_SHOW_LABEL,
46     CTVL_BOTH = SETTINGS_VALUE_SHOW_BOTH,
47     CTVL_NONE,
48   };
49 static void UNUSED
50 ctables_vlabel_unique (enum ctables_vlabel vlabel)
51 {
52   /* This ensures that all of the values are unique. */
53   switch (vlabel)
54     {
55     case CTVL_DEFAULT:
56     case CTVL_NAME:
57     case CTVL_LABEL:
58     case CTVL_BOTH:
59     case CTVL_NONE:
60       abort ();
61     }
62 }
63
64 /* XXX:
65    - unweighted summaries (U*)
66    - lower confidence limits (*.LCL)
67    - upper confidence limits (*.UCL)
68    - standard error (*.SE)
69  */
70 #define SUMMARIES                                                       \
71     /* All variables. */                                                \
72     S(CTSF_COUNT, "COUNT", N_("Count"), CTF_COUNT, CTFA_ALL)            \
73     S(CTSF_ECOUNT, "ECOUNT", N_("Adjusted Count"), CTF_COUNT, CTFA_ALL) \
74     S(CTSF_ROWPCT_COUNT, "ROWPCT.COUNT", N_("Row %"), CTF_PERCENT, CTFA_ALL) \
75     S(CTSF_COLPCT_COUNT, "COLPCT.COUNT", N_("Column %"), CTF_PERCENT, CTFA_ALL) \
76     S(CTSF_TABLEPCT_COUNT, "TABLEPCT.COUNT", N_("Table %"), CTF_PERCENT, CTFA_ALL) \
77     S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT.COUNT", N_("Subtable %"), CTF_PERCENT, CTFA_ALL) \
78     S(CTSF_LAYERPCT_COUNT, "LAYERPCT.COUNT", N_("Layer %"), CTF_PERCENT, CTFA_ALL) \
79     S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT.COUNT", N_("Layer Row %"), CTF_PERCENT, CTFA_ALL) \
80     S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT.COUNT", N_("Layer Column %"), CTF_PERCENT, CTFA_ALL) \
81     S(CTSF_ROWPCT_VALIDN, "ROWPCT.VALIDN", N_("Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
82     S(CTSF_COLPCT_VALIDN, "COLPCT.VALIDN", N_("Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
83     S(CTSF_TABLEPCT_VALIDN, "TABLEPCT.VALIDN", N_("Table Valid N %"), CTF_PERCENT, CTFA_ALL) \
84     S(CTSF_SUBTABLEPCT_VALIDN, "SUBTABLEPCT.VALIDN", N_("Subtable Valid N %"), CTF_PERCENT, CTFA_ALL) \
85     S(CTSF_LAYERPCT_VALIDN, "LAYERPCT.VALIDN", N_("Layer Valid N %"), CTF_PERCENT, CTFA_ALL) \
86     S(CTSF_LAYERROWPCT_VALIDN, "LAYERROWPCT.VALIDN", N_("Layer Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
87     S(CTSF_LAYERCOLPCT_VALIDN, "LAYERCOLPCT.VALIDN", N_("Layer Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
88     S(CTSF_ROWPCT_TOTALN, "ROWPCT.TOTALN", N_("Row Total N %"), CTF_PERCENT, CTFA_ALL) \
89     S(CTSF_COLPCT_TOTALN, "COLPCT.TOTALN", N_("Column Total N %"), CTF_PERCENT, CTFA_ALL) \
90     S(CTSF_TABLEPCT_TOTALN, "TABLEPCT.TOTALN", N_("Table Total N %"), CTF_PERCENT, CTFA_ALL) \
91     S(CTSF_SUBTABLEPCT_TOTALN, "SUBTABLEPCT.TOTALN", N_("Subtable Total N %"), CTF_PERCENT, CTFA_ALL) \
92     S(CTSF_LAYERPCT_TOTALN, "LAYERPCT.TOTALN", N_("Layer Total N %"), CTF_PERCENT, CTFA_ALL) \
93     S(CTSF_LAYERROWPCT_TOTALN, "LAYERROWPCT.TOTALN", N_("Layer Row Total N %"), CTF_PERCENT, CTFA_ALL) \
94     S(CTSF_LAYERCOLPCT_TOTALN, "LAYERCOLPCT.TOTALN", N_("Layer Column Total N %"), CTF_PERCENT, CTFA_ALL) \
95                                                                         \
96     /* Scale variables, totals, and subtotals. */                       \
97     S(CTSF_MAXIMUM, "MAXIMUM", N_("Maximum"), CTF_GENERAL, CTFA_SCALE)  \
98     S(CTSF_MEAN, "MEAN", N_("Mean"), CTF_GENERAL, CTFA_SCALE)           \
99     S(CTSF_MEDIAN, "MEDIAN", N_("Median"), CTF_GENERAL, CTFA_SCALE)     \
100     S(CTSF_MINIMUM, "MINIMUM", N_("Minimum"), CTF_GENERAL, CTFA_SCALE)  \
101     S(CTSF_MISSING, "MISSING", N_("Missing"), CTF_GENERAL, CTFA_SCALE)  \
102     S(CTSF_MODE, "MODE", N_("Mode"), CTF_GENERAL, CTFA_SCALE)           \
103     S(CTSF_PTILE, "PTILE", N_("Percentile"), CTF_GENERAL, CTFA_SCALE)   \
104     S(CTSF_RANGE, "RANGE", N_("Range"), CTF_GENERAL, CTFA_SCALE)        \
105     S(CTSF_SEMEAN, "SEMEAN", N_("Std Error of Mean"), CTF_GENERAL, CTFA_SCALE) \
106     S(CTSF_STDDEV, "STDDEV", N_("Std Deviation"), CTF_GENERAL, CTFA_SCALE) \
107     S(CTSF_SUM, "SUM", N_("Sum"), CTF_GENERAL, CTFA_SCALE)              \
108     S(CSTF_TOTALN, "TOTALN", N_("Total N"), CTF_COUNT, CTFA_SCALE)      \
109     S(CTSF_ETOTALN, "ETOTALN", N_("Adjusted Total N"), CTF_COUNT, CTFA_SCALE) \
110     S(CTSF_VALIDN, "VALIDN", N_("Valid N"), CTF_COUNT, CTFA_SCALE)      \
111     S(CTSF_EVALIDN, "EVALIDN", N_("Adjusted Valid N"), CTF_COUNT, CTFA_SCALE) \
112     S(CTSF_VARIANCE, "VARIANCE", N_("Variance"), CTF_GENERAL, CTFA_SCALE) \
113     S(CTSF_ROWPCT_SUM, "ROWPCT.SUM", N_("Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
114     S(CTSF_COLPCT_SUM, "COLPCT.SUM", N_("Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
115     S(CTSF_TABLEPCT_SUM, "TABLEPCT.SUM", N_("Table Sum %"), CTF_PERCENT, CTFA_SCALE) \
116     S(CTSF_SUBTABLEPCT_SUM, "SUBTABLEPCT.SUM", N_("Subtable Sum %"), CTF_PERCENT, CTFA_SCALE) \
117     S(CTSF_LAYERPCT_SUM, "LAYERPCT.SUM", N_("Layer Sum %"), CTF_PERCENT, CTFA_SCALE) \
118     S(CTSF_LAYERROWPCT_SUM, "LAYERROWPCT.SUM", N_("Layer Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
119     S(CTSF_LAYERCOLPCT_SUM, "LAYERCOLPCT.SUM", N_("Layer Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
120                                                                         \
121     /* Multiple response sets. */                                       \
122   S(CTSF_RESPONSES, "RESPONSES", N_("Responses"), CTF_COUNT, CTFA_MRSETS) \
123     S(CTSF_ROWPCT_RESPONSES, "ROWPCT.RESPONSES", N_("Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
124     S(CTSF_COLPCT_RESPONSES, "COLPCT.RESPONSES", N_("Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
125     S(CTSF_TABLEPCT_RESPONSES, "TABLEPCT.RESPONSES", N_("Table Responses %"), CTF_PERCENT, CTFA_MRSETS) \
126     S(CTSF_SUBTABLEPCT_RESPONSES, "SUBTABLEPCT.RESPONSES", N_("Subtable Responses %"), CTF_PERCENT, CTFA_MRSETS) \
127     S(CTSF_LAYERPCT_RESPONSES, "LAYERPCT.RESPONSES", N_("Layer Responses %"), CTF_PERCENT, CTFA_MRSETS) \
128     S(CTSF_LAYERROWPCT_RESPONSES, "LAYERROWPCT.RESPONSES", N_("Layer Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
129     S(CTSF_LAYERCOLPCT_RESPONSES, "LAYERCOLPCT.RESPONSES", N_("Layer Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
130     S(CTSF_ROWPCT_RESPONSES_COUNT, "ROWPCT.RESPONSES.COUNT", N_("Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
131     S(CTSF_COLPCT_RESPONSES_COUNT, "COLPCT.RESPONSES.COUNT", N_("Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
132     S(CTSF_TABLEPCT_RESPONSES_COUNT, "TABLEPCT.RESPONSES.COUNT", N_("Table Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
133     S(CTSF_SUBTABLEPCT_RESPONSES_COUNT, "SUBTABLEPCT.RESPONSES.COUNT", N_("Subtable Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
134     S(CTSF_LAYERPCT_RESPONSES_COUNT, "LAYERPCT.RESPONSES.COUNT", N_("Layer Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
135     S(CTSF_LAYERROWPCT_RESPONSES_COUNT, "LAYERROWPCT.RESPONSES.COUNT", N_("Layer Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
136     S(CTSF_LAYERCOLPCT_RESPONSES_COUNT, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
137     S(CTSF_ROWPCT_COUNT_RESPONSES, "ROWPCT.COUNT.RESPONSES", N_("Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
138     S(CTSF_COLPCT_COUNT_RESPONSES, "COLPCT.COUNT.RESPONSES", N_("Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
139     S(CTSF_TABLEPCT_COUNT_RESPONSES, "TABLEPCT.COUNT.RESPONSES", N_("Table Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
140     S(CTSF_SUBTABLEPCT_COUNT_RESPONSES, "SUBTABLEPCT.COUNT.RESPONSES", N_("Subtable Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
141     S(CTSF_LAYERPCT_COUNT_RESPONSES, "LAYERPCT.COUNT.RESPONSES", N_("Layer Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
142     S(CTSF_LAYERROWPCT_COUNT_RESPONSES, "LAYERROWPCT.COUNT.RESPONSES", N_("Layer Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
143     S(CTSF_LAYERCOLPCT_COUNT_RESPONSES, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS)
144
145 enum ctables_summary_function
146   {
147 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) ENUM,
148     SUMMARIES
149 #undef S
150   };
151
152 enum {
153 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) +1
154   N_CTSF_FUNCTIONS = SUMMARIES
155 #undef S
156 };
157
158 struct ctables
159   {
160     struct pivot_table_look *look;
161
162     /* If this is NULL, zeros are displayed using the normal print format.
163        Otherwise, this string is displayed. */
164     char *zero;
165
166     /* If this is NULL, missing values are displayed using the normal print
167        format.  Otherwise, this string is displayed. */
168     char *missing;
169
170     /* Indexed by variable dictionary index. */
171     enum ctables_vlabel *vlabels;
172
173     bool mrsets_count_duplicates; /* MRSETS. */
174     bool smissing_listwise;       /* SMISSING. */
175     struct variable *base_weight; /* WEIGHT. */
176     int hide_threshold;           /* HIDESMALLCOUNTS. */
177
178     struct ctables_table *tables;
179     size_t n_tables;
180   };
181
182 struct ctables_postcompute
183   {
184     struct hmap_node hmap_node; /* In struct ctables's 'pcompute' hmap. */
185     const char *name;           /* Name, without leading &. */
186
187     struct ctables_postcompute_expr *expr;
188     char *label;
189     /* XXX FORMAT */
190     bool hide_source_cats;
191   };
192
193 struct ctables_postcompute_expr
194   {
195     enum ctables_postcompute_op
196       {
197         /* Terminals. */
198         CTPO_CAT_NUMBER,
199         CTPO_CAT_STRING,
200         CTPO_CAT_RANGE,
201         CTPO_CAT_MISSING,
202         /* XXX OTHERNM */
203         /* XXX SUBTOTAL and HSUBTOTAL */
204
205         /* Nonterminals. */
206         CTPO_ADD,
207         CTPO_SUB,
208         CTPO_MUL,
209         CTPO_DIV,
210         CTPO_POW,
211       }
212     op;
213
214     union
215       {
216         /* CTPO_CAT_NUMBER, CTPO_NUMBER. */
217         double number;
218
219         /* CTPO_CAT_RANGE.
220
221            XXX what about string ranges? */
222         double range[2];
223
224         /* CTPO_ADD, CTPO_SUB, CTPO_MUL, CTPO_DIV, CTPO_POW. */
225         struct ctables_postcompute_expr *subs[2];
226       };
227   };
228
229 enum ctables_label_position
230   {
231     CTLP_NORMAL,
232     CTLP_OPPOSITE,
233     CTLP_LAYER,
234   };
235
236 struct ctables_table
237   {
238     struct ctables_axis *axes[PIVOT_N_AXES];
239
240     enum pivot_axis_type slabels_position;
241     bool slabels_visible;
242
243     enum ctables_label_position row_labels;
244     enum ctables_label_position col_labels;
245
246     /* Indexed by variable dictionary index. */
247     struct ctables_categories **categories;
248     size_t n_categories;
249
250     double cilevel;
251
252     char *caption;
253     char *corner;
254     char *title;
255
256     struct ctables_chisq *chisq;
257     struct ctables_pairwise *pairwise;
258   };
259
260 struct ctables_var
261   {
262     bool is_mrset;
263     union
264       {
265         struct variable *var;
266         const struct mrset *mrset;
267       };
268   };
269
270 static const struct fmt_spec *
271 ctables_var_get_print_format (const struct ctables_var *var)
272 {
273   return (var->is_mrset
274           ? var_get_print_format (var->mrset->vars[0])
275           : var_get_print_format (var->var));
276 }
277
278 static const char *
279 ctables_var_name (const struct ctables_var *var)
280 {
281   return var->is_mrset ? var->mrset->name : var_get_name (var->var);
282 }
283
284 struct ctables_categories
285   {
286     size_t n_refs;
287
288     /* Explicit categories. */
289     struct ctables_cat_value *values;
290     size_t n_values;
291
292     /* Implicit categories. */
293     bool sort_ascending;
294     bool include_missing;
295     enum { CTCS_VALUE, CTCS_LABEL, CTCS_FUNCTION } key;
296     enum ctables_summary_function sort_func;
297     struct variable *sort_func_var;
298     double percentile;
299
300     /* Totals. */
301     bool show_totals;
302     bool totals_before;
303     char *total_label;
304
305     /* Empty categories. */
306     bool show_empty;
307   };
308
309 struct ctables_cat_value
310   {
311     enum ctables_cat_value_type
312       {
313         CCVT_NUMBER,
314         CCVT_STRING,
315         CCVT_RANGE,
316         CCVT_MISSING,
317         CCVT_OTHERNM,
318         CCVT_SUBTOTAL,
319         CCVT_HSUBTOTAL,
320       }
321     type;
322
323     union
324       {
325         double number;          /* CCVT_NUMBER. */
326         char *string;           /* CCVT_STRING. */
327         double range[2];        /* CCVT_RANGE. */
328         char *subtotal_label;   /* CCVT_SUBTOTAL, CCVT_HSUBTOTAL. */
329       };
330   };
331
332 static void
333 ctables_cat_value_uninit (struct ctables_cat_value *cv)
334 {
335   if (!cv)
336     return;
337
338   switch (cv->type)
339     {
340     case CCVT_NUMBER:
341     case CCVT_RANGE:
342     case CCVT_MISSING:
343     case CCVT_OTHERNM:
344       break;
345
346     case CCVT_STRING:
347       free (cv->string);
348       break;
349
350     case CCVT_SUBTOTAL:
351     case CCVT_HSUBTOTAL:
352       free (cv->subtotal_label);
353     }
354 }
355
356 static void
357 ctables_categories_unref (struct ctables_categories *c)
358 {
359   if (!c)
360     return;
361
362   assert (c->n_refs > 0);
363   if (--c->n_refs)
364     return;
365
366   for (size_t i = 0; i < c->n_values; i++)
367     ctables_cat_value_uninit (&c->values[i]);
368   free (c->values);
369   free (c->total_label);
370   free (c);
371 }
372
373 /* Chi-square test (SIGTEST). */
374 struct ctables_chisq
375   {
376     double alpha;
377     bool include_mrsets;
378     bool all_visible;
379   };
380
381 /* Pairwise comparison test (COMPARETEST). */
382 struct ctables_pairwise
383   {
384     enum { PROP, MEAN } type;
385     double alpha[2];
386     bool include_mrsets;
387     bool meansvariance_allcats;
388     bool all_visible;
389     enum { BONFERRONI = 1, BH } adjust;
390     bool merge;
391     bool apa_style;
392     bool show_sig;
393   };
394
395 struct ctables_axis
396   {
397     enum ctables_axis_op
398       {
399         /* Terminals. */
400         CTAO_VAR,
401
402         /* Nonterminals. */
403         CTAO_STACK,             /* + */
404         CTAO_NEST,              /* > */
405       }
406     op;
407
408     union
409       {
410         /* Terminals. */
411         struct
412           {
413             struct ctables_var var;
414             bool scale;
415             struct ctables_summary *summaries;
416             size_t n_summaries;
417             size_t allocated_summaries;
418           };
419
420         /* Nonterminals. */
421         struct ctables_axis *subs[2];
422       };
423
424     struct msg_location *loc;
425   };
426
427 static void ctables_axis_destroy (struct ctables_axis *);
428
429 enum ctables_format
430   {
431     CTF_COUNT,
432     CTF_PERCENT,
433     CTF_GENERAL
434   };
435
436 enum ctables_function_availability
437   {
438     CTFA_ALL,                /* Any variables. */
439     CTFA_SCALE,              /* Only scale variables, totals, and subtotals. */
440     CTFA_MRSETS,             /* Only multiple-response sets */
441   };
442
443 struct ctables_summary
444   {
445     enum ctables_summary_function function;
446     double percentile;          /* CTSF_PTILE only. */
447     char *label;
448     struct fmt_spec format;     /* XXX extra CTABLES formats */
449   };
450
451 static void
452 ctables_summary_uninit (struct ctables_summary *s)
453 {
454   if (s)
455     free (s->label);
456 }
457
458 static bool
459 parse_col_width (struct lexer *lexer, const char *name, double *width)
460 {
461   lex_match (lexer, T_EQUALS);
462   if (lex_match_id (lexer, "DEFAULT"))
463     *width = SYSMIS;
464   else if (lex_force_num_range_closed (lexer, name, 0, DBL_MAX))
465     {
466       *width = lex_number (lexer);
467       lex_get (lexer);
468     }
469   else
470     return false;
471
472   return true;
473 }
474
475 static bool
476 parse_bool (struct lexer *lexer, bool *b)
477 {
478   if (lex_match_id (lexer, "NO"))
479     *b = false;
480   else if (lex_match_id (lexer, "YES"))
481     *b = true;
482   else
483     {
484       lex_error_expecting (lexer, "YES", "NO");
485       return false;
486     }
487   return true;
488 }
489
490 static enum ctables_function_availability
491 ctables_function_availability (enum ctables_summary_function f)
492 {
493   static enum ctables_function_availability availability[] = {
494 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = AVAILABILITY,
495     SUMMARIES
496 #undef S
497   };
498
499   return availability[f];
500 }
501
502 static bool
503 parse_ctables_summary_function (struct lexer *lexer,
504                                 enum ctables_summary_function *f)
505 {
506   struct pair
507     {
508       enum ctables_summary_function function;
509       struct substring name;
510     };
511   static struct pair names[] = {
512 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) \
513     { ENUM, SS_LITERAL_INITIALIZER (NAME) },
514     SUMMARIES
515
516     /* The .COUNT suffix may be omitted. */
517     S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _, _)
518     S(CTSF_COLPCT_COUNT, "COLPCT", _, _, _)
519     S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _, _)
520     S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _, _)
521     S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _, _)
522     S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _, _)
523     S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _, _)
524 #undef S
525   };
526
527   if (!lex_force_id (lexer))
528     return false;
529
530   for (size_t i = 0; i < sizeof names / sizeof *names; i++)
531     if (ss_equals_case (names[i].name, lex_tokss (lexer)))
532       {
533         *f = names[i].function;
534         lex_get (lexer);
535         return true;
536       }
537
538   lex_error (lexer, _("Expecting summary function name."));
539   return false;
540 }
541
542 static void
543 ctables_axis_destroy (struct ctables_axis *axis)
544 {
545   if (!axis)
546     return;
547
548   switch (axis->op)
549     {
550     case CTAO_VAR:
551       for (size_t i = 0; i < axis->n_summaries; i++)
552         ctables_summary_uninit (&axis->summaries[i]);
553       free (axis->summaries);
554       break;
555
556     case CTAO_STACK:
557     case CTAO_NEST:
558       ctables_axis_destroy (axis->subs[0]);
559       ctables_axis_destroy (axis->subs[1]);
560       break;
561     }
562   msg_location_destroy (axis->loc);
563   free (axis);
564 }
565
566 static struct ctables_axis *
567 ctables_axis_new_nonterminal (enum ctables_axis_op op,
568                               struct ctables_axis *sub0,
569                               struct ctables_axis *sub1,
570                               struct lexer *lexer, int start_ofs)
571 {
572   struct ctables_axis *axis = xmalloc (sizeof *axis);
573   *axis = (struct ctables_axis) {
574     .op = op,
575     .subs = { sub0, sub1 },
576     .loc = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
577   };
578   return axis;
579 }
580
581 struct ctables_axis_parse_ctx
582   {
583     struct lexer *lexer;
584     struct dictionary *dict;
585     struct ctables *ct;
586     struct ctables_table *t;
587   };
588
589 static struct fmt_spec
590 ctables_summary_default_format (enum ctables_summary_function function,
591                                 const struct ctables_var *var)
592 {
593   static const enum ctables_format default_formats[] = {
594 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
595     SUMMARIES
596 #undef S
597   };
598   switch (default_formats[function])
599     {
600     case CTF_COUNT:
601       return (struct fmt_spec) { .type = FMT_F, .w = 40 };
602
603     case CTF_PERCENT:
604       return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
605
606     case CTF_GENERAL:
607       return *ctables_var_get_print_format (var);
608
609     default:
610       NOT_REACHED ();
611     }
612 }
613
614 static const char *
615 ctables_summary_function_name (enum ctables_summary_function function)
616 {
617   static const char *names[] = {
618 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = NAME,
619     SUMMARIES
620 #undef S
621   };
622   return names[function];
623 }
624
625 static bool
626 add_summary (struct ctables_axis *axis,
627              enum ctables_summary_function function, double percentile,
628              const char *label, const struct fmt_spec *format,
629              const struct msg_location *loc)
630 {
631   if (axis->op == CTAO_VAR)
632     {
633       if (axis->n_summaries >= axis->allocated_summaries)
634         axis->summaries = x2nrealloc (axis->summaries,
635                                       &axis->allocated_summaries,
636                                       sizeof *axis->summaries);
637
638       const char *function_name = ctables_summary_function_name (function);
639       const char *var_name = ctables_var_name (&axis->var);
640       switch (ctables_function_availability (function))
641         {
642         case CTFA_MRSETS:
643           if (!axis->var.is_mrset)
644             {
645               msg_at (SE, loc, _("Summary function %s applies only to multiple "
646                                  "response sets."), function_name);
647               msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
648                       var_name);
649               return false;
650             }
651           break;
652
653         case CTFA_SCALE:
654           if (!axis->scale)
655             {
656               msg_at (SE, loc,
657                       _("Summary function %s applies only to scale variables."),
658                       function_name);
659               msg_at (SN, axis->loc, _("'%s' is not a scale variable."),
660                       var_name);
661               return false;
662             }
663           break;
664
665         case CTFA_ALL:
666           break;
667         }
668
669       struct ctables_summary *dst = &axis->summaries[axis->n_summaries++];
670       *dst = (struct ctables_summary) {
671         .function = function,
672         .percentile = percentile,
673         .label = xstrdup (label),
674         .format = (format ? *format
675                    : ctables_summary_default_format (function, &axis->var)),
676       };
677       return true;
678     }
679   else
680     {
681       for (size_t i = 0; i < 2; i++)
682         if (!add_summary (axis->subs[i], function, percentile, label, format,
683                           loc))
684           return false;
685       return true;
686     }
687 }
688
689 static struct ctables_axis *ctables_axis_parse_stack (
690   struct ctables_axis_parse_ctx *);
691
692 static bool
693 ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
694                    struct ctables_var *var)
695 {
696   if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
697     {
698       *var = (struct ctables_var) {
699         .is_mrset = true,
700         .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
701       };
702       if (!var->mrset)
703         {
704           lex_error (lexer, _("'%s' does not name a multiple-response set "
705                               "in the active file dictionary."),
706                      lex_tokcstr (lexer));
707           return false;
708         }
709       lex_get (lexer);
710       return true;
711     }
712   else
713     {
714       *var = (struct ctables_var) {
715         .is_mrset = false,
716         .var = parse_variable (lexer, dict),
717       };
718       return var->var != NULL;
719     }
720 }
721
722 static struct ctables_axis *
723 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
724 {
725   if (lex_match (ctx->lexer, T_LPAREN))
726     {
727       struct ctables_axis *sub = ctables_axis_parse_stack (ctx);
728       if (!sub || !lex_force_match (ctx->lexer, T_RPAREN))
729         {
730           ctables_axis_destroy (sub);
731           return NULL;
732         }
733       return sub;
734     }
735
736   if (!lex_force_id (ctx->lexer))
737     return NULL;
738
739   int start_ofs = lex_ofs (ctx->lexer);
740   struct ctables_var var;
741   if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
742     return NULL;
743
744   struct ctables_axis *axis = xmalloc (sizeof *axis);
745   *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
746
747   /* XXX should figure out default measures by reading data */
748   axis->scale = (var.is_mrset ? false
749                  : lex_match_phrase (ctx->lexer, "[S]") ? true
750                  : lex_match_phrase (ctx->lexer, "[C]") ? false
751                  : var_get_measure (var.var) == MEASURE_SCALE);
752   axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
753                                 lex_ofs (ctx->lexer) - 1);
754   return axis;
755 }
756
757 static struct ctables_axis *
758 ctables_axis_parse_postfix (struct ctables_axis_parse_ctx *ctx)
759 {
760   struct ctables_axis *sub = ctables_axis_parse_primary (ctx);
761   if (!sub || !lex_match (ctx->lexer, T_LBRACK))
762     return sub;
763
764   do
765     {
766       int start_ofs = lex_ofs (ctx->lexer);
767
768       /* Parse function. */
769       enum ctables_summary_function function;
770       if (!parse_ctables_summary_function (ctx->lexer, &function))
771         goto error;
772
773       /* Parse percentile. */
774       double percentile = 0;
775       if (function == CTSF_PTILE)
776         {
777           if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
778             goto error;
779           percentile = lex_number (ctx->lexer);
780           lex_get (ctx->lexer);
781         }
782
783       /* Parse label. */
784       char *label;
785       if (lex_is_string (ctx->lexer))
786         {
787           label = ss_xstrdup (lex_tokss (ctx->lexer));
788           lex_get (ctx->lexer);
789         }
790       else if (function == CTSF_PTILE)
791         label = xasprintf (_("Percentile %.2f"), percentile);
792       else
793         {
794           static const char *default_labels[] = {
795 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = LABEL,
796             SUMMARIES
797 #undef S
798           };
799           label = xstrdup (gettext (default_labels[function]));
800         }
801
802       /* Parse format. */
803       struct fmt_spec format;
804       const struct fmt_spec *formatp;
805       if (lex_token (ctx->lexer) == T_ID)
806         {
807           if (!parse_format_specifier (ctx->lexer, &format)
808               || !fmt_check_output (&format)
809               || !fmt_check_type_compat (&format, VAL_NUMERIC))
810             {
811               free (label);
812               goto error;
813             }
814           formatp = &format;
815         }
816       else
817         formatp = NULL;
818
819       struct msg_location *loc = lex_ofs_location (ctx->lexer, start_ofs,
820                                                    lex_ofs (ctx->lexer) - 1);
821       add_summary (sub, function, percentile, label, formatp, loc);
822       free (label);
823       msg_location_destroy (loc);
824
825       lex_match (ctx->lexer, T_COMMA);
826     }
827   while (!lex_match (ctx->lexer, T_RBRACK));
828
829   return sub;
830
831 error:
832   ctables_axis_destroy (sub);
833   return NULL;
834 }
835
836 static const struct ctables_axis *
837 find_scale (const struct ctables_axis *axis)
838 {
839   if (!axis)
840     return NULL;
841   else if (axis->op == CTAO_VAR)
842     {
843       if (axis->scale)
844         {
845           assert (!axis->var.is_mrset);
846           return axis;
847         }
848       else
849         return NULL;
850     }
851   else
852     {
853       for (size_t i = 0; i < 2; i++)
854         {
855           const struct ctables_axis *scale = find_scale (axis->subs[i]);
856           if (scale)
857             return scale;
858         }
859       return NULL;
860     }
861 }
862
863 static const struct ctables_axis *
864 find_categorical_summary (const struct ctables_axis *axis)
865 {
866   if (!axis)
867     return NULL;
868   else if (axis->op == CTAO_VAR)
869     return !axis->scale && axis->n_summaries ? axis : NULL;
870   else
871     {
872       for (size_t i = 0; i < 2; i++)
873         {
874           const struct ctables_axis *sum
875             = find_categorical_summary (axis->subs[i]);
876           if (sum)
877             return sum;
878         }
879       return NULL;
880     }
881 }
882
883 static struct ctables_axis *
884 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
885 {
886   int start_ofs = lex_ofs (ctx->lexer);
887   struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
888   if (!lhs)
889     return NULL;
890
891   while (lex_match (ctx->lexer, T_GT))
892     {
893       struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
894       if (!rhs)
895         return NULL;
896
897       struct ctables_axis *nest = ctables_axis_new_nonterminal (
898         CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
899
900       const struct ctables_axis *outer_scale = find_scale (lhs);
901       const struct ctables_axis *inner_scale = find_scale (rhs);
902       if (outer_scale && inner_scale)
903         {
904           msg_at (SE, nest->loc, _("Cannot nest scale variables."));
905           msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
906           msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
907           ctables_axis_destroy (nest);
908           return NULL;
909         }
910
911       const struct ctables_axis *outer_sum = find_categorical_summary (lhs);
912       if (outer_sum)
913         {
914           msg_at (SE, nest->loc,
915                   _("Summaries may only be requested for categorical variables "
916                     "at the innermost nesting level."));
917           msg_at (SN, outer_sum->loc,
918                   _("This outer categorical variable has a summary."));
919           ctables_axis_destroy (nest);
920           return NULL;
921         }
922
923       lhs = nest;
924     }
925
926   return lhs;
927 }
928
929 static struct ctables_axis *
930 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
931 {
932   int start_ofs = lex_ofs (ctx->lexer);
933   struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
934   if (!lhs)
935     return NULL;
936
937   while (lex_match (ctx->lexer, T_PLUS))
938     {
939       struct ctables_axis *rhs = ctables_axis_parse_nest (ctx);
940       if (!rhs)
941         return NULL;
942
943       lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
944                                           ctx->lexer, start_ofs);
945     }
946
947   return lhs;
948 }
949
950 static bool
951 ctables_axis_parse (struct lexer *lexer, struct dictionary *dict,
952                     struct ctables *ct, struct ctables_table *t,
953                     enum pivot_axis_type a)
954 {
955   if (lex_token (lexer) == T_BY
956       || lex_token (lexer) == T_SLASH
957       || lex_token (lexer) == T_ENDCMD)
958     return true;
959
960   struct ctables_axis_parse_ctx ctx = {
961     .lexer = lexer,
962     .dict = dict,
963     .ct = ct,
964     .t = t
965   };
966   t->axes[a] = ctables_axis_parse_stack (&ctx);
967   return t->axes[a] != NULL;
968 }
969
970 static void
971 ctables_chisq_destroy (struct ctables_chisq *chisq)
972 {
973   free (chisq);
974 }
975
976 static void
977 ctables_pairwise_destroy (struct ctables_pairwise *pairwise)
978 {
979   free (pairwise);
980 }
981
982 static void
983 ctables_table_uninit (struct ctables_table *t)
984 {
985   if (!t)
986     return;
987
988   for (size_t i = 0; i < t->n_categories; i++)
989     ctables_categories_unref (t->categories[i]);
990   free (t->categories);
991
992   ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
993   ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
994   ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
995   free (t->caption);
996   free (t->corner);
997   free (t->title);
998   ctables_chisq_destroy (t->chisq);
999   ctables_pairwise_destroy (t->pairwise);
1000 }
1001
1002 static void
1003 ctables_destroy (struct ctables *ct)
1004 {
1005   if (!ct)
1006     return;
1007
1008   pivot_table_look_unref (ct->look);
1009   free (ct->zero);
1010   free (ct->missing);
1011   free (ct->vlabels);
1012   for (size_t i = 0; i < ct->n_tables; i++)
1013     ctables_table_uninit (&ct->tables[i]);
1014   free (ct->tables);
1015   free (ct);
1016 }
1017
1018 static struct ctables_cat_value
1019 ccvt_range (double low, double high)
1020 {
1021   return (struct ctables_cat_value) {
1022     .type = CCVT_RANGE,
1023     .range = { low, high }
1024   };
1025 }
1026
1027 static bool
1028 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
1029                                 struct ctables_table *t)
1030 {
1031   if (!lex_match_id (lexer, "VARIABLES"))
1032     return false;
1033   lex_match (lexer, T_EQUALS);
1034
1035   struct variable **vars;
1036   size_t n_vars;
1037   if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
1038     return false;
1039
1040   struct ctables_categories *c = xmalloc (sizeof *c);
1041   *c = (struct ctables_categories) { .n_refs = n_vars };
1042   for (size_t i = 0; i < n_vars; i++)
1043     {
1044       struct ctables_categories **cp
1045         = &t->categories[var_get_dict_index (vars[i])];
1046       ctables_categories_unref (*cp);
1047       *cp = c;
1048     }
1049   free (vars);
1050
1051   if (lex_match (lexer, T_LBRACK))
1052     {
1053       size_t allocated_values = 0;
1054       do
1055         {
1056           if (c->n_values >= allocated_values)
1057             c->values = x2nrealloc (c->values, &allocated_values,
1058                                     sizeof *c->values);
1059
1060           struct ctables_cat_value *v = &c->values[c->n_values];
1061           if (lex_match_id (lexer, "OTHERNM"))
1062             v->type = CCVT_OTHERNM;
1063           else if (lex_match_id (lexer, "MISSING"))
1064             v->type = CCVT_MISSING;
1065           else if (lex_match_id (lexer, "SUBTOTAL"))
1066             *v = (struct ctables_cat_value)
1067               { .type = CCVT_SUBTOTAL, .subtotal_label = NULL };
1068           else if (lex_match_id (lexer, "HSUBTOTAL"))
1069             *v = (struct ctables_cat_value)
1070               { .type = CCVT_HSUBTOTAL, .subtotal_label = NULL };
1071           else if (lex_match_id (lexer, "LO"))
1072             {
1073               if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
1074                 return false;
1075               *v = ccvt_range (-DBL_MAX, lex_number (lexer));
1076               lex_get (lexer);
1077             }
1078           else if (lex_is_number (lexer))
1079             {
1080               double number = lex_number (lexer);
1081               lex_get (lexer);
1082               if (lex_match_id (lexer, "THRU"))
1083                 {
1084                   v->type = CCVT_RANGE;
1085                   v->range[0] = number;
1086                   if (lex_match_id (lexer, "HI"))
1087                     *v = ccvt_range (number, DBL_MAX);
1088                   else
1089                     {
1090                       if (!lex_force_num (lexer))
1091                         return false;
1092                       *v = ccvt_range (number, lex_number (lexer));
1093                       lex_get (lexer);
1094                     }
1095                 }
1096               else
1097                 *v = (struct ctables_cat_value) {
1098                   .type = CCVT_NUMBER,
1099                   .number = number
1100                 };
1101             }
1102           else if (lex_is_string (lexer))
1103             {
1104               *v = (struct ctables_cat_value) {
1105                 .type = CCVT_STRING,
1106                 .string = ss_xstrdup (lex_tokss (lexer)),
1107               };
1108               lex_get (lexer);
1109             }
1110           else
1111             {
1112               lex_error (lexer, NULL);
1113               return false;
1114             }
1115
1116           if ((v->type == CCVT_SUBTOTAL || v->type == CCVT_HSUBTOTAL)
1117               && lex_match (lexer, T_EQUALS))
1118             {
1119               if (!lex_force_string (lexer))
1120                 return false;
1121
1122               v->subtotal_label = ss_xstrdup (lex_tokss (lexer));
1123               lex_get (lexer);
1124             }
1125
1126           c->n_values++;
1127           lex_match (lexer, T_COMMA);
1128         }
1129       while (!lex_match (lexer, T_RBRACK));
1130     }
1131
1132   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
1133     {
1134       if (!c->n_values && lex_match_id (lexer, "ORDER"))
1135         {
1136           lex_match (lexer, T_EQUALS);
1137           if (lex_match_id (lexer, "A"))
1138             c->sort_ascending = true;
1139           else if (lex_match_id (lexer, "D"))
1140             c->sort_ascending = false;
1141           else
1142             {
1143               lex_error_expecting (lexer, "A", "D");
1144               return false;
1145             }
1146         }
1147       else if (!c->n_values && lex_match_id (lexer, "KEY"))
1148         {
1149           lex_match (lexer, T_EQUALS);
1150           if (lex_match_id (lexer, "VALUE"))
1151             c->key = CTCS_VALUE;
1152           else if (lex_match_id (lexer, "LABEL"))
1153             c->key = CTCS_LABEL;
1154           else
1155             {
1156               c->key = CTCS_FUNCTION;
1157               if (!parse_ctables_summary_function (lexer, &c->sort_func))
1158                 return false;
1159
1160               if (lex_match (lexer, T_LPAREN))
1161                 {
1162                   c->sort_func_var = parse_variable (lexer, dict);
1163                   if (!c->sort_func_var)
1164                     return false;
1165
1166                   if (c->sort_func == CTSF_PTILE)
1167                     {
1168                       lex_match (lexer, T_COMMA);
1169                       if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
1170                         return false;
1171                       c->percentile = lex_number (lexer);
1172                       lex_get (lexer);
1173                     }
1174
1175                   if (!lex_force_match (lexer, T_RPAREN))
1176                     return false;
1177                 }
1178               else if (ctables_function_availability (c->sort_func)
1179                        == CTFA_SCALE)
1180                 {
1181                   bool UNUSED b = lex_force_match (lexer, T_LPAREN);
1182                   return false;
1183                 }
1184             }
1185         }
1186       else if (!c->n_values && lex_match_id (lexer, "MISSING"))
1187         {
1188           lex_match (lexer, T_EQUALS);
1189           if (lex_match_id (lexer, "INCLUDE"))
1190             c->include_missing = true;
1191           else if (lex_match_id (lexer, "EXCLUDE"))
1192             c->include_missing = false;
1193           else
1194             {
1195               lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1196               return false;
1197             }
1198         }
1199       else if (lex_match_id (lexer, "TOTAL"))
1200         {
1201           lex_match (lexer, T_EQUALS);
1202           if (!parse_bool (lexer, &c->show_totals))
1203             return false;
1204         }
1205       else if (lex_match_id (lexer, "LABEL"))
1206         {
1207           lex_match (lexer, T_EQUALS);
1208           if (!lex_force_string (lexer))
1209             return false;
1210           free (c->total_label);
1211           c->total_label = ss_xstrdup (lex_tokss (lexer));
1212           lex_get (lexer);
1213         }
1214       else if (lex_match_id (lexer, "POSITION"))
1215         {
1216           lex_match (lexer, T_EQUALS);
1217           if (lex_match_id (lexer, "BEFORE"))
1218             c->totals_before = true;
1219           else if (lex_match_id (lexer, "AFTER"))
1220             c->totals_before = false;
1221           else
1222             {
1223               lex_error_expecting (lexer, "BEFORE", "AFTER");
1224               return false;
1225             }
1226         }
1227       else if (lex_match_id (lexer, "EMPTY"))
1228         {
1229           lex_match (lexer, T_EQUALS);
1230           if (lex_match_id (lexer, "INCLUDE"))
1231             c->show_empty = true;
1232           else if (lex_match_id (lexer, "EXCLUDE"))
1233             c->show_empty = false;
1234           else
1235             {
1236               lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1237               return false;
1238             }
1239         }
1240       else
1241         {
1242           if (!c->n_values)
1243             lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
1244                                  "TOTAL", "LABEL", "POSITION", "EMPTY");
1245           else
1246             lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
1247           return false;
1248         }
1249     }
1250   return true;
1251 }
1252
1253 struct var_array
1254   {
1255     struct variable **vars;
1256     size_t n;
1257   };
1258
1259 static void
1260 var_array_uninit (struct var_array *va)
1261 {
1262   if (va)
1263     free (va->vars);
1264 }
1265
1266 struct var_array2
1267   {
1268     struct var_array *vas;
1269     size_t n;
1270   };
1271
1272 static void
1273 var_array2_uninit (struct var_array2 *vaa)
1274 {
1275   if (vaa)
1276     {
1277       for (size_t i = 0; i < vaa->n; i++)
1278         var_array_uninit (&vaa->vas[i]);
1279       free (vaa->vas);
1280     }
1281 }
1282
1283 static struct var_array2
1284 nest_fts (struct var_array2 va0, struct var_array2 va1)
1285 {
1286   if (!va0.n)
1287     return va1;
1288   else if (!va1.n)
1289     return va0;
1290
1291   struct var_array2 vaa = { .vas = xnmalloc (va0.n, va1.n * sizeof *vaa.vas) };
1292   for (size_t i = 0; i < va0.n; i++)
1293     for (size_t j = 0; j < va1.n; j++)
1294       {
1295         size_t allocate = va0.vas[i].n + va1.vas[j].n;
1296         struct variable **vars = xnmalloc (allocate, sizeof *vars);
1297         size_t n = 0;
1298         for (size_t k = 0; k < va0.vas[i].n; k++)
1299           vars[n++] = va0.vas[i].vars[k];
1300         for (size_t k = 0; k < va1.vas[j].n; k++)
1301           vars[n++] = va1.vas[j].vars[k];
1302         assert (n == allocate);
1303
1304         vaa.vas[vaa.n++] = (struct var_array) { .vars = vars, n = n };
1305       }
1306   var_array2_uninit (&va0);
1307   var_array2_uninit (&va1);
1308   return vaa;
1309 }
1310
1311 static struct var_array2
1312 stack_fts (struct var_array2 va0, struct var_array2 va1)
1313 {
1314   struct var_array2 vaa = { .vas = xnmalloc (va0.n + va1.n, sizeof *vaa.vas) };
1315   for (size_t i = 0; i < va0.n; i++)
1316     vaa.vas[vaa.n++] = va0.vas[i];
1317   for (size_t i = 0; i < va1.n; i++)
1318     vaa.vas[vaa.n++] = va1.vas[i];
1319   assert (vaa.n == va0.n + va1.n);
1320   free (va0.vas);
1321   free (va1.vas);
1322   return vaa;
1323 }
1324
1325 static struct var_array2
1326 enumerate_fts (const struct ctables_axis *a)
1327 {
1328   if (!a)
1329     return (struct var_array2) { .n = 0 };
1330
1331   switch (a->op)
1332     {
1333     case CTAO_VAR:
1334       assert (!a->var.is_mrset);
1335       struct variable **v = xmalloc (sizeof *v);
1336       *v = a->var.var;
1337       struct var_array *va = xmalloc (sizeof *va);
1338       *va = (struct var_array) { .vars = v, .n = 1 };
1339       return (struct var_array2) { .vas = va, .n = 1 };
1340
1341     case CTAO_STACK:
1342       return stack_fts (enumerate_fts (a->subs[0]),
1343                         enumerate_fts (a->subs[1]));
1344
1345     case CTAO_NEST:
1346       return nest_fts (enumerate_fts (a->subs[0]),
1347                        enumerate_fts (a->subs[1]));
1348     }
1349
1350   NOT_REACHED ();
1351 }
1352
1353 struct ctables_freqtab
1354   {
1355     struct var_array vars;
1356     struct hmap data;           /* Contains "struct freq"s. */
1357   };
1358
1359 static bool
1360 ctables_execute (struct dataset *ds, struct ctables *ct)
1361 {
1362   struct ctables_freqtab **fts = NULL;
1363   size_t n_fts = 0;
1364   size_t allocated_fts = 0;
1365   for (size_t i = 0; i < ct->n_tables; i++)
1366     {
1367       struct ctables_table *t = &ct->tables[i];
1368       struct var_array2 vaa = enumerate_fts (t->axes[PIVOT_AXIS_ROW]);
1369       vaa = nest_fts (vaa, enumerate_fts (t->axes[PIVOT_AXIS_COLUMN]));
1370       vaa = nest_fts (vaa, enumerate_fts (t->axes[PIVOT_AXIS_LAYER]));
1371       for (size_t i = 0; i < vaa.n; i++)
1372         {
1373           for (size_t j = 0; j < vaa.vas[i].n; j++)
1374             {
1375               if (j)
1376                 fputs (", ", stdout);
1377               fputs (var_get_name (vaa.vas[i].vars[j]), stdout);
1378             }
1379           putchar ('\n');
1380         }
1381
1382       for (size_t j = 0; j < vaa.n; j++)
1383         {
1384           if (n_fts >= allocated_fts)
1385             fts = x2nrealloc (fts, &allocated_fts, sizeof *fts);
1386
1387           struct ctables_freqtab *ft = xmalloc (sizeof *ft);
1388           *ft = (struct ctables_freqtab) {
1389             .vars = vaa.vas[j],
1390             .data = HMAP_INITIALIZER (ft->data),
1391           };
1392           fts[n_fts++] = ft;
1393         }
1394
1395       free (vaa.vas);
1396     }
1397
1398   struct casereader *input = casereader_create_filter_weight (proc_open (ds),
1399                                                               dataset_dict (ds),
1400                                                               NULL, NULL);
1401   bool warn_on_invalid = true;
1402   for (struct ccase *c = casereader_read (input); c;
1403        case_unref (c), c = casereader_read (input))
1404     {
1405       double weight = dict_get_case_weight (dataset_dict (ds), c,
1406                                             &warn_on_invalid);
1407       for (size_t i = 0; i < n_fts; i++)
1408         {
1409           struct ctables_freqtab *ft = fts[i];
1410
1411           size_t hash = 0;
1412
1413           for (size_t j = 0; j < ft->vars.n; j++)
1414             {
1415               const struct variable *var = ft->vars.vars[j];
1416               hash = value_hash (case_data (c, var), var_get_width (var), hash);
1417             }
1418
1419           struct freq *f;
1420           HMAP_FOR_EACH_WITH_HASH (f, struct freq, node, hash, &ft->data)
1421             {
1422               for (size_t j = 0; j < ft->vars.n; j++)
1423                 {
1424                   const struct variable *var = ft->vars.vars[j];
1425                   if (!value_equal (case_data (c, var), &f->values[j],
1426                                     var_get_width (var)))
1427                     goto next_hash_node;
1428                 }
1429
1430               f->count += weight;
1431               goto next_ft;
1432
1433             next_hash_node: ;
1434             }
1435
1436         f = xmalloc (table_entry_size (ft->vars.n));
1437         f->count = weight;
1438         for (size_t j = 0; j < ft->vars.n; j++)
1439           {
1440             const struct variable *var = ft->vars.vars[j];
1441             value_clone (&f->values[j], case_data (c, var),
1442                          var_get_width (var));
1443           }
1444         hmap_insert (&ft->data, &f->node, hash);
1445
1446         next_ft: ;
1447         }
1448     }
1449   casereader_destroy (input);
1450
1451   for (size_t i = 0; i < n_fts; i++)
1452     {
1453       struct ctables_freqtab *ft = fts[i];
1454       struct freq *f, *next;
1455       HMAP_FOR_EACH_SAFE (f, next, struct freq, node, &ft->data)
1456         {
1457           hmap_delete (&ft->data, &f->node);
1458           for (size_t j = 0; j < ft->vars.n; j++)
1459             {
1460               const struct variable *var = ft->vars.vars[j];
1461               value_destroy (&f->values[j], var_get_width (var));
1462             }
1463           free (f);
1464         }
1465       hmap_destroy (&ft->data);
1466       var_array_uninit (&ft->vars);
1467       free (ft);
1468     }
1469   free (fts);
1470
1471   return proc_commit (ds);
1472 }
1473
1474 int
1475 cmd_ctables (struct lexer *lexer, struct dataset *ds)
1476 {
1477   size_t n_vars = dict_get_n_vars (dataset_dict (ds));
1478   enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
1479   for (size_t i = 0; i < n_vars; i++)
1480     vlabels[i] = CTVL_DEFAULT;
1481
1482   struct ctables *ct = xmalloc (sizeof *ct);
1483   *ct = (struct ctables) {
1484     .look = pivot_table_look_unshare (pivot_table_look_ref (
1485                                         pivot_table_look_get_default ())),
1486     .vlabels = vlabels,
1487     .hide_threshold = 5,
1488   };
1489
1490   if (!lex_force_match (lexer, T_SLASH))
1491     goto error;
1492
1493   while (!lex_match_id (lexer, "TABLE"))
1494     {
1495       if (lex_match_id (lexer, "FORMAT"))
1496         {
1497           double widths[2] = { SYSMIS, SYSMIS };
1498           double units_per_inch = 72.0;
1499
1500           while (lex_token (lexer) != T_SLASH)
1501             {
1502               if (lex_match_id (lexer, "MINCOLWIDTH"))
1503                 {
1504                   if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
1505                     goto error;
1506                 }
1507               else if (lex_match_id (lexer, "MAXCOLWIDTH"))
1508                 {
1509                   if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
1510                     goto error;
1511                 }
1512               else if (lex_match_id (lexer, "UNITS"))
1513                 {
1514                   lex_match (lexer, T_EQUALS);
1515                   if (lex_match_id (lexer, "POINTS"))
1516                     units_per_inch = 72.0;
1517                   else if (lex_match_id (lexer, "INCHES"))
1518                     units_per_inch = 1.0;
1519                   else if (lex_match_id (lexer, "CM"))
1520                     units_per_inch = 2.54;
1521                   else
1522                     {
1523                       lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
1524                       goto error;
1525                     }
1526                 }
1527               else if (lex_match_id (lexer, "EMPTY"))
1528                 {
1529                   free (ct->zero);
1530                   ct->zero = NULL;
1531
1532                   lex_match (lexer, T_EQUALS);
1533                   if (lex_match_id (lexer, "ZERO"))
1534                     {
1535                       /* Nothing to do. */
1536                     }
1537                   else if (lex_match_id (lexer, "BLANK"))
1538                     ct->zero = xstrdup ("");
1539                   else if (lex_force_string (lexer))
1540                     {
1541                       ct->zero = ss_xstrdup (lex_tokss (lexer));
1542                       lex_get (lexer);
1543                     }
1544                   else
1545                     goto error;
1546                 }
1547               else if (lex_match_id (lexer, "MISSING"))
1548                 {
1549                   lex_match (lexer, T_EQUALS);
1550                   if (!lex_force_string (lexer))
1551                     goto error;
1552
1553                   free (ct->missing);
1554                   ct->missing = (strcmp (lex_tokcstr (lexer), ".")
1555                                  ? ss_xstrdup (lex_tokss (lexer))
1556                                  : NULL);
1557                   lex_get (lexer);
1558                 }
1559               else
1560                 {
1561                   lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
1562                                        "UNITS", "EMPTY", "MISSING");
1563                   goto error;
1564                 }
1565             }
1566
1567           if (widths[0] != SYSMIS && widths[1] != SYSMIS
1568               && widths[0] > widths[1])
1569             {
1570               msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
1571               goto error;
1572             }
1573
1574           for (size_t i = 0; i < 2; i++)
1575             if (widths[i] != SYSMIS)
1576               {
1577                 int *wr = ct->look->width_ranges[TABLE_HORZ];
1578                 wr[i] = widths[i] / units_per_inch * 96.0;
1579                 if (wr[0] > wr[1])
1580                   wr[!i] = wr[i];
1581               }
1582         }
1583       else if (lex_match_id (lexer, "VLABELS"))
1584         {
1585           if (!lex_force_match_id (lexer, "VARIABLES"))
1586             goto error;
1587           lex_match (lexer, T_EQUALS);
1588
1589           struct variable **vars;
1590           size_t n_vars;
1591           if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
1592                                 PV_NO_SCRATCH))
1593             goto error;
1594
1595           if (!lex_force_match_id (lexer, "DISPLAY"))
1596             {
1597               free (vars);
1598               goto error;
1599             }
1600           lex_match (lexer, T_EQUALS);
1601
1602           enum ctables_vlabel vlabel;
1603           if (lex_match_id (lexer, "DEFAULT"))
1604             vlabel = CTVL_DEFAULT;
1605           else if (lex_match_id (lexer, "NAME"))
1606             vlabel = CTVL_NAME;
1607           else if (lex_match_id (lexer, "LABEL"))
1608             vlabel = CTVL_LABEL;
1609           else if (lex_match_id (lexer, "BOTH"))
1610             vlabel = CTVL_BOTH;
1611           else if (lex_match_id (lexer, "NONE"))
1612             vlabel = CTVL_NONE;
1613           else
1614             {
1615               lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
1616                                    "BOTH", "NONE");
1617               free (vars);
1618               goto error;
1619             }
1620
1621           for (size_t i = 0; i < n_vars; i++)
1622             ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
1623           free (vars);
1624         }
1625       else if (lex_match_id (lexer, "MRSETS"))
1626         {
1627           if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
1628             goto error;
1629           lex_match (lexer, T_EQUALS);
1630           if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
1631             goto error;
1632         }
1633       else if (lex_match_id (lexer, "SMISSING"))
1634         {
1635           if (lex_match_id (lexer, "VARIABLE"))
1636             ct->smissing_listwise = false;
1637           else if (lex_match_id (lexer, "LISTWISE"))
1638             ct->smissing_listwise = true;
1639           else
1640             {
1641               lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
1642               goto error;
1643             }
1644         }
1645       /* XXX PCOMPUTE */
1646       else if (lex_match_id (lexer, "WEIGHT"))
1647         {
1648           if (!lex_force_match_id (lexer, "VARIABLE"))
1649             goto error;
1650           lex_match (lexer, T_EQUALS);
1651           ct->base_weight = parse_variable (lexer, dataset_dict (ds));
1652           if (!ct->base_weight)
1653             goto error;
1654         }
1655       else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
1656         {
1657           if (!lex_force_match_id (lexer, "COUNT"))
1658             goto error;
1659           lex_match (lexer, T_EQUALS);
1660           if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
1661             goto error;
1662           ct->hide_threshold = lex_integer (lexer);
1663           lex_get (lexer);
1664         }
1665       else
1666         {
1667           lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
1668                                "SMISSING", "PCOMPUTE", "PPROPERTIES",
1669                                "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
1670           goto error;
1671         }
1672
1673       if (!lex_force_match (lexer, T_SLASH))
1674         goto error;
1675     }
1676
1677   size_t allocated_tables = 0;
1678   do
1679     {
1680       if (ct->n_tables >= allocated_tables)
1681         ct->tables = x2nrealloc (ct->tables, &allocated_tables,
1682                                  sizeof *ct->tables);
1683
1684       struct ctables_table *t = &ct->tables[ct->n_tables++];
1685       *t = (struct ctables_table) {
1686         .slabels_position = PIVOT_AXIS_COLUMN,
1687         .slabels_visible = true,
1688         .row_labels = CTLP_NORMAL,
1689         .col_labels = CTLP_NORMAL,
1690         .categories = xcalloc (dict_get_n_vars (dataset_dict (ds)),
1691                                sizeof *t->categories),
1692         .n_categories = dict_get_n_vars (dataset_dict (ds)),
1693         .cilevel = 95,
1694       };
1695
1696       lex_match (lexer, T_EQUALS);
1697       if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
1698         goto error;
1699       if (lex_match (lexer, T_BY))
1700         {
1701           if (!ctables_axis_parse (lexer, dataset_dict (ds),
1702                                    ct, t, PIVOT_AXIS_COLUMN))
1703             goto error;
1704
1705           if (lex_match (lexer, T_BY))
1706             {
1707               if (!ctables_axis_parse (lexer, dataset_dict (ds),
1708                                        ct, t, PIVOT_AXIS_LAYER))
1709                 goto error;
1710             }
1711         }
1712
1713       if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
1714           && !t->axes[PIVOT_AXIS_LAYER])
1715         {
1716           lex_error (lexer, _("At least one variable must be specified."));
1717           goto error;
1718         }
1719
1720       const struct ctables_axis *scales[PIVOT_N_AXES];
1721       size_t n_scales = 0;
1722       for (size_t i = 0; i < 3; i++)
1723         {
1724           scales[i] = find_scale (t->axes[i]);
1725           if (scales[i])
1726             n_scales++;
1727         }
1728       if (n_scales > 1)
1729         {
1730           msg (SE, _("Scale variables may appear only on one dimension."));
1731           if (scales[PIVOT_AXIS_ROW])
1732             msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
1733                     _("This scale variable appears in the rows dimension."));
1734           if (scales[PIVOT_AXIS_COLUMN])
1735             msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
1736                     _("This scale variable appears in the columns dimension."));
1737           if (scales[PIVOT_AXIS_LAYER])
1738             msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
1739                     _("This scale variable appears in the layer dimension."));
1740           goto error;
1741         }
1742
1743       if (lex_token (lexer) == T_ENDCMD)
1744         break;
1745       if (!lex_force_match (lexer, T_SLASH))
1746         break;
1747
1748       while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
1749         {
1750           if (lex_match_id (lexer, "SLABELS"))
1751             {
1752               while (lex_token (lexer) != T_SLASH)
1753                 {
1754                   if (lex_match_id (lexer, "POSITION"))
1755                     {
1756                       lex_match (lexer, T_EQUALS);
1757                       if (lex_match_id (lexer, "COLUMN"))
1758                         t->slabels_position = PIVOT_AXIS_COLUMN;
1759                       else if (lex_match_id (lexer, "ROW"))
1760                         t->slabels_position = PIVOT_AXIS_ROW;
1761                       else if (lex_match_id (lexer, "LAYER"))
1762                         t->slabels_position = PIVOT_AXIS_LAYER;
1763                       else
1764                         {
1765                           lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
1766                           goto error;
1767                         }
1768                     }
1769                   else if (lex_match_id (lexer, "VISIBLE"))
1770                     {
1771                       lex_match (lexer, T_EQUALS);
1772                       if (!parse_bool (lexer, &t->slabels_visible))
1773                         goto error;
1774                     }
1775                   else
1776                     {
1777                       lex_error_expecting (lexer, "POSITION", "VISIBLE");
1778                       goto error;
1779                     }
1780                 }
1781             }
1782           else if (lex_match_id (lexer, "CLABELS"))
1783             {
1784               while (lex_token (lexer) != T_SLASH)
1785                 {
1786                   if (lex_match_id (lexer, "AUTO"))
1787                     t->row_labels = t->col_labels = CTLP_NORMAL;
1788                   else if (lex_match_id (lexer, "ROWLABELS"))
1789                     {
1790                       lex_match (lexer, T_EQUALS);
1791                       if (lex_match_id (lexer, "OPPOSITE"))
1792                         t->row_labels = CTLP_OPPOSITE;
1793                       else if (lex_match_id (lexer, "LAYER"))
1794                         t->row_labels = CTLP_LAYER;
1795                       else
1796                         {
1797                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
1798                           goto error;
1799                         }
1800                     }
1801                   else if (lex_match_id (lexer, "COLLABELS"))
1802                     {
1803                       lex_match (lexer, T_EQUALS);
1804                       if (lex_match_id (lexer, "OPPOSITE"))
1805                         t->col_labels = CTLP_OPPOSITE;
1806                       else if (lex_match_id (lexer, "LAYER"))
1807                         t->col_labels = CTLP_LAYER;
1808                       else
1809                         {
1810                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
1811                           goto error;
1812                         }
1813                     }
1814                   else
1815                     {
1816                       lex_error_expecting (lexer, "AUTO", "ROWLABELS",
1817                                            "COLLABELS");
1818                       goto error;
1819                     }
1820                 }
1821             }
1822           else if (lex_match_id (lexer, "CRITERIA"))
1823             {
1824               if (!lex_force_match_id (lexer, "CILEVEL"))
1825                 goto error;
1826               lex_match (lexer, T_EQUALS);
1827
1828               if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
1829                 goto error;
1830               t->cilevel = lex_number (lexer);
1831               lex_get (lexer);
1832             }
1833           else if (lex_match_id (lexer, "CATEGORIES"))
1834             {
1835               if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
1836                 goto error;
1837             }
1838           else if (lex_match_id (lexer, "TITLES"))
1839             {
1840               do
1841                 {
1842                   char **textp;
1843                   if (lex_match_id (lexer, "CAPTION"))
1844                     textp = &t->caption;
1845                   else if (lex_match_id (lexer, "CORNER"))
1846                     textp = &t->corner;
1847                   else if (lex_match_id (lexer, "TITLE"))
1848                     textp = &t->title;
1849                   else
1850                     {
1851                       lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
1852                       goto error;
1853                     }
1854                   lex_match (lexer, T_EQUALS);
1855
1856                   struct string s = DS_EMPTY_INITIALIZER;
1857                   while (lex_is_string (lexer))
1858                     {
1859                       if (!ds_is_empty (&s))
1860                         ds_put_byte (&s, ' ');
1861                       ds_put_substring (&s, lex_tokss (lexer));
1862                       lex_get (lexer);
1863                     }
1864                   free (*textp);
1865                   *textp = ds_steal_cstr (&s);
1866                 }
1867               while (lex_token (lexer) != T_SLASH
1868                      && lex_token (lexer) != T_ENDCMD);
1869             }
1870           else if (lex_match_id (lexer, "SIGTEST"))
1871             {
1872               if (!t->chisq)
1873                 {
1874                   t->chisq = xmalloc (sizeof *t->chisq);
1875                   *t->chisq = (struct ctables_chisq) {
1876                     .alpha = .05,
1877                     .include_mrsets = true,
1878                     .all_visible = true,
1879                   };
1880                 }
1881
1882               do
1883                 {
1884                   if (lex_match_id (lexer, "TYPE"))
1885                     {
1886                       lex_match (lexer, T_EQUALS);
1887                       if (!lex_force_match_id (lexer, "CHISQUARE"))
1888                         goto error;
1889                     }
1890                   else if (lex_match_id (lexer, "ALPHA"))
1891                     {
1892                       lex_match (lexer, T_EQUALS);
1893                       if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
1894                         goto error;
1895                       t->chisq->alpha = lex_number (lexer);
1896                       lex_get (lexer);
1897                     }
1898                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
1899                     {
1900                       lex_match (lexer, T_EQUALS);
1901                       if (parse_bool (lexer, &t->chisq->include_mrsets))
1902                         goto error;
1903                     }
1904                   else if (lex_match_id (lexer, "CATEGORIES"))
1905                     {
1906                       lex_match (lexer, T_EQUALS);
1907                       if (lex_match_id (lexer, "ALLVISIBLE"))
1908                         t->chisq->all_visible = true;
1909                       else if (lex_match_id (lexer, "SUBTOTALS"))
1910                         t->chisq->all_visible = false;
1911                       else
1912                         {
1913                           lex_error_expecting (lexer,
1914                                                "ALLVISIBLE", "SUBTOTALS");
1915                           goto error;
1916                         }
1917                     }
1918                   else
1919                     {
1920                       lex_error_expecting (lexer, "TYPE", "ALPHA",
1921                                            "INCLUDEMRSETS", "CATEGORIES");
1922                       goto error;
1923                     }
1924                 }
1925               while (lex_token (lexer) != T_SLASH
1926                      && lex_token (lexer) != T_ENDCMD);
1927             }
1928           else if (lex_match_id (lexer, "COMPARETEST"))
1929             {
1930               if (!t->pairwise)
1931                 {
1932                   t->pairwise = xmalloc (sizeof *t->pairwise);
1933                   *t->pairwise = (struct ctables_pairwise) {
1934                     .type = PROP,
1935                     .alpha = { .05, .05 },
1936                     .adjust = BONFERRONI,
1937                     .include_mrsets = true,
1938                     .meansvariance_allcats = true,
1939                     .all_visible = true,
1940                     .merge = false,
1941                     .apa_style = true,
1942                     .show_sig = false,
1943                   };
1944                 }
1945
1946               do
1947                 {
1948                   if (lex_match_id (lexer, "TYPE"))
1949                     {
1950                       lex_match (lexer, T_EQUALS);
1951                       if (lex_match_id (lexer, "PROP"))
1952                         t->pairwise->type = PROP;
1953                       else if (lex_match_id (lexer, "MEAN"))
1954                         t->pairwise->type = MEAN;
1955                       else
1956                         {
1957                           lex_error_expecting (lexer, "PROP", "MEAN");
1958                           goto error;
1959                         }
1960                     }
1961                   else if (lex_match_id (lexer, "ALPHA"))
1962                     {
1963                       lex_match (lexer, T_EQUALS);
1964
1965                       if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
1966                         goto error;
1967                       double a0 = lex_number (lexer);
1968                       lex_get (lexer);
1969
1970                       lex_match (lexer, T_COMMA);
1971                       if (lex_is_number (lexer))
1972                         {
1973                           if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
1974                             goto error;
1975                           double a1 = lex_number (lexer);
1976                           lex_get (lexer);
1977
1978                           t->pairwise->alpha[0] = MIN (a0, a1);
1979                           t->pairwise->alpha[1] = MAX (a0, a1);
1980                         }
1981                       else
1982                         t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
1983                     }
1984                   else if (lex_match_id (lexer, "ADJUST"))
1985                     {
1986                       lex_match (lexer, T_EQUALS);
1987                       if (lex_match_id (lexer, "BONFERRONI"))
1988                         t->pairwise->adjust = BONFERRONI;
1989                       else if (lex_match_id (lexer, "BH"))
1990                         t->pairwise->adjust = BH;
1991                       else if (lex_match_id (lexer, "NONE"))
1992                         t->pairwise->adjust = 0;
1993                       else
1994                         {
1995                           lex_error_expecting (lexer, "BONFERRONI", "BH",
1996                                                "NONE");
1997                           goto error;
1998                         }
1999                     }
2000                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
2001                     {
2002                       lex_match (lexer, T_EQUALS);
2003                       if (!parse_bool (lexer, &t->pairwise->include_mrsets))
2004                         goto error;
2005                     }
2006                   else if (lex_match_id (lexer, "MEANSVARIANCE"))
2007                     {
2008                       lex_match (lexer, T_EQUALS);
2009                       if (lex_match_id (lexer, "ALLCATS"))
2010                         t->pairwise->meansvariance_allcats = true;
2011                       else if (lex_match_id (lexer, "TESTEDCATS"))
2012                         t->pairwise->meansvariance_allcats = false;
2013                       else
2014                         {
2015                           lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
2016                           goto error;
2017                         }
2018                     }
2019                   else if (lex_match_id (lexer, "CATEGORIES"))
2020                     {
2021                       lex_match (lexer, T_EQUALS);
2022                       if (lex_match_id (lexer, "ALLVISIBLE"))
2023                         t->pairwise->all_visible = true;
2024                       else if (lex_match_id (lexer, "SUBTOTALS"))
2025                         t->pairwise->all_visible = false;
2026                       else
2027                         {
2028                           lex_error_expecting (lexer, "ALLVISIBLE",
2029                                                "SUBTOTALS");
2030                           goto error;
2031                         }
2032                     }
2033                   else if (lex_match_id (lexer, "MERGE"))
2034                     {
2035                       lex_match (lexer, T_EQUALS);
2036                       if (!parse_bool (lexer, &t->pairwise->merge))
2037                         goto error;
2038                     }
2039                   else if (lex_match_id (lexer, "STYLE"))
2040                     {
2041                       lex_match (lexer, T_EQUALS);
2042                       if (lex_match_id (lexer, "APA"))
2043                         t->pairwise->apa_style = true;
2044                       else if (lex_match_id (lexer, "SIMPLE"))
2045                         t->pairwise->apa_style = false;
2046                       else
2047                         {
2048                           lex_error_expecting (lexer, "APA", "SIMPLE");
2049                           goto error;
2050                         }
2051                     }
2052                   else if (lex_match_id (lexer, "SHOWSIG"))
2053                     {
2054                       lex_match (lexer, T_EQUALS);
2055                       if (!parse_bool (lexer, &t->pairwise->show_sig))
2056                         goto error;
2057                     }
2058                   else
2059                     {
2060                       lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
2061                                            "INCLUDEMRSETS", "MEANSVARIANCE",
2062                                            "CATEGORIES", "MERGE", "STYLE",
2063                                            "SHOWSIG");
2064                       goto error;
2065                     }
2066                 }
2067               while (lex_token (lexer) != T_SLASH
2068                      && lex_token (lexer) != T_ENDCMD);
2069             }
2070           else
2071             {
2072               lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
2073                                    "CRITERIA", "CATEGORIES", "TITLES",
2074                                    "SIGTEST", "COMPARETEST");
2075               goto error;
2076             }
2077         }
2078
2079       if (t->row_labels != CTLP_NORMAL && t->col_labels != CTLP_NORMAL)
2080         {
2081           msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
2082           goto error;
2083         }
2084
2085     }
2086   while (lex_token (lexer) != T_ENDCMD);
2087
2088   bool ok = ctables_execute (ds, ct);
2089   ctables_destroy (ct);
2090   return ok ? CMD_SUCCESS : CMD_FAILURE;
2091
2092 error:
2093   ctables_destroy (ct);
2094   return CMD_FAILURE;
2095 }
2096