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

/* cdhmm.c ---  HMM context handling functions */

/* $Id: cdhmm.c,v 1.3 2002/09/11 22:01:50 ri Exp $ */

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

/* append right context name rc[] to buffer name[] */
void
add_right_context(char name[], char *rc)
{
  char *p;
  int i;

  if ((p = strchr(name, HMM_RC_DLIM_C)) != NULL) {
    p++;
    *p = '\0';
  } else {
    strcat(name, HMM_RC_DLIM);
  }
  i = strlen(name);
  center_name(rc, &(name[i]));
}
/* insert legt context name lc[] to buffer name[] */
void
add_left_context(char name[], char *lc)
{
  char *p;
  char buf[40];

  if ((p = strchr(name, HMM_LC_DLIM_C)) != NULL) {
    p++;
  } else {
    p = name;
  }
  center_name(lc, buf);
  strcat(buf, HMM_LC_DLIM);
  strcat(buf, p);
  strcpy(name, buf);
}

static char gbuf[40];

/* search for right context HMM, appending right context string "rc_name" to
   the base phone "base".  returns NULL if not found */
HMM_Logical *
get_right_context_HMM(HMM_Logical *base, char *rc_name, HTK_HMM_INFO *hmminfo)
{
  strcpy(gbuf, base->name);
  add_right_context(gbuf, rc_name);
  return(htk_hmmdata_lookup_logical(hmminfo, gbuf));
}

/* search for left context HMM, appending left context string "lc_name" to
   the base phone "base".  returns NULL if not found */
HMM_Logical *
get_left_context_HMM(HMM_Logical *base, char *lc_name, HTK_HMM_INFO *hmminfo)
{
  strcpy(gbuf, base->name);
  add_left_context(gbuf, lc_name);
  return(htk_hmmdata_lookup_logical(hmminfo, gbuf));
}
  
/* return center(base) phone name */
/* modify content of buf[] */
char *
center_name(char *hmmname, char *buf)
{
  char *p, *s, *d;

  p = hmmname;
  d = buf;

  /* move next to '-' */
  while (*p != HMM_LC_DLIM_C && *p != '\0') p++;
  if (*p == '\0') s = hmmname;
  else s = ++p;

  while (*s != HMM_RC_DLIM_C && *s != '\0') {
    *d = *s;
    d++;
    s++;
  }
  *d = '\0';

  return (buf);
}

/* return left+center(base) phone name */
/* modify content of buf[] */
char *
leftcenter_name(char *hmmname, char *buf)
{
  char *p;
  /* strip off "+..." */
  strcpy(buf, hmmname);
  if ((p = strchr(buf, HMM_RC_DLIM_C)) != NULL) {
    *p = '\0';
  }
  return(buf);
}

/* return right+center(base) phone name */
/* modify content of buf[] */
char *
rightcenter_name(char *hmmname, char *buf)
{
  char *p;
  /* strip off "...-" */
  if ((p = strchr(hmmname, HMM_LC_DLIM_C)) != NULL && *(p+1) != '\0') {
    strcpy(buf, p+1);
  } else {
    strcpy(buf, hmmname);
  }
  return(buf);
}
