// file: ts_tree_2.cc
//

// isip include files
//
#include "tie_state.h"
#include "tie_state_constants.h"

// method: index_tree_cc
// arguments :
//   Link_list* leaf_list:(input) the leaf list of the tree
//   int_4& label: (input/output) the global label of tied states
//   State** new_states: (output) the new tied states 
//   State** states: (input) the old states
//   float_4* occupancy: (input) the states occupancy
//   int_4 num_features: (input) the number of features
//   int_4 num_mixtures: (input) the number of mixtures
//
//  return: a logical_1 indicating status
//

// this function is to index the leaf node (tied states) of the tree 
//
logical_1 index_tree_cc(Link_list* leaf_list_a, int_4& label_a,
			State** new_states_a, State** states_a,
			float_4* occupancy_a, int_4 num_features_a,
			int_4 num_mixtures_a) {

  
  // local variables
  //
  Dt_node* dt_node = (Dt_node*)NULL;
  int_4 num_states = (int_4)0;  
  Link_node* link_nd = (Link_node*)NULL;
  int_4* leaf_states = (int_4*)NULL;
  float_4* max_scale = (float_4*)NULL;
  float_4 scale = (float_4)-1000.0;
  int_4 typical_state = (int_4)0;
  
  // loop the leaf list, assign the label to tied states and
  // output to the new states file
  //
  link_nd = leaf_list_a->get_head_cc();
  
  while(link_nd != (Link_node*)NULL) {

    // set the index of the new state corresponding to this leaf node
    //
    dt_node = (Dt_node*)link_nd->get_item_cc();   
    dt_node->set_label_cc(label_a);
    
    // define the state with the largest scale or lowest variance as the
    // typical state for this node.
    //
    num_states = dt_node->get_num_states_cc();
    leaf_states = dt_node->get_state_index_cc();
    
    scale = (float_4)-1000.0;
    for (int_4 i = 0; i < num_states; i++) {
      max_scale = states_a[leaf_states[i]]->get_scale_cc();
      if (max_scale[0] > scale) {
	typical_state = leaf_states[i];
	scale = max_scale[0];
      }
    }
    
    // create a new state 
    //
    new_states_a[label_a] = new State(*states_a[typical_state]);
    link_nd = link_nd->get_next_cc();
    label_a++;
  }

  // exit gracefully
  //
  return ISIP_TRUE;
}


