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