checkin of 0.3.0
[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 <stdlib.h>
26 #include "alloc.h"
27 #include "command.h"
28 #include "error.h"
29 #include "lexer.h"
30 #include "misc.h"
31 #include "str.h"
32 #include "var.h"
33 #include "vfm.h"
34
35 /* Variables to transpose. */
36 static struct variable **var;
37 static int nvar;
38
39 /* Variable containing new variable names. */
40 static struct variable *newnames;
41
42 /* List of variable names. */
43 struct varname
44   {
45     struct varname *next;
46     char name[1];
47   };
48
49 /* New variable names. */
50 static struct varname *new_names_head, *new_names_tail;
51 static int case_count;
52
53 static int build_dictionary (void);
54
55 /* Parses and executes FLIP. */
56 int
57 cmd_flip (void)
58 {
59   lex_match_id ("FLIP");
60   lex_match ('/');
61   if (lex_match_id ("VARIABLES"))
62     {
63       lex_match ('=');
64       if (!parse_variables (&default_dict, &var, &nvar, PV_NO_DUPLICATE))
65         return CMD_FAILURE;
66       lex_match ('/');
67     }
68   else
69     fill_all_vars (&var, &nvar, FV_NO_SYSTEM);
70
71   lex_match ('/');
72   if (lex_match_id ("NEWNAMES"))
73     {
74       lex_match ('=');
75       newnames = parse_variable ();
76       if (!newnames)
77         {
78           free (var);
79           return CMD_FAILURE;
80         }
81     }
82   else
83     newnames = find_variable ("CASE_LBL");
84
85   if (newnames)
86     {
87       int i;
88       
89       for (i = 0; i < nvar; i++)
90         if (var[i] == newnames)
91           {
92             memcpy (&var[i], &var[i + 1], sizeof *var * (nvar - i - 1));
93             nvar--;
94             break;
95           }
96     }
97
98   case_count = 0;
99   temp_trns = temporary = 0;
100   vfm_sink = &flip_stream;
101   new_names_tail = NULL;
102   procedure (NULL, NULL, NULL);
103
104   clear_default_dict ();
105   if (!build_dictionary ())
106     {
107       discard_variables ();
108       free (var);
109       return CMD_FAILURE;
110     }
111
112   free (var);
113   return lex_end_of_command ();
114 }
115
116 /* Make a new variable with base name NAME, which is bowdlerized and
117    mangled until acceptable, and returns success. */
118 static int
119 make_new_var (char name[])
120 {
121   /* Fix invalid characters. */
122   {
123     char *cp;
124   
125     for (cp = name; *cp && !isspace (*cp); cp++)
126       {
127         *cp = toupper ((unsigned char) *cp);
128         if (!isalpha (*cp) && *cp != '@' && *cp != '#'
129             && (cp == name || (*cp != '.' && *cp != '$' && *cp != '_')))
130           {
131             if (cp == name)
132               *cp = 'V';        /* _ not valid in first position. */
133             else
134               *cp = '_';
135           }
136       }
137     *cp = 0;
138   }
139   
140   if (create_variable (&default_dict, name, NUMERIC, 0))
141     return 1;
142
143   /* Add numeric extensions until acceptable. */
144   {
145     int len = (int) strlen (name);
146     char n[9];
147     int i;
148
149     for (i = 1; i < 10000000; i++)
150       {
151         int ofs = min (7 - intlog10 (i), len);
152         memcpy (n, name, ofs);
153         sprintf (&n[ofs], "%d", i);
154
155         if (create_variable (&default_dict, n, NUMERIC, 0))
156           return 1;
157       }
158   }
159
160   msg (SE, _("Could not create acceptable variant for variable %s."), name);
161   return 0;
162 }
163
164 /* Make a new dictionary for all the new variable names. */
165 static int
166 build_dictionary (void)
167 {
168   force_create_variable (&default_dict, "CASE_LBL", ALPHA, 8);
169
170   if (!new_names_tail)
171     {
172       int i;
173       
174       if (case_count > 99999)
175         {
176           msg (SE, _("Cannot create more than 99999 variable names."));
177           return 0;
178         }
179       
180       for (i = 0; i < case_count; i++)
181         {
182           char s[9];
183
184           sprintf (s, "VAR%03d", i);
185           force_create_variable (&default_dict, s, NUMERIC, 0);
186         }
187     }
188   else
189     {
190       struct varname *v, *n;
191
192       new_names_tail->next = NULL;
193       for (v = new_names_head; v; v = n)
194         {
195           n = v->next;
196           if (!make_new_var (v->name))
197             {
198               for (; v; v = n)
199                 {
200                   n = v->next;
201                   free (v);
202                 }
203               return 0;
204             }
205           free (v);
206         }
207     }
208   
209   return 1;
210 }
211      
212
213 /* Each case to be transposed. */
214 struct flip_case
215   {
216     struct flip_case *next;
217     double v[1];
218   };
219
220 /* Sink: Cases during transposition. */
221 static int internal;                    /* Internal vs. external flipping. */
222 static char *sink_old_names;            /* Old variable names. */
223 static unsigned long sink_cases;        /* Number of cases. */
224 static struct flip_case *head, *tail;   /* internal == 1: Cases. */
225 static FILE *sink_file;                 /* internal == 0: Temporary file. */
226
227 /* Source: Cases after transposition. */
228 static struct flip_case *src;           /* Internal transposition records. */
229 static char *src_old_names;             /* Old variable names. */
230 static unsigned long src_cases;         /* Number of cases. */
231 static FILE *src_file;                  /* src == NULL: Temporary file. */
232
233 /* Initialize the FLIP stream. */
234 static void 
235 flip_stream_init (void)
236 {
237   internal = 1;
238   sink_cases = 0;
239   tail = NULL;
240   
241   {
242     size_t n = nvar;
243     char *p;
244     int i;
245     
246     for (i = 0; i < nvar; i++)
247       n += strlen (var[i]->name);
248     p = sink_old_names = xmalloc (n);
249     for (i = 0; i < nvar; i++)
250       p = stpcpy (p, var[i]->name) + 1;
251   }
252 }
253
254 /* Reads the FLIP stream and passes it to write_case(). */
255 static void
256 flip_stream_read (void)
257 {
258   if (src || (src == NULL && src_file == NULL))
259     {
260       /* Internal transposition, or empty file. */
261       int i, j;
262       char *p = src_old_names;
263       
264       for (i = 0; i < nvar; i++)
265         {
266           struct flip_case *iter;
267           
268           st_bare_pad_copy (temp_case->data[0].s, p, 8);
269           p = strchr (p, 0) + 1;
270
271           for (iter = src, j = 1; iter; iter = iter->next, j++)
272             temp_case->data[j].f = iter->v[i];
273
274           if (!write_case ())
275             return;
276         }
277     }
278   else
279     {
280       int i;
281       char *p = src_old_names;
282       
283       for (i = 0; i < nvar; i++)
284         {
285           st_bare_pad_copy (temp_case->data[0].s, p, 8);
286           p = strchr (p, 0) + 1;
287
288           if (fread (&temp_case->data[1], sizeof (double), src_cases,
289                      src_file) != src_cases)
290             msg (FE, _("Error reading FLIP source file: %s."),
291                  strerror (errno));
292
293           if (!write_case ())
294             return;
295         }
296     }
297 }
298
299 /* Writes temp_case to the FLIP stream. */
300 static void
301 flip_stream_write (void)
302 {
303   sink_cases++;
304
305   if (newnames)
306     {
307       struct varname *v;
308       char name[INT_DIGITS + 2];
309
310       if (newnames->type == NUMERIC)
311         sprintf (name, "V%d", (int) temp_case->data[newnames->fv].f);
312       else
313         {
314           int width = min (newnames->width, 8);
315           memcpy (name, temp_case->data[newnames->fv].s, width);
316           name[width] = 0;
317         }
318
319       v = xmalloc (sizeof (struct varname) + strlen (name) - 1);
320       strcpy (v->name, name);
321       
322       if (new_names_tail == NULL)
323         new_names_head = v;
324       else
325         new_names_tail->next = v;
326       new_names_tail = v;
327     }
328   else
329     case_count++;
330
331   if (internal)
332     {
333 #if 0
334       flip_case *c = malloc (sizeof (flip_case)
335                              + sizeof (double) * (nvar - 1));
336       
337       if (c != NULL)
338         {
339           /* Write to internal file. */
340           int i;
341
342           for (i = 0; i < nvar; i++)
343             if (var[i]->type == NUMERIC)
344               c->v[i] = temp_case->data[var[i]->fv].f;
345             else
346               c->v[i] = SYSMIS;
347
348           if (tail == NULL)
349             head = c;
350           else
351             tail->next = c;
352           tail = c;
353           
354           return;
355         }
356       else
357 #endif
358         {
359           /* Initialize external file. */
360           struct flip_case *iter, *next;
361
362           internal = 0;
363
364           sink_file = tmpfile ();
365           if (!sink_file)
366             msg (FE, _("Could not create temporary file for FLIP."));
367
368           if (tail)
369             tail->next = NULL;
370           for (iter = head; iter; iter = next)
371             {
372               next = iter->next;
373
374               if (fwrite (iter->v, sizeof (double), nvar, sink_file)
375                   != (size_t) nvar)
376                 msg (FE, _("Error writing FLIP file: %s."),
377                      strerror (errno));
378               free (iter);
379             }
380         }
381     }
382
383   /* Write to external file. */
384   {
385     double *d = local_alloc (sizeof *d * nvar);
386     int i;
387
388     for (i = 0; i < nvar; i++)
389       if (var[i]->type == NUMERIC)
390         d[i] = temp_case->data[var[i]->fv].f;
391       else
392         d[i] = SYSMIS;
393           
394     if (fwrite (d, sizeof *d, nvar, sink_file) != (size_t) nvar)
395       msg (FE, _("Error writing FLIP file: %s."),
396            strerror (errno));
397
398     local_free (d);
399   }
400 }
401       
402 /* Transpose the external file. */
403 static void
404 transpose_external_file (void)
405 {
406   unsigned long n_cases;
407   unsigned long cur_case;
408   double *case_buf, *temp_buf;
409
410   n_cases = 4 * 1024 * 1024 / ((nvar + 1) * sizeof *case_buf);
411   if (n_cases < 2)
412     n_cases = 2;
413   for (;;)
414     {
415       assert (n_cases >= 2 /* 1 */);
416       case_buf = ((n_cases <= 2 ? xmalloc : (void *(*)(size_t)) malloc)
417                   ((nvar + 1) * sizeof *case_buf * n_cases));
418       if (case_buf)
419         break;
420
421       n_cases /= 2;
422       if (n_cases < 2)
423         n_cases = 2;
424     }
425
426   /* A temporary buffer that holds n_cases elements. */
427   temp_buf = &case_buf[nvar * n_cases];
428
429   src_file = tmpfile ();
430   if (!src_file)
431     msg (FE, _("Error creating FLIP source file."));
432   
433   if (fseek (sink_file, 0, SEEK_SET) != 0)
434     msg (FE, _("Error rewinding FLIP file: %s."), strerror (errno));
435
436   for (cur_case = 0; cur_case < sink_cases; )
437     {
438       unsigned long read_cases = min (sink_cases - cur_case, n_cases);
439       int i;
440
441       if (read_cases != fread (case_buf, sizeof *case_buf * nvar,
442                                read_cases, sink_file))
443         msg (FE, _("Error reading FLIP file: %s."), strerror (errno));
444
445       for (i = 0; i < nvar; i++)
446         {
447           unsigned long j;
448           
449           for (j = 0; j < read_cases; j++)
450             temp_buf[j] = case_buf[i + j * nvar];
451
452           if (fseek (src_file,
453                      sizeof *case_buf * (cur_case + i * sink_cases),
454                      SEEK_SET) != 0)
455             msg (FE, _("Error seeking FLIP source file: %s."),
456                        strerror (errno));
457
458           if (fwrite (temp_buf, sizeof *case_buf, read_cases, src_file)
459               != read_cases)
460             msg (FE, _("Error writing FLIP source file: %s."),
461                  strerror (errno));
462         }
463
464       cur_case += read_cases;
465     }
466
467   if (fseek (src_file, 0, SEEK_SET) != 0)
468     msg (FE, _("Error rewind FLIP source file: %s."), strerror (errno));
469
470   fclose (sink_file);
471
472   free (case_buf);
473 }
474
475 /* Change the FLIP stream from sink to source mode. */
476 static void
477 flip_stream_mode (void)
478 {
479   src_cases = sink_cases;
480   src_old_names = sink_old_names;
481   sink_old_names = NULL;
482   
483   if (internal)
484     {
485       if (tail)
486         {
487           tail->next = NULL;
488           src = head;
489         }
490       else
491         {
492           src = NULL;
493           src_file = NULL;
494         }
495     }
496   else
497     {
498       src = NULL;
499       transpose_external_file ();
500     }
501 }
502
503 /* Destroy source's internal data. */
504 static void
505 flip_stream_destroy_source (void)
506 {
507   free (src_old_names);
508   if (internal)
509     {
510       struct flip_case *iter, *next;
511
512       for (iter = src; iter; iter = next)
513         {
514           next = iter->next;
515           free (iter);
516         }
517     }
518   else
519     fclose (src_file);
520 }
521
522 /* Destroy sink's internal data. */
523 static void
524 flip_stream_destroy_sink (void)
525 {
526   struct flip_case *iter, *next;
527   
528   free (sink_old_names);
529   if (tail == NULL)
530     return;
531
532   tail->next = NULL;
533   for (iter = head; iter; iter = next)
534     {
535       next = iter->next;
536       free (iter);
537     }
538 }
539
540 struct case_stream flip_stream = 
541   {
542     flip_stream_init,
543     flip_stream_read,
544     flip_stream_write,
545     flip_stream_mode,
546     flip_stream_destroy_source,
547     flip_stream_destroy_sink,
548     "FLIP",
549   };