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