sys-file-writer: Write identical sets of value labels only once.
[pspp] / src / data / sys-file-writer.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2007, 2009, 2010, 2011 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
29 #include "data/attributes.h"
30 #include "data/case.h"
31 #include "data/casewriter-provider.h"
32 #include "data/casewriter.h"
33 #include "data/dictionary.h"
34 #include "data/file-handle-def.h"
35 #include "data/file-name.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 "libpspp/float-format.h"
45 #include "libpspp/i18n.h"
46 #include "libpspp/integer-format.h"
47 #include "libpspp/message.h"
48 #include "libpspp/misc.h"
49 #include "libpspp/str.h"
50 #include "libpspp/string-array.h"
51 #include "libpspp/version.h"
52
53 #include "gl/xmemdup0.h"
54 #include "gl/minmax.h"
55 #include "gl/unlocked-io.h"
56 #include "gl/xalloc.h"
57
58 #include "gettext.h"
59 #define _(msgid) gettext (msgid)
60 #define N_(msgid) (msgid)
61
62 /* Compression bias used by PSPP.  Values between (1 -
63    COMPRESSION_BIAS) and (251 - COMPRESSION_BIAS) inclusive can be
64    compressed. */
65 #define COMPRESSION_BIAS 100
66
67 /* System file writer. */
68 struct sfm_writer
69   {
70     struct file_handle *fh;     /* File handle. */
71     struct fh_lock *lock;       /* Mutual exclusion for file. */
72     FILE *file;                 /* File stream. */
73     struct replace_file *rf;    /* Ticket for replacing output file. */
74
75     bool compress;              /* 1=compressed, 0=not compressed. */
76     casenumber case_cnt;        /* Number of cases written so far. */
77
78     /* Compression buffering.
79
80        Compressed data is output as groups of 8 1-byte opcodes
81        followed by up to 8 (depending on the opcodes) 8-byte data
82        items.  Data items and opcodes arrive at the same time but
83        must be reordered for writing to disk, thus a small amount
84        of buffering here. */
85     uint8_t opcodes[8];         /* Buffered opcodes. */
86     int opcode_cnt;             /* Number of buffered opcodes. */
87     uint8_t data[8][8];         /* Buffered data. */
88     int data_cnt;               /* Number of buffered data items. */
89
90     /* Variables. */
91     struct sfm_var *sfm_vars;   /* Variables. */
92     size_t sfm_var_cnt;         /* Number of variables. */
93     size_t segment_cnt;         /* Number of variables including extra segments
94                                    for long string variables. */
95   };
96
97 static const struct casewriter_class sys_file_casewriter_class;
98
99 static void write_header (struct sfm_writer *, const struct dictionary *);
100 static void write_variable (struct sfm_writer *, const struct variable *);
101 static void write_value_labels (struct sfm_writer *,
102                                 const struct dictionary *);
103 static void write_integer_info_record (struct sfm_writer *,
104                                        const struct dictionary *);
105 static void write_float_info_record (struct sfm_writer *);
106
107 static void write_longvar_table (struct sfm_writer *w,
108                                  const struct dictionary *dict);
109
110 static void write_encoding_record (struct sfm_writer *w,
111                                    const struct dictionary *);
112
113 static void write_vls_length_table (struct sfm_writer *w,
114                               const struct dictionary *dict);
115
116 static void write_long_string_value_labels (struct sfm_writer *,
117                                             const struct dictionary *);
118
119 static void write_mrsets (struct sfm_writer *, const struct dictionary *,
120                           bool pre_v14);
121
122 static void write_variable_display_parameters (struct sfm_writer *w,
123                                                const struct dictionary *dict);
124
125 static void write_documents (struct sfm_writer *, const struct dictionary *);
126
127 static void write_data_file_attributes (struct sfm_writer *,
128                                         const struct dictionary *);
129 static void write_variable_attributes (struct sfm_writer *,
130                                        const struct dictionary *);
131
132 static void write_int (struct sfm_writer *, int32_t);
133 static inline void convert_double_to_output_format (double, uint8_t[8]);
134 static void write_float (struct sfm_writer *, double);
135 static void write_string (struct sfm_writer *, const char *, size_t);
136 static void write_utf8_string (struct sfm_writer *, const char *encoding,
137                                const char *string, size_t width);
138 static void write_utf8_record (struct sfm_writer *, const char *encoding,
139                                const struct string *content, int subtype);
140 static void write_string_record (struct sfm_writer *,
141                                  const struct substring content, int subtype);
142 static void write_bytes (struct sfm_writer *, const void *, size_t);
143 static void write_zeros (struct sfm_writer *, size_t);
144 static void write_spaces (struct sfm_writer *, size_t);
145 static void write_value (struct sfm_writer *, const union value *, int width);
146
147 static void write_case_uncompressed (struct sfm_writer *,
148                                      const struct ccase *);
149 static void write_case_compressed (struct sfm_writer *, const struct ccase *);
150 static void flush_compressed (struct sfm_writer *);
151 static void put_cmp_opcode (struct sfm_writer *, uint8_t);
152 static void put_cmp_number (struct sfm_writer *, double);
153 static void put_cmp_string (struct sfm_writer *, const void *, size_t);
154
155 static bool write_error (const struct sfm_writer *);
156 static bool close_writer (struct sfm_writer *);
157
158 /* Returns default options for writing a system file. */
159 struct sfm_write_options
160 sfm_writer_default_options (void)
161 {
162   struct sfm_write_options opts;
163   opts.create_writeable = true;
164   opts.compress = settings_get_scompression ();
165   opts.version = 3;
166   return opts;
167 }
168
169 /* Opens the system file designated by file handle FH for writing
170    cases from dictionary D according to the given OPTS.
171
172    No reference to D is retained, so it may be modified or
173    destroyed at will after this function returns.  D is not
174    modified by this function, except to assign short names. */
175 struct casewriter *
176 sfm_open_writer (struct file_handle *fh, struct dictionary *d,
177                  struct sfm_write_options opts)
178 {
179   struct sfm_writer *w;
180   mode_t mode;
181   int i;
182
183   /* Check version. */
184   if (opts.version != 2 && opts.version != 3)
185     {
186       msg (ME, _("Unknown system file version %d. Treating as version %d."),
187            opts.version, 3);
188       opts.version = 3;
189     }
190
191   /* Create and initialize writer. */
192   w = xmalloc (sizeof *w);
193   w->fh = fh_ref (fh);
194   w->lock = NULL;
195   w->file = NULL;
196   w->rf = NULL;
197
198   w->compress = opts.compress;
199   w->case_cnt = 0;
200
201   w->opcode_cnt = w->data_cnt = 0;
202
203   /* Figure out how to map in-memory case data to on-disk case
204      data.  Also count the number of segments.  Very long strings
205      occupy multiple segments, otherwise each variable only takes
206      one segment. */
207   w->segment_cnt = sfm_dictionary_to_sfm_vars (d, &w->sfm_vars,
208                                                &w->sfm_var_cnt);
209
210   /* Open file handle as an exclusive writer. */
211   /* TRANSLATORS: this fragment will be interpolated into
212      messages in fh_lock() that identify types of files. */
213   w->lock = fh_lock (fh, FH_REF_FILE, N_("system file"), FH_ACC_WRITE, true);
214   if (w->lock == NULL)
215     goto error;
216
217   /* Create the file on disk. */
218   mode = 0444;
219   if (opts.create_writeable)
220     mode |= 0222;
221   w->rf = replace_file_start (fh_get_file_name (fh), "wb", mode,
222                               &w->file, NULL);
223   if (w->rf == NULL)
224     {
225       msg (ME, _("Error opening `%s' for writing as a system file: %s."),
226            fh_get_file_name (fh), strerror (errno));
227       goto error;
228     }
229
230   /* Write the file header. */
231   write_header (w, d);
232
233   /* Write basic variable info. */
234   short_names_assign (d);
235   for (i = 0; i < dict_get_var_cnt (d); i++)
236     write_variable (w, dict_get_var (d, i));
237
238   write_value_labels (w, d);
239
240   if (dict_get_document_line_cnt (d) > 0)
241     write_documents (w, d);
242
243   write_integer_info_record (w, d);
244   write_float_info_record (w);
245
246   write_mrsets (w, d, true);
247
248   write_variable_display_parameters (w, d);
249
250   if (opts.version >= 3)
251     write_longvar_table (w, d);
252
253   write_vls_length_table (w, d);
254
255   write_long_string_value_labels (w, d);
256
257   if (attrset_count (dict_get_attributes (d)))
258     write_data_file_attributes (w, d);
259   write_variable_attributes (w, d);
260
261   write_mrsets (w, d, false);
262
263   write_encoding_record (w, d);
264
265   /* Write end-of-headers record. */
266   write_int (w, 999);
267   write_int (w, 0);
268
269   if (write_error (w))
270     goto error;
271
272   return casewriter_create (dict_get_proto (d), &sys_file_casewriter_class, w);
273
274 error:
275   close_writer (w);
276   return NULL;
277 }
278
279 /* Returns value of X truncated to two least-significant digits. */
280 static int
281 rerange (int x)
282 {
283   if (x < 0)
284     x = -x;
285   if (x >= 100)
286     x %= 100;
287   return x;
288 }
289
290 /* Calculates the offset of data for TARGET_VAR from the
291    beginning of each case's data for dictionary D.  The return
292    value is in "octs" (8-byte units). */
293 static int
294 calc_oct_idx (const struct dictionary *d, struct variable *target_var)
295 {
296   int oct_idx;
297   int i;
298
299   oct_idx = 0;
300   for (i = 0; i < dict_get_var_cnt (d); i++)
301     {
302       struct variable *var = dict_get_var (d, i);
303       if (var == target_var)
304         break;
305       oct_idx += sfm_width_to_octs (var_get_width (var));
306     }
307   return oct_idx;
308 }
309
310 /* Write the sysfile_header header to system file W. */
311 static void
312 write_header (struct sfm_writer *w, const struct dictionary *d)
313 {
314   char prod_name[61];
315   char creation_date[10];
316   char creation_time[9];
317   const char *file_label;
318   struct variable *weight;
319
320   time_t t;
321
322   /* Record-type code. */
323   write_string (w, "$FL2", 4);
324
325   /* Product identification. */
326   snprintf (prod_name, sizeof prod_name, "@(#) SPSS DATA FILE %s - %s",
327             version, host_system);
328   write_string (w, prod_name, 60);
329
330   /* Layout code. */
331   write_int (w, 2);
332
333   /* Number of `union value's per case. */
334   write_int (w, calc_oct_idx (d, NULL));
335
336   /* Compressed? */
337   write_int (w, w->compress);
338
339   /* Weight variable. */
340   weight = dict_get_weight (d);
341   write_int (w, weight != NULL ? calc_oct_idx (d, weight) + 1 : 0);
342
343   /* Number of cases.  We don't know this in advance, so we write
344      -1 to indicate an unknown number of cases.  Later we can
345      come back and overwrite it with the true value. */
346   write_int (w, -1);
347
348   /* Compression bias. */
349   write_float (w, COMPRESSION_BIAS);
350
351   /* Creation date and time. */
352   if (time (&t) == (time_t) -1)
353     {
354       strcpy (creation_date, "01 Jan 70");
355       strcpy (creation_time, "00:00:00");
356     }
357   else
358     {
359       static const char *const month_name[12] =
360         {
361           "Jan", "Feb", "Mar", "Apr", "May", "Jun",
362           "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
363         };
364       struct tm *tmp = localtime (&t);
365       int day = rerange (tmp->tm_mday);
366       int mon = rerange (tmp->tm_mon + 1);
367       int year = rerange (tmp->tm_year);
368       int hour = rerange (tmp->tm_hour + 1);
369       int min = rerange (tmp->tm_min + 1);
370       int sec = rerange (tmp->tm_sec + 1);
371
372       snprintf (creation_date, sizeof creation_date,
373                 "%02d %s %02d", day, month_name[mon - 1], year);
374       snprintf (creation_time, sizeof creation_time,
375                 "%02d:%02d:%02d", hour - 1, min - 1, sec - 1);
376     }
377   write_string (w, creation_date, 9);
378   write_string (w, creation_time, 8);
379
380   /* File label. */
381   file_label = dict_get_label (d);
382   if (file_label == NULL)
383     file_label = "";
384   write_utf8_string (w, dict_get_encoding (d), file_label, 64);
385
386   /* Padding. */
387   write_zeros (w, 3);
388 }
389
390 /* Write format spec FMT to W, after adjusting it to be
391    compatible with the given WIDTH. */
392 static void
393 write_format (struct sfm_writer *w, struct fmt_spec fmt, int width)
394 {
395   assert (fmt_check_output (&fmt));
396   assert (sfm_width_to_segments (width) == 1);
397
398   if (width > 0)
399     fmt_resize (&fmt, width);
400   write_int (w, (fmt_to_io (fmt.type) << 16) | (fmt.w << 8) | fmt.d);
401 }
402
403 /* Write a string continuation variable record for each 8-byte
404    section beyond the initial 8 bytes, for a variable of the
405    given WIDTH. */
406 static void
407 write_variable_continuation_records (struct sfm_writer *w, int width)
408 {
409   int position;
410
411   assert (sfm_width_to_segments (width) == 1);
412   for (position = 8; position < width; position += 8)
413     {
414       write_int (w, 2);   /* Record type. */
415       write_int (w, -1);  /* Width. */
416       write_int (w, 0);   /* No variable label. */
417       write_int (w, 0);   /* No missing values. */
418       write_int (w, 0);   /* Print format. */
419       write_int (w, 0);   /* Write format. */
420       write_zeros (w, 8);   /* Name. */
421     }
422 }
423
424 /* Write the variable record(s) for variable V to system file
425    W. */
426 static void
427 write_variable (struct sfm_writer *w, const struct variable *v)
428 {
429   int width = var_get_width (v);
430   int segment_cnt = sfm_width_to_segments (width);
431   int seg0_width = sfm_segment_alloc_width (width, 0);
432   const char *encoding = var_get_encoding (v);
433   struct missing_values mv;
434   int i;
435
436   /* Record type. */
437   write_int (w, 2);
438
439   /* Width. */
440   write_int (w, seg0_width);
441
442   /* Variable has a variable label? */
443   write_int (w, var_has_label (v));
444
445   /* Number of missing values.  If there is a range, then the
446      range counts as 2 missing values and causes the number to be
447      negated. */
448   mv_copy (&mv, var_get_missing_values (v));
449   if (mv_get_width (&mv) > 8)
450     mv_resize (&mv, 8);
451   if (mv_has_range (&mv))
452     write_int (w, -2 - mv_n_values (&mv));
453   else
454     write_int (w, mv_n_values (&mv));
455
456   /* Print and write formats. */
457   write_format (w, *var_get_print_format (v), seg0_width);
458   write_format (w, *var_get_write_format (v), seg0_width);
459
460   /* Short name.
461      The full name is in a translation table written
462      separately. */
463   write_utf8_string (w, encoding, var_get_short_name (v, 0), 8);
464
465   /* Value label. */
466   if (var_has_label (v))
467     {
468       char *label = recode_string (encoding, UTF8, var_get_label (v), -1);
469       size_t label_len = MIN (strlen (label), 255);
470       size_t padded_len = ROUND_UP (label_len, 4);
471       write_int (w, label_len);
472       write_string (w, label, padded_len);
473       free (label);
474     }
475
476   /* Write the missing values, if any, range first. */
477   if (mv_has_range (&mv))
478     {
479       double x, y;
480       mv_get_range (&mv, &x, &y);
481       write_float (w, x);
482       write_float (w, y);
483     }
484   for (i = 0; i < mv_n_values (&mv); i++)
485     write_value (w, mv_get_value (&mv, i), mv_get_width (&mv));
486
487   write_variable_continuation_records (w, seg0_width);
488
489   /* Write additional segments for very long string variables. */
490   for (i = 1; i < segment_cnt; i++)
491     {
492       int seg_width = sfm_segment_alloc_width (width, i);
493       struct fmt_spec fmt = fmt_for_output (FMT_A, MAX (seg_width, 1), 0);
494
495       write_int (w, 2);           /* Variable record. */
496       write_int (w, seg_width);   /* Width. */
497       write_int (w, 0);           /* No variable label. */
498       write_int (w, 0);           /* No missing values. */
499       write_format (w, fmt, seg_width); /* Print format. */
500       write_format (w, fmt, seg_width); /* Write format. */
501       write_utf8_string (w, encoding, var_get_short_name (v, i), 8);
502
503       write_variable_continuation_records (w, seg_width);
504     }
505
506   mv_destroy (&mv);
507 }
508
509 /* Writes the value labels to system file W.
510
511    Value labels for long string variables are written separately,
512    by write_long_string_value_labels. */
513 static void
514 write_value_labels (struct sfm_writer *w, const struct dictionary *d)
515 {
516   struct label_set
517     {
518       struct hmap_node hmap_node;
519       const struct val_labs *val_labs;
520       int *indexes;
521       size_t n_indexes, allocated_indexes;
522     };
523
524   size_t n_sets, allocated_sets;
525   struct label_set **sets;
526   struct hmap same_sets;
527   size_t i;
528   int idx;
529
530   n_sets = allocated_sets = 0;
531   sets = NULL;
532   hmap_init (&same_sets);
533
534   idx = 0;
535   for (i = 0; i < dict_get_var_cnt (d); i++)
536     {
537       struct variable *v = dict_get_var (d, i);
538
539       if (var_has_value_labels (v) && var_get_width (v) <= 8)
540         {
541           const struct val_labs *val_labs = var_get_value_labels (v);
542           unsigned int hash = val_labs_hash (val_labs, 0);
543           struct label_set *set;
544
545           HMAP_FOR_EACH_WITH_HASH (set, struct label_set, hmap_node,
546                                    hash, &same_sets)
547             {
548               if (val_labs_equal (set->val_labs, val_labs))
549                 {
550                   if (set->n_indexes >= set->allocated_indexes)
551                     set->indexes = x2nrealloc (set->indexes,
552                                                &set->allocated_indexes,
553                                                sizeof *set->indexes);
554                   set->indexes[set->n_indexes++] = idx;
555                   goto next_var;
556                 }
557             }
558
559           set = xmalloc (sizeof *set);
560           set->val_labs = val_labs;
561           set->indexes = xmalloc (sizeof *set->indexes);
562           set->indexes[0] = idx;
563           set->n_indexes = 1;
564           set->allocated_indexes = 1;
565           hmap_insert (&same_sets, &set->hmap_node, hash);
566
567           if (n_sets >= allocated_sets)
568             sets = x2nrealloc (sets, &allocated_sets, sizeof *sets);
569           sets[n_sets++] = set;
570         }
571
572     next_var:
573       idx += sfm_width_to_octs (var_get_width (v));
574     }
575
576   for (i = 0; i < n_sets; i++)
577     {
578       const struct label_set *set = sets[i];
579       const struct val_labs *val_labs = set->val_labs;
580       size_t n_labels = val_labs_count (val_labs);
581       int width = val_labs_get_width (val_labs);
582       const struct val_lab **labels;
583       size_t j;
584
585       /* Value label record. */
586       write_int (w, 3);             /* Record type. */
587       write_int (w, n_labels);
588       labels = val_labs_sorted (val_labs);
589       for (j = 0; j < n_labels; j++)
590         {
591           const struct val_lab *vl = labels[j];
592           char *label = recode_string (dict_get_encoding (d), UTF8,
593                                        val_lab_get_escaped_label (vl), -1);
594           uint8_t len = MIN (strlen (label), 255);
595
596           write_value (w, val_lab_get_value (vl), width);
597           write_bytes (w, &len, 1);
598           write_bytes (w, label, len);
599           write_zeros (w, REM_RND_UP (len + 1, 8));
600           free (label);
601         }
602       free (labels);
603
604       /* Value label variable record. */
605       write_int (w, 4);              /* Record type. */
606       write_int (w, set->n_indexes);
607       for (j = 0; j < set->n_indexes; j++)
608         write_int (w, set->indexes[j] + 1);
609     }
610
611   for (i = 0; i < n_sets; i++)
612     {
613       struct label_set *set = sets[i];
614
615       free (set->indexes);
616       free (set);
617     }
618   free (sets);
619   hmap_destroy (&same_sets);
620 }
621
622 /* Writes record type 6, document record. */
623 static void
624 write_documents (struct sfm_writer *w, const struct dictionary *d)
625 {
626   const struct string_array *docs = dict_get_documents (d);
627   const char *enc = dict_get_encoding (d);
628   size_t i;
629
630   write_int (w, 6);             /* Record type. */
631   write_int (w, docs->n);
632   for (i = 0; i < docs->n; i++)
633     {
634       char *s = recode_string (enc, "UTF-8", docs->strings[i], -1);
635       size_t s_len = strlen (s);
636       size_t write_len = MIN (s_len, DOC_LINE_LENGTH);
637
638       write_bytes (w, s, write_len);
639       write_spaces (w, DOC_LINE_LENGTH - write_len);
640       free (s);
641     }
642 }
643
644 static void
645 put_attrset (struct string *string, const struct attrset *attrs)
646 {
647   const struct attribute *attr;
648   struct attrset_iterator i;
649
650   for (attr = attrset_first (attrs, &i); attr != NULL;
651        attr = attrset_next (attrs, &i)) 
652     {
653       size_t n_values = attribute_get_n_values (attr);
654       size_t j;
655
656       ds_put_cstr (string, attribute_get_name (attr));
657       ds_put_byte (string, '(');
658       for (j = 0; j < n_values; j++) 
659         ds_put_format (string, "'%s'\n", attribute_get_value (attr, j));
660       ds_put_byte (string, ')');
661     }
662 }
663
664 static void
665 write_data_file_attributes (struct sfm_writer *w,
666                             const struct dictionary *d)
667 {
668   struct string s = DS_EMPTY_INITIALIZER;
669   put_attrset (&s, dict_get_attributes (d));
670   write_utf8_record (w, dict_get_encoding (d), &s, 17);
671   ds_destroy (&s);
672 }
673
674 static void
675 write_variable_attributes (struct sfm_writer *w, const struct dictionary *d)
676 {
677   struct string s = DS_EMPTY_INITIALIZER;
678   size_t n_vars = dict_get_var_cnt (d);
679   size_t n_attrsets = 0;
680   size_t i;
681
682   for (i = 0; i < n_vars; i++)
683     { 
684       struct variable *v = dict_get_var (d, i);
685       struct attrset *attrs = var_get_attributes (v);
686       if (attrset_count (attrs)) 
687         {
688           if (n_attrsets++)
689             ds_put_byte (&s, '/');
690           ds_put_format (&s, "%s:", var_get_name (v));
691           put_attrset (&s, attrs);
692         }
693     }
694   if (n_attrsets)
695     write_utf8_record (w, dict_get_encoding (d), &s, 18);
696   ds_destroy (&s);
697 }
698
699 /* Write multiple response sets.  If PRE_V14 is true, writes sets supported by
700    SPSS before release 14, otherwise writes sets supported only by later
701    versions. */
702 static void
703 write_mrsets (struct sfm_writer *w, const struct dictionary *dict,
704               bool pre_v14)
705 {
706   const char *encoding = dict_get_encoding (dict);
707   struct string s = DS_EMPTY_INITIALIZER;
708   size_t n_mrsets;
709   size_t i;
710
711   n_mrsets = dict_get_n_mrsets (dict);
712   if (n_mrsets == 0)
713     return;
714
715   for (i = 0; i < n_mrsets; i++)
716     {
717       const struct mrset *mrset = dict_get_mrset (dict, i);
718       char *name;
719       size_t j;
720
721       if ((mrset->type != MRSET_MD || mrset->cat_source != MRSET_COUNTEDVALUES)
722           != pre_v14)
723         continue;
724
725       name = recode_string (encoding, "UTF-8", mrset->name, -1);
726       ds_put_format (&s, "%s=", name);
727       free (name);
728
729       if (mrset->type == MRSET_MD)
730         {
731           char *counted;
732
733           if (mrset->cat_source == MRSET_COUNTEDVALUES)
734             ds_put_format (&s, "E %d ", mrset->label_from_var_label ? 11 : 1);
735           else
736             ds_put_byte (&s, 'D');
737
738           if (mrset->width == 0)
739             counted = xasprintf ("%.0f", mrset->counted.f);
740           else
741             counted = xmemdup0 (value_str (&mrset->counted, mrset->width),
742                                 mrset->width);
743           ds_put_format (&s, "%zu %s", strlen (counted), counted);
744           free (counted);
745         }
746       else
747         ds_put_byte (&s, 'C');
748       ds_put_byte (&s, ' ');
749
750       if (mrset->label && !mrset->label_from_var_label)
751         {
752           char *label = recode_string (encoding, "UTF-8", mrset->label, -1);
753           ds_put_format (&s, "%zu %s", strlen (label), label);
754           free (label);
755         }
756       else
757         ds_put_cstr (&s, "0 ");
758
759       for (j = 0; j < mrset->n_vars; j++)
760         {
761           const char *short_name_utf8 = var_get_short_name (mrset->vars[j], 0);
762           char *short_name = recode_string (encoding, "UTF-8",
763                                             short_name_utf8, -1);
764           str_lowercase (short_name);
765           ds_put_format (&s, " %s", short_name);
766           free (short_name);
767         }
768       ds_put_byte (&s, '\n');
769     }
770
771   if (!ds_is_empty (&s))
772     write_string_record (w, ds_ss (&s), pre_v14 ? 7 : 19);
773   ds_destroy (&s);
774 }
775
776 /* Write the alignment, width and scale values. */
777 static void
778 write_variable_display_parameters (struct sfm_writer *w,
779                                    const struct dictionary *dict)
780 {
781   int i;
782
783   write_int (w, 7);             /* Record type. */
784   write_int (w, 11);            /* Record subtype. */
785   write_int (w, 4);             /* Data item (int32) size. */
786   write_int (w, w->segment_cnt * 3); /* Number of data items. */
787
788   for (i = 0; i < dict_get_var_cnt (dict); ++i)
789     {
790       struct variable *v = dict_get_var (dict, i);
791       int width = var_get_width (v);
792       int segment_cnt = sfm_width_to_segments (width);
793       int measure = (var_get_measure (v) == MEASURE_NOMINAL ? 1
794                      : var_get_measure (v) == MEASURE_ORDINAL ? 2
795                      : 3);
796       int alignment = (var_get_alignment (v) == ALIGN_LEFT ? 0
797                        : var_get_alignment (v) == ALIGN_RIGHT ? 1
798                        : 2);
799       int i;
800
801       for (i = 0; i < segment_cnt; i++)
802         {
803           int width_left = width - sfm_segment_effective_offset (width, i);
804           write_int (w, measure);
805           write_int (w, (i == 0 ? var_get_display_width (v)
806                          : var_default_display_width (width_left)));
807           write_int (w, alignment);
808         }
809     }
810 }
811
812 /* Writes the table of lengths for very long string variables. */
813 static void
814 write_vls_length_table (struct sfm_writer *w,
815                         const struct dictionary *dict)
816 {
817   struct string map;
818   int i;
819
820   ds_init_empty (&map);
821   for (i = 0; i < dict_get_var_cnt (dict); ++i)
822     {
823       const struct variable *v = dict_get_var (dict, i);
824       if (sfm_width_to_segments (var_get_width (v)) > 1)
825         ds_put_format (&map, "%s=%05d%c\t",
826                        var_get_short_name (v, 0), var_get_width (v), 0);
827     }
828   if (!ds_is_empty (&map))
829     write_utf8_record (w, dict_get_encoding (dict), &map, 14);
830   ds_destroy (&map);
831 }
832
833
834 static void
835 write_long_string_value_labels (struct sfm_writer *w,
836                                 const struct dictionary *dict)
837 {
838   size_t n_vars = dict_get_var_cnt (dict);
839   size_t size, i;
840   off_t start UNUSED;
841
842   /* Figure out the size in advance. */
843   size = 0;
844   for (i = 0; i < n_vars; i++)
845     {
846       struct variable *var = dict_get_var (dict, i);
847       const struct val_labs *val_labs = var_get_value_labels (var);
848       const char *encoding = var_get_encoding (var);
849       int width = var_get_width (var);
850       const struct val_lab *val_lab;
851
852       if (val_labs_count (val_labs) == 0 || width < 9)
853         continue;
854
855       size += 12;
856       size += recode_string_len (encoding, "UTF-8", var_get_name (var), -1);
857       for (val_lab = val_labs_first (val_labs); val_lab != NULL;
858            val_lab = val_labs_next (val_labs, val_lab))
859         {
860           size += 8 + width;
861           size += recode_string_len (encoding, "UTF-8",
862                                      val_lab_get_escaped_label (val_lab), -1);
863         }
864     }
865   if (size == 0)
866     return;
867
868   write_int (w, 7);             /* Record type. */
869   write_int (w, 21);            /* Record subtype */
870   write_int (w, 1);             /* Data item (byte) size. */
871   write_int (w, size);          /* Number of data items. */
872
873   start = ftello (w->file);
874   for (i = 0; i < n_vars; i++)
875     {
876       struct variable *var = dict_get_var (dict, i);
877       const struct val_labs *val_labs = var_get_value_labels (var);
878       const char *encoding = var_get_encoding (var);
879       int width = var_get_width (var);
880       const struct val_lab *val_lab;
881       char *var_name;
882
883       if (val_labs_count (val_labs) == 0 || width < 9)
884         continue;
885
886       var_name = recode_string (encoding, "UTF-8", var_get_name (var), -1);
887       write_int (w, strlen (var_name));
888       write_bytes (w, var_name, strlen (var_name));
889       free (var_name);
890
891       write_int (w, width);
892       write_int (w, val_labs_count (val_labs));
893       for (val_lab = val_labs_first (val_labs); val_lab != NULL;
894            val_lab = val_labs_next (val_labs, val_lab))
895         {
896           char *label;
897           size_t len;
898
899           write_int (w, width);
900           write_bytes (w, value_str (val_lab_get_value (val_lab), width),
901                        width);
902
903           label = recode_string (var_get_encoding (var), "UTF-8",
904                                  val_lab_get_escaped_label (val_lab), -1);
905           len = strlen (label);
906           write_int (w, len);
907           write_bytes (w, label, len);
908           free (label);
909         }
910     }
911   assert (ftello (w->file) == start + size);
912 }
913
914 static void
915 write_encoding_record (struct sfm_writer *w,
916                        const struct dictionary *d)
917 {
918   /* IANA says "...character set names may be up to 40 characters taken
919      from the printable characters of US-ASCII," so character set names
920      don't need to be recoded to be in UTF-8.
921
922      We convert encoding names to uppercase because SPSS writes encoding
923      names in uppercase. */
924   char *encoding = xstrdup (dict_get_encoding (d));
925   str_uppercase (encoding);
926   write_string_record (w, ss_cstr (encoding), 20);
927   free (encoding);
928 }
929
930 /* Writes the long variable name table. */
931 static void
932 write_longvar_table (struct sfm_writer *w, const struct dictionary *dict)
933 {
934   struct string map;
935   size_t i;
936
937   ds_init_empty (&map);
938   for (i = 0; i < dict_get_var_cnt (dict); i++)
939     {
940       struct variable *v = dict_get_var (dict, i);
941       if (i)
942         ds_put_byte (&map, '\t');
943       ds_put_format (&map, "%s=%s",
944                      var_get_short_name (v, 0), var_get_name (v));
945     }
946   write_utf8_record (w, dict_get_encoding (dict), &map, 13);
947   ds_destroy (&map);
948 }
949
950 /* Write integer information record. */
951 static void
952 write_integer_info_record (struct sfm_writer *w,
953                            const struct dictionary *d)
954 {
955   int version_component[3];
956   int float_format;
957   int codepage;
958
959   /* Parse the version string. */
960   memset (version_component, 0, sizeof version_component);
961   sscanf (bare_version, "%d.%d.%d",
962           &version_component[0], &version_component[1], &version_component[2]);
963
964   /* Figure out the floating-point format. */
965   if (FLOAT_NATIVE_64_BIT == FLOAT_IEEE_DOUBLE_LE
966       || FLOAT_NATIVE_64_BIT == FLOAT_IEEE_DOUBLE_BE)
967     float_format = 1;
968   else if (FLOAT_NATIVE_64_BIT == FLOAT_Z_LONG)
969     float_format = 2;
970   else if (FLOAT_NATIVE_64_BIT == FLOAT_VAX_D)
971     float_format = 3;
972   else
973     abort ();
974
975   /* Choose codepage. */
976   codepage = sys_get_codepage_from_encoding (dict_get_encoding (d));
977   if (codepage == 0)
978     {
979       /* Default to "7-bit ASCII" if the codepage number is unknown, because
980          many files use this codepage number regardless of their actual
981          encoding. */
982       codepage = 2;
983     }
984
985   /* Write record. */
986   write_int (w, 7);             /* Record type. */
987   write_int (w, 3);             /* Record subtype. */
988   write_int (w, 4);             /* Data item (int32) size. */
989   write_int (w, 8);             /* Number of data items. */
990   write_int (w, version_component[0]);
991   write_int (w, version_component[1]);
992   write_int (w, version_component[2]);
993   write_int (w, -1);          /* Machine code. */
994   write_int (w, float_format);
995   write_int (w, 1);           /* Compression code. */
996   write_int (w, INTEGER_NATIVE == INTEGER_MSB_FIRST ? 1 : 2);
997   write_int (w, codepage);
998 }
999
1000 /* Write floating-point information record. */
1001 static void
1002 write_float_info_record (struct sfm_writer *w)
1003 {
1004   write_int (w, 7);             /* Record type. */
1005   write_int (w, 4);             /* Record subtype. */
1006   write_int (w, 8);             /* Data item (flt64) size. */
1007   write_int (w, 3);             /* Number of data items. */
1008   write_float (w, SYSMIS);      /* System-missing value. */
1009   write_float (w, HIGHEST);     /* Value used for HIGHEST in missing values. */
1010   write_float (w, LOWEST);      /* Value used for LOWEST in missing values. */
1011 }
1012 \f
1013 /* Writes case C to system file W. */
1014 static void
1015 sys_file_casewriter_write (struct casewriter *writer, void *w_,
1016                            struct ccase *c)
1017 {
1018   struct sfm_writer *w = w_;
1019
1020   if (ferror (w->file))
1021     {
1022       casewriter_force_error (writer);
1023       case_unref (c);
1024       return;
1025     }
1026
1027   w->case_cnt++;
1028
1029   if (!w->compress)
1030     write_case_uncompressed (w, c);
1031   else
1032     write_case_compressed (w, c);
1033
1034   case_unref (c);
1035 }
1036
1037 /* Destroys system file writer W. */
1038 static void
1039 sys_file_casewriter_destroy (struct casewriter *writer, void *w_)
1040 {
1041   struct sfm_writer *w = w_;
1042   if (!close_writer (w))
1043     casewriter_force_error (writer);
1044 }
1045
1046 /* Returns true if an I/O error has occurred on WRITER, false otherwise. */
1047 static bool
1048 write_error (const struct sfm_writer *writer)
1049 {
1050   return ferror (writer->file);
1051 }
1052
1053 /* Closes a system file after we're done with it.
1054    Returns true if successful, false if an I/O error occurred. */
1055 static bool
1056 close_writer (struct sfm_writer *w)
1057 {
1058   bool ok;
1059
1060   if (w == NULL)
1061     return true;
1062
1063   ok = true;
1064   if (w->file != NULL)
1065     {
1066       /* Flush buffer. */
1067       if (w->opcode_cnt > 0)
1068         flush_compressed (w);
1069       fflush (w->file);
1070
1071       ok = !write_error (w);
1072
1073       /* Seek back to the beginning and update the number of cases.
1074          This is just a courtesy to later readers, so there's no need
1075          to check return values or report errors. */
1076       if (ok && w->case_cnt <= INT32_MAX && !fseeko (w->file, 80, SEEK_SET))
1077         {
1078           write_int (w, w->case_cnt);
1079           clearerr (w->file);
1080         }
1081
1082       if (fclose (w->file) == EOF)
1083         ok = false;
1084
1085       if (!ok)
1086         msg (ME, _("An I/O error occurred writing system file `%s'."),
1087              fh_get_file_name (w->fh));
1088
1089       if (ok ? !replace_file_commit (w->rf) : !replace_file_abort (w->rf))
1090         ok = false;
1091     }
1092
1093   fh_unlock (w->lock);
1094   fh_unref (w->fh);
1095
1096   free (w->sfm_vars);
1097   free (w);
1098
1099   return ok;
1100 }
1101
1102 /* System file writer casewriter class. */
1103 static const struct casewriter_class sys_file_casewriter_class =
1104   {
1105     sys_file_casewriter_write,
1106     sys_file_casewriter_destroy,
1107     NULL,
1108   };
1109 \f
1110 /* Writes case C to system file W, without compressing it. */
1111 static void
1112 write_case_uncompressed (struct sfm_writer *w, const struct ccase *c)
1113 {
1114   size_t i;
1115
1116   for (i = 0; i < w->sfm_var_cnt; i++)
1117     {
1118       struct sfm_var *v = &w->sfm_vars[i];
1119
1120       if (v->var_width == 0)
1121         write_float (w, case_num_idx (c, v->case_index));
1122       else
1123         {
1124           write_bytes (w, case_str_idx (c, v->case_index) + v->offset,
1125                        v->segment_width);
1126           write_spaces (w, v->padding);
1127         }
1128     }
1129 }
1130
1131 /* Writes case C to system file W, with compression. */
1132 static void
1133 write_case_compressed (struct sfm_writer *w, const struct ccase *c)
1134 {
1135   size_t i;
1136
1137   for (i = 0; i < w->sfm_var_cnt; i++)
1138     {
1139       struct sfm_var *v = &w->sfm_vars[i];
1140
1141       if (v->var_width == 0)
1142         {
1143           double d = case_num_idx (c, v->case_index);
1144           if (d == SYSMIS)
1145             put_cmp_opcode (w, 255);
1146           else if (d >= 1 - COMPRESSION_BIAS
1147                    && d <= 251 - COMPRESSION_BIAS
1148                    && d == (int) d)
1149             put_cmp_opcode (w, (int) d + COMPRESSION_BIAS);
1150           else
1151             {
1152               put_cmp_opcode (w, 253);
1153               put_cmp_number (w, d);
1154             }
1155         }
1156       else
1157         {
1158           int offset = v->offset;
1159           int width, padding;
1160
1161           /* This code properly deals with a width that is not a
1162              multiple of 8, by ensuring that the final partial
1163              oct (8 byte unit) is treated as padded with spaces
1164              on the right. */
1165           for (width = v->segment_width; width > 0; width -= 8, offset += 8)
1166             {
1167               const void *data = case_str_idx (c, v->case_index) + offset;
1168               int chunk_size = MIN (width, 8);
1169               if (!memcmp (data, "        ", chunk_size))
1170                 put_cmp_opcode (w, 254);
1171               else
1172                 {
1173                   put_cmp_opcode (w, 253);
1174                   put_cmp_string (w, data, chunk_size);
1175                 }
1176             }
1177
1178           /* This code deals properly with padding that is not a
1179              multiple of 8 bytes, by discarding the remainder,
1180              which was already effectively padded with spaces in
1181              the previous loop.  (Note that v->width + v->padding
1182              is always a multiple of 8.) */
1183           for (padding = v->padding / 8; padding > 0; padding--)
1184             put_cmp_opcode (w, 254);
1185         }
1186     }
1187 }
1188
1189 /* Flushes buffered compressed opcodes and data to W.
1190    The compression buffer must not be empty. */
1191 static void
1192 flush_compressed (struct sfm_writer *w)
1193 {
1194   assert (w->opcode_cnt > 0 && w->opcode_cnt <= 8);
1195
1196   write_bytes (w, w->opcodes, w->opcode_cnt);
1197   write_zeros (w, 8 - w->opcode_cnt);
1198
1199   write_bytes (w, w->data, w->data_cnt * sizeof *w->data);
1200
1201   w->opcode_cnt = w->data_cnt = 0;
1202 }
1203
1204 /* Appends OPCODE to the buffered set of compression opcodes in
1205    W.  Flushes the compression buffer beforehand if necessary. */
1206 static void
1207 put_cmp_opcode (struct sfm_writer *w, uint8_t opcode)
1208 {
1209   if (w->opcode_cnt >= 8)
1210     flush_compressed (w);
1211
1212   w->opcodes[w->opcode_cnt++] = opcode;
1213 }
1214
1215 /* Appends NUMBER to the buffered compression data in W.  The
1216    buffer must not be full; the way to assure that is to call
1217    this function only just after a call to put_cmp_opcode, which
1218    will flush the buffer as necessary. */
1219 static void
1220 put_cmp_number (struct sfm_writer *w, double number)
1221 {
1222   assert (w->opcode_cnt > 0);
1223   assert (w->data_cnt < 8);
1224
1225   convert_double_to_output_format (number, w->data[w->data_cnt++]);
1226 }
1227
1228 /* Appends SIZE bytes of DATA to the buffered compression data in
1229    W, followed by enough spaces to pad the output data to exactly
1230    8 bytes (thus, SIZE must be no greater than 8).  The buffer
1231    must not be full; the way to assure that is to call this
1232    function only just after a call to put_cmp_opcode, which will
1233    flush the buffer as necessary. */
1234 static void
1235 put_cmp_string (struct sfm_writer *w, const void *data, size_t size)
1236 {
1237   assert (w->opcode_cnt > 0);
1238   assert (w->data_cnt < 8);
1239   assert (size <= 8);
1240
1241   memset (w->data[w->data_cnt], ' ', 8);
1242   memcpy (w->data[w->data_cnt], data, size);
1243   w->data_cnt++;
1244 }
1245 \f
1246 /* Writes 32-bit integer X to the output file for writer W. */
1247 static void
1248 write_int (struct sfm_writer *w, int32_t x)
1249 {
1250   write_bytes (w, &x, sizeof x);
1251 }
1252
1253 /* Converts NATIVE to the 64-bit format used in output files in
1254    OUTPUT. */
1255 static inline void
1256 convert_double_to_output_format (double native, uint8_t output[8])
1257 {
1258   /* If "double" is not a 64-bit type, then convert it to a
1259      64-bit type.  Otherwise just copy it. */
1260   if (FLOAT_NATIVE_DOUBLE != FLOAT_NATIVE_64_BIT)
1261     float_convert (FLOAT_NATIVE_DOUBLE, &native, FLOAT_NATIVE_64_BIT, output);
1262   else
1263     memcpy (output, &native, sizeof native);
1264 }
1265
1266 /* Writes floating-point number X to the output file for writer
1267    W. */
1268 static void
1269 write_float (struct sfm_writer *w, double x)
1270 {
1271   uint8_t output[8];
1272   convert_double_to_output_format (x, output);
1273   write_bytes (w, output, sizeof output);
1274 }
1275
1276 /* Writes contents of VALUE with the given WIDTH to W, padding
1277    with zeros to a multiple of 8 bytes.
1278    To avoid a branch, and because we don't actually need to
1279    support it, WIDTH must be no bigger than 8. */
1280 static void
1281 write_value (struct sfm_writer *w, const union value *value, int width)
1282 {
1283   assert (width <= 8);
1284   if (width == 0)
1285     write_float (w, value->f);
1286   else
1287     {
1288       write_bytes (w, value_str (value, width), width);
1289       write_zeros (w, 8 - width);
1290     }
1291 }
1292
1293 /* Writes null-terminated STRING in a field of the given WIDTH to W.  If STRING
1294    is longer than WIDTH, it is truncated; if STRING is shorter than WIDTH, it
1295    is padded on the right with spaces. */
1296 static void
1297 write_string (struct sfm_writer *w, const char *string, size_t width)
1298 {
1299   size_t data_bytes = MIN (strlen (string), width);
1300   size_t pad_bytes = width - data_bytes;
1301   write_bytes (w, string, data_bytes);
1302   while (pad_bytes-- > 0)
1303     putc (' ', w->file);
1304 }
1305
1306 /* Recodes null-terminated UTF-8 encoded STRING into ENCODING, and writes the
1307    recoded version in a field of the given WIDTH to W.  The string is truncated
1308    or padded on the right with spaces to exactly WIDTH bytes. */
1309 static void
1310 write_utf8_string (struct sfm_writer *w, const char *encoding,
1311                    const char *string, size_t width)
1312 {
1313   char *s = recode_string (encoding, "UTF-8", string, -1);
1314   write_string (w, s, width);
1315   free (s);
1316 }
1317
1318 /* Writes a record with type 7, subtype SUBTYPE that contains CONTENT recoded
1319    from UTF-8 encoded into ENCODING. */
1320 static void
1321 write_utf8_record (struct sfm_writer *w, const char *encoding,
1322                    const struct string *content, int subtype)
1323 {
1324   struct substring s;
1325
1326   s = recode_substring_pool (encoding, "UTF-8", ds_ss (content), NULL);
1327   write_string_record (w, s, subtype);
1328   ss_dealloc (&s);
1329 }
1330
1331 /* Writes a record with type 7, subtype SUBTYPE that contains the string
1332    CONTENT. */
1333 static void
1334 write_string_record (struct sfm_writer *w,
1335                      const struct substring content, int subtype)
1336 {
1337   write_int (w, 7);
1338   write_int (w, subtype);
1339   write_int (w, 1);
1340   write_int (w, ss_length (content));
1341   write_bytes (w, ss_data (content), ss_length (content));
1342 }
1343
1344 /* Writes SIZE bytes of DATA to W's output file. */
1345 static void
1346 write_bytes (struct sfm_writer *w, const void *data, size_t size)
1347 {
1348   fwrite (data, 1, size, w->file);
1349 }
1350
1351 /* Writes N zeros to W's output file. */
1352 static void
1353 write_zeros (struct sfm_writer *w, size_t n)
1354 {
1355   while (n-- > 0)
1356     putc (0, w->file);
1357 }
1358
1359 /* Writes N spaces to W's output file. */
1360 static void
1361 write_spaces (struct sfm_writer *w, size_t n)
1362 {
1363   while (n-- > 0)
1364     putc (' ', w->file);
1365 }