Make PSPP able to read all the portable files I could find on the
[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 (&por_file_casewriter_class, w);
170
171  error:
172   close_writer (w);
173   return NULL;
174
175  open_error:
176   msg (ME, _("An error occurred while opening \"%s\" for writing "
177              "as a portable file: %s."),
178        fh_get_file_name (fh), strerror (errno));
179   goto error;
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   buf_write (w, "/", 1);
218 }
219
220 /* Write N to the portable file as an integer field. */
221 static void
222 write_int (struct pfm_writer *w, int n)
223 {
224   char buffer[64];
225   format_trig_int (n, false, buffer);
226   buf_write (w, buffer, strlen (buffer));
227   buf_write (w, "/", 1);
228 }
229
230 /* Write S to the portable file as a string field. */
231 static void
232 write_string (struct pfm_writer *w, const char *s)
233 {
234   size_t n = strlen (s);
235   write_int (w, (int) n);
236   buf_write (w, s, n);
237 }
238 \f
239 /* Write file header. */
240 static void
241 write_header (struct pfm_writer *w)
242 {
243   static const char spss2ascii[256] =
244     {
245       "0000000000000000000000000000000000000000000000000000000000000000"
246       "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ."
247       "<(+|&[]!$*);^-/|,%_>?`:$@'=\"000000~-0000123456789000-()0{}\\00000"
248       "0000000000000000000000000000000000000000000000000000000000000000"
249     };
250   int i;
251
252   for (i = 0; i < 5; i++)
253     buf_write (w, "ASCII SPSS PORT FILE                    ", 40);
254
255   buf_write (w, spss2ascii, 256);
256   buf_write (w, "SPSSPORT", 8);
257 }
258
259 /* Writes version, date, and identification records. */
260 static void
261 write_version_data (struct pfm_writer *w)
262 {
263   char date_str[9];
264   char time_str[7];
265   time_t t;
266   struct tm tm;
267   struct tm *tmp;
268
269   if ((time_t) -1 == time (&t))
270     {
271       tm.tm_sec = tm.tm_min = tm.tm_hour = tm.tm_mon = tm.tm_year = 0;
272       tm.tm_mday = 1;
273       tmp = &tm;
274     }
275   else
276     tmp = localtime (&t);
277
278   sprintf (date_str, "%04d%02d%02d",
279            tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday);
280   sprintf (time_str, "%02d%02d%02d", tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
281   buf_write (w, "A", 1);
282   write_string (w, date_str);
283   write_string (w, time_str);
284
285   /* Product identification. */
286   buf_write (w, "1", 1);
287   write_string (w, version);
288
289   /* Subproduct identification. */
290   buf_write (w, "3", 1);
291   write_string (w, host_system);
292 }
293
294 /* Write format F to file H.  The format is first resized to fit
295    a value of the given WIDTH, which is handy in case F
296    represents a string longer than 255 bytes and thus WIDTH is
297    truncated to 255 bytes.  */
298 static void
299 write_format (struct pfm_writer *w, struct fmt_spec f, int width)
300 {
301   fmt_resize (&f, width);
302   write_int (w, fmt_to_io (f.type));
303   write_int (w, f.w);
304   write_int (w, f.d);
305 }
306
307 /* Write value V for variable VV to file H. */
308 static void
309 write_value (struct pfm_writer *w, union value *v, struct variable *vv)
310 {
311   if (var_is_numeric (vv))
312     write_float (w, v->f);
313   else
314     {
315       int width = MIN (var_get_width (vv), MAX_POR_WIDTH);
316       write_int (w, width);
317       buf_write (w, v->s, width);
318     }
319 }
320
321 /* Write variable records. */
322 static void
323 write_variables (struct pfm_writer *w, struct dictionary *dict)
324 {
325   int i;
326
327   short_names_assign (dict);
328
329   if (dict_get_weight (dict) != NULL) 
330     {
331       buf_write (w, "6", 1);
332       write_string (w, var_get_short_name (dict_get_weight (dict), 0));
333     }
334   
335   buf_write (w, "4", 1);
336   write_int (w, dict_get_var_cnt (dict));
337   write_int (w, 161);
338
339   for (i = 0; i < dict_get_var_cnt (dict); i++)
340     {
341       struct variable *v = dict_get_var (dict, i);
342       struct missing_values mv;
343       int width = MIN (var_get_width (v), MAX_POR_WIDTH);
344
345       buf_write (w, "7", 1);
346       write_int (w, width);
347       write_string (w, var_get_short_name (v, 0));
348       write_format (w, *var_get_print_format (v), width);
349       write_format (w, *var_get_write_format (v), width);
350
351       /* Write missing values. */
352       mv_copy (&mv, var_get_missing_values (v));
353       while (mv_has_range (&mv))
354         {
355           double x, y;
356           mv_pop_range (&mv, &x, &y);
357           if (x == LOWEST)
358             {
359               buf_write (w, "9", 1);
360               write_float (w, y);
361             }
362           else if (y == HIGHEST)
363             {
364               buf_write (w, "A", 1);
365               write_float (w, y);
366             }
367           else
368             {
369               buf_write (w, "B", 1);
370               write_float (w, x);
371               write_float (w, y);
372             }
373         }
374       while (mv_has_value (&mv))
375         {
376           union value value;
377           mv_pop_value (&mv, &value);
378           buf_write (w, "8", 1);
379           write_value (w, &value, v);
380         }
381
382       /* Write variable label. */
383       if (var_get_label (v) != NULL)
384         {
385           buf_write (w, "C", 1);
386           write_string (w, var_get_label (v));
387         }
388     }
389 }
390
391 /* Write value labels to disk.  FIXME: Inefficient. */
392 static void
393 write_value_labels (struct pfm_writer *w, const struct dictionary *dict)
394 {
395   int i;
396
397   for (i = 0; i < dict_get_var_cnt (dict); i++)
398     {
399       struct val_labs_iterator *j;
400       struct variable *v = dict_get_var (dict, i);
401       const struct val_labs *val_labs = var_get_value_labels (v);
402       struct val_lab *vl;
403
404       if (val_labs == NULL)
405         continue;
406
407       buf_write (w, "D", 1);
408       write_int (w, 1);
409       write_string (w, var_get_short_name (v, 0));
410       write_int (w, val_labs_count (val_labs));
411
412       for (vl = val_labs_first_sorted (val_labs, &j); vl != NULL;
413            vl = val_labs_next (val_labs, &j))
414         {
415           write_value (w, &vl->value, v);
416           write_string (w, vl->label);
417         }
418     }
419 }
420
421 /* Write documents in DICT to portable file W. */
422 static void
423 write_documents (struct pfm_writer *w, const struct dictionary *dict)
424 {
425   size_t line_cnt = dict_get_document_line_cnt (dict);
426   struct string line = DS_EMPTY_INITIALIZER;
427   int i;
428
429   buf_write (w, "E", 1);
430   write_int (w, line_cnt);
431   for (i = 0; i < line_cnt; i++)
432     {
433       dict_get_document_line (dict, i, &line);
434       write_string (w, ds_cstr (&line));
435     }
436   ds_destroy (&line);
437 }
438
439 /* Writes case C to the portable file represented by WRITER. */
440 static void
441 por_file_casewriter_write (struct casewriter *writer, void *w_,
442                            struct ccase *c)
443 {
444   struct pfm_writer *w = w_;
445   int i;
446
447   if (!ferror (w->file))
448     {
449       for (i = 0; i < w->var_cnt; i++)
450         {
451           struct pfm_var *v = &w->vars[i];
452
453           if (v->width == 0)
454             write_float (w, case_num_idx (c, v->fv));
455           else
456             {
457               write_int (w, v->width);
458               buf_write (w, case_str_idx (c, v->fv), v->width);
459             }
460         }
461     }
462   else
463     casewriter_force_error (writer);
464
465   case_destroy (c);
466 }
467
468 static void
469 por_file_casewriter_destroy (struct casewriter *writer, void *w_)
470 {
471   struct pfm_writer *w = w_;
472   if (!close_writer (w))
473     casewriter_force_error (writer);
474 }
475
476 /* Closes a portable file after we're done with it.
477    Returns true if successful, false if an I/O error occurred. */
478 static bool
479 close_writer (struct pfm_writer *w)
480 {
481   bool ok;
482
483   if (w == NULL)
484     return true;
485
486   ok = true;
487   if (w->file != NULL)
488     {
489       char buf[80];
490       memset (buf, 'Z', sizeof buf);
491       buf_write (w, buf, w->lc >= 80 ? 80 : 80 - w->lc);
492
493       ok = !ferror (w->file);
494       if (fclose (w->file) == EOF)
495         ok = false;
496
497       if (!ok)
498         msg (ME, _("An I/O error occurred writing portable file \"%s\"."),
499              fh_get_file_name (w->fh));
500     }
501
502   fh_close (w->fh, "portable file", "we");
503
504   free (w->vars);
505   free (w);
506
507   return ok;
508 }
509 \f
510 /* Base-30 conversion.
511
512    Portable files represent numbers in base-30 format, so we need
513    to be able to convert real and integer number to that base.
514    Older versions of PSPP used libgmp to do so, but this added a
515    big library dependency to do just one thing.  Now we do it
516    ourselves internally.
517
518    Important fact: base 30 is called "trigesimal". */
519
520 /* Conversion base. */
521 #define BASE 30                         /* As an integer. */
522 #define LDBASE ((long double) BASE)     /* As a long double. */
523
524 /* This is floor(log30(2**31)), the minimum number of trigesimal
525    digits that a `long int' can hold. */
526 #define CHUNK_SIZE 6
527
528 /* pow_tab[i] = pow (30, pow (2, i)) */
529 static long double pow_tab[16];
530
531 /* Initializes pow_tab[]. */
532 static void
533 init_pow_tab (void)
534 {
535   static bool did_init = false;
536   long double power;
537   size_t i;
538
539   /* Only initialize once. */
540   if (did_init)
541     return;
542   did_init = true;
543
544   /* Set each element of pow_tab[] until we run out of numerical
545      range. */
546   i = 0;
547   for (power = 30.0L; power < DBL_MAX; power *= power)
548     {
549       assert (i < sizeof pow_tab / sizeof *pow_tab);
550       pow_tab[i++] = power;
551     }
552 }
553
554 /* Returns 30**EXPONENT, for 0 <= EXPONENT <= log30(DBL_MAX). */
555 static long double
556 pow30_nonnegative (int exponent)
557 {
558   long double power;
559   int i;
560
561   assert (exponent >= 0);
562   assert (exponent < 1L << (sizeof pow_tab / sizeof *pow_tab));
563
564   power = 1.L;
565   for (i = 0; exponent > 0; exponent >>= 1, i++)
566     if (exponent & 1)
567       power *= pow_tab[i];
568
569   return power;
570 }
571
572 /* Returns 30**EXPONENT, for log30(DBL_MIN) <= EXPONENT <=
573    log30(DBL_MAX). */
574 static long double
575 pow30 (int exponent)
576 {
577   if (exponent >= 0)
578     return pow30_nonnegative (exponent);
579   else
580     return 1.L / pow30_nonnegative (-exponent);
581 }
582
583 /* Returns the character corresponding to TRIG. */
584 static int
585 trig_to_char (int trig)
586 {
587   assert (trig >= 0 && trig < 30);
588   return "0123456789ABCDEFGHIJKLMNOPQRST"[trig];
589 }
590
591 /* Formats the TRIG_CNT trigs in TRIGS[], writing them as
592    null-terminated STRING.  The trigesimal point is inserted
593    after TRIG_PLACES characters have been printed, if necessary
594    adding extra zeros at either end for correctness.  Returns the
595    character after the formatted number. */
596 static char *
597 format_trig_digits (char *string,
598                     const char trigs[], int trig_cnt, int trig_places)
599 {
600   if (trig_places < 0)
601     {
602       *string++ = '.';
603       while (trig_places++ < 0)
604         *string++ = '0';
605       trig_places = -1;
606     }
607   while (trig_cnt-- > 0)
608     {
609       if (trig_places-- == 0)
610         *string++ = '.';
611       *string++ = trig_to_char (*trigs++);
612     }
613   while (trig_places-- > 0)
614     *string++ = '0';
615   *string = '\0';
616   return string;
617 }
618
619 /* Helper function for format_trig_int() that formats VALUE as a
620    trigesimal integer at CP.  VALUE must be nonnegative.
621    Returns the character following the formatted integer. */
622 static char *
623 recurse_format_trig_int (char *cp, int value)
624 {
625   int trig = value % BASE;
626   value /= BASE;
627   if (value > 0)
628     cp = recurse_format_trig_int (cp, value);
629   *cp++ = trig_to_char (trig);
630   return cp;
631 }
632
633 /* Formats VALUE as a trigesimal integer in null-terminated
634    STRING[].  VALUE must be in the range -DBL_MAX...DBL_MAX.  If
635    FORCE_SIGN is true, a sign is always inserted; otherwise, a
636    sign is only inserted if VALUE is negative. */
637 static char *
638 format_trig_int (int value, bool force_sign, char string[])
639 {
640   /* Insert sign. */
641   if (value < 0)
642     {
643       *string++ = '-';
644       value = -value;
645     }
646   else if (force_sign)
647     *string++ = '+';
648
649   /* Format integer. */
650   string = recurse_format_trig_int (string, value);
651   *string = '\0';
652   return string;
653 }
654
655 /* Determines whether the TRIG_CNT trigesimals in TRIGS[] warrant
656    rounding up or down.  Returns true if TRIGS[] represents a
657    value greater than half, false if less than half.  If TRIGS[]
658    is exactly half, examines TRIGS[-1] and returns true if odd,
659    false if even ("round to even"). */
660 static bool
661 should_round_up (const char trigs[], int trig_cnt)
662 {
663   assert (trig_cnt > 0);
664
665   if (*trigs < BASE / 2)
666     {
667       /* Less than half: round down. */
668       return false;
669     }
670   else if (*trigs > BASE / 2)
671     {
672       /* Greater than half: round up. */
673       return true;
674     }
675   else
676     {
677       /* Approximately half: look more closely. */
678       int i;
679       for (i = 1; i < trig_cnt; i++)
680         if (trigs[i] > 0)
681           {
682             /* Slightly greater than half: round up. */
683             return true;
684           }
685
686       /* Exactly half: round to even. */
687       return trigs[-1] % 2;
688     }
689 }
690
691 /* Rounds up the rightmost trig in the TRIG_CNT trigs in TRIGS[],
692    carrying to the left as necessary.  Returns true if
693    successful, false on failure (due to a carry out of the
694    leftmost position). */
695 static bool
696 try_round_up (char *trigs, int trig_cnt)
697 {
698   while (trig_cnt > 0)
699     {
700       char *round_trig = trigs + --trig_cnt;
701       if (*round_trig != BASE - 1)
702         {
703           /* Round this trig up to the next value. */
704           ++*round_trig;
705           return true;
706         }
707
708       /* Carry over to the next trig to the left. */
709       *round_trig = 0;
710     }
711
712   /* Ran out of trigs to carry. */
713   return false;
714 }
715
716 /* Converts VALUE to trigesimal format in string OUTPUT[] with the
717    equivalent of at least BASE_10_PRECISION decimal digits of
718    precision.  The output format may use conventional or
719    scientific notation.  Missing, infinite, and extreme values
720    are represented with "*.". */
721 static void
722 format_trig_double (long double value, int base_10_precision, char output[])
723 {
724   /* Original VALUE was negative? */
725   bool negative;
726
727   /* Number of significant trigesimals. */
728   int base_30_precision;
729
730   /* Base-2 significand and exponent for original VALUE. */
731   double base_2_sig;
732   int base_2_exp;
733
734   /* VALUE as a set of trigesimals. */
735   char buffer[DBL_DIG + 16];
736   char *trigs;
737   int trig_cnt;
738
739   /* Number of trigesimal places for trigs.
740      trigs[0] has coefficient 30**(trig_places - 1),
741      trigs[1] has coefficient 30**(trig_places - 2),
742      and so on.
743      In other words, the trigesimal point is just before trigs[0].
744    */
745   int trig_places;
746
747   /* Number of trigesimal places left to write into BUFFER. */
748   int trigs_to_output;
749
750   init_pow_tab ();
751
752   /* Handle special cases. */
753   if (value == SYSMIS)
754     goto missing_value;
755   if (value == 0.)
756     goto zero;
757
758   /* Make VALUE positive. */
759   if (value < 0)
760     {
761       value = -value;
762       negative = true;
763     }
764   else
765     negative = false;
766
767   /* Adjust VALUE to roughly 30**3, by shifting the trigesimal
768      point left or right as necessary.  We approximate the
769      base-30 exponent by obtaining the base-2 exponent, then
770      multiplying by log30(2).  This approximation is sufficient
771      to ensure that the adjusted VALUE is always in the range
772      0...30**6, an invariant of the loop below. */
773   errno = 0;
774   base_2_sig = frexp (value, &base_2_exp);
775   if (errno != 0 || !finite (base_2_sig))
776     goto missing_value;
777   if (base_2_exp == 0 && base_2_sig == 0.)
778     goto zero;
779   if (base_2_exp <= INT_MIN / 20379L || base_2_exp >= INT_MAX / 20379L)
780     goto missing_value;
781   trig_places = (base_2_exp * 20379L / 100000L) + CHUNK_SIZE / 2;
782   value *= pow30 (CHUNK_SIZE - trig_places);
783
784   /* Dump all the trigs to buffer[], CHUNK_SIZE at a time. */
785   trigs = buffer;
786   trig_cnt = 0;
787   for (trigs_to_output = DIV_RND_UP (DBL_DIG * 2, 3) + 1 + (CHUNK_SIZE / 2);
788        trigs_to_output > 0;
789        trigs_to_output -= CHUNK_SIZE)
790     {
791       long chunk;
792       int trigs_left;
793
794       /* The current chunk is just the integer part of VALUE,
795          truncated to the nearest integer.  The chunk fits in a
796          long. */
797       chunk = value;
798       assert (pow30 (CHUNK_SIZE) <= LONG_MAX);
799       assert (chunk >= 0 && chunk < pow30 (CHUNK_SIZE));
800
801       value -= chunk;
802
803       /* Append the chunk, in base 30, to trigs[]. */
804       for (trigs_left = CHUNK_SIZE; chunk > 0 && trigs_left > 0; )
805         {
806           trigs[trig_cnt + --trigs_left] = chunk % 30;
807           chunk /= 30;
808         }
809       while (trigs_left > 0)
810         trigs[trig_cnt + --trigs_left] = 0;
811       trig_cnt += CHUNK_SIZE;
812
813       /* Proceed to the next chunk. */
814       if (value == 0.)
815         break;
816       value *= pow (LDBASE, CHUNK_SIZE);
817     }
818
819   /* Strip leading zeros. */
820   while (trig_cnt > 1 && *trigs == 0)
821     {
822       trigs++;
823       trig_cnt--;
824       trig_places--;
825     }
826
827   /* Round to requested precision, conservatively estimating the
828      required base-30 precision as 2/3 of the base-10 precision
829      (log30(10) = .68). */
830   assert (base_10_precision > 0);
831   if (base_10_precision > LDBL_DIG)
832     base_10_precision = LDBL_DIG;
833   base_30_precision = DIV_RND_UP (base_10_precision * 2, 3);
834   if (trig_cnt > base_30_precision)
835     {
836       if (should_round_up (trigs + base_30_precision,
837                            trig_cnt - base_30_precision))
838         {
839           /* Try to round up. */
840           if (try_round_up (trigs, base_30_precision))
841             {
842               /* Rounding up worked. */
843               trig_cnt = base_30_precision;
844             }
845           else
846             {
847               /* Couldn't round up because we ran out of trigs to
848                  carry into.  Do the carry here instead. */
849               *trigs = 1;
850               trig_cnt = 1;
851               trig_places++;
852             }
853         }
854       else
855         {
856           /* Round down. */
857           trig_cnt = base_30_precision;
858         }
859     }
860   else
861     {
862       /* No rounding required: fewer digits available than
863          requested. */
864     }
865
866   /* Strip trailing zeros. */
867   while (trig_cnt > 1 && trigs[trig_cnt - 1] == 0)
868     trig_cnt--;
869
870   /* Write output. */
871   if (negative)
872     *output++ = '-';
873   if (trig_places >= -1 && trig_places < trig_cnt + 3)
874     {
875       /* Use conventional notation. */
876       format_trig_digits (output, trigs, trig_cnt, trig_places);
877     }
878   else
879     {
880       /* Use scientific notation. */
881       char *op;
882       op = format_trig_digits (output, trigs, trig_cnt, trig_cnt);
883       op = format_trig_int (trig_places - trig_cnt, true, op);
884     }
885   return;
886
887  zero:
888   strcpy (output, "0");
889   return;
890
891  missing_value:
892   strcpy (output, "*.");
893   return;
894 }
895 \f
896 static struct casewriter_class por_file_casewriter_class =
897   {
898     por_file_casewriter_write,
899     por_file_casewriter_destroy,
900     NULL,
901   };