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