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