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