from distutils.core import Extension

import sys, os

VERSION = "0.9"

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"
           ]

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

EXTRA_LINK_ARGS = []
EXTRA_COMPILE_ARGS = []

if "--timing" in sys.argv:
    MODULES.append("libteacup")
    EXTRA_COMPILE_ARGS.append("-DMEASURE_TIMING")

if "--threaded" in sys.argv:
    EXTRA_COMPILE_ARGS.append("-DTHREADED")
    sys.argv.remove("--threaded")

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

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 HAS_UINT64   %d
#define LP64         %d
#define HAS_FLOAT128 %d

""" % (HAS_UINT64, LP64, HAS_FLOAT128))
    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.

include_dir = '%s'
version     = '%s'
hasUInt64   = %d
LP64        = %d

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, HAS_UINT64, LP64))
    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)

