//
// String.cpp  -  Custom string class
// By: Odis
//
#include <cstdlib>
#include <iostream>

#include "string.h"

using namespace std;

// Constructor via length, empty and null terminated
String::String(int length)
{
   if ( length > 0 )
   {
     mString = new char[length+1]; // +1 for null terminator
     mString[0] = '\0';
     
     mRef = 1;
     
     cout << "String(int) called, new string that is " << length << " char's long." << endl;
   }
   else
    cout << "String::String(int length) -> ERROR! Bad length!" << endl << endl;
}

// Constructor via string
String::String(const char *str)
{
  int maxlength = strlen(str)+1;
  mString = new char[maxlength];
  
  strncpy(mString,str,maxlength); /* copy contents */
  mString[maxlength] = '\0';
  
  mRef = 1;
  
  cout << "String(char) called with new data as: " << this->GetString() << endl;
}

// Destructor
String::~String()
{
  cout << "Destructor called on string with contents of: " << this->GetString() << endl;
  KILL(mString);
}


// Return a new -String-
String *String::DupString()
{
  String *str = NULL; // initialize to null

  cout << "DupString called!" << endl;
  
  str = new String(this->GetString());
  
  if ( str != NULL )
   return str;
  else
   return NULL;
}

// Merge strings
bool String::Merge(String *str)
{
  if ( str == NULL && str->Size() > 0)
   return false;

  cout << "Merge called between " << str->GetString() << " and " << this->GetString() << endl;

  if ( !StrCmp( str->GetString(), this->GetString()) ) // compare the two
  {
    unsigned int oldref = this->GetRef();

    for ( int i = 0; i < str->GetRef(); i++ ) // loop GetRef number of times
     this->AddRef();                          // Add the reference
     
     if ( this->GetRef() > oldref ) // added a few refs
     {
       str->Kill(); // get rid of other str
       return true;
     }
     else
      return false;
  }
  else
   return false;
}

// set the string
bool String::SetString(const char *str)
{
  if ( mString != NULL )
   KILL(mString);
   
  int maxlength = strlen(str)+1;
  mString = new char[maxlength];

  strncpy(mString,str,maxlength); /* copy contents */
  mString[maxlength] = '\0';
}

/// functions \\\

bool StrCmp( const char *astr, const char *bstr )
{
  if ( !astr )
	return true;

  if ( !bstr )
    return true;

  for ( ; *astr || *bstr; astr++, bstr++ )
  {
	if ( tolower(*astr) != tolower(*bstr) )
	    return true; // whoops, they dont match!
  }

  // match!
  return false;
}