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