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
20 /* AIX requires this to be the first thing in the file. */
23 #define alloca __builtin_alloca
31 #ifndef alloca /* predefined by HP cc +Olibcalls */
44 #include <unistd.h> /* Required by SunOS4. */
49 #include "file-handle.h"
57 #include "value-labels.h"
61 #include "debug-print.h"
63 /* PORTME: This file may require substantial revision for those
64 systems that don't meet the typical 32-bit integer/64-bit double
65 model. It's kinda hard to tell without having one of them on my
68 /* Compression bias used by PSPP. Values between (1 -
69 COMPRESSION_BIAS) and (251 - COMPRESSION_BIAS) inclusive can be
71 #define COMPRESSION_BIAS 100
73 /* sfm writer file_handle extension. */
76 FILE *file; /* Actual file. */
78 int compressed; /* 1=compressed, 0=not compressed. */
79 flt64 *buf; /* Buffered data. */
80 flt64 *end; /* Buffer end. */
81 flt64 *ptr; /* Current location in buffer. */
82 unsigned char *x; /* Location in current instruction octet. */
83 unsigned char *y; /* End of instruction octet. */
84 int n_cases; /* Number of cases written so far. */
86 char *elem_type; /* ALPHA or NUMERIC for each flt64 element. */
89 static struct fh_ext_class sfm_w_class;
91 static char *append_string_max (char *, const char *, const char *);
92 static int write_header (struct sfm_write_info *inf);
93 static int bufwrite (struct file_handle *h, const void *buf, size_t nbytes);
94 static int write_variable (struct sfm_write_info *inf, struct variable *v);
95 static int write_value_labels (struct sfm_write_info *inf, struct variable * s, int index);
96 static int write_rec_7_34 (struct sfm_write_info *inf);
97 static int write_documents (struct sfm_write_info *inf);
99 /* Writes the dictionary INF->dict to system file INF->h. The system
100 file is compressed if INF->compress is nonzero. INF->case_size is
101 set to the number of flt64 elements in a single case. Returns
102 nonzero only if successful. */
104 sfm_write_dictionary (struct sfm_write_info *inf)
106 struct dictionary *d = inf->dict;
107 struct sfm_fhuser_ext *ext;
111 if (inf->h->class != NULL)
113 msg (ME, _("Cannot write file %s as system file: already opened for %s."),
114 fh_handle_name (inf->h), inf->h->class->name);
118 msg (VM (1), _("%s: Opening system-file handle %s for writing."),
119 fh_handle_filename (inf->h), fh_handle_name (inf->h));
121 /* Open the physical disk file. */
122 inf->h->class = &sfm_w_class;
123 inf->h->ext = ext = xmalloc (sizeof (struct sfm_fhuser_ext));
124 ext->file = fopen (inf->h->norm_fn, "wb");
125 ext->elem_type = NULL;
126 if (ext->file == NULL)
128 msg (ME, _("An error occurred while opening \"%s\" for writing "
129 "as a system file: %s."), inf->h->fn, strerror (errno));
135 /* Initialize the sfm_fhuser_ext structure. */
136 ext->compressed = inf->compress;
137 ext->buf = ext->ptr = NULL;
138 ext->x = ext->y = NULL;
141 /* Write the file header. */
142 if (!write_header (inf))
145 /* Write basic variable info. */
146 for (i = 0; i < d->nvar; i++)
147 write_variable (inf, d->var[i]);
149 /* Write out value labels. */
150 for (index = i = 0; i < d->nvar; i++)
152 struct variable *v = d->var[i];
154 if (!write_value_labels (inf, v, index))
156 index += (v->type == NUMERIC ? 1
157 : DIV_RND_UP (v->width, sizeof (flt64)));
160 if (d->documents != NULL && !write_documents (inf))
162 if (!write_rec_7_34 (inf))
165 /* Write record 999. */
174 rec_999.rec_type = 999;
177 if (!bufwrite (inf->h, &rec_999, sizeof rec_999))
181 msg (VM (2), _("Wrote system-file header successfully."));
186 msg (VM (1), _("Error writing system-file header."));
188 inf->h->class = NULL;
190 free (ext->elem_type);
191 ext->elem_type = NULL;
195 /* Returns value of X truncated to two least-significant digits. */
206 /* Write the sysfile_header header to the system file represented by
209 write_header (struct sfm_write_info *inf)
211 struct dictionary *d = inf->dict;
212 struct sfm_fhuser_ext *ext = inf->h->ext;
213 struct sysfile_header hdr;
219 memcpy (hdr.rec_type, "$FL2", 4);
221 p = stpcpy (hdr.prod_name, "@(#) SPSS DATA FILE ");
222 p = append_string_max (p, version, &hdr.prod_name[60]);
223 p = append_string_max (p, " - ", &hdr.prod_name[60]);
224 p = append_string_max (p, host_system, &hdr.prod_name[60]);
225 memset (p, ' ', &hdr.prod_name[60] - p);
230 for (i = 0; i < d->nvar; i++)
232 struct variable *v = d->var[i];
233 hdr.case_size += (v->type == NUMERIC ? 1
234 : DIV_RND_UP (v->width, sizeof (flt64)));
236 inf->case_size = hdr.case_size;
238 p = ext->elem_type = xmalloc (inf->case_size);
239 for (i = 0; i < d->nvar; i++)
241 struct variable *v = d->var[i];
242 int count = (v->type == NUMERIC ? 1
243 : DIV_RND_UP (v->width, sizeof (flt64)));
248 hdr.compressed = inf->compress;
250 update_weighting (d);
251 if (d->weight_index != -1)
253 int recalc_weight_index = 1;
255 for (i = 0; i < d->weight_index; i++)
257 struct variable *v = d->var[i];
258 recalc_weight_index += (v->type == NUMERIC ? 1
259 : DIV_RND_UP (v->width, sizeof (flt64)));
261 hdr.weight_index = recalc_weight_index;
264 hdr.weight_index = 0;
267 hdr.bias = COMPRESSION_BIAS;
269 if ((time_t) - 1 == time (&t))
271 memcpy (hdr.creation_date, "01 Jan 70", 9);
272 memcpy (hdr.creation_time, "00:00:00", 8);
276 static const char *month_name[12] =
278 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
279 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
281 struct tm *tmp = localtime (&t);
282 int day = rerange (tmp->tm_mday);
283 int mon = rerange (tmp->tm_mon + 1);
284 int year = rerange (tmp->tm_year);
285 int hour = rerange (tmp->tm_hour + 1);
286 int min = rerange (tmp->tm_min + 1);
287 int sec = rerange (tmp->tm_sec + 1);
290 sprintf (buf, "%02d %s %02d", day, month_name[mon - 1], year);
291 memcpy (hdr.creation_date, buf, sizeof hdr.creation_date);
292 sprintf (buf, "%02d:%02d:%02d", hour - 1, min - 1, sec - 1);
293 memcpy (hdr.creation_time, buf, sizeof hdr.creation_time);
296 st_bare_pad_copy (hdr.file_label, d->label ? d->label : "",
297 sizeof hdr.file_label);
298 memset (hdr.padding, 0, sizeof hdr.padding);
300 if (!bufwrite (inf->h, &hdr, sizeof hdr))
305 /* Translates format spec from internal form in SRC to system file
308 write_format_spec (struct fmt_spec *src, int32 *dest)
310 *dest = (formats[src->type].spss << 16) | (src->w << 8) | src->d;
313 /* Write the variable record(s) for primary variable P and secondary
314 variable S to the system file represented by INF. */
316 write_variable (struct sfm_write_info *inf, struct variable *v)
318 struct sysfile_variable sv;
320 /* Missing values. */
321 flt64 m[3]; /* Missing value values. */
322 int nm; /* Number of missing values, possibly negative. */
325 sv.type = (v->type == NUMERIC ? 0 : v->width);
326 sv.has_var_label = (v->label != NULL);
328 switch (v->miss_type)
336 for (nm = 0; nm < v->miss_type; nm++)
337 m[nm] = v->missing[nm].f;
340 m[0] = v->missing[0].f;
341 m[1] = v->missing[1].f;
345 m[0] = second_lowest_flt64;
346 m[1] = v->missing[0].f;
350 m[0] = v->missing[0].f;
354 case MISSING_RANGE_1:
355 m[0] = v->missing[0].f;
356 m[1] = v->missing[1].f;
357 m[2] = v->missing[2].f;
361 m[0] = second_lowest_flt64;
362 m[1] = v->missing[0].f;
363 m[2] = v->missing[1].f;
367 m[0] = v->missing[0].f;
368 m[1] = second_lowest_flt64;
369 m[2] = v->missing[1].f;
376 sv.n_missing_values = nm;
377 write_format_spec (&v->print, &sv.print);
378 write_format_spec (&v->write, &sv.write);
379 memcpy (sv.name, v->name, strlen (v->name));
380 memset (&sv.name[strlen (v->name)], ' ', 8 - strlen (v->name));
381 if (!bufwrite (inf->h, &sv, sizeof sv))
395 l.label_len = min (strlen (v->label), 120);
396 ext_len = ROUND_UP (l.label_len, sizeof l.label_len);
397 memcpy (l.label, v->label, l.label_len);
398 memset (&l.label[l.label_len], ' ', ext_len - l.label_len);
400 if (!bufwrite (inf->h, &l, offsetof (struct label, label) + ext_len))
404 if (nm && !bufwrite (inf->h, m, sizeof *m * nm))
407 if (v->type == ALPHA && v->width > (int) sizeof (flt64))
413 sv.has_var_label = 0;
414 sv.n_missing_values = 0;
415 memset (&sv.print, 0, sizeof sv.print);
416 memset (&sv.write, 0, sizeof sv.write);
417 memset (&sv.name, 0, sizeof sv.name);
419 pad_count = DIV_RND_UP (v->width, (int) sizeof (flt64)) - 1;
420 for (i = 0; i < pad_count; i++)
421 if (!bufwrite (inf->h, &sv, sizeof sv))
428 /* Writes the value labels for variable V having system file variable
429 index INDEX to the system file associated with INF. Returns
430 nonzero only if successful. */
432 write_value_labels (struct sfm_write_info * inf, struct variable *v, int index)
434 struct value_label_rec
441 struct variable_index_rec
448 struct val_labs_iterator *i;
449 struct value_label_rec *vlr;
450 struct variable_index_rec vir;
455 if (!val_labs_count (v->val_labs))
458 /* Pass 1: Count bytes. */
459 vlr_size = (sizeof (struct value_label_rec)
460 + sizeof (flt64) * (val_labs_count (v->val_labs) - 1));
461 for (vl = val_labs_first (v->val_labs, &i); vl != NULL;
462 vl = val_labs_next (v->val_labs, &i))
463 vlr_size += ROUND_UP (strlen (vl->label) + 1, sizeof (flt64));
465 /* Pass 2: Copy bytes. */
466 vlr = xmalloc (vlr_size);
468 vlr->n_labels = val_labs_count (v->val_labs);
470 for (vl = val_labs_first_sorted (v->val_labs, &i); vl != NULL;
471 vl = val_labs_next (v->val_labs, &i))
473 size_t len = strlen (vl->label);
475 *loc++ = vl->value.f;
476 *(unsigned char *) loc = len;
477 memcpy (&((unsigned char *) loc)[1], vl->label, len);
478 memset (&((unsigned char *) loc)[1 + len], ' ',
479 REM_RND_UP (len + 1, sizeof (flt64)));
480 loc += DIV_RND_UP (len + 1, sizeof (flt64));
483 if (!bufwrite (inf->h, vlr, vlr_size))
492 vir.vars[0] = index + 1;
493 if (!bufwrite (inf->h, &vir, sizeof vir))
499 /* Writes record type 6, document record. */
501 write_documents (struct sfm_write_info * inf)
503 struct dictionary *d = inf->dict;
506 int32 rec_type P; /* Always 6. */
507 int32 n_lines P; /* Number of lines of documents. */
512 rec_6.n_lines = d->n_documents;
513 if (!bufwrite (inf->h, &rec_6, sizeof rec_6))
515 if (!bufwrite (inf->h, d->documents, 80 * d->n_documents))
521 /* Writes record type 7, subtypes 3 and 4. */
523 write_rec_7_34 (struct sfm_write_info * inf)
540 /* Components of the version number, from major to minor. */
541 int version_component[3];
543 /* Used to step through the version string. */
546 /* Parses the version string, which is assumed to be of the form
547 #.#x, where each # is a string of digits, and x is a single
549 version_component[0] = strtol (bare_version, &p, 10);
552 version_component[1] = strtol (bare_version, &p, 10);
553 version_component[2] = (isalpha ((unsigned char) *p)
554 ? tolower ((unsigned char) *p) - 'a' : 0);
556 rec_7.rec_type_3 = 7;
558 rec_7.data_type_3 = sizeof (int32);
560 rec_7.elem_3[0] = version_component[0];
561 rec_7.elem_3[1] = version_component[1];
562 rec_7.elem_3[2] = version_component[2];
563 rec_7.elem_3[3] = -1;
565 /* PORTME: 1=IEEE754, 2=IBM 370, 3=DEC VAX E. */
572 /* PORTME: 1=big-endian, 2=little-endian. */
579 /* PORTME: 1=EBCDIC, 2=7-bit ASCII, 3=8-bit ASCII, 4=DEC Kanji. */
582 rec_7.rec_type_4 = 7;
584 rec_7.data_type_4 = sizeof (flt64);
586 rec_7.elem_4[0] = -FLT64_MAX;
587 rec_7.elem_4[1] = FLT64_MAX;
588 rec_7.elem_4[2] = second_lowest_flt64;
590 if (!bufwrite (inf->h, &rec_7, sizeof rec_7))
595 /* Write NBYTES starting at BUF to the system file represented by
598 bufwrite (struct file_handle * h, const void *buf, size_t nbytes)
600 struct sfm_fhuser_ext *ext = h->ext;
603 if (1 != fwrite (buf, nbytes, 1, ext->file))
605 msg (ME, _("%s: Writing system file: %s."), h->fn, strerror (errno));
611 /* Copies string DEST to SRC with the proviso that DEST does not reach
612 byte END; no null terminator is copied. Returns a pointer to the
613 byte after the last byte copied. */
615 append_string_max (char *dest, const char *src, const char *end)
617 int nbytes = min (end - dest, (int) strlen (src));
618 memcpy (dest, src, nbytes);
619 return dest + nbytes;
622 /* Makes certain that the compression buffer of H has room for another
623 element. If there's not room, pads out the current instruction
624 octet with zero and dumps out the buffer. */
626 ensure_buf_space (struct file_handle *h)
628 struct sfm_fhuser_ext *ext = h->ext;
630 if (ext->ptr >= ext->end)
632 memset (ext->x, 0, ext->y - ext->x);
635 if (!bufwrite (h, ext->buf, sizeof *ext->buf * 128))
641 /* Writes case ELEM consisting of N_ELEM flt64 elements to the system
642 file represented by H. Return success. */
644 sfm_write_case (struct file_handle * h, const flt64 *elem, int n_elem)
646 struct sfm_fhuser_ext *ext = h->ext;
647 const flt64 *end_elem = &elem[n_elem];
648 char *elem_type = ext->elem_type;
652 if (ext->compressed == 0)
653 return bufwrite (h, elem, sizeof *elem * n_elem);
655 if (ext->buf == NULL)
657 ext->buf = xmalloc (sizeof *ext->buf * 128);
659 ext->end = &ext->buf[128];
660 ext->x = (unsigned char *) (ext->ptr++);
661 ext->y = (unsigned char *) (ext->ptr);
663 for (; elem < end_elem; elem++, elem_type++)
665 if (ext->x >= ext->y)
667 if (!ensure_buf_space (h))
669 ext->x = (unsigned char *) (ext->ptr++);
670 ext->y = (unsigned char *) (ext->ptr);
673 if (*elem_type == NUMERIC)
675 if (*elem == -FLT64_MAX)
682 int value = *elem < 0 ? *elem - EPSILON : *elem + EPSILON;
684 if (value >= 1 - COMPRESSION_BIAS
685 && value <= 251 - COMPRESSION_BIAS
686 && approx_eq (value, *elem))
688 *ext->x++ = value + COMPRESSION_BIAS;
695 if (0 == memcmp ((char *) elem,
705 if (!ensure_buf_space (h))
713 /* Closes a system file after we're done with it. */
715 sfm_close (struct file_handle * h)
717 struct sfm_fhuser_ext *ext = h->ext;
719 if (ext->buf != NULL && ext->ptr > ext->buf)
721 memset (ext->x, 0, ext->y - ext->x);
722 bufwrite (h, ext->buf, (ext->ptr - ext->buf) * sizeof *ext->buf);
725 /* Attempt to seek back to the beginning in order to write the
726 number of cases. If that's not possible (i.e., we're writing to
727 a tty or a pipe), then it's not a big deal because we wrote the
728 code that indicates an unknown number of cases. */
729 if (0 == fseek (ext->file, offsetof (struct sysfile_header, ncases),
732 int32 n_cases = ext->n_cases;
734 /* I don't really care about the return value: it doesn't matter
735 whether this data is written. This is the only situation in
736 which you will see me fail to check a return value. */
737 fwrite (&n_cases, sizeof n_cases, 1, ext->file);
740 if (EOF == fclose (ext->file))
741 msg (ME, _("%s: Closing system file: %s."), h->fn, strerror (errno));
744 free (ext->elem_type);
748 static struct fh_ext_class sfm_w_class =
751 N_("writing as a system file"),