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