b900c2292f81f19801e4fe8da794aeff581bb020
[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    Portable files represent numbers in base-30 format, so we need
418    to be able to convert real and integer number to that base.
419    Older versions of PSPP used libgmp to do so, but this added a
420    big library dependency to do just one thing.  Now we do it
421    ourselves internally.
422
423    Important fact: base 30 is called "trigesimal". */
424
425 /* Conversion base. */
426 #define BASE 30                         /* As an integer. */
427 #define LDBASE ((long double) BASE)     /* As a long double. */
428
429 /* This is floor(log30(2**31)), the minimum number of trigesimal
430    digits that a `long int' can hold. */
431 #define CHUNK_SIZE 6                    
432
433 /* pow_tab[i] = pow (30, pow (2, i)) */
434 static long double pow_tab[16];
435
436 /* Initializes pow_tab[]. */
437 static void
438 init_pow_tab (void) 
439 {
440   static bool did_init = false;
441   long double power;
442   size_t i;
443
444   /* Only initialize once. */
445   if (did_init)
446     return;
447   did_init = true;
448
449   /* Set each element of pow_tab[] until we run out of numerical
450      range. */
451   i = 0;
452   for (power = 30.0L; power < DBL_MAX; power *= power)
453     {
454       assert (i < sizeof pow_tab / sizeof *pow_tab);
455       pow_tab[i++] = power;
456     }
457 }
458
459 /* Returns 30**EXPONENT, for 0 <= EXPONENT <= log30(DBL_MAX). */
460 static long double
461 pow30_nonnegative (int exponent)
462 {
463   long double power;
464   int i;
465
466   assert (exponent >= 0);
467   assert (exponent < 1L << (sizeof pow_tab / sizeof *pow_tab));
468
469   power = 1.L;
470   for (i = 0; exponent > 0; exponent >>= 1, i++)
471     if (exponent & 1)
472       power *= pow_tab[i];
473
474   return power;
475 }
476
477 /* Returns 30**EXPONENT, for log30(DBL_MIN) <= EXPONENT <=
478    log30(DBL_MAX). */
479 static long double
480 pow30 (int exponent)
481 {
482   if (exponent >= 0)
483     return pow30_nonnegative (exponent);
484   else
485     return 1.L / pow30_nonnegative (-exponent);
486 }
487
488 /* Returns the character corresponding to TRIG. */
489 static int
490 trig_to_char (int trig)
491 {
492   assert (trig >= 0 && trig < 30);
493   return "0123456789ABCDEFGHIJKLMNOPQRST"[trig];
494 }
495
496 /* Formats the TRIG_CNT trigs in TRIGS[], writing them as
497    null-terminated STRING.  The trigesimal point is inserted
498    after TRIG_PLACES characters have been printed, if necessary
499    adding extra zeros at either end for correctness.  Returns the
500    character after the formatted number. */
501 static char *
502 format_trig_digits (char *string,
503                     const char trigs[], int trig_cnt, int trig_places)
504 {
505   if (trig_places < 0)
506     {
507       *string++ = '.';
508       while (trig_places++ < 0)
509         *string++ = '0';
510       trig_places = -1;
511     }
512   while (trig_cnt-- > 0)
513     {
514       if (trig_places-- == 0)
515         *string++ = '.';
516       *string++ = trig_to_char (*trigs++);
517     }
518   while (trig_places-- > 0)
519     *string++ = '0';
520   *string = '\0';
521   return string;
522 }
523
524 /* Helper function for format_trig_int() that formats VALUE as a
525    trigesimal integer at CP.  VALUE must be nonnegative.
526    Returns the character following the formatted integer. */
527 static char *
528 recurse_format_trig_int (char *cp, int value)
529 {
530   int trig = value % BASE;
531   value /= BASE;
532   if (value > 0)
533     cp = recurse_format_trig_int (cp, value);
534   *cp++ = trig_to_char (trig);
535   return cp;
536 }
537
538 /* Formats VALUE as a trigesimal integer in null-terminated
539    STRING[].  VALUE must be in the range -DBL_MAX...DBL_MAX.  If
540    FORCE_SIGN is true, a sign is always inserted; otherwise, a
541    sign is only inserted if VALUE is negative. */
542 static char *
543 format_trig_int (int value, bool force_sign, char string[])
544 {
545   /* Insert sign. */
546   if (value < 0)
547     {
548       *string++ = '-';
549       value = -value;
550     }
551   else if (force_sign)
552     *string++ = '+';
553
554   /* Format integer. */
555   string = recurse_format_trig_int (string, value);
556   *string = '\0';
557   return string;
558 }
559
560 /* Determines whether the TRIG_CNT trigesimals in TRIGS[] warrant
561    rounding up or down.  Returns true if TRIGS[] represents a
562    value greater than half, false if less than half.  If TRIGS[]
563    is exactly half, examines TRIGS[-1] and returns true if odd,
564    false if even ("round to even"). */
565 static bool
566 should_round_up (const char trigs[], int trig_cnt)
567 {
568   assert (trig_cnt > 0);
569
570   if (*trigs < BASE / 2)
571     {
572       /* Less than half: round down. */
573       return false;
574     }
575   else if (*trigs > BASE / 2)
576     {
577       /* Greater than half: round up. */
578       return true;
579     }
580   else
581     {
582       /* Approximately half: look more closely. */
583       int i;
584       for (i = 1; i < trig_cnt; i++)
585         if (trigs[i] > 0)
586           {
587             /* Slightly greater than half: round up. */
588             return true;
589           }
590
591       /* Exactly half: round to even. */
592       return trigs[-1] % 2;
593     }
594 }
595
596 /* Rounds up the rightmost trig in the TRIG_CNT trigs in TRIGS[],
597    carrying to the left as necessary.  Returns true if
598    successful, false on failure (due to a carry out of the
599    leftmost position). */
600 static bool
601 try_round_up (char *trigs, int trig_cnt)
602 {
603   while (trig_cnt > 0)
604     {
605       char *round_trig = trigs + --trig_cnt;
606       if (*round_trig != BASE - 1)
607         {
608           /* Round this trig up to the next value. */
609           ++*round_trig;
610           return true;
611         }
612
613       /* Carry over to the next trig to the left. */
614       *round_trig = 0;
615     }
616
617   /* Ran out of trigs to carry. */
618   return false;
619 }
620
621 /* Converts VALUE to trigesimal format in string OUTPUT[] with the
622    equivalent of at least BASE_10_PRECISION decimal digits of
623    precision.  The output format may use conventional or
624    scientific notation.  Missing, infinite, and extreme values
625    are represented with "*.". */
626 static void
627 format_trig_double (long double value, int base_10_precision, char output[])
628 {
629   /* Original VALUE was negative? */
630   bool negative;
631
632   /* Number of significant trigesimals. */
633   int base_30_precision;
634
635   /* Base-2 significand and exponent for original VALUE. */
636   double base_2_sig;
637   int base_2_exp;
638
639   /* VALUE as a set of trigesimals. */
640   char buffer[DBL_DIG + 16];
641   char *trigs;
642   int trig_cnt;
643
644   /* Number of trigesimal places for trigs.
645      trigs[0] has coefficient 30**(trig_places - 1),
646      trigs[1] has coefficient 30**(trig_places - 2),
647      and so on.
648      In other words, the trigesimal point is just before trigs[0].
649    */
650   int trig_places;
651
652   /* Number of trigesimal places left to write into BUFFER. */
653   int trigs_to_output;
654
655   init_pow_tab ();
656
657   /* Handle special cases. */
658   if (value == SYSMIS)
659     goto missing_value;
660   if (value == 0.)
661     goto zero;
662
663   /* Make VALUE positive. */
664   if (value < 0)
665     {
666       value = -value;
667       negative = true;
668     }
669   else
670     negative = false;
671
672   /* Adjust VALUE to roughly 30**3, by shifting the trigesimal
673      point left or right as necessary.  We approximate the
674      base-30 exponent by obtaining the base-2 exponent, then
675      multiplying by log30(2).  This approximation is sufficient
676      to ensure that the adjusted VALUE is always in the range
677      0...30**6, an invariant of the loop below. */
678   errno = 0;
679   base_2_sig = frexp (value, &base_2_exp);
680   if (errno != 0 || !finite (base_2_sig))
681     goto missing_value;
682   if (base_2_exp == 0 && base_2_sig == 0.)
683     goto zero;
684   if (base_2_exp <= INT_MIN / 20379L || base_2_exp >= INT_MAX / 20379L)
685     goto missing_value;
686   trig_places = (base_2_exp * 20379L / 100000L) + CHUNK_SIZE / 2;
687   value *= pow30 (CHUNK_SIZE - trig_places);
688
689   /* Dump all the trigs to buffer[], CHUNK_SIZE at a time. */
690   trigs = buffer;
691   trig_cnt = 0;
692   for (trigs_to_output = DIV_RND_UP (DBL_DIG * 2, 3) + 1 + (CHUNK_SIZE / 2);
693        trigs_to_output > 0;
694        trigs_to_output -= CHUNK_SIZE)
695     {
696       long chunk;
697       int trigs_left;
698
699       /* The current chunk is just the integer part of VALUE,
700          truncated to the nearest integer.  The chunk fits in a
701          long. */
702       chunk = value;
703       assert (pow30 (CHUNK_SIZE) <= LONG_MAX);
704       assert (chunk >= 0 && chunk < pow30 (CHUNK_SIZE));
705
706       value -= chunk;
707
708       /* Append the chunk, in base 30, to trigs[]. */
709       for (trigs_left = CHUNK_SIZE; chunk > 0 && trigs_left > 0; )
710         {
711           trigs[trig_cnt + --trigs_left] = chunk % 30;
712           chunk /= 30;
713         }
714       while (trigs_left > 0)
715         trigs[trig_cnt + --trigs_left] = 0;
716       trig_cnt += CHUNK_SIZE;
717
718       /* Proceed to the next chunk. */
719       if (value == 0.)
720         break;
721       value *= pow (LDBASE, CHUNK_SIZE);
722     }
723
724   /* Strip leading zeros. */
725   while (trig_cnt > 1 && *trigs == 0)
726     {
727       trigs++;
728       trig_cnt--;
729       trig_places--;
730     }
731
732   /* Round to requested precision, conservatively estimating the
733      required base-30 precision as 2/3 of the base-10 precision
734      (log30(10) = .68). */
735   assert (base_10_precision > 0);
736   base_30_precision = DIV_RND_UP (base_10_precision * 2, 3);
737   if (trig_cnt > base_30_precision)
738     {
739       if (should_round_up (trigs + base_30_precision,
740                            trig_cnt - base_30_precision))
741         {
742           /* Try to round up. */
743           if (try_round_up (trigs, base_30_precision))
744             {
745               /* Rounding up worked. */
746               trig_cnt = base_30_precision;
747             }
748           else
749             {
750               /* Couldn't round up because we ran out of trigs to
751                  carry into.  Do the carry here instead. */
752               *trigs = 1;
753               trig_cnt = 1;
754               trig_places++;
755             }
756         }
757       else
758         {
759           /* Round down. */
760           trig_cnt = base_30_precision;
761         }
762     }
763   else
764     {
765       /* No rounding required: fewer digits available than
766          requested. */
767     }
768
769   /* Strip trailing zeros. */
770   while (trig_cnt > 1 && trigs[trig_cnt - 1] == 0)
771     trig_cnt--;
772
773   /* Write output. */
774   if (negative)
775     *output++ = '-';
776   if (trig_places >= -1 && trig_places < trig_cnt + 3)
777     {
778       /* Use conventional notation. */
779       format_trig_digits (output, trigs, trig_cnt, trig_places);
780     }
781   else
782     {
783       /* Use scientific notation. */
784       char *op;
785       op = format_trig_digits (output, trigs, trig_cnt, trig_cnt);
786       op = format_trig_int (trig_places - trig_cnt, true, op);
787     }
788   return;
789
790  zero:
791   strcpy (output, "0");
792   return;
793
794  missing_value:
795   strcpy (output, "*.");
796   return;
797 }