// file: itri_file_0.cc
//

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

// isip include files
//
#include "init_triphones.h"
#include "init_triphones_constants.h"

// method: expand_filename_cc
//
// arguments:
//  char_1*& fname: (input/output) name needing expansion
//
// return: a logical_1 value indicating status
//
// this method replaces all environment variables and other such
// things in a string with their equivalent expansions. in other
// words, variables or aliases anywhere in the string will be
// replaced. this method uses popen/pclose rather than complicated
// function calls and string replacements.
//
logical_1 expand_filename_cc(char_1*& fname_a) {

  // dummy variables
  //
  char_1* oname = (char_1*)NULL;
  logical_1 flag_match = ISIP_FALSE;

  // remove new-line characters
  //
  int_4 len = strlen((char*)fname_a);
  if (fname_a[len - 1] == ISIP_NEWLINE) {
    fname_a[len - 1] = ISIP_NULL;
    len --;
  }
  
  // scan the incoming string for special characters
  //
  for (int_4 i = 0; i < len; i++) {
    if (strchr((char*)ITRI_ENV_DELIMITERS, fname_a[i]) != (char*)NULL) {

      // create space to store the expanded string
      //
      oname = new char_1[ISIP_MAX_FNAME_SIZE];

      // set flag and break
      //
      flag_match = ISIP_TRUE;
      break;
    }
  }
  
  // if necessary, expand the string
  //
  while (flag_match == ISIP_TRUE) {

    // build a Unix command
    //
    sprintf((char*)oname, "echo %s\n", (char*)fname_a);
    
    // execute the pipe
    //
    FILE* fp = popen((char*)oname, "r");
    fgets((char*)oname, ISIP_MAX_FNAME_SIZE, fp);
    pclose(fp);

    // strip the trailing linefeed
    //
    len = strlen((char*)oname) - (int_4)1;
    oname[len] = ISIP_NULL;

    // copy this over to the input filename
    //
    strcpy((char*)fname_a, (char*)oname);
    
    // make sure everything got expanded
    //
    flag_match = ISIP_FALSE;
    for (int_4 i = 0; i < len; i++) {
      if (strchr((char*)ITRI_ENV_DELIMITERS, fname_a[i]) != (char*)NULL) {
	flag_match = ISIP_TRUE;
	break;
      }
    }
  }

  // delete memory
  //
  if (oname != (char_1*)NULL) {
    delete [] oname;
  }
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
