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