import sys
import os
import importlib


##########################################
# Load all the core modules
##########################################

# Important! Symbols must be available
# globally! WILL NOT WORK WITHOUT
olddl = sys.getdlopenflags()
sys.setdlopenflags(os.RTLD_LAZY | os.RTLD_GLOBAL)

# Standalone (don't depend on other core modules)
from . import exception


# TODO - can we get some order that will work with RTLD_NOW?
# Probably not - there are circular dependencies
# (modulemanager and modulebase, for example)
from . import python
from . import util
from . import output
from . import parallel
from . import datastore
from . import math
from . import tensor
from . import system
from . import modulebase
from . import modulemanager
from . import basisset

from . import testing

# restore old DL flags
sys.setdlopenflags(olddl)



##########################################
# Load other python stuff from this directory
##########################################
from .ModuleCheck import *
from .ModuleAdministrator import *



def Init(argv, out = "stdout", color = True, debug = False):
  """Initializes the BPModule core

  Initializes MPI, tensor libraries, etc, as well as the
  output streams.
  """

  if out == "stdout":
    output.SetOut_Stdout()
  else:
    output.SetOut_File(out)

  output.SetColor(color)
  output.SetDebug(debug) 

  # Set the command line
  util.SetCmdline(argv)

  # Initialize Parallel
  parallel.Init()

  # Initialize tensor
  tensor.Init()


  # Set some info about the base module and
  # print it
  # Also, set some options (currently unused)
  for name,minfo in modulemanager.minfo.items():
      minfo["name"] = name
      minfo["key"] = "CORE"
      minfo["path"] = os.path.dirname(modulemanager.__file__) + "/"



def Finalize():
  output.Output("Finalizing tensors\n")
  tensor.Finalize()

  output.Output("Finalizing parallelization\n")
  parallel.Finalize()

  util.ClearCmdline()


@@ -305,239 +305,255 @@
 L)%0A%0A
-# Standalone (don't depend on other core modules)%0Afrom . import exception%0A%0A%0A# TODO - can we get some order that will work with RTLD_NOW?%0A# Probably not - there are circular dependencies%0A# (modulemanager and modulebase, for example)
+%0A###############################################%0A# Some slight ordering of importing%0A# Despite using RTLD_LAZY, the%0A# PyInit_** functions may require some%0A# symbols to be loaded when they are called%0A###############################################%0A
 %0Afro
@@ -563,20 +563,23 @@
  import 
-pyth
+excepti
 on%0Afrom 
@@ -654,17 +654,14 @@
 ort 
-datastore
+python
 %0Afro
@@ -676,16 +676,17 @@
 rt math%0A
+%0A
 from . i
@@ -716,14 +716,61 @@
 ort 
-system
+datastore%0Afrom . import system%0Afrom . import basisset
 %0Afro
@@ -818,39 +818,16 @@
 emanager
-%0Afrom . import basisset
 %0A%0Afrom .

Clean up __init__ a little