#include "Python.h"

static PyObject *
ex_huj(PyObject *self, PyObject *args)
{
	float *command;
	float i;
	int len, j;
	char s[16];
	char sout[9] = "00000000";
	const char* final_value;


    if (!PyArg_ParseTuple(args, "f", command))
        return NULL;

	i = *command;

	/////////////////////////////////////////
	sprintf(s, "%X", *((unsigned int*)&i));// Thank you Karba
	/////////////////////////////////////////

	///////////////////////////////////////////////
	len = strlen(s);///////////////////////////////
	for(j = 0; j<len; j++) sout[8-len+j] = s[j];///
	///////////////////////////////////////////////

	for(j = 0; j<2; j++)
	{
		char b;
		b = sout[2*j];
		sout[2*j] = sout[2*(3-j)];
		sout[2*(3-j)] = b;
		b = sout[2*j+1];
		sout[2*j+1] = sout[2*(3-j)+1];
		sout[2*(3-j)+1] = b;
	}

	final_value = sout;

    return Py_BuildValue("s", final_value);
}

static PyObject *
i2h(PyObject *self, PyObject *args)
{
	int *command;
	int i;
	int len, j;
	char s[16];
	char sout[9] = "00000000";
	const char* final_value;


    if (!PyArg_ParseTuple(args, "i", command))
        return NULL;

	i = *command;

	/////////////////////////////////////////
	sprintf(s, "%X", i);/////////////////////
	/////////////////////////////////////////

	///////////////////////////////////////////////
	len = strlen(s);///////////////////////////////
	for(j = 0; j<len; j++) sout[8-len+j] = s[j];///
	///////////////////////////////////////////////

	for(j = 0; j<2; j++)
	{
		char b;
		b = sout[2*j];
		sout[2*j] = sout[2*(3-j)];
		sout[2*(3-j)] = b;
		b = sout[2*j+1];
		sout[2*j+1] = sout[2*(3-j)+1];
		sout[2*(3-j)+1] = b;
	}

	final_value = sout;

    return Py_BuildValue("s", final_value);
}

static PyMethodDef example_methods[] = {
	{"f2h", ex_huj, METH_VARARGS, "string f2h(float) return float value as a hex string"},
	{"i2h", i2h, METH_VARARGS, "string f2h(float) return int value as a hex string"},
	{NULL, NULL}
};

PyMODINIT_FUNC
initnewpython(void)
{
	Py_InitModule("newpython", example_methods);
}