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