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