// file: dec_read_7.cc
//

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

// isip include files
//
#include "decoder.h"
#include "decoder_constants.h"
 
// method: read_gram_list_cc
//
// arguments:
//  FILE* fp: (input) file pointer
//  
// return: a logical_1 indicating status
//
// this method reads in the list of lattices provided in the grammar
// list; these lattices will be used for hierarchical grammars
//
logical_1 Decoder::read_gram_list_cc(FILE* fp_a) {

  // local variables
  //
  char_1* name = new char_1[ISIP_MAX_STRING_LENGTH];
  char_1* filename = new char_1[ISIP_MAX_STRING_LENGTH];
  Lattice* lat = (Lattice*)NULL;
  FILE* fp_lat = (FILE*)NULL;
  
  // check file
  //
  if (fp_a == (FILE*)NULL) {
    error_handler_cc((char_1*)"read_gram_list_cc",
		     (char_1*)"NULL input file pointer");
    exit(ISIP_PROTO_ERROR);
  }
  
  // initialize the link list of grammars
  //
  gram_list_d = new Link_list();
  
  // parse each line a separate into grammar name and grammar file
  //
  while (fscanf(fp_a, "%s", name) != EOF) {
    
    // ignore if this is a comment line
    //
    if (name[0] == (char_1)'#') {
      fscanf(fp_a, "%[^\n]", name);
      fscanf(fp_a, "%[\n]", name);
    }

    // otherwise this is not a comment line
    //
    else {
    
      // read the name of the grammar and the file defining the
      // grammar (in a lattice format)
      //
      fscanf(fp_a, "%s", (char*)filename);
      
      // check to see if both name and file are specified
      //
      if ((name != (char_1*)NULL) && (filename != (char_1*)NULL)) {
	
	// create a new lattice object
	//
	lat = new Lattice();
	
	// open the file
	//
	fp_lat = fopen((char*)filename, "r");
	if (fp_lat == (FILE*)NULL) {
	  error_handler_cc((char_1*)"read_gram_list_cc",
			   (char_1*)"grammar file not found");
	  exit(ISIP_PROTO_ERROR);
	}
	
	// read the lattice and set the name
	//
	lat->read_lattice_cc(fp_lat, lexicon_d);
	lat->set_name_cc(name);
	
	// insert the lattice into the grammar list
	//
	gram_list_d->insert_cc(lat);	

      } // end if bot name and file exist
      
      // else error
      //
      else {
	error_handler_cc((char_1*)"read_gram_list_cc",
			 (char_1*)"specify both grammar name and file");
	exit(ISIP_PROTO_ERROR);
      }
    }
    
    // reset the buffers
    //
    memset(name, int_4(0), ISIP_MAX_STRING_LENGTH);
    memset(filename, int_4(0), ISIP_MAX_STRING_LENGTH);
  }
  
  // clean up memory
  //
  delete [] name;
  delete [] filename;
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
