// Local
#include "config.h"

// STDC++
#include <iostream>
#include <string>

// C++ Libraries
#include <ui-utilcpp/Text.hpp>
#include <ui-utilcpp/Recoder.hpp>
#include <ui-utilcpp/CharsetMagic.hpp>

int main(int argc, char *argv[])
{
	int exitCode(0);

	try
	{
		if (argc < 2)
		{
			throw UI::Util::Exception("Wrong usage");
		}

		std::string const data(argv[1]);
		std::string const outEnc((argc > 2 && std::string(argv[2]) != "") ? argv[2] : "UTF-8");
		std::string const inEnc ((argc > 3 && std::string(argv[3]) != "") ? argv[3] : UI::Util::CharsetMagic::guess(data));
		bool const sloppy((argc > 4) && std::string(argv[4]) == "sloppy");

		std::cerr << "Input  charset   : " << inEnc << std::endl;
		std::cerr << "Output charset   : " << outEnc << std::endl;
		std::cerr << "Sloppy conversion: " << sloppy << std::endl;

		std::cout << UI::Util::Recoder(inEnc, outEnc, sloppy).run(data);
	}
	catch (std::exception const & e)
	{
		std::cerr << "Exception: " << e.what() << "." << std::endl;
		std::cerr << std::endl;
		std::cerr << "Usage: ui-utilcpp-recoder data [outEnc [inEnc [\"sloppy\"]]]" << std::endl << std::endl;
		std::cerr << "Writes conversion result to cout, informational output to cerr." << std::endl;
		exitCode=1;
	}

	return exitCode;
}
