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