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., 59 Temple Place - Suite 330, Boston, MA
29 #include <unistd.h> /* Required by SunOS4. */
34 #include "file-handle.h"
40 #include "value-labels.h"
44 #include "debug-print.h"
46 /* PORTME: This file may require substantial revision for those
47 systems that don't meet the typical 32-bit integer/64-bit double
48 model. It's kinda hard to tell without having one of them on my
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 /* sfm writer file_handle extension. */
59 FILE *file; /* Actual file. */
61 int compressed; /* 1=compressed, 0=not compressed. */
62 flt64 *buf; /* Buffered data. */
63 flt64 *end; /* Buffer end. */
64 flt64 *ptr; /* Current location in buffer. */
65 unsigned char *x; /* Location in current instruction octet. */
66 unsigned char *y; /* End of instruction octet. */
67 int n_cases; /* Number of cases written so far. */
69 char *elem_type; /* ALPHA or NUMERIC for each flt64 element. */
72 static struct fh_ext_class sfm_w_class;
74 static char *append_string_max (char *, const char *, const char *);
75 static int write_header (struct sfm_write_info *inf);
76 static int bufwrite (struct file_handle *h, const void *buf, size_t nbytes);
77 static int write_variable (struct sfm_write_info *inf, struct variable *v);
78 static int write_value_labels (struct sfm_write_info *inf, struct variable * s, int index);
79 static int write_rec_7_34 (struct sfm_write_info *inf);
80 static int write_documents (struct sfm_write_info *inf);
82 /* Writes the dictionary INF->dict to system file INF->h. The system
83 file is compressed if INF->compress is nonzero. INF->case_size is
84 set to the number of flt64 elements in a single case. Returns
85 nonzero only if successful. */
87 sfm_write_dictionary (struct sfm_write_info *inf)
89 struct dictionary *d = inf->dict;
90 struct sfm_fhuser_ext *ext;
94 if (inf->h->class != NULL)
96 msg (ME, _("Cannot write file %s as system file: already opened for %s."),
97 fh_handle_name (inf->h), inf->h->class->name);
101 msg (VM (1), _("%s: Opening system-file handle %s for writing."),
102 fh_handle_filename (inf->h), fh_handle_name (inf->h));
104 /* Open the physical disk file. */
105 inf->h->class = &sfm_w_class;
106 inf->h->ext = ext = xmalloc (sizeof (struct sfm_fhuser_ext));
107 ext->file = fopen (inf->h->norm_fn, "wb");
108 ext->elem_type = NULL;
109 if (ext->file == NULL)
111 msg (ME, _("An error occurred while opening \"%s\" for writing "
112 "as a system file: %s."), inf->h->fn, strerror (errno));
118 /* Initialize the sfm_fhuser_ext structure. */
119 ext->compressed = inf->compress;
120 ext->buf = ext->ptr = NULL;
121 ext->x = ext->y = NULL;
124 /* Write the file header. */
125 if (!write_header (inf))
128 /* Write basic variable info. */
129 for (i = 0; i < dict_get_var_cnt (d); i++)
130 write_variable (inf, dict_get_var (d, i));
132 /* Write out value labels. */
133 for (index = i = 0; i < dict_get_var_cnt (d); i++)
135 struct variable *v = dict_get_var (d, i);
137 if (!write_value_labels (inf, v, index))
139 index += (v->type == NUMERIC ? 1
140 : DIV_RND_UP (v->width, sizeof (flt64)));
143 if (dict_get_documents (d) != NULL && !write_documents (inf))
145 if (!write_rec_7_34 (inf))
148 /* Write record 999. */
157 rec_999.rec_type = 999;
160 if (!bufwrite (inf->h, &rec_999, sizeof rec_999))
164 msg (VM (2), _("Wrote system-file header successfully."));
169 msg (VM (1), _("Error writing system-file header."));
171 inf->h->class = NULL;
173 free (ext->elem_type);
174 ext->elem_type = NULL;
178 /* Returns value of X truncated to two least-significant digits. */
189 /* Write the sysfile_header header to the system file represented by
192 write_header (struct sfm_write_info *inf)
194 struct dictionary *d = inf->dict;
195 struct sfm_fhuser_ext *ext = inf->h->ext;
196 struct sysfile_header hdr;
202 memcpy (hdr.rec_type, "$FL2", 4);
204 p = stpcpy (hdr.prod_name, "@(#) SPSS DATA FILE ");
205 p = append_string_max (p, version, &hdr.prod_name[60]);
206 p = append_string_max (p, " - ", &hdr.prod_name[60]);
207 p = append_string_max (p, host_system, &hdr.prod_name[60]);
208 memset (p, ' ', &hdr.prod_name[60] - p);
213 for (i = 0; i < dict_get_var_cnt (d); i++)
215 struct variable *v = dict_get_var (d, i);
216 hdr.case_size += (v->type == NUMERIC ? 1
217 : DIV_RND_UP (v->width, sizeof (flt64)));
219 inf->case_size = hdr.case_size;
221 p = ext->elem_type = xmalloc (inf->case_size);
222 for (i = 0; i < dict_get_var_cnt (d); i++)
224 struct variable *v = dict_get_var (d, i);
225 int count = (v->type == NUMERIC ? 1
226 : DIV_RND_UP (v->width, sizeof (flt64)));
231 hdr.compressed = inf->compress;
233 if (dict_get_weight (d) != NULL)
235 struct variable *weight_var;
236 int recalc_weight_index = 1;
239 weight_var = dict_get_weight (d);
242 struct variable *v = dict_get_var (d, i);
245 recalc_weight_index += (v->type == NUMERIC ? 1
246 : DIV_RND_UP (v->width, sizeof (flt64)));
248 hdr.weight_index = recalc_weight_index;
251 hdr.weight_index = 0;
254 hdr.bias = COMPRESSION_BIAS;
256 if ((time_t) - 1 == time (&t))
258 memcpy (hdr.creation_date, "01 Jan 70", 9);
259 memcpy (hdr.creation_time, "00:00:00", 8);
263 static const char *month_name[12] =
265 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
266 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
268 struct tm *tmp = localtime (&t);
269 int day = rerange (tmp->tm_mday);
270 int mon = rerange (tmp->tm_mon + 1);
271 int year = rerange (tmp->tm_year);
272 int hour = rerange (tmp->tm_hour + 1);
273 int min = rerange (tmp->tm_min + 1);
274 int sec = rerange (tmp->tm_sec + 1);
277 sprintf (buf, "%02d %s %02d", day, month_name[mon - 1], year);
278 memcpy (hdr.creation_date, buf, sizeof hdr.creation_date);
279 sprintf (buf, "%02d:%02d:%02d", hour - 1, min - 1, sec - 1);
280 memcpy (hdr.creation_time, buf, sizeof hdr.creation_time);
284 const char *label = dict_get_label (d);
288 st_bare_pad_copy (hdr.file_label, label, sizeof hdr.file_label);
291 memset (hdr.padding, 0, sizeof hdr.padding);
293 if (!bufwrite (inf->h, &hdr, sizeof hdr))
298 /* Translates format spec from internal form in SRC to system file
301 write_format_spec (struct fmt_spec *src, int32 *dest)
303 *dest = (formats[src->type].spss << 16) | (src->w << 8) | src->d;
306 /* Write the variable record(s) for primary variable P and secondary
307 variable S to the system file represented by INF. */
309 write_variable (struct sfm_write_info *inf, struct variable *v)
311 struct sysfile_variable sv;
313 /* Missing values. */
314 flt64 m[3]; /* Missing value values. */
315 int nm; /* Number of missing values, possibly negative. */
318 sv.type = (v->type == NUMERIC ? 0 : v->width);
319 sv.has_var_label = (v->label != NULL);
321 switch (v->miss_type)
329 for (nm = 0; nm < v->miss_type; nm++)
330 m[nm] = v->missing[nm].f;
333 m[0] = v->missing[0].f;
334 m[1] = v->missing[1].f;
338 m[0] = second_lowest_flt64;
339 m[1] = v->missing[0].f;
343 m[0] = v->missing[0].f;
347 case MISSING_RANGE_1:
348 m[0] = v->missing[0].f;
349 m[1] = v->missing[1].f;
350 m[2] = v->missing[2].f;
354 m[0] = second_lowest_flt64;
355 m[1] = v->missing[0].f;
356 m[2] = v->missing[1].f;
360 m[0] = v->missing[0].f;
361 m[1] = second_lowest_flt64;
362 m[2] = v->missing[1].f;
369 sv.n_missing_values = nm;
370 write_format_spec (&v->print, &sv.print);
371 write_format_spec (&v->write, &sv.write);
372 memcpy (sv.name, v->name, strlen (v->name));
373 memset (&sv.name[strlen (v->name)], ' ', 8 - strlen (v->name));
374 if (!bufwrite (inf->h, &sv, sizeof sv))
388 l.label_len = min (strlen (v->label), 120);
389 ext_len = ROUND_UP (l.label_len, sizeof l.label_len);
390 memcpy (l.label, v->label, l.label_len);
391 memset (&l.label[l.label_len], ' ', ext_len - l.label_len);
393 if (!bufwrite (inf->h, &l, offsetof (struct label, label) + ext_len))
397 if (nm && !bufwrite (inf->h, m, sizeof *m * nm))
400 if (v->type == ALPHA && v->width > (int) sizeof (flt64))
406 sv.has_var_label = 0;
407 sv.n_missing_values = 0;
408 memset (&sv.print, 0, sizeof sv.print);
409 memset (&sv.write, 0, sizeof sv.write);
410 memset (&sv.name, 0, sizeof sv.name);
412 pad_count = DIV_RND_UP (v->width, (int) sizeof (flt64)) - 1;
413 for (i = 0; i < pad_count; i++)
414 if (!bufwrite (inf->h, &sv, sizeof sv))
421 /* Writes the value labels for variable V having system file variable
422 index INDEX to the system file associated with INF. Returns
423 nonzero only if successful. */
425 write_value_labels (struct sfm_write_info * inf, struct variable *v, int index)
427 struct value_label_rec
434 struct variable_index_rec
441 struct val_labs_iterator *i;
442 struct value_label_rec *vlr;
443 struct variable_index_rec vir;
448 if (!val_labs_count (v->val_labs))
451 /* Pass 1: Count bytes. */
452 vlr_size = (sizeof (struct value_label_rec)
453 + sizeof (flt64) * (val_labs_count (v->val_labs) - 1));
454 for (vl = val_labs_first (v->val_labs, &i); vl != NULL;
455 vl = val_labs_next (v->val_labs, &i))
456 vlr_size += ROUND_UP (strlen (vl->label) + 1, sizeof (flt64));
458 /* Pass 2: Copy bytes. */
459 vlr = xmalloc (vlr_size);
461 vlr->n_labels = val_labs_count (v->val_labs);
463 for (vl = val_labs_first_sorted (v->val_labs, &i); vl != NULL;
464 vl = val_labs_next (v->val_labs, &i))
466 size_t len = strlen (vl->label);
468 *loc++ = vl->value.f;
469 *(unsigned char *) loc = len;
470 memcpy (&((unsigned char *) loc)[1], vl->label, len);
471 memset (&((unsigned char *) loc)[1 + len], ' ',
472 REM_RND_UP (len + 1, sizeof (flt64)));
473 loc += DIV_RND_UP (len + 1, sizeof (flt64));
476 if (!bufwrite (inf->h, vlr, vlr_size))
485 vir.vars[0] = index + 1;
486 if (!bufwrite (inf->h, &vir, sizeof vir))
492 /* Writes record type 6, document record. */
494 write_documents (struct sfm_write_info * inf)
496 struct dictionary *d = inf->dict;
499 int32 rec_type P; /* Always 6. */
500 int32 n_lines P; /* Number of lines of documents. */
504 const char *documents;
507 documents = dict_get_documents (d);
508 n_lines = strlen (documents) / 80;
511 rec_6.n_lines = n_lines;
512 if (!bufwrite (inf->h, &rec_6, sizeof rec_6))
514 if (!bufwrite (inf->h, documents, 80 * n_lines))
520 /* Writes record type 7, subtypes 3 and 4. */
522 write_rec_7_34 (struct sfm_write_info * inf)
539 /* Components of the version number, from major to minor. */
540 int version_component[3];
542 /* Used to step through the version string. */
545 /* Parses the version string, which is assumed to be of the form
546 #.#x, where each # is a string of digits, and x is a single
548 version_component[0] = strtol (bare_version, &p, 10);
551 version_component[1] = strtol (bare_version, &p, 10);
552 version_component[2] = (isalpha ((unsigned char) *p)
553 ? tolower ((unsigned char) *p) - 'a' : 0);
555 rec_7.rec_type_3 = 7;
557 rec_7.data_type_3 = sizeof (int32);
559 rec_7.elem_3[0] = version_component[0];
560 rec_7.elem_3[1] = version_component[1];
561 rec_7.elem_3[2] = version_component[2];
562 rec_7.elem_3[3] = -1;
564 /* PORTME: 1=IEEE754, 2=IBM 370, 3=DEC VAX E. */
571 /* PORTME: 1=big-endian, 2=little-endian. */
578 /* PORTME: 1=EBCDIC, 2=7-bit ASCII, 3=8-bit ASCII, 4=DEC Kanji. */
581 rec_7.rec_type_4 = 7;
583 rec_7.data_type_4 = sizeof (flt64);
585 rec_7.elem_4[0] = -FLT64_MAX;
586 rec_7.elem_4[1] = FLT64_MAX;
587 rec_7.elem_4[2] = second_lowest_flt64;
589 if (!bufwrite (inf->h, &rec_7, sizeof rec_7))
594 /* Write NBYTES starting at BUF to the system file represented by
597 bufwrite (struct file_handle * h, const void *buf, size_t nbytes)
599 struct sfm_fhuser_ext *ext = h->ext;
602 if (1 != fwrite (buf, nbytes, 1, ext->file))
604 msg (ME, _("%s: Writing system file: %s."), h->fn, strerror (errno));
610 /* Copies string DEST to SRC with the proviso that DEST does not reach
611 byte END; no null terminator is copied. Returns a pointer to the
612 byte after the last byte copied. */
614 append_string_max (char *dest, const char *src, const char *end)
616 int nbytes = min (end - dest, (int) strlen (src));
617 memcpy (dest, src, nbytes);
618 return dest + nbytes;
621 /* Makes certain that the compression buffer of H has room for another
622 element. If there's not room, pads out the current instruction
623 octet with zero and dumps out the buffer. */
625 ensure_buf_space (struct file_handle *h)
627 struct sfm_fhuser_ext *ext = h->ext;
629 if (ext->ptr >= ext->end)
631 memset (ext->x, 0, ext->y - ext->x);
634 if (!bufwrite (h, ext->buf, sizeof *ext->buf * 128))
640 /* Writes case ELEM consisting of N_ELEM flt64 elements to the system
641 file represented by H. Return success. */
643 sfm_write_case (struct file_handle * h, const flt64 *elem, int n_elem)
645 struct sfm_fhuser_ext *ext = h->ext;
646 const flt64 *end_elem = &elem[n_elem];
647 char *elem_type = ext->elem_type;
651 if (ext->compressed == 0)
652 return bufwrite (h, elem, sizeof *elem * n_elem);
654 if (ext->buf == NULL)
656 ext->buf = xmalloc (sizeof *ext->buf * 128);
658 ext->end = &ext->buf[128];
659 ext->x = (unsigned char *) (ext->ptr++);
660 ext->y = (unsigned char *) (ext->ptr);
662 for (; elem < end_elem; elem++, elem_type++)
664 if (ext->x >= ext->y)
666 if (!ensure_buf_space (h))
668 ext->x = (unsigned char *) (ext->ptr++);
669 ext->y = (unsigned char *) (ext->ptr);
672 if (*elem_type == NUMERIC)
674 if (*elem == -FLT64_MAX)
681 int value = *elem < 0 ? *elem - EPSILON : *elem + EPSILON;
683 if (value >= 1 - COMPRESSION_BIAS
684 && value <= 251 - COMPRESSION_BIAS
685 && approx_eq (value, *elem))
687 *ext->x++ = value + COMPRESSION_BIAS;
694 if (0 == memcmp ((char *) elem,
704 if (!ensure_buf_space (h))
712 /* Closes a system file after we're done with it. */
714 sfm_close (struct file_handle * h)
716 struct sfm_fhuser_ext *ext = h->ext;
718 if (ext->buf != NULL && ext->ptr > ext->buf)
720 memset (ext->x, 0, ext->y - ext->x);
721 bufwrite (h, ext->buf, (ext->ptr - ext->buf) * sizeof *ext->buf);
724 /* Attempt to seek back to the beginning in order to write the
725 number of cases. If that's not possible (i.e., we're writing to
726 a tty or a pipe), then it's not a big deal because we wrote the
727 code that indicates an unknown number of cases. */
728 if (0 == fseek (ext->file, offsetof (struct sysfile_header, ncases),
731 int32 n_cases = ext->n_cases;
733 /* I don't really care about the return value: it doesn't matter
734 whether this data is written. This is the only situation in
735 which you will see me fail to check a return value. */
736 fwrite (&n_cases, sizeof n_cases, 1, ext->file);
739 if (EOF == fclose (ext->file))
740 msg (ME, _("%s: Closing system file: %s."), h->fn, strerror (errno));
743 free (ext->elem_type);
747 static struct fh_ext_class sfm_w_class =
750 N_("writing as a system file"),