1 /* PSPP - computes sample statistics.
2 Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3 Written by Ben Pfaff <blp@gnu.org>.
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
10 This program is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
30 #include "file-handle.h"
37 #include "value-labels.h"
41 #include "debug-print.h"
43 /* PORTME: This file may require substantial revision for those
44 systems that don't meet the typical 32-bit integer/64-bit double
45 model. It's kinda hard to tell without having one of them on my
48 /* sfm's file_handle extension. */
51 FILE *file; /* Actual file. */
52 int opened; /* Reference count. */
54 struct dictionary *dict; /* File's dictionary. */
56 int reverse_endian; /* 1=file has endianness opposite us. */
57 int case_size; /* Number of `values's per case. */
58 long ncases; /* Number of cases, -1 if unknown. */
59 int compressed; /* 1=compressed, 0=not compressed. */
60 double bias; /* Compression bias, usually 100.0. */
61 int weight_index; /* 0-based index of weighting variable, or -1. */
63 /* File's special constants. */
68 /* Uncompression buffer. */
69 flt64 *buf; /* Buffer data. */
70 flt64 *ptr; /* Current location in buffer. */
71 flt64 *end; /* End of buffer data. */
73 /* Compression instruction octet. */
74 unsigned char x[sizeof (flt64)];
75 /* Current instruction octet. */
76 unsigned char *y; /* Location in current instruction octet. */
79 static struct fh_ext_class sfm_r_class;
82 void dump_dictionary (struct dictionary * dict);
87 /* bswap_int32(): Reverse the byte order of 32-bit integer *X. */
89 bswap_int32 (int32 *x)
91 unsigned char *y = (unsigned char *) x;
103 /* Reverse the byte order of 64-bit floating point *X. */
105 bswap_flt64 (flt64 *x)
107 unsigned char *y = (unsigned char *) x;
128 corrupt_msg (int class, const char *format,...)
129 __attribute__ ((format (printf, 2, 3)));
131 /* Displays a corrupt sysfile error. */
133 corrupt_msg (int class, const char *format,...)
140 va_start (args, format);
141 vsnprintf (buf, 1024, format, args);
149 getl_location (&e.where.filename, &e.where.line_number);
150 e.title = _("corrupt system file: ");
157 /* Closes a system file after we're done with it. */
159 sfm_close (struct file_handle * h)
161 struct sfm_fhuser_ext *ext = h->ext;
164 assert (ext->opened == 0);
165 if (EOF == fn_close (h->fn, ext->file))
166 msg (ME, _("%s: Closing system file: %s."), h->fn, strerror (errno));
171 /* Closes a system file if we're done with it. */
173 sfm_maybe_close (struct file_handle *h)
175 struct sfm_fhuser_ext *ext = h->ext;
177 if (ext->opened == 1)
183 /* Dictionary reader. */
185 static void *bufread (struct file_handle * handle, void *buf, size_t nbytes,
188 static int read_header (struct file_handle * h, struct sfm_read_info * inf);
189 static int parse_format_spec (struct file_handle * h, int32 s,
190 struct fmt_spec * v, struct variable *vv);
191 static int read_value_labels (struct file_handle * h, struct variable ** var_by_index);
192 static int read_variables (struct file_handle * h, struct variable *** var_by_index);
193 static int read_machine_int32_info (struct file_handle * h, int size, int count);
194 static int read_machine_flt64_info (struct file_handle * h, int size, int count);
195 static int read_documents (struct file_handle * h);
197 /* Displays the message X with corrupt_msg, then jumps to the lossage
207 /* Calls bufread with the specified arguments, and jumps to lossage if
209 #define assertive_bufread(a,b,c,d) \
212 if (!bufread (a,b,c,d)) \
217 /* Reads the dictionary from file with handle H, and returns it in a
218 dictionary structure. This dictionary may be modified in order to
219 rename, reorder, and delete variables, etc. */
221 sfm_read_dictionary (struct file_handle * h, struct sfm_read_info * inf)
223 /* The file handle extension record. */
224 struct sfm_fhuser_ext *ext;
226 /* Allows for quick reference to variables according to indexes
227 relative to position within a case. */
228 struct variable **var_by_index = NULL;
230 /* Check whether the file is already open. */
231 if (h->class == &sfm_r_class)
237 else if (h->class != NULL)
239 msg (ME, _("Cannot read file %s as system file: already opened for %s."),
240 fh_handle_name (h), h->class->name);
244 msg (VM (1), _("%s: Opening system-file handle %s for reading."),
245 fh_handle_filename (h), fh_handle_name (h));
247 /* Open the physical disk file. */
248 ext = xmalloc (sizeof (struct sfm_fhuser_ext));
249 ext->file = fn_open (h->norm_fn, "rb");
250 if (ext->file == NULL)
252 msg (ME, _("An error occurred while opening \"%s\" for reading "
253 "as a system file: %s."), h->fn, strerror (errno));
259 /* Initialize the sfm_fhuser_ext structure. */
260 h->class = &sfm_r_class;
263 ext->buf = ext->ptr = ext->end = NULL;
264 ext->y = ext->x + sizeof ext->x;
267 /* Default special constants. */
268 ext->sysmis = -FLT64_MAX;
269 ext->highest = FLT64_MAX;
270 ext->lowest = second_lowest_flt64;
272 /* Read the header. */
273 if (!read_header (h, inf))
276 /* Read about the variables. */
277 if (!read_variables (h, &var_by_index))
280 /* Handle weighting. */
281 if (ext->weight_index != -1)
283 struct variable *wv = var_by_index[ext->weight_index];
286 lose ((ME, _("%s: Weighting variable may not be a continuation of "
287 "a long string variable."), h->fn));
288 else if (wv->type == ALPHA)
289 lose ((ME, _("%s: Weighting variable may not be a string variable."),
292 dict_set_weight (ext->dict, wv);
295 dict_set_weight (ext->dict, NULL);
297 /* Read records of types 3, 4, 6, and 7. */
302 assertive_bufread (h, &rec_type, sizeof rec_type, 0);
303 if (ext->reverse_endian)
304 bswap_int32 (&rec_type);
309 if (!read_value_labels (h, var_by_index))
314 lose ((ME, _("%s: Orphaned variable index record (type 4). Type 4 "
315 "records must always immediately follow type 3 records."),
319 if (!read_documents (h))
335 assertive_bufread (h, &data, sizeof data, 0);
336 if (ext->reverse_endian)
338 bswap_int32 (&data.subtype);
339 bswap_int32 (&data.size);
340 bswap_int32 (&data.count);
343 /*if(data.size != sizeof(int32) && data.size != sizeof(flt64))
344 lose((ME, "%s: Element size in record type 7, subtype %d, is "
345 "not either the size of IN (%d) or OBS (%d); actual value "
347 h->fn, data.subtype, sizeof(int32), sizeof(flt64),
350 switch (data.subtype)
353 if (!read_machine_int32_info (h, data.size, data.count))
358 if (!read_machine_flt64_info (h, data.size, data.count))
364 case 11: /* ?? Used by SPSS 8.0. */
369 msg (MW, _("%s: Unrecognized record type 7, subtype %d "
370 "encountered in system file."), h->fn, data.subtype);
376 void *x = bufread (h, NULL, data.size * data.count, 0);
388 assertive_bufread (h, &filler, sizeof filler, 0);
389 goto break_out_of_loop;
393 lose ((ME, _("%s: Unrecognized record type %d."), h->fn, rec_type));
398 /* Come here on successful completion. */
399 msg (VM (2), _("Read system-file dictionary successfully."));
402 dump_dictionary (ext->dict);
408 /* Come here on unsuccessful completion. */
409 msg (VM (1), _("Error reading system-file header."));
412 fn_close (h->fn, ext->file);
413 if (ext && ext->dict)
414 dict_destroy (ext->dict);
421 /* Read record type 7, subtype 3. */
423 read_machine_int32_info (struct file_handle * h, int size, int count)
425 struct sfm_fhuser_ext *ext = h->ext;
432 if (size != sizeof (int32) || count != 8)
433 lose ((ME, _("%s: Bad size (%d) or count (%d) field on record type 7, "
434 "subtype 3. Expected size %d, count 8."),
435 h->fn, size, count, sizeof (int32)));
437 assertive_bufread (h, data, sizeof data, 0);
438 if (ext->reverse_endian)
439 for (i = 0; i < 8; i++)
440 bswap_int32 (&data[i]);
442 /* PORTME: Check floating-point representation. */
445 lose ((ME, _("%s: Floating-point representation in system file is not "
446 "IEEE-754. PSPP cannot convert between floating-point "
447 "formats."), h->fn));
450 /* PORTME: Check recorded file endianness against intuited file
452 #ifdef WORDS_BIGENDIAN
457 if (ext->reverse_endian)
459 if (file_bigendian ^ (data[6] == 1))
460 lose ((ME, _("%s: File-indicated endianness (%s) does not match endianness "
461 "intuited from file header (%s)."),
462 h->fn, file_bigendian ? _("big-endian") : _("little-endian"),
463 data[6] == 1 ? _("big-endian") : (data[6] == 2 ? _("little-endian")
466 /* PORTME: Character representation code. */
467 if (data[7] != 2 && data[7] != 3)
468 lose ((ME, _("%s: File-indicated character representation code (%s) is not "
470 data[7] == 1 ? "EBCDIC" : (data[7] == 4 ? _("DEC Kanji") : _("Unknown"))));
478 /* Read record type 7, subtype 4. */
480 read_machine_flt64_info (struct file_handle * h, int size, int count)
482 struct sfm_fhuser_ext *ext = h->ext;
488 if (size != sizeof (flt64) || count != 3)
489 lose ((ME, _("%s: Bad size (%d) or count (%d) field on record type 7, "
490 "subtype 4. Expected size %d, count 8."),
491 h->fn, size, count, sizeof (flt64)));
493 assertive_bufread (h, data, sizeof data, 0);
494 if (ext->reverse_endian)
495 for (i = 0; i < 3; i++)
496 bswap_flt64 (&data[i]);
498 if (data[0] != SYSMIS || data[1] != FLT64_MAX
499 || data[2] != second_lowest_flt64)
501 ext->sysmis = data[0];
502 ext->highest = data[1];
503 ext->lowest = data[2];
504 msg (MW, _("%s: File-indicated value is different from internal value "
505 "for at least one of the three system values. SYSMIS: "
506 "indicated %g, expected %g; HIGHEST: %g, %g; LOWEST: "
508 h->fn, (double) data[0], (double) SYSMIS,
509 (double) data[1], (double) FLT64_MAX,
510 (double) data[2], (double) second_lowest_flt64);
520 read_header (struct file_handle * h, struct sfm_read_info * inf)
522 struct sfm_fhuser_ext *ext = h->ext; /* File extension strcut. */
523 struct sysfile_header hdr; /* Disk buffer. */
524 struct dictionary *dict; /* File dictionary. */
525 char prod_name[sizeof hdr.prod_name + 1]; /* Buffer for product name. */
526 int skip_amt; /* Amount of product name to omit. */
529 /* Create the dictionary. */
530 dict = ext->dict = dict_create ();
532 /* Read header, check magic. */
533 assertive_bufread (h, &hdr, sizeof hdr, 0);
534 if (0 != strncmp ("$FL2", hdr.rec_type, 4))
535 lose ((ME, _("%s: Bad magic. Proper system files begin with "
536 "the four characters `$FL2'. This file will not be read."),
539 /* Check eye-catcher string. */
540 memcpy (prod_name, hdr.prod_name, sizeof hdr.prod_name);
541 for (i = 0; i < 60; i++)
542 if (!isprint ((unsigned char) prod_name[i]))
544 for (i = 59; i >= 0; i--)
545 if (!isgraph ((unsigned char) prod_name[i]))
550 prod_name[60] = '\0';
554 static const char *prefix[N_PREFIXES] =
556 "@(#) SPSS DATA FILE",
562 for (i = 0; i < N_PREFIXES; i++)
563 if (!strncmp (prefix[i], hdr.prod_name, strlen (prefix[i])))
565 skip_amt = strlen (prefix[i]);
570 /* Check endianness. */
571 /* PORTME: endianness. */
572 if (hdr.layout_code == 2)
573 ext->reverse_endian = 0;
576 bswap_int32 (&hdr.layout_code);
577 if (hdr.layout_code != 2)
578 lose ((ME, _("%s: File layout code has unexpected value %d. Value "
579 "should be 2, in big-endian or little-endian format."),
580 h->fn, hdr.layout_code));
582 ext->reverse_endian = 1;
583 bswap_int32 (&hdr.case_size);
584 bswap_int32 (&hdr.compressed);
585 bswap_int32 (&hdr.weight_index);
586 bswap_int32 (&hdr.ncases);
587 bswap_flt64 (&hdr.bias);
590 /* Copy basic info and verify correctness. */
591 ext->case_size = hdr.case_size;
592 if (hdr.case_size <= 0 || ext->case_size > (INT_MAX
593 / (int) sizeof (union value) / 2))
594 lose ((ME, _("%s: Number of elements per case (%d) is not between 1 "
595 "and %d."), h->fn, hdr.case_size, INT_MAX / sizeof (union value) / 2));
597 ext->compressed = hdr.compressed;
599 ext->weight_index = hdr.weight_index - 1;
600 if (hdr.weight_index < 0 || hdr.weight_index > hdr.case_size)
601 lose ((ME, _("%s: Index of weighting variable (%d) is not between 0 "
602 "and number of elements per case (%d)."),
603 h->fn, hdr.weight_index, ext->case_size));
605 ext->ncases = hdr.ncases;
606 if (ext->ncases < -1 || ext->ncases > INT_MAX / 2)
607 lose ((ME, _("%s: Number of cases in file (%ld) is not between -1 and "
608 "%d."), h->fn, (long) ext->ncases, INT_MAX / 2));
610 ext->bias = hdr.bias;
611 if (ext->bias != 100.0)
612 corrupt_msg (MW, _("%s: Compression bias (%g) is not the usual "
613 "value of 100."), h->fn, ext->bias);
615 /* Make a file label only on the condition that the given label is
616 not all spaces or nulls. */
620 for (i = sizeof hdr.file_label - 1; i >= 0; i--)
621 if (!isspace ((unsigned char) hdr.file_label[i])
622 && hdr.file_label[i] != 0)
624 char *label = xmalloc (i + 2);
625 memcpy (label, hdr.file_label, i + 1);
627 dict_set_label (dict, label);
637 memcpy (inf->creation_date, hdr.creation_date, 9);
638 inf->creation_date[9] = 0;
640 memcpy (inf->creation_time, hdr.creation_time, 8);
641 inf->creation_time[8] = 0;
643 #ifdef WORDS_BIGENDIAN
644 inf->bigendian = !ext->reverse_endian;
646 inf->bigendian = ext->reverse_endian;
649 inf->compressed = hdr.compressed;
651 inf->ncases = hdr.ncases;
653 for (cp = &prod_name[skip_amt]; cp < &prod_name[60]; cp++)
654 if (isgraph ((unsigned char) *cp))
656 strcpy (inf->product, cp);
665 /* Reads most of the dictionary from file H; also fills in the
666 associated VAR_BY_INDEX array. The get.* elements in the
667 created dictionary are set to appropriate values to allow the
670 read_variables (struct file_handle * h, struct variable *** var_by_index)
674 struct sfm_fhuser_ext *ext = h->ext; /* File extension record. */
675 struct dictionary *dict = ext->dict; /* Dictionary being constructed. */
676 struct sysfile_variable sv; /* Disk buffer. */
677 int long_string_count = 0; /* # of long string continuation
678 records still expected. */
679 int next_value = 0; /* Index to next `value' structure. */
681 /* Allocate variables. */
682 *var_by_index = xmalloc (sizeof **var_by_index * ext->case_size);
684 /* Read in the entry for each variable and use the info to
685 initialize the dictionary. */
686 for (i = 0; i < ext->case_size; i++)
692 assertive_bufread (h, &sv, sizeof sv, 0);
694 if (ext->reverse_endian)
696 bswap_int32 (&sv.rec_type);
697 bswap_int32 (&sv.type);
698 bswap_int32 (&sv.has_var_label);
699 bswap_int32 (&sv.n_missing_values);
700 bswap_int32 (&sv.print);
701 bswap_int32 (&sv.write);
704 if (sv.rec_type != 2)
705 lose ((ME, _("%s: position %d: Bad record type (%d); "
706 "the expected value was 2."), h->fn, i, sv.rec_type));
708 /* If there was a long string previously, make sure that the
709 continuations are present; otherwise make sure there aren't
711 if (long_string_count)
714 lose ((ME, _("%s: position %d: String variable does not have "
715 "proper number of continuation records."), h->fn, i));
717 (*var_by_index)[i] = NULL;
721 else if (sv.type == -1)
722 lose ((ME, _("%s: position %d: Superfluous long string continuation "
723 "record."), h->fn, i));
725 /* Check fields for validity. */
726 if (sv.type < 0 || sv.type > 255)
727 lose ((ME, _("%s: position %d: Bad variable type code %d."),
729 if (sv.has_var_label != 0 && sv.has_var_label != 1)
730 lose ((ME, _("%s: position %d: Variable label indicator field is not "
731 "0 or 1."), h->fn, i));
732 if (sv.n_missing_values < -3 || sv.n_missing_values > 3
733 || sv.n_missing_values == -1)
734 lose ((ME, _("%s: position %d: Missing value indicator field is not "
735 "-3, -2, 0, 1, 2, or 3."), h->fn, i));
737 /* Copy first character of variable name. */
738 if (!isalpha ((unsigned char) sv.name[0])
739 && sv.name[0] != '@' && sv.name[0] != '#')
740 lose ((ME, _("%s: position %d: Variable name begins with invalid "
741 "character."), h->fn, i));
742 if (islower ((unsigned char) sv.name[0]))
743 msg (MW, _("%s: position %d: Variable name begins with lowercase letter "
744 "%c."), h->fn, i, sv.name[0]);
745 if (sv.name[0] == '#')
746 msg (MW, _("%s: position %d: Variable name begins with octothorpe "
747 "(`#'). Scratch variables should not appear in system "
748 "files."), h->fn, i);
749 name[0] = toupper ((unsigned char) (sv.name[0]));
751 /* Copy remaining characters of variable name. */
752 for (j = 1; j < 8; j++)
754 int c = (unsigned char) sv.name[j];
758 else if (islower (c))
760 msg (MW, _("%s: position %d: Variable name character %d is "
761 "lowercase letter %c."), h->fn, i, j + 1, sv.name[j]);
762 name[j] = toupper ((unsigned char) (c));
764 else if (isalnum (c) || c == '.' || c == '@'
765 || c == '#' || c == '$' || c == '_')
768 lose ((ME, _("%s: position %d: character `\\%03o' (%c) is not valid in a "
769 "variable name."), h->fn, i, c, c));
773 /* Create variable. */
774 vv = (*var_by_index)[i] = dict_create_var (dict, name, sv.type);
776 lose ((ME, _("%s: Duplicate variable name `%s' within system file."),
779 /* Case reading data. */
780 vv->get.fv = next_value;
784 vv->get.nv = DIV_RND_UP (sv.type, sizeof (flt64));
785 long_string_count = vv->get.nv - 1;
786 next_value += vv->get.nv;
788 /* Get variable label, if any. */
789 if (sv.has_var_label == 1)
794 /* Read length of label. */
795 assertive_bufread (h, &len, sizeof len, 0);
796 if (ext->reverse_endian)
800 if (len < 0 || len > 255)
801 lose ((ME, _("%s: Variable %s indicates variable label of invalid "
802 "length %d."), h->fn, vv->name, len));
804 /* Read label into variable structure. */
805 vv->label = bufread (h, NULL, ROUND_UP (len, sizeof (int32)), len + 1);
806 if (vv->label == NULL)
808 vv->label[len] = '\0';
811 /* Set missing values. */
812 if (sv.n_missing_values != 0)
816 if (vv->width > MAX_SHORT_STRING)
817 lose ((ME, _("%s: Long string variable %s may not have missing "
818 "values."), h->fn, vv->name));
820 assertive_bufread (h, mv, sizeof *mv * abs (sv.n_missing_values), 0);
822 if (ext->reverse_endian && vv->type == NUMERIC)
823 for (j = 0; j < abs (sv.n_missing_values); j++)
824 bswap_flt64 (&mv[j]);
826 if (sv.n_missing_values > 0)
828 vv->miss_type = sv.n_missing_values;
829 if (vv->type == NUMERIC)
830 for (j = 0; j < sv.n_missing_values; j++)
831 vv->missing[j].f = mv[j];
833 for (j = 0; j < sv.n_missing_values; j++)
834 memcpy (vv->missing[j].s, &mv[j], vv->width);
840 if (vv->type == ALPHA)
841 lose ((ME, _("%s: String variable %s may not have missing "
842 "values specified as a range."), h->fn, vv->name));
844 if (mv[0] == ext->lowest)
846 vv->miss_type = MISSING_LOW;
847 vv->missing[x++].f = mv[1];
849 else if (mv[1] == ext->highest)
851 vv->miss_type = MISSING_HIGH;
852 vv->missing[x++].f = mv[0];
856 vv->miss_type = MISSING_RANGE;
857 vv->missing[x++].f = mv[0];
858 vv->missing[x++].f = mv[1];
861 if (sv.n_missing_values == -3)
864 vv->missing[x++].f = mv[2];
869 vv->miss_type = MISSING_NONE;
871 if (!parse_format_spec (h, sv.print, &vv->print, vv)
872 || !parse_format_spec (h, sv.write, &vv->write, vv))
876 /* Some consistency checks. */
877 if (long_string_count != 0)
878 lose ((ME, _("%s: Long string continuation records omitted at end of "
879 "dictionary."), h->fn));
880 if (next_value != ext->case_size)
881 lose ((ME, _("%s: System file header indicates %d variable positions but "
882 "%d were read from file."), h->fn, ext->case_size, next_value));
893 /* Translates the format spec from sysfile format to internal
896 parse_format_spec (struct file_handle *h, int32 s, struct fmt_spec *v, struct variable *vv)
898 if ((size_t) ((s >> 16) & 0xff)
899 >= sizeof translate_fmt / sizeof *translate_fmt)
900 lose ((ME, _("%s: Bad format specifier byte (%d)."),
901 h->fn, (s >> 16) & 0xff));
903 v->type = translate_fmt[(s >> 16) & 0xff];
904 v->w = (s >> 8) & 0xff;
907 /* FIXME? Should verify the resulting specifier more thoroughly. */
910 lose ((ME, _("%s: Bad format specifier byte (%d)."),
911 h->fn, (s >> 16) & 0xff));
912 if ((vv->type == ALPHA) ^ ((formats[v->type].cat & FCAT_STRING) != 0))
913 lose ((ME, _("%s: %s variable %s has %s format specifier %s."),
914 h->fn, vv->type == ALPHA ? _("String") : _("Numeric"),
916 formats[v->type].cat & FCAT_STRING ? _("string") : _("numeric"),
917 formats[v->type].name));
924 /* Reads value labels from sysfile H and inserts them into the
925 associated dictionary. */
927 read_value_labels (struct file_handle * h, struct variable ** var_by_index)
929 struct sfm_fhuser_ext *ext = h->ext; /* File extension record. */
933 unsigned char raw_value[8]; /* Value as uninterpreted bytes. */
934 union value value; /* Value. */
935 char *label; /* Null-terminated label string. */
938 struct label *labels = NULL;
939 int32 n_labels; /* Number of labels. */
941 struct variable **var = NULL; /* Associated variables. */
942 int32 n_vars; /* Number of associated variables. */
946 /* First step: read the contents of the type 3 record and record its
947 contents. Note that we can't do much with the data since we
948 don't know yet whether it is of numeric or string type. */
950 /* Read number of labels. */
951 assertive_bufread (h, &n_labels, sizeof n_labels, 0);
952 if (ext->reverse_endian)
953 bswap_int32 (&n_labels);
955 /* Allocate memory. */
956 labels = xmalloc (n_labels * sizeof *labels);
957 for (i = 0; i < n_labels; i++)
958 labels[i].label = NULL;
960 /* Read each value/label tuple into labels[]. */
961 for (i = 0; i < n_labels; i++)
963 struct label *label = labels + i;
964 unsigned char label_len;
968 assertive_bufread (h, label->raw_value, sizeof label->raw_value, 0);
970 /* Read label length. */
971 assertive_bufread (h, &label_len, sizeof label_len, 0);
972 padded_len = ROUND_UP (label_len + 1, sizeof (flt64));
974 /* Read label, padding. */
975 label->label = xmalloc (padded_len + 1);
976 assertive_bufread (h, label->label, padded_len - 1, 0);
977 label->label[label_len] = 0;
980 /* Second step: Read the type 4 record that has the list of
981 variables to which the value labels are to be applied. */
983 /* Read record type of type 4 record. */
987 assertive_bufread (h, &rec_type, sizeof rec_type, 0);
988 if (ext->reverse_endian)
989 bswap_int32 (&rec_type);
992 lose ((ME, _("%s: Variable index record (type 4) does not immediately "
993 "follow value label record (type 3) as it should."), h->fn));
996 /* Read number of variables associated with value label from type 4
998 assertive_bufread (h, &n_vars, sizeof n_vars, 0);
999 if (ext->reverse_endian)
1000 bswap_int32 (&n_vars);
1001 if (n_vars < 1 || n_vars > dict_get_var_cnt (ext->dict))
1002 lose ((ME, _("%s: Number of variables associated with a value label (%d) "
1003 "is not between 1 and the number of variables (%d)."),
1004 h->fn, n_vars, dict_get_var_cnt (ext->dict)));
1006 /* Read the list of variables. */
1007 var = xmalloc (n_vars * sizeof *var);
1008 for (i = 0; i < n_vars; i++)
1013 /* Read variable index, check range. */
1014 assertive_bufread (h, &var_index, sizeof var_index, 0);
1015 if (ext->reverse_endian)
1016 bswap_int32 (&var_index);
1017 if (var_index < 1 || var_index > ext->case_size)
1018 lose ((ME, _("%s: Variable index associated with value label (%d) is "
1019 "not between 1 and the number of values (%d)."),
1020 h->fn, var_index, ext->case_size));
1022 /* Make sure it's a real variable. */
1023 v = var_by_index[var_index - 1];
1025 lose ((ME, _("%s: Variable index associated with value label (%d) "
1026 "refers to a continuation of a string variable, not to "
1027 "an actual variable."), h->fn, var_index));
1028 if (v->type == ALPHA && v->width > MAX_SHORT_STRING)
1029 lose ((ME, _("%s: Value labels are not allowed on long string "
1030 "variables (%s)."), h->fn, v->name));
1032 /* Add it to the list of variables. */
1036 /* Type check the variables. */
1037 for (i = 1; i < n_vars; i++)
1038 if (var[i]->type != var[0]->type)
1039 lose ((ME, _("%s: Variables associated with value label are not all of "
1040 "identical type. Variable %s has %s type, but variable %s has "
1042 var[0]->name, var[0]->type == ALPHA ? _("string") : _("numeric"),
1043 var[i]->name, var[i]->type == ALPHA ? _("string") : _("numeric")));
1045 /* Fill in labels[].value, now that we know the desired type. */
1046 for (i = 0; i < n_labels; i++)
1048 struct label *label = labels + i;
1050 if (var[0]->type == ALPHA)
1052 const int copy_len = min (sizeof (label->raw_value),
1053 sizeof (label->label));
1054 memcpy (label->value.s, label->raw_value, copy_len);
1057 assert (sizeof f == sizeof label->raw_value);
1058 memcpy (&f, label->raw_value, sizeof f);
1059 if (ext->reverse_endian)
1065 /* Assign the value_label's to each variable. */
1066 for (i = 0; i < n_vars; i++)
1068 struct variable *v = var[i];
1071 /* Add each label to the variable. */
1072 for (j = 0; j < n_labels; j++)
1074 struct label *label = labels + j;
1075 if (!val_labs_replace (v->val_labs, label->value, label->label))
1078 if (var[0]->type == NUMERIC)
1079 msg (MW, _("%s: File contains duplicate label for value %g for "
1080 "variable %s."), h->fn, label->value.f, v->name);
1082 msg (MW, _("%s: File contains duplicate label for value `%.*s' "
1083 "for variable %s."),
1084 h->fn, v->width, label->value.s, v->name);
1088 for (i = 0; i < n_labels; i++)
1089 free (labels[i].label);
1097 for (i = 0; i < n_labels; i++)
1098 free (labels[i].label);
1105 /* Reads NBYTES bytes from the file represented by H. If BUF is
1106 non-NULL, uses that as the buffer; otherwise allocates at least
1107 MINALLOC bytes. Returns a pointer to the buffer on success, NULL
1110 bufread (struct file_handle * h, void *buf, size_t nbytes, size_t minalloc)
1112 struct sfm_fhuser_ext *ext = h->ext;
1115 buf = xmalloc (max (nbytes, minalloc));
1116 if (1 != fread (buf, nbytes, 1, ext->file))
1118 if (ferror (ext->file))
1119 msg (ME, _("%s: Reading system file: %s."), h->fn, strerror (errno));
1121 corrupt_msg (ME, _("%s: Unexpected end of file."), h->fn);
1127 /* Reads a document record, type 6, from system file H, and sets up
1128 the documents and n_documents fields in the associated
1131 read_documents (struct file_handle * h)
1133 struct sfm_fhuser_ext *ext = h->ext;
1134 struct dictionary *dict = ext->dict;
1138 if (dict_get_documents (dict) != NULL)
1139 lose ((ME, _("%s: System file contains multiple type 6 (document) records."),
1142 assertive_bufread (h, &n_lines, sizeof n_lines, 0);
1144 lose ((ME, _("%s: Number of document lines (%ld) must be greater than 0."),
1145 h->fn, (long) n_lines));
1147 documents = bufread (h, NULL, 80 * n_lines, n_lines * 80 + 1);
1148 /* FIXME? Run through asciify. */
1149 if (documents == NULL)
1151 documents[80 * n_lines] = '\0';
1152 dict_set_documents (dict, documents);
1160 #if GLOBAL_DEBUGGING
1161 #include "debug-print.h"
1162 /* Displays dictionary DICT on stdout. */
1164 dump_dictionary (struct dictionary * dict)
1168 debug_printf ((_("dictionary:\n")));
1169 for (i = 0; i < dict->nvar; i++)
1172 struct variable *v = dict->var[i];
1175 debug_printf ((" var %s", v->name));
1176 debug_printf (("(type:%s,%d)", (v->type == NUMERIC ? _("num")
1177 : (v->type == ALPHA ? _("str") : "!!!")),
1179 debug_printf (("(fv:%d,%d)", v->fv, v->nv));
1180 debug_printf (("(left:%s)(miss:", v->left ? _("left") : _("right")));
1182 switch (v->miss_type)
1186 debug_printf ((_("none")));
1190 debug_printf ((_("one")));
1194 debug_printf ((_("two")));
1198 debug_printf ((_("three")));
1202 debug_printf ((_("range")));
1206 debug_printf ((_("low")));
1210 debug_printf ((_("high")));
1212 case MISSING_RANGE_1:
1214 debug_printf ((_("range+1")));
1218 debug_printf ((_("low+1")));
1220 case MISSING_HIGH_1:
1222 debug_printf ((_("high+1")));
1227 for (j = 0; j < n; j++)
1228 if (v->type == NUMERIC)
1229 debug_printf ((",%g", v->missing[j].f));
1231 debug_printf ((",\"%.*s\"", v->width, v->missing[j].s));
1232 strcpy (print, fmt_to_string (&v->print));
1233 debug_printf ((")(fmt:%s,%s)(lbl:%s)\n",
1234 print, fmt_to_string (&v->write),
1235 v->label ? v->label : "nolabel"));
1242 /* Reads compressed data into H->BUF and sets other pointers
1243 appropriately. Returns nonzero only if both no errors occur and
1246 buffer_input (struct file_handle * h)
1248 struct sfm_fhuser_ext *ext = h->ext;
1251 if (ext->buf == NULL)
1252 ext->buf = xmalloc (sizeof *ext->buf * 128);
1253 amt = fread (ext->buf, sizeof *ext->buf, 128, ext->file);
1254 if (ferror (ext->file))
1256 msg (ME, _("%s: Error reading file: %s."), h->fn, strerror (errno));
1259 ext->ptr = ext->buf;
1260 ext->end = &ext->buf[amt];
1264 /* Reads a single case consisting of compressed data from system file
1265 H into the array TEMP[] according to dictionary DICT, and returns
1266 nonzero only if successful. */
1267 /* Data in system files is compressed in the following manner:
1268 data values are grouped into sets of eight; each of the eight has
1269 one instruction byte, which are output together in an octet; each
1270 byte gives a value for that byte or indicates that the value can be
1271 found following the instructions. */
1273 read_compressed_data (struct file_handle * h, flt64 * temp)
1275 struct sfm_fhuser_ext *ext = h->ext;
1277 const unsigned char *p_end = ext->x + sizeof (flt64);
1278 unsigned char *p = ext->y;
1280 const flt64 *temp_beg = temp;
1281 const flt64 *temp_end = &temp[ext->case_size];
1285 for (; p < p_end; p++)
1289 /* Code 0 is ignored. */
1292 /* Code 252 is end of file. */
1293 if (temp_beg != temp)
1294 lose ((ME, _("%s: Compressed data is corrupted. Data ends "
1295 "partway through a case."), h->fn));
1298 /* Code 253 indicates that the value is stored explicitly
1299 following the instruction bytes. */
1300 if (ext->ptr == NULL || ext->ptr >= ext->end)
1301 if (!buffer_input (h))
1303 lose ((ME, _("%s: Unexpected end of file."), h->fn));
1306 memcpy (temp++, ext->ptr++, sizeof *temp);
1307 if (temp >= temp_end)
1311 /* Code 254 indicates a string that is all blanks. */
1312 memset (temp++, ' ', sizeof *temp);
1313 if (temp >= temp_end)
1317 /* Code 255 indicates the system-missing value. */
1318 *temp = ext->sysmis;
1319 if (ext->reverse_endian)
1322 if (temp >= temp_end)
1326 /* Codes 1 through 251 inclusive are taken to indicate a
1327 value of (BYTE - BIAS), where BYTE is the byte's value
1328 and BIAS is the compression bias (generally 100.0). */
1329 *temp = *p - ext->bias;
1330 if (ext->reverse_endian)
1333 if (temp >= temp_end)
1338 /* We have reached the end of this instruction octet. Read
1340 if (ext->ptr == NULL || ext->ptr >= ext->end)
1341 if (!buffer_input (h))
1343 if (temp_beg != temp)
1344 lose ((ME, _("%s: Unexpected end of file."), h->fn));
1347 memcpy (ext->x, ext->ptr++, sizeof *temp);
1355 /* We have filled up an entire record. Update state and return
1361 /* We have been unsuccessful at filling a record, either through i/o
1362 error or through an end-of-file indication. Update state and
1363 return unsuccessfully. */
1367 /* Reads one case from system file H into the value array PERM
1368 according to the instructions given in associated dictionary DICT,
1369 which must have the get.* elements appropriately set. Returns
1370 nonzero only if successful. */
1372 sfm_read_case (struct file_handle * h, union value * perm, struct dictionary * dict)
1374 struct sfm_fhuser_ext *ext = h->ext;
1381 /* The first concern is to obtain a full case relative to the data
1382 file. (Cases in the data file have no particular relationship to
1383 cases in the active file.) */
1384 nbytes = sizeof *temp * ext->case_size;
1385 temp = local_alloc (nbytes);
1387 if (ext->compressed == 0)
1389 size_t amt = fread (temp, 1, nbytes, ext->file);
1393 if (ferror (ext->file))
1394 msg (ME, _("%s: Reading system file: %s."), h->fn, strerror (errno));
1396 msg (ME, _("%s: Partial record at end of system file."), h->fn);
1400 else if (!read_compressed_data (h, temp))
1403 /* Translate a case in data file format to a case in active file
1405 for (i = 0; i < dict_get_var_cnt (dict); i++)
1407 struct variable *v = dict_get_var (dict, i);
1409 if (v->get.fv == -1)
1412 if (v->type == NUMERIC)
1414 flt64 src = temp[v->get.fv];
1415 if (ext->reverse_endian)
1417 perm[v->fv].f = src == ext->sysmis ? SYSMIS : src;
1420 memcpy (&perm[v->fv].s, &temp[v->get.fv], v->width);
1431 static struct fh_ext_class sfm_r_class =
1434 N_("reading as a system file"),