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
20 /* AIX requires this to be the first thing in the file. */
23 #define alloca __builtin_alloca
31 #ifndef alloca /* predefined by HP cc +Olibcalls */
46 #include "file-handle.h"
57 #include "debug-print.h"
59 /* PORTME: This file may require substantial revision for those
60 systems that don't meet the typical 32-bit integer/64-bit double
61 model. It's kinda hard to tell without having one of them on my
64 /* sfm's file_handle extension. */
67 FILE *file; /* Actual file. */
68 int opened; /* Reference count. */
70 struct dictionary *dict; /* File's dictionary. */
72 int reverse_endian; /* 1=file has endianness opposite us. */
73 int case_size; /* Number of `values's per case. */
74 long ncases; /* Number of cases, -1 if unknown. */
75 int compressed; /* 1=compressed, 0=not compressed. */
76 double bias; /* Compression bias, usually 100.0. */
77 int weight_index; /* 0-based index of weighting variable, or -1. */
79 /* File's special constants. */
84 /* Uncompression buffer. */
85 flt64 *buf; /* Buffer data. */
86 flt64 *ptr; /* Current location in buffer. */
87 flt64 *end; /* End of buffer data. */
89 /* Compression instruction octet. */
90 unsigned char x[sizeof (flt64)];
91 /* Current instruction octet. */
92 unsigned char *y; /* Location in current instruction octet. */
95 static struct fh_ext_class sfm_r_class;
98 void dump_dictionary (struct dictionary * dict);
103 /* bswap_int32(): Reverse the byte order of 32-bit integer *X. */
105 #include <asm/byteorder.h>
106 #include <netinet/in.h>
108 bswap_int32 (int32 * x)
112 #else /* not Linux */
114 bswap_int32 (int32 * x)
116 unsigned char *y = (char *) x;
125 #endif /* not Linux */
127 /* Reverse the byte order of 64-bit floating point *X. */
129 bswap_flt64 (flt64 * x)
131 /* Note that under compilers of any quality, half of this function
132 should optimize out as dead code. */
133 unsigned char *y = (char *) x;
135 if (sizeof (flt64) == 8)
156 for (x = 0; x < sizeof (flt64) / 2; x++)
159 y[x] = y[sizeof (flt64) - x];
160 y[sizeof (flt64) - x] = t;
166 corrupt_msg (int class, const char *format,...)
167 __attribute__ ((format (printf, 2, 3)));
169 /* Displays a corrupt sysfile error. */
171 corrupt_msg (int class, const char *format,...)
178 va_start (args, format);
179 vsnprintf (buf, 1024, format, args);
187 getl_location (&e.where.filename, &e.where.line_number);
188 e.title = _("corrupt system file: ");
195 /* Closes a system file after we're done with it. */
197 sfm_close (struct file_handle * h)
199 struct sfm_fhuser_ext *ext = h->ext;
202 assert (ext->opened == 0);
203 if (EOF == fn_close (h->fn, ext->file))
204 msg (ME, _("%s: Closing system file: %s."), h->fn, strerror (errno));
209 /* Closes a system file if we're done with it. */
211 sfm_maybe_close (struct file_handle *h)
213 struct sfm_fhuser_ext *ext = h->ext;
215 if (ext->opened == 1)
221 /* Dictionary reader. */
223 static void *bufread (struct file_handle * handle, void *buf, size_t nbytes,
226 static int read_header (struct file_handle * h, struct sfm_read_info * inf);
227 static int parse_format_spec (struct file_handle * h, int32 s,
228 struct fmt_spec * v, struct variable *vv);
229 static int read_value_labels (struct file_handle * h, struct variable ** var_by_index);
230 static int read_variables (struct file_handle * h, struct variable *** var_by_index);
231 static int read_machine_int32_info (struct file_handle * h, int size, int count);
232 static int read_machine_flt64_info (struct file_handle * h, int size, int count);
233 static int read_documents (struct file_handle * h);
235 /* Displays the message X with corrupt_msg, then jumps to the lossage
245 /* Calls bufread with the specified arguments, and jumps to lossage if
247 #define assertive_bufread(a,b,c,d) \
250 if (!bufread (a,b,c,d)) \
255 /* Reads the dictionary from file with handle H, and returns it in a
256 dictionary structure. This dictionary may be modified in order to
257 rename, reorder, and delete variables, etc. */
259 sfm_read_dictionary (struct file_handle * h, struct sfm_read_info * inf)
261 /* The file handle extension record. */
262 struct sfm_fhuser_ext *ext;
264 /* Allows for quick reference to variables according to indexes
265 relative to position within a case. */
266 struct variable **var_by_index = NULL;
268 /* Check whether the file is already open. */
269 if (h->class == &sfm_r_class)
275 else if (h->class != NULL)
277 msg (ME, _("Cannot read file %s as system file: already opened for %s."),
278 fh_handle_name (h), h->class->name);
282 msg (VM (1), _("%s: Opening system-file handle %s for reading."),
283 fh_handle_filename (h), fh_handle_name (h));
285 /* Open the physical disk file. */
286 ext = xmalloc (sizeof (struct sfm_fhuser_ext));
287 ext->file = fn_open (h->norm_fn, "rb");
288 if (ext->file == NULL)
290 msg (ME, _("An error occurred while opening \"%s\" for reading "
291 "as a system file: %s."), h->fn, strerror (errno));
297 /* Initialize the sfm_fhuser_ext structure. */
298 h->class = &sfm_r_class;
301 ext->buf = ext->ptr = ext->end = NULL;
302 ext->y = ext->x + sizeof ext->x;
305 /* Default special constants. */
306 ext->sysmis = -FLT64_MAX;
307 ext->highest = FLT64_MAX;
308 ext->lowest = second_lowest_flt64;
310 /* Read the header. */
311 if (!read_header (h, inf))
314 /* Read about the variables. */
315 if (!read_variables (h, &var_by_index))
318 /* Handle weighting. */
319 if (ext->weight_index != -1)
321 struct variable *wv = var_by_index[ext->weight_index];
324 lose ((ME, _("%s: Weighting variable may not be a continuation of "
325 "a long string variable."), h->fn));
326 else if (wv->type == ALPHA)
327 lose ((ME, _("%s: Weighting variable may not be a string variable."),
330 strcpy (ext->dict->weight_var, wv->name);
333 ext->dict->weight_var[0] = 0;
335 /* Read records of types 3, 4, 6, and 7. */
340 assertive_bufread (h, &rec_type, sizeof rec_type, 0);
341 if (ext->reverse_endian)
342 bswap_int32 (&rec_type);
347 if (!read_value_labels (h, var_by_index))
352 lose ((ME, _("%s: Orphaned variable index record (type 4). Type 4 "
353 "records must always immediately follow type 3 records."),
357 if (!read_documents (h))
373 assertive_bufread (h, &data, sizeof data, 0);
374 if (ext->reverse_endian)
376 bswap_int32 (&data.subtype);
377 bswap_int32 (&data.size);
378 bswap_int32 (&data.count);
381 /*if(data.size != sizeof(int32) && data.size != sizeof(flt64))
382 lose((ME, "%s: Element size in record type 7, subtype %d, is "
383 "not either the size of IN (%d) or OBS (%d); actual value "
385 h->fn, data.subtype, sizeof(int32), sizeof(flt64),
388 switch (data.subtype)
391 if (!read_machine_int32_info (h, data.size, data.count))
396 if (!read_machine_flt64_info (h, data.size, data.count))
402 case 11: /* ?? Used by SPSS 8.0. */
407 msg (MW, _("%s: Unrecognized record type 7, subtype %d "
408 "encountered in system file."), h->fn, data.subtype);
414 void *x = bufread (h, NULL, data.size * data.count, 0);
426 assertive_bufread (h, &filler, sizeof filler, 0);
427 goto break_out_of_loop;
431 lose ((ME, _("%s: Unrecognized record type %d."), h->fn, rec_type));
436 /* Come here on successful completion. */
437 msg (VM (2), _("Read system-file dictionary successfully."));
440 dump_dictionary (ext->dict);
446 /* Come here on unsuccessful completion. */
447 msg (VM (1), _("Error reading system-file header."));
450 fn_close (h->fn, ext->file);
451 if (ext && ext->dict)
452 free_dictionary (ext->dict);
459 /* Read record type 7, subtype 3. */
461 read_machine_int32_info (struct file_handle * h, int size, int count)
463 struct sfm_fhuser_ext *ext = h->ext;
470 if (size != sizeof (int32) || count != 8)
471 lose ((ME, _("%s: Bad size (%d) or count (%d) field on record type 7, "
472 "subtype 3. Expected size %d, count 8."),
473 h->fn, size, count, sizeof (int32)));
475 assertive_bufread (h, data, sizeof data, 0);
476 if (ext->reverse_endian)
477 for (i = 0; i < 8; i++)
478 bswap_int32 (&data[i]);
480 /* PORTME: Check floating-point representation. */
483 lose ((ME, _("%s: Floating-point representation in system file is not "
484 "IEEE-754. PSPP cannot convert between floating-point "
485 "formats."), h->fn));
488 /* PORTME: Check recorded file endianness against intuited file
490 #ifdef WORDS_BIGENDIAN
495 if (ext->reverse_endian)
497 if (file_bigendian ^ (data[6] == 1))
498 lose ((ME, _("%s: File-indicated endianness (%s) does not match endianness "
499 "intuited from file header (%s)."),
500 h->fn, file_bigendian ? _("big-endian") : _("little-endian"),
501 data[6] == 1 ? _("big-endian") : (data[6] == 2 ? _("little-endian")
504 /* PORTME: Character representation code. */
505 if (data[7] != 2 && data[7] != 3)
506 lose ((ME, _("%s: File-indicated character representation code (%s) is not "
508 data[7] == 1 ? "EBCDIC" : (data[7] == 4 ? _("DEC Kanji") : _("Unknown"))));
516 /* Read record type 7, subtype 4. */
518 read_machine_flt64_info (struct file_handle * h, int size, int count)
520 struct sfm_fhuser_ext *ext = h->ext;
526 if (size != sizeof (flt64) || count != 3)
527 lose ((ME, _("%s: Bad size (%d) or count (%d) field on record type 7, "
528 "subtype 4. Expected size %d, count 8."),
529 h->fn, size, count, sizeof (flt64)));
531 assertive_bufread (h, data, sizeof data, 0);
532 if (ext->reverse_endian)
533 for (i = 0; i < 3; i++)
534 bswap_flt64 (&data[i]);
536 if (data[0] != SYSMIS || data[1] != FLT64_MAX
537 || data[2] != second_lowest_flt64)
539 ext->sysmis = data[0];
540 ext->highest = data[1];
541 ext->lowest = data[2];
542 msg (MW, _("%s: File-indicated value is different from internal value "
543 "for at least one of the three system values. SYSMIS: "
544 "indicated %g, expected %g; HIGHEST: %g, %g; LOWEST: "
546 h->fn, (double) data[0], (double) SYSMIS,
547 (double) data[1], (double) FLT64_MAX,
548 (double) data[2], (double) second_lowest_flt64);
558 read_header (struct file_handle * h, struct sfm_read_info * inf)
560 struct sfm_fhuser_ext *ext = h->ext; /* File extension strcut. */
561 struct sysfile_header hdr; /* Disk buffer. */
562 struct dictionary *dict; /* File dictionary. */
563 char prod_name[sizeof hdr.prod_name + 1]; /* Buffer for product name. */
564 int skip_amt; /* Amount of product name to omit. */
567 /* Create the dictionary. */
568 dict = ext->dict = xmalloc (sizeof *dict);
570 dict->var_by_name = NULL;
573 dict->nval = -1; /* Unknown. */
576 dict->weight_var[0] = 0;
577 dict->weight_index = -1;
578 dict->filter_var[0] = 0;
580 dict->n_documents = 0;
581 dict->documents = NULL;
583 /* Read header, check magic. */
584 assertive_bufread (h, &hdr, sizeof hdr, 0);
585 if (0 != strncmp ("$FL2", hdr.rec_type, 4))
586 lose ((ME, _("%s: Bad magic. Proper system files begin with "
587 "the four characters `$FL2'. This file will not be read."),
590 /* Check eye-catcher string. */
591 memcpy (prod_name, hdr.prod_name, sizeof hdr.prod_name);
592 for (i = 0; i < 60; i++)
593 if (!isprint ((unsigned char) prod_name[i]))
595 for (i = 59; i >= 0; i--)
596 if (!isgraph ((unsigned char) prod_name[i]))
601 prod_name[60] = '\0';
605 static const char *prefix[N_PREFIXES] =
607 "@(#) SPSS DATA FILE",
613 for (i = 0; i < N_PREFIXES; i++)
614 if (!strncmp (prefix[i], hdr.prod_name, strlen (prefix[i])))
616 skip_amt = strlen (prefix[i]);
621 /* Check endianness. */
622 /* PORTME: endianness. */
623 if (hdr.layout_code == 2)
624 ext->reverse_endian = 0;
627 bswap_int32 (&hdr.layout_code);
628 if (hdr.layout_code != 2)
629 lose ((ME, _("%s: File layout code has unexpected value %d. Value "
630 "should be 2, in big-endian or little-endian format."),
631 h->fn, hdr.layout_code));
633 ext->reverse_endian = 1;
634 bswap_int32 (&hdr.case_size);
635 bswap_int32 (&hdr.compressed);
636 bswap_int32 (&hdr.weight_index);
637 bswap_int32 (&hdr.ncases);
638 bswap_flt64 (&hdr.bias);
641 /* Copy basic info and verify correctness. */
642 ext->case_size = hdr.case_size;
643 if (hdr.case_size <= 0 || ext->case_size > (INT_MAX
644 / (int) sizeof (union value) / 2))
645 lose ((ME, _("%s: Number of elements per case (%d) is not between 1 "
646 "and %d."), h->fn, hdr.case_size, INT_MAX / sizeof (union value) / 2));
648 ext->compressed = hdr.compressed;
650 ext->weight_index = hdr.weight_index - 1;
651 if (hdr.weight_index < 0 || hdr.weight_index > hdr.case_size)
652 lose ((ME, _("%s: Index of weighting variable (%d) is not between 0 "
653 "and number of elements per case (%d)."),
654 h->fn, hdr.weight_index, ext->case_size));
656 ext->ncases = hdr.ncases;
657 if (ext->ncases < -1 || ext->ncases > INT_MAX / 2)
658 lose ((ME, _("%s: Number of cases in file (%ld) is not between -1 and "
659 "%d."), h->fn, (long) ext->ncases, INT_MAX / 2));
661 ext->bias = hdr.bias;
662 if (ext->bias != 100.0)
663 corrupt_msg (MW, _("%s: Compression bias (%g) is not the usual "
664 "value of 100."), h->fn, ext->bias);
666 /* Make a file label only on the condition that the given label is
667 not all spaces or nulls. */
672 for (i = sizeof hdr.file_label - 1; i >= 0; i--)
673 if (!isspace ((unsigned char) hdr.file_label[i])
674 && hdr.file_label[i] != 0)
676 dict->label = xmalloc (i + 2);
677 memcpy (dict->label, hdr.file_label, i + 1);
678 dict->label[i + 1] = 0;
687 memcpy (inf->creation_date, hdr.creation_date, 9);
688 inf->creation_date[9] = 0;
690 memcpy (inf->creation_time, hdr.creation_time, 8);
691 inf->creation_time[8] = 0;
693 #ifdef WORDS_BIGENDIAN
694 inf->bigendian = !ext->reverse_endian;
696 inf->bigendian = ext->reverse_endian;
699 inf->compressed = hdr.compressed;
701 inf->ncases = hdr.ncases;
703 for (cp = &prod_name[skip_amt]; cp < &prod_name[60]; cp++)
704 if (isgraph ((unsigned char) *cp))
706 strcpy (inf->product, cp);
715 /* Reads most of the dictionary from file H; also fills in the
716 associated VAR_BY_INDEX array.
718 Note: the dictionary returned by this function has an invalid NVAL
719 element, also the VAR[] array does not have the FV and LV elements
720 set, however the NV elements *are* set. This is because the caller
721 will probably modify the dictionary before reading it in from the
722 file. Also, the get.* elements are set to appropriate values to
723 allow the file to be read. */
725 read_variables (struct file_handle * h, struct variable *** var_by_index)
729 struct sfm_fhuser_ext *ext = h->ext; /* File extension record. */
730 struct dictionary *dict = ext->dict; /* Dictionary being constructed. */
731 struct sysfile_variable sv; /* Disk buffer. */
732 int long_string_count = 0; /* # of long string continuation
733 records still expected. */
734 int next_value = 0; /* Index to next `value' structure. */
736 /* Allocate variables. */
737 dict->var = xmalloc (sizeof *dict->var * ext->case_size);
738 *var_by_index = xmalloc (sizeof **var_by_index * ext->case_size);
740 /* Read in the entry for each variable and use the info to
741 initialize the dictionary. */
742 for (i = 0; i < ext->case_size; i++)
747 assertive_bufread (h, &sv, sizeof sv, 0);
749 if (ext->reverse_endian)
751 bswap_int32 (&sv.rec_type);
752 bswap_int32 (&sv.type);
753 bswap_int32 (&sv.has_var_label);
754 bswap_int32 (&sv.n_missing_values);
755 bswap_int32 (&sv.print);
756 bswap_int32 (&sv.write);
759 if (sv.rec_type != 2)
760 lose ((ME, _("%s: position %d: Bad record type (%d); "
761 "the expected value was 2."), h->fn, i, sv.rec_type));
763 /* If there was a long string previously, make sure that the
764 continuations are present; otherwise make sure there aren't
766 if (long_string_count)
769 lose ((ME, _("%s: position %d: String variable does not have "
770 "proper number of continuation records."), h->fn, i));
772 (*var_by_index)[i] = NULL;
776 else if (sv.type == -1)
777 lose ((ME, _("%s: position %d: Superfluous long string continuation "
778 "record."), h->fn, i));
780 /* Check fields for validity. */
781 if (sv.type < 0 || sv.type > 255)
782 lose ((ME, _("%s: position %d: Bad variable type code %d."),
784 if (sv.has_var_label != 0 && sv.has_var_label != 1)
785 lose ((ME, _("%s: position %d: Variable label indicator field is not "
786 "0 or 1."), h->fn, i));
787 if (sv.n_missing_values < -3 || sv.n_missing_values > 3
788 || sv.n_missing_values == -1)
789 lose ((ME, _("%s: position %d: Missing value indicator field is not "
790 "-3, -2, 0, 1, 2, or 3."), h->fn, i));
792 /* Construct internal variable structure, initialize critical bits. */
793 vv = (*var_by_index)[i] = dict->var[dict->nvar++] = xmalloc (sizeof *vv);
794 vv->index = dict->nvar - 1;
799 /* Copy first character of variable name. */
800 if (!isalpha ((unsigned char) sv.name[0])
801 && sv.name[0] != '@' && sv.name[0] != '#')
802 lose ((ME, _("%s: position %d: Variable name begins with invalid "
803 "character."), h->fn, i));
804 if (islower ((unsigned char) sv.name[0]))
805 msg (MW, _("%s: position %d: Variable name begins with lowercase letter "
806 "%c."), h->fn, i, sv.name[0]);
807 if (sv.name[0] == '#')
808 msg (MW, _("%s: position %d: Variable name begins with octothorpe "
809 "(`#'). Scratch variables should not appear in system "
810 "files."), h->fn, i);
811 vv->name[0] = toupper ((unsigned char) (sv.name[0]));
813 /* Copy remaining characters of variable name. */
814 for (j = 1; j < 8; j++)
816 int c = (unsigned char) sv.name[j];
820 else if (islower (c))
822 msg (MW, _("%s: position %d: Variable name character %d is "
823 "lowercase letter %c."), h->fn, i, j + 1, sv.name[j]);
824 vv->name[j] = toupper ((unsigned char) (c));
826 else if (isalnum (c) || c == '.' || c == '@'
827 || c == '#' || c == '$' || c == '_')
830 lose ((ME, _("%s: position %d: character `\\%03o' (%c) is not valid in a "
831 "variable name."), h->fn, i, c, c));
835 /* Set type, width, and `left' fields and allocate `value'
842 vv->get.fv = next_value++;
849 vv->nv = DIV_RND_UP (vv->width, MAX_SHORT_STRING);
850 vv->get.nv = DIV_RND_UP (vv->width, sizeof (flt64));
851 vv->get.fv = next_value;
852 next_value += vv->get.nv;
853 long_string_count = vv->get.nv - 1;
855 vv->left = (vv->name[0] == '#');
857 /* Get variable label, if any. */
858 if (sv.has_var_label == 1)
863 /* Read length of label. */
864 assertive_bufread (h, &len, sizeof len, 0);
865 if (ext->reverse_endian)
869 if (len < 0 || len > 255)
870 lose ((ME, _("%s: Variable %s indicates variable label of invalid "
871 "length %d."), h->fn, vv->name, len));
873 /* Read label into variable structure. */
874 vv->label = bufread (h, NULL, ROUND_UP (len, sizeof (int32)), len + 1);
875 if (vv->label == NULL)
877 vv->label[len] = '\0';
880 /* Set missing values. */
881 if (sv.n_missing_values != 0)
885 if (vv->width > MAX_SHORT_STRING)
886 lose ((ME, _("%s: Long string variable %s may not have missing "
887 "values."), h->fn, vv->name));
889 assertive_bufread (h, mv, sizeof *mv * abs (sv.n_missing_values), 0);
891 if (ext->reverse_endian && vv->type == NUMERIC)
892 for (j = 0; j < abs (sv.n_missing_values); j++)
893 bswap_flt64 (&mv[j]);
895 if (sv.n_missing_values > 0)
897 vv->miss_type = sv.n_missing_values;
898 if (vv->type == NUMERIC)
899 for (j = 0; j < sv.n_missing_values; j++)
900 vv->missing[j].f = mv[j];
902 for (j = 0; j < sv.n_missing_values; j++)
903 memcpy (vv->missing[j].s, &mv[j], vv->width);
909 if (vv->type == ALPHA)
910 lose ((ME, _("%s: String variable %s may not have missing "
911 "values specified as a range."), h->fn, vv->name));
913 if (mv[0] == ext->lowest)
915 vv->miss_type = MISSING_LOW;
916 vv->missing[x++].f = mv[1];
918 else if (mv[1] == ext->highest)
920 vv->miss_type = MISSING_HIGH;
921 vv->missing[x++].f = mv[0];
925 vv->miss_type = MISSING_RANGE;
926 vv->missing[x++].f = mv[0];
927 vv->missing[x++].f = mv[1];
930 if (sv.n_missing_values == -3)
933 vv->missing[x++].f = mv[2];
938 vv->miss_type = MISSING_NONE;
940 if (!parse_format_spec (h, sv.print, &vv->print, vv)
941 || !parse_format_spec (h, sv.write, &vv->write, vv))
945 /* Some consistency checks. */
946 if (long_string_count != 0)
947 lose ((ME, _("%s: Long string continuation records omitted at end of "
948 "dictionary."), h->fn));
949 if (next_value != ext->case_size)
950 lose ((ME, _("%s: System file header indicates %d variable positions but "
951 "%d were read from file."), h->fn, ext->case_size, next_value));
952 dict->var = xrealloc (dict->var, sizeof *dict->var * dict->nvar);
954 /* Construct AVL tree of dictionary in order to speed up later
955 processing and to check for duplicate varnames. */
956 dict->var_by_name = avl_create (NULL, cmp_variable, NULL);
957 for (i = 0; i < dict->nvar; i++)
958 if (NULL != avl_insert (dict->var_by_name, dict->var[i]))
959 lose ((ME, _("%s: Duplicate variable name `%s' within system file."),
960 h->fn, dict->var[i]->name));
965 for (i = 0; i < dict->nvar; i++)
967 free (dict->var[i]->label);
971 if (dict->var_by_name)
972 avl_destroy (dict->var_by_name, NULL);
979 /* Translates the format spec from sysfile format to internal
982 parse_format_spec (struct file_handle *h, int32 s, struct fmt_spec *v, struct variable *vv)
984 if ((size_t) ((s >> 16) & 0xff)
985 >= sizeof translate_fmt / sizeof *translate_fmt)
986 lose ((ME, _("%s: Bad format specifier byte (%d)."),
987 h->fn, (s >> 16) & 0xff));
989 v->type = translate_fmt[(s >> 16) & 0xff];
990 v->w = (s >> 8) & 0xff;
993 /* FIXME? Should verify the resulting specifier more thoroughly. */
996 lose ((ME, _("%s: Bad format specifier byte (%d)."),
997 h->fn, (s >> 16) & 0xff));
998 if ((vv->type == ALPHA) ^ ((formats[v->type].cat & FCAT_STRING) != 0))
999 lose ((ME, _("%s: %s variable %s has %s format specifier %s."),
1000 h->fn, vv->type == ALPHA ? _("String") : _("Numeric"),
1002 formats[v->type].cat & FCAT_STRING ? _("string") : _("numeric"),
1003 formats[v->type].name));
1010 /* Reads value labels from sysfile H and inserts them into the
1011 associated dictionary. */
1013 read_value_labels (struct file_handle * h, struct variable ** var_by_index)
1015 struct sfm_fhuser_ext *ext = h->ext; /* File extension record. */
1017 flt64 *raw_label = NULL; /* Array of raw label values. */
1018 struct value_label **cooked_label = NULL; /* Array of cooked labels. */
1019 int32 n_labels; /* Number of labels. */
1021 struct variable **var = NULL; /* Associated variables. */
1022 int32 n_vars; /* Number of associated variables. */
1026 /* First step: read the contents of the type 3 record and record its
1027 contents. Note that we can't do much with the data since we
1028 don't know yet whether it is of numeric or string type. */
1030 /* Read number of labels. */
1031 assertive_bufread (h, &n_labels, sizeof n_labels, 0);
1032 if (ext->reverse_endian)
1033 bswap_int32 (&n_labels);
1035 /* Allocate memory. */
1036 raw_label = xmalloc (sizeof *raw_label * n_labels);
1037 cooked_label = xmalloc (sizeof *cooked_label * n_labels);
1038 for (i = 0; i < n_labels; i++)
1039 cooked_label[i] = NULL;
1041 /* Read each value/label tuple. */
1042 for (i = 0; i < n_labels; i++)
1045 unsigned char label_len;
1049 /* Read value, label length. */
1050 assertive_bufread (h, &value, sizeof value, 0);
1051 assertive_bufread (h, &label_len, 1, 0);
1052 memcpy (&raw_label[i], &value, sizeof value);
1055 cooked_label[i] = xmalloc (sizeof **cooked_label);
1056 cooked_label[i]->s = xmalloc (label_len + 1);
1057 assertive_bufread (h, cooked_label[i]->s, label_len, 0);
1058 cooked_label[i]->s[label_len] = 0;
1061 rem = REM_RND_UP (label_len + 1, sizeof (flt64));
1063 assertive_bufread (h, &value, rem, 0);
1066 /* Second step: Read the type 4 record that has the list of
1067 variables to which the value labels are to be applied. */
1069 /* Read record type of type 4 record. */
1073 assertive_bufread (h, &rec_type, sizeof rec_type, 0);
1074 if (ext->reverse_endian)
1075 bswap_int32 (&rec_type);
1078 lose ((ME, _("%s: Variable index record (type 4) does not immediately "
1079 "follow value label record (type 3) as it ought."), h->fn));
1082 /* Read number of variables associated with value label from type 4
1084 assertive_bufread (h, &n_vars, sizeof n_vars, 0);
1085 if (ext->reverse_endian)
1086 bswap_int32 (&n_vars);
1087 if (n_vars < 1 || n_vars > ext->dict->nvar)
1088 lose ((ME, _("%s: Number of variables associated with a value label (%d) "
1089 "is not between 1 and the number of variables (%d)."),
1090 h->fn, n_vars, ext->dict->nvar));
1092 /* Allocate storage. */
1093 var = xmalloc (sizeof *var * n_vars);
1095 /* Read the list of variables. */
1096 for (i = 0; i < n_vars; i++)
1101 /* Read variable index, check range. */
1102 assertive_bufread (h, &var_index, sizeof var_index, 0);
1103 if (ext->reverse_endian)
1104 bswap_int32 (&var_index);
1105 if (var_index < 1 || var_index > ext->case_size)
1106 lose ((ME, _("%s: Variable index associated with value label (%d) is "
1107 "not between 1 and the number of values (%d)."),
1108 h->fn, var_index, ext->case_size));
1110 /* Make sure it's a real variable. */
1111 v = var_by_index[var_index - 1];
1113 lose ((ME, _("%s: Variable index associated with value label (%d) refers "
1114 "to a continuation of a string variable, not to an actual "
1115 "variable."), h->fn, var_index));
1116 if (v->type == ALPHA && v->width > MAX_SHORT_STRING)
1117 lose ((ME, _("%s: Value labels are not allowed on long string variables "
1118 "(%s)."), h->fn, v->name));
1120 /* Add it to the list of variables. */
1124 /* Type check the variables. */
1125 for (i = 1; i < n_vars; i++)
1126 if (var[i]->type != var[0]->type)
1127 lose ((ME, _("%s: Variables associated with value label are not all of "
1128 "identical type. Variable %s has %s type, but variable %s has "
1130 var[0]->name, var[0]->type == ALPHA ? _("string") : _("numeric"),
1131 var[i]->name, var[i]->type == ALPHA ? _("string") : _("numeric")));
1133 /* Create a value_label for each value/label tuple, now that we know
1134 the desired type. */
1135 for (i = 0; i < n_labels; i++)
1137 if (var[0]->type == ALPHA)
1139 const int copy_len = min (sizeof (flt64), MAX_SHORT_STRING);
1140 memcpy (cooked_label[i]->v.s, (char *) &raw_label[i], copy_len);
1141 if (MAX_SHORT_STRING > copy_len)
1142 memset (&cooked_label[i]->v.s[copy_len], ' ',
1143 MAX_SHORT_STRING - copy_len);
1145 cooked_label[i]->v.f = raw_label[i];
1146 if (ext->reverse_endian)
1147 bswap_flt64 (&cooked_label[i]->v.f);
1149 cooked_label[i]->ref_count = n_vars;
1152 /* Assign the value_label's to each variable. */
1153 for (i = 0; i < n_vars; i++)
1155 struct variable *v = var[i];
1158 /* Create AVL tree if necessary. */
1160 v->val_lab = avl_create (NULL, val_lab_cmp, (void *) (v->width));
1162 /* Add each label to the variable. */
1163 for (j = 0; j < n_labels; j++)
1165 struct value_label *old = avl_replace (v->val_lab, cooked_label[j]);
1169 if (var[0]->type == NUMERIC)
1170 msg (MW, _("%s: File contains duplicate label for value %g for "
1171 "variable %s."), h->fn, cooked_label[j]->v.f, v->name);
1173 msg (MW, _("%s: File contains duplicate label for value `%.*s' "
1174 "for variable %s."), h->fn, v->width,
1175 cooked_label[j]->v.s, v->name);
1177 free_value_label (old);
1181 free (cooked_label);
1188 for (i = 0; i < n_labels; i++)
1189 if (cooked_label[i])
1191 free (cooked_label[i]->s);
1192 free (cooked_label[i]);
1199 /* Reads NBYTES bytes from the file represented by H. If BUF is
1200 non-NULL, uses that as the buffer; otherwise allocates at least
1201 MINALLOC bytes. Returns a pointer to the buffer on success, NULL
1204 bufread (struct file_handle * h, void *buf, size_t nbytes, size_t minalloc)
1206 struct sfm_fhuser_ext *ext = h->ext;
1209 buf = xmalloc (max (nbytes, minalloc));
1210 if (1 != fread (buf, nbytes, 1, ext->file))
1212 if (ferror (ext->file))
1213 msg (ME, _("%s: Reading system file: %s."), h->fn, strerror (errno));
1215 corrupt_msg (ME, _("%s: Unexpected end of file."), h->fn);
1221 /* Reads a document record, type 6, from system file H, and sets up
1222 the documents and n_documents fields in the associated
1225 read_documents (struct file_handle * h)
1227 struct sfm_fhuser_ext *ext = h->ext;
1228 struct dictionary *dict = ext->dict;
1231 if (dict->documents != NULL)
1232 lose ((ME, _("%s: System file contains multiple type 6 (document) records."),
1235 assertive_bufread (h, &n_lines, sizeof n_lines, 0);
1236 dict->n_documents = n_lines;
1237 if (dict->n_documents <= 0)
1238 lose ((ME, _("%s: Number of document lines (%ld) must be greater than 0."),
1239 h->fn, (long) dict->n_documents));
1241 dict->documents = bufread (h, NULL, 80 * n_lines, 0);
1242 if (dict->documents == NULL)
1250 #if GLOBAL_DEBUGGING
1251 #include "debug-print.h"
1252 /* Displays dictionary DICT on stdout. */
1254 dump_dictionary (struct dictionary * dict)
1258 debug_printf ((_("dictionary:\n")));
1259 for (i = 0; i < dict->nvar; i++)
1262 struct variable *v = dict->var[i];
1265 debug_printf ((" var %s", v->name));
1266 /*debug_printf (("(indices:%d,%d)", v->index, v->foo));*/
1267 debug_printf (("(type:%s,%d)", (v->type == NUMERIC ? _("num")
1268 : (v->type == ALPHA ? _("str") : "!!!")),
1270 debug_printf (("(fv:%d,%d)", v->fv, v->nv));
1271 /*debug_printf (("(get.fv:%d,%d)", v->get.fv, v->get.nv));*/
1272 debug_printf (("(left:%s)(miss:", v->left ? _("left") : _("right")));
1274 switch (v->miss_type)
1278 debug_printf ((_("none")));
1282 debug_printf ((_("one")));
1286 debug_printf ((_("two")));
1290 debug_printf ((_("three")));
1294 debug_printf ((_("range")));
1298 debug_printf ((_("low")));
1302 debug_printf ((_("high")));
1304 case MISSING_RANGE_1:
1306 debug_printf ((_("range+1")));
1310 debug_printf ((_("low+1")));
1312 case MISSING_HIGH_1:
1314 debug_printf ((_("high+1")));
1319 for (j = 0; j < n; j++)
1320 if (v->type == NUMERIC)
1321 debug_printf ((",%g", v->missing[j].f));
1323 debug_printf ((",\"%.*s\"", v->width, v->missing[j].s));
1324 strcpy (print, fmt_to_string (&v->print));
1325 debug_printf ((")(fmt:%s,%s)(lbl:%s)\n",
1326 print, fmt_to_string (&v->write),
1327 v->label ? v->label : "nolabel"));
1334 /* Reads compressed data into H->BUF and sets other pointers
1335 appropriately. Returns nonzero only if both no errors occur and
1338 buffer_input (struct file_handle * h)
1340 struct sfm_fhuser_ext *ext = h->ext;
1343 if (ext->buf == NULL)
1344 ext->buf = xmalloc (sizeof *ext->buf * 128);
1345 amt = fread (ext->buf, sizeof *ext->buf, 128, ext->file);
1346 if (ferror (ext->file))
1348 msg (ME, _("%s: Error reading file: %s."), h->fn, strerror (errno));
1351 ext->ptr = ext->buf;
1352 ext->end = &ext->buf[amt];
1356 /* Reads a single case consisting of compressed data from system file
1357 H into the array TEMP[] according to dictionary DICT, and returns
1358 nonzero only if successful. */
1359 /* Data in system files is compressed in the following manner:
1360 data values are grouped into sets of eight; each of the eight has
1361 one instruction byte, which are output together in an octet; each
1362 byte gives a value for that byte or indicates that the value can be
1363 found following the instructions. */
1365 read_compressed_data (struct file_handle * h, flt64 * temp)
1367 struct sfm_fhuser_ext *ext = h->ext;
1369 const unsigned char *p_end = ext->x + sizeof (flt64);
1370 unsigned char *p = ext->y;
1372 const flt64 *temp_beg = temp;
1373 const flt64 *temp_end = &temp[ext->case_size];
1377 for (; p < p_end; p++)
1381 /* Code 0 is ignored. */
1384 /* Code 252 is end of file. */
1385 if (temp_beg != temp)
1386 lose ((ME, _("%s: Compressed data is corrupted. Data ends "
1387 "partway through a case."), h->fn));
1390 /* Code 253 indicates that the value is stored explicitly
1391 following the instruction bytes. */
1392 if (ext->ptr == NULL || ext->ptr >= ext->end)
1393 if (!buffer_input (h))
1395 lose ((ME, _("%s: Unexpected end of file."), h->fn));
1398 memcpy (temp++, ext->ptr++, sizeof *temp);
1399 if (temp >= temp_end)
1403 /* Code 254 indicates a string that is all blanks. */
1404 memset (temp++, ' ', sizeof *temp);
1405 if (temp >= temp_end)
1409 /* Code 255 indicates the system-missing value. */
1410 *temp = ext->sysmis;
1411 if (ext->reverse_endian)
1414 if (temp >= temp_end)
1418 /* Codes 1 through 251 inclusive are taken to indicate a
1419 value of (BYTE - BIAS), where BYTE is the byte's value
1420 and BIAS is the compression bias (generally 100.0). */
1421 *temp = *p - ext->bias;
1422 if (ext->reverse_endian)
1425 if (temp >= temp_end)
1430 /* We have reached the end of this instruction octet. Read
1432 if (ext->ptr == NULL || ext->ptr >= ext->end)
1433 if (!buffer_input (h))
1435 if (temp_beg != temp)
1436 lose ((ME, _("%s: Unexpected end of file."), h->fn));
1439 memcpy (ext->x, ext->ptr++, sizeof *temp);
1447 /* We have filled up an entire record. Update state and return
1453 /* We have been unsuccessful at filling a record, either through i/o
1454 error or through an end-of-file indication. Update state and
1455 return unsuccessfully. */
1459 /* Reads one case from system file H into the value array PERM
1460 according to the instructions given in associated dictionary DICT,
1461 which must have the get.* elements appropriately set. Returns
1462 nonzero only if successful. */
1464 sfm_read_case (struct file_handle * h, union value * perm, struct dictionary * dict)
1466 struct sfm_fhuser_ext *ext = h->ext;
1473 /* Make sure the caller remembered to finish polishing the
1474 dictionary returned by sfm_read_dictionary(). */
1475 assert (dict->nval > 0);
1477 /* The first concern is to obtain a full case relative to the data
1478 file. (Cases in the data file have no particular relationship to
1479 cases in the active file.) */
1480 nbytes = sizeof *temp * ext->case_size;
1481 temp = local_alloc (nbytes);
1483 if (ext->compressed == 0)
1485 size_t amt = fread (temp, 1, nbytes, ext->file);
1489 if (ferror (ext->file))
1490 msg (ME, _("%s: Reading system file: %s."), h->fn, strerror (errno));
1492 msg (ME, _("%s: Partial record at end of system file."), h->fn);
1496 else if (!read_compressed_data (h, temp))
1499 /* Translate a case in data file format to a case in active file
1501 for (i = 0; i < dict->nvar; i++)
1503 struct variable *v = dict->var[i];
1505 if (v->get.fv == -1)
1508 if (v->type == NUMERIC)
1510 flt64 src = temp[v->get.fv];
1511 if (ext->reverse_endian)
1513 perm[v->fv].f = src == ext->sysmis ? SYSMIS : src;
1516 memcpy (&perm[v->fv].s, &temp[v->get.fv], v->width);
1527 static struct fh_ext_class sfm_r_class =
1530 N_("reading as a system file"),