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