// file: pfil_load_0.cc
//

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

// isip include files
//
#include "param_file.h"

#include "param_file_constants.h"
#include <integral_constants.h>

// method: load_cc
//
// arguments:
//   FILE* fp: file pointer
//
// return:  a logical_1 indicating status
//
// this method loads the parameter file, sending it to the parser
// to interpret items
//
logical_1 Param_file::load_cc(FILE* fp_a) {
  
  // check argument
  //
  if (fp_a == (FILE*)NULL) {
    error_handler_cc((char_1*)"load_cc",
		     (char_1*)"file pointer is null");
  }

  char_1 buffer[PFIL_MAX_BUFFER_SIZE];
  memset(buffer,0,PFIL_MAX_BUFFER_SIZE);
  
  char_1 statement[PFIL_MAX_BUFFER_SIZE];
  memset(statement,0,PFIL_MAX_BUFFER_SIZE);
  
  char_1* buffer_pos = buffer;

  // check for the magic string at the begining of the file, if defined
  //
  if (magic_string_d != (char_1*)NULL) {
    fgets((char*)buffer, PFIL_MAX_BUFFER_SIZE,fp_a);
    if (!strstr((char*)buffer, (char*)magic_string_d)) {
      error_handler_cc((char_1*)"load_cc",
		       (char_1*)"invalid file format");		     
      return ISIP_FALSE;
    }
  }
  
  // read in the next line
  //
  while (fgets((char*)buffer_pos,PFIL_MAX_BUFFER_SIZE,fp_a)) {
    int_4 statement_length;
    int_4 line_length;

    // find the length of the string read in
    //
    line_length = strlen((char*)buffer_pos);
    
    // increment the buffer_pos to the END of the data for the either
    // calculating size or reading the next line
    //
    buffer_pos += line_length;

    memcpy((char_1*)statement, (char_1*)buffer,
	   ((int_4)buffer_pos - (int_4)buffer));
    
    // pre-parse the buffer
    //
    statement_length = pre_parse_cc(statement);
    
    // statement_length also tells if pre_parse_cc found an error
    // in the buffer (ie: checks for a valid statement)
    //
    // if error, no real problem, just read more lines
    //
    if (statement_length != ISIP_FALSE) {
      
      // parse the statement
      //
      if (parse_cc(statement,statement_length) != ISIP_TRUE) {
	return ISIP_FALSE;
      }
      
      // reset the buffer_position to start reading for the next 
      // statement
      //
      buffer_pos = buffer;

      memset(statement, (int)0, PFIL_MAX_BUFFER_SIZE);
    }
  }
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
