import cvisual

# I am performing the import statements within functions to prevent polluting the global
# namespace
def _try_init_numeric():
    try:
        import Numeric
        cvisual._init_numeric_impl()
        return True
    except:
        return False

def _try_init_numarray():
    try:
        import numarray
        cvisual._init_numarray_impl()
        return True
    except:
        return False
    
have_numeric = _try_init_numeric()
have_numarray = _try_init_numarray()

# Why a one-element list? Because Python in one of its more asinine decisions
# chose to make it nearly impossible to modify a variable in global scope.
# This crude trickery makes it possible.
backend = [ None ]

def set_array_backend( which):
    """set_array_backend("numeric") -> Use Numeric.array for arrays internally.
    set_array_backend("numarray") -> Use libnumarray.NDarray for arrays internally."""
    if which == "numeric":
        if not have_numeric:
            raise ValueError, "Numeric is not available"
        backend[0] = "Numeric"
        cvisual._use_numeric_impl()
    elif which == "numarray":
        if not have_numarray:
            raise ValueError, "libnumarray is not available"
        backend[0] = "numarray"
        cvisual._use_numarray_impl()
    else:
        raise ValueError, "Invalid array backend."

if have_numeric:
    set_array_backend( "numeric")
elif have_numarray:
    set_array_backend( "numarray")
else:
    raise RuntimeError, "Neither Numeric nor numarray could be found."
        