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 struct variable *v = dict_get_var (dict, i);
302 struct missing_values mv;
304 if (!buf_write (w, "7", 1) || !write_int (w, v->width)
305 || !write_string (w, v->short_name)
306 || !write_format (w, &v->print) || !write_format (w, &v->write))
309 /* Write missing values. */
310 mv_copy (&mv, &v->miss);
311 while (mv_has_range (&mv))
314 mv_pop_range (&mv, &x, &y);
317 if (!buf_write (w, "9", 1) || !write_float (w, y))
320 else if (y == HIGHEST)
322 if (!buf_write (w, "A", 1) || !write_float (w, y))
326 if (!buf_write (w, "B", 1) || !write_float (w, x)
327 || !write_float (w, y))
331 while (mv_has_value (&mv))
334 mv_pop_value (&mv, &value);
335 if (!buf_write (w, "8", 1) || !write_value (w, &value, v))
339 if (v->label && (!buf_write (w, "C", 1) || !write_string (w, v->label)))
346 /* Write value labels to disk. FIXME: Inefficient. */
348 write_value_labels (struct pfm_writer *w, const struct dictionary *dict)
352 for (i = 0; i < dict_get_var_cnt (dict); i++)
354 struct val_labs_iterator *j;
355 struct variable *v = dict_get_var (dict, i);
358 if (!val_labs_count (v->val_labs))
361 if (!buf_write (w, "D", 1)
363 || !write_string (w, v->short_name)
364 || !write_int (w, val_labs_count (v->val_labs)))
367 for (vl = val_labs_first_sorted (v->val_labs, &j); vl != NULL;
368 vl = val_labs_next (v->val_labs, &j))
369 if (!write_value (w, &vl->value, v)
370 || !write_string (w, vl->label))
380 /* Writes case ELEM to the portable file represented by H. Returns
383 pfm_write_case (struct pfm_writer *w, struct ccase *c)
387 for (i = 0; i < w->var_cnt; i++)
389 struct pfm_var *v = &w->vars[i];
393 if (!write_float (w, case_num (c, v->fv)))
398 if (!write_int (w, v->width)
399 || !buf_write (w, case_str (c, v->fv), v->width))
407 /* Closes a portable file after we're done with it. */
409 pfm_close_writer (struct pfm_writer *w)
414 fh_close (w->fh, "portable file", "we");
424 memset (buf, 'Z', n);
425 buf_write (w, buf, n);
427 if (fclose (w->file) == EOF)
428 msg (ME, _("%s: Closing portable file: %s."),
429 handle_get_filename (w->fh), strerror (errno));
436 /* Base-30 conversion.
438 Portable files represent numbers in base-30 format, so we need
439 to be able to convert real and integer number to that base.
440 Older versions of PSPP used libgmp to do so, but this added a
441 big library dependency to do just one thing. Now we do it
442 ourselves internally.
444 Important fact: base 30 is called "trigesimal". */
446 /* Conversion base. */
447 #define BASE 30 /* As an integer. */
448 #define LDBASE ((long double) BASE) /* As a long double. */
450 /* This is floor(log30(2**31)), the minimum number of trigesimal
451 digits that a `long int' can hold. */
454 /* pow_tab[i] = pow (30, pow (2, i)) */
455 static long double pow_tab[16];
457 /* Initializes pow_tab[]. */
461 static bool did_init = false;
465 /* Only initialize once. */
470 /* Set each element of pow_tab[] until we run out of numerical
473 for (power = 30.0L; power < DBL_MAX; power *= power)
475 assert (i < sizeof pow_tab / sizeof *pow_tab);
476 pow_tab[i++] = power;
480 /* Returns 30**EXPONENT, for 0 <= EXPONENT <= log30(DBL_MAX). */
482 pow30_nonnegative (int exponent)
487 assert (exponent >= 0);
488 assert (exponent < 1L << (sizeof pow_tab / sizeof *pow_tab));
491 for (i = 0; exponent > 0; exponent >>= 1, i++)
498 /* Returns 30**EXPONENT, for log30(DBL_MIN) <= EXPONENT <=
504 return pow30_nonnegative (exponent);
506 return 1.L / pow30_nonnegative (-exponent);
509 /* Returns the character corresponding to TRIG. */
511 trig_to_char (int trig)
513 assert (trig >= 0 && trig < 30);
514 return "0123456789ABCDEFGHIJKLMNOPQRST"[trig];
517 /* Formats the TRIG_CNT trigs in TRIGS[], writing them as
518 null-terminated STRING. The trigesimal point is inserted
519 after TRIG_PLACES characters have been printed, if necessary
520 adding extra zeros at either end for correctness. Returns the
521 character after the formatted number. */
523 format_trig_digits (char *string,
524 const char trigs[], int trig_cnt, int trig_places)
529 while (trig_places++ < 0)
533 while (trig_cnt-- > 0)
535 if (trig_places-- == 0)
537 *string++ = trig_to_char (*trigs++);
539 while (trig_places-- > 0)
545 /* Helper function for format_trig_int() that formats VALUE as a
546 trigesimal integer at CP. VALUE must be nonnegative.
547 Returns the character following the formatted integer. */
549 recurse_format_trig_int (char *cp, int value)
551 int trig = value % BASE;
554 cp = recurse_format_trig_int (cp, value);
555 *cp++ = trig_to_char (trig);
559 /* Formats VALUE as a trigesimal integer in null-terminated
560 STRING[]. VALUE must be in the range -DBL_MAX...DBL_MAX. If
561 FORCE_SIGN is true, a sign is always inserted; otherwise, a
562 sign is only inserted if VALUE is negative. */
564 format_trig_int (int value, bool force_sign, char string[])
575 /* Format integer. */
576 string = recurse_format_trig_int (string, value);
581 /* Determines whether the TRIG_CNT trigesimals in TRIGS[] warrant
582 rounding up or down. Returns true if TRIGS[] represents a
583 value greater than half, false if less than half. If TRIGS[]
584 is exactly half, examines TRIGS[-1] and returns true if odd,
585 false if even ("round to even"). */
587 should_round_up (const char trigs[], int trig_cnt)
589 assert (trig_cnt > 0);
591 if (*trigs < BASE / 2)
593 /* Less than half: round down. */
596 else if (*trigs > BASE / 2)
598 /* Greater than half: round up. */
603 /* Approximately half: look more closely. */
605 for (i = 1; i < trig_cnt; i++)
608 /* Slightly greater than half: round up. */
612 /* Exactly half: round to even. */
613 return trigs[-1] % 2;
617 /* Rounds up the rightmost trig in the TRIG_CNT trigs in TRIGS[],
618 carrying to the left as necessary. Returns true if
619 successful, false on failure (due to a carry out of the
620 leftmost position). */
622 try_round_up (char *trigs, int trig_cnt)
626 char *round_trig = trigs + --trig_cnt;
627 if (*round_trig != BASE - 1)
629 /* Round this trig up to the next value. */
634 /* Carry over to the next trig to the left. */
638 /* Ran out of trigs to carry. */
642 /* Converts VALUE to trigesimal format in string OUTPUT[] with the
643 equivalent of at least BASE_10_PRECISION decimal digits of
644 precision. The output format may use conventional or
645 scientific notation. Missing, infinite, and extreme values
646 are represented with "*.". */
648 format_trig_double (long double value, int base_10_precision, char output[])
650 /* Original VALUE was negative? */
653 /* Number of significant trigesimals. */
654 int base_30_precision;
656 /* Base-2 significand and exponent for original VALUE. */
660 /* VALUE as a set of trigesimals. */
661 char buffer[DBL_DIG + 16];
665 /* Number of trigesimal places for trigs.
666 trigs[0] has coefficient 30**(trig_places - 1),
667 trigs[1] has coefficient 30**(trig_places - 2),
669 In other words, the trigesimal point is just before trigs[0].
673 /* Number of trigesimal places left to write into BUFFER. */
678 /* Handle special cases. */
684 /* Make VALUE positive. */
693 /* Adjust VALUE to roughly 30**3, by shifting the trigesimal
694 point left or right as necessary. We approximate the
695 base-30 exponent by obtaining the base-2 exponent, then
696 multiplying by log30(2). This approximation is sufficient
697 to ensure that the adjusted VALUE is always in the range
698 0...30**6, an invariant of the loop below. */
700 base_2_sig = frexp (value, &base_2_exp);
701 if (errno != 0 || !finite (base_2_sig))
703 if (base_2_exp == 0 && base_2_sig == 0.)
705 if (base_2_exp <= INT_MIN / 20379L || base_2_exp >= INT_MAX / 20379L)
707 trig_places = (base_2_exp * 20379L / 100000L) + CHUNK_SIZE / 2;
708 value *= pow30 (CHUNK_SIZE - trig_places);
710 /* Dump all the trigs to buffer[], CHUNK_SIZE at a time. */
713 for (trigs_to_output = DIV_RND_UP (DBL_DIG * 2, 3) + 1 + (CHUNK_SIZE / 2);
715 trigs_to_output -= CHUNK_SIZE)
720 /* The current chunk is just the integer part of VALUE,
721 truncated to the nearest integer. The chunk fits in a
724 assert (pow30 (CHUNK_SIZE) <= LONG_MAX);
725 assert (chunk >= 0 && chunk < pow30 (CHUNK_SIZE));
729 /* Append the chunk, in base 30, to trigs[]. */
730 for (trigs_left = CHUNK_SIZE; chunk > 0 && trigs_left > 0; )
732 trigs[trig_cnt + --trigs_left] = chunk % 30;
735 while (trigs_left > 0)
736 trigs[trig_cnt + --trigs_left] = 0;
737 trig_cnt += CHUNK_SIZE;
739 /* Proceed to the next chunk. */
742 value *= pow (LDBASE, CHUNK_SIZE);
745 /* Strip leading zeros. */
746 while (trig_cnt > 1 && *trigs == 0)
753 /* Round to requested precision, conservatively estimating the
754 required base-30 precision as 2/3 of the base-10 precision
755 (log30(10) = .68). */
756 assert (base_10_precision > 0);
757 base_30_precision = DIV_RND_UP (base_10_precision * 2, 3);
758 if (trig_cnt > base_30_precision)
760 if (should_round_up (trigs + base_30_precision,
761 trig_cnt - base_30_precision))
763 /* Try to round up. */
764 if (try_round_up (trigs, base_30_precision))
766 /* Rounding up worked. */
767 trig_cnt = base_30_precision;
771 /* Couldn't round up because we ran out of trigs to
772 carry into. Do the carry here instead. */
781 trig_cnt = base_30_precision;
786 /* No rounding required: fewer digits available than
790 /* Strip trailing zeros. */
791 while (trig_cnt > 1 && trigs[trig_cnt - 1] == 0)
797 if (trig_places >= -1 && trig_places < trig_cnt + 3)
799 /* Use conventional notation. */
800 format_trig_digits (output, trigs, trig_cnt, trig_places);
804 /* Use scientific notation. */
806 op = format_trig_digits (output, trigs, trig_cnt, trig_cnt);
807 op = format_trig_int (trig_places - trig_cnt, true, op);
812 strcpy (output, "0");
816 strcpy (output, "*.");