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