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