Fix warnings in flip command.
[pspp-builds.git] / src / language / stats / flip.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2009 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include "config.h"
18
19 #include <ctype.h>
20 #include <errno.h>
21 #include <float.h>
22 #include <limits.h>
23 #include <stdlib.h>
24
25 #include <data/case.h>
26 #include <data/casereader.h>
27 #include <data/casereader-provider.h>
28 #include <data/dictionary.h>
29 #include <data/procedure.h>
30 #include <data/settings.h>
31 #include <data/short-names.h>
32 #include <data/value.h>
33 #include <data/variable.h>
34 #include <language/command.h>
35 #include <language/lexer/lexer.h>
36 #include <language/lexer/variable-parser.h>
37 #include <libpspp/array.h>
38 #include <libpspp/assertion.h>
39 #include <libpspp/message.h>
40 #include <libpspp/misc.h>
41 #include <libpspp/pool.h>
42 #include <libpspp/str.h>
43 #include <data/data-in.h>
44 #include <data/data-out.h>
45 #include "intprops.h"
46 #include "minmax.h"
47 #include "xalloc.h"
48
49 #include "gettext.h"
50 #define _(msgid) gettext (msgid)
51
52 /* List of variable names. */
53 struct var_names
54   {
55     const char **names;
56     size_t n_names, allocated_names;
57   };
58
59 static void var_names_init (struct var_names *);
60 static void var_names_add (struct pool *, struct var_names *, const char *);
61
62 /* Represents a FLIP input program. */
63 struct flip_pgm
64   {
65     struct pool *pool;          /* Pool containing FLIP data. */
66     size_t n_vars;              /* Pre-flip number of variables. */
67     int n_cases;                /* Pre-flip number of cases. */
68
69     struct variable *new_names_var; /* Variable with new variable names. */
70     struct dictionary *dict;     /* Dictionary of the names */
71     struct var_names old_names; /* Variable names before FLIP. */
72     struct var_names new_names; /* Variable names after FLIP. */
73
74     FILE *file;                 /* Temporary file containing data. */
75     size_t cases_read;          /* Number of cases already read. */
76     bool error;                 /* Error reading temporary file? */
77   };
78
79 static const struct casereader_class flip_casereader_class;
80
81 static void destroy_flip_pgm (struct flip_pgm *);
82 static bool flip_file (struct flip_pgm *);
83 static void make_new_var (struct dictionary *, const char *name);
84
85 /* Parses and executes FLIP. */
86 int
87 cmd_flip (struct lexer *lexer, struct dataset *ds)
88 {
89   struct dictionary *dict = dataset_dict (ds);
90   const struct variable **vars;
91   struct flip_pgm *flip;
92   struct casereader *input, *reader;
93   struct ccase *c;
94   size_t i;
95   bool ok;
96
97   if (proc_make_temporary_transformations_permanent (ds))
98     msg (SW, _("FLIP ignores TEMPORARY.  "
99                "Temporary transformations will be made permanent."));
100
101   flip = pool_create_container (struct flip_pgm, pool);
102   flip->n_vars = 0;
103   flip->n_cases = 0;
104   flip->new_names_var = NULL;
105   var_names_init (&flip->old_names);
106   var_names_init (&flip->new_names);
107   flip->file = NULL;
108   flip->cases_read = 0;
109   flip->error = false;
110   flip->dict = dict;
111
112   lex_match (lexer, '/');
113   if (lex_match_id (lexer, "VARIABLES"))
114     {
115       lex_match (lexer, '=');
116       if (!parse_variables_const (lexer, dict, &vars, &flip->n_vars,
117                                   PV_NO_DUPLICATE))
118         goto error;
119       lex_match (lexer, '/');
120     }
121   else
122     dict_get_vars (dict, &vars, &flip->n_vars, DC_SYSTEM);
123   pool_register (flip->pool, free, vars);
124
125   lex_match (lexer, '/');
126   if (lex_match_id (lexer, "NEWNAMES"))
127     {
128       lex_match (lexer, '=');
129       flip->new_names_var = parse_variable (lexer, dict);
130       if (!flip->new_names_var)
131         goto error;
132     }
133   else
134     flip->new_names_var = dict_lookup_var (dict, "CASE_LBL");
135
136   if (flip->new_names_var)
137     {
138       for (i = 0; i < flip->n_vars; i++)
139         if (vars[i] == flip->new_names_var)
140           {
141             remove_element (vars, flip->n_vars, sizeof *vars, i);
142             flip->n_vars--;
143             break;
144           }
145     }
146
147   flip->file = pool_tmpfile (flip->pool);
148   if (flip->file == NULL)
149     {
150       msg (SE, _("Could not create temporary file for FLIP."));
151       goto error;
152     }
153
154   /* Save old variable names for use as values of CASE_LBL
155      variable in flipped file. */
156   for (i = 0; i < flip->n_vars; i++)
157     var_names_add (flip->pool, &flip->old_names,
158                    pool_strdup (flip->pool, var_get_name (vars[i])));
159
160   /* Read the active file into a flip_sink. */
161   proc_discard_output (ds);
162
163   input = proc_open (ds);
164   while ((c = casereader_read (input)) != NULL)
165     {
166       flip->n_cases++;
167       for (i = 0; i < flip->n_vars; i++)
168         {
169           const struct variable *v = vars[i];
170           double out = var_is_numeric (v) ? case_num (c, v) : SYSMIS;
171           fwrite (&out, sizeof out, 1, flip->file);
172         }
173       if (flip->new_names_var != NULL)
174         {
175           const union value *value = case_data (c, flip->new_names_var);
176           const char *name;
177           if (var_is_numeric (flip->new_names_var))
178             {
179               double f = value->f;
180               name = (f == SYSMIS ? "VSYSMIS"
181                       : f < INT_MIN ? "VNEGINF"
182                       : f > INT_MAX ? "VPOSINF"
183                       : pool_asprintf (flip->pool, "V%d", (int) f));
184             }
185           else
186             {
187               name = data_out_pool (value, dict_get_encoding (flip->dict), var_get_write_format (flip->new_names_var),
188                  flip->pool);
189         
190             }
191           var_names_add (flip->pool, &flip->new_names, name);
192         }
193       case_unref (c);
194     }
195   ok = casereader_destroy (input);
196   ok = proc_commit (ds) && ok;
197
198   /* Flip the data we read. */
199   if (!ok || !flip_file (flip))
200     {
201       proc_discard_active_file (ds);
202       goto error;
203     }
204
205   /* Flip the dictionary. */
206   dict_clear (dict);
207   dict_create_var_assert (dict, "CASE_LBL", 8);
208   for (i = 0; i < flip->n_cases; i++)
209     if (flip->new_names.n_names)
210       make_new_var (dict, flip->new_names.names[i]);
211     else
212       {
213         char s[VAR_NAME_LEN + 1];
214         sprintf (s, "VAR%03d", i);
215         dict_create_var_assert (dict, s, 0);
216       }
217
218   /* Set up flipped data for reading. */
219   reader = casereader_create_sequential (NULL, dict_get_proto (dict),
220                                          flip->n_vars,
221                                          &flip_casereader_class, flip);
222   proc_set_active_file_data (ds, reader);
223   return lex_end_of_command (lexer);
224
225  error:
226   destroy_flip_pgm (flip);
227   return CMD_CASCADING_FAILURE;
228 }
229
230 /* Destroys FLIP. */
231 static void
232 destroy_flip_pgm (struct flip_pgm *flip)
233 {
234   if (flip != NULL)
235     pool_destroy (flip->pool);
236 }
237
238 /* Make a new variable with base name NAME, which is bowdlerized and
239    mangled until acceptable. */
240 static void
241 make_new_var (struct dictionary *dict, const char *name_)
242 {
243   char *name = xstrdup (name_);
244   char *cp;
245
246   /* Trim trailing spaces. */
247   cp = strchr (name, '\0');
248   while (cp > name && isspace ((unsigned char) cp[-1]))
249     *--cp = '\0';
250
251   /* Fix invalid characters. */
252   for (cp = name; *cp && cp < name + VAR_NAME_LEN; cp++)
253     if (cp == name)
254       {
255         if (!lex_is_id1 (*cp) || *cp == '$')
256           *cp = 'V';
257       }
258     else
259       {
260         if (!lex_is_idn (*cp))
261           *cp = '_';
262       }
263   *cp = '\0';
264   str_uppercase (name);
265
266   /* Use the mangled name, if it is available, or add numeric
267      extensions until we find one that is. */
268   if (!dict_create_var (dict, name, 0))
269     {
270       int len = strlen (name);
271       int i;
272       for (i = 1; ; i++)
273         {
274           char n[VAR_NAME_LEN + 1];
275           int ofs = MIN (VAR_NAME_LEN - 1 - intlog10 (i), len);
276           strncpy (n, name, ofs);
277           sprintf (&n[ofs], "%d", i);
278
279           if (dict_create_var (dict, n, 0))
280             break;
281         }
282     }
283   free (name);
284 }
285
286 /* Transposes the external file into a new file. */
287 static bool
288 flip_file (struct flip_pgm *flip)
289 {
290   size_t case_bytes;
291   size_t case_capacity;
292   size_t case_idx;
293   double *input_buf, *output_buf;
294   FILE *input_file, *output_file;
295
296   /* Allocate memory for many cases. */
297   case_bytes = flip->n_vars * sizeof *input_buf;
298   case_capacity = settings_get_workspace () / case_bytes;
299   if (case_capacity > flip->n_cases * 2)
300     case_capacity = flip->n_cases * 2;
301   if (case_capacity < 2)
302     case_capacity = 2;
303   for (;;)
304     {
305       size_t bytes = case_bytes * case_capacity;
306       if (case_capacity > 2)
307         input_buf = malloc (bytes);
308       else
309         input_buf = xmalloc (bytes);
310       if (input_buf != NULL)
311         break;
312
313       case_capacity /= 2;
314       if (case_capacity < 2)
315         case_capacity = 2;
316     }
317   pool_register (flip->pool, free, input_buf);
318
319   /* Use half the allocated memory for input_buf, half for
320      output_buf. */
321   case_capacity /= 2;
322   output_buf = input_buf + flip->n_vars * case_capacity;
323
324   input_file = flip->file;
325   if (fseek (input_file, 0, SEEK_SET) != 0)
326     {
327       msg (SE, _("Error rewinding FLIP file: %s."), strerror (errno));
328       return false;
329     }
330
331   output_file = pool_tmpfile (flip->pool);
332   if (output_file == NULL)
333     {
334       msg (SE, _("Error creating FLIP source file."));
335       return false;
336     }
337
338   for (case_idx = 0; case_idx < flip->n_cases; )
339     {
340       unsigned long read_cases = MIN (flip->n_cases - case_idx,
341                                       case_capacity);
342       size_t i;
343
344       if (read_cases != fread (input_buf, case_bytes, read_cases, input_file))
345         {
346           if (ferror (input_file))
347             msg (SE, _("Error reading FLIP file: %s."), strerror (errno));
348           else
349             msg (SE, _("Unexpected end of file reading FLIP file."));
350           return false;
351         }
352
353       for (i = 0; i < flip->n_vars; i++)
354         {
355           unsigned long j;
356
357           for (j = 0; j < read_cases; j++)
358             output_buf[j] = input_buf[i + j * flip->n_vars];
359
360           if (fseeko (output_file,
361                       sizeof *input_buf * (case_idx
362                                            + (off_t) i * flip->n_cases),
363                       SEEK_SET) != 0)
364             {
365               msg (SE, _("Error seeking FLIP source file: %s."),
366                    strerror (errno));
367               return false;
368             }
369
370           if (fwrite (output_buf, sizeof *output_buf, read_cases, output_file)
371               != read_cases)
372             {
373               msg (SE, _("Error writing FLIP source file: %s."),
374                    strerror (errno));
375               return false;
376             }
377         }
378
379       case_idx += read_cases;
380     }
381
382   if (pool_fclose (flip->pool, input_file) == EOF)
383     {
384       msg (SE, _("Error closing FLIP source file: %s."), strerror (errno));
385       return false;
386     }
387   pool_unregister (flip->pool, input_buf);
388   free (input_buf);
389
390   if (fseek (output_file, 0, SEEK_SET) != 0)
391     {
392       msg (SE, _("Error rewinding FLIP source file: %s."), strerror (errno));
393       return false;
394     }
395   flip->file = output_file;
396
397   return true;
398 }
399
400 /* Reads and returns one case.
401    Returns a null pointer at end of file or if an I/O error occurred. */
402 static struct ccase *
403 flip_casereader_read (struct casereader *reader, void *flip_)
404 {
405   struct flip_pgm *flip = flip_;
406   struct ccase *c;
407   size_t i;
408
409   if (flip->error || flip->cases_read >= flip->n_vars)
410     return false;
411
412   c = case_create (casereader_get_proto (reader));
413   data_in (ss_cstr (flip->old_names.names[flip->cases_read]), dict_get_encoding (flip->dict), 
414         FMT_A, 0,
415         0, 0,
416         flip->dict, 
417         case_data_rw_idx (c, 0), 8);
418         
419   for (i = 0; i < flip->n_cases; i++)
420     {
421       double in;
422       if (fread (&in, sizeof in, 1, flip->file) != 1)
423         {
424           case_unref (c);
425           if (ferror (flip->file))
426             msg (SE, _("Error reading FLIP temporary file: %s."),
427                  strerror (errno));
428           else if (feof (flip->file))
429             msg (SE, _("Unexpected end of file reading FLIP temporary file."));
430           else
431             NOT_REACHED ();
432           flip->error = true;
433           return NULL;
434         }
435       case_data_rw_idx (c, i + 1)->f = in;
436     }
437
438   flip->cases_read++;
439
440   return c;
441 }
442
443 /* Destroys the source.
444    Returns true if successful read, false if an I/O occurred
445    during destruction or previously. */
446 static void
447 flip_casereader_destroy (struct casereader *reader UNUSED, void *flip_)
448 {
449   struct flip_pgm *flip = flip_;
450   if (flip->error)
451     casereader_force_error (reader);
452   destroy_flip_pgm (flip);
453 }
454
455 static const struct casereader_class flip_casereader_class =
456   {
457     flip_casereader_read,
458     flip_casereader_destroy,
459     NULL,
460     NULL,
461   };
462 \f
463 static void
464 var_names_init (struct var_names *vn)
465 {
466   vn->names = NULL;
467   vn->n_names = 0;
468   vn->allocated_names = 0;
469 }
470
471 static void
472 var_names_add (struct pool *pool, struct var_names *vn, const char *name)
473 {
474   if (vn->n_names >= vn->allocated_names)
475     vn->names = pool_2nrealloc (pool, vn->names, &vn->allocated_names,
476                                 sizeof *vn->names);
477   vn->names[vn->n_names++] = name;
478 }
479