//String.cc
#include "String.hh"

#include <iostream>
String operator+( const String& lhs, const String& rhs ) {
	String result(lhs); // Copy lhs into res with constructor
	result += rhs ; // Use operator+= function which is a member of the class
	return result ;
}

String& String::operator=( const String& a ) {
		if ( &a != this ) {
			insert(a._s) ;
		}

		return *this ;
}
String& String::operator+=( const String& a ) {
	  int newlen = _len + a._len ;
	  char * newstr = new char[ newlen+1 ] ;

	  strcpy(newstr, _s) ;
	  strcpy(newstr + _len, a._s) ;

	  if (_s) delete[] _s ;
	  
	  _s = newstr ;
	  _len = newlen ;

	  return *this ;
}
String& String::subString( int start, int stop ) {
	/*
	 * Return a substring
	 *
	 * if stop is negative, interpret as len - stop
	 * if start is negative, set start = 0
	 *
	 * if start > stop, return reversed string
	 */

	bool reverse = 0;
	int len = 0;
	char * tmp;

	// Higher than Range
	if ( start > _len ) {
	    start = _len ;
	}

	if ( stop > _len ) {
	    stop = _len ;
	}

	// Lower than Range
	if ( start < 0 ) {
	    start = _len + start%_len ;
	}
	if ( stop < 0 ) {
	    stop = _len + stop%_len ;
	}

	// Set length
	len = stop - start;

	if ( start > stop ) {
	    // Make sure len is positive
	    len = -1 * len ;
	    reverse = 1;
	}

	// allocate
	tmp = new char[ len - 1];
	tmp[len] = '\0';

	for ( int i = 0 ; i < len ; i++ )
	{
		if ( reverse )
		{
			tmp[i] = _s[ start - i ];
		}
		else
		{
			tmp[i] = _s[ start + i ];
		}
	}

	// make it a String again
	String * result = new String(tmp);
	delete tmp;

	return *result;
}
