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

#include <Python.h>

#include <maya/MLibrary.h>
#include <maya/MGlobal.h>
#include <maya/MString.h>
#include <maya/MStringArray.h>


PyObject*
mel(PyObject* self, PyObject* args)
{
	const char* command;
	if (PyArg_ParseTuple(args, "s", &command))
	{
		printf("Executing '%s'...\n", command);
		MStringArray results;
		MStatus status = MGlobal::executeCommand(MString(command), results);
		if (status != MS::kSuccess)
			printf("// Error: %s\n", status.errorString().asChar());
		else
			for (unsigned int i = 0; i < results.length(); i++)
				printf("// %s\n", results[i].asChar());
	}

	Py_INCREF(Py_None);
	return Py_None;
}


PyMethodDef mayaMethodTable[] =
{
	{"mel", mel, METH_VARARGS, "Run MEL Command"},
	{NULL, NULL}
};


int main(int argc, char** argv)
{
	printf("// pymaya v1.0\n");

	// get filename
	if (argc > 2)
	{
		fprintf(stderr, "Usage: pymaya [<filename>]\n");
		exit(1);
	}

	// initialize Maya
	if (MLibrary::initialize(true, argv[0], true) != MS::kSuccess)
		exit(1);

	// initialize Python
	Py_Initialize();

	// add and initialize the module
	PyImport_AddModule("maya");
	Py_InitModule("maya", mayaMethodTable);

	// import it so that the scene file doesn't have to
	PyRun_SimpleString("from maya import mel\n");

	if (argc == 2)
	{
		MString command = MString("execfile('") + MString(argv[1]) + MString("')");
		PyRun_SimpleString(command.asChar());
	}
	else
		PyRun_InteractiveLoop(stdin, "stdin");

	// shut down Python
	Py_Finalize();

	// shut down Maya (and exit)
	MLibrary::cleanup(0);
}

