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: already opened for %s."),
96 fh_handle_name (inf->h), inf->h->class->name);
100 msg (VM (1), _("%s: Opening system-file handle %s for writing."),
101 fh_handle_filename (inf->h), fh_handle_name (inf->h));
103 /* Open the physical disk file. */
104 inf->h->class = &sfm_w_class;
105 inf->h->ext = ext = xmalloc (sizeof (struct sfm_fhuser_ext));
106 ext->file = fopen (inf->h->norm_fn, "wb");
107 ext->elem_type = NULL;
108 if (ext->file == NULL)
110 msg (ME, _("An error occurred while opening \"%s\" for writing "
111 "as a system file: %s."), inf->h->fn, strerror (errno));
117 /* Initialize the sfm_fhuser_ext structure. */
118 ext->compressed = inf->compress;
119 ext->buf = ext->ptr = NULL;
120 ext->x = ext->y = NULL;
123 /* Write the file header. */
124 if (!write_header (inf))
127 /* Write basic variable info. */
128 for (i = 0; i < dict_get_var_cnt (d); i++)
129 write_variable (inf, dict_get_var (d, i));
131 /* Write out value labels. */
132 for (index = i = 0; i < dict_get_var_cnt (d); i++)
134 struct variable *v = dict_get_var (d, i);
136 if (!write_value_labels (inf, v, index))
138 index += (v->type == NUMERIC ? 1
139 : DIV_RND_UP (v->width, sizeof (flt64)));
142 if (dict_get_documents (d) != NULL && !write_documents (inf))
144 if (!write_rec_7_34 (inf))
147 /* Write record 999. */
156 rec_999.rec_type = 999;
159 if (!bufwrite (inf->h, &rec_999, sizeof rec_999))
163 msg (VM (2), _("Wrote system-file header successfully."));
168 msg (VM (1), _("Error writing system-file header."));
170 inf->h->class = NULL;
172 free (ext->elem_type);
173 ext->elem_type = NULL;
177 /* Returns value of X truncated to two least-significant digits. */
188 /* Write the sysfile_header header to the system file represented by
191 write_header (struct sfm_write_info *inf)
193 struct dictionary *d = inf->dict;
194 struct sfm_fhuser_ext *ext = inf->h->ext;
195 struct sysfile_header hdr;
201 memcpy (hdr.rec_type, "$FL2", 4);
203 p = stpcpy (hdr.prod_name, "@(#) SPSS DATA FILE ");
204 p = append_string_max (p, version, &hdr.prod_name[60]);
205 p = append_string_max (p, " - ", &hdr.prod_name[60]);
206 p = append_string_max (p, host_system, &hdr.prod_name[60]);
207 memset (p, ' ', &hdr.prod_name[60] - p);
212 for (i = 0; i < dict_get_var_cnt (d); i++)
214 struct variable *v = dict_get_var (d, i);
215 hdr.case_size += (v->type == NUMERIC ? 1
216 : DIV_RND_UP (v->width, sizeof (flt64)));
218 inf->case_size = hdr.case_size;
220 p = ext->elem_type = xmalloc (inf->case_size);
221 for (i = 0; i < dict_get_var_cnt (d); i++)
223 struct variable *v = dict_get_var (d, i);
224 int count = (v->type == NUMERIC ? 1
225 : DIV_RND_UP (v->width, sizeof (flt64)));
230 hdr.compressed = inf->compress;
232 if (dict_get_weight (d) != NULL)
234 struct variable *weight_var;
235 int recalc_weight_index = 1;
238 weight_var = dict_get_weight (d);
241 struct variable *v = dict_get_var (d, i);
244 recalc_weight_index += (v->type == NUMERIC ? 1
245 : DIV_RND_UP (v->width, sizeof (flt64)));
247 hdr.weight_index = recalc_weight_index;
250 hdr.weight_index = 0;
253 hdr.bias = COMPRESSION_BIAS;
255 if ((time_t) - 1 == time (&t))
257 memcpy (hdr.creation_date, "01 Jan 70", 9);
258 memcpy (hdr.creation_time, "00:00:00", 8);
262 static const char *month_name[12] =
264 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
265 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
267 struct tm *tmp = localtime (&t);
268 int day = rerange (tmp->tm_mday);
269 int mon = rerange (tmp->tm_mon + 1);
270 int year = rerange (tmp->tm_year);
271 int hour = rerange (tmp->tm_hour + 1);
272 int min = rerange (tmp->tm_min + 1);
273 int sec = rerange (tmp->tm_sec + 1);
276 sprintf (buf, "%02d %s %02d", day, month_name[mon - 1], year);
277 memcpy (hdr.creation_date, buf, sizeof hdr.creation_date);
278 sprintf (buf, "%02d:%02d:%02d", hour - 1, min - 1, sec - 1);
279 memcpy (hdr.creation_time, buf, sizeof hdr.creation_time);
283 const char *label = dict_get_label (d);
287 st_bare_pad_copy (hdr.file_label, label, sizeof hdr.file_label);
290 memset (hdr.padding, 0, sizeof hdr.padding);
292 if (!bufwrite (inf->h, &hdr, sizeof hdr))
297 /* Translates format spec from internal form in SRC to system file
300 write_format_spec (struct fmt_spec *src, int32 *dest)
302 *dest = (formats[src->type].spss << 16) | (src->w << 8) | src->d;
305 /* Write the variable record(s) for primary variable P and secondary
306 variable S to the system file represented by INF. */
308 write_variable (struct sfm_write_info *inf, struct variable *v)
310 struct sysfile_variable sv;
312 /* Missing values. */
313 flt64 m[3]; /* Missing value values. */
314 int nm; /* Number of missing values, possibly negative. */
317 sv.type = (v->type == NUMERIC ? 0 : v->width);
318 sv.has_var_label = (v->label != NULL);
320 switch (v->miss_type)
328 for (nm = 0; nm < v->miss_type; nm++)
329 m[nm] = v->missing[nm].f;
332 m[0] = v->missing[0].f;
333 m[1] = v->missing[1].f;
337 m[0] = second_lowest_flt64;
338 m[1] = v->missing[0].f;
342 m[0] = v->missing[0].f;
346 case MISSING_RANGE_1:
347 m[0] = v->missing[0].f;
348 m[1] = v->missing[1].f;
349 m[2] = v->missing[2].f;
353 m[0] = second_lowest_flt64;
354 m[1] = v->missing[0].f;
355 m[2] = v->missing[1].f;
359 m[0] = v->missing[0].f;
360 m[1] = second_lowest_flt64;
361 m[2] = v->missing[1].f;
368 sv.n_missing_values = nm;
369 write_format_spec (&v->print, &sv.print);
370 write_format_spec (&v->write, &sv.write);
371 memcpy (sv.name, v->name, strlen (v->name));
372 memset (&sv.name[strlen (v->name)], ' ', 8 - strlen (v->name));
373 if (!bufwrite (inf->h, &sv, sizeof sv))
387 l.label_len = min (strlen (v->label), 120);
388 ext_len = ROUND_UP (l.label_len, sizeof l.label_len);
389 memcpy (l.label, v->label, l.label_len);
390 memset (&l.label[l.label_len], ' ', ext_len - l.label_len);
392 if (!bufwrite (inf->h, &l, offsetof (struct label, label) + ext_len))
396 if (nm && !bufwrite (inf->h, m, sizeof *m * nm))
399 if (v->type == ALPHA && v->width > (int) sizeof (flt64))
405 sv.has_var_label = 0;
406 sv.n_missing_values = 0;
407 memset (&sv.print, 0, sizeof sv.print);
408 memset (&sv.write, 0, sizeof sv.write);
409 memset (&sv.name, 0, sizeof sv.name);
411 pad_count = DIV_RND_UP (v->width, (int) sizeof (flt64)) - 1;
412 for (i = 0; i < pad_count; i++)
413 if (!bufwrite (inf->h, &sv, sizeof sv))
420 /* Writes the value labels for variable V having system file variable
421 index INDEX to the system file associated with INF. Returns
422 nonzero only if successful. */
424 write_value_labels (struct sfm_write_info * inf, struct variable *v, int index)
426 struct value_label_rec
433 struct variable_index_rec
440 struct val_labs_iterator *i;
441 struct value_label_rec *vlr;
442 struct variable_index_rec vir;
447 if (!val_labs_count (v->val_labs))
450 /* Pass 1: Count bytes. */
451 vlr_size = (sizeof (struct value_label_rec)
452 + sizeof (flt64) * (val_labs_count (v->val_labs) - 1));
453 for (vl = val_labs_first (v->val_labs, &i); vl != NULL;
454 vl = val_labs_next (v->val_labs, &i))
455 vlr_size += ROUND_UP (strlen (vl->label) + 1, sizeof (flt64));
457 /* Pass 2: Copy bytes. */
458 vlr = xmalloc (vlr_size);
460 vlr->n_labels = val_labs_count (v->val_labs);
462 for (vl = val_labs_first_sorted (v->val_labs, &i); vl != NULL;
463 vl = val_labs_next (v->val_labs, &i))
465 size_t len = strlen (vl->label);
467 *loc++ = vl->value.f;
468 *(unsigned char *) loc = len;
469 memcpy (&((unsigned char *) loc)[1], vl->label, len);
470 memset (&((unsigned char *) loc)[1 + len], ' ',
471 REM_RND_UP (len + 1, sizeof (flt64)));
472 loc += DIV_RND_UP (len + 1, sizeof (flt64));
475 if (!bufwrite (inf->h, vlr, vlr_size))
484 vir.vars[0] = index + 1;
485 if (!bufwrite (inf->h, &vir, sizeof vir))
491 /* Writes record type 6, document record. */
493 write_documents (struct sfm_write_info * inf)
495 struct dictionary *d = inf->dict;
498 int32 rec_type P; /* Always 6. */
499 int32 n_lines P; /* Number of lines of documents. */
503 const char *documents;
506 documents = dict_get_documents (d);
507 n_lines = strlen (documents) / 80;
510 rec_6.n_lines = n_lines;
511 if (!bufwrite (inf->h, &rec_6, sizeof rec_6))
513 if (!bufwrite (inf->h, documents, 80 * n_lines))
519 /* Writes record type 7, subtypes 3 and 4. */
521 write_rec_7_34 (struct sfm_write_info * inf)
538 /* Components of the version number, from major to minor. */
539 int version_component[3];
541 /* Used to step through the version string. */
544 /* Parses the version string, which is assumed to be of the form
545 #.#x, where each # is a string of digits, and x is a single
547 version_component[0] = strtol (bare_version, &p, 10);
550 version_component[1] = strtol (bare_version, &p, 10);
551 version_component[2] = (isalpha ((unsigned char) *p)
552 ? tolower ((unsigned char) *p) - 'a' : 0);
554 rec_7.rec_type_3 = 7;
556 rec_7.data_type_3 = sizeof (int32);
558 rec_7.elem_3[0] = version_component[0];
559 rec_7.elem_3[1] = version_component[1];
560 rec_7.elem_3[2] = version_component[2];
561 rec_7.elem_3[3] = -1;
563 /* PORTME: 1=IEEE754, 2=IBM 370, 3=DEC VAX E. */
570 /* PORTME: 1=big-endian, 2=little-endian. */
577 /* PORTME: 1=EBCDIC, 2=7-bit ASCII, 3=8-bit ASCII, 4=DEC Kanji. */
580 rec_7.rec_type_4 = 7;
582 rec_7.data_type_4 = sizeof (flt64);
584 rec_7.elem_4[0] = -FLT64_MAX;
585 rec_7.elem_4[1] = FLT64_MAX;
586 rec_7.elem_4[2] = second_lowest_flt64;
588 if (!bufwrite (inf->h, &rec_7, sizeof rec_7))
593 /* Write NBYTES starting at BUF to the system file represented by
596 bufwrite (struct file_handle * h, const void *buf, size_t nbytes)
598 struct sfm_fhuser_ext *ext = h->ext;
601 if (1 != fwrite (buf, nbytes, 1, ext->file))
603 msg (ME, _("%s: Writing system file: %s."), h->fn, strerror (errno));
609 /* Copies string DEST to SRC with the proviso that DEST does not reach
610 byte END; no null terminator is copied. Returns a pointer to the
611 byte after the last byte copied. */
613 append_string_max (char *dest, const char *src, const char *end)
615 int nbytes = min (end - dest, (int) strlen (src));
616 memcpy (dest, src, nbytes);
617 return dest + nbytes;
620 /* Makes certain that the compression buffer of H has room for another
621 element. If there's not room, pads out the current instruction
622 octet with zero and dumps out the buffer. */
624 ensure_buf_space (struct file_handle *h)
626 struct sfm_fhuser_ext *ext = h->ext;
628 if (ext->ptr >= ext->end)
630 memset (ext->x, 0, ext->y - ext->x);
633 if (!bufwrite (h, ext->buf, sizeof *ext->buf * 128))
639 /* Writes case ELEM consisting of N_ELEM flt64 elements to the system
640 file represented by H. Return success. */
642 sfm_write_case (struct file_handle * h, const flt64 *elem, int n_elem)
644 struct sfm_fhuser_ext *ext = h->ext;
645 const flt64 *end_elem = &elem[n_elem];
646 char *elem_type = ext->elem_type;
650 if (ext->compressed == 0)
651 return bufwrite (h, elem, sizeof *elem * n_elem);
653 if (ext->buf == NULL)
655 ext->buf = xmalloc (sizeof *ext->buf * 128);
657 ext->end = &ext->buf[128];
658 ext->x = (unsigned char *) (ext->ptr++);
659 ext->y = (unsigned char *) (ext->ptr);
661 for (; elem < end_elem; elem++, elem_type++)
663 if (ext->x >= ext->y)
665 if (!ensure_buf_space (h))
667 ext->x = (unsigned char *) (ext->ptr++);
668 ext->y = (unsigned char *) (ext->ptr);
671 if (*elem_type == NUMERIC)
673 if (*elem == -FLT64_MAX)
678 else if (*elem > INT_MIN && *elem < INT_MAX)
682 if (value >= 1 - COMPRESSION_BIAS
683 && value <= 251 - COMPRESSION_BIAS
686 *ext->x++ = value + COMPRESSION_BIAS;
693 if (0 == memcmp ((char *) elem,
703 if (!ensure_buf_space (h))
711 /* Closes a system file after we're done with it. */
713 sfm_close (struct file_handle * h)
715 struct sfm_fhuser_ext *ext = h->ext;
717 if (ext->buf != NULL && ext->ptr > ext->buf)
719 memset (ext->x, 0, ext->y - ext->x);
720 bufwrite (h, ext->buf, (ext->ptr - ext->buf) * sizeof *ext->buf);
723 /* Attempt to seek back to the beginning in order to write the
724 number of cases. If that's not possible (i.e., we're writing to
725 a tty or a pipe), then it's not a big deal because we wrote the
726 code that indicates an unknown number of cases. */
727 if (0 == fseek (ext->file, offsetof (struct sysfile_header, ncases),
730 int32 n_cases = ext->n_cases;
732 /* I don't really care about the return value: it doesn't matter
733 whether this data is written. This is the only situation in
734 which you will see me fail to check a return value. */
735 fwrite (&n_cases, sizeof n_cases, 1, ext->file);
738 if (EOF == fclose (ext->file))
739 msg (ME, _("%s: Closing system file: %s."), h->fn, strerror (errno));
742 free (ext->elem_type);
746 static struct fh_ext_class sfm_w_class =
749 N_("writing as a system file"),