// file: ht_set_0.cc
//

// system include files
//
#include <string.h>

// isip include files
//
#include "hash_table.h"
#include "hash_table_constants.h"
 
// method: set_size_cc
//
// arguments:
//  int_4 size : (input) size of hash table
//
// return: a logical_1 indicating success
//
// this method sets the size of the hash table and rehashes the current
// entries
//
logical_1 Hash_table::set_size_cc(int_4 size_a) {

  // check the simple cases first
  //
  if (size_a <= 0) {

    // free memory in the hash table lists
    // this is assuming that the items are deleted independently
    //
    Hash_cell* next = (Hash_cell*)NULL;
    for (int_4 k = 0; k < size_d; k++) {
      for (Hash_cell* cell = cells_d[k]; cell != (Hash_cell*)NULL;
	   cell = next) {
	next = cell->get_next_cc();
	delete cell;
      }
    }
    if (cells_d != (Hash_cell**)NULL) {
      delete [] cells_d;
      cells_d = (Hash_cell**)NULL;
    }

    return ISIP_TRUE;
  }

  // check for the no-change condition
  //
  if (size_d == size_a) {
    return ISIP_TRUE;
  }

  // check for an empty table that needs to be sized
  //
  if (cells_d == (Hash_cell**)NULL) {
    cells_d = new Hash_cell*[size_a];
    size_d = size_a;
    memset(cells_d, 0, sizeof(Hash_cell*)*size_d);    
    return ISIP_TRUE;
  }
  
  // if the size has changed, then copy over elements if they exist.
  //
  Hash_cell** old_cells = cells_d;
  int_4 old_size = size_d;

  // set the new size and allocate
  //
  size_d = size_a;
  cells_d = new Hash_cell*[size_d];
  memset(cells_d, 0, sizeof(Hash_cell*)*size_d);
  
  // loop through and rehash everything
  //
  Hash_cell* next = (Hash_cell*)NULL;
  for (int_4 k = 0; k < old_size; k++) {
    for (Hash_cell* cell = old_cells[k]; cell != (Hash_cell*)NULL;
	 cell = next) {

      // get the next pointer
      //
      next = cell->get_next_cc();

      // insert the cell into the new table
      //
      hash_insert_cc(cell);
    }
  }

  // clean up the old table
  //
  delete [] old_cells;
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
