// gcc -Wall -g -o test_embed_python test_embed_python.c `pkg-config --cflags --libs python-2.7`

#include <Python.h>

PyObject *pName, *pModule;

const char *module = "test";

#if PY_VERSION_HEX >= 0x03000000
wchar_t *module_py = L"test.py";
#else
char *module_py = "test.py";
#endif

int call_python()
{
        PyObject *pFunc, *pValue;
        const char *func = "call_python";
#if PY_VERSION_HEX >= 0x03000000
        wchar_t *argv[2] = {module_py, 0};
#else
        char *argv[2] = {module_py, 0};
#endif

        printf("running embedded python...\n");

        Py_Initialize();
        PySys_SetArgv(1, argv);

#if PY_VERSION_HEX >= 0x02060000
        pName = PyUnicode_FromString(module);
#else
        pName = PyString_FromString(module);
#endif
        /* Error checking of pName left out */

        pModule = PyImport_Import(pName);
        Py_DECREF(pName);

        if (pModule == NULL) {
                PyErr_Print();
                fprintf(stderr, "Failed to load \"%s\"\n", module);
                Py_Finalize();
                exit(1);
        }

        pFunc = PyObject_GetAttrString(pModule, func);

        if ( ! (pFunc && PyCallable_Check(pFunc)) ) {
                if (PyErr_Occurred())
                        PyErr_Print();
                fprintf(stderr, "Cannot find function \"%s\"\n", func);
                Py_XDECREF(pFunc);
                Py_DECREF(pModule);
                Py_Finalize();
                exit(1);
        }

        pValue = PyObject_CallObject(pFunc, NULL);
        if (pValue == NULL) {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                Py_Finalize();
                exit(1);
        }
        //printf("   Result of call: %ld\n", PyLong_AsLong(pValue));

        Py_DECREF(pValue);
        Py_Finalize();
        printf("...done\n");
        return 0;
}

int main( int argc, char *argv[])
{

        call_python();
        call_python();

	return 0;
}

