// hashtable3.h

/*
 Written by
 Huang,Jessica C : jessica9@MIT.EDU
 Huang,Kai : kaih@MIT.EDU
 Huang, Edward : eych@MIT.EDU
 Shi,Melissa F : mshi@MIT.EDU
 
 September 25, 2001

 May be freely reproduced for educational or personal use
*/

#ifndef __HASHTABLE_H__
#define __HASHTABLE_H__

#include "types.h"


typedef struct Pair_s {
    Vect vect;
    Key key1;
    Key key2;
    struct Pair_s *next;
} Pair;

#define HASHSIZE 800000
typedef Pair *Hashtable[ HASHSIZE ];


void initHash( Hashtable ht )
{
    unsigned long i;

    for ( i = 0; i < HASHSIZE; ++i )
        ht[ i ] = NULL;
}


void hashPut( Hashtable ht, Vect vect, Key key1, Key key2 )
{
    unsigned long lvect = convertVect( vect );
    unsigned long index = lvect % HASHSIZE;
    Pair *ppair;

    if ( ht[ index ] == NULL ) {
        ppair = malloc( sizeof( Pair ) );
        copyVect( ppair->vect, vect );
        copyKey( ppair->key1, key1 );
        copyKey( ppair->key2, key2 );
        ppair->next = NULL;
        ht[ index ] = ppair;
    } else {
        ppair = ht[ index ];
        while ( ppair->next != NULL )
            ppair = ppair->next;
        ppair->next = malloc( sizeof( Pair ) );
        copyVect( ppair->next->vect, vect );
        copyKey( ppair->next->key1, key1 );
        copyKey( ppair->next->key2, key2 );
        ppair->next->next = NULL;
    }
}


//returns 1 if vect is found and 0 if vect is not found
//if found, associated keys are returned in key1 and key2
int hashGet( Hashtable ht, Vect vect, Key key1, Key key2 )
{
    unsigned long lvect = convertVect( vect );
    unsigned long index = lvect % HASHSIZE;
    Pair *ppair;

    for ( ppair = ht[ index ]; ppair != NULL; ppair = ppair->next ) {
        if ( convertVect( ppair->vect ) == lvect ) {
            copyKey( key1, ppair->key1 );
            copyKey( key2, ppair->key2 );
            return 1;
        }
    }

    return 0;
}


#endif //__HASHTABLE_H__

