/* MCS 507 L-8 Fri 28 Jan 2022 : revertStrings.c */
 
/* We extend Python with a C program to revert strings. */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int passString ( int n, char *s );
/*
 * Takes the n characters in the string s
 * and reverts the characters in the string. */

int test ( void );
/*
 * Main interactive test function.
 * Prompts the user for the length of
 * the string and a string of characters.
 * Prints the input and output of
 * the function passString. */

int test ( void )
{
   int n;
   char *s;

   printf("give length n : ");
   scanf("%d",&n);
   s = (char*)calloc(n,sizeof(char));
   printf("give a string : ");
   scanf("%s",s);
   n = strlen(s);

   printf(" input string : %s\n",s); 
   passString(n,s);
   printf("output string : %s\n",s); 

   return 0;
}

int passString ( int n, char *s )
{
   int i;
   char buffer;

   for(i=0; i<n/2; i++)
   {
      buffer = s[i];
      s[i] = s[n-1-i];
      s[n-1-i] = buffer;
   }
   return 0;
}

/* To compile this properly, run gcc -I$(PYTHON3) 
 * where PYTHON3 defines the location of the Python.h file */

#include "Python.h"

static PyObject *revertStrings_revert ( PyObject *self, PyObject *args )
{
   PyObject *result;
   int n; 
   char *s;

   if(!PyArg_ParseTuple(args,"is",&n,&s)) return NULL;

   passString(n,s);

   result = (PyObject*)Py_BuildValue("s",s);

   return result;
}

static PyObject *revertStrings_test ( PyObject *self, PyObject *args )
{
   test();
   return (PyObject*)Py_BuildValue(""); 
}

static PyMethodDef revertStringsMethods[] =
{
   { "passString" , revertStrings_revert , METH_VARARGS, 
     "reverting the characters in a string" } , 
   { "test" , revertStrings_test , METH_VARARGS,
     "interactive test on reverting a string" } , 
   { NULL , NULL, 0, NULL }
};

static struct PyModuleDef revertStringsModule = {
   PyModuleDef_HEAD_INIT,
   "revertStrings",
   NULL, /* no module documentation */
   -1,
   revertStringsMethods
};

PyMODINIT_FUNC
PyInit_revertStrings(void)
{
   return PyModule_Create(&revertStringsModule);
}
