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