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