single totals work
[pspp] / src / language / stats / ctables.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2021 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <math.h>
20
21 #include "data/casereader.h"
22 #include "data/dataset.h"
23 #include "data/dictionary.h"
24 #include "data/mrset.h"
25 #include "language/command.h"
26 #include "language/lexer/format-parser.h"
27 #include "language/lexer/lexer.h"
28 #include "language/lexer/variable-parser.h"
29 #include "libpspp/array.h"
30 #include "libpspp/assertion.h"
31 #include "libpspp/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 ctables_cell_insert (struct ctables_table *t,
2212                      const struct ccase *c,
2213                      size_t ir, size_t ic, size_t il,
2214                      double weight)
2215 {
2216   size_t ix[PIVOT_N_AXES] = {
2217     [PIVOT_AXIS_ROW] = ir,
2218     [PIVOT_AXIS_COLUMN] = ic,
2219     [PIVOT_AXIS_LAYER] = il,
2220   };
2221
2222   const struct ctables_category *cats[PIVOT_N_AXES][10];
2223   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2224     {
2225       const struct var_array *va = &t->vaas[a].vas[ix[a]];
2226       for (size_t i = 0; i < va->n; i++)
2227         {
2228           if (i == va->scale_idx)
2229             continue;
2230
2231           const struct variable *var = va->vars[i];
2232           const union value *value = case_data (c, var);
2233
2234           if (var_is_numeric (var) && value->f == SYSMIS)
2235             return;
2236
2237           cats[a][i] = ctables_categories_match (
2238             t->categories[var_get_dict_index (var)], value, var);
2239           if (!cats[a][i])
2240             return;
2241         }
2242     }
2243
2244   ctables_cell_insert__ (t, c, ix, cats, weight);
2245
2246   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2247     {
2248       const struct var_array *va = &t->vaas[a].vas[ix[a]];
2249       for (size_t i = 0; i < va->n; i++)
2250         {
2251           if (i == va->scale_idx)
2252             continue;
2253
2254           const struct variable *var = va->vars[i];
2255
2256           const struct ctables_category *total = ctables_categories_total (
2257             t->categories[var_get_dict_index (var)]);
2258           if (total)
2259             {
2260               const struct ctables_category *save = cats[a][i];
2261               cats[a][i] = total;
2262               ctables_cell_insert__ (t, c, ix, cats, weight);
2263               cats[a][i] = save;
2264             }
2265         }
2266     }
2267 }
2268
2269 static bool
2270 ctables_execute (struct dataset *ds, struct ctables *ct)
2271 {
2272   for (size_t i = 0; i < ct->n_tables; i++)
2273     {
2274       struct ctables_table *t = ct->tables[i];
2275       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2276         if (t->axes[a])
2277           {
2278             t->vaas[a] = enumerate_fts (a, t->axes[a]);
2279
2280             for (size_t j = 0; j < t->vaas[a].n; j++)
2281               {
2282                 struct var_array *va = &t->vaas[a].vas[j];
2283                 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2284                   {
2285                     va->domains[dt] = xmalloc (va->n * sizeof *va->domains[dt]);
2286                     va->n_domains[dt] = 0;
2287
2288                     for (size_t k = 0; k < va->n; k++)
2289                       {
2290                         if (k == va->scale_idx)
2291                           continue;
2292
2293                         switch (dt)
2294                           {
2295                           case CTDT_TABLE:
2296                             continue;
2297
2298                           case CTDT_LAYER:
2299                             if (a != PIVOT_AXIS_LAYER)
2300                               continue;
2301                             break;
2302
2303                           case CTDT_SUBTABLE:
2304                           case CTDT_ROW:
2305                           case CTDT_COL:
2306                             if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
2307                                 : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
2308                                 : a == PIVOT_AXIS_ROW)
2309                               {
2310                                 if (k == va->n - 1
2311                                     || (va->scale_idx == va->n - 1
2312                                         && k == va->n - 2))
2313                                   continue;
2314                               }
2315                             break;
2316
2317                           case CTDT_LAYERROW:
2318                             if (a == PIVOT_AXIS_COLUMN)
2319                               continue;
2320                             break;
2321
2322                           case CTDT_LAYERCOL:
2323                             if (a == PIVOT_AXIS_ROW)
2324                               continue;
2325                             break;
2326                           }
2327
2328                         va->domains[dt][va->n_domains[dt]++] = k;
2329                       }
2330                   }
2331               }
2332           }
2333         else
2334           {
2335             struct var_array *va = xmalloc (sizeof *va);
2336             *va = (struct var_array) { .n = 0 };
2337             t->vaas[a] = (struct var_array2) { .vas = va, .n = 1 };
2338           }
2339
2340       for (size_t i = 0; i < t->vaas[t->summary_axis].n; i++)
2341         {
2342           struct var_array *va = &t->vaas[t->summary_axis].vas[i];
2343           if (!va->n_summaries)
2344             {
2345               va->summaries = xmalloc (sizeof *va->summaries);
2346               va->n_summaries = 1;
2347
2348               enum ctables_summary_function function
2349                 = va->summary_var ? CTSF_MEAN : CTSF_COUNT;
2350               struct ctables_var var = { .is_mrset = false, .var = va->summary_var };
2351
2352               *va->summaries = (struct ctables_summary_spec) {
2353                 .function = function,
2354                 .format = ctables_summary_default_format (function, &var),
2355                 .label = ctables_summary_default_label (function, 0),
2356               };
2357               if (!va->summary_var)
2358                 va->summary_var = va->vars[0];
2359             }
2360         }
2361     }
2362
2363   struct casereader *input = casereader_create_filter_weight (proc_open (ds),
2364                                                               dataset_dict (ds),
2365                                                               NULL, NULL);
2366   bool warn_on_invalid = true;
2367   double total_weight = 0;
2368   for (struct ccase *c = casereader_read (input); c;
2369        case_unref (c), c = casereader_read (input))
2370     {
2371       double weight = dict_get_case_weight (dataset_dict (ds), c,
2372                                             &warn_on_invalid);
2373       total_weight += weight;
2374
2375       for (size_t i = 0; i < ct->n_tables; i++)
2376         {
2377           struct ctables_table *t = ct->tables[i];
2378
2379           for (size_t ir = 0; ir < t->vaas[PIVOT_AXIS_ROW].n; ir++)
2380             for (size_t ic = 0; ic < t->vaas[PIVOT_AXIS_COLUMN].n; ic++)
2381               for (size_t il = 0; il < t->vaas[PIVOT_AXIS_LAYER].n; il++)
2382                 ctables_cell_insert (t, c, ir, ic, il, weight);
2383         }
2384     }
2385   casereader_destroy (input);
2386
2387   for (size_t i = 0; i < ct->n_tables; i++)
2388     {
2389       struct ctables_table *t = ct->tables[i];
2390
2391       struct pivot_table *pt = pivot_table_create__ (
2392         (t->title
2393          ? pivot_value_new_user_text (t->title, SIZE_MAX)
2394          : pivot_value_new_text (N_("Custom Tables"))),
2395         NULL);
2396       if (t->caption)
2397         pivot_table_set_caption (
2398           pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
2399       if (t->corner)
2400         pivot_table_set_caption (
2401           pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
2402
2403       pivot_table_set_look (pt, ct->look);
2404       struct pivot_dimension *d[PIVOT_N_AXES];
2405       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2406         {
2407           static const char *names[] = {
2408             [PIVOT_AXIS_ROW] = N_("Rows"),
2409             [PIVOT_AXIS_COLUMN] = N_("Columns"),
2410             [PIVOT_AXIS_LAYER] = N_("Layers"),
2411           };
2412           d[a] = (t->axes[a] || a == t->summary_axis
2413                   ? pivot_dimension_create (pt, a, names[a])
2414                   : NULL);
2415           if (!d[a])
2416             continue;
2417
2418           assert (t->axes[a]);
2419
2420           struct ctables_cell **sorted = xnmalloc (t->cells.count, sizeof *sorted);
2421
2422           struct ctables_cell *f;
2423           size_t n = 0;
2424           HMAP_FOR_EACH (f, struct ctables_cell, node, &t->cells)
2425             sorted[n++] = f;
2426           assert (n == t->cells.count);
2427
2428           struct ctables_cell_sort_aux aux = { .t = t, .a = a };
2429           sort (sorted, n, sizeof *sorted, ctables_cell_compare_3way, &aux);
2430
2431           size_t max_depth = 0;
2432           for (size_t j = 0; j < t->vaas[a].n; j++)
2433             if (t->vaas[a].vas[j].n > max_depth)
2434               max_depth = t->vaas[a].vas[j].n;
2435
2436           struct pivot_category **groups = xnmalloc (max_depth, sizeof *groups);
2437           struct pivot_category *top = NULL;
2438           int prev_leaf = 0;
2439           for (size_t j = 0; j < n; j++)
2440             {
2441               struct ctables_cell *f = sorted[j];
2442               const struct var_array *va = &t->vaas[a].vas[f->axes[a].vaa_idx];
2443
2444               size_t n_common = 0;
2445               bool new_subtable = false;
2446               if (j > 0)
2447                 {
2448                   struct ctables_cell *prev = sorted[j - 1];
2449                   if (prev->axes[a].vaa_idx == f->axes[a].vaa_idx)
2450                     {
2451                       for (; n_common < va->n; n_common++)
2452                         if (n_common != va->scale_idx
2453                             && (prev->axes[a].cvs[n_common].category
2454                                 != f->axes[a].cvs[n_common].category
2455                                 || !value_equal (&prev->axes[a].cvs[n_common].value,
2456                                                  &f->axes[a].cvs[n_common].value,
2457                                                  var_get_type (va->vars[n_common]))))
2458                           break;
2459                     }
2460                   else
2461                     new_subtable = true;
2462                 }
2463               else
2464                 new_subtable = true;
2465
2466               if (new_subtable)
2467                 {
2468                   enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (va->vars[0])];
2469                   top = d[a]->root;
2470                   if (vlabel != CTVL_NONE)
2471                     top = pivot_category_create_group__ (
2472                       top, pivot_value_new_variable (va->vars[0]));
2473                 }
2474               if (n_common == va->n)
2475                 {
2476                   f->axes[a].leaf = prev_leaf;
2477                   continue;
2478                 }
2479
2480               for (size_t k = n_common; k < va->n; k++)
2481                 {
2482                   struct pivot_category *parent = k > 0 ? groups[k - 1] : top;
2483
2484                   struct pivot_value *label
2485                     = (k == va->scale_idx ? NULL
2486                        : f->axes[a].cvs[k].category->type == CCT_TOTAL
2487                        ? pivot_value_new_user_text (f->axes[a].cvs[k].category->total_label,
2488                                                     SIZE_MAX)
2489                        : pivot_value_new_var_value (va->vars[k],
2490                                                     &f->axes[a].cvs[k].value));
2491                   if (k == va->n - 1)
2492                     {
2493                       if (a == t->summary_axis)
2494                         {
2495                           if (label)
2496                             parent = pivot_category_create_group__ (parent, label);
2497                           for (size_t m = 0; m < va->n_summaries; m++)
2498                             {
2499                               int leaf = pivot_category_create_leaf (
2500                                 parent, pivot_value_new_text (va->summaries[m].label));
2501                               if (m == 0)
2502                                 prev_leaf = leaf;
2503                             }
2504                         }
2505                       else
2506                         {
2507                           /* This assertion is true as long as the summary axis
2508                              is the axis where the summaries are displayed. */
2509                           assert (label);
2510
2511                           prev_leaf = pivot_category_create_leaf (parent, label);
2512                         }
2513                       break;
2514                     }
2515
2516                   if (label)
2517                     parent = pivot_category_create_group__ (parent, label);
2518
2519                   enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (va->vars[k + 1])];
2520                   if (vlabel != CTVL_NONE)
2521                     parent = pivot_category_create_group__ (
2522                       parent, pivot_value_new_variable (va->vars[k + 1]));
2523                   groups[k] = parent;
2524                 }
2525
2526               f->axes[a].leaf = prev_leaf;
2527             }
2528           free (sorted);
2529           free (groups);
2530         }
2531       struct ctables_cell *f;
2532       HMAP_FOR_EACH (f, struct ctables_cell, node, &t->cells)
2533         {
2534           const struct var_array *ss = &t->vaas[t->summary_axis].vas[f->axes[t->summary_axis].vaa_idx];
2535           for (size_t j = 0; j < ss->n_summaries; j++)
2536             {
2537               size_t dindexes[3];
2538               size_t n_dindexes = 0;
2539
2540               for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2541                 if (d[a])
2542                   {
2543                     int leaf = f->axes[a].leaf;
2544                     if (a == t->summary_axis)
2545                       leaf += j;
2546                     dindexes[n_dindexes++] = leaf;
2547                   }
2548
2549               double d = ctables_summary_value (f, &f->summaries[j], &ss->summaries[j]);
2550               struct pivot_value *value = pivot_value_new_number (d);
2551               value->numeric.format = ss->summaries[j].format;
2552               pivot_table_put (pt, dindexes, n_dindexes, value);
2553             }
2554         }
2555
2556       pivot_table_submit (pt);
2557     }
2558
2559   return proc_commit (ds);
2560 }
2561
2562 int
2563 cmd_ctables (struct lexer *lexer, struct dataset *ds)
2564 {
2565   size_t n_vars = dict_get_n_vars (dataset_dict (ds));
2566   enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
2567   enum settings_value_show tvars = settings_get_show_variables ();
2568   for (size_t i = 0; i < n_vars; i++)
2569     vlabels[i] = (enum ctables_vlabel) tvars;
2570
2571   struct ctables *ct = xmalloc (sizeof *ct);
2572   *ct = (struct ctables) {
2573     .look = pivot_table_look_unshare (pivot_table_look_ref (
2574                                         pivot_table_look_get_default ())),
2575     .vlabels = vlabels,
2576     .hide_threshold = 5,
2577   };
2578   ct->look->omit_empty = false;
2579
2580   if (!lex_force_match (lexer, T_SLASH))
2581     goto error;
2582
2583   while (!lex_match_id (lexer, "TABLE"))
2584     {
2585       if (lex_match_id (lexer, "FORMAT"))
2586         {
2587           double widths[2] = { SYSMIS, SYSMIS };
2588           double units_per_inch = 72.0;
2589
2590           while (lex_token (lexer) != T_SLASH)
2591             {
2592               if (lex_match_id (lexer, "MINCOLWIDTH"))
2593                 {
2594                   if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
2595                     goto error;
2596                 }
2597               else if (lex_match_id (lexer, "MAXCOLWIDTH"))
2598                 {
2599                   if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
2600                     goto error;
2601                 }
2602               else if (lex_match_id (lexer, "UNITS"))
2603                 {
2604                   lex_match (lexer, T_EQUALS);
2605                   if (lex_match_id (lexer, "POINTS"))
2606                     units_per_inch = 72.0;
2607                   else if (lex_match_id (lexer, "INCHES"))
2608                     units_per_inch = 1.0;
2609                   else if (lex_match_id (lexer, "CM"))
2610                     units_per_inch = 2.54;
2611                   else
2612                     {
2613                       lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
2614                       goto error;
2615                     }
2616                 }
2617               else if (lex_match_id (lexer, "EMPTY"))
2618                 {
2619                   free (ct->zero);
2620                   ct->zero = NULL;
2621
2622                   lex_match (lexer, T_EQUALS);
2623                   if (lex_match_id (lexer, "ZERO"))
2624                     {
2625                       /* Nothing to do. */
2626                     }
2627                   else if (lex_match_id (lexer, "BLANK"))
2628                     ct->zero = xstrdup ("");
2629                   else if (lex_force_string (lexer))
2630                     {
2631                       ct->zero = ss_xstrdup (lex_tokss (lexer));
2632                       lex_get (lexer);
2633                     }
2634                   else
2635                     goto error;
2636                 }
2637               else if (lex_match_id (lexer, "MISSING"))
2638                 {
2639                   lex_match (lexer, T_EQUALS);
2640                   if (!lex_force_string (lexer))
2641                     goto error;
2642
2643                   free (ct->missing);
2644                   ct->missing = (strcmp (lex_tokcstr (lexer), ".")
2645                                  ? ss_xstrdup (lex_tokss (lexer))
2646                                  : NULL);
2647                   lex_get (lexer);
2648                 }
2649               else
2650                 {
2651                   lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
2652                                        "UNITS", "EMPTY", "MISSING");
2653                   goto error;
2654                 }
2655             }
2656
2657           if (widths[0] != SYSMIS && widths[1] != SYSMIS
2658               && widths[0] > widths[1])
2659             {
2660               msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
2661               goto error;
2662             }
2663
2664           for (size_t i = 0; i < 2; i++)
2665             if (widths[i] != SYSMIS)
2666               {
2667                 int *wr = ct->look->width_ranges[TABLE_HORZ];
2668                 wr[i] = widths[i] / units_per_inch * 96.0;
2669                 if (wr[0] > wr[1])
2670                   wr[!i] = wr[i];
2671               }
2672         }
2673       else if (lex_match_id (lexer, "VLABELS"))
2674         {
2675           if (!lex_force_match_id (lexer, "VARIABLES"))
2676             goto error;
2677           lex_match (lexer, T_EQUALS);
2678
2679           struct variable **vars;
2680           size_t n_vars;
2681           if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
2682                                 PV_NO_SCRATCH))
2683             goto error;
2684
2685           if (!lex_force_match_id (lexer, "DISPLAY"))
2686             {
2687               free (vars);
2688               goto error;
2689             }
2690           lex_match (lexer, T_EQUALS);
2691
2692           enum ctables_vlabel vlabel;
2693           if (lex_match_id (lexer, "DEFAULT"))
2694             vlabel = (enum ctables_vlabel) settings_get_show_variables ();
2695           else if (lex_match_id (lexer, "NAME"))
2696             vlabel = CTVL_NAME;
2697           else if (lex_match_id (lexer, "LABEL"))
2698             vlabel = CTVL_LABEL;
2699           else if (lex_match_id (lexer, "BOTH"))
2700             vlabel = CTVL_BOTH;
2701           else if (lex_match_id (lexer, "NONE"))
2702             vlabel = CTVL_NONE;
2703           else
2704             {
2705               lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
2706                                    "BOTH", "NONE");
2707               free (vars);
2708               goto error;
2709             }
2710
2711           for (size_t i = 0; i < n_vars; i++)
2712             ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
2713           free (vars);
2714         }
2715       else if (lex_match_id (lexer, "MRSETS"))
2716         {
2717           if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
2718             goto error;
2719           lex_match (lexer, T_EQUALS);
2720           if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
2721             goto error;
2722         }
2723       else if (lex_match_id (lexer, "SMISSING"))
2724         {
2725           if (lex_match_id (lexer, "VARIABLE"))
2726             ct->smissing_listwise = false;
2727           else if (lex_match_id (lexer, "LISTWISE"))
2728             ct->smissing_listwise = true;
2729           else
2730             {
2731               lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
2732               goto error;
2733             }
2734         }
2735       /* XXX PCOMPUTE */
2736       else if (lex_match_id (lexer, "WEIGHT"))
2737         {
2738           if (!lex_force_match_id (lexer, "VARIABLE"))
2739             goto error;
2740           lex_match (lexer, T_EQUALS);
2741           ct->base_weight = parse_variable (lexer, dataset_dict (ds));
2742           if (!ct->base_weight)
2743             goto error;
2744         }
2745       else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
2746         {
2747           if (!lex_force_match_id (lexer, "COUNT"))
2748             goto error;
2749           lex_match (lexer, T_EQUALS);
2750           if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
2751             goto error;
2752           ct->hide_threshold = lex_integer (lexer);
2753           lex_get (lexer);
2754         }
2755       else
2756         {
2757           lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
2758                                "SMISSING", "PCOMPUTE", "PPROPERTIES",
2759                                "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
2760           goto error;
2761         }
2762
2763       if (!lex_force_match (lexer, T_SLASH))
2764         goto error;
2765     }
2766
2767   size_t allocated_tables = 0;
2768   do
2769     {
2770       if (ct->n_tables >= allocated_tables)
2771         ct->tables = x2nrealloc (ct->tables, &allocated_tables,
2772                                  sizeof *ct->tables);
2773
2774       struct ctables_category *cat = xmalloc (sizeof *cat);
2775       *cat = (struct ctables_category) {
2776         .type = CCT_VALUE,
2777         .include_missing = false,
2778         .sort_ascending = true,
2779       };
2780
2781       struct ctables_categories *c = xmalloc (sizeof *c);
2782       size_t n_vars = dict_get_n_vars (dataset_dict (ds));
2783       *c = (struct ctables_categories) {
2784         .n_refs = n_vars,
2785         .cats = cat,
2786         .n_cats = 1,
2787       };
2788
2789       struct ctables_categories **categories = xnmalloc (n_vars,
2790                                                          sizeof *categories);
2791       for (size_t i = 0; i < n_vars; i++)
2792         categories[i] = c;
2793
2794       struct ctables_table *t = xmalloc (sizeof *t);
2795       *t = (struct ctables_table) {
2796         .cells = HMAP_INITIALIZER (t->cells),
2797         .slabels_position = PIVOT_AXIS_COLUMN,
2798         .slabels_visible = true,
2799         .row_labels = CTLP_NORMAL,
2800         .col_labels = CTLP_NORMAL,
2801         .categories = categories,
2802         .n_categories = n_vars,
2803         .cilevel = 95,
2804       };
2805       for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2806         hmap_init (&t->domains[dt]);
2807       ct->tables[ct->n_tables++] = t;
2808
2809       lex_match (lexer, T_EQUALS);
2810       if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
2811         goto error;
2812       if (lex_match (lexer, T_BY))
2813         {
2814           if (!ctables_axis_parse (lexer, dataset_dict (ds),
2815                                    ct, t, PIVOT_AXIS_COLUMN))
2816             goto error;
2817
2818           if (lex_match (lexer, T_BY))
2819             {
2820               if (!ctables_axis_parse (lexer, dataset_dict (ds),
2821                                        ct, t, PIVOT_AXIS_LAYER))
2822                 goto error;
2823             }
2824         }
2825
2826       if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
2827           && !t->axes[PIVOT_AXIS_LAYER])
2828         {
2829           lex_error (lexer, _("At least one variable must be specified."));
2830           goto error;
2831         }
2832
2833       const struct ctables_axis *scales[PIVOT_N_AXES];
2834       size_t n_scales = 0;
2835       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2836         {
2837           scales[a] = find_scale (t->axes[a]);
2838           if (scales[a])
2839             n_scales++;
2840         }
2841       if (n_scales > 1)
2842         {
2843           msg (SE, _("Scale variables may appear only on one axis."));
2844           if (scales[PIVOT_AXIS_ROW])
2845             msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
2846                     _("This scale variable appears on the rows axis."));
2847           if (scales[PIVOT_AXIS_COLUMN])
2848             msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
2849                     _("This scale variable appears on the columns axis."));
2850           if (scales[PIVOT_AXIS_LAYER])
2851             msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
2852                     _("This scale variable appears on the layer axis."));
2853           goto error;
2854         }
2855
2856       const struct ctables_axis *summaries[PIVOT_N_AXES];
2857       size_t n_summaries = 0;
2858       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2859         {
2860           summaries[a] = (scales[a]
2861                           ? scales[a]
2862                           : find_categorical_summary_spec (t->axes[a]));
2863           if (summaries[a])
2864             n_summaries++;
2865         }
2866       if (n_summaries > 1)
2867         {
2868           msg (SE, _("Summaries may appear only on one axis."));
2869           if (summaries[PIVOT_AXIS_ROW])
2870             msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
2871                     _("This variable on the rows axis has a summary."));
2872           if (summaries[PIVOT_AXIS_COLUMN])
2873             msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
2874                     _("This variable on the columns axis has a summary."));
2875           if (summaries[PIVOT_AXIS_LAYER])
2876             msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
2877                     _("This variable on the layers axis has a summary."));
2878           goto error;
2879         }
2880       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2881         if (n_summaries ? summaries[a] : t->axes[a])
2882           {
2883             t->summary_axis = a;
2884             break;
2885           }
2886
2887       if (lex_token (lexer) == T_ENDCMD)
2888         break;
2889       if (!lex_force_match (lexer, T_SLASH))
2890         break;
2891
2892       while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
2893         {
2894           if (lex_match_id (lexer, "SLABELS"))
2895             {
2896               while (lex_token (lexer) != T_SLASH)
2897                 {
2898                   if (lex_match_id (lexer, "POSITION"))
2899                     {
2900                       lex_match (lexer, T_EQUALS);
2901                       if (lex_match_id (lexer, "COLUMN"))
2902                         t->slabels_position = PIVOT_AXIS_COLUMN;
2903                       else if (lex_match_id (lexer, "ROW"))
2904                         t->slabels_position = PIVOT_AXIS_ROW;
2905                       else if (lex_match_id (lexer, "LAYER"))
2906                         t->slabels_position = PIVOT_AXIS_LAYER;
2907                       else
2908                         {
2909                           lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
2910                           goto error;
2911                         }
2912                     }
2913                   else if (lex_match_id (lexer, "VISIBLE"))
2914                     {
2915                       lex_match (lexer, T_EQUALS);
2916                       if (!parse_bool (lexer, &t->slabels_visible))
2917                         goto error;
2918                     }
2919                   else
2920                     {
2921                       lex_error_expecting (lexer, "POSITION", "VISIBLE");
2922                       goto error;
2923                     }
2924                 }
2925             }
2926           else if (lex_match_id (lexer, "CLABELS"))
2927             {
2928               while (lex_token (lexer) != T_SLASH)
2929                 {
2930                   if (lex_match_id (lexer, "AUTO"))
2931                     t->row_labels = t->col_labels = CTLP_NORMAL;
2932                   else if (lex_match_id (lexer, "ROWLABELS"))
2933                     {
2934                       lex_match (lexer, T_EQUALS);
2935                       if (lex_match_id (lexer, "OPPOSITE"))
2936                         t->row_labels = CTLP_OPPOSITE;
2937                       else if (lex_match_id (lexer, "LAYER"))
2938                         t->row_labels = CTLP_LAYER;
2939                       else
2940                         {
2941                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
2942                           goto error;
2943                         }
2944                     }
2945                   else if (lex_match_id (lexer, "COLLABELS"))
2946                     {
2947                       lex_match (lexer, T_EQUALS);
2948                       if (lex_match_id (lexer, "OPPOSITE"))
2949                         t->col_labels = CTLP_OPPOSITE;
2950                       else if (lex_match_id (lexer, "LAYER"))
2951                         t->col_labels = CTLP_LAYER;
2952                       else
2953                         {
2954                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
2955                           goto error;
2956                         }
2957                     }
2958                   else
2959                     {
2960                       lex_error_expecting (lexer, "AUTO", "ROWLABELS",
2961                                            "COLLABELS");
2962                       goto error;
2963                     }
2964                 }
2965             }
2966           else if (lex_match_id (lexer, "CRITERIA"))
2967             {
2968               if (!lex_force_match_id (lexer, "CILEVEL"))
2969                 goto error;
2970               lex_match (lexer, T_EQUALS);
2971
2972               if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
2973                 goto error;
2974               t->cilevel = lex_number (lexer);
2975               lex_get (lexer);
2976             }
2977           else if (lex_match_id (lexer, "CATEGORIES"))
2978             {
2979               if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
2980                 goto error;
2981             }
2982           else if (lex_match_id (lexer, "TITLES"))
2983             {
2984               do
2985                 {
2986                   char **textp;
2987                   if (lex_match_id (lexer, "CAPTION"))
2988                     textp = &t->caption;
2989                   else if (lex_match_id (lexer, "CORNER"))
2990                     textp = &t->corner;
2991                   else if (lex_match_id (lexer, "TITLE"))
2992                     textp = &t->title;
2993                   else
2994                     {
2995                       lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
2996                       goto error;
2997                     }
2998                   lex_match (lexer, T_EQUALS);
2999
3000                   struct string s = DS_EMPTY_INITIALIZER;
3001                   while (lex_is_string (lexer))
3002                     {
3003                       if (!ds_is_empty (&s))
3004                         ds_put_byte (&s, ' ');
3005                       ds_put_substring (&s, lex_tokss (lexer));
3006                       lex_get (lexer);
3007                     }
3008                   free (*textp);
3009                   *textp = ds_steal_cstr (&s);
3010                 }
3011               while (lex_token (lexer) != T_SLASH
3012                      && lex_token (lexer) != T_ENDCMD);
3013             }
3014           else if (lex_match_id (lexer, "SIGTEST"))
3015             {
3016               if (!t->chisq)
3017                 {
3018                   t->chisq = xmalloc (sizeof *t->chisq);
3019                   *t->chisq = (struct ctables_chisq) {
3020                     .alpha = .05,
3021                     .include_mrsets = true,
3022                     .all_visible = true,
3023                   };
3024                 }
3025
3026               do
3027                 {
3028                   if (lex_match_id (lexer, "TYPE"))
3029                     {
3030                       lex_match (lexer, T_EQUALS);
3031                       if (!lex_force_match_id (lexer, "CHISQUARE"))
3032                         goto error;
3033                     }
3034                   else if (lex_match_id (lexer, "ALPHA"))
3035                     {
3036                       lex_match (lexer, T_EQUALS);
3037                       if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
3038                         goto error;
3039                       t->chisq->alpha = lex_number (lexer);
3040                       lex_get (lexer);
3041                     }
3042                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3043                     {
3044                       lex_match (lexer, T_EQUALS);
3045                       if (parse_bool (lexer, &t->chisq->include_mrsets))
3046                         goto error;
3047                     }
3048                   else if (lex_match_id (lexer, "CATEGORIES"))
3049                     {
3050                       lex_match (lexer, T_EQUALS);
3051                       if (lex_match_id (lexer, "ALLVISIBLE"))
3052                         t->chisq->all_visible = true;
3053                       else if (lex_match_id (lexer, "SUBTOTALS"))
3054                         t->chisq->all_visible = false;
3055                       else
3056                         {
3057                           lex_error_expecting (lexer,
3058                                                "ALLVISIBLE", "SUBTOTALS");
3059                           goto error;
3060                         }
3061                     }
3062                   else
3063                     {
3064                       lex_error_expecting (lexer, "TYPE", "ALPHA",
3065                                            "INCLUDEMRSETS", "CATEGORIES");
3066                       goto error;
3067                     }
3068                 }
3069               while (lex_token (lexer) != T_SLASH
3070                      && lex_token (lexer) != T_ENDCMD);
3071             }
3072           else if (lex_match_id (lexer, "COMPARETEST"))
3073             {
3074               if (!t->pairwise)
3075                 {
3076                   t->pairwise = xmalloc (sizeof *t->pairwise);
3077                   *t->pairwise = (struct ctables_pairwise) {
3078                     .type = PROP,
3079                     .alpha = { .05, .05 },
3080                     .adjust = BONFERRONI,
3081                     .include_mrsets = true,
3082                     .meansvariance_allcats = true,
3083                     .all_visible = true,
3084                     .merge = false,
3085                     .apa_style = true,
3086                     .show_sig = false,
3087                   };
3088                 }
3089
3090               do
3091                 {
3092                   if (lex_match_id (lexer, "TYPE"))
3093                     {
3094                       lex_match (lexer, T_EQUALS);
3095                       if (lex_match_id (lexer, "PROP"))
3096                         t->pairwise->type = PROP;
3097                       else if (lex_match_id (lexer, "MEAN"))
3098                         t->pairwise->type = MEAN;
3099                       else
3100                         {
3101                           lex_error_expecting (lexer, "PROP", "MEAN");
3102                           goto error;
3103                         }
3104                     }
3105                   else if (lex_match_id (lexer, "ALPHA"))
3106                     {
3107                       lex_match (lexer, T_EQUALS);
3108
3109                       if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3110                         goto error;
3111                       double a0 = lex_number (lexer);
3112                       lex_get (lexer);
3113
3114                       lex_match (lexer, T_COMMA);
3115                       if (lex_is_number (lexer))
3116                         {
3117                           if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3118                             goto error;
3119                           double a1 = lex_number (lexer);
3120                           lex_get (lexer);
3121
3122                           t->pairwise->alpha[0] = MIN (a0, a1);
3123                           t->pairwise->alpha[1] = MAX (a0, a1);
3124                         }
3125                       else
3126                         t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
3127                     }
3128                   else if (lex_match_id (lexer, "ADJUST"))
3129                     {
3130                       lex_match (lexer, T_EQUALS);
3131                       if (lex_match_id (lexer, "BONFERRONI"))
3132                         t->pairwise->adjust = BONFERRONI;
3133                       else if (lex_match_id (lexer, "BH"))
3134                         t->pairwise->adjust = BH;
3135                       else if (lex_match_id (lexer, "NONE"))
3136                         t->pairwise->adjust = 0;
3137                       else
3138                         {
3139                           lex_error_expecting (lexer, "BONFERRONI", "BH",
3140                                                "NONE");
3141                           goto error;
3142                         }
3143                     }
3144                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3145                     {
3146                       lex_match (lexer, T_EQUALS);
3147                       if (!parse_bool (lexer, &t->pairwise->include_mrsets))
3148                         goto error;
3149                     }
3150                   else if (lex_match_id (lexer, "MEANSVARIANCE"))
3151                     {
3152                       lex_match (lexer, T_EQUALS);
3153                       if (lex_match_id (lexer, "ALLCATS"))
3154                         t->pairwise->meansvariance_allcats = true;
3155                       else if (lex_match_id (lexer, "TESTEDCATS"))
3156                         t->pairwise->meansvariance_allcats = false;
3157                       else
3158                         {
3159                           lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
3160                           goto error;
3161                         }
3162                     }
3163                   else if (lex_match_id (lexer, "CATEGORIES"))
3164                     {
3165                       lex_match (lexer, T_EQUALS);
3166                       if (lex_match_id (lexer, "ALLVISIBLE"))
3167                         t->pairwise->all_visible = true;
3168                       else if (lex_match_id (lexer, "SUBTOTALS"))
3169                         t->pairwise->all_visible = false;
3170                       else
3171                         {
3172                           lex_error_expecting (lexer, "ALLVISIBLE",
3173                                                "SUBTOTALS");
3174                           goto error;
3175                         }
3176                     }
3177                   else if (lex_match_id (lexer, "MERGE"))
3178                     {
3179                       lex_match (lexer, T_EQUALS);
3180                       if (!parse_bool (lexer, &t->pairwise->merge))
3181                         goto error;
3182                     }
3183                   else if (lex_match_id (lexer, "STYLE"))
3184                     {
3185                       lex_match (lexer, T_EQUALS);
3186                       if (lex_match_id (lexer, "APA"))
3187                         t->pairwise->apa_style = true;
3188                       else if (lex_match_id (lexer, "SIMPLE"))
3189                         t->pairwise->apa_style = false;
3190                       else
3191                         {
3192                           lex_error_expecting (lexer, "APA", "SIMPLE");
3193                           goto error;
3194                         }
3195                     }
3196                   else if (lex_match_id (lexer, "SHOWSIG"))
3197                     {
3198                       lex_match (lexer, T_EQUALS);
3199                       if (!parse_bool (lexer, &t->pairwise->show_sig))
3200                         goto error;
3201                     }
3202                   else
3203                     {
3204                       lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
3205                                            "INCLUDEMRSETS", "MEANSVARIANCE",
3206                                            "CATEGORIES", "MERGE", "STYLE",
3207                                            "SHOWSIG");
3208                       goto error;
3209                     }
3210                 }
3211               while (lex_token (lexer) != T_SLASH
3212                      && lex_token (lexer) != T_ENDCMD);
3213             }
3214           else
3215             {
3216               lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
3217                                    "CRITERIA", "CATEGORIES", "TITLES",
3218                                    "SIGTEST", "COMPARETEST");
3219               goto error;
3220             }
3221         }
3222
3223       if (t->row_labels != CTLP_NORMAL && t->col_labels != CTLP_NORMAL)
3224         {
3225           msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
3226           goto error;
3227         }
3228
3229     }
3230   while (lex_token (lexer) != T_ENDCMD);
3231
3232   bool ok = ctables_execute (ds, ct);
3233   ctables_destroy (ct);
3234   return ok ? CMD_SUCCESS : CMD_FAILURE;
3235
3236 error:
3237   ctables_destroy (ct);
3238   return CMD_FAILURE;
3239 }
3240