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