a89a86ea641e559d432c29f78f8fb439e79ccb79
[pspp] / utilities / pspp-dump-sav.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2007, 2008, 2009, 2010, 2011 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 <ctype.h>
20 #include <errno.h>
21 #include <getopt.h>
22 #include <inttypes.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25
26 #include "data/val-type.h"
27 #include "libpspp/cast.h"
28 #include "libpspp/compiler.h"
29 #include "libpspp/float-format.h"
30 #include "libpspp/integer-format.h"
31 #include "libpspp/misc.h"
32
33 #include "gl/error.h"
34 #include "gl/minmax.h"
35 #include "gl/progname.h"
36 #include "gl/version-etc.h"
37 #include "gl/xalloc.h"
38
39 #define ID_MAX_LEN 64
40
41 struct sfm_reader
42   {
43     const char *file_name;
44     FILE *file;
45
46     int n_variable_records, n_variables;
47
48     int *var_widths;
49     size_t n_var_widths, allocated_var_widths;
50
51     enum integer_format integer_format;
52     enum float_format float_format;
53
54     bool compressed;
55     double bias;
56   };
57
58 static void read_header (struct sfm_reader *);
59 static void read_variable_record (struct sfm_reader *);
60 static void read_value_label_record (struct sfm_reader *);
61 static void read_document_record (struct sfm_reader *);
62 static void read_extension_record (struct sfm_reader *);
63 static void read_machine_integer_info (struct sfm_reader *,
64                                        size_t size, size_t count);
65 static void read_machine_float_info (struct sfm_reader *,
66                                      size_t size, size_t count);
67 static void read_mrsets (struct sfm_reader *, size_t size, size_t count);
68 static void read_display_parameters (struct sfm_reader *,
69                                      size_t size, size_t count);
70 static void read_long_var_name_map (struct sfm_reader *r,
71                                     size_t size, size_t count);
72 static void read_long_string_map (struct sfm_reader *r,
73                                   size_t size, size_t count);
74 static void read_datafile_attributes (struct sfm_reader *r,
75                                       size_t size, size_t count);
76 static void read_variable_attributes (struct sfm_reader *r,
77                                       size_t size, size_t count);
78 static void read_ncases64 (struct sfm_reader *, size_t size, size_t count);
79 static void read_character_encoding (struct sfm_reader *r,
80                                        size_t size, size_t count);
81 static void read_long_string_value_labels (struct sfm_reader *r,
82                                            size_t size, size_t count);
83 static void read_unknown_extension (struct sfm_reader *,
84                                     size_t size, size_t count);
85 static void read_compressed_data (struct sfm_reader *, int max_cases);
86
87 static struct text_record *open_text_record (
88   struct sfm_reader *, size_t size);
89 static void close_text_record (struct text_record *);
90 static bool read_variable_to_value_pair (struct text_record *,
91                                          char **key, char **value);
92 static char *text_tokenize (struct text_record *, int delimiter);
93 static bool text_match (struct text_record *text, int c);
94 static const char *text_parse_counted_string (struct text_record *);
95 static size_t text_pos (const struct text_record *);
96
97 static void usage (void);
98 static void sys_warn (struct sfm_reader *, const char *, ...)
99      PRINTF_FORMAT (2, 3);
100 static void sys_error (struct sfm_reader *, const char *, ...)
101      PRINTF_FORMAT (2, 3)
102      NO_RETURN;
103
104 static void read_bytes (struct sfm_reader *, void *, size_t);
105 static bool try_read_bytes (struct sfm_reader *, void *, size_t);
106 static int read_int (struct sfm_reader *);
107 static int64_t read_int64 (struct sfm_reader *);
108 static double read_float (struct sfm_reader *);
109 static void read_string (struct sfm_reader *, char *, size_t);
110 static void skip_bytes (struct sfm_reader *, size_t);
111 static void trim_spaces (char *);
112
113 int
114 main (int argc, char *argv[])
115 {
116   int max_cases = 0;
117   struct sfm_reader r;
118   int i;
119
120   set_program_name (argv[0]);
121
122   for (;;)
123     {
124       static const struct option long_options[] =
125         {
126           { "data",    optional_argument, NULL, 'd' },
127           { "help",    no_argument,       NULL, 'h' },
128           { "version", no_argument,       NULL, 'v' },
129           { NULL,      0,                 NULL, 0 },
130         };
131
132       int c;
133
134       c = getopt_long (argc, argv, "d::hv", long_options, NULL);
135       if (c == -1)
136         break;
137
138       switch (c)
139         {
140         case 'd':
141           max_cases = optarg ? atoi (optarg) : INT_MAX;
142           break;
143
144         case 'v':
145           version_etc (stdout, "pspp-dump-sav", PACKAGE_NAME, PACKAGE_VERSION,
146                        "Ben Pfaff", "John Darrington", NULL_SENTINEL);
147           exit (EXIT_SUCCESS);
148
149         case 'h':
150           usage ();
151           exit (EXIT_SUCCESS);
152
153         default:
154           exit (EXIT_FAILURE);
155         }
156     }
157
158   if (optind == argc)
159     error (1, 0, "at least one non-option argument is required; "
160            "use --help for help");
161
162   for (i = optind; i < argc; i++)
163     {
164       int rec_type;
165
166       r.file_name = argv[i];
167       r.file = fopen (r.file_name, "rb");
168       if (r.file == NULL)
169         error (EXIT_FAILURE, errno, "error opening `%s'", r.file_name);
170       r.n_variable_records = 0;
171       r.n_variables = 0;
172       r.n_var_widths = 0;
173       r.allocated_var_widths = 0;
174       r.var_widths = 0;
175       r.compressed = false;
176
177       if (argc - optind > 1)
178         printf ("Reading \"%s\":\n", r.file_name);
179       
180       read_header (&r);
181       while ((rec_type = read_int (&r)) != 999)
182         {
183           switch (rec_type)
184             {
185             case 2:
186               read_variable_record (&r);
187               break;
188
189             case 3:
190               read_value_label_record (&r);
191               break;
192
193             case 4:
194               sys_error (&r, "Misplaced type 4 record.");
195
196             case 6:
197               read_document_record (&r);
198               break;
199
200             case 7:
201               read_extension_record (&r);
202               break;
203
204             default:
205               sys_error (&r, "Unrecognized record type %d.", rec_type);
206             }
207         }
208       printf ("%08llx: end-of-dictionary record "
209               "(first byte of data at %08llx)\n",
210               (long long int) ftello (r.file),
211               (long long int) ftello (r.file) + 4);
212
213       if (r.compressed && max_cases > 0)
214         read_compressed_data (&r, max_cases);
215
216       fclose (r.file);
217     }
218   
219   return 0;
220 }
221
222 static void
223 read_header (struct sfm_reader *r)
224 {
225   char rec_type[5];
226   char eye_catcher[61];
227   uint8_t raw_layout_code[4];
228   int32_t layout_code;
229   int32_t nominal_case_size;
230   int32_t compressed;
231   int32_t weight_index;
232   int32_t ncases;
233   uint8_t raw_bias[8];
234   char creation_date[10];
235   char creation_time[9];
236   char file_label[65];
237
238   read_string (r, rec_type, sizeof rec_type);
239   read_string (r, eye_catcher, sizeof eye_catcher);
240
241   if (strcmp ("$FL2", rec_type) != 0)
242     sys_error (r, "This is not an SPSS system file.");
243
244   /* Identify integer format. */
245   read_bytes (r, raw_layout_code, sizeof raw_layout_code);
246   if ((!integer_identify (2, raw_layout_code, sizeof raw_layout_code,
247                           &r->integer_format)
248        && !integer_identify (3, raw_layout_code, sizeof raw_layout_code,
249                              &r->integer_format))
250       || (r->integer_format != INTEGER_MSB_FIRST
251           && r->integer_format != INTEGER_LSB_FIRST))
252     sys_error (r, "This is not an SPSS system file.");
253   layout_code = integer_get (r->integer_format,
254                              raw_layout_code, sizeof raw_layout_code);
255
256   nominal_case_size = read_int (r);
257   compressed = read_int (r);
258   weight_index = read_int (r);
259   ncases = read_int (r);
260
261   r->compressed = compressed != 0;
262
263   /* Identify floating-point format and obtain compression bias. */
264   read_bytes (r, raw_bias, sizeof raw_bias);
265   if (float_identify (100.0, raw_bias, sizeof raw_bias, &r->float_format) == 0)
266     {
267       sys_warn (r, "Compression bias is not the usual value of 100, or system "
268                 "file uses unrecognized floating-point format.");
269       if (r->integer_format == INTEGER_MSB_FIRST)
270         r->float_format = FLOAT_IEEE_DOUBLE_BE;
271       else
272         r->float_format = FLOAT_IEEE_DOUBLE_LE;
273     }
274   r->bias = float_get_double (r->float_format, raw_bias);
275
276   read_string (r, creation_date, sizeof creation_date);
277   read_string (r, creation_time, sizeof creation_time);
278   read_string (r, file_label, sizeof file_label);
279   trim_spaces (file_label);
280   skip_bytes (r, 3);
281
282   printf ("File header record:\n");
283   printf ("\t%17s: %s\n", "Product name", eye_catcher);
284   printf ("\t%17s: %"PRId32"\n", "Layout code", layout_code);
285   printf ("\t%17s: %"PRId32"\n", "Compressed", compressed);
286   printf ("\t%17s: %"PRId32"\n", "Weight index", weight_index);
287   printf ("\t%17s: %"PRId32"\n", "Number of cases", ncases);
288   printf ("\t%17s: %g\n", "Compression bias", r->bias);
289   printf ("\t%17s: %s\n", "Creation date", creation_date);
290   printf ("\t%17s: %s\n", "Creation time", creation_time);
291   printf ("\t%17s: \"%s\"\n", "File label", file_label);
292 }
293
294 static const char *
295 format_name (int format)
296 {
297   switch ((format >> 16) & 0xff)
298     {
299     case 1: return "A";
300     case 2: return "AHEX";
301     case 3: return "COMMA";
302     case 4: return "DOLLAR";
303     case 5: return "F";
304     case 6: return "IB";
305     case 7: return "PIBHEX";
306     case 8: return "P";
307     case 9: return "PIB";
308     case 10: return "PK";
309     case 11: return "RB";
310     case 12: return "RBHEX";
311     case 15: return "Z";
312     case 16: return "N";
313     case 17: return "E";
314     case 20: return "DATE";
315     case 21: return "TIME";
316     case 22: return "DATETIME";
317     case 23: return "ADATE";
318     case 24: return "JDATE";
319     case 25: return "DTIME";
320     case 26: return "WKDAY";
321     case 27: return "MONTH";
322     case 28: return "MOYR";
323     case 29: return "QYR";
324     case 30: return "WKYR";
325     case 31: return "PCT";
326     case 32: return "DOT";
327     case 33: return "CCA";
328     case 34: return "CCB";
329     case 35: return "CCC";
330     case 36: return "CCD";
331     case 37: return "CCE";
332     case 38: return "EDATE";
333     case 39: return "SDATE";
334     default: return "invalid";
335     }
336 }
337
338 /* Reads a variable (type 2) record from R and adds the
339    corresponding variable to DICT.
340    Also skips past additional variable records for long string
341    variables. */
342 static void
343 read_variable_record (struct sfm_reader *r)
344 {
345   int width;
346   int has_variable_label;
347   int missing_value_code;
348   int print_format;
349   int write_format;
350   char name[9];
351
352   printf ("%08llx: variable record #%d\n",
353           (long long int) ftello (r->file), r->n_variable_records++);
354
355   width = read_int (r);
356   has_variable_label = read_int (r);
357   missing_value_code = read_int (r);
358   print_format = read_int (r);
359   write_format = read_int (r);
360   read_string (r, name, sizeof name);
361   name[strcspn (name, " ")] = '\0';
362
363   if (width >= 0)
364     r->n_variables++;
365
366   if (r->n_var_widths >= r->allocated_var_widths)
367     r->var_widths = x2nrealloc (r->var_widths, &r->allocated_var_widths,
368                                 sizeof *r->var_widths);
369   r->var_widths[r->n_var_widths++] = width;
370
371   printf ("\tWidth: %d (%s)\n",
372           width,
373           width > 0 ? "string"
374           : width == 0 ? "numeric"
375           : "long string continuation record");
376   printf ("\tVariable label: %d\n", has_variable_label);
377   printf ("\tMissing values code: %d (%s)\n", missing_value_code,
378           (missing_value_code == 0 ? "no missing values"
379            : missing_value_code == 1 ? "one missing value"
380            : missing_value_code == 2 ? "two missing values"
381            : missing_value_code == 3 ? "three missing values"
382            : missing_value_code == -2 ? "one missing value range"
383            : missing_value_code == -3 ? "one missing value, one range"
384            : "bad value"));
385   printf ("\tPrint format: %06x (%s%d.%d)\n",
386           print_format, format_name (print_format),
387           (print_format >> 8) & 0xff, print_format & 0xff);
388   printf ("\tWrite format: %06x (%s%d.%d)\n",
389           write_format, format_name (write_format),
390           (write_format >> 8) & 0xff, write_format & 0xff);
391   printf ("\tName: %s\n", name);
392
393   /* Get variable label, if any. */
394   if (has_variable_label != 0 && has_variable_label != 1)
395     sys_error (r, "Variable label indicator field is not 0 or 1.");
396   if (has_variable_label == 1)
397     {
398       long long int offset = ftello (r->file);
399       size_t len, read_len;
400       char label[255 + 1];
401
402       len = read_int (r);
403
404       /* Read up to 255 bytes of label. */
405       read_len = MIN (sizeof label - 1, len);
406       read_string (r, label, read_len + 1);
407       printf("\t%08llx Variable label: \"%s\"\n", offset, label);
408
409       /* Skip unread label bytes. */
410       skip_bytes (r, len - read_len);
411
412       /* Skip label padding up to multiple of 4 bytes. */
413       skip_bytes (r, ROUND_UP (len, 4) - len);
414     }
415
416   /* Set missing values. */
417   if (missing_value_code != 0)
418     {
419       int i;
420
421       printf ("\t%08llx Missing values:", (long long int) ftello (r->file));
422       if (!width)
423         {
424           if (missing_value_code < -3 || missing_value_code > 3
425               || missing_value_code == -1)
426             sys_error (r, "Numeric missing value indicator field is not "
427                        "-3, -2, 0, 1, 2, or 3.");
428           if (missing_value_code < 0)
429             {
430               double low = read_float (r);
431               double high = read_float (r);
432               printf (" %g...%g", low, high);
433               missing_value_code = -missing_value_code - 2;
434             }
435           for (i = 0; i < missing_value_code; i++)
436             printf (" %g", read_float (r));
437         }
438       else if (width > 0)
439         {
440           if (missing_value_code < 1 || missing_value_code > 3)
441             sys_error (r, "String missing value indicator field is not "
442                        "0, 1, 2, or 3.");
443           for (i = 0; i < missing_value_code; i++)
444             {
445               char string[9];
446               read_string (r, string, sizeof string);
447               printf (" \"%s\"", string);
448             }
449         }
450       putchar ('\n');
451     }
452 }
453
454 static void
455 print_untyped_value (struct sfm_reader *r, char raw_value[8])
456 {
457   int n_printable;
458   double value;
459
460   value = float_get_double (r->float_format, raw_value);
461   for (n_printable = 0; n_printable < sizeof raw_value; n_printable++)
462     if (!isprint (raw_value[n_printable]))
463       break;
464
465   printf ("%g/\"%.*s\"", value, n_printable, raw_value);
466 }
467
468 /* Reads value labels from sysfile R and inserts them into the
469    associated dictionary. */
470 static void
471 read_value_label_record (struct sfm_reader *r)
472 {
473   int label_cnt, var_cnt;
474   int i;
475
476   printf ("%08llx: value labels record\n", (long long int) ftello (r->file));
477
478   /* Read number of labels. */
479   label_cnt = read_int (r);
480   for (i = 0; i < label_cnt; i++)
481     {
482       char raw_value[8];
483       unsigned char label_len;
484       size_t padded_len;
485       char label[256];
486
487       read_bytes (r, raw_value, sizeof raw_value);
488
489       /* Read label length. */
490       read_bytes (r, &label_len, sizeof label_len);
491       padded_len = ROUND_UP (label_len + 1, 8);
492
493       /* Read label, padding. */
494       read_bytes (r, label, padded_len - 1);
495       label[label_len] = 0;
496
497       printf ("\t");
498       print_untyped_value (r, raw_value);
499       printf (": \"%s\"\n", label);
500     }
501
502   /* Now, read the type 4 record that has the list of variables
503      to which the value labels are to be applied. */
504
505   /* Read record type of type 4 record. */
506   if (read_int (r) != 4)
507     sys_error (r, "Variable index record (type 4) does not immediately "
508                "follow value label record (type 3) as it should.");
509
510   /* Read number of variables associated with value label from type 4
511      record. */
512   printf ("\t%08llx: apply to variables", (long long int) ftello (r->file));
513   var_cnt = read_int (r);
514   for (i = 0; i < var_cnt; i++)
515     printf (" #%d", read_int (r));
516   putchar ('\n');
517 }
518
519 static void
520 read_document_record (struct sfm_reader *r)
521 {
522   int n_lines;
523   int i;
524
525   printf ("%08llx: document record\n", (long long int) ftello (r->file));
526   n_lines = read_int (r);
527   printf ("\t%d lines of documents\n", n_lines);
528
529   for (i = 0; i < n_lines; i++)
530     {
531       char line[81];
532       printf ("\t%08llx: ", (long long int) ftello (r->file));
533       read_string (r, line, sizeof line);
534       trim_spaces (line);
535       printf ("line %d: \"%s\"\n", i, line);
536     }
537 }
538
539 static void
540 read_extension_record (struct sfm_reader *r)
541 {
542   long long int offset = ftello (r->file);
543   int subtype = read_int (r);
544   size_t size = read_int (r);
545   size_t count = read_int (r);
546   size_t bytes = size * count;
547
548   printf ("%08llx: Record 7, subtype %d, size=%zu, count=%zu\n",
549           offset, subtype, size, count);
550
551   switch (subtype)
552     {
553     case 3:
554       read_machine_integer_info (r, size, count);
555       return;
556
557     case 4:
558       read_machine_float_info (r, size, count);
559       return;
560
561     case 5:
562       /* Variable sets information.  We don't use these yet.
563          They only apply to GUIs; see VARSETS on the APPLY
564          DICTIONARY command in SPSS documentation. */
565       break;
566
567     case 6:
568       /* DATE variable information.  We don't use it yet, but we
569          should. */
570       break;
571
572     case 7:
573     case 19:
574       read_mrsets (r, size, count);
575       return;
576
577     case 11:
578       read_display_parameters (r, size, count);
579       return;
580
581     case 13:
582       read_long_var_name_map (r, size, count);
583       return;
584
585     case 14:
586       read_long_string_map (r, size, count);
587       return;
588
589     case 16:
590       read_ncases64 (r, size, count);
591       return;
592
593     case 17:
594       read_datafile_attributes (r, size, count);
595       return;
596
597     case 18:
598       read_variable_attributes (r, size, count);
599       return;
600
601     case 20:
602       read_character_encoding (r, size, count);
603       return;
604
605     case 21:
606       read_long_string_value_labels (r, size, count);
607       return;
608
609     default:
610       sys_warn (r, "Unrecognized record type 7, subtype %d.", subtype);
611       read_unknown_extension (r, size, count);
612       return;
613     }
614
615   skip_bytes (r, bytes);
616 }
617
618 static void
619 read_machine_integer_info (struct sfm_reader *r, size_t size, size_t count)
620 {
621   long long int offset = ftello (r->file);
622   int version_major = read_int (r);
623   int version_minor = read_int (r);
624   int version_revision = read_int (r);
625   int machine_code = read_int (r);
626   int float_representation = read_int (r);
627   int compression_code = read_int (r);
628   int integer_representation = read_int (r);
629   int character_code = read_int (r);
630
631   printf ("%08llx: machine integer info\n", offset);
632   if (size != 4 || count != 8)
633     sys_error (r, "Bad size (%zu) or count (%zu) field on record type 7, "
634                "subtype 3.", size, count);
635
636   printf ("\tVersion: %d.%d.%d\n",
637           version_major, version_minor, version_revision);
638   printf ("\tMachine code: %d\n", machine_code);
639   printf ("\tFloating point representation: %d (%s)\n",
640           float_representation,
641           float_representation == 1 ? "IEEE 754"
642           : float_representation == 2 ? "IBM 370"
643           : float_representation == 3 ? "DEC VAX"
644           : "unknown");
645   printf ("\tCompression code: %d\n", compression_code);
646   printf ("\tEndianness: %d (%s)\n", integer_representation,
647           integer_representation == 1 ? "big"
648           : integer_representation == 2 ? "little" : "unknown");
649   printf ("\tCharacter code: %d\n", character_code);
650 }
651
652 /* Read record type 7, subtype 4. */
653 static void
654 read_machine_float_info (struct sfm_reader *r, size_t size, size_t count)
655 {
656   long long int offset = ftello (r->file);
657   double sysmis = read_float (r);
658   double highest = read_float (r);
659   double lowest = read_float (r);
660
661   printf ("%08llx: machine float info\n", offset);
662   if (size != 8 || count != 3)
663     sys_error (r, "Bad size (%zu) or count (%zu) on extension 4.",
664                size, count);
665
666   printf ("\tsysmis: %g\n", sysmis);
667   if (sysmis != SYSMIS)
668     sys_warn (r, "File specifies unexpected value %g as %s.",
669               sysmis, "SYSMIS");
670
671   printf ("\thighest: %g\n", highest);
672   if (highest != HIGHEST)
673     sys_warn (r, "File specifies unexpected value %g as %s.",
674               highest, "HIGHEST");
675
676   printf ("\tlowest: %g\n", lowest);
677   if (lowest != LOWEST)
678     sys_warn (r, "File specifies unexpected value %g as %s.",
679               lowest, "LOWEST");
680 }
681
682 /* Read record type 7, subtype 7. */
683 static void
684 read_mrsets (struct sfm_reader *r, size_t size, size_t count)
685 {
686   struct text_record *text;
687
688   printf ("%08llx: multiple response sets\n",
689           (long long int) ftello (r->file));
690   text = open_text_record (r, size * count);
691   for (;;)
692     {
693       const char *name;
694       enum { MRSET_MC, MRSET_MD } type;
695       bool cat_label_from_counted_values = false;
696       bool label_from_var_label = false;
697       const char *counted;
698       const char *label;
699       const char *variables;
700
701       name = text_tokenize (text, '=');
702       if (name == NULL)
703         break;
704
705       if (text_match (text, 'C'))
706         {
707           type = MRSET_MC;
708           counted = NULL;
709           if (!text_match (text, ' '))
710             {
711               sys_warn (r, "missing space following 'C' at offset %zu "
712                         "in mrsets record", text_pos (text));
713               break;
714             }
715         }
716       else if (text_match (text, 'D'))
717         {
718           type = MRSET_MD;
719         }
720       else if (text_match (text, 'E'))
721         {
722           char *number;
723
724           type = MRSET_MD;
725           cat_label_from_counted_values = true;
726
727           if (!text_match (text, ' '))
728             {
729               sys_warn (r, "Missing space following `%c' at offset %zu "
730                         "in MRSETS record", 'E', text_pos (text));
731               break;
732             }
733
734           number = text_tokenize (text, ' ');
735           if (!strcmp (number, "11"))
736             label_from_var_label = true;
737           else if (strcmp (number, "1"))
738             sys_warn (r, "Unexpected label source value `%s' "
739                       "following `E' at offset %zu in MRSETS record",
740                       number, text_pos (text));
741
742         }
743       else
744         {
745           sys_warn (r, "missing `C', `D', or `E' at offset %zu "
746                     "in mrsets record", text_pos (text));
747           break;
748         }
749
750       if (type == MRSET_MD)
751         {
752           counted = text_parse_counted_string (text);
753           if (counted == NULL)
754             break;
755         }
756
757       label = text_parse_counted_string (text);
758       if (label == NULL)
759         break;
760
761       variables = text_tokenize (text, '\n');
762       if (variables == NULL)
763         {
764           sys_warn (r, "missing variable names following label "
765                     "at offset %zu in mrsets record", text_pos (text));
766           break;
767         }
768
769       printf ("\t\"%s\": multiple %s set",
770               name, type == MRSET_MC ? "category" : "dichotomy");
771       if (counted != NULL)
772         printf (", counted value \"%s\"", counted);
773       if (cat_label_from_counted_values)
774         printf (", category labels from counted values");
775       if (label[0] != '\0')
776         printf (", label \"%s\"", label);
777       if (label_from_var_label)
778         printf (", label from variable label");
779       printf(", variables \"%s\"\n", variables);
780     }
781   close_text_record (text);
782 }
783
784 /* Read record type 7, subtype 11. */
785 static void
786 read_display_parameters (struct sfm_reader *r, size_t size, size_t count)
787 {
788   size_t n_vars;
789   bool includes_width;
790   size_t i;
791
792   printf ("%08llx: variable display parameters\n",
793           (long long int) ftello (r->file));
794   if (size != 4)
795     {
796       sys_warn (r, "Bad size %zu on extension 11.", size);
797       skip_bytes (r, size * count);
798       return;
799     }
800
801   n_vars = r->n_variables;
802   if (count == 3 * n_vars)
803     includes_width = true;
804   else if (count == 2 * n_vars)
805     includes_width = false;
806   else
807     {
808       sys_warn (r, "Extension 11 has bad count %zu (for %zu variables.",
809                 count, n_vars);
810       skip_bytes (r, size * count);
811       return;
812     }
813
814   for (i = 0; i < n_vars; ++i)
815     {
816       int measure = read_int (r);
817       int width = includes_width ? read_int (r) : 0;
818       int align = read_int (r);
819
820       printf ("\tVar #%zu: measure=%d (%s)", i, measure,
821               (measure == 1 ? "nominal"
822                : measure == 2 ? "ordinal"
823                : measure == 3 ? "scale"
824                : "invalid"));
825       if (includes_width)
826         printf (", width=%d", width);
827       printf (", align=%d (%s)\n", align,
828               (align == 0 ? "left"
829                : align == 1 ? "right"
830                : align == 2 ? "centre"
831                : "invalid"));
832     }
833 }
834
835 /* Reads record type 7, subtype 13, which gives the long name
836    that corresponds to each short name.  */
837 static void
838 read_long_var_name_map (struct sfm_reader *r, size_t size, size_t count)
839 {
840   struct text_record *text;
841   char *var;
842   char *long_name;
843
844   printf ("%08llx: long variable names (short => long)\n",
845           (long long int) ftello (r->file));
846   text = open_text_record (r, size * count);
847   while (read_variable_to_value_pair (text, &var, &long_name))
848     printf ("\t%s => %s\n", var, long_name);
849   close_text_record (text);
850 }
851
852 /* Reads record type 7, subtype 14, which gives the real length
853    of each very long string.  Rearranges DICT accordingly. */
854 static void
855 read_long_string_map (struct sfm_reader *r, size_t size, size_t count)
856 {
857   struct text_record *text;
858   char *var;
859   char *length_s;
860
861   printf ("%08llx: very long strings (variable => length)\n",
862           (long long int) ftello (r->file));
863   text = open_text_record (r, size * count);
864   while (read_variable_to_value_pair (text, &var, &length_s))
865     printf ("\t%s => %d\n", var, atoi (length_s));
866   close_text_record (text);
867 }
868
869 static bool
870 read_attributes (struct sfm_reader *r, struct text_record *text,
871                  const char *variable)
872 {
873   const char *key;
874   int index;
875
876   for (;;) 
877     {
878       key = text_tokenize (text, '(');
879       if (key == NULL)
880         return true;
881   
882       for (index = 1; ; index++)
883         {
884           /* Parse the value. */
885           const char *value = text_tokenize (text, '\n');
886           if (value == NULL) 
887             {
888               sys_warn (r, "%s: Error parsing attribute value %s[%d]",
889                         variable, key, index);
890               return false;
891             }
892           if (strlen (value) < 2
893               || value[0] != '\'' || value[strlen (value) - 1] != '\'')
894             sys_warn (r, "%s: Attribute value %s[%d] is not quoted: %s",
895                       variable, key, index, value);
896           else
897             printf ("\t%s: %s[%d] = \"%.*s\"\n",
898                     variable, key, index, (int) strlen (value) - 2, value + 1);
899
900           /* Was this the last value for this attribute? */
901           if (text_match (text, ')'))
902             break;
903         }
904
905       if (text_match (text, '/'))
906         return true; 
907     }
908 }
909
910 /* Read extended number of cases record. */
911 static void
912 read_ncases64 (struct sfm_reader *r, size_t size, size_t count)
913 {
914   int64_t unknown, ncases64;
915
916   if (size != 8)
917     {
918       sys_warn (r, "Bad size %zu for extended number of cases.", size);
919       skip_bytes (r, size * count);
920       return;
921     }
922   if (count != 2)
923     {
924       sys_warn (r, "Bad count %zu for extended number of cases.", size);
925       skip_bytes (r, size * count);
926       return;
927     }
928   unknown = read_int64 (r);
929   ncases64 = read_int64 (r);
930   printf ("%08llx: extended number of cases: "
931           "unknown=%"PRId64", ncases64=%"PRId64"\n",
932           (long long int) ftello (r->file), unknown, ncases64);
933 }
934
935 static void
936 read_datafile_attributes (struct sfm_reader *r, size_t size, size_t count) 
937 {
938   struct text_record *text;
939   
940   printf ("%08llx: datafile attributes\n", (long long int) ftello (r->file));
941   text = open_text_record (r, size * count);
942   read_attributes (r, text, "datafile");
943   close_text_record (text);
944 }
945
946 static void
947 read_character_encoding (struct sfm_reader *r, size_t size, size_t count)
948 {
949   long long int posn =  ftello (r->file);
950   char *encoding = xcalloc (size, count + 1);
951   read_string (r, encoding, count + 1);
952
953   printf ("%08llx: Character Encoding: %s\n", posn, encoding);
954 }
955
956 static void
957 read_long_string_value_labels (struct sfm_reader *r, size_t size, size_t count)
958 {
959   long long int start = ftello (r->file);
960
961   printf ("%08llx: long string value labels\n", start);
962   while (ftello (r->file) - start < size * count)
963     {
964       long long posn = ftello (r->file);
965       char var_name[ID_MAX_LEN + 1];
966       int var_name_len;
967       int n_values;
968       int width;
969       int i;
970
971       /* Read variable name. */
972       var_name_len = read_int (r);
973       if (var_name_len > ID_MAX_LEN)
974         sys_error (r, "Variable name length in long string value label "
975                    "record (%d) exceeds %d-byte limit.",
976                    var_name_len, ID_MAX_LEN);
977       read_string (r, var_name, var_name_len + 1);
978
979       /* Read width, number of values. */
980       width = read_int (r);
981       n_values = read_int (r);
982
983       printf ("\t%08llx: %s, width %d, %d values\n",
984               posn, var_name, width, n_values);
985
986       /* Read values. */
987       for (i = 0; i < n_values; i++)
988         {
989           char *value;
990           int value_length;
991
992           char *label;
993           int label_length;
994
995           posn = ftello (r->file);
996
997           /* Read value. */
998           value_length = read_int (r);
999           value = xmalloc (value_length + 1);
1000           read_string (r, value, value_length + 1);
1001
1002           /* Read label. */
1003           label_length = read_int (r);
1004           label = xmalloc (label_length + 1);
1005           read_string (r, label, label_length + 1);
1006
1007           printf ("\t\t%08llx: \"%s\" (%d bytes) => \"%s\" (%d bytes)\n",
1008                   posn, value, value_length, label, label_length);
1009
1010           free (value);
1011           free (label);
1012         }
1013     }
1014 }
1015
1016 static void
1017 hex_dump (size_t offset, const void *buffer_, size_t buffer_size)
1018 {
1019   const uint8_t *buffer = buffer_;
1020
1021   while (buffer_size > 0)
1022     {
1023       size_t n = MIN (buffer_size, 16);
1024       size_t i;
1025
1026       printf ("%04zx", offset);
1027       for (i = 0; i < 16; i++)
1028         {
1029           if (i < n)
1030             printf ("%c%02x", i == 8 ? '-' : ' ', buffer[i]);
1031           else
1032             printf ("   ");
1033         }
1034
1035       printf (" |");
1036       for (i = 0; i < 16; i++)
1037         {
1038           unsigned char c = i < n ? buffer[i] : ' ';
1039           putchar (isprint (c) ? c : '.');
1040         }
1041       printf ("|\n");
1042
1043       offset += n;
1044       buffer += n;
1045       buffer_size -= n;
1046     }
1047 }
1048
1049 /* Reads and prints any type 7 record that we don't understand. */
1050 static void
1051 read_unknown_extension (struct sfm_reader *r, size_t size, size_t count)
1052 {
1053   unsigned char *buffer;
1054   size_t i;
1055
1056   if (size == 0 || count > 65536 / size)
1057     skip_bytes (r, size * count);
1058   else if (size != 1)
1059     {
1060       buffer = xmalloc (size);
1061       for (i = 0; i < count; i++)
1062         {
1063           read_bytes (r, buffer, size);
1064           hex_dump (i * size, buffer, size);
1065         }
1066       free (buffer);
1067     }
1068   else
1069     {
1070       buffer = xmalloc (count);
1071       read_bytes (r, buffer, count);
1072       if (memchr (buffer, 0, count) == 0)
1073         for (i = 0; i < count; i++)
1074           {
1075             unsigned char c = buffer[i];
1076
1077             if (c == '\\')
1078               printf ("\\\\");
1079             else if (c == '\n' || isprint (c))
1080               putchar (c);
1081             else
1082               printf ("\\%02x", c);
1083           }
1084       else
1085         hex_dump (0, buffer, count);
1086       free (buffer);
1087     }
1088 }
1089
1090 static void
1091 read_variable_attributes (struct sfm_reader *r, size_t size, size_t count) 
1092 {
1093   struct text_record *text;
1094   
1095   printf ("%08llx: variable attributes\n", (long long int) ftello (r->file));
1096   text = open_text_record (r, size * count);
1097   for (;;) 
1098     {
1099       const char *variable = text_tokenize (text, ':');
1100       if (variable == NULL || !read_attributes (r, text, variable))
1101         break; 
1102     }
1103   close_text_record (text);
1104 }
1105
1106 static void
1107 read_compressed_data (struct sfm_reader *r, int max_cases)
1108 {
1109   enum { N_OPCODES = 8 };
1110   uint8_t opcodes[N_OPCODES];
1111   long long int opcode_ofs;
1112   int opcode_idx;
1113   int case_num;
1114   int i;
1115
1116   read_int (r);
1117   printf ("\n%08llx: compressed data:\n", (long long int) ftello (r->file));
1118
1119   opcode_idx = N_OPCODES;
1120   opcode_ofs = 0;
1121   case_num = 0;
1122   for (case_num = 0; case_num < max_cases; case_num++)
1123     {
1124       printf ("%08llx: case %d's uncompressible data begins\n",
1125               (long long int) ftello (r->file), case_num);
1126       for (i = 0; i < r->n_var_widths; )
1127         {
1128           int width = r->var_widths[i];
1129           char raw_value[8];
1130           int opcode;
1131
1132           if (opcode_idx >= N_OPCODES)
1133             {
1134               opcode_ofs = ftello (r->file);
1135               if (i == 0)
1136                 {
1137                   if (!try_read_bytes (r, opcodes, 8))
1138                     return;
1139                 }
1140               else
1141                 read_bytes (r, opcodes, 8);
1142               opcode_idx = 0;
1143             }
1144           opcode = opcodes[opcode_idx];
1145           printf ("%08llx: variable %d: opcode %d: ",
1146                   opcode_ofs + opcode_idx, i, opcode);
1147
1148           switch (opcode)
1149             {
1150             default:
1151               printf ("%g", opcode - r->bias);
1152               if (width != 0)
1153                 printf (", but this is a string variable (width=%d)", width);
1154               printf ("\n");
1155               i++;
1156               break;
1157
1158             case 0:
1159               printf ("ignored padding\n");
1160               break;
1161
1162             case 252:
1163               printf ("end of data\n");
1164               return;
1165
1166             case 253:
1167               read_bytes (r, raw_value, 8);
1168               printf ("uncompressible data: ");
1169               print_untyped_value (r, raw_value);
1170               printf ("\n");
1171               i++;
1172               break;
1173
1174             case 254:
1175               printf ("spaces");
1176               if (width == 0)
1177                 printf (", but this is a numeric variable");
1178               printf ("\n");
1179               i++;
1180               break;
1181
1182             case 255:
1183               printf ("SYSMIS");
1184               if (width != 0)
1185                 printf (", but this is a string variable (width=%d)", width);
1186               printf ("\n");
1187               i++;
1188               break;
1189             }
1190
1191           opcode_idx++;
1192         }
1193     }
1194 }
1195 \f
1196 /* Helpers for reading records that consist of structured text
1197    strings. */
1198
1199 /* State. */
1200 struct text_record
1201   {
1202     struct sfm_reader *reader;  /* Reader. */
1203     char *buffer;               /* Record contents. */
1204     size_t size;                /* Size of buffer. */
1205     size_t pos;                 /* Current position in buffer. */
1206   };
1207
1208 /* Reads SIZE bytes into a text record for R,
1209    and returns the new text record. */
1210 static struct text_record *
1211 open_text_record (struct sfm_reader *r, size_t size)
1212 {
1213   struct text_record *text = xmalloc (sizeof *text);
1214   char *buffer = xmalloc (size + 1);
1215   read_bytes (r, buffer, size);
1216   buffer[size] = '\0';
1217   text->reader = r;
1218   text->buffer = buffer;
1219   text->size = size;
1220   text->pos = 0;
1221   return text;
1222 }
1223
1224 /* Closes TEXT and frees its storage.
1225    Not really needed, because the pool will free the text record anyway,
1226    but can be used to free it earlier. */
1227 static void
1228 close_text_record (struct text_record *text)
1229 {
1230   free (text->buffer);
1231   free (text);
1232 }
1233
1234 static char *
1235 text_tokenize (struct text_record *text, int delimiter)
1236 {
1237   size_t start = text->pos;
1238   while (text->pos < text->size
1239          && text->buffer[text->pos] != delimiter
1240          && text->buffer[text->pos] != '\0')
1241     text->pos++;
1242   if (start == text->pos)
1243     return NULL;
1244   text->buffer[text->pos++] = '\0';
1245   return &text->buffer[start];
1246 }
1247
1248 static bool
1249 text_match (struct text_record *text, int c) 
1250 {
1251   if (text->pos < text->size && text->buffer[text->pos] == c) 
1252     {
1253       text->pos++;
1254       return true;
1255     }
1256   else
1257     return false;
1258 }
1259
1260 /* Reads a integer value expressed in decimal, then a space, then a string that
1261    consists of exactly as many bytes as specified by the integer, then a space,
1262    from TEXT.  Returns the string, null-terminated, as a subset of TEXT's
1263    buffer (so the caller should not free the string). */
1264 static const char *
1265 text_parse_counted_string (struct text_record *text)
1266 {
1267   size_t start;
1268   size_t n;
1269   char *s;
1270
1271   start = text->pos;
1272   n = 0;
1273   while (isdigit ((unsigned char) text->buffer[text->pos]))
1274     n = (n * 10) + (text->buffer[text->pos++] - '0');
1275   if (start == text->pos)
1276     {
1277       sys_error (text->reader, "expecting digit at offset %zu in record",
1278                  text->pos);
1279       return NULL;
1280     }
1281
1282   if (!text_match (text, ' '))
1283     {
1284       sys_error (text->reader, "expecting space at offset %zu in record",
1285                  text->pos);
1286       return NULL;
1287     }
1288
1289   if (text->pos + n > text->size)
1290     {
1291       sys_error (text->reader, "%zu-byte string starting at offset %zu "
1292                  "exceeds record length %zu", n, text->pos, text->size);
1293       return NULL;
1294     }
1295
1296   s = &text->buffer[text->pos];
1297   if (s[n] != ' ')
1298     {
1299       sys_error (text->reader, "expecting space at offset %zu following "
1300                  "%zu-byte string", text->pos + n, n);
1301       return NULL;
1302     }
1303   s[n] = '\0';
1304   text->pos += n + 1;
1305   return s;
1306 }
1307
1308 /* Reads a variable=value pair from TEXT.
1309    Looks up the variable in DICT and stores it into *VAR.
1310    Stores a null-terminated value into *VALUE. */
1311 static bool
1312 read_variable_to_value_pair (struct text_record *text,
1313                              char **key, char **value)
1314 {
1315   *key = text_tokenize (text, '=');
1316   *value = text_tokenize (text, '\t');
1317   if (!*key || !*value)
1318     return false;
1319
1320   while (text->pos < text->size
1321          && (text->buffer[text->pos] == '\t'
1322              || text->buffer[text->pos] == '\0'))
1323     text->pos++;
1324   return true;
1325 }
1326
1327 /* Returns the current byte offset inside the TEXT's string. */
1328 static size_t
1329 text_pos (const struct text_record *text)
1330 {
1331   return text->pos;
1332 }
1333 \f
1334 static void
1335 usage (void)
1336 {
1337   printf ("\
1338 %s, a utility for dissecting system files.\n\
1339 Usage: %s [OPTION]... SYSFILE...\n\
1340 where each SYSFILE is the name of a system file.\n\
1341 \n\
1342 Options:\n\
1343   --data[=MAXCASES]   print (up to MAXCASES cases of) compressed data\n\
1344   --help              display this help and exit\n\
1345   --version           output version information and exit\n",
1346           program_name, program_name);
1347 }
1348
1349 /* Displays a corruption message. */
1350 static void
1351 sys_msg (struct sfm_reader *r, const char *format, va_list args)
1352 {
1353   printf ("\"%s\" near offset 0x%llx: ",
1354           r->file_name, (long long int) ftello (r->file));
1355   vprintf (format, args);
1356   putchar ('\n');
1357 }
1358
1359 /* Displays a warning for the current file position. */
1360 static void
1361 sys_warn (struct sfm_reader *r, const char *format, ...)
1362 {
1363   va_list args;
1364
1365   va_start (args, format);
1366   sys_msg (r, format, args);
1367   va_end (args);
1368 }
1369
1370 /* Displays an error for the current file position,
1371    marks it as in an error state,
1372    and aborts reading it using longjmp. */
1373 static void
1374 sys_error (struct sfm_reader *r, const char *format, ...)
1375 {
1376   va_list args;
1377
1378   va_start (args, format);
1379   sys_msg (r, format, args);
1380   va_end (args);
1381
1382   exit (EXIT_FAILURE);
1383 }
1384 \f
1385 /* Reads BYTE_CNT bytes into BUF.
1386    Returns true if exactly BYTE_CNT bytes are successfully read.
1387    Aborts if an I/O error or a partial read occurs.
1388    If EOF_IS_OK, then an immediate end-of-file causes false to be
1389    returned; otherwise, immediate end-of-file causes an abort
1390    too. */
1391 static inline bool
1392 read_bytes_internal (struct sfm_reader *r, bool eof_is_ok,
1393                      void *buf, size_t byte_cnt)
1394 {
1395   size_t bytes_read = fread (buf, 1, byte_cnt, r->file);
1396   if (bytes_read == byte_cnt)
1397     return true;
1398   else if (ferror (r->file))
1399     sys_error (r, "System error: %s.", strerror (errno));
1400   else if (!eof_is_ok || bytes_read != 0)
1401     sys_error (r, "Unexpected end of file.");
1402   else
1403     return false;
1404 }
1405
1406 /* Reads BYTE_CNT into BUF.
1407    Aborts upon I/O error or if end-of-file is encountered. */
1408 static void
1409 read_bytes (struct sfm_reader *r, void *buf, size_t byte_cnt)
1410 {
1411   read_bytes_internal (r, false, buf, byte_cnt);
1412 }
1413
1414 /* Reads BYTE_CNT bytes into BUF.
1415    Returns true if exactly BYTE_CNT bytes are successfully read.
1416    Returns false if an immediate end-of-file is encountered.
1417    Aborts if an I/O error or a partial read occurs. */
1418 static bool
1419 try_read_bytes (struct sfm_reader *r, void *buf, size_t byte_cnt)
1420 {
1421   return read_bytes_internal (r, true, buf, byte_cnt);
1422 }
1423
1424 /* Reads a 32-bit signed integer from R and returns its value in
1425    host format. */
1426 static int
1427 read_int (struct sfm_reader *r)
1428 {
1429   uint8_t integer[4];
1430   read_bytes (r, integer, sizeof integer);
1431   return integer_get (r->integer_format, integer, sizeof integer);
1432 }
1433
1434 /* Reads a 64-bit signed integer from R and returns its value in
1435    host format. */
1436 static int64_t
1437 read_int64 (struct sfm_reader *r)
1438 {
1439   uint8_t integer[8];
1440   read_bytes (r, integer, sizeof integer);
1441   return integer_get (r->integer_format, integer, sizeof integer);
1442 }
1443
1444 /* Reads a 64-bit floating-point number from R and returns its
1445    value in host format. */
1446 static double
1447 read_float (struct sfm_reader *r)
1448 {
1449   uint8_t number[8];
1450   read_bytes (r, number, sizeof number);
1451   return float_get_double (r->float_format, number);
1452 }
1453
1454 /* Reads exactly SIZE - 1 bytes into BUFFER
1455    and stores a null byte into BUFFER[SIZE - 1]. */
1456 static void
1457 read_string (struct sfm_reader *r, char *buffer, size_t size)
1458 {
1459   assert (size > 0);
1460   read_bytes (r, buffer, size - 1);
1461   buffer[size - 1] = '\0';
1462 }
1463
1464 /* Skips BYTES bytes forward in R. */
1465 static void
1466 skip_bytes (struct sfm_reader *r, size_t bytes)
1467 {
1468   while (bytes > 0)
1469     {
1470       char buffer[1024];
1471       size_t chunk = MIN (sizeof buffer, bytes);
1472       read_bytes (r, buffer, chunk);
1473       bytes -= chunk;
1474     }
1475 }
1476
1477 static void
1478 trim_spaces (char *s)
1479 {
1480   char *end = strchr (s, '\0');
1481   while (end > s && end[-1] == ' ')
1482     end--;
1483   *end = '\0';
1484 }