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