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