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