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