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