/*
 Escape Quotes written by Mike Olson
 Copyright (c) 2001 Fourthought, Inc. USA.   All Rights Reserved.
 See  http://4suite.org/COPYRIGHT  for license and copyright information
*/

#include <Python.h>
#include <string.h>

static char escape__doc__[] = 
"escape(string)\n\
\n\
Replace all ' with \\' and \\ with \\\\";

static PyObject *escape(PyObject *self, PyObject *args) {
  Py_UNICODE *orig;
  Py_UNICODE *news;
  int ctr, add, newCtr, size;
  PyObject *rt,*origPy;
  if (!PyArg_ParseTuple(args, "O:escape", &origPy)) {
    return NULL;
  }

  if (origPy == Py_None) {
    return PyUnicode_DecodeUTF8("",0,NULL);
  }
  if (!PyUnicode_Check(origPy)) {
    origPy = PyUnicode_FromObject(origPy);
    if (!origPy) return NULL;
  };
  orig = PyUnicode_AS_UNICODE(origPy);
  add = size = PyUnicode_GET_SIZE(origPy);
  for (ctr = 0;ctr < size+1;ctr ++) {
    if (orig[ctr] == '\'') {
      add ++;
    }else if (orig[ctr] == '\\') {
      add ++;
    }
  }
  news = malloc(sizeof(Py_UNICODE) * (add+1));
  news[add] = '\0';
  newCtr = 0;
  for (ctr = 0;ctr < size;ctr ++) {
    if (orig[ctr] == '\'') {
      news[newCtr++] = '\\';
      news[newCtr++] = '\'';
    }else if (orig[ctr] == '\\') {
      news[newCtr++] = '\\';
      news[newCtr++] = '\\';
    }else{
      news[newCtr++] = orig[ctr];
    }
  }
  /*Py_DECREF(origPy);*/
  rt = PyUnicode_FromUnicode(news,add);
  free(news);
  return rt;


}

static PyMethodDef escapeQuotesMethods[] = {
     { "escape",  escape,  METH_VARARGS, escape__doc__ },
     { NULL, NULL }
};

DL_EXPORT(void) initEscapeQuotesc(void) {
  PyObject *module, *dict;
  module = Py_InitModule("EscapeQuotesc", escapeQuotesMethods);
  dict = PyModule_GetDict(module);
}
