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