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