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