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