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