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