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