/******* rtmp_hash.c *********/

#include "librtmp_local.h"

/* returns a pointer to the point if found, null if not */
point *
routemap_hash_find(hash_table,element)
     ROUTEMAP_HASH_TABLE *hash_table;
     point *element;
{
  int32 bucket_num;
  ROUTEMAP_BUCKET_LIST *ptr;
  int32 poly_num;

  if (element->which_poly==-1) 
    poly_num=9;
  else
    poly_num=element->which_poly;
  bucket_num=((poly_num % hash_table->poly_mod) +
	      (10*(((int)element->x - hash_table->bot_x) / hash_table->x_div)) +
	      (1000*(((int)element->y - hash_table->bot_y) / hash_table->y_div)));
/*  printf("finding from bucket num %d. Element is %f,%f,%d\n",bucket_num,element->x,element->y,element->which_poly); */
  if ((bucket_num<0) || (bucket_num>=hash_table->num_buckets))
    return (NULL);
  for (ptr=hash_table->bucket[bucket_num]; ptr!=NULL; ptr=ptr->next)
    {
/*      printf("looking at %f,%f,%d\n",ptr->p->x,ptr->p->y,ptr->p->which_poly); */
      if ((SAME(element->x,ptr->p->x)) && (SAME(element->y,ptr->p->y)) && 
	  (element->which_poly==ptr->p->which_poly) &&
	  (element->radius_num==ptr->p->radius_num))
	return(ptr->p);
    }
  return (NULL);
}


/* inserts element into the hash table */
void
routemap_hash_insert(hash_table,element)
     ROUTEMAP_HASH_TABLE *hash_table;
     point *element;
{
  int32 bucket_num;
  ROUTEMAP_BUCKET_LIST *new_element;
  int32 poly_num;

  if (element->which_poly==-1) 
    poly_num=9;
  else
    poly_num=element->which_poly;
  bucket_num=((poly_num % hash_table->poly_mod) +
	      (10*(((int)element->x - hash_table->bot_x) / hash_table->x_div)) +
	      (1000*(((int)element->y - hash_table->bot_y) / hash_table->y_div)));
/*  printf("inseing into bucket num %d. Element is %f,%f,%d\n",bucket_num,element->x,element->y,element->which_poly); */
  if ((bucket_num>=0) && (bucket_num<hash_table->num_buckets))
    {
      new_element=(ROUTEMAP_BUCKET_LIST *)(malloc(sizeof(ROUTEMAP_BUCKET_LIST)));
      new_element->p=element;
      new_element->next=hash_table->bucket[bucket_num];
      hash_table->bucket[bucket_num]=new_element;
    }

}
 

/* creates an empty hash table with #size buckets */ 
void
routemap_hash_init(hash_table,poly_mod,bot_x,bot_y,div_x,div_y)
     ROUTEMAP_HASH_TABLE *hash_table;
     int32 poly_mod,bot_x,bot_y,div_x,div_y;
{
  int32 i;

  hash_table->poly_mod=poly_mod;
  hash_table->bot_x=bot_x;
  hash_table->bot_y=bot_y;
  hash_table->x_div=div_x;
  hash_table->y_div=div_y;
  hash_table->num_buckets=10*100*100;   /* fix this hack later */
  hash_table->bucket= (ROUTEMAP_BUCKET_LIST **) 
    (malloc (sizeof(ROUTEMAP_BUCKET_LIST *)*hash_table->num_buckets));
  for (i=0;i<hash_table->num_buckets;i++)
    hash_table->bucket[i]=NULL;
}
