from distutils.core import Extension

import sys, os

VERSION = "1.1.1"
VERSION_HEX = "0x010101000"

NUMARRAY_PACKAGES = ["numarray"]

NUMARRAY_PACKAGE_DIRS = {"numarray":"Lib"}

MODULES = ["_conv",
           "_sort",
           "_bytes",
           "_ufunc",
           "_ufuncBool",
           "_ufuncInt8",
           "_ufuncUInt8",
           "_ufuncInt16",
           "_ufuncUInt16",
           "_ufuncInt32",
           "_ufuncUInt32",
           "_ufuncFloat32",
           "_ufuncFloat64",
           "_ufuncComplex32",
           "_ufuncComplex64",
           "_ndarray",
           "_numarray",
           "_chararray",
           "_objectarray",
           "memory",
           "_converter",
           "_operator",
           "_ufunc",
           "libnumarray",
           "libnumeric",
           ]

NUMARRAY_DATA_FILES = [('numarray', ['LICENSE.txt','Lib/testdata.fits'])]

EXTRA_LINK_ARGS = []
EXTRA_COMPILE_ARGS = []

# compile c-modules with timing code which generally has to be
# added manually.
if "--timing" in sys.argv:
    MODULES.append("libteacup")
    EXTRA_COMPILE_ARGS.append("-DMEASURE_TIMING")

# Specify this to build numarray on an unthreaded Python.
if "--unthreaded" in sys.argv:
    EXTRA_COMPILE_ARGS.append("-DUNTHREADED")
    sys.argv.remove("--unthreaded")

# Specify this to try to exploit multiple processors.  A work
# in progress...
if "--smp" in sys.argv:
    EXTRA_COMPILE_ARGS.append("-DNA_SMP=1")
    sys.argv.remove("--smp")

if "--selftest" in sys.argv:
    SELFTEST = 1
    sys.argv.remove("--selftest")
else:
    SELFTEST = 0
    
HAS_UINT64 = 1

codeargs = ""
if sys.platform == "osf1V5":
    EXTRA_COMPILE_ARGS.extend(["-ieee"])
elif sys.platform == "linux2":
    if sys.maxint > 2**31-1:
        pass
    else:
        pass
elif sys.platform == "sunos5":
    pass
elif sys.platform == "win32":
    if sys.version.find("MSC") > 0:
        HAS_UINT64 = 0
elif sys.platform == "cygwin":
    EXTRA_LINK_ARGS += ["-L/lib", "-lm", "-lc", "-lgcc", "-L/lib/mingw", "-lmingwex"]
elif sys.platform == "darwin":
    EXTRA_COMPILE_ARGS.extend(["-Ddarwin"])
elif sys.platform == "irix646":
    pass
elif sys.platform == "freebsd4-i386":
    pass
else:
    pass

MODULES.extend(["_ufuncInt64"]) 
if HAS_UINT64:
    codeargs = "--hasUInt64"
    MODULES.extend(["_ufuncUInt64"]) 

gencode = "--gencode" in sys.argv        # Initial gencode value from switch
if gencode:
    sys.argv.remove("--gencode")

genapi = genufuncs = gencode

if "--genufuncs" in sys.argv:
    genufuncs = 1
    sys.argv.remove("--genufuncs")

if "--genapi" in sys.argv:
    genapi = 1
    sys.argv.remove("--genapi")

if (not os.path.exists("Include/numarray/numconfig.h") or
   not os.path.exists("Src/convmodule.c")):
    gencode = 1

def locate_headers():
    for a in sys.argv:
        if "--local" == a[:len("--local")]:
            words = a.split("=")
            return os.path.join(words[1].strip().rstrip(), "numarray")
    else:
        py_version_short = "%d.%d" % sys.version_info[:2]
        base = sys.exec_prefix
        template = {
            "win32"     : '%(base)s/Include/numarray',
            "darwin"    : '%(base)s/include/python%(py_version_short)s/numarray',
            "posix"     : '%(base)s/include/python%(py_version_short)s/numarray',
            }
        try:
            return template[sys.platform] % locals()
        except KeyError:
            return template["posix"] % locals()

class OurExtension(Extension):
    """OurBaseExtension is an Extension with implicit include_dirs,
    extra_compile_args, and extra_link_args.  Used to construct our
    c-api shared library.
    """
    def __init__(self, module, Sources=None, lib_dirs=[], libs=[]):
        if Sources is None:
            Sources = [os.path.join("Src",module+"module.c")]
        Extension.__init__(self, "numarray."+module, Sources,
                           include_dirs=["Include/numarray"],
                           library_dirs=lib_dirs,
                           libraries=libs,
                           extra_compile_args=EXTRA_COMPILE_ARGS,
                           extra_link_args=EXTRA_LINK_ARGS)

NUMARRAY_EXTENSIONS = map(OurExtension, MODULES)

def prepare(modules):
    print "Using EXTRA_COMPILE_ARGS =",EXTRA_COMPILE_ARGS

    # Generate numarray configuration header file
    
    f = open(os.path.join("Include","numarray","numconfig.h"),"w")
    f.write("""
/* This file is generated by setup.py.  DO NOT EDIT. */

#define NUMARRAY_VERSION_HEX %s

""" % (VERSION_HEX))
    f.close()
    del f

    for a in sys.argv:
	if a.startswith("--install-headers"):
	    INCLUDE_DIR = a.split("=")[1]
	    break
    else:
	INCLUDE_DIR = locate_headers()

    #  Generate the numinclude.py, the numarray configuration module.
    f = open(os.path.join("Lib", "numinclude.py"), "w")
    f.write("""
# This file is generated by setup.py.  DO NOT EDIT.

import _ndarray

include_dir = '%s'
version     = '%s'
hasUInt64   = _ndarray.hasUInt64()
LP64        = _ndarray.lp64()

if not len(include_dir):   # default to same directory as numarray .py's
   import numinclude
   include_dir = "/".join(numinclude.__file__.split("/")[:-1])
   
""" % ( INCLUDE_DIR, VERSION))
    f.close()

    python = sys.executable + " "
    if genufuncs:
        os.system(python + os.path.join("Lib","codegenerator.py") + " " + codeargs)
    if genapi:
        os.system(python + os.path.join("Include","numarray", "genapis.py") + " " + codeargs)

# if __name__ == "__main__":
prepare(MODULES)

