// file: lat_wer_1.cc
//

// system include file
//
#include <string.h>

// isip include files
//
#include "lattice.h"
#include "lattice_constants.h"

// method: get_refs_word_cc
//
// arguments:
//  int_4& nref: (output) number of words in reference
//  Hash_table* lexicon: (input) lexicon for this task
//
// return: a Word** with a list of word pointers
//
// this method splits the reference transcription string into
// individual words and returns a list of word models
//
Word** Lattice::get_ref_words_cc(int_4& num_a, Hash_table* lexicon_a) {

  // get the null word pointer if it exists
  //
  if ((lexicon_a->hash_lookup_cc(WRD_NULL)) != (Hash_cell*)NULL) {
    null_word_d =
      (Word*)((lexicon_a->hash_lookup_cc(WRD_NULL))->get_item_cc());
  }
  
  // if no utterance is specified, error
  //
  if (utterance_d == (char_1*)NULL) {
    error_handler_cc((char_1*)"get_ref_words_cc",
		     (char_1*)"No reference utterance found for lattice");
  }

  // copy the utterance string before tokenizing and work on the copy
  //
  char_1* str = (char_1*)NULL;
  char_1* utt = new char_1[strlen((char*)utterance_d) + 1];
  strcpy((char*)utt, (char*)utterance_d);

  // store the word transcription strings in a linked list for starters
  //
  Link_list* str_list = new Link_list();

  // tokenize the utterance string and place each token in the list
  //
  int_4 idx = (int_4)0;
  str = (char_1*)strtok((char*)utt, ISIP_STRING_SPACE);

  // check for sentence start
  //
  if (strcmp((char*)str, (char*)WRD_SENT_START) != 0) {
    str_list->insert_cc(WRD_SENT_START);
    idx++;
  }
  
  // loop over the rest of the string
  //
  while (str != (char_1*)NULL) {
    str_list->insert_cc(str);
    idx++;
    str = (char_1*)strtok(NULL, ISIP_STRING_SPACE);
  }

  // check for sentence end
  //
  Link_node* nd = str_list->get_curr_cc();
  str = (char_1*)(nd->get_item_cc());
  if (strcmp((char*)str, (char*)WRD_SENT_END) != 0) {
    str_list->insert_cc(WRD_SENT_END);
    idx++;
  }
  
  // create the word list
  //
  num_a = idx;
  Word** words = new Word*[num_a];
  
  // now generate the corresponding word models for each word
  //
  idx = (int_4)0;
  Hash_cell* hcell = (Hash_cell*)NULL;
  for (nd = str_list->get_head_cc(); nd != (Link_node*)NULL;
       nd = nd->get_next_cc()) {

    // get the string
    //
    str = (char_1*)(nd->get_item_cc());

    // get the corresponding word
    //
    hcell = lexicon_a->hash_lookup_cc(str);
    if (hcell == (Hash_cell*)NULL) {
      fprintf(stdout, "%s\n", str);
      error_handler_cc((char_1*)"get_ref_words_cc",
		       (char_1*)"word not found in lexicon");
    }
    words[idx++] = (Word*)(hcell->get_item_cc());

  } // end for loop

  // free memory
  //
  delete [] utt;
  utt = (char_1*)NULL;
  delete str_list;
  str_list = (Link_list*)NULL;
  
  // exit gracefully
  //
  return words;
}
