Adopt use of gnulib for portability.
[pspp-builds.git] / src / flip.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 "error.h"
22 #include <ctype.h>
23 #include <errno.h>
24 #include <float.h>
25 #include <limits.h>
26 #include <stdlib.h>
27 #include "algorithm.h"
28 #include "alloc.h"
29 #include "case.h"
30 #include "command.h"
31 #include "dictionary.h"
32 #include "error.h"
33 #include "lexer.h"
34 #include "misc.h"
35 #include "settings.h"
36 #include "str.h"
37 #include "val.h"
38 #include "var.h"
39 #include "vfm.h"
40
41 #ifdef HAVE_SYS_TYPES_H
42 #include <sys/types.h>
43 #endif
44
45 #include "gettext.h"
46 #define _(msgid) gettext (msgid)
47
48 /* List of variable names. */
49 struct varname
50   {
51     struct varname *next;
52     char name[SHORT_NAME_LEN + 1];
53   };
54
55 /* Represents a FLIP input program. */
56 struct flip_pgm 
57   {
58     struct variable **var;      /* Variables to transpose. */
59     int *idx_to_fv;             /* var[]->index to compacted sink case fv. */
60     int var_cnt;                /* Number of elements in `var'. */
61     int case_cnt;               /* Pre-flip case count. */
62     size_t case_size;           /* Post-flip bytes per case. */
63
64     struct variable *new_names; /* Variable containing new variable names. */
65     struct varname *new_names_head; /* First new variable. */
66     struct varname *new_names_tail; /* Last new variable. */
67
68     FILE *file;                 /* Temporary file containing data. */
69   };
70
71 static void destroy_flip_pgm (struct flip_pgm *);
72 static struct case_sink *flip_sink_create (struct flip_pgm *);
73 static struct case_source *flip_source_create (struct flip_pgm *);
74 static void flip_file (struct flip_pgm *);
75 static int build_dictionary (struct flip_pgm *);
76
77 static const struct case_source_class flip_source_class;
78 static const struct case_sink_class flip_sink_class;
79
80 /* Parses and executes FLIP. */
81 int
82 cmd_flip (void)
83 {
84   struct flip_pgm *flip;
85
86   if (temporary != 0)
87     {
88       msg (SM, _("FLIP ignores TEMPORARY.  "
89                  "Temporary transformations will be made permanent."));
90       cancel_temporary (); 
91     }
92
93   flip = xmalloc (sizeof *flip);
94   flip->var = NULL;
95   flip->idx_to_fv = dict_get_compacted_idx_to_fv (default_dict);
96   flip->var_cnt = 0;
97   flip->case_cnt = 0;
98   flip->new_names = NULL;
99   flip->new_names_head = NULL;
100   flip->new_names_tail = NULL;
101   flip->file = NULL;
102
103   lex_match ('/');
104   if (lex_match_id ("VARIABLES"))
105     {
106       lex_match ('=');
107       if (!parse_variables (default_dict, &flip->var, &flip->var_cnt, PV_NO_DUPLICATE))
108         return CMD_FAILURE;
109       lex_match ('/');
110     }
111   else
112     dict_get_vars (default_dict, &flip->var, &flip->var_cnt, 1u << DC_SYSTEM);
113
114   lex_match ('/');
115   if (lex_match_id ("NEWNAMES"))
116     {
117       lex_match ('=');
118       flip->new_names = parse_variable ();
119       if (!flip->new_names)
120         goto error;
121     }
122   else
123     flip->new_names = dict_lookup_var (default_dict, "CASE_LBL");
124
125   if (flip->new_names)
126     {
127       int i;
128       
129       for (i = 0; i < flip->var_cnt; i++)
130         if (flip->var[i] == flip->new_names)
131           {
132             remove_element (flip->var, flip->var_cnt, sizeof *flip->var, i);
133             flip->var_cnt--;
134             break;
135           }
136     }
137
138   /* Read the active file into a flip_sink. */
139   flip->case_cnt = 0;
140   temp_trns = temporary = 0;
141   vfm_sink = flip_sink_create (flip);
142   flip->new_names_tail = NULL;
143   procedure (NULL, NULL);
144
145   /* Flip the data we read. */
146   flip_file (flip);
147
148   /* Flip the dictionary. */
149   dict_clear (default_dict);
150   if (!build_dictionary (flip))
151     {
152       discard_variables ();
153       goto error;
154     }
155   flip->case_size = dict_get_case_size (default_dict);
156
157   /* Set up flipped data for reading. */
158   vfm_source = flip_source_create (flip);
159
160   return lex_end_of_command ();
161
162  error:
163   destroy_flip_pgm (flip);
164   return CMD_FAILURE;
165 }
166
167 /* Destroys FLIP. */
168 static void
169 destroy_flip_pgm (struct flip_pgm *flip) 
170 {
171   struct varname *iter, *next;
172   
173   free (flip->var);
174   free (flip->idx_to_fv);
175   for (iter = flip->new_names_head; iter != NULL; iter = next) 
176     {
177       next = iter->next;
178       free (iter);
179     }
180   if (flip->file != NULL)
181     fclose (flip->file);
182   free (flip);
183 }
184
185 /* Make a new variable with base name NAME, which is bowdlerized and
186    mangled until acceptable, and returns success. */
187 static int
188 make_new_var (char name[])
189 {
190   char *cp;
191
192   /* Trim trailing spaces. */
193   cp = strchr (name, '\0');
194   while (cp > name && isspace ((unsigned char) cp[-1]))
195     *--cp = '\0';
196
197   /* Fix invalid characters. */
198   for (cp = name; *cp && cp < name + SHORT_NAME_LEN; cp++)
199     if (cp == name) 
200       {
201         if (!CHAR_IS_ID1 (*cp) || *cp == '$')
202           *cp = 'V';
203       }
204     else
205       {
206         if (!CHAR_IS_IDN (*cp))
207           *cp = '_'; 
208       }
209   *cp = '\0';
210   str_uppercase (name);
211   
212   if (dict_create_var (default_dict, name, 0))
213     return 1;
214
215   /* Add numeric extensions until acceptable. */
216   {
217     const int len = (int) strlen (name);
218     char n[SHORT_NAME_LEN + 1];
219     int i;
220
221     for (i = 1; i < 10000000; i++)
222       {
223         int ofs = min (7 - intlog10 (i), len);
224         memcpy (n, name, ofs);
225         sprintf (&n[ofs], "%d", i);
226
227         if (dict_create_var (default_dict, n, 0))
228           return 1;
229       }
230   }
231
232   msg (SE, _("Could not create acceptable variant for variable %s."), name);
233   return 0;
234 }
235
236 /* Make a new dictionary for all the new variable names. */
237 static int
238 build_dictionary (struct flip_pgm *flip)
239 {
240   dict_create_var_assert (default_dict, "CASE_LBL", 8);
241
242   if (flip->new_names_head == NULL)
243     {
244       int i;
245       
246       if (flip->case_cnt > 99999)
247         {
248           msg (SE, _("Cannot create more than 99999 variable names."));
249           return 0;
250         }
251       
252       for (i = 0; i < flip->case_cnt; i++)
253         {
254           struct variable *v;
255           char s[SHORT_NAME_LEN + 1];
256
257           sprintf (s, "VAR%03d", i);
258           v = dict_create_var_assert (default_dict, s, 0);
259         }
260     }
261   else
262     {
263       struct varname *v;
264
265       for (v = flip->new_names_head; v; v = v->next)
266         if (!make_new_var (v->name))
267           return 0;
268     }
269   
270   return 1;
271 }
272      
273 /* Cases during transposition. */
274 struct flip_sink_info 
275   {
276     struct flip_pgm *flip;              /* FLIP program. */
277     union value *output_buf;            /* Case output buffer. */
278   };
279
280 /* Creates a flip sink based on FLIP. */
281 static struct case_sink *
282 flip_sink_create (struct flip_pgm *flip) 
283 {
284   struct flip_sink_info *info = xmalloc (sizeof *info);
285   int i;
286
287   info->flip = flip;
288   info->output_buf = xmalloc (sizeof *info->output_buf * flip->var_cnt);
289
290   flip->file = tmpfile ();
291   if (!flip->file)
292     msg (FE, _("Could not create temporary file for FLIP."));
293
294   /* Write variable names as first case. */
295   for (i = 0; i < flip->var_cnt; i++) 
296     buf_copy_str_rpad (info->output_buf[i].s, MAX_SHORT_STRING,
297                        flip->var[i]->name);
298   if (fwrite (info->output_buf, sizeof *info->output_buf,
299               flip->var_cnt, flip->file) != (size_t) flip->var_cnt)
300     msg (FE, _("Error writing FLIP file: %s."), strerror (errno));
301
302   flip->case_cnt = 1;
303
304   return create_case_sink (&flip_sink_class, default_dict, info);
305 }
306
307 /* Writes case C to the FLIP sink. */
308 static void
309 flip_sink_write (struct case_sink *sink, const struct ccase *c)
310 {
311   struct flip_sink_info *info = sink->aux;
312   struct flip_pgm *flip = info->flip;
313   int i;
314   
315   flip->case_cnt++;
316
317   if (flip->new_names != NULL)
318     {
319       struct varname *v = xmalloc (sizeof (struct varname));
320       v->next = NULL;
321       if (flip->new_names->type == NUMERIC) 
322         {
323           double f = case_num (c, flip->idx_to_fv[flip->new_names->index]);
324
325           if (f == SYSMIS)
326             strcpy (v->name, "VSYSMIS");
327           else if (f < INT_MIN)
328             strcpy (v->name, "VNEGINF");
329           else if (f > INT_MAX)
330             strcpy (v->name, "VPOSINF");
331           else 
332             {
333               char name[INT_DIGITS + 2];
334               sprintf (name, "V%d", (int) f);
335               str_copy_trunc (v->name, sizeof v->name, name);
336             }
337         }
338       else
339         {
340           int width = min (flip->new_names->width, MAX_SHORT_STRING);
341           memcpy (v->name, case_str (c, flip->idx_to_fv[flip->new_names->index]),
342                   width);
343           v->name[width] = 0;
344         }
345       
346       if (flip->new_names_head == NULL)
347         flip->new_names_head = v;
348       else
349         flip->new_names_tail->next = v;
350       flip->new_names_tail = v;
351     }
352
353   /* Write to external file. */
354   for (i = 0; i < flip->var_cnt; i++)
355     {
356       double out;
357       
358       if (flip->var[i]->type == NUMERIC)
359         out = case_num (c, flip->idx_to_fv[flip->var[i]->index]);
360       else
361         out = SYSMIS;
362       info->output_buf[i].f = out;
363     }
364           
365   if (fwrite (info->output_buf, sizeof *info->output_buf,
366               flip->var_cnt, flip->file) != (size_t) flip->var_cnt)
367     msg (FE, _("Error writing FLIP file: %s."), strerror (errno));
368 }
369
370 /* Transposes the external file into a new file. */
371 static void
372 flip_file (struct flip_pgm *flip)
373 {
374   size_t case_bytes;
375   size_t case_capacity;
376   size_t case_idx;
377   union value *input_buf, *output_buf;
378   FILE *input_file, *output_file;
379
380   /* Allocate memory for many cases. */
381   case_bytes = flip->var_cnt * sizeof *input_buf;
382   case_capacity = get_max_workspace() / case_bytes;
383   if (case_capacity > flip->case_cnt * 2)
384     case_capacity = flip->case_cnt * 2;
385   if (case_capacity < 2)
386     case_capacity = 2;
387   for (;;)
388     {
389       size_t bytes = case_bytes * case_capacity;
390       if (case_capacity > 2)
391         input_buf = malloc (bytes);
392       else
393         input_buf = xmalloc (bytes);
394       if (input_buf != NULL)
395         break;
396
397       case_capacity /= 2;
398       if (case_capacity < 2)
399         case_capacity = 2;
400     }
401
402   /* Use half the allocated memory for input_buf, half for
403      output_buf. */
404   case_capacity /= 2;
405   output_buf = input_buf + flip->var_cnt * case_capacity;
406
407   input_file = flip->file;
408   if (fseek (input_file, 0, SEEK_SET) != 0)
409     msg (FE, _("Error rewinding FLIP file: %s."), strerror (errno));
410
411   output_file = tmpfile ();
412   if (output_file == NULL)
413     msg (FE, _("Error creating FLIP source file."));
414   
415   for (case_idx = 0; case_idx < flip->case_cnt; )
416     {
417       unsigned long read_cases = min (flip->case_cnt - case_idx,
418                                       case_capacity);
419       int i;
420
421       if (read_cases != fread (input_buf, case_bytes, read_cases, input_file))
422         msg (FE, _("Error reading FLIP file: %s."), strerror (errno));
423
424       for (i = 0; i < flip->var_cnt; i++)
425         {
426           unsigned long j;
427           
428           for (j = 0; j < read_cases; j++)
429             output_buf[j] = input_buf[i + j * flip->var_cnt];
430
431 #ifndef HAVE_FSEEKO
432 #define fseeko fseek
433 #endif
434
435 #ifndef HAVE_OFF_T
436 #define off_t long int
437 #endif
438
439           if (fseeko (output_file,
440                       sizeof *input_buf * (case_idx
441                                            + (off_t) i * flip->case_cnt),
442                       SEEK_SET) != 0)
443             msg (FE, _("Error seeking FLIP source file: %s."),
444                        strerror (errno));
445
446           if (fwrite (output_buf, sizeof *output_buf, read_cases, output_file)
447               != read_cases)
448             msg (FE, _("Error writing FLIP source file: %s."),
449                  strerror (errno));
450         }
451
452       case_idx += read_cases;
453     }
454
455   fclose (input_file);
456   free (input_buf);
457   
458   if (fseek (output_file, 0, SEEK_SET) != 0)
459     msg (FE, _("Error rewind FLIP source file: %s."), strerror (errno));
460   flip->file = output_file;
461 }
462
463 /* Destroy sink's internal data. */
464 static void
465 flip_sink_destroy (struct case_sink *sink)
466 {
467   struct flip_sink_info *info = sink->aux;
468
469   free (info->output_buf);
470   free (info);
471 }
472
473 /* FLIP sink class. */
474 static const struct case_sink_class flip_sink_class = 
475   {
476     "FLIP",
477     NULL,
478     flip_sink_write,
479     flip_sink_destroy,
480     NULL,
481   };
482
483 /* Creates and returns a FLIP source based on PGM,
484    which should have already been used as a sink. */
485 static struct case_source *
486 flip_source_create (struct flip_pgm *pgm)
487 {
488   return create_case_source (&flip_source_class, pgm);
489 }
490
491 /* Reads the FLIP stream.  Copies each case into C and calls
492    WRITE_CASE passing WC_DATA. */
493 static void
494 flip_source_read (struct case_source *source,
495                   struct ccase *c,
496                   write_case_func *write_case, write_case_data wc_data)
497 {
498   struct flip_pgm *flip = source->aux;
499   union value *input_buf;
500   int i;
501
502   input_buf = xmalloc (sizeof *input_buf * flip->case_cnt);
503   for (i = 0; i < flip->var_cnt; i++)
504     {
505       size_t j;
506       
507       if (fread (input_buf, sizeof *input_buf, flip->case_cnt,
508                  flip->file) != flip->case_cnt) 
509         {
510           if (ferror (flip->file))
511             msg (SE, _("Error reading FLIP temporary file: %s."),
512                  strerror (errno));
513           else if (feof (flip->file))
514             msg (SE, _("Unexpected end of file reading FLIP temporary file."));
515           else
516             assert (0);
517           break;
518         }
519
520       for (j = 0; j < flip->case_cnt; j++)
521         case_data_rw (c, j)->f = input_buf[j].f;
522       if (!write_case (wc_data))
523         break;
524     }
525   free (input_buf);
526 }
527
528 /* Destroy internal data in SOURCE. */
529 static void
530 flip_source_destroy (struct case_source *source)
531 {
532   struct flip_pgm *flip = source->aux;
533
534   destroy_flip_pgm (flip);
535 }
536
537 static const struct case_source_class flip_source_class = 
538   {
539     "FLIP",
540     NULL,
541     flip_source_read,
542     flip_source_destroy
543   };