// file: lxt_tree_0.cc
//

// isip include files
//
#include "lex_tree.h"
#include "lex_tree_constants.h"

// method: build_tree_cc
//
// arguments:
//  Lattice_node* lnode : (input) the lattice node for the word to add
//  float_4 score: (input) the lm score for this word
//
// return: a logical_1 to indicate success
//
// this method loops over all pronunciations of the input word, for
// each pronunciation it checks phone-by-phone if the current phone is
// already on the correct branch of the tree and inserts the word and
// score in the corresponding node
//
logical_1 Lex_tree::build_tree_cc(Lattice_node* lnode_a, float_4 score_a) {
  
  // phone / word parameters
  //
  int_4 phone = (int_4)-1;
  int_4 num_prons = (int_4)0;
  int_4* num_ph = (int_4*)NULL;
  int_4** phlist = (int_4**)NULL;
  
  // get the word data
  //
  Word* word = lnode_a->get_word_cc();
  num_prons = word->get_num_prons_cc();
  phlist = word->get_phone_list_cc();
  num_ph = word->get_num_phones_cc();
  
  // dummy lexical nodes
  //
  Lex_node* curr_node = (Lex_node*)NULL;
  Lex_node* next_node = (Lex_node*)NULL;
  Lex_node* stop_node = (Lex_node*)NULL;

  // add the word to the head node
  //
  head_d->add_word_cc(lnode_a, score_a);
  
  // memory manager
  //
  Memory_manager* manager = Link_list::get_manager_cc();

  // create a stop node for this word if it has a valid pronunciation
  //
  if (num_prons > (int_4)0) {
    stop_node = manager->new_lex_cc();
    stop_node->set_phone_cc(LXN_STOP_PHONE);
    stop_node->set_type_cc(LXN_WORDGRAPH);
    stop_node->add_word_cc(lnode_a, score_a);
  }
  
  // loop over all the pronunciations for this word
  //
  for (int_4 i = 0; i < num_prons; i++) {
    
    // set the next node as current
    //
    next_node = head_d;
    
    // loop over all phones in this pronunciations
    //
    for (int_4 j = 0; j < num_ph[i]; j++) {
      
      // set the current node
      //
      curr_node = next_node;
      
      // the jth phone of this ith pronunciation
      //
      phone = phlist[i][j];
      
      // get the node in the tree that contains this phone
      //
      next_node = curr_node->make_node_cc(phone);
      next_node->add_word_cc(lnode_a, score_a);
      next_node->set_type_cc(LXN_WORDGRAPH);
  
    } // end for j

    // add the stop node at the end of word and mark as word end
    //
    next_node->add_child_cc(stop_node);
    next_node->set_word_end_cc(ISIP_TRUE);

  } // end loop over all pronunciations
  
  // exit gracefully
  //
  return ISIP_TRUE;  
}
