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