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