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