// file: lxt_grow_0.cc
//

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

// method: grow_tree_cc
//
// arguments:
//  Lattice_node* ltn: (input) the lattice node to grow the tree with
//  float_4 score: (input) the score for this word
//  int_4 index: (input) index of lattice node that should not be added to tree
//
// return: a logical_1 flag indicating status
//
// this method adds the given lattice node to the appropriate place in
// the tree --- if the lattice node contains the !NULL word then it
// loops over all its successor words and adds those instead of the
// !NULL word
//
logical_1 Lex_tree::grow_tree_cc(Lattice_node* ltn_a, float_4 score_a,
				 int_4 index_a) {

  // check if this lattice node is a !NULL node
  // 
  Word* word = ltn_a->get_word_cc();
  char_1* wdname = word->get_name_cc();
  
  // if NULL node or net start node we need to look at all following
  // nodes of this node
  //
  if ((strcmp((char*)wdname, (char*)WRD_NULL) == 0) ||
      (strcmp((char*)wdname, (char*)WRD_NET_START) == 0)) {
    
    // get all possible next words and the LM word scores for this
    // !NULL node from current lattice node
    //
    Link_list* next_list = ltn_a->get_next_nodes_cc();
    Link_list* prev_list = ltn_a->get_prev_nodes_cc();
    float_4* lscore = ltn_a->get_lm_scores_cc();
    
    // lattice variables
    //
    Lattice_node* lnode = (Lattice_node*)NULL;
    Lattice_node* prev_node = (Lattice_node*)NULL;
    int_4 idx = (int_4)0;
  
    // add all the words to the tree
    //
    for (Link_node* nd = next_list->get_head_cc();
	 nd != (Link_node*)NULL; nd = nd->get_next_cc()) {
      
      // get the next lattice node
      //
      lnode = (Lattice_node*)(nd->get_item_cc());

      // check to see if this node is also a previous node of ltn_a
      // which indicate a circular loop
      //
      for (Link_node* node = prev_list->get_head_cc();
	   node != (Link_node*)NULL; node = node->get_next_cc()) {

	prev_node = (Lattice_node*)(node->get_item_cc());
	if (lnode == prev_node) {
	  prev_node = (Lattice_node*)NULL;
	  break;
	}
      }
	    
      // add to tree if not in a circular loop
      //
      if (prev_node != (Lattice_node*)NULL) {
	if (index_a == (int_4)0) {
	  grow_tree_cc(lnode, lscore[idx++], (int_4)0);
	}
      }
      else {
	if (lnode->get_node_index_cc() != index_a) {	
	  grow_tree_cc(lnode, lscore[idx++], ltn_a->get_node_index_cc());
	}
	else {
	  index_a = (int_4)0;
	}
      }
    }
  } // end if this is null word
  
  // otherwise add this lattice node to the tree
  //
  else {
    
    // set the child nodes and so on to build the tree
    //	  
    build_tree_cc(ltn_a, score_a);
  }
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
