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