// Local
#include "config.h"

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

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

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

	if (argc != 3)
	{
		std::cerr << "Simple grep-like test program: compares line per line, prints matching lines." << std::endl;
		std::cerr << "Usage0: " << argv[0] << " <regex> <file>" << std::endl;
		std::cerr << "Usage1: " << argv[0] << " RANDOM <max>" << std::endl;
		exit(1);
	}

	try
	{
		std::string regex((std::string) argv[1]);
		if (regex == "RANDOM")
		{
			// Random test
			const long max(UI::Util::ato<long>(argv[2]));
			long count(0);
			long matches(0);
			std::string regex(UI::Util::genAlphaNumericKey(4));
			std::cout << "Regex: " << regex << std::endl;
			while (count < max)
			{
				std::string text(UI::Util::genAlphaNumericKey(160));
				if (UI::Util::PosixRegex(regex, REG_EXTENDED).run(text))
				{
					std::cout << text << std::endl;
					++matches;
				}
				++count;
			}
			std::cout << matches << " matches in " << count << " random comparisons." << std::endl;
		}
		else
		{
			std::string fileName((std::string) argv[2]);
			std::ifstream f(fileName.c_str(), std::ios::in);
			char line[160];
			while (!f.eof())
			{
				f.getline(line, 160);
				if (UI::Util::PosixRegex(regex, REG_EXTENDED).run(line))
					std::cout << line << std::endl;
			}
		}
	}
	catch (UI::Util::PosixRegex::Exception const & e)
	{
		std::cerr << "Posix Err Code: " << e.getCode() << "." << std::endl;
		std::cerr << "Posix Err Text: " << e.what() << "." << std::endl;
	}
	catch (...)
	{
		std::cerr << "Unknown exception" << std::endl;
	}
	return(retValue);
}
