/*
 * Regular Expression program copyright (C) 2009 H.Niwa
 */

/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

#include "config.h"

#include <stdio.h>

#ifndef __MINGW32__
#include <regex.h>
#endif /* __MINGW32__ */

#include <string>
#include <complex>

#include "syserr.h"

#ifdef __MINGW32__
int Regex(std::string ptn, std::string str, 
		std::string& forestr, std::string& matchstr, 
			std::string& reststr)
{
	syserr("disable regex\n");
	return 0;
}

int Sub(std::string ptn, std::string str, 
		std::string replacestr, std::string& outputstr)
{
	syserr("disable sub\n");
	return 0;
}

int GSub(std::string ptn, std::string str, 
		std::string replacestr, std::string& outputstr)
{
	syserr("disable gsub\n");
	return 0;
}

#else 

int Regex(std::string ptn, std::string str, 
		std::string& forestr, std::string& matchstr, 
			std::string& reststr)
{
	int	r;
	regex_t	reg;
	regmatch_t match[1];

	matchstr = "";

	if ((r = regcomp(&reg, ptn.c_str(), REG_EXTENDED)) != 0) {
		syserr("internal error: regcomp %d \n", r);
		return 0;
	}
	
	r =  regexec(&reg, str.c_str(), 1, match, 0);
	regfree(&reg);

	if (r != 0) {
		forestr = "";
		matchstr = "";
		reststr = str;
		return 0;
	}

	forestr = str.substr(0, match[0].rm_so);
	matchstr = str.substr(match[0].rm_so, match[0].rm_eo-match[0].rm_so);
	reststr = str.substr(match[0].rm_eo, str.length());
	
	return 1;
}

int Sub(std::string ptn, std::string str, 
		std::string replacestr, std::string& outputstr)
{
	std::string fore, match, rest;
	
	if (Regex(ptn, str, fore, match, rest)) {
//printf("Sub Regex fore %s match %s rest %s \n", fore.c_str(), match.c_str(), rest.c_str());
		outputstr = fore + replacestr + rest;
		return 1;
	} else {
		outputstr = str;
		return 0;
	}
}

int GSub(std::string ptn, std::string str, 
		std::string replacestr, std::string& outputstr)
{
	std::string fore, match, rest, output;
	
	if (Regex(ptn, str, fore, match, rest)) {
//printf("GSub Regex fore %s match %s rest %s \n", fore.c_str(), match.c_str(), rest.c_str());

		if (str == rest) {
			outputstr = str;
			return 1;
		}
		
		GSub(ptn, rest, replacestr, output); 
		outputstr = fore + replacestr + output;
		return 1;
	} else {
		outputstr = str;
		return 0;
	}
}

#endif /* __MINGW32__ */

