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