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