from libtbx.str_utils import show_string
import libtbx.load_env
import re
import sys, os
op = os.path

Import("env_base", "env_etc")

env_etc.ccp4io_dist = libtbx.env.dist_path("ccp4io")

# FIXME
# Set lower size limits for MTZ file contents; this is a fix for an obscure
# bug which causes Phenix to crash on MacOS 10.5.  Probably not necessary in
# all circumstances though.
if env_etc.compiler == "win32_cl":
  # XXX for reasons that are unclear to me, defining CALL_LIKE_SUN is necessary
  # to get the proper function names in ccp4_fortran.h using VC++
  env_etc.ccp4io_defines = ["/Di386", "/D_MVS", "/DMXTALS=32", "/DMSETS=32",
    "/DMCOLUMNS=128", "/DCALL_LIKE_SUN"]
else:
  env_etc.ccp4io_defines = ["-DMSETS=32", "-DMXTALS=32", "-DMCOLUMNS=128"]

env_etc.ccp4io_include = "/usr/include/ccp4"

build_ccp4io_adaptbx = libtbx.env.under_build("ccp4io_adaptbx")
if (not op.isdir(build_ccp4io_adaptbx)):
  os.mkdir(build_ccp4io_adaptbx)
  assert op.isdir(build_ccp4io_adaptbx)

env = env_base.Clone(
  SHLINKFLAGS=env_etc.shlinkflags)
env.Append(CCFLAGS=env_etc.ccp4io_defines)
env.Append(SHCCFLAGS=env_etc.ccp4io_defines)
env_etc.include_registry.append(
  env=env,
  paths=[
    "#",
    op.dirname(env_etc.ccp4io_include),
    env_etc.ccp4io_include,
    op.join(env_etc.ccp4io_dist)])
env.Append(LIBS=[env_etc.libm, "ccp4c"])
# XXX 2012-06-16: is this actually necessary here, or just in code that links to
# ccp4io.lib?
if (os.name == "nt") :
  env.Prepend(LIBS=["Advapi32"])
if (   op.normcase(op.dirname(env_etc.ccp4io_dist))
    != op.normcase("ccp4io")):
  env.Repository(op.dirname(env_etc.ccp4io_dist))
source = []

c_files = []

probe_file_name = "/usr/include/ccp4/cmaplib.h"
env_etc.ccp4io_has_cmaplib = op.isfile(probe_file_name)

need_f_c = (
     libtbx.env.has_module("solve_resolve")
  or libtbx.env.find_in_repositories(relative_path="mosflm_fable"))
if need_f_c or os.name != "nt" and not libtbx.env.module_is_installed("ccp4io"):
  source.append(op.join("#ccp4io_adaptbx", "fortran_call_stubs.c"))
  source.append(op.join("#ccp4io_adaptbx", "printf_wrappers.c"))

# static library for solve_resolve
env_etc.ccp4io_lib = ["ccp4io", "ccp4c"]

if not libtbx.env.module_is_installed("ccp4io"):
  env.SharedLibrary(target='#lib/ccp4io', source=source)
  if (    libtbx.env.has_module("boost")
      and not env_etc.no_boost_python):
    Import( "env_no_includes_boost_python_ext" )
    sources = [ "#ccp4io_adaptbx/ext.cpp" ]
    env_ext = env_no_includes_boost_python_ext.Clone()
    env_ext.Prepend( LIBS = ["ccp4io", "ccp4c"] )
    env_etc.include_registry.append(
      env = env_ext,
      paths = [
        os.path.join( env_etc.ccp4io_dist),
        env_etc.boost_include,
        env_etc.python_include,
        ]
      )
    env_ext.SharedLibrary( target = "#lib/ccp4io_adaptbx_ext", source = sources )
