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