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