/* Copyright (c) 1991-2002 Doshita Lab. Speech Group, Kyoto University */
/* Copyright (c) 2000-2002 Speech and Acoustics Processing Lab., NAIST */
/*   All rights reserved   */

/* init_phmm.c --- read in hmmdefs file & initialize */

/* $Id: init_phmm.c,v 1.4 2003/01/06 08:05:37 ri Exp $ */

#include <sent/stddefs.h>
#include <sent/htk_hmm.h>

/* initialize phoneme HMM structure */
HTK_HMM_INFO *
hmminfo_new()
{
  HTK_HMM_INFO *new;

  new = (HTK_HMM_INFO *)mymalloc(sizeof(HTK_HMM_INFO));

  return(new);
}

/* initialize phoneme HMM */
void
init_hmminfo(HTK_HMM_INFO *hmminfo, char *hmmfilename, char *namemapfile)
{
  FILE *fp;

  j_printerr("Reading in HMM definition...");
  /* read hmmdef file */
  if ((fp = fopen_readfile(hmmfilename)) == NULL) {
    j_error("failed to open %s\n",hmmfilename);
  }
  if (rdhmmdef(fp, hmminfo) == FALSE) {
    j_error("read error in %s\n",hmmfilename);
  }
  if (fclose_readfile(fp) < 0) {
    j_error("failed to close %s\n", hmmfilename);
  }
  
  j_printerr("   defined HMMs: %5d\n", hmminfo->totalhmmnum);

  /* make mapping from logically named HMM to real defined HMM name */
  if (namemapfile != NULL) {
    /* use HMMList map file */
    if ((fp = fopen_readfile(namemapfile)) == NULL) {
      j_error("failed to open %s\n",namemapfile);
    }
    if (rdhmmlist(fp, hmminfo) == FALSE) {
      j_error("HMMList \"%s\" read error\n",namemapfile);
    }
    if (fclose_readfile(fp) < 0) {
      j_error("failed to close %s\n", namemapfile);
    }
    j_printerr("  logical names: %5d in HMMList\n", hmminfo->totallogicalnum);
  } else {
    /* add the names of physical HMMs as logical names */
    hmm_add_physical_to_logical(hmminfo);
    j_printerr("  logical names: %5d\n", hmminfo->totallogicalnum);
  }

  /* extract basephone */
  make_hmm_basephone_list(hmminfo);
  j_printerr("    base phones: %5d used in logical\n", hmminfo->basephone.num);

  /* Guess we need to handle context dependency */
  /* (word-internal CD is done statically, cross-word CD dynamically */
  if (guess_if_cd_hmm(hmminfo)) {
    hmminfo->is_triphone = TRUE;
  } else {
    hmminfo->is_triphone = FALSE;
  }

  hmminfo->sp = NULL;
  
  j_printerr("done\n");
}

void
htk_hmm_set_pause_model(HTK_HMM_INFO *hmminfo, char *spmodel_name)
{
  HMM_Logical *l;

  l = htk_hmmdata_lookup_logical(hmminfo, spmodel_name);
  if (l == NULL) {
    j_printerr("Warning: no model named as \"%s\"\n", spmodel_name);
  }
  hmminfo->sp = l;
}
