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