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