// file: tr_lxt_cstr_2.cc
//

// isip include files
//
#include "train_lex_tree.h"
#include "train_lex_tree_constants.h"

// method: constructor
//
// arguments:
//  Train_Hash_cell* history : (input) the hash cell containing the lattice node
//
// return: none
//
// this is an overloaded constructor
//
Train_Lex_tree::Train_Lex_tree(Train_Hash_cell* history_a) {

  // the memory manager
  //
  Train_Memory_manager* manager = Train_Link_list::get_manager_cc();
  
  // lattice variables
  //
  Train_Lattice_node* lnode = (Train_Lattice_node*)NULL;
  Train_Lattice_node* lnode1 = (Train_Lattice_node*)NULL;

  // initialize the word history
  //
  history_d = history_a;
  Train_Lattice_node* latnode = (Train_Lattice_node*)(history_d->get_item_cc());
  head_d = (Train_Lex_node*)NULL;

  // mark status as true i.e. active
  //
  status_d = ISIP_TRUE;

  // get all possible next words for this history from the lattice node
  //
  int_4 count = (int_4)0;
  Train_Link_list* next_list = latnode->get_next_nodes_cc();

  // if there are no next words return
  //
  if (next_list != (Train_Link_list*)NULL) {
  
    // create a start node for this tree
    //
    head_d = manager->new_lex_cc();
    head_d->set_phone_cc(TRAIN_LXN_START_PHONE);
    
    float_8* lscore = latnode->get_lm_scores_cc();
    for (Train_Link_node* nd = next_list->get_head_cc(); nd != (Train_Link_node*)NULL;
	 nd = nd->get_next_cc()) {
      
      // get the next lattice node
      //
      lnode = (Train_Lattice_node*)(nd->get_item_cc());

      // check if the next lattice node is a !NULL node
      // 
      Train_Word* node_word = lnode->get_word_cc();
      char_1* word_name = node_word->get_name_cc();

      // if NULL node we need to look at all following nodes of this
      // NULL node
      //
      if (strcmp((char*)word_name, (char*)"WRD_NULL") == 0) {

	// get all possible next words and the LM word scores for this
	// !NULL node from current lattice node
	//
        int_4 count1 = (int_4)0;
      	Train_Link_list* next_list1 = lnode->get_next_nodes_cc();
	float_8* lscore1 = lnode->get_lm_scores_cc();

	// add all the words to the tree
	//
	for (Train_Link_node* nd1 = next_list1->get_head_cc();
	    nd1 != (Train_Link_node*)NULL; nd1 = nd1->get_next_cc()) {
	  
	  // get the next lattice node
	  //
	  lnode1 = (Train_Lattice_node*)(nd1->get_item_cc());
	  
	  // add this lattice node to the tree (with the LM word score)
	  //
	  head_d->add_word_cc(lnode1, lscore1[count1]);
	  
	  // set the chile nodes and so on to build the tree
	  //
	  build_tree_cc(lnode1, lscore1[count1]);
	  
	  //increment count
	  //
	  count1++; 
        }
      }

      else {
	
	// add this lattice node to the tree (with the LM word score)
	//
	head_d->add_word_cc(lnode, lscore[count]);
	
	// set the child nodes and so on to build the tree
	//
	build_tree_cc(lnode, lscore[count]);
	
	// increment count
	//
	count++;
      }
    }
  }
  
  // exit gracefully
  //
}
