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. */
33 #include "file-handle.h"
39 #include "value-labels.h"
43 #include "debug-print.h"
45 /* PORTME: This file may require substantial revision for those
46 systems that don't meet the typical 32-bit integer/64-bit double
47 model. It's kinda hard to tell without having one of them on my
50 /* Compression bias used by PSPP. Values between (1 -
51 COMPRESSION_BIAS) and (251 - COMPRESSION_BIAS) inclusive can be
53 #define COMPRESSION_BIAS 100
55 /* sfm writer file_handle extension. */
58 FILE *file; /* Actual file. */
60 int compressed; /* 1=compressed, 0=not compressed. */
61 flt64 *buf; /* Buffered data. */
62 flt64 *end; /* Buffer end. */
63 flt64 *ptr; /* Current location in buffer. */
64 unsigned char *x; /* Location in current instruction octet. */
65 unsigned char *y; /* End of instruction octet. */
66 int n_cases; /* Number of cases written so far. */
68 char *elem_type; /* ALPHA or NUMERIC for each flt64 element. */
71 static struct fh_ext_class sfm_w_class;
73 static char *append_string_max (char *, const char *, const char *);
74 static int write_header (struct sfm_write_info *inf);
75 static int bufwrite (struct file_handle *h, const void *buf, size_t nbytes);
76 static int write_variable (struct sfm_write_info *inf, struct variable *v);
77 static int write_value_labels (struct sfm_write_info *inf, struct variable * s, int index);
78 static int write_rec_7_34 (struct sfm_write_info *inf);
79 static int write_documents (struct sfm_write_info *inf);
81 /* Writes the dictionary INF->dict to system file INF->h. The system
82 file is compressed if INF->compress is nonzero. INF->case_size is
83 set to the number of flt64 elements in a single case. Returns
84 nonzero only if successful. */
86 sfm_write_dictionary (struct sfm_write_info *inf)
88 struct dictionary *d = inf->dict;
89 struct sfm_fhuser_ext *ext;
93 if (inf->h->class != NULL)
95 msg (ME, _("Cannot write file %s as system file: "
96 "already opened for %s."),
97 handle_get_name (inf->h), inf->h->class->name);
101 msg (VM (1), _("%s: Opening system-file handle %s for writing."),
102 handle_get_filename (inf->h), handle_get_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 (handle_get_filename (inf->h), "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."),
113 handle_get_filename (inf->h), strerror (errno));
119 /* Initialize the sfm_fhuser_ext structure. */
120 ext->compressed = inf->compress;
121 ext->buf = ext->ptr = NULL;
122 ext->x = ext->y = NULL;
125 /* Write the file header. */
126 if (!write_header (inf))
129 /* Write basic variable info. */
130 for (i = 0; i < dict_get_var_cnt (d); i++)
131 write_variable (inf, dict_get_var (d, i));
133 /* Write out value labels. */
134 for (index = i = 0; i < dict_get_var_cnt (d); i++)
136 struct variable *v = dict_get_var (d, i);
138 if (!write_value_labels (inf, v, index))
140 index += (v->type == NUMERIC ? 1
141 : DIV_RND_UP (v->width, sizeof (flt64)));
144 if (dict_get_documents (d) != NULL && !write_documents (inf))
146 if (!write_rec_7_34 (inf))
149 /* Write record 999. */
158 rec_999.rec_type = 999;
161 if (!bufwrite (inf->h, &rec_999, sizeof rec_999))
165 msg (VM (2), _("Wrote system-file header successfully."));
170 msg (VM (1), _("Error writing system-file header."));
172 inf->h->class = NULL;
174 free (ext->elem_type);
175 ext->elem_type = NULL;
179 /* Returns value of X truncated to two least-significant digits. */
190 /* Write the sysfile_header header to the system file represented by
193 write_header (struct sfm_write_info *inf)
195 struct dictionary *d = inf->dict;
196 struct sfm_fhuser_ext *ext = inf->h->ext;
197 struct sysfile_header hdr;
203 memcpy (hdr.rec_type, "$FL2", 4);
205 p = stpcpy (hdr.prod_name, "@(#) SPSS DATA FILE ");
206 p = append_string_max (p, version, &hdr.prod_name[60]);
207 p = append_string_max (p, " - ", &hdr.prod_name[60]);
208 p = append_string_max (p, host_system, &hdr.prod_name[60]);
209 memset (p, ' ', &hdr.prod_name[60] - p);
214 for (i = 0; i < dict_get_var_cnt (d); i++)
216 struct variable *v = dict_get_var (d, i);
217 hdr.case_size += (v->type == NUMERIC ? 1
218 : DIV_RND_UP (v->width, sizeof (flt64)));
220 inf->case_size = hdr.case_size;
222 p = ext->elem_type = xmalloc (inf->case_size);
223 for (i = 0; i < dict_get_var_cnt (d); i++)
225 struct variable *v = dict_get_var (d, i);
226 int count = (v->type == NUMERIC ? 1
227 : DIV_RND_UP (v->width, sizeof (flt64)));
232 hdr.compressed = inf->compress;
234 if (dict_get_weight (d) != NULL)
236 struct variable *weight_var;
237 int recalc_weight_index = 1;
240 weight_var = dict_get_weight (d);
243 struct variable *v = dict_get_var (d, i);
246 recalc_weight_index += (v->type == NUMERIC ? 1
247 : DIV_RND_UP (v->width, sizeof (flt64)));
249 hdr.weight_index = recalc_weight_index;
252 hdr.weight_index = 0;
255 hdr.bias = COMPRESSION_BIAS;
257 if ((time_t) - 1 == time (&t))
259 memcpy (hdr.creation_date, "01 Jan 70", 9);
260 memcpy (hdr.creation_time, "00:00:00", 8);
264 static const char *month_name[12] =
266 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
267 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
269 struct tm *tmp = localtime (&t);
270 int day = rerange (tmp->tm_mday);
271 int mon = rerange (tmp->tm_mon + 1);
272 int year = rerange (tmp->tm_year);
273 int hour = rerange (tmp->tm_hour + 1);
274 int min = rerange (tmp->tm_min + 1);
275 int sec = rerange (tmp->tm_sec + 1);
278 sprintf (buf, "%02d %s %02d", day, month_name[mon - 1], year);
279 memcpy (hdr.creation_date, buf, sizeof hdr.creation_date);
280 sprintf (buf, "%02d:%02d:%02d", hour - 1, min - 1, sec - 1);
281 memcpy (hdr.creation_time, buf, sizeof hdr.creation_time);
285 const char *label = dict_get_label (d);
289 st_bare_pad_copy (hdr.file_label, label, sizeof hdr.file_label);
292 memset (hdr.padding, 0, sizeof hdr.padding);
294 if (!bufwrite (inf->h, &hdr, sizeof hdr))
299 /* Translates format spec from internal form in SRC to system file
302 write_format_spec (struct fmt_spec *src, int32 *dest)
304 *dest = (formats[src->type].spss << 16) | (src->w << 8) | src->d;
307 /* Write the variable record(s) for primary variable P and secondary
308 variable S to the system file represented by INF. */
310 write_variable (struct sfm_write_info *inf, struct variable *v)
312 struct sysfile_variable sv;
314 /* Missing values. */
315 flt64 m[3]; /* Missing value values. */
316 int nm; /* Number of missing values, possibly negative. */
319 sv.type = (v->type == NUMERIC ? 0 : v->width);
320 sv.has_var_label = (v->label != NULL);
322 switch (v->miss_type)
330 for (nm = 0; nm < v->miss_type; nm++)
331 m[nm] = v->missing[nm].f;
334 m[0] = v->missing[0].f;
335 m[1] = v->missing[1].f;
339 m[0] = second_lowest_flt64;
340 m[1] = v->missing[0].f;
344 m[0] = v->missing[0].f;
348 case MISSING_RANGE_1:
349 m[0] = v->missing[0].f;
350 m[1] = v->missing[1].f;
351 m[2] = v->missing[2].f;
355 m[0] = second_lowest_flt64;
356 m[1] = v->missing[0].f;
357 m[2] = v->missing[1].f;
361 m[0] = v->missing[0].f;
362 m[1] = second_lowest_flt64;
363 m[2] = v->missing[1].f;
371 sv.n_missing_values = nm;
372 write_format_spec (&v->print, &sv.print);
373 write_format_spec (&v->write, &sv.write);
374 memcpy (sv.name, v->name, strlen (v->name));
375 memset (&sv.name[strlen (v->name)], ' ', 8 - strlen (v->name));
376 if (!bufwrite (inf->h, &sv, sizeof sv))
390 l.label_len = min (strlen (v->label), 255);
391 ext_len = ROUND_UP (l.label_len, sizeof l.label_len);
392 memcpy (l.label, v->label, l.label_len);
393 memset (&l.label[l.label_len], ' ', ext_len - l.label_len);
395 if (!bufwrite (inf->h, &l, offsetof (struct label, label) + ext_len))
399 if (nm && !bufwrite (inf->h, m, sizeof *m * nm))
402 if (v->type == ALPHA && v->width > (int) sizeof (flt64))
408 sv.has_var_label = 0;
409 sv.n_missing_values = 0;
410 memset (&sv.print, 0, sizeof sv.print);
411 memset (&sv.write, 0, sizeof sv.write);
412 memset (&sv.name, 0, sizeof sv.name);
414 pad_count = DIV_RND_UP (v->width, (int) sizeof (flt64)) - 1;
415 for (i = 0; i < pad_count; i++)
416 if (!bufwrite (inf->h, &sv, sizeof sv))
423 /* Writes the value labels for variable V having system file variable
424 index INDEX to the system file associated with INF. Returns
425 nonzero only if successful. */
427 write_value_labels (struct sfm_write_info * inf, struct variable *v, int index)
429 struct value_label_rec
436 struct variable_index_rec
443 struct val_labs_iterator *i;
444 struct value_label_rec *vlr;
445 struct variable_index_rec vir;
450 if (!val_labs_count (v->val_labs))
453 /* Pass 1: Count bytes. */
454 vlr_size = (sizeof (struct value_label_rec)
455 + sizeof (flt64) * (val_labs_count (v->val_labs) - 1));
456 for (vl = val_labs_first (v->val_labs, &i); vl != NULL;
457 vl = val_labs_next (v->val_labs, &i))
458 vlr_size += ROUND_UP (strlen (vl->label) + 1, sizeof (flt64));
460 /* Pass 2: Copy bytes. */
461 vlr = xmalloc (vlr_size);
463 vlr->n_labels = val_labs_count (v->val_labs);
465 for (vl = val_labs_first_sorted (v->val_labs, &i); vl != NULL;
466 vl = val_labs_next (v->val_labs, &i))
468 size_t len = strlen (vl->label);
470 *loc++ = vl->value.f;
471 *(unsigned char *) loc = len;
472 memcpy (&((unsigned char *) loc)[1], vl->label, len);
473 memset (&((unsigned char *) loc)[1 + len], ' ',
474 REM_RND_UP (len + 1, sizeof (flt64)));
475 loc += DIV_RND_UP (len + 1, sizeof (flt64));
478 if (!bufwrite (inf->h, vlr, vlr_size))
487 vir.vars[0] = index + 1;
488 if (!bufwrite (inf->h, &vir, sizeof vir))
494 /* Writes record type 6, document record. */
496 write_documents (struct sfm_write_info * inf)
498 struct dictionary *d = inf->dict;
501 int32 rec_type P; /* Always 6. */
502 int32 n_lines P; /* Number of lines of documents. */
506 const char *documents;
509 documents = dict_get_documents (d);
510 n_lines = strlen (documents) / 80;
513 rec_6.n_lines = n_lines;
514 if (!bufwrite (inf->h, &rec_6, sizeof rec_6))
516 if (!bufwrite (inf->h, documents, 80 * n_lines))
522 /* Writes record type 7, subtypes 3 and 4. */
524 write_rec_7_34 (struct sfm_write_info * inf)
541 /* Components of the version number, from major to minor. */
542 int version_component[3];
544 /* Used to step through the version string. */
547 /* Parses the version string, which is assumed to be of the form
548 #.#x, where each # is a string of digits, and x is a single
550 version_component[0] = strtol (bare_version, &p, 10);
553 version_component[1] = strtol (bare_version, &p, 10);
554 version_component[2] = (isalpha ((unsigned char) *p)
555 ? tolower ((unsigned char) *p) - 'a' : 0);
557 rec_7.rec_type_3 = 7;
559 rec_7.data_type_3 = sizeof (int32);
561 rec_7.elem_3[0] = version_component[0];
562 rec_7.elem_3[1] = version_component[1];
563 rec_7.elem_3[2] = version_component[2];
564 rec_7.elem_3[3] = -1;
566 /* PORTME: 1=IEEE754, 2=IBM 370, 3=DEC VAX E. */
573 /* PORTME: 1=big-endian, 2=little-endian. */
580 /* PORTME: 1=EBCDIC, 2=7-bit ASCII, 3=8-bit ASCII, 4=DEC Kanji. */
583 rec_7.rec_type_4 = 7;
585 rec_7.data_type_4 = sizeof (flt64);
587 rec_7.elem_4[0] = -FLT64_MAX;
588 rec_7.elem_4[1] = FLT64_MAX;
589 rec_7.elem_4[2] = second_lowest_flt64;
591 if (!bufwrite (inf->h, &rec_7, sizeof rec_7))
596 /* Write NBYTES starting at BUF to the system file represented by
599 bufwrite (struct file_handle * h, const void *buf, size_t nbytes)
601 struct sfm_fhuser_ext *ext = h->ext;
604 if (1 != fwrite (buf, nbytes, 1, ext->file))
606 msg (ME, _("%s: Writing system file: %s."),
607 handle_get_filename (h), strerror (errno));
613 /* Copies string DEST to SRC with the proviso that DEST does not reach
614 byte END; no null terminator is copied. Returns a pointer to the
615 byte after the last byte copied. */
617 append_string_max (char *dest, const char *src, const char *end)
619 int nbytes = min (end - dest, (int) strlen (src));
620 memcpy (dest, src, nbytes);
621 return dest + nbytes;
624 /* Makes certain that the compression buffer of H has room for another
625 element. If there's not room, pads out the current instruction
626 octet with zero and dumps out the buffer. */
628 ensure_buf_space (struct file_handle *h)
630 struct sfm_fhuser_ext *ext = h->ext;
632 if (ext->ptr >= ext->end)
634 memset (ext->x, 0, ext->y - ext->x);
637 if (!bufwrite (h, ext->buf, sizeof *ext->buf * 128))
643 /* Writes case ELEM consisting of N_ELEM flt64 elements to the system
644 file represented by H. Return success. */
646 sfm_write_case (struct file_handle * h, const flt64 *elem, int n_elem)
648 struct sfm_fhuser_ext *ext = h->ext;
649 const flt64 *end_elem = &elem[n_elem];
650 char *elem_type = ext->elem_type;
654 if (ext->compressed == 0)
655 return bufwrite (h, elem, sizeof *elem * n_elem);
657 if (ext->buf == NULL)
659 ext->buf = xmalloc (sizeof *ext->buf * 128);
661 ext->end = &ext->buf[128];
662 ext->x = (unsigned char *) (ext->ptr++);
663 ext->y = (unsigned char *) (ext->ptr);
665 for (; elem < end_elem; elem++, elem_type++)
667 if (ext->x >= ext->y)
669 if (!ensure_buf_space (h))
671 ext->x = (unsigned char *) (ext->ptr++);
672 ext->y = (unsigned char *) (ext->ptr);
675 if (*elem_type == NUMERIC)
677 if (*elem == -FLT64_MAX)
682 else if (*elem > INT_MIN && *elem < INT_MAX)
686 if (value >= 1 - COMPRESSION_BIAS
687 && value <= 251 - COMPRESSION_BIAS
690 *ext->x++ = value + COMPRESSION_BIAS;
697 if (0 == memcmp ((char *) elem,
707 if (!ensure_buf_space (h))
715 /* Closes a system file after we're done with it. */
717 sfm_close (struct file_handle * h)
719 struct sfm_fhuser_ext *ext = h->ext;
721 if (ext->buf != NULL && ext->ptr > ext->buf)
723 memset (ext->x, 0, ext->y - ext->x);
724 bufwrite (h, ext->buf, (ext->ptr - ext->buf) * sizeof *ext->buf);
727 /* Attempt to seek back to the beginning in order to write the
728 number of cases. If that's not possible (i.e., we're writing to
729 a tty or a pipe), then it's not a big deal because we wrote the
730 code that indicates an unknown number of cases. */
731 if (0 == fseek (ext->file, offsetof (struct sysfile_header, ncases),
734 int32 n_cases = ext->n_cases;
736 /* I don't really care about the return value: it doesn't matter
737 whether this data is written. This is the only situation in
738 which you will see me fail to check a return value. */
739 fwrite (&n_cases, sizeof n_cases, 1, ext->file);
742 if (EOF == fclose (ext->file))
743 msg (ME, _("%s: Closing system file: %s."),
744 handle_get_filename (h), strerror (errno));
747 free (ext->elem_type);
751 static struct fh_ext_class sfm_w_class =
754 N_("writing as a system file"),