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