all but last category
[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 "data/casereader.h"
20 #include "data/dataset.h"
21 #include "data/dictionary.h"
22 #include "data/mrset.h"
23 #include "language/command.h"
24 #include "language/lexer/format-parser.h"
25 #include "language/lexer/lexer.h"
26 #include "language/lexer/variable-parser.h"
27 #include "language/stats/freq.h"
28 #include "libpspp/array.h"
29 #include "libpspp/assertion.h"
30 #include "libpspp/hmap.h"
31 #include "libpspp/message.h"
32 #include "libpspp/string-array.h"
33 #include "output/pivot-table.h"
34
35 #include "gl/minmax.h"
36 #include "gl/xalloc.h"
37
38 #include "gettext.h"
39 #define _(msgid) gettext (msgid)
40 #define N_(msgid) (msgid)
41
42 enum ctables_vlabel
43   {
44     CTVL_DEFAULT = SETTINGS_VALUE_SHOW_DEFAULT,
45     CTVL_NAME = SETTINGS_VALUE_SHOW_VALUE,
46     CTVL_LABEL = SETTINGS_VALUE_SHOW_LABEL,
47     CTVL_BOTH = SETTINGS_VALUE_SHOW_BOTH,
48     CTVL_NONE,
49   };
50 static void UNUSED
51 ctables_vlabel_unique (enum ctables_vlabel vlabel)
52 {
53   /* This ensures that all of the values are unique. */
54   switch (vlabel)
55     {
56     case CTVL_DEFAULT:
57     case CTVL_NAME:
58     case CTVL_LABEL:
59     case CTVL_BOTH:
60     case CTVL_NONE:
61       abort ();
62     }
63 }
64
65 /* XXX:
66    - unweighted summaries (U*)
67    - lower confidence limits (*.LCL)
68    - upper confidence limits (*.UCL)
69    - standard error (*.SE)
70  */
71 #define SUMMARIES                                                       \
72     /* All variables. */                                                \
73     S(CTSF_COUNT, "COUNT", N_("Count"), CTF_COUNT, CTFA_ALL)            \
74     S(CTSF_ECOUNT, "ECOUNT", N_("Adjusted Count"), CTF_COUNT, CTFA_ALL) \
75     S(CTSF_ROWPCT_COUNT, "ROWPCT.COUNT", N_("Row %"), CTF_PERCENT, CTFA_ALL) \
76     S(CTSF_COLPCT_COUNT, "COLPCT.COUNT", N_("Column %"), CTF_PERCENT, CTFA_ALL) \
77     S(CTSF_TABLEPCT_COUNT, "TABLEPCT.COUNT", N_("Table %"), CTF_PERCENT, CTFA_ALL) \
78     S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT.COUNT", N_("Subtable %"), CTF_PERCENT, CTFA_ALL) \
79     S(CTSF_LAYERPCT_COUNT, "LAYERPCT.COUNT", N_("Layer %"), CTF_PERCENT, CTFA_ALL) \
80     S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT.COUNT", N_("Layer Row %"), CTF_PERCENT, CTFA_ALL) \
81     S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT.COUNT", N_("Layer Column %"), CTF_PERCENT, CTFA_ALL) \
82     S(CTSF_ROWPCT_VALIDN, "ROWPCT.VALIDN", N_("Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
83     S(CTSF_COLPCT_VALIDN, "COLPCT.VALIDN", N_("Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
84     S(CTSF_TABLEPCT_VALIDN, "TABLEPCT.VALIDN", N_("Table Valid N %"), CTF_PERCENT, CTFA_ALL) \
85     S(CTSF_SUBTABLEPCT_VALIDN, "SUBTABLEPCT.VALIDN", N_("Subtable Valid N %"), CTF_PERCENT, CTFA_ALL) \
86     S(CTSF_LAYERPCT_VALIDN, "LAYERPCT.VALIDN", N_("Layer Valid N %"), CTF_PERCENT, CTFA_ALL) \
87     S(CTSF_LAYERROWPCT_VALIDN, "LAYERROWPCT.VALIDN", N_("Layer Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
88     S(CTSF_LAYERCOLPCT_VALIDN, "LAYERCOLPCT.VALIDN", N_("Layer Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
89     S(CTSF_ROWPCT_TOTALN, "ROWPCT.TOTALN", N_("Row Total N %"), CTF_PERCENT, CTFA_ALL) \
90     S(CTSF_COLPCT_TOTALN, "COLPCT.TOTALN", N_("Column Total N %"), CTF_PERCENT, CTFA_ALL) \
91     S(CTSF_TABLEPCT_TOTALN, "TABLEPCT.TOTALN", N_("Table Total N %"), CTF_PERCENT, CTFA_ALL) \
92     S(CTSF_SUBTABLEPCT_TOTALN, "SUBTABLEPCT.TOTALN", N_("Subtable Total N %"), CTF_PERCENT, CTFA_ALL) \
93     S(CTSF_LAYERPCT_TOTALN, "LAYERPCT.TOTALN", N_("Layer Total N %"), CTF_PERCENT, CTFA_ALL) \
94     S(CTSF_LAYERROWPCT_TOTALN, "LAYERROWPCT.TOTALN", N_("Layer Row Total N %"), CTF_PERCENT, CTFA_ALL) \
95     S(CTSF_LAYERCOLPCT_TOTALN, "LAYERCOLPCT.TOTALN", N_("Layer Column Total N %"), CTF_PERCENT, CTFA_ALL) \
96                                                                         \
97     /* Scale variables, totals, and subtotals. */                       \
98     S(CTSF_MAXIMUM, "MAXIMUM", N_("Maximum"), CTF_GENERAL, CTFA_SCALE)  \
99     S(CTSF_MEAN, "MEAN", N_("Mean"), CTF_GENERAL, CTFA_SCALE)           \
100     S(CTSF_MEDIAN, "MEDIAN", N_("Median"), CTF_GENERAL, CTFA_SCALE)     \
101     S(CTSF_MINIMUM, "MINIMUM", N_("Minimum"), CTF_GENERAL, CTFA_SCALE)  \
102     S(CTSF_MISSING, "MISSING", N_("Missing"), CTF_GENERAL, CTFA_SCALE)  \
103     S(CTSF_MODE, "MODE", N_("Mode"), CTF_GENERAL, CTFA_SCALE)           \
104     S(CTSF_PTILE, "PTILE", N_("Percentile"), CTF_GENERAL, CTFA_SCALE)   \
105     S(CTSF_RANGE, "RANGE", N_("Range"), CTF_GENERAL, CTFA_SCALE)        \
106     S(CTSF_SEMEAN, "SEMEAN", N_("Std Error of Mean"), CTF_GENERAL, CTFA_SCALE) \
107     S(CTSF_STDDEV, "STDDEV", N_("Std Deviation"), CTF_GENERAL, CTFA_SCALE) \
108     S(CTSF_SUM, "SUM", N_("Sum"), CTF_GENERAL, CTFA_SCALE)              \
109     S(CSTF_TOTALN, "TOTALN", N_("Total N"), CTF_COUNT, CTFA_SCALE)      \
110     S(CTSF_ETOTALN, "ETOTALN", N_("Adjusted Total N"), CTF_COUNT, CTFA_SCALE) \
111     S(CTSF_VALIDN, "VALIDN", N_("Valid N"), CTF_COUNT, CTFA_SCALE)      \
112     S(CTSF_EVALIDN, "EVALIDN", N_("Adjusted Valid N"), CTF_COUNT, CTFA_SCALE) \
113     S(CTSF_VARIANCE, "VARIANCE", N_("Variance"), CTF_GENERAL, CTFA_SCALE) \
114     S(CTSF_ROWPCT_SUM, "ROWPCT.SUM", N_("Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
115     S(CTSF_COLPCT_SUM, "COLPCT.SUM", N_("Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
116     S(CTSF_TABLEPCT_SUM, "TABLEPCT.SUM", N_("Table Sum %"), CTF_PERCENT, CTFA_SCALE) \
117     S(CTSF_SUBTABLEPCT_SUM, "SUBTABLEPCT.SUM", N_("Subtable Sum %"), CTF_PERCENT, CTFA_SCALE) \
118     S(CTSF_LAYERPCT_SUM, "LAYERPCT.SUM", N_("Layer Sum %"), CTF_PERCENT, CTFA_SCALE) \
119     S(CTSF_LAYERROWPCT_SUM, "LAYERROWPCT.SUM", N_("Layer Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
120     S(CTSF_LAYERCOLPCT_SUM, "LAYERCOLPCT.SUM", N_("Layer Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
121                                                                         \
122     /* Multiple response sets. */                                       \
123   S(CTSF_RESPONSES, "RESPONSES", N_("Responses"), CTF_COUNT, CTFA_MRSETS) \
124     S(CTSF_ROWPCT_RESPONSES, "ROWPCT.RESPONSES", N_("Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
125     S(CTSF_COLPCT_RESPONSES, "COLPCT.RESPONSES", N_("Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
126     S(CTSF_TABLEPCT_RESPONSES, "TABLEPCT.RESPONSES", N_("Table Responses %"), CTF_PERCENT, CTFA_MRSETS) \
127     S(CTSF_SUBTABLEPCT_RESPONSES, "SUBTABLEPCT.RESPONSES", N_("Subtable Responses %"), CTF_PERCENT, CTFA_MRSETS) \
128     S(CTSF_LAYERPCT_RESPONSES, "LAYERPCT.RESPONSES", N_("Layer Responses %"), CTF_PERCENT, CTFA_MRSETS) \
129     S(CTSF_LAYERROWPCT_RESPONSES, "LAYERROWPCT.RESPONSES", N_("Layer Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
130     S(CTSF_LAYERCOLPCT_RESPONSES, "LAYERCOLPCT.RESPONSES", N_("Layer Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
131     S(CTSF_ROWPCT_RESPONSES_COUNT, "ROWPCT.RESPONSES.COUNT", N_("Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
132     S(CTSF_COLPCT_RESPONSES_COUNT, "COLPCT.RESPONSES.COUNT", N_("Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
133     S(CTSF_TABLEPCT_RESPONSES_COUNT, "TABLEPCT.RESPONSES.COUNT", N_("Table Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
134     S(CTSF_SUBTABLEPCT_RESPONSES_COUNT, "SUBTABLEPCT.RESPONSES.COUNT", N_("Subtable Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
135     S(CTSF_LAYERPCT_RESPONSES_COUNT, "LAYERPCT.RESPONSES.COUNT", N_("Layer Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
136     S(CTSF_LAYERROWPCT_RESPONSES_COUNT, "LAYERROWPCT.RESPONSES.COUNT", N_("Layer Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
137     S(CTSF_LAYERCOLPCT_RESPONSES_COUNT, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
138     S(CTSF_ROWPCT_COUNT_RESPONSES, "ROWPCT.COUNT.RESPONSES", N_("Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
139     S(CTSF_COLPCT_COUNT_RESPONSES, "COLPCT.COUNT.RESPONSES", N_("Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
140     S(CTSF_TABLEPCT_COUNT_RESPONSES, "TABLEPCT.COUNT.RESPONSES", N_("Table Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
141     S(CTSF_SUBTABLEPCT_COUNT_RESPONSES, "SUBTABLEPCT.COUNT.RESPONSES", N_("Subtable Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
142     S(CTSF_LAYERPCT_COUNT_RESPONSES, "LAYERPCT.COUNT.RESPONSES", N_("Layer Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
143     S(CTSF_LAYERROWPCT_COUNT_RESPONSES, "LAYERROWPCT.COUNT.RESPONSES", N_("Layer Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
144     S(CTSF_LAYERCOLPCT_COUNT_RESPONSES, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS)
145
146 enum ctables_summary_function
147   {
148 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) ENUM,
149     SUMMARIES
150 #undef S
151   };
152
153 enum {
154 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) +1
155   N_CTSF_FUNCTIONS = SUMMARIES
156 #undef S
157 };
158
159 struct ctables
160   {
161     struct pivot_table_look *look;
162
163     /* If this is NULL, zeros are displayed using the normal print format.
164        Otherwise, this string is displayed. */
165     char *zero;
166
167     /* If this is NULL, missing values are displayed using the normal print
168        format.  Otherwise, this string is displayed. */
169     char *missing;
170
171     /* Indexed by variable dictionary index. */
172     enum ctables_vlabel *vlabels;
173
174     bool mrsets_count_duplicates; /* MRSETS. */
175     bool smissing_listwise;       /* SMISSING. */
176     struct variable *base_weight; /* WEIGHT. */
177     int hide_threshold;           /* HIDESMALLCOUNTS. */
178
179     struct ctables_table *tables;
180     size_t n_tables;
181   };
182
183 struct ctables_postcompute
184   {
185     struct hmap_node hmap_node; /* In struct ctables's 'pcompute' hmap. */
186     const char *name;           /* Name, without leading &. */
187
188     struct ctables_postcompute_expr *expr;
189     char *label;
190     /* XXX FORMAT */
191     bool hide_source_cats;
192   };
193
194 struct ctables_postcompute_expr
195   {
196     enum ctables_postcompute_op
197       {
198         /* Terminals. */
199         CTPO_CAT_NUMBER,
200         CTPO_CAT_STRING,
201         CTPO_CAT_RANGE,
202         CTPO_CAT_MISSING,
203         /* XXX OTHERNM */
204         /* XXX SUBTOTAL and HSUBTOTAL */
205
206         /* Nonterminals. */
207         CTPO_ADD,
208         CTPO_SUB,
209         CTPO_MUL,
210         CTPO_DIV,
211         CTPO_POW,
212       }
213     op;
214
215     union
216       {
217         /* CTPO_CAT_NUMBER, CTPO_NUMBER. */
218         double number;
219
220         /* CTPO_CAT_RANGE.
221
222            XXX what about string ranges? */
223         double range[2];
224
225         /* CTPO_ADD, CTPO_SUB, CTPO_MUL, CTPO_DIV, CTPO_POW. */
226         struct ctables_postcompute_expr *subs[2];
227       };
228   };
229
230 enum ctables_label_position
231   {
232     CTLP_NORMAL,
233     CTLP_OPPOSITE,
234     CTLP_LAYER,
235   };
236
237 struct ctables_table
238   {
239     struct ctables_axis *axes[PIVOT_N_AXES];
240
241     enum pivot_axis_type slabels_position;
242     bool slabels_visible;
243
244     enum ctables_label_position row_labels;
245     enum ctables_label_position col_labels;
246
247     /* Indexed by variable dictionary index. */
248     struct ctables_categories **categories;
249     size_t n_categories;
250
251     double cilevel;
252
253     char *caption;
254     char *corner;
255     char *title;
256
257     struct ctables_chisq *chisq;
258     struct ctables_pairwise *pairwise;
259
260     struct ctables_freqtab **fts;
261     size_t n_fts;
262   };
263
264 struct ctables_var
265   {
266     bool is_mrset;
267     union
268       {
269         struct variable *var;
270         const struct mrset *mrset;
271       };
272   };
273
274 static const struct fmt_spec *
275 ctables_var_get_print_format (const struct ctables_var *var)
276 {
277   return (var->is_mrset
278           ? var_get_print_format (var->mrset->vars[0])
279           : var_get_print_format (var->var));
280 }
281
282 static const char *
283 ctables_var_name (const struct ctables_var *var)
284 {
285   return var->is_mrset ? var->mrset->name : var_get_name (var->var);
286 }
287
288 struct ctables_categories
289   {
290     size_t n_refs;
291
292     /* Explicit categories. */
293     struct ctables_cat_value *values;
294     size_t n_values;
295
296     /* Implicit categories. */
297     bool sort_ascending;
298     bool include_missing;
299     enum { CTCS_VALUE, CTCS_LABEL, CTCS_FUNCTION } key;
300     enum ctables_summary_function sort_func;
301     struct variable *sort_func_var;
302     double percentile;
303
304     /* Totals. */
305     bool show_totals;
306     bool totals_before;
307     char *total_label;
308
309     /* Empty categories. */
310     bool show_empty;
311   };
312
313 struct ctables_cat_value
314   {
315     enum ctables_cat_value_type
316       {
317         CCVT_NUMBER,
318         CCVT_STRING,
319         CCVT_RANGE,
320         CCVT_MISSING,
321         CCVT_OTHERNM,
322         CCVT_SUBTOTAL,
323         CCVT_HSUBTOTAL,
324       }
325     type;
326
327     union
328       {
329         double number;          /* CCVT_NUMBER. */
330         char *string;           /* CCVT_STRING. */
331         double range[2];        /* CCVT_RANGE. */
332         char *subtotal_label;   /* CCVT_SUBTOTAL, CCVT_HSUBTOTAL. */
333       };
334   };
335
336 static void
337 ctables_cat_value_uninit (struct ctables_cat_value *cv)
338 {
339   if (!cv)
340     return;
341
342   switch (cv->type)
343     {
344     case CCVT_NUMBER:
345     case CCVT_RANGE:
346     case CCVT_MISSING:
347     case CCVT_OTHERNM:
348       break;
349
350     case CCVT_STRING:
351       free (cv->string);
352       break;
353
354     case CCVT_SUBTOTAL:
355     case CCVT_HSUBTOTAL:
356       free (cv->subtotal_label);
357     }
358 }
359
360 static void
361 ctables_categories_unref (struct ctables_categories *c)
362 {
363   if (!c)
364     return;
365
366   assert (c->n_refs > 0);
367   if (--c->n_refs)
368     return;
369
370   for (size_t i = 0; i < c->n_values; i++)
371     ctables_cat_value_uninit (&c->values[i]);
372   free (c->values);
373   free (c->total_label);
374   free (c);
375 }
376
377 /* Chi-square test (SIGTEST). */
378 struct ctables_chisq
379   {
380     double alpha;
381     bool include_mrsets;
382     bool all_visible;
383   };
384
385 /* Pairwise comparison test (COMPARETEST). */
386 struct ctables_pairwise
387   {
388     enum { PROP, MEAN } type;
389     double alpha[2];
390     bool include_mrsets;
391     bool meansvariance_allcats;
392     bool all_visible;
393     enum { BONFERRONI = 1, BH } adjust;
394     bool merge;
395     bool apa_style;
396     bool show_sig;
397   };
398
399 struct ctables_axis
400   {
401     enum ctables_axis_op
402       {
403         /* Terminals. */
404         CTAO_VAR,
405
406         /* Nonterminals. */
407         CTAO_STACK,             /* + */
408         CTAO_NEST,              /* > */
409       }
410     op;
411
412     union
413       {
414         /* Terminals. */
415         struct
416           {
417             struct ctables_var var;
418             bool scale;
419             struct ctables_summary *summaries;
420             size_t n_summaries;
421             size_t allocated_summaries;
422           };
423
424         /* Nonterminals. */
425         struct ctables_axis *subs[2];
426       };
427
428     struct msg_location *loc;
429   };
430
431 static void ctables_axis_destroy (struct ctables_axis *);
432
433 enum ctables_format
434   {
435     CTF_COUNT,
436     CTF_PERCENT,
437     CTF_GENERAL
438   };
439
440 enum ctables_function_availability
441   {
442     CTFA_ALL,                /* Any variables. */
443     CTFA_SCALE,              /* Only scale variables, totals, and subtotals. */
444     CTFA_MRSETS,             /* Only multiple-response sets */
445   };
446
447 struct ctables_summary
448   {
449     enum ctables_summary_function function;
450     double percentile;          /* CTSF_PTILE only. */
451     char *label;
452     struct fmt_spec format;     /* XXX extra CTABLES formats */
453   };
454
455 static void
456 ctables_summary_uninit (struct ctables_summary *s)
457 {
458   if (s)
459     free (s->label);
460 }
461
462 static bool
463 parse_col_width (struct lexer *lexer, const char *name, double *width)
464 {
465   lex_match (lexer, T_EQUALS);
466   if (lex_match_id (lexer, "DEFAULT"))
467     *width = SYSMIS;
468   else if (lex_force_num_range_closed (lexer, name, 0, DBL_MAX))
469     {
470       *width = lex_number (lexer);
471       lex_get (lexer);
472     }
473   else
474     return false;
475
476   return true;
477 }
478
479 static bool
480 parse_bool (struct lexer *lexer, bool *b)
481 {
482   if (lex_match_id (lexer, "NO"))
483     *b = false;
484   else if (lex_match_id (lexer, "YES"))
485     *b = true;
486   else
487     {
488       lex_error_expecting (lexer, "YES", "NO");
489       return false;
490     }
491   return true;
492 }
493
494 static enum ctables_function_availability
495 ctables_function_availability (enum ctables_summary_function f)
496 {
497   static enum ctables_function_availability availability[] = {
498 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = AVAILABILITY,
499     SUMMARIES
500 #undef S
501   };
502
503   return availability[f];
504 }
505
506 static bool
507 parse_ctables_summary_function (struct lexer *lexer,
508                                 enum ctables_summary_function *f)
509 {
510   struct pair
511     {
512       enum ctables_summary_function function;
513       struct substring name;
514     };
515   static struct pair names[] = {
516 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) \
517     { ENUM, SS_LITERAL_INITIALIZER (NAME) },
518     SUMMARIES
519
520     /* The .COUNT suffix may be omitted. */
521     S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _, _)
522     S(CTSF_COLPCT_COUNT, "COLPCT", _, _, _)
523     S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _, _)
524     S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _, _)
525     S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _, _)
526     S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _, _)
527     S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _, _)
528 #undef S
529   };
530
531   if (!lex_force_id (lexer))
532     return false;
533
534   for (size_t i = 0; i < sizeof names / sizeof *names; i++)
535     if (ss_equals_case (names[i].name, lex_tokss (lexer)))
536       {
537         *f = names[i].function;
538         lex_get (lexer);
539         return true;
540       }
541
542   lex_error (lexer, _("Expecting summary function name."));
543   return false;
544 }
545
546 static void
547 ctables_axis_destroy (struct ctables_axis *axis)
548 {
549   if (!axis)
550     return;
551
552   switch (axis->op)
553     {
554     case CTAO_VAR:
555       for (size_t i = 0; i < axis->n_summaries; i++)
556         ctables_summary_uninit (&axis->summaries[i]);
557       free (axis->summaries);
558       break;
559
560     case CTAO_STACK:
561     case CTAO_NEST:
562       ctables_axis_destroy (axis->subs[0]);
563       ctables_axis_destroy (axis->subs[1]);
564       break;
565     }
566   msg_location_destroy (axis->loc);
567   free (axis);
568 }
569
570 static struct ctables_axis *
571 ctables_axis_new_nonterminal (enum ctables_axis_op op,
572                               struct ctables_axis *sub0,
573                               struct ctables_axis *sub1,
574                               struct lexer *lexer, int start_ofs)
575 {
576   struct ctables_axis *axis = xmalloc (sizeof *axis);
577   *axis = (struct ctables_axis) {
578     .op = op,
579     .subs = { sub0, sub1 },
580     .loc = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
581   };
582   return axis;
583 }
584
585 struct ctables_axis_parse_ctx
586   {
587     struct lexer *lexer;
588     struct dictionary *dict;
589     struct ctables *ct;
590     struct ctables_table *t;
591   };
592
593 static struct fmt_spec
594 ctables_summary_default_format (enum ctables_summary_function function,
595                                 const struct ctables_var *var)
596 {
597   static const enum ctables_format default_formats[] = {
598 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
599     SUMMARIES
600 #undef S
601   };
602   switch (default_formats[function])
603     {
604     case CTF_COUNT:
605       return (struct fmt_spec) { .type = FMT_F, .w = 40 };
606
607     case CTF_PERCENT:
608       return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
609
610     case CTF_GENERAL:
611       return *ctables_var_get_print_format (var);
612
613     default:
614       NOT_REACHED ();
615     }
616 }
617
618 static const char *
619 ctables_summary_function_name (enum ctables_summary_function function)
620 {
621   static const char *names[] = {
622 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = NAME,
623     SUMMARIES
624 #undef S
625   };
626   return names[function];
627 }
628
629 static bool
630 add_summary (struct ctables_axis *axis,
631              enum ctables_summary_function function, double percentile,
632              const char *label, const struct fmt_spec *format,
633              const struct msg_location *loc)
634 {
635   if (axis->op == CTAO_VAR)
636     {
637       if (axis->n_summaries >= axis->allocated_summaries)
638         axis->summaries = x2nrealloc (axis->summaries,
639                                       &axis->allocated_summaries,
640                                       sizeof *axis->summaries);
641
642       const char *function_name = ctables_summary_function_name (function);
643       const char *var_name = ctables_var_name (&axis->var);
644       switch (ctables_function_availability (function))
645         {
646         case CTFA_MRSETS:
647           if (!axis->var.is_mrset)
648             {
649               msg_at (SE, loc, _("Summary function %s applies only to multiple "
650                                  "response sets."), function_name);
651               msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
652                       var_name);
653               return false;
654             }
655           break;
656
657         case CTFA_SCALE:
658           if (!axis->scale)
659             {
660               msg_at (SE, loc,
661                       _("Summary function %s applies only to scale variables."),
662                       function_name);
663               msg_at (SN, axis->loc, _("'%s' is not a scale variable."),
664                       var_name);
665               return false;
666             }
667           break;
668
669         case CTFA_ALL:
670           break;
671         }
672
673       struct ctables_summary *dst = &axis->summaries[axis->n_summaries++];
674       *dst = (struct ctables_summary) {
675         .function = function,
676         .percentile = percentile,
677         .label = xstrdup (label),
678         .format = (format ? *format
679                    : ctables_summary_default_format (function, &axis->var)),
680       };
681       return true;
682     }
683   else
684     {
685       for (size_t i = 0; i < 2; i++)
686         if (!add_summary (axis->subs[i], function, percentile, label, format,
687                           loc))
688           return false;
689       return true;
690     }
691 }
692
693 static struct ctables_axis *ctables_axis_parse_stack (
694   struct ctables_axis_parse_ctx *);
695
696 static bool
697 ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
698                    struct ctables_var *var)
699 {
700   if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
701     {
702       *var = (struct ctables_var) {
703         .is_mrset = true,
704         .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
705       };
706       if (!var->mrset)
707         {
708           lex_error (lexer, _("'%s' does not name a multiple-response set "
709                               "in the active file dictionary."),
710                      lex_tokcstr (lexer));
711           return false;
712         }
713       lex_get (lexer);
714       return true;
715     }
716   else
717     {
718       *var = (struct ctables_var) {
719         .is_mrset = false,
720         .var = parse_variable (lexer, dict),
721       };
722       return var->var != NULL;
723     }
724 }
725
726 static struct ctables_axis *
727 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
728 {
729   if (lex_match (ctx->lexer, T_LPAREN))
730     {
731       struct ctables_axis *sub = ctables_axis_parse_stack (ctx);
732       if (!sub || !lex_force_match (ctx->lexer, T_RPAREN))
733         {
734           ctables_axis_destroy (sub);
735           return NULL;
736         }
737       return sub;
738     }
739
740   if (!lex_force_id (ctx->lexer))
741     return NULL;
742
743   int start_ofs = lex_ofs (ctx->lexer);
744   struct ctables_var var;
745   if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
746     return NULL;
747
748   struct ctables_axis *axis = xmalloc (sizeof *axis);
749   *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
750
751   /* XXX should figure out default measures by reading data */
752   axis->scale = (var.is_mrset ? false
753                  : lex_match_phrase (ctx->lexer, "[S]") ? true
754                  : lex_match_phrase (ctx->lexer, "[C]") ? false
755                  : var_get_measure (var.var) == MEASURE_SCALE);
756   axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
757                                 lex_ofs (ctx->lexer) - 1);
758   return axis;
759 }
760
761 static struct ctables_axis *
762 ctables_axis_parse_postfix (struct ctables_axis_parse_ctx *ctx)
763 {
764   struct ctables_axis *sub = ctables_axis_parse_primary (ctx);
765   if (!sub || !lex_match (ctx->lexer, T_LBRACK))
766     return sub;
767
768   do
769     {
770       int start_ofs = lex_ofs (ctx->lexer);
771
772       /* Parse function. */
773       enum ctables_summary_function function;
774       if (!parse_ctables_summary_function (ctx->lexer, &function))
775         goto error;
776
777       /* Parse percentile. */
778       double percentile = 0;
779       if (function == CTSF_PTILE)
780         {
781           if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
782             goto error;
783           percentile = lex_number (ctx->lexer);
784           lex_get (ctx->lexer);
785         }
786
787       /* Parse label. */
788       char *label;
789       if (lex_is_string (ctx->lexer))
790         {
791           label = ss_xstrdup (lex_tokss (ctx->lexer));
792           lex_get (ctx->lexer);
793         }
794       else if (function == CTSF_PTILE)
795         label = xasprintf (_("Percentile %.2f"), percentile);
796       else
797         {
798           static const char *default_labels[] = {
799 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = LABEL,
800             SUMMARIES
801 #undef S
802           };
803           label = xstrdup (gettext (default_labels[function]));
804         }
805
806       /* Parse format. */
807       struct fmt_spec format;
808       const struct fmt_spec *formatp;
809       if (lex_token (ctx->lexer) == T_ID)
810         {
811           if (!parse_format_specifier (ctx->lexer, &format)
812               || !fmt_check_output (&format)
813               || !fmt_check_type_compat (&format, VAL_NUMERIC))
814             {
815               free (label);
816               goto error;
817             }
818           formatp = &format;
819         }
820       else
821         formatp = NULL;
822
823       struct msg_location *loc = lex_ofs_location (ctx->lexer, start_ofs,
824                                                    lex_ofs (ctx->lexer) - 1);
825       add_summary (sub, function, percentile, label, formatp, loc);
826       free (label);
827       msg_location_destroy (loc);
828
829       lex_match (ctx->lexer, T_COMMA);
830     }
831   while (!lex_match (ctx->lexer, T_RBRACK));
832
833   return sub;
834
835 error:
836   ctables_axis_destroy (sub);
837   return NULL;
838 }
839
840 static const struct ctables_axis *
841 find_scale (const struct ctables_axis *axis)
842 {
843   if (!axis)
844     return NULL;
845   else if (axis->op == CTAO_VAR)
846     {
847       if (axis->scale)
848         {
849           assert (!axis->var.is_mrset);
850           return axis;
851         }
852       else
853         return NULL;
854     }
855   else
856     {
857       for (size_t i = 0; i < 2; i++)
858         {
859           const struct ctables_axis *scale = find_scale (axis->subs[i]);
860           if (scale)
861             return scale;
862         }
863       return NULL;
864     }
865 }
866
867 static const struct ctables_axis *
868 find_categorical_summary (const struct ctables_axis *axis)
869 {
870   if (!axis)
871     return NULL;
872   else if (axis->op == CTAO_VAR)
873     return !axis->scale && axis->n_summaries ? axis : NULL;
874   else
875     {
876       for (size_t i = 0; i < 2; i++)
877         {
878           const struct ctables_axis *sum
879             = find_categorical_summary (axis->subs[i]);
880           if (sum)
881             return sum;
882         }
883       return NULL;
884     }
885 }
886
887 static struct ctables_axis *
888 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
889 {
890   int start_ofs = lex_ofs (ctx->lexer);
891   struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
892   if (!lhs)
893     return NULL;
894
895   while (lex_match (ctx->lexer, T_GT))
896     {
897       struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
898       if (!rhs)
899         return NULL;
900
901       struct ctables_axis *nest = ctables_axis_new_nonterminal (
902         CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
903
904       const struct ctables_axis *outer_scale = find_scale (lhs);
905       const struct ctables_axis *inner_scale = find_scale (rhs);
906       if (outer_scale && inner_scale)
907         {
908           msg_at (SE, nest->loc, _("Cannot nest scale variables."));
909           msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
910           msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
911           ctables_axis_destroy (nest);
912           return NULL;
913         }
914
915       const struct ctables_axis *outer_sum = find_categorical_summary (lhs);
916       if (outer_sum)
917         {
918           msg_at (SE, nest->loc,
919                   _("Summaries may only be requested for categorical variables "
920                     "at the innermost nesting level."));
921           msg_at (SN, outer_sum->loc,
922                   _("This outer categorical variable has a summary."));
923           ctables_axis_destroy (nest);
924           return NULL;
925         }
926
927       lhs = nest;
928     }
929
930   return lhs;
931 }
932
933 static struct ctables_axis *
934 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
935 {
936   int start_ofs = lex_ofs (ctx->lexer);
937   struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
938   if (!lhs)
939     return NULL;
940
941   while (lex_match (ctx->lexer, T_PLUS))
942     {
943       struct ctables_axis *rhs = ctables_axis_parse_nest (ctx);
944       if (!rhs)
945         return NULL;
946
947       lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
948                                           ctx->lexer, start_ofs);
949     }
950
951   return lhs;
952 }
953
954 static bool
955 ctables_axis_parse (struct lexer *lexer, struct dictionary *dict,
956                     struct ctables *ct, struct ctables_table *t,
957                     enum pivot_axis_type a)
958 {
959   if (lex_token (lexer) == T_BY
960       || lex_token (lexer) == T_SLASH
961       || lex_token (lexer) == T_ENDCMD)
962     return true;
963
964   struct ctables_axis_parse_ctx ctx = {
965     .lexer = lexer,
966     .dict = dict,
967     .ct = ct,
968     .t = t
969   };
970   t->axes[a] = ctables_axis_parse_stack (&ctx);
971   return t->axes[a] != NULL;
972 }
973
974 static void
975 ctables_chisq_destroy (struct ctables_chisq *chisq)
976 {
977   free (chisq);
978 }
979
980 static void
981 ctables_pairwise_destroy (struct ctables_pairwise *pairwise)
982 {
983   free (pairwise);
984 }
985
986 static void
987 ctables_table_uninit (struct ctables_table *t)
988 {
989   if (!t)
990     return;
991
992   for (size_t i = 0; i < t->n_categories; i++)
993     ctables_categories_unref (t->categories[i]);
994   free (t->categories);
995
996   ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
997   ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
998   ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
999   free (t->caption);
1000   free (t->corner);
1001   free (t->title);
1002   ctables_chisq_destroy (t->chisq);
1003   ctables_pairwise_destroy (t->pairwise);
1004 }
1005
1006 static void
1007 ctables_destroy (struct ctables *ct)
1008 {
1009   if (!ct)
1010     return;
1011
1012   pivot_table_look_unref (ct->look);
1013   free (ct->zero);
1014   free (ct->missing);
1015   free (ct->vlabels);
1016   for (size_t i = 0; i < ct->n_tables; i++)
1017     ctables_table_uninit (&ct->tables[i]);
1018   free (ct->tables);
1019   free (ct);
1020 }
1021
1022 static struct ctables_cat_value
1023 ccvt_range (double low, double high)
1024 {
1025   return (struct ctables_cat_value) {
1026     .type = CCVT_RANGE,
1027     .range = { low, high }
1028   };
1029 }
1030
1031 static bool
1032 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
1033                                 struct ctables_table *t)
1034 {
1035   if (!lex_match_id (lexer, "VARIABLES"))
1036     return false;
1037   lex_match (lexer, T_EQUALS);
1038
1039   struct variable **vars;
1040   size_t n_vars;
1041   if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
1042     return false;
1043
1044   struct ctables_categories *c = xmalloc (sizeof *c);
1045   *c = (struct ctables_categories) { .n_refs = n_vars };
1046   for (size_t i = 0; i < n_vars; i++)
1047     {
1048       struct ctables_categories **cp
1049         = &t->categories[var_get_dict_index (vars[i])];
1050       ctables_categories_unref (*cp);
1051       *cp = c;
1052     }
1053   free (vars);
1054
1055   if (lex_match (lexer, T_LBRACK))
1056     {
1057       size_t allocated_values = 0;
1058       do
1059         {
1060           if (c->n_values >= allocated_values)
1061             c->values = x2nrealloc (c->values, &allocated_values,
1062                                     sizeof *c->values);
1063
1064           struct ctables_cat_value *v = &c->values[c->n_values];
1065           if (lex_match_id (lexer, "OTHERNM"))
1066             v->type = CCVT_OTHERNM;
1067           else if (lex_match_id (lexer, "MISSING"))
1068             v->type = CCVT_MISSING;
1069           else if (lex_match_id (lexer, "SUBTOTAL"))
1070             *v = (struct ctables_cat_value)
1071               { .type = CCVT_SUBTOTAL, .subtotal_label = NULL };
1072           else if (lex_match_id (lexer, "HSUBTOTAL"))
1073             *v = (struct ctables_cat_value)
1074               { .type = CCVT_HSUBTOTAL, .subtotal_label = NULL };
1075           else if (lex_match_id (lexer, "LO"))
1076             {
1077               if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
1078                 return false;
1079               *v = ccvt_range (-DBL_MAX, lex_number (lexer));
1080               lex_get (lexer);
1081             }
1082           else if (lex_is_number (lexer))
1083             {
1084               double number = lex_number (lexer);
1085               lex_get (lexer);
1086               if (lex_match_id (lexer, "THRU"))
1087                 {
1088                   v->type = CCVT_RANGE;
1089                   v->range[0] = number;
1090                   if (lex_match_id (lexer, "HI"))
1091                     *v = ccvt_range (number, DBL_MAX);
1092                   else
1093                     {
1094                       if (!lex_force_num (lexer))
1095                         return false;
1096                       *v = ccvt_range (number, lex_number (lexer));
1097                       lex_get (lexer);
1098                     }
1099                 }
1100               else
1101                 *v = (struct ctables_cat_value) {
1102                   .type = CCVT_NUMBER,
1103                   .number = number
1104                 };
1105             }
1106           else if (lex_is_string (lexer))
1107             {
1108               *v = (struct ctables_cat_value) {
1109                 .type = CCVT_STRING,
1110                 .string = ss_xstrdup (lex_tokss (lexer)),
1111               };
1112               lex_get (lexer);
1113             }
1114           else
1115             {
1116               lex_error (lexer, NULL);
1117               return false;
1118             }
1119
1120           if ((v->type == CCVT_SUBTOTAL || v->type == CCVT_HSUBTOTAL)
1121               && lex_match (lexer, T_EQUALS))
1122             {
1123               if (!lex_force_string (lexer))
1124                 return false;
1125
1126               v->subtotal_label = ss_xstrdup (lex_tokss (lexer));
1127               lex_get (lexer);
1128             }
1129
1130           c->n_values++;
1131           lex_match (lexer, T_COMMA);
1132         }
1133       while (!lex_match (lexer, T_RBRACK));
1134     }
1135
1136   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
1137     {
1138       if (!c->n_values && lex_match_id (lexer, "ORDER"))
1139         {
1140           lex_match (lexer, T_EQUALS);
1141           if (lex_match_id (lexer, "A"))
1142             c->sort_ascending = true;
1143           else if (lex_match_id (lexer, "D"))
1144             c->sort_ascending = false;
1145           else
1146             {
1147               lex_error_expecting (lexer, "A", "D");
1148               return false;
1149             }
1150         }
1151       else if (!c->n_values && lex_match_id (lexer, "KEY"))
1152         {
1153           lex_match (lexer, T_EQUALS);
1154           if (lex_match_id (lexer, "VALUE"))
1155             c->key = CTCS_VALUE;
1156           else if (lex_match_id (lexer, "LABEL"))
1157             c->key = CTCS_LABEL;
1158           else
1159             {
1160               c->key = CTCS_FUNCTION;
1161               if (!parse_ctables_summary_function (lexer, &c->sort_func))
1162                 return false;
1163
1164               if (lex_match (lexer, T_LPAREN))
1165                 {
1166                   c->sort_func_var = parse_variable (lexer, dict);
1167                   if (!c->sort_func_var)
1168                     return false;
1169
1170                   if (c->sort_func == CTSF_PTILE)
1171                     {
1172                       lex_match (lexer, T_COMMA);
1173                       if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
1174                         return false;
1175                       c->percentile = lex_number (lexer);
1176                       lex_get (lexer);
1177                     }
1178
1179                   if (!lex_force_match (lexer, T_RPAREN))
1180                     return false;
1181                 }
1182               else if (ctables_function_availability (c->sort_func)
1183                        == CTFA_SCALE)
1184                 {
1185                   bool UNUSED b = lex_force_match (lexer, T_LPAREN);
1186                   return false;
1187                 }
1188             }
1189         }
1190       else if (!c->n_values && lex_match_id (lexer, "MISSING"))
1191         {
1192           lex_match (lexer, T_EQUALS);
1193           if (lex_match_id (lexer, "INCLUDE"))
1194             c->include_missing = true;
1195           else if (lex_match_id (lexer, "EXCLUDE"))
1196             c->include_missing = false;
1197           else
1198             {
1199               lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1200               return false;
1201             }
1202         }
1203       else if (lex_match_id (lexer, "TOTAL"))
1204         {
1205           lex_match (lexer, T_EQUALS);
1206           if (!parse_bool (lexer, &c->show_totals))
1207             return false;
1208         }
1209       else if (lex_match_id (lexer, "LABEL"))
1210         {
1211           lex_match (lexer, T_EQUALS);
1212           if (!lex_force_string (lexer))
1213             return false;
1214           free (c->total_label);
1215           c->total_label = ss_xstrdup (lex_tokss (lexer));
1216           lex_get (lexer);
1217         }
1218       else if (lex_match_id (lexer, "POSITION"))
1219         {
1220           lex_match (lexer, T_EQUALS);
1221           if (lex_match_id (lexer, "BEFORE"))
1222             c->totals_before = true;
1223           else if (lex_match_id (lexer, "AFTER"))
1224             c->totals_before = false;
1225           else
1226             {
1227               lex_error_expecting (lexer, "BEFORE", "AFTER");
1228               return false;
1229             }
1230         }
1231       else if (lex_match_id (lexer, "EMPTY"))
1232         {
1233           lex_match (lexer, T_EQUALS);
1234           if (lex_match_id (lexer, "INCLUDE"))
1235             c->show_empty = true;
1236           else if (lex_match_id (lexer, "EXCLUDE"))
1237             c->show_empty = false;
1238           else
1239             {
1240               lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1241               return false;
1242             }
1243         }
1244       else
1245         {
1246           if (!c->n_values)
1247             lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
1248                                  "TOTAL", "LABEL", "POSITION", "EMPTY");
1249           else
1250             lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
1251           return false;
1252         }
1253     }
1254   return true;
1255 }
1256
1257 struct var_array
1258   {
1259     struct variable **vars;
1260     size_t n;
1261   };
1262
1263 static void
1264 var_array_uninit (struct var_array *va)
1265 {
1266   if (va)
1267     free (va->vars);
1268 }
1269
1270 struct var_array2
1271   {
1272     struct var_array *vas;
1273     size_t n;
1274   };
1275
1276 static void
1277 var_array2_uninit (struct var_array2 *vaa)
1278 {
1279   if (vaa)
1280     {
1281       for (size_t i = 0; i < vaa->n; i++)
1282         var_array_uninit (&vaa->vas[i]);
1283       free (vaa->vas);
1284     }
1285 }
1286
1287 static struct var_array2
1288 nest_fts (struct var_array2 va0, struct var_array2 va1)
1289 {
1290   if (!va0.n)
1291     return va1;
1292   else if (!va1.n)
1293     return va0;
1294
1295   struct var_array2 vaa = { .vas = xnmalloc (va0.n, va1.n * sizeof *vaa.vas) };
1296   for (size_t i = 0; i < va0.n; i++)
1297     for (size_t j = 0; j < va1.n; j++)
1298       {
1299         size_t allocate = va0.vas[i].n + va1.vas[j].n;
1300         struct variable **vars = xnmalloc (allocate, sizeof *vars);
1301         size_t n = 0;
1302         for (size_t k = 0; k < va0.vas[i].n; k++)
1303           vars[n++] = va0.vas[i].vars[k];
1304         for (size_t k = 0; k < va1.vas[j].n; k++)
1305           vars[n++] = va1.vas[j].vars[k];
1306         assert (n == allocate);
1307
1308         vaa.vas[vaa.n++] = (struct var_array) { .vars = vars, n = n };
1309       }
1310   var_array2_uninit (&va0);
1311   var_array2_uninit (&va1);
1312   return vaa;
1313 }
1314
1315 static struct var_array2
1316 stack_fts (struct var_array2 va0, struct var_array2 va1)
1317 {
1318   struct var_array2 vaa = { .vas = xnmalloc (va0.n + va1.n, sizeof *vaa.vas) };
1319   for (size_t i = 0; i < va0.n; i++)
1320     vaa.vas[vaa.n++] = va0.vas[i];
1321   for (size_t i = 0; i < va1.n; i++)
1322     vaa.vas[vaa.n++] = va1.vas[i];
1323   assert (vaa.n == va0.n + va1.n);
1324   free (va0.vas);
1325   free (va1.vas);
1326   return vaa;
1327 }
1328
1329 static struct var_array2
1330 enumerate_fts (const struct ctables_axis *a)
1331 {
1332   if (!a)
1333     return (struct var_array2) { .n = 0 };
1334
1335   switch (a->op)
1336     {
1337     case CTAO_VAR:
1338       assert (!a->var.is_mrset);
1339       struct variable **v = xmalloc (sizeof *v);
1340       *v = a->var.var;
1341       struct var_array *va = xmalloc (sizeof *va);
1342       *va = (struct var_array) { .vars = v, .n = 1 };
1343       return (struct var_array2) { .vas = va, .n = 1 };
1344
1345     case CTAO_STACK:
1346       return stack_fts (enumerate_fts (a->subs[0]),
1347                         enumerate_fts (a->subs[1]));
1348
1349     case CTAO_NEST:
1350       return nest_fts (enumerate_fts (a->subs[0]),
1351                        enumerate_fts (a->subs[1]));
1352     }
1353
1354   NOT_REACHED ();
1355 }
1356
1357 struct ctables_freqtab
1358   {
1359     struct var_array vars;
1360     struct hmap data;           /* Contains "struct freq"s. */
1361     struct freq **sorted;
1362   };
1363
1364 static int
1365 compare_freq_3way (const void *a_, const void *b_, const void *vars_)
1366 {
1367   const struct var_array *vars = vars_;
1368   struct freq *const *a = a_;
1369   struct freq *const *b = b_;
1370
1371   for (size_t i = 0; i < vars->n; i++)
1372     {
1373       int cmp = value_compare_3way (&(*a)->values[i], &(*b)->values[i],
1374                                     var_get_width (vars->vars[i]));
1375       if (cmp)
1376         return cmp;
1377     }
1378   
1379   return 0;
1380 }
1381
1382 static bool
1383 ctables_execute (struct dataset *ds, struct ctables *ct)
1384 {
1385   for (size_t i = 0; i < ct->n_tables; i++)
1386     {
1387       size_t allocated_fts = 0;
1388
1389       struct ctables_table *t = &ct->tables[i];
1390       struct var_array2 vaa = enumerate_fts (t->axes[PIVOT_AXIS_ROW]);
1391       vaa = nest_fts (vaa, enumerate_fts (t->axes[PIVOT_AXIS_COLUMN]));
1392       vaa = nest_fts (vaa, enumerate_fts (t->axes[PIVOT_AXIS_LAYER]));
1393       for (size_t i = 0; i < vaa.n; i++)
1394         {
1395           for (size_t j = 0; j < vaa.vas[i].n; j++)
1396             {
1397               if (j)
1398                 fputs (", ", stdout);
1399               fputs (var_get_name (vaa.vas[i].vars[j]), stdout);
1400             }
1401           putchar ('\n');
1402         }
1403
1404       for (size_t j = 0; j < vaa.n; j++)
1405         {
1406           struct ctables_freqtab *ft = xmalloc (sizeof *ft);
1407           *ft = (struct ctables_freqtab) {
1408             .vars = vaa.vas[j],
1409             .data = HMAP_INITIALIZER (ft->data),
1410           };
1411
1412           if (t->n_fts >= allocated_fts)
1413             t->fts = x2nrealloc (t->fts, &allocated_fts, sizeof *t->fts);
1414           t->fts[t->n_fts++] = ft;
1415         }
1416
1417       free (vaa.vas);
1418     }
1419
1420   struct casereader *input = casereader_create_filter_weight (proc_open (ds),
1421                                                               dataset_dict (ds),
1422                                                               NULL, NULL);
1423   bool warn_on_invalid = true;
1424   for (struct ccase *c = casereader_read (input); c;
1425        case_unref (c), c = casereader_read (input))
1426     {
1427       double weight = dict_get_case_weight (dataset_dict (ds), c,
1428                                             &warn_on_invalid);
1429
1430       for (size_t i = 0; i < ct->n_tables; i++)
1431         {
1432           struct ctables_table *t = &ct->tables[i];
1433
1434           for (size_t j = 0; j < t->n_fts; j++)
1435             {
1436               struct ctables_freqtab *ft = t->fts[j];
1437
1438               for (size_t k = 0; k < ft->vars.n; k++)
1439                 {
1440                   const struct variable *var = ft->vars.vars[k];
1441                   switch (var_is_value_missing (var, case_data (c, var)))
1442                     {
1443                     case MV_SYSTEM:
1444                       goto next_ft;
1445
1446                     case MV_USER:
1447                       if (!t->categories[var_get_dict_index (var)]
1448                           || !t->categories[var_get_dict_index (var)]->include_missing)
1449                         goto next_ft;
1450                       break;
1451                     }
1452                 }
1453               size_t hash = 0;
1454               for (size_t k = 0; k < ft->vars.n; k++)
1455                 {
1456                   const struct variable *var = ft->vars.vars[k];
1457                   hash = value_hash (case_data (c, var), var_get_width (var), hash);
1458                 }
1459
1460               struct freq *f;
1461               HMAP_FOR_EACH_WITH_HASH (f, struct freq, node, hash, &ft->data)
1462                 {
1463                   for (size_t k = 0; k < ft->vars.n; k++)
1464                     {
1465                       const struct variable *var = ft->vars.vars[k];
1466                       if (!value_equal (case_data (c, var), &f->values[k],
1467                                         var_get_width (var)))
1468                         goto next_hash_node;
1469                     }
1470
1471                   f->count += weight;
1472                   goto next_ft;
1473
1474                 next_hash_node: ;
1475                 }
1476
1477               f = xmalloc (table_entry_size (ft->vars.n));
1478               f->count = weight;
1479               for (size_t k = 0; k < ft->vars.n; k++)
1480                 {
1481                   const struct variable *var = ft->vars.vars[k];
1482                   value_clone (&f->values[k], case_data (c, var),
1483                                var_get_width (var));
1484                 }
1485               hmap_insert (&ft->data, &f->node, hash);
1486
1487             next_ft: ;
1488             }
1489         }
1490     }
1491   casereader_destroy (input);
1492
1493   for (size_t i = 0; i < ct->n_tables; i++)
1494     {
1495       struct ctables_table *t = &ct->tables[i];
1496
1497       struct pivot_table *pt = pivot_table_create (N_("Custom Tables"));
1498       struct pivot_dimension *d = pivot_dimension_create (
1499         pt, PIVOT_AXIS_ROW, N_("Rows"));
1500       for (size_t j = 0; j < t->n_fts; j++)
1501         {
1502           struct ctables_freqtab *ft = t->fts[j];
1503           ft->sorted = xnmalloc (ft->data.count, sizeof *ft->sorted);
1504
1505           struct freq *f;
1506           size_t n = 0;
1507           HMAP_FOR_EACH (f, struct freq, node, &ft->data)
1508             ft->sorted[n++] = f;
1509           assert (n == ft->data.count);
1510           sort (ft->sorted, n, sizeof *ft->sorted,
1511                 compare_freq_3way, &ft->vars);
1512
1513           struct pivot_category **groups = xnmalloc (ft->vars.n,
1514                                                      sizeof *groups);
1515           for (size_t k = 0; k < n; k++)
1516             {
1517               struct freq *prev = k > 0 ? ft->sorted[k - 1] : NULL;
1518               struct freq *f = ft->sorted[k];
1519
1520               size_t n_common = 0;
1521               if (prev)
1522                 for (; n_common + 1 < ft->vars.n; n_common++)
1523                   if (!value_equal (&prev->values[n_common],
1524                                     &f->values[n_common],
1525                                     var_get_type (ft->vars.vars[n_common])))
1526                     break;
1527
1528               for (size_t m = n_common; m + 1 < ft->vars.n; m++)
1529                 {
1530                   struct pivot_category *parent = m > 0 ? groups[m - 1] : d->root;
1531                   if (true)
1532                     parent = pivot_category_create_group__ (
1533                       parent, pivot_value_new_variable (ft->vars.vars[m]));
1534                   groups[m] = pivot_category_create_group__ (
1535                     parent,
1536                     pivot_value_new_var_value (ft->vars.vars[m], &f->values[m]));
1537                 }
1538
1539               int leaf = pivot_category_create_leaf (
1540                 ft->vars.n > 1 ? groups[ft->vars.n - 2] : d->root,
1541                 pivot_value_new_var_value (ft->vars.vars[ft->vars.n - 1],
1542                                            &f->values[ft->vars.n - 1]));
1543
1544               pivot_table_put1 (pt, leaf, pivot_value_new_number (f->count));
1545             }
1546           free (groups);
1547         }
1548       pivot_table_submit (pt);
1549     }
1550
1551   for (size_t i = 0; i < ct->n_tables; i++)
1552     {
1553       struct ctables_table *t = &ct->tables[i];
1554
1555       for (size_t j = 0; j < t->n_fts; j++)
1556         {
1557           struct ctables_freqtab *ft = t->fts[j];
1558           struct freq *f, *next;
1559           HMAP_FOR_EACH_SAFE (f, next, struct freq, node, &ft->data)
1560             {
1561               hmap_delete (&ft->data, &f->node);
1562               for (size_t k = 0; k < ft->vars.n; k++)
1563                 {
1564                   const struct variable *var = ft->vars.vars[k];
1565                   value_destroy (&f->values[k], var_get_width (var));
1566                 }
1567               free (f);
1568             }
1569           hmap_destroy (&ft->data);
1570           free (ft->sorted);
1571           var_array_uninit (&ft->vars);
1572           free (ft);
1573         }
1574       free (t->fts);
1575     }
1576
1577   return proc_commit (ds);
1578 }
1579
1580 int
1581 cmd_ctables (struct lexer *lexer, struct dataset *ds)
1582 {
1583   size_t n_vars = dict_get_n_vars (dataset_dict (ds));
1584   enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
1585   for (size_t i = 0; i < n_vars; i++)
1586     vlabels[i] = CTVL_DEFAULT;
1587
1588   struct ctables *ct = xmalloc (sizeof *ct);
1589   *ct = (struct ctables) {
1590     .look = pivot_table_look_unshare (pivot_table_look_ref (
1591                                         pivot_table_look_get_default ())),
1592     .vlabels = vlabels,
1593     .hide_threshold = 5,
1594   };
1595
1596   if (!lex_force_match (lexer, T_SLASH))
1597     goto error;
1598
1599   while (!lex_match_id (lexer, "TABLE"))
1600     {
1601       if (lex_match_id (lexer, "FORMAT"))
1602         {
1603           double widths[2] = { SYSMIS, SYSMIS };
1604           double units_per_inch = 72.0;
1605
1606           while (lex_token (lexer) != T_SLASH)
1607             {
1608               if (lex_match_id (lexer, "MINCOLWIDTH"))
1609                 {
1610                   if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
1611                     goto error;
1612                 }
1613               else if (lex_match_id (lexer, "MAXCOLWIDTH"))
1614                 {
1615                   if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
1616                     goto error;
1617                 }
1618               else if (lex_match_id (lexer, "UNITS"))
1619                 {
1620                   lex_match (lexer, T_EQUALS);
1621                   if (lex_match_id (lexer, "POINTS"))
1622                     units_per_inch = 72.0;
1623                   else if (lex_match_id (lexer, "INCHES"))
1624                     units_per_inch = 1.0;
1625                   else if (lex_match_id (lexer, "CM"))
1626                     units_per_inch = 2.54;
1627                   else
1628                     {
1629                       lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
1630                       goto error;
1631                     }
1632                 }
1633               else if (lex_match_id (lexer, "EMPTY"))
1634                 {
1635                   free (ct->zero);
1636                   ct->zero = NULL;
1637
1638                   lex_match (lexer, T_EQUALS);
1639                   if (lex_match_id (lexer, "ZERO"))
1640                     {
1641                       /* Nothing to do. */
1642                     }
1643                   else if (lex_match_id (lexer, "BLANK"))
1644                     ct->zero = xstrdup ("");
1645                   else if (lex_force_string (lexer))
1646                     {
1647                       ct->zero = ss_xstrdup (lex_tokss (lexer));
1648                       lex_get (lexer);
1649                     }
1650                   else
1651                     goto error;
1652                 }
1653               else if (lex_match_id (lexer, "MISSING"))
1654                 {
1655                   lex_match (lexer, T_EQUALS);
1656                   if (!lex_force_string (lexer))
1657                     goto error;
1658
1659                   free (ct->missing);
1660                   ct->missing = (strcmp (lex_tokcstr (lexer), ".")
1661                                  ? ss_xstrdup (lex_tokss (lexer))
1662                                  : NULL);
1663                   lex_get (lexer);
1664                 }
1665               else
1666                 {
1667                   lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
1668                                        "UNITS", "EMPTY", "MISSING");
1669                   goto error;
1670                 }
1671             }
1672
1673           if (widths[0] != SYSMIS && widths[1] != SYSMIS
1674               && widths[0] > widths[1])
1675             {
1676               msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
1677               goto error;
1678             }
1679
1680           for (size_t i = 0; i < 2; i++)
1681             if (widths[i] != SYSMIS)
1682               {
1683                 int *wr = ct->look->width_ranges[TABLE_HORZ];
1684                 wr[i] = widths[i] / units_per_inch * 96.0;
1685                 if (wr[0] > wr[1])
1686                   wr[!i] = wr[i];
1687               }
1688         }
1689       else if (lex_match_id (lexer, "VLABELS"))
1690         {
1691           if (!lex_force_match_id (lexer, "VARIABLES"))
1692             goto error;
1693           lex_match (lexer, T_EQUALS);
1694
1695           struct variable **vars;
1696           size_t n_vars;
1697           if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
1698                                 PV_NO_SCRATCH))
1699             goto error;
1700
1701           if (!lex_force_match_id (lexer, "DISPLAY"))
1702             {
1703               free (vars);
1704               goto error;
1705             }
1706           lex_match (lexer, T_EQUALS);
1707
1708           enum ctables_vlabel vlabel;
1709           if (lex_match_id (lexer, "DEFAULT"))
1710             vlabel = CTVL_DEFAULT;
1711           else if (lex_match_id (lexer, "NAME"))
1712             vlabel = CTVL_NAME;
1713           else if (lex_match_id (lexer, "LABEL"))
1714             vlabel = CTVL_LABEL;
1715           else if (lex_match_id (lexer, "BOTH"))
1716             vlabel = CTVL_BOTH;
1717           else if (lex_match_id (lexer, "NONE"))
1718             vlabel = CTVL_NONE;
1719           else
1720             {
1721               lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
1722                                    "BOTH", "NONE");
1723               free (vars);
1724               goto error;
1725             }
1726
1727           for (size_t i = 0; i < n_vars; i++)
1728             ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
1729           free (vars);
1730         }
1731       else if (lex_match_id (lexer, "MRSETS"))
1732         {
1733           if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
1734             goto error;
1735           lex_match (lexer, T_EQUALS);
1736           if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
1737             goto error;
1738         }
1739       else if (lex_match_id (lexer, "SMISSING"))
1740         {
1741           if (lex_match_id (lexer, "VARIABLE"))
1742             ct->smissing_listwise = false;
1743           else if (lex_match_id (lexer, "LISTWISE"))
1744             ct->smissing_listwise = true;
1745           else
1746             {
1747               lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
1748               goto error;
1749             }
1750         }
1751       /* XXX PCOMPUTE */
1752       else if (lex_match_id (lexer, "WEIGHT"))
1753         {
1754           if (!lex_force_match_id (lexer, "VARIABLE"))
1755             goto error;
1756           lex_match (lexer, T_EQUALS);
1757           ct->base_weight = parse_variable (lexer, dataset_dict (ds));
1758           if (!ct->base_weight)
1759             goto error;
1760         }
1761       else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
1762         {
1763           if (!lex_force_match_id (lexer, "COUNT"))
1764             goto error;
1765           lex_match (lexer, T_EQUALS);
1766           if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
1767             goto error;
1768           ct->hide_threshold = lex_integer (lexer);
1769           lex_get (lexer);
1770         }
1771       else
1772         {
1773           lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
1774                                "SMISSING", "PCOMPUTE", "PPROPERTIES",
1775                                "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
1776           goto error;
1777         }
1778
1779       if (!lex_force_match (lexer, T_SLASH))
1780         goto error;
1781     }
1782
1783   size_t allocated_tables = 0;
1784   do
1785     {
1786       if (ct->n_tables >= allocated_tables)
1787         ct->tables = x2nrealloc (ct->tables, &allocated_tables,
1788                                  sizeof *ct->tables);
1789
1790       struct ctables_table *t = &ct->tables[ct->n_tables++];
1791       *t = (struct ctables_table) {
1792         .slabels_position = PIVOT_AXIS_COLUMN,
1793         .slabels_visible = true,
1794         .row_labels = CTLP_NORMAL,
1795         .col_labels = CTLP_NORMAL,
1796         .categories = xcalloc (dict_get_n_vars (dataset_dict (ds)),
1797                                sizeof *t->categories),
1798         .n_categories = dict_get_n_vars (dataset_dict (ds)),
1799         .cilevel = 95,
1800       };
1801
1802       lex_match (lexer, T_EQUALS);
1803       if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
1804         goto error;
1805       if (lex_match (lexer, T_BY))
1806         {
1807           if (!ctables_axis_parse (lexer, dataset_dict (ds),
1808                                    ct, t, PIVOT_AXIS_COLUMN))
1809             goto error;
1810
1811           if (lex_match (lexer, T_BY))
1812             {
1813               if (!ctables_axis_parse (lexer, dataset_dict (ds),
1814                                        ct, t, PIVOT_AXIS_LAYER))
1815                 goto error;
1816             }
1817         }
1818
1819       if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
1820           && !t->axes[PIVOT_AXIS_LAYER])
1821         {
1822           lex_error (lexer, _("At least one variable must be specified."));
1823           goto error;
1824         }
1825
1826       const struct ctables_axis *scales[PIVOT_N_AXES];
1827       size_t n_scales = 0;
1828       for (size_t i = 0; i < 3; i++)
1829         {
1830           scales[i] = find_scale (t->axes[i]);
1831           if (scales[i])
1832             n_scales++;
1833         }
1834       if (n_scales > 1)
1835         {
1836           msg (SE, _("Scale variables may appear only on one dimension."));
1837           if (scales[PIVOT_AXIS_ROW])
1838             msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
1839                     _("This scale variable appears in the rows dimension."));
1840           if (scales[PIVOT_AXIS_COLUMN])
1841             msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
1842                     _("This scale variable appears in the columns dimension."));
1843           if (scales[PIVOT_AXIS_LAYER])
1844             msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
1845                     _("This scale variable appears in the layer dimension."));
1846           goto error;
1847         }
1848
1849       if (lex_token (lexer) == T_ENDCMD)
1850         break;
1851       if (!lex_force_match (lexer, T_SLASH))
1852         break;
1853
1854       while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
1855         {
1856           if (lex_match_id (lexer, "SLABELS"))
1857             {
1858               while (lex_token (lexer) != T_SLASH)
1859                 {
1860                   if (lex_match_id (lexer, "POSITION"))
1861                     {
1862                       lex_match (lexer, T_EQUALS);
1863                       if (lex_match_id (lexer, "COLUMN"))
1864                         t->slabels_position = PIVOT_AXIS_COLUMN;
1865                       else if (lex_match_id (lexer, "ROW"))
1866                         t->slabels_position = PIVOT_AXIS_ROW;
1867                       else if (lex_match_id (lexer, "LAYER"))
1868                         t->slabels_position = PIVOT_AXIS_LAYER;
1869                       else
1870                         {
1871                           lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
1872                           goto error;
1873                         }
1874                     }
1875                   else if (lex_match_id (lexer, "VISIBLE"))
1876                     {
1877                       lex_match (lexer, T_EQUALS);
1878                       if (!parse_bool (lexer, &t->slabels_visible))
1879                         goto error;
1880                     }
1881                   else
1882                     {
1883                       lex_error_expecting (lexer, "POSITION", "VISIBLE");
1884                       goto error;
1885                     }
1886                 }
1887             }
1888           else if (lex_match_id (lexer, "CLABELS"))
1889             {
1890               while (lex_token (lexer) != T_SLASH)
1891                 {
1892                   if (lex_match_id (lexer, "AUTO"))
1893                     t->row_labels = t->col_labels = CTLP_NORMAL;
1894                   else if (lex_match_id (lexer, "ROWLABELS"))
1895                     {
1896                       lex_match (lexer, T_EQUALS);
1897                       if (lex_match_id (lexer, "OPPOSITE"))
1898                         t->row_labels = CTLP_OPPOSITE;
1899                       else if (lex_match_id (lexer, "LAYER"))
1900                         t->row_labels = CTLP_LAYER;
1901                       else
1902                         {
1903                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
1904                           goto error;
1905                         }
1906                     }
1907                   else if (lex_match_id (lexer, "COLLABELS"))
1908                     {
1909                       lex_match (lexer, T_EQUALS);
1910                       if (lex_match_id (lexer, "OPPOSITE"))
1911                         t->col_labels = CTLP_OPPOSITE;
1912                       else if (lex_match_id (lexer, "LAYER"))
1913                         t->col_labels = CTLP_LAYER;
1914                       else
1915                         {
1916                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
1917                           goto error;
1918                         }
1919                     }
1920                   else
1921                     {
1922                       lex_error_expecting (lexer, "AUTO", "ROWLABELS",
1923                                            "COLLABELS");
1924                       goto error;
1925                     }
1926                 }
1927             }
1928           else if (lex_match_id (lexer, "CRITERIA"))
1929             {
1930               if (!lex_force_match_id (lexer, "CILEVEL"))
1931                 goto error;
1932               lex_match (lexer, T_EQUALS);
1933
1934               if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
1935                 goto error;
1936               t->cilevel = lex_number (lexer);
1937               lex_get (lexer);
1938             }
1939           else if (lex_match_id (lexer, "CATEGORIES"))
1940             {
1941               if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
1942                 goto error;
1943             }
1944           else if (lex_match_id (lexer, "TITLES"))
1945             {
1946               do
1947                 {
1948                   char **textp;
1949                   if (lex_match_id (lexer, "CAPTION"))
1950                     textp = &t->caption;
1951                   else if (lex_match_id (lexer, "CORNER"))
1952                     textp = &t->corner;
1953                   else if (lex_match_id (lexer, "TITLE"))
1954                     textp = &t->title;
1955                   else
1956                     {
1957                       lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
1958                       goto error;
1959                     }
1960                   lex_match (lexer, T_EQUALS);
1961
1962                   struct string s = DS_EMPTY_INITIALIZER;
1963                   while (lex_is_string (lexer))
1964                     {
1965                       if (!ds_is_empty (&s))
1966                         ds_put_byte (&s, ' ');
1967                       ds_put_substring (&s, lex_tokss (lexer));
1968                       lex_get (lexer);
1969                     }
1970                   free (*textp);
1971                   *textp = ds_steal_cstr (&s);
1972                 }
1973               while (lex_token (lexer) != T_SLASH
1974                      && lex_token (lexer) != T_ENDCMD);
1975             }
1976           else if (lex_match_id (lexer, "SIGTEST"))
1977             {
1978               if (!t->chisq)
1979                 {
1980                   t->chisq = xmalloc (sizeof *t->chisq);
1981                   *t->chisq = (struct ctables_chisq) {
1982                     .alpha = .05,
1983                     .include_mrsets = true,
1984                     .all_visible = true,
1985                   };
1986                 }
1987
1988               do
1989                 {
1990                   if (lex_match_id (lexer, "TYPE"))
1991                     {
1992                       lex_match (lexer, T_EQUALS);
1993                       if (!lex_force_match_id (lexer, "CHISQUARE"))
1994                         goto error;
1995                     }
1996                   else if (lex_match_id (lexer, "ALPHA"))
1997                     {
1998                       lex_match (lexer, T_EQUALS);
1999                       if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
2000                         goto error;
2001                       t->chisq->alpha = lex_number (lexer);
2002                       lex_get (lexer);
2003                     }
2004                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
2005                     {
2006                       lex_match (lexer, T_EQUALS);
2007                       if (parse_bool (lexer, &t->chisq->include_mrsets))
2008                         goto error;
2009                     }
2010                   else if (lex_match_id (lexer, "CATEGORIES"))
2011                     {
2012                       lex_match (lexer, T_EQUALS);
2013                       if (lex_match_id (lexer, "ALLVISIBLE"))
2014                         t->chisq->all_visible = true;
2015                       else if (lex_match_id (lexer, "SUBTOTALS"))
2016                         t->chisq->all_visible = false;
2017                       else
2018                         {
2019                           lex_error_expecting (lexer,
2020                                                "ALLVISIBLE", "SUBTOTALS");
2021                           goto error;
2022                         }
2023                     }
2024                   else
2025                     {
2026                       lex_error_expecting (lexer, "TYPE", "ALPHA",
2027                                            "INCLUDEMRSETS", "CATEGORIES");
2028                       goto error;
2029                     }
2030                 }
2031               while (lex_token (lexer) != T_SLASH
2032                      && lex_token (lexer) != T_ENDCMD);
2033             }
2034           else if (lex_match_id (lexer, "COMPARETEST"))
2035             {
2036               if (!t->pairwise)
2037                 {
2038                   t->pairwise = xmalloc (sizeof *t->pairwise);
2039                   *t->pairwise = (struct ctables_pairwise) {
2040                     .type = PROP,
2041                     .alpha = { .05, .05 },
2042                     .adjust = BONFERRONI,
2043                     .include_mrsets = true,
2044                     .meansvariance_allcats = true,
2045                     .all_visible = true,
2046                     .merge = false,
2047                     .apa_style = true,
2048                     .show_sig = false,
2049                   };
2050                 }
2051
2052               do
2053                 {
2054                   if (lex_match_id (lexer, "TYPE"))
2055                     {
2056                       lex_match (lexer, T_EQUALS);
2057                       if (lex_match_id (lexer, "PROP"))
2058                         t->pairwise->type = PROP;
2059                       else if (lex_match_id (lexer, "MEAN"))
2060                         t->pairwise->type = MEAN;
2061                       else
2062                         {
2063                           lex_error_expecting (lexer, "PROP", "MEAN");
2064                           goto error;
2065                         }
2066                     }
2067                   else if (lex_match_id (lexer, "ALPHA"))
2068                     {
2069                       lex_match (lexer, T_EQUALS);
2070
2071                       if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
2072                         goto error;
2073                       double a0 = lex_number (lexer);
2074                       lex_get (lexer);
2075
2076                       lex_match (lexer, T_COMMA);
2077                       if (lex_is_number (lexer))
2078                         {
2079                           if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
2080                             goto error;
2081                           double a1 = lex_number (lexer);
2082                           lex_get (lexer);
2083
2084                           t->pairwise->alpha[0] = MIN (a0, a1);
2085                           t->pairwise->alpha[1] = MAX (a0, a1);
2086                         }
2087                       else
2088                         t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
2089                     }
2090                   else if (lex_match_id (lexer, "ADJUST"))
2091                     {
2092                       lex_match (lexer, T_EQUALS);
2093                       if (lex_match_id (lexer, "BONFERRONI"))
2094                         t->pairwise->adjust = BONFERRONI;
2095                       else if (lex_match_id (lexer, "BH"))
2096                         t->pairwise->adjust = BH;
2097                       else if (lex_match_id (lexer, "NONE"))
2098                         t->pairwise->adjust = 0;
2099                       else
2100                         {
2101                           lex_error_expecting (lexer, "BONFERRONI", "BH",
2102                                                "NONE");
2103                           goto error;
2104                         }
2105                     }
2106                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
2107                     {
2108                       lex_match (lexer, T_EQUALS);
2109                       if (!parse_bool (lexer, &t->pairwise->include_mrsets))
2110                         goto error;
2111                     }
2112                   else if (lex_match_id (lexer, "MEANSVARIANCE"))
2113                     {
2114                       lex_match (lexer, T_EQUALS);
2115                       if (lex_match_id (lexer, "ALLCATS"))
2116                         t->pairwise->meansvariance_allcats = true;
2117                       else if (lex_match_id (lexer, "TESTEDCATS"))
2118                         t->pairwise->meansvariance_allcats = false;
2119                       else
2120                         {
2121                           lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
2122                           goto error;
2123                         }
2124                     }
2125                   else if (lex_match_id (lexer, "CATEGORIES"))
2126                     {
2127                       lex_match (lexer, T_EQUALS);
2128                       if (lex_match_id (lexer, "ALLVISIBLE"))
2129                         t->pairwise->all_visible = true;
2130                       else if (lex_match_id (lexer, "SUBTOTALS"))
2131                         t->pairwise->all_visible = false;
2132                       else
2133                         {
2134                           lex_error_expecting (lexer, "ALLVISIBLE",
2135                                                "SUBTOTALS");
2136                           goto error;
2137                         }
2138                     }
2139                   else if (lex_match_id (lexer, "MERGE"))
2140                     {
2141                       lex_match (lexer, T_EQUALS);
2142                       if (!parse_bool (lexer, &t->pairwise->merge))
2143                         goto error;
2144                     }
2145                   else if (lex_match_id (lexer, "STYLE"))
2146                     {
2147                       lex_match (lexer, T_EQUALS);
2148                       if (lex_match_id (lexer, "APA"))
2149                         t->pairwise->apa_style = true;
2150                       else if (lex_match_id (lexer, "SIMPLE"))
2151                         t->pairwise->apa_style = false;
2152                       else
2153                         {
2154                           lex_error_expecting (lexer, "APA", "SIMPLE");
2155                           goto error;
2156                         }
2157                     }
2158                   else if (lex_match_id (lexer, "SHOWSIG"))
2159                     {
2160                       lex_match (lexer, T_EQUALS);
2161                       if (!parse_bool (lexer, &t->pairwise->show_sig))
2162                         goto error;
2163                     }
2164                   else
2165                     {
2166                       lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
2167                                            "INCLUDEMRSETS", "MEANSVARIANCE",
2168                                            "CATEGORIES", "MERGE", "STYLE",
2169                                            "SHOWSIG");
2170                       goto error;
2171                     }
2172                 }
2173               while (lex_token (lexer) != T_SLASH
2174                      && lex_token (lexer) != T_ENDCMD);
2175             }
2176           else
2177             {
2178               lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
2179                                    "CRITERIA", "CATEGORIES", "TITLES",
2180                                    "SIGTEST", "COMPARETEST");
2181               goto error;
2182             }
2183         }
2184
2185       if (t->row_labels != CTLP_NORMAL && t->col_labels != CTLP_NORMAL)
2186         {
2187           msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
2188           goto error;
2189         }
2190
2191     }
2192   while (lex_token (lexer) != T_ENDCMD);
2193
2194   bool ok = ctables_execute (ds, ct);
2195   ctables_destroy (ct);
2196   return ok ? CMD_SUCCESS : CMD_FAILURE;
2197
2198 error:
2199   ctables_destroy (ct);
2200   return CMD_FAILURE;
2201 }
2202