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