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