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 #include <libpspp/debug-print.h>
51 /* Compression bias used by PSPP. Values between (1 -
52 COMPRESSION_BIAS) and (251 - COMPRESSION_BIAS) inclusive can be
54 #define COMPRESSION_BIAS 100
56 /* System file writer. */
59 struct file_handle *fh; /* File handle. */
60 FILE *file; /* File stream. */
62 int needs_translation; /* 0=use fast path, 1=translation needed. */
63 int compress; /* 1=compressed, 0=not compressed. */
64 int case_cnt; /* Number of cases written so far. */
65 size_t flt64_cnt; /* Number of flt64 elements in case. */
67 /* Compression buffering. */
68 flt64 *buf; /* Buffered data. */
69 flt64 *end; /* Buffer end. */
70 flt64 *ptr; /* Current location in buffer. */
71 unsigned char *x; /* Location in current instruction octet. */
72 unsigned char *y; /* End of instruction octet. */
75 struct sfm_var *vars; /* Variables. */
76 size_t var_cnt; /* Number of variables. */
79 /* A variable in a system file. */
82 int width; /* 0=numeric, otherwise string width. */
83 int fv; /* Index into case. */
84 size_t flt64_cnt; /* Number of flt64 elements. */
87 static char *append_string_max (char *, const char *, const char *);
88 static void write_header (struct sfm_writer *, const struct dictionary *);
89 static void buf_write (struct sfm_writer *, const void *, size_t);
90 static void write_variable (struct sfm_writer *, struct variable *);
91 static void write_value_labels (struct sfm_writer *,
92 struct variable *, int idx);
93 static void write_rec_7_34 (struct sfm_writer *);
95 static void write_longvar_table (struct sfm_writer *w,
96 const struct dictionary *dict);
98 static void write_variable_display_parameters (struct sfm_writer *w,
99 const struct dictionary *dict);
101 static void write_documents (struct sfm_writer *, const struct dictionary *);
102 static int does_dict_need_translation (const struct dictionary *);
105 var_flt64_cnt (const struct variable *v)
107 return v->type == NUMERIC ? 1 : DIV_RND_UP (v->width, sizeof (flt64));
110 /* Returns default options for writing a system file. */
111 struct sfm_write_options
112 sfm_writer_default_options (void)
114 struct sfm_write_options opts;
115 opts.create_writeable = true;
116 opts.compress = get_scompression ();
121 /* Opens the system file designated by file handle FH for writing
122 cases from dictionary D according to the given OPTS. If
123 COMPRESS is nonzero, the system file will be compressed.
125 No reference to D is retained, so it may be modified or
126 destroyed at will after this function returns. D is not
127 modified by this function, except to assign short names. */
129 sfm_open_writer (struct file_handle *fh, struct dictionary *d,
130 struct sfm_write_options opts)
132 struct sfm_writer *w = NULL;
139 if (opts.version != 2 && opts.version != 3)
141 msg (ME, _("Unknown system file version %d. Treating as version %d."),
147 mode = S_IRUSR | S_IRGRP | S_IROTH;
148 if (opts.create_writeable)
149 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
150 fd = open (fh_get_filename (fh), O_WRONLY | O_CREAT | O_TRUNC, mode);
154 /* Open file handle. */
155 if (!fh_open (fh, FH_REF_FILE, "system file", "we"))
158 /* Create and initialize writer. */
159 w = xmalloc (sizeof *w);
161 w->file = fdopen (fd, "w");
163 w->needs_translation = does_dict_need_translation (d);
164 w->compress = opts.compress;
168 w->buf = w->end = w->ptr = NULL;
171 w->var_cnt = dict_get_var_cnt (d);
172 w->vars = xnmalloc (w->var_cnt, sizeof *w->vars);
173 for (i = 0; i < w->var_cnt; i++)
175 const struct variable *dv = dict_get_var (d, i);
176 struct sfm_var *sv = &w->vars[i];
177 sv->width = dv->width;
179 sv->flt64_cnt = var_flt64_cnt (dv);
182 /* Check that file create succeeded. */
189 /* Write the file header. */
192 /* Write basic variable info. */
193 dict_assign_short_names (d);
194 for (i = 0; i < dict_get_var_cnt (d); i++)
195 write_variable (w, dict_get_var (d, i));
197 /* Write out value labels. */
198 for (idx = i = 0; i < dict_get_var_cnt (d); i++)
200 struct variable *v = dict_get_var (d, i);
202 write_value_labels (w, v, idx);
203 idx += var_flt64_cnt (v);
206 if (dict_get_documents (d) != NULL)
207 write_documents (w, d);
211 write_variable_display_parameters (w, d);
213 if (opts.version >= 3)
214 write_longvar_table (w, d);
216 /* Write end-of-headers record. */
225 rec_999.rec_type = 999;
228 buf_write (w, &rec_999, sizeof rec_999);
233 w->buf = xnmalloc (128, sizeof *w->buf);
235 w->end = &w->buf[128];
236 w->x = (unsigned char *) w->ptr++;
237 w->y = (unsigned char *) w->ptr;
240 if (sfm_write_error (w))
246 sfm_close_writer (w);
250 msg (ME, _("Error opening \"%s\" for writing as a system file: %s."),
251 fh_get_filename (fh), strerror (errno));
256 does_dict_need_translation (const struct dictionary *d)
262 for (i = 0; i < dict_get_var_cnt (d); i++)
264 struct variable *v = dict_get_var (d, i);
265 if (v->fv != case_idx)
272 /* Returns value of X truncated to two least-significant digits. */
283 /* Write the sysfile_header header to system file W. */
285 write_header (struct sfm_writer *w, const struct dictionary *d)
287 struct sysfile_header hdr;
293 memcpy (hdr.rec_type, "$FL2", 4);
295 p = stpcpy (hdr.prod_name, "@(#) SPSS DATA FILE ");
296 p = append_string_max (p, version, &hdr.prod_name[60]);
297 p = append_string_max (p, " - ", &hdr.prod_name[60]);
298 p = append_string_max (p, host_system, &hdr.prod_name[60]);
299 memset (p, ' ', &hdr.prod_name[60] - p);
304 for (i = 0; i < dict_get_var_cnt (d); i++)
305 w->flt64_cnt += var_flt64_cnt (dict_get_var (d, i));
306 hdr.case_size = w->flt64_cnt;
308 hdr.compress = w->compress;
310 if (dict_get_weight (d) != NULL)
312 struct variable *weight_var;
313 int recalc_weight_idx = 1;
316 weight_var = dict_get_weight (d);
319 struct variable *v = dict_get_var (d, i);
322 recalc_weight_idx += var_flt64_cnt (v);
324 hdr.weight_idx = recalc_weight_idx;
330 hdr.bias = COMPRESSION_BIAS;
332 if (time (&t) == (time_t) -1)
334 memcpy (hdr.creation_date, "01 Jan 70", 9);
335 memcpy (hdr.creation_time, "00:00:00", 8);
339 static const char *month_name[12] =
341 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
342 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
344 struct tm *tmp = localtime (&t);
345 int day = rerange (tmp->tm_mday);
346 int mon = rerange (tmp->tm_mon + 1);
347 int year = rerange (tmp->tm_year);
348 int hour = rerange (tmp->tm_hour + 1);
349 int min = rerange (tmp->tm_min + 1);
350 int sec = rerange (tmp->tm_sec + 1);
353 sprintf (buf, "%02d %s %02d", day, month_name[mon - 1], year);
354 memcpy (hdr.creation_date, buf, sizeof hdr.creation_date);
355 sprintf (buf, "%02d:%02d:%02d", hour - 1, min - 1, sec - 1);
356 memcpy (hdr.creation_time, buf, sizeof hdr.creation_time);
360 const char *label = dict_get_label (d);
364 buf_copy_str_rpad (hdr.file_label, sizeof hdr.file_label, label);
367 memset (hdr.padding, 0, sizeof hdr.padding);
369 buf_write (w, &hdr, sizeof hdr);
372 /* Translates format spec from internal form in SRC to system file
375 write_format_spec (struct fmt_spec *src, int32 *dest)
377 *dest = (formats[src->type].spss << 16) | (src->w << 8) | src->d;
380 /* Write the variable record(s) for primary variable P and secondary
381 variable S to system file W. */
383 write_variable (struct sfm_writer *w, struct variable *v)
385 struct sysfile_variable sv;
387 /* Missing values. */
388 struct missing_values mv;
389 flt64 m[3]; /* Missing value values. */
390 int nm; /* Number of missing values, possibly negative. */
394 sv.has_var_label = (v->label != NULL);
396 mv_copy (&mv, &v->miss);
398 if (mv_has_range (&mv))
401 mv_pop_range (&mv, &x, &y);
402 m[nm++] = x == LOWEST ? second_lowest_flt64 : x;
403 m[nm++] = y == HIGHEST ? FLT64_MAX : y;
405 while (mv_has_value (&mv))
408 mv_pop_value (&mv, &value);
409 if (v->type == NUMERIC)
412 buf_copy_rpad ((char *) &m[nm], sizeof m[nm], value.s, v->width);
415 if (mv_has_range (&v->miss))
418 sv.n_missing_values = nm;
419 write_format_spec (&v->print, &sv.print);
420 write_format_spec (&v->write, &sv.write);
421 buf_copy_str_rpad (sv.name, sizeof sv.name, v->short_name);
422 buf_write (w, &sv, sizeof sv);
435 l.label_len = min (strlen (v->label), 255);
436 ext_len = ROUND_UP (l.label_len, sizeof l.label_len);
437 memcpy (l.label, v->label, l.label_len);
438 memset (&l.label[l.label_len], ' ', ext_len - l.label_len);
440 buf_write (w, &l, offsetof (struct label, label) + ext_len);
444 buf_write (w, m, sizeof *m * abs (nm));
446 if (v->type == ALPHA && v->width > (int) sizeof (flt64))
452 sv.has_var_label = 0;
453 sv.n_missing_values = 0;
454 memset (&sv.print, 0, sizeof sv.print);
455 memset (&sv.write, 0, sizeof sv.write);
456 memset (&sv.name, 0, sizeof sv.name);
458 pad_count = DIV_RND_UP (v->width, (int) sizeof (flt64)) - 1;
459 for (i = 0; i < pad_count; i++)
460 buf_write (w, &sv, sizeof sv);
464 /* Writes the value labels for variable V having system file
465 variable index IDX to system file W. */
467 write_value_labels (struct sfm_writer *w, struct variable *v, int idx)
469 struct value_label_rec
483 struct val_labs_iterator *i;
484 struct value_label_rec *vlr;
485 struct var_idx_rec vir;
490 if (!val_labs_count (v->val_labs))
493 /* Pass 1: Count bytes. */
494 vlr_size = (sizeof (struct value_label_rec)
495 + sizeof (flt64) * (val_labs_count (v->val_labs) - 1));
496 for (vl = val_labs_first (v->val_labs, &i); vl != NULL;
497 vl = val_labs_next (v->val_labs, &i))
498 vlr_size += ROUND_UP (strlen (vl->label) + 1, sizeof (flt64));
500 /* Pass 2: Copy bytes. */
501 vlr = xmalloc (vlr_size);
503 vlr->n_labels = val_labs_count (v->val_labs);
505 for (vl = val_labs_first_sorted (v->val_labs, &i); vl != NULL;
506 vl = val_labs_next (v->val_labs, &i))
508 size_t len = strlen (vl->label);
510 *loc++ = vl->value.f;
511 *(unsigned char *) loc = len;
512 memcpy (&((char *) loc)[1], vl->label, len);
513 memset (&((char *) loc)[1 + len], ' ',
514 REM_RND_UP (len + 1, sizeof (flt64)));
515 loc += DIV_RND_UP (len + 1, sizeof (flt64));
518 buf_write (w, vlr, vlr_size);
523 vir.vars[0] = idx + 1;
524 buf_write (w, &vir, sizeof vir);
527 /* Writes record type 6, document record. */
529 write_documents (struct sfm_writer *w, const struct dictionary *d)
533 int32 rec_type P; /* Always 6. */
534 int32 n_lines P; /* Number of lines of documents. */
538 const char *documents;
541 documents = dict_get_documents (d);
542 n_lines = strlen (documents) / 80;
545 rec_6.n_lines = n_lines;
546 buf_write (w, &rec_6, sizeof rec_6);
547 buf_write (w, documents, 80 * n_lines);
550 /* Write the alignment, width and scale values */
552 write_variable_display_parameters (struct sfm_writer *w,
553 const struct dictionary *dict)
565 vdp_hdr.rec_type = 7;
566 vdp_hdr.subtype = 11;
567 vdp_hdr.elem_size = 4;
568 vdp_hdr.n_elem = w->var_cnt * 3;
570 buf_write (w, &vdp_hdr, sizeof vdp_hdr);
572 for ( i = 0 ; i < w->var_cnt ; ++i )
583 v = dict_get_var(dict, i);
585 params.measure = v->measure;
586 params.width = v->display_width;
587 params.align = v->alignment;
589 buf_write (w, ¶ms, sizeof(params));
593 /* Writes the long variable name table */
595 write_longvar_table (struct sfm_writer *w, const struct dictionary *dict)
606 struct string long_name_map;
609 ds_init (&long_name_map, 10 * dict_get_var_cnt (dict));
610 for (i = 0; i < dict_get_var_cnt (dict); i++)
612 struct variable *v = dict_get_var (dict, i);
615 ds_putc (&long_name_map, '\t');
616 ds_printf (&long_name_map, "%s=%s", v->short_name, v->name);
621 lv_hdr.elem_size = 1;
622 lv_hdr.n_elem = ds_length (&long_name_map);
624 buf_write (w, &lv_hdr, sizeof lv_hdr);
625 buf_write (w, ds_data (&long_name_map), ds_length (&long_name_map));
627 ds_destroy (&long_name_map);
630 /* Writes record type 7, subtypes 3 and 4. */
632 write_rec_7_34 (struct sfm_writer *w)
649 /* Components of the version number, from major to minor. */
650 int version_component[3];
652 /* Used to step through the version string. */
655 /* Parses the version string, which is assumed to be of the form
656 #.#x, where each # is a string of digits, and x is a single
658 version_component[0] = strtol (bare_version, &p, 10);
661 version_component[1] = strtol (bare_version, &p, 10);
662 version_component[2] = (isalpha ((unsigned char) *p)
663 ? tolower ((unsigned char) *p) - 'a' : 0);
665 rec_7.rec_type_3 = 7;
667 rec_7.data_type_3 = sizeof (int32);
669 rec_7.elem_3[0] = version_component[0];
670 rec_7.elem_3[1] = version_component[1];
671 rec_7.elem_3[2] = version_component[2];
672 rec_7.elem_3[3] = -1;
674 /* PORTME: 1=IEEE754, 2=IBM 370, 3=DEC VAX E. */
681 /* PORTME: 1=big-endian, 2=little-endian. */
688 /* PORTME: 1=EBCDIC, 2=7-bit ASCII, 3=8-bit ASCII, 4=DEC Kanji. */
691 rec_7.rec_type_4 = 7;
693 rec_7.data_type_4 = sizeof (flt64);
695 rec_7.elem_4[0] = -FLT64_MAX;
696 rec_7.elem_4[1] = FLT64_MAX;
697 rec_7.elem_4[2] = second_lowest_flt64;
699 buf_write (w, &rec_7, sizeof rec_7);
702 /* Write NBYTES starting at BUF to the system file represented by
705 buf_write (struct sfm_writer *w, const void *buf, size_t nbytes)
707 assert (buf != NULL);
708 fwrite (buf, nbytes, 1, w->file);
711 /* Copies string DEST to SRC with the proviso that DEST does not reach
712 byte END; no null terminator is copied. Returns a pointer to the
713 byte after the last byte copied. */
715 append_string_max (char *dest, const char *src, const char *end)
717 int nbytes = min (end - dest, (int) strlen (src));
718 memcpy (dest, src, nbytes);
719 return dest + nbytes;
722 /* Makes certain that the compression buffer of H has room for another
723 element. If there's not room, pads out the current instruction
724 octet with zero and dumps out the buffer. */
726 ensure_buf_space (struct sfm_writer *w)
728 if (w->ptr >= w->end)
730 memset (w->x, 0, w->y - w->x);
733 buf_write (w, w->buf, sizeof *w->buf * 128);
737 static void write_compressed_data (struct sfm_writer *w, const flt64 *elem);
739 /* Writes case C to system file W.
740 Returns 1 if successful, 0 if an I/O error occurred. */
742 sfm_write_case (struct sfm_writer *w, const struct ccase *c)
744 if (ferror (w->file))
749 if (!w->needs_translation && !w->compress
750 && sizeof (flt64) == sizeof (union value))
752 /* Fast path: external and internal representations are the
753 same and the dictionary is properly ordered. Write
755 buf_write (w, case_data_all (c), sizeof (union value) * w->flt64_cnt);
759 /* Slow path: internal and external representations differ.
760 Write into a bounce buffer, then write to W. */
766 bounce_size = sizeof *bounce * w->flt64_cnt;
767 bounce = bounce_cur = local_alloc (bounce_size);
769 for (i = 0; i < w->var_cnt; i++)
771 struct sfm_var *v = &w->vars[i];
774 *bounce_cur = case_num (c, v->fv);
776 memcpy (bounce_cur, case_data (c, v->fv)->s, v->width);
777 bounce_cur += v->flt64_cnt;
781 buf_write (w, bounce, bounce_size);
783 write_compressed_data (w, bounce);
788 return !sfm_write_error (w);
792 put_instruction (struct sfm_writer *w, unsigned char instruction)
796 ensure_buf_space (w);
797 w->x = (unsigned char *) w->ptr++;
798 w->y = (unsigned char *) w->ptr;
800 *w->x++ = instruction;
804 put_element (struct sfm_writer *w, const flt64 *elem)
806 ensure_buf_space (w);
807 memcpy (w->ptr++, elem, sizeof *elem);
811 write_compressed_data (struct sfm_writer *w, const flt64 *elem)
815 for (i = 0; i < w->var_cnt; i++)
817 struct sfm_var *v = &w->vars[i];
821 if (*elem == -FLT64_MAX)
822 put_instruction (w, 255);
823 else if (*elem >= 1 - COMPRESSION_BIAS
824 && *elem <= 251 - COMPRESSION_BIAS
825 && *elem == (int) *elem)
826 put_instruction (w, (int) *elem + COMPRESSION_BIAS);
829 put_instruction (w, 253);
830 put_element (w, elem);
838 for (j = 0; j < v->flt64_cnt; j++, elem++)
840 if (!memcmp (elem, " ", sizeof (flt64)))
841 put_instruction (w, 254);
844 put_instruction (w, 253);
845 put_element (w, elem);
852 /* Returns true if an I/O error has occurred on WRITER, false otherwise. */
854 sfm_write_error (const struct sfm_writer *writer)
856 return ferror (writer->file);
859 /* Closes a system file after we're done with it.
860 Returns true if successful, false if an I/O error occurred. */
862 sfm_close_writer (struct sfm_writer *w)
873 if (w->buf != NULL && w->ptr > w->buf)
875 memset (w->x, 0, w->y - w->x);
876 buf_write (w, w->buf, (w->ptr - w->buf) * sizeof *w->buf);
880 ok = !sfm_write_error (w);
882 /* Seek back to the beginning and update the number of cases.
883 This is just a courtesy to later readers, so there's no need
884 to check return values or report errors. */
885 if (ok && !fseek (w->file, offsetof (struct sysfile_header, case_cnt),
888 int32 case_cnt = w->case_cnt;
889 fwrite (&case_cnt, sizeof case_cnt, 1, w->file);
893 if (fclose (w->file) == EOF)
897 msg (ME, _("An I/O error occurred writing system file \"%s\"."),
898 fh_get_filename (w->fh));
901 fh_close (w->fh, "system file", "we");