// file: lat_index_0.cc
//

// isip include files
//
#include "lattice.h"
#include "lattice_constants.h"

// method: latcell_compare_cc
//
// arguments:
//  Hash_cell** hc1 : (input) hash cell with the first lattice node
//  Hash_cell** hc2 : (input) hash cell with the other lattice node
//
// return: an int_4 containing result of comparison
//
// this method compares two hash cells by frame index of lattice node
//
static int latcell_compare_cc(const void* hc1_a, const void* hc2_a) {

  // result value of comparison
  //
  int_4 value = (int_4)0;

  // lattice nodes in the two nodes
  //
  Lattice_node* ln1 = (Lattice_node*)((*(Hash_cell**)hc1_a)->get_item_cc());
  Lattice_node* ln2 = (Lattice_node*)((*(Hash_cell**)hc2_a)->get_item_cc());

  // frame indices of the two lattice nodes
  //
  int_4 fr1 = ln1->get_frame_index_cc();
  int_4 fr2 = ln2->get_frame_index_cc();

  // compare the two and set value
  //
  if (fr1 > fr2) {
    value = (int_4)1;
  }
  if (fr1 < fr2) {
    value = (int_4)-1;
  }

  // exit gracefully
  //
  return (int)value;
}
  
// method: index_nodes_cc
//
// arguments: none
//
// return: a logical_1 indicating status
//
// this method re-assigns the node indices of the lattice nodes to
// reflect the start to end progression of the lattice
//
logical_1 Lattice::index_nodes_cc() {

  // dummy variables
  //
  int_4 idx = (int_4)0;
  Lattice_node* latn = (Lattice_node*)NULL;
  
  // put all the lattice nodes in an array
  //
  Hash_cell** hcells = new Hash_cell*[num_nodes_d];
  Hash_cell** lcells = lnode_d->get_cells_cc();
  int_4 hsize = lnode_d->get_size_cc();
  for (int_4 i = 0; i < hsize; i++) {
    for (Hash_cell* cell = lcells[i]; cell != (Hash_cell*)NULL;
	 cell = cell->get_next_cc()) {
      hcells[idx++] = cell;
    }
  }    
  
  // now sort this array in ascending order according to time
  //
  qsort(hcells, num_nodes_d, sizeof(Hash_cell*), latcell_compare_cc);

  // reset the indices of all lattice nodes
  //
  for (int_4 i = 0; i < num_nodes_d; i++) {
    latn = (Lattice_node*)(hcells[i]->get_item_cc());
    latn->set_node_index_cc(i);
  }

  // free memory
  //
  delete [] hcells;
  
  // exit gracefully
  //
  return ISIP_TRUE;
}


