
"""Setup file for python module gpk_avg.
This does weighted, trimmed averages and
Kruskal least-squares monotonic fits.
"""
import sys

def info(s):
	sys.stdout.flush()
	sys.stderr.writelines([s, '\n'])
	sys.stderr.flush()

def _libtrunc(s):
	a = s.split('/')
	for tgt in ['lib64', 'lib']:
		if tgt in a:
			i = a.index(tgt)
			return os.path.join(*(a[:i+1]))
	return s

# The following code helps you find libgpk.so and libgpkio.so,
# so long as they are somewhere on LD_LIBRARY_PATH.    This may be important
# if you are using a binary distribution which may have its own limited idea
# of a search path, and you have added more directories (for your own software)
# to LD_LIBRARY_PATH.
import os
import stat

GPKLIB_LIB = None
pl = os.environ.get('LD_LIBRARY_PATH', '').split(':')
for p in pl:
	for ext in ['so', 'a']:
		pp = os.path.join(p, 'libgpk.%s' % ext)
		if os.path.isfile(pp) and os.access(pp, os.R_OK):
			GPKLIB_LIB = p
			break
	if GPKLIB_LIB is not None:
		break
if GPKLIB_LIB is None:
	info("#WARN: Cannot find gpklib.so on the LD_LIBRARY_PATH.  Searching elsewhere.")
	pl = []
	if 'HOME' in os.environ:
		pl.append(os.path.join(os.environ['HOME'], 'local/lib'))
		pl.append(os.path.join(os.environ['HOME'], 'lib'))
	for p in sys.path:
		pl.append(_libtrunc(p))
	for p in pl:
		for ext in ['so', 'a']:
			pp = os.path.join(p, 'libgpk.%s' % ext)
			if(os.path.isfile(pp) and os.access(pp, os.R_OK)
				and (GPKLIB_LIB is None
					or os.stat(pp)[stat.ST_MTIME]>os.stat(GPKLIB_LIB)[stat.ST_MTIME])
				):
				GPKLIB_LIB = p
if GPKLIB_LIB is None:
	info("#ERROR: Cannot find gpklib.so.  Please set LD_LIBRARY_PATH or install gpklib.")
	sys.exit(1)
info("#INFO: Found newest gpklib.so at %s" % GPKLIB_LIB)

# This tells where the libgpk include files go:
GPKLIB_INCLUDES = os.path.join(os.path.split(GPKLIB_LIB)[0], 'include')
# GPKLIB_INCLUDES = '/home/mace/gpk/local/include'
print 'includes=', GPKLIB_INCLUDES

from gmisclib import Num

# Copyright 2006,2007 Greg Kochanski
# Released under the LGPL, version 2 or later.

from distutils.core import setup, Extension

setup(name="gpkavg", version="1.0.1",
	description = "Robust Averaging.",
	author = "Greg Kochanski",
	author_email = "gpk@kochanski.org",
	ext_modules = [
		Extension("gpkavg", [ "gpk_avg_py.cc" ],
				libraries = ["gpk"],
				# Places to look for gpklib.h and gpkio.h:
				include_dirs = [
						GPKLIB_INCLUDES,
						Num.get_include()
						],

				# Places to look or libgpk and libgpkio:
				library_dirs = [
						GPKLIB_LIB
						],
				language = 'c++'
			)
		]
	)
