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 "pfm-write.h"
32 #include "dictionary.h"
34 #include "file-handle.h"
39 #include "value-labels.h"
44 #define _(msgid) gettext (msgid)
46 #include "debug-print.h"
48 /* Portable file writer. */
51 struct file_handle *fh; /* File handle. */
52 FILE *file; /* File stream. */
54 int lc; /* Number of characters on this line so far. */
56 size_t var_cnt; /* Number of variables. */
57 struct pfm_var *vars; /* Variables. */
60 /* A variable to write to the portable file. */
63 int width; /* 0=numeric, otherwise string var width. */
64 int fv; /* Starting case index. */
67 static int buf_write (struct pfm_writer *, const void *, size_t);
68 static int write_header (struct pfm_writer *);
69 static int write_version_data (struct pfm_writer *);
70 static int write_variables (struct pfm_writer *, struct dictionary *);
71 static int write_value_labels (struct pfm_writer *, const struct dictionary *);
73 static void format_trig_double (long double, int base_10_precision, char[]);
74 static char *format_trig_int (int, bool force_sign, char[]);
76 /* Writes the dictionary DICT to portable file HANDLE. Returns
77 nonzero only if successful. DICT will not be modified, except
78 to assign short names. */
80 pfm_open_writer (struct file_handle *fh, struct dictionary *dict)
82 struct pfm_writer *w = NULL;
85 if (!fh_open (fh, "portable file", "we"))
88 /* Open the physical disk file. */
89 w = xmalloc (sizeof *w);
91 w->file = fopen (handle_get_filename (fh), "wb");
96 /* Check that file create succeeded. */
99 msg (ME, _("An error occurred while opening \"%s\" for writing "
100 "as a portable file: %s."),
101 handle_get_filename (fh), strerror (errno));
106 w->var_cnt = dict_get_var_cnt (dict);
107 w->vars = xmalloc (sizeof *w->vars * w->var_cnt);
108 for (i = 0; i < w->var_cnt; i++)
110 const struct variable *dv = dict_get_var (dict, i);
111 struct pfm_var *pv = &w->vars[i];
112 pv->width = dv->width;
116 /* Write file header. */
117 if (!write_header (w)
118 || !write_version_data (w)
119 || !write_variables (w, dict)
120 || !write_value_labels (w, dict)
121 || !buf_write (w, "F", 1))
127 pfm_close_writer (w);
131 /* Write NBYTES starting at BUF to the portable file represented by
132 H. Break lines properly every 80 characters. */
134 buf_write (struct pfm_writer *w, const void *buf_, size_t nbytes)
136 const char *buf = buf_;
138 assert (buf != NULL);
139 while (nbytes + w->lc >= 80)
141 size_t n = 80 - w->lc;
143 if (n && fwrite (buf, n, 1, w->file) != 1)
146 if (fwrite ("\r\n", 2, 1, w->file) != 1)
154 if (nbytes && 1 != fwrite (buf, nbytes, 1, w->file))
161 msg (ME, _("%s: Writing portable file: %s."),
162 handle_get_filename (w->fh), strerror (errno));
166 /* Write D to the portable file as a floating-point field, and return
169 write_float (struct pfm_writer *w, double d)
172 format_trig_double (d, DBL_DIG, buffer);
173 return buf_write (w, buffer, strlen (buffer)) && buf_write (w, "/", 1);
176 /* Write N to the portable file as an integer field, and return success. */
178 write_int (struct pfm_writer *w, int n)
181 format_trig_int (n, false, buffer);
182 return buf_write (w, buffer, strlen (buffer)) && buf_write (w, "/", 1);
185 /* Write S to the portable file as a string field. */
187 write_string (struct pfm_writer *w, const char *s)
189 size_t n = strlen (s);
190 return write_int (w, (int) n) && buf_write (w, s, n);
193 /* Write file header. */
195 write_header (struct pfm_writer *w)
201 for (i = 0; i < 5; i++)
202 if (!buf_write (w, "ASCII SPSS PORT FILE ", 40))
207 /* PORTME: Translation table from SPSS character code to this
208 computer's native character code (which is probably ASCII). */
209 static const unsigned char spss2ascii[256] =
211 "0000000000000000000000000000000000000000000000000000000000000000"
212 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ."
213 "<(+|&[]!$*);^-/|,%_>?`:$@'=\"000000~-0000123456789000-()0{}\\00000"
214 "0000000000000000000000000000000000000000000000000000000000000000"
217 if (!buf_write (w, spss2ascii, 256))
221 if (!buf_write (w, "SPSSPORT", 8))
227 /* Writes version, date, and identification records. */
229 write_version_data (struct pfm_writer *w)
231 if (!buf_write (w, "A", 1))
241 if ((time_t) -1 == time (&t))
243 tm.tm_sec = tm.tm_min = tm.tm_hour = tm.tm_mon = tm.tm_year = 0;
248 tmp = localtime (&t);
250 sprintf (date_str, "%04d%02d%02d",
251 tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday);
252 sprintf (time_str, "%02d%02d%02d", tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
253 if (!write_string (w, date_str) || !write_string (w, time_str))
257 /* Product identification. */
258 if (!buf_write (w, "1", 1) || !write_string (w, version))
261 /* Subproduct identification. */
262 if (!buf_write (w, "3", 1) || !write_string (w, host_system))
268 /* Write format F to file H, and return success. */
270 write_format (struct pfm_writer *w, struct fmt_spec *f)
272 return (write_int (w, formats[f->type].spss)
273 && write_int (w, f->w)
274 && write_int (w, f->d));
277 /* Write value V for variable VV to file H, and return success. */
279 write_value (struct pfm_writer *w, union value *v, struct variable *vv)
281 if (vv->type == NUMERIC)
282 return write_float (w, v->f);
284 return write_int (w, vv->width) && buf_write (w, v->s, vv->width);
287 /* Write variable records, and return success. */
289 write_variables (struct pfm_writer *w, struct dictionary *dict)
293 dict_assign_short_names (dict);
295 if (!buf_write (w, "4", 1) || !write_int (w, dict_get_var_cnt (dict))
296 || !write_int (w, 161))
299 for (i = 0; i < dict_get_var_cnt (dict); i++)
301 static const char *miss_types[MISSING_COUNT] =
303 "", "8", "88", "888", "B ", "9", "A", "B 8", "98", "A8",
309 struct variable *v = dict_get_var (dict, i);
311 if (!buf_write (w, "7", 1) || !write_int (w, v->width)
312 || !write_string (w, v->short_name)
313 || !write_format (w, &v->print) || !write_format (w, &v->write))
316 for (m = miss_types[v->miss_type], j = 0; j < (int) strlen (m); j++)
317 if ((m[j] != ' ' && !buf_write (w, &m[j], 1))
318 || !write_value (w, &v->missing[j], v))
321 if (v->label && (!buf_write (w, "C", 1) || !write_string (w, v->label)))
328 /* Write value labels to disk. FIXME: Inefficient. */
330 write_value_labels (struct pfm_writer *w, const struct dictionary *dict)
334 for (i = 0; i < dict_get_var_cnt (dict); i++)
336 struct val_labs_iterator *j;
337 struct variable *v = dict_get_var (dict, i);
340 if (!val_labs_count (v->val_labs))
343 if (!buf_write (w, "D", 1)
345 || !write_string (w, v->short_name)
346 || !write_int (w, val_labs_count (v->val_labs)))
349 for (vl = val_labs_first_sorted (v->val_labs, &j); vl != NULL;
350 vl = val_labs_next (v->val_labs, &j))
351 if (!write_value (w, &vl->value, v)
352 || !write_string (w, vl->label))
362 /* Writes case ELEM to the portable file represented by H. Returns
365 pfm_write_case (struct pfm_writer *w, struct ccase *c)
369 for (i = 0; i < w->var_cnt; i++)
371 struct pfm_var *v = &w->vars[i];
375 if (!write_float (w, case_num (c, v->fv)))
380 if (!write_int (w, v->width)
381 || !buf_write (w, case_str (c, v->fv), v->width))
389 /* Closes a portable file after we're done with it. */
391 pfm_close_writer (struct pfm_writer *w)
396 fh_close (w->fh, "portable file", "we");
406 memset (buf, 'Z', n);
407 buf_write (w, buf, n);
409 if (fclose (w->file) == EOF)
410 msg (ME, _("%s: Closing portable file: %s."),
411 handle_get_filename (w->fh), strerror (errno));
418 /* Base-30 conversion.
420 Portable files represent numbers in base-30 format, so we need
421 to be able to convert real and integer number to that base.
422 Older versions of PSPP used libgmp to do so, but this added a
423 big library dependency to do just one thing. Now we do it
424 ourselves internally.
426 Important fact: base 30 is called "trigesimal". */
428 /* Conversion base. */
429 #define BASE 30 /* As an integer. */
430 #define LDBASE ((long double) BASE) /* As a long double. */
432 /* This is floor(log30(2**31)), the minimum number of trigesimal
433 digits that a `long int' can hold. */
436 /* pow_tab[i] = pow (30, pow (2, i)) */
437 static long double pow_tab[16];
439 /* Initializes pow_tab[]. */
443 static bool did_init = false;
447 /* Only initialize once. */
452 /* Set each element of pow_tab[] until we run out of numerical
455 for (power = 30.0L; power < DBL_MAX; power *= power)
457 assert (i < sizeof pow_tab / sizeof *pow_tab);
458 pow_tab[i++] = power;
462 /* Returns 30**EXPONENT, for 0 <= EXPONENT <= log30(DBL_MAX). */
464 pow30_nonnegative (int exponent)
469 assert (exponent >= 0);
470 assert (exponent < 1L << (sizeof pow_tab / sizeof *pow_tab));
473 for (i = 0; exponent > 0; exponent >>= 1, i++)
480 /* Returns 30**EXPONENT, for log30(DBL_MIN) <= EXPONENT <=
486 return pow30_nonnegative (exponent);
488 return 1.L / pow30_nonnegative (-exponent);
491 /* Returns the character corresponding to TRIG. */
493 trig_to_char (int trig)
495 assert (trig >= 0 && trig < 30);
496 return "0123456789ABCDEFGHIJKLMNOPQRST"[trig];
499 /* Formats the TRIG_CNT trigs in TRIGS[], writing them as
500 null-terminated STRING. The trigesimal point is inserted
501 after TRIG_PLACES characters have been printed, if necessary
502 adding extra zeros at either end for correctness. Returns the
503 character after the formatted number. */
505 format_trig_digits (char *string,
506 const char trigs[], int trig_cnt, int trig_places)
511 while (trig_places++ < 0)
515 while (trig_cnt-- > 0)
517 if (trig_places-- == 0)
519 *string++ = trig_to_char (*trigs++);
521 while (trig_places-- > 0)
527 /* Helper function for format_trig_int() that formats VALUE as a
528 trigesimal integer at CP. VALUE must be nonnegative.
529 Returns the character following the formatted integer. */
531 recurse_format_trig_int (char *cp, int value)
533 int trig = value % BASE;
536 cp = recurse_format_trig_int (cp, value);
537 *cp++ = trig_to_char (trig);
541 /* Formats VALUE as a trigesimal integer in null-terminated
542 STRING[]. VALUE must be in the range -DBL_MAX...DBL_MAX. If
543 FORCE_SIGN is true, a sign is always inserted; otherwise, a
544 sign is only inserted if VALUE is negative. */
546 format_trig_int (int value, bool force_sign, char string[])
557 /* Format integer. */
558 string = recurse_format_trig_int (string, value);
563 /* Determines whether the TRIG_CNT trigesimals in TRIGS[] warrant
564 rounding up or down. Returns true if TRIGS[] represents a
565 value greater than half, false if less than half. If TRIGS[]
566 is exactly half, examines TRIGS[-1] and returns true if odd,
567 false if even ("round to even"). */
569 should_round_up (const char trigs[], int trig_cnt)
571 assert (trig_cnt > 0);
573 if (*trigs < BASE / 2)
575 /* Less than half: round down. */
578 else if (*trigs > BASE / 2)
580 /* Greater than half: round up. */
585 /* Approximately half: look more closely. */
587 for (i = 1; i < trig_cnt; i++)
590 /* Slightly greater than half: round up. */
594 /* Exactly half: round to even. */
595 return trigs[-1] % 2;
599 /* Rounds up the rightmost trig in the TRIG_CNT trigs in TRIGS[],
600 carrying to the left as necessary. Returns true if
601 successful, false on failure (due to a carry out of the
602 leftmost position). */
604 try_round_up (char *trigs, int trig_cnt)
608 char *round_trig = trigs + --trig_cnt;
609 if (*round_trig != BASE - 1)
611 /* Round this trig up to the next value. */
616 /* Carry over to the next trig to the left. */
620 /* Ran out of trigs to carry. */
624 /* Converts VALUE to trigesimal format in string OUTPUT[] with the
625 equivalent of at least BASE_10_PRECISION decimal digits of
626 precision. The output format may use conventional or
627 scientific notation. Missing, infinite, and extreme values
628 are represented with "*.". */
630 format_trig_double (long double value, int base_10_precision, char output[])
632 /* Original VALUE was negative? */
635 /* Number of significant trigesimals. */
636 int base_30_precision;
638 /* Base-2 significand and exponent for original VALUE. */
642 /* VALUE as a set of trigesimals. */
643 char buffer[DBL_DIG + 16];
647 /* Number of trigesimal places for trigs.
648 trigs[0] has coefficient 30**(trig_places - 1),
649 trigs[1] has coefficient 30**(trig_places - 2),
651 In other words, the trigesimal point is just before trigs[0].
655 /* Number of trigesimal places left to write into BUFFER. */
660 /* Handle special cases. */
666 /* Make VALUE positive. */
675 /* Adjust VALUE to roughly 30**3, by shifting the trigesimal
676 point left or right as necessary. We approximate the
677 base-30 exponent by obtaining the base-2 exponent, then
678 multiplying by log30(2). This approximation is sufficient
679 to ensure that the adjusted VALUE is always in the range
680 0...30**6, an invariant of the loop below. */
682 base_2_sig = frexp (value, &base_2_exp);
683 if (errno != 0 || !finite (base_2_sig))
685 if (base_2_exp == 0 && base_2_sig == 0.)
687 if (base_2_exp <= INT_MIN / 20379L || base_2_exp >= INT_MAX / 20379L)
689 trig_places = (base_2_exp * 20379L / 100000L) + CHUNK_SIZE / 2;
690 value *= pow30 (CHUNK_SIZE - trig_places);
692 /* Dump all the trigs to buffer[], CHUNK_SIZE at a time. */
695 for (trigs_to_output = DIV_RND_UP (DBL_DIG * 2, 3) + 1 + (CHUNK_SIZE / 2);
697 trigs_to_output -= CHUNK_SIZE)
702 /* The current chunk is just the integer part of VALUE,
703 truncated to the nearest integer. The chunk fits in a
706 assert (pow30 (CHUNK_SIZE) <= LONG_MAX);
707 assert (chunk >= 0 && chunk < pow30 (CHUNK_SIZE));
711 /* Append the chunk, in base 30, to trigs[]. */
712 for (trigs_left = CHUNK_SIZE; chunk > 0 && trigs_left > 0; )
714 trigs[trig_cnt + --trigs_left] = chunk % 30;
717 while (trigs_left > 0)
718 trigs[trig_cnt + --trigs_left] = 0;
719 trig_cnt += CHUNK_SIZE;
721 /* Proceed to the next chunk. */
724 value *= pow (LDBASE, CHUNK_SIZE);
727 /* Strip leading zeros. */
728 while (trig_cnt > 1 && *trigs == 0)
735 /* Round to requested precision, conservatively estimating the
736 required base-30 precision as 2/3 of the base-10 precision
737 (log30(10) = .68). */
738 assert (base_10_precision > 0);
739 base_30_precision = DIV_RND_UP (base_10_precision * 2, 3);
740 if (trig_cnt > base_30_precision)
742 if (should_round_up (trigs + base_30_precision,
743 trig_cnt - base_30_precision))
745 /* Try to round up. */
746 if (try_round_up (trigs, base_30_precision))
748 /* Rounding up worked. */
749 trig_cnt = base_30_precision;
753 /* Couldn't round up because we ran out of trigs to
754 carry into. Do the carry here instead. */
763 trig_cnt = base_30_precision;
768 /* No rounding required: fewer digits available than
772 /* Strip trailing zeros. */
773 while (trig_cnt > 1 && trigs[trig_cnt - 1] == 0)
779 if (trig_places >= -1 && trig_places < trig_cnt + 3)
781 /* Use conventional notation. */
782 format_trig_digits (output, trigs, trig_cnt, trig_places);
786 /* Use scientific notation. */
788 op = format_trig_digits (output, trigs, trig_cnt, trig_cnt);
789 op = format_trig_int (trig_places - trig_cnt, true, op);
794 strcpy (output, "0");
798 strcpy (output, "*.");