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