Add support for variable sets in the system file format.
[pspp] / src / data / sys-file-writer.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-2000, 2006-2014 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU 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, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "data/sys-file-writer.h"
20 #include "data/sys-file-private.h"
21
22 #include <ctype.h>
23 #include <errno.h>
24 #include <stdint.h>
25 #include <stdlib.h>
26 #include <sys/stat.h>
27 #include <time.h>
28 #include <zlib.h>
29
30 #include "data/attributes.h"
31 #include "data/case.h"
32 #include "data/casewriter-provider.h"
33 #include "data/casewriter.h"
34 #include "data/dictionary.h"
35 #include "data/file-handle-def.h"
36 #include "data/format.h"
37 #include "data/make-file.h"
38 #include "data/missing-values.h"
39 #include "data/mrset.h"
40 #include "data/settings.h"
41 #include "data/short-names.h"
42 #include "data/value-labels.h"
43 #include "data/variable.h"
44 #include "data/varset.h"
45 #include "libpspp/float-format.h"
46 #include "libpspp/i18n.h"
47 #include "libpspp/integer-format.h"
48 #include "libpspp/message.h"
49 #include "libpspp/misc.h"
50 #include "libpspp/str.h"
51 #include "libpspp/string-array.h"
52 #include "libpspp/version.h"
53
54 #include "gl/xmemdup0.h"
55 #include "gl/minmax.h"
56 #include "gl/unlocked-io.h"
57 #include "gl/xalloc.h"
58
59 #include "gettext.h"
60 #define _(msgid) gettext (msgid)
61 #define N_(msgid) (msgid)
62
63 /* Compression bias used by PSPP.  Values between (1 -
64    COMPRESSION_BIAS) and (251 - COMPRESSION_BIAS) inclusive can be
65    compressed. */
66 #define COMPRESSION_BIAS 100
67
68 /* System file writer. */
69 struct sfm_writer
70   {
71     struct file_handle *fh;     /* File handle. */
72     struct fh_lock *lock;       /* Mutual exclusion for file. */
73     FILE *file;                 /* File stream. */
74     struct replace_file *rf;    /* Ticket for replacing output file. */
75
76     enum any_compression compression;
77     casenumber n_cases;         /* Number of cases written so far. */
78     uint8_t space;              /* ' ' in the file's character encoding. */
79
80     /* Simple compression buffering.
81
82        Compressed data is output as a series of 8-byte elements, with 1 to 9
83        such elements clustered together.  The first element in a cluster is 8
84        1-byte opcodes.  Some opcodes call for an additional element in the
85        cluster (hence, if there are eight such opcodes, then the cluster
86        contains a full 9 elements).
87
88        cbuf[] holds a cluster at a time. */
89     uint8_t cbuf[9][8];
90     int n_opcodes;              /* Number of opcodes in cbuf[0] so far. */
91     int n_elements;             /* Number of elements in cbuf[] so far. */
92
93     /* ZLIB compression. */
94     z_stream zstream;           /* ZLIB deflater. */
95     off_t zstart;
96     struct zblock *blocks;
97     size_t n_blocks, allocated_blocks;
98
99     /* Variables. */
100     struct sfm_var *sfm_vars;   /* Variables. */
101     size_t sfm_n_vars;          /* Number of variables. */
102     size_t n_segments;          /* Number of variables including extra segments
103                                    for long string variables. */
104   };
105
106 struct zblock
107   {
108     unsigned int uncompressed_size;
109     unsigned int compressed_size;
110   };
111
112 static const struct casewriter_class sys_file_casewriter_class;
113
114 static void write_header (struct sfm_writer *, const struct dictionary *);
115 static void write_variable (struct sfm_writer *, const struct variable *);
116 static void write_value_labels (struct sfm_writer *,
117                                 const struct dictionary *);
118 static void write_integer_info_record (struct sfm_writer *,
119                                        const struct dictionary *);
120 static void write_float_info_record (struct sfm_writer *);
121
122 static void write_longvar_table (struct sfm_writer *w,
123                                  const struct dictionary *dict);
124
125 static void write_encoding_record (struct sfm_writer *w,
126                                    const struct dictionary *);
127
128 static void write_vls_length_table (struct sfm_writer *w,
129                               const struct dictionary *dict);
130
131 static void write_long_string_value_labels (struct sfm_writer *,
132                                             const struct dictionary *);
133 static void write_long_string_missing_values (struct sfm_writer *,
134                                               const struct dictionary *);
135
136 static void write_varsets (struct sfm_writer *, const struct dictionary *);
137 static void write_mrsets (struct sfm_writer *, const struct dictionary *,
138                           bool pre_v14);
139
140 static void write_variable_display_parameters (struct sfm_writer *w,
141                                                const struct dictionary *dict);
142
143 static void write_documents (struct sfm_writer *, const struct dictionary *);
144
145 static void write_data_file_attributes (struct sfm_writer *,
146                                         const struct dictionary *);
147 static void write_variable_attributes (struct sfm_writer *,
148                                        const struct dictionary *);
149
150 static void write_int (struct sfm_writer *, int32_t);
151 static void write_int64 (struct sfm_writer *, int64_t);
152 static inline void convert_double_to_output_format (double, uint8_t[8]);
153 static void write_float (struct sfm_writer *, double);
154 static void write_string (struct sfm_writer *, const char *, size_t);
155 static void write_utf8_string (struct sfm_writer *, const char *encoding,
156                                const char *string, size_t width);
157 static void write_utf8_record (struct sfm_writer *, const char *encoding,
158                                const struct string *content, int subtype);
159 static void write_string_record (struct sfm_writer *,
160                                  const struct substring content, int subtype);
161 static void write_bytes (struct sfm_writer *, const void *, size_t);
162 static void write_zeros (struct sfm_writer *, size_t);
163 static void write_spaces (struct sfm_writer *, size_t);
164 static void write_value (struct sfm_writer *, const union value *, int width);
165
166 static void write_case_uncompressed (struct sfm_writer *,
167                                      const struct ccase *);
168 static void write_case_compressed (struct sfm_writer *, const struct ccase *);
169 static void flush_compressed (struct sfm_writer *);
170 static void put_cmp_opcode (struct sfm_writer *, uint8_t);
171 static void put_cmp_number (struct sfm_writer *, double);
172 static void put_cmp_string (struct sfm_writer *, const void *, size_t);
173
174 static bool start_zstream (struct sfm_writer *);
175 static void finish_zstream (struct sfm_writer *);
176 static void write_ztrailer (struct sfm_writer *);
177
178 static bool write_error (const struct sfm_writer *);
179 static bool close_writer (struct sfm_writer *);
180
181 /* Returns default options for writing a system file. */
182 struct sfm_write_options
183 sfm_writer_default_options (void)
184 {
185   struct sfm_write_options opts;
186   opts.compression = (settings_get_scompression ()
187                       ? ANY_COMP_SIMPLE
188                       : ANY_COMP_NONE);
189   opts.create_writeable = true;
190   opts.version = 3;
191   return opts;
192 }
193
194 /* Opens the system file designated by file handle FH for writing
195    cases from dictionary D according to the given OPTS.
196
197    No reference to D is retained, so it may be modified or
198    destroyed at will after this function returns.  D is not
199    modified by this function, except to assign short names. */
200 struct casewriter *
201 sfm_open_writer (struct file_handle *fh, struct dictionary *d,
202                  struct sfm_write_options opts)
203 {
204   struct encoding_info encoding_info;
205   mode_t mode;
206   int i;
207
208   /* Check version. */
209   if (opts.version != 2 && opts.version != 3)
210     {
211       msg (ME, _("Unknown system file version %d. Treating as version %d."),
212            opts.version, 3);
213       opts.version = 3;
214     }
215
216   /* Create and initialize writer. */
217   struct sfm_writer *w = XZALLOC (struct sfm_writer);
218   w->fh = fh_ref (fh);
219   w->lock = NULL;
220   w->file = NULL;
221   w->rf = NULL;
222
223   /* Use the requested compression, except that no EBCDIC-based ZLIB compressed
224      files have been observed, so drop back to simple compression for those
225      files. */
226   w->compression = opts.compression;
227   if (w->compression == ANY_COMP_ZLIB
228       && is_encoding_ebcdic_compatible (dict_get_encoding (d)))
229     w->compression = ANY_COMP_SIMPLE;
230
231   w->n_cases = 0;
232
233   w->n_opcodes = w->n_elements = 0;
234   memset (w->cbuf[0], 0, 8);
235
236   /* Figure out how to map in-memory case data to on-disk case
237      data.  Also count the number of segments.  Very long strings
238      occupy multiple segments, otherwise each variable only takes
239      one segment. */
240   w->n_segments = sfm_dictionary_to_sfm_vars (d, &w->sfm_vars, &w->sfm_n_vars);
241
242   /* Open file handle as an exclusive writer. */
243   /* TRANSLATORS: this fragment will be interpolated into
244      messages in fh_lock() that identify types of files. */
245   w->lock = fh_lock (fh, FH_REF_FILE, N_("system file"), FH_ACC_WRITE, true);
246   if (w->lock == NULL)
247     goto error;
248
249   /* Create the file on disk. */
250   mode = 0444;
251   if (opts.create_writeable)
252     mode |= 0222;
253   w->rf = replace_file_start (fh, "wb", mode, &w->file);
254   if (w->rf == NULL)
255     {
256       msg (ME, _("Error opening `%s' for writing as a system file: %s."),
257            fh_get_file_name (fh), strerror (errno));
258       goto error;
259     }
260
261   get_encoding_info (&encoding_info, dict_get_encoding (d));
262   w->space = encoding_info.space[0];
263
264   /* Write the file header. */
265   write_header (w, d);
266
267   /* Write basic variable info. */
268   short_names_assign (d);
269   for (i = 0; i < dict_get_n_vars (d); i++)
270     write_variable (w, dict_get_var (d, i));
271
272   write_value_labels (w, d);
273
274   if (dict_get_document_n_lines (d) > 0)
275     write_documents (w, d);
276
277   write_integer_info_record (w, d);
278   write_float_info_record (w);
279
280   write_varsets (w, d);
281   write_mrsets (w, d, true);
282
283   write_variable_display_parameters (w, d);
284
285   if (opts.version >= 3)
286     write_longvar_table (w, d);
287
288   write_vls_length_table (w, d);
289
290   write_long_string_value_labels (w, d);
291   write_long_string_missing_values (w, d);
292
293   if (opts.version >= 3)
294     {
295       if (attrset_count (dict_get_attributes (d)))
296         write_data_file_attributes (w, d);
297       write_variable_attributes (w, d);
298     }
299
300   write_mrsets (w, d, false);
301
302   write_encoding_record (w, d);
303
304   /* Write end-of-headers record. */
305   write_int (w, 999);
306   write_int (w, 0);
307
308   if (w->compression == ANY_COMP_ZLIB)
309     {
310       w->zstream.zalloc = Z_NULL;
311       w->zstream.zfree = Z_NULL;
312       w->zstream.opaque = Z_NULL;
313       w->zstart = ftello (w->file);
314
315       write_int64 (w, w->zstart);
316       write_int64 (w, 0);
317       write_int64 (w, 0);
318
319       start_zstream (w);
320     }
321
322   if (write_error (w))
323     goto error;
324
325   return casewriter_create (dict_get_proto (d), &sys_file_casewriter_class, w);
326
327 error:
328   close_writer (w);
329   return NULL;
330 }
331
332 /* Returns value of X truncated to two least-significant digits. */
333 static int
334 rerange (int x)
335 {
336   if (x < 0)
337     x = -x;
338   if (x >= 100)
339     x %= 100;
340   return x;
341 }
342
343 /* Calculates the offset of data for TARGET_VAR from the
344    beginning of each case's data for dictionary D.  The return
345    value is in "octs" (8-byte units). */
346 static int
347 calc_oct_idx (const struct dictionary *d, struct variable *target_var)
348 {
349   int oct_idx;
350   int i;
351
352   oct_idx = 0;
353   for (i = 0; i < dict_get_n_vars (d); i++)
354     {
355       struct variable *var = dict_get_var (d, i);
356       if (var == target_var)
357         break;
358       oct_idx += sfm_width_to_octs (var_get_width (var));
359     }
360   return oct_idx;
361 }
362
363 /* Write the sysfile_header header to system file W. */
364 static void
365 write_header (struct sfm_writer *w, const struct dictionary *d)
366 {
367   const char *dict_encoding = dict_get_encoding (d);
368   char prod_name[61];
369   const char *file_label;
370   struct variable *weight;
371
372   time_t t;
373
374   /* Record-type code. */
375   if (is_encoding_ebcdic_compatible (dict_encoding))
376     write_string (w, EBCDIC_MAGIC, 4);
377   else if (w->compression == ANY_COMP_ZLIB)
378     write_string (w, ASCII_ZMAGIC, 4);
379   else
380     write_string (w, ASCII_MAGIC, 4);
381
382   /* Product identification. */
383   snprintf (prod_name, sizeof prod_name, "@(#) SPSS DATA FILE %s - %s",
384             version, host_system);
385   write_utf8_string (w, dict_encoding, prod_name, 60);
386
387   /* Layout code. */
388   write_int (w, 2);
389
390   /* Number of `union value's per case. */
391   write_int (w, calc_oct_idx (d, NULL));
392
393   /* Compressed? */
394   write_int (w, (w->compression == ANY_COMP_NONE ? 0
395                  : w->compression == ANY_COMP_SIMPLE ? 1
396                  : 2));
397
398   /* Weight variable. */
399   weight = dict_get_weight (d);
400   write_int (w, weight != NULL ? calc_oct_idx (d, weight) + 1 : 0);
401
402   /* Number of cases.  We don't know this in advance, so we write
403      -1 to indicate an unknown number of cases.  Later we can
404      come back and overwrite it with the true value. */
405   write_int (w, -1);
406
407   /* Compression bias. */
408   write_float (w, COMPRESSION_BIAS);
409
410   /* Creation date and time. */
411   char *creation_date, *creation_time;
412   if (time (&t) == (time_t) -1)
413     {
414       creation_date = xstrdup ("01 Jan 70");
415       creation_time = xstrdup ("00:00:00");
416     }
417   else
418     {
419       static const char *const month_name[12] =
420         {
421           "Jan", "Feb", "Mar", "Apr", "May", "Jun",
422           "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
423         };
424       struct tm *tmp = localtime (&t);
425       int day = rerange (tmp->tm_mday);
426       int mon = rerange (tmp->tm_mon + 1);
427       int year = rerange (tmp->tm_year);
428       int hour = rerange (tmp->tm_hour + 1);
429       int min = rerange (tmp->tm_min + 1);
430       int sec = rerange (tmp->tm_sec + 1);
431
432       creation_date = xasprintf ("%02d %s %02d",
433                                  day, month_name[mon - 1], year);
434       creation_time = xasprintf ("%02d:%02d:%02d", hour - 1, min - 1, sec - 1);
435     }
436   write_utf8_string (w, dict_encoding, creation_date, 9);
437   write_utf8_string (w, dict_encoding, creation_time, 8);
438   free (creation_time);
439   free (creation_date);
440
441   /* File label. */
442   file_label = dict_get_label (d);
443   if (file_label == NULL)
444     file_label = "";
445   write_utf8_string (w, dict_encoding, file_label, 64);
446
447   /* Padding. */
448   write_zeros (w, 3);
449 }
450
451 /* Write format spec FMT to W, after adjusting it to be
452    compatible with the given WIDTH. */
453 static void
454 write_format (struct sfm_writer *w, struct fmt_spec fmt, int width)
455 {
456   assert (fmt_check_output (fmt));
457   assert (sfm_width_to_segments (width) == 1);
458
459   if (width > 0)
460     fmt_resize (&fmt, width);
461   write_int (w, (fmt_to_io (fmt.type) << 16) | (fmt.w << 8) | fmt.d);
462 }
463
464 /* Write a string continuation variable record for each 8-byte
465    section beyond the initial 8 bytes, for a variable of the
466    given WIDTH. */
467 static void
468 write_variable_continuation_records (struct sfm_writer *w, int width)
469 {
470   int position;
471
472   assert (sfm_width_to_segments (width) == 1);
473   for (position = 8; position < width; position += 8)
474     {
475       write_int (w, 2);   /* Record type. */
476       write_int (w, -1);  /* Width. */
477       write_int (w, 0);   /* No variable label. */
478       write_int (w, 0);   /* No missing values. */
479       write_int (w, 0);   /* Print format. */
480       write_int (w, 0);   /* Write format. */
481       write_zeros (w, 8);   /* Name. */
482     }
483 }
484
485 /* Write the variable record(s) for variable V to system file
486    W. */
487 static void
488 write_variable (struct sfm_writer *w, const struct variable *v)
489 {
490   int width = var_get_width (v);
491   int n_segments = sfm_width_to_segments (width);
492   int seg0_width = sfm_segment_alloc_width (width, 0);
493   const char *encoding = var_get_encoding (v);
494   int i;
495
496   /* Record type. */
497   write_int (w, 2);
498
499   /* Width. */
500   write_int (w, seg0_width);
501
502   /* Variable has a variable label? */
503   write_int (w, var_has_label (v));
504
505   /* Number of missing values.  If there is a range, then the
506      range counts as 2 missing values and causes the number to be
507      negated.
508
509      Missing values for long string variables are written in a separate
510      record. */
511   enum { MAX_SHORT_STRING = 8 };
512   if (width <= MAX_SHORT_STRING)
513     {
514       const struct missing_values *mv = var_get_missing_values (v);
515       if (mv_has_range (mv))
516         write_int (w, -2 - mv_n_values (mv));
517       else
518         write_int (w, mv_n_values (mv));
519     }
520   else
521     write_int (w, 0);
522
523   /* Print and write formats. */
524   write_format (w, var_get_print_format (v), seg0_width);
525   write_format (w, var_get_write_format (v), seg0_width);
526
527   /* Short name.
528      The full name is in a translation table written
529      separately. */
530   write_utf8_string (w, encoding, var_get_short_name (v, 0), 8);
531
532   /* Value label. */
533   if (var_has_label (v))
534     {
535       char *label = recode_string (encoding, UTF8, var_get_label (v), -1);
536       size_t label_len = MIN (strlen (label), 255);
537       size_t padded_len = ROUND_UP (label_len, 4);
538       write_int (w, label_len);
539       write_string (w, label, padded_len);
540       free (label);
541     }
542
543   /* Write the missing values, if any, range first. */
544   if (width <= MAX_SHORT_STRING)
545     {
546       const struct missing_values *mv = var_get_missing_values (v);
547       if (mv_has_range (mv))
548         {
549           double x, y;
550           mv_get_range (mv, &x, &y);
551           write_float (w, x);
552           write_float (w, y);
553         }
554       for (i = 0; i < mv_n_values (mv); i++)
555         write_value (w, mv_get_value (mv, i), width);
556     }
557
558   write_variable_continuation_records (w, seg0_width);
559
560   /* Write additional segments for very long string variables. */
561   for (i = 1; i < n_segments; i++)
562     {
563       int seg_width = sfm_segment_alloc_width (width, i);
564       struct fmt_spec fmt = fmt_for_output (FMT_A, MAX (seg_width, 1), 0);
565
566       write_int (w, 2);           /* Variable record. */
567       write_int (w, seg_width);   /* Width. */
568       write_int (w, 0);           /* No variable label. */
569       write_int (w, 0);           /* No missing values. */
570       write_format (w, fmt, seg_width); /* Print format. */
571       write_format (w, fmt, seg_width); /* Write format. */
572       write_utf8_string (w, encoding, var_get_short_name (v, i), 8);
573
574       write_variable_continuation_records (w, seg_width);
575     }
576 }
577
578 /* Writes the value labels to system file W.
579
580    Value labels for long string variables are written separately,
581    by write_long_string_value_labels. */
582 static void
583 write_value_labels (struct sfm_writer *w, const struct dictionary *d)
584 {
585   struct label_set
586     {
587       struct hmap_node hmap_node;
588       const struct val_labs *val_labs;
589       int *indexes;
590       size_t n_indexes, allocated_indexes;
591     };
592
593   size_t n_sets, allocated_sets;
594   struct label_set **sets;
595   struct hmap same_sets;
596   size_t i;
597   int idx;
598
599   n_sets = allocated_sets = 0;
600   sets = NULL;
601   hmap_init (&same_sets);
602
603   idx = 0;
604   for (i = 0; i < dict_get_n_vars (d); i++)
605     {
606       struct variable *v = dict_get_var (d, i);
607
608       if (var_has_value_labels (v) && var_get_width (v) <= 8)
609         {
610           const struct val_labs *val_labs = var_get_value_labels (v);
611           unsigned int hash = val_labs_hash (val_labs, 0);
612           struct label_set *set;
613
614           HMAP_FOR_EACH_WITH_HASH (set, struct label_set, hmap_node,
615                                    hash, &same_sets)
616             {
617               if (val_labs_equal (set->val_labs, val_labs))
618                 {
619                   if (set->n_indexes >= set->allocated_indexes)
620                     set->indexes = x2nrealloc (set->indexes,
621                                                &set->allocated_indexes,
622                                                sizeof *set->indexes);
623                   set->indexes[set->n_indexes++] = idx;
624                   goto next_var;
625                 }
626             }
627
628           set = xmalloc (sizeof *set);
629           set->val_labs = val_labs;
630           set->indexes = xmalloc (sizeof *set->indexes);
631           set->indexes[0] = idx;
632           set->n_indexes = 1;
633           set->allocated_indexes = 1;
634           hmap_insert (&same_sets, &set->hmap_node, hash);
635
636           if (n_sets >= allocated_sets)
637             sets = x2nrealloc (sets, &allocated_sets, sizeof *sets);
638           sets[n_sets++] = set;
639         }
640
641     next_var:
642       idx += sfm_width_to_octs (var_get_width (v));
643     }
644
645   for (i = 0; i < n_sets; i++)
646     {
647       const struct label_set *set = sets[i];
648       const struct val_labs *val_labs = set->val_labs;
649       size_t n_labels = val_labs_count (val_labs);
650       int width = val_labs_get_width (val_labs);
651       const struct val_lab **labels;
652       size_t j;
653
654       /* Value label record. */
655       write_int (w, 3);             /* Record type. */
656       write_int (w, n_labels);
657       labels = val_labs_sorted (val_labs);
658       for (j = 0; j < n_labels; j++)
659         {
660           const struct val_lab *vl = labels[j];
661           char *label = recode_string (dict_get_encoding (d), UTF8,
662                                        val_lab_get_escaped_label (vl), -1);
663           uint8_t len = MIN (strlen (label), 255);
664
665           write_value (w, val_lab_get_value (vl), width);
666           write_bytes (w, &len, 1);
667           write_bytes (w, label, len);
668           write_zeros (w, REM_RND_UP (len + 1, 8));
669           free (label);
670         }
671       free (labels);
672
673       /* Value label variable record. */
674       write_int (w, 4);              /* Record type. */
675       write_int (w, set->n_indexes);
676       for (j = 0; j < set->n_indexes; j++)
677         write_int (w, set->indexes[j] + 1);
678     }
679
680   for (i = 0; i < n_sets; i++)
681     {
682       struct label_set *set = sets[i];
683
684       free (set->indexes);
685       free (set);
686     }
687   free (sets);
688   hmap_destroy (&same_sets);
689 }
690
691 /* Writes record type 6, document record. */
692 static void
693 write_documents (struct sfm_writer *w, const struct dictionary *d)
694 {
695   const struct string_array *docs = dict_get_documents (d);
696   const char *enc = dict_get_encoding (d);
697   size_t i;
698
699   write_int (w, 6);             /* Record type. */
700   write_int (w, docs->n);
701   for (i = 0; i < docs->n; i++)
702     {
703       char *s = recode_string (enc, "UTF-8", docs->strings[i], -1);
704       size_t s_len = strlen (s);
705       size_t write_len = MIN (s_len, DOC_LINE_LENGTH);
706
707       write_bytes (w, s, write_len);
708       write_spaces (w, DOC_LINE_LENGTH - write_len);
709       free (s);
710     }
711 }
712
713 static void
714 put_attrset (struct string *string, const struct attrset *attrs)
715 {
716   const struct attribute *attr;
717   struct attrset_iterator i;
718
719   for (attr = attrset_first (attrs, &i); attr != NULL;
720        attr = attrset_next (attrs, &i))
721     {
722       size_t n_values = attribute_get_n_values (attr);
723       size_t j;
724
725       ds_put_cstr (string, attribute_get_name (attr));
726       ds_put_byte (string, '(');
727       for (j = 0; j < n_values; j++)
728         ds_put_format (string, "'%s'\n", attribute_get_value (attr, j));
729       ds_put_byte (string, ')');
730     }
731 }
732
733 static void
734 write_data_file_attributes (struct sfm_writer *w,
735                             const struct dictionary *d)
736 {
737   struct string s = DS_EMPTY_INITIALIZER;
738   put_attrset (&s, dict_get_attributes (d));
739   write_utf8_record (w, dict_get_encoding (d), &s, 17);
740   ds_destroy (&s);
741 }
742
743 static void
744 add_role_attribute (enum var_role role, struct attrset *attrs)
745 {
746   struct attribute *attr;
747   const char *s;
748
749   switch (role)
750     {
751     case ROLE_INPUT:
752     default:
753       s = "0";
754       break;
755
756     case ROLE_TARGET:
757       s = "1";
758       break;
759
760     case ROLE_BOTH:
761       s = "2";
762       break;
763
764     case ROLE_NONE:
765       s = "3";
766       break;
767
768     case ROLE_PARTITION:
769       s = "4";
770       break;
771
772     case ROLE_SPLIT:
773       s = "5";
774       break;
775     }
776   attrset_delete (attrs, "$@Role");
777
778   attr = attribute_create ("$@Role");
779   attribute_add_value (attr, s);
780   attrset_add (attrs, attr);
781 }
782
783 static void
784 write_variable_attributes (struct sfm_writer *w, const struct dictionary *d)
785 {
786   struct string s = DS_EMPTY_INITIALIZER;
787   size_t n_vars = dict_get_n_vars (d);
788   size_t n_attrsets = 0;
789   size_t i;
790
791   for (i = 0; i < n_vars; i++)
792     {
793       struct variable *v = dict_get_var (d, i);
794       struct attrset attrs;
795
796       attrset_clone (&attrs, var_get_attributes (v));
797
798       add_role_attribute (var_get_role (v), &attrs);
799       if (n_attrsets++)
800         ds_put_byte (&s, '/');
801       ds_put_format (&s, "%s:", var_get_name (v));
802       put_attrset (&s, &attrs);
803       attrset_destroy (&attrs);
804     }
805   if (n_attrsets)
806     write_utf8_record (w, dict_get_encoding (d), &s, 18);
807   ds_destroy (&s);
808 }
809
810 /* Write variable sets. */
811 static void
812 write_varsets (struct sfm_writer *w, const struct dictionary *dict)
813 {
814   const char *encoding = dict_get_encoding (dict);
815
816   if (is_encoding_ebcdic_compatible (encoding))
817     {
818       /* FIXME. */
819       return;
820     }
821
822   size_t n_varsets = dict_get_n_varsets (dict);
823   if (n_varsets == 0)
824     return;
825
826   struct string s = DS_EMPTY_INITIALIZER;
827   for (size_t i = 0; i < n_varsets; i++)
828     {
829       const struct varset *varset = dict_get_varset (dict, i);
830
831       char *name = recode_string (encoding, "UTF-8", varset->name, -1);
832       ds_put_format (&s, "%s= ", name);
833       free (name);
834
835       for (size_t j = 0; j < varset->n_vars; j++)
836         {
837           if (j)
838             ds_put_byte (&s, ' ');
839
840           const char *name_utf8 = var_get_name (varset->vars[j]);
841           char *name = recode_string (encoding, "UTF-8", name_utf8, -1);
842           ds_put_cstr (&s, name);
843           free (name);
844         }
845       ds_put_byte (&s, '\n');
846     }
847
848   if (!ds_is_empty (&s))
849     write_string_record (w, ds_ss (&s), 5);
850   ds_destroy (&s);
851 }
852
853 /* Write multiple response sets.  If PRE_V14 is true, writes sets supported by
854    SPSS before release 14, otherwise writes sets supported only by later
855    versions. */
856 static void
857 write_mrsets (struct sfm_writer *w, const struct dictionary *dict,
858               bool pre_v14)
859 {
860   const char *encoding = dict_get_encoding (dict);
861   struct string s = DS_EMPTY_INITIALIZER;
862   size_t n_mrsets;
863   size_t i;
864
865   if (is_encoding_ebcdic_compatible (encoding))
866     {
867       /* FIXME. */
868       return;
869     }
870
871   n_mrsets = dict_get_n_mrsets (dict);
872   if (n_mrsets == 0)
873     return;
874
875   for (i = 0; i < n_mrsets; i++)
876     {
877       const struct mrset *mrset = dict_get_mrset (dict, i);
878       char *name;
879       size_t j;
880
881       if ((mrset->type != MRSET_MD || mrset->cat_source != MRSET_COUNTEDVALUES)
882           != pre_v14)
883         continue;
884
885       name = recode_string (encoding, "UTF-8", mrset->name, -1);
886       ds_put_format (&s, "%s=", name);
887       free (name);
888
889       if (mrset->type == MRSET_MD)
890         {
891           char *counted;
892
893           if (mrset->cat_source == MRSET_COUNTEDVALUES)
894             ds_put_format (&s, "E %d ", mrset->label_from_var_label ? 11 : 1);
895           else
896             ds_put_byte (&s, 'D');
897
898           if (mrset->width == 0)
899             counted = xasprintf ("%.0f", mrset->counted.f);
900           else
901             counted = xmemdup0 (mrset->counted.s, mrset->width);
902           ds_put_format (&s, "%zu %s", strlen (counted), counted);
903           free (counted);
904         }
905       else
906         ds_put_byte (&s, 'C');
907       ds_put_byte (&s, ' ');
908
909       if (mrset->label && !mrset->label_from_var_label)
910         {
911           char *label = recode_string (encoding, "UTF-8", mrset->label, -1);
912           ds_put_format (&s, "%zu %s", strlen (label), label);
913           free (label);
914         }
915       else
916         ds_put_cstr (&s, "0 ");
917
918       for (j = 0; j < mrset->n_vars; j++)
919         {
920           const char *short_name_utf8 = var_get_short_name (mrset->vars[j], 0);
921           char *lower_name_utf8 = utf8_to_lower (short_name_utf8);
922           char *short_name = recode_string (encoding, "UTF-8",
923                                             lower_name_utf8, -1);
924           ds_put_format (&s, " %s", short_name);
925           free (short_name);
926           free (lower_name_utf8);
927         }
928       ds_put_byte (&s, '\n');
929     }
930
931   if (!ds_is_empty (&s))
932     write_string_record (w, ds_ss (&s), pre_v14 ? 7 : 19);
933   ds_destroy (&s);
934 }
935
936 /* Write the alignment, width and scale values. */
937 static void
938 write_variable_display_parameters (struct sfm_writer *w,
939                                    const struct dictionary *dict)
940 {
941   int i;
942
943   write_int (w, 7);             /* Record type. */
944   write_int (w, 11);            /* Record subtype. */
945   write_int (w, 4);             /* Data item (int32) size. */
946   write_int (w, w->n_segments * 3); /* Number of data items. */
947
948   for (i = 0; i < dict_get_n_vars (dict); ++i)
949     {
950       struct variable *v = dict_get_var (dict, i);
951       int width = var_get_width (v);
952       int n_segments = sfm_width_to_segments (width);
953       int measure = (var_get_measure (v) == MEASURE_NOMINAL ? 1
954                      : var_get_measure (v) == MEASURE_ORDINAL ? 2
955                      : 3);
956       int alignment = (var_get_alignment (v) == ALIGN_LEFT ? 0
957                        : var_get_alignment (v) == ALIGN_RIGHT ? 1
958                        : 2);
959       int i;
960
961       for (i = 0; i < n_segments; i++)
962         {
963           int width_left = width - sfm_segment_effective_offset (width, i);
964           write_int (w, measure);
965           write_int (w, (i == 0 ? var_get_display_width (v)
966                          : var_default_display_width (width_left)));
967           write_int (w, alignment);
968         }
969     }
970 }
971
972 /* Writes the table of lengths for very long string variables. */
973 static void
974 write_vls_length_table (struct sfm_writer *w,
975                         const struct dictionary *dict)
976 {
977   struct string map;
978   int i;
979
980   ds_init_empty (&map);
981   for (i = 0; i < dict_get_n_vars (dict); ++i)
982     {
983       const struct variable *v = dict_get_var (dict, i);
984       if (sfm_width_to_segments (var_get_width (v)) > 1)
985         ds_put_format (&map, "%s=%05d%c\t",
986                        var_get_short_name (v, 0), var_get_width (v), 0);
987     }
988   if (!ds_is_empty (&map))
989     write_utf8_record (w, dict_get_encoding (dict), &map, 14);
990   ds_destroy (&map);
991 }
992
993 static void
994 write_long_string_value_labels (struct sfm_writer *w,
995                                 const struct dictionary *dict)
996 {
997   const char *encoding = dict_get_encoding (dict);
998   size_t n_vars = dict_get_n_vars (dict);
999   size_t size, i;
1000
1001   /* Figure out the size in advance. */
1002   size = 0;
1003   for (i = 0; i < n_vars; i++)
1004     {
1005       struct variable *var = dict_get_var (dict, i);
1006       const struct val_labs *val_labs = var_get_value_labels (var);
1007       int width = var_get_width (var);
1008       const struct val_lab *val_lab;
1009
1010       if (val_labs_count (val_labs) == 0 || width < 9)
1011         continue;
1012
1013       size += 12;
1014       size += recode_string_len (encoding, "UTF-8", var_get_name (var), -1);
1015       for (val_lab = val_labs_first (val_labs); val_lab != NULL;
1016            val_lab = val_labs_next (val_labs, val_lab))
1017         {
1018           size += 8 + width;
1019           size += recode_string_len (encoding, "UTF-8",
1020                                      val_lab_get_escaped_label (val_lab), -1);
1021         }
1022     }
1023   if (size == 0)
1024     return;
1025
1026   write_int (w, 7);             /* Record type. */
1027   write_int (w, 21);            /* Record subtype */
1028   write_int (w, 1);             /* Data item (byte) size. */
1029   write_int (w, size);          /* Number of data items. */
1030
1031   for (i = 0; i < n_vars; i++)
1032     {
1033       struct variable *var = dict_get_var (dict, i);
1034       const struct val_labs *val_labs = var_get_value_labels (var);
1035       int width = var_get_width (var);
1036       const struct val_lab *val_lab;
1037       char *var_name;
1038
1039       if (val_labs_count (val_labs) == 0 || width < 9)
1040         continue;
1041
1042       var_name = recode_string (encoding, "UTF-8", var_get_name (var), -1);
1043       write_int (w, strlen (var_name));
1044       write_bytes (w, var_name, strlen (var_name));
1045       free (var_name);
1046
1047       write_int (w, width);
1048       write_int (w, val_labs_count (val_labs));
1049       for (val_lab = val_labs_first (val_labs); val_lab != NULL;
1050            val_lab = val_labs_next (val_labs, val_lab))
1051         {
1052           char *label;
1053           size_t len;
1054
1055           write_int (w, width);
1056           write_bytes (w, val_lab_get_value (val_lab)->s, width);
1057
1058           label = recode_string (var_get_encoding (var), "UTF-8",
1059                                  val_lab_get_escaped_label (val_lab), -1);
1060           len = strlen (label);
1061           write_int (w, len);
1062           write_bytes (w, label, len);
1063           free (label);
1064         }
1065     }
1066 }
1067
1068 static void
1069 write_long_string_missing_values (struct sfm_writer *w,
1070                                   const struct dictionary *dict)
1071 {
1072   const char *encoding = dict_get_encoding (dict);
1073   size_t n_vars = dict_get_n_vars (dict);
1074   size_t size, i;
1075
1076   /* Figure out the size in advance. */
1077   size = 0;
1078   for (i = 0; i < n_vars; i++)
1079     {
1080       struct variable *var = dict_get_var (dict, i);
1081       const struct missing_values *mv = var_get_missing_values (var);
1082       int width = var_get_width (var);
1083
1084       if (mv_is_empty (mv) || width < 9)
1085         continue;
1086
1087       size += 4;
1088       size += recode_string_len (encoding, "UTF-8", var_get_name (var), -1);
1089       size += 1;
1090       size += 4;
1091       size += mv_n_values (mv) * 8;
1092     }
1093   if (size == 0)
1094     return;
1095
1096   write_int (w, 7);             /* Record type. */
1097   write_int (w, 22);            /* Record subtype */
1098   write_int (w, 1);             /* Data item (byte) size. */
1099   write_int (w, size);          /* Number of data items. */
1100
1101   for (i = 0; i < n_vars; i++)
1102     {
1103       struct variable *var = dict_get_var (dict, i);
1104       const struct missing_values *mv = var_get_missing_values (var);
1105       int width = var_get_width (var);
1106       uint8_t n_missing_values;
1107       char *var_name;
1108       int j;
1109
1110       if (mv_is_empty (mv) || width < 9)
1111         continue;
1112
1113       var_name = recode_string (encoding, "UTF-8", var_get_name (var), -1);
1114       write_int (w, strlen (var_name));
1115       write_bytes (w, var_name, strlen (var_name));
1116       free (var_name);
1117
1118       n_missing_values = mv_n_values (mv);
1119       write_bytes (w, &n_missing_values, 1);
1120
1121       write_int (w, 8);
1122
1123       for (j = 0; j < n_missing_values; j++)
1124         {
1125           const union value *value = mv_get_value (mv, j);
1126           write_bytes (w, value->s, 8);
1127         }
1128     }
1129 }
1130
1131 static void
1132 write_encoding_record (struct sfm_writer *w,
1133                        const struct dictionary *d)
1134 {
1135   /* IANA says "...character set names may be up to 40 characters taken
1136      from the printable characters of US-ASCII," so character set names
1137      don't need to be recoded to be in UTF-8.
1138
1139      We convert encoding names to uppercase because SPSS writes encoding
1140      names in uppercase. */
1141   char *encoding = xstrdup (dict_get_encoding (d));
1142   str_uppercase (encoding);
1143   write_string_record (w, ss_cstr (encoding), 20);
1144   free (encoding);
1145 }
1146
1147 /* Writes the long variable name table. */
1148 static void
1149 write_longvar_table (struct sfm_writer *w, const struct dictionary *dict)
1150 {
1151   struct string map;
1152   size_t i;
1153
1154   ds_init_empty (&map);
1155   for (i = 0; i < dict_get_n_vars (dict); i++)
1156     {
1157       struct variable *v = dict_get_var (dict, i);
1158       if (i)
1159         ds_put_byte (&map, '\t');
1160       ds_put_format (&map, "%s=%s",
1161                      var_get_short_name (v, 0), var_get_name (v));
1162     }
1163   write_utf8_record (w, dict_get_encoding (dict), &map, 13);
1164   ds_destroy (&map);
1165 }
1166
1167 /* Write integer information record. */
1168 static void
1169 write_integer_info_record (struct sfm_writer *w,
1170                            const struct dictionary *d)
1171 {
1172   const char *dict_encoding = dict_get_encoding (d);
1173   int version_component[3];
1174   int float_format;
1175   int codepage;
1176
1177   /* Parse the version string. */
1178   memset (version_component, 0, sizeof version_component);
1179   sscanf (bare_version, "%d.%d.%d",
1180           &version_component[0], &version_component[1], &version_component[2]);
1181
1182   /* Figure out the floating-point format. */
1183   if (FLOAT_NATIVE_64_BIT == FLOAT_IEEE_DOUBLE_LE
1184       || FLOAT_NATIVE_64_BIT == FLOAT_IEEE_DOUBLE_BE)
1185     float_format = 1;
1186   else if (FLOAT_NATIVE_64_BIT == FLOAT_Z_LONG)
1187     float_format = 2;
1188   else if (FLOAT_NATIVE_64_BIT == FLOAT_VAX_D)
1189     float_format = 3;
1190   else
1191     abort ();
1192
1193   /* Choose codepage. */
1194   codepage = sys_get_codepage_from_encoding (dict_encoding);
1195   if (codepage == 0)
1196     {
1197       /* The codepage is unknown.  Choose a default.
1198
1199          For an EBCDIC-compatible encoding, use the value for EBCDIC.
1200
1201          For an ASCII-compatible encoding, default to "7-bit ASCII", because
1202          many files use this codepage number regardless of their actual
1203          encoding.
1204       */
1205       if (is_encoding_ascii_compatible (dict_encoding))
1206         codepage = 2;
1207       else if (is_encoding_ebcdic_compatible (dict_encoding))
1208         codepage = 1;
1209     }
1210
1211   /* Write record. */
1212   write_int (w, 7);             /* Record type. */
1213   write_int (w, 3);             /* Record subtype. */
1214   write_int (w, 4);             /* Data item (int32) size. */
1215   write_int (w, 8);             /* Number of data items. */
1216   write_int (w, version_component[0]);
1217   write_int (w, version_component[1]);
1218   write_int (w, version_component[2]);
1219   write_int (w, -1);          /* Machine code. */
1220   write_int (w, float_format);
1221   write_int (w, 1);           /* Compression code. */
1222   write_int (w, INTEGER_NATIVE == INTEGER_MSB_FIRST ? 1 : 2);
1223   write_int (w, codepage);
1224 }
1225
1226 /* Write floating-point information record. */
1227 static void
1228 write_float_info_record (struct sfm_writer *w)
1229 {
1230   write_int (w, 7);             /* Record type. */
1231   write_int (w, 4);             /* Record subtype. */
1232   write_int (w, 8);             /* Data item (flt64) size. */
1233   write_int (w, 3);             /* Number of data items. */
1234   write_float (w, SYSMIS);      /* System-missing value. */
1235   write_float (w, HIGHEST);     /* Value used for HIGHEST in missing values. */
1236   write_float (w, LOWEST);      /* Value used for LOWEST in missing values. */
1237 }
1238 \f
1239 /* Writes case C to system file W. */
1240 static void
1241 sys_file_casewriter_write (struct casewriter *writer, void *w_,
1242                            struct ccase *c)
1243 {
1244   struct sfm_writer *w = w_;
1245
1246   if (ferror (w->file))
1247     {
1248       casewriter_force_error (writer);
1249       case_unref (c);
1250       return;
1251     }
1252
1253   w->n_cases++;
1254
1255   if (w->compression == ANY_COMP_NONE)
1256     write_case_uncompressed (w, c);
1257   else
1258     write_case_compressed (w, c);
1259
1260   case_unref (c);
1261 }
1262
1263 /* Destroys system file writer W. */
1264 static void
1265 sys_file_casewriter_destroy (struct casewriter *writer, void *w_)
1266 {
1267   struct sfm_writer *w = w_;
1268   if (!close_writer (w))
1269     casewriter_force_error (writer);
1270 }
1271
1272 /* Returns true if an I/O error has occurred on WRITER, false otherwise. */
1273 static bool
1274 write_error (const struct sfm_writer *writer)
1275 {
1276   return ferror (writer->file);
1277 }
1278
1279 /* Closes a system file after we're done with it.
1280    Returns true if successful, false if an I/O error occurred. */
1281 static bool
1282 close_writer (struct sfm_writer *w)
1283 {
1284   bool ok;
1285
1286   if (w == NULL)
1287     return true;
1288
1289   ok = true;
1290   if (w->file != NULL)
1291     {
1292       /* Flush buffer. */
1293       flush_compressed (w);
1294       if (w->compression == ANY_COMP_ZLIB)
1295         {
1296           finish_zstream (w);
1297           write_ztrailer (w);
1298         }
1299       fflush (w->file);
1300
1301       ok = !write_error (w);
1302
1303       /* Seek back to the beginning and update the number of cases.
1304          This is just a courtesy to later readers, so there's no need
1305          to check return values or report errors. */
1306       if (ok && w->n_cases <= INT32_MAX && !fseeko (w->file, 80, SEEK_SET))
1307         {
1308           write_int (w, w->n_cases);
1309           clearerr (w->file);
1310         }
1311
1312       if (fclose (w->file) == EOF)
1313         ok = false;
1314
1315       if (!ok)
1316         msg (ME, _("An I/O error occurred writing system file `%s'."),
1317              fh_get_file_name (w->fh));
1318
1319       if (ok ? !replace_file_commit (w->rf) : !replace_file_abort (w->rf))
1320         ok = false;
1321     }
1322
1323   free (w->blocks);
1324
1325   fh_unlock (w->lock);
1326   fh_unref (w->fh);
1327
1328   free (w->sfm_vars);
1329   free (w);
1330
1331   return ok;
1332 }
1333
1334 /* System file writer casewriter class. */
1335 static const struct casewriter_class sys_file_casewriter_class =
1336   {
1337     sys_file_casewriter_write,
1338     sys_file_casewriter_destroy,
1339     NULL,
1340   };
1341 \f
1342 /* Writes case C to system file W, without compressing it. */
1343 static void
1344 write_case_uncompressed (struct sfm_writer *w, const struct ccase *c)
1345 {
1346   size_t i;
1347
1348   for (i = 0; i < w->sfm_n_vars; i++)
1349     {
1350       struct sfm_var *v = &w->sfm_vars[i];
1351
1352       if (v->var_width == 0)
1353         write_float (w, case_num_idx (c, v->case_index));
1354       else
1355         {
1356           write_bytes (w, case_str_idx (c, v->case_index) + v->offset,
1357                        v->segment_width);
1358           write_spaces (w, v->padding);
1359         }
1360     }
1361 }
1362
1363 /* Writes case C to system file W, with compression. */
1364 static void
1365 write_case_compressed (struct sfm_writer *w, const struct ccase *c)
1366 {
1367   size_t i;
1368
1369   for (i = 0; i < w->sfm_n_vars; i++)
1370     {
1371       struct sfm_var *v = &w->sfm_vars[i];
1372
1373       if (v->var_width == 0)
1374         {
1375           double d = case_num_idx (c, v->case_index);
1376           if (d == SYSMIS)
1377             put_cmp_opcode (w, 255);
1378           else if (d >= 1 - COMPRESSION_BIAS
1379                    && d <= 251 - COMPRESSION_BIAS
1380                    && d == (int) d)
1381             put_cmp_opcode (w, (int) d + COMPRESSION_BIAS);
1382           else
1383             put_cmp_number (w, d);
1384         }
1385       else
1386         {
1387           int offset = v->offset;
1388           int width, padding;
1389
1390           /* This code properly deals with a width that is not a
1391              multiple of 8, by ensuring that the final partial
1392              oct (8 byte unit) is treated as padded with spaces
1393              on the right. */
1394           for (width = v->segment_width; width > 0; width -= 8, offset += 8)
1395             {
1396               const void *data = case_str_idx (c, v->case_index) + offset;
1397               int chunk_size = MIN (width, 8);
1398               if (!memcmp (data, "        ", chunk_size))
1399                 put_cmp_opcode (w, 254);
1400               else
1401                 put_cmp_string (w, data, chunk_size);
1402             }
1403
1404           /* This code deals properly with padding that is not a
1405              multiple of 8 bytes, by discarding the remainder,
1406              which was already effectively padded with spaces in
1407              the previous loop.  (Note that v->width + v->padding
1408              is always a multiple of 8.) */
1409           for (padding = v->padding / 8; padding > 0; padding--)
1410             put_cmp_opcode (w, 254);
1411         }
1412     }
1413 }
1414
1415 static bool
1416 start_zstream (struct sfm_writer *w)
1417 {
1418   int error;
1419
1420   error = deflateInit (&w->zstream, 1);
1421   if (error != Z_OK)
1422     {
1423       msg (ME, _("Failed to initialize ZLIB for compression (%s)."),
1424            w->zstream.msg);
1425       return false;
1426     }
1427   return true;
1428 }
1429
1430 static void
1431 finish_zstream (struct sfm_writer *w)
1432 {
1433   struct zblock *block;
1434   int error;
1435
1436   assert (w->zstream.total_in <= ZBLOCK_SIZE);
1437
1438   w->zstream.next_in = NULL;
1439   w->zstream.avail_in = 0;
1440   do
1441     {
1442       uint8_t buf[4096];
1443
1444       w->zstream.next_out = buf;
1445       w->zstream.avail_out = sizeof buf;
1446       error = deflate (&w->zstream, Z_FINISH);
1447       write_bytes (w, buf, w->zstream.next_out - buf);
1448     }
1449   while (error == Z_OK);
1450
1451   if (error != Z_STREAM_END)
1452     msg (ME, _("Failed to complete ZLIB stream compression (%s)."),
1453          w->zstream.msg);
1454
1455   if (w->n_blocks >= w->allocated_blocks)
1456     w->blocks = x2nrealloc (w->blocks, &w->allocated_blocks,
1457                             sizeof *w->blocks);
1458   block = &w->blocks[w->n_blocks++];
1459   block->uncompressed_size = w->zstream.total_in;
1460   block->compressed_size = w->zstream.total_out;
1461   deflateEnd (&w->zstream);
1462 }
1463
1464 static void
1465 write_zlib (struct sfm_writer *w, const void *data_, unsigned int n)
1466 {
1467   const uint8_t *data = data_;
1468
1469   while (n > 0)
1470     {
1471       unsigned int chunk;
1472
1473       if (w->zstream.total_in >= ZBLOCK_SIZE)
1474         {
1475           finish_zstream (w);
1476           start_zstream (w);
1477         }
1478
1479       chunk = MIN (n, ZBLOCK_SIZE - w->zstream.total_in);
1480
1481       w->zstream.next_in = CONST_CAST (uint8_t *, data);
1482       w->zstream.avail_in = chunk;
1483       do
1484         {
1485           uint8_t buf[4096];
1486           int error;
1487
1488           w->zstream.next_out = buf;
1489           w->zstream.avail_out = sizeof buf;
1490           error = deflate (&w->zstream, Z_NO_FLUSH);
1491           write_bytes (w, buf, w->zstream.next_out - buf);
1492           if (error != Z_OK)
1493             {
1494               msg (ME, _("ZLIB stream compression failed (%s)."),
1495                    w->zstream.msg);
1496               return;
1497             }
1498         }
1499       while (w->zstream.avail_in > 0 || w->zstream.avail_out == 0);
1500       data += chunk;
1501       n -= chunk;
1502     }
1503 }
1504
1505 static void
1506 write_ztrailer (struct sfm_writer *w)
1507 {
1508   long long int uncompressed_ofs;
1509   long long int compressed_ofs;
1510   const struct zblock *block;
1511
1512   write_int64 (w, -COMPRESSION_BIAS);
1513   write_int64 (w, 0);
1514   write_int (w, ZBLOCK_SIZE);
1515   write_int (w, w->n_blocks);
1516
1517   uncompressed_ofs = w->zstart;
1518   compressed_ofs = w->zstart + 24;
1519   for (block = w->blocks; block < &w->blocks[w->n_blocks]; block++)
1520     {
1521       write_int64 (w, uncompressed_ofs);
1522       write_int64 (w, compressed_ofs);
1523       write_int (w, block->uncompressed_size);
1524       write_int (w, block->compressed_size);
1525
1526       uncompressed_ofs += block->uncompressed_size;
1527       compressed_ofs += block->compressed_size;
1528     }
1529
1530   if (!fseeko (w->file, w->zstart + 8, SEEK_SET))
1531     {
1532       write_int64 (w, compressed_ofs);
1533       write_int64 (w, 24 + (w->n_blocks * 24));
1534     }
1535   else
1536     msg (ME, _("%s: Seek failed (%s)."),
1537          fh_get_file_name (w->fh), strerror (errno));
1538 }
1539
1540 /* Flushes buffered compressed opcodes and data to W. */
1541 static void
1542 flush_compressed (struct sfm_writer *w)
1543 {
1544   if (w->n_opcodes)
1545     {
1546       unsigned int n = 8 * (1 + w->n_elements);
1547       if (w->compression == ANY_COMP_SIMPLE)
1548         write_bytes (w, w->cbuf, n);
1549       else
1550         write_zlib (w, w->cbuf, n);
1551
1552       w->n_opcodes = w->n_elements = 0;
1553       memset (w->cbuf[0], 0, 8);
1554     }
1555 }
1556
1557 /* Appends OPCODE to the buffered set of compression opcodes in
1558    W.  Flushes the compression buffer beforehand if necessary. */
1559 static void
1560 put_cmp_opcode (struct sfm_writer *w, uint8_t opcode)
1561 {
1562   if (w->n_opcodes >= 8)
1563     flush_compressed (w);
1564
1565   w->cbuf[0][w->n_opcodes++] = opcode;
1566 }
1567
1568 /* Appends NUMBER to the buffered compression data in W. */
1569 static void
1570 put_cmp_number (struct sfm_writer *w, double number)
1571 {
1572   put_cmp_opcode (w, 253);
1573   convert_double_to_output_format (number, w->cbuf[++w->n_elements]);
1574 }
1575
1576 /* Appends SIZE bytes of DATA to the buffered compression data in
1577    W, followed by enough spaces to pad the output data to exactly
1578    8 bytes (thus, SIZE must be no greater than 8). */
1579 static void
1580 put_cmp_string (struct sfm_writer *w, const void *data, size_t size)
1581 {
1582   assert (size <= 8);
1583
1584   put_cmp_opcode (w, 253);
1585   w->n_elements++;
1586   memset (w->cbuf[w->n_elements], w->space, 8);
1587   memcpy (w->cbuf[w->n_elements], data, size);
1588 }
1589 \f
1590 /* Writes 32-bit integer X to the output file for writer W. */
1591 static void
1592 write_int (struct sfm_writer *w, int32_t x)
1593 {
1594   write_bytes (w, &x, sizeof x);
1595 }
1596
1597 /* Writes 64-bit integer X to the output file for writer W. */
1598 static void
1599 write_int64 (struct sfm_writer *w, int64_t x)
1600 {
1601   write_bytes (w, &x, sizeof x);
1602 }
1603
1604 /* Converts NATIVE to the 64-bit format used in output files in
1605    OUTPUT. */
1606 static inline void
1607 convert_double_to_output_format (double native, uint8_t output[8])
1608 {
1609   /* If "double" is not a 64-bit type, then convert it to a
1610      64-bit type.  Otherwise just copy it. */
1611   if (FLOAT_NATIVE_DOUBLE != FLOAT_NATIVE_64_BIT)
1612     float_convert (FLOAT_NATIVE_DOUBLE, &native, FLOAT_NATIVE_64_BIT, output);
1613   else
1614     memcpy (output, &native, sizeof native);
1615 }
1616
1617 /* Writes floating-point number X to the output file for writer
1618    W. */
1619 static void
1620 write_float (struct sfm_writer *w, double x)
1621 {
1622   uint8_t output[8];
1623   convert_double_to_output_format (x, output);
1624   write_bytes (w, output, sizeof output);
1625 }
1626
1627 /* Writes contents of VALUE with the given WIDTH to W, padding
1628    with zeros to a multiple of 8 bytes.
1629    To avoid a branch, and because we don't actually need to
1630    support it, WIDTH must be no bigger than 8. */
1631 static void
1632 write_value (struct sfm_writer *w, const union value *value, int width)
1633 {
1634   assert (width <= 8);
1635   if (width == 0)
1636     write_float (w, value->f);
1637   else
1638     {
1639       write_bytes (w, value->s, width);
1640       write_zeros (w, 8 - width);
1641     }
1642 }
1643
1644 /* Writes null-terminated STRING in a field of the given WIDTH to W.  If STRING
1645    is longer than WIDTH, it is truncated; if STRING is shorter than WIDTH, it
1646    is padded on the right with spaces. */
1647 static void
1648 write_string (struct sfm_writer *w, const char *string, size_t width)
1649 {
1650   size_t data_bytes = MIN (strlen (string), width);
1651   size_t pad_bytes = width - data_bytes;
1652   write_bytes (w, string, data_bytes);
1653   while (pad_bytes-- > 0)
1654     putc (w->space, w->file);
1655 }
1656
1657 /* Recodes null-terminated UTF-8 encoded STRING into ENCODING, and writes the
1658    recoded version in a field of the given WIDTH to W.  The string is truncated
1659    or padded on the right with spaces to exactly WIDTH bytes. */
1660 static void
1661 write_utf8_string (struct sfm_writer *w, const char *encoding,
1662                    const char *string, size_t width)
1663 {
1664   char *s = recode_string (encoding, "UTF-8", string, -1);
1665   write_string (w, s, width);
1666   free (s);
1667 }
1668
1669 /* Writes a record with type 7, subtype SUBTYPE that contains CONTENT recoded
1670    from UTF-8 encoded into ENCODING. */
1671 static void
1672 write_utf8_record (struct sfm_writer *w, const char *encoding,
1673                    const struct string *content, int subtype)
1674 {
1675   struct substring s;
1676
1677   s = recode_substring_pool (encoding, "UTF-8", ds_ss (content), NULL);
1678   write_string_record (w, s, subtype);
1679   ss_dealloc (&s);
1680 }
1681
1682 /* Writes a record with type 7, subtype SUBTYPE that contains the string
1683    CONTENT. */
1684 static void
1685 write_string_record (struct sfm_writer *w,
1686                      const struct substring content, int subtype)
1687 {
1688   write_int (w, 7);
1689   write_int (w, subtype);
1690   write_int (w, 1);
1691   write_int (w, ss_length (content));
1692   write_bytes (w, ss_data (content), ss_length (content));
1693 }
1694
1695 /* Writes SIZE bytes of DATA to W's output file. */
1696 static void
1697 write_bytes (struct sfm_writer *w, const void *data, size_t size)
1698 {
1699   fwrite (data, 1, size, w->file);
1700 }
1701
1702 /* Writes N zeros to W's output file. */
1703 static void
1704 write_zeros (struct sfm_writer *w, size_t n)
1705 {
1706   while (n-- > 0)
1707     putc (0, w->file);
1708 }
1709
1710 /* Writes N spaces to W's output file. */
1711 static void
1712 write_spaces (struct sfm_writer *w, size_t n)
1713 {
1714   while (n-- > 0)
1715     putc (w->space, w->file);
1716 }