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