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