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