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