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