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