#include <iostream>
#include <string>

#include <regex.h>

const int MAX_MATCHES(20);

void elements(const std::string &input)
{
    regex_t ElementRegEx;
	regcomp(&ElementRegEx, "([0-9]+)", REG_EXTENDED);
	
	regmatch_t ElementMatches[MAX_MATCHES];
	if (!regexec(&ElementRegEx, input.c_str(), MAX_MATCHES, ElementMatches, 0))
	{
		int Element = 0;
		
		while ((ElementMatches[Element].rm_so != -1) && (ElementMatches[Element].rm_eo != -1))
		{
			regmatch_t &ElementMatch = ElementMatches[Element];
			std::string CurrentElement(input.substr(ElementMatch.rm_so, ElementMatch.rm_eo - ElementMatch.rm_so));
			std::cout << '\t' << CurrentElement << '\n';
			
			++Element;
		}
	}
}

void cycles(const std::string &input)
{
	regex_t CycleRegEx;
	regcomp(&CycleRegEx, "([0-9]+[ ]*,[ ]*)*[0-9]+", REG_EXTENDED);
	
	regmatch_t CycleMatches[MAX_MATCHES];
	if (!regexec(&CycleRegEx, input.c_str(), MAX_MATCHES, CycleMatches, 0))
	{
		int Cycle = 0;
		
		while ((CycleMatches[Cycle].rm_so != -1) && (CycleMatches[Cycle].rm_eo != -1))
		{
			regmatch_t &CycleMatch = CycleMatches[Cycle];
			const std::string CurrentCycle(input.substr(CycleMatch.rm_so, CycleMatch.rm_eo - CycleMatch.rm_so));
			std::cout << CurrentCycle << '\n';
			
			elements(CurrentCycle);
			++Cycle;
		}
	}
	
	regfree(&CycleRegEx);
}

int main(int argc, char **argv)
{
    std::string input("(1,2,5)(3,4)");
    
    std::cout << "input: " << input << "\n\n";
    
	cycles(input);
	return 0;
}
