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"
29 #include <unistd.h> /* Required by SunOS4. */
33 #include "dictionary.h"
35 #include "file-handle.h"
41 #include "value-labels.h"
45 #include "debug-print.h"
47 /* Compression bias used by PSPP. Values between (1 -
48 COMPRESSION_BIAS) and (251 - COMPRESSION_BIAS) inclusive can be
50 #define COMPRESSION_BIAS 100
52 /* System file writer. */
55 struct file_handle *fh; /* File handle. */
56 FILE *file; /* File stream. */
58 int needs_translation; /* 0=use fast path, 1=translation needed. */
59 int compress; /* 1=compressed, 0=not compressed. */
60 int case_cnt; /* Number of cases written so far. */
61 size_t flt64_cnt; /* Number of flt64 elements in case. */
63 /* Compression buffering. */
64 flt64 *buf; /* Buffered data. */
65 flt64 *end; /* Buffer end. */
66 flt64 *ptr; /* Current location in buffer. */
67 unsigned char *x; /* Location in current instruction octet. */
68 unsigned char *y; /* End of instruction octet. */
71 struct sfm_var *vars; /* Variables. */
72 size_t var_cnt; /* Number of variables. */
75 /* A variable in a system file. */
78 int width; /* 0=numeric, otherwise string width. */
79 int fv; /* Index into case. */
80 size_t flt64_cnt; /* Number of flt64 elements. */
83 static char *append_string_max (char *, const char *, const char *);
84 static int write_header (struct sfm_writer *, const struct dictionary *);
85 static int buf_write (struct sfm_writer *, const void *, size_t);
86 static int write_variable (struct sfm_writer *, struct variable *);
87 static int write_value_labels (struct sfm_writer *,
88 struct variable *, int idx);
89 static int write_rec_7_34 (struct sfm_writer *);
91 static int write_longvar_table (struct sfm_writer *w,
92 const struct dictionary *dict);
94 static int write_variable_display_parameters (struct sfm_writer *w,
95 const struct dictionary *dict);
98 static int write_documents (struct sfm_writer *, const struct dictionary *);
99 static int does_dict_need_translation (const struct dictionary *);
102 var_flt64_cnt (const struct variable *v)
104 return v->type == NUMERIC ? 1 : DIV_RND_UP (v->width, sizeof (flt64));
107 /* Opens the system file designated by file handle FH for writing
108 cases from dictionary D. If COMPRESS is nonzero, the
109 system file will be compressed. If OMIT_LONG_NAMES is nonzero, the
110 long name table will be omitted.
112 No reference to D is retained, so it may be modified or
113 destroyed at will after this function returns. D is not
114 modified by this function, except to assign short names. */
116 sfm_open_writer (struct file_handle *fh,
117 struct dictionary *d, int compress,
118 short omit_long_names)
120 struct sfm_writer *w = NULL;
124 if (!fh_open (fh, "system file", "we"))
127 /* Create and initialize writer. */
128 w = xmalloc (sizeof *w);
130 w->file = fopen (handle_get_filename (fh), "wb");
132 w->needs_translation = does_dict_need_translation (d);
133 w->compress = compress;
137 w->buf = w->end = w->ptr = NULL;
140 w->var_cnt = dict_get_var_cnt (d);
141 w->vars = xmalloc (sizeof *w->vars * w->var_cnt);
142 for (i = 0; i < w->var_cnt; i++)
144 const struct variable *dv = dict_get_var (d, i);
145 struct sfm_var *sv = &w->vars[i];
146 sv->width = dv->width;
148 sv->flt64_cnt = var_flt64_cnt (dv);
151 /* Check that file create succeeded. */
154 msg (ME, _("Error opening \"%s\" for writing "
155 "as a system file: %s."),
156 handle_get_filename (w->fh), strerror (errno));
161 /* Write the file header. */
162 if (!write_header (w, d))
165 /* Write basic variable info. */
166 dict_assign_short_names (d);
167 for (i = 0; i < dict_get_var_cnt (d); i++)
168 write_variable (w, dict_get_var (d, i));
170 /* Write out value labels. */
171 for (idx = i = 0; i < dict_get_var_cnt (d); i++)
173 struct variable *v = dict_get_var (d, i);
175 if (!write_value_labels (w, v, idx))
177 idx += var_flt64_cnt (v);
180 if (dict_get_documents (d) != NULL && !write_documents (w, d))
183 if (!write_rec_7_34 (w))
186 if (!write_variable_display_parameters (w, d))
189 if (!omit_long_names)
191 if (!write_longvar_table (w, d))
195 /* Write end-of-headers record. */
204 rec_999.rec_type = 999;
207 if (!buf_write (w, &rec_999, sizeof rec_999))
213 w->buf = xmalloc (sizeof *w->buf * 128);
215 w->end = &w->buf[128];
216 w->x = (unsigned char *) w->ptr++;
217 w->y = (unsigned char *) w->ptr;
223 sfm_close_writer (w);
228 does_dict_need_translation (const struct dictionary *d)
234 for (i = 0; i < dict_get_var_cnt (d); i++)
236 struct variable *v = dict_get_var (d, i);
237 if (v->fv != case_idx)
244 /* Returns value of X truncated to two least-significant digits. */
255 /* Write the sysfile_header header to system file W. */
257 write_header (struct sfm_writer *w, const struct dictionary *d)
259 struct sysfile_header hdr;
265 memcpy (hdr.rec_type, "$FL2", 4);
267 p = stpcpy (hdr.prod_name, "@(#) SPSS DATA FILE ");
268 p = append_string_max (p, version, &hdr.prod_name[60]);
269 p = append_string_max (p, " - ", &hdr.prod_name[60]);
270 p = append_string_max (p, host_system, &hdr.prod_name[60]);
271 memset (p, ' ', &hdr.prod_name[60] - p);
276 for (i = 0; i < dict_get_var_cnt (d); i++)
277 w->flt64_cnt += var_flt64_cnt (dict_get_var (d, i));
278 hdr.case_size = w->flt64_cnt;
280 hdr.compress = w->compress;
282 if (dict_get_weight (d) != NULL)
284 struct variable *weight_var;
285 int recalc_weight_idx = 1;
288 weight_var = dict_get_weight (d);
291 struct variable *v = dict_get_var (d, i);
294 recalc_weight_idx += var_flt64_cnt (v);
296 hdr.weight_idx = recalc_weight_idx;
302 hdr.bias = COMPRESSION_BIAS;
304 if (time (&t) == (time_t) -1)
306 memcpy (hdr.creation_date, "01 Jan 70", 9);
307 memcpy (hdr.creation_time, "00:00:00", 8);
311 static const char *month_name[12] =
313 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
314 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
316 struct tm *tmp = localtime (&t);
317 int day = rerange (tmp->tm_mday);
318 int mon = rerange (tmp->tm_mon + 1);
319 int year = rerange (tmp->tm_year);
320 int hour = rerange (tmp->tm_hour + 1);
321 int min = rerange (tmp->tm_min + 1);
322 int sec = rerange (tmp->tm_sec + 1);
325 sprintf (buf, "%02d %s %02d", day, month_name[mon - 1], year);
326 memcpy (hdr.creation_date, buf, sizeof hdr.creation_date);
327 sprintf (buf, "%02d:%02d:%02d", hour - 1, min - 1, sec - 1);
328 memcpy (hdr.creation_time, buf, sizeof hdr.creation_time);
332 const char *label = dict_get_label (d);
336 st_bare_pad_copy (hdr.file_label, label, sizeof hdr.file_label);
339 memset (hdr.padding, 0, sizeof hdr.padding);
341 if (!buf_write (w, &hdr, sizeof hdr))
346 /* Translates format spec from internal form in SRC to system file
349 write_format_spec (struct fmt_spec *src, int32 *dest)
351 *dest = (formats[src->type].spss << 16) | (src->w << 8) | src->d;
354 /* Write the variable record(s) for primary variable P and secondary
355 variable S to system file W. */
357 write_variable (struct sfm_writer *w, struct variable *v)
359 struct sysfile_variable sv;
361 /* Missing values. */
362 flt64 m[3]; /* Missing value values. */
363 int nm; /* Number of missing values, possibly negative. */
367 sv.has_var_label = (v->label != NULL);
369 switch (v->miss_type)
377 for (nm = 0; nm < v->miss_type; nm++)
378 m[nm] = v->missing[nm].f;
381 m[0] = v->missing[0].f;
382 m[1] = v->missing[1].f;
386 m[0] = second_lowest_flt64;
387 m[1] = v->missing[0].f;
391 m[0] = v->missing[0].f;
395 case MISSING_RANGE_1:
396 m[0] = v->missing[0].f;
397 m[1] = v->missing[1].f;
398 m[2] = v->missing[2].f;
402 m[0] = second_lowest_flt64;
403 m[1] = v->missing[0].f;
404 m[2] = v->missing[1].f;
408 m[0] = v->missing[0].f;
409 m[1] = second_lowest_flt64;
410 m[2] = v->missing[1].f;
418 sv.n_missing_values = nm;
419 write_format_spec (&v->print, &sv.print);
420 write_format_spec (&v->write, &sv.write);
421 st_bare_pad_copy (sv.name, v->short_name, sizeof sv.name);
422 if (!buf_write (w, &sv, sizeof sv))
436 l.label_len = min (strlen (v->label), 255);
437 ext_len = ROUND_UP (l.label_len, sizeof l.label_len);
438 memcpy (l.label, v->label, l.label_len);
439 memset (&l.label[l.label_len], ' ', ext_len - l.label_len);
441 if (!buf_write (w, &l, offsetof (struct label, label) + ext_len))
445 if (nm && !buf_write (w, m, sizeof *m * 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 if (!buf_write (w, &sv, sizeof sv))
469 /* Writes the value labels for variable V having system file variable
470 index IDX to system file W. Returns
471 nonzero only if successful. */
473 write_value_labels (struct sfm_writer *w, struct variable *v, int idx)
475 struct value_label_rec
489 struct val_labs_iterator *i;
490 struct value_label_rec *vlr;
491 struct var_idx_rec vir;
496 if (!val_labs_count (v->val_labs))
499 /* Pass 1: Count bytes. */
500 vlr_size = (sizeof (struct value_label_rec)
501 + sizeof (flt64) * (val_labs_count (v->val_labs) - 1));
502 for (vl = val_labs_first (v->val_labs, &i); vl != NULL;
503 vl = val_labs_next (v->val_labs, &i))
504 vlr_size += ROUND_UP (strlen (vl->label) + 1, sizeof (flt64));
506 /* Pass 2: Copy bytes. */
507 vlr = xmalloc (vlr_size);
509 vlr->n_labels = val_labs_count (v->val_labs);
511 for (vl = val_labs_first_sorted (v->val_labs, &i); vl != NULL;
512 vl = val_labs_next (v->val_labs, &i))
514 size_t len = strlen (vl->label);
516 *loc++ = vl->value.f;
517 *(unsigned char *) loc = len;
518 memcpy (&((unsigned char *) loc)[1], vl->label, len);
519 memset (&((unsigned char *) loc)[1 + len], ' ',
520 REM_RND_UP (len + 1, sizeof (flt64)));
521 loc += DIV_RND_UP (len + 1, sizeof (flt64));
524 if (!buf_write (w, vlr, vlr_size))
533 vir.vars[0] = idx + 1;
534 if (!buf_write (w, &vir, sizeof vir))
540 /* Writes record type 6, document record. */
542 write_documents (struct sfm_writer *w, const struct dictionary *d)
546 int32 rec_type P; /* Always 6. */
547 int32 n_lines P; /* Number of lines of documents. */
551 const char *documents;
554 documents = dict_get_documents (d);
555 n_lines = strlen (documents) / 80;
558 rec_6.n_lines = n_lines;
559 if (!buf_write (w, &rec_6, sizeof rec_6))
561 if (!buf_write (w, documents, 80 * n_lines))
567 /* Write the alignment, width and scale values */
569 write_variable_display_parameters (struct sfm_writer *w,
570 const struct dictionary *dict)
582 vdp_hdr.rec_type = 7;
583 vdp_hdr.subtype = 11;
584 vdp_hdr.elem_size = 4;
585 vdp_hdr.n_elem = w->var_cnt * 3;
587 if (!buf_write (w, &vdp_hdr, sizeof vdp_hdr))
590 for ( i = 0 ; i < w->var_cnt ; ++i )
601 v = dict_get_var(dict, i);
603 params.measure = v->measure;
604 params.width = v->display_width;
605 params.align = v->alignment;
607 if (!buf_write (w, ¶ms, sizeof(params)))
614 /* Writes the long variable name table */
616 write_longvar_table (struct sfm_writer *w, const struct dictionary *dict)
627 struct string long_name_map;
630 ds_init (&long_name_map, 10 * dict_get_var_cnt (dict));
631 for (i = 0; i < dict_get_var_cnt (dict); i++)
633 struct variable *v = dict_get_var (dict, i);
636 ds_putc (&long_name_map, '\t');
637 ds_printf (&long_name_map, "%s=%s", v->short_name, v->name);
642 lv_hdr.elem_size = 1;
643 lv_hdr.n_elem = ds_length (&long_name_map);
645 if (!buf_write (w, &lv_hdr, sizeof lv_hdr)
646 || !buf_write (w, ds_data (&long_name_map), ds_length (&long_name_map)))
649 ds_destroy (&long_name_map);
653 ds_destroy (&long_name_map);
657 /* Writes record type 7, subtypes 3 and 4. */
659 write_rec_7_34 (struct sfm_writer *w)
676 /* Components of the version number, from major to minor. */
677 int version_component[3];
679 /* Used to step through the version string. */
682 /* Parses the version string, which is assumed to be of the form
683 #.#x, where each # is a string of digits, and x is a single
685 version_component[0] = strtol (bare_version, &p, 10);
688 version_component[1] = strtol (bare_version, &p, 10);
689 version_component[2] = (isalpha ((unsigned char) *p)
690 ? tolower ((unsigned char) *p) - 'a' : 0);
692 rec_7.rec_type_3 = 7;
694 rec_7.data_type_3 = sizeof (int32);
696 rec_7.elem_3[0] = version_component[0];
697 rec_7.elem_3[1] = version_component[1];
698 rec_7.elem_3[2] = version_component[2];
699 rec_7.elem_3[3] = -1;
701 /* PORTME: 1=IEEE754, 2=IBM 370, 3=DEC VAX E. */
708 /* PORTME: 1=big-endian, 2=little-endian. */
715 /* PORTME: 1=EBCDIC, 2=7-bit ASCII, 3=8-bit ASCII, 4=DEC Kanji. */
718 rec_7.rec_type_4 = 7;
720 rec_7.data_type_4 = sizeof (flt64);
722 rec_7.elem_4[0] = -FLT64_MAX;
723 rec_7.elem_4[1] = FLT64_MAX;
724 rec_7.elem_4[2] = second_lowest_flt64;
726 if (!buf_write (w, &rec_7, sizeof rec_7))
731 /* Write NBYTES starting at BUF to the system file represented by
734 buf_write (struct sfm_writer *w, const void *buf, size_t nbytes)
736 assert (buf != NULL);
737 if (fwrite (buf, nbytes, 1, w->file) != 1)
739 msg (ME, _("%s: Writing system file: %s."),
740 handle_get_filename (w->fh), strerror (errno));
746 /* Copies string DEST to SRC with the proviso that DEST does not reach
747 byte END; no null terminator is copied. Returns a pointer to the
748 byte after the last byte copied. */
750 append_string_max (char *dest, const char *src, const char *end)
752 int nbytes = min (end - dest, (int) strlen (src));
753 memcpy (dest, src, nbytes);
754 return dest + nbytes;
757 /* Makes certain that the compression buffer of H has room for another
758 element. If there's not room, pads out the current instruction
759 octet with zero and dumps out the buffer. */
761 ensure_buf_space (struct sfm_writer *w)
763 if (w->ptr >= w->end)
765 memset (w->x, 0, w->y - w->x);
768 if (!buf_write (w, w->buf, sizeof *w->buf * 128))
774 static void write_compressed_data (struct sfm_writer *w, const flt64 *elem);
776 /* Writes case C to system file W.
777 Returns nonzero if successful. */
779 sfm_write_case (struct sfm_writer *w, struct ccase *c)
783 if (!w->needs_translation && !w->compress
784 && sizeof (flt64) == sizeof (union value))
786 /* Fast path: external and internal representations are the
787 same and the dictionary is properly ordered. Write
789 buf_write (w, case_data_all (c), sizeof (union value) * w->flt64_cnt);
793 /* Slow path: internal and external representations differ.
794 Write into a bounce buffer, then write to W. */
800 bounce_size = sizeof *bounce * w->flt64_cnt;
801 bounce = bounce_cur = local_alloc (bounce_size);
803 for (i = 0; i < w->var_cnt; i++)
805 struct sfm_var *v = &w->vars[i];
808 *bounce_cur = case_num (c, v->fv);
810 memcpy (bounce_cur, case_data (c, v->fv)->s, v->width);
811 bounce_cur += v->flt64_cnt;
815 buf_write (w, bounce, bounce_size);
817 write_compressed_data (w, bounce);
826 put_instruction (struct sfm_writer *w, unsigned char instruction)
830 if (!ensure_buf_space (w))
832 w->x = (unsigned char *) w->ptr++;
833 w->y = (unsigned char *) w->ptr;
835 *w->x++ = instruction;
839 put_element (struct sfm_writer *w, const flt64 *elem)
841 if (!ensure_buf_space (w))
843 memcpy (w->ptr++, elem, sizeof *elem);
847 write_compressed_data (struct sfm_writer *w, const flt64 *elem)
851 for (i = 0; i < w->var_cnt; i++)
853 struct sfm_var *v = &w->vars[i];
857 if (*elem == -FLT64_MAX)
858 put_instruction (w, 255);
859 else if (*elem >= 1 - COMPRESSION_BIAS
860 && *elem <= 251 - COMPRESSION_BIAS
861 && *elem == (int) *elem)
862 put_instruction (w, (int) *elem + COMPRESSION_BIAS);
865 put_instruction (w, 253);
866 put_element (w, elem);
874 for (j = 0; j < v->flt64_cnt; j++, elem++)
876 if (!memcmp (elem, " ", sizeof (flt64)))
877 put_instruction (w, 254);
880 put_instruction (w, 253);
881 put_element (w, elem);
888 /* Closes a system file after we're done with it. */
890 sfm_close_writer (struct sfm_writer *w)
895 fh_close (w->fh, "system file", "we");
900 if (w->buf != NULL && w->ptr > w->buf)
902 memset (w->x, 0, w->y - w->x);
903 buf_write (w, w->buf, (w->ptr - w->buf) * sizeof *w->buf);
906 /* Seek back to the beginning and update the number of cases.
907 This is just a courtesy to later readers, so there's no need
908 to check return values or report errors. */
909 if (!fseek (w->file, offsetof (struct sysfile_header, case_cnt), SEEK_SET))
911 int32 case_cnt = w->case_cnt;
913 /* I don't really care about the return value: it doesn't
914 matter whether this data is written. */
915 fwrite (&case_cnt, sizeof case_cnt, 1, w->file);
918 if (fclose (w->file) == EOF)
919 msg (ME, _("%s: Closing system file: %s."),
920 handle_get_filename (w->fh), strerror (errno));