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