Import("env")
Import("env_etc")


def ver(tuple3):
    if tuple3 is None:
        return 0
    if type(tuple3) is not tuple:
        return tuple3
    t = tuple3[0] * 100 * 100 + tuple3[1] * 100
    if len(tuple3) > 2:
        t = t + tuple3[2]
    return t


outlier_helpers_env = env.Clone()
ccflags = outlier_helpers_env["SHCCFLAGS"]


# XCode 7.3 compiler update results in some test failures with -O3 or -O3
# optimization enabled, therefore reduce optimization to -O1 specifically for
# this one extension for clang_version > 7.0.2
# (XCode 7.3 distributes clang_version 7.3.0)
# http://phenix-online.org/pipermail/cctbxbb/2016-April/001284.html
# https://gist.github.com/yamaya/2924292
#
if env_etc.clang_version is not None and ver(env_etc.clang_version) > ver((7, 0, 2)):
    for o in ("-O3", "-O2"):
        if o in ccflags:
            ccflags.remove(o)
            ccflags.append("-O1")

outlier_helpers_env.Replace(SHCCFLAGS=ccflags)
outlier_helpers_obj = outlier_helpers_env.SharedObject(
    source="boost_python/outlier_helpers.cc"
)

sources = [
    "boost_python/parameterisation_helpers.cc",
    "boost_python/gallego_yezzi.cc",
    "boost_python/mahalanobis.cc",
    outlier_helpers_obj,
    "boost_python/restraints_helpers.cc",
    "boost_python/rtmats.cc",
    "boost_python/gaussian_smoother.cc",
    "boost_python/gaussian_smoother_2D.cc",
    "boost_python/gaussian_smoother_3D.cc",
    "boost_python/refinement_ext.cc",
]

env.SharedLibrary(
    target="#/lib/dials_refinement_helpers_ext", source=sources, LIBS=env["LIBS"]
)
