// file: dec_decode_1.cc
//

// system include files
//
#include <unistd.h>

// isip include files
//
#include "decoder.h"
#include "decoder_constants.h"

// method: decode_cc
//
// arguments:
//  char_1*& hypotheses: (input) output the hypotheses
//
// return: logical_1 indicating status
//
// this method performs the final search and output hypotheses
// Note: Communicator API
//
logical_1 Decoder::decode_cc(char_1*& hypotheses_a, char_1*& alignment_a,
			     char_1* hypo_file_a, char_1* mfc_file_a) {

  // we have now finished the state sequences so we need to backtrace
  // i.e. find an emitting word level trace with the highest score and
  // follow backpointers to the start trace
  //
  backtrace_cc();
  
  // write the alignment of sentence-hypotheses to buffer
  //
  write_output_cc((char_1 *&)alignment_a);
  //  fprintf(stdout, "alignment_a = %s\n", alignment_a);

  Lattice* lat = NULL;
  
  // build the lattice if this is ngram decoding
  //
  if (function_mode_d == DEC_NGRAM_DECODE_FUNCTION) {
    build_lattice_cc(lat);
  }
  else {
    lat = lattice_d;
  }
  
  lattice_to_nbest_cc(lat, hypotheses_a, nbest_max_paths_d, nbest_beam_d);
  if (function_mode_d == DEC_NGRAM_DECODE_FUNCTION) {
    delete lat;
  } 

  //  fprintf(stdout, "hypotheses_a = %s\n", hypotheses_a);  
  
  // write hypothesis to file if requested
  //
  if (hypo_file_a != NULL) {
    FILE* fpo = fopen((char*)hypo_file_a, "w");
    if (fpo) {

      // print the n-best list of sentence-hypotheses to file
      //
      write_output_cc(fpo);
      fclose(fpo);
    }
  }

  // write the whole mfc data to file
  //
  if (mfc_file_a != NULL) {
    FILE* fpm = fopen((char*)mfc_file_a, "w");
    if (fpm) {
      fwrite(buf_d, sizeof(float_8), size_d, fpm);
      fclose(fpm);
    }
  }
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
