Add support for reading and writing SPV files.
[pspp] / src / language / dictionary / sys-file-info.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2009, 2010, 2011, 2012, 2013, 2014 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 #include <config.h>
17
18 #include <ctype.h>
19 #include <errno.h>
20 #include <float.h>
21 #include <stdlib.h>
22
23 #include "data/any-reader.h"
24 #include "data/attributes.h"
25 #include "data/casereader.h"
26 #include "data/dataset.h"
27 #include "data/dictionary.h"
28 #include "data/file-handle-def.h"
29 #include "data/format.h"
30 #include "data/missing-values.h"
31 #include "data/value-labels.h"
32 #include "data/variable.h"
33 #include "data/vector.h"
34 #include "language/command.h"
35 #include "language/data-io/file-handle.h"
36 #include "language/lexer/lexer.h"
37 #include "language/lexer/variable-parser.h"
38 #include "libpspp/array.h"
39 #include "libpspp/hash-functions.h"
40 #include "libpspp/i18n.h"
41 #include "libpspp/message.h"
42 #include "libpspp/misc.h"
43 #include "libpspp/pool.h"
44 #include "libpspp/string-array.h"
45 #include "output/pivot-table.h"
46 #include "output/text-item.h"
47 #include "output/table-item.h"
48
49 #include "gl/count-one-bits.h"
50 #include "gl/localcharset.h"
51 #include "gl/intprops.h"
52 #include "gl/minmax.h"
53 #include "gl/xalloc.h"
54
55 #include "gettext.h"
56 #define _(msgid) gettext (msgid)
57 #define N_(msgid) (msgid)
58
59 /* Information to include in displaying a dictionary. */
60 enum
61   {
62     /* Variable table. */
63     DF_NAME              = 1 << 0,
64     DF_POSITION          = 1 << 1,
65     DF_LABEL             = 1 << 2,
66     DF_MEASUREMENT_LEVEL = 1 << 3,
67     DF_ROLE              = 1 << 4,
68     DF_WIDTH             = 1 << 5,
69     DF_ALIGNMENT         = 1 << 6,
70     DF_PRINT_FORMAT      = 1 << 7,
71     DF_WRITE_FORMAT      = 1 << 8,
72     DF_MISSING_VALUES    = 1 << 9,
73 #define DF_ALL_VARIABLE ((1 << 10) - 1)
74
75     /* Value labels table. */
76     DF_VALUE_LABELS      = 1 << 10,
77
78     /* Attribute table. */
79     DF_AT_ATTRIBUTES     = 1 << 11, /* Attributes whose names begin with @. */
80     DF_ATTRIBUTES        = 1 << 12, /* All other attributes. */
81   };
82
83 static void display_variables (const struct variable **, size_t, int flags);
84 static void display_value_labels (const struct variable **, size_t);
85 static void display_attributes (const struct attrset *,
86                                 const struct variable **, size_t, int flags);
87
88 static void report_encodings (const struct file_handle *, struct pool *,
89                               char **titles, bool *ids,
90                               char **strings, size_t n_strings);
91
92 static void
93 add_row (struct pivot_table *table, const char *attribute,
94          struct pivot_value *value)
95 {
96   int row = pivot_category_create_leaf (table->dimensions[0]->root,
97                                         pivot_value_new_text (attribute));
98   if (value)
99     pivot_table_put1 (table, row, value);
100 }
101
102 /* SYSFILE INFO utility. */
103 int
104 cmd_sysfile_info (struct lexer *lexer, struct dataset *ds UNUSED)
105 {
106   struct any_reader *any_reader;
107   struct file_handle *h;
108   struct dictionary *d;
109   struct casereader *reader;
110   struct any_read_info info;
111   char *encoding;
112
113   h = NULL;
114   encoding = NULL;
115   for (;;)
116     {
117       lex_match (lexer, T_SLASH);
118
119       if (lex_match_id (lexer, "FILE") || lex_is_string (lexer))
120         {
121           lex_match (lexer, T_EQUALS);
122
123           fh_unref (h);
124           h = fh_parse (lexer, FH_REF_FILE, NULL);
125           if (h == NULL)
126             goto error;
127         }
128       else if (lex_match_id (lexer, "ENCODING"))
129         {
130           lex_match (lexer, T_EQUALS);
131
132           if (!lex_force_string (lexer))
133             goto error;
134
135           free (encoding);
136           encoding = ss_xstrdup (lex_tokss (lexer));
137
138           lex_get (lexer);
139         }
140       else
141         break;
142     }
143
144   if (h == NULL)
145     {
146       lex_sbc_missing ("FILE");
147       goto error;
148     }
149
150   any_reader = any_reader_open (h);
151   if (!any_reader)
152     {
153       free (encoding);
154       return CMD_FAILURE;
155     }
156
157   if (encoding && !strcasecmp (encoding, "detect"))
158     {
159       char **titles, **strings;
160       struct pool *pool;
161       size_t n_strings;
162       bool *ids;
163
164       pool = pool_create ();
165       n_strings = any_reader_get_strings (any_reader, pool,
166                                           &titles, &ids, &strings);
167       any_reader_close (any_reader);
168
169       report_encodings (h, pool, titles, ids, strings, n_strings);
170       fh_unref (h);
171       pool_destroy (pool);
172       free (encoding);
173
174       return CMD_SUCCESS;
175     }
176
177   reader = any_reader_decode (any_reader, encoding, &d, &info);
178   if (!reader)
179     goto error;
180   casereader_destroy (reader);
181
182   struct pivot_table *table = pivot_table_create (N_("File Information"));
183   pivot_dimension_create (table, PIVOT_AXIS_ROW, N_("Attribute"));
184
185   add_row (table, N_("File"),
186            pivot_value_new_user_text (fh_get_file_name (h), -1));
187
188   const char *label = dict_get_label (d);
189   add_row (table, N_("Label"),
190            label ? pivot_value_new_user_text (label, -1) : NULL);
191
192   add_row (table, N_("Created"),
193            pivot_value_new_user_text_nocopy (
194              xasprintf ("%s %s by %s", info.creation_date,
195                         info.creation_time, info.product)));
196
197   if (info.product_ext)
198     add_row (table, N_("Product"),
199              pivot_value_new_user_text (info.product_ext, -1));
200
201   add_row (table, N_("Integer Format"),
202            pivot_value_new_text (
203              info.integer_format == INTEGER_MSB_FIRST ? N_("Big Endian")
204              : info.integer_format == INTEGER_LSB_FIRST ? N_("Little Endian")
205              : N_("Unknown")));
206
207   add_row (table, N_("Real Format"),
208            pivot_value_new_text (
209              info.float_format == FLOAT_IEEE_DOUBLE_LE ? N_("IEEE 754 LE.")
210              : info.float_format == FLOAT_IEEE_DOUBLE_BE ? N_("IEEE 754 BE.")
211              : info.float_format == FLOAT_VAX_D ? N_("VAX D.")
212              : info.float_format == FLOAT_VAX_G ? N_("VAX G.")
213              : info.float_format == FLOAT_Z_LONG ? N_("IBM 390 Hex Long.")
214              : N_("Unknown")));
215
216   add_row (table, N_("Variables"),
217            pivot_value_new_integer (dict_get_var_cnt (d)));
218
219   add_row (table, N_("Cases"),
220            (info.case_cnt == -1
221             ? pivot_value_new_text (N_("Unknown"))
222             : pivot_value_new_integer (info.case_cnt)));
223
224   add_row (table, N_("Type"),
225            pivot_value_new_text (info.klass->name));
226
227   struct variable *weight_var = dict_get_weight (d);
228   add_row (table, N_("Weight"),
229            (weight_var
230             ? pivot_value_new_variable (weight_var)
231             : pivot_value_new_text (N_("Not weighted"))));
232
233   add_row (table, N_("Compression"),
234            (info.compression == ANY_COMP_NONE
235             ? pivot_value_new_text (N_("None"))
236             : pivot_value_new_user_text (
237               info.compression == ANY_COMP_SIMPLE ? "SAV" : "ZSAV", -1)));
238
239   add_row (table, N_("Encoding"),
240            pivot_value_new_user_text (dict_get_encoding (d), -1));
241
242   pivot_table_submit (table);
243
244   size_t n_vars = dict_get_var_cnt (d);
245   const struct variable **vars = xnmalloc (n_vars, sizeof *vars);
246   for (size_t i = 0; i < dict_get_var_cnt (d); i++)
247     vars[i] = dict_get_var (d, i);
248   display_variables (vars, n_vars, DF_ALL_VARIABLE);
249   display_value_labels (vars, n_vars);
250   display_attributes (dict_get_attributes (dataset_dict (ds)),
251                       vars, n_vars, DF_ATTRIBUTES);
252   free (vars);
253
254   dict_unref (d);
255
256   fh_unref (h);
257   free (encoding);
258   any_read_info_destroy (&info);
259   return CMD_SUCCESS;
260
261 error:
262   fh_unref (h);
263   free (encoding);
264   return CMD_FAILURE;
265 }
266 \f
267 /* DISPLAY utility. */
268
269 static void display_macros (void);
270 static void display_documents (const struct dictionary *dict);
271 static void display_vectors (const struct dictionary *dict, int sorted);
272
273 int
274 cmd_display (struct lexer *lexer, struct dataset *ds)
275 {
276   /* Whether to sort the list of variables alphabetically. */
277   int sorted;
278
279   /* Variables to display. */
280   size_t n;
281   const struct variable **vl;
282
283   if (lex_match_id (lexer, "MACROS"))
284     display_macros ();
285   else if (lex_match_id (lexer, "DOCUMENTS"))
286     display_documents (dataset_dict (ds));
287   else if (lex_match_id (lexer, "FILE"))
288     {
289       if (!lex_force_match_id (lexer, "LABEL"))
290         return CMD_FAILURE;
291
292       const char *label = dict_get_label (dataset_dict (ds));
293
294       struct pivot_table *table = pivot_table_create (N_("File Label"));
295       pivot_dimension_create (table, PIVOT_AXIS_ROW, N_("Label"),
296                               N_("Label"));
297       pivot_table_put1 (table, 0,
298                         (label ? pivot_value_new_user_text (label, -1)
299                          : pivot_value_new_text (N_("(none)"))));
300       pivot_table_submit (table);
301     }
302   else
303     {
304       int flags;
305
306       sorted = lex_match_id (lexer, "SORTED");
307
308       if (lex_match_id (lexer, "VECTORS"))
309         {
310           display_vectors (dataset_dict(ds), sorted);
311           return CMD_SUCCESS;
312         }
313       else if (lex_match_id (lexer, "SCRATCH"))
314         {
315           dict_get_vars (dataset_dict (ds), &vl, &n, DC_ORDINARY);
316           flags = DF_NAME;
317         }
318       else
319         {
320           struct subcommand
321             {
322               const char *name;
323               int flags;
324             };
325           static const struct subcommand subcommands[] =
326             {
327               {"@ATTRIBUTES", DF_ATTRIBUTES | DF_AT_ATTRIBUTES},
328               {"ATTRIBUTES", DF_ATTRIBUTES},
329               {"DICTIONARY", (DF_NAME | DF_POSITION | DF_LABEL
330                               | DF_MEASUREMENT_LEVEL | DF_ROLE | DF_WIDTH
331                               | DF_ALIGNMENT | DF_PRINT_FORMAT
332                               | DF_WRITE_FORMAT | DF_MISSING_VALUES
333                               | DF_VALUE_LABELS)},
334               {"INDEX", DF_NAME | DF_POSITION},
335               {"LABELS", DF_NAME | DF_POSITION | DF_LABEL},
336               {"NAMES", DF_NAME},
337               {"VARIABLES", (DF_NAME | DF_POSITION | DF_PRINT_FORMAT
338                              | DF_WRITE_FORMAT | DF_MISSING_VALUES)},
339               {NULL, 0},
340             };
341           const struct subcommand *sbc;
342           struct dictionary *dict = dataset_dict (ds);
343
344           flags = 0;
345           for (sbc = subcommands; sbc->name != NULL; sbc++)
346             if (lex_match_id (lexer, sbc->name))
347               {
348                 flags = sbc->flags;
349                 break;
350               }
351
352           lex_match (lexer, T_SLASH);
353           lex_match_id (lexer, "VARIABLES");
354           lex_match (lexer, T_EQUALS);
355
356           if (lex_token (lexer) != T_ENDCMD)
357             {
358               if (!parse_variables_const (lexer, dict, &vl, &n, PV_NONE))
359                 {
360                   free (vl);
361                   return CMD_FAILURE;
362                 }
363             }
364           else
365             dict_get_vars (dict, &vl, &n, 0);
366         }
367
368       if (n > 0)
369         {
370           sort (vl, n, sizeof *vl, (sorted
371                                     ? compare_var_ptrs_by_name
372                                     : compare_var_ptrs_by_dict_index), NULL);
373
374           int variable_flags = flags & DF_ALL_VARIABLE;
375           if (variable_flags)
376             display_variables (vl, n, variable_flags);
377
378           if (flags & DF_VALUE_LABELS)
379             display_value_labels (vl, n);
380
381           int attribute_flags = flags & (DF_ATTRIBUTES | DF_AT_ATTRIBUTES);
382           if (attribute_flags)
383             display_attributes (dict_get_attributes (dataset_dict (ds)),
384                                 vl, n, attribute_flags);
385         }
386       else
387         msg (SW, _("No variables to display."));
388
389       free (vl);
390     }
391
392   return CMD_SUCCESS;
393 }
394
395 static void
396 display_macros (void)
397 {
398   msg (SW, _("Macros not supported."));
399 }
400
401 static void
402 display_documents (const struct dictionary *dict)
403 {
404   struct pivot_table *table = pivot_table_create (N_("Documents"));
405   struct pivot_dimension *d = pivot_dimension_create (
406     table, PIVOT_AXIS_COLUMN, N_("Documents"), N_("Document"));
407   d->hide_all_labels = true;
408
409   const struct string_array *documents = dict_get_documents (dict);
410   if (!documents->n)
411     pivot_table_put1 (table, 0, pivot_value_new_text (N_("(none)")));
412   else
413     {
414       struct string s = DS_EMPTY_INITIALIZER;
415       for (size_t i = 0; i < documents->n; i++)
416         {
417           if (i)
418             ds_put_byte (&s, '\n');
419           ds_put_cstr (&s, documents->strings[i]);
420         }
421       pivot_table_put1 (table, 0,
422                         pivot_value_new_user_text_nocopy (ds_steal_cstr (&s)));
423     }
424
425   pivot_table_submit (table);
426 }
427
428 static void
429 display_variables (const struct variable **vl, size_t n, int flags)
430 {
431   struct pivot_table *table = pivot_table_create (N_("Variables"));
432
433   struct pivot_dimension *attributes = pivot_dimension_create (
434     table, PIVOT_AXIS_COLUMN, N_("Attributes"));
435
436   struct heading
437     {
438       int flag;
439       const char *title;
440     };
441   static const struct heading headings[] = {
442     { DF_POSITION, N_("Position") },
443     { DF_LABEL, N_("Label") },
444     { DF_MEASUREMENT_LEVEL, N_("Measurement Level") },
445     { DF_ROLE, N_("Role") },
446     { DF_WIDTH, N_("Width") },
447     { DF_ALIGNMENT, N_("Alignment") },
448     { DF_PRINT_FORMAT, N_("Print Format") },
449     { DF_WRITE_FORMAT, N_("Write Format") },
450     { DF_MISSING_VALUES, N_("Missing Values") },
451   };
452   for (size_t i = 0; i < sizeof headings / sizeof *headings; i++)
453     if (flags & headings[i].flag)
454       pivot_category_create_leaf (attributes->root,
455                                   pivot_value_new_text (headings[i].title));
456
457   struct pivot_dimension *names = pivot_dimension_create (
458     table, PIVOT_AXIS_ROW, N_("Name"));
459   names->root->show_label = true;
460
461   for (size_t i = 0; i < n; i++)
462     {
463       const struct variable *v = vl[i];
464
465       struct pivot_value *name = pivot_value_new_variable (v);
466       name->variable.show = SETTINGS_VALUE_SHOW_VALUE;
467       int row = pivot_category_create_leaf (names->root, name);
468
469       int x = 0;
470       if (flags & DF_POSITION)
471         pivot_table_put2 (table, x++, row, pivot_value_new_integer (
472                             var_get_dict_index (v) + 1));
473
474       if (flags & DF_LABEL)
475         {
476           const char *label = var_get_label (v);
477           if (label)
478             pivot_table_put2 (table, x, row,
479                               pivot_value_new_user_text (label, -1));
480           x++;
481         }
482
483       if (flags & DF_MEASUREMENT_LEVEL)
484         pivot_table_put2 (
485           table, x++, row,
486           pivot_value_new_text (measure_to_string (var_get_measure (v))));
487
488       if (flags & DF_ROLE)
489         pivot_table_put2 (
490           table, x++, row,
491           pivot_value_new_text (var_role_to_string (var_get_role (v))));
492
493       if (flags & DF_WIDTH)
494         pivot_table_put2 (
495           table, x++, row,
496           pivot_value_new_integer (var_get_display_width (v)));
497
498       if (flags & DF_ALIGNMENT)
499         pivot_table_put2 (
500           table, x++, row,
501           pivot_value_new_text (alignment_to_string (
502                                   var_get_alignment (v))));
503
504       if (flags & DF_PRINT_FORMAT)
505         {
506           const struct fmt_spec *print = var_get_print_format (v);
507           char s[FMT_STRING_LEN_MAX + 1];
508
509           pivot_table_put2 (
510             table, x++, row,
511             pivot_value_new_user_text (fmt_to_string (print, s), -1));
512         }
513
514       if (flags & DF_WRITE_FORMAT)
515         {
516           const struct fmt_spec *write = var_get_write_format (v);
517           char s[FMT_STRING_LEN_MAX + 1];
518
519           pivot_table_put2 (
520             table, x++, row,
521             pivot_value_new_user_text (fmt_to_string (write, s), -1));
522         }
523
524       if (flags & DF_MISSING_VALUES)
525         {
526           char *s = mv_to_string (var_get_missing_values (v),
527                                   var_get_encoding (v));
528           if (s)
529             pivot_table_put2 (
530               table, x, row,
531               pivot_value_new_user_text_nocopy (s));
532
533           x++;
534         }
535     }
536
537   pivot_table_submit (table);
538 }
539
540 static bool
541 any_value_labels (const struct variable **vars, size_t n_vars)
542 {
543   for (size_t i = 0; i < n_vars; i++)
544     if (val_labs_count (var_get_value_labels (vars[i])))
545       return true;
546   return false;
547 }
548
549 static void
550 display_value_labels (const struct variable **vars, size_t n_vars)
551 {
552   if (!any_value_labels (vars, n_vars))
553     return;
554
555   struct pivot_table *table = pivot_table_create (N_("Value Labels"));
556
557   pivot_dimension_create (table, PIVOT_AXIS_COLUMN,
558                           N_("Label"), N_("Label"));
559
560   struct pivot_dimension *values = pivot_dimension_create (
561     table, PIVOT_AXIS_ROW, N_("Variable Value"));
562   values->root->show_label = true;
563
564   struct pivot_footnote *missing_footnote = pivot_table_create_footnote (
565     table, pivot_value_new_text (N_("User-missing value")));
566
567   for (size_t i = 0; i < n_vars; i++)
568     {
569       const struct val_labs *val_labs = var_get_value_labels (vars[i]);
570       size_t n_labels = val_labs_count (val_labs);
571       if (!n_labels)
572         continue;
573
574       struct pivot_category *group = pivot_category_create_group__ (
575         values->root, pivot_value_new_variable (vars[i]));
576
577       const struct val_lab **labels = val_labs_sorted (val_labs);
578       for (size_t j = 0; j < n_labels; j++)
579         {
580           const struct val_lab *vl = labels[j];
581
582           struct pivot_value *value = pivot_value_new_var_value (
583             vars[i], &vl->value);
584           if (value->type == PIVOT_VALUE_NUMERIC)
585             value->numeric.show = SETTINGS_VALUE_SHOW_VALUE;
586           else
587             value->string.show = SETTINGS_VALUE_SHOW_VALUE;
588           if (var_is_value_missing (vars[i], &vl->value, MV_USER))
589             pivot_value_add_footnote (value, missing_footnote);
590           int row = pivot_category_create_leaf (group, value);
591
592           struct pivot_value *label = pivot_value_new_var_value (
593             vars[i], &vl->value);
594           char *escaped_label = xstrdup (val_lab_get_escaped_label (vl));
595           if (label->type == PIVOT_VALUE_NUMERIC)
596             {
597               free (label->numeric.value_label);
598               label->numeric.value_label = escaped_label;
599               label->numeric.show = SETTINGS_VALUE_SHOW_LABEL;
600             }
601           else
602             {
603               free (label->string.value_label);
604               label->string.value_label = escaped_label;
605               label->string.show = SETTINGS_VALUE_SHOW_LABEL;
606             }
607           pivot_table_put2 (table, 0, row, label);
608         }
609       free (labels);
610     }
611   pivot_table_submit (table);
612 }
613 \f
614 static bool
615 is_at_name (const char *name)
616 {
617   return name[0] == '@' || (name[0] == '$' && name[1] == '@');
618 }
619
620 static size_t
621 count_attributes (const struct attrset *set, int flags)
622 {
623   struct attrset_iterator i;
624   struct attribute *attr;
625   size_t n_attrs;
626
627   n_attrs = 0;
628   for (attr = attrset_first (set, &i); attr != NULL;
629        attr = attrset_next (set, &i))
630     if (flags & DF_AT_ATTRIBUTES || !is_at_name (attribute_get_name (attr)))
631       n_attrs += attribute_get_n_values (attr);
632   return n_attrs;
633 }
634
635 static void
636 display_attrset (struct pivot_table *table, struct pivot_value *set_name,
637                  const struct attrset *set, int flags)
638 {
639   size_t n_total = count_attributes (set, flags);
640   if (!n_total)
641     {
642       pivot_value_destroy (set_name);
643       return;
644     }
645
646   struct pivot_category *group = pivot_category_create_group__ (
647     table->dimensions[1]->root, set_name);
648
649   size_t n_attrs = attrset_count (set);
650   struct attribute **attrs = attrset_sorted (set);
651   for (size_t i = 0; i < n_attrs; i++)
652     {
653       const struct attribute *attr = attrs[i];
654       const char *name = attribute_get_name (attr);
655
656       if (!(flags & DF_AT_ATTRIBUTES) && is_at_name (name))
657         continue;
658
659       size_t n_values = attribute_get_n_values (attr);
660       for (size_t j = 0; j < n_values; j++)
661         {
662           int row = pivot_category_create_leaf (
663             group,
664             (n_values > 1
665              ? pivot_value_new_user_text_nocopy (xasprintf (
666                                                    "%s[%zu]", name, j + 1))
667              : pivot_value_new_user_text (name, -1)));
668           pivot_table_put2 (table, 0, row,
669                             pivot_value_new_user_text (
670                               attribute_get_value (attr, j), -1));
671         }
672     }
673   free (attrs);
674 }
675
676 static void
677 display_attributes (const struct attrset *dict_attrset,
678                     const struct variable **vars, size_t n_vars, int flags)
679 {
680   struct pivot_table *table = pivot_table_create (
681     N_("Variable and Dataset Attributes"));
682
683   pivot_dimension_create (table, PIVOT_AXIS_COLUMN,
684                           N_("Value"), N_("Value"));
685
686   struct pivot_dimension *variables = pivot_dimension_create (
687     table, PIVOT_AXIS_ROW, N_("Variable and Name"));
688   variables->root->show_label = true;
689
690   display_attrset (table, pivot_value_new_text (N_("(dataset)")),
691                    dict_attrset, flags);
692   for (size_t i = 0; i < n_vars; i++)
693     display_attrset (table, pivot_value_new_variable (vars[i]),
694                      var_get_attributes (vars[i]), flags);
695
696   if (pivot_table_is_empty (table))
697     pivot_table_unref (table);
698   else
699     pivot_table_submit (table);
700 }
701
702 /* Display a list of vectors.  If SORTED is nonzero then they are
703    sorted alphabetically. */
704 static void
705 display_vectors (const struct dictionary *dict, int sorted)
706 {
707   size_t n_vectors = dict_get_vector_cnt (dict);
708   if (n_vectors == 0)
709     {
710       msg (SW, _("No vectors defined."));
711       return;
712     }
713
714   const struct vector **vectors = xnmalloc (n_vectors, sizeof *vectors);
715   for (size_t i = 0; i < n_vectors; i++)
716     vectors[i] = dict_get_vector (dict, i);
717   if (sorted)
718     qsort (vectors, n_vectors, sizeof *vectors, compare_vector_ptrs_by_name);
719
720   struct pivot_table *table = pivot_table_create (N_("Vectors"));
721   pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Attributes"),
722                           N_("Variable"), N_("Print Format"));
723   struct pivot_dimension *vector_dim = pivot_dimension_create (
724     table, PIVOT_AXIS_ROW, N_("Vector and Position"));
725   vector_dim->root->show_label = true;
726
727   for (size_t i = 0; i < n_vectors; i++)
728     {
729       const struct vector *vec = vectors[i];
730
731       struct pivot_category *group = pivot_category_create_group__ (
732         vector_dim->root, pivot_value_new_user_text (
733           vector_get_name (vectors[i]), -1));
734
735       for (size_t j = 0; j < vector_get_var_cnt (vec); j++)
736         {
737           struct variable *var = vector_get_var (vec, j);
738
739           int row = pivot_category_create_leaf (
740             group, pivot_value_new_integer (j + 1));
741
742           pivot_table_put2 (table, 0, row, pivot_value_new_variable (var));
743           char fmt_string[FMT_STRING_LEN_MAX + 1];
744           fmt_to_string (var_get_print_format (var), fmt_string);
745           pivot_table_put2 (table, 1, row,
746                             pivot_value_new_user_text (fmt_string, -1));
747         }
748     }
749
750   pivot_table_submit (table);
751
752   free (vectors);
753 }
754 \f
755 /* Encoding analysis. */
756
757 static const char *encoding_names[] = {
758   /* These encodings are from http://encoding.spec.whatwg.org/, as retrieved
759      February 2014.  Encodings not supported by glibc and encodings relevant
760      only to HTML have been removed. */
761   "utf-8",
762   "windows-1252",
763   "iso-8859-2",
764   "iso-8859-3",
765   "iso-8859-4",
766   "iso-8859-5",
767   "iso-8859-6",
768   "iso-8859-7",
769   "iso-8859-8",
770   "iso-8859-10",
771   "iso-8859-13",
772   "iso-8859-14",
773   "iso-8859-16",
774   "macintosh",
775   "windows-874",
776   "windows-1250",
777   "windows-1251",
778   "windows-1253",
779   "windows-1254",
780   "windows-1255",
781   "windows-1256",
782   "windows-1257",
783   "windows-1258",
784   "koi8-r",
785   "koi8-u",
786   "ibm866",
787   "gb18030",
788   "big5",
789   "euc-jp",
790   "iso-2022-jp",
791   "shift_jis",
792   "euc-kr",
793
794   /* Added by user request. */
795   "ibm850",
796   "din_66003",
797 };
798 #define N_ENCODING_NAMES (sizeof encoding_names / sizeof *encoding_names)
799
800 struct encoding
801   {
802     uint64_t encodings;
803     char **utf8_strings;
804     unsigned int hash;
805   };
806
807 static char **
808 recode_strings (struct pool *pool,
809                 char **strings, bool *ids, size_t n,
810                 const char *encoding)
811 {
812   char **utf8_strings;
813   size_t i;
814
815   utf8_strings = pool_alloc (pool, n * sizeof *utf8_strings);
816   for (i = 0; i < n; i++)
817     {
818       struct substring utf8;
819       int error;
820
821       error = recode_pedantically ("UTF-8", encoding, ss_cstr (strings[i]),
822                                    pool, &utf8);
823       if (!error)
824         {
825           ss_rtrim (&utf8, ss_cstr (" "));
826           utf8.string[utf8.length] = '\0';
827
828           if (ids[i] && !id_is_plausible (utf8.string, false))
829             error = EINVAL;
830         }
831
832       if (error)
833         return NULL;
834
835       utf8_strings[i] = utf8.string;
836     }
837
838   return utf8_strings;
839 }
840
841 static struct encoding *
842 find_duplicate_encoding (struct encoding *encodings, size_t n_encodings,
843                          char **utf8_strings, size_t n_strings,
844                          unsigned int hash)
845 {
846   struct encoding *e;
847
848   for (e = encodings; e < &encodings[n_encodings]; e++)
849     {
850       int i;
851
852       if (e->hash != hash)
853         goto next_encoding;
854
855       for (i = 0; i < n_strings; i++)
856         if (strcmp (utf8_strings[i], e->utf8_strings[i]))
857           goto next_encoding;
858
859       return e;
860     next_encoding:;
861     }
862
863   return NULL;
864 }
865
866 static bool
867 all_equal (const struct encoding *encodings, size_t n_encodings,
868            size_t string_idx)
869 {
870   const char *s0;
871   size_t i;
872
873   s0 = encodings[0].utf8_strings[string_idx];
874   for (i = 1; i < n_encodings; i++)
875     if (strcmp (s0, encodings[i].utf8_strings[string_idx]))
876       return false;
877
878   return true;
879 }
880
881 static int
882 equal_prefix (const struct encoding *encodings, size_t n_encodings,
883               size_t string_idx)
884 {
885   const char *s0;
886   size_t prefix;
887   size_t i;
888
889   s0 = encodings[0].utf8_strings[string_idx];
890   prefix = strlen (s0);
891   for (i = 1; i < n_encodings; i++)
892     {
893       const char *si = encodings[i].utf8_strings[string_idx];
894       size_t j;
895
896       for (j = 0; j < prefix; j++)
897         if (s0[j] != si[j])
898           {
899             prefix = j;
900             if (!prefix)
901               return 0;
902             break;
903           }
904     }
905
906   while (prefix > 0 && s0[prefix - 1] != ' ')
907     prefix--;
908   return prefix;
909 }
910
911 static int
912 equal_suffix (const struct encoding *encodings, size_t n_encodings,
913               size_t string_idx)
914 {
915   const char *s0;
916   size_t s0_len;
917   size_t suffix;
918   size_t i;
919
920   s0 = encodings[0].utf8_strings[string_idx];
921   s0_len = strlen (s0);
922   suffix = s0_len;
923   for (i = 1; i < n_encodings; i++)
924     {
925       const char *si = encodings[i].utf8_strings[string_idx];
926       size_t si_len = strlen (si);
927       size_t j;
928
929       if (si_len < suffix)
930         suffix = si_len;
931       for (j = 0; j < suffix; j++)
932         if (s0[s0_len - j - 1] != si[si_len - j - 1])
933           {
934             suffix = j;
935             if (!suffix)
936               return 0;
937             break;
938           }
939     }
940
941   while (suffix > 0 && s0[s0_len - suffix] != ' ')
942     suffix--;
943   return suffix;
944 }
945
946 static void
947 report_encodings (const struct file_handle *h, struct pool *pool,
948                   char **titles, bool *ids, char **strings, size_t n_strings)
949 {
950   struct encoding encodings[N_ENCODING_NAMES];
951   size_t n_encodings, n_unique_strings;
952
953   n_encodings = 0;
954   for (size_t i = 0; i < N_ENCODING_NAMES; i++)
955     {
956       char **utf8_strings;
957       struct encoding *e;
958       unsigned int hash;
959
960       utf8_strings = recode_strings (pool, strings, ids, n_strings,
961                                      encoding_names[i]);
962       if (!utf8_strings)
963         continue;
964
965       /* Hash utf8_strings. */
966       hash = 0;
967       for (size_t j = 0; j < n_strings; j++)
968         hash = hash_string (utf8_strings[j], hash);
969
970       /* If there's a duplicate encoding, just mark it. */
971       e = find_duplicate_encoding (encodings, n_encodings,
972                                    utf8_strings, n_strings, hash);
973       if (e)
974         {
975           e->encodings |= UINT64_C (1) << i;
976           continue;
977         }
978
979       e = &encodings[n_encodings++];
980       e->encodings = UINT64_C (1) << i;
981       e->utf8_strings = utf8_strings;
982       e->hash = hash;
983     }
984   if (!n_encodings)
985     {
986       msg (SW, _("No valid encodings found."));
987       return;
988     }
989
990   /* Table of valid encodings. */
991   struct pivot_table *table = pivot_table_create__ (
992     pivot_value_new_text_format (N_("Usable encodings for %s."),
993                                  fh_get_name (h)));
994   table->caption = pivot_value_new_text_format (
995     N_("Encodings that can successfully read %s (by specifying the encoding "
996        "name on the GET command's ENCODING subcommand).  Encodings that "
997        "yield identical text are listed together."),
998     fh_get_name (h));
999
1000   pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Encodings"),
1001                           N_("Encodings"));
1002   struct pivot_dimension *number = pivot_dimension_create__ (
1003     table, PIVOT_AXIS_ROW, pivot_value_new_user_text ("#", -1));
1004   number->root->show_label = true;
1005
1006   for (size_t i = 0; i < n_encodings; i++)
1007     {
1008       struct string s = DS_EMPTY_INITIALIZER;
1009       for (size_t j = 0; j < 64; j++)
1010         if (encodings[i].encodings & (UINT64_C (1) << j))
1011           ds_put_format (&s, "%s, ", encoding_names[j]);
1012       ds_chomp (&s, ss_cstr (", "));
1013
1014       int row = pivot_category_create_leaf (number->root,
1015                                             pivot_value_new_integer (i + 1));
1016       pivot_table_put2 (
1017         table, 0, row, pivot_value_new_user_text_nocopy (ds_steal_cstr (&s)));
1018     }
1019   pivot_table_submit (table);
1020
1021   n_unique_strings = 0;
1022   for (size_t i = 0; i < n_strings; i++)
1023     if (!all_equal (encodings, n_encodings, i))
1024       n_unique_strings++;
1025   if (!n_unique_strings)
1026     return;
1027
1028   /* Table of alternative interpretations. */
1029   table = pivot_table_create__ (
1030     pivot_value_new_text_format (N_("%s Encoded Text Strings"),
1031                                  fh_get_name (h)));
1032   table->caption = pivot_value_new_text (
1033     N_("Text strings in the file dictionary that the previously listed "
1034        "encodings interpret differently, along with the interpretations."));
1035
1036   pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Text"), N_("Text"));
1037
1038   number = pivot_dimension_create__ (table, PIVOT_AXIS_ROW,
1039                                      pivot_value_new_user_text ("#", -1));
1040   number->root->show_label = true;
1041   for (size_t i = 0; i < n_encodings; i++)
1042     pivot_category_create_leaf (number->root,
1043                                 pivot_value_new_integer (i + 1));
1044
1045   struct pivot_dimension *purpose = pivot_dimension_create (
1046     table, PIVOT_AXIS_ROW, N_("Purpose"));
1047   purpose->root->show_label = true;
1048
1049   for (size_t i = 0; i < n_strings; i++)
1050     if (!all_equal (encodings, n_encodings, i))
1051       {
1052         int prefix = equal_prefix (encodings, n_encodings, i);
1053         int suffix = equal_suffix (encodings, n_encodings, i);
1054
1055         int purpose_idx = pivot_category_create_leaf (
1056           purpose->root, pivot_value_new_user_text (titles[i], -1));
1057
1058         for (size_t j = 0; j < n_encodings; j++)
1059           {
1060             const char *s = encodings[j].utf8_strings[i] + prefix;
1061
1062             if (prefix || suffix)
1063               {
1064                 size_t len = strlen (s) - suffix;
1065                 struct string entry;
1066
1067                 ds_init_empty (&entry);
1068                 if (prefix)
1069                   ds_put_cstr (&entry, "...");
1070                 ds_put_substring (&entry, ss_buffer (s, len));
1071                 if (suffix)
1072                   ds_put_cstr (&entry, "...");
1073
1074                 pivot_table_put3 (table, 0, j, purpose_idx,
1075                                   pivot_value_new_user_text_nocopy (
1076                                     ds_steal_cstr (&entry)));
1077               }
1078             else
1079               pivot_table_put3 (table, 0, j, purpose_idx,
1080                                 pivot_value_new_user_text (s, -1));
1081           }
1082       }
1083
1084   pivot_table_submit (table);
1085 }