/***********************************************************
Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
The Netherlands.

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and its 
documentation for any purpose and without fee is hereby granted, 
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in 
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.

STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

******************************************************************/

/* Regular expression substitution objects */

#include "allobjects.h"
#include "modsupport.h"
#include "import.h"

static PyObject *
expand(PyObject *repl, PyObject *regs, PyObject *str)
{

    PyObject *backslash = PyString_FromString("\\");
    int count = PySequence_Count(repl, backslash);

    if (count == -1) {
	DECREF(backslash);
	err_setstr(TypeError, "Invalid object type for count()");
	return NULL;
    }

    if (count == 0) {
	DECREF(backslash);
	INCREF(repl);
	return repl;
    }

    DECREF(backslash);
    {
	char *newstr = alloca(count * PyObject_Length(repl) +
			      PyObject_Length(str) + 1);
	int i = 0, j = 0;
	int next = 0;
	char *replstr = PyString_AsString(repl);
	char *origstr = PyString_AsString(str);
	int repllen = PySequence_Length(repl);
	char c;
	while (i < repllen) {
	    c = replstr[i];
	    i = i + 1;
	    if (c != '\\' || i >= repllen)
		newstr[next++] = c;
	    else {
		c = replstr[i];
		i = i + 1;
		if ('0' <= c && c <= '9') {
		    PyObject *reg = PySequence_GetItem(regs, c-'0');
		    PyObject *a = PySequence_GetItem(reg, 0);
		    PyObject *b = PySequence_GetItem(reg, 1);
		    int ia = PyInt_AsLong(a);
		    int ib = PyInt_AsLong(b);
		    DECREF(a);
		    DECREF(b);
		    DECREF(reg);
		    for (j = ia; j < ib; j++)
			newstr[next++] = origstr[j];
		}
		else if (c == '\\')
		    newstr[next++] = c;
		else {
		    newstr[next++] = '\\';
		    newstr[next++] = c;
		}
	    }
	}
	return PyString_FromStringAndSize(newstr, next);
    }
}

static PyObject *regex;

static PyObject *
regsub_sub(PyObject *self, PyObject *args)
{
    PyObject *pat;
    PyObject *repl;
    PyObject *str;
    PyObject *prog;
    PyObject *search_result;

    if (! PyArg_ParseTuple(args, "OSS", &pat, &repl, &str))
	return NULL;

    if (PyString_Check(pat))
	prog = PyObject_CallMethod(regex, "compile", "O", pat);
    else
	/* already compiled we presume */
	prog = pat;

    search_result = PyObject_CallMethod(prog, "search", "O", str);

    if (PyInt_AsLong(search_result) >= 0) {
	PyObject *regs = PyObject_GetAttrString(prog, "regs");
	PyObject *reg = PySequence_GetItem(regs, 0);
	PyObject *a = PySequence_GetItem(reg, 0);
	PyObject *b = PySequence_GetItem(reg, 1);
	PyObject *first = PySequence_GetSlice(str, 0, PyInt_AsLong(a));
	PyObject *last = PySequence_GetSlice(str, PyInt_AsLong(b),
					     PyObject_Length(str));
	PyObject *middle = expand(repl, regs, str);
	PyObject *tmp = PySequence_Concat(first, middle);
	PyObject *result = PySequence_Concat(tmp, last);
	DECREF(prog);
	DECREF(regs);
	DECREF(reg);
	DECREF(a);
	DECREF(b);
	DECREF(first);
	DECREF(middle);
	DECREF(last);
	DECREF(tmp);
	return result;
    }
    INCREF(str);
    return str;
}

static PyObject *
regsub_gsub(PyObject *self, PyObject *args)
{
    PyObject *pat;
    PyObject *repl;
    PyObject *str;
    PyObject *prog;
    PyObject *search_result;
    int start = 0;
    int firsttime = 1;
    int slen;
    PyObject *result, *tmp;
    PyObject *regs;
    PyObject *reg;
    PyObject *a;
    PyObject *b;
    PyObject *first, *middle, *last, *regstr;

    if (! PyArg_ParseTuple(args, "OSS", &pat, &repl, &str))
	return NULL;

    slen = PyObject_Length(str);
    result = PyString_FromString("");
    regstr = PyString_FromString("regs");

    if (PyString_Check(pat))
	prog = PyObject_CallMethod(regex, "compile", "O", pat);
    else
	/* already compiled we presume */
	prog = pat;

    search_result = PyObject_CallMethod(prog, "search", "Oi", str, start);

    while (PyInt_AsLong(search_result) >= 0) {
	regs = PyObject_GetAttr(prog, regstr);
	reg = PySequence_GetItem(regs, 0);
	a = PySequence_GetItem(reg, 0);
	b = PySequence_GetItem(reg, 1);
	if (a == b && PyInt_AsLong(b) == start && !firsttime) {
	    search_result = PyObject_CallMethod(prog, "search", "Oi", str, start+1);
	    if (start >= slen || search_result < 0)
		break;
	    DECREF(regs);
	    DECREF(reg);
	    DECREF(a);
	    DECREF(b);
	    regs = PyObject_GetAttr(prog, regstr);
	    reg = PySequence_GetItem(regs, 0);
	    a = PySequence_GetItem(reg, 0);
	    b = PySequence_GetItem(reg, 1);
	}
	first = PySequence_GetSlice(str, start, PyInt_AsLong(a));
	middle = expand(repl, regs, str);
	start = PyInt_AsLong(b);
	firsttime = 0;
	tmp = PySequence_Concat(result, first);
	result = PySequence_Concat(tmp, expand(repl, regs, str));
	DECREF(tmp);
	DECREF(regs);
	XDECREF(reg);
	DECREF(a);
	DECREF(b);
	DECREF(first);
	DECREF(middle);
	search_result = PyObject_CallMethod(prog, "search", "Oi", str, start);
    }
    last = PySequence_GetSlice(str, start, slen);
    tmp = PySequence_Concat(result, last);
    DECREF(result);
    DECREF(last);
    DECREF(prog);
    DECREF(regstr);
    return tmp;
}

static struct methodlist regsub_methods[] = {
	{"sub",		(method)regsub_sub},
	{"gsub",	(method)regsub_gsub},
	{NULL,		NULL}		/* sentinel */
};

void
initregsubop()
{
    initmodule("regsubop", regsub_methods);
    if (err_occurred())
	fatal("can't initialize module regsubop");

    regex = PyImport_ImportModule("regex");
}

