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