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