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