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