Use fseeko module from gnulib instead of our home-grown solution.
[pspp-builds.git] / src / language / stats / flip.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000 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/value.h>
32 #include <data/variable.h>
33 #include <language/command.h>
34 #include <language/lexer/lexer.h>
35 #include <language/lexer/variable-parser.h>
36 #include <libpspp/array.h>
37 #include <libpspp/assertion.h>
38 #include <libpspp/message.h>
39 #include <libpspp/misc.h>
40 #include <libpspp/pool.h>
41 #include <libpspp/str.h>
42
43 #include "intprops.h"
44 #include "minmax.h"
45 #include "xalloc.h"
46
47 #include "gettext.h"
48 #define _(msgid) gettext (msgid)
49
50 /* List of variable names. */
51 struct varname
52   {
53     struct varname *next;
54     char name[SHORT_NAME_LEN + 1];
55   };
56
57 /* Represents a FLIP input program. */
58 struct flip_pgm
59   {
60     struct pool *pool;          /* Pool containing FLIP data. */
61     const struct variable **var;      /* Variables to transpose. */
62     size_t var_cnt;             /* Number of elements in `var'. */
63     int case_cnt;               /* Pre-flip case count. */
64
65     struct variable *new_names; /* Variable containing new variable names. */
66     struct varname *new_names_head; /* First new variable. */
67     struct varname *new_names_tail; /* Last new variable. */
68
69     FILE *file;                 /* Temporary file containing data. */
70     union value *input_buf;     /* Input buffer for temporary file. */
71     size_t cases_read;          /* Number of cases already read. */
72     bool error;                 /* Error reading temporary file? */
73   };
74
75 static const struct casereader_class flip_casereader_class;
76
77 static void destroy_flip_pgm (struct flip_pgm *);
78 static bool flip_file (struct flip_pgm *);
79 static bool build_dictionary (struct dictionary *, struct flip_pgm *);
80 static bool write_flip_case (struct flip_pgm *, const struct ccase *);
81
82 /* Parses and executes FLIP. */
83 int
84 cmd_flip (struct lexer *lexer, struct dataset *ds)
85 {
86   struct dictionary *dict = dataset_dict (ds);
87   struct flip_pgm *flip;
88   struct casereader *input, *reader;
89   union value *output_buf;
90   struct ccase c;
91   size_t i;
92   bool ok;
93
94   if (proc_make_temporary_transformations_permanent (ds))
95     msg (SW, _("FLIP ignores TEMPORARY.  "
96                "Temporary transformations will be made permanent."));
97
98   flip = pool_create_container (struct flip_pgm, pool);
99   flip->var = NULL;
100   flip->var_cnt = 0;
101   flip->case_cnt = 0;
102   flip->new_names = NULL;
103   flip->new_names_head = NULL;
104   flip->new_names_tail = NULL;
105   flip->file = NULL;
106   flip->input_buf = NULL;
107   flip->cases_read = 0;
108   flip->error = false;
109
110   lex_match (lexer, '/');
111   if (lex_match_id (lexer, "VARIABLES"))
112     {
113       lex_match (lexer, '=');
114       if (!parse_variables_const (lexer, dict, &flip->var, &flip->var_cnt,
115                                   PV_NO_DUPLICATE))
116         goto error;
117       lex_match (lexer, '/');
118     }
119   else
120     dict_get_vars (dict, &flip->var, &flip->var_cnt, 1u << DC_SYSTEM);
121   pool_register (flip->pool, free, flip->var);
122
123   lex_match (lexer, '/');
124   if (lex_match_id (lexer, "NEWNAMES"))
125     {
126       lex_match (lexer, '=');
127       flip->new_names = parse_variable (lexer, dict);
128       if (!flip->new_names)
129         goto error;
130     }
131   else
132     flip->new_names = dict_lookup_var (dict, "CASE_LBL");
133
134   if (flip->new_names)
135     {
136       for (i = 0; i < flip->var_cnt; i++)
137         if (flip->var[i] == flip->new_names)
138           {
139             remove_element (flip->var, flip->var_cnt, sizeof *flip->var, i);
140             flip->var_cnt--;
141             break;
142           }
143     }
144
145   output_buf = pool_nalloc (flip->pool, flip->var_cnt, sizeof *output_buf);
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   /* Write variable names as first case. */
155   for (i = 0; i < flip->var_cnt; i++)
156     buf_copy_str_rpad (output_buf[i].s, MAX_SHORT_STRING,
157                        var_get_name (flip->var[i]));
158   if (fwrite (output_buf, sizeof *output_buf,
159               flip->var_cnt, flip->file) != (size_t) flip->var_cnt)
160     {
161       msg (SE, _("Error writing FLIP file: %s."), strerror (errno));
162       goto error;
163     }
164
165   flip->case_cnt = 1;
166
167   /* Read the active file into a flip_sink. */
168   proc_discard_output (ds);
169
170   input = proc_open (ds);
171   while (casereader_read (input, &c))
172     {
173       write_flip_case (flip, &c);
174       case_destroy (&c);
175     }
176   ok = casereader_destroy (input);
177   ok = proc_commit (ds) && ok;
178
179   /* Flip the data we read. */
180   if (!ok || !flip_file (flip))
181     {
182       proc_discard_active_file (ds);
183       goto error;
184     }
185
186   /* Flip the dictionary. */
187   dict_clear (dict);
188   if (!build_dictionary (dict, flip))
189     {
190       proc_discard_active_file (ds);
191       goto error;
192     }
193
194   /* Set up flipped data for reading. */
195   reader = casereader_create_sequential (NULL, dict_get_next_value_idx (dict),
196                                          flip->var_cnt,
197                                          &flip_casereader_class, flip);
198   proc_set_active_file_data (ds, reader);
199   return lex_end_of_command (lexer);
200
201  error:
202   destroy_flip_pgm (flip);
203   return CMD_CASCADING_FAILURE;
204 }
205
206 /* Destroys FLIP. */
207 static void
208 destroy_flip_pgm (struct flip_pgm *flip)
209 {
210   if (flip != NULL)
211     pool_destroy (flip->pool);
212 }
213
214 /* Make a new variable with base name NAME, which is bowdlerized and
215    mangled until acceptable, and returns success. */
216 static int
217 make_new_var (struct dictionary *dict, char name[])
218 {
219   char *cp;
220
221   /* Trim trailing spaces. */
222   cp = strchr (name, '\0');
223   while (cp > name && isspace ((unsigned char) cp[-1]))
224     *--cp = '\0';
225
226   /* Fix invalid characters. */
227   for (cp = name; *cp && cp < name + SHORT_NAME_LEN; cp++)
228     if (cp == name)
229       {
230         if (!lex_is_id1 (*cp) || *cp == '$')
231           *cp = 'V';
232       }
233     else
234       {
235         if (!lex_is_idn (*cp))
236           *cp = '_';
237       }
238   *cp = '\0';
239   str_uppercase (name);
240
241   if (dict_create_var (dict, name, 0))
242     return 1;
243
244   /* Add numeric extensions until acceptable. */
245   {
246     const int len = (int) strlen (name);
247     char n[SHORT_NAME_LEN + 1];
248     int i;
249
250     for (i = 1; i < 10000000; i++)
251       {
252         int ofs = MIN (7 - intlog10 (i), len);
253         memcpy (n, name, ofs);
254         sprintf (&n[ofs], "%d", i);
255
256         if (dict_create_var (dict, n, 0))
257           return 1;
258       }
259   }
260
261   msg (SE, _("Could not create acceptable variant for variable %s."), name);
262   return 0;
263 }
264
265 /* Make a new dictionary for all the new variable names. */
266 static bool
267 build_dictionary (struct dictionary *dict, struct flip_pgm *flip)
268 {
269   dict_create_var_assert (dict, "CASE_LBL", 8);
270
271   if (flip->new_names_head == NULL)
272     {
273       int i;
274
275       if (flip->case_cnt > 99999)
276         {
277           msg (SE, _("Cannot create more than 99999 variable names."));
278           return false;
279         }
280
281       for (i = 0; i < flip->case_cnt - 1; i++)
282         {
283           struct variable *v;
284           char s[SHORT_NAME_LEN + 1];
285
286           sprintf (s, "VAR%03d", i);
287           v = dict_create_var_assert (dict, s, 0);
288         }
289     }
290   else
291     {
292       struct varname *v;
293
294       for (v = flip->new_names_head; v; v = v->next)
295         if (!make_new_var (dict, v->name))
296           return false;
297     }
298
299   return true;
300 }
301
302 /* Writes case C to the FLIP sink.
303    Returns true if successful, false if an I/O error occurred. */
304 static bool
305 write_flip_case (struct flip_pgm *flip, const struct ccase *c)
306 {
307   size_t i;
308
309   flip->case_cnt++;
310
311   if (flip->new_names != NULL)
312     {
313       struct varname *v = pool_alloc (flip->pool, sizeof *v);
314       v->next = NULL;
315       if (var_is_numeric (flip->new_names))
316         {
317           double f = case_num (c, flip->new_names);
318
319           if (f == SYSMIS)
320             strcpy (v->name, "VSYSMIS");
321           else if (f < INT_MIN)
322             strcpy (v->name, "VNEGINF");
323           else if (f > INT_MAX)
324             strcpy (v->name, "VPOSINF");
325           else
326             snprintf (v->name, sizeof v->name, "V%d", (int) f);
327         }
328       else
329         {
330           int width = MIN (var_get_width (flip->new_names), MAX_SHORT_STRING);
331           memcpy (v->name, case_str (c, flip->new_names), width);
332           v->name[width] = 0;
333         }
334
335       if (flip->new_names_head == NULL)
336         flip->new_names_head = v;
337       else
338         flip->new_names_tail->next = v;
339       flip->new_names_tail = v;
340     }
341
342   /* Write to external file. */
343   for (i = 0; i < flip->var_cnt; i++)
344     {
345       const struct variable *v = flip->var[i];
346       double out = var_is_numeric (v) ? case_num (c, v) : SYSMIS;
347       fwrite (&out, sizeof out, 1, flip->file);
348     }
349   return true;
350 }
351
352 /* Transposes the external file into a new file. */
353 static bool
354 flip_file (struct flip_pgm *flip)
355 {
356   size_t case_bytes;
357   size_t case_capacity;
358   size_t case_idx;
359   union value *input_buf, *output_buf;
360   FILE *input_file, *output_file;
361
362   /* Allocate memory for many cases. */
363   case_bytes = flip->var_cnt * sizeof *input_buf;
364   case_capacity = get_workspace () / case_bytes;
365   if (case_capacity > flip->case_cnt * 2)
366     case_capacity = flip->case_cnt * 2;
367   if (case_capacity < 2)
368     case_capacity = 2;
369   for (;;)
370     {
371       size_t bytes = case_bytes * case_capacity;
372       if (case_capacity > 2)
373         input_buf = malloc (bytes);
374       else
375         input_buf = xmalloc (bytes);
376       if (input_buf != NULL)
377         break;
378
379       case_capacity /= 2;
380       if (case_capacity < 2)
381         case_capacity = 2;
382     }
383   pool_register (flip->pool, free, input_buf);
384
385   /* Use half the allocated memory for input_buf, half for
386      output_buf. */
387   case_capacity /= 2;
388   output_buf = input_buf + flip->var_cnt * case_capacity;
389
390   input_file = flip->file;
391   if (fseek (input_file, 0, SEEK_SET) != 0)
392     {
393       msg (SE, _("Error rewinding FLIP file: %s."), strerror (errno));
394       return false;
395     }
396
397   output_file = pool_tmpfile (flip->pool);
398   if (output_file == NULL)
399     {
400       msg (SE, _("Error creating FLIP source file."));
401       return false;
402     }
403
404   for (case_idx = 0; case_idx < flip->case_cnt; )
405     {
406       unsigned long read_cases = MIN (flip->case_cnt - case_idx,
407                                       case_capacity);
408       size_t i;
409
410       if (read_cases != fread (input_buf, case_bytes, read_cases, input_file))
411         {
412           if (ferror (input_file))
413             msg (SE, _("Error reading FLIP file: %s."), strerror (errno));
414           else
415             msg (SE, _("Unexpected end of file reading FLIP file."));
416           return false;
417         }
418
419       for (i = 0; i < flip->var_cnt; i++)
420         {
421           unsigned long j;
422
423           for (j = 0; j < read_cases; j++)
424             output_buf[j] = input_buf[i + j * flip->var_cnt];
425
426           if (fseeko (output_file,
427                       sizeof *input_buf * (case_idx
428                                            + (off_t) i * flip->case_cnt),
429                       SEEK_SET) != 0)
430             {
431               msg (SE, _("Error seeking FLIP source file: %s."),
432                    strerror (errno));
433               return false;
434             }
435
436           if (fwrite (output_buf, sizeof *output_buf, read_cases, output_file)
437               != read_cases)
438             {
439               msg (SE, _("Error writing FLIP source file: %s."),
440                    strerror (errno));
441               return false;
442             }
443         }
444
445       case_idx += read_cases;
446     }
447
448   if (pool_fclose (flip->pool, input_file) == EOF)
449     {
450       msg (SE, _("Error closing FLIP source file: %s."), strerror (errno));
451       return false;
452     }
453   pool_unregister (flip->pool, input_buf);
454   free (input_buf);
455
456   if (fseek (output_file, 0, SEEK_SET) != 0)
457     {
458       msg (SE, _("Error rewinding FLIP source file: %s."), strerror (errno));
459       return false;
460     }
461   flip->file = output_file;
462
463   return true;
464 }
465
466 /* Reads one case into C.
467    Returns true if successful, false at end of file or if an
468    I/O error occurred. */
469 static bool
470 flip_casereader_read (struct casereader *reader UNUSED, void *flip_,
471                       struct ccase *c)
472 {
473   struct flip_pgm *flip = flip_;
474   size_t i;
475
476   if (flip->error || flip->cases_read >= flip->var_cnt)
477     return false;
478
479   case_create (c, flip->case_cnt);
480   for (i = 0; i < flip->case_cnt; i++)
481     {
482       double in;
483       if (fread (&in, sizeof in, 1, flip->file) != 1)
484         {
485           case_destroy (c);
486           if (ferror (flip->file))
487             msg (SE, _("Error reading FLIP temporary file: %s."),
488                  strerror (errno));
489           else if (feof (flip->file))
490             msg (SE, _("Unexpected end of file reading FLIP temporary file."));
491           else
492             NOT_REACHED ();
493           flip->error = true;
494           return false;
495         }
496       case_data_rw_idx (c, i)->f = in;
497     }
498
499   flip->cases_read++;
500
501   return true;
502 }
503
504 /* Destroys the source.
505    Returns true if successful read, false if an I/O occurred
506    during destruction or previously. */
507 static void
508 flip_casereader_destroy (struct casereader *reader UNUSED, void *flip_)
509 {
510   struct flip_pgm *flip = flip_;
511   if (flip->error)
512     casereader_force_error (reader);
513   destroy_flip_pgm (flip);
514 }
515
516 static const struct casereader_class flip_casereader_class =
517   {
518     flip_casereader_read,
519     flip_casereader_destroy,
520     NULL,
521     NULL,
522   };