#include <cstdarg>
#include <cstdio>

#include "SPrintF.h"

/***********************************************/

char *SPrintF::buffer = NULL;
int SPrintF::bufSize = 1024;

/***********************************************/

std::string SPrintF::format(const std::string &fmt, ...)
{
	if (!buffer)
		buffer = new char[bufSize];

	va_list varArg;

	va_start(varArg, fmt);
	int charCount = vsnprintf(buffer, bufSize, fmt.c_str(), varArg) + 1;
	va_end(varArg);

	if (charCount > bufSize)
	{
		if (buffer)
			delete [] buffer;
		bufSize = charCount;
		buffer = new char[bufSize];
	}

	return buffer;
}

/***********************************************/

std::string SPrintF::trimAndClean(const std::string &in)
{
	// trimming the surrounding whitespace

	unsigned int first, last;
	first = in.find_first_not_of(" \t");
	last = in.find_last_not_of(" \t");

	if (first == std::string::npos || last == std::string::npos)
		return "";

	std::string out = in.substr(first, last - first + 1);

	// getting rid of tabs
	for (unsigned int i = 0; i < out.size(); i++)
		if (out[i] == '\t')
			out[i] = ' ';

	// getting rid of double spaces, and spaces before punctuation

	unsigned int erasePos;
	while(erasePos = out.find("  ") != std::string::npos)
		out.erase(erasePos, 1);

	return out;
}

/***********************************************/

void SPrintF::free()
{
	if (buffer)
		delete buffer;
}
