#ifndef BLUECORE_STRING_UTILITIES_H
#define BLUECORE_STRING_UTILITIES_H

#include <iostream>
#include <string>
#include <vector>

namespace BlueCore {
	

#define SPACES " \t\r\n" 


/** 
 * Function to remove whitespaces from the end of the string.
 * @param s String to be trimmed.
 * @param t String containing whitespaces. Default: space, tab, carriage return and newline.
 */
inline std::string trim_right(
	const std::string &s,
	const std::string &t = SPACES )
{ 
	std::string::size_type i (s.find_last_not_of (t));

	if (i == std::string::npos)
    	return "";
	else
		return std::string( s, 0, i ); 
}



/** 
 * Function to remove whitespaces from the beginning of the string.
 * @param s String to be trimmed.
 * @param t String containing whitespaces. Default: space, tab, carriage return and newline.
 */
inline std::string trim_left(
	const std::string &s,
	const std::string &t = SPACES )
{
	return std::string( s, s.find_first_not_of(t) ); 
}


/** 
 * Function to remove whitespaces from the beginning and the end of the string.
 * @param s String to be trimmed.
 * @param t String containing whitespaces. Default: space, tab, carriage return and newline.
 */
inline std::string trim(
	const std::string &s,
	const std::string &t = SPACES )
{ 
	std::string::size_type a = s.find_first_not_of(t), b = s.find_last_not_of(t); 

	if ( a == std::string::npos || b == std::string::npos )
    	return "";

	return std::string( s, a, b-a+1 );
}



/**
 * Splits a string into pieces, and returns them in an array.
 * @param s String to be exploded.
 * @param v Vector which receives the pieces.
 * @param t String containing whitespaces. Default: space, tab, carriage return and newline.
 * @param trim_spaces Flag to decide if pieces should be trimmed. Default: false.
 */
inline void explode(
	const std::string &s, 
	std::vector<std::string> &v,
	const bool trim_spaces = false,
	const std::string &t = SPACES )
{
	std::string::size_type a, b;
	
	a = s.find_first_not_of(t), b = s.find_first_of(t, a);

	while( a != std::string::npos )
	{
		if( trim_spaces )
			v.push_back( trim( s.substr(a, b-a) ) );
		else
			v.push_back( s.substr(a, b-a) );
			
		a = s.find_first_not_of(t, b), b = s.find_first_of(t, a);
	}
}



/**
 * Function to assemble strings from a vector into one strng.
 * @param v Vector which conatins the string pieces.
 * @param t String which is places between peaces. Default: one space " ".
 * @return Assembled string.
 */
inline std::string implode(
	const std::vector<std::string> &v,
	const std::string &t = " " )
{
	unsigned int i;
	std::string s;
	
	for( i = 0; i < (v.size() - 1); i++)
	{
		s.append( v[i] );
		s.append( t );
	}

	return s+v[i];
}

} // namespace BlueCore

#endif
