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 "sfm-write.h"
31 #include <unistd.h> /* Required by SunOS4. */
35 #include "dictionary.h"
37 #include "file-handle.h"
43 #include "stat-macros.h"
45 #include "value-labels.h"
50 #define _(msgid) gettext (msgid)
52 #include "debug-print.h"
54 /* Compression bias used by PSPP. Values between (1 -
55 COMPRESSION_BIAS) and (251 - COMPRESSION_BIAS) inclusive can be
57 #define COMPRESSION_BIAS 100
59 /* System file writer. */
62 struct file_handle *fh; /* File handle. */
63 FILE *file; /* File stream. */
65 int needs_translation; /* 0=use fast path, 1=translation needed. */
66 int compress; /* 1=compressed, 0=not compressed. */
67 int case_cnt; /* Number of cases written so far. */
68 size_t flt64_cnt; /* Number of flt64 elements in case. */
70 /* Compression buffering. */
71 flt64 *buf; /* Buffered data. */
72 flt64 *end; /* Buffer end. */
73 flt64 *ptr; /* Current location in buffer. */
74 unsigned char *x; /* Location in current instruction octet. */
75 unsigned char *y; /* End of instruction octet. */
78 struct sfm_var *vars; /* Variables. */
79 size_t var_cnt; /* Number of variables. */
82 /* A variable in a system file. */
85 int width; /* 0=numeric, otherwise string width. */
86 int fv; /* Index into case. */
87 size_t flt64_cnt; /* Number of flt64 elements. */
90 static char *append_string_max (char *, const char *, const char *);
91 static int write_header (struct sfm_writer *, const struct dictionary *);
92 static int buf_write (struct sfm_writer *, const void *, size_t);
93 static int write_variable (struct sfm_writer *, struct variable *);
94 static int write_value_labels (struct sfm_writer *,
95 struct variable *, int idx);
96 static int write_rec_7_34 (struct sfm_writer *);
98 static int write_longvar_table (struct sfm_writer *w,
99 const struct dictionary *dict);
101 static int write_variable_display_parameters (struct sfm_writer *w,
102 const struct dictionary *dict);
105 static int write_documents (struct sfm_writer *, const struct dictionary *);
106 static int does_dict_need_translation (const struct dictionary *);
109 var_flt64_cnt (const struct variable *v)
111 return v->type == NUMERIC ? 1 : DIV_RND_UP (v->width, sizeof (flt64));
114 /* Returns default options for writing a system file. */
115 struct sfm_write_options
116 sfm_writer_default_options (void)
118 struct sfm_write_options opts;
119 opts.create_writeable = true;
120 opts.compress = get_scompression ();
125 /* Opens the system file designated by file handle FH for writing
126 cases from dictionary D according to the given OPTS. If
127 COMPRESS is nonzero, the system file will be compressed.
129 No reference to D is retained, so it may be modified or
130 destroyed at will after this function returns. D is not
131 modified by this function, except to assign short names. */
133 sfm_open_writer (struct file_handle *fh, struct dictionary *d,
134 struct sfm_write_options opts)
136 struct sfm_writer *w = NULL;
143 if (opts.version != 2 && opts.version != 3)
145 msg (ME, _("Unknown system file version %d. Treating as version %d."),
151 mode = S_IRUSR | S_IRGRP | S_IROTH;
152 if (opts.create_writeable)
153 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
154 fd = open (fh_get_filename (fh), O_WRONLY | O_CREAT | O_TRUNC, mode);
158 /* Open file handle. */
159 if (!fh_open (fh, "system file", "we"))
162 /* Create and initialize writer. */
163 w = xmalloc (sizeof *w);
165 w->file = fdopen (fd, "w");
167 w->needs_translation = does_dict_need_translation (d);
168 w->compress = opts.compress;
172 w->buf = w->end = w->ptr = NULL;
175 w->var_cnt = dict_get_var_cnt (d);
176 w->vars = xnmalloc (w->var_cnt, sizeof *w->vars);
177 for (i = 0; i < w->var_cnt; i++)
179 const struct variable *dv = dict_get_var (d, i);
180 struct sfm_var *sv = &w->vars[i];
181 sv->width = dv->width;
183 sv->flt64_cnt = var_flt64_cnt (dv);
186 /* Check that file create succeeded. */
193 /* Write the file header. */
194 if (!write_header (w, d))
197 /* Write basic variable info. */
198 dict_assign_short_names (d);
199 for (i = 0; i < dict_get_var_cnt (d); i++)
200 write_variable (w, dict_get_var (d, i));
202 /* Write out value labels. */
203 for (idx = i = 0; i < dict_get_var_cnt (d); i++)
205 struct variable *v = dict_get_var (d, i);
207 if (!write_value_labels (w, v, idx))
209 idx += var_flt64_cnt (v);
212 if (dict_get_documents (d) != NULL && !write_documents (w, d))
215 if (!write_rec_7_34 (w))
218 if (!write_variable_display_parameters (w, d))
221 if (opts.version >= 3)
223 if (!write_longvar_table (w, d))
227 /* Write end-of-headers record. */
236 rec_999.rec_type = 999;
239 if (!buf_write (w, &rec_999, sizeof rec_999))
245 w->buf = xnmalloc (128, sizeof *w->buf);
247 w->end = &w->buf[128];
248 w->x = (unsigned char *) w->ptr++;
249 w->y = (unsigned char *) w->ptr;
255 sfm_close_writer (w);
259 msg (ME, _("Error opening \"%s\" for writing as a system file: %s."),
260 fh_get_filename (w->fh), strerror (errno));
266 does_dict_need_translation (const struct dictionary *d)
272 for (i = 0; i < dict_get_var_cnt (d); i++)
274 struct variable *v = dict_get_var (d, i);
275 if (v->fv != case_idx)
282 /* Returns value of X truncated to two least-significant digits. */
293 /* Write the sysfile_header header to system file W. */
295 write_header (struct sfm_writer *w, const struct dictionary *d)
297 struct sysfile_header hdr;
303 memcpy (hdr.rec_type, "$FL2", 4);
305 p = stpcpy (hdr.prod_name, "@(#) SPSS DATA FILE ");
306 p = append_string_max (p, version, &hdr.prod_name[60]);
307 p = append_string_max (p, " - ", &hdr.prod_name[60]);
308 p = append_string_max (p, host_system, &hdr.prod_name[60]);
309 memset (p, ' ', &hdr.prod_name[60] - p);
314 for (i = 0; i < dict_get_var_cnt (d); i++)
315 w->flt64_cnt += var_flt64_cnt (dict_get_var (d, i));
316 hdr.case_size = w->flt64_cnt;
318 hdr.compress = w->compress;
320 if (dict_get_weight (d) != NULL)
322 struct variable *weight_var;
323 int recalc_weight_idx = 1;
326 weight_var = dict_get_weight (d);
329 struct variable *v = dict_get_var (d, i);
332 recalc_weight_idx += var_flt64_cnt (v);
334 hdr.weight_idx = recalc_weight_idx;
340 hdr.bias = COMPRESSION_BIAS;
342 if (time (&t) == (time_t) -1)
344 memcpy (hdr.creation_date, "01 Jan 70", 9);
345 memcpy (hdr.creation_time, "00:00:00", 8);
349 static const char *month_name[12] =
351 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
352 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
354 struct tm *tmp = localtime (&t);
355 int day = rerange (tmp->tm_mday);
356 int mon = rerange (tmp->tm_mon + 1);
357 int year = rerange (tmp->tm_year);
358 int hour = rerange (tmp->tm_hour + 1);
359 int min = rerange (tmp->tm_min + 1);
360 int sec = rerange (tmp->tm_sec + 1);
363 sprintf (buf, "%02d %s %02d", day, month_name[mon - 1], year);
364 memcpy (hdr.creation_date, buf, sizeof hdr.creation_date);
365 sprintf (buf, "%02d:%02d:%02d", hour - 1, min - 1, sec - 1);
366 memcpy (hdr.creation_time, buf, sizeof hdr.creation_time);
370 const char *label = dict_get_label (d);
374 buf_copy_str_rpad (hdr.file_label, sizeof hdr.file_label, label);
377 memset (hdr.padding, 0, sizeof hdr.padding);
379 if (!buf_write (w, &hdr, sizeof hdr))
384 /* Translates format spec from internal form in SRC to system file
387 write_format_spec (struct fmt_spec *src, int32 *dest)
389 *dest = (formats[src->type].spss << 16) | (src->w << 8) | src->d;
392 /* Write the variable record(s) for primary variable P and secondary
393 variable S to system file W. */
395 write_variable (struct sfm_writer *w, struct variable *v)
397 struct sysfile_variable sv;
399 /* Missing values. */
400 struct missing_values mv;
401 flt64 m[3]; /* Missing value values. */
402 int nm; /* Number of missing values, possibly negative. */
406 sv.has_var_label = (v->label != NULL);
408 mv_copy (&mv, &v->miss);
410 if (mv_has_range (&mv))
413 mv_pop_range (&mv, &x, &y);
414 m[nm++] = x == LOWEST ? second_lowest_flt64 : x;
415 m[nm++] = y == HIGHEST ? FLT64_MAX : y;
417 while (mv_has_value (&mv))
420 mv_pop_value (&mv, &value);
421 if (v->type == NUMERIC)
424 buf_copy_rpad ((char *) &m[nm], sizeof m[nm], value.s, v->width);
427 if (mv_has_range (&v->miss))
430 sv.n_missing_values = nm;
431 write_format_spec (&v->print, &sv.print);
432 write_format_spec (&v->write, &sv.write);
433 buf_copy_str_rpad (sv.name, sizeof sv.name, v->short_name);
434 if (!buf_write (w, &sv, sizeof sv))
448 l.label_len = min (strlen (v->label), 255);
449 ext_len = ROUND_UP (l.label_len, sizeof l.label_len);
450 memcpy (l.label, v->label, l.label_len);
451 memset (&l.label[l.label_len], ' ', ext_len - l.label_len);
453 if (!buf_write (w, &l, offsetof (struct label, label) + ext_len))
457 if (nm && !buf_write (w, m, sizeof *m * abs (nm)))
460 if (v->type == ALPHA && v->width > (int) sizeof (flt64))
466 sv.has_var_label = 0;
467 sv.n_missing_values = 0;
468 memset (&sv.print, 0, sizeof sv.print);
469 memset (&sv.write, 0, sizeof sv.write);
470 memset (&sv.name, 0, sizeof sv.name);
472 pad_count = DIV_RND_UP (v->width, (int) sizeof (flt64)) - 1;
473 for (i = 0; i < pad_count; i++)
474 if (!buf_write (w, &sv, sizeof sv))
481 /* Writes the value labels for variable V having system file variable
482 index IDX to system file W. Returns
483 nonzero only if successful. */
485 write_value_labels (struct sfm_writer *w, struct variable *v, int idx)
487 struct value_label_rec
501 struct val_labs_iterator *i;
502 struct value_label_rec *vlr;
503 struct var_idx_rec vir;
508 if (!val_labs_count (v->val_labs))
511 /* Pass 1: Count bytes. */
512 vlr_size = (sizeof (struct value_label_rec)
513 + sizeof (flt64) * (val_labs_count (v->val_labs) - 1));
514 for (vl = val_labs_first (v->val_labs, &i); vl != NULL;
515 vl = val_labs_next (v->val_labs, &i))
516 vlr_size += ROUND_UP (strlen (vl->label) + 1, sizeof (flt64));
518 /* Pass 2: Copy bytes. */
519 vlr = xmalloc (vlr_size);
521 vlr->n_labels = val_labs_count (v->val_labs);
523 for (vl = val_labs_first_sorted (v->val_labs, &i); vl != NULL;
524 vl = val_labs_next (v->val_labs, &i))
526 size_t len = strlen (vl->label);
528 *loc++ = vl->value.f;
529 *(unsigned char *) loc = len;
530 memcpy (&((char *) loc)[1], vl->label, len);
531 memset (&((char *) loc)[1 + len], ' ',
532 REM_RND_UP (len + 1, sizeof (flt64)));
533 loc += DIV_RND_UP (len + 1, sizeof (flt64));
536 if (!buf_write (w, vlr, vlr_size))
545 vir.vars[0] = idx + 1;
546 if (!buf_write (w, &vir, sizeof vir))
552 /* Writes record type 6, document record. */
554 write_documents (struct sfm_writer *w, const struct dictionary *d)
558 int32 rec_type P; /* Always 6. */
559 int32 n_lines P; /* Number of lines of documents. */
563 const char *documents;
566 documents = dict_get_documents (d);
567 n_lines = strlen (documents) / 80;
570 rec_6.n_lines = n_lines;
571 if (!buf_write (w, &rec_6, sizeof rec_6))
573 if (!buf_write (w, documents, 80 * n_lines))
579 /* Write the alignment, width and scale values */
581 write_variable_display_parameters (struct sfm_writer *w,
582 const struct dictionary *dict)
594 vdp_hdr.rec_type = 7;
595 vdp_hdr.subtype = 11;
596 vdp_hdr.elem_size = 4;
597 vdp_hdr.n_elem = w->var_cnt * 3;
599 if (!buf_write (w, &vdp_hdr, sizeof vdp_hdr))
602 for ( i = 0 ; i < w->var_cnt ; ++i )
613 v = dict_get_var(dict, i);
615 params.measure = v->measure;
616 params.width = v->display_width;
617 params.align = v->alignment;
619 if (!buf_write (w, ¶ms, sizeof(params)))
626 /* Writes the long variable name table */
628 write_longvar_table (struct sfm_writer *w, const struct dictionary *dict)
639 struct string long_name_map;
642 ds_init (&long_name_map, 10 * dict_get_var_cnt (dict));
643 for (i = 0; i < dict_get_var_cnt (dict); i++)
645 struct variable *v = dict_get_var (dict, i);
648 ds_putc (&long_name_map, '\t');
649 ds_printf (&long_name_map, "%s=%s", v->short_name, v->name);
654 lv_hdr.elem_size = 1;
655 lv_hdr.n_elem = ds_length (&long_name_map);
657 if (!buf_write (w, &lv_hdr, sizeof lv_hdr)
658 || !buf_write (w, ds_data (&long_name_map), ds_length (&long_name_map)))
661 ds_destroy (&long_name_map);
665 ds_destroy (&long_name_map);
669 /* Writes record type 7, subtypes 3 and 4. */
671 write_rec_7_34 (struct sfm_writer *w)
688 /* Components of the version number, from major to minor. */
689 int version_component[3];
691 /* Used to step through the version string. */
694 /* Parses the version string, which is assumed to be of the form
695 #.#x, where each # is a string of digits, and x is a single
697 version_component[0] = strtol (bare_version, &p, 10);
700 version_component[1] = strtol (bare_version, &p, 10);
701 version_component[2] = (isalpha ((unsigned char) *p)
702 ? tolower ((unsigned char) *p) - 'a' : 0);
704 rec_7.rec_type_3 = 7;
706 rec_7.data_type_3 = sizeof (int32);
708 rec_7.elem_3[0] = version_component[0];
709 rec_7.elem_3[1] = version_component[1];
710 rec_7.elem_3[2] = version_component[2];
711 rec_7.elem_3[3] = -1;
713 /* PORTME: 1=IEEE754, 2=IBM 370, 3=DEC VAX E. */
720 /* PORTME: 1=big-endian, 2=little-endian. */
727 /* PORTME: 1=EBCDIC, 2=7-bit ASCII, 3=8-bit ASCII, 4=DEC Kanji. */
730 rec_7.rec_type_4 = 7;
732 rec_7.data_type_4 = sizeof (flt64);
734 rec_7.elem_4[0] = -FLT64_MAX;
735 rec_7.elem_4[1] = FLT64_MAX;
736 rec_7.elem_4[2] = second_lowest_flt64;
738 if (!buf_write (w, &rec_7, sizeof rec_7))
743 /* Write NBYTES starting at BUF to the system file represented by
746 buf_write (struct sfm_writer *w, const void *buf, size_t nbytes)
748 assert (buf != NULL);
749 if (fwrite (buf, nbytes, 1, w->file) != 1)
751 msg (ME, _("%s: Writing system file: %s."),
752 fh_get_filename (w->fh), strerror (errno));
758 /* Copies string DEST to SRC with the proviso that DEST does not reach
759 byte END; no null terminator is copied. Returns a pointer to the
760 byte after the last byte copied. */
762 append_string_max (char *dest, const char *src, const char *end)
764 int nbytes = min (end - dest, (int) strlen (src));
765 memcpy (dest, src, nbytes);
766 return dest + nbytes;
769 /* Makes certain that the compression buffer of H has room for another
770 element. If there's not room, pads out the current instruction
771 octet with zero and dumps out the buffer. */
773 ensure_buf_space (struct sfm_writer *w)
775 if (w->ptr >= w->end)
777 memset (w->x, 0, w->y - w->x);
780 if (!buf_write (w, w->buf, sizeof *w->buf * 128))
786 static void write_compressed_data (struct sfm_writer *w, const flt64 *elem);
788 /* Writes case C to system file W.
789 Returns nonzero if successful. */
791 sfm_write_case (struct sfm_writer *w, struct ccase *c)
795 if (!w->needs_translation && !w->compress
796 && sizeof (flt64) == sizeof (union value))
798 /* Fast path: external and internal representations are the
799 same and the dictionary is properly ordered. Write
801 buf_write (w, case_data_all (c), sizeof (union value) * w->flt64_cnt);
805 /* Slow path: internal and external representations differ.
806 Write into a bounce buffer, then write to W. */
812 bounce_size = sizeof *bounce * w->flt64_cnt;
813 bounce = bounce_cur = local_alloc (bounce_size);
815 for (i = 0; i < w->var_cnt; i++)
817 struct sfm_var *v = &w->vars[i];
820 *bounce_cur = case_num (c, v->fv);
822 memcpy (bounce_cur, case_data (c, v->fv)->s, v->width);
823 bounce_cur += v->flt64_cnt;
827 buf_write (w, bounce, bounce_size);
829 write_compressed_data (w, bounce);
838 put_instruction (struct sfm_writer *w, unsigned char instruction)
842 if (!ensure_buf_space (w))
844 w->x = (unsigned char *) w->ptr++;
845 w->y = (unsigned char *) w->ptr;
847 *w->x++ = instruction;
851 put_element (struct sfm_writer *w, const flt64 *elem)
853 if (!ensure_buf_space (w))
855 memcpy (w->ptr++, elem, sizeof *elem);
859 write_compressed_data (struct sfm_writer *w, const flt64 *elem)
863 for (i = 0; i < w->var_cnt; i++)
865 struct sfm_var *v = &w->vars[i];
869 if (*elem == -FLT64_MAX)
870 put_instruction (w, 255);
871 else if (*elem >= 1 - COMPRESSION_BIAS
872 && *elem <= 251 - COMPRESSION_BIAS
873 && *elem == (int) *elem)
874 put_instruction (w, (int) *elem + COMPRESSION_BIAS);
877 put_instruction (w, 253);
878 put_element (w, elem);
886 for (j = 0; j < v->flt64_cnt; j++, elem++)
888 if (!memcmp (elem, " ", sizeof (flt64)))
889 put_instruction (w, 254);
892 put_instruction (w, 253);
893 put_element (w, elem);
900 /* Closes a system file after we're done with it. */
902 sfm_close_writer (struct sfm_writer *w)
907 fh_close (w->fh, "system file", "we");
912 if (w->buf != NULL && w->ptr > w->buf)
914 memset (w->x, 0, w->y - w->x);
915 buf_write (w, w->buf, (w->ptr - w->buf) * sizeof *w->buf);
918 /* Seek back to the beginning and update the number of cases.
919 This is just a courtesy to later readers, so there's no need
920 to check return values or report errors. */
921 if (!fseek (w->file, offsetof (struct sysfile_header, case_cnt), SEEK_SET))
923 int32 case_cnt = w->case_cnt;
925 /* I don't really care about the return value: it doesn't
926 matter whether this data is written. */
927 fwrite (&case_cnt, sizeof case_cnt, 1, w->file);
930 if (fclose (w->file) == EOF)
931 msg (ME, _("%s: Closing system file: %s."),
932 fh_get_filename (w->fh), strerror (errno));