magic-elimination.patch from patch #6230.
[pspp-builds.git] / src / data / por-file-writer.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18 #include "por-file-writer.h"
19
20 #include <ctype.h>
21 #include <errno.h>
22 #include <float.h>
23 #include <math.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <sys/stat.h>
27 #include <time.h>
28
29 #include <data/case.h>
30 #include <data/casewriter-provider.h>
31 #include <data/casewriter.h>
32 #include <data/dictionary.h>
33 #include <data/file-handle-def.h>
34 #include <data/file-name.h>
35 #include <data/format.h>
36 #include <data/missing-values.h>
37 #include <data/short-names.h>
38 #include <data/value-labels.h>
39 #include <data/variable.h>
40
41 #include <libpspp/alloc.h>
42 #include <libpspp/hash.h>
43 #include <libpspp/message.h>
44 #include <libpspp/misc.h>
45 #include <libpspp/str.h>
46 #include <libpspp/version.h>
47
48 #include "gettext.h"
49 #define _(msgid) gettext (msgid)
50
51 /* Maximum width of a variable in a portable file. */
52 #define MAX_POR_WIDTH 255
53
54 /* Portable file writer. */
55 struct pfm_writer
56   {
57     struct file_handle *fh;     /* File handle. */
58     FILE *file;                 /* File stream. */
59
60     int lc;                     /* Number of characters on this line so far. */
61
62     size_t var_cnt;             /* Number of variables. */
63     struct pfm_var *vars;       /* Variables. */
64
65     int digits;                 /* Digits of precision. */
66   };
67
68 /* A variable to write to the portable file. */
69 struct pfm_var
70   {
71     int width;                  /* 0=numeric, otherwise string var width. */
72     int fv;                     /* Starting case index. */
73   };
74
75 static struct casewriter_class por_file_casewriter_class;
76
77 static bool close_writer (struct pfm_writer *);
78 static void buf_write (struct pfm_writer *, const void *, size_t);
79 static void write_header (struct pfm_writer *);
80 static void write_version_data (struct pfm_writer *);
81 static void write_variables (struct pfm_writer *, struct dictionary *);
82 static void write_value_labels (struct pfm_writer *,
83                                 const struct dictionary *);
84 static void write_documents (struct pfm_writer *,
85                              const struct dictionary *);
86
87 static void format_trig_double (long double, int base_10_precision, char[]);
88 static char *format_trig_int (int, bool force_sign, char[]);
89
90 /* Returns default options for writing a portable file. */
91 struct pfm_write_options
92 pfm_writer_default_options (void)
93 {
94   struct pfm_write_options opts;
95   opts.create_writeable = true;
96   opts.type = PFM_COMM;
97   opts.digits = DBL_DIG;
98   return opts;
99 }
100
101 /* Writes the dictionary DICT to portable file HANDLE according
102    to the given OPTS.  Returns nonzero only if successful.  DICT
103    will not be modified, except to assign short names. */
104 struct casewriter *
105 pfm_open_writer (struct file_handle *fh, struct dictionary *dict,
106                  struct pfm_write_options opts)
107 {
108   struct pfm_writer *w = NULL;
109   mode_t mode;
110   FILE *file;
111   size_t i;
112
113   /* Open file handle. */
114   if (!fh_open (fh, FH_REF_FILE, "portable file", "we"))
115     return NULL;
116
117   /* Create file. */
118   mode = S_IRUSR | S_IRGRP | S_IROTH;
119   if (opts.create_writeable)
120     mode |= S_IWUSR | S_IWGRP | S_IWOTH;
121   file = create_stream (fh_get_file_name (fh), "w", mode);
122   if (file == NULL)
123     {
124       fh_close (fh, "portable file", "we");
125       msg (ME, _("An error occurred while opening \"%s\" for writing "
126                  "as a portable file: %s."),
127            fh_get_file_name (fh), strerror (errno));
128       return NULL;
129     }
130
131   /* Initialize data structures. */
132   w = xmalloc (sizeof *w);
133   w->fh = fh;
134   w->file = file;
135
136   w->lc = 0;
137   w->var_cnt = 0;
138   w->vars = NULL;
139
140   w->var_cnt = dict_get_var_cnt (dict);
141   w->vars = xnmalloc (w->var_cnt, sizeof *w->vars);
142   for (i = 0; i < w->var_cnt; i++)
143     {
144       const struct variable *dv = dict_get_var (dict, i);
145       struct pfm_var *pv = &w->vars[i];
146       pv->width = MIN (var_get_width (dv), MAX_POR_WIDTH);
147       pv->fv = var_get_case_index (dv);
148     }
149
150   w->digits = opts.digits;
151   if (w->digits < 1)
152     {
153       msg (ME, _("Invalid decimal digits count %d.  Treating as %d."),
154            w->digits, DBL_DIG);
155       w->digits = DBL_DIG;
156     }
157
158   /* Write file header. */
159   write_header (w);
160   write_version_data (w);
161   write_variables (w, dict);
162   write_value_labels (w, dict);
163   if (dict_get_document_line_cnt (dict) > 0)
164     write_documents (w, dict);
165   buf_write (w, "F", 1);
166   if (ferror (w->file))
167     {
168       close_writer (w);
169       return NULL;
170     }
171   return casewriter_create (dict_get_next_value_idx (dict),
172                             &por_file_casewriter_class, w);
173 }
174 \f
175 /* Write NBYTES starting at BUF to the portable file represented by
176    H.  Break lines properly every 80 characters.  */
177 static void
178 buf_write (struct pfm_writer *w, const void *buf_, size_t nbytes)
179 {
180   const char *buf = buf_;
181
182   if (ferror (w->file))
183     return;
184
185   assert (buf != NULL);
186   while (nbytes + w->lc >= 80)
187     {
188       size_t n = 80 - w->lc;
189
190       if (n)
191         fwrite (buf, n, 1, w->file);
192       fwrite ("\r\n", 2, 1, w->file);
193
194       nbytes -= n;
195       buf += n;
196       w->lc = 0;
197     }
198   fwrite (buf, nbytes, 1, w->file);
199
200   w->lc += nbytes;
201 }
202
203 /* Write D to the portable file as a floating-point field. */
204 static void
205 write_float (struct pfm_writer *w, double d)
206 {
207   char buffer[64];
208   format_trig_double (d, floor (d) == d ? DBL_DIG : w->digits, buffer);
209   buf_write (w, buffer, strlen (buffer));
210   buf_write (w, "/", 1);
211 }
212
213 /* Write N to the portable file as an integer field. */
214 static void
215 write_int (struct pfm_writer *w, int n)
216 {
217   char buffer[64];
218   format_trig_int (n, false, buffer);
219   buf_write (w, buffer, strlen (buffer));
220   buf_write (w, "/", 1);
221 }
222
223 /* Write S to the portable file as a string field. */
224 static void
225 write_string (struct pfm_writer *w, const char *s)
226 {
227   size_t n = strlen (s);
228   write_int (w, (int) n);
229   buf_write (w, s, n);
230 }
231 \f
232 /* Write file header. */
233 static void
234 write_header (struct pfm_writer *w)
235 {
236   static const char spss2ascii[256] =
237     {
238       "0000000000000000000000000000000000000000000000000000000000000000"
239       "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ."
240       "<(+|&[]!$*);^-/|,%_>?`:$@'=\"000000~-0000123456789000-()0{}\\00000"
241       "0000000000000000000000000000000000000000000000000000000000000000"
242     };
243   int i;
244
245   for (i = 0; i < 5; i++)
246     buf_write (w, "ASCII SPSS PORT FILE                    ", 40);
247
248   buf_write (w, spss2ascii, 256);
249   buf_write (w, "SPSSPORT", 8);
250 }
251
252 /* Writes version, date, and identification records. */
253 static void
254 write_version_data (struct pfm_writer *w)
255 {
256   char date_str[9];
257   char time_str[7];
258   time_t t;
259   struct tm tm;
260   struct tm *tmp;
261
262   if ((time_t) -1 == time (&t))
263     {
264       tm.tm_sec = tm.tm_min = tm.tm_hour = tm.tm_mon = tm.tm_year = 0;
265       tm.tm_mday = 1;
266       tmp = &tm;
267     }
268   else
269     tmp = localtime (&t);
270
271   sprintf (date_str, "%04d%02d%02d",
272            tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday);
273   sprintf (time_str, "%02d%02d%02d", tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
274   buf_write (w, "A", 1);
275   write_string (w, date_str);
276   write_string (w, time_str);
277
278   /* Product identification. */
279   buf_write (w, "1", 1);
280   write_string (w, version);
281
282   /* Subproduct identification. */
283   buf_write (w, "3", 1);
284   write_string (w, host_system);
285 }
286
287 /* Write format F to file H.  The format is first resized to fit
288    a value of the given WIDTH, which is handy in case F
289    represents a string longer than 255 bytes and thus WIDTH is
290    truncated to 255 bytes.  */
291 static void
292 write_format (struct pfm_writer *w, struct fmt_spec f, int width)
293 {
294   fmt_resize (&f, width);
295   write_int (w, fmt_to_io (f.type));
296   write_int (w, f.w);
297   write_int (w, f.d);
298 }
299
300 /* Write value V for variable VV to file H. */
301 static void
302 write_value (struct pfm_writer *w, union value *v, struct variable *vv)
303 {
304   if (var_is_numeric (vv))
305     write_float (w, v->f);
306   else
307     {
308       int width = MIN (var_get_width (vv), MAX_POR_WIDTH);
309       write_int (w, width);
310       buf_write (w, v->s, width);
311     }
312 }
313
314 /* Write variable records. */
315 static void
316 write_variables (struct pfm_writer *w, struct dictionary *dict)
317 {
318   int i;
319
320   short_names_assign (dict);
321
322   if (dict_get_weight (dict) != NULL) 
323     {
324       buf_write (w, "6", 1);
325       write_string (w, var_get_short_name (dict_get_weight (dict), 0));
326     }
327   
328   buf_write (w, "4", 1);
329   write_int (w, dict_get_var_cnt (dict));
330   write_int (w, 161);
331
332   for (i = 0; i < dict_get_var_cnt (dict); i++)
333     {
334       struct variable *v = dict_get_var (dict, i);
335       struct missing_values mv;
336       int width = MIN (var_get_width (v), MAX_POR_WIDTH);
337
338       buf_write (w, "7", 1);
339       write_int (w, width);
340       write_string (w, var_get_short_name (v, 0));
341       write_format (w, *var_get_print_format (v), width);
342       write_format (w, *var_get_write_format (v), width);
343
344       /* Write missing values. */
345       mv_copy (&mv, var_get_missing_values (v));
346       while (mv_has_range (&mv))
347         {
348           double x, y;
349           mv_pop_range (&mv, &x, &y);
350           if (x == LOWEST)
351             {
352               buf_write (w, "9", 1);
353               write_float (w, y);
354             }
355           else if (y == HIGHEST)
356             {
357               buf_write (w, "A", 1);
358               write_float (w, y);
359             }
360           else
361             {
362               buf_write (w, "B", 1);
363               write_float (w, x);
364               write_float (w, y);
365             }
366         }
367       while (mv_has_value (&mv))
368         {
369           union value value;
370           mv_pop_value (&mv, &value);
371           buf_write (w, "8", 1);
372           write_value (w, &value, v);
373         }
374
375       /* Write variable label. */
376       if (var_get_label (v) != NULL)
377         {
378           buf_write (w, "C", 1);
379           write_string (w, var_get_label (v));
380         }
381     }
382 }
383
384 /* Write value labels to disk.  FIXME: Inefficient. */
385 static void
386 write_value_labels (struct pfm_writer *w, const struct dictionary *dict)
387 {
388   int i;
389
390   for (i = 0; i < dict_get_var_cnt (dict); i++)
391     {
392       struct val_labs_iterator *j;
393       struct variable *v = dict_get_var (dict, i);
394       const struct val_labs *val_labs = var_get_value_labels (v);
395       struct val_lab *vl;
396
397       if (val_labs == NULL)
398         continue;
399
400       buf_write (w, "D", 1);
401       write_int (w, 1);
402       write_string (w, var_get_short_name (v, 0));
403       write_int (w, val_labs_count (val_labs));
404
405       for (vl = val_labs_first_sorted (val_labs, &j); vl != NULL;
406            vl = val_labs_next (val_labs, &j))
407         {
408           write_value (w, &vl->value, v);
409           write_string (w, vl->label);
410         }
411     }
412 }
413
414 /* Write documents in DICT to portable file W. */
415 static void
416 write_documents (struct pfm_writer *w, const struct dictionary *dict)
417 {
418   size_t line_cnt = dict_get_document_line_cnt (dict);
419   struct string line = DS_EMPTY_INITIALIZER;
420   int i;
421
422   buf_write (w, "E", 1);
423   write_int (w, line_cnt);
424   for (i = 0; i < line_cnt; i++)
425     {
426       dict_get_document_line (dict, i, &line);
427       write_string (w, ds_cstr (&line));
428     }
429   ds_destroy (&line);
430 }
431
432 /* Writes case C to the portable file represented by WRITER. */
433 static void
434 por_file_casewriter_write (struct casewriter *writer, void *w_,
435                            struct ccase *c)
436 {
437   struct pfm_writer *w = w_;
438   int i;
439
440   if (!ferror (w->file))
441     {
442       for (i = 0; i < w->var_cnt; i++)
443         {
444           struct pfm_var *v = &w->vars[i];
445
446           if (v->width == 0)
447             write_float (w, case_num_idx (c, v->fv));
448           else
449             {
450               write_int (w, v->width);
451               buf_write (w, case_str_idx (c, v->fv), v->width);
452             }
453         }
454     }
455   else
456     casewriter_force_error (writer);
457
458   case_destroy (c);
459 }
460
461 static void
462 por_file_casewriter_destroy (struct casewriter *writer, void *w_)
463 {
464   struct pfm_writer *w = w_;
465   if (!close_writer (w))
466     casewriter_force_error (writer);
467 }
468
469 /* Closes a portable file after we're done with it.
470    Returns true if successful, false if an I/O error occurred. */
471 static bool
472 close_writer (struct pfm_writer *w)
473 {
474   bool ok;
475
476   if (w == NULL)
477     return true;
478
479   ok = true;
480   if (w->file != NULL)
481     {
482       char buf[80];
483       memset (buf, 'Z', sizeof buf);
484       buf_write (w, buf, w->lc >= 80 ? 80 : 80 - w->lc);
485
486       ok = !ferror (w->file);
487       if (fclose (w->file) == EOF)
488         ok = false;
489
490       if (!ok)
491         msg (ME, _("An I/O error occurred writing portable file \"%s\"."),
492              fh_get_file_name (w->fh));
493     }
494
495   fh_close (w->fh, "portable file", "we");
496
497   free (w->vars);
498   free (w);
499
500   return ok;
501 }
502 \f
503 /* Base-30 conversion.
504
505    Portable files represent numbers in base-30 format, so we need
506    to be able to convert real and integer number to that base.
507    Older versions of PSPP used libgmp to do so, but this added a
508    big library dependency to do just one thing.  Now we do it
509    ourselves internally.
510
511    Important fact: base 30 is called "trigesimal". */
512
513 /* Conversion base. */
514 #define BASE 30                         /* As an integer. */
515 #define LDBASE ((long double) BASE)     /* As a long double. */
516
517 /* This is floor(log30(2**31)), the minimum number of trigesimal
518    digits that a `long int' can hold. */
519 #define CHUNK_SIZE 6
520
521 /* pow_tab[i] = pow (30, pow (2, i)) */
522 static long double pow_tab[16];
523
524 /* Initializes pow_tab[]. */
525 static void
526 init_pow_tab (void)
527 {
528   static bool did_init = false;
529   long double power;
530   size_t i;
531
532   /* Only initialize once. */
533   if (did_init)
534     return;
535   did_init = true;
536
537   /* Set each element of pow_tab[] until we run out of numerical
538      range. */
539   i = 0;
540   for (power = 30.0L; power < DBL_MAX; power *= power)
541     {
542       assert (i < sizeof pow_tab / sizeof *pow_tab);
543       pow_tab[i++] = power;
544     }
545 }
546
547 /* Returns 30**EXPONENT, for 0 <= EXPONENT <= log30(DBL_MAX). */
548 static long double
549 pow30_nonnegative (int exponent)
550 {
551   long double power;
552   int i;
553
554   assert (exponent >= 0);
555   assert (exponent < 1L << (sizeof pow_tab / sizeof *pow_tab));
556
557   power = 1.L;
558   for (i = 0; exponent > 0; exponent >>= 1, i++)
559     if (exponent & 1)
560       power *= pow_tab[i];
561
562   return power;
563 }
564
565 /* Returns 30**EXPONENT, for log30(DBL_MIN) <= EXPONENT <=
566    log30(DBL_MAX). */
567 static long double
568 pow30 (int exponent)
569 {
570   if (exponent >= 0)
571     return pow30_nonnegative (exponent);
572   else
573     return 1.L / pow30_nonnegative (-exponent);
574 }
575
576 /* Returns the character corresponding to TRIG. */
577 static int
578 trig_to_char (int trig)
579 {
580   assert (trig >= 0 && trig < 30);
581   return "0123456789ABCDEFGHIJKLMNOPQRST"[trig];
582 }
583
584 /* Formats the TRIG_CNT trigs in TRIGS[], writing them as
585    null-terminated STRING.  The trigesimal point is inserted
586    after TRIG_PLACES characters have been printed, if necessary
587    adding extra zeros at either end for correctness.  Returns the
588    character after the formatted number. */
589 static char *
590 format_trig_digits (char *string,
591                     const char trigs[], int trig_cnt, int trig_places)
592 {
593   if (trig_places < 0)
594     {
595       *string++ = '.';
596       while (trig_places++ < 0)
597         *string++ = '0';
598       trig_places = -1;
599     }
600   while (trig_cnt-- > 0)
601     {
602       if (trig_places-- == 0)
603         *string++ = '.';
604       *string++ = trig_to_char (*trigs++);
605     }
606   while (trig_places-- > 0)
607     *string++ = '0';
608   *string = '\0';
609   return string;
610 }
611
612 /* Helper function for format_trig_int() that formats VALUE as a
613    trigesimal integer at CP.  VALUE must be nonnegative.
614    Returns the character following the formatted integer. */
615 static char *
616 recurse_format_trig_int (char *cp, int value)
617 {
618   int trig = value % BASE;
619   value /= BASE;
620   if (value > 0)
621     cp = recurse_format_trig_int (cp, value);
622   *cp++ = trig_to_char (trig);
623   return cp;
624 }
625
626 /* Formats VALUE as a trigesimal integer in null-terminated
627    STRING[].  VALUE must be in the range -DBL_MAX...DBL_MAX.  If
628    FORCE_SIGN is true, a sign is always inserted; otherwise, a
629    sign is only inserted if VALUE is negative. */
630 static char *
631 format_trig_int (int value, bool force_sign, char string[])
632 {
633   /* Insert sign. */
634   if (value < 0)
635     {
636       *string++ = '-';
637       value = -value;
638     }
639   else if (force_sign)
640     *string++ = '+';
641
642   /* Format integer. */
643   string = recurse_format_trig_int (string, value);
644   *string = '\0';
645   return string;
646 }
647
648 /* Determines whether the TRIG_CNT trigesimals in TRIGS[] warrant
649    rounding up or down.  Returns true if TRIGS[] represents a
650    value greater than half, false if less than half.  If TRIGS[]
651    is exactly half, examines TRIGS[-1] and returns true if odd,
652    false if even ("round to even"). */
653 static bool
654 should_round_up (const char trigs[], int trig_cnt)
655 {
656   assert (trig_cnt > 0);
657
658   if (*trigs < BASE / 2)
659     {
660       /* Less than half: round down. */
661       return false;
662     }
663   else if (*trigs > BASE / 2)
664     {
665       /* Greater than half: round up. */
666       return true;
667     }
668   else
669     {
670       /* Approximately half: look more closely. */
671       int i;
672       for (i = 1; i < trig_cnt; i++)
673         if (trigs[i] > 0)
674           {
675             /* Slightly greater than half: round up. */
676             return true;
677           }
678
679       /* Exactly half: round to even. */
680       return trigs[-1] % 2;
681     }
682 }
683
684 /* Rounds up the rightmost trig in the TRIG_CNT trigs in TRIGS[],
685    carrying to the left as necessary.  Returns true if
686    successful, false on failure (due to a carry out of the
687    leftmost position). */
688 static bool
689 try_round_up (char *trigs, int trig_cnt)
690 {
691   while (trig_cnt > 0)
692     {
693       char *round_trig = trigs + --trig_cnt;
694       if (*round_trig != BASE - 1)
695         {
696           /* Round this trig up to the next value. */
697           ++*round_trig;
698           return true;
699         }
700
701       /* Carry over to the next trig to the left. */
702       *round_trig = 0;
703     }
704
705   /* Ran out of trigs to carry. */
706   return false;
707 }
708
709 /* Converts VALUE to trigesimal format in string OUTPUT[] with the
710    equivalent of at least BASE_10_PRECISION decimal digits of
711    precision.  The output format may use conventional or
712    scientific notation.  Missing, infinite, and extreme values
713    are represented with "*.". */
714 static void
715 format_trig_double (long double value, int base_10_precision, char output[])
716 {
717   /* Original VALUE was negative? */
718   bool negative;
719
720   /* Number of significant trigesimals. */
721   int base_30_precision;
722
723   /* Base-2 significand and exponent for original VALUE. */
724   double base_2_sig;
725   int base_2_exp;
726
727   /* VALUE as a set of trigesimals. */
728   char buffer[DBL_DIG + 16];
729   char *trigs;
730   int trig_cnt;
731
732   /* Number of trigesimal places for trigs.
733      trigs[0] has coefficient 30**(trig_places - 1),
734      trigs[1] has coefficient 30**(trig_places - 2),
735      and so on.
736      In other words, the trigesimal point is just before trigs[0].
737    */
738   int trig_places;
739
740   /* Number of trigesimal places left to write into BUFFER. */
741   int trigs_to_output;
742
743   init_pow_tab ();
744
745   /* Handle special cases. */
746   if (value == SYSMIS)
747     goto missing_value;
748   if (value == 0.)
749     goto zero;
750
751   /* Make VALUE positive. */
752   if (value < 0)
753     {
754       value = -value;
755       negative = true;
756     }
757   else
758     negative = false;
759
760   /* Adjust VALUE to roughly 30**3, by shifting the trigesimal
761      point left or right as necessary.  We approximate the
762      base-30 exponent by obtaining the base-2 exponent, then
763      multiplying by log30(2).  This approximation is sufficient
764      to ensure that the adjusted VALUE is always in the range
765      0...30**6, an invariant of the loop below. */
766   errno = 0;
767   base_2_sig = frexp (value, &base_2_exp);
768   if (errno != 0 || !finite (base_2_sig))
769     goto missing_value;
770   if (base_2_exp == 0 && base_2_sig == 0.)
771     goto zero;
772   if (base_2_exp <= INT_MIN / 20379L || base_2_exp >= INT_MAX / 20379L)
773     goto missing_value;
774   trig_places = (base_2_exp * 20379L / 100000L) + CHUNK_SIZE / 2;
775   value *= pow30 (CHUNK_SIZE - trig_places);
776
777   /* Dump all the trigs to buffer[], CHUNK_SIZE at a time. */
778   trigs = buffer;
779   trig_cnt = 0;
780   for (trigs_to_output = DIV_RND_UP (DBL_DIG * 2, 3) + 1 + (CHUNK_SIZE / 2);
781        trigs_to_output > 0;
782        trigs_to_output -= CHUNK_SIZE)
783     {
784       long chunk;
785       int trigs_left;
786
787       /* The current chunk is just the integer part of VALUE,
788          truncated to the nearest integer.  The chunk fits in a
789          long. */
790       chunk = value;
791       assert (pow30 (CHUNK_SIZE) <= LONG_MAX);
792       assert (chunk >= 0 && chunk < pow30 (CHUNK_SIZE));
793
794       value -= chunk;
795
796       /* Append the chunk, in base 30, to trigs[]. */
797       for (trigs_left = CHUNK_SIZE; chunk > 0 && trigs_left > 0; )
798         {
799           trigs[trig_cnt + --trigs_left] = chunk % 30;
800           chunk /= 30;
801         }
802       while (trigs_left > 0)
803         trigs[trig_cnt + --trigs_left] = 0;
804       trig_cnt += CHUNK_SIZE;
805
806       /* Proceed to the next chunk. */
807       if (value == 0.)
808         break;
809       value *= pow (LDBASE, CHUNK_SIZE);
810     }
811
812   /* Strip leading zeros. */
813   while (trig_cnt > 1 && *trigs == 0)
814     {
815       trigs++;
816       trig_cnt--;
817       trig_places--;
818     }
819
820   /* Round to requested precision, conservatively estimating the
821      required base-30 precision as 2/3 of the base-10 precision
822      (log30(10) = .68). */
823   assert (base_10_precision > 0);
824   if (base_10_precision > LDBL_DIG)
825     base_10_precision = LDBL_DIG;
826   base_30_precision = DIV_RND_UP (base_10_precision * 2, 3);
827   if (trig_cnt > base_30_precision)
828     {
829       if (should_round_up (trigs + base_30_precision,
830                            trig_cnt - base_30_precision))
831         {
832           /* Try to round up. */
833           if (try_round_up (trigs, base_30_precision))
834             {
835               /* Rounding up worked. */
836               trig_cnt = base_30_precision;
837             }
838           else
839             {
840               /* Couldn't round up because we ran out of trigs to
841                  carry into.  Do the carry here instead. */
842               *trigs = 1;
843               trig_cnt = 1;
844               trig_places++;
845             }
846         }
847       else
848         {
849           /* Round down. */
850           trig_cnt = base_30_precision;
851         }
852     }
853   else
854     {
855       /* No rounding required: fewer digits available than
856          requested. */
857     }
858
859   /* Strip trailing zeros. */
860   while (trig_cnt > 1 && trigs[trig_cnt - 1] == 0)
861     trig_cnt--;
862
863   /* Write output. */
864   if (negative)
865     *output++ = '-';
866   if (trig_places >= -1 && trig_places < trig_cnt + 3)
867     {
868       /* Use conventional notation. */
869       format_trig_digits (output, trigs, trig_cnt, trig_places);
870     }
871   else
872     {
873       /* Use scientific notation. */
874       char *op;
875       op = format_trig_digits (output, trigs, trig_cnt, trig_cnt);
876       op = format_trig_int (trig_places - trig_cnt, true, op);
877     }
878   return;
879
880  zero:
881   strcpy (output, "0");
882   return;
883
884  missing_value:
885   strcpy (output, "*.");
886   return;
887 }
888 \f
889 static struct casewriter_class por_file_casewriter_class =
890   {
891     por_file_casewriter_write,
892     por_file_casewriter_destroy,
893     NULL,
894   };