#include <string>
#include <sstream>
#include <iostream>


/* Step 1: 'value' needs to be converted (back) to a string.
 * Step 2: Determine how many commas need to be added based on the length of
 *         the generated string:
 *            "0".."999" contains 1..3 characters: add 0 commas
 *            "1000".."999999" contains 4..6 characters: add 1 comma
 *            "1000000".."999999999" contains 7..9 characters: add 2 commas
 *         So ((num_chars-1) / 3) gives the number of commas to add.
 * Step 3: Push commas into the final string array.
 */
std::string add_commas(const int& value)
{
	std::stringstream ss;
	ss.str(""); // Clear the buffer

	/* Negative sign will throw off calculation due to the extra '-' at the
	 * front.  Remove it until the very end.
	 */
	if (value < 0)
		ss << -value;
	else
		ss << value;

	std::string result(ss.str());

	unsigned num_chars = result.length();
	unsigned num_commas = (num_chars - 1) / 3;

	for (unsigned i = 0; i < num_commas; ++i)
	{
		result.insert((num_chars - 3) - 3 * i, ",");
	}

	// Need to re-insert leading '-' sign?
	if (value < 0)
		result.insert(0, "-");

	return result;
}


void show_usage(char* filename)
{
	std::cout << filename << ": Add commas to numbers >= 1000.\n";
	std::cout << "  Example: Entering ``1000'' results in ``1,000'' and\n";
	std::cout << "           ``1234567'' results in ``1,234,567'', while\n";
	std::cout << "           ``0'' through ``999'' remain ``0'' through\n";
	std::cout << "           ``999'', respectively.\n";
	std::cout << std::endl;
	std::cout << "  Note: There is no error-checking, so if you pass in a\n";
	std::cout << "        non-number value, you'll crash the program.  You\n";
	std::cout << "        have been warned.\n";
	std::cout << std::endl;
}


int main(int argc, char* argv[])
{
	if (argc == 1)
	{
		show_usage(argv[0]);
		return 0;
	}

	for (int i = 1; i < argc; ++i)
	{
		std::cout << "\t#" << i << ": " << add_commas(atoi(argv[i])) << std::endl;
	}

	return 0;
}
