/* 	File: am_managed_string.c
 * 	Author(s): Pat Gunn
 * 	Date: 14 Aug 2003
 * 	Purpose: See the .h
 */

#include "am_managed_string.h"
#include "amma.h"
#include "am_string.h"

#define MANAGED_STRING_CODE 15217

managed_string* mk_managed_string(char* src)
{
  managed_string* returner = AM_MALLOC(managed_string);
  returner->content = mk_copy_string(src);
  returner->length = strlen(returner->content);
  returner->managed_string_code = MANAGED_STRING_CODE;
  return returner;
}

void free_managed_string(managed_string* here)
{
  if(here->managed_string_code != MANAGED_STRING_CODE)
    {my_error("Tried to free something that's not a managed string!\n");}
  here->managed_string_code = 0; 
  am_free_string(here->content);
  AM_FREE(here, managed_string);
}

void append_to_managed_string(managed_string* targ, char* stuff)
{
  char* newstr;
  
  newstr = mk_concat_strings(targ->content, stuff);
  am_free_string(targ->content);
  targ->content = newstr;
  targ->length = strlen(targ->content);
}

void prepend_to_managed_string(managed_string* targ, char* stuff)
{
  char* newstr;
  
  newstr = mk_concat_strings(stuff, targ->content);
  am_free_string(targ->content);
  targ->content = newstr;
  targ->length = strlen(targ->content);
}

void trans_managed_string(managed_string* targ, char* chars, char rep)
{
  char* newstr;
  
  newstr = mk_copy_string_trans_chars(targ->content, chars, rep);
  am_free_string(targ->content);
  targ->content = newstr; /* Length remains the same. */
}

managed_string* mk_copy_managed_string(managed_string* src)
{
  return mk_managed_string(src->content);
}

char* mk_string_from_managed_string(managed_string* src)
{
  return mk_copy_string(src->content);
}

char* ref_string_from_managed_string(managed_string* src)
{
  return src->content;
}

#define WEIRD_BUFF_SIZE 100000
void fprintf_into_managed_string(managed_string* targ, char* fmt, ...)
{
  va_list ap;
  char buff[WEIRD_BUFF_SIZE];
  
  va_start(ap, fmt);
  vsprintf(buff, fmt, ap);
  va_end(ap);
  
  if(strlen(buff) >= WEIRD_BUFF_SIZE)
    {
    printf("String length is too long, exceeded static buffer.\n");
    my_error("String length is too long, exceeded static buffer.\n");
    }
  append_to_managed_string(targ, buff);
}

