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