Plugged some memory leaks.
[pspp-builds.git] / src / dictionary.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 "dictionary.h"
22 #include <stdlib.h>
23 #include <ctype.h>
24 #include "algorithm.h"
25 #include "alloc.h"
26 #include "case.h"
27 #include "error.h"
28 #include "hash.h"
29 #include "misc.h"
30 #include "str.h"
31 #include "value-labels.h"
32 #include "var.h"
33
34 /* A dictionary. */
35 struct dictionary
36   {
37     struct variable **var;      /* Variables. */
38     size_t var_cnt, var_cap;    /* Number of variables, capacity. */
39     struct hsh_table *name_tab; /* Variable index by name. */
40     struct hsh_table *long_name_tab; /* Variable indexed by long name */
41     int next_value_idx;         /* Index of next `union value' to allocate. */
42     struct variable **split;    /* SPLIT FILE vars. */
43     size_t split_cnt;           /* SPLIT FILE count. */
44     struct variable *weight;    /* WEIGHT variable. */
45     struct variable *filter;    /* FILTER variable. */
46     int case_limit;             /* Current case limit (N command). */
47     char *label;                /* File label. */
48     char *documents;            /* Documents, as a string. */
49     struct vector **vector;     /* Vectors of variables. */
50     size_t vector_cnt;          /* Number of vectors. */
51   };
52
53
54
55
56
57 int
58 compare_long_names(const void *a_, const void *b_, void *aux UNUSED)
59 {
60   const struct name_table_entry *a = a_;
61   const struct name_table_entry *b = b_;
62
63   return strcasecmp(a->longname, b->longname);
64 }
65
66
67 /* Long names use case insensitive comparison */
68 unsigned int
69 hash_long_name (const void *e_, void *aux UNUSED) 
70 {
71   const struct name_table_entry *e = e_;
72   unsigned int hash;
73   int i;
74
75   char *s = strdup(e->longname);
76
77   for ( i = 0 ; i < strlen(s) ; ++i ) 
78     s[i] = toupper(s[i]);
79
80   hash = hsh_hash_string (s);
81   
82   free (s);
83
84   return hash;
85 }
86
87
88
89
90 static char *make_short_name(struct dictionary *dict, const char *longname) ;
91
92
93 /* Creates and returns a new dictionary. */
94 struct dictionary *
95 dict_create (void) 
96 {
97   struct dictionary *d = xmalloc (sizeof *d);
98   
99   d->var = NULL;
100   d->var_cnt = d->var_cap = 0;
101   d->name_tab = hsh_create (8, compare_var_names, hash_var_name, NULL, NULL);
102   d->long_name_tab = hsh_create (8, compare_long_names, hash_long_name, 
103                                  (hsh_free_func *) free_nte, NULL);
104   d->next_value_idx = 0;
105   d->split = NULL;
106   d->split_cnt = 0;
107   d->weight = NULL;
108   d->filter = NULL;
109   d->case_limit = 0;
110   d->label = NULL;
111   d->documents = NULL;
112   d->vector = NULL;
113   d->vector_cnt = 0;
114
115   return d;
116 }
117
118 /* Creates and returns a (deep) copy of an existing
119    dictionary. */
120 struct dictionary *
121 dict_clone (const struct dictionary *s) 
122 {
123   struct dictionary *d;
124   size_t i;
125
126   assert (s != NULL);
127
128   d = dict_create ();
129
130   for (i = 0; i < s->var_cnt; i++)
131     dict_clone_var (d, s->var[i], s->var[i]->name, s->var[i]->longname);
132
133   d->next_value_idx = s->next_value_idx;
134
135   d->split_cnt = s->split_cnt;
136   if (d->split_cnt > 0) 
137     {
138       d->split = xmalloc (d->split_cnt * sizeof *d->split);
139       for (i = 0; i < d->split_cnt; i++) 
140         d->split[i] = dict_lookup_var_assert (d, s->split[i]->name);
141     }
142
143   if (s->weight != NULL) 
144     d->weight = dict_lookup_var_assert (d, s->weight->name);
145
146   if (s->filter != NULL) 
147     d->filter = dict_lookup_var_assert (d, s->filter->name);
148
149   d->case_limit = s->case_limit;
150   dict_set_label (d, dict_get_label (s));
151   dict_set_documents (d, dict_get_documents (s));
152
153   for (i = 0; i < s->vector_cnt; i++) 
154     dict_create_vector (d, s->vector[i]->name,
155                         s->vector[i]->var, s->vector[i]->cnt);
156
157   return d;
158 }
159
160 /* Clears the contents from a dictionary without destroying the
161    dictionary itself. */
162 void
163 dict_clear (struct dictionary *d) 
164 {
165   /* FIXME?  Should we really clear case_limit, label, documents?
166      Others are necessarily cleared by deleting all the variables.*/
167   int i;
168
169   assert (d != NULL);
170
171   for (i = 0; i < d->var_cnt; i++) 
172     {
173       struct variable *v = d->var[i];
174       var_clear_aux (v);
175       val_labs_destroy (v->val_labs);
176       free (v->label);
177       free (v); 
178     }
179   free (d->var);
180   d->var = NULL;
181   d->var_cnt = d->var_cap = 0;
182   hsh_clear (d->name_tab);
183   if ( d->long_name_tab) 
184     hsh_clear (d->long_name_tab);
185   d->next_value_idx = 0;
186   free (d->split);
187   d->split = NULL;
188   d->split_cnt = 0;
189   d->weight = NULL;
190   d->filter = NULL;
191   d->case_limit = 0;
192   free (d->label);
193   d->label = NULL;
194   free (d->documents);
195   d->documents = NULL;
196   dict_clear_vectors (d);
197 }
198
199 /* Allocate the pointer TEXT and fill it with text representing the
200    long variable name buffer.  SIZE will contain the size of TEXT.
201    TEXT must be freed by the caller when no longer required.
202 */
203 void
204 dict_get_varname_block(const struct dictionary *dict, char **text, int *size)
205 {
206   char *buf = 0;
207   int bufsize = 0;
208   struct hsh_iterator hi;
209   struct name_table_entry *nte;
210   short first = 1;
211
212   for ( nte = hsh_first(dict->long_name_tab, &hi);
213         nte; 
214         nte = hsh_next(dict->long_name_tab, &hi))
215     {
216       bufsize += strlen(nte->name) + strlen(nte->longname) + 2;
217       buf = xrealloc(buf, bufsize + 1);
218       if ( first ) 
219         strcpy(buf, "");
220       first = 0;
221
222       strcat(buf, nte->name);
223       strcat(buf, "=");
224       strcat(buf, nte->longname);
225       strcat(buf, "\t");
226     }
227
228   if ( bufsize > 0 ) 
229     {
230       /* Loose the final delimiting TAB */
231       buf[bufsize]='\0';
232       bufsize--;
233     }
234   
235   *text = buf;
236   *size = bufsize;
237 }
238
239 /* Add a new entry into the dictionary's long name table, and update the 
240    corresponding variable with the relevant long name.
241 */
242 void
243 dict_add_longvar_entry(struct dictionary *d, 
244                        const char *name, 
245                        const char *longname)
246 {
247   struct variable *v;
248   assert ( name ) ;
249   assert ( longname );
250   struct name_table_entry *nte = xmalloc (sizeof (struct name_table_entry));
251   nte->longname = strdup(longname);
252   nte->name = strdup(name);
253
254   /* Look up the name in name_tab */
255   v = hsh_find ( d->name_tab, name);
256   if ( !v ) 
257     {
258       msg (FE, _("The entry \"%s\" in the variable name map, has no corresponding variable"), name);
259       return ;
260     }
261   assert ( 0 == strcmp(v->name, name) );
262   v->longname = nte->longname;
263
264   hsh_insert(d->long_name_tab, nte);
265 }
266
267 /* Destroy and free up an nte */
268 void
269 free_nte(struct name_table_entry *nte)
270 {
271   assert(nte);
272   free(nte->longname);
273   free(nte->name);
274   free(nte);
275 }
276
277
278 /* Destroys the aux data for every variable in D, by calling
279    var_clear_aux() for each variable. */
280 void
281 dict_clear_aux (struct dictionary *d) 
282 {
283   int i;
284   
285   assert (d != NULL);
286   
287   for (i = 0; i < d->var_cnt; i++)
288     var_clear_aux (d->var[i]);
289 }
290
291 /* Clears a dictionary and destroys it. */
292 void
293 dict_destroy (struct dictionary *d)
294 {
295   if (d != NULL) 
296     {
297       dict_clear (d);
298       hsh_destroy (d->name_tab);
299       hsh_destroy (d->long_name_tab);
300       free (d);
301     }
302 }
303
304 /* Returns the number of variables in D. */
305 size_t
306 dict_get_var_cnt (const struct dictionary *d) 
307 {
308   assert (d != NULL);
309
310   return d->var_cnt;
311 }
312
313 /* Returns the variable in D with index IDX, which must be
314    between 0 and the count returned by dict_get_var_cnt(),
315    exclusive. */
316 struct variable *
317 dict_get_var (const struct dictionary *d, size_t idx) 
318 {
319   assert (d != NULL);
320   assert (idx < d->var_cnt);
321
322   return d->var[idx];
323 }
324
325 /* Sets *VARS to an array of pointers to variables in D and *CNT
326    to the number of variables in *D.  By default all variables
327    are returned, but bits may be set in EXCLUDE_CLASSES to
328    exclude ordinary, system, and/or scratch variables. */
329 void
330 dict_get_vars (const struct dictionary *d, struct variable ***vars,
331                size_t *cnt, unsigned exclude_classes)
332 {
333   size_t count;
334   size_t i;
335   
336   assert (d != NULL);
337   assert (vars != NULL);
338   assert (cnt != NULL);
339   assert ((exclude_classes & ~((1u << DC_ORDINARY)
340                                | (1u << DC_SYSTEM)
341                                | (1u << DC_SCRATCH))) == 0);
342   
343   count = 0;
344   for (i = 0; i < d->var_cnt; i++)
345     if (!(exclude_classes & (1u << dict_class_from_id (d->var[i]->name))))
346       count++;
347
348   *vars = xmalloc (count * sizeof **vars);
349   *cnt = 0;
350   for (i = 0; i < d->var_cnt; i++)
351     if (!(exclude_classes & (1u << dict_class_from_id (d->var[i]->name))))
352       (*vars)[(*cnt)++] = d->var[i];
353   assert (*cnt == count);
354 }
355
356
357 static struct variable * dict_create_var_x (struct dictionary *d, 
358                                             const char *name, int width, 
359                                             short name_is_short) ;
360
361 /* Creates and returns a new variable in D with the given LONGNAME
362    and WIDTH.  Returns a null pointer if the given LONGNAME would
363    duplicate that of an existing variable in the dictionary.
364 */
365 struct variable *
366 dict_create_var (struct dictionary *d, const char *longname, int width)
367 {
368   return dict_create_var_x(d, longname, width, 0);
369 }
370
371
372 /* Creates and returns a new variable in D with the given SHORTNAME and 
373    WIDTH.  The long name table is not updated */
374 struct variable *
375 dict_create_var_from_short (struct dictionary *d, const char *shortname, 
376                             int width)
377 {
378   return dict_create_var_x(d, shortname, width, 1);
379 }
380
381
382
383 /* Creates and returns a new variable in D with the given NAME
384    and WIDTH.  
385    If NAME_IS_SHORT, assume NAME is the short name.  Otherwise assumes
386    NAME is the long name, and creates the corresponding entry in the 
387    Dictionary's lookup name table .
388    Returns a null pointer if the given NAME would
389    duplicate that of an existing variable in the dictionary. 
390    
391 */
392 static struct variable *
393 dict_create_var_x (struct dictionary *d, const char *name, int width, 
394                  short name_is_short) 
395 {
396   struct variable *v;
397
398   assert (d != NULL);
399   assert (name != NULL);
400
401   assert (strlen (name) >= 1);
402
403   assert (width >= 0 && width < 256);
404     
405   if ( name_is_short ) 
406     assert(strlen (name) <= SHORT_NAME_LEN);
407   else
408     assert(strlen (name) <= LONG_NAME_LEN);
409
410   /* Make sure there's not already a variable by that name. */
411   if (dict_lookup_var (d, name) != NULL)
412     return NULL;
413
414   /* Allocate and initialize variable. */
415   v = xmalloc (sizeof *v);
416
417   if ( name_is_short )
418     {
419       strncpy (v->name, name, sizeof v->name);
420       v->name[SHORT_NAME_LEN] = '\0';
421     }
422   else
423     {
424       const char *sn = make_short_name(d, name);
425       strncpy(v->name, sn, SHORT_NAME_LEN);
426       free(sn);
427     }
428   
429
430   v->index = d->var_cnt;
431   v->type = width == 0 ? NUMERIC : ALPHA;
432   v->width = width;
433   v->fv = d->next_value_idx;
434   v->nv = width == 0 ? 1 : DIV_RND_UP (width, 8);
435   v->init = 1;
436   v->reinit = dict_class_from_id (v->name) != DC_SCRATCH;
437   v->miss_type = MISSING_NONE;
438   if (v->type == NUMERIC)
439     {
440       v->print.type = FMT_F;
441       v->print.w = 8;
442       v->print.d = 2;
443
444       v->alignment = ALIGN_RIGHT;
445       v->display_width = 8;
446       v->measure = MEASURE_SCALE;
447     }
448   else
449     {
450       v->print.type = FMT_A;
451       v->print.w = v->width;
452       v->print.d = 0;
453
454       v->alignment = ALIGN_LEFT;
455       v->display_width = 8;
456       v->measure = MEASURE_NOMINAL;
457     }
458   v->write = v->print;
459   v->val_labs = val_labs_create (v->width);
460   v->label = NULL;
461   v->aux = NULL;
462   v->aux_dtor = NULL;
463
464   /* Update dictionary. */
465   if (d->var_cnt >= d->var_cap) 
466     {
467       d->var_cap = 8 + 2 * d->var_cap; 
468       d->var = xrealloc (d->var, d->var_cap * sizeof *d->var);
469     }
470   d->var[v->index] = v;
471   d->var_cnt++;
472   hsh_force_insert (d->name_tab, v);
473
474   if ( ! name_is_short) 
475     dict_add_longvar_entry(d, v->name, name);
476
477   d->next_value_idx += v->nv;
478
479   return v;
480 }
481
482 /* Creates and returns a new variable in D with the given NAME
483    and WIDTH.  Assert-fails if the given NAME would duplicate
484    that of an existing variable in the dictionary. */
485 struct variable *
486 dict_create_var_assert (struct dictionary *d, const char *longname, int width)
487 {
488   struct variable *v = dict_create_var (d, longname, width);
489   assert (v != NULL);
490   return v;
491 }
492
493 /* Creates a new variable in D with longname LONGNAME, as a copy of
494    existing  variable OV, which need not be in D or in any
495    dictionary. 
496    If SHORTNAME is non null, it will be used as the short name
497    otherwise a new short name will be generated.
498 */
499 struct variable *
500 dict_clone_var (struct dictionary *d, const struct variable *ov,
501                 const char *name, const char *longname)
502 {
503   struct variable *nv;
504
505   assert (d != NULL);
506   assert (ov != NULL);
507   assert (strlen (longname) <= LONG_NAME_LEN);
508
509   struct name_table_entry *nte = xmalloc (sizeof (struct name_table_entry));
510
511   nte->longname = strdup(longname);
512   if ( name ) 
513     {
514       assert (strlen (name) >= 1);
515       assert (strlen (name) <= SHORT_NAME_LEN);
516       nte->name = strdup(name);
517     }
518   else 
519     nte->name = make_short_name(d, longname);
520
521
522   nv = dict_create_var_from_short (d, nte->name, ov->width);
523   if (nv == NULL)
524     return NULL;
525
526   hsh_insert(d->long_name_tab, nte);
527   nv->longname = nte->longname;
528
529   nv->init = 1;
530   nv->reinit = ov->reinit;
531   nv->miss_type = ov->miss_type;
532   memcpy (nv->missing, ov->missing, sizeof nv->missing);
533   nv->print = ov->print;
534   nv->write = ov->write;
535   val_labs_destroy (nv->val_labs);
536   nv->val_labs = val_labs_copy (ov->val_labs);
537   if (ov->label != NULL)
538     nv->label = xstrdup (ov->label);
539
540   nv->alignment = ov->alignment;
541   nv->measure = ov->measure;
542   nv->display_width = ov->display_width;
543
544   return nv;
545 }
546
547 /* Changes the name of V in D to name NEW_NAME.  Assert-fails if
548    a variable named NEW_NAME is already in D, except that
549    NEW_NAME may be the same as V's existing name. */
550 void 
551 dict_rename_var (struct dictionary *d, struct variable *v,
552                  const char *new_name) 
553 {
554   assert (d != NULL);
555   assert (v != NULL);
556   assert (new_name != NULL);
557   assert (strlen (new_name) >= 1 && strlen (new_name) <= SHORT_NAME_LEN);
558   assert (dict_contains_var (d, v));
559
560   if (!strcmp (v->name, new_name))
561     return;
562
563   assert (dict_lookup_var (d, new_name) == NULL);
564
565   hsh_force_delete (d->name_tab, v);
566   strncpy (v->name, new_name, sizeof v->name);
567   v->name[SHORT_NAME_LEN] = '\0';
568   hsh_force_insert (d->name_tab, v);
569 }
570
571 /* Returns the variable named NAME in D, or a null pointer if no
572    variable has that name. */
573 struct variable *
574 dict_lookup_var (const struct dictionary *d, const char *name)
575 {
576   struct variable v;
577   struct variable *vr;
578   
579   char *short_name;
580   struct name_table_entry key;
581   struct name_table_entry *nte;
582
583   assert (d != NULL);
584   assert (name != NULL);
585   assert (strlen (name) >= 1 && strlen (name) <= LONG_NAME_LEN);
586
587   key.longname = name;
588   nte = hsh_find (d->long_name_tab, &key);
589   
590   if ( ! nte ) 
591   {
592     return 0;
593   }
594
595   short_name = nte->name ;
596
597   strncpy (v.name, short_name, sizeof v.name);
598   v.name[SHORT_NAME_LEN] = '\0';
599
600   vr = hsh_find (d->name_tab, &v);
601
602   return vr; 
603 }
604
605
606 /* Returns the variable named NAME in D.  Assert-fails if no
607    variable has that name. */
608 struct variable *
609 dict_lookup_var_assert (const struct dictionary *d, const char *name)
610 {
611   struct variable *v = dict_lookup_var (d, name);
612   assert (v != NULL);
613   return v;
614 }
615
616 /* Returns nonzero if variable V is in dictionary D. */
617 int
618 dict_contains_var (const struct dictionary *d, const struct variable *v)
619 {
620   assert (d != NULL);
621   assert (v != NULL);
622
623   return v->index >= 0 && v->index < d->var_cnt && d->var[v->index] == v;
624 }
625
626 /* Compares two double pointers to variables, which should point
627    to elements of a struct dictionary's `var' member array. */
628 static int
629 compare_var_ptrs (const void *a_, const void *b_, void *aux UNUSED) 
630 {
631   struct variable *const *a = a_;
632   struct variable *const *b = b_;
633
634   return *a < *b ? -1 : *a > *b;
635 }
636
637 /* Deletes variable V from dictionary D and frees V.
638
639    This is a very bad idea if there might be any pointers to V
640    from outside D.  In general, no variable in default_dict
641    should be deleted when any transformations are active, because
642    those transformations might reference the deleted variable.
643    The safest time to delete a variable is just after a procedure
644    has been executed, as done by MODIFY VARS.
645
646    Pointers to V within D are not a problem, because
647    dict_delete_var() knows to remove V from split variables,
648    weights, filters, etc. */
649 void
650 dict_delete_var (struct dictionary *d, struct variable *v) 
651 {
652   size_t i;
653
654   assert (d != NULL);
655   assert (v != NULL);
656   assert (dict_contains_var (d, v));
657   assert (d->var[v->index] == v);
658
659   /* Delete aux data. */
660   var_clear_aux (v);
661
662   /* Remove V from splits, weight, filter variables. */
663   d->split_cnt = remove_equal (d->split, d->split_cnt, sizeof *d->split,
664                                &v, compare_var_ptrs, NULL);
665   if (d->weight == v)
666     d->weight = NULL;
667   if (d->filter == v)
668     d->filter = NULL;
669   dict_clear_vectors (d);
670
671   /* Remove V from var array. */
672   remove_element (d->var, d->var_cnt, sizeof *d->var, v->index);
673   d->var_cnt--;
674
675   /* Update index. */
676   for (i = v->index; i < d->var_cnt; i++)
677     d->var[i]->index = i;
678
679   /* Update name hash. */
680   hsh_force_delete (d->name_tab, v);
681
682   /* Free memory. */
683   val_labs_destroy (v->val_labs);
684   free (v->label);
685   free (v);
686 }
687
688 /* Deletes the COUNT variables listed in VARS from D.  This is
689    unsafe; see the comment on dict_delete_var() for details. */
690 void 
691 dict_delete_vars (struct dictionary *d,
692                   struct variable *const *vars, size_t count) 
693 {
694   /* FIXME: this can be done in O(count) time, but this algorithm
695      is O(count**2). */
696   assert (d != NULL);
697   assert (count == 0 || vars != NULL);
698
699   while (count-- > 0)
700     dict_delete_var (d, *vars++);
701 }
702
703 /* Reorders the variables in D, placing the COUNT variables
704    listed in ORDER in that order at the beginning of D.  The
705    other variables in D, if any, retain their relative
706    positions. */
707 void 
708 dict_reorder_vars (struct dictionary *d,
709                    struct variable *const *order, size_t count) 
710 {
711   struct variable **new_var;
712   size_t i;
713   
714   assert (d != NULL);
715   assert (count == 0 || order != NULL);
716   assert (count <= d->var_cnt);
717
718   new_var = xmalloc (d->var_cnt * sizeof *new_var);
719   memcpy (new_var, order, count * sizeof *new_var);
720   for (i = 0; i < count; i++) 
721     {
722       assert (d->var[order[i]->index] != NULL);
723       d->var[order[i]->index] = NULL;
724       order[i]->index = i;
725     }
726   for (i = 0; i < d->var_cnt; i++)
727     if (d->var[i] != NULL)
728       {
729         assert (count < d->var_cnt);
730         new_var[count] = d->var[i];
731         new_var[count]->index = count;
732         count++;
733       }
734   free (d->var);
735   d->var = new_var;
736 }
737
738 /* Renames COUNT variables specified in VARS to the names given
739    in NEW_NAMES within dictionary D.  If the renaming would
740    result in a duplicate variable name, returns zero and stores a
741    name that would be duplicated into *ERR_NAME (if ERR_NAME is
742    non-null).  Otherwise, the renaming is successful, and nonzero
743    is returned. */
744 int
745 dict_rename_vars (struct dictionary *d,
746                   struct variable **vars, char **new_names,
747                   size_t count, char **err_name) 
748 {
749   char **old_names;
750   size_t i;
751   int success = 1;
752
753
754   assert (d != NULL);
755   assert (count == 0 || vars != NULL);
756   assert (count == 0 || new_names != NULL);
757
758
759   old_names = xmalloc (count * sizeof *old_names);
760   for (i = 0; i < count; i++) 
761     {
762       assert (d->var[vars[i]->index] == vars[i]);
763       hsh_force_delete (d->name_tab, vars[i]);
764       old_names[i] = xstrdup (vars[i]->name);
765     }
766   
767   for (i = 0; i < count; i++)
768     {
769       char *sn;
770       struct name_table_entry key;
771       struct name_table_entry *nte;
772       assert (new_names[i] != NULL);
773       assert (*new_names[i] != '\0');
774       assert (strlen (new_names[i]) <= LONG_NAME_LEN );
775       
776       sn = make_short_name(d, new_names[i]);
777       strncpy(vars[i]->name, sn, SHORT_NAME_LEN);
778       free(sn);
779       
780
781
782       key.longname = vars[i]->longname;
783       nte = hsh_find (d->long_name_tab, &key);
784       
785       free( nte->longname ) ;
786       nte->longname = strdup ( new_names[i]);
787       vars[i]->longname = nte->longname;
788
789       if (hsh_insert (d->name_tab, vars[i]) != NULL )
790         {
791           size_t fail_idx = i;
792           if (err_name != NULL) 
793             *err_name = new_names[i];
794
795           for (i = 0; i < fail_idx; i++)
796             hsh_force_delete (d->name_tab, vars[i]);
797           
798           for (i = 0; i < count; i++)
799             {
800               strcpy (vars[i]->name, old_names[i]);
801               hsh_force_insert (d->name_tab, vars[i]);
802  
803       key.longname = vars[i]->longname;
804       nte = hsh_find (d->long_name_tab, &key);
805       
806       free( nte->longname ) ;
807       nte->longname = strdup ( old_names[i]);
808       vars[i]->longname = nte->longname;
809
810             }
811
812           success = 0;
813           break;
814         }
815     }
816
817   for (i = 0; i < count; i++)
818     free (old_names[i]);
819   free (old_names);
820
821   return success;
822 }
823
824 /* Returns the weighting variable in dictionary D, or a null
825    pointer if the dictionary is unweighted. */
826 struct variable *
827 dict_get_weight (const struct dictionary *d) 
828 {
829   assert (d != NULL);
830   assert (d->weight == NULL || dict_contains_var (d, d->weight));
831   
832   return d->weight;
833 }
834
835 /* Returns the value of D's weighting variable in case C, except that a
836    negative weight is returned as 0.  Returns 1 if the dictionary is
837    unweighted. Will warn about missing, negative, or zero values if
838    warn_on_invalid is nonzero. The function will set warn_on_invalid to zero
839    if an invalid weight is found. */
840 double
841 dict_get_case_weight (const struct dictionary *d, const struct ccase *c, 
842                       int *warn_on_invalid)
843 {
844   assert (d != NULL);
845   assert (c != NULL);
846
847   if (d->weight == NULL)
848     return 1.0;
849   else 
850     {
851       double w = case_num (c, d->weight->fv);
852       if ( w < 0.0 || w == SYSMIS || is_num_user_missing(w, d->weight) )
853         w = 0.0;
854       if ( w == 0.0 && *warn_on_invalid ) {
855           *warn_on_invalid = 0;
856           msg (SW, _("At least one case in the data file had a weight value "
857                      "that was user-missing, system-missing, zero, or "
858                      "negative.  These case(s) were ignored."));
859       }
860       return w;
861     }
862 }
863
864 /* Sets the weighting variable of D to V, or turning off
865    weighting if V is a null pointer. */
866 void
867 dict_set_weight (struct dictionary *d, struct variable *v) 
868 {
869   assert (d != NULL);
870   assert (v == NULL || dict_contains_var (d, v));
871   assert (v == NULL || v->type == NUMERIC);
872
873   d->weight = v;
874 }
875
876 /* Returns the filter variable in dictionary D (see cmd_filter())
877    or a null pointer if the dictionary is unfiltered. */
878 struct variable *
879 dict_get_filter (const struct dictionary *d) 
880 {
881   assert (d != NULL);
882   assert (d->filter == NULL || dict_contains_var (d, d->filter));
883   
884   return d->filter;
885 }
886
887 /* Sets V as the filter variable for dictionary D.  Passing a
888    null pointer for V turn off filtering. */
889 void
890 dict_set_filter (struct dictionary *d, struct variable *v)
891 {
892   assert (d != NULL);
893   assert (v == NULL || dict_contains_var (d, v));
894
895   d->filter = v;
896 }
897
898 /* Returns the case limit for dictionary D, or zero if the number
899    of cases is unlimited (see cmd_n()). */
900 int
901 dict_get_case_limit (const struct dictionary *d) 
902 {
903   assert (d != NULL);
904
905   return d->case_limit;
906 }
907
908 /* Sets CASE_LIMIT as the case limit for dictionary D.  Zero for
909    CASE_LIMIT indicates no limit. */
910 void
911 dict_set_case_limit (struct dictionary *d, int case_limit) 
912 {
913   assert (d != NULL);
914   assert (case_limit >= 0);
915
916   d->case_limit = case_limit;
917 }
918
919 /* Returns the index of the next value to be added to D.  This
920    value is the number of `union value's that need to be
921    allocated to store a case for dictionary D. */
922 int
923 dict_get_next_value_idx (const struct dictionary *d) 
924 {
925   assert (d != NULL);
926
927   return d->next_value_idx;
928 }
929
930 /* Returns the number of bytes needed to store a case for
931    dictionary D. */
932 size_t
933 dict_get_case_size (const struct dictionary *d) 
934 {
935   assert (d != NULL);
936
937   return sizeof (union value) * dict_get_next_value_idx (d);
938 }
939
940 /* Deletes scratch variables in dictionary D and reassigns values
941    so that fragmentation is eliminated. */
942 void
943 dict_compact_values (struct dictionary *d) 
944 {
945   size_t i;
946
947   d->next_value_idx = 0;
948   for (i = 0; i < d->var_cnt; )
949     {
950       struct variable *v = d->var[i];
951
952       if (dict_class_from_id (v->name) != DC_SCRATCH) 
953         {
954           v->fv = d->next_value_idx;
955           d->next_value_idx += v->nv;
956           i++;
957         }
958       else
959         dict_delete_var (default_dict, v);
960     }
961 }
962
963 /* Copies values from SRC, which represents a case arranged
964    according to dictionary D, to DST, which represents a case
965    arranged according to the dictionary that will be produced by
966    dict_compact_values(D). */
967 void
968 dict_compact_case (const struct dictionary *d,
969                    struct ccase *dst, const struct ccase *src)
970 {
971   size_t i;
972   size_t value_idx;
973
974   value_idx = 0;
975   for (i = 0; i < d->var_cnt; i++) 
976     {
977       struct variable *v = d->var[i];
978
979       if (dict_class_from_id (v->name) != DC_SCRATCH)
980         {
981           case_copy (dst, value_idx, src, v->fv, v->nv);
982           value_idx += v->nv;
983         }
984     }
985 }
986
987 /* Returns the number of values that would be used by a case if
988    dict_compact_values() were called. */
989 size_t
990 dict_get_compacted_value_cnt (const struct dictionary *d) 
991 {
992   size_t i;
993   size_t cnt;
994
995   cnt = 0;
996   for (i = 0; i < d->var_cnt; i++)
997     if (dict_class_from_id (d->var[i]->name) != DC_SCRATCH) 
998       cnt += d->var[i]->nv;
999   return cnt;
1000 }
1001
1002 /* Creates and returns an array mapping from a dictionary index
1003    to the `fv' that the corresponding variable will have after
1004    calling dict_compact_values().  Scratch variables receive -1
1005    for `fv' because dict_compact_values() will delete them. */
1006 int *
1007 dict_get_compacted_idx_to_fv (const struct dictionary *d) 
1008 {
1009   size_t i;
1010   size_t next_value_idx;
1011   int *idx_to_fv;
1012   
1013   idx_to_fv = xmalloc (d->var_cnt * sizeof *idx_to_fv);
1014   next_value_idx = 0;
1015   for (i = 0; i < d->var_cnt; i++)
1016     {
1017       struct variable *v = d->var[i];
1018
1019       if (dict_class_from_id (v->name) != DC_SCRATCH) 
1020         {
1021           idx_to_fv[i] = next_value_idx;
1022           next_value_idx += v->nv;
1023         }
1024       else 
1025         idx_to_fv[i] = -1;
1026     }
1027   return idx_to_fv;
1028 }
1029
1030 /* Returns the SPLIT FILE vars (see cmd_split_file()).  Call
1031    dict_get_split_cnt() to determine how many SPLIT FILE vars
1032    there are.  Returns a null pointer if and only if there are no
1033    SPLIT FILE vars. */
1034 struct variable *const *
1035 dict_get_split_vars (const struct dictionary *d) 
1036 {
1037   assert (d != NULL);
1038   
1039   return d->split;
1040 }
1041
1042 /* Returns the number of SPLIT FILE vars. */
1043 size_t
1044 dict_get_split_cnt (const struct dictionary *d) 
1045 {
1046   assert (d != NULL);
1047
1048   return d->split_cnt;
1049 }
1050
1051 /* Sets CNT split vars SPLIT in dictionary D. */
1052 void
1053 dict_set_split_vars (struct dictionary *d,
1054                      struct variable *const *split, size_t cnt)
1055 {
1056   assert (d != NULL);
1057   assert (cnt == 0 || split != NULL);
1058
1059   d->split_cnt = cnt;
1060   d->split = xrealloc (d->split, cnt * sizeof *d->split);
1061   memcpy (d->split, split, cnt * sizeof *d->split);
1062 }
1063
1064 /* Returns the file label for D, or a null pointer if D is
1065    unlabeled (see cmd_file_label()). */
1066 const char *
1067 dict_get_label (const struct dictionary *d) 
1068 {
1069   assert (d != NULL);
1070
1071   return d->label;
1072 }
1073
1074 /* Sets D's file label to LABEL, truncating it to a maximum of 60
1075    characters. */
1076 void
1077 dict_set_label (struct dictionary *d, const char *label) 
1078 {
1079   assert (d != NULL);
1080
1081   free (d->label);
1082   if (label == NULL)
1083     d->label = NULL;
1084   else if (strlen (label) < 60)
1085     d->label = xstrdup (label);
1086   else 
1087     {
1088       d->label = xmalloc (61);
1089       memcpy (d->label, label, 60);
1090       d->label[60] = '\0';
1091     }
1092 }
1093
1094 /* Returns the documents for D, or a null pointer if D has no
1095    documents (see cmd_document()).. */
1096 const char *
1097 dict_get_documents (const struct dictionary *d) 
1098 {
1099   assert (d != NULL);
1100
1101   return d->documents;
1102 }
1103
1104 /* Sets the documents for D to DOCUMENTS, or removes D's
1105    documents if DOCUMENT is a null pointer. */
1106 void
1107 dict_set_documents (struct dictionary *d, const char *documents)
1108 {
1109   assert (d != NULL);
1110
1111   free (d->documents);
1112   if (documents == NULL)
1113     d->documents = NULL;
1114   else
1115     d->documents = xstrdup (documents);
1116 }
1117
1118 /* Creates in D a vector named NAME that contains CNT variables
1119    VAR (see cmd_vector()).  Returns nonzero if successful, or
1120    zero if a vector named NAME already exists in D. */
1121 int
1122 dict_create_vector (struct dictionary *d,
1123                     const char *name,
1124                     struct variable **var, size_t cnt) 
1125 {
1126   struct vector *vector;
1127
1128   assert (d != NULL);
1129   assert (name != NULL);
1130   assert (strlen (name) > 0 && strlen (name) <= SHORT_NAME_LEN );
1131   assert (var != NULL);
1132   assert (cnt > 0);
1133   
1134   if (dict_lookup_vector (d, name) != NULL)
1135     return 0;
1136
1137   d->vector = xrealloc (d->vector, (d->vector_cnt + 1) * sizeof *d->vector);
1138   vector = d->vector[d->vector_cnt] = xmalloc (sizeof *vector);
1139   vector->idx = d->vector_cnt++;
1140   strncpy (vector->name, name, SHORT_NAME_LEN);
1141   vector->name[SHORT_NAME_LEN] = '\0';
1142   vector->var = xmalloc (cnt * sizeof *var);
1143   memcpy (vector->var, var, cnt * sizeof *var);
1144   vector->cnt = cnt;
1145   
1146   return 1;
1147 }
1148
1149 /* Returns the vector in D with index IDX, which must be less
1150    than dict_get_vector_cnt (D). */
1151 const struct vector *
1152 dict_get_vector (const struct dictionary *d, size_t idx) 
1153 {
1154   assert (d != NULL);
1155   assert (idx < d->vector_cnt);
1156
1157   return d->vector[idx];
1158 }
1159
1160 /* Returns the number of vectors in D. */
1161 size_t
1162 dict_get_vector_cnt (const struct dictionary *d) 
1163 {
1164   assert (d != NULL);
1165
1166   return d->vector_cnt;
1167 }
1168
1169 /* Looks up and returns the vector within D with the given
1170    NAME. */
1171 const struct vector *
1172 dict_lookup_vector (const struct dictionary *d, const char *name) 
1173 {
1174   size_t i;
1175
1176   assert (d != NULL);
1177   assert (name != NULL);
1178
1179   for (i = 0; i < d->vector_cnt; i++)
1180     if (!strcmp (d->vector[i]->name, name))
1181       return d->vector[i];
1182   return NULL;
1183 }
1184
1185 /* Deletes all vectors from D. */
1186 void
1187 dict_clear_vectors (struct dictionary *d) 
1188 {
1189   size_t i;
1190   
1191   assert (d != NULL);
1192
1193   for (i = 0; i < d->vector_cnt; i++) 
1194     {
1195       free (d->vector[i]->var);
1196       free (d->vector[i]);
1197     }
1198   free (d->vector);
1199   d->vector = NULL;
1200   d->vector_cnt = 0;
1201 }
1202
1203
1204 static const char * quasi_base27(int i);
1205
1206
1207 /* Convert I to quasi base 27 
1208    The result is a staticly allocated string.
1209 */
1210 static const char *
1211 quasi_base27(int i)
1212 {
1213   static char result[SHORT_NAME_LEN + 1];
1214   static char reverse[SHORT_NAME_LEN + 1];
1215
1216   /* FIXME: check the result cant overflow these arrays */
1217
1218   char *s = result ;
1219   const int radix = 27;
1220   int units;
1221
1222   /* and here's the quasi-ness of this routine */
1223   i = i + ( i / radix );
1224
1225   strcpy(result,"");
1226   do {
1227     units = i % radix;
1228     *s++ = (units > 0 ) ? units + 'A' - 1 : 'A';
1229     i = i / radix; 
1230   } while (i > 0 ) ;
1231   *s = '\0';
1232
1233   /* Reverse the result */
1234   i = strlen(result);
1235   s = reverse;
1236   while(i >= 0)
1237         *s++ = result[--i];
1238   *s = '\0';
1239         
1240   return reverse;
1241 }
1242
1243
1244 /* Generate a short name, given a long name.
1245    The return value of this function must be freed by the caller. 
1246 */
1247 static char *
1248 make_short_name(struct dictionary *dict, const char *longname)
1249 {
1250   int i = 0;
1251   char *p;
1252  
1253
1254   char *d = xmalloc ( SHORT_NAME_LEN + 1);
1255
1256   /* Truncate the name */
1257   strncpy(d, longname, SHORT_NAME_LEN);
1258   d[SHORT_NAME_LEN] = '\0';
1259
1260   /* Convert to upper case */
1261   for ( p = d; *p ; ++p )
1262         *p = toupper(*p);
1263
1264   /* If a variable with that name already exists, then munge it
1265      until there's no conflict */
1266   while (0 != hsh_find (dict->name_tab, d))
1267   {
1268         const char *suffix = quasi_base27(i++);
1269
1270         d[SHORT_NAME_LEN -  strlen(suffix) - 1 ] = '_';
1271         d[SHORT_NAME_LEN -  strlen(suffix)  ] = '\0';
1272         strcat(d, suffix);
1273   }
1274
1275   return d;
1276 }
1277
1278
1279
1280