Clean up treatment of missing values by moving all the code into
[pspp-builds.git] / src / sfm-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 "sfm-write.h"
22 #include "sfmP.h"
23 #include "error.h"
24 #include <stdlib.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <time.h>
28 #if HAVE_UNISTD_H
29 #include <unistd.h>     /* Required by SunOS4. */
30 #endif
31 #include "alloc.h"
32 #include "case.h"
33 #include "dictionary.h"
34 #include "error.h"
35 #include "file-handle.h"
36 #include "getl.h"
37 #include "hash.h"
38 #include "magic.h"
39 #include "misc.h"
40 #include "str.h"
41 #include "value-labels.h"
42 #include "var.h"
43 #include "version.h"
44
45 #include "gettext.h"
46 #define _(msgid) gettext (msgid)
47
48 #include "debug-print.h"
49
50 /* Compression bias used by PSPP.  Values between (1 -
51    COMPRESSION_BIAS) and (251 - COMPRESSION_BIAS) inclusive can be
52    compressed. */
53 #define COMPRESSION_BIAS 100
54
55 /* System file writer. */
56 struct sfm_writer
57   {
58     struct file_handle *fh;     /* File handle. */
59     FILE *file;                 /* File stream. */
60
61     int needs_translation;      /* 0=use fast path, 1=translation needed. */
62     int compress;               /* 1=compressed, 0=not compressed. */
63     int case_cnt;               /* Number of cases written so far. */
64     size_t flt64_cnt;           /* Number of flt64 elements in case. */
65
66     /* Compression buffering. */
67     flt64 *buf;                 /* Buffered data. */
68     flt64 *end;                 /* Buffer end. */
69     flt64 *ptr;                 /* Current location in buffer. */
70     unsigned char *x;           /* Location in current instruction octet. */
71     unsigned char *y;           /* End of instruction octet. */
72
73     /* Variables. */
74     struct sfm_var *vars;       /* Variables. */
75     size_t var_cnt;             /* Number of variables. */
76   };
77
78 /* A variable in a system file. */
79 struct sfm_var 
80   {
81     int width;                  /* 0=numeric, otherwise string width. */
82     int fv;                     /* Index into case. */
83     size_t flt64_cnt;           /* Number of flt64 elements. */
84   };
85
86 static char *append_string_max (char *, const char *, const char *);
87 static int write_header (struct sfm_writer *, const struct dictionary *);
88 static int buf_write (struct sfm_writer *, const void *, size_t);
89 static int write_variable (struct sfm_writer *, struct variable *);
90 static int write_value_labels (struct sfm_writer *,
91                                struct variable *, int idx);
92 static int write_rec_7_34 (struct sfm_writer *);
93
94 static int write_longvar_table (struct sfm_writer *w, 
95                                 const struct dictionary *dict);
96
97 static int write_variable_display_parameters (struct sfm_writer *w, 
98                                               const struct dictionary *dict);
99
100
101 static int write_documents (struct sfm_writer *, const struct dictionary *);
102 static int does_dict_need_translation (const struct dictionary *);
103
104 static inline int
105 var_flt64_cnt (const struct variable *v) 
106 {
107   return v->type == NUMERIC ? 1 : DIV_RND_UP (v->width, sizeof (flt64));
108 }
109
110 /* Opens the system file designated by file handle FH for writing
111    cases from dictionary D.  If COMPRESS is nonzero, the
112    system file will be compressed.  If OMIT_LONG_NAMES is nonzero, the
113    long name table will be omitted.
114
115    No reference to D is retained, so it may be modified or
116    destroyed at will after this function returns.  D is not
117    modified by this function, except to assign short names. */
118 struct sfm_writer *
119 sfm_open_writer (struct file_handle *fh,
120                  struct dictionary *d, int compress, 
121                  short omit_long_names)
122 {
123   struct sfm_writer *w = NULL;
124   int idx;
125   int i;
126
127   if (!fh_open (fh, "system file", "we"))
128     goto error;
129
130   /* Create and initialize writer. */
131   w = xmalloc (sizeof *w);
132   w->fh = fh;
133   w->file = fopen (handle_get_filename (fh), "wb");
134
135   w->needs_translation = does_dict_need_translation (d);
136   w->compress = compress;
137   w->case_cnt = 0;
138   w->flt64_cnt = 0;
139
140   w->buf = w->end = w->ptr = NULL;
141   w->x = w->y = NULL;
142
143   w->var_cnt = dict_get_var_cnt (d);
144   w->vars = xmalloc (sizeof *w->vars * w->var_cnt);
145   for (i = 0; i < w->var_cnt; i++) 
146     {
147       const struct variable *dv = dict_get_var (d, i);
148       struct sfm_var *sv = &w->vars[i];
149       sv->width = dv->width;
150       sv->fv = dv->fv;
151       sv->flt64_cnt = var_flt64_cnt (dv);
152     }
153
154   /* Check that file create succeeded. */
155   if (w->file == NULL)
156     {
157       msg (ME, _("Error opening \"%s\" for writing "
158                  "as a system file: %s."),
159            handle_get_filename (w->fh), strerror (errno));
160       err_cond_fail ();
161       goto error;
162     }
163
164   /* Write the file header. */
165   if (!write_header (w, d))
166     goto error;
167
168   /* Write basic variable info. */
169   dict_assign_short_names (d);
170   for (i = 0; i < dict_get_var_cnt (d); i++)
171     write_variable (w, dict_get_var (d, i));
172
173   /* Write out value labels. */
174   for (idx = i = 0; i < dict_get_var_cnt (d); i++)
175     {
176       struct variable *v = dict_get_var (d, i);
177
178       if (!write_value_labels (w, v, idx))
179         goto error;
180       idx += var_flt64_cnt (v);
181     }
182
183   if (dict_get_documents (d) != NULL && !write_documents (w, d))
184     goto error;
185
186   if (!write_rec_7_34 (w))
187     goto error;
188
189   if (!write_variable_display_parameters (w, d))
190     goto error;
191
192   if (!omit_long_names) 
193     {
194       if (!write_longvar_table (w, d))
195         goto error;
196     }
197
198   /* Write end-of-headers record. */
199   {
200     struct
201       {
202         int32 rec_type P;
203         int32 filler P;
204       }
205     rec_999;
206
207     rec_999.rec_type = 999;
208     rec_999.filler = 0;
209
210     if (!buf_write (w, &rec_999, sizeof rec_999))
211       goto error;
212   }
213
214   if (w->compress) 
215     {
216       w->buf = xmalloc (sizeof *w->buf * 128);
217       w->ptr = w->buf;
218       w->end = &w->buf[128];
219       w->x = (unsigned char *) w->ptr++;
220       w->y = (unsigned char *) w->ptr;
221     }
222   
223   return w;
224
225  error:
226   sfm_close_writer (w);
227   return NULL;
228 }
229
230 static int
231 does_dict_need_translation (const struct dictionary *d)
232 {
233   size_t case_idx;
234   size_t i;
235
236   case_idx = 0;
237   for (i = 0; i < dict_get_var_cnt (d); i++) 
238     {
239       struct variable *v = dict_get_var (d, i);
240       if (v->fv != case_idx)
241         return 0;
242       case_idx += v->nv;
243     }
244   return 1;
245 }
246
247 /* Returns value of X truncated to two least-significant digits. */
248 static int
249 rerange (int x)
250 {
251   if (x < 0)
252     x = -x;
253   if (x >= 100)
254     x %= 100;
255   return x;
256 }
257
258 /* Write the sysfile_header header to system file W. */
259 static int
260 write_header (struct sfm_writer *w, const struct dictionary *d)
261 {
262   struct sysfile_header hdr;
263   char *p;
264   int i;
265
266   time_t t;
267
268   memcpy (hdr.rec_type, "$FL2", 4);
269
270   p = stpcpy (hdr.prod_name, "@(#) SPSS DATA FILE ");
271   p = append_string_max (p, version, &hdr.prod_name[60]);
272   p = append_string_max (p, " - ", &hdr.prod_name[60]);
273   p = append_string_max (p, host_system, &hdr.prod_name[60]);
274   memset (p, ' ', &hdr.prod_name[60] - p);
275
276   hdr.layout_code = 2;
277
278   w->flt64_cnt = 0;
279   for (i = 0; i < dict_get_var_cnt (d); i++)
280     w->flt64_cnt += var_flt64_cnt (dict_get_var (d, i));
281   hdr.case_size = w->flt64_cnt;
282
283   hdr.compress = w->compress;
284
285   if (dict_get_weight (d) != NULL)
286     {
287       struct variable *weight_var;
288       int recalc_weight_idx = 1;
289       int i;
290
291       weight_var = dict_get_weight (d);
292       for (i = 0; ; i++) 
293         {
294           struct variable *v = dict_get_var (d, i);
295           if (v == weight_var)
296             break;
297           recalc_weight_idx += var_flt64_cnt (v);
298         }
299       hdr.weight_idx = recalc_weight_idx;
300     }
301   else
302     hdr.weight_idx = 0;
303
304   hdr.case_cnt = -1;
305   hdr.bias = COMPRESSION_BIAS;
306
307   if (time (&t) == (time_t) -1)
308     {
309       memcpy (hdr.creation_date, "01 Jan 70", 9);
310       memcpy (hdr.creation_time, "00:00:00", 8);
311     }
312   else
313     {
314       static const char *month_name[12] =
315         {
316           "Jan", "Feb", "Mar", "Apr", "May", "Jun",
317           "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
318         };
319       struct tm *tmp = localtime (&t);
320       int day = rerange (tmp->tm_mday);
321       int mon = rerange (tmp->tm_mon + 1);
322       int year = rerange (tmp->tm_year);
323       int hour = rerange (tmp->tm_hour + 1);
324       int min = rerange (tmp->tm_min + 1);
325       int sec = rerange (tmp->tm_sec + 1);
326       char buf[10];
327
328       sprintf (buf, "%02d %s %02d", day, month_name[mon - 1], year);
329       memcpy (hdr.creation_date, buf, sizeof hdr.creation_date);
330       sprintf (buf, "%02d:%02d:%02d", hour - 1, min - 1, sec - 1);
331       memcpy (hdr.creation_time, buf, sizeof hdr.creation_time);
332     }
333   
334   {
335     const char *label = dict_get_label (d);
336     if (label == NULL)
337       label = "";
338
339     buf_copy_str_rpad (hdr.file_label, sizeof hdr.file_label, label); 
340   }
341   
342   memset (hdr.padding, 0, sizeof hdr.padding);
343
344   if (!buf_write (w, &hdr, sizeof hdr))
345     return 0;
346   return 1;
347 }
348
349 /* Translates format spec from internal form in SRC to system file
350    format in DEST. */
351 static inline void
352 write_format_spec (struct fmt_spec *src, int32 *dest)
353 {
354   *dest = (formats[src->type].spss << 16) | (src->w << 8) | src->d;
355 }
356
357 /* Write the variable record(s) for primary variable P and secondary
358    variable S to system file W. */
359 static int
360 write_variable (struct sfm_writer *w, struct variable *v)
361 {
362   struct sysfile_variable sv;
363
364   /* Missing values. */
365   struct missing_values mv;
366   flt64 m[3];           /* Missing value values. */
367   int nm;               /* Number of missing values, possibly negative. */
368
369   sv.rec_type = 2;
370   sv.type = v->width;
371   sv.has_var_label = (v->label != NULL);
372
373   mv_copy (&mv, &v->miss);
374   nm = 0;
375   if (mv_has_range (&mv)) 
376     {
377       double x, y;
378       mv_pop_range (&mv, &x, &y);
379       m[nm++] = x == LOWEST ? second_lowest_flt64 : x;
380       m[nm++] = y == HIGHEST ? FLT64_MAX : y;
381     }
382   while (mv_has_value (&mv))
383     {
384       union value value;
385       mv_pop_value (&mv, &value);
386       if (v->type == NUMERIC)
387         m[nm] = value.f;
388       else
389         buf_copy_rpad ((char *) &m[nm], sizeof m[nm], value.s, v->width);
390       nm++;
391     }
392   if (mv_has_range (&v->miss))
393     nm = -nm;
394
395   sv.n_missing_values = nm;
396   write_format_spec (&v->print, &sv.print);
397   write_format_spec (&v->write, &sv.write);
398   buf_copy_str_rpad (sv.name, sizeof sv.name, v->short_name);
399   if (!buf_write (w, &sv, sizeof sv))
400     return 0;
401
402   if (v->label)
403     {
404       struct label
405         {
406           int32 label_len P;
407           char label[255] P;
408         }
409       l;
410
411       int ext_len;
412
413       l.label_len = min (strlen (v->label), 255);
414       ext_len = ROUND_UP (l.label_len, sizeof l.label_len);
415       memcpy (l.label, v->label, l.label_len);
416       memset (&l.label[l.label_len], ' ', ext_len - l.label_len);
417
418       if (!buf_write (w, &l, offsetof (struct label, label) + ext_len))
419         return 0;
420     }
421
422   if (nm && !buf_write (w, m, sizeof *m * abs (nm)))
423     return 0;
424
425   if (v->type == ALPHA && v->width > (int) sizeof (flt64))
426     {
427       int i;
428       int pad_count;
429
430       sv.type = -1;
431       sv.has_var_label = 0;
432       sv.n_missing_values = 0;
433       memset (&sv.print, 0, sizeof sv.print);
434       memset (&sv.write, 0, sizeof sv.write);
435       memset (&sv.name, 0, sizeof sv.name);
436
437       pad_count = DIV_RND_UP (v->width, (int) sizeof (flt64)) - 1;
438       for (i = 0; i < pad_count; i++)
439         if (!buf_write (w, &sv, sizeof sv))
440           return 0;
441     }
442
443   return 1;
444 }
445
446 /* Writes the value labels for variable V having system file variable
447    index IDX to system file W.  Returns
448    nonzero only if successful. */
449 static int
450 write_value_labels (struct sfm_writer *w, struct variable *v, int idx)
451 {
452   struct value_label_rec
453     {
454       int32 rec_type P;
455       int32 n_labels P;
456       flt64 labels[1] P;
457     };
458
459   struct var_idx_rec
460     {
461       int32 rec_type P;
462       int32 n_vars P;
463       int32 vars[1] P;
464     };
465
466   struct val_labs_iterator *i;
467   struct value_label_rec *vlr;
468   struct var_idx_rec vir;
469   struct val_lab *vl;
470   size_t vlr_size;
471   flt64 *loc;
472
473   if (!val_labs_count (v->val_labs))
474     return 1;
475
476   /* Pass 1: Count bytes. */
477   vlr_size = (sizeof (struct value_label_rec)
478               + sizeof (flt64) * (val_labs_count (v->val_labs) - 1));
479   for (vl = val_labs_first (v->val_labs, &i); vl != NULL;
480        vl = val_labs_next (v->val_labs, &i))
481     vlr_size += ROUND_UP (strlen (vl->label) + 1, sizeof (flt64));
482
483   /* Pass 2: Copy bytes. */
484   vlr = xmalloc (vlr_size);
485   vlr->rec_type = 3;
486   vlr->n_labels = val_labs_count (v->val_labs);
487   loc = vlr->labels;
488   for (vl = val_labs_first_sorted (v->val_labs, &i); vl != NULL;
489        vl = val_labs_next (v->val_labs, &i))
490     {
491       size_t len = strlen (vl->label);
492
493       *loc++ = vl->value.f;
494       *(unsigned char *) loc = len;
495       memcpy (&((unsigned char *) loc)[1], vl->label, len);
496       memset (&((unsigned char *) loc)[1 + len], ' ',
497               REM_RND_UP (len + 1, sizeof (flt64)));
498       loc += DIV_RND_UP (len + 1, sizeof (flt64));
499     }
500   
501   if (!buf_write (w, vlr, vlr_size))
502     {
503       free (vlr);
504       return 0;
505     }
506   free (vlr);
507
508   vir.rec_type = 4;
509   vir.n_vars = 1;
510   vir.vars[0] = idx + 1;
511   if (!buf_write (w, &vir, sizeof vir))
512     return 0;
513
514   return 1;
515 }
516
517 /* Writes record type 6, document record. */
518 static int
519 write_documents (struct sfm_writer *w, const struct dictionary *d)
520 {
521   struct
522     {
523       int32 rec_type P;         /* Always 6. */
524       int32 n_lines P;          /* Number of lines of documents. */
525     }
526   rec_6;
527
528   const char *documents;
529   size_t n_lines;
530
531   documents = dict_get_documents (d);
532   n_lines = strlen (documents) / 80;
533
534   rec_6.rec_type = 6;
535   rec_6.n_lines = n_lines;
536   if (!buf_write (w, &rec_6, sizeof rec_6))
537     return 0;
538   if (!buf_write (w, documents, 80 * n_lines))
539     return 0;
540
541   return 1;
542 }
543
544 /* Write the alignment, width and scale values */
545 static int
546 write_variable_display_parameters (struct sfm_writer *w, 
547                                    const struct dictionary *dict)
548 {
549   int i;
550
551   struct
552   {
553     int32 rec_type P;
554     int32 subtype P;
555     int32 elem_size P;
556     int32 n_elem P;
557   } vdp_hdr;
558
559   vdp_hdr.rec_type = 7;
560   vdp_hdr.subtype = 11;
561   vdp_hdr.elem_size = 4;
562   vdp_hdr.n_elem = w->var_cnt * 3;
563
564   if (!buf_write (w, &vdp_hdr, sizeof vdp_hdr))
565     return 0;
566
567   for ( i = 0 ; i < w->var_cnt ; ++i ) 
568     {
569       struct variable *v;
570       struct
571       {
572         int32 measure P;
573         int32 width P;
574         int32 align P;
575       }
576       params;
577
578       v = dict_get_var(dict, i);
579
580       params.measure = v->measure;
581       params.width = v->display_width;
582       params.align = v->alignment;
583       
584       if (!buf_write (w, &params, sizeof(params)))
585         return 0;
586     }
587   
588   return 1;
589 }
590
591 /* Writes the long variable name table */
592 static int
593 write_longvar_table (struct sfm_writer *w, const struct dictionary *dict)
594 {
595   struct
596     {
597       int32 rec_type P;
598       int32 subtype P;
599       int32 elem_size P;
600       int32 n_elem P;
601     }
602   lv_hdr;
603
604   struct string long_name_map;
605   size_t i;
606
607   ds_init (&long_name_map, 10 * dict_get_var_cnt (dict));
608   for (i = 0; i < dict_get_var_cnt (dict); i++)
609     {
610       struct variable *v = dict_get_var (dict, i);
611       
612       if (i)
613         ds_putc (&long_name_map, '\t');
614       ds_printf (&long_name_map, "%s=%s", v->short_name, v->name);
615     }
616
617   lv_hdr.rec_type = 7;
618   lv_hdr.subtype = 13;
619   lv_hdr.elem_size = 1;
620   lv_hdr.n_elem = ds_length (&long_name_map);
621
622   if (!buf_write (w, &lv_hdr, sizeof lv_hdr)
623       || !buf_write (w, ds_data (&long_name_map), ds_length (&long_name_map)))
624     goto error;
625
626   ds_destroy (&long_name_map);
627   return 1;
628
629  error:
630   ds_destroy (&long_name_map);
631   return 0;
632 }
633
634 /* Writes record type 7, subtypes 3 and 4. */
635 static int
636 write_rec_7_34 (struct sfm_writer *w)
637 {
638   struct
639     {
640       int32 rec_type_3 P;
641       int32 subtype_3 P;
642       int32 data_type_3 P;
643       int32 n_elem_3 P;
644       int32 elem_3[8] P;
645       int32 rec_type_4 P;
646       int32 subtype_4 P;
647       int32 data_type_4 P;
648       int32 n_elem_4 P;
649       flt64 elem_4[3] P;
650     }
651   rec_7;
652
653   /* Components of the version number, from major to minor. */
654   int version_component[3];
655   
656   /* Used to step through the version string. */
657   char *p;
658
659   /* Parses the version string, which is assumed to be of the form
660      #.#x, where each # is a string of digits, and x is a single
661      letter. */
662   version_component[0] = strtol (bare_version, &p, 10);
663   if (*p == '.')
664     p++;
665   version_component[1] = strtol (bare_version, &p, 10);
666   version_component[2] = (isalpha ((unsigned char) *p)
667                           ? tolower ((unsigned char) *p) - 'a' : 0);
668     
669   rec_7.rec_type_3 = 7;
670   rec_7.subtype_3 = 3;
671   rec_7.data_type_3 = sizeof (int32);
672   rec_7.n_elem_3 = 8;
673   rec_7.elem_3[0] = version_component[0];
674   rec_7.elem_3[1] = version_component[1];
675   rec_7.elem_3[2] = version_component[2];
676   rec_7.elem_3[3] = -1;
677
678   /* PORTME: 1=IEEE754, 2=IBM 370, 3=DEC VAX E. */
679 #ifdef FPREP_IEEE754
680   rec_7.elem_3[4] = 1;
681 #endif
682
683   rec_7.elem_3[5] = 1;
684
685   /* PORTME: 1=big-endian, 2=little-endian. */
686 #if WORDS_BIGENDIAN
687   rec_7.elem_3[6] = 1;
688 #else
689   rec_7.elem_3[6] = 2;
690 #endif
691
692   /* PORTME: 1=EBCDIC, 2=7-bit ASCII, 3=8-bit ASCII, 4=DEC Kanji. */
693   rec_7.elem_3[7] = 2;
694
695   rec_7.rec_type_4 = 7;
696   rec_7.subtype_4 = 4;
697   rec_7.data_type_4 = sizeof (flt64);
698   rec_7.n_elem_4 = 3;
699   rec_7.elem_4[0] = -FLT64_MAX;
700   rec_7.elem_4[1] = FLT64_MAX;
701   rec_7.elem_4[2] = second_lowest_flt64;
702
703   if (!buf_write (w, &rec_7, sizeof rec_7))
704     return 0;
705   return 1;
706 }
707
708 /* Write NBYTES starting at BUF to the system file represented by
709    H. */
710 static int
711 buf_write (struct sfm_writer *w, const void *buf, size_t nbytes)
712 {
713   assert (buf != NULL);
714   if (fwrite (buf, nbytes, 1, w->file) != 1)
715     {
716       msg (ME, _("%s: Writing system file: %s."),
717            handle_get_filename (w->fh), strerror (errno));
718       return 0;
719     }
720   return 1;
721 }
722
723 /* Copies string DEST to SRC with the proviso that DEST does not reach
724    byte END; no null terminator is copied.  Returns a pointer to the
725    byte after the last byte copied. */
726 static char *
727 append_string_max (char *dest, const char *src, const char *end)
728 {
729   int nbytes = min (end - dest, (int) strlen (src));
730   memcpy (dest, src, nbytes);
731   return dest + nbytes;
732 }
733
734 /* Makes certain that the compression buffer of H has room for another
735    element.  If there's not room, pads out the current instruction
736    octet with zero and dumps out the buffer. */
737 static inline int
738 ensure_buf_space (struct sfm_writer *w)
739 {
740   if (w->ptr >= w->end)
741     {
742       memset (w->x, 0, w->y - w->x);
743       w->x = w->y;
744       w->ptr = w->buf;
745       if (!buf_write (w, w->buf, sizeof *w->buf * 128))
746         return 0;
747     }
748   return 1;
749 }
750
751 static void write_compressed_data (struct sfm_writer *w, const flt64 *elem);
752
753 /* Writes case C to system file W.
754    Returns nonzero if successful. */
755 int
756 sfm_write_case (struct sfm_writer *w, struct ccase *c)
757 {
758   w->case_cnt++;
759
760   if (!w->needs_translation && !w->compress
761       && sizeof (flt64) == sizeof (union value)) 
762     {
763       /* Fast path: external and internal representations are the
764          same and the dictionary is properly ordered.  Write
765          directly to file. */
766       buf_write (w, case_data_all (c), sizeof (union value) * w->flt64_cnt);
767     }
768   else 
769     {
770       /* Slow path: internal and external representations differ.
771          Write into a bounce buffer, then write to W. */
772       flt64 *bounce;
773       flt64 *bounce_cur;
774       size_t bounce_size;
775       size_t i;
776
777       bounce_size = sizeof *bounce * w->flt64_cnt;
778       bounce = bounce_cur = local_alloc (bounce_size);
779
780       for (i = 0; i < w->var_cnt; i++) 
781         {
782           struct sfm_var *v = &w->vars[i];
783
784           if (v->width == 0) 
785             *bounce_cur = case_num (c, v->fv);
786           else 
787             memcpy (bounce_cur, case_data (c, v->fv)->s, v->width);
788           bounce_cur += v->flt64_cnt;
789         }
790
791       if (!w->compress)
792         buf_write (w, bounce, bounce_size);
793       else
794         write_compressed_data (w, bounce);
795
796       local_free (bounce); 
797     }
798   
799   return 1;
800 }
801
802 static void
803 put_instruction (struct sfm_writer *w, unsigned char instruction) 
804 {
805   if (w->x >= w->y)
806     {
807       if (!ensure_buf_space (w))
808         return;
809       w->x = (unsigned char *) w->ptr++;
810       w->y = (unsigned char *) w->ptr;
811     }
812   *w->x++ = instruction;
813 }
814
815 static void
816 put_element (struct sfm_writer *w, const flt64 *elem) 
817 {
818   if (!ensure_buf_space (w))
819     return;
820   memcpy (w->ptr++, elem, sizeof *elem);
821 }
822
823 static void
824 write_compressed_data (struct sfm_writer *w, const flt64 *elem) 
825 {
826   size_t i;
827
828   for (i = 0; i < w->var_cnt; i++)
829     {
830       struct sfm_var *v = &w->vars[i];
831
832       if (v->width == 0) 
833         {
834           if (*elem == -FLT64_MAX)
835             put_instruction (w, 255);
836           else if (*elem >= 1 - COMPRESSION_BIAS
837                    && *elem <= 251 - COMPRESSION_BIAS
838                    && *elem == (int) *elem) 
839             put_instruction (w, (int) *elem + COMPRESSION_BIAS);
840           else
841             {
842               put_instruction (w, 253);
843               put_element (w, elem);
844             }
845           elem++;
846         }
847       else 
848         {
849           size_t j;
850           
851           for (j = 0; j < v->flt64_cnt; j++, elem++) 
852             {
853               if (!memcmp (elem, "        ", sizeof (flt64)))
854                 put_instruction (w, 254);
855               else 
856                 {
857                   put_instruction (w, 253);
858                   put_element (w, elem);
859                 }
860             }
861         }
862     }
863 }
864
865 /* Closes a system file after we're done with it. */
866 void
867 sfm_close_writer (struct sfm_writer *w)
868 {
869   if (w == NULL)
870     return;
871
872   fh_close (w->fh, "system file", "we");
873   
874   if (w->file != NULL) 
875     {
876       /* Flush buffer. */
877       if (w->buf != NULL && w->ptr > w->buf)
878         {
879           memset (w->x, 0, w->y - w->x);
880           buf_write (w, w->buf, (w->ptr - w->buf) * sizeof *w->buf);
881         }
882
883       /* Seek back to the beginning and update the number of cases.
884          This is just a courtesy to later readers, so there's no need
885          to check return values or report errors. */
886       if (!fseek (w->file, offsetof (struct sysfile_header, case_cnt), SEEK_SET))
887         {
888           int32 case_cnt = w->case_cnt;
889
890           /* I don't really care about the return value: it doesn't
891              matter whether this data is written. */
892           fwrite (&case_cnt, sizeof case_cnt, 1, w->file);
893         }
894
895       if (fclose (w->file) == EOF)
896         msg (ME, _("%s: Closing system file: %s."),
897              handle_get_filename (w->fh), strerror (errno));
898     }
899
900   free (w->buf);
901   free (w->vars);
902   free (w);
903 }