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