bdd93c99254ad2cfd210899bdf12ae70568758c2
[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., 59 Temple Place - Suite 330, Boston, MA
18    02111-1307, 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 "gmp.h"
36 #include "hash.h"
37 #include "magic.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 *, const struct dictionary *);
68 static int write_value_labels (struct pfm_writer *, const struct dictionary *);
69
70 /* Writes the dictionary DICT to portable file HANDLE.  Returns
71    nonzero only if successful. */
72 struct pfm_writer *
73 pfm_open_writer (struct file_handle *fh, const struct dictionary *dict)
74 {
75   struct pfm_writer *w = NULL;
76   size_t i;
77
78   if (!fh_open (fh, "portable file", "we"))
79     goto error;
80   
81   /* Open the physical disk file. */
82   w = xmalloc (sizeof *w);
83   w->fh = fh;
84   w->file = fopen (handle_get_filename (fh), "wb");
85   w->lc = 0;
86   w->var_cnt = 0;
87   w->vars = NULL;
88   
89   /* Check that file create succeeded. */
90   if (w->file == NULL)
91     {
92       msg (ME, _("An error occurred while opening \"%s\" for writing "
93            "as a portable file: %s."),
94            handle_get_filename (fh), strerror (errno));
95       err_cond_fail ();
96       goto error;
97     }
98   
99   w->var_cnt = dict_get_var_cnt (dict);
100   w->vars = xmalloc (sizeof *w->vars * w->var_cnt);
101   for (i = 0; i < w->var_cnt; i++) 
102     {
103       const struct variable *dv = dict_get_var (dict, i);
104       struct pfm_var *pv = &w->vars[i];
105       pv->width = dv->width;
106       pv->fv = dv->fv;
107     }
108
109   /* Write file header. */
110   if (!write_header (w)
111       || !write_version_data (w)
112       || !write_variables (w, dict)
113       || !write_value_labels (w, dict)
114       || !buf_write (w, "F", 1))
115     goto error;
116
117   return w;
118
119 error:
120   pfm_close_writer (w);
121   return NULL;
122 }
123 \f  
124 /* Write NBYTES starting at BUF to the portable file represented by
125    H.  Break lines properly every 80 characters.  */
126 static int
127 buf_write (struct pfm_writer *w, const void *buf_, size_t nbytes)
128 {
129   const char *buf = buf_;
130
131   assert (buf != NULL);
132   while (nbytes + w->lc >= 80)
133     {
134       size_t n = 80 - w->lc;
135       
136       if (n && fwrite (buf, n, 1, w->file) != 1)
137         goto error;
138       
139       if (fwrite ("\r\n", 2, 1, w->file) != 1)
140         goto error;
141
142       nbytes -= n;
143       buf += n;
144       w->lc = 0;
145     }
146
147   if (nbytes && 1 != fwrite (buf, nbytes, 1, w->file))
148     goto error;
149   w->lc += nbytes;
150   
151   return 1;
152
153  error:
154   msg (ME, _("%s: Writing portable file: %s."),
155        handle_get_filename (w->fh), strerror (errno));
156   return 0;
157 }
158
159 /* Write D to the portable file as a floating-point field, and return
160    success. */
161 static int
162 write_float (struct pfm_writer *w, double d)
163 {
164   int neg = 0;
165   char *mantissa;
166   int mantissa_len;
167   mp_exp_t exponent;
168   char *buf, *cp;
169   int success;
170
171   if (d < 0.)
172     {
173       d = -d;
174       neg = 1;
175     }
176   
177   if (d == fabs (SYSMIS) || d == HUGE_VAL)
178     return buf_write (w, "*.", 2);
179   
180   /* Use GNU libgmp2 to convert D into base-30. */
181   {
182     mpf_t f;
183     
184     mpf_init_set_d (f, d);
185     mantissa = mpf_get_str (NULL, &exponent, 30, 0, f);
186     mpf_clear (f);
187
188     for (cp = mantissa; *cp; cp++)
189       *cp = toupper (*cp);
190   }
191   
192   /* Choose standard or scientific notation. */
193   mantissa_len = (int) strlen (mantissa);
194   cp = buf = local_alloc (mantissa_len + 32);
195   if (neg)
196     *cp++ = '-';
197   if (mantissa_len == 0)
198     *cp++ = '0';
199   else if (exponent < -4 || exponent > (mp_exp_t) mantissa_len)
200     {
201       /* Scientific notation. */
202       *cp++ = mantissa[0];
203       *cp++ = '.';
204       cp = stpcpy (cp, &mantissa[1]);
205       cp = spprintf (cp, "%+ld", (long) (exponent - 1));
206     }
207   else if (exponent <= 0)
208     {
209       /* Standard notation, D <= 1. */
210       *cp++ = '.';
211       memset (cp, '0', -exponent);
212       cp += -exponent;
213       cp = stpcpy (cp, mantissa);
214     }
215   else 
216     {
217       /* Standard notation, D > 1. */
218       memcpy (cp, mantissa, exponent);
219       cp += exponent;
220       *cp++ = '.';
221       cp = stpcpy (cp, &mantissa[exponent]);
222     }
223   *cp++ = '/';
224   
225   success = buf_write (w, buf, cp - buf);
226   local_free (buf);
227   free (mantissa);
228   return success;
229 }
230
231 /* Write N to the portable file as an integer field, and return success. */
232 static int
233 write_int (struct pfm_writer *w, int n)
234 {
235   char buf[64];
236   char *bp = &buf[64];
237   int neg = 0;
238
239   *--bp = '/';
240   
241   if (n < 0)
242     {
243       n = -n;
244       neg = 1;
245     }
246   
247   do
248     {
249       int r = n % 30;
250
251       /* PORTME: character codes. */
252       if (r < 10)
253         *--bp = r + '0';
254       else
255         *--bp = r - 10 + 'A';
256
257       n /= 30;
258     }
259   while (n > 0);
260
261   if (neg)
262     *--bp = '-';
263
264   return buf_write (w, bp, &buf[64] - bp);
265 }
266
267 /* Write S to the portable file as a string field. */
268 static int
269 write_string (struct pfm_writer *w, const char *s)
270 {
271   size_t n = strlen (s);
272   return write_int (w, (int) n) && buf_write (w, s, n);
273 }
274 \f
275 /* Write file header. */
276 static int
277 write_header (struct pfm_writer *w)
278 {
279   /* PORTME. */
280   {
281     int i;
282
283     for (i = 0; i < 5; i++)
284       if (!buf_write (w, "ASCII SPSS PORT FILE                    ", 40))
285         return 0;
286   }
287   
288   {
289     /* PORTME: Translation table from SPSS character code to this
290        computer's native character code (which is probably ASCII). */
291     static const unsigned char spss2ascii[256] =
292       {
293         "0000000000000000000000000000000000000000000000000000000000000000"
294         "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ."
295         "<(+|&[]!$*);^-/|,%_>?`:$@'=\"000000~-0000123456789000-()0{}\\00000"
296         "0000000000000000000000000000000000000000000000000000000000000000"
297       };
298
299     if (!buf_write (w, spss2ascii, 256))
300       return 0;
301   }
302
303   if (!buf_write (w, "SPSSPORT", 8))
304     return 0;
305
306   return 1;
307 }
308
309 /* Writes version, date, and identification records. */
310 static int
311 write_version_data (struct pfm_writer *w)
312 {
313   if (!buf_write (w, "A", 1))
314     return 0;
315   
316   {
317     char date_str[9];
318     char time_str[7];
319     time_t t;
320     struct tm tm;
321     struct tm *tmp;
322
323     if ((time_t) -1 == time (&t))
324       {
325         tm.tm_sec = tm.tm_min = tm.tm_hour = tm.tm_mon = tm.tm_year = 0;
326         tm.tm_mday = 1;
327         tmp = &tm;
328       }
329     else 
330       tmp = localtime (&t);
331     
332     sprintf (date_str, "%04d%02d%02d",
333              tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday);
334     sprintf (time_str, "%02d%02d%02d", tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
335     if (!write_string (w, date_str) || !write_string (w, time_str))
336       return 0;
337   }
338
339   /* Product identification. */
340   if (!buf_write (w, "1", 1) || !write_string (w, version))
341     return 0;
342
343   /* Subproduct identification. */
344   if (!buf_write (w, "3", 1) || !write_string (w, host_system))
345     return 0;
346
347   return 1;
348 }
349
350 /* Write format F to file H, and return success. */
351 static int
352 write_format (struct pfm_writer *w, struct fmt_spec *f)
353 {
354   return (write_int (w, formats[f->type].spss)
355           && write_int (w, f->w)
356           && write_int (w, f->d));
357 }
358
359 /* Write value V for variable VV to file H, and return success. */
360 static int
361 write_value (struct pfm_writer *w, union value *v, struct variable *vv)
362 {
363   if (vv->type == NUMERIC)
364     return write_float (w, v->f);
365   else
366     return write_int (w, vv->width) && buf_write (w, v->s, vv->width);
367 }
368
369 /* Write variable records, and return success. */
370 static int
371 write_variables (struct pfm_writer *w, const struct dictionary *dict)
372 {
373   int i;
374   
375   if (!buf_write (w, "4", 1) || !write_int (w, dict_get_var_cnt (dict))
376       || !write_int (w, 161))
377     return 0;
378
379   for (i = 0; i < dict_get_var_cnt (dict); i++)
380     {
381       static const char *miss_types[MISSING_COUNT] =
382         {
383           "", "8", "88", "888", "B ", "9", "A", "B 8", "98", "A8",
384         };
385
386       const char *m;
387       int j;
388
389       struct variable *v = dict_get_var (dict, i);
390       
391       if (!buf_write (w, "7", 1) || !write_int (w, v->width)
392           || !write_string (w, v->name)
393           || !write_format (w, &v->print) || !write_format (w, &v->write))
394         return 0;
395
396       for (m = miss_types[v->miss_type], j = 0; j < (int) strlen (m); j++)
397         if ((m[j] != ' ' && !buf_write (w, &m[j], 1))
398             || !write_value (w, &v->missing[j], v))
399           return 0;
400
401       if (v->label && (!buf_write (w, "C", 1) || !write_string (w, v->label)))
402         return 0;
403     }
404
405   return 1;
406 }
407
408 /* Write value labels to disk.  FIXME: Inefficient. */
409 static int
410 write_value_labels (struct pfm_writer *w, const struct dictionary *dict)
411 {
412   int i;
413
414   for (i = 0; i < dict_get_var_cnt (dict); i++)
415     {
416       struct val_labs_iterator *j;
417       struct variable *v = dict_get_var (dict, i);
418       struct val_lab *vl;
419
420       if (!val_labs_count (v->val_labs))
421         continue;
422
423       if (!buf_write (w, "D", 1)
424           || !write_int (w, 1)
425           || !write_string (w, v->name)
426           || !write_int (w, val_labs_count (v->val_labs)))
427         return 0;
428
429       for (vl = val_labs_first_sorted (v->val_labs, &j); vl != NULL;
430            vl = val_labs_next (v->val_labs, &j)) 
431         if (!write_value (w, &vl->value, v)
432             || !write_string (w, vl->label)) 
433           {
434             val_labs_done (&j);
435             return 0; 
436           }
437     }
438
439   return 1;
440 }
441
442 /* Writes case ELEM to the portable file represented by H.  Returns
443    success. */
444 int 
445 pfm_write_case (struct pfm_writer *w, struct ccase *c)
446 {
447   int i;
448   
449   for (i = 0; i < w->var_cnt; i++)
450     {
451       struct pfm_var *v = &w->vars[i];
452       
453       if (v->width == 0)
454         {
455           if (!write_float (w, case_num (c, v->fv)))
456             return 0;
457         }
458       else
459         {
460           if (!write_int (w, v->width)
461               || !buf_write (w, case_str (c, v->fv), v->width))
462             return 0;
463         }
464     }
465
466   return 1;
467 }
468
469 /* Closes a portable file after we're done with it. */
470 void
471 pfm_close_writer (struct pfm_writer *w)
472 {
473   if (w == NULL)
474     return;
475
476   fh_close (w->fh, "portable file", "we");
477   
478   if (w->file != NULL)
479     {
480       char buf[80];
481     
482       int n = 80 - w->lc;
483       if (n == 0)
484         n = 80;
485
486       memset (buf, 'Z', n);
487       buf_write (w, buf, n);
488
489       if (fclose (w->file) == EOF)
490         msg (ME, _("%s: Closing portable file: %s."),
491              handle_get_filename (w->fh), strerror (errno));
492     }
493
494   free (w->vars);
495   free (w);
496 }