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"
31 #include <unistd.h> /* Required by SunOS4. */
35 #include "dictionary.h"
37 #include "file-handle-def.h"
42 #include "stat-macros.h"
44 #include "value-labels.h"
49 #define _(msgid) gettext (msgid)
51 #include "debug-print.h"
53 /* Compression bias used by PSPP. Values between (1 -
54 COMPRESSION_BIAS) and (251 - COMPRESSION_BIAS) inclusive can be
56 #define COMPRESSION_BIAS 100
58 /* System file writer. */
61 struct file_handle *fh; /* File handle. */
62 FILE *file; /* File stream. */
64 int needs_translation; /* 0=use fast path, 1=translation needed. */
65 int compress; /* 1=compressed, 0=not compressed. */
66 int case_cnt; /* Number of cases written so far. */
67 size_t flt64_cnt; /* Number of flt64 elements in case. */
69 /* Compression buffering. */
70 flt64 *buf; /* Buffered data. */
71 flt64 *end; /* Buffer end. */
72 flt64 *ptr; /* Current location in buffer. */
73 unsigned char *x; /* Location in current instruction octet. */
74 unsigned char *y; /* End of instruction octet. */
77 struct sfm_var *vars; /* Variables. */
78 size_t var_cnt; /* Number of variables. */
81 /* A variable in a system file. */
84 int width; /* 0=numeric, otherwise string width. */
85 int fv; /* Index into case. */
86 size_t flt64_cnt; /* Number of flt64 elements. */
89 static char *append_string_max (char *, const char *, const char *);
90 static void write_header (struct sfm_writer *, const struct dictionary *);
91 static void buf_write (struct sfm_writer *, const void *, size_t);
92 static void write_variable (struct sfm_writer *, struct variable *);
93 static void write_value_labels (struct sfm_writer *,
94 struct variable *, int idx);
95 static void write_rec_7_34 (struct sfm_writer *);
97 static void write_longvar_table (struct sfm_writer *w,
98 const struct dictionary *dict);
100 static void write_variable_display_parameters (struct sfm_writer *w,
101 const struct dictionary *dict);
103 static void write_documents (struct sfm_writer *, const struct dictionary *);
104 static int does_dict_need_translation (const struct dictionary *);
107 var_flt64_cnt (const struct variable *v)
109 return v->type == NUMERIC ? 1 : DIV_RND_UP (v->width, sizeof (flt64));
112 /* Returns default options for writing a system file. */
113 struct sfm_write_options
114 sfm_writer_default_options (void)
116 struct sfm_write_options opts;
117 opts.create_writeable = true;
118 opts.compress = get_scompression ();
123 /* Opens the system file designated by file handle FH for writing
124 cases from dictionary D according to the given OPTS. If
125 COMPRESS is nonzero, the system file will be compressed.
127 No reference to D is retained, so it may be modified or
128 destroyed at will after this function returns. D is not
129 modified by this function, except to assign short names. */
131 sfm_open_writer (struct file_handle *fh, struct dictionary *d,
132 struct sfm_write_options opts)
134 struct sfm_writer *w = NULL;
141 if (opts.version != 2 && opts.version != 3)
143 msg (ME, _("Unknown system file version %d. Treating as version %d."),
149 mode = S_IRUSR | S_IRGRP | S_IROTH;
150 if (opts.create_writeable)
151 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
152 fd = open (fh_get_filename (fh), O_WRONLY | O_CREAT | O_TRUNC, mode);
156 /* Open file handle. */
157 if (!fh_open (fh, FH_REF_FILE, "system file", "we"))
160 /* Create and initialize writer. */
161 w = xmalloc (sizeof *w);
163 w->file = fdopen (fd, "w");
165 w->needs_translation = does_dict_need_translation (d);
166 w->compress = opts.compress;
170 w->buf = w->end = w->ptr = NULL;
173 w->var_cnt = dict_get_var_cnt (d);
174 w->vars = xnmalloc (w->var_cnt, sizeof *w->vars);
175 for (i = 0; i < w->var_cnt; i++)
177 const struct variable *dv = dict_get_var (d, i);
178 struct sfm_var *sv = &w->vars[i];
179 sv->width = dv->width;
181 sv->flt64_cnt = var_flt64_cnt (dv);
184 /* Check that file create succeeded. */
191 /* Write the file header. */
194 /* Write basic variable info. */
195 dict_assign_short_names (d);
196 for (i = 0; i < dict_get_var_cnt (d); i++)
197 write_variable (w, dict_get_var (d, i));
199 /* Write out value labels. */
200 for (idx = i = 0; i < dict_get_var_cnt (d); i++)
202 struct variable *v = dict_get_var (d, i);
204 write_value_labels (w, v, idx);
205 idx += var_flt64_cnt (v);
208 if (dict_get_documents (d) != NULL)
209 write_documents (w, d);
213 write_variable_display_parameters (w, d);
215 if (opts.version >= 3)
216 write_longvar_table (w, d);
218 /* Write end-of-headers record. */
227 rec_999.rec_type = 999;
230 buf_write (w, &rec_999, sizeof rec_999);
235 w->buf = xnmalloc (128, sizeof *w->buf);
237 w->end = &w->buf[128];
238 w->x = (unsigned char *) w->ptr++;
239 w->y = (unsigned char *) w->ptr;
242 if (sfm_write_error (w))
248 sfm_close_writer (w);
252 msg (ME, _("Error opening \"%s\" for writing as a system file: %s."),
253 fh_get_filename (fh), strerror (errno));
258 does_dict_need_translation (const struct dictionary *d)
264 for (i = 0; i < dict_get_var_cnt (d); i++)
266 struct variable *v = dict_get_var (d, i);
267 if (v->fv != case_idx)
274 /* Returns value of X truncated to two least-significant digits. */
285 /* Write the sysfile_header header to system file W. */
287 write_header (struct sfm_writer *w, const struct dictionary *d)
289 struct sysfile_header hdr;
295 memcpy (hdr.rec_type, "$FL2", 4);
297 p = stpcpy (hdr.prod_name, "@(#) SPSS DATA FILE ");
298 p = append_string_max (p, version, &hdr.prod_name[60]);
299 p = append_string_max (p, " - ", &hdr.prod_name[60]);
300 p = append_string_max (p, host_system, &hdr.prod_name[60]);
301 memset (p, ' ', &hdr.prod_name[60] - p);
306 for (i = 0; i < dict_get_var_cnt (d); i++)
307 w->flt64_cnt += var_flt64_cnt (dict_get_var (d, i));
308 hdr.case_size = w->flt64_cnt;
310 hdr.compress = w->compress;
312 if (dict_get_weight (d) != NULL)
314 struct variable *weight_var;
315 int recalc_weight_idx = 1;
318 weight_var = dict_get_weight (d);
321 struct variable *v = dict_get_var (d, i);
324 recalc_weight_idx += var_flt64_cnt (v);
326 hdr.weight_idx = recalc_weight_idx;
332 hdr.bias = COMPRESSION_BIAS;
334 if (time (&t) == (time_t) -1)
336 memcpy (hdr.creation_date, "01 Jan 70", 9);
337 memcpy (hdr.creation_time, "00:00:00", 8);
341 static const char *month_name[12] =
343 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
344 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
346 struct tm *tmp = localtime (&t);
347 int day = rerange (tmp->tm_mday);
348 int mon = rerange (tmp->tm_mon + 1);
349 int year = rerange (tmp->tm_year);
350 int hour = rerange (tmp->tm_hour + 1);
351 int min = rerange (tmp->tm_min + 1);
352 int sec = rerange (tmp->tm_sec + 1);
355 sprintf (buf, "%02d %s %02d", day, month_name[mon - 1], year);
356 memcpy (hdr.creation_date, buf, sizeof hdr.creation_date);
357 sprintf (buf, "%02d:%02d:%02d", hour - 1, min - 1, sec - 1);
358 memcpy (hdr.creation_time, buf, sizeof hdr.creation_time);
362 const char *label = dict_get_label (d);
366 buf_copy_str_rpad (hdr.file_label, sizeof hdr.file_label, label);
369 memset (hdr.padding, 0, sizeof hdr.padding);
371 buf_write (w, &hdr, sizeof hdr);
374 /* Translates format spec from internal form in SRC to system file
377 write_format_spec (struct fmt_spec *src, int32 *dest)
379 *dest = (formats[src->type].spss << 16) | (src->w << 8) | src->d;
382 /* Write the variable record(s) for primary variable P and secondary
383 variable S to system file W. */
385 write_variable (struct sfm_writer *w, struct variable *v)
387 struct sysfile_variable sv;
389 /* Missing values. */
390 struct missing_values mv;
391 flt64 m[3]; /* Missing value values. */
392 int nm; /* Number of missing values, possibly negative. */
396 sv.has_var_label = (v->label != NULL);
398 mv_copy (&mv, &v->miss);
400 if (mv_has_range (&mv))
403 mv_pop_range (&mv, &x, &y);
404 m[nm++] = x == LOWEST ? second_lowest_flt64 : x;
405 m[nm++] = y == HIGHEST ? FLT64_MAX : y;
407 while (mv_has_value (&mv))
410 mv_pop_value (&mv, &value);
411 if (v->type == NUMERIC)
414 buf_copy_rpad ((char *) &m[nm], sizeof m[nm], value.s, v->width);
417 if (mv_has_range (&v->miss))
420 sv.n_missing_values = nm;
421 write_format_spec (&v->print, &sv.print);
422 write_format_spec (&v->write, &sv.write);
423 buf_copy_str_rpad (sv.name, sizeof sv.name, v->short_name);
424 buf_write (w, &sv, sizeof sv);
437 l.label_len = min (strlen (v->label), 255);
438 ext_len = ROUND_UP (l.label_len, sizeof l.label_len);
439 memcpy (l.label, v->label, l.label_len);
440 memset (&l.label[l.label_len], ' ', ext_len - l.label_len);
442 buf_write (w, &l, offsetof (struct label, label) + ext_len);
446 buf_write (w, m, sizeof *m * abs (nm));
448 if (v->type == ALPHA && v->width > (int) sizeof (flt64))
454 sv.has_var_label = 0;
455 sv.n_missing_values = 0;
456 memset (&sv.print, 0, sizeof sv.print);
457 memset (&sv.write, 0, sizeof sv.write);
458 memset (&sv.name, 0, sizeof sv.name);
460 pad_count = DIV_RND_UP (v->width, (int) sizeof (flt64)) - 1;
461 for (i = 0; i < pad_count; i++)
462 buf_write (w, &sv, sizeof sv);
466 /* Writes the value labels for variable V having system file
467 variable index IDX to system file W. */
469 write_value_labels (struct sfm_writer *w, struct variable *v, int idx)
471 struct value_label_rec
485 struct val_labs_iterator *i;
486 struct value_label_rec *vlr;
487 struct var_idx_rec vir;
492 if (!val_labs_count (v->val_labs))
495 /* Pass 1: Count bytes. */
496 vlr_size = (sizeof (struct value_label_rec)
497 + sizeof (flt64) * (val_labs_count (v->val_labs) - 1));
498 for (vl = val_labs_first (v->val_labs, &i); vl != NULL;
499 vl = val_labs_next (v->val_labs, &i))
500 vlr_size += ROUND_UP (strlen (vl->label) + 1, sizeof (flt64));
502 /* Pass 2: Copy bytes. */
503 vlr = xmalloc (vlr_size);
505 vlr->n_labels = val_labs_count (v->val_labs);
507 for (vl = val_labs_first_sorted (v->val_labs, &i); vl != NULL;
508 vl = val_labs_next (v->val_labs, &i))
510 size_t len = strlen (vl->label);
512 *loc++ = vl->value.f;
513 *(unsigned char *) loc = len;
514 memcpy (&((char *) loc)[1], vl->label, len);
515 memset (&((char *) loc)[1 + len], ' ',
516 REM_RND_UP (len + 1, sizeof (flt64)));
517 loc += DIV_RND_UP (len + 1, sizeof (flt64));
520 buf_write (w, vlr, vlr_size);
525 vir.vars[0] = idx + 1;
526 buf_write (w, &vir, sizeof vir);
529 /* Writes record type 6, document record. */
531 write_documents (struct sfm_writer *w, const struct dictionary *d)
535 int32 rec_type P; /* Always 6. */
536 int32 n_lines P; /* Number of lines of documents. */
540 const char *documents;
543 documents = dict_get_documents (d);
544 n_lines = strlen (documents) / 80;
547 rec_6.n_lines = n_lines;
548 buf_write (w, &rec_6, sizeof rec_6);
549 buf_write (w, documents, 80 * n_lines);
552 /* Write the alignment, width and scale values */
554 write_variable_display_parameters (struct sfm_writer *w,
555 const struct dictionary *dict)
567 vdp_hdr.rec_type = 7;
568 vdp_hdr.subtype = 11;
569 vdp_hdr.elem_size = 4;
570 vdp_hdr.n_elem = w->var_cnt * 3;
572 buf_write (w, &vdp_hdr, sizeof vdp_hdr);
574 for ( i = 0 ; i < w->var_cnt ; ++i )
585 v = dict_get_var(dict, i);
587 params.measure = v->measure;
588 params.width = v->display_width;
589 params.align = v->alignment;
591 buf_write (w, ¶ms, sizeof(params));
595 /* Writes the long variable name table */
597 write_longvar_table (struct sfm_writer *w, const struct dictionary *dict)
608 struct string long_name_map;
611 ds_init (&long_name_map, 10 * dict_get_var_cnt (dict));
612 for (i = 0; i < dict_get_var_cnt (dict); i++)
614 struct variable *v = dict_get_var (dict, i);
617 ds_putc (&long_name_map, '\t');
618 ds_printf (&long_name_map, "%s=%s", v->short_name, v->name);
623 lv_hdr.elem_size = 1;
624 lv_hdr.n_elem = ds_length (&long_name_map);
626 buf_write (w, &lv_hdr, sizeof lv_hdr);
627 buf_write (w, ds_data (&long_name_map), ds_length (&long_name_map));
629 ds_destroy (&long_name_map);
632 /* Writes record type 7, subtypes 3 and 4. */
634 write_rec_7_34 (struct sfm_writer *w)
651 /* Components of the version number, from major to minor. */
652 int version_component[3];
654 /* Used to step through the version string. */
657 /* Parses the version string, which is assumed to be of the form
658 #.#x, where each # is a string of digits, and x is a single
660 version_component[0] = strtol (bare_version, &p, 10);
663 version_component[1] = strtol (bare_version, &p, 10);
664 version_component[2] = (isalpha ((unsigned char) *p)
665 ? tolower ((unsigned char) *p) - 'a' : 0);
667 rec_7.rec_type_3 = 7;
669 rec_7.data_type_3 = sizeof (int32);
671 rec_7.elem_3[0] = version_component[0];
672 rec_7.elem_3[1] = version_component[1];
673 rec_7.elem_3[2] = version_component[2];
674 rec_7.elem_3[3] = -1;
676 /* PORTME: 1=IEEE754, 2=IBM 370, 3=DEC VAX E. */
683 /* PORTME: 1=big-endian, 2=little-endian. */
690 /* PORTME: 1=EBCDIC, 2=7-bit ASCII, 3=8-bit ASCII, 4=DEC Kanji. */
693 rec_7.rec_type_4 = 7;
695 rec_7.data_type_4 = sizeof (flt64);
697 rec_7.elem_4[0] = -FLT64_MAX;
698 rec_7.elem_4[1] = FLT64_MAX;
699 rec_7.elem_4[2] = second_lowest_flt64;
701 buf_write (w, &rec_7, sizeof rec_7);
704 /* Write NBYTES starting at BUF to the system file represented by
707 buf_write (struct sfm_writer *w, const void *buf, size_t nbytes)
709 assert (buf != NULL);
710 fwrite (buf, nbytes, 1, w->file);
713 /* Copies string DEST to SRC with the proviso that DEST does not reach
714 byte END; no null terminator is copied. Returns a pointer to the
715 byte after the last byte copied. */
717 append_string_max (char *dest, const char *src, const char *end)
719 int nbytes = min (end - dest, (int) strlen (src));
720 memcpy (dest, src, nbytes);
721 return dest + nbytes;
724 /* Makes certain that the compression buffer of H has room for another
725 element. If there's not room, pads out the current instruction
726 octet with zero and dumps out the buffer. */
728 ensure_buf_space (struct sfm_writer *w)
730 if (w->ptr >= w->end)
732 memset (w->x, 0, w->y - w->x);
735 buf_write (w, w->buf, sizeof *w->buf * 128);
739 static void write_compressed_data (struct sfm_writer *w, const flt64 *elem);
741 /* Writes case C to system file W.
742 Returns 1 if successful, 0 if an I/O error occurred. */
744 sfm_write_case (struct sfm_writer *w, const struct ccase *c)
746 if (ferror (w->file))
751 if (!w->needs_translation && !w->compress
752 && sizeof (flt64) == sizeof (union value))
754 /* Fast path: external and internal representations are the
755 same and the dictionary is properly ordered. Write
757 buf_write (w, case_data_all (c), sizeof (union value) * w->flt64_cnt);
761 /* Slow path: internal and external representations differ.
762 Write into a bounce buffer, then write to W. */
768 bounce_size = sizeof *bounce * w->flt64_cnt;
769 bounce = bounce_cur = local_alloc (bounce_size);
771 for (i = 0; i < w->var_cnt; i++)
773 struct sfm_var *v = &w->vars[i];
776 *bounce_cur = case_num (c, v->fv);
778 memcpy (bounce_cur, case_data (c, v->fv)->s, v->width);
779 bounce_cur += v->flt64_cnt;
783 buf_write (w, bounce, bounce_size);
785 write_compressed_data (w, bounce);
790 return !sfm_write_error (w);
794 put_instruction (struct sfm_writer *w, unsigned char instruction)
798 ensure_buf_space (w);
799 w->x = (unsigned char *) w->ptr++;
800 w->y = (unsigned char *) w->ptr;
802 *w->x++ = instruction;
806 put_element (struct sfm_writer *w, const flt64 *elem)
808 ensure_buf_space (w);
809 memcpy (w->ptr++, elem, sizeof *elem);
813 write_compressed_data (struct sfm_writer *w, const flt64 *elem)
817 for (i = 0; i < w->var_cnt; i++)
819 struct sfm_var *v = &w->vars[i];
823 if (*elem == -FLT64_MAX)
824 put_instruction (w, 255);
825 else if (*elem >= 1 - COMPRESSION_BIAS
826 && *elem <= 251 - COMPRESSION_BIAS
827 && *elem == (int) *elem)
828 put_instruction (w, (int) *elem + COMPRESSION_BIAS);
831 put_instruction (w, 253);
832 put_element (w, elem);
840 for (j = 0; j < v->flt64_cnt; j++, elem++)
842 if (!memcmp (elem, " ", sizeof (flt64)))
843 put_instruction (w, 254);
846 put_instruction (w, 253);
847 put_element (w, elem);
854 /* Returns true if an I/O error has occurred on WRITER, false otherwise. */
856 sfm_write_error (const struct sfm_writer *writer)
858 return ferror (writer->file);
861 /* Closes a system file after we're done with it.
862 Returns true if successful, false if an I/O error occurred. */
864 sfm_close_writer (struct sfm_writer *w)
875 if (w->buf != NULL && w->ptr > w->buf)
877 memset (w->x, 0, w->y - w->x);
878 buf_write (w, w->buf, (w->ptr - w->buf) * sizeof *w->buf);
882 ok = !sfm_write_error (w);
884 /* Seek back to the beginning and update the number of cases.
885 This is just a courtesy to later readers, so there's no need
886 to check return values or report errors. */
887 if (ok && !fseek (w->file, offsetof (struct sysfile_header, case_cnt),
890 int32 case_cnt = w->case_cnt;
891 fwrite (&case_cnt, sizeof case_cnt, 1, w->file);
895 if (fclose (w->file) == EOF)
899 msg (ME, _("An I/O error occurred writing system file \"%s\"."),
900 fh_get_filename (w->fh));
903 fh_close (w->fh, "system file", "we");