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