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