it works!!
[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
1098       /* Read variable name. */
1099       int var_name_len = read_int (r);
1100       if (var_name_len > ID_MAX_LEN)
1101         sys_error (r, "Variable name length in long string value label "
1102                    "record (%d) exceeds %d-byte limit.",
1103                    var_name_len, ID_MAX_LEN);
1104       char var_name[ID_MAX_LEN + 1];
1105       read_string (r, var_name, var_name_len + 1);
1106
1107       /* Read number of values. */
1108       uint8_t n_missing_values;
1109       read_bytes (r, &n_missing_values, 1);
1110
1111       /* Read value length. */
1112       int value_length = read_int (r);
1113
1114       printf ("\t%08llx: %s, %d missing values, each %d bytes:",
1115               posn, var_name, n_missing_values, value_length);
1116
1117       /* Read values. */
1118       for (int i = 0; i < n_missing_values; i++)
1119         {
1120           posn = ftello (r->file);
1121
1122           /* Read value. */
1123           char *value = xmalloc (value_length + 1);
1124           read_string (r, value, value_length + 1);
1125
1126           printf (" \"%s\"", value);
1127
1128           free (value);
1129         }
1130       printf ("\n");
1131     }
1132 }
1133
1134 static void
1135 hex_dump (size_t offset, const void *buffer_, size_t buffer_size)
1136 {
1137   const uint8_t *buffer = buffer_;
1138
1139   while (buffer_size > 0)
1140     {
1141       size_t n = MIN (buffer_size, 16);
1142       size_t i;
1143
1144       printf ("%04zx", offset);
1145       for (i = 0; i < 16; i++)
1146         {
1147           if (i < n)
1148             printf ("%c%02x", i == 8 ? '-' : ' ', buffer[i]);
1149           else
1150             printf ("   ");
1151         }
1152
1153       printf (" |");
1154       for (i = 0; i < 16; i++)
1155         {
1156           unsigned char c = i < n ? buffer[i] : ' ';
1157           putchar (isprint (c) ? c : '.');
1158         }
1159       printf ("|\n");
1160
1161       offset += n;
1162       buffer += n;
1163       buffer_size -= n;
1164     }
1165 }
1166
1167 /* Reads and prints any type 7 record that we don't understand. */
1168 static void
1169 read_unknown_extension (struct sfm_reader *r, size_t size, size_t count)
1170 {
1171   unsigned char *buffer;
1172   size_t i;
1173
1174   if (size == 0 || count > 65536 / size)
1175     skip_bytes (r, size * count);
1176   else if (size != 1)
1177     {
1178       buffer = xmalloc (size);
1179       for (i = 0; i < count; i++)
1180         {
1181           read_bytes (r, buffer, size);
1182           hex_dump (i * size, buffer, size);
1183         }
1184       free (buffer);
1185     }
1186   else
1187     {
1188       buffer = xmalloc (count);
1189       read_bytes (r, buffer, count);
1190       print_string (CHAR_CAST (char *, buffer), count);
1191       free (buffer);
1192     }
1193 }
1194
1195 static void
1196 read_variable_attributes (struct sfm_reader *r, size_t size, size_t count)
1197 {
1198   struct text_record *text;
1199
1200   printf ("%08llx: variable attributes\n", (long long int) ftello (r->file));
1201   text = open_text_record (r, size, count);
1202   for (;;)
1203     {
1204       const char *variable = text_tokenize (text, ':');
1205       if (variable == NULL || !read_attributes (r, text, variable))
1206         break;
1207     }
1208   close_text_record (text);
1209 }
1210
1211 static void
1212 read_simple_compressed_data (struct sfm_reader *r, int max_cases)
1213 {
1214   enum { N_OPCODES = 8 };
1215   uint8_t opcodes[N_OPCODES];
1216   long long int opcode_ofs;
1217   int opcode_idx;
1218   int case_num;
1219   int i;
1220
1221   read_int (r);
1222   printf ("\n%08llx: compressed data:\n", (long long int) ftello (r->file));
1223
1224   opcode_idx = N_OPCODES;
1225   opcode_ofs = 0;
1226   case_num = 0;
1227   for (case_num = 0; case_num < max_cases; case_num++)
1228     {
1229       printf ("%08llx: case %d's uncompressible data begins\n",
1230               (long long int) ftello (r->file), case_num);
1231       for (i = 0; i < r->n_var_widths;)
1232         {
1233           int width = r->var_widths[i];
1234           char raw_value[8];
1235           int opcode;
1236
1237           if (opcode_idx >= N_OPCODES)
1238             {
1239               opcode_ofs = ftello (r->file);
1240               if (i == 0)
1241                 {
1242                   if (!try_read_bytes (r, opcodes, 8))
1243                     return;
1244                 }
1245               else
1246                 read_bytes (r, opcodes, 8);
1247               opcode_idx = 0;
1248             }
1249           opcode = opcodes[opcode_idx];
1250           printf ("%08llx: variable %d: opcode %d: ",
1251                   opcode_ofs + opcode_idx, i, opcode);
1252
1253           switch (opcode)
1254             {
1255             default:
1256               printf ("%.*g", DBL_DIG + 1, opcode - r->bias);
1257               if (width != 0)
1258                 printf (", but this is a string variable (width=%d)", width);
1259               printf ("\n");
1260               i++;
1261               break;
1262
1263             case 0:
1264               printf ("ignored padding\n");
1265               break;
1266
1267             case 252:
1268               printf ("end of data\n");
1269               return;
1270
1271             case 253:
1272               read_bytes (r, raw_value, 8);
1273               printf ("uncompressible data: ");
1274               print_untyped_value (r, raw_value);
1275               printf ("\n");
1276               i++;
1277               break;
1278
1279             case 254:
1280               printf ("spaces");
1281               if (width == 0)
1282                 printf (", but this is a numeric variable");
1283               printf ("\n");
1284               i++;
1285               break;
1286
1287             case 255:
1288               printf ("SYSMIS");
1289               if (width != 0)
1290                 printf (", but this is a string variable (width=%d)", width);
1291               printf ("\n");
1292               i++;
1293               break;
1294             }
1295
1296           opcode_idx++;
1297         }
1298     }
1299 }
1300
1301 static void
1302 read_zlib_compressed_data (struct sfm_reader *r)
1303 {
1304   long long int ofs;
1305   long long int this_ofs, next_ofs, next_len;
1306   long long int bias, zero;
1307   long long int expected_uncmp_ofs, expected_cmp_ofs;
1308   unsigned int block_size, n_blocks;
1309   unsigned int i;
1310
1311   read_int (r);
1312   ofs = ftello (r->file);
1313   printf ("\n%08llx: ZLIB compressed data header:\n", ofs);
1314
1315   this_ofs = read_int64 (r);
1316   next_ofs = read_int64 (r);
1317   next_len = read_int64 (r);
1318
1319   printf ("\tzheader_ofs: 0x%llx\n", this_ofs);
1320   if (this_ofs != ofs)
1321     printf ("\t\t(Expected 0x%llx.)\n", ofs);
1322   printf ("\tztrailer_ofs: 0x%llx\n", next_ofs);
1323   printf ("\tztrailer_len: %lld\n", next_len);
1324   if (next_len < 24 || next_len % 24)
1325     printf ("\t\t(Trailer length is not a positive multiple of 24.)\n");
1326
1327   printf ("\n%08llx: 0x%llx bytes of ZLIB compressed data\n",
1328           ofs + 8 * 3, next_ofs - (ofs + 8 * 3));
1329
1330   skip_bytes (r, next_ofs - (ofs + 8 * 3));
1331
1332   printf ("\n%08llx: ZLIB trailer fixed header:\n", next_ofs);
1333   bias = read_int64 (r);
1334   zero = read_int64 (r);
1335   block_size = read_int (r);
1336   n_blocks = read_int (r);
1337   printf ("\tbias: %lld\n", bias);
1338   printf ("\tzero: 0x%llx\n", zero);
1339   if (zero != 0)
1340     printf ("\t\t(Expected 0.)\n");
1341   printf ("\tblock_size: 0x%x\n", block_size);
1342   if (block_size != 0x3ff000)
1343     printf ("\t\t(Expected 0x3ff000.)\n");
1344   printf ("\tn_blocks: %u\n", n_blocks);
1345   if (n_blocks != next_len / 24 - 1)
1346     printf ("\t\t(Expected %llu.)\n", next_len / 24 - 1);
1347
1348   expected_uncmp_ofs = ofs;
1349   expected_cmp_ofs = ofs + 24;
1350   for (i = 0; i < n_blocks; i++)
1351     {
1352       long long int blockinfo_ofs = ftello (r->file);
1353       unsigned long long int uncompressed_ofs = read_int64 (r);
1354       unsigned long long int compressed_ofs = read_int64 (r);
1355       unsigned int uncompressed_size = read_int (r);
1356       unsigned int compressed_size = read_int (r);
1357
1358       printf ("\n%08llx: ZLIB block descriptor %d\n", blockinfo_ofs, i + 1);
1359
1360       printf ("\tuncompressed_ofs: 0x%llx\n", uncompressed_ofs);
1361       if (uncompressed_ofs != expected_uncmp_ofs)
1362         printf ("\t\t(Expected 0x%llx.)\n", ofs);
1363
1364       printf ("\tcompressed_ofs: 0x%llx\n", compressed_ofs);
1365       if (compressed_ofs != expected_cmp_ofs)
1366         printf ("\t\t(Expected 0x%llx.)\n", ofs + 24);
1367
1368       printf ("\tuncompressed_size: 0x%x\n", uncompressed_size);
1369       if (i < n_blocks - 1 && uncompressed_size != block_size)
1370         printf ("\t\t(Expected 0x%x.)\n", block_size);
1371
1372       printf ("\tcompressed_size: 0x%x\n", compressed_size);
1373       if (i == n_blocks - 1 && compressed_ofs + compressed_size != next_ofs)
1374         printf ("\t\t(This was expected to be 0x%llx.)\n",
1375                 next_ofs - compressed_size);
1376
1377       expected_uncmp_ofs += uncompressed_size;
1378       expected_cmp_ofs += compressed_size;
1379     }
1380 }
1381 \f
1382 /* Helpers for reading records that consist of structured text
1383    strings. */
1384
1385 /* State. */
1386 struct text_record
1387   {
1388     struct sfm_reader *reader;  /* Reader. */
1389     char *buffer;               /* Record contents. */
1390     size_t size;                /* Size of buffer. */
1391     size_t pos;                 /* Current position in buffer. */
1392   };
1393
1394 /* Reads SIZE * COUNT bytes into a text record for R,
1395    and returns the new text record. */
1396 static struct text_record *
1397 open_text_record (struct sfm_reader *r, size_t size, size_t count)
1398 {
1399   struct text_record *text = xmalloc (sizeof *text);
1400
1401   if (size_overflow_p (xsum (1, xtimes (size, count))))
1402     sys_error (r, "Extension record too large.");
1403
1404   size_t n_bytes = size * count;
1405   char *buffer = xmalloc (n_bytes + 1);
1406   read_bytes (r, buffer, n_bytes);
1407   buffer[n_bytes] = '\0';
1408   text->reader = r;
1409   text->buffer = buffer;
1410   text->size = n_bytes;
1411   text->pos = 0;
1412   return text;
1413 }
1414
1415 /* Closes TEXT and frees its storage.
1416    Not really needed, because the pool will free the text record anyway,
1417    but can be used to free it earlier. */
1418 static void
1419 close_text_record (struct text_record *text)
1420 {
1421   free (text->buffer);
1422   free (text);
1423 }
1424
1425 static char *
1426 text_tokenize (struct text_record *text, int delimiter)
1427 {
1428   size_t start = text->pos;
1429   while (text->pos < text->size
1430          && text->buffer[text->pos] != delimiter
1431          && text->buffer[text->pos] != '\0')
1432     text->pos++;
1433   if (start == text->pos)
1434     return NULL;
1435   text->buffer[text->pos++] = '\0';
1436   return &text->buffer[start];
1437 }
1438
1439 static bool
1440 text_match (struct text_record *text, int c)
1441 {
1442   if (text->pos < text->size && text->buffer[text->pos] == c)
1443     {
1444       text->pos++;
1445       return true;
1446     }
1447   else
1448     return false;
1449 }
1450
1451 /* Reads a integer value expressed in decimal, then a space, then a string that
1452    consists of exactly as many bytes as specified by the integer, then a space,
1453    from TEXT.  Returns the string, null-terminated, as a subset of TEXT's
1454    buffer (so the caller should not free the string). */
1455 static const char *
1456 text_parse_counted_string (struct text_record *text)
1457 {
1458   size_t start;
1459   size_t n;
1460   char *s;
1461
1462   start = text->pos;
1463   n = 0;
1464   while (isdigit ((unsigned char) text->buffer[text->pos]))
1465     n = (n * 10) + (text->buffer[text->pos++] - '0');
1466   if (start == text->pos)
1467     {
1468       sys_error (text->reader, "expecting digit at offset %zu in record",
1469                  text->pos);
1470       return NULL;
1471     }
1472
1473   if (!text_match (text, ' '))
1474     {
1475       sys_error (text->reader, "expecting space at offset %zu in record",
1476                  text->pos);
1477       return NULL;
1478     }
1479
1480   if (text->pos + n > text->size)
1481     {
1482       sys_error (text->reader, "%zu-byte string starting at offset %zu "
1483                  "exceeds record length %zu", n, text->pos, text->size);
1484       return NULL;
1485     }
1486
1487   s = &text->buffer[text->pos];
1488   if (s[n] != ' ')
1489     {
1490       sys_error (text->reader, "expecting space at offset %zu following "
1491                  "%zu-byte string", text->pos + n, n);
1492       return NULL;
1493     }
1494   s[n] = '\0';
1495   text->pos += n + 1;
1496   return s;
1497 }
1498
1499 /* Reads a variable=value pair from TEXT.
1500    Looks up the variable in DICT and stores it into *VAR.
1501    Stores a null-terminated value into *VALUE. */
1502 static bool
1503 read_variable_to_value_pair (struct text_record *text,
1504                              char **key, char **value)
1505 {
1506   *key = text_tokenize (text, '=');
1507   *value = text_tokenize (text, '\t');
1508   if (!*key || !*value)
1509     return false;
1510
1511   while (text->pos < text->size
1512          && (text->buffer[text->pos] == '\t'
1513              || text->buffer[text->pos] == '\0'))
1514     text->pos++;
1515   return true;
1516 }
1517
1518 /* Returns the current byte offset inside the TEXT's string. */
1519 static size_t
1520 text_pos (const struct text_record *text)
1521 {
1522   return text->pos;
1523 }
1524
1525 static const char *
1526 text_get_all (const struct text_record *text)
1527 {
1528   return text->buffer;
1529 }
1530 \f
1531 static void
1532 usage (void)
1533 {
1534   printf ("\
1535 %s, a utility for dissecting system files.\n\
1536 Usage: %s [OPTION]... SYSFILE...\n\
1537 where each SYSFILE is the name of a system file.\n\
1538 \n\
1539 Options:\n\
1540   --data[=MAXCASES]   print (up to MAXCASES cases of) compressed data\n\
1541   --help              display this help and exit\n\
1542   --version           output version information and exit\n",
1543           program_name, program_name);
1544 }
1545
1546 /* Displays a corruption message. */
1547 static void
1548 sys_msg (struct sfm_reader *r, const char *format, va_list args)
1549 {
1550   printf ("\"%s\" near offset 0x%llx: ",
1551           r->file_name, (long long int) ftello (r->file));
1552   vprintf (format, args);
1553   putchar ('\n');
1554 }
1555
1556 /* Displays a warning for the current file position. */
1557 static void
1558 sys_warn (struct sfm_reader *r, const char *format, ...)
1559 {
1560   va_list args;
1561
1562   va_start (args, format);
1563   sys_msg (r, format, args);
1564   va_end (args);
1565 }
1566
1567 /* Displays an error for the current file position,
1568    marks it as in an error state,
1569    and aborts reading it using longjmp. */
1570 static void
1571 sys_error (struct sfm_reader *r, const char *format, ...)
1572 {
1573   va_list args;
1574
1575   va_start (args, format);
1576   sys_msg (r, format, args);
1577   va_end (args);
1578
1579   exit (EXIT_FAILURE);
1580 }
1581 \f
1582 /* Reads BYTE_CNT bytes into BUF.
1583    Returns true if exactly BYTE_CNT bytes are successfully read.
1584    Aborts if an I/O error or a partial read occurs.
1585    If EOF_IS_OK, then an immediate end-of-file causes false to be
1586    returned; otherwise, immediate end-of-file causes an abort
1587    too. */
1588 static inline bool
1589 read_bytes_internal (struct sfm_reader *r, bool eof_is_ok,
1590                      void *buf, size_t n_bytes)
1591 {
1592   size_t bytes_read = fread (buf, 1, n_bytes, r->file);
1593   if (bytes_read == n_bytes)
1594     return true;
1595   else if (ferror (r->file))
1596     sys_error (r, "System error: %s.", strerror (errno));
1597   else if (!eof_is_ok || bytes_read != 0)
1598     sys_error (r, "Unexpected end of file.");
1599   else
1600     return false;
1601 }
1602
1603 /* Reads BYTE_CNT into BUF.
1604    Aborts upon I/O error or if end-of-file is encountered. */
1605 static void
1606 read_bytes (struct sfm_reader *r, void *buf, size_t n_bytes)
1607 {
1608   read_bytes_internal (r, false, buf, n_bytes);
1609 }
1610
1611 /* Reads BYTE_CNT bytes into BUF.
1612    Returns true if exactly BYTE_CNT bytes are successfully read.
1613    Returns false if an immediate end-of-file is encountered.
1614    Aborts if an I/O error or a partial read occurs. */
1615 static bool
1616 try_read_bytes (struct sfm_reader *r, void *buf, size_t n_bytes)
1617 {
1618   return read_bytes_internal (r, true, buf, n_bytes);
1619 }
1620
1621 /* Reads a 32-bit signed integer from R and returns its value in
1622    host format. */
1623 static int
1624 read_int (struct sfm_reader *r)
1625 {
1626   uint8_t integer[4];
1627   read_bytes (r, integer, sizeof integer);
1628   return integer_get (r->integer_format, integer, sizeof integer);
1629 }
1630
1631 /* Reads a 64-bit signed integer from R and returns its value in
1632    host format. */
1633 static int64_t
1634 read_int64 (struct sfm_reader *r)
1635 {
1636   uint8_t integer[8];
1637   read_bytes (r, integer, sizeof integer);
1638   return integer_get (r->integer_format, integer, sizeof integer);
1639 }
1640
1641 /* Reads a 64-bit floating-point number from R and returns its
1642    value in host format. */
1643 static double
1644 read_float (struct sfm_reader *r)
1645 {
1646   uint8_t number[8];
1647   read_bytes (r, number, sizeof number);
1648   return float_get_double (r->float_format, number);
1649 }
1650
1651 /* Reads exactly SIZE - 1 bytes into BUFFER
1652    and stores a null byte into BUFFER[SIZE - 1]. */
1653 static void
1654 read_string (struct sfm_reader *r, char *buffer, size_t size)
1655 {
1656   assert (size > 0);
1657   read_bytes (r, buffer, size - 1);
1658   buffer[size - 1] = '\0';
1659 }
1660
1661 /* Skips BYTES bytes forward in R. */
1662 static void
1663 skip_bytes (struct sfm_reader *r, size_t bytes)
1664 {
1665   while (bytes > 0)
1666     {
1667       char buffer[1024];
1668       size_t chunk = MIN (sizeof buffer, bytes);
1669       read_bytes (r, buffer, chunk);
1670       bytes -= chunk;
1671     }
1672 }
1673
1674 static void
1675 trim_spaces (char *s)
1676 {
1677   char *end = strchr (s, '\0');
1678   while (end > s && end[-1] == ' ')
1679     end--;
1680   *end = '\0';
1681 }
1682
1683 static void
1684 print_string (const char *s, size_t len)
1685 {
1686   if (memchr (s, 0, len) == 0)
1687     {
1688       size_t i;
1689
1690       for (i = 0; i < len; i++)
1691         {
1692           unsigned char c = s[i];
1693
1694           if (c == '\\')
1695             printf ("\\\\");
1696           else if (c == '\n' || isprint (c))
1697             putchar (c);
1698           else
1699             printf ("\\%02x", c);
1700         }
1701       putchar ('\n');
1702     }
1703   else
1704     hex_dump (0, s, len);
1705 }