//
//
//
//    regex.cc
//
//    Source code for regular expression class.
//
//    Modified for class Project (2003-09-18, 2003-10-04).
//
//    =========================================================================
//
//    Copyright (C) 2001-2003 by Matt Roberts, KK5JY.
//
//    This library is free software; you can redistribute it and/or
//    modify it under the terms of the GNU Lesser General Public
//    License as published by the Free Software Foundation; either
//    version 2.1 of the License, or (at your option) any later version.
//
//    This library 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
//    Lesser General Public License for more details.
//
//    You should have received a copy of the GNU Lesser General Public
//    License along with this library; if not, write to the Free Software
//    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//    =========================================================================
//
//
//


#include <string>
#include <sys/types.h>
#include <regex.h>

#include <my++/regex.h>


my::regex::regex (const std::string &ex, int fl) {
	set(ex, fl);
}

my::regex::regex (const my::regex &r) {
	copy(r);
}

my::regex::regex (int fl) : cflags(fl) {
	/* noop */
}

my::regex::~regex (void) {
	if (!re_str.empty())
		regfree(&re_exp);
}

bool my::regex::compare (const std::string &s) const {

#if 0
	std::string debug = "compare(\'" + re_str + "\', \'" + s + "\'):\n\tflags = ";
	if (cflags & icase)
		debug += " icase";
	if (cflags & extended)
		debug += " extended";
	if (cflags & nosub)
		debug += " nosub";
	std::cerr << debug << std::endl;
#endif

	return (regexec (&re_exp, s.c_str(), 0, 0, 0) == 0);
}

bool my::regex::compare (const my::regex &r) const {
	return ( (re_str == r.re_str) &&
			(cflags == r.cflags) );
}

void my::regex::copy (const my::regex &r) {
	if (! r.re_str.empty()) {
		if (!re_str.empty()) {
			regfree(&re_exp);
			re_str.erase();
			cflags = 0;
		}

		if (regcomp (&re_exp, r.re_str.c_str(), r.cflags) == 0) {
			re_str = r.re_str;
			cflags = r.cflags;
		}
	}
}

void my::regex::set (const std::string &s, int fl) {
	if (!s.empty()) {
		if (!re_str.empty()) {
			regfree(&re_exp);
			re_str.erase();
		}

		if (regcomp (&re_exp, s.c_str(), nosub) == 0) {
			re_str = s;
			cflags = fl;
		}
	}
}

void my::regex::compile (void) {
	if (!re_str.empty())
		regcomp(&re_exp, re_str.c_str(), cflags);
}

//
//
// recommended test application
//
//

//
// int main (int argc, char **argv) {
// 	if (argc < 3) {
// 		cerr << "Usage: regex [pattern] [string]" << endl;
// 		return 1;
// 	}
// 
// 	regex r(argv[1]);
// 
// 	if (r == argv[2])
// 		cerr << "Match." << endl;
// 	else
// 		cerr << "No match." << endl;
// 
// 	return 0;
// }

// EOF: regex.cc
