// file: pfile__parse_2.cc
//
 
// isip include files
//
#include "param_file.h"
#include "param_file_constants.h"

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

// method: symbol_pad_cc
//
// arguments:
//  char_1* buffer: (input/output) the string to be symbol padded
//  int_4 len: (input) the length of the string
//  char_1* chars: (input) symbols used to pad the string
//
// return: a logical_1 indicating status
//
// this methods adjusts the space between symbols inside the string 
//
logical_1 Param_file::symbol_pad_cc(char_1*& buffer_a, int_4 len,
				    char_1* chars_a) {

  if ((buffer_a == (char_1*)NULL) || (chars_a == (char_1*)NULL)) {
   error_handler_cc((char_1*)"symbol_pad_cc",
		    (char_1*)"the input string is NULL");
  }
  
  char_1* buffer = (char_1*)NULL;
  int_4 size_str = strlen((char*)buffer_a);
  
  // allocate the buffer
  //
  if (buffer == (char_1*)NULL) {
    buffer = new char_1[size_str + 1];
  }

  // copy over the source string
  //
  strcpy((char*)buffer, (char*)buffer_a);

  // reallocate the input buffer
  //
  delete [] buffer_a;
  buffer_a = new char_1[2 * size_str + 1];
  
  // buff_p: the pointer to the original buffer that is read from
  // fixed_buff_p: the pointer that is written to.
  //
  char_1* buff_p = buffer;
  char_1* fixed_buff_p = buffer_a;

  int_4 state = PFIL_STATE_PAD_NOSPACE;
  
  // enter the state machine
  //
  while (*buff_p != (char_1)NULL) {
    
    if (state == PFIL_STATE_PAD_NOSPACE) {

      if (strchr((char*)chars_a, (char)*buff_p) != (char_1)NULL) {
	if (fixed_buff_p != buffer_a) {
	  *fixed_buff_p++ = (char_1)PFIL_SPACE_CHR;
	}
	*fixed_buff_p++ = *buff_p;
	*fixed_buff_p++ = (char_1)PFIL_SPACE_CHR;
	state=PFIL_STATE_PAD_SPACE;
      }
      else if (*buff_p == (char_1)PFIL_SPACE_CHR) {
	*fixed_buff_p++ = (char_1)PFIL_SPACE_CHR;
	state = PFIL_STATE_PAD_SPACE;
      }
      else {
	*fixed_buff_p++ = *buff_p;
      }
    }
    else if (state == PFIL_STATE_PAD_SPACE) {
      
      if (strchr((char*)chars_a, (char)*buff_p) != (char_1)NULL) {      
	*fixed_buff_p++ = *buff_p;
	*fixed_buff_p++ = (char_1)PFIL_SPACE_CHR;
      }
      else if (*buff_p == (char_1)PFIL_SPACE_CHR) {

	// do nothing
	//
      }
      else {
	
	// simple character, return to state 0
	//
	*fixed_buff_p++ = *buff_p;
	state = PFIL_STATE_PAD_NOSPACE;
      }
    }
    buff_p++;
  }

  *fixed_buff_p = (char_1)NULL;
  fixed_buff_p--;

  if (*fixed_buff_p == (char_1)PFIL_SPACE_CHR) {
    *fixed_buff_p = (char_1)NULL;
    fixed_buff_p--;
  }
  
  // clean up
  //
  delete [] buffer;
  buffer = (char_1*)NULL;  
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
