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