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