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