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

/* rdhmmlist.c --- read in HMMList file and set into hmminfo */

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

/* NOTE: hmmlist oversedes physical HMM */

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

#define MAXLINEINHMMLIST 256	/* max length per line in HMMList */

boolean
rdhmmlist(FILE *fp, HTK_HMM_INFO *hmminfo)
{
  char *buf, *lname, *pname;
  HMM_Logical *new, *match;
  HTK_HMM_Data *mapped;
  boolean ok_flag = TRUE;
  int n;
  /* 1 column ... define HMM_Logical of the name as referring to HMM of the same name */
  /* 2 column ... define HMM_Logical of the name "$1" which has pointer to $2 */

  buf = (char *)mymalloc(MAXLINEINHMMLIST);
  n = 0;
  while (getl(buf, MAXLINEINHMMLIST, fp) != NULL) {
    n++;
    lname = first_token(buf);
    pname = next_token_if_any();
    if (pname == NULL) {
      /* 1 column */
      mapped = htk_hmmdata_lookup_physical(hmminfo, lname);
      if (mapped == NULL) {
	j_printerr("Error: HMMList: line %d: physical HMM \"%s\" not found\n", n, lname);
	ok_flag = FALSE;
	continue;
      }
    } else {
      /* 2 column */
      mapped = htk_hmmdata_lookup_physical(hmminfo, pname);
      if (mapped == NULL) {
	j_printerr("Error: HMMList: line %d: physical HMM \"%s\" not found\n", n, pname);
	ok_flag = FALSE;
	continue;
      }
    }
    /* create new HMM_Logical */
    new = (HMM_Logical *)mybmalloc(sizeof(HMM_Logical));
    new->name = mybstrdup(lname);
    new->is_pseudo = FALSE;
    new->body.defined = mapped;
    new->next = hmminfo->lgstart;
    hmminfo->lgstart = new;
    /* add index to search index tree */
    if (hmminfo->logical_root == NULL) {
      hmminfo->logical_root = aptree_make_root_node(new);
    } else {
      match = aptree_search_data(new->name, hmminfo->logical_root);
      if (strmatch(match->name, new->name)) {
	j_printerr("Error: HMMList: line %d: logical HMM \"%s\" duplicated\n", n, new->name);
	ok_flag = FALSE;
      } else {
	aptree_add_entry(new->name, new, match->name, &(hmminfo->logical_root));
      }
    }
    
  }

  hmminfo->totallogicalnum = n;
  return(ok_flag);
}
