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., 51 Franklin Street, Fifth Floor, Boston, MA
21 #include "sys-file-writer.h"
22 #include "sfm-private.h"
23 #include <libpspp/message.h>
31 #include <libpspp/alloc.h>
33 #include "dictionary.h"
34 #include <libpspp/message.h>
35 #include "file-handle-def.h"
36 #include <libpspp/hash.h>
37 #include <libpspp/magic.h>
38 #include <libpspp/misc.h>
40 #include "stat-macros.h"
41 #include <libpspp/str.h>
42 #include "value-labels.h"
44 #include <libpspp/version.h>
47 #define _(msgid) gettext (msgid)
49 /* Compression bias used by PSPP. Values between (1 -
50 COMPRESSION_BIAS) and (251 - COMPRESSION_BIAS) inclusive can be
52 #define COMPRESSION_BIAS 100
54 /* System file writer. */
57 struct file_handle *fh; /* File handle. */
58 FILE *file; /* File stream. */
60 int needs_translation; /* 0=use fast path, 1=translation needed. */
61 int compress; /* 1=compressed, 0=not compressed. */
62 int case_cnt; /* Number of cases written so far. */
63 size_t flt64_cnt; /* Number of flt64 elements in case. */
65 /* Compression buffering. */
66 flt64 *buf; /* Buffered data. */
67 flt64 *end; /* Buffer end. */
68 flt64 *ptr; /* Current location in buffer. */
69 unsigned char *x; /* Location in current instruction octet. */
70 unsigned char *y; /* End of instruction octet. */
73 struct sfm_var *vars; /* Variables. */
74 size_t var_cnt; /* Number of variables. */
77 /* A variable in a system file. */
80 int width; /* 0=numeric, otherwise string width. */
81 int fv; /* Index into case. */
82 size_t flt64_cnt; /* Number of flt64 elements. */
85 static char *append_string_max (char *, const char *, const char *);
86 static void write_header (struct sfm_writer *, const struct dictionary *);
87 static void buf_write (struct sfm_writer *, const void *, size_t);
88 static void write_variable (struct sfm_writer *, struct variable *);
89 static void write_value_labels (struct sfm_writer *,
90 struct variable *, int idx);
91 static void write_rec_7_34 (struct sfm_writer *);
93 static void write_longvar_table (struct sfm_writer *w,
94 const struct dictionary *dict);
96 static void write_variable_display_parameters (struct sfm_writer *w,
97 const struct dictionary *dict);
99 static void write_documents (struct sfm_writer *, const struct dictionary *);
100 static int does_dict_need_translation (const struct dictionary *);
103 var_flt64_cnt (const struct variable *v)
105 return v->type == NUMERIC ? 1 : DIV_RND_UP (v->width, sizeof (flt64));
108 /* Returns default options for writing a system file. */
109 struct sfm_write_options
110 sfm_writer_default_options (void)
112 struct sfm_write_options opts;
113 opts.create_writeable = true;
114 opts.compress = get_scompression ();
119 /* Opens the system file designated by file handle FH for writing
120 cases from dictionary D according to the given OPTS. If
121 COMPRESS is nonzero, the system file will be compressed.
123 No reference to D is retained, so it may be modified or
124 destroyed at will after this function returns. D is not
125 modified by this function, except to assign short names. */
127 sfm_open_writer (struct file_handle *fh, struct dictionary *d,
128 struct sfm_write_options opts)
130 struct sfm_writer *w = NULL;
137 if (opts.version != 2 && opts.version != 3)
139 msg (ME, _("Unknown system file version %d. Treating as version %d."),
145 mode = S_IRUSR | S_IRGRP | S_IROTH;
146 if (opts.create_writeable)
147 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
148 fd = open (fh_get_file_name (fh), O_WRONLY | O_CREAT | O_TRUNC, mode);
152 /* Open file handle. */
153 if (!fh_open (fh, FH_REF_FILE, "system file", "we"))
156 /* Create and initialize writer. */
157 w = xmalloc (sizeof *w);
159 w->file = fdopen (fd, "w");
161 w->needs_translation = does_dict_need_translation (d);
162 w->compress = opts.compress;
166 w->buf = w->end = w->ptr = NULL;
169 w->var_cnt = dict_get_var_cnt (d);
170 w->vars = xnmalloc (w->var_cnt, sizeof *w->vars);
171 for (i = 0; i < w->var_cnt; i++)
173 const struct variable *dv = dict_get_var (d, i);
174 struct sfm_var *sv = &w->vars[i];
175 sv->width = dv->width;
177 sv->flt64_cnt = var_flt64_cnt (dv);
180 /* Check that file create succeeded. */
187 /* Write the file header. */
190 /* Write basic variable info. */
191 dict_assign_short_names (d);
192 for (i = 0; i < dict_get_var_cnt (d); i++)
193 write_variable (w, dict_get_var (d, i));
195 /* Write out value labels. */
196 for (idx = i = 0; i < dict_get_var_cnt (d); i++)
198 struct variable *v = dict_get_var (d, i);
200 write_value_labels (w, v, idx);
201 idx += var_flt64_cnt (v);
204 if (dict_get_documents (d) != NULL)
205 write_documents (w, d);
209 write_variable_display_parameters (w, d);
211 if (opts.version >= 3)
212 write_longvar_table (w, d);
214 /* Write end-of-headers record. */
223 rec_999.rec_type = 999;
226 buf_write (w, &rec_999, sizeof rec_999);
231 w->buf = xnmalloc (128, sizeof *w->buf);
233 w->end = &w->buf[128];
234 w->x = (unsigned char *) w->ptr++;
235 w->y = (unsigned char *) w->ptr;
238 if (sfm_write_error (w))
244 sfm_close_writer (w);
248 msg (ME, _("Error opening \"%s\" for writing as a system file: %s."),
249 fh_get_file_name (fh), strerror (errno));
254 does_dict_need_translation (const struct dictionary *d)
260 for (i = 0; i < dict_get_var_cnt (d); i++)
262 struct variable *v = dict_get_var (d, i);
263 if (v->fv != case_idx)
270 /* Returns value of X truncated to two least-significant digits. */
281 /* Write the sysfile_header header to system file W. */
283 write_header (struct sfm_writer *w, const struct dictionary *d)
285 struct sysfile_header hdr;
291 memcpy (hdr.rec_type, "$FL2", 4);
293 p = stpcpy (hdr.prod_name, "@(#) SPSS DATA FILE ");
294 p = append_string_max (p, version, &hdr.prod_name[60]);
295 p = append_string_max (p, " - ", &hdr.prod_name[60]);
296 p = append_string_max (p, host_system, &hdr.prod_name[60]);
297 memset (p, ' ', &hdr.prod_name[60] - p);
302 for (i = 0; i < dict_get_var_cnt (d); i++)
303 w->flt64_cnt += var_flt64_cnt (dict_get_var (d, i));
304 hdr.case_size = w->flt64_cnt;
306 hdr.compress = w->compress;
308 if (dict_get_weight (d) != NULL)
310 struct variable *weight_var;
311 int recalc_weight_idx = 1;
314 weight_var = dict_get_weight (d);
317 struct variable *v = dict_get_var (d, i);
320 recalc_weight_idx += var_flt64_cnt (v);
322 hdr.weight_idx = recalc_weight_idx;
328 hdr.bias = COMPRESSION_BIAS;
330 if (time (&t) == (time_t) -1)
332 memcpy (hdr.creation_date, "01 Jan 70", 9);
333 memcpy (hdr.creation_time, "00:00:00", 8);
337 static const char *month_name[12] =
339 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
340 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
342 struct tm *tmp = localtime (&t);
343 int day = rerange (tmp->tm_mday);
344 int mon = rerange (tmp->tm_mon + 1);
345 int year = rerange (tmp->tm_year);
346 int hour = rerange (tmp->tm_hour + 1);
347 int min = rerange (tmp->tm_min + 1);
348 int sec = rerange (tmp->tm_sec + 1);
351 sprintf (buf, "%02d %s %02d", day, month_name[mon - 1], year);
352 memcpy (hdr.creation_date, buf, sizeof hdr.creation_date);
353 sprintf (buf, "%02d:%02d:%02d", hour - 1, min - 1, sec - 1);
354 memcpy (hdr.creation_time, buf, sizeof hdr.creation_time);
358 const char *label = dict_get_label (d);
362 buf_copy_str_rpad (hdr.file_label, sizeof hdr.file_label, label);
365 memset (hdr.padding, 0, sizeof hdr.padding);
367 buf_write (w, &hdr, sizeof hdr);
370 /* Translates format spec from internal form in SRC to system file
373 write_format_spec (struct fmt_spec *src, int32_t *dest)
375 *dest = (formats[src->type].spss << 16) | (src->w << 8) | src->d;
378 /* Write the variable record(s) for primary variable P and secondary
379 variable S to system file W. */
381 write_variable (struct sfm_writer *w, struct variable *v)
383 struct sysfile_variable sv;
385 /* Missing values. */
386 struct missing_values mv;
387 flt64 m[3]; /* Missing value values. */
388 int nm; /* Number of missing values, possibly negative. */
392 sv.has_var_label = (v->label != NULL);
394 mv_copy (&mv, &v->miss);
396 if (mv_has_range (&mv))
399 mv_pop_range (&mv, &x, &y);
400 m[nm++] = x == LOWEST ? second_lowest_flt64 : x;
401 m[nm++] = y == HIGHEST ? FLT64_MAX : y;
403 while (mv_has_value (&mv))
406 mv_pop_value (&mv, &value);
407 if (v->type == NUMERIC)
410 buf_copy_rpad ((char *) &m[nm], sizeof m[nm], value.s, v->width);
413 if (mv_has_range (&v->miss))
416 sv.n_missing_values = nm;
417 write_format_spec (&v->print, &sv.print);
418 write_format_spec (&v->write, &sv.write);
419 buf_copy_str_rpad (sv.name, sizeof sv.name, v->short_name);
420 buf_write (w, &sv, sizeof sv);
433 l.label_len = min (strlen (v->label), 255);
434 ext_len = ROUND_UP (l.label_len, sizeof l.label_len);
435 memcpy (l.label, v->label, l.label_len);
436 memset (&l.label[l.label_len], ' ', ext_len - l.label_len);
438 buf_write (w, &l, offsetof (struct label, label) + ext_len);
442 buf_write (w, m, sizeof *m * abs (nm));
444 if (v->type == ALPHA && v->width > (int) sizeof (flt64))
450 sv.has_var_label = 0;
451 sv.n_missing_values = 0;
452 memset (&sv.print, 0, sizeof sv.print);
453 memset (&sv.write, 0, sizeof sv.write);
454 memset (&sv.name, 0, sizeof sv.name);
456 pad_count = DIV_RND_UP (v->width, (int) sizeof (flt64)) - 1;
457 for (i = 0; i < pad_count; i++)
458 buf_write (w, &sv, sizeof sv);
462 /* Writes the value labels for variable V having system file
463 variable index IDX to system file W. */
465 write_value_labels (struct sfm_writer *w, struct variable *v, int idx)
467 struct value_label_rec
481 struct val_labs_iterator *i;
482 struct value_label_rec *vlr;
483 struct var_idx_rec vir;
488 if (!val_labs_count (v->val_labs))
491 /* Pass 1: Count bytes. */
492 vlr_size = (sizeof (struct value_label_rec)
493 + sizeof (flt64) * (val_labs_count (v->val_labs) - 1));
494 for (vl = val_labs_first (v->val_labs, &i); vl != NULL;
495 vl = val_labs_next (v->val_labs, &i))
496 vlr_size += ROUND_UP (strlen (vl->label) + 1, sizeof (flt64));
498 /* Pass 2: Copy bytes. */
499 vlr = xmalloc (vlr_size);
501 vlr->n_labels = val_labs_count (v->val_labs);
503 for (vl = val_labs_first_sorted (v->val_labs, &i); vl != NULL;
504 vl = val_labs_next (v->val_labs, &i))
506 size_t len = strlen (vl->label);
508 *loc++ = vl->value.f;
509 *(unsigned char *) loc = len;
510 memcpy (&((char *) loc)[1], vl->label, len);
511 memset (&((char *) loc)[1 + len], ' ',
512 REM_RND_UP (len + 1, sizeof (flt64)));
513 loc += DIV_RND_UP (len + 1, sizeof (flt64));
516 buf_write (w, vlr, vlr_size);
521 vir.vars[0] = idx + 1;
522 buf_write (w, &vir, sizeof vir);
525 /* Writes record type 6, document record. */
527 write_documents (struct sfm_writer *w, const struct dictionary *d)
531 int32_t rec_type P; /* Always 6. */
532 int32_t n_lines P; /* Number of lines of documents. */
536 const char *documents;
539 documents = dict_get_documents (d);
540 n_lines = strlen (documents) / 80;
543 rec_6.n_lines = n_lines;
544 buf_write (w, &rec_6, sizeof rec_6);
545 buf_write (w, documents, 80 * n_lines);
548 /* Write the alignment, width and scale values */
550 write_variable_display_parameters (struct sfm_writer *w,
551 const struct dictionary *dict)
563 vdp_hdr.rec_type = 7;
564 vdp_hdr.subtype = 11;
565 vdp_hdr.elem_size = 4;
566 vdp_hdr.n_elem = w->var_cnt * 3;
568 buf_write (w, &vdp_hdr, sizeof vdp_hdr);
570 for ( i = 0 ; i < w->var_cnt ; ++i )
581 v = dict_get_var(dict, i);
583 params.measure = v->measure;
584 params.width = v->display_width;
585 params.align = v->alignment;
587 buf_write (w, ¶ms, sizeof(params));
591 /* Writes the long variable name table */
593 write_longvar_table (struct sfm_writer *w, const struct dictionary *dict)
604 struct string long_name_map;
607 ds_init (&long_name_map, 10 * dict_get_var_cnt (dict));
608 for (i = 0; i < dict_get_var_cnt (dict); i++)
610 struct variable *v = dict_get_var (dict, i);
613 ds_putc (&long_name_map, '\t');
614 ds_printf (&long_name_map, "%s=%s", v->short_name, v->name);
619 lv_hdr.elem_size = 1;
620 lv_hdr.n_elem = ds_length (&long_name_map);
622 buf_write (w, &lv_hdr, sizeof lv_hdr);
623 buf_write (w, ds_data (&long_name_map), ds_length (&long_name_map));
625 ds_destroy (&long_name_map);
628 /* Writes record type 7, subtypes 3 and 4. */
630 write_rec_7_34 (struct sfm_writer *w)
634 int32_t rec_type_3 P;
636 int32_t data_type_3 P;
639 int32_t rec_type_4 P;
641 int32_t data_type_4 P;
647 /* Components of the version number, from major to minor. */
648 int version_component[3];
650 /* Used to step through the version string. */
653 /* Parses the version string, which is assumed to be of the form
654 #.#x, where each # is a string of digits, and x is a single
656 version_component[0] = strtol (bare_version, &p, 10);
659 version_component[1] = strtol (bare_version, &p, 10);
660 version_component[2] = (isalpha ((unsigned char) *p)
661 ? tolower ((unsigned char) *p) - 'a' : 0);
663 rec_7.rec_type_3 = 7;
665 rec_7.data_type_3 = sizeof (int32_t);
667 rec_7.elem_3[0] = version_component[0];
668 rec_7.elem_3[1] = version_component[1];
669 rec_7.elem_3[2] = version_component[2];
670 rec_7.elem_3[3] = -1;
672 /* PORTME: 1=IEEE754, 2=IBM 370, 3=DEC VAX E. */
679 /* PORTME: 1=big-endian, 2=little-endian. */
686 /* PORTME: 1=EBCDIC, 2=7-bit ASCII, 3=8-bit ASCII, 4=DEC Kanji. */
689 rec_7.rec_type_4 = 7;
691 rec_7.data_type_4 = sizeof (flt64);
693 rec_7.elem_4[0] = -FLT64_MAX;
694 rec_7.elem_4[1] = FLT64_MAX;
695 rec_7.elem_4[2] = second_lowest_flt64;
697 buf_write (w, &rec_7, sizeof rec_7);
700 /* Write NBYTES starting at BUF to the system file represented by
703 buf_write (struct sfm_writer *w, const void *buf, size_t nbytes)
705 assert (buf != NULL);
706 fwrite (buf, nbytes, 1, w->file);
709 /* Copies string DEST to SRC with the proviso that DEST does not reach
710 byte END; no null terminator is copied. Returns a pointer to the
711 byte after the last byte copied. */
713 append_string_max (char *dest, const char *src, const char *end)
715 int nbytes = min (end - dest, (int) strlen (src));
716 memcpy (dest, src, nbytes);
717 return dest + nbytes;
720 /* Makes certain that the compression buffer of H has room for another
721 element. If there's not room, pads out the current instruction
722 octet with zero and dumps out the buffer. */
724 ensure_buf_space (struct sfm_writer *w)
726 if (w->ptr >= w->end)
728 memset (w->x, 0, w->y - w->x);
731 buf_write (w, w->buf, sizeof *w->buf * 128);
735 static void write_compressed_data (struct sfm_writer *w, const flt64 *elem);
737 /* Writes case C to system file W.
738 Returns 1 if successful, 0 if an I/O error occurred. */
740 sfm_write_case (struct sfm_writer *w, const struct ccase *c)
742 if (ferror (w->file))
747 if (!w->needs_translation && !w->compress
748 && sizeof (flt64) == sizeof (union value))
750 /* Fast path: external and internal representations are the
751 same and the dictionary is properly ordered. Write
753 buf_write (w, case_data_all (c), sizeof (union value) * w->flt64_cnt);
757 /* Slow path: internal and external representations differ.
758 Write into a bounce buffer, then write to W. */
764 bounce_size = sizeof *bounce * w->flt64_cnt;
765 bounce = bounce_cur = local_alloc (bounce_size);
767 for (i = 0; i < w->var_cnt; i++)
769 struct sfm_var *v = &w->vars[i];
772 *bounce_cur = case_num (c, v->fv);
774 memcpy (bounce_cur, case_data (c, v->fv)->s, v->width);
775 bounce_cur += v->flt64_cnt;
779 buf_write (w, bounce, bounce_size);
781 write_compressed_data (w, bounce);
786 return !sfm_write_error (w);
790 put_instruction (struct sfm_writer *w, unsigned char instruction)
794 ensure_buf_space (w);
795 w->x = (unsigned char *) w->ptr++;
796 w->y = (unsigned char *) w->ptr;
798 *w->x++ = instruction;
802 put_element (struct sfm_writer *w, const flt64 *elem)
804 ensure_buf_space (w);
805 memcpy (w->ptr++, elem, sizeof *elem);
809 write_compressed_data (struct sfm_writer *w, const flt64 *elem)
813 for (i = 0; i < w->var_cnt; i++)
815 struct sfm_var *v = &w->vars[i];
819 if (*elem == -FLT64_MAX)
820 put_instruction (w, 255);
821 else if (*elem >= 1 - COMPRESSION_BIAS
822 && *elem <= 251 - COMPRESSION_BIAS
823 && *elem == (int) *elem)
824 put_instruction (w, (int) *elem + COMPRESSION_BIAS);
827 put_instruction (w, 253);
828 put_element (w, elem);
836 for (j = 0; j < v->flt64_cnt; j++, elem++)
838 if (!memcmp (elem, " ", sizeof (flt64)))
839 put_instruction (w, 254);
842 put_instruction (w, 253);
843 put_element (w, elem);
850 /* Returns true if an I/O error has occurred on WRITER, false otherwise. */
852 sfm_write_error (const struct sfm_writer *writer)
854 return ferror (writer->file);
857 /* Closes a system file after we're done with it.
858 Returns true if successful, false if an I/O error occurred. */
860 sfm_close_writer (struct sfm_writer *w)
871 if (w->buf != NULL && w->ptr > w->buf)
873 memset (w->x, 0, w->y - w->x);
874 buf_write (w, w->buf, (w->ptr - w->buf) * sizeof *w->buf);
878 ok = !sfm_write_error (w);
880 /* Seek back to the beginning and update the number of cases.
881 This is just a courtesy to later readers, so there's no need
882 to check return values or report errors. */
883 if (ok && !fseek (w->file, offsetof (struct sysfile_header, case_cnt),
886 int32_t case_cnt = w->case_cnt;
887 fwrite (&case_cnt, sizeof case_cnt, 1, w->file);
891 if (fclose (w->file) == EOF)
895 msg (ME, _("An I/O error occurred writing system file \"%s\"."),
896 fh_get_file_name (w->fh));
899 fh_close (w->fh, "system file", "we");