// file: ts_occupancy_0.cc
//
// isip include files
//
#include "tie_state.h"
#include "tie_state_constants.h"
#include <string.h>

// method: read_occupancy_cc
//
// arguments:
//  float_4*& occupancy_a: (output) the states occupancy 
//  int_4 num_st: (input) the number of states
//  int_4 num_mix: (input) the number of mixtures
//  char_1* list_file: (input) the name of input occupancy list file
//
// return: a logical_1 indicating status
//
// this method reads the states occupancy
//
logical_1 read_occupancy_cc(float_4*& occupancy_a, int_4 num_st_a,
			    int_4 num_mix_a, char_1* list_file_a) {

  // open the list file
  //
  FILE* fp_occ = fopen((char*)list_file_a, "r");
  if (fp_occ == (FILE*)NULL) {
    fprintf(stdout, "Error : cannot open input file %s\n", list_file_a);
    exit(ISIP_PROTO_ERROR);
  }
  
  // make sure memory is allocated 
  //
  if(occupancy_a == (float_4*)NULL) {
    occupancy_a = new float_4[num_st_a];
    memset(occupancy_a, 0, num_st_a * sizeof(float_4));
  }
  
  // local variables
  //
  float_4 st_count = 0;
  int_4 index = 0;
  
  // file pointer to the occupancy file in the lists
  //
  FILE* fpi = (FILE*)NULL;
  
  // loop through all the occupancy files in the input file list
  //
  while (fgets((char*)list_file_a, ISIP_MAX_STRING_LENGTH, fp_occ) !=
         (char*)NULL) {
    
    expand_filename_cc(list_file_a);
    
    fpi = fopen((char*)list_file_a, "r");
    if (fpi == (FILE*)NULL) {
      fprintf(stdout, "Cannot open file %s\n", list_file_a);
      
      // exit(ISIP_PROTO_ERROR);
      continue;
    }
    
    // loop over all states
    //
    while (fscanf(fpi, "%ld %f\n", &index, &st_count) != EOF) {
      occupancy_a[index] += st_count;
    }
    
    // close file
    //
    fclose(fpi);
    
  } // end loop through all the files in the list

  // close file
  //
  fclose(fp_occ);
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
