/* Copyright (c) 1997 by Lele Gaifax.  All Rights Reserved
 *
 * This file is part of Nothing (yet).
 *
 * $RCSfile: import_ns.m,v $
 * $Revision: 1.1 $
 * $Date: 1997/03/23 08:02:05 $
 *
 * Created Thu Mar 13 20:30:24 1997.
 */

#include <Python/Python.h>
#include "PyNSBundledModule.h"

int PyNS_FindRegisteredModule (const char *name,
			       char *pathBuf,
			       int pathLen)
{
  NSString *path = [PyNSBundledModule pathOfModule:[NSString stringWithCString:name]];

  if (path == nil)
    return NO;
  else
    {
      [path getCString:pathBuf maxLength:pathLen-1];
      return YES;
    }
}

PyObject *
PyNS_LoadResourceModule (const char *name, const char *buf)
{
  NSBundle *mbundle = [NSBundle bundleWithPath:[NSString stringWithCString:buf]];

  if (mbundle == nil)
    {
      PyErr_SetString (PyExc_ImportError, "Cannot load bundle code");
      return NULL;
    }
  else
    {
      PyObject *m, *d, *s;
      id module;

      [[mbundle principalClass] initModule];

      m = PyDict_GetItemString (PyImport_GetModuleDict(), name);

      if (m == NULL)
	{
	  if (PyErr_Occurred() == NULL)
	    PyErr_SetString (PyExc_SystemError, "bundled module not initialized properly");
	  return NULL;
        }

      /* Remember the filename as the __file__ attribute */
      d = PyModule_GetDict (m);
      s = PyString_FromString (buf);
      if (s == NULL || PyDict_SetItemString (d, "__file__", s) != 0)
	PyErr_Clear(); /* Not important enough to report */
      Py_XDECREF(s);

      if (Py_VerboseFlag)
	fprintf (stderr,
		 "import %s # dynamically loaded from bundle %s\n",
		 name, buf);
      Py_INCREF(m);
      return m;
    }
}

			       
