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