Sorting categories by explicit values.
[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 && cats->n_values)
1918           {
1919             const struct ctables_cat_value *a_cv = ctables_categories_match (cats, val_a, var);
1920             const struct ctables_cat_value *b_cv = ctables_categories_match (cats, val_b, var);
1921             assert (a_cv && b_cv);
1922             return (a_cv == b_cv ? cmp
1923                     : a_cv > b_cv ? 1
1924                     : -1);
1925           }
1926
1927         return cmp;
1928       }
1929   return 0;
1930 }
1931
1932 /* Algorithm:
1933
1934    For each row:
1935        For each ctables_table:
1936            For each combination of row vars:
1937                For each combination of column vars:
1938                    For each combination of layer vars:
1939                        Add entry
1940    Make a table of row values:
1941        Sort entries by row values
1942        Assign a 0-based index to each actual value
1943        Construct a dimension
1944    Make a table of column values
1945    Make a table of layer values
1946    For each entry:
1947        Fill the table entry using the indexes from before.
1948  */
1949
1950 static struct ctables_domain *
1951 ctables_domain_insert (struct ctables_table *t, struct ctables_freq *f,
1952                        enum ctables_domain_type domain)
1953 {
1954   size_t hash = 0;
1955   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
1956     {
1957       size_t idx = f->axes[a].vaa_idx;
1958       const struct var_array *va = &t->vaas[a].vas[idx];
1959       hash = hash_int (idx, hash);
1960       for (size_t i = 0; i < va->n_domains[domain]; i++)
1961         {
1962           size_t v_idx = va->domains[domain][i];
1963           hash = value_hash (&f->axes[a].values[v_idx],
1964                              var_get_width (va->vars[v_idx]), hash);
1965         }
1966     }
1967
1968   struct ctables_domain *d;
1969   HMAP_FOR_EACH_WITH_HASH (d, struct ctables_domain, node, hash, &t->domains[domain])
1970     {
1971       const struct ctables_freq *df = d->example;
1972       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
1973         {
1974           size_t idx = f->axes[a].vaa_idx;
1975           if (idx != df->axes[a].vaa_idx)
1976             goto not_equal;
1977
1978           const struct var_array *va = &t->vaas[a].vas[idx];
1979           for (size_t i = 0; i < va->n_domains[domain]; i++)
1980             {
1981               size_t v_idx = va->domains[domain][i];
1982               if (!value_equal (&df->axes[a].values[v_idx],
1983                                 &f->axes[a].values[v_idx],
1984                                 var_get_width (va->vars[v_idx])))
1985                 goto not_equal;
1986             }
1987         }
1988       return d;
1989
1990     not_equal: ;
1991     }
1992
1993   d = xmalloc (sizeof *d);
1994   *d = (struct ctables_domain) { .example = f };
1995   hmap_insert (&t->domains[domain], &d->node, hash);
1996   return d;
1997 }
1998
1999 static const struct ctables_cat_value *
2000 ctables_categories_match (const struct ctables_categories *cats,
2001                           const union value *v, const struct variable *var)
2002 {
2003   const struct ctables_cat_value *othernm = NULL;
2004   for (size_t i = cats->n_values; i-- > 0; )
2005     {
2006       const struct ctables_cat_value *cv = &cats->values[i];
2007       switch (cv->type)
2008         {
2009         case CCVT_NUMBER:
2010           if (cv->number == v->f)
2011             return cv;
2012           break;
2013
2014         case CCVT_STRING:
2015           NOT_REACHED ();
2016
2017         case CCVT_RANGE:
2018           if ((cv->range[0] == -DBL_MAX || v->f >= cv->range[0])
2019               && (cv->range[1] == DBL_MAX || v->f <= cv->range[1]))
2020             return cv;
2021           break;
2022
2023         case CCVT_MISSING:
2024           if (var_is_value_missing (var, v))
2025             return cv;
2026           break;
2027
2028         case CCVT_OTHERNM:
2029           if (!othernm)
2030             othernm = cv;
2031           break;
2032
2033         case CCVT_SUBTOTAL:
2034         case CCVT_HSUBTOTAL:
2035           break;
2036         }
2037     }
2038
2039   return var_is_value_missing (var, v) ? NULL : othernm;
2040 }
2041
2042 static void
2043 ctables_freqtab_insert (struct ctables_table *t,
2044                         const struct ccase *c,
2045                         size_t ir, size_t ic, size_t il,
2046                         double weight)
2047 {
2048   size_t ix[PIVOT_N_AXES] = {
2049     [PIVOT_AXIS_ROW] = ir,
2050     [PIVOT_AXIS_COLUMN] = ic,
2051     [PIVOT_AXIS_LAYER] = il,
2052   };
2053   const struct var_array *ss = &t->vaas[t->summary_axis].vas[ix[t->summary_axis]];
2054
2055   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2056     {
2057       const struct var_array *va = &t->vaas[a].vas[ix[a]];
2058       for (size_t i = 0; i < va->n; i++)
2059         {
2060           if (i == va->scale_idx)
2061             continue;
2062
2063           const struct ctables_categories *cats = t->categories[var_get_dict_index (va->vars[i])];
2064           if (!cats || !cats->n_values)
2065             continue;
2066
2067           if (!ctables_categories_match (cats, case_data (c, va->vars[i]), va->vars[i]))
2068             return;
2069         }
2070     }
2071
2072   size_t hash = 0;
2073   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2074     {
2075       const struct var_array *va = &t->vaas[a].vas[ix[a]];
2076       hash = hash_int (ix[a], hash);
2077       for (size_t i = 0; i < va->n; i++)
2078         if (i != va->scale_idx)
2079           hash = value_hash (case_data (c, va->vars[i]),
2080                              var_get_width (va->vars[i]), hash);
2081     }
2082
2083   struct ctables_freq *f;
2084   HMAP_FOR_EACH_WITH_HASH (f, struct ctables_freq, node, hash, &t->ft)
2085     {
2086       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2087         {
2088           const struct var_array *va = &t->vaas[a].vas[ix[a]];
2089           if (f->axes[a].vaa_idx != ix[a])
2090             goto not_equal;
2091           for (size_t i = 0; i < va->n; i++)
2092             if (i != va->scale_idx
2093                 && !value_equal (case_data (c, va->vars[i]),
2094                                  &f->axes[a].values[i],
2095                                  var_get_width (va->vars[i])))
2096                 goto not_equal;
2097         }
2098
2099       goto summarize;
2100
2101     not_equal: ;
2102     }
2103
2104   f = xmalloc (sizeof *f);
2105   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2106     {
2107       const struct var_array *va = &t->vaas[a].vas[ix[a]];
2108       f->axes[a].vaa_idx = ix[a];
2109       f->axes[a].values = (va->n
2110                            ? xnmalloc (va->n, sizeof *f->axes[a].values)
2111                            : NULL);
2112       for (size_t i = 0; i < va->n; i++)
2113         value_clone (&f->axes[a].values[i], case_data (c, va->vars[i]),
2114                      var_get_width (va->vars[i]));
2115     }
2116   f->summaries = xmalloc (ss->n_summaries * sizeof *f->summaries);
2117   for (size_t i = 0; i < ss->n_summaries; i++)
2118     ctables_summary_init (&f->summaries[i], &ss->summaries[i]);
2119   for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2120     f->domains[dt] = ctables_domain_insert (t, f, dt);
2121   hmap_insert (&t->ft, &f->node, hash);
2122
2123 summarize:
2124   for (size_t i = 0; i < ss->n_summaries; i++)
2125     ctables_summary_add (&f->summaries[i], &ss->summaries[i], ss->summary_var,
2126                          case_data (c, ss->summary_var), weight);
2127   for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2128     f->domains[dt]->valid += weight;
2129 }
2130
2131 static bool
2132 ctables_execute (struct dataset *ds, struct ctables *ct)
2133 {
2134   for (size_t i = 0; i < ct->n_tables; i++)
2135     {
2136       struct ctables_table *t = ct->tables[i];
2137       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2138         if (t->axes[a])
2139           {
2140             t->vaas[a] = enumerate_fts (a, t->axes[a]);
2141
2142             for (size_t j = 0; j < t->vaas[a].n; j++)
2143               {
2144                 struct var_array *va = &t->vaas[a].vas[j];
2145                 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2146                   {
2147                     va->domains[dt] = xmalloc (va->n * sizeof *va->domains[dt]);
2148                     va->n_domains[dt] = 0;
2149
2150                     for (size_t k = 0; k < va->n; k++)
2151                       {
2152                         if (k == va->scale_idx)
2153                           continue;
2154
2155                         switch (dt)
2156                           {
2157                           case CTDT_TABLE:
2158                             continue;
2159
2160                           case CTDT_LAYER:
2161                             if (a != PIVOT_AXIS_LAYER)
2162                               continue;
2163                             break;
2164
2165                           case CTDT_SUBTABLE:
2166                           case CTDT_ROW:
2167                           case CTDT_COL:
2168                             if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
2169                                 : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
2170                                 : a == PIVOT_AXIS_ROW)
2171                               {
2172                                 if (k == va->n - 1
2173                                     || (va->scale_idx == va->n - 1
2174                                         && k == va->n - 2))
2175                                   continue;
2176                               }
2177                             break;
2178
2179                           case CTDT_LAYERROW:
2180                             if (a == PIVOT_AXIS_COLUMN)
2181                               continue;
2182                             break;
2183
2184                           case CTDT_LAYERCOL:
2185                             if (a == PIVOT_AXIS_ROW)
2186                               continue;
2187                             break;
2188                           }
2189
2190                         va->domains[dt][va->n_domains[dt]++] = k;
2191                       }
2192                   }
2193               }
2194           }
2195         else
2196           {
2197             struct var_array *va = xmalloc (sizeof *va);
2198             *va = (struct var_array) { .n = 0 };
2199             t->vaas[a] = (struct var_array2) { .vas = va, .n = 1 };
2200           }
2201
2202       for (size_t i = 0; i < t->vaas[t->summary_axis].n; i++)
2203         {
2204           struct var_array *va = &t->vaas[t->summary_axis].vas[i];
2205           if (!va->n_summaries)
2206             {
2207               va->summaries = xmalloc (sizeof *va->summaries);
2208               va->n_summaries = 1;
2209
2210               enum ctables_summary_function function
2211                 = va->summary_var ? CTSF_MEAN : CTSF_COUNT;
2212               struct ctables_var var = { .is_mrset = false, .var = va->summary_var };
2213
2214               *va->summaries = (struct ctables_summary_spec) {
2215                 .function = function,
2216                 .format = ctables_summary_default_format (function, &var),
2217                 .label = ctables_summary_default_label (function, 0),
2218               };
2219               if (!va->summary_var)
2220                 va->summary_var = va->vars[0];
2221             }
2222         }
2223     }
2224
2225   struct casereader *input = casereader_create_filter_weight (proc_open (ds),
2226                                                               dataset_dict (ds),
2227                                                               NULL, NULL);
2228   bool warn_on_invalid = true;
2229   double total_weight = 0;
2230   for (struct ccase *c = casereader_read (input); c;
2231        case_unref (c), c = casereader_read (input))
2232     {
2233       double weight = dict_get_case_weight (dataset_dict (ds), c,
2234                                             &warn_on_invalid);
2235       total_weight += weight;
2236
2237       for (size_t i = 0; i < ct->n_tables; i++)
2238         {
2239           struct ctables_table *t = ct->tables[i];
2240
2241           for (size_t ir = 0; ir < t->vaas[PIVOT_AXIS_ROW].n; ir++)
2242             for (size_t ic = 0; ic < t->vaas[PIVOT_AXIS_COLUMN].n; ic++)
2243               for (size_t il = 0; il < t->vaas[PIVOT_AXIS_LAYER].n; il++)
2244                 ctables_freqtab_insert (t, c, ir, ic, il, weight);
2245         }
2246     }
2247   casereader_destroy (input);
2248
2249   for (size_t i = 0; i < ct->n_tables; i++)
2250     {
2251       struct ctables_table *t = ct->tables[i];
2252
2253       struct pivot_table *pt = pivot_table_create__ (
2254         (t->title
2255          ? pivot_value_new_user_text (t->title, SIZE_MAX)
2256          : pivot_value_new_text (N_("Custom Tables"))),
2257         NULL);
2258       if (t->caption)
2259         pivot_table_set_caption (
2260           pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
2261       if (t->corner)
2262         pivot_table_set_caption (
2263           pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
2264
2265       pivot_table_set_look (pt, ct->look);
2266       struct pivot_dimension *d[PIVOT_N_AXES];
2267       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2268         {
2269           static const char *names[] = {
2270             [PIVOT_AXIS_ROW] = N_("Rows"),
2271             [PIVOT_AXIS_COLUMN] = N_("Columns"),
2272             [PIVOT_AXIS_LAYER] = N_("Layers"),
2273           };
2274           d[a] = (t->axes[a] || a == t->summary_axis
2275                   ? pivot_dimension_create (pt, a, names[a])
2276                   : NULL);
2277           if (!d[a])
2278             continue;
2279
2280           assert (t->axes[a]);
2281
2282           struct ctables_freq **sorted = xnmalloc (t->ft.count, sizeof *sorted);
2283
2284           struct ctables_freq *f;
2285           size_t n = 0;
2286           HMAP_FOR_EACH (f, struct ctables_freq, node, &t->ft)
2287             sorted[n++] = f;
2288           assert (n == t->ft.count);
2289
2290           struct ctables_freq_sort_aux aux = { .t = t, .a = a };
2291           sort (sorted, n, sizeof *sorted, ctables_freq_compare_3way, &aux);
2292
2293           size_t max_depth = 0;
2294           for (size_t j = 0; j < t->vaas[a].n; j++)
2295             if (t->vaas[a].vas[j].n > max_depth)
2296               max_depth = t->vaas[a].vas[j].n;
2297
2298           struct pivot_category **groups = xnmalloc (max_depth, sizeof *groups);
2299           struct pivot_category *top = NULL;
2300           int prev_leaf = 0;
2301           for (size_t j = 0; j < n; j++)
2302             {
2303               struct ctables_freq *f = sorted[j];
2304               const struct var_array *va = &t->vaas[a].vas[f->axes[a].vaa_idx];
2305
2306               size_t n_common = 0;
2307               bool new_subtable = false;
2308               if (j > 0)
2309                 {
2310                   struct ctables_freq *prev = sorted[j - 1];
2311                   if (prev->axes[a].vaa_idx == f->axes[a].vaa_idx)
2312                     {
2313                       for (; n_common < va->n; n_common++)
2314                         if (n_common != va->scale_idx
2315                             && !value_equal (&prev->axes[a].values[n_common],
2316                                              &f->axes[a].values[n_common],
2317                                              var_get_type (va->vars[n_common])))
2318                           break;
2319                     }
2320                   else
2321                     new_subtable = true;
2322                 }
2323               else
2324                 new_subtable = true;
2325
2326               if (new_subtable)
2327                 {
2328                   enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (va->vars[0])];
2329                   top = d[a]->root;
2330                   if (vlabel != CTVL_NONE)
2331                     top = pivot_category_create_group__ (
2332                       top, pivot_value_new_variable (va->vars[0]));
2333                 }
2334               if (n_common == va->n)
2335                 {
2336                   f->axes[a].leaf = prev_leaf;
2337                   continue;
2338                 }
2339
2340               for (size_t k = n_common; k < va->n; k++)
2341                 {
2342                   struct pivot_category *parent = k > 0 ? groups[k - 1] : top;
2343
2344                   struct pivot_value *label
2345                     = (k != va->scale_idx
2346                        ? pivot_value_new_var_value (va->vars[k],
2347                                                     &f->axes[a].values[k])
2348                        : NULL);
2349                   if (k == va->n - 1)
2350                     {
2351                       if (a == t->summary_axis)
2352                         {
2353                           if (label)
2354                             parent = pivot_category_create_group__ (parent, label);
2355                           for (size_t m = 0; m < va->n_summaries; m++)
2356                             {
2357                               int leaf = pivot_category_create_leaf (
2358                                 parent, pivot_value_new_text (va->summaries[m].label));
2359                               if (m == 0)
2360                                 prev_leaf = leaf;
2361                             }
2362                         }
2363                       else
2364                         {
2365                           /* This assertion is true as long as the summary axis
2366                              is the axis where the summaries are displayed. */
2367                           assert (label);
2368
2369                           prev_leaf = pivot_category_create_leaf (parent, label);
2370                         }
2371                       break;
2372                     }
2373
2374                   if (label)
2375                     parent = pivot_category_create_group__ (parent, label);
2376
2377                   enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (va->vars[k + 1])];
2378                   if (vlabel != CTVL_NONE)
2379                     parent = pivot_category_create_group__ (
2380                       parent, pivot_value_new_variable (va->vars[k + 1]));
2381                   groups[k] = parent;
2382                 }
2383
2384               f->axes[a].leaf = prev_leaf;
2385             }
2386           free (sorted);
2387           free (groups);
2388         }
2389       struct ctables_freq *f;
2390       HMAP_FOR_EACH (f, struct ctables_freq, node, &t->ft)
2391         {
2392           const struct var_array *ss = &t->vaas[t->summary_axis].vas[f->axes[t->summary_axis].vaa_idx];
2393           for (size_t j = 0; j < ss->n_summaries; j++)
2394             {
2395               size_t dindexes[3];
2396               size_t n_dindexes = 0;
2397
2398               for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2399                 if (d[a])
2400                   {
2401                     int leaf = f->axes[a].leaf;
2402                     if (a == t->summary_axis)
2403                       leaf += j;
2404                     dindexes[n_dindexes++] = leaf;
2405                   }
2406
2407               double d = ctables_summary_value (f, &f->summaries[j], &ss->summaries[j]);
2408               struct pivot_value *value = pivot_value_new_number (d);
2409               value->numeric.format = ss->summaries[j].format;
2410               pivot_table_put (pt, dindexes, n_dindexes, value);
2411             }
2412         }
2413
2414       pivot_table_submit (pt);
2415     }
2416
2417 #if 0
2418   for (size_t i = 0; i < ct->n_tables; i++)
2419     {
2420       struct ctables_table *t = ct->tables[i];
2421
2422       for (size_t j = 0; j < t->n_fts; j++)
2423         {
2424           struct ctables_freqtab *ft = t->fts[j];
2425           struct ctables_freq *f, *next;
2426           HMAP_FOR_EACH_SAFE (f, next, struct ctables_freq, node, &ft->data)
2427             {
2428               hmap_delete (&ft->data, &f->node);
2429               for (size_t k = 0; k < ft->n_summaries; k++)
2430                 ctables_summary_uninit (&f->summaries[k], &ft->summaries[k]);
2431               free (f->summaries);
2432               for (size_t k = 0; k < ft->vars.n; k++)
2433                 {
2434                   const struct variable *var = ft->vars.vars[k];
2435                   value_destroy (&f->values[k], var_get_width (var));
2436                 }
2437               free (f);
2438             }
2439           hmap_destroy (&ft->data);
2440           var_array_uninit (&ft->vars);
2441           free (ft);
2442         }
2443       free (t->fts);
2444     }
2445 #endif
2446   
2447   return proc_commit (ds);
2448 }
2449
2450 int
2451 cmd_ctables (struct lexer *lexer, struct dataset *ds)
2452 {
2453   size_t n_vars = dict_get_n_vars (dataset_dict (ds));
2454   enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
2455   enum settings_value_show tvars = settings_get_show_variables ();
2456   for (size_t i = 0; i < n_vars; i++)
2457     vlabels[i] = (enum ctables_vlabel) tvars;
2458
2459   struct ctables *ct = xmalloc (sizeof *ct);
2460   *ct = (struct ctables) {
2461     .look = pivot_table_look_unshare (pivot_table_look_ref (
2462                                         pivot_table_look_get_default ())),
2463     .vlabels = vlabels,
2464     .hide_threshold = 5,
2465   };
2466   ct->look->omit_empty = false;
2467
2468   if (!lex_force_match (lexer, T_SLASH))
2469     goto error;
2470
2471   while (!lex_match_id (lexer, "TABLE"))
2472     {
2473       if (lex_match_id (lexer, "FORMAT"))
2474         {
2475           double widths[2] = { SYSMIS, SYSMIS };
2476           double units_per_inch = 72.0;
2477
2478           while (lex_token (lexer) != T_SLASH)
2479             {
2480               if (lex_match_id (lexer, "MINCOLWIDTH"))
2481                 {
2482                   if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
2483                     goto error;
2484                 }
2485               else if (lex_match_id (lexer, "MAXCOLWIDTH"))
2486                 {
2487                   if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
2488                     goto error;
2489                 }
2490               else if (lex_match_id (lexer, "UNITS"))
2491                 {
2492                   lex_match (lexer, T_EQUALS);
2493                   if (lex_match_id (lexer, "POINTS"))
2494                     units_per_inch = 72.0;
2495                   else if (lex_match_id (lexer, "INCHES"))
2496                     units_per_inch = 1.0;
2497                   else if (lex_match_id (lexer, "CM"))
2498                     units_per_inch = 2.54;
2499                   else
2500                     {
2501                       lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
2502                       goto error;
2503                     }
2504                 }
2505               else if (lex_match_id (lexer, "EMPTY"))
2506                 {
2507                   free (ct->zero);
2508                   ct->zero = NULL;
2509
2510                   lex_match (lexer, T_EQUALS);
2511                   if (lex_match_id (lexer, "ZERO"))
2512                     {
2513                       /* Nothing to do. */
2514                     }
2515                   else if (lex_match_id (lexer, "BLANK"))
2516                     ct->zero = xstrdup ("");
2517                   else if (lex_force_string (lexer))
2518                     {
2519                       ct->zero = ss_xstrdup (lex_tokss (lexer));
2520                       lex_get (lexer);
2521                     }
2522                   else
2523                     goto error;
2524                 }
2525               else if (lex_match_id (lexer, "MISSING"))
2526                 {
2527                   lex_match (lexer, T_EQUALS);
2528                   if (!lex_force_string (lexer))
2529                     goto error;
2530
2531                   free (ct->missing);
2532                   ct->missing = (strcmp (lex_tokcstr (lexer), ".")
2533                                  ? ss_xstrdup (lex_tokss (lexer))
2534                                  : NULL);
2535                   lex_get (lexer);
2536                 }
2537               else
2538                 {
2539                   lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
2540                                        "UNITS", "EMPTY", "MISSING");
2541                   goto error;
2542                 }
2543             }
2544
2545           if (widths[0] != SYSMIS && widths[1] != SYSMIS
2546               && widths[0] > widths[1])
2547             {
2548               msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
2549               goto error;
2550             }
2551
2552           for (size_t i = 0; i < 2; i++)
2553             if (widths[i] != SYSMIS)
2554               {
2555                 int *wr = ct->look->width_ranges[TABLE_HORZ];
2556                 wr[i] = widths[i] / units_per_inch * 96.0;
2557                 if (wr[0] > wr[1])
2558                   wr[!i] = wr[i];
2559               }
2560         }
2561       else if (lex_match_id (lexer, "VLABELS"))
2562         {
2563           if (!lex_force_match_id (lexer, "VARIABLES"))
2564             goto error;
2565           lex_match (lexer, T_EQUALS);
2566
2567           struct variable **vars;
2568           size_t n_vars;
2569           if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
2570                                 PV_NO_SCRATCH))
2571             goto error;
2572
2573           if (!lex_force_match_id (lexer, "DISPLAY"))
2574             {
2575               free (vars);
2576               goto error;
2577             }
2578           lex_match (lexer, T_EQUALS);
2579
2580           enum ctables_vlabel vlabel;
2581           if (lex_match_id (lexer, "DEFAULT"))
2582             vlabel = (enum ctables_vlabel) settings_get_show_variables ();
2583           else if (lex_match_id (lexer, "NAME"))
2584             vlabel = CTVL_NAME;
2585           else if (lex_match_id (lexer, "LABEL"))
2586             vlabel = CTVL_LABEL;
2587           else if (lex_match_id (lexer, "BOTH"))
2588             vlabel = CTVL_BOTH;
2589           else if (lex_match_id (lexer, "NONE"))
2590             vlabel = CTVL_NONE;
2591           else
2592             {
2593               lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
2594                                    "BOTH", "NONE");
2595               free (vars);
2596               goto error;
2597             }
2598
2599           for (size_t i = 0; i < n_vars; i++)
2600             ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
2601           free (vars);
2602         }
2603       else if (lex_match_id (lexer, "MRSETS"))
2604         {
2605           if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
2606             goto error;
2607           lex_match (lexer, T_EQUALS);
2608           if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
2609             goto error;
2610         }
2611       else if (lex_match_id (lexer, "SMISSING"))
2612         {
2613           if (lex_match_id (lexer, "VARIABLE"))
2614             ct->smissing_listwise = false;
2615           else if (lex_match_id (lexer, "LISTWISE"))
2616             ct->smissing_listwise = true;
2617           else
2618             {
2619               lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
2620               goto error;
2621             }
2622         }
2623       /* XXX PCOMPUTE */
2624       else if (lex_match_id (lexer, "WEIGHT"))
2625         {
2626           if (!lex_force_match_id (lexer, "VARIABLE"))
2627             goto error;
2628           lex_match (lexer, T_EQUALS);
2629           ct->base_weight = parse_variable (lexer, dataset_dict (ds));
2630           if (!ct->base_weight)
2631             goto error;
2632         }
2633       else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
2634         {
2635           if (!lex_force_match_id (lexer, "COUNT"))
2636             goto error;
2637           lex_match (lexer, T_EQUALS);
2638           if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
2639             goto error;
2640           ct->hide_threshold = lex_integer (lexer);
2641           lex_get (lexer);
2642         }
2643       else
2644         {
2645           lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
2646                                "SMISSING", "PCOMPUTE", "PPROPERTIES",
2647                                "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
2648           goto error;
2649         }
2650
2651       if (!lex_force_match (lexer, T_SLASH))
2652         goto error;
2653     }
2654
2655   size_t allocated_tables = 0;
2656   do
2657     {
2658       if (ct->n_tables >= allocated_tables)
2659         ct->tables = x2nrealloc (ct->tables, &allocated_tables,
2660                                  sizeof *ct->tables);
2661
2662       struct ctables_table *t = xmalloc (sizeof *t);
2663       *t = (struct ctables_table) {
2664         .ft = HMAP_INITIALIZER (t->ft),
2665         .slabels_position = PIVOT_AXIS_COLUMN,
2666         .slabels_visible = true,
2667         .row_labels = CTLP_NORMAL,
2668         .col_labels = CTLP_NORMAL,
2669         .categories = xcalloc (dict_get_n_vars (dataset_dict (ds)),
2670                                sizeof *t->categories),
2671         .n_categories = dict_get_n_vars (dataset_dict (ds)),
2672         .cilevel = 95,
2673       };
2674       for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2675         hmap_init (&t->domains[dt]);
2676       ct->tables[ct->n_tables++] = t;
2677
2678       lex_match (lexer, T_EQUALS);
2679       if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
2680         goto error;
2681       if (lex_match (lexer, T_BY))
2682         {
2683           if (!ctables_axis_parse (lexer, dataset_dict (ds),
2684                                    ct, t, PIVOT_AXIS_COLUMN))
2685             goto error;
2686
2687           if (lex_match (lexer, T_BY))
2688             {
2689               if (!ctables_axis_parse (lexer, dataset_dict (ds),
2690                                        ct, t, PIVOT_AXIS_LAYER))
2691                 goto error;
2692             }
2693         }
2694
2695       if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
2696           && !t->axes[PIVOT_AXIS_LAYER])
2697         {
2698           lex_error (lexer, _("At least one variable must be specified."));
2699           goto error;
2700         }
2701
2702       const struct ctables_axis *scales[PIVOT_N_AXES];
2703       size_t n_scales = 0;
2704       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2705         {
2706           scales[a] = find_scale (t->axes[a]);
2707           if (scales[a])
2708             n_scales++;
2709         }
2710       if (n_scales > 1)
2711         {
2712           msg (SE, _("Scale variables may appear only on one axis."));
2713           if (scales[PIVOT_AXIS_ROW])
2714             msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
2715                     _("This scale variable appears on the rows axis."));
2716           if (scales[PIVOT_AXIS_COLUMN])
2717             msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
2718                     _("This scale variable appears on the columns axis."));
2719           if (scales[PIVOT_AXIS_LAYER])
2720             msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
2721                     _("This scale variable appears on the layer axis."));
2722           goto error;
2723         }
2724
2725       const struct ctables_axis *summaries[PIVOT_N_AXES];
2726       size_t n_summaries = 0;
2727       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2728         {
2729           summaries[a] = (scales[a]
2730                           ? scales[a]
2731                           : find_categorical_summary_spec (t->axes[a]));
2732           if (summaries[a])
2733             n_summaries++;
2734         }
2735       if (n_summaries > 1)
2736         {
2737           msg (SE, _("Summaries may appear only on one axis."));
2738           if (summaries[PIVOT_AXIS_ROW])
2739             msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
2740                     _("This variable on the rows axis has a summary."));
2741           if (summaries[PIVOT_AXIS_COLUMN])
2742             msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
2743                     _("This variable on the columns axis has a summary."));
2744           if (summaries[PIVOT_AXIS_LAYER])
2745             msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
2746                     _("This variable on the layers axis has a summary."));
2747           goto error;
2748         }
2749       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2750         if (n_summaries ? summaries[a] : t->axes[a])
2751           {
2752             t->summary_axis = a;
2753             break;
2754           }
2755
2756       if (lex_token (lexer) == T_ENDCMD)
2757         break;
2758       if (!lex_force_match (lexer, T_SLASH))
2759         break;
2760
2761       while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
2762         {
2763           if (lex_match_id (lexer, "SLABELS"))
2764             {
2765               while (lex_token (lexer) != T_SLASH)
2766                 {
2767                   if (lex_match_id (lexer, "POSITION"))
2768                     {
2769                       lex_match (lexer, T_EQUALS);
2770                       if (lex_match_id (lexer, "COLUMN"))
2771                         t->slabels_position = PIVOT_AXIS_COLUMN;
2772                       else if (lex_match_id (lexer, "ROW"))
2773                         t->slabels_position = PIVOT_AXIS_ROW;
2774                       else if (lex_match_id (lexer, "LAYER"))
2775                         t->slabels_position = PIVOT_AXIS_LAYER;
2776                       else
2777                         {
2778                           lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
2779                           goto error;
2780                         }
2781                     }
2782                   else if (lex_match_id (lexer, "VISIBLE"))
2783                     {
2784                       lex_match (lexer, T_EQUALS);
2785                       if (!parse_bool (lexer, &t->slabels_visible))
2786                         goto error;
2787                     }
2788                   else
2789                     {
2790                       lex_error_expecting (lexer, "POSITION", "VISIBLE");
2791                       goto error;
2792                     }
2793                 }
2794             }
2795           else if (lex_match_id (lexer, "CLABELS"))
2796             {
2797               while (lex_token (lexer) != T_SLASH)
2798                 {
2799                   if (lex_match_id (lexer, "AUTO"))
2800                     t->row_labels = t->col_labels = CTLP_NORMAL;
2801                   else if (lex_match_id (lexer, "ROWLABELS"))
2802                     {
2803                       lex_match (lexer, T_EQUALS);
2804                       if (lex_match_id (lexer, "OPPOSITE"))
2805                         t->row_labels = CTLP_OPPOSITE;
2806                       else if (lex_match_id (lexer, "LAYER"))
2807                         t->row_labels = CTLP_LAYER;
2808                       else
2809                         {
2810                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
2811                           goto error;
2812                         }
2813                     }
2814                   else if (lex_match_id (lexer, "COLLABELS"))
2815                     {
2816                       lex_match (lexer, T_EQUALS);
2817                       if (lex_match_id (lexer, "OPPOSITE"))
2818                         t->col_labels = CTLP_OPPOSITE;
2819                       else if (lex_match_id (lexer, "LAYER"))
2820                         t->col_labels = CTLP_LAYER;
2821                       else
2822                         {
2823                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
2824                           goto error;
2825                         }
2826                     }
2827                   else
2828                     {
2829                       lex_error_expecting (lexer, "AUTO", "ROWLABELS",
2830                                            "COLLABELS");
2831                       goto error;
2832                     }
2833                 }
2834             }
2835           else if (lex_match_id (lexer, "CRITERIA"))
2836             {
2837               if (!lex_force_match_id (lexer, "CILEVEL"))
2838                 goto error;
2839               lex_match (lexer, T_EQUALS);
2840
2841               if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
2842                 goto error;
2843               t->cilevel = lex_number (lexer);
2844               lex_get (lexer);
2845             }
2846           else if (lex_match_id (lexer, "CATEGORIES"))
2847             {
2848               if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
2849                 goto error;
2850             }
2851           else if (lex_match_id (lexer, "TITLES"))
2852             {
2853               do
2854                 {
2855                   char **textp;
2856                   if (lex_match_id (lexer, "CAPTION"))
2857                     textp = &t->caption;
2858                   else if (lex_match_id (lexer, "CORNER"))
2859                     textp = &t->corner;
2860                   else if (lex_match_id (lexer, "TITLE"))
2861                     textp = &t->title;
2862                   else
2863                     {
2864                       lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
2865                       goto error;
2866                     }
2867                   lex_match (lexer, T_EQUALS);
2868
2869                   struct string s = DS_EMPTY_INITIALIZER;
2870                   while (lex_is_string (lexer))
2871                     {
2872                       if (!ds_is_empty (&s))
2873                         ds_put_byte (&s, ' ');
2874                       ds_put_substring (&s, lex_tokss (lexer));
2875                       lex_get (lexer);
2876                     }
2877                   free (*textp);
2878                   *textp = ds_steal_cstr (&s);
2879                 }
2880               while (lex_token (lexer) != T_SLASH
2881                      && lex_token (lexer) != T_ENDCMD);
2882             }
2883           else if (lex_match_id (lexer, "SIGTEST"))
2884             {
2885               if (!t->chisq)
2886                 {
2887                   t->chisq = xmalloc (sizeof *t->chisq);
2888                   *t->chisq = (struct ctables_chisq) {
2889                     .alpha = .05,
2890                     .include_mrsets = true,
2891                     .all_visible = true,
2892                   };
2893                 }
2894
2895               do
2896                 {
2897                   if (lex_match_id (lexer, "TYPE"))
2898                     {
2899                       lex_match (lexer, T_EQUALS);
2900                       if (!lex_force_match_id (lexer, "CHISQUARE"))
2901                         goto error;
2902                     }
2903                   else if (lex_match_id (lexer, "ALPHA"))
2904                     {
2905                       lex_match (lexer, T_EQUALS);
2906                       if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
2907                         goto error;
2908                       t->chisq->alpha = lex_number (lexer);
2909                       lex_get (lexer);
2910                     }
2911                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
2912                     {
2913                       lex_match (lexer, T_EQUALS);
2914                       if (parse_bool (lexer, &t->chisq->include_mrsets))
2915                         goto error;
2916                     }
2917                   else if (lex_match_id (lexer, "CATEGORIES"))
2918                     {
2919                       lex_match (lexer, T_EQUALS);
2920                       if (lex_match_id (lexer, "ALLVISIBLE"))
2921                         t->chisq->all_visible = true;
2922                       else if (lex_match_id (lexer, "SUBTOTALS"))
2923                         t->chisq->all_visible = false;
2924                       else
2925                         {
2926                           lex_error_expecting (lexer,
2927                                                "ALLVISIBLE", "SUBTOTALS");
2928                           goto error;
2929                         }
2930                     }
2931                   else
2932                     {
2933                       lex_error_expecting (lexer, "TYPE", "ALPHA",
2934                                            "INCLUDEMRSETS", "CATEGORIES");
2935                       goto error;
2936                     }
2937                 }
2938               while (lex_token (lexer) != T_SLASH
2939                      && lex_token (lexer) != T_ENDCMD);
2940             }
2941           else if (lex_match_id (lexer, "COMPARETEST"))
2942             {
2943               if (!t->pairwise)
2944                 {
2945                   t->pairwise = xmalloc (sizeof *t->pairwise);
2946                   *t->pairwise = (struct ctables_pairwise) {
2947                     .type = PROP,
2948                     .alpha = { .05, .05 },
2949                     .adjust = BONFERRONI,
2950                     .include_mrsets = true,
2951                     .meansvariance_allcats = true,
2952                     .all_visible = true,
2953                     .merge = false,
2954                     .apa_style = true,
2955                     .show_sig = false,
2956                   };
2957                 }
2958
2959               do
2960                 {
2961                   if (lex_match_id (lexer, "TYPE"))
2962                     {
2963                       lex_match (lexer, T_EQUALS);
2964                       if (lex_match_id (lexer, "PROP"))
2965                         t->pairwise->type = PROP;
2966                       else if (lex_match_id (lexer, "MEAN"))
2967                         t->pairwise->type = MEAN;
2968                       else
2969                         {
2970                           lex_error_expecting (lexer, "PROP", "MEAN");
2971                           goto error;
2972                         }
2973                     }
2974                   else if (lex_match_id (lexer, "ALPHA"))
2975                     {
2976                       lex_match (lexer, T_EQUALS);
2977
2978                       if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
2979                         goto error;
2980                       double a0 = lex_number (lexer);
2981                       lex_get (lexer);
2982
2983                       lex_match (lexer, T_COMMA);
2984                       if (lex_is_number (lexer))
2985                         {
2986                           if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
2987                             goto error;
2988                           double a1 = lex_number (lexer);
2989                           lex_get (lexer);
2990
2991                           t->pairwise->alpha[0] = MIN (a0, a1);
2992                           t->pairwise->alpha[1] = MAX (a0, a1);
2993                         }
2994                       else
2995                         t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
2996                     }
2997                   else if (lex_match_id (lexer, "ADJUST"))
2998                     {
2999                       lex_match (lexer, T_EQUALS);
3000                       if (lex_match_id (lexer, "BONFERRONI"))
3001                         t->pairwise->adjust = BONFERRONI;
3002                       else if (lex_match_id (lexer, "BH"))
3003                         t->pairwise->adjust = BH;
3004                       else if (lex_match_id (lexer, "NONE"))
3005                         t->pairwise->adjust = 0;
3006                       else
3007                         {
3008                           lex_error_expecting (lexer, "BONFERRONI", "BH",
3009                                                "NONE");
3010                           goto error;
3011                         }
3012                     }
3013                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3014                     {
3015                       lex_match (lexer, T_EQUALS);
3016                       if (!parse_bool (lexer, &t->pairwise->include_mrsets))
3017                         goto error;
3018                     }
3019                   else if (lex_match_id (lexer, "MEANSVARIANCE"))
3020                     {
3021                       lex_match (lexer, T_EQUALS);
3022                       if (lex_match_id (lexer, "ALLCATS"))
3023                         t->pairwise->meansvariance_allcats = true;
3024                       else if (lex_match_id (lexer, "TESTEDCATS"))
3025                         t->pairwise->meansvariance_allcats = false;
3026                       else
3027                         {
3028                           lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
3029                           goto error;
3030                         }
3031                     }
3032                   else if (lex_match_id (lexer, "CATEGORIES"))
3033                     {
3034                       lex_match (lexer, T_EQUALS);
3035                       if (lex_match_id (lexer, "ALLVISIBLE"))
3036                         t->pairwise->all_visible = true;
3037                       else if (lex_match_id (lexer, "SUBTOTALS"))
3038                         t->pairwise->all_visible = false;
3039                       else
3040                         {
3041                           lex_error_expecting (lexer, "ALLVISIBLE",
3042                                                "SUBTOTALS");
3043                           goto error;
3044                         }
3045                     }
3046                   else if (lex_match_id (lexer, "MERGE"))
3047                     {
3048                       lex_match (lexer, T_EQUALS);
3049                       if (!parse_bool (lexer, &t->pairwise->merge))
3050                         goto error;
3051                     }
3052                   else if (lex_match_id (lexer, "STYLE"))
3053                     {
3054                       lex_match (lexer, T_EQUALS);
3055                       if (lex_match_id (lexer, "APA"))
3056                         t->pairwise->apa_style = true;
3057                       else if (lex_match_id (lexer, "SIMPLE"))
3058                         t->pairwise->apa_style = false;
3059                       else
3060                         {
3061                           lex_error_expecting (lexer, "APA", "SIMPLE");
3062                           goto error;
3063                         }
3064                     }
3065                   else if (lex_match_id (lexer, "SHOWSIG"))
3066                     {
3067                       lex_match (lexer, T_EQUALS);
3068                       if (!parse_bool (lexer, &t->pairwise->show_sig))
3069                         goto error;
3070                     }
3071                   else
3072                     {
3073                       lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
3074                                            "INCLUDEMRSETS", "MEANSVARIANCE",
3075                                            "CATEGORIES", "MERGE", "STYLE",
3076                                            "SHOWSIG");
3077                       goto error;
3078                     }
3079                 }
3080               while (lex_token (lexer) != T_SLASH
3081                      && lex_token (lexer) != T_ENDCMD);
3082             }
3083           else
3084             {
3085               lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
3086                                    "CRITERIA", "CATEGORIES", "TITLES",
3087                                    "SIGTEST", "COMPARETEST");
3088               goto error;
3089             }
3090         }
3091
3092       if (t->row_labels != CTLP_NORMAL && t->col_labels != CTLP_NORMAL)
3093         {
3094           msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
3095           goto error;
3096         }
3097
3098     }
3099   while (lex_token (lexer) != T_ENDCMD);
3100
3101   bool ok = ctables_execute (ds, ct);
3102   ctables_destroy (ct);
3103   return ok ? CMD_SUCCESS : CMD_FAILURE;
3104
3105 error:
3106   ctables_destroy (ct);
3107   return CMD_FAILURE;
3108 }
3109