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