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