//--------------------------------------------------------------------
// File: sighashVals.cpp
// Nov. 16 2001
// K.Becker
//
// simulation of signature hashing 

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>


int    Htable[11] = { 17,35,14,16,25,29,24,27,36,13,28 };
int    nKeys = 11;    // number of keys
int    AddrSpace = 11;
int    debug = 0;     // debug OFF

int hash( int key )
{
  return key % AddrSpace;
}

int step( int key)
{
  return key / AddrSpace;
}

int sig( int key, int pos )
{
  if (pos == 0) 
    return key % 15;
  else
    return (sig(key, pos-1)+1) * key % 15;
}

//-------------------------------------------------------//
int next ( int loc, int stepsize )
{
  // calculate the next location in the table
  // with wrap-around 
  // wraps as often as necessary mostly for Computed Chaining
  //   which could have reeely big steps
  int v;

  v = loc + stepsize;
  while ( v >= AddrSpace )
    v -= AddrSpace;
  return v;

} // next

//-------------------------------------------------------//
int prev ( int loc, int stepsize )
{
  // calculate the next location in the table
  // going backwards (with wrap-around)
  int v;

  v = loc - stepsize;
  while ( v < 0 )
    v += AddrSpace;
  return v;

} // prev



int main( int argc, char* argv[]) {
  
  double 
    d,        // growth factor
    N,        // number of buckets
    key,      // key to hash
    S;        // that mysterious 'S'
  
  int  i,j,   // for indexing
    addr,     // address returned by Hash2Addr
    first,    // 'name' of first address
    last,     // 'name' of last address
    buckets;  // number of buckets we have
  

  int*   counts;        // count keys hashed to each address
  int    keyCount = 0;  // tally keys 
  int    home;
  int    naddr;
  

  printf("Signature Hashing Simulation:\n\n");

  // deal with debug switch
  if ((argc > 1) && (strcmp(argv[1],"-d")==0))
    debug = 1; // debug ON
  if (argc >2) // we have -d #
    debug = argv[2][0] - 48;

  printf("DEBUG SWITCH IS %i.\n\n",debug);
  if (!debug)
    {
      printf("To run a trace, run program with '-d' or '-d 2'\n");
      exit(0);
    }

  for (i=0; i < nKeys; i++)
    {
      printf("Key %i\n         ", Htable[i]);
      home = hash(Htable[i]);
      naddr = home;
      for (j = 0; j < 5; j++)
	printf("%2i  ",j);
      printf("\nH[i,j] = %2i",home);
      for (j = 1; j < 5; j++)
	{
	  naddr = next(naddr, step(Htable[i]));
	  printf("  %2i",naddr);
	}
      printf("\nS[i,j] = %2i",sig(Htable[i],0));
      for (j = 1; j < 5; j++)
	{
	  printf("  %2i",sig(Htable[i],j));
	}
	  
      printf("\n\n");
    }

  printf("Done.\n");


} // main

