Changed all the licence notices in all the files.
[pspp] / 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., 51 Franklin Street, Fifth Floor, Boston, MA
18    02110-1301, 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 + 1);
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   dict_add_longvar_entry (d, new_name, new_name);
570 }
571
572 /* Returns the variable named NAME in D, or a null pointer if no
573    variable has that name. */
574 struct variable *
575 dict_lookup_var (const struct dictionary *d, const char *name)
576 {
577   struct variable v;
578   struct variable *vr;
579   
580   char *short_name;
581   struct name_table_entry key;
582   struct name_table_entry *nte;
583
584   assert (d != NULL);
585   assert (name != NULL);
586   assert (strlen (name) >= 1 && strlen (name) <= LONG_NAME_LEN);
587
588   key.longname = name;
589   nte = hsh_find (d->long_name_tab, &key);
590   
591   if ( ! nte ) 
592   {
593     return 0;
594   }
595
596   short_name = nte->name ;
597
598   strncpy (v.name, short_name, sizeof v.name);
599   v.name[SHORT_NAME_LEN] = '\0';
600
601   vr = hsh_find (d->name_tab, &v);
602
603   return vr; 
604 }
605
606
607 /* Returns the variable named NAME in D.  Assert-fails if no
608    variable has that name. */
609 struct variable *
610 dict_lookup_var_assert (const struct dictionary *d, const char *name)
611 {
612   struct variable *v = dict_lookup_var (d, name);
613   assert (v != NULL);
614   return v;
615 }
616
617 /* Returns nonzero if variable V is in dictionary D. */
618 int
619 dict_contains_var (const struct dictionary *d, const struct variable *v)
620 {
621   assert (d != NULL);
622   assert (v != NULL);
623
624   return v->index >= 0 && v->index < d->var_cnt && d->var[v->index] == v;
625 }
626
627 /* Compares two double pointers to variables, which should point
628    to elements of a struct dictionary's `var' member array. */
629 static int
630 compare_var_ptrs (const void *a_, const void *b_, void *aux UNUSED) 
631 {
632   struct variable *const *a = a_;
633   struct variable *const *b = b_;
634
635   return *a < *b ? -1 : *a > *b;
636 }
637
638 /* Deletes variable V from dictionary D and frees V.
639
640    This is a very bad idea if there might be any pointers to V
641    from outside D.  In general, no variable in default_dict
642    should be deleted when any transformations are active, because
643    those transformations might reference the deleted variable.
644    The safest time to delete a variable is just after a procedure
645    has been executed, as done by MODIFY VARS.
646
647    Pointers to V within D are not a problem, because
648    dict_delete_var() knows to remove V from split variables,
649    weights, filters, etc. */
650 void
651 dict_delete_var (struct dictionary *d, struct variable *v) 
652 {
653   size_t i;
654
655   assert (d != NULL);
656   assert (v != NULL);
657   assert (dict_contains_var (d, v));
658   assert (d->var[v->index] == v);
659
660   /* Delete aux data. */
661   var_clear_aux (v);
662
663   /* Remove V from splits, weight, filter variables. */
664   d->split_cnt = remove_equal (d->split, d->split_cnt, sizeof *d->split,
665                                &v, compare_var_ptrs, NULL);
666   if (d->weight == v)
667     d->weight = NULL;
668   if (d->filter == v)
669     d->filter = NULL;
670   dict_clear_vectors (d);
671
672   /* Remove V from var array. */
673   remove_element (d->var, d->var_cnt, sizeof *d->var, v->index);
674   d->var_cnt--;
675
676   /* Update index. */
677   for (i = v->index; i < d->var_cnt; i++)
678     d->var[i]->index = i;
679
680   /* Update name hash. */
681   hsh_force_delete (d->name_tab, v);
682
683   /* Free memory. */
684   val_labs_destroy (v->val_labs);
685   free (v->label);
686   free (v);
687 }
688
689 /* Deletes the COUNT variables listed in VARS from D.  This is
690    unsafe; see the comment on dict_delete_var() for details. */
691 void 
692 dict_delete_vars (struct dictionary *d,
693                   struct variable *const *vars, size_t count) 
694 {
695   /* FIXME: this can be done in O(count) time, but this algorithm
696      is O(count**2). */
697   assert (d != NULL);
698   assert (count == 0 || vars != NULL);
699
700   while (count-- > 0)
701     dict_delete_var (d, *vars++);
702 }
703
704 /* Reorders the variables in D, placing the COUNT variables
705    listed in ORDER in that order at the beginning of D.  The
706    other variables in D, if any, retain their relative
707    positions. */
708 void 
709 dict_reorder_vars (struct dictionary *d,
710                    struct variable *const *order, size_t count) 
711 {
712   struct variable **new_var;
713   size_t i;
714   
715   assert (d != NULL);
716   assert (count == 0 || order != NULL);
717   assert (count <= d->var_cnt);
718
719   new_var = xmalloc (d->var_cnt * sizeof *new_var);
720   memcpy (new_var, order, count * sizeof *new_var);
721   for (i = 0; i < count; i++) 
722     {
723       assert (d->var[order[i]->index] != NULL);
724       d->var[order[i]->index] = NULL;
725       order[i]->index = i;
726     }
727   for (i = 0; i < d->var_cnt; i++)
728     if (d->var[i] != NULL)
729       {
730         assert (count < d->var_cnt);
731         new_var[count] = d->var[i];
732         new_var[count]->index = count;
733         count++;
734       }
735   free (d->var);
736   d->var = new_var;
737 }
738
739 /* Renames COUNT variables specified in VARS to the names given
740    in NEW_NAMES within dictionary D.  If the renaming would
741    result in a duplicate variable name, returns zero and stores a
742    name that would be duplicated into *ERR_NAME (if ERR_NAME is
743    non-null).  Otherwise, the renaming is successful, and nonzero
744    is returned. */
745 int
746 dict_rename_vars (struct dictionary *d,
747                   struct variable **vars, char **new_names,
748                   size_t count, char **err_name) 
749 {
750   char **old_names;
751   size_t i;
752   int success = 1;
753
754
755   assert (d != NULL);
756   assert (count == 0 || vars != NULL);
757   assert (count == 0 || new_names != NULL);
758
759
760   old_names = xmalloc (count * sizeof *old_names);
761   for (i = 0; i < count; i++) 
762     {
763       assert (d->var[vars[i]->index] == vars[i]);
764       hsh_force_delete (d->name_tab, vars[i]);
765       old_names[i] = xstrdup (vars[i]->name);
766     }
767   
768   for (i = 0; i < count; i++)
769     {
770       char *sn;
771       struct name_table_entry key;
772       struct name_table_entry *nte;
773       assert (new_names[i] != NULL);
774       assert (*new_names[i] != '\0');
775       assert (strlen (new_names[i]) <= LONG_NAME_LEN );
776       
777       sn = make_short_name(d, new_names[i]);
778       strncpy(vars[i]->name, sn, SHORT_NAME_LEN + 1);
779       free(sn);
780       
781
782
783       key.longname = vars[i]->longname;
784       nte = hsh_find (d->long_name_tab, &key);
785       
786       free( nte->longname ) ;
787       nte->longname = strdup ( new_names[i]);
788       vars[i]->longname = nte->longname;
789
790       if (hsh_insert (d->name_tab, vars[i]) != NULL )
791         {
792           size_t fail_idx = i;
793           if (err_name != NULL) 
794             *err_name = new_names[i];
795
796           for (i = 0; i < fail_idx; i++)
797             hsh_force_delete (d->name_tab, vars[i]);
798           
799           for (i = 0; i < count; i++)
800             {
801               strcpy (vars[i]->name, old_names[i]);
802               hsh_force_insert (d->name_tab, vars[i]);
803  
804       key.longname = vars[i]->longname;
805       nte = hsh_find (d->long_name_tab, &key);
806       
807       free( nte->longname ) ;
808       nte->longname = strdup ( old_names[i]);
809       vars[i]->longname = nte->longname;
810
811             }
812
813           success = 0;
814           break;
815         }
816     }
817
818   for (i = 0; i < count; i++)
819     free (old_names[i]);
820   free (old_names);
821
822   return success;
823 }
824
825 /* Returns the weighting variable in dictionary D, or a null
826    pointer if the dictionary is unweighted. */
827 struct variable *
828 dict_get_weight (const struct dictionary *d) 
829 {
830   assert (d != NULL);
831   assert (d->weight == NULL || dict_contains_var (d, d->weight));
832   
833   return d->weight;
834 }
835
836 /* Returns the value of D's weighting variable in case C, except that a
837    negative weight is returned as 0.  Returns 1 if the dictionary is
838    unweighted. Will warn about missing, negative, or zero values if
839    warn_on_invalid is nonzero. The function will set warn_on_invalid to zero
840    if an invalid weight is found. */
841 double
842 dict_get_case_weight (const struct dictionary *d, const struct ccase *c, 
843                       int *warn_on_invalid)
844 {
845   assert (d != NULL);
846   assert (c != NULL);
847
848   if (d->weight == NULL)
849     return 1.0;
850   else 
851     {
852       double w = case_num (c, d->weight->fv);
853       if ( w < 0.0 || w == SYSMIS || is_num_user_missing(w, d->weight) )
854         w = 0.0;
855       if ( w == 0.0 && *warn_on_invalid ) {
856           *warn_on_invalid = 0;
857           msg (SW, _("At least one case in the data file had a weight value "
858                      "that was user-missing, system-missing, zero, or "
859                      "negative.  These case(s) were ignored."));
860       }
861       return w;
862     }
863 }
864
865 /* Sets the weighting variable of D to V, or turning off
866    weighting if V is a null pointer. */
867 void
868 dict_set_weight (struct dictionary *d, struct variable *v) 
869 {
870   assert (d != NULL);
871   assert (v == NULL || dict_contains_var (d, v));
872   assert (v == NULL || v->type == NUMERIC);
873
874   d->weight = v;
875 }
876
877 /* Returns the filter variable in dictionary D (see cmd_filter())
878    or a null pointer if the dictionary is unfiltered. */
879 struct variable *
880 dict_get_filter (const struct dictionary *d) 
881 {
882   assert (d != NULL);
883   assert (d->filter == NULL || dict_contains_var (d, d->filter));
884   
885   return d->filter;
886 }
887
888 /* Sets V as the filter variable for dictionary D.  Passing a
889    null pointer for V turn off filtering. */
890 void
891 dict_set_filter (struct dictionary *d, struct variable *v)
892 {
893   assert (d != NULL);
894   assert (v == NULL || dict_contains_var (d, v));
895
896   d->filter = v;
897 }
898
899 /* Returns the case limit for dictionary D, or zero if the number
900    of cases is unlimited (see cmd_n()). */
901 int
902 dict_get_case_limit (const struct dictionary *d) 
903 {
904   assert (d != NULL);
905
906   return d->case_limit;
907 }
908
909 /* Sets CASE_LIMIT as the case limit for dictionary D.  Zero for
910    CASE_LIMIT indicates no limit. */
911 void
912 dict_set_case_limit (struct dictionary *d, int case_limit) 
913 {
914   assert (d != NULL);
915   assert (case_limit >= 0);
916
917   d->case_limit = case_limit;
918 }
919
920 /* Returns the index of the next value to be added to D.  This
921    value is the number of `union value's that need to be
922    allocated to store a case for dictionary D. */
923 int
924 dict_get_next_value_idx (const struct dictionary *d) 
925 {
926   assert (d != NULL);
927
928   return d->next_value_idx;
929 }
930
931 /* Returns the number of bytes needed to store a case for
932    dictionary D. */
933 size_t
934 dict_get_case_size (const struct dictionary *d) 
935 {
936   assert (d != NULL);
937
938   return sizeof (union value) * dict_get_next_value_idx (d);
939 }
940
941 /* Deletes scratch variables in dictionary D and reassigns values
942    so that fragmentation is eliminated. */
943 void
944 dict_compact_values (struct dictionary *d) 
945 {
946   size_t i;
947
948   d->next_value_idx = 0;
949   for (i = 0; i < d->var_cnt; )
950     {
951       struct variable *v = d->var[i];
952
953       if (dict_class_from_id (v->name) != DC_SCRATCH) 
954         {
955           v->fv = d->next_value_idx;
956           d->next_value_idx += v->nv;
957           i++;
958         }
959       else
960         dict_delete_var (default_dict, v);
961     }
962 }
963
964 /* Copies values from SRC, which represents a case arranged
965    according to dictionary D, to DST, which represents a case
966    arranged according to the dictionary that will be produced by
967    dict_compact_values(D). */
968 void
969 dict_compact_case (const struct dictionary *d,
970                    struct ccase *dst, const struct ccase *src)
971 {
972   size_t i;
973   size_t value_idx;
974
975   value_idx = 0;
976   for (i = 0; i < d->var_cnt; i++) 
977     {
978       struct variable *v = d->var[i];
979
980       if (dict_class_from_id (v->name) != DC_SCRATCH)
981         {
982           case_copy (dst, value_idx, src, v->fv, v->nv);
983           value_idx += v->nv;
984         }
985     }
986 }
987
988 /* Returns the number of values that would be used by a case if
989    dict_compact_values() were called. */
990 size_t
991 dict_get_compacted_value_cnt (const struct dictionary *d) 
992 {
993   size_t i;
994   size_t cnt;
995
996   cnt = 0;
997   for (i = 0; i < d->var_cnt; i++)
998     if (dict_class_from_id (d->var[i]->name) != DC_SCRATCH) 
999       cnt += d->var[i]->nv;
1000   return cnt;
1001 }
1002
1003 /* Creates and returns an array mapping from a dictionary index
1004    to the `fv' that the corresponding variable will have after
1005    calling dict_compact_values().  Scratch variables receive -1
1006    for `fv' because dict_compact_values() will delete them. */
1007 int *
1008 dict_get_compacted_idx_to_fv (const struct dictionary *d) 
1009 {
1010   size_t i;
1011   size_t next_value_idx;
1012   int *idx_to_fv;
1013   
1014   idx_to_fv = xmalloc (d->var_cnt * sizeof *idx_to_fv);
1015   next_value_idx = 0;
1016   for (i = 0; i < d->var_cnt; i++)
1017     {
1018       struct variable *v = d->var[i];
1019
1020       if (dict_class_from_id (v->name) != DC_SCRATCH) 
1021         {
1022           idx_to_fv[i] = next_value_idx;
1023           next_value_idx += v->nv;
1024         }
1025       else 
1026         idx_to_fv[i] = -1;
1027     }
1028   return idx_to_fv;
1029 }
1030
1031 /* Returns the SPLIT FILE vars (see cmd_split_file()).  Call
1032    dict_get_split_cnt() to determine how many SPLIT FILE vars
1033    there are.  Returns a null pointer if and only if there are no
1034    SPLIT FILE vars. */
1035 struct variable *const *
1036 dict_get_split_vars (const struct dictionary *d) 
1037 {
1038   assert (d != NULL);
1039   
1040   return d->split;
1041 }
1042
1043 /* Returns the number of SPLIT FILE vars. */
1044 size_t
1045 dict_get_split_cnt (const struct dictionary *d) 
1046 {
1047   assert (d != NULL);
1048
1049   return d->split_cnt;
1050 }
1051
1052 /* Sets CNT split vars SPLIT in dictionary D. */
1053 void
1054 dict_set_split_vars (struct dictionary *d,
1055                      struct variable *const *split, size_t cnt)
1056 {
1057   assert (d != NULL);
1058   assert (cnt == 0 || split != NULL);
1059
1060   d->split_cnt = cnt;
1061   d->split = xrealloc (d->split, cnt * sizeof *d->split);
1062   memcpy (d->split, split, cnt * sizeof *d->split);
1063 }
1064
1065 /* Returns the file label for D, or a null pointer if D is
1066    unlabeled (see cmd_file_label()). */
1067 const char *
1068 dict_get_label (const struct dictionary *d) 
1069 {
1070   assert (d != NULL);
1071
1072   return d->label;
1073 }
1074
1075 /* Sets D's file label to LABEL, truncating it to a maximum of 60
1076    characters. */
1077 void
1078 dict_set_label (struct dictionary *d, const char *label) 
1079 {
1080   assert (d != NULL);
1081
1082   free (d->label);
1083   if (label == NULL)
1084     d->label = NULL;
1085   else if (strlen (label) < 60)
1086     d->label = xstrdup (label);
1087   else 
1088     {
1089       d->label = xmalloc (61);
1090       memcpy (d->label, label, 60);
1091       d->label[60] = '\0';
1092     }
1093 }
1094
1095 /* Returns the documents for D, or a null pointer if D has no
1096    documents (see cmd_document()).. */
1097 const char *
1098 dict_get_documents (const struct dictionary *d) 
1099 {
1100   assert (d != NULL);
1101
1102   return d->documents;
1103 }
1104
1105 /* Sets the documents for D to DOCUMENTS, or removes D's
1106    documents if DOCUMENT is a null pointer. */
1107 void
1108 dict_set_documents (struct dictionary *d, const char *documents)
1109 {
1110   assert (d != NULL);
1111
1112   free (d->documents);
1113   if (documents == NULL)
1114     d->documents = NULL;
1115   else
1116     d->documents = xstrdup (documents);
1117 }
1118
1119 /* Creates in D a vector named NAME that contains CNT variables
1120    VAR (see cmd_vector()).  Returns nonzero if successful, or
1121    zero if a vector named NAME already exists in D. */
1122 int
1123 dict_create_vector (struct dictionary *d,
1124                     const char *name,
1125                     struct variable **var, size_t cnt) 
1126 {
1127   struct vector *vector;
1128
1129   assert (d != NULL);
1130   assert (name != NULL);
1131   assert (strlen (name) > 0 && strlen (name) <= SHORT_NAME_LEN );
1132   assert (var != NULL);
1133   assert (cnt > 0);
1134   
1135   if (dict_lookup_vector (d, name) != NULL)
1136     return 0;
1137
1138   d->vector = xrealloc (d->vector, (d->vector_cnt + 1) * sizeof *d->vector);
1139   vector = d->vector[d->vector_cnt] = xmalloc (sizeof *vector);
1140   vector->idx = d->vector_cnt++;
1141   strncpy (vector->name, name, SHORT_NAME_LEN);
1142   vector->name[SHORT_NAME_LEN] = '\0';
1143   vector->var = xmalloc (cnt * sizeof *var);
1144   memcpy (vector->var, var, cnt * sizeof *var);
1145   vector->cnt = cnt;
1146   
1147   return 1;
1148 }
1149
1150 /* Returns the vector in D with index IDX, which must be less
1151    than dict_get_vector_cnt (D). */
1152 const struct vector *
1153 dict_get_vector (const struct dictionary *d, size_t idx) 
1154 {
1155   assert (d != NULL);
1156   assert (idx < d->vector_cnt);
1157
1158   return d->vector[idx];
1159 }
1160
1161 /* Returns the number of vectors in D. */
1162 size_t
1163 dict_get_vector_cnt (const struct dictionary *d) 
1164 {
1165   assert (d != NULL);
1166
1167   return d->vector_cnt;
1168 }
1169
1170 /* Looks up and returns the vector within D with the given
1171    NAME. */
1172 const struct vector *
1173 dict_lookup_vector (const struct dictionary *d, const char *name) 
1174 {
1175   size_t i;
1176
1177   assert (d != NULL);
1178   assert (name != NULL);
1179
1180   for (i = 0; i < d->vector_cnt; i++)
1181     if (!strcmp (d->vector[i]->name, name))
1182       return d->vector[i];
1183   return NULL;
1184 }
1185
1186 /* Deletes all vectors from D. */
1187 void
1188 dict_clear_vectors (struct dictionary *d) 
1189 {
1190   size_t i;
1191   
1192   assert (d != NULL);
1193
1194   for (i = 0; i < d->vector_cnt; i++) 
1195     {
1196       free (d->vector[i]->var);
1197       free (d->vector[i]);
1198     }
1199   free (d->vector);
1200   d->vector = NULL;
1201   d->vector_cnt = 0;
1202 }
1203
1204
1205 static const char * quasi_base27(int i);
1206
1207
1208 /* Convert I to quasi base 27 
1209    The result is a staticly allocated string.
1210 */
1211 static const char *
1212 quasi_base27(int i)
1213 {
1214   static char result[SHORT_NAME_LEN + 1];
1215   static char reverse[SHORT_NAME_LEN + 1];
1216
1217   /* FIXME: check the result cant overflow these arrays */
1218
1219   char *s = result ;
1220   const int radix = 27;
1221   int units;
1222
1223   /* and here's the quasi-ness of this routine */
1224   i = i + ( i / radix );
1225
1226   strcpy(result,"");
1227   do {
1228     units = i % radix;
1229     *s++ = (units > 0 ) ? units + 'A' - 1 : 'A';
1230     i = i / radix; 
1231   } while (i > 0 ) ;
1232   *s = '\0';
1233
1234   /* Reverse the result */
1235   i = strlen(result);
1236   s = reverse;
1237   while(i >= 0)
1238         *s++ = result[--i];
1239   *s = '\0';
1240         
1241   return reverse;
1242 }
1243
1244
1245 /* Generate a short name, given a long name.
1246    The return value of this function must be freed by the caller. 
1247 */
1248 static char *
1249 make_short_name(struct dictionary *dict, const char *longname)
1250 {
1251   int i = 0;
1252   char *p;
1253  
1254
1255   char *d = xmalloc ( SHORT_NAME_LEN + 1);
1256
1257   /* Truncate the name */
1258   strncpy(d, longname, SHORT_NAME_LEN);
1259   d[SHORT_NAME_LEN] = '\0';
1260
1261   /* Convert to upper case */
1262   for ( p = d; *p ; ++p )
1263         *p = toupper(*p);
1264
1265   /* If a variable with that name already exists, then munge it
1266      until there's no conflict */
1267   while (0 != hsh_find (dict->name_tab, d))
1268   {
1269         const char *suffix = quasi_base27(i++);
1270
1271         d[SHORT_NAME_LEN -  strlen(suffix) - 1 ] = '_';
1272         d[SHORT_NAME_LEN -  strlen(suffix)  ] = '\0';
1273         strcat(d, suffix);
1274   }
1275
1276
1277   return d;
1278 }
1279
1280
1281
1282