// file: dec_lmch_1.cc
//
 
// isip include files
//
#include "decoder.h"
#include "decoder_constants.h"
 
// method: get_newhist_cc
//
// arguments:
//  Lex_node* strlex: (input) the lexical node holding the desired history
//  
// return: a void_p* with the new history word(s)
//
// this method finds the desired new history node as per the
// appropriate LM type
//
void_p* Decoder::get_newhist_cc(Lex_node* strlex_a) {

  // word node variables
  //
  Ngram_node* ngnode = (Ngram_node*)NULL;
  Lattice_node* latnode = (Lattice_node*)NULL;
  void_p* newhist = (void_p*)NULL;
  Word* word = (Word*)NULL;
  char_1* wdname = (char_1*)NULL;
  
  // identify the current LM type
  //
  logical_1 lextype = strlex_a->get_type_cc(); 
 
  // if this is ngram, need to switch to network LM
  //
  if (lextype == LXN_NGRAM) {
    
    // get the identity of the current word
    //
    ngnode = (Ngram_node*)(strlex_a->get_words_cc()->
			   get_head_cc()->get_item_cc());
    word = ngnode->get_word_cc();
    
    // check if this word represents entry to another LM
    //
    wdname = word->get_name_cc();
    if (*wdname == ISIP_DOLLAR) {
      
      // get the corresponding LM
      //
      Lattice* lattice = (Lattice*)NULL;
      Lattice* tmplat = (Lattice*)NULL;
      
      // loop over the network list and find the network corresponding
      // to this word
      //
      for (Link_node* ln = gram_list_d->get_head_cc();
	   ln != (Link_node*)NULL; ln = ln->get_next_cc()) {
	
	// check the lattice name
	//
	tmplat = (Lattice*)(ln->get_item_cc());
	if (strcmp((char*)wdname, (char*)(tmplat->get_name_cc())) == 0) {
	  lattice = tmplat;
	  break;
	}
      } // end for loop
      
      // make sure the grammar is a valid network
      //
      if (lattice == (Lattice*)NULL) {
	error_handler_cc((char_1*)"switch_lm_cc",
			 (char_1*)"null network associated with word");
      }
      
      // get the start words of the grammar
      //
      latnode = lattice->get_start_node_cc();
      newhist = next_histwords_cc((void_p*)NULL, (void_p)latnode);
    }
  } // end if lex type is ngram 
  
  // otherwise for word graph type, need to switch to ngram LM
  //
  else if (lextype == LXN_WORDGRAPH) {
    
    // determine the identity of the current word
    //
    latnode = (Lattice_node*)(strlex_a->get_words_cc()->
			      get_head_cc()->get_item_cc());
    word = latnode->get_word_cc();
    
    // check if this word represents entry to another LM
    //
    wdname = word->get_name_cc();
    if (*wdname == ISIP_DOLLAR) {
      
      // create a new trace with this word as the ngram history
      //
      ngnode = ngram_d->get_unigram_cc(word);
      newhist = next_histwords_cc((void_p*)NULL, (void_p)ngnode);
    }
  } // end else lex type is word graph 
  
  // exit gracefully
  //
  return newhist;
}
