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