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