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