Adopt use of gnulib for portability.
[pspp-builds.git] / src / pfm-write.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18    02110-1301, USA. */
19
20 #include <config.h>
21 #include "pfm-write.h"
22 #include "error.h"
23 #include <ctype.h>
24 #include <errno.h>
25 #include <float.h>
26 #include <math.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <time.h>
30 #include "alloc.h"
31 #include "case.h"
32 #include "dictionary.h"
33 #include "error.h"
34 #include "file-handle.h"
35 #include "hash.h"
36 #include "magic.h"
37 #include "misc.h"
38 #include "str.h"
39 #include "value-labels.h"
40 #include "var.h"
41 #include "version.h"
42
43 #include "gettext.h"
44 #define _(msgid) gettext (msgid)
45
46 #include "debug-print.h"
47
48 /* Portable file writer. */
49 struct pfm_writer
50   {
51     struct file_handle *fh;     /* File handle. */
52     FILE *file;                 /* File stream. */
53
54     int lc;                     /* Number of characters on this line so far. */
55
56     size_t var_cnt;             /* Number of variables. */
57     struct pfm_var *vars;       /* Variables. */
58   };
59
60 /* A variable to write to the portable file. */
61 struct pfm_var 
62   {
63     int width;                  /* 0=numeric, otherwise string var width. */
64     int fv;                     /* Starting case index. */
65   };
66
67 static int buf_write (struct pfm_writer *, const void *, size_t);
68 static int write_header (struct pfm_writer *);
69 static int write_version_data (struct pfm_writer *);
70 static int write_variables (struct pfm_writer *, struct dictionary *);
71 static int write_value_labels (struct pfm_writer *, const struct dictionary *);
72
73 static void format_trig_double (long double, int base_10_precision, char[]);
74 static char *format_trig_int (int, bool force_sign, char[]);
75
76 /* Writes the dictionary DICT to portable file HANDLE.  Returns
77    nonzero only if successful.  DICT will not be modified, except
78    to assign short names. */
79 struct pfm_writer *
80 pfm_open_writer (struct file_handle *fh, struct dictionary *dict)
81 {
82   struct pfm_writer *w = NULL;
83   size_t i;
84
85   if (!fh_open (fh, "portable file", "we"))
86     goto error;
87   
88   /* Open the physical disk file. */
89   w = xmalloc (sizeof *w);
90   w->fh = fh;
91   w->file = fopen (handle_get_filename (fh), "wb");
92   w->lc = 0;
93   w->var_cnt = 0;
94   w->vars = NULL;
95   
96   /* Check that file create succeeded. */
97   if (w->file == NULL)
98     {
99       msg (ME, _("An error occurred while opening \"%s\" for writing "
100            "as a portable file: %s."),
101            handle_get_filename (fh), strerror (errno));
102       err_cond_fail ();
103       goto error;
104     }
105   
106   w->var_cnt = dict_get_var_cnt (dict);
107   w->vars = xmalloc (sizeof *w->vars * w->var_cnt);
108   for (i = 0; i < w->var_cnt; i++) 
109     {
110       const struct variable *dv = dict_get_var (dict, i);
111       struct pfm_var *pv = &w->vars[i];
112       pv->width = dv->width;
113       pv->fv = dv->fv;
114     }
115
116   /* Write file header. */
117   if (!write_header (w)
118       || !write_version_data (w)
119       || !write_variables (w, dict)
120       || !write_value_labels (w, dict)
121       || !buf_write (w, "F", 1))
122     goto error;
123
124   return w;
125
126 error:
127   pfm_close_writer (w);
128   return NULL;
129 }
130 \f  
131 /* Write NBYTES starting at BUF to the portable file represented by
132    H.  Break lines properly every 80 characters.  */
133 static int
134 buf_write (struct pfm_writer *w, const void *buf_, size_t nbytes)
135 {
136   const char *buf = buf_;
137
138   assert (buf != NULL);
139   while (nbytes + w->lc >= 80)
140     {
141       size_t n = 80 - w->lc;
142       
143       if (n && fwrite (buf, n, 1, w->file) != 1)
144         goto error;
145       
146       if (fwrite ("\r\n", 2, 1, w->file) != 1)
147         goto error;
148
149       nbytes -= n;
150       buf += n;
151       w->lc = 0;
152     }
153
154   if (nbytes && 1 != fwrite (buf, nbytes, 1, w->file))
155     goto error;
156   w->lc += nbytes;
157   
158   return 1;
159
160  error:
161   msg (ME, _("%s: Writing portable file: %s."),
162        handle_get_filename (w->fh), strerror (errno));
163   return 0;
164 }
165
166 /* Write D to the portable file as a floating-point field, and return
167    success. */
168 static int
169 write_float (struct pfm_writer *w, double d)
170 {
171   char buffer[64];
172   format_trig_double (d, DBL_DIG, buffer);
173   return buf_write (w, buffer, strlen (buffer)) && buf_write (w, "/", 1);
174 }
175
176 /* Write N to the portable file as an integer field, and return success. */
177 static int
178 write_int (struct pfm_writer *w, int n)
179 {
180   char buffer[64];
181   format_trig_int (n, false, buffer);
182   return buf_write (w, buffer, strlen (buffer)) && buf_write (w, "/", 1);
183 }
184
185 /* Write S to the portable file as a string field. */
186 static int
187 write_string (struct pfm_writer *w, const char *s)
188 {
189   size_t n = strlen (s);
190   return write_int (w, (int) n) && buf_write (w, s, n);
191 }
192 \f
193 /* Write file header. */
194 static int
195 write_header (struct pfm_writer *w)
196 {
197   /* PORTME. */
198   {
199     int i;
200
201     for (i = 0; i < 5; i++)
202       if (!buf_write (w, "ASCII SPSS PORT FILE                    ", 40))
203         return 0;
204   }
205   
206   {
207     /* PORTME: Translation table from SPSS character code to this
208        computer's native character code (which is probably ASCII). */
209     static const unsigned char spss2ascii[256] =
210       {
211         "0000000000000000000000000000000000000000000000000000000000000000"
212         "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ."
213         "<(+|&[]!$*);^-/|,%_>?`:$@'=\"000000~-0000123456789000-()0{}\\00000"
214         "0000000000000000000000000000000000000000000000000000000000000000"
215       };
216
217     if (!buf_write (w, spss2ascii, 256))
218       return 0;
219   }
220
221   if (!buf_write (w, "SPSSPORT", 8))
222     return 0;
223
224   return 1;
225 }
226
227 /* Writes version, date, and identification records. */
228 static int
229 write_version_data (struct pfm_writer *w)
230 {
231   if (!buf_write (w, "A", 1))
232     return 0;
233   
234   {
235     char date_str[9];
236     char time_str[7];
237     time_t t;
238     struct tm tm;
239     struct tm *tmp;
240
241     if ((time_t) -1 == time (&t))
242       {
243         tm.tm_sec = tm.tm_min = tm.tm_hour = tm.tm_mon = tm.tm_year = 0;
244         tm.tm_mday = 1;
245         tmp = &tm;
246       }
247     else 
248       tmp = localtime (&t);
249     
250     sprintf (date_str, "%04d%02d%02d",
251              tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday);
252     sprintf (time_str, "%02d%02d%02d", tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
253     if (!write_string (w, date_str) || !write_string (w, time_str))
254       return 0;
255   }
256
257   /* Product identification. */
258   if (!buf_write (w, "1", 1) || !write_string (w, version))
259     return 0;
260
261   /* Subproduct identification. */
262   if (!buf_write (w, "3", 1) || !write_string (w, host_system))
263     return 0;
264
265   return 1;
266 }
267
268 /* Write format F to file H, and return success. */
269 static int
270 write_format (struct pfm_writer *w, struct fmt_spec *f)
271 {
272   return (write_int (w, formats[f->type].spss)
273           && write_int (w, f->w)
274           && write_int (w, f->d));
275 }
276
277 /* Write value V for variable VV to file H, and return success. */
278 static int
279 write_value (struct pfm_writer *w, union value *v, struct variable *vv)
280 {
281   if (vv->type == NUMERIC)
282     return write_float (w, v->f);
283   else
284     return write_int (w, vv->width) && buf_write (w, v->s, vv->width);
285 }
286
287 /* Write variable records, and return success. */
288 static int
289 write_variables (struct pfm_writer *w, struct dictionary *dict)
290 {
291   int i;
292
293   dict_assign_short_names (dict);
294   
295   if (!buf_write (w, "4", 1) || !write_int (w, dict_get_var_cnt (dict))
296       || !write_int (w, 161))
297     return 0;
298
299   for (i = 0; i < dict_get_var_cnt (dict); i++)
300     {
301       static const char *miss_types[MISSING_COUNT] =
302         {
303           "", "8", "88", "888", "B ", "9", "A", "B 8", "98", "A8",
304         };
305
306       const char *m;
307       int j;
308
309       struct variable *v = dict_get_var (dict, i);
310       
311       if (!buf_write (w, "7", 1) || !write_int (w, v->width)
312           || !write_string (w, v->short_name)
313           || !write_format (w, &v->print) || !write_format (w, &v->write))
314         return 0;
315
316       for (m = miss_types[v->miss_type], j = 0; j < (int) strlen (m); j++)
317         if ((m[j] != ' ' && !buf_write (w, &m[j], 1))
318             || !write_value (w, &v->missing[j], v))
319           return 0;
320
321       if (v->label && (!buf_write (w, "C", 1) || !write_string (w, v->label)))
322         return 0;
323     }
324
325   return 1;
326 }
327
328 /* Write value labels to disk.  FIXME: Inefficient. */
329 static int
330 write_value_labels (struct pfm_writer *w, const struct dictionary *dict)
331 {
332   int i;
333
334   for (i = 0; i < dict_get_var_cnt (dict); i++)
335     {
336       struct val_labs_iterator *j;
337       struct variable *v = dict_get_var (dict, i);
338       struct val_lab *vl;
339
340       if (!val_labs_count (v->val_labs))
341         continue;
342
343       if (!buf_write (w, "D", 1)
344           || !write_int (w, 1)
345           || !write_string (w, v->short_name)
346           || !write_int (w, val_labs_count (v->val_labs)))
347         return 0;
348
349       for (vl = val_labs_first_sorted (v->val_labs, &j); vl != NULL;
350            vl = val_labs_next (v->val_labs, &j)) 
351         if (!write_value (w, &vl->value, v)
352             || !write_string (w, vl->label)) 
353           {
354             val_labs_done (&j);
355             return 0; 
356           }
357     }
358
359   return 1;
360 }
361
362 /* Writes case ELEM to the portable file represented by H.  Returns
363    success. */
364 int 
365 pfm_write_case (struct pfm_writer *w, struct ccase *c)
366 {
367   int i;
368   
369   for (i = 0; i < w->var_cnt; i++)
370     {
371       struct pfm_var *v = &w->vars[i];
372       
373       if (v->width == 0)
374         {
375           if (!write_float (w, case_num (c, v->fv)))
376             return 0;
377         }
378       else
379         {
380           if (!write_int (w, v->width)
381               || !buf_write (w, case_str (c, v->fv), v->width))
382             return 0;
383         }
384     }
385
386   return 1;
387 }
388
389 /* Closes a portable file after we're done with it. */
390 void
391 pfm_close_writer (struct pfm_writer *w)
392 {
393   if (w == NULL)
394     return;
395
396   fh_close (w->fh, "portable file", "we");
397   
398   if (w->file != NULL)
399     {
400       char buf[80];
401     
402       int n = 80 - w->lc;
403       if (n == 0)
404         n = 80;
405
406       memset (buf, 'Z', n);
407       buf_write (w, buf, n);
408
409       if (fclose (w->file) == EOF)
410         msg (ME, _("%s: Closing portable file: %s."),
411              handle_get_filename (w->fh), strerror (errno));
412     }
413
414   free (w->vars);
415   free (w);
416 }
417 \f
418 /* Base-30 conversion.
419
420    Portable files represent numbers in base-30 format, so we need
421    to be able to convert real and integer number to that base.
422    Older versions of PSPP used libgmp to do so, but this added a
423    big library dependency to do just one thing.  Now we do it
424    ourselves internally.
425
426    Important fact: base 30 is called "trigesimal". */
427
428 /* Conversion base. */
429 #define BASE 30                         /* As an integer. */
430 #define LDBASE ((long double) BASE)     /* As a long double. */
431
432 /* This is floor(log30(2**31)), the minimum number of trigesimal
433    digits that a `long int' can hold. */
434 #define CHUNK_SIZE 6                    
435
436 /* pow_tab[i] = pow (30, pow (2, i)) */
437 static long double pow_tab[16];
438
439 /* Initializes pow_tab[]. */
440 static void
441 init_pow_tab (void) 
442 {
443   static bool did_init = false;
444   long double power;
445   size_t i;
446
447   /* Only initialize once. */
448   if (did_init)
449     return;
450   did_init = true;
451
452   /* Set each element of pow_tab[] until we run out of numerical
453      range. */
454   i = 0;
455   for (power = 30.0L; power < DBL_MAX; power *= power)
456     {
457       assert (i < sizeof pow_tab / sizeof *pow_tab);
458       pow_tab[i++] = power;
459     }
460 }
461
462 /* Returns 30**EXPONENT, for 0 <= EXPONENT <= log30(DBL_MAX). */
463 static long double
464 pow30_nonnegative (int exponent)
465 {
466   long double power;
467   int i;
468
469   assert (exponent >= 0);
470   assert (exponent < 1L << (sizeof pow_tab / sizeof *pow_tab));
471
472   power = 1.L;
473   for (i = 0; exponent > 0; exponent >>= 1, i++)
474     if (exponent & 1)
475       power *= pow_tab[i];
476
477   return power;
478 }
479
480 /* Returns 30**EXPONENT, for log30(DBL_MIN) <= EXPONENT <=
481    log30(DBL_MAX). */
482 static long double
483 pow30 (int exponent)
484 {
485   if (exponent >= 0)
486     return pow30_nonnegative (exponent);
487   else
488     return 1.L / pow30_nonnegative (-exponent);
489 }
490
491 /* Returns the character corresponding to TRIG. */
492 static int
493 trig_to_char (int trig)
494 {
495   assert (trig >= 0 && trig < 30);
496   return "0123456789ABCDEFGHIJKLMNOPQRST"[trig];
497 }
498
499 /* Formats the TRIG_CNT trigs in TRIGS[], writing them as
500    null-terminated STRING.  The trigesimal point is inserted
501    after TRIG_PLACES characters have been printed, if necessary
502    adding extra zeros at either end for correctness.  Returns the
503    character after the formatted number. */
504 static char *
505 format_trig_digits (char *string,
506                     const char trigs[], int trig_cnt, int trig_places)
507 {
508   if (trig_places < 0)
509     {
510       *string++ = '.';
511       while (trig_places++ < 0)
512         *string++ = '0';
513       trig_places = -1;
514     }
515   while (trig_cnt-- > 0)
516     {
517       if (trig_places-- == 0)
518         *string++ = '.';
519       *string++ = trig_to_char (*trigs++);
520     }
521   while (trig_places-- > 0)
522     *string++ = '0';
523   *string = '\0';
524   return string;
525 }
526
527 /* Helper function for format_trig_int() that formats VALUE as a
528    trigesimal integer at CP.  VALUE must be nonnegative.
529    Returns the character following the formatted integer. */
530 static char *
531 recurse_format_trig_int (char *cp, int value)
532 {
533   int trig = value % BASE;
534   value /= BASE;
535   if (value > 0)
536     cp = recurse_format_trig_int (cp, value);
537   *cp++ = trig_to_char (trig);
538   return cp;
539 }
540
541 /* Formats VALUE as a trigesimal integer in null-terminated
542    STRING[].  VALUE must be in the range -DBL_MAX...DBL_MAX.  If
543    FORCE_SIGN is true, a sign is always inserted; otherwise, a
544    sign is only inserted if VALUE is negative. */
545 static char *
546 format_trig_int (int value, bool force_sign, char string[])
547 {
548   /* Insert sign. */
549   if (value < 0)
550     {
551       *string++ = '-';
552       value = -value;
553     }
554   else if (force_sign)
555     *string++ = '+';
556
557   /* Format integer. */
558   string = recurse_format_trig_int (string, value);
559   *string = '\0';
560   return string;
561 }
562
563 /* Determines whether the TRIG_CNT trigesimals in TRIGS[] warrant
564    rounding up or down.  Returns true if TRIGS[] represents a
565    value greater than half, false if less than half.  If TRIGS[]
566    is exactly half, examines TRIGS[-1] and returns true if odd,
567    false if even ("round to even"). */
568 static bool
569 should_round_up (const char trigs[], int trig_cnt)
570 {
571   assert (trig_cnt > 0);
572
573   if (*trigs < BASE / 2)
574     {
575       /* Less than half: round down. */
576       return false;
577     }
578   else if (*trigs > BASE / 2)
579     {
580       /* Greater than half: round up. */
581       return true;
582     }
583   else
584     {
585       /* Approximately half: look more closely. */
586       int i;
587       for (i = 1; i < trig_cnt; i++)
588         if (trigs[i] > 0)
589           {
590             /* Slightly greater than half: round up. */
591             return true;
592           }
593
594       /* Exactly half: round to even. */
595       return trigs[-1] % 2;
596     }
597 }
598
599 /* Rounds up the rightmost trig in the TRIG_CNT trigs in TRIGS[],
600    carrying to the left as necessary.  Returns true if
601    successful, false on failure (due to a carry out of the
602    leftmost position). */
603 static bool
604 try_round_up (char *trigs, int trig_cnt)
605 {
606   while (trig_cnt > 0)
607     {
608       char *round_trig = trigs + --trig_cnt;
609       if (*round_trig != BASE - 1)
610         {
611           /* Round this trig up to the next value. */
612           ++*round_trig;
613           return true;
614         }
615
616       /* Carry over to the next trig to the left. */
617       *round_trig = 0;
618     }
619
620   /* Ran out of trigs to carry. */
621   return false;
622 }
623
624 /* Converts VALUE to trigesimal format in string OUTPUT[] with the
625    equivalent of at least BASE_10_PRECISION decimal digits of
626    precision.  The output format may use conventional or
627    scientific notation.  Missing, infinite, and extreme values
628    are represented with "*.". */
629 static void
630 format_trig_double (long double value, int base_10_precision, char output[])
631 {
632   /* Original VALUE was negative? */
633   bool negative;
634
635   /* Number of significant trigesimals. */
636   int base_30_precision;
637
638   /* Base-2 significand and exponent for original VALUE. */
639   double base_2_sig;
640   int base_2_exp;
641
642   /* VALUE as a set of trigesimals. */
643   char buffer[DBL_DIG + 16];
644   char *trigs;
645   int trig_cnt;
646
647   /* Number of trigesimal places for trigs.
648      trigs[0] has coefficient 30**(trig_places - 1),
649      trigs[1] has coefficient 30**(trig_places - 2),
650      and so on.
651      In other words, the trigesimal point is just before trigs[0].
652    */
653   int trig_places;
654
655   /* Number of trigesimal places left to write into BUFFER. */
656   int trigs_to_output;
657
658   init_pow_tab ();
659
660   /* Handle special cases. */
661   if (value == SYSMIS)
662     goto missing_value;
663   if (value == 0.)
664     goto zero;
665
666   /* Make VALUE positive. */
667   if (value < 0)
668     {
669       value = -value;
670       negative = true;
671     }
672   else
673     negative = false;
674
675   /* Adjust VALUE to roughly 30**3, by shifting the trigesimal
676      point left or right as necessary.  We approximate the
677      base-30 exponent by obtaining the base-2 exponent, then
678      multiplying by log30(2).  This approximation is sufficient
679      to ensure that the adjusted VALUE is always in the range
680      0...30**6, an invariant of the loop below. */
681   errno = 0;
682   base_2_sig = frexp (value, &base_2_exp);
683   if (errno != 0 || !finite (base_2_sig))
684     goto missing_value;
685   if (base_2_exp == 0 && base_2_sig == 0.)
686     goto zero;
687   if (base_2_exp <= INT_MIN / 20379L || base_2_exp >= INT_MAX / 20379L)
688     goto missing_value;
689   trig_places = (base_2_exp * 20379L / 100000L) + CHUNK_SIZE / 2;
690   value *= pow30 (CHUNK_SIZE - trig_places);
691
692   /* Dump all the trigs to buffer[], CHUNK_SIZE at a time. */
693   trigs = buffer;
694   trig_cnt = 0;
695   for (trigs_to_output = DIV_RND_UP (DBL_DIG * 2, 3) + 1 + (CHUNK_SIZE / 2);
696        trigs_to_output > 0;
697        trigs_to_output -= CHUNK_SIZE)
698     {
699       long chunk;
700       int trigs_left;
701
702       /* The current chunk is just the integer part of VALUE,
703          truncated to the nearest integer.  The chunk fits in a
704          long. */
705       chunk = value;
706       assert (pow30 (CHUNK_SIZE) <= LONG_MAX);
707       assert (chunk >= 0 && chunk < pow30 (CHUNK_SIZE));
708
709       value -= chunk;
710
711       /* Append the chunk, in base 30, to trigs[]. */
712       for (trigs_left = CHUNK_SIZE; chunk > 0 && trigs_left > 0; )
713         {
714           trigs[trig_cnt + --trigs_left] = chunk % 30;
715           chunk /= 30;
716         }
717       while (trigs_left > 0)
718         trigs[trig_cnt + --trigs_left] = 0;
719       trig_cnt += CHUNK_SIZE;
720
721       /* Proceed to the next chunk. */
722       if (value == 0.)
723         break;
724       value *= pow (LDBASE, CHUNK_SIZE);
725     }
726
727   /* Strip leading zeros. */
728   while (trig_cnt > 1 && *trigs == 0)
729     {
730       trigs++;
731       trig_cnt--;
732       trig_places--;
733     }
734
735   /* Round to requested precision, conservatively estimating the
736      required base-30 precision as 2/3 of the base-10 precision
737      (log30(10) = .68). */
738   assert (base_10_precision > 0);
739   base_30_precision = DIV_RND_UP (base_10_precision * 2, 3);
740   if (trig_cnt > base_30_precision)
741     {
742       if (should_round_up (trigs + base_30_precision,
743                            trig_cnt - base_30_precision))
744         {
745           /* Try to round up. */
746           if (try_round_up (trigs, base_30_precision))
747             {
748               /* Rounding up worked. */
749               trig_cnt = base_30_precision;
750             }
751           else
752             {
753               /* Couldn't round up because we ran out of trigs to
754                  carry into.  Do the carry here instead. */
755               *trigs = 1;
756               trig_cnt = 1;
757               trig_places++;
758             }
759         }
760       else
761         {
762           /* Round down. */
763           trig_cnt = base_30_precision;
764         }
765     }
766   else
767     {
768       /* No rounding required: fewer digits available than
769          requested. */
770     }
771
772   /* Strip trailing zeros. */
773   while (trig_cnt > 1 && trigs[trig_cnt - 1] == 0)
774     trig_cnt--;
775
776   /* Write output. */
777   if (negative)
778     *output++ = '-';
779   if (trig_places >= -1 && trig_places < trig_cnt + 3)
780     {
781       /* Use conventional notation. */
782       format_trig_digits (output, trigs, trig_cnt, trig_places);
783     }
784   else
785     {
786       /* Use scientific notation. */
787       char *op;
788       op = format_trig_digits (output, trigs, trig_cnt, trig_cnt);
789       op = format_trig_int (trig_places - trig_cnt, true, op);
790     }
791   return;
792
793  zero:
794   strcpy (output, "0");
795   return;
796
797  missing_value:
798   strcpy (output, "*.");
799   return;
800 }