[cpl-plugin-xsh] 02/04: New upstream version 2.6.0+dfsg

Ole Streicher olebole at moszumanska.debian.org
Sat Apr 18 16:17:04 UTC 2015


This is an automated email from the git hooks/post-receive script.

olebole pushed a commit to branch debian
in repository cpl-plugin-xsh.

commit 3b3533fe1d822d61ff4d44e664d088a267030164
Author: Ole Streicher <olebole at debian.org>
Date:   Sat Apr 18 18:15:10 2015 +0200

    New upstream version 2.6.0+dfsg
---
 ChangeLog                                          |   27 +
 Makefile.am                                        |    2 +-
 Makefile.in                                        |    9 +-
 acinclude.m4                                       |    4 +-
 aclocal.m4                                         |    1 +
 admin/config.guess                                 |  313 +-
 admin/config.sub                                   |   56 +-
 calib/cal_size                                     |    2 +-
 calib/gasgano/config/XSHOO.prefs                   |    2 +-
 calib/gasgano/config/xsh_wkf.oca                   |   88 +
 calib/gasgano/config/xshoo.oca                     |  564 +-
 calib/gasgano/config/xshoo.tpl.oca                 |   39 +-
 configure                                          |  276 +-
 configure.ac                                       |    9 +-
 hdrl/Makefile.am                                   |  106 +
 hdrl/Makefile.in                                   | 1307 +++
 hdrl/acinclude.m4                                  |   99 +
 aclocal.m4 => hdrl/aclocal.m4                      |    4 -
 hdrl/admin/compile                                 |  347 +
 {admin => hdrl/admin}/config.guess                 |  313 +-
 {admin => hdrl/admin}/config.sub                   |   56 +-
 hdrl/admin/depcomp                                 |  791 ++
 hdrl/admin/install-sh                              |  527 ++
 hdrl/admin/ltmain.sh                               | 9655 ++++++++++++++++++++
 hdrl/admin/missing                                 |  215 +
 hdrl/admin/test-driver                             |  127 +
 hdrl/config.h.in                                   |  124 +
 configure => hdrl/configure                        | 8705 ++++++++----------
 hdrl/configure.ac                                  |  131 +
 hdrl/hdrl.h                                        |   65 +
 hdrl/hdrl_bpm_2d.c                                 | 1289 +++
 hdrl/hdrl_bpm_2d.h                                 |  101 +
 hdrl/hdrl_bpm_3d.c                                 |  511 ++
 hdrl/hdrl_bpm_3d.h                                 |   84 +
 hdrl/hdrl_bpm_fit.c                                |  665 ++
 hdrl/hdrl_bpm_fit.h                                |   81 +
 hdrl/hdrl_bpm_utils.c                              |  318 +
 hdrl/hdrl_bpm_utils.h                              |   56 +
 hdrl/hdrl_buffer.c                                 |  331 +
 hdrl/hdrl_buffer.h                                 |   51 +
 hdrl/hdrl_collapse.c                               | 1991 ++++
 hdrl/hdrl_collapse.h                               |  174 +
 hdrl/hdrl_combine.c                                |  100 +
 hdrl/hdrl_combine.h                                |   64 +
 hdrl/hdrl_elemop.c                                 |  835 ++
 hdrl/hdrl_elemop.h                                 |  231 +
 hdrl/hdrl_fit.c                                    |  501 +
 hdrl/hdrl_fit.h                                    |   57 +
 hdrl/hdrl_flat.c                                   |  561 ++
 hdrl/hdrl_flat.h                                   |   72 +
 hdrl/hdrl_image.c                                  |  801 ++
 hdrl/hdrl_image.h                                  |  131 +
 hdrl/hdrl_image_defs.h                             |   48 +
 hdrl/hdrl_image_math.c                             |  609 ++
 hdrl/hdrl_image_math.h                             |   64 +
 hdrl/hdrl_imagelist.h                              |   37 +
 hdrl/hdrl_imagelist_basic.c                        |  722 ++
 hdrl/hdrl_imagelist_basic.h                        |   79 +
 hdrl/hdrl_imagelist_basic_body.h                   |   83 +
 hdrl/hdrl_imagelist_defs.h                         |   51 +
 hdrl/hdrl_imagelist_io.c                           |  660 ++
 hdrl/hdrl_imagelist_io.h                           |   91 +
 hdrl/hdrl_imagelist_view.c                         |  461 +
 hdrl/hdrl_imagelist_view.h                         |   61 +
 hdrl/hdrl_iter.c                                   |  219 +
 hdrl/hdrl_iter.h                                   |   98 +
 hdrl/hdrl_lacosmics.c                              |  727 ++
 hdrl/hdrl_lacosmics.h                              |   73 +
 hdrl/hdrl_overscan.c                               | 1721 ++++
 hdrl/hdrl_overscan.h                               |  146 +
 hdrl/hdrl_overscan_defs.h                          |   79 +
 hdrl/hdrl_parameter.c                              |  163 +
 hdrl/hdrl_parameter.h                              |  139 +
 hdrl/hdrl_parameter_defs.h                         |   51 +
 hdrl/hdrl_prototyping.c                            | 1269 +++
 hdrl/hdrl_prototyping.h                            |   65 +
 hdrl/hdrl_sigclip.c                                |  882 ++
 hdrl/hdrl_sigclip.h                                |  108 +
 hdrl/hdrl_strehl.c                                 | 1335 +++
 hdrl/hdrl_strehl.h                                 |   99 +
 hdrl/hdrl_test.h                                   |   54 +
 hdrl/hdrl_types.h                                  |   82 +
 hdrl/hdrl_utils.c                                  | 1394 +++
 hdrl/hdrl_utils.h                                  |  281 +
 hdrl/igam.c                                        |  247 +
 hdrl/m4macros/cpl.m4                               | 1435 +++
 hdrl/m4macros/eso.m4                               | 1116 +++
 hdrl/m4macros/libtool.m4                           | 7992 ++++++++++++++++
 hdrl/m4macros/ltoptions.m4                         |  384 +
 hdrl/m4macros/ltsugar.m4                           |  123 +
 hdrl/m4macros/ltversion.m4                         |   23 +
 hdrl/m4macros/lt~obsolete.m4                       |   98 +
 hdrl/m4macros/purify.m4                            |   27 +
 hdrl/tests/Makefile.am                             |   94 +
 {irplib => hdrl}/tests/Makefile.in                 |  722 +-
 hdrl/tests/hdrl_bpm_2d-test.c                      |  233 +
 hdrl/tests/hdrl_bpm_3d-test.c                      |  266 +
 hdrl/tests/hdrl_bpm_fit-test.c                     |  227 +
 hdrl/tests/hdrl_bpm_utils-test.c                   |  414 +
 hdrl/tests/hdrl_buffer-test.c                      |   98 +
 hdrl/tests/hdrl_collapse-test.c                    |  635 ++
 hdrl/tests/hdrl_combine-test.c                     |  333 +
 hdrl/tests/hdrl_elemop-test.c                      |  950 ++
 hdrl/tests/hdrl_fit-test.c                         |  320 +
 hdrl/tests/hdrl_image-test.c                       |  481 +
 hdrl/tests/hdrl_imagelist_basic-test.c             |  161 +
 hdrl/tests/hdrl_imagelist_io-test.c                |  204 +
 hdrl/tests/hdrl_imagelist_view-test.c              |  507 +
 hdrl/tests/hdrl_lacosmics-test.c                   |  244 +
 hdrl/tests/hdrl_overscan-test.c                    |  856 ++
 hdrl/tests/hdrl_parameter-test.c                   |  192 +
 hdrl/tests/hdrl_sigclip-test.c                     |  705 ++
 hdrl/tests/hdrl_strehl-test.c                      |  585 ++
 hdrl/tests/hdrl_utils-test.c                       |  629 ++
 irplib/Makefile.in                                 |    7 +
 irplib/irplib_framelist.c                          |    2 +-
 irplib/irplib_mkmaster.c                           |    2 +-
 irplib/irplib_plugin.c                             |   66 +-
 irplib/irplib_ppm.c                                |   23 +-
 irplib/irplib_sdp_spectrum.c                       |   46 +-
 irplib/irplib_slitpos.c                            |   28 +-
 irplib/irplib_spectrum.c                           |   25 +-
 irplib/irplib_strehl.c                             |   12 +-
 irplib/irplib_utils.c                              |  106 +-
 irplib/irplib_wavecal.c                            |   23 +-
 irplib/irplib_wlxcorr.c                            |   31 +-
 irplib/tests/Makefile.am                           |    2 +-
 irplib/tests/Makefile.in                           |    9 +-
 irplib/tests/irplib_plugin-test.c                  |    3 -
 irplib/tests/irplib_sdp_spectrum-test.c            |    5 +-
 irplib/tests/irplib_wlxcorr-test.c                 |   20 +-
 m4macros/hdrl.m4                                   |   28 +
 recipes/Makefile.am                                |  111 +-
 recipes/Makefile.in                                |  183 +-
 recipes/xsh_lingain.c                              |    8 +-
 recipes/xsh_mflat.c                                |  112 +-
 recipes/xsh_respon_slit_stare.c                    |   17 +-
 reflex/Makefile.in                                 |    7 +
 reflex/xsh_calib_interactive_common.py             |   15 +-
 reflex/xsh_object_interactive_common.py            |   16 +-
 reflex/xsh_object_interactive_common_ifu.py        |   14 +-
 reflex/xsh_wkf.oca                                 |  193 +-
 reflex/xsh_wkf_stare.oca                           |  163 +
 reflex/xshooter.xml.in                             |   82 +-
 regtests/Makefile.in                               |    7 +
 regtests/tests/Makefile.in                         |    7 +
 xsh/Makefile.am                                    |   15 +-
 xsh/Makefile.in                                    |   36 +-
 xsh/tests/Makefile.am                              |   17 +-
 xsh/tests/Makefile.in                              |   61 +-
 .../{test-xsh_slitmap.c => test-spectrum_stat.c}   |  147 +-
 xsh/tests/test-tell_catalog.c                      |  145 +
 ...ct_vacuum_to_air.c => test-telluric_sampling.c} |  167 +-
 xsh/tests/test-xsh_bspline_interpol.c              |    2 +-
 xsh/tests/test-xsh_compute_noise_map.c             |    2 +-
 xsh/tests/test-xsh_correct_vacuum_to_air.c         |    3 +
 xsh/tests/test-xsh_create_master_bias.c            |   15 +-
 xsh/tests/test-xsh_create_master_dark.c            |   14 +-
 xsh/tests/test-xsh_data_order.c                    |    1 -
 xsh/tests/test-xsh_data_wave_tab_2d.c              |    1 -
 xsh/tests/test-xsh_data_wave_tab_2d_sample.c       |    1 -
 xsh/tests/test-xsh_detect_line_file.c              |    1 +
 xsh/tests/test-xsh_slitmap.c                       |    1 -
 xsh/tests/test-xsh_subtract_sky_nod.c              |    1 -
 xsh/tests/tests.c                                  |   32 +-
 xsh/tests/tests.h                                  |    2 +-
 xsh/xsh_badpixelmap.c                              |   75 +-
 xsh/xsh_badpixelmap.h                              |    4 +
 xsh/xsh_compute_linearity.c                        |   45 +-
 xsh/xsh_create_master.c                            |   18 +-
 xsh/xsh_detmon.c                                   | 4714 +---------
 xsh/xsh_detmon.h                                   |  267 +-
 xsh/xsh_detmon_dfs.h                               |   52 +
 xsh/xsh_detmon_lg.c                                | 8138 +++++++++--------
 xsh/xsh_detmon_lg.h                                |   70 +-
 xsh/xsh_detmon_lg_impl.h                           |   15 +-
 xsh/xsh_detmon_utils.c                             |  277 +
 xsh/xsh_detmon_utils.h                             |   64 +
 xsh/xsh_dfs.c                                      |  203 +-
 xsh/xsh_drl_check.c                                |    2 +-
 xsh/xsh_dump.c                                     |   11 +-
 xsh/xsh_flexcor.c                                  |    3 +-
 xsh/xsh_follow_arclines.c                          |    4 +
 xsh/xsh_hdrl_functions.c                           |  139 +
 xsh/xsh_hdrl_functions.h                           |   46 +
 xsh/xsh_irplib_mkmaster.c                          |    3 +-
 xsh/xsh_ksigma_clip.c                              |  245 +
 xsh/{xsh_detmon_lg_impl.h => xsh_ksigma_clip.h}    |   58 +-
 xsh/xsh_model_kernel.c                             |    2 +-
 xsh/xsh_parameters.c                               |   43 +-
 xsh/xsh_pfits.c                                    |   73 +-
 xsh/xsh_pfits_qc.c                                 |    6 +-
 xsh/xsh_pfits_qc.h                                 |    2 +-
 xsh/xsh_qc_definition.h                            |    3 +-
 xsh/xsh_qc_handling.c                              |   49 +
 xsh/xsh_qc_handling.h                              |    7 +
 xsh/xsh_remove_crh_multi.c                         |    2 +-
 xsh/xsh_remove_crh_single.c                        |   48 +-
 xsh/xsh_subtract_sky_nod.c                         |   82 -
 xsh/xsh_subtract_sky_single.c                      |    2 +-
 xsh/xsh_utils_image.c                              |    8 +-
 xsh/xsh_utils_response.c                           |    2 +-
 xsh/xsh_utils_scired_slit.c                        |   27 +-
 203 files changed, 66698 insertions(+), 15369 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index bbc47c3..8026d2d 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,30 @@
+2.6.0
+   PSO release
+2.5.8
+   Fixed problems portability jenkins on test-xsh_create_masterbias, test-xsh_create_masterdark
+2.5.7
+   Fixed linearity computation (and problems unit tests)
+   added in decode-bp parameter help most frequent codes (PIPE-5678) 
+2.5.6
+   Fixed PIPE-5605 (allow empty inputs in reflex workflow)
+   "safer definition of temporary files in case of no sky background subtraction (as temporary frames slitmap_frame,wavemap_frame were not created)" recipes/xsh_respon_slit_stare.c
+2.5.5
+    "fixed bug in using optimised model cfg after AFC correction in NIR (PIPE-5608)" xsh_flexcor.c
+    fixed PIPE-5439 (use of proper formula to correct vacuum-air telluric model spectra wave dependency)
+    Fixed PIPE-3930 about use of standard error/quality info in fits header
+2.5.4 
+    To solve a Paranal problem changed OCA rules to classify also AFC in slit mode
+    To solve PSO robustness problem "in case specres_stdev is nan re-set specres_stdev to -999 to allow saving of product" xsh_follow_arclines.c
+
+    "changed hsearch from 500 to 200 to improve robustness (PIPE-5369)" xsh_utils_response.c
+
+    Fixed oca rule problem (from Paranal) due to missing check on ORDER_TAB_EDGES input on JH filed case
+    Added dependency from HDRL (useful for lingain and CRH)
+    Fixed PIPE-5176 (TLAPSE wrong value in case of single input frame)
+2.5.3 
+    Added flux merged 2d products to reflex_end_products (Andrea Mehner request)
+    Fix PIPE-3930, 4145, 5242
+    Fixed 2RB generation (Paranal)  problem
 2.5.2
     Fix problem displaying IDP products when no flux calibrated spectrum is generated
     Fix problem reducing JH data
diff --git a/Makefile.am b/Makefile.am
index 142f2a1..d5ed31d 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -26,7 +26,7 @@ DISTCLEANFILES = *~
 
 COMPILE_FIRST = irplib
 
-TOPSUBDIRS = xsh recipes regtests reflex
+TOPSUBDIRS = hdrl xsh recipes regtests reflex
 
 
 
diff --git a/Makefile.in b/Makefile.in
index e29fdd4..f9ae5f6 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -93,6 +93,7 @@ subdir = .
 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps = $(top_srcdir)/m4macros/cpl.m4 \
 	$(top_srcdir)/m4macros/eso.m4 $(top_srcdir)/m4macros/gsl.m4 \
+	$(top_srcdir)/m4macros/hdrl.m4 \
 	$(top_srcdir)/m4macros/libtool.m4 \
 	$(top_srcdir)/m4macros/ltoptions.m4 \
 	$(top_srcdir)/m4macros/ltsugar.m4 \
@@ -273,6 +274,10 @@ GREP = @GREP@
 GSL_INCLUDES = @GSL_INCLUDES@
 GSL_LDFLAGS = @GSL_LDFLAGS@
 GSL_LIBS = @GSL_LIBS@
+HDRL_INCLUDES = @HDRL_INCLUDES@
+HDRL_INTERNAL_CFLAGS = @HDRL_INTERNAL_CFLAGS@
+HDRL_LDFLAGS = @HDRL_LDFLAGS@
+HDRL_LIBS = @HDRL_LIBS@
 INSTALL = @INSTALL@
 INSTALL_DATA = @INSTALL_DATA@
 INSTALL_PROGRAM = @INSTALL_PROGRAM@
@@ -290,6 +295,7 @@ LIBCPLCORE = @LIBCPLCORE@
 LIBCPLDFS = @LIBCPLDFS@
 LIBCPLDRS = @LIBCPLDRS@
 LIBCPLUI = @LIBCPLUI@
+LIBHDRL = @LIBHDRL@
 LIBIRPLIB = @LIBIRPLIB@
 LIBLAPACK = @LIBLAPACK@
 LIBOBJS = @LIBOBJS@
@@ -392,6 +398,7 @@ psdir = @psdir@
 sbindir = @sbindir@
 sharedstatedir = @sharedstatedir@
 srcdir = @srcdir@
+subdirs = @subdirs@
 sysconfdir = @sysconfdir@
 target = @target@
 target_alias = @target_alias@
@@ -408,7 +415,7 @@ AUTOMAKE_OPTIONS = 1.8 foreign
 ACLOCAL_AMFLAGS = -I m4macros
 DISTCLEANFILES = *~
 COMPILE_FIRST = irplib
-TOPSUBDIRS = xsh recipes regtests reflex
+TOPSUBDIRS = hdrl xsh recipes regtests reflex
 HTML_SUBDIRS = 
 SUBDIRS = $(COMPILE_FIRST) $(TOPSUBDIRS) $(COMPILE_LAST)
 EXTRA_DIST = m4macros/eso.m4 m4macros/cpl.m4 m4macros/gsl.m4 admin/html.am \
diff --git a/acinclude.m4 b/acinclude.m4
index f5399ac..18725c5 100644
--- a/acinclude.m4
+++ b/acinclude.m4
@@ -272,12 +272,13 @@ AC_DEFUN([XSH_CREATE_SYMBOLS],
 
     # Symbols for package include file and library search paths
 
-    XSH_INCLUDES='-I$(top_srcdir)/xsh -I$(top_srcdir)/irplib'
+    XSH_INCLUDES='-I$(top_srcdir)/xsh -I$(top_srcdir)/irplib -I$(top_srcdir)/hdrl'
     XSH_LDFLAGS='-L$(top_builddir)/xsh'
 
     # Library aliases
     LIBXSH='$(top_builddir)/xsh/libxsh.la'
     LIBIRPLIB='$(top_builddir)/irplib/libirplib.la'
+    LIBHDRL='$(top_builddir)/hdrl/libhdrl.la'
 
     # Using irplib_fits_update_checksums function:
     IRPLIB_CPPFLAGS='-DIRPLIB_USE_FITS_UPDATE_CHECKSUM'
@@ -289,6 +290,7 @@ AC_DEFUN([XSH_CREATE_SYMBOLS],
     AC_SUBST(LIBXSH)
     AC_SUBST(LIBIRPLIB)
     AC_SUBST(IRPLIB_CPPFLAGS)
+    AC_SUBST(HDRL_INCLUDES)
 
     # Check for CPL and user defined libraries
     AC_REQUIRE([CPL_CHECK_LIBS])
diff --git a/aclocal.m4 b/aclocal.m4
index 8aaed40..2fd96e5 100644
--- a/aclocal.m4
+++ b/aclocal.m4
@@ -1131,6 +1131,7 @@ AC_SUBST([am__untar])
 m4_include([m4macros/cpl.m4])
 m4_include([m4macros/eso.m4])
 m4_include([m4macros/gsl.m4])
+m4_include([m4macros/hdrl.m4])
 m4_include([m4macros/libtool.m4])
 m4_include([m4macros/ltoptions.m4])
 m4_include([m4macros/ltsugar.m4])
diff --git a/admin/config.guess b/admin/config.guess
index 1804e9f..1f5c50c 100755
--- a/admin/config.guess
+++ b/admin/config.guess
@@ -1,10 +1,8 @@
 #! /bin/sh
 # Attempt to guess a canonical system name.
-#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
-#   2011, 2012, 2013 Free Software Foundation, Inc.
+#   Copyright 1992-2014 Free Software Foundation, Inc.
 
-timestamp='2012-12-29'
+timestamp='2014-03-23'
 
 # This file is free software; you can redistribute it and/or modify it
 # under the terms of the GNU General Public License as published by
@@ -26,7 +24,7 @@ timestamp='2012-12-29'
 # program.  This Exception is an additional permission under section 7
 # of the GNU General Public License, version 3 ("GPLv3").
 #
-# Originally written by Per Bothner. 
+# Originally written by Per Bothner.
 #
 # You can get the latest version of this script from:
 # http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
@@ -52,9 +50,7 @@ version="\
 GNU config.guess ($timestamp)
 
 Originally written by Per Bothner.
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011,
-2012, 2013 Free Software Foundation, Inc.
+Copyright 1992-2014 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
@@ -136,6 +132,27 @@ UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
 UNAME_SYSTEM=`(uname -s) 2>/dev/null`  || UNAME_SYSTEM=unknown
 UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
 
+case "${UNAME_SYSTEM}" in
+Linux|GNU|GNU/*)
+	# If the system lacks a compiler, then just pick glibc.
+	# We could probably try harder.
+	LIBC=gnu
+
+	eval $set_cc_for_build
+	cat <<-EOF > $dummy.c
+	#include <features.h>
+	#if defined(__UCLIBC__)
+	LIBC=uclibc
+	#elif defined(__dietlibc__)
+	LIBC=dietlibc
+	#else
+	LIBC=gnu
+	#endif
+	EOF
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC' | sed 's, ,,g'`
+	;;
+esac
+
 # Note: order is significant - the case branches are not exclusive.
 
 case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
@@ -809,7 +826,7 @@ EOF
     *:MINGW*:*)
 	echo ${UNAME_MACHINE}-pc-mingw32
 	exit ;;
-    i*:MSYS*:*)
+    *:MSYS*:*)
 	echo ${UNAME_MACHINE}-pc-msys
 	exit ;;
     i*:windows32*:*)
@@ -857,21 +874,21 @@ EOF
 	exit ;;
     *:GNU:*:*)
 	# the GNU system
-	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
+	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
 	exit ;;
     *:GNU/*:*:*)
 	# other systems with GNU libc and userland
-	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu
+	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC}
 	exit ;;
     i*86:Minix:*:*)
 	echo ${UNAME_MACHINE}-pc-minix
 	exit ;;
     aarch64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     aarch64_be:Linux:*:*)
 	UNAME_MACHINE=aarch64_be
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     alpha:Linux:*:*)
 	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
@@ -884,59 +901,54 @@ EOF
 	  EV68*) UNAME_MACHINE=alphaev68 ;;
 	esac
 	objdump --private-headers /bin/sh | grep -q ld.so.1
-	if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
-	echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
+	if test "$?" = 0 ; then LIBC="gnulibc1" ; fi
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    arc:Linux:*:* | arceb:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     arm*:Linux:*:*)
 	eval $set_cc_for_build
 	if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
 	    | grep -q __ARM_EABI__
 	then
-	    echo ${UNAME_MACHINE}-unknown-linux-gnu
+	    echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	else
 	    if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \
 		| grep -q __ARM_PCS_VFP
 	    then
-		echo ${UNAME_MACHINE}-unknown-linux-gnueabi
+		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi
 	    else
-		echo ${UNAME_MACHINE}-unknown-linux-gnueabihf
+		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf
 	    fi
 	fi
 	exit ;;
     avr32*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     cris:Linux:*:*)
-	echo ${UNAME_MACHINE}-axis-linux-gnu
+	echo ${UNAME_MACHINE}-axis-linux-${LIBC}
 	exit ;;
     crisv32:Linux:*:*)
-	echo ${UNAME_MACHINE}-axis-linux-gnu
+	echo ${UNAME_MACHINE}-axis-linux-${LIBC}
 	exit ;;
     frv:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     hexagon:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     i*86:Linux:*:*)
-	LIBC=gnu
-	eval $set_cc_for_build
-	sed 's/^	//' << EOF >$dummy.c
-	#ifdef __dietlibc__
-	LIBC=dietlibc
-	#endif
-EOF
-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'`
-	echo "${UNAME_MACHINE}-pc-linux-${LIBC}"
+	echo ${UNAME_MACHINE}-pc-linux-${LIBC}
 	exit ;;
     ia64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     m32r*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     m68*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     mips:Linux:*:* | mips64:Linux:*:*)
 	eval $set_cc_for_build
@@ -955,54 +967,63 @@ EOF
 	#endif
 EOF
 	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
-	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
+	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; }
 	;;
-    or32:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+    openrisc*:Linux:*:*)
+	echo or1k-unknown-linux-${LIBC}
+	exit ;;
+    or32:Linux:*:* | or1k*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     padre:Linux:*:*)
-	echo sparc-unknown-linux-gnu
+	echo sparc-unknown-linux-${LIBC}
 	exit ;;
     parisc64:Linux:*:* | hppa64:Linux:*:*)
-	echo hppa64-unknown-linux-gnu
+	echo hppa64-unknown-linux-${LIBC}
 	exit ;;
     parisc:Linux:*:* | hppa:Linux:*:*)
 	# Look for CPU level
 	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
-	  PA7*) echo hppa1.1-unknown-linux-gnu ;;
-	  PA8*) echo hppa2.0-unknown-linux-gnu ;;
-	  *)    echo hppa-unknown-linux-gnu ;;
+	  PA7*) echo hppa1.1-unknown-linux-${LIBC} ;;
+	  PA8*) echo hppa2.0-unknown-linux-${LIBC} ;;
+	  *)    echo hppa-unknown-linux-${LIBC} ;;
 	esac
 	exit ;;
     ppc64:Linux:*:*)
-	echo powerpc64-unknown-linux-gnu
+	echo powerpc64-unknown-linux-${LIBC}
 	exit ;;
     ppc:Linux:*:*)
-	echo powerpc-unknown-linux-gnu
+	echo powerpc-unknown-linux-${LIBC}
+	exit ;;
+    ppc64le:Linux:*:*)
+	echo powerpc64le-unknown-linux-${LIBC}
+	exit ;;
+    ppcle:Linux:*:*)
+	echo powerpcle-unknown-linux-${LIBC}
 	exit ;;
     s390:Linux:*:* | s390x:Linux:*:*)
-	echo ${UNAME_MACHINE}-ibm-linux
+	echo ${UNAME_MACHINE}-ibm-linux-${LIBC}
 	exit ;;
     sh64*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     sh*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     sparc:Linux:*:* | sparc64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     tile*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     vax:Linux:*:*)
-	echo ${UNAME_MACHINE}-dec-linux-gnu
+	echo ${UNAME_MACHINE}-dec-linux-${LIBC}
 	exit ;;
     x86_64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     xtensa*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     i*86:DYNIX/ptx:4*:*)
 	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
@@ -1235,19 +1256,31 @@ EOF
 	exit ;;
     *:Darwin:*:*)
 	UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
-	case $UNAME_PROCESSOR in
-	    i386)
-		eval $set_cc_for_build
-		if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
-		  if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
-		      (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
-		      grep IS_64BIT_ARCH >/dev/null
-		  then
-		      UNAME_PROCESSOR="x86_64"
-		  fi
-		fi ;;
-	    unknown) UNAME_PROCESSOR=powerpc ;;
-	esac
+	eval $set_cc_for_build
+	if test "$UNAME_PROCESSOR" = unknown ; then
+	    UNAME_PROCESSOR=powerpc
+	fi
+	if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then
+	    if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+		if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
+		    (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+		    grep IS_64BIT_ARCH >/dev/null
+		then
+		    case $UNAME_PROCESSOR in
+			i386) UNAME_PROCESSOR=x86_64 ;;
+			powerpc) UNAME_PROCESSOR=powerpc64 ;;
+		    esac
+		fi
+	    fi
+	elif test "$UNAME_PROCESSOR" = i386 ; then
+	    # Avoid executing cc on OS X 10.9, as it ships with a stub
+	    # that puts up a graphical alert prompting to install
+	    # developer tools.  Any system running Mac OS X 10.7 or
+	    # later (Darwin 11 and later) is required to have a 64-bit
+	    # processor. This is not true of the ARM version of Darwin
+	    # that Apple uses in portable devices.
+	    UNAME_PROCESSOR=x86_64
+	fi
 	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
 	exit ;;
     *:procnto*:*:* | *:QNX:[0123456789]*:*)
@@ -1338,154 +1371,6 @@ EOF
 	exit ;;
 esac
 
-eval $set_cc_for_build
-cat >$dummy.c <<EOF
-#ifdef _SEQUENT_
-# include <sys/types.h>
-# include <sys/utsname.h>
-#endif
-main ()
-{
-#if defined (sony)
-#if defined (MIPSEB)
-  /* BFD wants "bsd" instead of "newsos".  Perhaps BFD should be changed,
-     I don't know....  */
-  printf ("mips-sony-bsd\n"); exit (0);
-#else
-#include <sys/param.h>
-  printf ("m68k-sony-newsos%s\n",
-#ifdef NEWSOS4
-	"4"
-#else
-	""
-#endif
-	); exit (0);
-#endif
-#endif
-
-#if defined (__arm) && defined (__acorn) && defined (__unix)
-  printf ("arm-acorn-riscix\n"); exit (0);
-#endif
-
-#if defined (hp300) && !defined (hpux)
-  printf ("m68k-hp-bsd\n"); exit (0);
-#endif
-
-#if defined (NeXT)
-#if !defined (__ARCHITECTURE__)
-#define __ARCHITECTURE__ "m68k"
-#endif
-  int version;
-  version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
-  if (version < 4)
-    printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
-  else
-    printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
-  exit (0);
-#endif
-
-#if defined (MULTIMAX) || defined (n16)
-#if defined (UMAXV)
-  printf ("ns32k-encore-sysv\n"); exit (0);
-#else
-#if defined (CMU)
-  printf ("ns32k-encore-mach\n"); exit (0);
-#else
-  printf ("ns32k-encore-bsd\n"); exit (0);
-#endif
-#endif
-#endif
-
-#if defined (__386BSD__)
-  printf ("i386-pc-bsd\n"); exit (0);
-#endif
-
-#if defined (sequent)
-#if defined (i386)
-  printf ("i386-sequent-dynix\n"); exit (0);
-#endif
-#if defined (ns32000)
-  printf ("ns32k-sequent-dynix\n"); exit (0);
-#endif
-#endif
-
-#if defined (_SEQUENT_)
-    struct utsname un;
-
-    uname(&un);
-
-    if (strncmp(un.version, "V2", 2) == 0) {
-	printf ("i386-sequent-ptx2\n"); exit (0);
-    }
-    if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
-	printf ("i386-sequent-ptx1\n"); exit (0);
-    }
-    printf ("i386-sequent-ptx\n"); exit (0);
-
-#endif
-
-#if defined (vax)
-# if !defined (ultrix)
-#  include <sys/param.h>
-#  if defined (BSD)
-#   if BSD == 43
-      printf ("vax-dec-bsd4.3\n"); exit (0);
-#   else
-#    if BSD == 199006
-      printf ("vax-dec-bsd4.3reno\n"); exit (0);
-#    else
-      printf ("vax-dec-bsd\n"); exit (0);
-#    endif
-#   endif
-#  else
-    printf ("vax-dec-bsd\n"); exit (0);
-#  endif
-# else
-    printf ("vax-dec-ultrix\n"); exit (0);
-# endif
-#endif
-
-#if defined (alliant) && defined (i860)
-  printf ("i860-alliant-bsd\n"); exit (0);
-#endif
-
-  exit (1);
-}
-EOF
-
-$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` &&
-	{ echo "$SYSTEM_NAME"; exit; }
-
-# Apollos put the system type in the environment.
-
-test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; }
-
-# Convex versions that predate uname can use getsysinfo(1)
-
-if [ -x /usr/convex/getsysinfo ]
-then
-    case `getsysinfo -f cpu_type` in
-    c1*)
-	echo c1-convex-bsd
-	exit ;;
-    c2*)
-	if getsysinfo -f scalar_acc
-	then echo c32-convex-bsd
-	else echo c2-convex-bsd
-	fi
-	exit ;;
-    c34*)
-	echo c34-convex-bsd
-	exit ;;
-    c38*)
-	echo c38-convex-bsd
-	exit ;;
-    c4*)
-	echo c4-convex-bsd
-	exit ;;
-    esac
-fi
-
 cat >&2 <<EOF
 $0: unable to guess system type
 
diff --git a/admin/config.sub b/admin/config.sub
index 52f04bc..66c5074 100755
--- a/admin/config.sub
+++ b/admin/config.sub
@@ -1,10 +1,8 @@
 #! /bin/sh
 # Configuration validation subroutine script.
-#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
-#   2011, 2012, 2013 Free Software Foundation, Inc.
+#   Copyright 1992-2014 Free Software Foundation, Inc.
 
-timestamp='2012-12-29'
+timestamp='2014-07-28'
 
 # This file is free software; you can redistribute it and/or modify it
 # under the terms of the GNU General Public License as published by
@@ -70,9 +68,7 @@ Report bugs and patches to <config-patches at gnu.org>."
 version="\
 GNU config.sub ($timestamp)
 
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011,
-2012, 2013 Free Software Foundation, Inc.
+Copyright 1992-2014 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
@@ -256,12 +252,12 @@ case $basic_machine in
 	| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
 	| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
 	| am33_2.0 \
-	| arc \
+	| arc | arceb \
 	| arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \
 	| avr | avr32 \
 	| be32 | be64 \
 	| bfin \
-	| c4x | clipper \
+	| c4x | c8051 | clipper \
 	| d10v | d30v | dlx | dsp16xx \
 	| epiphany \
 	| fido | fr30 | frv \
@@ -269,6 +265,7 @@ case $basic_machine in
 	| hexagon \
 	| i370 | i860 | i960 | ia64 \
 	| ip2k | iq2000 \
+	| k1om \
 	| le32 | le64 \
 	| lm32 \
 	| m32c | m32r | m32rle | m68000 | m68k | m88k \
@@ -286,20 +283,22 @@ case $basic_machine in
 	| mips64vr5900 | mips64vr5900el \
 	| mipsisa32 | mipsisa32el \
 	| mipsisa32r2 | mipsisa32r2el \
+	| mipsisa32r6 | mipsisa32r6el \
 	| mipsisa64 | mipsisa64el \
 	| mipsisa64r2 | mipsisa64r2el \
+	| mipsisa64r6 | mipsisa64r6el \
 	| mipsisa64sb1 | mipsisa64sb1el \
 	| mipsisa64sr71k | mipsisa64sr71kel \
+	| mipsr5900 | mipsr5900el \
 	| mipstx39 | mipstx39el \
 	| mn10200 | mn10300 \
 	| moxie \
 	| mt \
 	| msp430 \
 	| nds32 | nds32le | nds32be \
-	| nios | nios2 \
+	| nios | nios2 | nios2eb | nios2el \
 	| ns16k | ns32k \
-	| open8 \
-	| or32 \
+	| open8 | or1k | or1knd | or32 \
 	| pdp10 | pdp11 | pj | pjl \
 	| powerpc | powerpc64 | powerpc64le | powerpcle \
 	| pyramid \
@@ -327,7 +326,7 @@ case $basic_machine in
 	c6x)
 		basic_machine=tic6x-unknown
 		;;
-	m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | picochip)
+	m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | nvptx | picochip)
 		basic_machine=$basic_machine-unknown
 		os=-none
 		;;
@@ -369,13 +368,13 @@ case $basic_machine in
 	| aarch64-* | aarch64_be-* \
 	| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
 	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
-	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
+	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \
 	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
 	| avr-* | avr32-* \
 	| be32-* | be64-* \
 	| bfin-* | bs2000-* \
 	| c[123]* | c30-* | [cjt]90-* | c4x-* \
-	| clipper-* | craynv-* | cydra-* \
+	| c8051-* | clipper-* | craynv-* | cydra-* \
 	| d10v-* | d30v-* | dlx-* \
 	| elxsi-* \
 	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
@@ -384,6 +383,7 @@ case $basic_machine in
 	| hexagon-* \
 	| i*86-* | i860-* | i960-* | ia64-* \
 	| ip2k-* | iq2000-* \
+	| k1om-* \
 	| le32-* | le64-* \
 	| lm32-* \
 	| m32c-* | m32r-* | m32rle-* \
@@ -403,18 +403,22 @@ case $basic_machine in
 	| mips64vr5900-* | mips64vr5900el-* \
 	| mipsisa32-* | mipsisa32el-* \
 	| mipsisa32r2-* | mipsisa32r2el-* \
+	| mipsisa32r6-* | mipsisa32r6el-* \
 	| mipsisa64-* | mipsisa64el-* \
 	| mipsisa64r2-* | mipsisa64r2el-* \
+	| mipsisa64r6-* | mipsisa64r6el-* \
 	| mipsisa64sb1-* | mipsisa64sb1el-* \
 	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
+	| mipsr5900-* | mipsr5900el-* \
 	| mipstx39-* | mipstx39el-* \
 	| mmix-* \
 	| mt-* \
 	| msp430-* \
 	| nds32-* | nds32le-* | nds32be-* \
-	| nios-* | nios2-* \
+	| nios-* | nios2-* | nios2eb-* | nios2el-* \
 	| none-* | np1-* | ns16k-* | ns32k-* \
 	| open8-* \
+	| or1k*-* \
 	| orion-* \
 	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
 	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
@@ -796,7 +800,7 @@ case $basic_machine in
 		os=-mingw64
 		;;
 	mingw32)
-		basic_machine=i386-pc
+		basic_machine=i686-pc
 		os=-mingw32
 		;;
 	mingw32ce)
@@ -824,6 +828,10 @@ case $basic_machine in
 		basic_machine=powerpc-unknown
 		os=-morphos
 		;;
+	moxiebox)
+		basic_machine=moxie-unknown
+		os=-moxiebox
+		;;
 	msdos)
 		basic_machine=i386-pc
 		os=-msdos
@@ -832,7 +840,7 @@ case $basic_machine in
 		basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
 		;;
 	msys)
-		basic_machine=i386-pc
+		basic_machine=i686-pc
 		os=-msys
 		;;
 	mvs)
@@ -1354,7 +1362,7 @@ case $os in
 	-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
 	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\
 	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
-	      | -sym* | -kopensolaris* \
+	      | -sym* | -kopensolaris* | -plan9* \
 	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
 	      | -aos* | -aros* \
 	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
@@ -1369,14 +1377,14 @@ case $os in
 	      | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
 	      | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
 	      | -linux-newlib* | -linux-musl* | -linux-uclibc* \
-	      | -uxpv* | -beos* | -mpeix* | -udk* \
+	      | -uxpv* | -beos* | -mpeix* | -udk* | -moxiebox* \
 	      | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
 	      | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
 	      | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
 	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
 	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
 	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
-	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*)
+	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* | -tirtos*)
 	# Remember, each alternative MUST END IN *, to match a version number.
 		;;
 	-qnx*)
@@ -1500,9 +1508,6 @@ case $os in
 	-aros*)
 		os=-aros
 		;;
-	-kaos*)
-		os=-kaos
-		;;
 	-zvmoe)
 		os=-zvmoe
 		;;
@@ -1551,6 +1556,9 @@ case $basic_machine in
 	c4x-* | tic4x-*)
 		os=-coff
 		;;
+	c8051-*)
+		os=-elf
+		;;
 	hexagon-*)
 		os=-elf
 		;;
diff --git a/calib/cal_size b/calib/cal_size
index ec9e5a2..eaf098e 100644
--- a/calib/cal_size
+++ b/calib/cal_size
@@ -1 +1 @@
-659436
+659120
diff --git a/calib/gasgano/config/XSHOO.prefs b/calib/gasgano/config/XSHOO.prefs
index e24cffb..3f5c6f8 100644
--- a/calib/gasgano/config/XSHOO.prefs
+++ b/calib/gasgano/config/XSHOO.prefs
@@ -41,7 +41,7 @@ PRINTER_NAME=lp
 PRINT_FONT=Monospaced:16
 PRINT_ORIENTATION=P
 RADEC_CONVERSION=true
-RECIPE_SET=xsh_cfg_recover=/home/quality/pipelines/xshoo/lib/esopipes-plugins/xshoo-2.5.2/xsh_cfg_recover.so;xsh_lingain=/home/quality/pipelines/xshoo/lib/esopipes-plugins/xshoo-2.5.2/xsh_lingain.so;xsh_mbias=/home/quality/pipelines/xshoo/lib/esopipes-plugins/xshoo-2.5.2/xsh_mbias.so;xsh_mdark=/home/quality/pipelines/xshoo/lib/esopipes-plugins/xshoo-2.5.2/xsh_mdark.so;xsh_predict=/home/quality/pipelines/xshoo/lib/esopipes-plugins/xshoo-2.5.2/xsh_predict.so;xsh_orderpos=/home/quality/pipe [...]
+RECIPE_SET=xsh_cfg_recover=/home/quality/pipelines/xshoo/lib/esopipes-plugins/xshoo-2.6.0/xsh_cfg_recover.so;xsh_lingain=/home/quality/pipelines/xshoo/lib/esopipes-plugins/xshoo-2.6.0/xsh_lingain.so;xsh_mbias=/home/quality/pipelines/xshoo/lib/esopipes-plugins/xshoo-2.6.0/xsh_mbias.so;xsh_mdark=/home/quality/pipelines/xshoo/lib/esopipes-plugins/xshoo-2.6.0/xsh_mdark.so;xsh_predict=/home/quality/pipelines/xshoo/lib/esopipes-plugins/xshoo-2.6.0/xsh_predict.so;xsh_orderpos=/home/quality/pipe [...]
 SCRIPTS_DIR=/home/astro2/gasgano/scripts/gas-scripts
 SHORTEN_FILES_PATH=false
 SHORT_FILENAME=true
diff --git a/calib/gasgano/config/xsh_wkf.oca b/calib/gasgano/config/xsh_wkf.oca
index 2dd2c64..2fe20c7 100644
--- a/calib/gasgano/config/xsh_wkf.oca
+++ b/calib/gasgano/config/xsh_wkf.oca
@@ -3449,3 +3449,91 @@ recipe xsh_flexcomp {
   product DISP_TAB_AFC_NIR { PRO.CATG="DISP_TAB_AFC_NIR"; PRO.EXT="0002.fits";}
 
 }
+
+
+
+
+action XSH_FLEX_SLIT_UVB
+{
+
+minRet = 1; maxRet = 1;
+select file as MASTER_BIAS_UVB from calibFiles where PRO.CATG=="MASTER_BIAS_UVB"
+   and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.OUT1.GAIN==DET.OUT1.GAIN and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and inputFile.SEQ.ARM==SEQ.ARM;
+
+minRet = 1; maxRet = 1;
+select file as ORDER_TAB_EDGES_SLIT_UVB from calibFiles where PRO.CATG=="ORDER_TAB_EDGES_SLIT_UVB"
+   and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and inputFile.SEQ.ARM==SEQ.ARM;
+
+minRet = 1; maxRet = 1;
+select file as WAVE_TAB_2D_UVB from calibFiles where PRO.CATG=="WAVE_TAB_2D_UVB" and INS.OPTI3.NAME=="Pin_row" and (MJD-OBS < inputFile.MJD-OBS or MJD-OBS >= inputFile.MJD-OBS);
+
+
+minRet = 1; maxRet = 1;
+select file as ARC_LINE_LIST_AFC_UVB from calibFiles where PRO.CATG=="ARC_LINE_LIST_AFC_UVB";
+
+minRet = 1; maxRet = 1;
+select file as SPECTRAL_FORMAT_TAB_UVB from calibFiles where PRO.CATG=="SPECTRAL_FORMAT_TAB_UVB" and MJD-OBS < inputFile.MJD-OBS;
+
+recipe xsh_flexcomp {
+}
+
+  product WAVE_TAB_AFC_UVB { PRO.CATG="WAVE_TAB_AFC_UVB"; PRO.EXT="0000.fits";}
+  product ORDER_TAB_AFC_UVB { PRO.CATG="ORDER_TAB_AFC_UVB"; PRO.EXT="0001.fits";}
+  product DISP_TAB_AFC_UVB { PRO.CATG="DISP_TAB_AFC_UVB"; PRO.EXT="0002.fits";}
+}
+
+action XSH_FLEX_SLIT_VIS
+{
+
+minRet = 1; maxRet = 1;
+select file as MASTER_BIAS_VIS from calibFiles where PRO.CATG=="MASTER_BIAS_VIS"
+   and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.OUT1.GAIN==DET.OUT1.GAIN and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and inputFile.SEQ.ARM==SEQ.ARM;
+
+minRet = 1; maxRet = 1;
+select file as ORDER_TAB_EDGES_SLIT_VIS from calibFiles where PRO.CATG=="ORDER_TAB_EDGES_SLIT_VIS"
+   and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and inputFile.SEQ.ARM==SEQ.ARM;
+
+minRet = 1; maxRet = 1;
+select file as WAVE_TAB_2D_VIS from calibFiles where PRO.CATG=="WAVE_TAB_2D_VIS" and INS.OPTI3.NAME=="Pin_row" and (MJD-OBS < inputFile.MJD-OBS or MJD-OBS >= inputFile.MJD-OBS);
+
+minRet = 1; maxRet = 1;
+select file as ARC_LINE_LIST_AFC_VIS from calibFiles where PRO.CATG=="ARC_LINE_LIST_AFC_VIS";
+
+minRet = 1; maxRet = 1;
+select file as SPECTRAL_FORMAT_TAB_VIS from calibFiles where PRO.CATG=="SPECTRAL_FORMAT_TAB_VIS" and MJD-OBS < inputFile.MJD-OBS;
+
+recipe xsh_flexcomp {
+}
+  product WAVE_TAB_AFC_VIS { PRO.CATG="WAVE_TAB_AFC_VIS"; PRO.EXT="0000.fits";}
+  product ORDER_TAB_AFC_VIS { PRO.CATG="ORDER_TAB_AFC_VIS"; PRO.EXT="0001.fits";}
+  product DISP_TAB_AFC_VIS { PRO.CATG="DISP_TAB_AFC_VIS"; PRO.EXT="0002.fits";}
+
+}
+
+action XSH_FLEX_SLIT_NIR
+{
+
+minRet = 1; maxRet = 1;
+select file as ORDER_TAB_EDGES_SLIT_NIR from calibFiles where PRO.CATG=="ORDER_TAB_EDGES_SLIT_NIR"
+   and inputFile.DET.CHIP.ID==DET.CHIP.ID;
+
+minRet = 1; maxRet = 1;
+select file as WAVE_TAB_2D_NIR from calibFiles where PRO.CATG=="WAVE_TAB_2D_NIR" and INS.OPTI3.NAME=="Pin_row" and (MJD-OBS < inputFile.MJD-OBS or MJD-OBS >= inputFile.MJD-OBS);
+
+minRet = 1; maxRet = 1;
+select file as ARC_LINE_LIST_AFC_NIR from calibFiles where PRO.CATG=="ARC_LINE_LIST_AFC_NIR";
+
+minRet = 1; maxRet = 1;
+select file as SPECTRAL_FORMAT_TAB_NIR from calibFiles where PRO.CATG=="SPECTRAL_FORMAT_TAB_NIR" and MJD-OBS < inputFile.MJD-OBS;
+
+minRet = 0; maxRet = 1;
+select file as MASTER_BP_MAP_NIR from calibFiles where PRO.CATG=="MASTER_BP_MAP_NIR"
+   and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.WIN1.NX==DET.WIN1.NX and inputFile.DET.WIN1.NY==DET.WIN1.NY and inputFile.DET.READ.CLOCK==DET.READ.CLOCK and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and inputFile.SEQ.ARM==SEQ.ARM;
+
+recipe xsh_flexcomp {
+}
+  product WAVE_TAB_AFC_NIR { PRO.CATG="WAVE_TAB_AFC_NIR"; PRO.EXT="0000.fits";}
+  product ORDER_TAB_AFC_NIR { PRO.CATG="ORDER_TAB_AFC_NIR"; PRO.EXT="0001.fits";}
+  product DISP_TAB_AFC_NIR { PRO.CATG="DISP_TAB_AFC_NIR"; PRO.EXT="0002.fits";}
+
+}
diff --git a/calib/gasgano/config/xshoo.oca b/calib/gasgano/config/xshoo.oca
index 08ba97d..4cefea5 100644
--- a/calib/gasgano/config/xshoo.oca
+++ b/calib/gasgano/config/xshoo.oca
@@ -425,6 +425,33 @@ and INS.OPTI2.NAME=="IFU" then
 
 
 if
+  DPR.CATG=="CALIB" and DPR.TYPE=="LAMP,AFC" and DPR.TECH=="ECHELLE" and SEQ.ARM=="UVB" and INS.OPTI2.NAME=="SLOT" and INS.OPTI3.NAME=="Pin_0.5" and (TPL.ID=="SHOOT_slt_acq" or TPL.ID=="XSHOOTER_gen_cal_AFC") and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "FLEX_SLIT_UVB";
+  DO.CATG = "AFC_ATT_UVB";
+  CATG = "CALIB";
+}
+
+if
+  DPR.CATG=="CALIB" and DPR.TYPE=="LAMP,AFC" and DPR.TECH=="ECHELLE" and SEQ.ARM=="VIS" and INS.OPTI2.NAME=="SLOT" and INS.OPTI4.NAME=="Pin_0.5" and (TPL.ID=="SHOOT_slt_acq" or TPL.ID=="XSHOOTER_gen_cal_AFC") and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "FLEX_SLIT_VIS";
+  DO.CATG = "AFC_ATT_VIS";
+  CATG = "CALIB";
+}
+
+if
+  DPR.CATG=="CALIB" and DPR.TYPE=="LAMP,AFC" and DPR.TECH=="ECHELLE" and SEQ.ARM=="NIR" and INS.OPTI2.NAME=="SLOT" and INS.OPTI5.NAME=="Pin_0.5" and (TPL.ID=="SHOOT_slt_acq" or TPL.ID=="XSHOOTER_gen_cal_AFC") and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "FLEX_SLIT_NIR";
+  DO.CATG = "AFC_ATT_NIR";
+  CATG = "CALIB";
+}
+
+if
   DPR.CATG=="CALIB" and DPR.TYPE=="LAMP,AFC" and DPR.TECH=="ECHELLE"
   and SEQ.ARM=="UVB" and INS.OPTI2.NAME=="SLOT" and
   INS.OPTI3.NAME=="Pin_0.5" and (TPL.ID=="SHOOT_ifu_acq" or
@@ -1012,6 +1039,64 @@ and INS.OPTI5.NAME like "%JH%" then
 }
 
 
+
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%OBJECT%" and DPR.TECH
+like "%ECHELLE,SLIT,MAPPING%" and SEQ.ARM like "%UVB%" then
+{
+  DO.CATG = "OBJECT_SLIT_STARE_UVB";
+  RAW.TYPE = "SCIENCE_SLIT_STARE_UVB";
+}
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%OBJECT%" and DPR.TECH
+like "%ECHELLE,SLIT,MAPPING%" and SEQ.ARM like "%VIS%" then
+{
+  DO.CATG = "OBJECT_SLIT_STARE_VIS";
+  RAW.TYPE = "SCIENCE_SLIT_STARE_VIS";
+}
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%OBJECT%" and DPR.TECH
+like "%ECHELLE,SLIT,MAPPING%" and SEQ.ARM like "%NIR%" then
+{
+  DO.CATG = "OBJECT_SLIT_STARE_NIR";
+  RAW.TYPE = "SCIENCE_SLIT_STARE_NIR";
+}
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%OBJECT%" and DPR.TECH
+like "%ECHELLE,SLIT,MAPPING%" and SEQ.ARM like "%NIR%" 
+and INS.OPTI5.NAME like "%JH%" then
+{
+  DO.CATG = "OBJECT_SLIT_STARE_NIR";
+  RAW.TYPE = "SCIENCE_SLIT_STARE_JH_NIR";
+}
+
+
+
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%SKY%" and DPR.TECH
+like "%ECHELLE,SLIT,MAPPING%" and SEQ.ARM like "%UVB%" then
+{
+  DO.CATG = "SKY_SLIT_UVB";
+  RAW.TYPE = "SCIENCE_SLIT_STARE_UVB";
+}
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%SKY%" and DPR.TECH
+like "%ECHELLE,SLIT,MAPPING%" and SEQ.ARM like "%VIS%" then
+{
+  DO.CATG = "SKY_SLIT_VIS";
+  RAW.TYPE = "SCIENCE_SLIT_STARE_VIS";
+}
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%SKY%" and DPR.TECH
+like "%ECHELLE,SLIT,MAPPING%" and SEQ.ARM like "%NIR%" then
+{
+  DO.CATG = "SKY_SLIT_NIR";
+  RAW.TYPE = "SCIENCE_SLIT_STARE_NIR";
+}
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%SKY%" and DPR.TECH
+like "%ECHELLE,SLIT,MAPPING%" and SEQ.ARM like "%NIR%" 
+and INS.OPTI5.NAME like "%JH%" then
+{
+  DO.CATG = "SKY_SLIT_NIR";
+  RAW.TYPE = "SCIENCE_SLIT_STARE_JH_NIR";
+}
+
+
+
+
 if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%OBJECT%" and DPR.TECH
 like "%ECHELLE,IFU,STARE%" and SEQ.ARM like "%UVB%" then
 {
@@ -1067,6 +1152,59 @@ and INS.OPTI5.NAME like "%JH%" then
 
 
 
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%OBJECT%" and DPR.TECH
+like "%ECHELLE,IFU,MAPPING%" and SEQ.ARM like "%UVB%" then
+{
+  DO.CATG = "OBJECT_IFU_STARE_UVB";
+  RAW.TYPE = "SCIENCE_IFU_STARE_UVB";
+}
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%OBJECT%" and DPR.TECH
+like "%ECHELLE,IFU,MAPPING%" and SEQ.ARM like "%VIS%" then
+{
+  DO.CATG = "OBJECT_IFU_STARE_VIS";
+  RAW.TYPE = "SCIENCE_IFU_STARE_VIS";
+}
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%OBJECT%" and DPR.TECH
+like "%ECHELLE,IFU,MAPPING%" and SEQ.ARM like "%NIR%" then
+{
+  DO.CATG = "OBJECT_IFU_STARE_NIR";
+  RAW.TYPE = "SCIENCE_IFU_STARE_NIR";
+}
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%OBJECT%" and DPR.TECH
+like "%ECHELLE,IFU,MAPPING%" and SEQ.ARM like "%NIR%" 
+and INS.OPTI5.NAME like "%JH%" then
+{
+  DO.CATG = "OBJECT_IFU_STARE_NIR";
+  RAW.TYPE = "SCIENCE_IFU_STARE_JH_NIR";
+}
+
+
+
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%SKY%" and DPR.TECH
+like "%ECHELLE,IFU,MAPPING%" and SEQ.ARM like "%UVB%" then
+{
+  DO.CATG = "SKY_IFU_UVB";
+  RAW.TYPE = "SCIENCE_IFU_STARE_UVB";
+}
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%SKY%" and DPR.TECH
+like "%ECHELLE,IFU,MAPPING%" and SEQ.ARM like "%VIS%" then
+{
+  DO.CATG = "SKY_IFU_VIS";
+  RAW.TYPE = "SCIENCE_IFU_STARE_VIS";
+}
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%SKY%" and DPR.TECH
+like "%ECHELLE,IFU,MAPPING%" and SEQ.ARM like "%NIR%" then
+{
+  DO.CATG = "SKY_IFU_NIR";
+  RAW.TYPE = "SCIENCE_IFU_STARE_NIR";
+}
+if DPR.CATG like "%SCIENCE%" and DPR.TYPE like "%SKY%" and DPR.TECH
+like "%ECHELLE,IFU,MAPPING%" and SEQ.ARM like "%NIR%" 
+and INS.OPTI5.NAME like "%JH%" then
+{
+  DO.CATG = "SKY_IFU_NIR";
+  RAW.TYPE = "SCIENCE_IFU_STARE_JH_NIR";
+}
 
 
 
@@ -1905,54 +2043,54 @@ if PRO.CATG like "%SLICE_OFFSET_TABLE_NIR%" then
 // SELECTIONS
 //===========================================================================
 
-select execute(XSH_LINGAIN_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="LINEARITY_UVB";
-select execute(XSH_LINGAIN_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="LINEARITY_VIS";
-select execute(XSH_LINGAIN_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="LINEARITY_NIR";
+select execute(ACTION_LINGAIN_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="LINEARITY_UVB";
+select execute(ACTION_LINGAIN_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="LINEARITY_VIS";
+select execute(ACTION_LINGAIN_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="LINEARITY_NIR";
 
-select execute(XSH_MBIAS_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="BIAS_UVB"
+select execute(ACTION_MBIAS_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="BIAS_UVB"
   group by DET.WIN1.BINX,DET.WIN1.BINY,DET.READ.CLOCK,SEQ.ARM,TPL.START;
-select execute(XSH_MBIAS_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="BIAS_VIS"
+select execute(ACTION_MBIAS_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="BIAS_VIS"
   group by DET.WIN1.BINX,DET.WIN1.BINY,DET.READ.CLOCK,SEQ.ARM,TPL.START;
 
-select execute(XSH_MDARK_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="DARK_UVB"
+select execute(ACTION_MDARK_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="DARK_UVB"
   group by DET.WIN1.BINX,DET.WIN1.BINY,DET.READ.CLOCK,DET.WIN1.UIT1,TPL.START;
 
-select execute(XSH_MDARK_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="DARK_VIS"
+select execute(ACTION_MDARK_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="DARK_VIS"
   group by DET.WIN1.BINX,DET.WIN1.BINY,DET.READ.CLOCK,DET.WIN1.UIT1,TPL.START;
 
-select execute(XSH_MDARK_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="DARK_NIR"
+select execute(ACTION_MDARK_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="DARK_NIR"
   group by DET.NDIT,DET.DIT,TPL.START;
 
 
-select execute(XSH_PREDICT_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "FMTCHK_UVB";
-select execute(XSH_PREDICT_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "FMTCHK_VIS";
-select execute(XSH_PREDICT_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FMTCHK_NIR";
+select execute(ACTION_PREDICT_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "FMTCHK_UVB";
+select execute(ACTION_PREDICT_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "FMTCHK_VIS";
+select execute(ACTION_PREDICT_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FMTCHK_NIR";
 
-select execute(XSH_ORDERPOS_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "ORDERDEF_UVB";
-select execute(XSH_ORDERPOS_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "ORDERDEF_VIS";
-select execute(XSH_ORDERPOS_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "ORDERDEF_NIR";
+select execute(ACTION_ORDERPOS_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "ORDERDEF_UVB";
+select execute(ACTION_ORDERPOS_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "ORDERDEF_VIS";
+select execute(ACTION_ORDERPOS_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "ORDERDEF_NIR";
 
-select execute(XSH_MFLAT_SLIT_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FLAT_SLIT_UVB";
-select execute(XSH_MFLAT_SLIT_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FLAT_SLIT_VIS";
-select execute(XSH_MFLAT_SLIT_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FLAT_SLIT_JH_NIR";
-select execute(XSH_MFLAT_SLIT_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FLAT_SLIT_NIR";
+select execute(ACTION_MFLAT_SLIT_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FLAT_SLIT_UVB";
+select execute(ACTION_MFLAT_SLIT_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FLAT_SLIT_VIS";
+select execute(ACTION_MFLAT_SLIT_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FLAT_SLIT_JH_NIR";
+select execute(ACTION_MFLAT_SLIT_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FLAT_SLIT_NIR";
 
-select execute(XSH_MFLAT_IFU_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FLAT_IFU_UVB";
-select execute(XSH_MFLAT_IFU_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FLAT_IFU_VIS";
-select execute(XSH_MFLAT_IFU_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FLAT_IFU_NIR";
+select execute(ACTION_MFLAT_IFU_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FLAT_IFU_UVB";
+select execute(ACTION_MFLAT_IFU_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FLAT_IFU_VIS";
+select execute(ACTION_MFLAT_IFU_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "FLAT_IFU_NIR";
 
-select execute(XSH_WAVECAL_SLIT_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "ARC_SLIT_UVB";
-select execute(XSH_WAVECAL_SLIT_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "ARC_SLIT_VIS";
-select execute(XSH_WAVECAL_SLIT_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "ARC_SLIT_JH_NIR";
-select execute(XSH_WAVECAL_SLIT_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "ARC_SLIT_NIR";
+select execute(ACTION_WAVECAL_SLIT_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "ARC_SLIT_UVB";
+select execute(ACTION_WAVECAL_SLIT_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "ARC_SLIT_VIS";
+select execute(ACTION_WAVECAL_SLIT_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "ARC_SLIT_JH_NIR";
+select execute(ACTION_WAVECAL_SLIT_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "ARC_SLIT_NIR";
 
-select execute(XSH_WAVECAL_IFU_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "ARC_IFU_UVB";
-select execute(XSH_WAVECAL_IFU_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "ARC_IFU_VIS";
-select execute(XSH_WAVECAL_IFU_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "ARC_IFU_NIR";
+select execute(ACTION_WAVECAL_IFU_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "ARC_IFU_UVB";
+select execute(ACTION_WAVECAL_IFU_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "ARC_IFU_VIS";
+select execute(ACTION_WAVECAL_IFU_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "ARC_IFU_NIR";
 
-select execute(XSH_2DMAP_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "WAVE_UVB";
-select execute(XSH_2DMAP_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "WAVE_VIS";
-select execute(XSH_2DMAP_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "WAVE_NIR";
+select execute(ACTION_2DMAP_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "WAVE_UVB";
+select execute(ACTION_2DMAP_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "WAVE_VIS";
+select execute(ACTION_2DMAP_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "WAVE_NIR";
 
 
 select execute(ACTION_FLEX_IFU_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="FLEX_IFU_UVB" and INS.OPTI3.NAME=="Pin_0.5" and INS.OPTI2.NAME=="SLOT";
@@ -1960,66 +2098,68 @@ select execute(ACTION_FLEX_IFU_VIS) from inputFiles where SIG.TEMPLATE == 1 and
 select execute(ACTION_FLEX_IFU_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="FLEX_IFU_NIR" and INS.OPTI5.NAME=="Pin_0.5" and INS.OPTI2.NAME=="SLOT";
 
 
+select execute(ACTION_FLEX_SLIT_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="FLEX_SLIT_UVB" and INS.OPTI3.NAME=="Pin_0.5" and INS.OPTI2.NAME=="SLOT";
+select execute(ACTION_FLEX_SLIT_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="FLEX_SLIT_VIS" and INS.OPTI4.NAME=="Pin_0.5" and INS.OPTI2.NAME=="SLOT";
+select execute(ACTION_FLEX_SLIT_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE=="FLEX_SLIT_NIR" and INS.OPTI5.NAME=="Pin_0.5" and INS.OPTI2.NAME=="SLOT";
 
 
 // To be changed to RESPONSE RECIPE
-select execute(XSH_SCIRED_SLIT_STARE_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_TELL_SLIT_STARE_UVB";
-select execute(XSH_SCIRED_SLIT_STARE_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_TELL_SLIT_STARE_VIS";
-select execute(XSH_SCIRED_SLIT_STARE_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_STARE_NIR";
-
+select execute(ACTION_SCIRED_SLIT_STARE_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_TELL_SLIT_STARE_UVB";
+select execute(ACTION_SCIRED_SLIT_STARE_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_TELL_SLIT_STARE_VIS";
+select execute(ACTION_SCIRED_SLIT_STARE_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_STARE_NIR";
 
-select execute(XSH_SCIRED_SLIT_NOD_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_NOD_UVB";
-select execute(XSH_SCIRED_SLIT_NOD_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_NOD_VIS";
-select execute(XSH_SCIRED_SLIT_NOD_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_NOD_JH_NIR";
-select execute(XSH_SCIRED_SLIT_NOD_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_NOD_NIR";
 
+select execute(ACTION_SCIRED_SLIT_NOD_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_NOD_UVB";
+select execute(ACTION_SCIRED_SLIT_NOD_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_NOD_VIS";
+select execute(ACTION_SCIRED_SLIT_NOD_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_NOD_JH_NIR";
+select execute(ACTION_SCIRED_SLIT_NOD_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_NOD_NIR";
 
-select execute(XSH_SCIRED_IFU_STARE_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_TELL_IFU_STARE_UVB";
-select execute(XSH_SCIRED_IFU_STARE_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_TELL_IFU_STARE_VIS";
-select execute(XSH_SCIRED_IFU_STARE_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_IFU_STARE_JH_NIR";
-select execute(XSH_SCIRED_IFU_STARE_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_IFU_STARE_NIR";
 
+select execute(ACTION_SCIRED_IFU_STARE_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_TELL_IFU_STARE_UVB";
+select execute(ACTION_SCIRED_IFU_STARE_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_TELL_IFU_STARE_VIS";
+select execute(ACTION_SCIRED_IFU_STARE_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_IFU_STARE_JH_NIR";
+select execute(ACTION_SCIRED_IFU_STARE_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_IFU_STARE_NIR";
 
-select execute(XSH_SCIRED_IFU_OFFSET_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_IFU_OFFSET_UVB";
-select execute(XSH_SCIRED_IFU_OFFSET_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_IFU_OFFSET_VIS";
-select execute(XSH_SCIRED_IFU_OFFSET_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_IFU_OFFSET_NIR";
 
-select execute(XSH_SCIRED_SLIT_OFFSET_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_OFFSET_UVB";
-select execute(XSH_SCIRED_SLIT_OFFSET_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_OFFSET_VIS";
-select execute(XSH_SCIRED_SLIT_OFFSET_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_OFFSET_JH_NIR";
-select execute(XSH_SCIRED_SLIT_OFFSET_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_OFFSET_NIR";
+select execute(ACTION_SCIRED_IFU_OFFSET_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_IFU_OFFSET_UVB";
+select execute(ACTION_SCIRED_IFU_OFFSET_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_IFU_OFFSET_VIS";
+select execute(ACTION_SCIRED_IFU_OFFSET_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_IFU_OFFSET_NIR";
 
+select execute(ACTION_SCIRED_SLIT_OFFSET_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_OFFSET_UVB";
+select execute(ACTION_SCIRED_SLIT_OFFSET_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_OFFSET_VIS";
+select execute(ACTION_SCIRED_SLIT_OFFSET_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_OFFSET_JH_NIR";
+select execute(ACTION_SCIRED_SLIT_OFFSET_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_TELL_SLIT_OFFSET_NIR";
 
 
 
 // To be changed to RESPONSE RECIPE
-select execute(XSH_RESPONSE_SLIT_STARE_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_FLUX_SLIT_STARE_UVB";
-select execute(XSH_RESPONSE_SLIT_STARE_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_FLUX_SLIT_STARE_VIS";
-select execute(XSH_RESPONSE_SLIT_STARE_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_STARE_JH_NIR";
-select execute(XSH_RESPONSE_SLIT_STARE_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_STARE_NIR";
+select execute(ACTION_RESPONSE_SLIT_STARE_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_FLUX_SLIT_STARE_UVB";
+select execute(ACTION_RESPONSE_SLIT_STARE_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_FLUX_SLIT_STARE_VIS";
+select execute(ACTION_RESPONSE_SLIT_STARE_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_STARE_JH_NIR";
+select execute(ACTION_RESPONSE_SLIT_STARE_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_STARE_NIR";
 
-select execute(XSH_RESPONSE_SLIT_OFFSET_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_OFFSET_UVB";
-select execute(XSH_RESPONSE_SLIT_OFFSET_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_OFFSET_VIS";
-select execute(XSH_RESPONSE_SLIT_OFFSET_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_OFFSET_JH_NIR";
-select execute(XSH_RESPONSE_SLIT_OFFSET_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_OFFSET_NIR";
+select execute(ACTION_RESPONSE_SLIT_OFFSET_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_OFFSET_UVB";
+select execute(ACTION_RESPONSE_SLIT_OFFSET_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_OFFSET_VIS";
+select execute(ACTION_RESPONSE_SLIT_OFFSET_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_OFFSET_JH_NIR";
+select execute(ACTION_RESPONSE_SLIT_OFFSET_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_OFFSET_NIR";
 
-select execute(XSH_RESPONSE_SLIT_NOD_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_NOD_UVB";
-select execute(XSH_RESPONSE_SLIT_NOD_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_NOD_VIS";
-select execute(XSH_RESPONSE_SLIT_NOD_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_NOD_JH_NIR";
-select execute(XSH_RESPONSE_SLIT_NOD_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_NOD_NIR";
+select execute(ACTION_RESPONSE_SLIT_NOD_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_NOD_UVB";
+select execute(ACTION_RESPONSE_SLIT_NOD_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_NOD_VIS";
+select execute(ACTION_RESPONSE_SLIT_NOD_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_NOD_JH_NIR";
+select execute(ACTION_RESPONSE_SLIT_NOD_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_SLIT_NOD_NIR";
 
 
 
-select execute(XSH_SCIRED_IFU_STARE_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_FLUX_IFU_STARE_UVB";
-select execute(XSH_SCIRED_IFU_STARE_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_FLUX_IFU_STARE_VIS";
-select execute(XSH_SCIRED_IFU_STARE_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_IFU_STARE_JH_NIR";
-select execute(XSH_SCIRED_IFU_STARE_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_IFU_STARE_NIR";
+select execute(ACTION_SCIRED_IFU_STARE_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_FLUX_IFU_STARE_UVB";
+select execute(ACTION_SCIRED_IFU_STARE_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "STD_FLUX_IFU_STARE_VIS";
+select execute(ACTION_SCIRED_IFU_STARE_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_IFU_STARE_JH_NIR";
+select execute(ACTION_SCIRED_IFU_STARE_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_IFU_STARE_NIR";
 
 
-select execute(XSH_SCIRED_IFU_OFFSET_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_IFU_OFFSET_UVB";
-select execute(XSH_SCIRED_IFU_OFFSET_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_IFU_OFFSET_VIS";
-select execute(XSH_SCIRED_IFU_OFFSET_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_IFU_OFFSET_JH_NIR";
-select execute(XSH_SCIRED_IFU_OFFSET_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_IFU_OFFSET_NIR";
+select execute(ACTION_SCIRED_IFU_OFFSET_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_IFU_OFFSET_UVB";
+select execute(ACTION_SCIRED_IFU_OFFSET_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_IFU_OFFSET_VIS";
+select execute(ACTION_SCIRED_IFU_OFFSET_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_IFU_OFFSET_JH_NIR";
+select execute(ACTION_SCIRED_IFU_OFFSET_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "STD_FLUX_IFU_OFFSET_NIR";
 
 
 
@@ -2033,30 +2173,30 @@ select execute(XSH_SCIRED_IFU_OFFSET_NIR) from inputFiles where SIG.TEMPLATE ==
 
 
 
-select execute(XSH_SCIRED_SLIT_STARE_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "OBJECT_SLIT_STARE_UVB";
-select execute(XSH_SCIRED_SLIT_STARE_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "OBJECT_SLIT_STARE_VIS";
-select execute(XSH_SCIRED_SLIT_STARE_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_SLIT_STARE_JH_NIR";
-select execute(XSH_SCIRED_SLIT_STARE_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_SLIT_STARE_NIR";
+select execute(ACTION_SCIRED_SLIT_STARE_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "OBJECT_SLIT_STARE_UVB";
+select execute(ACTION_SCIRED_SLIT_STARE_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "OBJECT_SLIT_STARE_VIS";
+select execute(ACTION_SCIRED_SLIT_STARE_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_SLIT_STARE_JH_NIR";
+select execute(ACTION_SCIRED_SLIT_STARE_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_SLIT_STARE_NIR";
 
-select execute(XSH_SCIRED_IFU_STARE_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "OBJECT_IFU_STARE_UVB";
-select execute(XSH_SCIRED_IFU_STARE_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "OBJECT_IFU_STARE_VIS";
-select execute(XSH_SCIRED_IFU_STARE_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_IFU_STARE_JH_NIR";
-select execute(XSH_SCIRED_IFU_STARE_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_IFU_STARE_NIR";
+select execute(ACTION_SCIRED_IFU_STARE_UVB) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "OBJECT_IFU_STARE_UVB";
+select execute(ACTION_SCIRED_IFU_STARE_VIS) from inputFiles where SIG.FRAME == 1 and RAW.TYPE == "OBJECT_IFU_STARE_VIS";
+select execute(ACTION_SCIRED_IFU_STARE_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_IFU_STARE_JH_NIR";
+select execute(ACTION_SCIRED_IFU_STARE_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_IFU_STARE_NIR";
 
-select execute(XSH_SCIRED_SLIT_NOD_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_SLIT_NOD_UVB";
-select execute(XSH_SCIRED_SLIT_NOD_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_SLIT_NOD_VIS";
-select execute(XSH_SCIRED_SLIT_NOD_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_SLIT_NOD_JH_NIR";
-select execute(XSH_SCIRED_SLIT_NOD_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_SLIT_NOD_NIR";
+select execute(ACTION_SCIRED_SLIT_NOD_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_SLIT_NOD_UVB";
+select execute(ACTION_SCIRED_SLIT_NOD_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_SLIT_NOD_VIS";
+select execute(ACTION_SCIRED_SLIT_NOD_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_SLIT_NOD_JH_NIR";
+select execute(ACTION_SCIRED_SLIT_NOD_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "OBJECT_SLIT_NOD_NIR";
 
-select execute(XSH_SCIRED_SLIT_OFFSET_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_SLIT_OFFSET_UVB";
-select execute(XSH_SCIRED_SLIT_OFFSET_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_SLIT_OFFSET_VIS";
-select execute(XSH_SCIRED_SLIT_OFFSET_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_SLIT_OFFSET_JH_NIR";
-select execute(XSH_SCIRED_SLIT_OFFSET_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_SLIT_OFFSET_NIR";
+select execute(ACTION_SCIRED_SLIT_OFFSET_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_SLIT_OFFSET_UVB";
+select execute(ACTION_SCIRED_SLIT_OFFSET_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_SLIT_OFFSET_VIS";
+select execute(ACTION_SCIRED_SLIT_OFFSET_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_SLIT_OFFSET_JH_NIR";
+select execute(ACTION_SCIRED_SLIT_OFFSET_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_SLIT_OFFSET_NIR";
 
-select execute(XSH_SCIRED_IFU_OFFSET_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_IFU_OFFSET_UVB";
-select execute(XSH_SCIRED_IFU_OFFSET_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_IFU_OFFSET_VIS";
-select execute(XSH_SCIRED_IFU_OFFSET_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_IFU_OFFSET_JH_NIR";
-select execute(XSH_SCIRED_IFU_OFFSET_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_IFU_OFFSET_NIR";
+select execute(ACTION_SCIRED_IFU_OFFSET_UVB) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_IFU_OFFSET_UVB";
+select execute(ACTION_SCIRED_IFU_OFFSET_VIS) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_IFU_OFFSET_VIS";
+select execute(ACTION_SCIRED_IFU_OFFSET_JH_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_IFU_OFFSET_JH_NIR";
+select execute(ACTION_SCIRED_IFU_OFFSET_NIR) from inputFiles where SIG.TEMPLATE == 1 and RAW.TYPE == "SCIENCE_IFU_OFFSET_NIR";
 
 
 
@@ -2066,7 +2206,7 @@ select execute(XSH_SCIRED_IFU_OFFSET_NIR) from inputFiles where SIG.TEMPLATE ==
 // ACTIONS
 //===========================================================================
 
-action XSH_MBIAS_UVB
+action ACTION_MBIAS_UVB
 {
 minRet = 0; maxRet = 1;
 select file as BP_MAP_RP_UVB from calibFiles where PRO.CATG=="BP_MAP_RP_UVB" and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
@@ -2079,7 +2219,7 @@ recipe xsh_mbias;
 }
 
 
-action XSH_MBIAS_VIS
+action ACTION_MBIAS_VIS
 {
 
 minRet = 0; maxRet = 1;
@@ -2093,7 +2233,7 @@ recipe xsh_mbias;
 
 
 
-action XSH_LINGAIN_UVB
+action ACTION_LINGAIN_UVB
 {
 
 recipe detmon_opt_lg
@@ -2108,7 +2248,7 @@ recipe detmon_opt_lg
 
 }
 
-action XSH_LINGAIN_VIS
+action ACTION_LINGAIN_VIS
 {
 
 recipe detmon_opt_lg
@@ -2123,7 +2263,7 @@ recipe detmon_opt_lg
 
 }
 
-action XSH_LINGAIN_NIR
+action ACTION_LINGAIN_NIR
 {
 
 recipe detmon_ir_lg
@@ -2140,7 +2280,7 @@ recipe detmon_ir_lg
 }
 
 //===========================================================================
-action XSH_MDARK_UVB
+action ACTION_MDARK_UVB
 {
 minRet = 1; maxRet = 1;
 select file as MASTER_BIAS_UVB from calibFiles where DO.CATG == "MASTER_BIAS_UVB"
@@ -2159,7 +2299,7 @@ select file as DRS_MDARK_UVB from calibFiles where DO.CATG == "DRS_MDARK_UVB";
 recipe xsh_mdark;
 }
 
-action XSH_MDARK_VIS
+action ACTION_MDARK_VIS
 {
 minRet = 1; maxRet = 1;
 select file as MASTER_BIAS_VIS from calibFiles where DO.CATG == "MASTER_BIAS_VIS"
@@ -2178,7 +2318,7 @@ select file as DRS_MDARK_VIS from calibFiles where DO.CATG == "DRS_MDARK_VIS";
 recipe xsh_mdark;
 }
 
-action XSH_MDARK_NIR
+action ACTION_MDARK_NIR
 {
 minRet = 0; maxRet = 1;
 select file as BP_MAP_RP_NIR from calibFiles where DO.CATG == "BP_MAP_RP_NIR";
@@ -2194,7 +2334,7 @@ recipe xsh_mdark;
 
 //===========================================================================
 
-action XSH_PREDICT_UVB
+action ACTION_PREDICT_UVB
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_UVB from calibFiles where DO.CATG == "SPECTRAL_FORMAT_TAB_UVB";
@@ -2236,7 +2376,7 @@ recipe xsh_predict
 
 }
 
-action XSH_PREDICT_VIS
+action ACTION_PREDICT_VIS
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_VIS from calibFiles where DO.CATG == "SPECTRAL_FORMAT_TAB_VIS";
@@ -2276,7 +2416,7 @@ recipe xsh_predict
 
 }
 
-action XSH_PREDICT_NIR
+action ACTION_PREDICT_NIR
 {
 
 minRet = 1; maxRet = 1;
@@ -2312,7 +2452,7 @@ recipe xsh_predict
 
 //===========================================================================
 
-action XSH_ORDERPOS_UVB
+action ACTION_ORDERPOS_UVB
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_UVB from calibFiles where DO.CATG == "SPECTRAL_FORMAT_TAB_UVB";
@@ -2331,7 +2471,7 @@ select file as BP_MAP_RP_UVB from calibFiles where DO.CATG == "BP_MAP_RP_UVB"
 recipe xsh_orderpos;
 }
 
-action XSH_ORDERPOS_VIS
+action ACTION_ORDERPOS_VIS
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_VIS from calibFiles where DO.CATG == "SPECTRAL_FORMAT_TAB_VIS";
@@ -2351,7 +2491,7 @@ select file as BP_MAP_RP_VIS from calibFiles where DO.CATG == "BP_MAP_RP_VIS"
 recipe xsh_orderpos;
 }
 
-action XSH_ORDERPOS_NIR
+action ACTION_ORDERPOS_NIR
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_NIR from calibFiles where DO.CATG == "SPECTRAL_FORMAT_TAB_NIR";
@@ -2369,7 +2509,7 @@ recipe xsh_orderpos;
 
 //===========================================================================
 
-action XSH_MFLAT_SLIT_UVB
+action ACTION_MFLAT_SLIT_UVB
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_UVB from calibFiles where DO.CATG == "SPECTRAL_FORMAT_TAB_UVB";
@@ -2393,7 +2533,7 @@ recipe xsh_mflat
 
 }
 
-action XSH_MFLAT_SLIT_VIS
+action ACTION_MFLAT_SLIT_VIS
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_VIS from calibFiles where DO.CATG == "SPECTRAL_FORMAT_TAB_VIS";
@@ -2416,7 +2556,7 @@ recipe xsh_mflat
 
 }
 
-action XSH_MFLAT_SLIT_NIR
+action ACTION_MFLAT_SLIT_NIR
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_NIR from calibFiles where DO.CATG == "SPECTRAL_FORMAT_TAB_NIR";
@@ -2436,7 +2576,7 @@ recipe xsh_mflat
 }
 
 
-action XSH_MFLAT_SLIT_JH_NIR
+action ACTION_MFLAT_SLIT_JH_NIR
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_JH_NIR from calibFiles where DO.CATG =="SPECTRAL_FORMAT_TAB_JH_NIR" and RAW.TYPE == "SPECTRAL_FORMAT_TAB_JH_NIR" and INS.OPTI5.NAME == "JH";
@@ -2459,7 +2599,7 @@ recipe xsh_mflat
 
 
 
-action XSH_MFLAT_IFU_UVB
+action ACTION_MFLAT_IFU_UVB
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_UVB from calibFiles where DO.CATG == "SPECTRAL_FORMAT_TAB_UVB";
@@ -2482,7 +2622,7 @@ recipe xsh_mflat
 
 }
 
-action XSH_MFLAT_IFU_VIS
+action ACTION_MFLAT_IFU_VIS
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_VIS from calibFiles where DO.CATG == "SPECTRAL_FORMAT_TAB_VIS";
@@ -2502,7 +2642,7 @@ recipe xsh_mflat;
 
 }
 
-action XSH_MFLAT_IFU_NIR
+action ACTION_MFLAT_IFU_NIR
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_NIR from calibFiles where DO.CATG == "SPECTRAL_FORMAT_TAB_NIR";
@@ -2520,7 +2660,7 @@ recipe xsh_mflat;
 
 //===========================================================================
 
-action XSH_2DMAP_UVB
+action ACTION_2DMAP_UVB
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_UVB from calibFiles where DO.CATG == "SPECTRAL_FORMAT_TAB_UVB";
@@ -2573,7 +2713,7 @@ recipe xsh_2dmap
 
 }
 
-action XSH_2DMAP_VIS
+action ACTION_2DMAP_VIS
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_VIS from calibFiles where DO.CATG == "SPECTRAL_FORMAT_TAB_VIS";
@@ -2625,7 +2765,7 @@ recipe xsh_2dmap
 
 }
 
-action XSH_2DMAP_NIR
+action ACTION_2DMAP_NIR
 {
 
 minRet = 1; maxRet = 1;
@@ -2635,8 +2775,7 @@ select file as SPECTRAL_FORMAT_TAB_NIR from calibFiles where DO.CATG == "SPECTRA
 //select file as MASTER_FLAT_SLIT_NIR from calibFiles where DO.CATG =="MASTER_FLAT_SLIT_NIR";
 
 minRet = 1; maxRet = 1;
-select file as ORDER_TAB_EDGES_SLIT_NIR from calibFiles where DO.CATG == "ORDER_TAB_EDGES_SLIT_NIR";
-
+select file as ORDER_TAB_EDGES_SLIT_NIR from calibFiles where PRO.CATG=="ORDER_TAB_EDGES_SLIT_NIR" and inputFile.DET.CHIP.ID==DET.CHIP.ID and INS.OPTI5.NAME!="0.9x11JH" and INS.OPTI5.NAME!="0.6x11JH";
 
 minRet = 1; maxRet = 1;
 select file as ARC_LINE_LIST_NIR from calibFiles where DO.CATG == "ARC_LINE_LIST_NIR";
@@ -2672,7 +2811,7 @@ recipe xsh_2dmap
 
 //===========================================================================
 
-action XSH_WAVECAL_SLIT_UVB
+action ACTION_WAVECAL_SLIT_UVB
 {
 
 minRet = 1; maxRet = 1;
@@ -2715,7 +2854,7 @@ recipe xsh_wavecal;
 
 }
 
-action XSH_WAVECAL_SLIT_VIS
+action ACTION_WAVECAL_SLIT_VIS
 {
 
 minRet = 1; maxRet = 1;
@@ -2754,7 +2893,7 @@ recipe xsh_wavecal;
 
 }
 
-action XSH_WAVECAL_SLIT_NIR
+action ACTION_WAVECAL_SLIT_NIR
 {
 
 minRet = 1; maxRet = 1;
@@ -2766,7 +2905,7 @@ select file as MASTER_FLAT_SLIT_NIR from calibFiles where DO.CATG == "MASTER_FLA
    and inputFile.INS.OPTI5.NAME==INS.OPTI5.NAME;
 
 minRet = 1; maxRet = 1;
-select file as ORDER_TAB_EDGES_SLIT_NIR from calibFiles where DO.CATG == "ORDER_TAB_EDGES_SLIT_NIR";
+select file as ORDER_TAB_EDGES_SLIT_NIR from calibFiles where PRO.CATG=="ORDER_TAB_EDGES_SLIT_NIR" and inputFile.DET.CHIP.ID==DET.CHIP.ID and INS.OPTI5.NAME!="0.9x11JH" and INS.OPTI5.NAME!="0.6x11JH";
 
 
 minRet = 1; maxRet = 1;
@@ -2793,7 +2932,7 @@ recipe xsh_wavecal;
 }
 
 
-action XSH_WAVECAL_SLIT_JH_NIR
+action ACTION_WAVECAL_SLIT_JH_NIR
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_JH_NIR from calibFiles where DO.CATG =="SPECTRAL_FORMAT_TAB_JH_NIR" and RAW.TYPE == "SPECTRAL_FORMAT_TAB_JH_NIR" and INS.OPTI5.NAME == "JH";
@@ -2804,7 +2943,7 @@ select file as MASTER_FLAT_SLIT_NIR from calibFiles where DO.CATG == "MASTER_FLA
    and inputFile.INS.OPTI5.NAME==INS.OPTI5.NAME;
 
 minRet = 1; maxRet = 1;
-select file as ORDER_TAB_EDGES_SLIT_NIR from calibFiles where DO.CATG == "ORDER_TAB_EDGES_SLIT_NIR";
+select file as ORDER_TAB_EDGES_SLIT_NIR from calibFiles where PRO.CATG=="ORDER_TAB_EDGES_SLIT_NIR" and inputFile.DET.CHIP.ID==DET.CHIP.ID and INS.OPTI5.NAME!="0.9x11JH" and INS.OPTI5.NAME!="0.6x11JH";
 
 
 minRet = 1; maxRet = 1;
@@ -2832,7 +2971,7 @@ recipe xsh_wavecal;
 
 //===========================================================================
 
-action XSH_WAVECAL_IFU_UVB
+action ACTION_WAVECAL_IFU_UVB
 {
 
 minRet = 1; maxRet = 1;
@@ -2874,7 +3013,7 @@ recipe xsh_wavecal;
 
 }
 
-action XSH_WAVECAL_IFU_VIS
+action ACTION_WAVECAL_IFU_VIS
 {
 
 minRet = 1; maxRet = 1;
@@ -2919,7 +3058,7 @@ recipe xsh_wavecal
 
 
 
-action XSH_WAVECAL_IFU_NIR
+action ACTION_WAVECAL_IFU_NIR
 {
 
 minRet = 1; maxRet = 1;
@@ -2930,7 +3069,8 @@ select file as MASTER_FLAT_IFU_NIR from calibFiles where DO.CATG == "MASTER_FLAT
    and inputFile.INS.OPTI5.NAME==INS.OPTI5.NAME;
 
 minRet = 1; maxRet = 1;
-select file as ORDER_TAB_EDGES_IFU_NIR from calibFiles where DO.CATG == "ORDER_TAB_EDGES_IFU_NIR";
+select file as ORDER_TAB_EDGES_IFU_NIR from calibFiles where PRO.CATG=="ORDER_TAB_EDGES_IFU_NIR" and inputFile.DET.CHIP.ID==DET.CHIP.ID and INS.OPTI5.NAME!="0.9x11JH" and INS.OPTI5.NAME!="0.6x11JH";
+
 
 
 minRet = 1; maxRet = 1;
@@ -2958,6 +3098,90 @@ recipe xsh_wavecal;
 
 
 //===========================================================================
+action ACTION_FLEX_SLIT_UVB
+{
+minRet = 0; maxRet = 1;
+select file as BP_MAP_RP_UVB from calibFiles where PRO.CATG=="BP_MAP_RP_UVB" and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
+
+minRet = 0; maxRet = 1;
+select file as BP_MAP_NL_UVB from calibFiles where PRO.CATG=="BP_MAP_NL_UVB" and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.CHIP1.ID==DET.CHIP1.ID;
+
+minRet = 1; maxRet = 1;
+select file as MASTER_BIAS_UVB from calibFiles where PRO.CATG=="MASTER_BIAS_UVB" and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.OUT1.GAIN==DET.OUT1.GAIN and inputFile.DET.CHIP1.ID==DET.CHIP1.ID;
+
+minRet = 1; maxRet = 1;
+select file as ORDER_TAB_EDGES_SLIT_UVB from calibFiles where PRO.CATG=="ORDER_TAB_EDGES_SLIT_UVB" and inputFile.DET.CHIP1.ID==DET.CHIP1.ID;
+
+minRet = 1; maxRet = 1;
+select file as XSH_MOD_CFG_OPT_2D_UVB from calibFiles where PRO.CATG=="XSH_MOD_CFG_OPT_2D_UVB" and (MJD-OBS < inputFile.MJD-OBS or MJD-OBS >= inputFile.MJD-OBS);
+
+minRet = 1; maxRet = 1;
+select file as ARC_LINE_LIST_AFC_UVB from calibFiles where PRO.CATG=="ARC_LINE_LIST_AFC_UVB" and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
+
+minRet = 1; maxRet = 1;
+select file as SPECTRAL_FORMAT_TAB_UVB from calibFiles where PRO.CATG=="SPECTRAL_FORMAT_TAB_UVB" and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
+
+  recipe xsh_flexcomp;
+  product XSH_MOD_CFG_OPT_AFC_UVB { PRO.CATG="XSH_MOD_CFG_OPT_AFC_UVB"; PRO.EXT="0000.fits";}
+  product ORDER_TAB_AFC_SLIT_UVB { PRO.CATG="ORDER_TAB_AFC_SLIT_UVB"; PRO.EXT="0002.fits";}
+  product DISP_TAB_AFC_UVB { PRO.CATG="DISP_TAB_AFC_UVB"; PRO.EXT="0003.fits";}
+}
+
+action ACTION_FLEX_SLIT_VIS
+{
+minRet = 0; maxRet = 1;
+select file as BP_MAP_RP_VIS from calibFiles where PRO.CATG=="BP_MAP_RP_VIS" and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
+
+minRet = 0; maxRet = 1;
+select file as BP_MAP_NL_VIS from calibFiles where PRO.CATG=="BP_MAP_NL_VIS" and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.CHIP1.ID==DET.CHIP1.ID;
+
+minRet = 1; maxRet = 1;
+select file as MASTER_BIAS_VIS from calibFiles where PRO.CATG=="MASTER_BIAS_VIS" and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINX and inputFile.DET.OUT1.GAIN==DET.OUT1.GAIN and inputFile.DET.CHIP1.ID==DET.CHIP1.ID;
+
+minRet = 1; maxRet = 1;
+select file as ORDER_TAB_EDGES_SLIT_VIS from calibFiles where PRO.CATG=="ORDER_TAB_EDGES_SLIT_VIS" and inputFile.DET.CHIP1.ID==DET.CHIP1.ID;
+
+minRet = 1; maxRet = 1;
+select file as XSH_MOD_CFG_OPT_2D_VIS from calibFiles where PRO.CATG=="XSH_MOD_CFG_OPT_2D_VIS" and (MJD-OBS < inputFile.MJD-OBS or MJD-OBS >= inputFile.MJD-OBS);
+
+minRet = 1; maxRet = 1;
+select file as ARC_LINE_LIST_AFC_VIS from calibFiles where PRO.CATG=="ARC_LINE_LIST_AFC_VIS" and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
+
+minRet = 1; maxRet = 1;
+select file as SPECTRAL_FORMAT_TAB_VIS from calibFiles where PRO.CATG=="SPECTRAL_FORMAT_TAB_VIS" and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
+
+  recipe xsh_flexcomp;
+  product XSH_MOD_CFG_OPT_AFC_VIS { PRO.CATG="XSH_MOD_CFG_OPT_AFC_VIS"; PRO.EXT="0000.fits";}
+  product ORDER_TAB_AFC_SLIT_VIS { PRO.CATG="ORDER_TAB_AFC_SLIT_VIS"; PRO.EXT="0002.fits";}
+  product DISP_TAB_AFC_VIS { PRO.CATG="DISP_TAB_AFC_VIS"; PRO.EXT="0003.fits";}
+}
+
+action ACTION_FLEX_SLIT_NIR
+{
+minRet = 0; maxRet = 1;
+select file as BP_MAP_RP_NIR from calibFiles where PRO.CATG=="BP_MAP_RP_NIR" and inputFile.DET.CHIP.ID==DET.CHIP.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
+
+minRet = 0; maxRet = 1;
+select file as BP_MAP_NL_NIR from calibFiles where PRO.CATG=="BP_MAP_NL_NIR" and inputFile.DET.CHIP.ID==DET.CHIP.ID;
+
+minRet = 1; maxRet = 1;
+select file as ORDER_TAB_EDGES_SLIT_NIR from calibFiles where PRO.CATG=="ORDER_TAB_EDGES_SLIT_NIR" and inputFile.DET.CHIP.ID==DET.CHIP.ID and INS.OPTI5.NAME != "0.9x11JH" and INS.OPTI5.NAME != "0.6x11JH";
+
+minRet = 1; maxRet = 1;
+select file as XSH_MOD_CFG_OPT_2D_NIR from calibFiles where PRO.CATG=="XSH_MOD_CFG_OPT_2D_NIR" and (MJD-OBS < inputFile.MJD-OBS or MJD-OBS >= inputFile.MJD-OBS);
+
+minRet = 1; maxRet = 1;
+select file as ARC_LINE_LIST_AFC_NIR from calibFiles where PRO.CATG=="ARC_LINE_LIST_AFC_NIR" and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
+
+minRet = 1; maxRet = 1;
+select file as SPECTRAL_FORMAT_TAB_NIR from calibFiles where PRO.CATG=="SPECTRAL_FORMAT_TAB_NIR" and (INS.OPTI5.NAME is undefined or INS.OPTI5.NAME like "%x11") and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
+
+recipe xsh_flexcomp;
+  product XSH_MOD_CFG_OPT_AFC_NIR { PRO.CATG="XSH_MOD_CFG_OPT_AFC_NIR"; PRO.EXT="0000.fits";}
+  product ORDER_TAB_AFC_SLIT_NIR { PRO.CATG="ORDER_TAB_AFC_SLIT_NIR"; PRO.EXT="0002.fits";}
+  product DISP_TAB_AFC_NIR { PRO.CATG="DISP_TAB_AFC_NIR"; PRO.EXT="0003.fits";}
+
+}
 
 
 //===========================================================================
@@ -3072,7 +3296,7 @@ select file as SPECTRAL_FORMAT_TAB_NIR from calibFiles where PRO.CATG=="SPECTRAL
 
 //===========================================================================
 
-action XSH_RESPONSE_SLIT_NOD_UVB
+action ACTION_RESPONSE_SLIT_NOD_UVB
 {
 
 minRet = 1; maxRet = 1;
@@ -3137,7 +3361,7 @@ recipe xsh_respon_slit_nod
 
 
 
-action XSH_RESPONSE_SLIT_NOD_VIS
+action ACTION_RESPONSE_SLIT_NOD_VIS
 {
 
 minRet = 1; maxRet = 1;
@@ -3200,7 +3424,7 @@ recipe xsh_respon_slit_nod
 }
 
 
-action XSH_RESPONSE_SLIT_NOD_NIR
+action ACTION_RESPONSE_SLIT_NOD_NIR
 {
 
 minRet = 1; maxRet = 1;
@@ -3256,7 +3480,7 @@ recipe xsh_respon_slit_nod
 
 
 
-action XSH_RESPONSE_SLIT_NOD_JH_NIR
+action ACTION_RESPONSE_SLIT_NOD_JH_NIR
 {
 
 minRet = 1; maxRet = 1;
@@ -3316,7 +3540,7 @@ recipe xsh_respon_slit_nod
 //===========================================================================
 
 
-action XSH_RESPONSE_SLIT_OFFSET_UVB
+action ACTION_RESPONSE_SLIT_OFFSET_UVB
 {
 
 minRet = 1; maxRet = 1;
@@ -3378,7 +3602,7 @@ recipe xsh_respon_slit_offset
   "--rectify-bin-slit=0.16";}
 }
 
-action XSH_RESPONSE_SLIT_OFFSET_VIS
+action ACTION_RESPONSE_SLIT_OFFSET_VIS
 {
 
 minRet = 1; maxRet = 1;
@@ -3442,7 +3666,7 @@ recipe xsh_respon_slit_offset
 
 
 
-action XSH_RESPONSE_SLIT_OFFSET_NIR
+action ACTION_RESPONSE_SLIT_OFFSET_NIR
 {
 
 minRet = 1; maxRet = 1;
@@ -3503,7 +3727,7 @@ recipe xsh_respon_slit_offset
 
 
 
-action XSH_RESPONSE_SLIT_OFFSET_JH_NIR
+action ACTION_RESPONSE_SLIT_OFFSET_JH_NIR
 {
 
 minRet = 1; maxRet = 1;
@@ -3566,7 +3790,7 @@ recipe xsh_respon_slit_offset
 
 //===========================================================================
 
-action XSH_RESPONSE_SLIT_STARE_UVB
+action ACTION_RESPONSE_SLIT_STARE_UVB
 {
 
 minRet = 1; maxRet = 1;
@@ -3633,7 +3857,7 @@ recipe xsh_respon_slit_stare
 }
 
 
-action XSH_RESPONSE_SLIT_STARE_VIS
+action ACTION_RESPONSE_SLIT_STARE_VIS
 {
 
 minRet = 1; maxRet = 1;
@@ -3704,7 +3928,7 @@ recipe xsh_respon_slit_stare
 
 //===========================================================================
 
-action XSH_SCIRED_SLIT_NOD_UVB
+action ACTION_SCIRED_SLIT_NOD_UVB
 {
 
 minRet = 1; maxRet = 1;
@@ -3757,7 +3981,7 @@ select file as RESP_FIT_POINTS_CAT_UVB from calibFiles where
 PRO.CATG=="RESP_FIT_POINTS_CAT_UVB" and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
 
 minRet = 0; maxRet = 1;
-select file as MRESPONSE_MERGE1D_SLIT_UVB from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_UVB";
+select file as MRESPONSE_MERGE1D_SLIT_UVB from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_UVB" and MDJ-OBS < inputFile.MJD-OBS;
 
 
 recipe xsh_scired_slit_nod
@@ -3770,7 +3994,7 @@ recipe xsh_scired_slit_nod
 
 
 
-action XSH_SCIRED_SLIT_NOD_VIS
+action ACTION_SCIRED_SLIT_NOD_VIS
 {
 
 minRet = 1; maxRet = 1;
@@ -3825,7 +4049,7 @@ minRet = 0; maxRet = 1;
 select file as RESP_FIT_POINTS_CAT_VIS from calibFiles where PRO.CATG=="RESP_FIT_POINTS_CAT_VIS" and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
 
 minRet = 0; maxRet = 1;
-select file as MRESPONSE_MERGE1D_SLIT_VIS from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_VIS";
+select file as MRESPONSE_MERGE1D_SLIT_VIS from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_VIS" and MDJ-OBS < inputFile.MJD-OBS;
 
 recipe xsh_scired_slit_nod
 {
@@ -3836,7 +4060,7 @@ recipe xsh_scired_slit_nod
 
 
 
-action XSH_SCIRED_SLIT_NOD_NIR
+action ACTION_SCIRED_SLIT_NOD_NIR
 {
 
 minRet = 1; maxRet = 1;
@@ -3883,7 +4107,7 @@ minRet = 0; maxRet = 1;
 select file as RESP_FIT_POINTS_CAT_NIR from calibFiles where PRO.CATG=="RESP_FIT_POINTS_CAT_NIR" and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
 
 minRet = 0; maxRet = 1;
-select file as MRESPONSE_MERGE1D_SLIT_NIR from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_NIR";
+select file as MRESPONSE_MERGE1D_SLIT_NIR from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_NIR" and MDJ-OBS < inputFile.MJD-OBS;
 
 
 recipe xsh_scired_slit_nod
@@ -3896,7 +4120,7 @@ recipe xsh_scired_slit_nod
 
 
 
-action XSH_SCIRED_SLIT_NOD_JH_NIR
+action ACTION_SCIRED_SLIT_NOD_JH_NIR
 {
 
 minRet = 1; maxRet = 1;
@@ -3943,7 +4167,7 @@ minRet = 0; maxRet = 1;
 select file as RESP_FIT_POINTS_CAT_NIR from calibFiles where PRO.CATG=="RESP_FIT_POINTS_CAT_NIR" and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
 
 minRet = 0; maxRet = 1;
-select file as MRESPONSE_MERGE1D_SLIT_NIR from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_NIR";
+select file as MRESPONSE_MERGE1D_SLIT_NIR from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_NIR" and MDJ-OBS < inputFile.MJD-OBS;
 
 
 recipe xsh_scired_slit_nod
@@ -3960,7 +4184,7 @@ recipe xsh_scired_slit_nod
 
 //===========================================================================
 
-action XSH_RESPONSE_SLIT_STARE_NIR
+action ACTION_RESPONSE_SLIT_STARE_NIR
 {
 
 minRet = 1; maxRet = 1;
@@ -4021,7 +4245,7 @@ recipe xsh_respon_slit_stare
 }
 
 
-action XSH_RESPONSE_SLIT_STARE_JH_NIR
+action ACTION_RESPONSE_SLIT_STARE_JH_NIR
 {
 
 minRet = 1; maxRet = 1;
@@ -4087,7 +4311,7 @@ recipe xsh_respon_slit_stare
 
 //===========================================================================
 
-action XSH_SCIRED_SLIT_OFFSET_UVB
+action ACTION_SCIRED_SLIT_OFFSET_UVB
 {
 
 minRet = 1; maxRet = 1;
@@ -4144,7 +4368,7 @@ select file as RESP_FIT_POINTS_CAT_UVB from calibFiles where
 PRO.CATG=="RESP_FIT_POINTS_CAT_UVB" and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
 
 minRet = 0; maxRet = 1;
-select file as MRESPONSE_MERGE1D_SLIT_UVB from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_UVB";
+select file as MRESPONSE_MERGE1D_SLIT_UVB from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_UVB" and MDJ-OBS < inputFile.MJD-OBS;
 
 
 recipe xsh_scired_slit_offset
@@ -4156,7 +4380,7 @@ recipe xsh_scired_slit_offset
 
 
 
-action XSH_SCIRED_SLIT_OFFSET_VIS
+action ACTION_SCIRED_SLIT_OFFSET_VIS
 {
 
 minRet = 1; maxRet = 1;
@@ -4209,7 +4433,7 @@ minRet = 0; maxRet = 1;
 select file as SKY_LINE_LIST_VIS from calibFiles where DO.CATG == "SKY_LINE_LIST_VIS";
 
 minRet = 0; maxRet = 1;
-select file as MRESPONSE_MERGE1D_SLIT_VIS from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_VIS";
+select file as MRESPONSE_MERGE1D_SLIT_VIS from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_VIS" and MDJ-OBS < inputFile.MJD-OBS;
 
 
 recipe xsh_scired_slit_offset
@@ -4221,7 +4445,7 @@ recipe xsh_scired_slit_offset
 
 
 
-action XSH_SCIRED_SLIT_OFFSET_NIR
+action ACTION_SCIRED_SLIT_OFFSET_NIR
 {
 
 minRet = 1; maxRet = 1;
@@ -4268,7 +4492,7 @@ minRet = 0; maxRet = 1;
 select file as SKY_LINE_LIST_NIR from calibFiles where DO.CATG == "SKY_LINE_LIST_NIR";
 
 minRet = 0; maxRet = 1;
-select file as MRESPONSE_MERGE1D_SLIT_NIR from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_NIR";
+select file as MRESPONSE_MERGE1D_SLIT_NIR from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_NIR" and MDJ-OBS < inputFile.MJD-OBS;
 
 
 recipe xsh_scired_slit_offset
@@ -4280,7 +4504,7 @@ recipe xsh_scired_slit_offset
 
 
 
-action XSH_SCIRED_SLIT_OFFSET_JH_NIR
+action ACTION_SCIRED_SLIT_OFFSET_JH_NIR
 {
 
 minRet = 1; maxRet = 1;
@@ -4328,7 +4552,7 @@ select file as SKY_LINE_LIST_NIR from calibFiles where DO.CATG == "SKY_LINE_LIST
 
 
 minRet = 0; maxRet = 1;
-select file as MRESPONSE_MERGE1D_SLIT_NIR from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_NIR";
+select file as MRESPONSE_MERGE1D_SLIT_NIR from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_NIR" and MDJ-OBS < inputFile.MJD-OBS;
 
 
 recipe xsh_scired_slit_offset
@@ -4348,7 +4572,7 @@ recipe xsh_scired_slit_offset
 
 
 
-action XSH_SCIRED_SLIT_STARE_UVB
+action ACTION_SCIRED_SLIT_STARE_UVB
 {
 
 minRet = 1; maxRet = 1;
@@ -4398,7 +4622,7 @@ minRet = 0; maxRet = 1;
 select file as SKY_LINE_LIST_UVB from calibFiles where DO.CATG == "SKY_LINE_LIST_UVB";
 
 minRet = 0; maxRet = 1;
-select file as MRESPONSE_MERGE1D_SLIT_UVB from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_UVB";
+select file as MRESPONSE_MERGE1D_SLIT_UVB from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_UVB" and MDJ-OBS < inputFile.MJD-OBS;
 
 
 recipe xsh_scired_slit_stare
@@ -4412,7 +4636,7 @@ recipe xsh_scired_slit_stare
   "--sky-slit-edges-mask=1.5";}
 }
 
-action XSH_SCIRED_SLIT_STARE_VIS
+action ACTION_SCIRED_SLIT_STARE_VIS
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_VIS from calibFiles where DO.CATG == "SPECTRAL_FORMAT_TAB_VIS";
@@ -4460,7 +4684,7 @@ minRet = 0; maxRet = 1;
 select file as SKY_LINE_LIST_VIS from calibFiles where DO.CATG == "SKY_LINE_LIST_VIS";
 
 minRet = 0; maxRet = 1;
-select file as MRESPONSE_MERGE1D_SLIT_VIS from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_VIS";
+select file as MRESPONSE_MERGE1D_SLIT_VIS from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_VIS" and MDJ-OBS < inputFile.MJD-OBS;
 
 
 recipe xsh_scired_slit_stare
@@ -4473,7 +4697,7 @@ recipe xsh_scired_slit_stare
   "--sky-slit-edges-mask=1.5";}
 }
 
-action XSH_SCIRED_SLIT_STARE_NIR
+action ACTION_SCIRED_SLIT_STARE_NIR
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_NIR from calibFiles where DO.CATG == "SPECTRAL_FORMAT_TAB_NIR";
@@ -4515,7 +4739,7 @@ select file as SKY_LINE_LIST_NIR from calibFiles where DO.CATG == "SKY_LINE_LIST
 
 
 minRet = 0; maxRet = 1;
-select file as MRESPONSE_MERGE1D_SLIT_NIR from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_NIR";
+select file as MRESPONSE_MERGE1D_SLIT_NIR from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_NIR" and MDJ-OBS < inputFile.MJD-OBS;
 
 
 recipe xsh_scired_slit_stare
@@ -4532,7 +4756,7 @@ recipe xsh_scired_slit_stare
 
 
 
-action XSH_SCIRED_SLIT_STARE_JH_NIR
+action ACTION_SCIRED_SLIT_STARE_JH_NIR
 {
 minRet = 1; maxRet = 1;
 select file as SPECTRAL_FORMAT_TAB_JH_NIR from calibFiles where DO.CATG =="SPECTRAL_FORMAT_TAB_JH_NIR" and RAW.TYPE == "SPECTRAL_FORMAT_TAB_JH_NIR" and INS.OPTI5.NAME == "JH";
@@ -4573,7 +4797,7 @@ minRet = 0; maxRet = 1;
 select file as SKY_LINE_LIST_NIR from calibFiles where DO.CATG == "SKY_LINE_LIST_NIR";
 
 minRet = 0; maxRet = 1;
-select file as MRESPONSE_MERGE1D_SLIT_NIR from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_NIR";
+select file as MRESPONSE_MERGE1D_SLIT_NIR from calibFiles where DO.CATG == "MRESPONSE_MERGE1D_SLIT_NIR" and MDJ-OBS < inputFile.MJD-OBS;
 
 
 recipe xsh_scired_slit_stare
@@ -4591,7 +4815,7 @@ recipe xsh_scired_slit_stare
 
 //===========================================================================
 
-action XSH_SCIRED_IFU_STARE_UVB
+action ACTION_SCIRED_IFU_STARE_UVB
 {
 minRet = 0; maxRet = 1;
 select file as BP_MAP_RP_UVB from calibFiles where PRO.CATG=="BP_MAP_RP_UVB" and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
@@ -4623,7 +4847,7 @@ select file as SPECTRAL_FORMAT_TAB_UVB from calibFiles where PRO.CATG=="SPECTRAL
   recipe xsh_scired_ifu_stare;
 }
 
-action XSH_SCIRED_IFU_STARE_VIS
+action ACTION_SCIRED_IFU_STARE_VIS
 {
 minRet = 0; maxRet = 1;
 select file as BP_MAP_RP_VIS from calibFiles where PRO.CATG=="BP_MAP_RP_VIS" and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
@@ -4655,7 +4879,7 @@ select file as SPECTRAL_FORMAT_TAB_VIS from calibFiles where PRO.CATG=="SPECTRAL
  recipe xsh_scired_ifu_stare;
 }
 
-action XSH_SCIRED_IFU_STARE_NIR
+action ACTION_SCIRED_IFU_STARE_NIR
 {
 minRet = 0; maxRet = 1;
 select file as BP_MAP_RP_NIR from calibFiles where PRO.CATG=="BP_MAP_RP_NIR" and inputFile.DET.CHIP.ID==DET.CHIP.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
@@ -4685,7 +4909,7 @@ select file as SPECTRAL_FORMAT_TAB_NIR from calibFiles where PRO.CATG=="SPECTRAL
 
 
 
-action XSH_SCIRED_IFU_STARE_JH_NIR
+action ACTION_SCIRED_IFU_STARE_JH_NIR
 {
 minRet = 0; maxRet = 1;
 select file as BP_MAP_RP_NIR from calibFiles where PRO.CATG=="BP_MAP_RP_NIR" and inputFile.DET.CHIP.ID==DET.CHIP.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
@@ -4719,7 +4943,7 @@ select file as SPECTRAL_FORMAT_TAB_JH_NIR from calibFiles where PRO.CATG=="SPECT
 
 
 
-action XSH_SCIRED_IFU_OFFSET_UVB
+action ACTION_SCIRED_IFU_OFFSET_UVB
 {
 minRet = 0; maxRet = 1;
 select file as BP_MAP_RP_UVB from calibFiles where PRO.CATG=="BP_MAP_RP_UVB" and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
@@ -4749,7 +4973,7 @@ select file as SPECTRAL_FORMAT_TAB_UVB from calibFiles where PRO.CATG=="SPECTRAL
 recipe xsh_scired_ifu_offset;
 }
 
-action XSH_SCIRED_IFU_OFFSET_VIS
+action ACTION_SCIRED_IFU_OFFSET_VIS
 {
 minRet = 0; maxRet = 1;
 select file as BP_MAP_RP_VIS from calibFiles where PRO.CATG=="BP_MAP_RP_VIS" and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
@@ -4778,7 +5002,7 @@ select file as SPECTRAL_FORMAT_TAB_VIS from calibFiles where PRO.CATG=="SPECTRAL
   recipe xsh_scired_ifu_offset;
 }
 
-action XSH_SCIRED_IFU_OFFSET_NIR
+action ACTION_SCIRED_IFU_OFFSET_NIR
 {
 minRet = 0; maxRet = 1;
 select file as BP_MAP_RP_NIR from calibFiles where PRO.CATG=="BP_MAP_RP_NIR" and inputFile.DET.CHIP.ID==DET.CHIP.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
@@ -4809,7 +5033,7 @@ select file as SPECTRAL_FORMAT_TAB_NIR from calibFiles where PRO.CATG=="SPECTRAL
 
 
 
-action XSH_SCIRED_IFU_OFF_NIR
+action ACTION_SCIRED_IFU_OFF_NIR
 {
 minRet = 0; maxRet = 1;
 select file as BP_MAP_RP_NIR from calibFiles where PRO.CATG=="BP_MAP_RP_NIR" and inputFile.DET.CHIP.ID==DET.CHIP.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
diff --git a/calib/gasgano/config/xshoo.tpl.oca b/calib/gasgano/config/xshoo.tpl.oca
index 6b101c2..0d6ed9b 100644
--- a/calib/gasgano/config/xshoo.tpl.oca
+++ b/calib/gasgano/config/xshoo.tpl.oca
@@ -129,8 +129,10 @@ if(RULE.STATE == "BASIC ERROR CHECK") then
 // 
 // *** BEGIN "START NEW TEMPLATE" *** // 
  
+
+// *** (MODIFIED) ADDED "START NEW TEMPLATE" *** // 
 if((RULE.STATE == "START NEW TEMPLATE") 
-   and (DO.TEMPLATE.STANDARD.VAR.TPL.EXPNO 
+   and (DO.TEMPLATE.STANDARD.VAR.TPL.SIZE 
         != DO.TEMPLATE.STANDARD.VAR.TPL.NEXP)) then 
 {
     // A previous template was aborted - close it. 
@@ -260,42 +262,13 @@ if(RULE.STATE == "CONTINUE TEMPLATE") then
 // 
 // *** BEGIN TEMPLATE CLOSURE CHECK *** //
 
-if((RULE.STATE != "IGNORE FILE") 
-   and (not (TPL.ID like "%irdifs%") or (DO.TEMPLATE.STANDARD.VAR.TPL.SIZE
-        == DO.TEMPLATE.STANDARD.VAR.TPL.NEXP))
-   and (DO.TEMPLATE.STANDARD.VAR.TPL.EXPNO
-        == DO.TEMPLATE.STANDARD.VAR.TPL.NEXP)) then 
-{
-
-    // This rule is not triggered for a combined IRDIS+IFS template,
-    // except if the last file of the template actually arrives last.
-
-    // The current template can be closed now. 
-    // 
-    // NOTE: this does not mean that the next exposure will start a new 
-    // template. Some instruments - AMBER, for example - can arbitrarily 
-    // reopen a template and add new exposures to it. 
-    // 
-
-    DO.TEMPLATE.STANDARD.LOG = 
-        DO.TEMPLATE.STANDARD.LOG 
-        + "\nINFO: Filled template [STANDARD][TPL.START: " 
-        + DO.TEMPLATE.STANDARD.VAR.TPL.START + "] with " 
-        + DO.TEMPLATE.STANDARD.VAR.TPL.SIZE + " exposure(s)" 
-        + "; last exposure " + DO.TEMPLATE.STANDARD.VAR.TPL.EXPNO + "/" + DO.TEMPLATE.STANDARD.VAR.TPL.NEXP
-        + "; expected " + DO.TEMPLATE.STANDARD.VAR.TPL.NEXP + "."; 
-
-
-    DO.TEMPLATE.STANDARD = DO.TEMPLATE.STANDARD + " CLOSE "; 
-    RULE.STATE = "CLOSE TEMPLATE"; 
-}
 
 if((RULE.STATE != "IGNORE FILE") 
    and (RULE.STATE != "CLOSE TEMPLATE") 
    and (DO.TEMPLATE.STANDARD.VAR.TPL.SIZE
         == DO.TEMPLATE.STANDARD.VAR.TPL.NEXP)) then 
 {
-    // This rule is triggered for any (combined IRDIS+IFS data)
+    // This rule is triggered for any (combined XSHOOTER data)
     // template, that may produce out-of-order files
 
     // The current template can be closed now. 
@@ -316,8 +289,9 @@ if((RULE.STATE != "IGNORE FILE")
 
     DO.TEMPLATE.STANDARD = DO.TEMPLATE.STANDARD + " CLOSE "; 
     RULE.STATE = "CLOSE TEMPLATE"; 
-}
 
+
+}
 if((RULE.STATE == "CLOSE TEMPLATE") 
    and (DO.TEMPLATE.STANDARD.VAR.TPL.SIZE 
         != DO.TEMPLATE.STANDARD.VAR.TPL.NEXP)) then 
@@ -356,3 +330,4 @@ if(T) then
 
 // *** END RULES *** // 
 
+
diff --git a/configure b/configure
index f0ce6ce..c598b08 100755
--- a/configure
+++ b/configure
@@ -1,6 +1,6 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for X-shooter Instrument Pipeline 2.5.2.
+# Generated by GNU Autoconf 2.69 for X-shooter Instrument Pipeline 2.6.0.
 #
 # Report bugs to <usd-help at eso.org>.
 #
@@ -590,12 +590,13 @@ MAKEFLAGS=
 # Identity of this package.
 PACKAGE_NAME='X-shooter Instrument Pipeline'
 PACKAGE_TARNAME='xshoo'
-PACKAGE_VERSION='2.5.2'
-PACKAGE_STRING='X-shooter Instrument Pipeline 2.5.2'
+PACKAGE_VERSION='2.6.0'
+PACKAGE_STRING='X-shooter Instrument Pipeline 2.6.0'
 PACKAGE_BUGREPORT='usd-help at eso.org'
 PACKAGE_URL=''
 
 ac_unique_file="Makefile.am"
+enable_option_checking=no
 ac_default_prefix=${PIPE_HOME:-/usr/local}
 # Factoring default headers for most tests.
 ac_includes_default="\
@@ -668,6 +669,11 @@ CFITSIO_LDFLAGS
 CFITSIO_INCLUDES
 LIBPTHREAD
 PTHREAD_CFLAGS
+HDRL_INCLUDES
+HDRL_INTERNAL_CFLAGS
+HDRL_LDFLAGS
+LIBHDRL
+HDRL_LIBS
 LIBLAPACK
 LAPACK_LDFLAGS
 LAPACK_INCLUDES
@@ -730,6 +736,7 @@ XSH_VERSION
 MAINT
 MAINTAINER_MODE_FALSE
 MAINTAINER_MODE_TRUE
+subdirs
 AM_BACKSLASH
 AM_DEFAULT_VERBOSITY
 AM_DEFAULT_V
@@ -859,7 +866,7 @@ CPPFLAGS
 DOXYGEN
 LATEX
 CPP'
-
+ac_subdirs_all='hdrl'
 
 # Initialize some variables set by options.
 ac_init_help=
@@ -1399,7 +1406,7 @@ if test "$ac_init_help" = "long"; then
   # Omit some internal or obsolete options to make the list less imposing.
   # This message is too long to be a string in the A/UX 3.1 sh.
   cat <<_ACEOF
-\`configure' configures X-shooter Instrument Pipeline 2.5.2 to adapt to many kinds of systems.
+\`configure' configures X-shooter Instrument Pipeline 2.6.0 to adapt to many kinds of systems.
 
 Usage: $0 [OPTION]... [VAR=VALUE]...
 
@@ -1470,7 +1477,7 @@ fi
 
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of X-shooter Instrument Pipeline 2.5.2:";;
+     short | recursive ) echo "Configuration of X-shooter Instrument Pipeline 2.6.0:";;
    esac
   cat <<\_ACEOF
 
@@ -1610,7 +1617,7 @@ fi
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-X-shooter Instrument Pipeline configure 2.5.2
+X-shooter Instrument Pipeline configure 2.6.0
 generated by GNU Autoconf 2.69
 
 Copyright (C) 2012 Free Software Foundation, Inc.
@@ -2025,7 +2032,7 @@ cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
-It was created by X-shooter Instrument Pipeline $as_me 2.5.2, which was
+It was created by X-shooter Instrument Pipeline $as_me 2.6.0, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   $ $0 $@
@@ -3007,7 +3014,7 @@ fi
 
 # Define the identity of the package.
  PACKAGE='xshoo'
- VERSION='2.5.2'
+ VERSION='2.6.0'
 
 
 cat >>confdefs.h <<_ACEOF
@@ -3058,9 +3065,14 @@ am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'
 
 
 
+
+
+subdirs="$subdirs hdrl"
+
 ac_config_headers="$ac_config_headers config.h"
 
 
+
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
 $as_echo "" >&6; }
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: *********** Configuring:  $PACKAGE $VERSION **********" >&5
@@ -5017,6 +5029,56 @@ $as_echo "$ac_res" >&6; }
 
 
 
+    flag=`echo std=c99 | sed 'y%.=/+-%___p_%'`
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -std=c99" >&5
+$as_echo_n "checking whether $CC supports -std=c99... " >&6; }
+if eval \${eso_cv_prog_cc_$flag+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+
+                       eval "eso_cv_prog_cc_$flag=no"
+                       ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+                       echo 'int main() { return 0; }' >conftest.$ac_ext
+
+                       try_compile="`$CC -std=c99 -c conftest.$ac_ext 2>&1`"
+                       if test -z "$try_compile"; then
+                           try_link="`$CC -std=c99 -o conftest$ac_exeext \
+                                    conftest.$ac_ext 2>&1`"
+                           if test -z "$try_link"; then
+                               eval "eso_cv_prog_cc_$flag=yes"
+                           fi
+                       fi
+                       rm -f conftest*
+
+                       ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+fi
+eval ac_res=\$eso_cv_prog_cc_$flag
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+
+    if eval "test \"`echo '$eso_cv_prog_cc_'$flag`\" = yes"; then
+        :
+        CFLAGS="$CFLAGS -std=c99"
+    else
+        :
+
+    fi
+
+
+
+
     flag=`echo Wall | sed 'y%.=/+-%___p_%'`
     { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -Wall" >&5
 $as_echo_n "checking whether $CC supports -Wall... " >&6; }
@@ -13109,7 +13171,7 @@ fi
     for i in $xsh_lapack_incdirs; do
         for j in $xsh_lapack_check_header; do
 
-            echo "configure: 13112: $i/$j" >&5
+            echo "configure: 13174: $i/$j" >&5
 
             if test -r "$i/$j"; then
                 echo "taking that" >&5
@@ -13141,7 +13203,7 @@ fi
     for i in $xsh_lapack_libdirs; do
         for j in $xsh_lapack_check_lib; do
 
-            echo "configure: 13144: $i/$j" >&5
+            echo "configure: 13206: $i/$j" >&5
 
             if test -r "$i/$j"; then
                 echo "taking that" >&5
@@ -13290,6 +13352,33 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
 
+#Defining HDRL within the source tree
+
+    HDRL_LOCATION="hdrl"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking HDRL in $HDRL_LOCATION" >&5
+$as_echo_n "checking HDRL in $HDRL_LOCATION... " >&6; }
+
+    # visibility hidden to not expose any hdrl symbols in the pipeline shared
+    # libraries
+    HDRL_INTERNAL_CFLAGS="-std=c99 -fvisibility=hidden"
+    # requires cpl and libm as it is a static library
+    HDRL_LIBS="-lhdrl -lcplcore -lcpldrs -lcplui -lcpldfs -lcext -lm"
+    # la file to be added to DEPENDENCIES libtool doesn't track static libs
+    LIBHDRL="\$(top_builddir)/$HDRL_LOCATION/libhdrl.la"
+    HDRL_LDFLAGS="-L\$(top_builddir)/$HDRL_LOCATION"
+    HDRL_INCLUDES="-I\$(top_srcdir)/$HDRL_LOCATION"
+
+
+
+
+
+
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5
+$as_echo "ok" >&6; }
+
+
+
 # Check for functions needed for plotting with irplib
 #AC_CHECK_FUNCS([popen])
 #AC_CHECK_FUNCS([pclose])
@@ -13571,7 +13660,7 @@ $as_echo_n "checking for cfitsio... " >&6; }
     for i in $cpl_cfitsio_incdirs; do
         for j in $cpl_cfitsio_check_header; do
 
-            echo "configure: 13574: $i/$j" >&5
+            echo "configure: 13663: $i/$j" >&5
 
             if test -r "$i/$j"; then
                 echo "taking that" >&5
@@ -13625,7 +13714,7 @@ $as_echo_n "checking for cfitsio... " >&6; }
     for i in $cpl_cfitsio_libdirs; do
         for j in $cpl_cfitsio_check_lib; do
 
-            echo "configure: 13628: $i/$j" >&5
+            echo "configure: 13717: $i/$j" >&5
 
             if test -r "$i/$j"; then
                 echo "taking that" >&5
@@ -14191,7 +14280,7 @@ fi
     for i in $cpl_incdirs; do
         for j in $cpl_check_cpl_header; do
 
-            echo "configure: 14194: $i/$j" >&5
+            echo "configure: 14283: $i/$j" >&5
 
             if test -r "$i/$j"; then
                 echo "taking that" >&5
@@ -14241,7 +14330,7 @@ fi
     for i in $cpl_libdirs; do
         for j in $cpl_check_cpl_lib; do
 
-            echo "configure: 14244: $i/$j" >&5
+            echo "configure: 14333: $i/$j" >&5
 
             if test -r "$i/$j"; then
                 echo "taking that" >&5
@@ -14376,7 +14465,7 @@ fi
     for i in $cpl_cext_incdirs; do
         for j in $cpl_cext_check_header; do
 
-            echo "configure: 14379: $i/$j" >&5
+            echo "configure: 14468: $i/$j" >&5
 
             if test -r "$i/$j"; then
                 echo "taking that" >&5
@@ -14432,7 +14521,7 @@ fi
     for i in $cpl_cext_libdirs; do
         for j in $cpl_cext_check_lib; do
 
-            echo "configure: 14435: $i/$j" >&5
+            echo "configure: 14524: $i/$j" >&5
 
             if test -r "$i/$j"; then
                 echo "taking that" >&5
@@ -14800,12 +14889,13 @@ $as_echo "no" >&6; }
 
     # Symbols for package include file and library search paths
 
-    XSH_INCLUDES='-I$(top_srcdir)/xsh -I$(top_srcdir)/irplib'
+    XSH_INCLUDES='-I$(top_srcdir)/xsh -I$(top_srcdir)/irplib -I$(top_srcdir)/hdrl'
     XSH_LDFLAGS='-L$(top_builddir)/xsh'
 
     # Library aliases
     LIBXSH='$(top_builddir)/xsh/libxsh.la'
     LIBIRPLIB='$(top_builddir)/irplib/libirplib.la'
+    LIBHDRL='$(top_builddir)/hdrl/libhdrl.la'
 
     # Using irplib_fits_update_checksums function:
     IRPLIB_CPPFLAGS='-DIRPLIB_USE_FITS_UPDATE_CHECKSUM'
@@ -14818,6 +14908,7 @@ $as_echo "no" >&6; }
 
 
 
+
     # Check for CPL and user defined libraries
 
 
@@ -15701,7 +15792,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log="
-This file was extended by X-shooter Instrument Pipeline $as_me 2.5.2, which was
+This file was extended by X-shooter Instrument Pipeline $as_me 2.6.0, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
@@ -15767,7 +15858,7 @@ _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 ac_cs_version="\\
-X-shooter Instrument Pipeline config.status 2.5.2
+X-shooter Instrument Pipeline config.status 2.6.0
 configured by $0, generated by GNU Autoconf 2.69,
   with options \\"\$ac_cs_config\\"
 
@@ -17539,6 +17630,151 @@ if test "$no_create" != yes; then
   # would make configure fail if this is the last instruction.
   $ac_cs_success || as_fn_exit 1
 fi
+
+#
+# CONFIG_SUBDIRS section.
+#
+if test "$no_recursion" != yes; then
+
+  # Remove --cache-file, --srcdir, and --disable-option-checking arguments
+  # so they do not pile up.
+  ac_sub_configure_args=
+  ac_prev=
+  eval "set x $ac_configure_args"
+  shift
+  for ac_arg
+  do
+    if test -n "$ac_prev"; then
+      ac_prev=
+      continue
+    fi
+    case $ac_arg in
+    -cache-file | --cache-file | --cache-fil | --cache-fi \
+    | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
+      ac_prev=cache_file ;;
+    -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
+    | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* \
+    | --c=*)
+      ;;
+    --config-cache | -C)
+      ;;
+    -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
+      ac_prev=srcdir ;;
+    -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
+      ;;
+    -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
+      ac_prev=prefix ;;
+    -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
+      ;;
+    --disable-option-checking)
+      ;;
+    *)
+      case $ac_arg in
+      *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+      esac
+      as_fn_append ac_sub_configure_args " '$ac_arg'" ;;
+    esac
+  done
+
+  # Always prepend --prefix to ensure using the same prefix
+  # in subdir configurations.
+  ac_arg="--prefix=$prefix"
+  case $ac_arg in
+  *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+  esac
+  ac_sub_configure_args="'$ac_arg' $ac_sub_configure_args"
+
+  # Pass --silent
+  if test "$silent" = yes; then
+    ac_sub_configure_args="--silent $ac_sub_configure_args"
+  fi
+
+  # Always prepend --disable-option-checking to silence warnings, since
+  # different subdirs can have different --enable and --with options.
+  ac_sub_configure_args="--disable-option-checking $ac_sub_configure_args"
+
+  ac_popdir=`pwd`
+  for ac_dir in : $subdirs; do test "x$ac_dir" = x: && continue
+
+    # Do not complain, so a configure script can configure whichever
+    # parts of a large source tree are present.
+    test -d "$srcdir/$ac_dir" || continue
+
+    ac_msg="=== configuring in $ac_dir (`pwd`/$ac_dir)"
+    $as_echo "$as_me:${as_lineno-$LINENO}: $ac_msg" >&5
+    $as_echo "$ac_msg" >&6
+    as_dir="$ac_dir"; as_fn_mkdir_p
+    ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+    cd "$ac_dir"
+
+    # Check for guested configure; otherwise get Cygnus style configure.
+    if test -f "$ac_srcdir/configure.gnu"; then
+      ac_sub_configure=$ac_srcdir/configure.gnu
+    elif test -f "$ac_srcdir/configure"; then
+      ac_sub_configure=$ac_srcdir/configure
+    elif test -f "$ac_srcdir/configure.in"; then
+      # This should be Cygnus configure.
+      ac_sub_configure=$ac_aux_dir/configure
+    else
+      { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: no configuration information is in $ac_dir" >&5
+$as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2;}
+      ac_sub_configure=
+    fi
+
+    # The recursion is here.
+    if test -n "$ac_sub_configure"; then
+      # Make the cache file name correct relative to the subdirectory.
+      case $cache_file in
+      [\\/]* | ?:[\\/]* ) ac_sub_cache_file=$cache_file ;;
+      *) # Relative name.
+	ac_sub_cache_file=$ac_top_build_prefix$cache_file ;;
+      esac
+
+      { $as_echo "$as_me:${as_lineno-$LINENO}: running $SHELL $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_srcdir" >&5
+$as_echo "$as_me: running $SHELL $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_srcdir" >&6;}
+      # The eval makes quoting arguments work.
+      eval "\$SHELL \"\$ac_sub_configure\" $ac_sub_configure_args \
+	   --cache-file=\"\$ac_sub_cache_file\" --srcdir=\"\$ac_srcdir\"" ||
+	as_fn_error $? "$ac_sub_configure failed for $ac_dir" "$LINENO" 5
+    fi
+
+    cd "$ac_popdir"
+  done
+fi
 if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
 $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
diff --git a/configure.ac b/configure.ac
index 2284b1b..a77cf36 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,5 +1,5 @@
 # Process this file with autoconf to produce a configure script.
-AC_INIT([X-shooter Instrument Pipeline], [2.5.2], [usd-help at eso.org],
+AC_INIT([X-shooter Instrument Pipeline], [2.6.0], [usd-help at eso.org],
 [xshoo])
 
 
@@ -14,8 +14,10 @@ AC_CANONICAL_HOST
 AC_CANONICAL_TARGET
 
 AM_INIT_AUTOMAKE
+AC_CONFIG_SUBDIRS([hdrl])
 AC_CONFIG_HEADERS([config.h])
 
+
 AC_MSG_RESULT([])
 AC_MSG_RESULT([*********** Configuring:  $PACKAGE $VERSION **********])
 AC_MSG_RESULT([])
@@ -52,6 +54,7 @@ AC_MSG_RESULT([*********** Checking ESO *****************************])
 ESO_ENABLE_DEBUG(no)
 ESO_ENABLE_STRICT(no)
 ESO_PROG_CC_FLAG([fno-builtin], [CFLAGS="$CFLAGS -fno-builtin"])
+ESO_PROG_CC_FLAG([std=c99], [CFLAGS="$CFLAGS -std=c99"])
 ESO_PROG_CC_FLAG([Wall], [CFLAGS="$CFLAGS -Wall"])
 
 AC_MSG_RESULT([*********** Checking doc *****************************])
@@ -111,6 +114,10 @@ LIB_CHECK_LAPACK
 
 ESO_FUNC_STRDUP
 
+#Defining HDRL within the source tree
+HDRL_CHECK([hdrl])
+
+
 # Check for functions needed for plotting with irplib
 #AC_CHECK_FUNCS([popen])
 #AC_CHECK_FUNCS([pclose])
diff --git a/hdrl/Makefile.am b/hdrl/Makefile.am
new file mode 100644
index 0000000..ad87f28
--- /dev/null
+++ b/hdrl/Makefile.am
@@ -0,0 +1,106 @@
+## Process this file with automake to produce Makefile.in
+
+##   This file is part of the HDRL Pipeline
+##   Copyright (C) 2012,2013 European Southern Observatory
+
+##   This library is free software; you can redistribute it and/or modify
+##   it under the terms of the GNU General Public License as published by
+##   the Free Software Foundation; either version 2 of the License, or
+##   (at your option) any later version.
+##   This program is distributed in the hope that it will be useful,
+##   but WITHOUT ANY WARRANTY; without even the implied warranty of
+##   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+##   GNU General Public License for more details.
+
+##   You should have received a copy of the GNU General Public License
+##   along with this program; if not, write to the Free Software
+##   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+AUTOMAKE_OPTIONS = 1.8 foreign
+
+DISTCLEANFILES = *~
+
+SUBDIRS = . tests
+
+EXTRA_DIST =  m4macros/eso.m4 m4macros/cpl.m4
+
+if MAINTAINER_MODE
+
+MAINTAINERCLEANFILES = Makefile.in
+
+endif
+
+ACLOCAL_AMFLAGS = -I m4macros
+
+AM_CPPFLAGS = -DCX_LOG_DOMAIN=\"HdrlLib\" -DHDRL_USE_PRIVATE $(CPL_INCLUDES)
+
+hdrlHEADERS = hdrl_overscan.h \
+		 hdrl_sigclip.h \
+		 hdrl_utils.h \
+		 hdrl_combine.h \
+		 hdrl_bpm_2d.h \
+		 hdrl_bpm_3d.h \
+		 hdrl_bpm_fit.h \
+		 hdrl_bpm_utils.h \
+		 hdrl_iter.h \
+		 hdrl_collapse.h \
+		 hdrl_elemop.h \
+		 hdrl_flat.h \
+		 hdrl_prototyping.h \
+		 hdrl_image.h \
+		 hdrl_image_math.h \
+		 hdrl_imagelist.h \
+		 hdrl_imagelist_io.h \
+		 hdrl_imagelist_basic.h \
+		 hdrl_imagelist_view.h \
+		 hdrl_parameter.h \
+		 hdrl_parameter_defs.h \
+		 hdrl_strehl.h \
+		 hdrl_types.h \
+		 hdrl_test.h \
+		 hdrl_buffer.h \
+		 hdrl_overscan_defs.h \
+		 hdrl_image_defs.h \
+		 hdrl_imagelist_defs.h \
+		 hdrl_imagelist_basic_body.h \
+		 hdrl_lacosmics.h \
+		 hdrl_fit.h \
+		 hdrl.h
+
+
+libhdrl_la_SOURCES = hdrl_overscan.c \
+		    hdrl_sigclip.c \
+		    hdrl_utils.c \
+		    hdrl_combine.c \
+		    hdrl_bpm_2d.c \
+		    hdrl_bpm_3d.c \
+		    hdrl_bpm_fit.c \
+		    hdrl_bpm_utils.c \
+		    hdrl_iter.c \
+		    hdrl_collapse.c \
+		    hdrl_elemop.c \
+		    hdrl_flat.c \
+		    hdrl_fit.c \
+		    hdrl_strehl.c \
+		    hdrl_prototyping.c \
+		    hdrl_image.c \
+		    hdrl_image_math.c \
+		    hdrl_imagelist_io.c \
+		    hdrl_imagelist_basic.c \
+		    hdrl_imagelist_view.c \
+		    hdrl_parameter.c \
+		    hdrl_lacosmics.c \
+		    hdrl_buffer.c \
+		    igam.c
+
+libhdrl_la_CFLAGS = $(AM_CFLAGS)
+libhdrl_la_LDFLAGS = $(CPL_LDFLAGS) -static
+libhdrl_la_LIBADD = $(LIBCPLDFS) $(LIBCPLUI) $(LIBCPLDRS) $(LIBCPLCORE) 
+
+if VLTSW
+lib_LTLIBRARIES = libhdrl.la
+pkginclude_HEADERS = $(hdrlHEADERS)
+else
+noinst_LTLIBRARIES = libhdrl.la
+noinst_HEADERS = $(hdrlHEADERS)
+endif
diff --git a/hdrl/Makefile.in b/hdrl/Makefile.in
new file mode 100644
index 0000000..cc13ca4
--- /dev/null
+++ b/hdrl/Makefile.in
@@ -0,0 +1,1307 @@
+# Makefile.in generated by automake 1.13.4 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994-2013 Free Software Foundation, Inc.
+
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+
+VPATH = @srcdir@
+am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
+am__make_running_with_option = \
+  case $${target_option-} in \
+      ?) ;; \
+      *) echo "am__make_running_with_option: internal error: invalid" \
+              "target option '$${target_option-}' specified" >&2; \
+         exit 1;; \
+  esac; \
+  has_opt=no; \
+  sane_makeflags=$$MAKEFLAGS; \
+  if $(am__is_gnu_make); then \
+    sane_makeflags=$$MFLAGS; \
+  else \
+    case $$MAKEFLAGS in \
+      *\\[\ \	]*) \
+        bs=\\; \
+        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
+          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
+    esac; \
+  fi; \
+  skip_next=no; \
+  strip_trailopt () \
+  { \
+    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
+  }; \
+  for flg in $$sane_makeflags; do \
+    test $$skip_next = yes && { skip_next=no; continue; }; \
+    case $$flg in \
+      *=*|--*) continue;; \
+        -*I) strip_trailopt 'I'; skip_next=yes;; \
+      -*I?*) strip_trailopt 'I';; \
+        -*O) strip_trailopt 'O'; skip_next=yes;; \
+      -*O?*) strip_trailopt 'O';; \
+        -*l) strip_trailopt 'l'; skip_next=yes;; \
+      -*l?*) strip_trailopt 'l';; \
+      -[dEDm]) skip_next=yes;; \
+      -[JT]) skip_next=yes;; \
+    esac; \
+    case $$flg in \
+      *$$target_option*) has_opt=yes; break;; \
+    esac; \
+  done; \
+  test $$has_opt = yes
+am__make_dryrun = (target_option=n; $(am__make_running_with_option))
+am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
+pkgdatadir = $(datadir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkglibexecdir = $(libexecdir)/@PACKAGE@
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = .
+DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
+	$(top_srcdir)/configure $(am__configure_deps) \
+	$(srcdir)/config.h.in $(top_srcdir)/admin/depcomp \
+	$(am__noinst_HEADERS_DIST) $(am__pkginclude_HEADERS_DIST) \
+	admin/compile admin/config.guess admin/config.sub \
+	admin/depcomp admin/install-sh admin/missing admin/ltmain.sh \
+	$(top_srcdir)/admin/compile $(top_srcdir)/admin/config.guess \
+	$(top_srcdir)/admin/config.sub $(top_srcdir)/admin/install-sh \
+	$(top_srcdir)/admin/ltmain.sh $(top_srcdir)/admin/missing
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/m4macros/libtool.m4 \
+	$(top_srcdir)/m4macros/ltoptions.m4 \
+	$(top_srcdir)/m4macros/ltsugar.m4 \
+	$(top_srcdir)/m4macros/ltversion.m4 \
+	$(top_srcdir)/m4macros/lt~obsolete.m4 \
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/m4macros/cpl.m4 \
+	$(top_srcdir)/m4macros/eso.m4 $(top_srcdir)/m4macros/purify.m4 \
+	$(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+	$(ACLOCAL_M4)
+am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \
+ configure.lineno config.status.lineno
+mkinstalldirs = $(install_sh) -d
+CONFIG_HEADER = config.h
+CONFIG_CLEAN_FILES =
+CONFIG_CLEAN_VPATH_FILES =
+am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj = case $$p in \
+    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=$$p;; \
+  esac;
+am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
+am__install_max = 40
+am__nobase_strip_setup = \
+  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip = \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list = $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
+  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
+    if (++n[$$2] == $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list = \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
+am__uninstall_files_from_dir = { \
+  test -z "$$files" \
+    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
+    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
+         $(am__cd) "$$dir" && rm -f $$files; }; \
+  }
+am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(pkgincludedir)"
+LTLIBRARIES = $(lib_LTLIBRARIES) $(noinst_LTLIBRARIES)
+am__DEPENDENCIES_1 =
+libhdrl_la_DEPENDENCIES = $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_libhdrl_la_OBJECTS = libhdrl_la-hdrl_overscan.lo \
+	libhdrl_la-hdrl_sigclip.lo libhdrl_la-hdrl_utils.lo \
+	libhdrl_la-hdrl_combine.lo libhdrl_la-hdrl_bpm_2d.lo \
+	libhdrl_la-hdrl_bpm_3d.lo libhdrl_la-hdrl_bpm_fit.lo \
+	libhdrl_la-hdrl_bpm_utils.lo libhdrl_la-hdrl_iter.lo \
+	libhdrl_la-hdrl_collapse.lo libhdrl_la-hdrl_elemop.lo \
+	libhdrl_la-hdrl_flat.lo libhdrl_la-hdrl_fit.lo \
+	libhdrl_la-hdrl_strehl.lo libhdrl_la-hdrl_prototyping.lo \
+	libhdrl_la-hdrl_image.lo libhdrl_la-hdrl_image_math.lo \
+	libhdrl_la-hdrl_imagelist_io.lo \
+	libhdrl_la-hdrl_imagelist_basic.lo \
+	libhdrl_la-hdrl_imagelist_view.lo libhdrl_la-hdrl_parameter.lo \
+	libhdrl_la-hdrl_lacosmics.lo libhdrl_la-hdrl_buffer.lo \
+	libhdrl_la-igam.lo
+libhdrl_la_OBJECTS = $(am_libhdrl_la_OBJECTS)
+AM_V_lt = $(am__v_lt_ at AM_V@)
+am__v_lt_ = $(am__v_lt_ at AM_DEFAULT_V@)
+am__v_lt_0 = --silent
+am__v_lt_1 = 
+libhdrl_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
+	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(libhdrl_la_CFLAGS) \
+	$(CFLAGS) $(libhdrl_la_LDFLAGS) $(LDFLAGS) -o $@
+ at VLTSW_FALSE@am_libhdrl_la_rpath =
+ at VLTSW_TRUE@am_libhdrl_la_rpath = -rpath $(libdir)
+AM_V_P = $(am__v_P_ at AM_V@)
+am__v_P_ = $(am__v_P_ at AM_DEFAULT_V@)
+am__v_P_0 = false
+am__v_P_1 = :
+AM_V_GEN = $(am__v_GEN_ at AM_V@)
+am__v_GEN_ = $(am__v_GEN_ at AM_DEFAULT_V@)
+am__v_GEN_0 = @echo "  GEN     " $@;
+am__v_GEN_1 = 
+AM_V_at = $(am__v_at_ at AM_V@)
+am__v_at_ = $(am__v_at_ at AM_DEFAULT_V@)
+am__v_at_0 = @
+am__v_at_1 = 
+DEFAULT_INCLUDES = -I. at am__isrc@
+depcomp = $(SHELL) $(top_srcdir)/admin/depcomp
+am__depfiles_maybe = depfiles
+am__mv = mv -f
+COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
+	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
+	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
+	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
+	$(AM_CFLAGS) $(CFLAGS)
+AM_V_CC = $(am__v_CC_ at AM_V@)
+am__v_CC_ = $(am__v_CC_ at AM_DEFAULT_V@)
+am__v_CC_0 = @echo "  CC      " $@;
+am__v_CC_1 = 
+CCLD = $(CC)
+LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
+	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
+	$(AM_LDFLAGS) $(LDFLAGS) -o $@
+AM_V_CCLD = $(am__v_CCLD_ at AM_V@)
+am__v_CCLD_ = $(am__v_CCLD_ at AM_DEFAULT_V@)
+am__v_CCLD_0 = @echo "  CCLD    " $@;
+am__v_CCLD_1 = 
+SOURCES = $(libhdrl_la_SOURCES)
+DIST_SOURCES = $(libhdrl_la_SOURCES)
+RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
+	ctags-recursive dvi-recursive html-recursive info-recursive \
+	install-data-recursive install-dvi-recursive \
+	install-exec-recursive install-html-recursive \
+	install-info-recursive install-pdf-recursive \
+	install-ps-recursive install-recursive installcheck-recursive \
+	installdirs-recursive pdf-recursive ps-recursive \
+	tags-recursive uninstall-recursive
+am__can_run_installinfo = \
+  case $$AM_UPDATE_INFO_DIR in \
+    n|no|NO) false;; \
+    *) (install-info --version) >/dev/null 2>&1;; \
+  esac
+am__noinst_HEADERS_DIST = hdrl_overscan.h hdrl_sigclip.h hdrl_utils.h \
+	hdrl_combine.h hdrl_bpm_2d.h hdrl_bpm_3d.h hdrl_bpm_fit.h \
+	hdrl_bpm_utils.h hdrl_iter.h hdrl_collapse.h hdrl_elemop.h \
+	hdrl_flat.h hdrl_prototyping.h hdrl_image.h hdrl_image_math.h \
+	hdrl_imagelist.h hdrl_imagelist_io.h hdrl_imagelist_basic.h \
+	hdrl_imagelist_view.h hdrl_parameter.h hdrl_parameter_defs.h \
+	hdrl_strehl.h hdrl_types.h hdrl_test.h hdrl_buffer.h \
+	hdrl_overscan_defs.h hdrl_image_defs.h hdrl_imagelist_defs.h \
+	hdrl_imagelist_basic_body.h hdrl_lacosmics.h hdrl_fit.h hdrl.h
+am__pkginclude_HEADERS_DIST = hdrl_overscan.h hdrl_sigclip.h \
+	hdrl_utils.h hdrl_combine.h hdrl_bpm_2d.h hdrl_bpm_3d.h \
+	hdrl_bpm_fit.h hdrl_bpm_utils.h hdrl_iter.h hdrl_collapse.h \
+	hdrl_elemop.h hdrl_flat.h hdrl_prototyping.h hdrl_image.h \
+	hdrl_image_math.h hdrl_imagelist.h hdrl_imagelist_io.h \
+	hdrl_imagelist_basic.h hdrl_imagelist_view.h hdrl_parameter.h \
+	hdrl_parameter_defs.h hdrl_strehl.h hdrl_types.h hdrl_test.h \
+	hdrl_buffer.h hdrl_overscan_defs.h hdrl_image_defs.h \
+	hdrl_imagelist_defs.h hdrl_imagelist_basic_body.h \
+	hdrl_lacosmics.h hdrl_fit.h hdrl.h
+HEADERS = $(noinst_HEADERS) $(pkginclude_HEADERS)
+RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive	\
+  distclean-recursive maintainer-clean-recursive
+am__recursive_targets = \
+  $(RECURSIVE_TARGETS) \
+  $(RECURSIVE_CLEAN_TARGETS) \
+  $(am__extra_recursive_targets)
+AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
+	cscope distdir dist dist-all distcheck
+am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) \
+	$(LISP)config.h.in
+# Read a list of newline-separated strings from the standard input,
+# and print each of them once, without duplicates.  Input order is
+# *not* preserved.
+am__uniquify_input = $(AWK) '\
+  BEGIN { nonempty = 0; } \
+  { items[$$0] = 1; nonempty = 1; } \
+  END { if (nonempty) { for (i in items) print i; }; } \
+'
+# Make sure the list of sources is unique.  This is necessary because,
+# e.g., the same source file might be shared among _SOURCES variables
+# for different programs/libraries.
+am__define_uniq_tagged_files = \
+  list='$(am__tagged_files)'; \
+  unique=`for i in $$list; do \
+    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+  done | $(am__uniquify_input)`
+ETAGS = etags
+CTAGS = ctags
+CSCOPE = cscope
+DIST_SUBDIRS = $(SUBDIRS)
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+distdir = $(PACKAGE)-$(VERSION)
+top_distdir = $(distdir)
+am__remove_distdir = \
+  if test -d "$(distdir)"; then \
+    find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \
+      && rm -rf "$(distdir)" \
+      || { sleep 5 && rm -rf "$(distdir)"; }; \
+  else :; fi
+am__post_remove_distdir = $(am__remove_distdir)
+am__relativize = \
+  dir0=`pwd`; \
+  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
+  sed_rest='s,^[^/]*/*,,'; \
+  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
+  sed_butlast='s,/*[^/]*$$,,'; \
+  while test -n "$$dir1"; do \
+    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
+    if test "$$first" != "."; then \
+      if test "$$first" = ".."; then \
+        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
+        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
+      else \
+        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
+        if test "$$first2" = "$$first"; then \
+          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
+        else \
+          dir2="../$$dir2"; \
+        fi; \
+        dir0="$$dir0"/"$$first"; \
+      fi; \
+    fi; \
+    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
+  done; \
+  reldir="$$dir2"
+DIST_ARCHIVES = $(distdir).tar.gz
+GZIP_ENV = --best
+DIST_TARGETS = dist-gzip
+distuninstallcheck_listfiles = find . -type f -print
+am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \
+  | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$'
+distcleancheck_listfiles = find . -type f -print
+ACLOCAL = @ACLOCAL@
+AMTAR = @AMTAR@
+AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPL_INCLUDES = @CPL_INCLUDES@
+CPL_LDFLAGS = @CPL_LDFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CX_INCLUDES = @CX_INCLUDES@
+CX_LDFLAGS = @CX_LDFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+DLLTOOL = @DLLTOOL@
+DOXYGEN = @DOXYGEN@
+DSYMUTIL = @DSYMUTIL@
+DUMPBIN = @DUMPBIN@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+ESO_DEBUG_FLAGS = @ESO_DEBUG_FLAGS@
+EXEEXT = @EXEEXT@
+FGREP = @FGREP@
+GREP = @GREP@
+HDRL_BINARY_AGE = @HDRL_BINARY_AGE@
+HDRL_BINARY_VERSION = @HDRL_BINARY_VERSION@
+HDRL_INCLUDES = @HDRL_INCLUDES@
+HDRL_INTERFACE_AGE = @HDRL_INTERFACE_AGE@
+HDRL_LDFLAGS = @HDRL_LDFLAGS@
+HDRL_MAJOR_VERSION = @HDRL_MAJOR_VERSION@
+HDRL_MICRO_VERSION = @HDRL_MICRO_VERSION@
+HDRL_MINOR_VERSION = @HDRL_MINOR_VERSION@
+HDRL_VERSION = @HDRL_VERSION@
+INSTALL = @INSTALL@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+LATEX = @LATEX@
+LD = @LD@
+LDFLAGS = @LDFLAGS@
+LIBCEXT = @LIBCEXT@
+LIBCPLCORE = @LIBCPLCORE@
+LIBCPLDFS = @LIBCPLDFS@
+LIBCPLDRS = @LIBCPLDRS@
+LIBCPLUI = @LIBCPLUI@
+LIBHDRL = @LIBHDRL@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LIBTOOL_DEPS = @LIBTOOL_DEPS@
+LIPO = @LIPO@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_REVISION = @LT_REVISION@
+MAINT = @MAINT@
+MAKEINFO = @MAKEINFO@
+MANIFEST_TOOL = @MANIFEST_TOOL@
+MKDIR_P = @MKDIR_P@
+NM = @NM@
+NMEDIT = @NMEDIT@
+OBJDUMP = @OBJDUMP@
+OBJEXT = @OBJEXT@
+OTOOL = @OTOOL@
+OTOOL64 = @OTOOL64@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_URL = @PACKAGE_URL@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+PURIFY_CMD = @PURIFY_CMD@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+abs_builddir = @abs_builddir@
+abs_srcdir = @abs_srcdir@
+abs_top_builddir = @abs_top_builddir@
+abs_top_srcdir = @abs_top_srcdir@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
+all_includes = @all_includes@
+all_ldflags = @all_ldflags@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+builddir = @builddir@
+datadir = @datadir@
+datarootdir = @datarootdir@
+docdir = @docdir@
+dvidir = @dvidir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+htmldir = @htmldir@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localedir = @localedir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+pdfdir = @pdfdir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+psdir = @psdir@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+srcdir = @srcdir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+top_build_prefix = @top_build_prefix@
+top_builddir = @top_builddir@
+top_srcdir = @top_srcdir@
+AUTOMAKE_OPTIONS = 1.8 foreign
+DISTCLEANFILES = *~
+SUBDIRS = . tests
+EXTRA_DIST = m4macros/eso.m4 m4macros/cpl.m4
+ at MAINTAINER_MODE_TRUE@MAINTAINERCLEANFILES = Makefile.in
+ACLOCAL_AMFLAGS = -I m4macros
+AM_CPPFLAGS = -DCX_LOG_DOMAIN=\"HdrlLib\" -DHDRL_USE_PRIVATE $(CPL_INCLUDES)
+hdrlHEADERS = hdrl_overscan.h \
+		 hdrl_sigclip.h \
+		 hdrl_utils.h \
+		 hdrl_combine.h \
+		 hdrl_bpm_2d.h \
+		 hdrl_bpm_3d.h \
+		 hdrl_bpm_fit.h \
+		 hdrl_bpm_utils.h \
+		 hdrl_iter.h \
+		 hdrl_collapse.h \
+		 hdrl_elemop.h \
+		 hdrl_flat.h \
+		 hdrl_prototyping.h \
+		 hdrl_image.h \
+		 hdrl_image_math.h \
+		 hdrl_imagelist.h \
+		 hdrl_imagelist_io.h \
+		 hdrl_imagelist_basic.h \
+		 hdrl_imagelist_view.h \
+		 hdrl_parameter.h \
+		 hdrl_parameter_defs.h \
+		 hdrl_strehl.h \
+		 hdrl_types.h \
+		 hdrl_test.h \
+		 hdrl_buffer.h \
+		 hdrl_overscan_defs.h \
+		 hdrl_image_defs.h \
+		 hdrl_imagelist_defs.h \
+		 hdrl_imagelist_basic_body.h \
+		 hdrl_lacosmics.h \
+		 hdrl_fit.h \
+		 hdrl.h
+
+libhdrl_la_SOURCES = hdrl_overscan.c \
+		    hdrl_sigclip.c \
+		    hdrl_utils.c \
+		    hdrl_combine.c \
+		    hdrl_bpm_2d.c \
+		    hdrl_bpm_3d.c \
+		    hdrl_bpm_fit.c \
+		    hdrl_bpm_utils.c \
+		    hdrl_iter.c \
+		    hdrl_collapse.c \
+		    hdrl_elemop.c \
+		    hdrl_flat.c \
+		    hdrl_fit.c \
+		    hdrl_strehl.c \
+		    hdrl_prototyping.c \
+		    hdrl_image.c \
+		    hdrl_image_math.c \
+		    hdrl_imagelist_io.c \
+		    hdrl_imagelist_basic.c \
+		    hdrl_imagelist_view.c \
+		    hdrl_parameter.c \
+		    hdrl_lacosmics.c \
+		    hdrl_buffer.c \
+		    igam.c
+
+libhdrl_la_CFLAGS = $(AM_CFLAGS)
+libhdrl_la_LDFLAGS = $(CPL_LDFLAGS) -static
+libhdrl_la_LIBADD = $(LIBCPLDFS) $(LIBCPLUI) $(LIBCPLDRS) $(LIBCPLCORE) 
+ at VLTSW_TRUE@lib_LTLIBRARIES = libhdrl.la
+ at VLTSW_TRUE@pkginclude_HEADERS = $(hdrlHEADERS)
+ at VLTSW_FALSE@noinst_LTLIBRARIES = libhdrl.la
+ at VLTSW_FALSE@noinst_HEADERS = $(hdrlHEADERS)
+all: config.h
+	$(MAKE) $(AM_MAKEFLAGS) all-recursive
+
+.SUFFIXES:
+.SUFFIXES: .c .lo .o .obj
+am--refresh: Makefile
+	@:
+$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am  $(am__configure_deps)
+	@for dep in $?; do \
+	  case '$(am__configure_deps)' in \
+	    *$$dep*) \
+	      echo ' cd $(srcdir) && $(AUTOMAKE) --foreign'; \
+	      $(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \
+		&& exit 0; \
+	      exit 1;; \
+	  esac; \
+	done; \
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+	@case '$?' in \
+	  *config.status*) \
+	    echo ' $(SHELL) ./config.status'; \
+	    $(SHELL) ./config.status;; \
+	  *) \
+	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \
+	    cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \
+	esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+	$(SHELL) ./config.status --recheck
+
+$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps)
+	$(am__cd) $(srcdir) && $(AUTOCONF)
+$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
+	$(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS)
+$(am__aclocal_m4_deps):
+
+config.h: stamp-h1
+	@if test ! -f $@; then rm -f stamp-h1; else :; fi
+	@if test ! -f $@; then $(MAKE) $(AM_MAKEFLAGS) stamp-h1; else :; fi
+
+stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status
+	@rm -f stamp-h1
+	cd $(top_builddir) && $(SHELL) ./config.status config.h
+$(srcdir)/config.h.in: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) 
+	($(am__cd) $(top_srcdir) && $(AUTOHEADER))
+	rm -f stamp-h1
+	touch $@
+
+distclean-hdr:
+	-rm -f config.h stamp-h1
+
+install-libLTLIBRARIES: $(lib_LTLIBRARIES)
+	@$(NORMAL_INSTALL)
+	@list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \
+	list2=; for p in $$list; do \
+	  if test -f $$p; then \
+	    list2="$$list2 $$p"; \
+	  else :; fi; \
+	done; \
+	test -z "$$list2" || { \
+	  echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \
+	  $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
+	}
+
+uninstall-libLTLIBRARIES:
+	@$(NORMAL_UNINSTALL)
+	@list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \
+	done
+
+clean-libLTLIBRARIES:
+	-test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES)
+	@list='$(lib_LTLIBRARIES)'; \
+	locs=`for p in $$list; do echo $$p; done | \
+	      sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \
+	      sort -u`; \
+	test -z "$$locs" || { \
+	  echo rm -f $${locs}; \
+	  rm -f $${locs}; \
+	}
+
+clean-noinstLTLIBRARIES:
+	-test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
+	@list='$(noinst_LTLIBRARIES)'; \
+	locs=`for p in $$list; do echo $$p; done | \
+	      sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \
+	      sort -u`; \
+	test -z "$$locs" || { \
+	  echo rm -f $${locs}; \
+	  rm -f $${locs}; \
+	}
+
+libhdrl.la: $(libhdrl_la_OBJECTS) $(libhdrl_la_DEPENDENCIES) $(EXTRA_libhdrl_la_DEPENDENCIES) 
+	$(AM_V_CCLD)$(libhdrl_la_LINK) $(am_libhdrl_la_rpath) $(libhdrl_la_OBJECTS) $(libhdrl_la_LIBADD) $(LIBS)
+
+mostlyclean-compile:
+	-rm -f *.$(OBJEXT)
+
+distclean-compile:
+	-rm -f *.tab.c
+
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_bpm_2d.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_bpm_3d.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_bpm_fit.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_bpm_utils.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_buffer.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_collapse.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_combine.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_elemop.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_fit.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_flat.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_image.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_image_math.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_imagelist_basic.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_imagelist_io.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_imagelist_view.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_iter.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_lacosmics.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_overscan.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_parameter.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_prototyping.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_sigclip.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_strehl.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-hdrl_utils.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhdrl_la-igam.Plo at am__quote@
+
+.c.o:
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(COMPILE) -c $<
+
+.c.obj:
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(COMPILE) -c `$(CYGPATH_W) '$<'`
+
+.c.lo:
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LTCOMPILE) -c -o $@ $<
+
+libhdrl_la-hdrl_overscan.lo: hdrl_overscan.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_overscan.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_overscan.Tpo -c -o libhdrl_la-hdrl_overscan.lo `test -f 'hdrl_overscan.c' || echo '$(srcdir)/'`hdrl_overscan.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_overscan.Tpo $(DEPDIR)/libhdrl_la-hdrl_overscan.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_overscan.c' object='libhdrl_la-hdrl_overscan.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_overscan.lo `test -f 'hdrl_overscan.c' || echo '$(srcdir)/'`hdrl_overscan.c
+
+libhdrl_la-hdrl_sigclip.lo: hdrl_sigclip.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_sigclip.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_sigclip.Tpo -c -o libhdrl_la-hdrl_sigclip.lo `test -f 'hdrl_sigclip.c' || echo '$(srcdir)/'`hdrl_sigclip.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_sigclip.Tpo $(DEPDIR)/libhdrl_la-hdrl_sigclip.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_sigclip.c' object='libhdrl_la-hdrl_sigclip.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_sigclip.lo `test -f 'hdrl_sigclip.c' || echo '$(srcdir)/'`hdrl_sigclip.c
+
+libhdrl_la-hdrl_utils.lo: hdrl_utils.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_utils.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_utils.Tpo -c -o libhdrl_la-hdrl_utils.lo `test -f 'hdrl_utils.c' || echo '$(srcdir)/'`hdrl_utils.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_utils.Tpo $(DEPDIR)/libhdrl_la-hdrl_utils.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_utils.c' object='libhdrl_la-hdrl_utils.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_utils.lo `test -f 'hdrl_utils.c' || echo '$(srcdir)/'`hdrl_utils.c
+
+libhdrl_la-hdrl_combine.lo: hdrl_combine.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_combine.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_combine.Tpo -c -o libhdrl_la-hdrl_combine.lo `test -f 'hdrl_combine.c' || echo '$(srcdir)/'`hdrl_combine.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_combine.Tpo $(DEPDIR)/libhdrl_la-hdrl_combine.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_combine.c' object='libhdrl_la-hdrl_combine.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_combine.lo `test -f 'hdrl_combine.c' || echo '$(srcdir)/'`hdrl_combine.c
+
+libhdrl_la-hdrl_bpm_2d.lo: hdrl_bpm_2d.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_bpm_2d.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_bpm_2d.Tpo -c -o libhdrl_la-hdrl_bpm_2d.lo `test -f 'hdrl_bpm_2d.c' || echo '$(srcdir)/'`hdrl_bpm_2d.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_bpm_2d.Tpo $(DEPDIR)/libhdrl_la-hdrl_bpm_2d.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_bpm_2d.c' object='libhdrl_la-hdrl_bpm_2d.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_bpm_2d.lo `test -f 'hdrl_bpm_2d.c' || echo '$(srcdir)/'`hdrl_bpm_2d.c
+
+libhdrl_la-hdrl_bpm_3d.lo: hdrl_bpm_3d.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_bpm_3d.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_bpm_3d.Tpo -c -o libhdrl_la-hdrl_bpm_3d.lo `test -f 'hdrl_bpm_3d.c' || echo '$(srcdir)/'`hdrl_bpm_3d.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_bpm_3d.Tpo $(DEPDIR)/libhdrl_la-hdrl_bpm_3d.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_bpm_3d.c' object='libhdrl_la-hdrl_bpm_3d.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_bpm_3d.lo `test -f 'hdrl_bpm_3d.c' || echo '$(srcdir)/'`hdrl_bpm_3d.c
+
+libhdrl_la-hdrl_bpm_fit.lo: hdrl_bpm_fit.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_bpm_fit.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_bpm_fit.Tpo -c -o libhdrl_la-hdrl_bpm_fit.lo `test -f 'hdrl_bpm_fit.c' || echo '$(srcdir)/'`hdrl_bpm_fit.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_bpm_fit.Tpo $(DEPDIR)/libhdrl_la-hdrl_bpm_fit.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_bpm_fit.c' object='libhdrl_la-hdrl_bpm_fit.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_bpm_fit.lo `test -f 'hdrl_bpm_fit.c' || echo '$(srcdir)/'`hdrl_bpm_fit.c
+
+libhdrl_la-hdrl_bpm_utils.lo: hdrl_bpm_utils.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_bpm_utils.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_bpm_utils.Tpo -c -o libhdrl_la-hdrl_bpm_utils.lo `test -f 'hdrl_bpm_utils.c' || echo '$(srcdir)/'`hdrl_bpm_utils.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_bpm_utils.Tpo $(DEPDIR)/libhdrl_la-hdrl_bpm_utils.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_bpm_utils.c' object='libhdrl_la-hdrl_bpm_utils.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_bpm_utils.lo `test -f 'hdrl_bpm_utils.c' || echo '$(srcdir)/'`hdrl_bpm_utils.c
+
+libhdrl_la-hdrl_iter.lo: hdrl_iter.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_iter.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_iter.Tpo -c -o libhdrl_la-hdrl_iter.lo `test -f 'hdrl_iter.c' || echo '$(srcdir)/'`hdrl_iter.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_iter.Tpo $(DEPDIR)/libhdrl_la-hdrl_iter.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_iter.c' object='libhdrl_la-hdrl_iter.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_iter.lo `test -f 'hdrl_iter.c' || echo '$(srcdir)/'`hdrl_iter.c
+
+libhdrl_la-hdrl_collapse.lo: hdrl_collapse.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_collapse.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_collapse.Tpo -c -o libhdrl_la-hdrl_collapse.lo `test -f 'hdrl_collapse.c' || echo '$(srcdir)/'`hdrl_collapse.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_collapse.Tpo $(DEPDIR)/libhdrl_la-hdrl_collapse.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_collapse.c' object='libhdrl_la-hdrl_collapse.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_collapse.lo `test -f 'hdrl_collapse.c' || echo '$(srcdir)/'`hdrl_collapse.c
+
+libhdrl_la-hdrl_elemop.lo: hdrl_elemop.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_elemop.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_elemop.Tpo -c -o libhdrl_la-hdrl_elemop.lo `test -f 'hdrl_elemop.c' || echo '$(srcdir)/'`hdrl_elemop.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_elemop.Tpo $(DEPDIR)/libhdrl_la-hdrl_elemop.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_elemop.c' object='libhdrl_la-hdrl_elemop.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_elemop.lo `test -f 'hdrl_elemop.c' || echo '$(srcdir)/'`hdrl_elemop.c
+
+libhdrl_la-hdrl_flat.lo: hdrl_flat.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_flat.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_flat.Tpo -c -o libhdrl_la-hdrl_flat.lo `test -f 'hdrl_flat.c' || echo '$(srcdir)/'`hdrl_flat.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_flat.Tpo $(DEPDIR)/libhdrl_la-hdrl_flat.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_flat.c' object='libhdrl_la-hdrl_flat.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_flat.lo `test -f 'hdrl_flat.c' || echo '$(srcdir)/'`hdrl_flat.c
+
+libhdrl_la-hdrl_fit.lo: hdrl_fit.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_fit.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_fit.Tpo -c -o libhdrl_la-hdrl_fit.lo `test -f 'hdrl_fit.c' || echo '$(srcdir)/'`hdrl_fit.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_fit.Tpo $(DEPDIR)/libhdrl_la-hdrl_fit.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_fit.c' object='libhdrl_la-hdrl_fit.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_fit.lo `test -f 'hdrl_fit.c' || echo '$(srcdir)/'`hdrl_fit.c
+
+libhdrl_la-hdrl_strehl.lo: hdrl_strehl.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_strehl.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_strehl.Tpo -c -o libhdrl_la-hdrl_strehl.lo `test -f 'hdrl_strehl.c' || echo '$(srcdir)/'`hdrl_strehl.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_strehl.Tpo $(DEPDIR)/libhdrl_la-hdrl_strehl.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_strehl.c' object='libhdrl_la-hdrl_strehl.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_strehl.lo `test -f 'hdrl_strehl.c' || echo '$(srcdir)/'`hdrl_strehl.c
+
+libhdrl_la-hdrl_prototyping.lo: hdrl_prototyping.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_prototyping.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_prototyping.Tpo -c -o libhdrl_la-hdrl_prototyping.lo `test -f 'hdrl_prototyping.c' || echo '$(srcdir)/'`hdrl_prototyping.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_prototyping.Tpo $(DEPDIR)/libhdrl_la-hdrl_prototyping.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_prototyping.c' object='libhdrl_la-hdrl_prototyping.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_prototyping.lo `test -f 'hdrl_prototyping.c' || echo '$(srcdir)/'`hdrl_prototyping.c
+
+libhdrl_la-hdrl_image.lo: hdrl_image.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_image.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_image.Tpo -c -o libhdrl_la-hdrl_image.lo `test -f 'hdrl_image.c' || echo '$(srcdir)/'`hdrl_image.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_image.Tpo $(DEPDIR)/libhdrl_la-hdrl_image.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_image.c' object='libhdrl_la-hdrl_image.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_image.lo `test -f 'hdrl_image.c' || echo '$(srcdir)/'`hdrl_image.c
+
+libhdrl_la-hdrl_image_math.lo: hdrl_image_math.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_image_math.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_image_math.Tpo -c -o libhdrl_la-hdrl_image_math.lo `test -f 'hdrl_image_math.c' || echo '$(srcdir)/'`hdrl_image_math.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_image_math.Tpo $(DEPDIR)/libhdrl_la-hdrl_image_math.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_image_math.c' object='libhdrl_la-hdrl_image_math.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_image_math.lo `test -f 'hdrl_image_math.c' || echo '$(srcdir)/'`hdrl_image_math.c
+
+libhdrl_la-hdrl_imagelist_io.lo: hdrl_imagelist_io.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_imagelist_io.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_imagelist_io.Tpo -c -o libhdrl_la-hdrl_imagelist_io.lo `test -f 'hdrl_imagelist_io.c' || echo '$(srcdir)/'`hdrl_imagelist_io.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_imagelist_io.Tpo $(DEPDIR)/libhdrl_la-hdrl_imagelist_io.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_imagelist_io.c' object='libhdrl_la-hdrl_imagelist_io.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_imagelist_io.lo `test -f 'hdrl_imagelist_io.c' || echo '$(srcdir)/'`hdrl_imagelist_io.c
+
+libhdrl_la-hdrl_imagelist_basic.lo: hdrl_imagelist_basic.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_imagelist_basic.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_imagelist_basic.Tpo -c -o libhdrl_la-hdrl_imagelist_basic.lo `test -f 'hdrl_imagelist_basic.c' || echo '$(srcdir)/'`hdrl_imagelist_basic.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_imagelist_basic.Tpo $(DEPDIR)/libhdrl_la-hdrl_imagelist_basic.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_imagelist_basic.c' object='libhdrl_la-hdrl_imagelist_basic.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_imagelist_basic.lo `test -f 'hdrl_imagelist_basic.c' || echo '$(srcdir)/'`hdrl_imagelist_basic.c
+
+libhdrl_la-hdrl_imagelist_view.lo: hdrl_imagelist_view.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_imagelist_view.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_imagelist_view.Tpo -c -o libhdrl_la-hdrl_imagelist_view.lo `test -f 'hdrl_imagelist_view.c' || echo '$(srcdir)/'`hdrl_imagelist_view.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_imagelist_view.Tpo $(DEPDIR)/libhdrl_la-hdrl_imagelist_view.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_imagelist_view.c' object='libhdrl_la-hdrl_imagelist_view.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_imagelist_view.lo `test -f 'hdrl_imagelist_view.c' || echo '$(srcdir)/'`hdrl_imagelist_view.c
+
+libhdrl_la-hdrl_parameter.lo: hdrl_parameter.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_parameter.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_parameter.Tpo -c -o libhdrl_la-hdrl_parameter.lo `test -f 'hdrl_parameter.c' || echo '$(srcdir)/'`hdrl_parameter.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_parameter.Tpo $(DEPDIR)/libhdrl_la-hdrl_parameter.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_parameter.c' object='libhdrl_la-hdrl_parameter.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_parameter.lo `test -f 'hdrl_parameter.c' || echo '$(srcdir)/'`hdrl_parameter.c
+
+libhdrl_la-hdrl_lacosmics.lo: hdrl_lacosmics.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_lacosmics.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_lacosmics.Tpo -c -o libhdrl_la-hdrl_lacosmics.lo `test -f 'hdrl_lacosmics.c' || echo '$(srcdir)/'`hdrl_lacosmics.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_lacosmics.Tpo $(DEPDIR)/libhdrl_la-hdrl_lacosmics.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_lacosmics.c' object='libhdrl_la-hdrl_lacosmics.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_lacosmics.lo `test -f 'hdrl_lacosmics.c' || echo '$(srcdir)/'`hdrl_lacosmics.c
+
+libhdrl_la-hdrl_buffer.lo: hdrl_buffer.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-hdrl_buffer.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-hdrl_buffer.Tpo -c -o libhdrl_la-hdrl_buffer.lo `test -f 'hdrl_buffer.c' || echo '$(srcdir)/'`hdrl_buffer.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-hdrl_buffer.Tpo $(DEPDIR)/libhdrl_la-hdrl_buffer.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='hdrl_buffer.c' object='libhdrl_la-hdrl_buffer.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-hdrl_buffer.lo `test -f 'hdrl_buffer.c' || echo '$(srcdir)/'`hdrl_buffer.c
+
+libhdrl_la-igam.lo: igam.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -MT libhdrl_la-igam.lo -MD -MP -MF $(DEPDIR)/libhdrl_la-igam.Tpo -c -o libhdrl_la-igam.lo `test -f 'igam.c' || echo '$(srcdir)/'`igam.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libhdrl_la-igam.Tpo $(DEPDIR)/libhdrl_la-igam.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='igam.c' object='libhdrl_la-igam.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libhdrl_la_CFLAGS) $(CFLAGS) -c -o libhdrl_la-igam.lo `test -f 'igam.c' || echo '$(srcdir)/'`igam.c
+
+mostlyclean-libtool:
+	-rm -f *.lo
+
+clean-libtool:
+	-rm -rf .libs _libs
+
+distclean-libtool:
+	-rm -f libtool config.lt
+install-pkgincludeHEADERS: $(pkginclude_HEADERS)
+	@$(NORMAL_INSTALL)
+	@list='$(pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \
+	if test -n "$$list"; then \
+	  echo " $(MKDIR_P) '$(DESTDIR)$(pkgincludedir)'"; \
+	  $(MKDIR_P) "$(DESTDIR)$(pkgincludedir)" || exit 1; \
+	fi; \
+	for p in $$list; do \
+	  if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(pkgincludedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(pkgincludedir)" || exit $$?; \
+	done
+
+uninstall-pkgincludeHEADERS:
+	@$(NORMAL_UNINSTALL)
+	@list='$(pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \
+	files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	dir='$(DESTDIR)$(pkgincludedir)'; $(am__uninstall_files_from_dir)
+
+# This directory's subdirectories are mostly independent; you can cd
+# into them and run 'make' without going through this Makefile.
+# To change the values of 'make' variables: instead of editing Makefiles,
+# (1) if the variable is set in 'config.status', edit 'config.status'
+#     (which will cause the Makefiles to be regenerated when you run 'make');
+# (2) otherwise, pass the desired values on the 'make' command line.
+$(am__recursive_targets):
+	@fail=; \
+	if $(am__make_keepgoing); then \
+	  failcom='fail=yes'; \
+	else \
+	  failcom='exit 1'; \
+	fi; \
+	dot_seen=no; \
+	target=`echo $@ | sed s/-recursive//`; \
+	case "$@" in \
+	  distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
+	  *) list='$(SUBDIRS)' ;; \
+	esac; \
+	for subdir in $$list; do \
+	  echo "Making $$target in $$subdir"; \
+	  if test "$$subdir" = "."; then \
+	    dot_seen=yes; \
+	    local_target="$$target-am"; \
+	  else \
+	    local_target="$$target"; \
+	  fi; \
+	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+	  || eval $$failcom; \
+	done; \
+	if test "$$dot_seen" = "no"; then \
+	  $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
+	fi; test -z "$$fail"
+
+ID: $(am__tagged_files)
+	$(am__define_uniq_tagged_files); mkid -fID $$unique
+tags: tags-recursive
+TAGS: tags
+
+tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
+	set x; \
+	here=`pwd`; \
+	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
+	  include_option=--etags-include; \
+	  empty_fix=.; \
+	else \
+	  include_option=--include; \
+	  empty_fix=; \
+	fi; \
+	list='$(SUBDIRS)'; for subdir in $$list; do \
+	  if test "$$subdir" = .; then :; else \
+	    test ! -f $$subdir/TAGS || \
+	      set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
+	  fi; \
+	done; \
+	$(am__define_uniq_tagged_files); \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
+	  test -n "$$unique" || unique=$$empty_fix; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
+	fi
+ctags: ctags-recursive
+
+CTAGS: ctags
+ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
+	$(am__define_uniq_tagged_files); \
+	test -z "$(CTAGS_ARGS)$$unique" \
+	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+	     $$unique
+
+GTAGS:
+	here=`$(am__cd) $(top_builddir) && pwd` \
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
+cscope: cscope.files
+	test ! -s cscope.files \
+	  || $(CSCOPE) -b -q $(AM_CSCOPEFLAGS) $(CSCOPEFLAGS) -i cscope.files $(CSCOPE_ARGS)
+clean-cscope:
+	-rm -f cscope.files
+cscope.files: clean-cscope cscopelist
+cscopelist: cscopelist-recursive
+
+cscopelist-am: $(am__tagged_files)
+	list='$(am__tagged_files)'; \
+	case "$(srcdir)" in \
+	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
+	  *) sdir=$(subdir)/$(srcdir) ;; \
+	esac; \
+	for i in $$list; do \
+	  if test -f "$$i"; then \
+	    echo "$(subdir)/$$i"; \
+	  else \
+	    echo "$$sdir/$$i"; \
+	  fi; \
+	done >> $(top_builddir)/cscope.files
+
+distclean-tags:
+	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+	-rm -f cscope.out cscope.in.out cscope.po.out cscope.files
+
+distdir: $(DISTFILES)
+	$(am__remove_distdir)
+	test -d "$(distdir)" || mkdir "$(distdir)"
+	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
+	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
+	list='$(DISTFILES)'; \
+	  dist_files=`for file in $$list; do echo $$file; done | \
+	  sed -e "s|^$$srcdirstrip/||;t" \
+	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
+	case $$dist_files in \
+	  */*) $(MKDIR_P) `echo "$$dist_files" | \
+			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
+			   sort -u` ;; \
+	esac; \
+	for file in $$dist_files; do \
+	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+	  if test -d $$d/$$file; then \
+	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
+	    fi; \
+	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
+	    fi; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
+	  else \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
+	    || exit 1; \
+	  fi; \
+	done
+	@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
+	  if test "$$subdir" = .; then :; else \
+	    $(am__make_dryrun) \
+	      || test -d "$(distdir)/$$subdir" \
+	      || $(MKDIR_P) "$(distdir)/$$subdir" \
+	      || exit 1; \
+	    dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
+	    $(am__relativize); \
+	    new_distdir=$$reldir; \
+	    dir1=$$subdir; dir2="$(top_distdir)"; \
+	    $(am__relativize); \
+	    new_top_distdir=$$reldir; \
+	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
+	    echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
+	    ($(am__cd) $$subdir && \
+	      $(MAKE) $(AM_MAKEFLAGS) \
+	        top_distdir="$$new_top_distdir" \
+	        distdir="$$new_distdir" \
+		am__remove_distdir=: \
+		am__skip_length_check=: \
+		am__skip_mode_fix=: \
+	        distdir) \
+	      || exit 1; \
+	  fi; \
+	done
+	-test -n "$(am__skip_mode_fix)" \
+	|| find "$(distdir)" -type d ! -perm -755 \
+		-exec chmod u+rwx,go+rx {} \; -o \
+	  ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \
+	  ! -type d ! -perm -400 -exec chmod a+r {} \; -o \
+	  ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \
+	|| chmod -R a+r "$(distdir)"
+dist-gzip: distdir
+	tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz
+	$(am__post_remove_distdir)
+
+dist-bzip2: distdir
+	tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2
+	$(am__post_remove_distdir)
+
+dist-lzip: distdir
+	tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz
+	$(am__post_remove_distdir)
+
+dist-xz: distdir
+	tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz
+	$(am__post_remove_distdir)
+
+dist-tarZ: distdir
+	tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z
+	$(am__post_remove_distdir)
+
+dist-shar: distdir
+	shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz
+	$(am__post_remove_distdir)
+
+dist-zip: distdir
+	-rm -f $(distdir).zip
+	zip -rq $(distdir).zip $(distdir)
+	$(am__post_remove_distdir)
+
+dist dist-all:
+	$(MAKE) $(AM_MAKEFLAGS) $(DIST_TARGETS) am__post_remove_distdir='@:'
+	$(am__post_remove_distdir)
+
+# This target untars the dist file and tries a VPATH configuration.  Then
+# it guarantees that the distribution is self-contained by making another
+# tarfile.
+distcheck: dist
+	case '$(DIST_ARCHIVES)' in \
+	*.tar.gz*) \
+	  GZIP=$(GZIP_ENV) gzip -dc $(distdir).tar.gz | $(am__untar) ;;\
+	*.tar.bz2*) \
+	  bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\
+	*.tar.lz*) \
+	  lzip -dc $(distdir).tar.lz | $(am__untar) ;;\
+	*.tar.xz*) \
+	  xz -dc $(distdir).tar.xz | $(am__untar) ;;\
+	*.tar.Z*) \
+	  uncompress -c $(distdir).tar.Z | $(am__untar) ;;\
+	*.shar.gz*) \
+	  GZIP=$(GZIP_ENV) gzip -dc $(distdir).shar.gz | unshar ;;\
+	*.zip*) \
+	  unzip $(distdir).zip ;;\
+	esac
+	chmod -R a-w $(distdir)
+	chmod u+w $(distdir)
+	mkdir $(distdir)/_build $(distdir)/_inst
+	chmod a-w $(distdir)
+	test -d $(distdir)/_build || exit 0; \
+	dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \
+	  && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \
+	  && am__cwd=`pwd` \
+	  && $(am__cd) $(distdir)/_build \
+	  && ../configure --srcdir=.. --prefix="$$dc_install_base" \
+	    $(AM_DISTCHECK_CONFIGURE_FLAGS) \
+	    $(DISTCHECK_CONFIGURE_FLAGS) \
+	  && $(MAKE) $(AM_MAKEFLAGS) \
+	  && $(MAKE) $(AM_MAKEFLAGS) dvi \
+	  && $(MAKE) $(AM_MAKEFLAGS) check \
+	  && $(MAKE) $(AM_MAKEFLAGS) install \
+	  && $(MAKE) $(AM_MAKEFLAGS) installcheck \
+	  && $(MAKE) $(AM_MAKEFLAGS) uninstall \
+	  && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \
+	        distuninstallcheck \
+	  && chmod -R a-w "$$dc_install_base" \
+	  && ({ \
+	       (cd ../.. && umask 077 && mkdir "$$dc_destdir") \
+	       && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \
+	       && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \
+	       && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \
+	            distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \
+	      } || { rm -rf "$$dc_destdir"; exit 1; }) \
+	  && rm -rf "$$dc_destdir" \
+	  && $(MAKE) $(AM_MAKEFLAGS) dist \
+	  && rm -rf $(DIST_ARCHIVES) \
+	  && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \
+	  && cd "$$am__cwd" \
+	  || exit 1
+	$(am__post_remove_distdir)
+	@(echo "$(distdir) archives ready for distribution: "; \
+	  list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \
+	  sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x'
+distuninstallcheck:
+	@test -n '$(distuninstallcheck_dir)' || { \
+	  echo 'ERROR: trying to run $@ with an empty' \
+	       '$$(distuninstallcheck_dir)' >&2; \
+	  exit 1; \
+	}; \
+	$(am__cd) '$(distuninstallcheck_dir)' || { \
+	  echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \
+	  exit 1; \
+	}; \
+	test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \
+	   || { echo "ERROR: files left after uninstall:" ; \
+	        if test -n "$(DESTDIR)"; then \
+	          echo "  (check DESTDIR support)"; \
+	        fi ; \
+	        $(distuninstallcheck_listfiles) ; \
+	        exit 1; } >&2
+distcleancheck: distclean
+	@if test '$(srcdir)' = . ; then \
+	  echo "ERROR: distcleancheck can only run from a VPATH build" ; \
+	  exit 1 ; \
+	fi
+	@test `$(distcleancheck_listfiles) | wc -l` -eq 0 \
+	  || { echo "ERROR: files left in build directory after distclean:" ; \
+	       $(distcleancheck_listfiles) ; \
+	       exit 1; } >&2
+check-am: all-am
+check: check-recursive
+all-am: Makefile $(LTLIBRARIES) $(HEADERS) config.h
+installdirs: installdirs-recursive
+installdirs-am:
+	for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(pkgincludedir)"; do \
+	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
+	done
+install: install-recursive
+install-exec: install-exec-recursive
+install-data: install-data-recursive
+uninstall: uninstall-recursive
+
+install-am: all-am
+	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-recursive
+install-strip:
+	if test -z '$(STRIP)'; then \
+	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+	      install; \
+	else \
+	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
+	fi
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
+	-test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES)
+
+maintainer-clean-generic:
+	@echo "This command is intended for maintainers to use"
+	@echo "it deletes files that may require special tools to rebuild."
+	-test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES)
+clean: clean-recursive
+
+clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \
+	clean-noinstLTLIBRARIES mostlyclean-am
+
+distclean: distclean-recursive
+	-rm -f $(am__CONFIG_DISTCLEAN_FILES)
+	-rm -rf ./$(DEPDIR)
+	-rm -f Makefile
+distclean-am: clean-am distclean-compile distclean-generic \
+	distclean-hdr distclean-libtool distclean-tags
+
+dvi: dvi-recursive
+
+dvi-am:
+
+html: html-recursive
+
+html-am:
+
+info: info-recursive
+
+info-am:
+
+install-data-am: install-pkgincludeHEADERS
+
+install-dvi: install-dvi-recursive
+
+install-dvi-am:
+
+install-exec-am: install-libLTLIBRARIES
+
+install-html: install-html-recursive
+
+install-html-am:
+
+install-info: install-info-recursive
+
+install-info-am:
+
+install-man:
+
+install-pdf: install-pdf-recursive
+
+install-pdf-am:
+
+install-ps: install-ps-recursive
+
+install-ps-am:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-recursive
+	-rm -f $(am__CONFIG_DISTCLEAN_FILES)
+	-rm -rf $(top_srcdir)/autom4te.cache
+	-rm -rf ./$(DEPDIR)
+	-rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-recursive
+
+mostlyclean-am: mostlyclean-compile mostlyclean-generic \
+	mostlyclean-libtool
+
+pdf: pdf-recursive
+
+pdf-am:
+
+ps: ps-recursive
+
+ps-am:
+
+uninstall-am: uninstall-libLTLIBRARIES uninstall-pkgincludeHEADERS
+
+.MAKE: $(am__recursive_targets) all install-am install-strip
+
+.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \
+	am--refresh check check-am clean clean-cscope clean-generic \
+	clean-libLTLIBRARIES clean-libtool clean-noinstLTLIBRARIES \
+	cscope cscopelist-am ctags ctags-am dist dist-all dist-bzip2 \
+	dist-gzip dist-lzip dist-shar dist-tarZ dist-xz dist-zip \
+	distcheck distclean distclean-compile distclean-generic \
+	distclean-hdr distclean-libtool distclean-tags distcleancheck \
+	distdir distuninstallcheck dvi dvi-am html html-am info \
+	info-am install install-am install-data install-data-am \
+	install-dvi install-dvi-am install-exec install-exec-am \
+	install-html install-html-am install-info install-info-am \
+	install-libLTLIBRARIES install-man install-pdf install-pdf-am \
+	install-pkgincludeHEADERS install-ps install-ps-am \
+	install-strip installcheck installcheck-am installdirs \
+	installdirs-am maintainer-clean maintainer-clean-generic \
+	mostlyclean mostlyclean-compile mostlyclean-generic \
+	mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \
+	uninstall-am uninstall-libLTLIBRARIES \
+	uninstall-pkgincludeHEADERS
+
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/hdrl/acinclude.m4 b/hdrl/acinclude.m4
new file mode 100644
index 0000000..cf87017
--- /dev/null
+++ b/hdrl/acinclude.m4
@@ -0,0 +1,99 @@
+# on SL6 aclocal 1.11 doesn't check this folder even though its in
+# AC_CONFIG_MACRO_DIR. Fixed in later aclocal versions
+m4_include([m4macros/cpl.m4])
+m4_include([m4macros/eso.m4])
+m4_include([m4macros/purify.m4])
+
+# HDRL_SET_VERSION_INFO(VERSION, [CURRENT], [REVISION], [AGE])
+#----------------------------------------------------------------
+# Setup various version information, especially the libtool versioning
+AC_DEFUN([HDRL_SET_VERSION_INFO],
+[
+    hdrldemo_version=`echo "$1" | sed -e 's/[[a-z,A-Z]].*$//'`
+
+    hdrldemo_major_version=`echo "$hdrldemo_version" | \
+        sed 's/\([[0-9]]*\).\(.*\)/\1/'`
+    hdrldemo_minor_version=`echo "$hdrldemo_version" | \
+        sed 's/\([[0-9]]*\).\([[0-9]]*\)\(.*\)/\2/'`
+    hdrldemo_micro_version=`echo "$hdrldemo_version" | \
+        sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'`
+
+    if test -z "$hdrldemo_major_version"; then hdrldemo_major_version=0
+    fi
+
+    if test -z "$hdrldemo_minor_version"; then hdrldemo_minor_version=0
+    fi
+
+    if test -z "$hdrldemo_micro_version"; then hdrldemo_micro_version=0
+    fi
+
+    HDRL_VERSION="$hdrldemo_version"
+    HDRL_MAJOR_VERSION=$hdrldemo_major_version
+    HDRL_MINOR_VERSION=$hdrldemo_minor_version
+    HDRL_MICRO_VERSION=$hdrldemo_micro_version
+
+    if test -z "$4"; then HDRL_INTERFACE_AGE=0
+    else HDRL_INTERFACE_AGE="$4"
+    fi
+
+    HDRL_BINARY_AGE=`expr 100 '*' $HDRL_MINOR_VERSION + $HDRL_MICRO_VERSION`
+    HDRL_BINARY_VERSION=`expr 10000 '*' $HDRL_MAJOR_VERSION + \
+                          $HDRL_BINARY_AGE`
+
+    AC_SUBST(HDRL_VERSION)
+    AC_SUBST(HDRL_MAJOR_VERSION)
+    AC_SUBST(HDRL_MINOR_VERSION)
+    AC_SUBST(HDRL_MICRO_VERSION)
+    AC_SUBST(HDRL_INTERFACE_AGE)
+    AC_SUBST(HDRL_BINARY_VERSION)
+    AC_SUBST(HDRL_BINARY_AGE)
+
+    AC_DEFINE_UNQUOTED(HDRL_MAJOR_VERSION, $HDRL_MAJOR_VERSION,
+                       [HDRL major version number])
+    AC_DEFINE_UNQUOTED(HDRL_MINOR_VERSION, $HDRL_MINOR_VERSION,
+                       [HDRL minor version number])
+    AC_DEFINE_UNQUOTED(HDRL_MICRO_VERSION, $HDRL_MICRO_VERSION,
+                       [HDRL micro version number])
+    AC_DEFINE_UNQUOTED(HDRL_INTERFACE_AGE, $HDRL_INTERFACE_AGE,
+                       [HDRL interface age])
+    AC_DEFINE_UNQUOTED(HDRL_BINARY_VERSION, $HDRL_BINARY_VERSION,
+                       [HDRL binary version number])
+    AC_DEFINE_UNQUOTED(HDRL_BINARY_AGE, $HDRL_BINARY_AGE,
+                       [HDRL binary age])
+
+    ESO_SET_LIBRARY_VERSION([$2], [$3], [$4])
+])
+
+
+# HDRL_CREATE_SYMBOLS
+#-----------------------
+# Define include and library related makefile symbols
+AC_DEFUN([HDRL_CREATE_SYMBOLS],
+[
+
+    # Symbols for package include file and library search paths
+
+    HDRL_INCLUDES='-I$(top_srcdir)'
+    HDRL_LDFLAGS='-L$(top_builddir)'
+
+    # Library aliases
+
+    LIBHDRL='$(top_builddir)/libhdrl.la'
+
+    # Substitute the defined symbols
+
+    AC_SUBST(HDRL_INCLUDES)
+    AC_SUBST(HDRL_LDFLAGS)
+
+    AC_SUBST(LIBHDRL)
+    AC_SUBST(LIBHDRL)
+
+    # Check for CPL and user defined libraries
+    AC_REQUIRE([CPL_CHECK_LIBS])
+
+    all_includes='$(HDRL_INCLUDES) $(CPL_INCLUDES)'
+    all_ldflags='$(HDRL_LDFLAGS) $(CPL_LDFLAGS)'
+
+    AC_SUBST(all_includes)
+    AC_SUBST(all_ldflags)
+])
diff --git a/aclocal.m4 b/hdrl/aclocal.m4
similarity index 99%
copy from aclocal.m4
copy to hdrl/aclocal.m4
index 8aaed40..45925d8 100644
--- a/aclocal.m4
+++ b/hdrl/aclocal.m4
@@ -1128,13 +1128,9 @@ AC_SUBST([am__tar])
 AC_SUBST([am__untar])
 ]) # _AM_PROG_TAR
 
-m4_include([m4macros/cpl.m4])
-m4_include([m4macros/eso.m4])
-m4_include([m4macros/gsl.m4])
 m4_include([m4macros/libtool.m4])
 m4_include([m4macros/ltoptions.m4])
 m4_include([m4macros/ltsugar.m4])
 m4_include([m4macros/ltversion.m4])
 m4_include([m4macros/lt~obsolete.m4])
-m4_include([m4macros/purify.m4])
 m4_include([acinclude.m4])
diff --git a/hdrl/admin/compile b/hdrl/admin/compile
new file mode 100755
index 0000000..531136b
--- /dev/null
+++ b/hdrl/admin/compile
@@ -0,0 +1,347 @@
+#! /bin/sh
+# Wrapper for compilers which do not understand '-c -o'.
+
+scriptversion=2012-10-14.11; # UTC
+
+# Copyright (C) 1999-2013 Free Software Foundation, Inc.
+# Written by Tom Tromey <tromey at cygnus.com>.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2, or (at your option)
+# any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# This file is maintained in Automake, please report
+# bugs to <bug-automake at gnu.org> or send patches to
+# <automake-patches at gnu.org>.
+
+nl='
+'
+
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent tools from complaining about whitespace usage.
+IFS=" ""	$nl"
+
+file_conv=
+
+# func_file_conv build_file lazy
+# Convert a $build file to $host form and store it in $file
+# Currently only supports Windows hosts. If the determined conversion
+# type is listed in (the comma separated) LAZY, no conversion will
+# take place.
+func_file_conv ()
+{
+  file=$1
+  case $file in
+    / | /[!/]*) # absolute file, and not a UNC file
+      if test -z "$file_conv"; then
+	# lazily determine how to convert abs files
+	case `uname -s` in
+	  MINGW*)
+	    file_conv=mingw
+	    ;;
+	  CYGWIN*)
+	    file_conv=cygwin
+	    ;;
+	  *)
+	    file_conv=wine
+	    ;;
+	esac
+      fi
+      case $file_conv/,$2, in
+	*,$file_conv,*)
+	  ;;
+	mingw/*)
+	  file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'`
+	  ;;
+	cygwin/*)
+	  file=`cygpath -m "$file" || echo "$file"`
+	  ;;
+	wine/*)
+	  file=`winepath -w "$file" || echo "$file"`
+	  ;;
+      esac
+      ;;
+  esac
+}
+
+# func_cl_dashL linkdir
+# Make cl look for libraries in LINKDIR
+func_cl_dashL ()
+{
+  func_file_conv "$1"
+  if test -z "$lib_path"; then
+    lib_path=$file
+  else
+    lib_path="$lib_path;$file"
+  fi
+  linker_opts="$linker_opts -LIBPATH:$file"
+}
+
+# func_cl_dashl library
+# Do a library search-path lookup for cl
+func_cl_dashl ()
+{
+  lib=$1
+  found=no
+  save_IFS=$IFS
+  IFS=';'
+  for dir in $lib_path $LIB
+  do
+    IFS=$save_IFS
+    if $shared && test -f "$dir/$lib.dll.lib"; then
+      found=yes
+      lib=$dir/$lib.dll.lib
+      break
+    fi
+    if test -f "$dir/$lib.lib"; then
+      found=yes
+      lib=$dir/$lib.lib
+      break
+    fi
+    if test -f "$dir/lib$lib.a"; then
+      found=yes
+      lib=$dir/lib$lib.a
+      break
+    fi
+  done
+  IFS=$save_IFS
+
+  if test "$found" != yes; then
+    lib=$lib.lib
+  fi
+}
+
+# func_cl_wrapper cl arg...
+# Adjust compile command to suit cl
+func_cl_wrapper ()
+{
+  # Assume a capable shell
+  lib_path=
+  shared=:
+  linker_opts=
+  for arg
+  do
+    if test -n "$eat"; then
+      eat=
+    else
+      case $1 in
+	-o)
+	  # configure might choose to run compile as 'compile cc -o foo foo.c'.
+	  eat=1
+	  case $2 in
+	    *.o | *.[oO][bB][jJ])
+	      func_file_conv "$2"
+	      set x "$@" -Fo"$file"
+	      shift
+	      ;;
+	    *)
+	      func_file_conv "$2"
+	      set x "$@" -Fe"$file"
+	      shift
+	      ;;
+	  esac
+	  ;;
+	-I)
+	  eat=1
+	  func_file_conv "$2" mingw
+	  set x "$@" -I"$file"
+	  shift
+	  ;;
+	-I*)
+	  func_file_conv "${1#-I}" mingw
+	  set x "$@" -I"$file"
+	  shift
+	  ;;
+	-l)
+	  eat=1
+	  func_cl_dashl "$2"
+	  set x "$@" "$lib"
+	  shift
+	  ;;
+	-l*)
+	  func_cl_dashl "${1#-l}"
+	  set x "$@" "$lib"
+	  shift
+	  ;;
+	-L)
+	  eat=1
+	  func_cl_dashL "$2"
+	  ;;
+	-L*)
+	  func_cl_dashL "${1#-L}"
+	  ;;
+	-static)
+	  shared=false
+	  ;;
+	-Wl,*)
+	  arg=${1#-Wl,}
+	  save_ifs="$IFS"; IFS=','
+	  for flag in $arg; do
+	    IFS="$save_ifs"
+	    linker_opts="$linker_opts $flag"
+	  done
+	  IFS="$save_ifs"
+	  ;;
+	-Xlinker)
+	  eat=1
+	  linker_opts="$linker_opts $2"
+	  ;;
+	-*)
+	  set x "$@" "$1"
+	  shift
+	  ;;
+	*.cc | *.CC | *.cxx | *.CXX | *.[cC]++)
+	  func_file_conv "$1"
+	  set x "$@" -Tp"$file"
+	  shift
+	  ;;
+	*.c | *.cpp | *.CPP | *.lib | *.LIB | *.Lib | *.OBJ | *.obj | *.[oO])
+	  func_file_conv "$1" mingw
+	  set x "$@" "$file"
+	  shift
+	  ;;
+	*)
+	  set x "$@" "$1"
+	  shift
+	  ;;
+      esac
+    fi
+    shift
+  done
+  if test -n "$linker_opts"; then
+    linker_opts="-link$linker_opts"
+  fi
+  exec "$@" $linker_opts
+  exit 1
+}
+
+eat=
+
+case $1 in
+  '')
+     echo "$0: No command.  Try '$0 --help' for more information." 1>&2
+     exit 1;
+     ;;
+  -h | --h*)
+    cat <<\EOF
+Usage: compile [--help] [--version] PROGRAM [ARGS]
+
+Wrapper for compilers which do not understand '-c -o'.
+Remove '-o dest.o' from ARGS, run PROGRAM with the remaining
+arguments, and rename the output as expected.
+
+If you are trying to build a whole package this is not the
+right script to run: please start by reading the file 'INSTALL'.
+
+Report bugs to <bug-automake at gnu.org>.
+EOF
+    exit $?
+    ;;
+  -v | --v*)
+    echo "compile $scriptversion"
+    exit $?
+    ;;
+  cl | *[/\\]cl | cl.exe | *[/\\]cl.exe )
+    func_cl_wrapper "$@"      # Doesn't return...
+    ;;
+esac
+
+ofile=
+cfile=
+
+for arg
+do
+  if test -n "$eat"; then
+    eat=
+  else
+    case $1 in
+      -o)
+	# configure might choose to run compile as 'compile cc -o foo foo.c'.
+	# So we strip '-o arg' only if arg is an object.
+	eat=1
+	case $2 in
+	  *.o | *.obj)
+	    ofile=$2
+	    ;;
+	  *)
+	    set x "$@" -o "$2"
+	    shift
+	    ;;
+	esac
+	;;
+      *.c)
+	cfile=$1
+	set x "$@" "$1"
+	shift
+	;;
+      *)
+	set x "$@" "$1"
+	shift
+	;;
+    esac
+  fi
+  shift
+done
+
+if test -z "$ofile" || test -z "$cfile"; then
+  # If no '-o' option was seen then we might have been invoked from a
+  # pattern rule where we don't need one.  That is ok -- this is a
+  # normal compilation that the losing compiler can handle.  If no
+  # '.c' file was seen then we are probably linking.  That is also
+  # ok.
+  exec "$@"
+fi
+
+# Name of file we expect compiler to create.
+cofile=`echo "$cfile" | sed 's|^.*[\\/]||; s|^[a-zA-Z]:||; s/\.c$/.o/'`
+
+# Create the lock directory.
+# Note: use '[/\\:.-]' here to ensure that we don't use the same name
+# that we are using for the .o file.  Also, base the name on the expected
+# object file name, since that is what matters with a parallel build.
+lockdir=`echo "$cofile" | sed -e 's|[/\\:.-]|_|g'`.d
+while true; do
+  if mkdir "$lockdir" >/dev/null 2>&1; then
+    break
+  fi
+  sleep 1
+done
+# FIXME: race condition here if user kills between mkdir and trap.
+trap "rmdir '$lockdir'; exit 1" 1 2 15
+
+# Run the compile.
+"$@"
+ret=$?
+
+if test -f "$cofile"; then
+  test "$cofile" = "$ofile" || mv "$cofile" "$ofile"
+elif test -f "${cofile}bj"; then
+  test "${cofile}bj" = "$ofile" || mv "${cofile}bj" "$ofile"
+fi
+
+rmdir "$lockdir"
+exit $ret
+
+# Local Variables:
+# mode: shell-script
+# sh-indentation: 2
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
+# End:
diff --git a/admin/config.guess b/hdrl/admin/config.guess
similarity index 88%
copy from admin/config.guess
copy to hdrl/admin/config.guess
index 1804e9f..1f5c50c 100755
--- a/admin/config.guess
+++ b/hdrl/admin/config.guess
@@ -1,10 +1,8 @@
 #! /bin/sh
 # Attempt to guess a canonical system name.
-#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
-#   2011, 2012, 2013 Free Software Foundation, Inc.
+#   Copyright 1992-2014 Free Software Foundation, Inc.
 
-timestamp='2012-12-29'
+timestamp='2014-03-23'
 
 # This file is free software; you can redistribute it and/or modify it
 # under the terms of the GNU General Public License as published by
@@ -26,7 +24,7 @@ timestamp='2012-12-29'
 # program.  This Exception is an additional permission under section 7
 # of the GNU General Public License, version 3 ("GPLv3").
 #
-# Originally written by Per Bothner. 
+# Originally written by Per Bothner.
 #
 # You can get the latest version of this script from:
 # http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
@@ -52,9 +50,7 @@ version="\
 GNU config.guess ($timestamp)
 
 Originally written by Per Bothner.
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011,
-2012, 2013 Free Software Foundation, Inc.
+Copyright 1992-2014 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
@@ -136,6 +132,27 @@ UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
 UNAME_SYSTEM=`(uname -s) 2>/dev/null`  || UNAME_SYSTEM=unknown
 UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
 
+case "${UNAME_SYSTEM}" in
+Linux|GNU|GNU/*)
+	# If the system lacks a compiler, then just pick glibc.
+	# We could probably try harder.
+	LIBC=gnu
+
+	eval $set_cc_for_build
+	cat <<-EOF > $dummy.c
+	#include <features.h>
+	#if defined(__UCLIBC__)
+	LIBC=uclibc
+	#elif defined(__dietlibc__)
+	LIBC=dietlibc
+	#else
+	LIBC=gnu
+	#endif
+	EOF
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC' | sed 's, ,,g'`
+	;;
+esac
+
 # Note: order is significant - the case branches are not exclusive.
 
 case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
@@ -809,7 +826,7 @@ EOF
     *:MINGW*:*)
 	echo ${UNAME_MACHINE}-pc-mingw32
 	exit ;;
-    i*:MSYS*:*)
+    *:MSYS*:*)
 	echo ${UNAME_MACHINE}-pc-msys
 	exit ;;
     i*:windows32*:*)
@@ -857,21 +874,21 @@ EOF
 	exit ;;
     *:GNU:*:*)
 	# the GNU system
-	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
+	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
 	exit ;;
     *:GNU/*:*:*)
 	# other systems with GNU libc and userland
-	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu
+	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC}
 	exit ;;
     i*86:Minix:*:*)
 	echo ${UNAME_MACHINE}-pc-minix
 	exit ;;
     aarch64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     aarch64_be:Linux:*:*)
 	UNAME_MACHINE=aarch64_be
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     alpha:Linux:*:*)
 	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
@@ -884,59 +901,54 @@ EOF
 	  EV68*) UNAME_MACHINE=alphaev68 ;;
 	esac
 	objdump --private-headers /bin/sh | grep -q ld.so.1
-	if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
-	echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
+	if test "$?" = 0 ; then LIBC="gnulibc1" ; fi
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    arc:Linux:*:* | arceb:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     arm*:Linux:*:*)
 	eval $set_cc_for_build
 	if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
 	    | grep -q __ARM_EABI__
 	then
-	    echo ${UNAME_MACHINE}-unknown-linux-gnu
+	    echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	else
 	    if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \
 		| grep -q __ARM_PCS_VFP
 	    then
-		echo ${UNAME_MACHINE}-unknown-linux-gnueabi
+		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi
 	    else
-		echo ${UNAME_MACHINE}-unknown-linux-gnueabihf
+		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf
 	    fi
 	fi
 	exit ;;
     avr32*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     cris:Linux:*:*)
-	echo ${UNAME_MACHINE}-axis-linux-gnu
+	echo ${UNAME_MACHINE}-axis-linux-${LIBC}
 	exit ;;
     crisv32:Linux:*:*)
-	echo ${UNAME_MACHINE}-axis-linux-gnu
+	echo ${UNAME_MACHINE}-axis-linux-${LIBC}
 	exit ;;
     frv:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     hexagon:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     i*86:Linux:*:*)
-	LIBC=gnu
-	eval $set_cc_for_build
-	sed 's/^	//' << EOF >$dummy.c
-	#ifdef __dietlibc__
-	LIBC=dietlibc
-	#endif
-EOF
-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'`
-	echo "${UNAME_MACHINE}-pc-linux-${LIBC}"
+	echo ${UNAME_MACHINE}-pc-linux-${LIBC}
 	exit ;;
     ia64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     m32r*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     m68*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     mips:Linux:*:* | mips64:Linux:*:*)
 	eval $set_cc_for_build
@@ -955,54 +967,63 @@ EOF
 	#endif
 EOF
 	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
-	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
+	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; }
 	;;
-    or32:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+    openrisc*:Linux:*:*)
+	echo or1k-unknown-linux-${LIBC}
+	exit ;;
+    or32:Linux:*:* | or1k*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     padre:Linux:*:*)
-	echo sparc-unknown-linux-gnu
+	echo sparc-unknown-linux-${LIBC}
 	exit ;;
     parisc64:Linux:*:* | hppa64:Linux:*:*)
-	echo hppa64-unknown-linux-gnu
+	echo hppa64-unknown-linux-${LIBC}
 	exit ;;
     parisc:Linux:*:* | hppa:Linux:*:*)
 	# Look for CPU level
 	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
-	  PA7*) echo hppa1.1-unknown-linux-gnu ;;
-	  PA8*) echo hppa2.0-unknown-linux-gnu ;;
-	  *)    echo hppa-unknown-linux-gnu ;;
+	  PA7*) echo hppa1.1-unknown-linux-${LIBC} ;;
+	  PA8*) echo hppa2.0-unknown-linux-${LIBC} ;;
+	  *)    echo hppa-unknown-linux-${LIBC} ;;
 	esac
 	exit ;;
     ppc64:Linux:*:*)
-	echo powerpc64-unknown-linux-gnu
+	echo powerpc64-unknown-linux-${LIBC}
 	exit ;;
     ppc:Linux:*:*)
-	echo powerpc-unknown-linux-gnu
+	echo powerpc-unknown-linux-${LIBC}
+	exit ;;
+    ppc64le:Linux:*:*)
+	echo powerpc64le-unknown-linux-${LIBC}
+	exit ;;
+    ppcle:Linux:*:*)
+	echo powerpcle-unknown-linux-${LIBC}
 	exit ;;
     s390:Linux:*:* | s390x:Linux:*:*)
-	echo ${UNAME_MACHINE}-ibm-linux
+	echo ${UNAME_MACHINE}-ibm-linux-${LIBC}
 	exit ;;
     sh64*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     sh*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     sparc:Linux:*:* | sparc64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     tile*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     vax:Linux:*:*)
-	echo ${UNAME_MACHINE}-dec-linux-gnu
+	echo ${UNAME_MACHINE}-dec-linux-${LIBC}
 	exit ;;
     x86_64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     xtensa*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     i*86:DYNIX/ptx:4*:*)
 	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
@@ -1235,19 +1256,31 @@ EOF
 	exit ;;
     *:Darwin:*:*)
 	UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
-	case $UNAME_PROCESSOR in
-	    i386)
-		eval $set_cc_for_build
-		if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
-		  if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
-		      (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
-		      grep IS_64BIT_ARCH >/dev/null
-		  then
-		      UNAME_PROCESSOR="x86_64"
-		  fi
-		fi ;;
-	    unknown) UNAME_PROCESSOR=powerpc ;;
-	esac
+	eval $set_cc_for_build
+	if test "$UNAME_PROCESSOR" = unknown ; then
+	    UNAME_PROCESSOR=powerpc
+	fi
+	if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then
+	    if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+		if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
+		    (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+		    grep IS_64BIT_ARCH >/dev/null
+		then
+		    case $UNAME_PROCESSOR in
+			i386) UNAME_PROCESSOR=x86_64 ;;
+			powerpc) UNAME_PROCESSOR=powerpc64 ;;
+		    esac
+		fi
+	    fi
+	elif test "$UNAME_PROCESSOR" = i386 ; then
+	    # Avoid executing cc on OS X 10.9, as it ships with a stub
+	    # that puts up a graphical alert prompting to install
+	    # developer tools.  Any system running Mac OS X 10.7 or
+	    # later (Darwin 11 and later) is required to have a 64-bit
+	    # processor. This is not true of the ARM version of Darwin
+	    # that Apple uses in portable devices.
+	    UNAME_PROCESSOR=x86_64
+	fi
 	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
 	exit ;;
     *:procnto*:*:* | *:QNX:[0123456789]*:*)
@@ -1338,154 +1371,6 @@ EOF
 	exit ;;
 esac
 
-eval $set_cc_for_build
-cat >$dummy.c <<EOF
-#ifdef _SEQUENT_
-# include <sys/types.h>
-# include <sys/utsname.h>
-#endif
-main ()
-{
-#if defined (sony)
-#if defined (MIPSEB)
-  /* BFD wants "bsd" instead of "newsos".  Perhaps BFD should be changed,
-     I don't know....  */
-  printf ("mips-sony-bsd\n"); exit (0);
-#else
-#include <sys/param.h>
-  printf ("m68k-sony-newsos%s\n",
-#ifdef NEWSOS4
-	"4"
-#else
-	""
-#endif
-	); exit (0);
-#endif
-#endif
-
-#if defined (__arm) && defined (__acorn) && defined (__unix)
-  printf ("arm-acorn-riscix\n"); exit (0);
-#endif
-
-#if defined (hp300) && !defined (hpux)
-  printf ("m68k-hp-bsd\n"); exit (0);
-#endif
-
-#if defined (NeXT)
-#if !defined (__ARCHITECTURE__)
-#define __ARCHITECTURE__ "m68k"
-#endif
-  int version;
-  version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
-  if (version < 4)
-    printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
-  else
-    printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
-  exit (0);
-#endif
-
-#if defined (MULTIMAX) || defined (n16)
-#if defined (UMAXV)
-  printf ("ns32k-encore-sysv\n"); exit (0);
-#else
-#if defined (CMU)
-  printf ("ns32k-encore-mach\n"); exit (0);
-#else
-  printf ("ns32k-encore-bsd\n"); exit (0);
-#endif
-#endif
-#endif
-
-#if defined (__386BSD__)
-  printf ("i386-pc-bsd\n"); exit (0);
-#endif
-
-#if defined (sequent)
-#if defined (i386)
-  printf ("i386-sequent-dynix\n"); exit (0);
-#endif
-#if defined (ns32000)
-  printf ("ns32k-sequent-dynix\n"); exit (0);
-#endif
-#endif
-
-#if defined (_SEQUENT_)
-    struct utsname un;
-
-    uname(&un);
-
-    if (strncmp(un.version, "V2", 2) == 0) {
-	printf ("i386-sequent-ptx2\n"); exit (0);
-    }
-    if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
-	printf ("i386-sequent-ptx1\n"); exit (0);
-    }
-    printf ("i386-sequent-ptx\n"); exit (0);
-
-#endif
-
-#if defined (vax)
-# if !defined (ultrix)
-#  include <sys/param.h>
-#  if defined (BSD)
-#   if BSD == 43
-      printf ("vax-dec-bsd4.3\n"); exit (0);
-#   else
-#    if BSD == 199006
-      printf ("vax-dec-bsd4.3reno\n"); exit (0);
-#    else
-      printf ("vax-dec-bsd\n"); exit (0);
-#    endif
-#   endif
-#  else
-    printf ("vax-dec-bsd\n"); exit (0);
-#  endif
-# else
-    printf ("vax-dec-ultrix\n"); exit (0);
-# endif
-#endif
-
-#if defined (alliant) && defined (i860)
-  printf ("i860-alliant-bsd\n"); exit (0);
-#endif
-
-  exit (1);
-}
-EOF
-
-$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` &&
-	{ echo "$SYSTEM_NAME"; exit; }
-
-# Apollos put the system type in the environment.
-
-test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; }
-
-# Convex versions that predate uname can use getsysinfo(1)
-
-if [ -x /usr/convex/getsysinfo ]
-then
-    case `getsysinfo -f cpu_type` in
-    c1*)
-	echo c1-convex-bsd
-	exit ;;
-    c2*)
-	if getsysinfo -f scalar_acc
-	then echo c32-convex-bsd
-	else echo c2-convex-bsd
-	fi
-	exit ;;
-    c34*)
-	echo c34-convex-bsd
-	exit ;;
-    c38*)
-	echo c38-convex-bsd
-	exit ;;
-    c4*)
-	echo c4-convex-bsd
-	exit ;;
-    esac
-fi
-
 cat >&2 <<EOF
 $0: unable to guess system type
 
diff --git a/admin/config.sub b/hdrl/admin/config.sub
similarity index 97%
copy from admin/config.sub
copy to hdrl/admin/config.sub
index 52f04bc..66c5074 100755
--- a/admin/config.sub
+++ b/hdrl/admin/config.sub
@@ -1,10 +1,8 @@
 #! /bin/sh
 # Configuration validation subroutine script.
-#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
-#   2011, 2012, 2013 Free Software Foundation, Inc.
+#   Copyright 1992-2014 Free Software Foundation, Inc.
 
-timestamp='2012-12-29'
+timestamp='2014-07-28'
 
 # This file is free software; you can redistribute it and/or modify it
 # under the terms of the GNU General Public License as published by
@@ -70,9 +68,7 @@ Report bugs and patches to <config-patches at gnu.org>."
 version="\
 GNU config.sub ($timestamp)
 
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011,
-2012, 2013 Free Software Foundation, Inc.
+Copyright 1992-2014 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
@@ -256,12 +252,12 @@ case $basic_machine in
 	| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
 	| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
 	| am33_2.0 \
-	| arc \
+	| arc | arceb \
 	| arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \
 	| avr | avr32 \
 	| be32 | be64 \
 	| bfin \
-	| c4x | clipper \
+	| c4x | c8051 | clipper \
 	| d10v | d30v | dlx | dsp16xx \
 	| epiphany \
 	| fido | fr30 | frv \
@@ -269,6 +265,7 @@ case $basic_machine in
 	| hexagon \
 	| i370 | i860 | i960 | ia64 \
 	| ip2k | iq2000 \
+	| k1om \
 	| le32 | le64 \
 	| lm32 \
 	| m32c | m32r | m32rle | m68000 | m68k | m88k \
@@ -286,20 +283,22 @@ case $basic_machine in
 	| mips64vr5900 | mips64vr5900el \
 	| mipsisa32 | mipsisa32el \
 	| mipsisa32r2 | mipsisa32r2el \
+	| mipsisa32r6 | mipsisa32r6el \
 	| mipsisa64 | mipsisa64el \
 	| mipsisa64r2 | mipsisa64r2el \
+	| mipsisa64r6 | mipsisa64r6el \
 	| mipsisa64sb1 | mipsisa64sb1el \
 	| mipsisa64sr71k | mipsisa64sr71kel \
+	| mipsr5900 | mipsr5900el \
 	| mipstx39 | mipstx39el \
 	| mn10200 | mn10300 \
 	| moxie \
 	| mt \
 	| msp430 \
 	| nds32 | nds32le | nds32be \
-	| nios | nios2 \
+	| nios | nios2 | nios2eb | nios2el \
 	| ns16k | ns32k \
-	| open8 \
-	| or32 \
+	| open8 | or1k | or1knd | or32 \
 	| pdp10 | pdp11 | pj | pjl \
 	| powerpc | powerpc64 | powerpc64le | powerpcle \
 	| pyramid \
@@ -327,7 +326,7 @@ case $basic_machine in
 	c6x)
 		basic_machine=tic6x-unknown
 		;;
-	m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | picochip)
+	m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | nvptx | picochip)
 		basic_machine=$basic_machine-unknown
 		os=-none
 		;;
@@ -369,13 +368,13 @@ case $basic_machine in
 	| aarch64-* | aarch64_be-* \
 	| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
 	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
-	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
+	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \
 	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
 	| avr-* | avr32-* \
 	| be32-* | be64-* \
 	| bfin-* | bs2000-* \
 	| c[123]* | c30-* | [cjt]90-* | c4x-* \
-	| clipper-* | craynv-* | cydra-* \
+	| c8051-* | clipper-* | craynv-* | cydra-* \
 	| d10v-* | d30v-* | dlx-* \
 	| elxsi-* \
 	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
@@ -384,6 +383,7 @@ case $basic_machine in
 	| hexagon-* \
 	| i*86-* | i860-* | i960-* | ia64-* \
 	| ip2k-* | iq2000-* \
+	| k1om-* \
 	| le32-* | le64-* \
 	| lm32-* \
 	| m32c-* | m32r-* | m32rle-* \
@@ -403,18 +403,22 @@ case $basic_machine in
 	| mips64vr5900-* | mips64vr5900el-* \
 	| mipsisa32-* | mipsisa32el-* \
 	| mipsisa32r2-* | mipsisa32r2el-* \
+	| mipsisa32r6-* | mipsisa32r6el-* \
 	| mipsisa64-* | mipsisa64el-* \
 	| mipsisa64r2-* | mipsisa64r2el-* \
+	| mipsisa64r6-* | mipsisa64r6el-* \
 	| mipsisa64sb1-* | mipsisa64sb1el-* \
 	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
+	| mipsr5900-* | mipsr5900el-* \
 	| mipstx39-* | mipstx39el-* \
 	| mmix-* \
 	| mt-* \
 	| msp430-* \
 	| nds32-* | nds32le-* | nds32be-* \
-	| nios-* | nios2-* \
+	| nios-* | nios2-* | nios2eb-* | nios2el-* \
 	| none-* | np1-* | ns16k-* | ns32k-* \
 	| open8-* \
+	| or1k*-* \
 	| orion-* \
 	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
 	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
@@ -796,7 +800,7 @@ case $basic_machine in
 		os=-mingw64
 		;;
 	mingw32)
-		basic_machine=i386-pc
+		basic_machine=i686-pc
 		os=-mingw32
 		;;
 	mingw32ce)
@@ -824,6 +828,10 @@ case $basic_machine in
 		basic_machine=powerpc-unknown
 		os=-morphos
 		;;
+	moxiebox)
+		basic_machine=moxie-unknown
+		os=-moxiebox
+		;;
 	msdos)
 		basic_machine=i386-pc
 		os=-msdos
@@ -832,7 +840,7 @@ case $basic_machine in
 		basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
 		;;
 	msys)
-		basic_machine=i386-pc
+		basic_machine=i686-pc
 		os=-msys
 		;;
 	mvs)
@@ -1354,7 +1362,7 @@ case $os in
 	-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
 	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\
 	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
-	      | -sym* | -kopensolaris* \
+	      | -sym* | -kopensolaris* | -plan9* \
 	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
 	      | -aos* | -aros* \
 	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
@@ -1369,14 +1377,14 @@ case $os in
 	      | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
 	      | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
 	      | -linux-newlib* | -linux-musl* | -linux-uclibc* \
-	      | -uxpv* | -beos* | -mpeix* | -udk* \
+	      | -uxpv* | -beos* | -mpeix* | -udk* | -moxiebox* \
 	      | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
 	      | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
 	      | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
 	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
 	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
 	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
-	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*)
+	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* | -tirtos*)
 	# Remember, each alternative MUST END IN *, to match a version number.
 		;;
 	-qnx*)
@@ -1500,9 +1508,6 @@ case $os in
 	-aros*)
 		os=-aros
 		;;
-	-kaos*)
-		os=-kaos
-		;;
 	-zvmoe)
 		os=-zvmoe
 		;;
@@ -1551,6 +1556,9 @@ case $basic_machine in
 	c4x-* | tic4x-*)
 		os=-coff
 		;;
+	c8051-*)
+		os=-elf
+		;;
 	hexagon-*)
 		os=-elf
 		;;
diff --git a/hdrl/admin/depcomp b/hdrl/admin/depcomp
new file mode 100755
index 0000000..4ebd5b3
--- /dev/null
+++ b/hdrl/admin/depcomp
@@ -0,0 +1,791 @@
+#! /bin/sh
+# depcomp - compile a program generating dependencies as side-effects
+
+scriptversion=2013-05-30.07; # UTC
+
+# Copyright (C) 1999-2013 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2, or (at your option)
+# any later version.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# Originally written by Alexandre Oliva <oliva at dcc.unicamp.br>.
+
+case $1 in
+  '')
+    echo "$0: No command.  Try '$0 --help' for more information." 1>&2
+    exit 1;
+    ;;
+  -h | --h*)
+    cat <<\EOF
+Usage: depcomp [--help] [--version] PROGRAM [ARGS]
+
+Run PROGRAMS ARGS to compile a file, generating dependencies
+as side-effects.
+
+Environment variables:
+  depmode     Dependency tracking mode.
+  source      Source file read by 'PROGRAMS ARGS'.
+  object      Object file output by 'PROGRAMS ARGS'.
+  DEPDIR      directory where to store dependencies.
+  depfile     Dependency file to output.
+  tmpdepfile  Temporary file to use when outputting dependencies.
+  libtool     Whether libtool is used (yes/no).
+
+Report bugs to <bug-automake at gnu.org>.
+EOF
+    exit $?
+    ;;
+  -v | --v*)
+    echo "depcomp $scriptversion"
+    exit $?
+    ;;
+esac
+
+# Get the directory component of the given path, and save it in the
+# global variables '$dir'.  Note that this directory component will
+# be either empty or ending with a '/' character.  This is deliberate.
+set_dir_from ()
+{
+  case $1 in
+    */*) dir=`echo "$1" | sed -e 's|/[^/]*$|/|'`;;
+      *) dir=;;
+  esac
+}
+
+# Get the suffix-stripped basename of the given path, and save it the
+# global variable '$base'.
+set_base_from ()
+{
+  base=`echo "$1" | sed -e 's|^.*/||' -e 's/\.[^.]*$//'`
+}
+
+# If no dependency file was actually created by the compiler invocation,
+# we still have to create a dummy depfile, to avoid errors with the
+# Makefile "include basename.Plo" scheme.
+make_dummy_depfile ()
+{
+  echo "#dummy" > "$depfile"
+}
+
+# Factor out some common post-processing of the generated depfile.
+# Requires the auxiliary global variable '$tmpdepfile' to be set.
+aix_post_process_depfile ()
+{
+  # If the compiler actually managed to produce a dependency file,
+  # post-process it.
+  if test -f "$tmpdepfile"; then
+    # Each line is of the form 'foo.o: dependency.h'.
+    # Do two passes, one to just change these to
+    #   $object: dependency.h
+    # and one to simply output
+    #   dependency.h:
+    # which is needed to avoid the deleted-header problem.
+    { sed -e "s,^.*\.[$lower]*:,$object:," < "$tmpdepfile"
+      sed -e "s,^.*\.[$lower]*:[$tab ]*,," -e 's,$,:,' < "$tmpdepfile"
+    } > "$depfile"
+    rm -f "$tmpdepfile"
+  else
+    make_dummy_depfile
+  fi
+}
+
+# A tabulation character.
+tab='	'
+# A newline character.
+nl='
+'
+# Character ranges might be problematic outside the C locale.
+# These definitions help.
+upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ
+lower=abcdefghijklmnopqrstuvwxyz
+digits=0123456789
+alpha=${upper}${lower}
+
+if test -z "$depmode" || test -z "$source" || test -z "$object"; then
+  echo "depcomp: Variables source, object and depmode must be set" 1>&2
+  exit 1
+fi
+
+# Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po.
+depfile=${depfile-`echo "$object" |
+  sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`}
+tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`}
+
+rm -f "$tmpdepfile"
+
+# Avoid interferences from the environment.
+gccflag= dashmflag=
+
+# Some modes work just like other modes, but use different flags.  We
+# parameterize here, but still list the modes in the big case below,
+# to make depend.m4 easier to write.  Note that we *cannot* use a case
+# here, because this file can only contain one case statement.
+if test "$depmode" = hp; then
+  # HP compiler uses -M and no extra arg.
+  gccflag=-M
+  depmode=gcc
+fi
+
+if test "$depmode" = dashXmstdout; then
+  # This is just like dashmstdout with a different argument.
+  dashmflag=-xM
+  depmode=dashmstdout
+fi
+
+cygpath_u="cygpath -u -f -"
+if test "$depmode" = msvcmsys; then
+  # This is just like msvisualcpp but w/o cygpath translation.
+  # Just convert the backslash-escaped backslashes to single forward
+  # slashes to satisfy depend.m4
+  cygpath_u='sed s,\\\\,/,g'
+  depmode=msvisualcpp
+fi
+
+if test "$depmode" = msvc7msys; then
+  # This is just like msvc7 but w/o cygpath translation.
+  # Just convert the backslash-escaped backslashes to single forward
+  # slashes to satisfy depend.m4
+  cygpath_u='sed s,\\\\,/,g'
+  depmode=msvc7
+fi
+
+if test "$depmode" = xlc; then
+  # IBM C/C++ Compilers xlc/xlC can output gcc-like dependency information.
+  gccflag=-qmakedep=gcc,-MF
+  depmode=gcc
+fi
+
+case "$depmode" in
+gcc3)
+## gcc 3 implements dependency tracking that does exactly what
+## we want.  Yay!  Note: for some reason libtool 1.4 doesn't like
+## it if -MD -MP comes after the -MF stuff.  Hmm.
+## Unfortunately, FreeBSD c89 acceptance of flags depends upon
+## the command line argument order; so add the flags where they
+## appear in depend2.am.  Note that the slowdown incurred here
+## affects only configure: in makefiles, %FASTDEP% shortcuts this.
+  for arg
+  do
+    case $arg in
+    -c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;;
+    *)  set fnord "$@" "$arg" ;;
+    esac
+    shift # fnord
+    shift # $arg
+  done
+  "$@"
+  stat=$?
+  if test $stat -ne 0; then
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+  mv "$tmpdepfile" "$depfile"
+  ;;
+
+gcc)
+## Note that this doesn't just cater to obsosete pre-3.x GCC compilers.
+## but also to in-use compilers like IMB xlc/xlC and the HP C compiler.
+## (see the conditional assignment to $gccflag above).
+## There are various ways to get dependency output from gcc.  Here's
+## why we pick this rather obscure method:
+## - Don't want to use -MD because we'd like the dependencies to end
+##   up in a subdir.  Having to rename by hand is ugly.
+##   (We might end up doing this anyway to support other compilers.)
+## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like
+##   -MM, not -M (despite what the docs say).  Also, it might not be
+##   supported by the other compilers which use the 'gcc' depmode.
+## - Using -M directly means running the compiler twice (even worse
+##   than renaming).
+  if test -z "$gccflag"; then
+    gccflag=-MD,
+  fi
+  "$@" -Wp,"$gccflag$tmpdepfile"
+  stat=$?
+  if test $stat -ne 0; then
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+  rm -f "$depfile"
+  echo "$object : \\" > "$depfile"
+  # The second -e expression handles DOS-style file names with drive
+  # letters.
+  sed -e 's/^[^:]*: / /' \
+      -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile"
+## This next piece of magic avoids the "deleted header file" problem.
+## The problem is that when a header file which appears in a .P file
+## is deleted, the dependency causes make to die (because there is
+## typically no way to rebuild the header).  We avoid this by adding
+## dummy dependencies for each header file.  Too bad gcc doesn't do
+## this for us directly.
+## Some versions of gcc put a space before the ':'.  On the theory
+## that the space means something, we add a space to the output as
+## well.  hp depmode also adds that space, but also prefixes the VPATH
+## to the object.  Take care to not repeat it in the output.
+## Some versions of the HPUX 10.20 sed can't process this invocation
+## correctly.  Breaking it into two sed invocations is a workaround.
+  tr ' ' "$nl" < "$tmpdepfile" \
+    | sed -e 's/^\\$//' -e '/^$/d' -e "s|.*$object$||" -e '/:$/d' \
+    | sed -e 's/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+hp)
+  # This case exists only to let depend.m4 do its work.  It works by
+  # looking at the text of this script.  This case will never be run,
+  # since it is checked for above.
+  exit 1
+  ;;
+
+sgi)
+  if test "$libtool" = yes; then
+    "$@" "-Wp,-MDupdate,$tmpdepfile"
+  else
+    "$@" -MDupdate "$tmpdepfile"
+  fi
+  stat=$?
+  if test $stat -ne 0; then
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+  rm -f "$depfile"
+
+  if test -f "$tmpdepfile"; then  # yes, the sourcefile depend on other files
+    echo "$object : \\" > "$depfile"
+    # Clip off the initial element (the dependent).  Don't try to be
+    # clever and replace this with sed code, as IRIX sed won't handle
+    # lines with more than a fixed number of characters (4096 in
+    # IRIX 6.2 sed, 8192 in IRIX 6.5).  We also remove comment lines;
+    # the IRIX cc adds comments like '#:fec' to the end of the
+    # dependency line.
+    tr ' ' "$nl" < "$tmpdepfile" \
+      | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' \
+      | tr "$nl" ' ' >> "$depfile"
+    echo >> "$depfile"
+    # The second pass generates a dummy entry for each header file.
+    tr ' ' "$nl" < "$tmpdepfile" \
+      | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \
+      >> "$depfile"
+  else
+    make_dummy_depfile
+  fi
+  rm -f "$tmpdepfile"
+  ;;
+
+xlc)
+  # This case exists only to let depend.m4 do its work.  It works by
+  # looking at the text of this script.  This case will never be run,
+  # since it is checked for above.
+  exit 1
+  ;;
+
+aix)
+  # The C for AIX Compiler uses -M and outputs the dependencies
+  # in a .u file.  In older versions, this file always lives in the
+  # current directory.  Also, the AIX compiler puts '$object:' at the
+  # start of each line; $object doesn't have directory information.
+  # Version 6 uses the directory in both cases.
+  set_dir_from "$object"
+  set_base_from "$object"
+  if test "$libtool" = yes; then
+    tmpdepfile1=$dir$base.u
+    tmpdepfile2=$base.u
+    tmpdepfile3=$dir.libs/$base.u
+    "$@" -Wc,-M
+  else
+    tmpdepfile1=$dir$base.u
+    tmpdepfile2=$dir$base.u
+    tmpdepfile3=$dir$base.u
+    "$@" -M
+  fi
+  stat=$?
+  if test $stat -ne 0; then
+    rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
+    exit $stat
+  fi
+
+  for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
+  do
+    test -f "$tmpdepfile" && break
+  done
+  aix_post_process_depfile
+  ;;
+
+tcc)
+  # tcc (Tiny C Compiler) understand '-MD -MF file' since version 0.9.26
+  # FIXME: That version still under development at the moment of writing.
+  #        Make that this statement remains true also for stable, released
+  #        versions.
+  # It will wrap lines (doesn't matter whether long or short) with a
+  # trailing '\', as in:
+  #
+  #   foo.o : \
+  #    foo.c \
+  #    foo.h \
+  #
+  # It will put a trailing '\' even on the last line, and will use leading
+  # spaces rather than leading tabs (at least since its commit 0394caf7
+  # "Emit spaces for -MD").
+  "$@" -MD -MF "$tmpdepfile"
+  stat=$?
+  if test $stat -ne 0; then
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+  rm -f "$depfile"
+  # Each non-empty line is of the form 'foo.o : \' or ' dep.h \'.
+  # We have to change lines of the first kind to '$object: \'.
+  sed -e "s|.*:|$object :|" < "$tmpdepfile" > "$depfile"
+  # And for each line of the second kind, we have to emit a 'dep.h:'
+  # dummy dependency, to avoid the deleted-header problem.
+  sed -n -e 's|^  *\(.*\) *\\$|\1:|p' < "$tmpdepfile" >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+## The order of this option in the case statement is important, since the
+## shell code in configure will try each of these formats in the order
+## listed in this file.  A plain '-MD' option would be understood by many
+## compilers, so we must ensure this comes after the gcc and icc options.
+pgcc)
+  # Portland's C compiler understands '-MD'.
+  # Will always output deps to 'file.d' where file is the root name of the
+  # source file under compilation, even if file resides in a subdirectory.
+  # The object file name does not affect the name of the '.d' file.
+  # pgcc 10.2 will output
+  #    foo.o: sub/foo.c sub/foo.h
+  # and will wrap long lines using '\' :
+  #    foo.o: sub/foo.c ... \
+  #     sub/foo.h ... \
+  #     ...
+  set_dir_from "$object"
+  # Use the source, not the object, to determine the base name, since
+  # that's sadly what pgcc will do too.
+  set_base_from "$source"
+  tmpdepfile=$base.d
+
+  # For projects that build the same source file twice into different object
+  # files, the pgcc approach of using the *source* file root name can cause
+  # problems in parallel builds.  Use a locking strategy to avoid stomping on
+  # the same $tmpdepfile.
+  lockdir=$base.d-lock
+  trap "
+    echo '$0: caught signal, cleaning up...' >&2
+    rmdir '$lockdir'
+    exit 1
+  " 1 2 13 15
+  numtries=100
+  i=$numtries
+  while test $i -gt 0; do
+    # mkdir is a portable test-and-set.
+    if mkdir "$lockdir" 2>/dev/null; then
+      # This process acquired the lock.
+      "$@" -MD
+      stat=$?
+      # Release the lock.
+      rmdir "$lockdir"
+      break
+    else
+      # If the lock is being held by a different process, wait
+      # until the winning process is done or we timeout.
+      while test -d "$lockdir" && test $i -gt 0; do
+        sleep 1
+        i=`expr $i - 1`
+      done
+    fi
+    i=`expr $i - 1`
+  done
+  trap - 1 2 13 15
+  if test $i -le 0; then
+    echo "$0: failed to acquire lock after $numtries attempts" >&2
+    echo "$0: check lockdir '$lockdir'" >&2
+    exit 1
+  fi
+
+  if test $stat -ne 0; then
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+  rm -f "$depfile"
+  # Each line is of the form `foo.o: dependent.h',
+  # or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'.
+  # Do two passes, one to just change these to
+  # `$object: dependent.h' and one to simply `dependent.h:'.
+  sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile"
+  # Some versions of the HPUX 10.20 sed can't process this invocation
+  # correctly.  Breaking it into two sed invocations is a workaround.
+  sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" \
+    | sed -e 's/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+hp2)
+  # The "hp" stanza above does not work with aCC (C++) and HP's ia64
+  # compilers, which have integrated preprocessors.  The correct option
+  # to use with these is +Maked; it writes dependencies to a file named
+  # 'foo.d', which lands next to the object file, wherever that
+  # happens to be.
+  # Much of this is similar to the tru64 case; see comments there.
+  set_dir_from  "$object"
+  set_base_from "$object"
+  if test "$libtool" = yes; then
+    tmpdepfile1=$dir$base.d
+    tmpdepfile2=$dir.libs/$base.d
+    "$@" -Wc,+Maked
+  else
+    tmpdepfile1=$dir$base.d
+    tmpdepfile2=$dir$base.d
+    "$@" +Maked
+  fi
+  stat=$?
+  if test $stat -ne 0; then
+     rm -f "$tmpdepfile1" "$tmpdepfile2"
+     exit $stat
+  fi
+
+  for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2"
+  do
+    test -f "$tmpdepfile" && break
+  done
+  if test -f "$tmpdepfile"; then
+    sed -e "s,^.*\.[$lower]*:,$object:," "$tmpdepfile" > "$depfile"
+    # Add 'dependent.h:' lines.
+    sed -ne '2,${
+               s/^ *//
+               s/ \\*$//
+               s/$/:/
+               p
+             }' "$tmpdepfile" >> "$depfile"
+  else
+    make_dummy_depfile
+  fi
+  rm -f "$tmpdepfile" "$tmpdepfile2"
+  ;;
+
+tru64)
+  # The Tru64 compiler uses -MD to generate dependencies as a side
+  # effect.  'cc -MD -o foo.o ...' puts the dependencies into 'foo.o.d'.
+  # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put
+  # dependencies in 'foo.d' instead, so we check for that too.
+  # Subdirectories are respected.
+  set_dir_from  "$object"
+  set_base_from "$object"
+
+  if test "$libtool" = yes; then
+    # Libtool generates 2 separate objects for the 2 libraries.  These
+    # two compilations output dependencies in $dir.libs/$base.o.d and
+    # in $dir$base.o.d.  We have to check for both files, because
+    # one of the two compilations can be disabled.  We should prefer
+    # $dir$base.o.d over $dir.libs/$base.o.d because the latter is
+    # automatically cleaned when .libs/ is deleted, while ignoring
+    # the former would cause a distcleancheck panic.
+    tmpdepfile1=$dir$base.o.d          # libtool 1.5
+    tmpdepfile2=$dir.libs/$base.o.d    # Likewise.
+    tmpdepfile3=$dir.libs/$base.d      # Compaq CCC V6.2-504
+    "$@" -Wc,-MD
+  else
+    tmpdepfile1=$dir$base.d
+    tmpdepfile2=$dir$base.d
+    tmpdepfile3=$dir$base.d
+    "$@" -MD
+  fi
+
+  stat=$?
+  if test $stat -ne 0; then
+    rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
+    exit $stat
+  fi
+
+  for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
+  do
+    test -f "$tmpdepfile" && break
+  done
+  # Same post-processing that is required for AIX mode.
+  aix_post_process_depfile
+  ;;
+
+msvc7)
+  if test "$libtool" = yes; then
+    showIncludes=-Wc,-showIncludes
+  else
+    showIncludes=-showIncludes
+  fi
+  "$@" $showIncludes > "$tmpdepfile"
+  stat=$?
+  grep -v '^Note: including file: ' "$tmpdepfile"
+  if test $stat -ne 0; then
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+  rm -f "$depfile"
+  echo "$object : \\" > "$depfile"
+  # The first sed program below extracts the file names and escapes
+  # backslashes for cygpath.  The second sed program outputs the file
+  # name when reading, but also accumulates all include files in the
+  # hold buffer in order to output them again at the end.  This only
+  # works with sed implementations that can handle large buffers.
+  sed < "$tmpdepfile" -n '
+/^Note: including file:  *\(.*\)/ {
+  s//\1/
+  s/\\/\\\\/g
+  p
+}' | $cygpath_u | sort -u | sed -n '
+s/ /\\ /g
+s/\(.*\)/'"$tab"'\1 \\/p
+s/.\(.*\) \\/\1:/
+H
+$ {
+  s/.*/'"$tab"'/
+  G
+  p
+}' >> "$depfile"
+  echo >> "$depfile" # make sure the fragment doesn't end with a backslash
+  rm -f "$tmpdepfile"
+  ;;
+
+msvc7msys)
+  # This case exists only to let depend.m4 do its work.  It works by
+  # looking at the text of this script.  This case will never be run,
+  # since it is checked for above.
+  exit 1
+  ;;
+
+#nosideeffect)
+  # This comment above is used by automake to tell side-effect
+  # dependency tracking mechanisms from slower ones.
+
+dashmstdout)
+  # Important note: in order to support this mode, a compiler *must*
+  # always write the preprocessed file to stdout, regardless of -o.
+  "$@" || exit $?
+
+  # Remove the call to Libtool.
+  if test "$libtool" = yes; then
+    while test "X$1" != 'X--mode=compile'; do
+      shift
+    done
+    shift
+  fi
+
+  # Remove '-o $object'.
+  IFS=" "
+  for arg
+  do
+    case $arg in
+    -o)
+      shift
+      ;;
+    $object)
+      shift
+      ;;
+    *)
+      set fnord "$@" "$arg"
+      shift # fnord
+      shift # $arg
+      ;;
+    esac
+  done
+
+  test -z "$dashmflag" && dashmflag=-M
+  # Require at least two characters before searching for ':'
+  # in the target name.  This is to cope with DOS-style filenames:
+  # a dependency such as 'c:/foo/bar' could be seen as target 'c' otherwise.
+  "$@" $dashmflag |
+    sed "s|^[$tab ]*[^:$tab ][^:][^:]*:[$tab ]*|$object: |" > "$tmpdepfile"
+  rm -f "$depfile"
+  cat < "$tmpdepfile" > "$depfile"
+  # Some versions of the HPUX 10.20 sed can't process this sed invocation
+  # correctly.  Breaking it into two sed invocations is a workaround.
+  tr ' ' "$nl" < "$tmpdepfile" \
+    | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \
+    | sed -e 's/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+dashXmstdout)
+  # This case only exists to satisfy depend.m4.  It is never actually
+  # run, as this mode is specially recognized in the preamble.
+  exit 1
+  ;;
+
+makedepend)
+  "$@" || exit $?
+  # Remove any Libtool call
+  if test "$libtool" = yes; then
+    while test "X$1" != 'X--mode=compile'; do
+      shift
+    done
+    shift
+  fi
+  # X makedepend
+  shift
+  cleared=no eat=no
+  for arg
+  do
+    case $cleared in
+    no)
+      set ""; shift
+      cleared=yes ;;
+    esac
+    if test $eat = yes; then
+      eat=no
+      continue
+    fi
+    case "$arg" in
+    -D*|-I*)
+      set fnord "$@" "$arg"; shift ;;
+    # Strip any option that makedepend may not understand.  Remove
+    # the object too, otherwise makedepend will parse it as a source file.
+    -arch)
+      eat=yes ;;
+    -*|$object)
+      ;;
+    *)
+      set fnord "$@" "$arg"; shift ;;
+    esac
+  done
+  obj_suffix=`echo "$object" | sed 's/^.*\././'`
+  touch "$tmpdepfile"
+  ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@"
+  rm -f "$depfile"
+  # makedepend may prepend the VPATH from the source file name to the object.
+  # No need to regex-escape $object, excess matching of '.' is harmless.
+  sed "s|^.*\($object *:\)|\1|" "$tmpdepfile" > "$depfile"
+  # Some versions of the HPUX 10.20 sed can't process the last invocation
+  # correctly.  Breaking it into two sed invocations is a workaround.
+  sed '1,2d' "$tmpdepfile" \
+    | tr ' ' "$nl" \
+    | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \
+    | sed -e 's/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile" "$tmpdepfile".bak
+  ;;
+
+cpp)
+  # Important note: in order to support this mode, a compiler *must*
+  # always write the preprocessed file to stdout.
+  "$@" || exit $?
+
+  # Remove the call to Libtool.
+  if test "$libtool" = yes; then
+    while test "X$1" != 'X--mode=compile'; do
+      shift
+    done
+    shift
+  fi
+
+  # Remove '-o $object'.
+  IFS=" "
+  for arg
+  do
+    case $arg in
+    -o)
+      shift
+      ;;
+    $object)
+      shift
+      ;;
+    *)
+      set fnord "$@" "$arg"
+      shift # fnord
+      shift # $arg
+      ;;
+    esac
+  done
+
+  "$@" -E \
+    | sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \
+             -e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \
+    | sed '$ s: \\$::' > "$tmpdepfile"
+  rm -f "$depfile"
+  echo "$object : \\" > "$depfile"
+  cat < "$tmpdepfile" >> "$depfile"
+  sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+msvisualcpp)
+  # Important note: in order to support this mode, a compiler *must*
+  # always write the preprocessed file to stdout.
+  "$@" || exit $?
+
+  # Remove the call to Libtool.
+  if test "$libtool" = yes; then
+    while test "X$1" != 'X--mode=compile'; do
+      shift
+    done
+    shift
+  fi
+
+  IFS=" "
+  for arg
+  do
+    case "$arg" in
+    -o)
+      shift
+      ;;
+    $object)
+      shift
+      ;;
+    "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI")
+        set fnord "$@"
+        shift
+        shift
+        ;;
+    *)
+        set fnord "$@" "$arg"
+        shift
+        shift
+        ;;
+    esac
+  done
+  "$@" -E 2>/dev/null |
+  sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile"
+  rm -f "$depfile"
+  echo "$object : \\" > "$depfile"
+  sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::'"$tab"'\1 \\:p' >> "$depfile"
+  echo "$tab" >> "$depfile"
+  sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+msvcmsys)
+  # This case exists only to let depend.m4 do its work.  It works by
+  # looking at the text of this script.  This case will never be run,
+  # since it is checked for above.
+  exit 1
+  ;;
+
+none)
+  exec "$@"
+  ;;
+
+*)
+  echo "Unknown depmode $depmode" 1>&2
+  exit 1
+  ;;
+esac
+
+exit 0
+
+# Local Variables:
+# mode: shell-script
+# sh-indentation: 2
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
+# End:
diff --git a/hdrl/admin/install-sh b/hdrl/admin/install-sh
new file mode 100755
index 0000000..377bb86
--- /dev/null
+++ b/hdrl/admin/install-sh
@@ -0,0 +1,527 @@
+#!/bin/sh
+# install - install a program, script, or datafile
+
+scriptversion=2011-11-20.07; # UTC
+
+# This originates from X11R5 (mit/util/scripts/install.sh), which was
+# later released in X11R6 (xc/config/util/install.sh) with the
+# following copyright and license.
+#
+# Copyright (C) 1994 X Consortium
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to
+# deal in the Software without restriction, including without limitation the
+# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+# sell copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
+# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
+# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+# Except as contained in this notice, the name of the X Consortium shall not
+# be used in advertising or otherwise to promote the sale, use or other deal-
+# ings in this Software without prior written authorization from the X Consor-
+# tium.
+#
+#
+# FSF changes to this file are in the public domain.
+#
+# Calling this script install-sh is preferred over install.sh, to prevent
+# 'make' implicit rules from creating a file called install from it
+# when there is no Makefile.
+#
+# This script is compatible with the BSD install script, but was written
+# from scratch.
+
+nl='
+'
+IFS=" ""	$nl"
+
+# set DOITPROG to echo to test this script
+
+# Don't use :- since 4.3BSD and earlier shells don't like it.
+doit=${DOITPROG-}
+if test -z "$doit"; then
+  doit_exec=exec
+else
+  doit_exec=$doit
+fi
+
+# Put in absolute file names if you don't have them in your path;
+# or use environment vars.
+
+chgrpprog=${CHGRPPROG-chgrp}
+chmodprog=${CHMODPROG-chmod}
+chownprog=${CHOWNPROG-chown}
+cmpprog=${CMPPROG-cmp}
+cpprog=${CPPROG-cp}
+mkdirprog=${MKDIRPROG-mkdir}
+mvprog=${MVPROG-mv}
+rmprog=${RMPROG-rm}
+stripprog=${STRIPPROG-strip}
+
+posix_glob='?'
+initialize_posix_glob='
+  test "$posix_glob" != "?" || {
+    if (set -f) 2>/dev/null; then
+      posix_glob=
+    else
+      posix_glob=:
+    fi
+  }
+'
+
+posix_mkdir=
+
+# Desired mode of installed file.
+mode=0755
+
+chgrpcmd=
+chmodcmd=$chmodprog
+chowncmd=
+mvcmd=$mvprog
+rmcmd="$rmprog -f"
+stripcmd=
+
+src=
+dst=
+dir_arg=
+dst_arg=
+
+copy_on_change=false
+no_target_directory=
+
+usage="\
+Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
+   or: $0 [OPTION]... SRCFILES... DIRECTORY
+   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
+   or: $0 [OPTION]... -d DIRECTORIES...
+
+In the 1st form, copy SRCFILE to DSTFILE.
+In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
+In the 4th, create DIRECTORIES.
+
+Options:
+     --help     display this help and exit.
+     --version  display version info and exit.
+
+  -c            (ignored)
+  -C            install only if different (preserve the last data modification time)
+  -d            create directories instead of installing files.
+  -g GROUP      $chgrpprog installed files to GROUP.
+  -m MODE       $chmodprog installed files to MODE.
+  -o USER       $chownprog installed files to USER.
+  -s            $stripprog installed files.
+  -t DIRECTORY  install into DIRECTORY.
+  -T            report an error if DSTFILE is a directory.
+
+Environment variables override the default commands:
+  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
+  RMPROG STRIPPROG
+"
+
+while test $# -ne 0; do
+  case $1 in
+    -c) ;;
+
+    -C) copy_on_change=true;;
+
+    -d) dir_arg=true;;
+
+    -g) chgrpcmd="$chgrpprog $2"
+	shift;;
+
+    --help) echo "$usage"; exit $?;;
+
+    -m) mode=$2
+	case $mode in
+	  *' '* | *'	'* | *'
+'*	  | *'*'* | *'?'* | *'['*)
+	    echo "$0: invalid mode: $mode" >&2
+	    exit 1;;
+	esac
+	shift;;
+
+    -o) chowncmd="$chownprog $2"
+	shift;;
+
+    -s) stripcmd=$stripprog;;
+
+    -t) dst_arg=$2
+	# Protect names problematic for 'test' and other utilities.
+	case $dst_arg in
+	  -* | [=\(\)!]) dst_arg=./$dst_arg;;
+	esac
+	shift;;
+
+    -T) no_target_directory=true;;
+
+    --version) echo "$0 $scriptversion"; exit $?;;
+
+    --)	shift
+	break;;
+
+    -*)	echo "$0: invalid option: $1" >&2
+	exit 1;;
+
+    *)  break;;
+  esac
+  shift
+done
+
+if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
+  # When -d is used, all remaining arguments are directories to create.
+  # When -t is used, the destination is already specified.
+  # Otherwise, the last argument is the destination.  Remove it from $@.
+  for arg
+  do
+    if test -n "$dst_arg"; then
+      # $@ is not empty: it contains at least $arg.
+      set fnord "$@" "$dst_arg"
+      shift # fnord
+    fi
+    shift # arg
+    dst_arg=$arg
+    # Protect names problematic for 'test' and other utilities.
+    case $dst_arg in
+      -* | [=\(\)!]) dst_arg=./$dst_arg;;
+    esac
+  done
+fi
+
+if test $# -eq 0; then
+  if test -z "$dir_arg"; then
+    echo "$0: no input file specified." >&2
+    exit 1
+  fi
+  # It's OK to call 'install-sh -d' without argument.
+  # This can happen when creating conditional directories.
+  exit 0
+fi
+
+if test -z "$dir_arg"; then
+  do_exit='(exit $ret); exit $ret'
+  trap "ret=129; $do_exit" 1
+  trap "ret=130; $do_exit" 2
+  trap "ret=141; $do_exit" 13
+  trap "ret=143; $do_exit" 15
+
+  # Set umask so as not to create temps with too-generous modes.
+  # However, 'strip' requires both read and write access to temps.
+  case $mode in
+    # Optimize common cases.
+    *644) cp_umask=133;;
+    *755) cp_umask=22;;
+
+    *[0-7])
+      if test -z "$stripcmd"; then
+	u_plus_rw=
+      else
+	u_plus_rw='% 200'
+      fi
+      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
+    *)
+      if test -z "$stripcmd"; then
+	u_plus_rw=
+      else
+	u_plus_rw=,u+rw
+      fi
+      cp_umask=$mode$u_plus_rw;;
+  esac
+fi
+
+for src
+do
+  # Protect names problematic for 'test' and other utilities.
+  case $src in
+    -* | [=\(\)!]) src=./$src;;
+  esac
+
+  if test -n "$dir_arg"; then
+    dst=$src
+    dstdir=$dst
+    test -d "$dstdir"
+    dstdir_status=$?
+  else
+
+    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
+    # might cause directories to be created, which would be especially bad
+    # if $src (and thus $dsttmp) contains '*'.
+    if test ! -f "$src" && test ! -d "$src"; then
+      echo "$0: $src does not exist." >&2
+      exit 1
+    fi
+
+    if test -z "$dst_arg"; then
+      echo "$0: no destination specified." >&2
+      exit 1
+    fi
+    dst=$dst_arg
+
+    # If destination is a directory, append the input filename; won't work
+    # if double slashes aren't ignored.
+    if test -d "$dst"; then
+      if test -n "$no_target_directory"; then
+	echo "$0: $dst_arg: Is a directory" >&2
+	exit 1
+      fi
+      dstdir=$dst
+      dst=$dstdir/`basename "$src"`
+      dstdir_status=0
+    else
+      # Prefer dirname, but fall back on a substitute if dirname fails.
+      dstdir=`
+	(dirname "$dst") 2>/dev/null ||
+	expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	     X"$dst" : 'X\(//\)[^/]' \| \
+	     X"$dst" : 'X\(//\)$' \| \
+	     X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
+	echo X"$dst" |
+	    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\/\)[^/].*/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\/\)$/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\).*/{
+		   s//\1/
+		   q
+		 }
+		 s/.*/./; q'
+      `
+
+      test -d "$dstdir"
+      dstdir_status=$?
+    fi
+  fi
+
+  obsolete_mkdir_used=false
+
+  if test $dstdir_status != 0; then
+    case $posix_mkdir in
+      '')
+	# Create intermediate dirs using mode 755 as modified by the umask.
+	# This is like FreeBSD 'install' as of 1997-10-28.
+	umask=`umask`
+	case $stripcmd.$umask in
+	  # Optimize common cases.
+	  *[2367][2367]) mkdir_umask=$umask;;
+	  .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
+
+	  *[0-7])
+	    mkdir_umask=`expr $umask + 22 \
+	      - $umask % 100 % 40 + $umask % 20 \
+	      - $umask % 10 % 4 + $umask % 2
+	    `;;
+	  *) mkdir_umask=$umask,go-w;;
+	esac
+
+	# With -d, create the new directory with the user-specified mode.
+	# Otherwise, rely on $mkdir_umask.
+	if test -n "$dir_arg"; then
+	  mkdir_mode=-m$mode
+	else
+	  mkdir_mode=
+	fi
+
+	posix_mkdir=false
+	case $umask in
+	  *[123567][0-7][0-7])
+	    # POSIX mkdir -p sets u+wx bits regardless of umask, which
+	    # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
+	    ;;
+	  *)
+	    tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+	    trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
+
+	    if (umask $mkdir_umask &&
+		exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
+	    then
+	      if test -z "$dir_arg" || {
+		   # Check for POSIX incompatibilities with -m.
+		   # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+		   # other-writable bit of parent directory when it shouldn't.
+		   # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+		   ls_ld_tmpdir=`ls -ld "$tmpdir"`
+		   case $ls_ld_tmpdir in
+		     d????-?r-*) different_mode=700;;
+		     d????-?--*) different_mode=755;;
+		     *) false;;
+		   esac &&
+		   $mkdirprog -m$different_mode -p -- "$tmpdir" && {
+		     ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
+		     test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+		   }
+		 }
+	      then posix_mkdir=:
+	      fi
+	      rmdir "$tmpdir/d" "$tmpdir"
+	    else
+	      # Remove any dirs left behind by ancient mkdir implementations.
+	      rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
+	    fi
+	    trap '' 0;;
+	esac;;
+    esac
+
+    if
+      $posix_mkdir && (
+	umask $mkdir_umask &&
+	$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+      )
+    then :
+    else
+
+      # The umask is ridiculous, or mkdir does not conform to POSIX,
+      # or it failed possibly due to a race condition.  Create the
+      # directory the slow way, step by step, checking for races as we go.
+
+      case $dstdir in
+	/*) prefix='/';;
+	[-=\(\)!]*) prefix='./';;
+	*)  prefix='';;
+      esac
+
+      eval "$initialize_posix_glob"
+
+      oIFS=$IFS
+      IFS=/
+      $posix_glob set -f
+      set fnord $dstdir
+      shift
+      $posix_glob set +f
+      IFS=$oIFS
+
+      prefixes=
+
+      for d
+      do
+	test X"$d" = X && continue
+
+	prefix=$prefix$d
+	if test -d "$prefix"; then
+	  prefixes=
+	else
+	  if $posix_mkdir; then
+	    (umask=$mkdir_umask &&
+	     $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+	    # Don't fail if two instances are running concurrently.
+	    test -d "$prefix" || exit 1
+	  else
+	    case $prefix in
+	      *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+	      *) qprefix=$prefix;;
+	    esac
+	    prefixes="$prefixes '$qprefix'"
+	  fi
+	fi
+	prefix=$prefix/
+      done
+
+      if test -n "$prefixes"; then
+	# Don't fail if two instances are running concurrently.
+	(umask $mkdir_umask &&
+	 eval "\$doit_exec \$mkdirprog $prefixes") ||
+	  test -d "$dstdir" || exit 1
+	obsolete_mkdir_used=true
+      fi
+    fi
+  fi
+
+  if test -n "$dir_arg"; then
+    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
+    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
+      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
+  else
+
+    # Make a couple of temp file names in the proper directory.
+    dsttmp=$dstdir/_inst.$$_
+    rmtmp=$dstdir/_rm.$$_
+
+    # Trap to clean up those temp files at exit.
+    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
+
+    # Copy the file name to the temp name.
+    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
+
+    # and set any options; do chmod last to preserve setuid bits.
+    #
+    # If any of these fail, we abort the whole thing.  If we want to
+    # ignore errors from any of these, just make sure not to ignore
+    # errors from the above "$doit $cpprog $src $dsttmp" command.
+    #
+    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
+    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
+    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
+
+    # If -C, don't bother to copy if it wouldn't change the file.
+    if $copy_on_change &&
+       old=`LC_ALL=C ls -dlL "$dst"	2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"	2>/dev/null` &&
+
+       eval "$initialize_posix_glob" &&
+       $posix_glob set -f &&
+       set X $old && old=:$2:$4:$5:$6 &&
+       set X $new && new=:$2:$4:$5:$6 &&
+       $posix_glob set +f &&
+
+       test "$old" = "$new" &&
+       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
+    then
+      rm -f "$dsttmp"
+    else
+      # Rename the file to the real destination.
+      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
+
+      # The rename failed, perhaps because mv can't rename something else
+      # to itself, or perhaps because mv is so ancient that it does not
+      # support -f.
+      {
+	# Now remove or move aside any old file at destination location.
+	# We try this two ways since rm can't unlink itself on some
+	# systems and the destination file might be busy for other
+	# reasons.  In this case, the final cleanup might fail but the new
+	# file should still install successfully.
+	{
+	  test ! -f "$dst" ||
+	  $doit $rmcmd -f "$dst" 2>/dev/null ||
+	  { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+	    { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+	  } ||
+	  { echo "$0: cannot unlink or rename $dst" >&2
+	    (exit 1); exit 1
+	  }
+	} &&
+
+	# Now rename the file to the real destination.
+	$doit $mvcmd "$dsttmp" "$dst"
+      }
+    fi || exit 1
+
+    trap '' 0
+  fi
+done
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
+# End:
diff --git a/hdrl/admin/ltmain.sh b/hdrl/admin/ltmain.sh
new file mode 100644
index 0000000..63ae69d
--- /dev/null
+++ b/hdrl/admin/ltmain.sh
@@ -0,0 +1,9655 @@
+
+# libtool (GNU libtool) 2.4.2
+# Written by Gordon Matzigkeit <gord at gnu.ai.mit.edu>, 1996
+
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006,
+# 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
+# This is free software; see the source for copying conditions.  There is NO
+# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+# GNU Libtool is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# As a special exception to the GNU General Public License,
+# if you distribute this file as part of a program or library that
+# is built using GNU Libtool, you may include this file under the
+# same distribution terms that you use for the rest of that program.
+#
+# GNU Libtool is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GNU Libtool; see the file COPYING.  If not, a copy
+# can be downloaded from http://www.gnu.org/licenses/gpl.html,
+# or obtained by writing to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+# Usage: $progname [OPTION]... [MODE-ARG]...
+#
+# Provide generalized library-building support services.
+#
+#       --config             show all configuration variables
+#       --debug              enable verbose shell tracing
+#   -n, --dry-run            display commands without modifying any files
+#       --features           display basic configuration information and exit
+#       --mode=MODE          use operation mode MODE
+#       --preserve-dup-deps  don't remove duplicate dependency libraries
+#       --quiet, --silent    don't print informational messages
+#       --no-quiet, --no-silent
+#                            print informational messages (default)
+#       --no-warn            don't display warning messages
+#       --tag=TAG            use configuration variables from tag TAG
+#   -v, --verbose            print more informational messages than default
+#       --no-verbose         don't print the extra informational messages
+#       --version            print version information
+#   -h, --help, --help-all   print short, long, or detailed help message
+#
+# MODE must be one of the following:
+#
+#         clean              remove files from the build directory
+#         compile            compile a source file into a libtool object
+#         execute            automatically set library path, then run a program
+#         finish             complete the installation of libtool libraries
+#         install            install libraries or executables
+#         link               create a library or an executable
+#         uninstall          remove libraries from an installed directory
+#
+# MODE-ARGS vary depending on the MODE.  When passed as first option,
+# `--mode=MODE' may be abbreviated as `MODE' or a unique abbreviation of that.
+# Try `$progname --help --mode=MODE' for a more detailed description of MODE.
+#
+# When reporting a bug, please describe a test case to reproduce it and
+# include the following information:
+#
+#         host-triplet:	$host
+#         shell:		$SHELL
+#         compiler:		$LTCC
+#         compiler flags:		$LTCFLAGS
+#         linker:		$LD (gnu? $with_gnu_ld)
+#         $progname:	(GNU libtool) 2.4.2
+#         automake:	$automake_version
+#         autoconf:	$autoconf_version
+#
+# Report bugs to <bug-libtool at gnu.org>.
+# GNU libtool home page: <http://www.gnu.org/software/libtool/>.
+# General help using GNU software: <http://www.gnu.org/gethelp/>.
+
+PROGRAM=libtool
+PACKAGE=libtool
+VERSION=2.4.2
+TIMESTAMP=""
+package_revision=1.3337
+
+# Be Bourne compatible
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac
+fi
+BIN_SH=xpg4; export BIN_SH # for Tru64
+DUALCASE=1; export DUALCASE # for MKS sh
+
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+$1
+_LTECHO_EOF'
+}
+
+# NLS nuisances: We save the old values to restore during execute mode.
+lt_user_locale=
+lt_safe_locale=
+for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
+do
+  eval "if test \"\${$lt_var+set}\" = set; then
+          save_$lt_var=\$$lt_var
+          $lt_var=C
+	  export $lt_var
+	  lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\"
+	  lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\"
+	fi"
+done
+LC_ALL=C
+LANGUAGE=C
+export LANGUAGE LC_ALL
+
+$lt_unset CDPATH
+
+
+# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
+# is ksh but when the shell is invoked as "sh" and the current value of
+# the _XPG environment variable is not equal to 1 (one), the special
+# positional parameter $0, within a function call, is the name of the
+# function.
+progpath="$0"
+
+
+
+: ${CP="cp -f"}
+test "${ECHO+set}" = set || ECHO=${as_echo-'printf %s\n'}
+: ${MAKE="make"}
+: ${MKDIR="mkdir"}
+: ${MV="mv -f"}
+: ${RM="rm -f"}
+: ${SHELL="${CONFIG_SHELL-/bin/sh}"}
+: ${Xsed="$SED -e 1s/^X//"}
+
+# Global variables:
+EXIT_SUCCESS=0
+EXIT_FAILURE=1
+EXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.
+EXIT_SKIP=77	  # $? = 77 is used to indicate a skipped test to automake.
+
+exit_status=$EXIT_SUCCESS
+
+# Make sure IFS has a sensible default
+lt_nl='
+'
+IFS=" 	$lt_nl"
+
+dirname="s,/[^/]*$,,"
+basename="s,^.*/,,"
+
+# func_dirname file append nondir_replacement
+# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
+# otherwise set result to NONDIR_REPLACEMENT.
+func_dirname ()
+{
+    func_dirname_result=`$ECHO "${1}" | $SED "$dirname"`
+    if test "X$func_dirname_result" = "X${1}"; then
+      func_dirname_result="${3}"
+    else
+      func_dirname_result="$func_dirname_result${2}"
+    fi
+} # func_dirname may be replaced by extended shell implementation
+
+
+# func_basename file
+func_basename ()
+{
+    func_basename_result=`$ECHO "${1}" | $SED "$basename"`
+} # func_basename may be replaced by extended shell implementation
+
+
+# func_dirname_and_basename file append nondir_replacement
+# perform func_basename and func_dirname in a single function
+# call:
+#   dirname:  Compute the dirname of FILE.  If nonempty,
+#             add APPEND to the result, otherwise set result
+#             to NONDIR_REPLACEMENT.
+#             value returned in "$func_dirname_result"
+#   basename: Compute filename of FILE.
+#             value retuned in "$func_basename_result"
+# Implementation must be kept synchronized with func_dirname
+# and func_basename. For efficiency, we do not delegate to
+# those functions but instead duplicate the functionality here.
+func_dirname_and_basename ()
+{
+    # Extract subdirectory from the argument.
+    func_dirname_result=`$ECHO "${1}" | $SED -e "$dirname"`
+    if test "X$func_dirname_result" = "X${1}"; then
+      func_dirname_result="${3}"
+    else
+      func_dirname_result="$func_dirname_result${2}"
+    fi
+    func_basename_result=`$ECHO "${1}" | $SED -e "$basename"`
+} # func_dirname_and_basename may be replaced by extended shell implementation
+
+
+# func_stripname prefix suffix name
+# strip PREFIX and SUFFIX off of NAME.
+# PREFIX and SUFFIX must not contain globbing or regex special
+# characters, hashes, percent signs, but SUFFIX may contain a leading
+# dot (in which case that matches only a dot).
+# func_strip_suffix prefix name
+func_stripname ()
+{
+    case ${2} in
+      .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;;
+      *)  func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;;
+    esac
+} # func_stripname may be replaced by extended shell implementation
+
+
+# These SED scripts presuppose an absolute path with a trailing slash.
+pathcar='s,^/\([^/]*\).*$,\1,'
+pathcdr='s,^/[^/]*,,'
+removedotparts=':dotsl
+		s@/\./@/@g
+		t dotsl
+		s,/\.$,/,'
+collapseslashes='s@/\{1,\}@/@g'
+finalslash='s,/*$,/,'
+
+# func_normal_abspath PATH
+# Remove doubled-up and trailing slashes, "." path components,
+# and cancel out any ".." path components in PATH after making
+# it an absolute path.
+#             value returned in "$func_normal_abspath_result"
+func_normal_abspath ()
+{
+  # Start from root dir and reassemble the path.
+  func_normal_abspath_result=
+  func_normal_abspath_tpath=$1
+  func_normal_abspath_altnamespace=
+  case $func_normal_abspath_tpath in
+    "")
+      # Empty path, that just means $cwd.
+      func_stripname '' '/' "`pwd`"
+      func_normal_abspath_result=$func_stripname_result
+      return
+    ;;
+    # The next three entries are used to spot a run of precisely
+    # two leading slashes without using negated character classes;
+    # we take advantage of case's first-match behaviour.
+    ///*)
+      # Unusual form of absolute path, do nothing.
+    ;;
+    //*)
+      # Not necessarily an ordinary path; POSIX reserves leading '//'
+      # and for example Cygwin uses it to access remote file shares
+      # over CIFS/SMB, so we conserve a leading double slash if found.
+      func_normal_abspath_altnamespace=/
+    ;;
+    /*)
+      # Absolute path, do nothing.
+    ;;
+    *)
+      # Relative path, prepend $cwd.
+      func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath
+    ;;
+  esac
+  # Cancel out all the simple stuff to save iterations.  We also want
+  # the path to end with a slash for ease of parsing, so make sure
+  # there is one (and only one) here.
+  func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$removedotparts" -e "$collapseslashes" -e "$finalslash"`
+  while :; do
+    # Processed it all yet?
+    if test "$func_normal_abspath_tpath" = / ; then
+      # If we ascended to the root using ".." the result may be empty now.
+      if test -z "$func_normal_abspath_result" ; then
+        func_normal_abspath_result=/
+      fi
+      break
+    fi
+    func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$pathcar"`
+    func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$pathcdr"`
+    # Figure out what to do with it
+    case $func_normal_abspath_tcomponent in
+      "")
+        # Trailing empty path component, ignore it.
+      ;;
+      ..)
+        # Parent dir; strip last assembled component from result.
+        func_dirname "$func_normal_abspath_result"
+        func_normal_abspath_result=$func_dirname_result
+      ;;
+      *)
+        # Actual path component, append it.
+        func_normal_abspath_result=$func_normal_abspath_result/$func_normal_abspath_tcomponent
+      ;;
+    esac
+  done
+  # Restore leading double-slash if one was found on entry.
+  func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result
+}
+
+# func_relative_path SRCDIR DSTDIR
+# generates a relative path from SRCDIR to DSTDIR, with a trailing
+# slash if non-empty, suitable for immediately appending a filename
+# without needing to append a separator.
+#             value returned in "$func_relative_path_result"
+func_relative_path ()
+{
+  func_relative_path_result=
+  func_normal_abspath "$1"
+  func_relative_path_tlibdir=$func_normal_abspath_result
+  func_normal_abspath "$2"
+  func_relative_path_tbindir=$func_normal_abspath_result
+
+  # Ascend the tree starting from libdir
+  while :; do
+    # check if we have found a prefix of bindir
+    case $func_relative_path_tbindir in
+      $func_relative_path_tlibdir)
+        # found an exact match
+        func_relative_path_tcancelled=
+        break
+        ;;
+      $func_relative_path_tlibdir*)
+        # found a matching prefix
+        func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir"
+        func_relative_path_tcancelled=$func_stripname_result
+        if test -z "$func_relative_path_result"; then
+          func_relative_path_result=.
+        fi
+        break
+        ;;
+      *)
+        func_dirname $func_relative_path_tlibdir
+        func_relative_path_tlibdir=${func_dirname_result}
+        if test "x$func_relative_path_tlibdir" = x ; then
+          # Have to descend all the way to the root!
+          func_relative_path_result=../$func_relative_path_result
+          func_relative_path_tcancelled=$func_relative_path_tbindir
+          break
+        fi
+        func_relative_path_result=../$func_relative_path_result
+        ;;
+    esac
+  done
+
+  # Now calculate path; take care to avoid doubling-up slashes.
+  func_stripname '' '/' "$func_relative_path_result"
+  func_relative_path_result=$func_stripname_result
+  func_stripname '/' '/' "$func_relative_path_tcancelled"
+  if test "x$func_stripname_result" != x ; then
+    func_relative_path_result=${func_relative_path_result}/${func_stripname_result}
+  fi
+
+  # Normalisation. If bindir is libdir, return empty string,
+  # else relative path ending with a slash; either way, target
+  # file name can be directly appended.
+  if test ! -z "$func_relative_path_result"; then
+    func_stripname './' '' "$func_relative_path_result/"
+    func_relative_path_result=$func_stripname_result
+  fi
+}
+
+# The name of this program:
+func_dirname_and_basename "$progpath"
+progname=$func_basename_result
+
+# Make sure we have an absolute path for reexecution:
+case $progpath in
+  [\\/]*|[A-Za-z]:\\*) ;;
+  *[\\/]*)
+     progdir=$func_dirname_result
+     progdir=`cd "$progdir" && pwd`
+     progpath="$progdir/$progname"
+     ;;
+  *)
+     save_IFS="$IFS"
+     IFS=${PATH_SEPARATOR-:}
+     for progdir in $PATH; do
+       IFS="$save_IFS"
+       test -x "$progdir/$progname" && break
+     done
+     IFS="$save_IFS"
+     test -n "$progdir" || progdir=`pwd`
+     progpath="$progdir/$progname"
+     ;;
+esac
+
+# Sed substitution that helps us do robust quoting.  It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed="${SED}"' -e 1s/^X//'
+sed_quote_subst='s/\([`"$\\]\)/\\\1/g'
+
+# Same as above, but do not quote variable references.
+double_quote_subst='s/\(["`\\]\)/\\\1/g'
+
+# Sed substitution that turns a string into a regex matching for the
+# string literally.
+sed_make_literal_regex='s,[].[^$\\*\/],\\&,g'
+
+# Sed substitution that converts a w32 file name or path
+# which contains forward slashes, into one that contains
+# (escaped) backslashes.  A very naive implementation.
+lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
+
+# Re-`\' parameter expansions in output of double_quote_subst that were
+# `\'-ed in input to the same.  If an odd number of `\' preceded a '$'
+# in input to double_quote_subst, that '$' was protected from expansion.
+# Since each input `\' is now two `\'s, look for any number of runs of
+# four `\'s followed by two `\'s and then a '$'.  `\' that '$'.
+bs='\\'
+bs2='\\\\'
+bs4='\\\\\\\\'
+dollar='\$'
+sed_double_backslash="\
+  s/$bs4/&\\
+/g
+  s/^$bs2$dollar/$bs&/
+  s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g
+  s/\n//g"
+
+# Standard options:
+opt_dry_run=false
+opt_help=false
+opt_quiet=false
+opt_verbose=false
+opt_warning=:
+
+# func_echo arg...
+# Echo program name prefixed message, along with the current mode
+# name if it has been set yet.
+func_echo ()
+{
+    $ECHO "$progname: ${opt_mode+$opt_mode: }$*"
+}
+
+# func_verbose arg...
+# Echo program name prefixed message in verbose mode only.
+func_verbose ()
+{
+    $opt_verbose && func_echo ${1+"$@"}
+
+    # A bug in bash halts the script if the last line of a function
+    # fails when set -e is in force, so we need another command to
+    # work around that:
+    :
+}
+
+# func_echo_all arg...
+# Invoke $ECHO with all args, space-separated.
+func_echo_all ()
+{
+    $ECHO "$*"
+}
+
+# func_error arg...
+# Echo program name prefixed message to standard error.
+func_error ()
+{
+    $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2
+}
+
+# func_warning arg...
+# Echo program name prefixed warning message to standard error.
+func_warning ()
+{
+    $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2
+
+    # bash bug again:
+    :
+}
+
+# func_fatal_error arg...
+# Echo program name prefixed message to standard error, and exit.
+func_fatal_error ()
+{
+    func_error ${1+"$@"}
+    exit $EXIT_FAILURE
+}
+
+# func_fatal_help arg...
+# Echo program name prefixed message to standard error, followed by
+# a help hint, and exit.
+func_fatal_help ()
+{
+    func_error ${1+"$@"}
+    func_fatal_error "$help"
+}
+help="Try \`$progname --help' for more information."  ## default
+
+
+# func_grep expression filename
+# Check whether EXPRESSION matches any line of FILENAME, without output.
+func_grep ()
+{
+    $GREP "$1" "$2" >/dev/null 2>&1
+}
+
+
+# func_mkdir_p directory-path
+# Make sure the entire path to DIRECTORY-PATH is available.
+func_mkdir_p ()
+{
+    my_directory_path="$1"
+    my_dir_list=
+
+    if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then
+
+      # Protect directory names starting with `-'
+      case $my_directory_path in
+        -*) my_directory_path="./$my_directory_path" ;;
+      esac
+
+      # While some portion of DIR does not yet exist...
+      while test ! -d "$my_directory_path"; do
+        # ...make a list in topmost first order.  Use a colon delimited
+	# list incase some portion of path contains whitespace.
+        my_dir_list="$my_directory_path:$my_dir_list"
+
+        # If the last portion added has no slash in it, the list is done
+        case $my_directory_path in */*) ;; *) break ;; esac
+
+        # ...otherwise throw away the child directory and loop
+        my_directory_path=`$ECHO "$my_directory_path" | $SED -e "$dirname"`
+      done
+      my_dir_list=`$ECHO "$my_dir_list" | $SED 's,:*$,,'`
+
+      save_mkdir_p_IFS="$IFS"; IFS=':'
+      for my_dir in $my_dir_list; do
+	IFS="$save_mkdir_p_IFS"
+        # mkdir can fail with a `File exist' error if two processes
+        # try to create one of the directories concurrently.  Don't
+        # stop in that case!
+        $MKDIR "$my_dir" 2>/dev/null || :
+      done
+      IFS="$save_mkdir_p_IFS"
+
+      # Bail out if we (or some other process) failed to create a directory.
+      test -d "$my_directory_path" || \
+        func_fatal_error "Failed to create \`$1'"
+    fi
+}
+
+
+# func_mktempdir [string]
+# Make a temporary directory that won't clash with other running
+# libtool processes, and avoids race conditions if possible.  If
+# given, STRING is the basename for that directory.
+func_mktempdir ()
+{
+    my_template="${TMPDIR-/tmp}/${1-$progname}"
+
+    if test "$opt_dry_run" = ":"; then
+      # Return a directory name, but don't create it in dry-run mode
+      my_tmpdir="${my_template}-$$"
+    else
+
+      # If mktemp works, use that first and foremost
+      my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null`
+
+      if test ! -d "$my_tmpdir"; then
+        # Failing that, at least try and use $RANDOM to avoid a race
+        my_tmpdir="${my_template}-${RANDOM-0}$$"
+
+        save_mktempdir_umask=`umask`
+        umask 0077
+        $MKDIR "$my_tmpdir"
+        umask $save_mktempdir_umask
+      fi
+
+      # If we're not in dry-run mode, bomb out on failure
+      test -d "$my_tmpdir" || \
+        func_fatal_error "cannot create temporary directory \`$my_tmpdir'"
+    fi
+
+    $ECHO "$my_tmpdir"
+}
+
+
+# func_quote_for_eval arg
+# Aesthetically quote ARG to be evaled later.
+# This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT
+# is double-quoted, suitable for a subsequent eval, whereas
+# FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters
+# which are still active within double quotes backslashified.
+func_quote_for_eval ()
+{
+    case $1 in
+      *[\\\`\"\$]*)
+	func_quote_for_eval_unquoted_result=`$ECHO "$1" | $SED "$sed_quote_subst"` ;;
+      *)
+        func_quote_for_eval_unquoted_result="$1" ;;
+    esac
+
+    case $func_quote_for_eval_unquoted_result in
+      # Double-quote args containing shell metacharacters to delay
+      # word splitting, command substitution and and variable
+      # expansion for a subsequent eval.
+      # Many Bourne shells cannot handle close brackets correctly
+      # in scan sets, so we specify it separately.
+      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
+        func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\""
+        ;;
+      *)
+        func_quote_for_eval_result="$func_quote_for_eval_unquoted_result"
+    esac
+}
+
+
+# func_quote_for_expand arg
+# Aesthetically quote ARG to be evaled later; same as above,
+# but do not quote variable references.
+func_quote_for_expand ()
+{
+    case $1 in
+      *[\\\`\"]*)
+	my_arg=`$ECHO "$1" | $SED \
+	    -e "$double_quote_subst" -e "$sed_double_backslash"` ;;
+      *)
+        my_arg="$1" ;;
+    esac
+
+    case $my_arg in
+      # Double-quote args containing shell metacharacters to delay
+      # word splitting and command substitution for a subsequent eval.
+      # Many Bourne shells cannot handle close brackets correctly
+      # in scan sets, so we specify it separately.
+      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
+        my_arg="\"$my_arg\""
+        ;;
+    esac
+
+    func_quote_for_expand_result="$my_arg"
+}
+
+
+# func_show_eval cmd [fail_exp]
+# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is
+# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
+# is given, then evaluate it.
+func_show_eval ()
+{
+    my_cmd="$1"
+    my_fail_exp="${2-:}"
+
+    ${opt_silent-false} || {
+      func_quote_for_expand "$my_cmd"
+      eval "func_echo $func_quote_for_expand_result"
+    }
+
+    if ${opt_dry_run-false}; then :; else
+      eval "$my_cmd"
+      my_status=$?
+      if test "$my_status" -eq 0; then :; else
+	eval "(exit $my_status); $my_fail_exp"
+      fi
+    fi
+}
+
+
+# func_show_eval_locale cmd [fail_exp]
+# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is
+# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
+# is given, then evaluate it.  Use the saved locale for evaluation.
+func_show_eval_locale ()
+{
+    my_cmd="$1"
+    my_fail_exp="${2-:}"
+
+    ${opt_silent-false} || {
+      func_quote_for_expand "$my_cmd"
+      eval "func_echo $func_quote_for_expand_result"
+    }
+
+    if ${opt_dry_run-false}; then :; else
+      eval "$lt_user_locale
+	    $my_cmd"
+      my_status=$?
+      eval "$lt_safe_locale"
+      if test "$my_status" -eq 0; then :; else
+	eval "(exit $my_status); $my_fail_exp"
+      fi
+    fi
+}
+
+# func_tr_sh
+# Turn $1 into a string suitable for a shell variable name.
+# Result is stored in $func_tr_sh_result.  All characters
+# not in the set a-zA-Z0-9_ are replaced with '_'. Further,
+# if $1 begins with a digit, a '_' is prepended as well.
+func_tr_sh ()
+{
+  case $1 in
+  [0-9]* | *[!a-zA-Z0-9_]*)
+    func_tr_sh_result=`$ECHO "$1" | $SED 's/^\([0-9]\)/_\1/; s/[^a-zA-Z0-9_]/_/g'`
+    ;;
+  * )
+    func_tr_sh_result=$1
+    ;;
+  esac
+}
+
+
+# func_version
+# Echo version message to standard output and exit.
+func_version ()
+{
+    $opt_debug
+
+    $SED -n '/(C)/!b go
+	:more
+	/\./!{
+	  N
+	  s/\n# / /
+	  b more
+	}
+	:go
+	/^# '$PROGRAM' (GNU /,/# warranty; / {
+        s/^# //
+	s/^# *$//
+        s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/
+        p
+     }' < "$progpath"
+     exit $?
+}
+
+# func_usage
+# Echo short help message to standard output and exit.
+func_usage ()
+{
+    $opt_debug
+
+    $SED -n '/^# Usage:/,/^#  *.*--help/ {
+        s/^# //
+	s/^# *$//
+	s/\$progname/'$progname'/
+	p
+    }' < "$progpath"
+    echo
+    $ECHO "run \`$progname --help | more' for full usage"
+    exit $?
+}
+
+# func_help [NOEXIT]
+# Echo long help message to standard output and exit,
+# unless 'noexit' is passed as argument.
+func_help ()
+{
+    $opt_debug
+
+    $SED -n '/^# Usage:/,/# Report bugs to/ {
+	:print
+        s/^# //
+	s/^# *$//
+	s*\$progname*'$progname'*
+	s*\$host*'"$host"'*
+	s*\$SHELL*'"$SHELL"'*
+	s*\$LTCC*'"$LTCC"'*
+	s*\$LTCFLAGS*'"$LTCFLAGS"'*
+	s*\$LD*'"$LD"'*
+	s/\$with_gnu_ld/'"$with_gnu_ld"'/
+	s/\$automake_version/'"`(${AUTOMAKE-automake} --version) 2>/dev/null |$SED 1q`"'/
+	s/\$autoconf_version/'"`(${AUTOCONF-autoconf} --version) 2>/dev/null |$SED 1q`"'/
+	p
+	d
+     }
+     /^# .* home page:/b print
+     /^# General help using/b print
+     ' < "$progpath"
+    ret=$?
+    if test -z "$1"; then
+      exit $ret
+    fi
+}
+
+# func_missing_arg argname
+# Echo program name prefixed message to standard error and set global
+# exit_cmd.
+func_missing_arg ()
+{
+    $opt_debug
+
+    func_error "missing argument for $1."
+    exit_cmd=exit
+}
+
+
+# func_split_short_opt shortopt
+# Set func_split_short_opt_name and func_split_short_opt_arg shell
+# variables after splitting SHORTOPT after the 2nd character.
+func_split_short_opt ()
+{
+    my_sed_short_opt='1s/^\(..\).*$/\1/;q'
+    my_sed_short_rest='1s/^..\(.*\)$/\1/;q'
+
+    func_split_short_opt_name=`$ECHO "$1" | $SED "$my_sed_short_opt"`
+    func_split_short_opt_arg=`$ECHO "$1" | $SED "$my_sed_short_rest"`
+} # func_split_short_opt may be replaced by extended shell implementation
+
+
+# func_split_long_opt longopt
+# Set func_split_long_opt_name and func_split_long_opt_arg shell
+# variables after splitting LONGOPT at the `=' sign.
+func_split_long_opt ()
+{
+    my_sed_long_opt='1s/^\(--[^=]*\)=.*/\1/;q'
+    my_sed_long_arg='1s/^--[^=]*=//'
+
+    func_split_long_opt_name=`$ECHO "$1" | $SED "$my_sed_long_opt"`
+    func_split_long_opt_arg=`$ECHO "$1" | $SED "$my_sed_long_arg"`
+} # func_split_long_opt may be replaced by extended shell implementation
+
+exit_cmd=:
+
+
+
+
+
+magic="%%%MAGIC variable%%%"
+magic_exe="%%%MAGIC EXE variable%%%"
+
+# Global variables.
+nonopt=
+preserve_args=
+lo2o="s/\\.lo\$/.${objext}/"
+o2lo="s/\\.${objext}\$/.lo/"
+extracted_archives=
+extracted_serial=0
+
+# If this variable is set in any of the actions, the command in it
+# will be execed at the end.  This prevents here-documents from being
+# left over by shells.
+exec_cmd=
+
+# func_append var value
+# Append VALUE to the end of shell variable VAR.
+func_append ()
+{
+    eval "${1}=\$${1}\${2}"
+} # func_append may be replaced by extended shell implementation
+
+# func_append_quoted var value
+# Quote VALUE and append to the end of shell variable VAR, separated
+# by a space.
+func_append_quoted ()
+{
+    func_quote_for_eval "${2}"
+    eval "${1}=\$${1}\\ \$func_quote_for_eval_result"
+} # func_append_quoted may be replaced by extended shell implementation
+
+
+# func_arith arithmetic-term...
+func_arith ()
+{
+    func_arith_result=`expr "${@}"`
+} # func_arith may be replaced by extended shell implementation
+
+
+# func_len string
+# STRING may not start with a hyphen.
+func_len ()
+{
+    func_len_result=`expr "${1}" : ".*" 2>/dev/null || echo $max_cmd_len`
+} # func_len may be replaced by extended shell implementation
+
+
+# func_lo2o object
+func_lo2o ()
+{
+    func_lo2o_result=`$ECHO "${1}" | $SED "$lo2o"`
+} # func_lo2o may be replaced by extended shell implementation
+
+
+# func_xform libobj-or-source
+func_xform ()
+{
+    func_xform_result=`$ECHO "${1}" | $SED 's/\.[^.]*$/.lo/'`
+} # func_xform may be replaced by extended shell implementation
+
+
+# func_fatal_configuration arg...
+# Echo program name prefixed message to standard error, followed by
+# a configuration failure hint, and exit.
+func_fatal_configuration ()
+{
+    func_error ${1+"$@"}
+    func_error "See the $PACKAGE documentation for more information."
+    func_fatal_error "Fatal configuration error."
+}
+
+
+# func_config
+# Display the configuration for all the tags in this script.
+func_config ()
+{
+    re_begincf='^# ### BEGIN LIBTOOL'
+    re_endcf='^# ### END LIBTOOL'
+
+    # Default configuration.
+    $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath"
+
+    # Now print the configurations for the tags.
+    for tagname in $taglist; do
+      $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath"
+    done
+
+    exit $?
+}
+
+# func_features
+# Display the features supported by this script.
+func_features ()
+{
+    echo "host: $host"
+    if test "$build_libtool_libs" = yes; then
+      echo "enable shared libraries"
+    else
+      echo "disable shared libraries"
+    fi
+    if test "$build_old_libs" = yes; then
+      echo "enable static libraries"
+    else
+      echo "disable static libraries"
+    fi
+
+    exit $?
+}
+
+# func_enable_tag tagname
+# Verify that TAGNAME is valid, and either flag an error and exit, or
+# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist
+# variable here.
+func_enable_tag ()
+{
+  # Global variable:
+  tagname="$1"
+
+  re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$"
+  re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$"
+  sed_extractcf="/$re_begincf/,/$re_endcf/p"
+
+  # Validate tagname.
+  case $tagname in
+    *[!-_A-Za-z0-9,/]*)
+      func_fatal_error "invalid tag name: $tagname"
+      ;;
+  esac
+
+  # Don't test for the "default" C tag, as we know it's
+  # there but not specially marked.
+  case $tagname in
+    CC) ;;
+    *)
+      if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then
+	taglist="$taglist $tagname"
+
+	# Evaluate the configuration.  Be careful to quote the path
+	# and the sed script, to avoid splitting on whitespace, but
+	# also don't use non-portable quotes within backquotes within
+	# quotes we have to do it in 2 steps:
+	extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"`
+	eval "$extractedcf"
+      else
+	func_error "ignoring unknown tag $tagname"
+      fi
+      ;;
+  esac
+}
+
+# func_check_version_match
+# Ensure that we are using m4 macros, and libtool script from the same
+# release of libtool.
+func_check_version_match ()
+{
+  if test "$package_revision" != "$macro_revision"; then
+    if test "$VERSION" != "$macro_version"; then
+      if test -z "$macro_version"; then
+        cat >&2 <<_LT_EOF
+$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the
+$progname: definition of this LT_INIT comes from an older release.
+$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION
+$progname: and run autoconf again.
+_LT_EOF
+      else
+        cat >&2 <<_LT_EOF
+$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the
+$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.
+$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION
+$progname: and run autoconf again.
+_LT_EOF
+      fi
+    else
+      cat >&2 <<_LT_EOF
+$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,
+$progname: but the definition of this LT_INIT comes from revision $macro_revision.
+$progname: You should recreate aclocal.m4 with macros from revision $package_revision
+$progname: of $PACKAGE $VERSION and run autoconf again.
+_LT_EOF
+    fi
+
+    exit $EXIT_MISMATCH
+  fi
+}
+
+
+# Shorthand for --mode=foo, only valid as the first argument
+case $1 in
+clean|clea|cle|cl)
+  shift; set dummy --mode clean ${1+"$@"}; shift
+  ;;
+compile|compil|compi|comp|com|co|c)
+  shift; set dummy --mode compile ${1+"$@"}; shift
+  ;;
+execute|execut|execu|exec|exe|ex|e)
+  shift; set dummy --mode execute ${1+"$@"}; shift
+  ;;
+finish|finis|fini|fin|fi|f)
+  shift; set dummy --mode finish ${1+"$@"}; shift
+  ;;
+install|instal|insta|inst|ins|in|i)
+  shift; set dummy --mode install ${1+"$@"}; shift
+  ;;
+link|lin|li|l)
+  shift; set dummy --mode link ${1+"$@"}; shift
+  ;;
+uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)
+  shift; set dummy --mode uninstall ${1+"$@"}; shift
+  ;;
+esac
+
+
+
+# Option defaults:
+opt_debug=:
+opt_dry_run=false
+opt_config=false
+opt_preserve_dup_deps=false
+opt_features=false
+opt_finish=false
+opt_help=false
+opt_help_all=false
+opt_silent=:
+opt_warning=:
+opt_verbose=:
+opt_silent=false
+opt_verbose=false
+
+
+# Parse options once, thoroughly.  This comes as soon as possible in the
+# script to make things like `--version' happen as quickly as we can.
+{
+  # this just eases exit handling
+  while test $# -gt 0; do
+    opt="$1"
+    shift
+    case $opt in
+      --debug|-x)	opt_debug='set -x'
+			func_echo "enabling shell trace mode"
+			$opt_debug
+			;;
+      --dry-run|--dryrun|-n)
+			opt_dry_run=:
+			;;
+      --config)
+			opt_config=:
+func_config
+			;;
+      --dlopen|-dlopen)
+			optarg="$1"
+			opt_dlopen="${opt_dlopen+$opt_dlopen
+}$optarg"
+			shift
+			;;
+      --preserve-dup-deps)
+			opt_preserve_dup_deps=:
+			;;
+      --features)
+			opt_features=:
+func_features
+			;;
+      --finish)
+			opt_finish=:
+set dummy --mode finish ${1+"$@"}; shift
+			;;
+      --help)
+			opt_help=:
+			;;
+      --help-all)
+			opt_help_all=:
+opt_help=': help-all'
+			;;
+      --mode)
+			test $# = 0 && func_missing_arg $opt && break
+			optarg="$1"
+			opt_mode="$optarg"
+case $optarg in
+  # Valid mode arguments:
+  clean|compile|execute|finish|install|link|relink|uninstall) ;;
+
+  # Catch anything else as an error
+  *) func_error "invalid argument for $opt"
+     exit_cmd=exit
+     break
+     ;;
+esac
+			shift
+			;;
+      --no-silent|--no-quiet)
+			opt_silent=false
+func_append preserve_args " $opt"
+			;;
+      --no-warning|--no-warn)
+			opt_warning=false
+func_append preserve_args " $opt"
+			;;
+      --no-verbose)
+			opt_verbose=false
+func_append preserve_args " $opt"
+			;;
+      --silent|--quiet)
+			opt_silent=:
+func_append preserve_args " $opt"
+        opt_verbose=false
+			;;
+      --verbose|-v)
+			opt_verbose=:
+func_append preserve_args " $opt"
+opt_silent=false
+			;;
+      --tag)
+			test $# = 0 && func_missing_arg $opt && break
+			optarg="$1"
+			opt_tag="$optarg"
+func_append preserve_args " $opt $optarg"
+func_enable_tag "$optarg"
+			shift
+			;;
+
+      -\?|-h)		func_usage				;;
+      --help)		func_help				;;
+      --version)	func_version				;;
+
+      # Separate optargs to long options:
+      --*=*)
+			func_split_long_opt "$opt"
+			set dummy "$func_split_long_opt_name" "$func_split_long_opt_arg" ${1+"$@"}
+			shift
+			;;
+
+      # Separate non-argument short options:
+      -\?*|-h*|-n*|-v*)
+			func_split_short_opt "$opt"
+			set dummy "$func_split_short_opt_name" "-$func_split_short_opt_arg" ${1+"$@"}
+			shift
+			;;
+
+      --)		break					;;
+      -*)		func_fatal_help "unrecognized option \`$opt'" ;;
+      *)		set dummy "$opt" ${1+"$@"};	shift; break  ;;
+    esac
+  done
+
+  # Validate options:
+
+  # save first non-option argument
+  if test "$#" -gt 0; then
+    nonopt="$opt"
+    shift
+  fi
+
+  # preserve --debug
+  test "$opt_debug" = : || func_append preserve_args " --debug"
+
+  case $host in
+    *cygwin* | *mingw* | *pw32* | *cegcc*)
+      # don't eliminate duplications in $postdeps and $predeps
+      opt_duplicate_compiler_generated_deps=:
+      ;;
+    *)
+      opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps
+      ;;
+  esac
+
+  $opt_help || {
+    # Sanity checks first:
+    func_check_version_match
+
+    if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
+      func_fatal_configuration "not configured to build any kind of library"
+    fi
+
+    # Darwin sucks
+    eval std_shrext=\"$shrext_cmds\"
+
+    # Only execute mode is allowed to have -dlopen flags.
+    if test -n "$opt_dlopen" && test "$opt_mode" != execute; then
+      func_error "unrecognized option \`-dlopen'"
+      $ECHO "$help" 1>&2
+      exit $EXIT_FAILURE
+    fi
+
+    # Change the help message to a mode-specific one.
+    generic_help="$help"
+    help="Try \`$progname --help --mode=$opt_mode' for more information."
+  }
+
+
+  # Bail if the options were screwed
+  $exit_cmd $EXIT_FAILURE
+}
+
+
+
+
+## ----------- ##
+##    Main.    ##
+## ----------- ##
+
+# func_lalib_p file
+# True iff FILE is a libtool `.la' library or `.lo' object file.
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_lalib_p ()
+{
+    test -f "$1" &&
+      $SED -e 4q "$1" 2>/dev/null \
+        | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1
+}
+
+# func_lalib_unsafe_p file
+# True iff FILE is a libtool `.la' library or `.lo' object file.
+# This function implements the same check as func_lalib_p without
+# resorting to external programs.  To this end, it redirects stdin and
+# closes it afterwards, without saving the original file descriptor.
+# As a safety measure, use it only where a negative result would be
+# fatal anyway.  Works if `file' does not exist.
+func_lalib_unsafe_p ()
+{
+    lalib_p=no
+    if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then
+	for lalib_p_l in 1 2 3 4
+	do
+	    read lalib_p_line
+	    case "$lalib_p_line" in
+		\#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;;
+	    esac
+	done
+	exec 0<&5 5<&-
+    fi
+    test "$lalib_p" = yes
+}
+
+# func_ltwrapper_script_p file
+# True iff FILE is a libtool wrapper script
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_ltwrapper_script_p ()
+{
+    func_lalib_p "$1"
+}
+
+# func_ltwrapper_executable_p file
+# True iff FILE is a libtool wrapper executable
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_ltwrapper_executable_p ()
+{
+    func_ltwrapper_exec_suffix=
+    case $1 in
+    *.exe) ;;
+    *) func_ltwrapper_exec_suffix=.exe ;;
+    esac
+    $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1
+}
+
+# func_ltwrapper_scriptname file
+# Assumes file is an ltwrapper_executable
+# uses $file to determine the appropriate filename for a
+# temporary ltwrapper_script.
+func_ltwrapper_scriptname ()
+{
+    func_dirname_and_basename "$1" "" "."
+    func_stripname '' '.exe' "$func_basename_result"
+    func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper"
+}
+
+# func_ltwrapper_p file
+# True iff FILE is a libtool wrapper script or wrapper executable
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_ltwrapper_p ()
+{
+    func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1"
+}
+
+
+# func_execute_cmds commands fail_cmd
+# Execute tilde-delimited COMMANDS.
+# If FAIL_CMD is given, eval that upon failure.
+# FAIL_CMD may read-access the current command in variable CMD!
+func_execute_cmds ()
+{
+    $opt_debug
+    save_ifs=$IFS; IFS='~'
+    for cmd in $1; do
+      IFS=$save_ifs
+      eval cmd=\"$cmd\"
+      func_show_eval "$cmd" "${2-:}"
+    done
+    IFS=$save_ifs
+}
+
+
+# func_source file
+# Source FILE, adding directory component if necessary.
+# Note that it is not necessary on cygwin/mingw to append a dot to
+# FILE even if both FILE and FILE.exe exist: automatic-append-.exe
+# behavior happens only for exec(3), not for open(2)!  Also, sourcing
+# `FILE.' does not work on cygwin managed mounts.
+func_source ()
+{
+    $opt_debug
+    case $1 in
+    */* | *\\*)	. "$1" ;;
+    *)		. "./$1" ;;
+    esac
+}
+
+
+# func_resolve_sysroot PATH
+# Replace a leading = in PATH with a sysroot.  Store the result into
+# func_resolve_sysroot_result
+func_resolve_sysroot ()
+{
+  func_resolve_sysroot_result=$1
+  case $func_resolve_sysroot_result in
+  =*)
+    func_stripname '=' '' "$func_resolve_sysroot_result"
+    func_resolve_sysroot_result=$lt_sysroot$func_stripname_result
+    ;;
+  esac
+}
+
+# func_replace_sysroot PATH
+# If PATH begins with the sysroot, replace it with = and
+# store the result into func_replace_sysroot_result.
+func_replace_sysroot ()
+{
+  case "$lt_sysroot:$1" in
+  ?*:"$lt_sysroot"*)
+    func_stripname "$lt_sysroot" '' "$1"
+    func_replace_sysroot_result="=$func_stripname_result"
+    ;;
+  *)
+    # Including no sysroot.
+    func_replace_sysroot_result=$1
+    ;;
+  esac
+}
+
+# func_infer_tag arg
+# Infer tagged configuration to use if any are available and
+# if one wasn't chosen via the "--tag" command line option.
+# Only attempt this if the compiler in the base compile
+# command doesn't match the default compiler.
+# arg is usually of the form 'gcc ...'
+func_infer_tag ()
+{
+    $opt_debug
+    if test -n "$available_tags" && test -z "$tagname"; then
+      CC_quoted=
+      for arg in $CC; do
+	func_append_quoted CC_quoted "$arg"
+      done
+      CC_expanded=`func_echo_all $CC`
+      CC_quoted_expanded=`func_echo_all $CC_quoted`
+      case $@ in
+      # Blanks in the command may have been stripped by the calling shell,
+      # but not from the CC environment variable when configure was run.
+      " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \
+      " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;;
+      # Blanks at the start of $base_compile will cause this to fail
+      # if we don't check for them as well.
+      *)
+	for z in $available_tags; do
+	  if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then
+	    # Evaluate the configuration.
+	    eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`"
+	    CC_quoted=
+	    for arg in $CC; do
+	      # Double-quote args containing other shell metacharacters.
+	      func_append_quoted CC_quoted "$arg"
+	    done
+	    CC_expanded=`func_echo_all $CC`
+	    CC_quoted_expanded=`func_echo_all $CC_quoted`
+	    case "$@ " in
+	    " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \
+	    " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*)
+	      # The compiler in the base compile command matches
+	      # the one in the tagged configuration.
+	      # Assume this is the tagged configuration we want.
+	      tagname=$z
+	      break
+	      ;;
+	    esac
+	  fi
+	done
+	# If $tagname still isn't set, then no tagged configuration
+	# was found and let the user know that the "--tag" command
+	# line option must be used.
+	if test -z "$tagname"; then
+	  func_echo "unable to infer tagged configuration"
+	  func_fatal_error "specify a tag with \`--tag'"
+#	else
+#	  func_verbose "using $tagname tagged configuration"
+	fi
+	;;
+      esac
+    fi
+}
+
+
+
+# func_write_libtool_object output_name pic_name nonpic_name
+# Create a libtool object file (analogous to a ".la" file),
+# but don't create it if we're doing a dry run.
+func_write_libtool_object ()
+{
+    write_libobj=${1}
+    if test "$build_libtool_libs" = yes; then
+      write_lobj=\'${2}\'
+    else
+      write_lobj=none
+    fi
+
+    if test "$build_old_libs" = yes; then
+      write_oldobj=\'${3}\'
+    else
+      write_oldobj=none
+    fi
+
+    $opt_dry_run || {
+      cat >${write_libobj}T <<EOF
+# $write_libobj - a libtool object file
+# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+#
+# Please DO NOT delete this file!
+# It is necessary for linking the library.
+
+# Name of the PIC object.
+pic_object=$write_lobj
+
+# Name of the non-PIC object
+non_pic_object=$write_oldobj
+
+EOF
+      $MV "${write_libobj}T" "${write_libobj}"
+    }
+}
+
+
+##################################################
+# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #
+##################################################
+
+# func_convert_core_file_wine_to_w32 ARG
+# Helper function used by file name conversion functions when $build is *nix,
+# and $host is mingw, cygwin, or some other w32 environment. Relies on a
+# correctly configured wine environment available, with the winepath program
+# in $build's $PATH.
+#
+# ARG is the $build file name to be converted to w32 format.
+# Result is available in $func_convert_core_file_wine_to_w32_result, and will
+# be empty on error (or when ARG is empty)
+func_convert_core_file_wine_to_w32 ()
+{
+  $opt_debug
+  func_convert_core_file_wine_to_w32_result="$1"
+  if test -n "$1"; then
+    # Unfortunately, winepath does not exit with a non-zero error code, so we
+    # are forced to check the contents of stdout. On the other hand, if the
+    # command is not found, the shell will set an exit code of 127 and print
+    # *an error message* to stdout. So we must check for both error code of
+    # zero AND non-empty stdout, which explains the odd construction:
+    func_convert_core_file_wine_to_w32_tmp=`winepath -w "$1" 2>/dev/null`
+    if test "$?" -eq 0 && test -n "${func_convert_core_file_wine_to_w32_tmp}"; then
+      func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" |
+        $SED -e "$lt_sed_naive_backslashify"`
+    else
+      func_convert_core_file_wine_to_w32_result=
+    fi
+  fi
+}
+# end: func_convert_core_file_wine_to_w32
+
+
+# func_convert_core_path_wine_to_w32 ARG
+# Helper function used by path conversion functions when $build is *nix, and
+# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly
+# configured wine environment available, with the winepath program in $build's
+# $PATH. Assumes ARG has no leading or trailing path separator characters.
+#
+# ARG is path to be converted from $build format to win32.
+# Result is available in $func_convert_core_path_wine_to_w32_result.
+# Unconvertible file (directory) names in ARG are skipped; if no directory names
+# are convertible, then the result may be empty.
+func_convert_core_path_wine_to_w32 ()
+{
+  $opt_debug
+  # unfortunately, winepath doesn't convert paths, only file names
+  func_convert_core_path_wine_to_w32_result=""
+  if test -n "$1"; then
+    oldIFS=$IFS
+    IFS=:
+    for func_convert_core_path_wine_to_w32_f in $1; do
+      IFS=$oldIFS
+      func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f"
+      if test -n "$func_convert_core_file_wine_to_w32_result" ; then
+        if test -z "$func_convert_core_path_wine_to_w32_result"; then
+          func_convert_core_path_wine_to_w32_result="$func_convert_core_file_wine_to_w32_result"
+        else
+          func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result"
+        fi
+      fi
+    done
+    IFS=$oldIFS
+  fi
+}
+# end: func_convert_core_path_wine_to_w32
+
+
+# func_cygpath ARGS...
+# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when
+# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2)
+# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or
+# (2), returns the Cygwin file name or path in func_cygpath_result (input
+# file name or path is assumed to be in w32 format, as previously converted
+# from $build's *nix or MSYS format). In case (3), returns the w32 file name
+# or path in func_cygpath_result (input file name or path is assumed to be in
+# Cygwin format). Returns an empty string on error.
+#
+# ARGS are passed to cygpath, with the last one being the file name or path to
+# be converted.
+#
+# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH
+# environment variable; do not put it in $PATH.
+func_cygpath ()
+{
+  $opt_debug
+  if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then
+    func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null`
+    if test "$?" -ne 0; then
+      # on failure, ensure result is empty
+      func_cygpath_result=
+    fi
+  else
+    func_cygpath_result=
+    func_error "LT_CYGPATH is empty or specifies non-existent file: \`$LT_CYGPATH'"
+  fi
+}
+#end: func_cygpath
+
+
+# func_convert_core_msys_to_w32 ARG
+# Convert file name or path ARG from MSYS format to w32 format.  Return
+# result in func_convert_core_msys_to_w32_result.
+func_convert_core_msys_to_w32 ()
+{
+  $opt_debug
+  # awkward: cmd appends spaces to result
+  func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null |
+    $SED -e 's/[ ]*$//' -e "$lt_sed_naive_backslashify"`
+}
+#end: func_convert_core_msys_to_w32
+
+
+# func_convert_file_check ARG1 ARG2
+# Verify that ARG1 (a file name in $build format) was converted to $host
+# format in ARG2. Otherwise, emit an error message, but continue (resetting
+# func_to_host_file_result to ARG1).
+func_convert_file_check ()
+{
+  $opt_debug
+  if test -z "$2" && test -n "$1" ; then
+    func_error "Could not determine host file name corresponding to"
+    func_error "  \`$1'"
+    func_error "Continuing, but uninstalled executables may not work."
+    # Fallback:
+    func_to_host_file_result="$1"
+  fi
+}
+# end func_convert_file_check
+
+
+# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH
+# Verify that FROM_PATH (a path in $build format) was converted to $host
+# format in TO_PATH. Otherwise, emit an error message, but continue, resetting
+# func_to_host_file_result to a simplistic fallback value (see below).
+func_convert_path_check ()
+{
+  $opt_debug
+  if test -z "$4" && test -n "$3"; then
+    func_error "Could not determine the host path corresponding to"
+    func_error "  \`$3'"
+    func_error "Continuing, but uninstalled executables may not work."
+    # Fallback.  This is a deliberately simplistic "conversion" and
+    # should not be "improved".  See libtool.info.
+    if test "x$1" != "x$2"; then
+      lt_replace_pathsep_chars="s|$1|$2|g"
+      func_to_host_path_result=`echo "$3" |
+        $SED -e "$lt_replace_pathsep_chars"`
+    else
+      func_to_host_path_result="$3"
+    fi
+  fi
+}
+# end func_convert_path_check
+
+
+# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG
+# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT
+# and appending REPL if ORIG matches BACKPAT.
+func_convert_path_front_back_pathsep ()
+{
+  $opt_debug
+  case $4 in
+  $1 ) func_to_host_path_result="$3$func_to_host_path_result"
+    ;;
+  esac
+  case $4 in
+  $2 ) func_append func_to_host_path_result "$3"
+    ;;
+  esac
+}
+# end func_convert_path_front_back_pathsep
+
+
+##################################################
+# $build to $host FILE NAME CONVERSION FUNCTIONS #
+##################################################
+# invoked via `$to_host_file_cmd ARG'
+#
+# In each case, ARG is the path to be converted from $build to $host format.
+# Result will be available in $func_to_host_file_result.
+
+
+# func_to_host_file ARG
+# Converts the file name ARG from $build format to $host format. Return result
+# in func_to_host_file_result.
+func_to_host_file ()
+{
+  $opt_debug
+  $to_host_file_cmd "$1"
+}
+# end func_to_host_file
+
+
+# func_to_tool_file ARG LAZY
+# converts the file name ARG from $build format to toolchain format. Return
+# result in func_to_tool_file_result.  If the conversion in use is listed
+# in (the comma separated) LAZY, no conversion takes place.
+func_to_tool_file ()
+{
+  $opt_debug
+  case ,$2, in
+    *,"$to_tool_file_cmd",*)
+      func_to_tool_file_result=$1
+      ;;
+    *)
+      $to_tool_file_cmd "$1"
+      func_to_tool_file_result=$func_to_host_file_result
+      ;;
+  esac
+}
+# end func_to_tool_file
+
+
+# func_convert_file_noop ARG
+# Copy ARG to func_to_host_file_result.
+func_convert_file_noop ()
+{
+  func_to_host_file_result="$1"
+}
+# end func_convert_file_noop
+
+
+# func_convert_file_msys_to_w32 ARG
+# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic
+# conversion to w32 is not available inside the cwrapper.  Returns result in
+# func_to_host_file_result.
+func_convert_file_msys_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    func_convert_core_msys_to_w32 "$1"
+    func_to_host_file_result="$func_convert_core_msys_to_w32_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_msys_to_w32
+
+
+# func_convert_file_cygwin_to_w32 ARG
+# Convert file name ARG from Cygwin to w32 format.  Returns result in
+# func_to_host_file_result.
+func_convert_file_cygwin_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    # because $build is cygwin, we call "the" cygpath in $PATH; no need to use
+    # LT_CYGPATH in this case.
+    func_to_host_file_result=`cygpath -m "$1"`
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_cygwin_to_w32
+
+
+# func_convert_file_nix_to_w32 ARG
+# Convert file name ARG from *nix to w32 format.  Requires a wine environment
+# and a working winepath. Returns result in func_to_host_file_result.
+func_convert_file_nix_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    func_convert_core_file_wine_to_w32 "$1"
+    func_to_host_file_result="$func_convert_core_file_wine_to_w32_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_nix_to_w32
+
+
+# func_convert_file_msys_to_cygwin ARG
+# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.
+# Returns result in func_to_host_file_result.
+func_convert_file_msys_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    func_convert_core_msys_to_w32 "$1"
+    func_cygpath -u "$func_convert_core_msys_to_w32_result"
+    func_to_host_file_result="$func_cygpath_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_msys_to_cygwin
+
+
+# func_convert_file_nix_to_cygwin ARG
+# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin installed
+# in a wine environment, working winepath, and LT_CYGPATH set.  Returns result
+# in func_to_host_file_result.
+func_convert_file_nix_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.
+    func_convert_core_file_wine_to_w32 "$1"
+    func_cygpath -u "$func_convert_core_file_wine_to_w32_result"
+    func_to_host_file_result="$func_cygpath_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_nix_to_cygwin
+
+
+#############################################
+# $build to $host PATH CONVERSION FUNCTIONS #
+#############################################
+# invoked via `$to_host_path_cmd ARG'
+#
+# In each case, ARG is the path to be converted from $build to $host format.
+# The result will be available in $func_to_host_path_result.
+#
+# Path separators are also converted from $build format to $host format.  If
+# ARG begins or ends with a path separator character, it is preserved (but
+# converted to $host format) on output.
+#
+# All path conversion functions are named using the following convention:
+#   file name conversion function    : func_convert_file_X_to_Y ()
+#   path conversion function         : func_convert_path_X_to_Y ()
+# where, for any given $build/$host combination the 'X_to_Y' value is the
+# same.  If conversion functions are added for new $build/$host combinations,
+# the two new functions must follow this pattern, or func_init_to_host_path_cmd
+# will break.
+
+
+# func_init_to_host_path_cmd
+# Ensures that function "pointer" variable $to_host_path_cmd is set to the
+# appropriate value, based on the value of $to_host_file_cmd.
+to_host_path_cmd=
+func_init_to_host_path_cmd ()
+{
+  $opt_debug
+  if test -z "$to_host_path_cmd"; then
+    func_stripname 'func_convert_file_' '' "$to_host_file_cmd"
+    to_host_path_cmd="func_convert_path_${func_stripname_result}"
+  fi
+}
+
+
+# func_to_host_path ARG
+# Converts the path ARG from $build format to $host format. Return result
+# in func_to_host_path_result.
+func_to_host_path ()
+{
+  $opt_debug
+  func_init_to_host_path_cmd
+  $to_host_path_cmd "$1"
+}
+# end func_to_host_path
+
+
+# func_convert_path_noop ARG
+# Copy ARG to func_to_host_path_result.
+func_convert_path_noop ()
+{
+  func_to_host_path_result="$1"
+}
+# end func_convert_path_noop
+
+
+# func_convert_path_msys_to_w32 ARG
+# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic
+# conversion to w32 is not available inside the cwrapper.  Returns result in
+# func_to_host_path_result.
+func_convert_path_msys_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # Remove leading and trailing path separator characters from ARG.  MSYS
+    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';
+    # and winepath ignores them completely.
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
+    func_to_host_path_result="$func_convert_core_msys_to_w32_result"
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_msys_to_w32
+
+
+# func_convert_path_cygwin_to_w32 ARG
+# Convert path ARG from Cygwin to w32 format.  Returns result in
+# func_to_host_file_result.
+func_convert_path_cygwin_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"`
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_cygwin_to_w32
+
+
+# func_convert_path_nix_to_w32 ARG
+# Convert path ARG from *nix to w32 format.  Requires a wine environment and
+# a working winepath.  Returns result in func_to_host_file_result.
+func_convert_path_nix_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
+    func_to_host_path_result="$func_convert_core_path_wine_to_w32_result"
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_nix_to_w32
+
+
+# func_convert_path_msys_to_cygwin ARG
+# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.
+# Returns result in func_to_host_file_result.
+func_convert_path_msys_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
+    func_cygpath -u -p "$func_convert_core_msys_to_w32_result"
+    func_to_host_path_result="$func_cygpath_result"
+    func_convert_path_check : : \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" : "$1"
+  fi
+}
+# end func_convert_path_msys_to_cygwin
+
+
+# func_convert_path_nix_to_cygwin ARG
+# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed in a
+# a wine environment, working winepath, and LT_CYGPATH set.  Returns result in
+# func_to_host_file_result.
+func_convert_path_nix_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # Remove leading and trailing path separator characters from
+    # ARG. msys behavior is inconsistent here, cygpath turns them
+    # into '.;' and ';.', and winepath ignores them completely.
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
+    func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result"
+    func_to_host_path_result="$func_cygpath_result"
+    func_convert_path_check : : \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" : "$1"
+  fi
+}
+# end func_convert_path_nix_to_cygwin
+
+
+# func_mode_compile arg...
+func_mode_compile ()
+{
+    $opt_debug
+    # Get the compilation command and the source file.
+    base_compile=
+    srcfile="$nonopt"  #  always keep a non-empty value in "srcfile"
+    suppress_opt=yes
+    suppress_output=
+    arg_mode=normal
+    libobj=
+    later=
+    pie_flag=
+
+    for arg
+    do
+      case $arg_mode in
+      arg  )
+	# do not "continue".  Instead, add this to base_compile
+	lastarg="$arg"
+	arg_mode=normal
+	;;
+
+      target )
+	libobj="$arg"
+	arg_mode=normal
+	continue
+	;;
+
+      normal )
+	# Accept any command-line options.
+	case $arg in
+	-o)
+	  test -n "$libobj" && \
+	    func_fatal_error "you cannot specify \`-o' more than once"
+	  arg_mode=target
+	  continue
+	  ;;
+
+	-pie | -fpie | -fPIE)
+          func_append pie_flag " $arg"
+	  continue
+	  ;;
+
+	-shared | -static | -prefer-pic | -prefer-non-pic)
+	  func_append later " $arg"
+	  continue
+	  ;;
+
+	-no-suppress)
+	  suppress_opt=no
+	  continue
+	  ;;
+
+	-Xcompiler)
+	  arg_mode=arg  #  the next one goes into the "base_compile" arg list
+	  continue      #  The current "srcfile" will either be retained or
+	  ;;            #  replaced later.  I would guess that would be a bug.
+
+	-Wc,*)
+	  func_stripname '-Wc,' '' "$arg"
+	  args=$func_stripname_result
+	  lastarg=
+	  save_ifs="$IFS"; IFS=','
+	  for arg in $args; do
+	    IFS="$save_ifs"
+	    func_append_quoted lastarg "$arg"
+	  done
+	  IFS="$save_ifs"
+	  func_stripname ' ' '' "$lastarg"
+	  lastarg=$func_stripname_result
+
+	  # Add the arguments to base_compile.
+	  func_append base_compile " $lastarg"
+	  continue
+	  ;;
+
+	*)
+	  # Accept the current argument as the source file.
+	  # The previous "srcfile" becomes the current argument.
+	  #
+	  lastarg="$srcfile"
+	  srcfile="$arg"
+	  ;;
+	esac  #  case $arg
+	;;
+      esac    #  case $arg_mode
+
+      # Aesthetically quote the previous argument.
+      func_append_quoted base_compile "$lastarg"
+    done # for arg
+
+    case $arg_mode in
+    arg)
+      func_fatal_error "you must specify an argument for -Xcompile"
+      ;;
+    target)
+      func_fatal_error "you must specify a target with \`-o'"
+      ;;
+    *)
+      # Get the name of the library object.
+      test -z "$libobj" && {
+	func_basename "$srcfile"
+	libobj="$func_basename_result"
+      }
+      ;;
+    esac
+
+    # Recognize several different file suffixes.
+    # If the user specifies -o file.o, it is replaced with file.lo
+    case $libobj in
+    *.[cCFSifmso] | \
+    *.ada | *.adb | *.ads | *.asm | \
+    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \
+    *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup)
+      func_xform "$libobj"
+      libobj=$func_xform_result
+      ;;
+    esac
+
+    case $libobj in
+    *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;;
+    *)
+      func_fatal_error "cannot determine name of library object from \`$libobj'"
+      ;;
+    esac
+
+    func_infer_tag $base_compile
+
+    for arg in $later; do
+      case $arg in
+      -shared)
+	test "$build_libtool_libs" != yes && \
+	  func_fatal_configuration "can not build a shared library"
+	build_old_libs=no
+	continue
+	;;
+
+      -static)
+	build_libtool_libs=no
+	build_old_libs=yes
+	continue
+	;;
+
+      -prefer-pic)
+	pic_mode=yes
+	continue
+	;;
+
+      -prefer-non-pic)
+	pic_mode=no
+	continue
+	;;
+      esac
+    done
+
+    func_quote_for_eval "$libobj"
+    test "X$libobj" != "X$func_quote_for_eval_result" \
+      && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"'	 &()|`$[]' \
+      && func_warning "libobj name \`$libobj' may not contain shell special characters."
+    func_dirname_and_basename "$obj" "/" ""
+    objname="$func_basename_result"
+    xdir="$func_dirname_result"
+    lobj=${xdir}$objdir/$objname
+
+    test -z "$base_compile" && \
+      func_fatal_help "you must specify a compilation command"
+
+    # Delete any leftover library objects.
+    if test "$build_old_libs" = yes; then
+      removelist="$obj $lobj $libobj ${libobj}T"
+    else
+      removelist="$lobj $libobj ${libobj}T"
+    fi
+
+    # On Cygwin there's no "real" PIC flag so we must build both object types
+    case $host_os in
+    cygwin* | mingw* | pw32* | os2* | cegcc*)
+      pic_mode=default
+      ;;
+    esac
+    if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then
+      # non-PIC code in shared libraries is not supported
+      pic_mode=default
+    fi
+
+    # Calculate the filename of the output object if compiler does
+    # not support -o with -c
+    if test "$compiler_c_o" = no; then
+      output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.${objext}
+      lockfile="$output_obj.lock"
+    else
+      output_obj=
+      need_locks=no
+      lockfile=
+    fi
+
+    # Lock this critical section if it is needed
+    # We use this script file to make the link, it avoids creating a new file
+    if test "$need_locks" = yes; then
+      until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do
+	func_echo "Waiting for $lockfile to be removed"
+	sleep 2
+      done
+    elif test "$need_locks" = warn; then
+      if test -f "$lockfile"; then
+	$ECHO "\
+*** ERROR, $lockfile exists and contains:
+`cat $lockfile 2>/dev/null`
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together.  If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+	$opt_dry_run || $RM $removelist
+	exit $EXIT_FAILURE
+      fi
+      func_append removelist " $output_obj"
+      $ECHO "$srcfile" > "$lockfile"
+    fi
+
+    $opt_dry_run || $RM $removelist
+    func_append removelist " $lockfile"
+    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15
+
+    func_to_tool_file "$srcfile" func_convert_file_msys_to_w32
+    srcfile=$func_to_tool_file_result
+    func_quote_for_eval "$srcfile"
+    qsrcfile=$func_quote_for_eval_result
+
+    # Only build a PIC object if we are building libtool libraries.
+    if test "$build_libtool_libs" = yes; then
+      # Without this assignment, base_compile gets emptied.
+      fbsd_hideous_sh_bug=$base_compile
+
+      if test "$pic_mode" != no; then
+	command="$base_compile $qsrcfile $pic_flag"
+      else
+	# Don't build PIC code
+	command="$base_compile $qsrcfile"
+      fi
+
+      func_mkdir_p "$xdir$objdir"
+
+      if test -z "$output_obj"; then
+	# Place PIC objects in $objdir
+	func_append command " -o $lobj"
+      fi
+
+      func_show_eval_locale "$command"	\
+          'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE'
+
+      if test "$need_locks" = warn &&
+	 test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
+	$ECHO "\
+*** ERROR, $lockfile contains:
+`cat $lockfile 2>/dev/null`
+
+but it should contain:
+$srcfile
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together.  If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+	$opt_dry_run || $RM $removelist
+	exit $EXIT_FAILURE
+      fi
+
+      # Just move the object if needed, then go on to compile the next one
+      if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then
+	func_show_eval '$MV "$output_obj" "$lobj"' \
+	  'error=$?; $opt_dry_run || $RM $removelist; exit $error'
+      fi
+
+      # Allow error messages only from the first compilation.
+      if test "$suppress_opt" = yes; then
+	suppress_output=' >/dev/null 2>&1'
+      fi
+    fi
+
+    # Only build a position-dependent object if we build old libraries.
+    if test "$build_old_libs" = yes; then
+      if test "$pic_mode" != yes; then
+	# Don't build PIC code
+	command="$base_compile $qsrcfile$pie_flag"
+      else
+	command="$base_compile $qsrcfile $pic_flag"
+      fi
+      if test "$compiler_c_o" = yes; then
+	func_append command " -o $obj"
+      fi
+
+      # Suppress compiler output if we already did a PIC compilation.
+      func_append command "$suppress_output"
+      func_show_eval_locale "$command" \
+        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'
+
+      if test "$need_locks" = warn &&
+	 test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
+	$ECHO "\
+*** ERROR, $lockfile contains:
+`cat $lockfile 2>/dev/null`
+
+but it should contain:
+$srcfile
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together.  If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+	$opt_dry_run || $RM $removelist
+	exit $EXIT_FAILURE
+      fi
+
+      # Just move the object if needed
+      if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then
+	func_show_eval '$MV "$output_obj" "$obj"' \
+	  'error=$?; $opt_dry_run || $RM $removelist; exit $error'
+      fi
+    fi
+
+    $opt_dry_run || {
+      func_write_libtool_object "$libobj" "$objdir/$objname" "$objname"
+
+      # Unlock the critical section if it was locked
+      if test "$need_locks" != no; then
+	removelist=$lockfile
+        $RM "$lockfile"
+      fi
+    }
+
+    exit $EXIT_SUCCESS
+}
+
+$opt_help || {
+  test "$opt_mode" = compile && func_mode_compile ${1+"$@"}
+}
+
+func_mode_help ()
+{
+    # We need to display help for each of the modes.
+    case $opt_mode in
+      "")
+        # Generic help is extracted from the usage comments
+        # at the start of this file.
+        func_help
+        ;;
+
+      clean)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE...
+
+Remove files from the build directory.
+
+RM is the name of the program to use to delete files associated with each FILE
+(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be passed
+to RM.
+
+If FILE is a libtool library, object or program, all the files associated
+with it are deleted. Otherwise, only FILE itself is deleted using RM."
+        ;;
+
+      compile)
+      $ECHO \
+"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE
+
+Compile a source file into a libtool library object.
+
+This mode accepts the following additional options:
+
+  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE
+  -no-suppress      do not suppress compiler output for multiple passes
+  -prefer-pic       try to build PIC objects only
+  -prefer-non-pic   try to build non-PIC objects only
+  -shared           do not build a \`.o' file suitable for static linking
+  -static           only build a \`.o' file suitable for static linking
+  -Wc,FLAG          pass FLAG directly to the compiler
+
+COMPILE-COMMAND is a command to be used in creating a \`standard' object file
+from the given SOURCEFILE.
+
+The output file name is determined by removing the directory component from
+SOURCEFILE, then substituting the C source code suffix \`.c' with the
+library object suffix, \`.lo'."
+        ;;
+
+      execute)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]...
+
+Automatically set library path, then run a program.
+
+This mode accepts the following additional options:
+
+  -dlopen FILE      add the directory containing FILE to the library path
+
+This mode sets the library path environment variable according to \`-dlopen'
+flags.
+
+If any of the ARGS are libtool executable wrappers, then they are translated
+into their corresponding uninstalled binary, and any of their required library
+directories are added to the library path.
+
+Then, COMMAND is executed, with ARGS as arguments."
+        ;;
+
+      finish)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=finish [LIBDIR]...
+
+Complete the installation of libtool libraries.
+
+Each LIBDIR is a directory that contains libtool libraries.
+
+The commands that this mode executes may require superuser privileges.  Use
+the \`--dry-run' option if you just want to see what would be executed."
+        ;;
+
+      install)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND...
+
+Install executables or libraries.
+
+INSTALL-COMMAND is the installation command.  The first component should be
+either the \`install' or \`cp' program.
+
+The following components of INSTALL-COMMAND are treated specially:
+
+  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for installation
+
+The rest of the components are interpreted as arguments to that command (only
+BSD-compatible install options are recognized)."
+        ;;
+
+      link)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=link LINK-COMMAND...
+
+Link object files or libraries together to form another library, or to
+create an executable program.
+
+LINK-COMMAND is a command using the C compiler that you would use to create
+a program from several object files.
+
+The following components of LINK-COMMAND are treated specially:
+
+  -all-static       do not do any dynamic linking at all
+  -avoid-version    do not add a version suffix if possible
+  -bindir BINDIR    specify path to binaries directory (for systems where
+                    libraries must be found in the PATH setting at runtime)
+  -dlopen FILE      \`-dlpreopen' FILE if it cannot be dlopened at runtime
+  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols
+  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)
+  -export-symbols SYMFILE
+                    try to export only the symbols listed in SYMFILE
+  -export-symbols-regex REGEX
+                    try to export only the symbols matching REGEX
+  -LLIBDIR          search LIBDIR for required installed libraries
+  -lNAME            OUTPUT-FILE requires the installed library libNAME
+  -module           build a library that can dlopened
+  -no-fast-install  disable the fast-install mode
+  -no-install       link a not-installable executable
+  -no-undefined     declare that a library does not refer to external symbols
+  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects
+  -objectlist FILE  Use a list of object files found in FILE to specify objects
+  -precious-files-regex REGEX
+                    don't remove output files matching REGEX
+  -release RELEASE  specify package release information
+  -rpath LIBDIR     the created library will eventually be installed in LIBDIR
+  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and libraries
+  -shared           only do dynamic linking of libtool libraries
+  -shrext SUFFIX    override the standard shared library file extension
+  -static           do not do any dynamic linking of uninstalled libtool libraries
+  -static-libtool-libs
+                    do not do any dynamic linking of libtool libraries
+  -version-info CURRENT[:REVISION[:AGE]]
+                    specify library version info [each variable defaults to 0]
+  -weak LIBNAME     declare that the target provides the LIBNAME interface
+  -Wc,FLAG
+  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler
+  -Wl,FLAG
+  -Xlinker FLAG     pass linker-specific FLAG directly to the linker
+  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)
+
+All other options (arguments beginning with \`-') are ignored.
+
+Every other argument is treated as a filename.  Files ending in \`.la' are
+treated as uninstalled libtool libraries, other files are standard or library
+object files.
+
+If the OUTPUT-FILE ends in \`.la', then a libtool library is created,
+only library objects (\`.lo' files) may be specified, and \`-rpath' is
+required, except when creating a convenience library.
+
+If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created
+using \`ar' and \`ranlib', or on Windows using \`lib'.
+
+If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file
+is created, otherwise an executable program is created."
+        ;;
+
+      uninstall)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...
+
+Remove libraries from an installation directory.
+
+RM is the name of the program to use to delete files associated with each FILE
+(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be passed
+to RM.
+
+If FILE is a libtool library, all the files associated with it are deleted.
+Otherwise, only FILE itself is deleted using RM."
+        ;;
+
+      *)
+        func_fatal_help "invalid operation mode \`$opt_mode'"
+        ;;
+    esac
+
+    echo
+    $ECHO "Try \`$progname --help' for more information about other modes."
+}
+
+# Now that we've collected a possible --mode arg, show help if necessary
+if $opt_help; then
+  if test "$opt_help" = :; then
+    func_mode_help
+  else
+    {
+      func_help noexit
+      for opt_mode in compile link execute install finish uninstall clean; do
+	func_mode_help
+      done
+    } | sed -n '1p; 2,$s/^Usage:/  or: /p'
+    {
+      func_help noexit
+      for opt_mode in compile link execute install finish uninstall clean; do
+	echo
+	func_mode_help
+      done
+    } |
+    sed '1d
+      /^When reporting/,/^Report/{
+	H
+	d
+      }
+      $x
+      /information about other modes/d
+      /more detailed .*MODE/d
+      s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/'
+  fi
+  exit $?
+fi
+
+
+# func_mode_execute arg...
+func_mode_execute ()
+{
+    $opt_debug
+    # The first argument is the command name.
+    cmd="$nonopt"
+    test -z "$cmd" && \
+      func_fatal_help "you must specify a COMMAND"
+
+    # Handle -dlopen flags immediately.
+    for file in $opt_dlopen; do
+      test -f "$file" \
+	|| func_fatal_help "\`$file' is not a file"
+
+      dir=
+      case $file in
+      *.la)
+	func_resolve_sysroot "$file"
+	file=$func_resolve_sysroot_result
+
+	# Check to see that this really is a libtool archive.
+	func_lalib_unsafe_p "$file" \
+	  || func_fatal_help "\`$lib' is not a valid libtool archive"
+
+	# Read the libtool library.
+	dlname=
+	library_names=
+	func_source "$file"
+
+	# Skip this library if it cannot be dlopened.
+	if test -z "$dlname"; then
+	  # Warn if it was a shared library.
+	  test -n "$library_names" && \
+	    func_warning "\`$file' was not linked with \`-export-dynamic'"
+	  continue
+	fi
+
+	func_dirname "$file" "" "."
+	dir="$func_dirname_result"
+
+	if test -f "$dir/$objdir/$dlname"; then
+	  func_append dir "/$objdir"
+	else
+	  if test ! -f "$dir/$dlname"; then
+	    func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'"
+	  fi
+	fi
+	;;
+
+      *.lo)
+	# Just add the directory containing the .lo file.
+	func_dirname "$file" "" "."
+	dir="$func_dirname_result"
+	;;
+
+      *)
+	func_warning "\`-dlopen' is ignored for non-libtool libraries and objects"
+	continue
+	;;
+      esac
+
+      # Get the absolute pathname.
+      absdir=`cd "$dir" && pwd`
+      test -n "$absdir" && dir="$absdir"
+
+      # Now add the directory to shlibpath_var.
+      if eval "test -z \"\$$shlibpath_var\""; then
+	eval "$shlibpath_var=\"\$dir\""
+      else
+	eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\""
+      fi
+    done
+
+    # This variable tells wrapper scripts just to set shlibpath_var
+    # rather than running their programs.
+    libtool_execute_magic="$magic"
+
+    # Check if any of the arguments is a wrapper script.
+    args=
+    for file
+    do
+      case $file in
+      -* | *.la | *.lo ) ;;
+      *)
+	# Do a test to see if this is really a libtool program.
+	if func_ltwrapper_script_p "$file"; then
+	  func_source "$file"
+	  # Transform arg to wrapped name.
+	  file="$progdir/$program"
+	elif func_ltwrapper_executable_p "$file"; then
+	  func_ltwrapper_scriptname "$file"
+	  func_source "$func_ltwrapper_scriptname_result"
+	  # Transform arg to wrapped name.
+	  file="$progdir/$program"
+	fi
+	;;
+      esac
+      # Quote arguments (to preserve shell metacharacters).
+      func_append_quoted args "$file"
+    done
+
+    if test "X$opt_dry_run" = Xfalse; then
+      if test -n "$shlibpath_var"; then
+	# Export the shlibpath_var.
+	eval "export $shlibpath_var"
+      fi
+
+      # Restore saved environment variables
+      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
+      do
+	eval "if test \"\${save_$lt_var+set}\" = set; then
+                $lt_var=\$save_$lt_var; export $lt_var
+	      else
+		$lt_unset $lt_var
+	      fi"
+      done
+
+      # Now prepare to actually exec the command.
+      exec_cmd="\$cmd$args"
+    else
+      # Display what would be done.
+      if test -n "$shlibpath_var"; then
+	eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\""
+	echo "export $shlibpath_var"
+      fi
+      $ECHO "$cmd$args"
+      exit $EXIT_SUCCESS
+    fi
+}
+
+test "$opt_mode" = execute && func_mode_execute ${1+"$@"}
+
+
+# func_mode_finish arg...
+func_mode_finish ()
+{
+    $opt_debug
+    libs=
+    libdirs=
+    admincmds=
+
+    for opt in "$nonopt" ${1+"$@"}
+    do
+      if test -d "$opt"; then
+	func_append libdirs " $opt"
+
+      elif test -f "$opt"; then
+	if func_lalib_unsafe_p "$opt"; then
+	  func_append libs " $opt"
+	else
+	  func_warning "\`$opt' is not a valid libtool archive"
+	fi
+
+      else
+	func_fatal_error "invalid argument \`$opt'"
+      fi
+    done
+
+    if test -n "$libs"; then
+      if test -n "$lt_sysroot"; then
+        sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"`
+        sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;"
+      else
+        sysroot_cmd=
+      fi
+
+      # Remove sysroot references
+      if $opt_dry_run; then
+        for lib in $libs; do
+          echo "removing references to $lt_sysroot and \`=' prefixes from $lib"
+        done
+      else
+        tmpdir=`func_mktempdir`
+        for lib in $libs; do
+	  sed -e "${sysroot_cmd} s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \
+	    > $tmpdir/tmp-la
+	  mv -f $tmpdir/tmp-la $lib
+	done
+        ${RM}r "$tmpdir"
+      fi
+    fi
+
+    if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
+      for libdir in $libdirs; do
+	if test -n "$finish_cmds"; then
+	  # Do each command in the finish commands.
+	  func_execute_cmds "$finish_cmds" 'admincmds="$admincmds
+'"$cmd"'"'
+	fi
+	if test -n "$finish_eval"; then
+	  # Do the single finish_eval.
+	  eval cmds=\"$finish_eval\"
+	  $opt_dry_run || eval "$cmds" || func_append admincmds "
+       $cmds"
+	fi
+      done
+    fi
+
+    # Exit here if they wanted silent mode.
+    $opt_silent && exit $EXIT_SUCCESS
+
+    if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
+      echo "----------------------------------------------------------------------"
+      echo "Libraries have been installed in:"
+      for libdir in $libdirs; do
+	$ECHO "   $libdir"
+      done
+      echo
+      echo "If you ever happen to want to link against installed libraries"
+      echo "in a given directory, LIBDIR, you must either use libtool, and"
+      echo "specify the full pathname of the library, or use the \`-LLIBDIR'"
+      echo "flag during linking and do at least one of the following:"
+      if test -n "$shlibpath_var"; then
+	echo "   - add LIBDIR to the \`$shlibpath_var' environment variable"
+	echo "     during execution"
+      fi
+      if test -n "$runpath_var"; then
+	echo "   - add LIBDIR to the \`$runpath_var' environment variable"
+	echo "     during linking"
+      fi
+      if test -n "$hardcode_libdir_flag_spec"; then
+	libdir=LIBDIR
+	eval flag=\"$hardcode_libdir_flag_spec\"
+
+	$ECHO "   - use the \`$flag' linker flag"
+      fi
+      if test -n "$admincmds"; then
+	$ECHO "   - have your system administrator run these commands:$admincmds"
+      fi
+      if test -f /etc/ld.so.conf; then
+	echo "   - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
+      fi
+      echo
+
+      echo "See any operating system documentation about shared libraries for"
+      case $host in
+	solaris2.[6789]|solaris2.1[0-9])
+	  echo "more information, such as the ld(1), crle(1) and ld.so(8) manual"
+	  echo "pages."
+	  ;;
+	*)
+	  echo "more information, such as the ld(1) and ld.so(8) manual pages."
+	  ;;
+      esac
+      echo "----------------------------------------------------------------------"
+    fi
+    exit $EXIT_SUCCESS
+}
+
+test "$opt_mode" = finish && func_mode_finish ${1+"$@"}
+
+
+# func_mode_install arg...
+func_mode_install ()
+{
+    $opt_debug
+    # There may be an optional sh(1) argument at the beginning of
+    # install_prog (especially on Windows NT).
+    if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh ||
+       # Allow the use of GNU shtool's install command.
+       case $nonopt in *shtool*) :;; *) false;; esac; then
+      # Aesthetically quote it.
+      func_quote_for_eval "$nonopt"
+      install_prog="$func_quote_for_eval_result "
+      arg=$1
+      shift
+    else
+      install_prog=
+      arg=$nonopt
+    fi
+
+    # The real first argument should be the name of the installation program.
+    # Aesthetically quote it.
+    func_quote_for_eval "$arg"
+    func_append install_prog "$func_quote_for_eval_result"
+    install_shared_prog=$install_prog
+    case " $install_prog " in
+      *[\\\ /]cp\ *) install_cp=: ;;
+      *) install_cp=false ;;
+    esac
+
+    # We need to accept at least all the BSD install flags.
+    dest=
+    files=
+    opts=
+    prev=
+    install_type=
+    isdir=no
+    stripme=
+    no_mode=:
+    for arg
+    do
+      arg2=
+      if test -n "$dest"; then
+	func_append files " $dest"
+	dest=$arg
+	continue
+      fi
+
+      case $arg in
+      -d) isdir=yes ;;
+      -f)
+	if $install_cp; then :; else
+	  prev=$arg
+	fi
+	;;
+      -g | -m | -o)
+	prev=$arg
+	;;
+      -s)
+	stripme=" -s"
+	continue
+	;;
+      -*)
+	;;
+      *)
+	# If the previous option needed an argument, then skip it.
+	if test -n "$prev"; then
+	  if test "x$prev" = x-m && test -n "$install_override_mode"; then
+	    arg2=$install_override_mode
+	    no_mode=false
+	  fi
+	  prev=
+	else
+	  dest=$arg
+	  continue
+	fi
+	;;
+      esac
+
+      # Aesthetically quote the argument.
+      func_quote_for_eval "$arg"
+      func_append install_prog " $func_quote_for_eval_result"
+      if test -n "$arg2"; then
+	func_quote_for_eval "$arg2"
+      fi
+      func_append install_shared_prog " $func_quote_for_eval_result"
+    done
+
+    test -z "$install_prog" && \
+      func_fatal_help "you must specify an install program"
+
+    test -n "$prev" && \
+      func_fatal_help "the \`$prev' option requires an argument"
+
+    if test -n "$install_override_mode" && $no_mode; then
+      if $install_cp; then :; else
+	func_quote_for_eval "$install_override_mode"
+	func_append install_shared_prog " -m $func_quote_for_eval_result"
+      fi
+    fi
+
+    if test -z "$files"; then
+      if test -z "$dest"; then
+	func_fatal_help "no file or destination specified"
+      else
+	func_fatal_help "you must specify a destination"
+      fi
+    fi
+
+    # Strip any trailing slash from the destination.
+    func_stripname '' '/' "$dest"
+    dest=$func_stripname_result
+
+    # Check to see that the destination is a directory.
+    test -d "$dest" && isdir=yes
+    if test "$isdir" = yes; then
+      destdir="$dest"
+      destname=
+    else
+      func_dirname_and_basename "$dest" "" "."
+      destdir="$func_dirname_result"
+      destname="$func_basename_result"
+
+      # Not a directory, so check to see that there is only one file specified.
+      set dummy $files; shift
+      test "$#" -gt 1 && \
+	func_fatal_help "\`$dest' is not a directory"
+    fi
+    case $destdir in
+    [\\/]* | [A-Za-z]:[\\/]*) ;;
+    *)
+      for file in $files; do
+	case $file in
+	*.lo) ;;
+	*)
+	  func_fatal_help "\`$destdir' must be an absolute directory name"
+	  ;;
+	esac
+      done
+      ;;
+    esac
+
+    # This variable tells wrapper scripts just to set variables rather
+    # than running their programs.
+    libtool_install_magic="$magic"
+
+    staticlibs=
+    future_libdirs=
+    current_libdirs=
+    for file in $files; do
+
+      # Do each installation.
+      case $file in
+      *.$libext)
+	# Do the static libraries later.
+	func_append staticlibs " $file"
+	;;
+
+      *.la)
+	func_resolve_sysroot "$file"
+	file=$func_resolve_sysroot_result
+
+	# Check to see that this really is a libtool archive.
+	func_lalib_unsafe_p "$file" \
+	  || func_fatal_help "\`$file' is not a valid libtool archive"
+
+	library_names=
+	old_library=
+	relink_command=
+	func_source "$file"
+
+	# Add the libdir to current_libdirs if it is the destination.
+	if test "X$destdir" = "X$libdir"; then
+	  case "$current_libdirs " in
+	  *" $libdir "*) ;;
+	  *) func_append current_libdirs " $libdir" ;;
+	  esac
+	else
+	  # Note the libdir as a future libdir.
+	  case "$future_libdirs " in
+	  *" $libdir "*) ;;
+	  *) func_append future_libdirs " $libdir" ;;
+	  esac
+	fi
+
+	func_dirname "$file" "/" ""
+	dir="$func_dirname_result"
+	func_append dir "$objdir"
+
+	if test -n "$relink_command"; then
+	  # Determine the prefix the user has applied to our future dir.
+	  inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"`
+
+	  # Don't allow the user to place us outside of our expected
+	  # location b/c this prevents finding dependent libraries that
+	  # are installed to the same prefix.
+	  # At present, this check doesn't affect windows .dll's that
+	  # are installed into $libdir/../bin (currently, that works fine)
+	  # but it's something to keep an eye on.
+	  test "$inst_prefix_dir" = "$destdir" && \
+	    func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir"
+
+	  if test -n "$inst_prefix_dir"; then
+	    # Stick the inst_prefix_dir data into the link command.
+	    relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"`
+	  else
+	    relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"`
+	  fi
+
+	  func_warning "relinking \`$file'"
+	  func_show_eval "$relink_command" \
+	    'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"'
+	fi
+
+	# See the names of the shared library.
+	set dummy $library_names; shift
+	if test -n "$1"; then
+	  realname="$1"
+	  shift
+
+	  srcname="$realname"
+	  test -n "$relink_command" && srcname="$realname"T
+
+	  # Install the shared library and build the symlinks.
+	  func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \
+	      'exit $?'
+	  tstripme="$stripme"
+	  case $host_os in
+	  cygwin* | mingw* | pw32* | cegcc*)
+	    case $realname in
+	    *.dll.a)
+	      tstripme=""
+	      ;;
+	    esac
+	    ;;
+	  esac
+	  if test -n "$tstripme" && test -n "$striplib"; then
+	    func_show_eval "$striplib $destdir/$realname" 'exit $?'
+	  fi
+
+	  if test "$#" -gt 0; then
+	    # Delete the old symlinks, and create new ones.
+	    # Try `ln -sf' first, because the `ln' binary might depend on
+	    # the symlink we replace!  Solaris /bin/ln does not understand -f,
+	    # so we also need to try rm && ln -s.
+	    for linkname
+	    do
+	      test "$linkname" != "$realname" \
+		&& func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })"
+	    done
+	  fi
+
+	  # Do each command in the postinstall commands.
+	  lib="$destdir/$realname"
+	  func_execute_cmds "$postinstall_cmds" 'exit $?'
+	fi
+
+	# Install the pseudo-library for information purposes.
+	func_basename "$file"
+	name="$func_basename_result"
+	instname="$dir/$name"i
+	func_show_eval "$install_prog $instname $destdir/$name" 'exit $?'
+
+	# Maybe install the static library, too.
+	test -n "$old_library" && func_append staticlibs " $dir/$old_library"
+	;;
+
+      *.lo)
+	# Install (i.e. copy) a libtool object.
+
+	# Figure out destination file name, if it wasn't already specified.
+	if test -n "$destname"; then
+	  destfile="$destdir/$destname"
+	else
+	  func_basename "$file"
+	  destfile="$func_basename_result"
+	  destfile="$destdir/$destfile"
+	fi
+
+	# Deduce the name of the destination old-style object file.
+	case $destfile in
+	*.lo)
+	  func_lo2o "$destfile"
+	  staticdest=$func_lo2o_result
+	  ;;
+	*.$objext)
+	  staticdest="$destfile"
+	  destfile=
+	  ;;
+	*)
+	  func_fatal_help "cannot copy a libtool object to \`$destfile'"
+	  ;;
+	esac
+
+	# Install the libtool object if requested.
+	test -n "$destfile" && \
+	  func_show_eval "$install_prog $file $destfile" 'exit $?'
+
+	# Install the old object if enabled.
+	if test "$build_old_libs" = yes; then
+	  # Deduce the name of the old-style object file.
+	  func_lo2o "$file"
+	  staticobj=$func_lo2o_result
+	  func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?'
+	fi
+	exit $EXIT_SUCCESS
+	;;
+
+      *)
+	# Figure out destination file name, if it wasn't already specified.
+	if test -n "$destname"; then
+	  destfile="$destdir/$destname"
+	else
+	  func_basename "$file"
+	  destfile="$func_basename_result"
+	  destfile="$destdir/$destfile"
+	fi
+
+	# If the file is missing, and there is a .exe on the end, strip it
+	# because it is most likely a libtool script we actually want to
+	# install
+	stripped_ext=""
+	case $file in
+	  *.exe)
+	    if test ! -f "$file"; then
+	      func_stripname '' '.exe' "$file"
+	      file=$func_stripname_result
+	      stripped_ext=".exe"
+	    fi
+	    ;;
+	esac
+
+	# Do a test to see if this is really a libtool program.
+	case $host in
+	*cygwin* | *mingw*)
+	    if func_ltwrapper_executable_p "$file"; then
+	      func_ltwrapper_scriptname "$file"
+	      wrapper=$func_ltwrapper_scriptname_result
+	    else
+	      func_stripname '' '.exe' "$file"
+	      wrapper=$func_stripname_result
+	    fi
+	    ;;
+	*)
+	    wrapper=$file
+	    ;;
+	esac
+	if func_ltwrapper_script_p "$wrapper"; then
+	  notinst_deplibs=
+	  relink_command=
+
+	  func_source "$wrapper"
+
+	  # Check the variables that should have been set.
+	  test -z "$generated_by_libtool_version" && \
+	    func_fatal_error "invalid libtool wrapper script \`$wrapper'"
+
+	  finalize=yes
+	  for lib in $notinst_deplibs; do
+	    # Check to see that each library is installed.
+	    libdir=
+	    if test -f "$lib"; then
+	      func_source "$lib"
+	    fi
+	    libfile="$libdir/"`$ECHO "$lib" | $SED 's%^.*/%%g'` ### testsuite: skip nested quoting test
+	    if test -n "$libdir" && test ! -f "$libfile"; then
+	      func_warning "\`$lib' has not been installed in \`$libdir'"
+	      finalize=no
+	    fi
+	  done
+
+	  relink_command=
+	  func_source "$wrapper"
+
+	  outputname=
+	  if test "$fast_install" = no && test -n "$relink_command"; then
+	    $opt_dry_run || {
+	      if test "$finalize" = yes; then
+	        tmpdir=`func_mktempdir`
+		func_basename "$file$stripped_ext"
+		file="$func_basename_result"
+	        outputname="$tmpdir/$file"
+	        # Replace the output file specification.
+	        relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'`
+
+	        $opt_silent || {
+	          func_quote_for_expand "$relink_command"
+		  eval "func_echo $func_quote_for_expand_result"
+	        }
+	        if eval "$relink_command"; then :
+	          else
+		  func_error "error: relink \`$file' with the above command before installing it"
+		  $opt_dry_run || ${RM}r "$tmpdir"
+		  continue
+	        fi
+	        file="$outputname"
+	      else
+	        func_warning "cannot relink \`$file'"
+	      fi
+	    }
+	  else
+	    # Install the binary that we compiled earlier.
+	    file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"`
+	  fi
+	fi
+
+	# remove .exe since cygwin /usr/bin/install will append another
+	# one anyway
+	case $install_prog,$host in
+	*/usr/bin/install*,*cygwin*)
+	  case $file:$destfile in
+	  *.exe:*.exe)
+	    # this is ok
+	    ;;
+	  *.exe:*)
+	    destfile=$destfile.exe
+	    ;;
+	  *:*.exe)
+	    func_stripname '' '.exe' "$destfile"
+	    destfile=$func_stripname_result
+	    ;;
+	  esac
+	  ;;
+	esac
+	func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?'
+	$opt_dry_run || if test -n "$outputname"; then
+	  ${RM}r "$tmpdir"
+	fi
+	;;
+      esac
+    done
+
+    for file in $staticlibs; do
+      func_basename "$file"
+      name="$func_basename_result"
+
+      # Set up the ranlib parameters.
+      oldlib="$destdir/$name"
+      func_to_tool_file "$oldlib" func_convert_file_msys_to_w32
+      tool_oldlib=$func_to_tool_file_result
+
+      func_show_eval "$install_prog \$file \$oldlib" 'exit $?'
+
+      if test -n "$stripme" && test -n "$old_striplib"; then
+	func_show_eval "$old_striplib $tool_oldlib" 'exit $?'
+      fi
+
+      # Do each command in the postinstall commands.
+      func_execute_cmds "$old_postinstall_cmds" 'exit $?'
+    done
+
+    test -n "$future_libdirs" && \
+      func_warning "remember to run \`$progname --finish$future_libdirs'"
+
+    if test -n "$current_libdirs"; then
+      # Maybe just do a dry run.
+      $opt_dry_run && current_libdirs=" -n$current_libdirs"
+      exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs'
+    else
+      exit $EXIT_SUCCESS
+    fi
+}
+
+test "$opt_mode" = install && func_mode_install ${1+"$@"}
+
+
+# func_generate_dlsyms outputname originator pic_p
+# Extract symbols from dlprefiles and create ${outputname}S.o with
+# a dlpreopen symbol table.
+func_generate_dlsyms ()
+{
+    $opt_debug
+    my_outputname="$1"
+    my_originator="$2"
+    my_pic_p="${3-no}"
+    my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'`
+    my_dlsyms=
+
+    if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+      if test -n "$NM" && test -n "$global_symbol_pipe"; then
+	my_dlsyms="${my_outputname}S.c"
+      else
+	func_error "not configured to extract global symbols from dlpreopened files"
+      fi
+    fi
+
+    if test -n "$my_dlsyms"; then
+      case $my_dlsyms in
+      "") ;;
+      *.c)
+	# Discover the nlist of each of the dlfiles.
+	nlist="$output_objdir/${my_outputname}.nm"
+
+	func_show_eval "$RM $nlist ${nlist}S ${nlist}T"
+
+	# Parse the name list into a source file.
+	func_verbose "creating $output_objdir/$my_dlsyms"
+
+	$opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\
+/* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */
+/* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */
+
+#ifdef __cplusplus
+extern \"C\" {
+#endif
+
+#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))
+#pragma GCC diagnostic ignored \"-Wstrict-prototypes\"
+#endif
+
+/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
+/* DATA imports from DLLs on WIN32 con't be const, because runtime
+   relocations are performed -- see ld's documentation on pseudo-relocs.  */
+# define LT_DLSYM_CONST
+#elif defined(__osf__)
+/* This system does not cope well with relocations in const data.  */
+# define LT_DLSYM_CONST
+#else
+# define LT_DLSYM_CONST const
+#endif
+
+/* External symbol declarations for the compiler. */\
+"
+
+	if test "$dlself" = yes; then
+	  func_verbose "generating symbol list for \`$output'"
+
+	  $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist"
+
+	  # Add our own program objects to the symbol list.
+	  progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP`
+	  for progfile in $progfiles; do
+	    func_to_tool_file "$progfile" func_convert_file_msys_to_w32
+	    func_verbose "extracting global C symbols from \`$func_to_tool_file_result'"
+	    $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'"
+	  done
+
+	  if test -n "$exclude_expsyms"; then
+	    $opt_dry_run || {
+	      eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T'
+	      eval '$MV "$nlist"T "$nlist"'
+	    }
+	  fi
+
+	  if test -n "$export_symbols_regex"; then
+	    $opt_dry_run || {
+	      eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T'
+	      eval '$MV "$nlist"T "$nlist"'
+	    }
+	  fi
+
+	  # Prepare the list of exported symbols
+	  if test -z "$export_symbols"; then
+	    export_symbols="$output_objdir/$outputname.exp"
+	    $opt_dry_run || {
+	      $RM $export_symbols
+	      eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"'
+	      case $host in
+	      *cygwin* | *mingw* | *cegcc* )
+                eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+                eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"'
+	        ;;
+	      esac
+	    }
+	  else
+	    $opt_dry_run || {
+	      eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"'
+	      eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T'
+	      eval '$MV "$nlist"T "$nlist"'
+	      case $host in
+	        *cygwin* | *mingw* | *cegcc* )
+	          eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+	          eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
+	          ;;
+	      esac
+	    }
+	  fi
+	fi
+
+	for dlprefile in $dlprefiles; do
+	  func_verbose "extracting global C symbols from \`$dlprefile'"
+	  func_basename "$dlprefile"
+	  name="$func_basename_result"
+          case $host in
+	    *cygwin* | *mingw* | *cegcc* )
+	      # if an import library, we need to obtain dlname
+	      if func_win32_import_lib_p "$dlprefile"; then
+	        func_tr_sh "$dlprefile"
+	        eval "curr_lafile=\$libfile_$func_tr_sh_result"
+	        dlprefile_dlbasename=""
+	        if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then
+	          # Use subshell, to avoid clobbering current variable values
+	          dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"`
+	          if test -n "$dlprefile_dlname" ; then
+	            func_basename "$dlprefile_dlname"
+	            dlprefile_dlbasename="$func_basename_result"
+	          else
+	            # no lafile. user explicitly requested -dlpreopen <import library>.
+	            $sharedlib_from_linklib_cmd "$dlprefile"
+	            dlprefile_dlbasename=$sharedlib_from_linklib_result
+	          fi
+	        fi
+	        $opt_dry_run || {
+	          if test -n "$dlprefile_dlbasename" ; then
+	            eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"'
+	          else
+	            func_warning "Could not compute DLL name from $name"
+	            eval '$ECHO ": $name " >> "$nlist"'
+	          fi
+	          func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	          eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe |
+	            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'"
+	        }
+	      else # not an import lib
+	        $opt_dry_run || {
+	          eval '$ECHO ": $name " >> "$nlist"'
+	          func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	          eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'"
+	        }
+	      fi
+	    ;;
+	    *)
+	      $opt_dry_run || {
+	        eval '$ECHO ": $name " >> "$nlist"'
+	        func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	        eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'"
+	      }
+	    ;;
+          esac
+	done
+
+	$opt_dry_run || {
+	  # Make sure we have at least an empty file.
+	  test -f "$nlist" || : > "$nlist"
+
+	  if test -n "$exclude_expsyms"; then
+	    $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T
+	    $MV "$nlist"T "$nlist"
+	  fi
+
+	  # Try sorting and uniquifying the output.
+	  if $GREP -v "^: " < "$nlist" |
+	      if sort -k 3 </dev/null >/dev/null 2>&1; then
+		sort -k 3
+	      else
+		sort +2
+	      fi |
+	      uniq > "$nlist"S; then
+	    :
+	  else
+	    $GREP -v "^: " < "$nlist" > "$nlist"S
+	  fi
+
+	  if test -f "$nlist"S; then
+	    eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"'
+	  else
+	    echo '/* NONE */' >> "$output_objdir/$my_dlsyms"
+	  fi
+
+	  echo >> "$output_objdir/$my_dlsyms" "\
+
+/* The mapping between symbol names and symbols.  */
+typedef struct {
+  const char *name;
+  void *address;
+} lt_dlsymlist;
+extern LT_DLSYM_CONST lt_dlsymlist
+lt_${my_prefix}_LTX_preloaded_symbols[];
+LT_DLSYM_CONST lt_dlsymlist
+lt_${my_prefix}_LTX_preloaded_symbols[] =
+{\
+  { \"$my_originator\", (void *) 0 },"
+
+	  case $need_lib_prefix in
+	  no)
+	    eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms"
+	    ;;
+	  *)
+	    eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms"
+	    ;;
+	  esac
+	  echo >> "$output_objdir/$my_dlsyms" "\
+  {0, (void *) 0}
+};
+
+/* This works around a problem in FreeBSD linker */
+#ifdef FREEBSD_WORKAROUND
+static const void *lt_preloaded_setup() {
+  return lt_${my_prefix}_LTX_preloaded_symbols;
+}
+#endif
+
+#ifdef __cplusplus
+}
+#endif\
+"
+	} # !$opt_dry_run
+
+	pic_flag_for_symtable=
+	case "$compile_command " in
+	*" -static "*) ;;
+	*)
+	  case $host in
+	  # compiling the symbol table file with pic_flag works around
+	  # a FreeBSD bug that causes programs to crash when -lm is
+	  # linked before any other PIC object.  But we must not use
+	  # pic_flag when linking with -static.  The problem exists in
+	  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.
+	  *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)
+	    pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;;
+	  *-*-hpux*)
+	    pic_flag_for_symtable=" $pic_flag"  ;;
+	  *)
+	    if test "X$my_pic_p" != Xno; then
+	      pic_flag_for_symtable=" $pic_flag"
+	    fi
+	    ;;
+	  esac
+	  ;;
+	esac
+	symtab_cflags=
+	for arg in $LTCFLAGS; do
+	  case $arg in
+	  -pie | -fpie | -fPIE) ;;
+	  *) func_append symtab_cflags " $arg" ;;
+	  esac
+	done
+
+	# Now compile the dynamic symbol file.
+	func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?'
+
+	# Clean up the generated files.
+	func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"'
+
+	# Transform the symbol file into the correct name.
+	symfileobj="$output_objdir/${my_outputname}S.$objext"
+	case $host in
+	*cygwin* | *mingw* | *cegcc* )
+	  if test -f "$output_objdir/$my_outputname.def"; then
+	    compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+	    finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+	  else
+	    compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	    finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	  fi
+	  ;;
+	*)
+	  compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	  finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	  ;;
+	esac
+	;;
+      *)
+	func_fatal_error "unknown suffix for \`$my_dlsyms'"
+	;;
+      esac
+    else
+      # We keep going just in case the user didn't refer to
+      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe
+      # really was required.
+
+      # Nullify the symbol file.
+      compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"`
+      finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"`
+    fi
+}
+
+# func_win32_libid arg
+# return the library type of file 'arg'
+#
+# Need a lot of goo to handle *both* DLLs and import libs
+# Has to be a shell function in order to 'eat' the argument
+# that is supplied when $file_magic_command is called.
+# Despite the name, also deal with 64 bit binaries.
+func_win32_libid ()
+{
+  $opt_debug
+  win32_libid_type="unknown"
+  win32_fileres=`file -L $1 2>/dev/null`
+  case $win32_fileres in
+  *ar\ archive\ import\ library*) # definitely import
+    win32_libid_type="x86 archive import"
+    ;;
+  *ar\ archive*) # could be an import, or static
+    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.
+    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |
+       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then
+      func_to_tool_file "$1" func_convert_file_msys_to_w32
+      win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" |
+	$SED -n -e '
+	    1,100{
+		/ I /{
+		    s,.*,import,
+		    p
+		    q
+		}
+	    }'`
+      case $win32_nmres in
+      import*)  win32_libid_type="x86 archive import";;
+      *)        win32_libid_type="x86 archive static";;
+      esac
+    fi
+    ;;
+  *DLL*)
+    win32_libid_type="x86 DLL"
+    ;;
+  *executable*) # but shell scripts are "executable" too...
+    case $win32_fileres in
+    *MS\ Windows\ PE\ Intel*)
+      win32_libid_type="x86 DLL"
+      ;;
+    esac
+    ;;
+  esac
+  $ECHO "$win32_libid_type"
+}
+
+# func_cygming_dll_for_implib ARG
+#
+# Platform-specific function to extract the
+# name of the DLL associated with the specified
+# import library ARG.
+# Invoked by eval'ing the libtool variable
+#    $sharedlib_from_linklib_cmd
+# Result is available in the variable
+#    $sharedlib_from_linklib_result
+func_cygming_dll_for_implib ()
+{
+  $opt_debug
+  sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"`
+}
+
+# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs
+#
+# The is the core of a fallback implementation of a
+# platform-specific function to extract the name of the
+# DLL associated with the specified import library LIBNAME.
+#
+# SECTION_NAME is either .idata$6 or .idata$7, depending
+# on the platform and compiler that created the implib.
+#
+# Echos the name of the DLL associated with the
+# specified import library.
+func_cygming_dll_for_implib_fallback_core ()
+{
+  $opt_debug
+  match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"`
+  $OBJDUMP -s --section "$1" "$2" 2>/dev/null |
+    $SED '/^Contents of section '"$match_literal"':/{
+      # Place marker at beginning of archive member dllname section
+      s/.*/====MARK====/
+      p
+      d
+    }
+    # These lines can sometimes be longer than 43 characters, but
+    # are always uninteresting
+    /:[	 ]*file format pe[i]\{,1\}-/d
+    /^In archive [^:]*:/d
+    # Ensure marker is printed
+    /^====MARK====/p
+    # Remove all lines with less than 43 characters
+    /^.\{43\}/!d
+    # From remaining lines, remove first 43 characters
+    s/^.\{43\}//' |
+    $SED -n '
+      # Join marker and all lines until next marker into a single line
+      /^====MARK====/ b para
+      H
+      $ b para
+      b
+      :para
+      x
+      s/\n//g
+      # Remove the marker
+      s/^====MARK====//
+      # Remove trailing dots and whitespace
+      s/[\. \t]*$//
+      # Print
+      /./p' |
+    # we now have a list, one entry per line, of the stringified
+    # contents of the appropriate section of all members of the
+    # archive which possess that section. Heuristic: eliminate
+    # all those which have a first or second character that is
+    # a '.' (that is, objdump's representation of an unprintable
+    # character.) This should work for all archives with less than
+    # 0x302f exports -- but will fail for DLLs whose name actually
+    # begins with a literal '.' or a single character followed by
+    # a '.'.
+    #
+    # Of those that remain, print the first one.
+    $SED -e '/^\./d;/^.\./d;q'
+}
+
+# func_cygming_gnu_implib_p ARG
+# This predicate returns with zero status (TRUE) if
+# ARG is a GNU/binutils-style import library. Returns
+# with nonzero status (FALSE) otherwise.
+func_cygming_gnu_implib_p ()
+{
+  $opt_debug
+  func_to_tool_file "$1" func_convert_file_msys_to_w32
+  func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`
+  test -n "$func_cygming_gnu_implib_tmp"
+}
+
+# func_cygming_ms_implib_p ARG
+# This predicate returns with zero status (TRUE) if
+# ARG is an MS-style import library. Returns
+# with nonzero status (FALSE) otherwise.
+func_cygming_ms_implib_p ()
+{
+  $opt_debug
+  func_to_tool_file "$1" func_convert_file_msys_to_w32
+  func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'`
+  test -n "$func_cygming_ms_implib_tmp"
+}
+
+# func_cygming_dll_for_implib_fallback ARG
+# Platform-specific function to extract the
+# name of the DLL associated with the specified
+# import library ARG.
+#
+# This fallback implementation is for use when $DLLTOOL
+# does not support the --identify-strict option.
+# Invoked by eval'ing the libtool variable
+#    $sharedlib_from_linklib_cmd
+# Result is available in the variable
+#    $sharedlib_from_linklib_result
+func_cygming_dll_for_implib_fallback ()
+{
+  $opt_debug
+  if func_cygming_gnu_implib_p "$1" ; then
+    # binutils import library
+    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"`
+  elif func_cygming_ms_implib_p "$1" ; then
+    # ms-generated import library
+    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"`
+  else
+    # unknown
+    sharedlib_from_linklib_result=""
+  fi
+}
+
+
+# func_extract_an_archive dir oldlib
+func_extract_an_archive ()
+{
+    $opt_debug
+    f_ex_an_ar_dir="$1"; shift
+    f_ex_an_ar_oldlib="$1"
+    if test "$lock_old_archive_extraction" = yes; then
+      lockfile=$f_ex_an_ar_oldlib.lock
+      until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do
+	func_echo "Waiting for $lockfile to be removed"
+	sleep 2
+      done
+    fi
+    func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \
+		   'stat=$?; rm -f "$lockfile"; exit $stat'
+    if test "$lock_old_archive_extraction" = yes; then
+      $opt_dry_run || rm -f "$lockfile"
+    fi
+    if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then
+     :
+    else
+      func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib"
+    fi
+}
+
+
+# func_extract_archives gentop oldlib ...
+func_extract_archives ()
+{
+    $opt_debug
+    my_gentop="$1"; shift
+    my_oldlibs=${1+"$@"}
+    my_oldobjs=""
+    my_xlib=""
+    my_xabs=""
+    my_xdir=""
+
+    for my_xlib in $my_oldlibs; do
+      # Extract the objects.
+      case $my_xlib in
+	[\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;;
+	*) my_xabs=`pwd`"/$my_xlib" ;;
+      esac
+      func_basename "$my_xlib"
+      my_xlib="$func_basename_result"
+      my_xlib_u=$my_xlib
+      while :; do
+        case " $extracted_archives " in
+	*" $my_xlib_u "*)
+	  func_arith $extracted_serial + 1
+	  extracted_serial=$func_arith_result
+	  my_xlib_u=lt$extracted_serial-$my_xlib ;;
+	*) break ;;
+	esac
+      done
+      extracted_archives="$extracted_archives $my_xlib_u"
+      my_xdir="$my_gentop/$my_xlib_u"
+
+      func_mkdir_p "$my_xdir"
+
+      case $host in
+      *-darwin*)
+	func_verbose "Extracting $my_xabs"
+	# Do not bother doing anything if just a dry run
+	$opt_dry_run || {
+	  darwin_orig_dir=`pwd`
+	  cd $my_xdir || exit $?
+	  darwin_archive=$my_xabs
+	  darwin_curdir=`pwd`
+	  darwin_base_archive=`basename "$darwin_archive"`
+	  darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true`
+	  if test -n "$darwin_arches"; then
+	    darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'`
+	    darwin_arch=
+	    func_verbose "$darwin_base_archive has multiple architectures $darwin_arches"
+	    for darwin_arch in  $darwin_arches ; do
+	      func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}"
+	      $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}"
+	      cd "unfat-$$/${darwin_base_archive}-${darwin_arch}"
+	      func_extract_an_archive "`pwd`" "${darwin_base_archive}"
+	      cd "$darwin_curdir"
+	      $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}"
+	    done # $darwin_arches
+            ## Okay now we've a bunch of thin objects, gotta fatten them up :)
+	    darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u`
+	    darwin_file=
+	    darwin_files=
+	    for darwin_file in $darwin_filelist; do
+	      darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP`
+	      $LIPO -create -output "$darwin_file" $darwin_files
+	    done # $darwin_filelist
+	    $RM -rf unfat-$$
+	    cd "$darwin_orig_dir"
+	  else
+	    cd $darwin_orig_dir
+	    func_extract_an_archive "$my_xdir" "$my_xabs"
+	  fi # $darwin_arches
+	} # !$opt_dry_run
+	;;
+      *)
+        func_extract_an_archive "$my_xdir" "$my_xabs"
+	;;
+      esac
+      my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP`
+    done
+
+    func_extract_archives_result="$my_oldobjs"
+}
+
+
+# func_emit_wrapper [arg=no]
+#
+# Emit a libtool wrapper script on stdout.
+# Don't directly open a file because we may want to
+# incorporate the script contents within a cygwin/mingw
+# wrapper executable.  Must ONLY be called from within
+# func_mode_link because it depends on a number of variables
+# set therein.
+#
+# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR
+# variable will take.  If 'yes', then the emitted script
+# will assume that the directory in which it is stored is
+# the $objdir directory.  This is a cygwin/mingw-specific
+# behavior.
+func_emit_wrapper ()
+{
+	func_emit_wrapper_arg1=${1-no}
+
+	$ECHO "\
+#! $SHELL
+
+# $output - temporary wrapper script for $objdir/$outputname
+# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+#
+# The $output program cannot be directly executed until all the libtool
+# libraries that it depends on are installed.
+#
+# This wrapper script should never be moved out of the build directory.
+# If it is, it will not operate correctly.
+
+# Sed substitution that helps us do robust quoting.  It backslashifies
+# metacharacters that are still active within double-quoted strings.
+sed_quote_subst='$sed_quote_subst'
+
+# Be Bourne compatible
+if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '\${1+\"\$@\"}'='\"\$@\"'
+  setopt NO_GLOB_SUBST
+else
+  case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac
+fi
+BIN_SH=xpg4; export BIN_SH # for Tru64
+DUALCASE=1; export DUALCASE # for MKS sh
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+relink_command=\"$relink_command\"
+
+# This environment variable determines our operation mode.
+if test \"\$libtool_install_magic\" = \"$magic\"; then
+  # install mode needs the following variables:
+  generated_by_libtool_version='$macro_version'
+  notinst_deplibs='$notinst_deplibs'
+else
+  # When we are sourced in execute mode, \$file and \$ECHO are already set.
+  if test \"\$libtool_execute_magic\" != \"$magic\"; then
+    file=\"\$0\""
+
+    qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"`
+    $ECHO "\
+
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+\$1
+_LTECHO_EOF'
+}
+    ECHO=\"$qECHO\"
+  fi
+
+# Very basic option parsing. These options are (a) specific to
+# the libtool wrapper, (b) are identical between the wrapper
+# /script/ and the wrapper /executable/ which is used only on
+# windows platforms, and (c) all begin with the string "--lt-"
+# (application programs are unlikely to have options which match
+# this pattern).
+#
+# There are only two supported options: --lt-debug and
+# --lt-dump-script. There is, deliberately, no --lt-help.
+#
+# The first argument to this parsing function should be the
+# script's $0 value, followed by "$@".
+lt_option_debug=
+func_parse_lt_options ()
+{
+  lt_script_arg0=\$0
+  shift
+  for lt_opt
+  do
+    case \"\$lt_opt\" in
+    --lt-debug) lt_option_debug=1 ;;
+    --lt-dump-script)
+        lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\`
+        test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=.
+        lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\`
+        cat \"\$lt_dump_D/\$lt_dump_F\"
+        exit 0
+      ;;
+    --lt-*)
+        \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2
+        exit 1
+      ;;
+    esac
+  done
+
+  # Print the debug banner immediately:
+  if test -n \"\$lt_option_debug\"; then
+    echo \"${outputname}:${output}:\${LINENO}: libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\" 1>&2
+  fi
+}
+
+# Used when --lt-debug. Prints its arguments to stdout
+# (redirection is the responsibility of the caller)
+func_lt_dump_args ()
+{
+  lt_dump_args_N=1;
+  for lt_arg
+  do
+    \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[\$lt_dump_args_N]: \$lt_arg\"
+    lt_dump_args_N=\`expr \$lt_dump_args_N + 1\`
+  done
+}
+
+# Core function for launching the target application
+func_exec_program_core ()
+{
+"
+  case $host in
+  # Backslashes separate directories on plain windows
+  *-*-mingw | *-*-os2* | *-cegcc*)
+    $ECHO "\
+      if test -n \"\$lt_option_debug\"; then
+        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir\\\\\$program\" 1>&2
+        func_lt_dump_args \${1+\"\$@\"} 1>&2
+      fi
+      exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
+"
+    ;;
+
+  *)
+    $ECHO "\
+      if test -n \"\$lt_option_debug\"; then
+        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir/\$program\" 1>&2
+        func_lt_dump_args \${1+\"\$@\"} 1>&2
+      fi
+      exec \"\$progdir/\$program\" \${1+\"\$@\"}
+"
+    ;;
+  esac
+  $ECHO "\
+      \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2
+      exit 1
+}
+
+# A function to encapsulate launching the target application
+# Strips options in the --lt-* namespace from \$@ and
+# launches target application with the remaining arguments.
+func_exec_program ()
+{
+  case \" \$* \" in
+  *\\ --lt-*)
+    for lt_wr_arg
+    do
+      case \$lt_wr_arg in
+      --lt-*) ;;
+      *) set x \"\$@\" \"\$lt_wr_arg\"; shift;;
+      esac
+      shift
+    done ;;
+  esac
+  func_exec_program_core \${1+\"\$@\"}
+}
+
+  # Parse options
+  func_parse_lt_options \"\$0\" \${1+\"\$@\"}
+
+  # Find the directory that this script lives in.
+  thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\`
+  test \"x\$thisdir\" = \"x\$file\" && thisdir=.
+
+  # Follow symbolic links until we get to the real thisdir.
+  file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\`
+  while test -n \"\$file\"; do
+    destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\`
+
+    # If there was a directory component, then change thisdir.
+    if test \"x\$destdir\" != \"x\$file\"; then
+      case \"\$destdir\" in
+      [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;;
+      *) thisdir=\"\$thisdir/\$destdir\" ;;
+      esac
+    fi
+
+    file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\`
+    file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\`
+  done
+
+  # Usually 'no', except on cygwin/mingw when embedded into
+  # the cwrapper.
+  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1
+  if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then
+    # special case for '.'
+    if test \"\$thisdir\" = \".\"; then
+      thisdir=\`pwd\`
+    fi
+    # remove .libs from thisdir
+    case \"\$thisdir\" in
+    *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;;
+    $objdir )   thisdir=. ;;
+    esac
+  fi
+
+  # Try to get the absolute directory name.
+  absdir=\`cd \"\$thisdir\" && pwd\`
+  test -n \"\$absdir\" && thisdir=\"\$absdir\"
+"
+
+	if test "$fast_install" = yes; then
+	  $ECHO "\
+  program=lt-'$outputname'$exeext
+  progdir=\"\$thisdir/$objdir\"
+
+  if test ! -f \"\$progdir/\$program\" ||
+     { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\
+       test \"X\$file\" != \"X\$progdir/\$program\"; }; then
+
+    file=\"\$\$-\$program\"
+
+    if test ! -d \"\$progdir\"; then
+      $MKDIR \"\$progdir\"
+    else
+      $RM \"\$progdir/\$file\"
+    fi"
+
+	  $ECHO "\
+
+    # relink executable if necessary
+    if test -n \"\$relink_command\"; then
+      if relink_command_output=\`eval \$relink_command 2>&1\`; then :
+      else
+	$ECHO \"\$relink_command_output\" >&2
+	$RM \"\$progdir/\$file\"
+	exit 1
+      fi
+    fi
+
+    $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
+    { $RM \"\$progdir/\$program\";
+      $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; }
+    $RM \"\$progdir/\$file\"
+  fi"
+	else
+	  $ECHO "\
+  program='$outputname'
+  progdir=\"\$thisdir/$objdir\"
+"
+	fi
+
+	$ECHO "\
+
+  if test -f \"\$progdir/\$program\"; then"
+
+	# fixup the dll searchpath if we need to.
+	#
+	# Fix the DLL searchpath if we need to.  Do this before prepending
+	# to shlibpath, because on Windows, both are PATH and uninstalled
+	# libraries must come first.
+	if test -n "$dllsearchpath"; then
+	  $ECHO "\
+    # Add the dll search path components to the executable PATH
+    PATH=$dllsearchpath:\$PATH
+"
+	fi
+
+	# Export our shlibpath_var if we have one.
+	if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+	  $ECHO "\
+    # Add our own library path to $shlibpath_var
+    $shlibpath_var=\"$temp_rpath\$$shlibpath_var\"
+
+    # Some systems cannot cope with colon-terminated $shlibpath_var
+    # The second colon is a workaround for a bug in BeOS R4 sed
+    $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\`
+
+    export $shlibpath_var
+"
+	fi
+
+	$ECHO "\
+    if test \"\$libtool_execute_magic\" != \"$magic\"; then
+      # Run the actual program with our arguments.
+      func_exec_program \${1+\"\$@\"}
+    fi
+  else
+    # The program doesn't exist.
+    \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
+    \$ECHO \"This script is just a wrapper for \$program.\" 1>&2
+    \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2
+    exit 1
+  fi
+fi\
+"
+}
+
+
+# func_emit_cwrapperexe_src
+# emit the source code for a wrapper executable on stdout
+# Must ONLY be called from within func_mode_link because
+# it depends on a number of variable set therein.
+func_emit_cwrapperexe_src ()
+{
+	cat <<EOF
+
+/* $cwrappersource - temporary wrapper executable for $objdir/$outputname
+   Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+
+   The $output program cannot be directly executed until all the libtool
+   libraries that it depends on are installed.
+
+   This wrapper executable should never be moved out of the build directory.
+   If it is, it will not operate correctly.
+*/
+EOF
+	    cat <<"EOF"
+#ifdef _MSC_VER
+# define _CRT_SECURE_NO_DEPRECATE 1
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef _MSC_VER
+# include <direct.h>
+# include <process.h>
+# include <io.h>
+#else
+# include <unistd.h>
+# include <stdint.h>
+# ifdef __CYGWIN__
+#  include <io.h>
+# endif
+#endif
+#include <malloc.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <string.h>
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+
+/* declarations of non-ANSI functions */
+#if defined(__MINGW32__)
+# ifdef __STRICT_ANSI__
+int _putenv (const char *);
+# endif
+#elif defined(__CYGWIN__)
+# ifdef __STRICT_ANSI__
+char *realpath (const char *, char *);
+int putenv (char *);
+int setenv (const char *, const char *, int);
+# endif
+/* #elif defined (other platforms) ... */
+#endif
+
+/* portability defines, excluding path handling macros */
+#if defined(_MSC_VER)
+# define setmode _setmode
+# define stat    _stat
+# define chmod   _chmod
+# define getcwd  _getcwd
+# define putenv  _putenv
+# define S_IXUSR _S_IEXEC
+# ifndef _INTPTR_T_DEFINED
+#  define _INTPTR_T_DEFINED
+#  define intptr_t int
+# endif
+#elif defined(__MINGW32__)
+# define setmode _setmode
+# define stat    _stat
+# define chmod   _chmod
+# define getcwd  _getcwd
+# define putenv  _putenv
+#elif defined(__CYGWIN__)
+# define HAVE_SETENV
+# define FOPEN_WB "wb"
+/* #elif defined (other platforms) ... */
+#endif
+
+#if defined(PATH_MAX)
+# define LT_PATHMAX PATH_MAX
+#elif defined(MAXPATHLEN)
+# define LT_PATHMAX MAXPATHLEN
+#else
+# define LT_PATHMAX 1024
+#endif
+
+#ifndef S_IXOTH
+# define S_IXOTH 0
+#endif
+#ifndef S_IXGRP
+# define S_IXGRP 0
+#endif
+
+/* path handling portability macros */
+#ifndef DIR_SEPARATOR
+# define DIR_SEPARATOR '/'
+# define PATH_SEPARATOR ':'
+#endif
+
+#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \
+  defined (__OS2__)
+# define HAVE_DOS_BASED_FILE_SYSTEM
+# define FOPEN_WB "wb"
+# ifndef DIR_SEPARATOR_2
+#  define DIR_SEPARATOR_2 '\\'
+# endif
+# ifndef PATH_SEPARATOR_2
+#  define PATH_SEPARATOR_2 ';'
+# endif
+#endif
+
+#ifndef DIR_SEPARATOR_2
+# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)
+#else /* DIR_SEPARATOR_2 */
+# define IS_DIR_SEPARATOR(ch) \
+	(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))
+#endif /* DIR_SEPARATOR_2 */
+
+#ifndef PATH_SEPARATOR_2
+# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)
+#else /* PATH_SEPARATOR_2 */
+# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)
+#endif /* PATH_SEPARATOR_2 */
+
+#ifndef FOPEN_WB
+# define FOPEN_WB "w"
+#endif
+#ifndef _O_BINARY
+# define _O_BINARY 0
+#endif
+
+#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))
+#define XFREE(stale) do { \
+  if (stale) { free ((void *) stale); stale = 0; } \
+} while (0)
+
+#if defined(LT_DEBUGWRAPPER)
+static int lt_debug = 1;
+#else
+static int lt_debug = 0;
+#endif
+
+const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */
+
+void *xmalloc (size_t num);
+char *xstrdup (const char *string);
+const char *base_name (const char *name);
+char *find_executable (const char *wrapper);
+char *chase_symlinks (const char *pathspec);
+int make_executable (const char *path);
+int check_executable (const char *path);
+char *strendzap (char *str, const char *pat);
+void lt_debugprintf (const char *file, int line, const char *fmt, ...);
+void lt_fatal (const char *file, int line, const char *message, ...);
+static const char *nonnull (const char *s);
+static const char *nonempty (const char *s);
+void lt_setenv (const char *name, const char *value);
+char *lt_extend_str (const char *orig_value, const char *add, int to_end);
+void lt_update_exe_path (const char *name, const char *value);
+void lt_update_lib_path (const char *name, const char *value);
+char **prepare_spawn (char **argv);
+void lt_dump_script (FILE *f);
+EOF
+
+	    cat <<EOF
+volatile const char * MAGIC_EXE = "$magic_exe";
+const char * LIB_PATH_VARNAME = "$shlibpath_var";
+EOF
+
+	    if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+              func_to_host_path "$temp_rpath"
+	      cat <<EOF
+const char * LIB_PATH_VALUE   = "$func_to_host_path_result";
+EOF
+	    else
+	      cat <<"EOF"
+const char * LIB_PATH_VALUE   = "";
+EOF
+	    fi
+
+	    if test -n "$dllsearchpath"; then
+              func_to_host_path "$dllsearchpath:"
+	      cat <<EOF
+const char * EXE_PATH_VARNAME = "PATH";
+const char * EXE_PATH_VALUE   = "$func_to_host_path_result";
+EOF
+	    else
+	      cat <<"EOF"
+const char * EXE_PATH_VARNAME = "";
+const char * EXE_PATH_VALUE   = "";
+EOF
+	    fi
+
+	    if test "$fast_install" = yes; then
+	      cat <<EOF
+const char * TARGET_PROGRAM_NAME = "lt-$outputname"; /* hopefully, no .exe */
+EOF
+	    else
+	      cat <<EOF
+const char * TARGET_PROGRAM_NAME = "$outputname"; /* hopefully, no .exe */
+EOF
+	    fi
+
+
+	    cat <<"EOF"
+
+#define LTWRAPPER_OPTION_PREFIX         "--lt-"
+
+static const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;
+static const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX "dump-script";
+static const char *debug_opt            = LTWRAPPER_OPTION_PREFIX "debug";
+
+int
+main (int argc, char *argv[])
+{
+  char **newargz;
+  int  newargc;
+  char *tmp_pathspec;
+  char *actual_cwrapper_path;
+  char *actual_cwrapper_name;
+  char *target_name;
+  char *lt_argv_zero;
+  intptr_t rval = 127;
+
+  int i;
+
+  program_name = (char *) xstrdup (base_name (argv[0]));
+  newargz = XMALLOC (char *, argc + 1);
+
+  /* very simple arg parsing; don't want to rely on getopt
+   * also, copy all non cwrapper options to newargz, except
+   * argz[0], which is handled differently
+   */
+  newargc=0;
+  for (i = 1; i < argc; i++)
+    {
+      if (strcmp (argv[i], dumpscript_opt) == 0)
+	{
+EOF
+	    case "$host" in
+	      *mingw* | *cygwin* )
+		# make stdout use "unix" line endings
+		echo "          setmode(1,_O_BINARY);"
+		;;
+	      esac
+
+	    cat <<"EOF"
+	  lt_dump_script (stdout);
+	  return 0;
+	}
+      if (strcmp (argv[i], debug_opt) == 0)
+	{
+          lt_debug = 1;
+          continue;
+	}
+      if (strcmp (argv[i], ltwrapper_option_prefix) == 0)
+        {
+          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX
+             namespace, but it is not one of the ones we know about and
+             have already dealt with, above (inluding dump-script), then
+             report an error. Otherwise, targets might begin to believe
+             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX
+             namespace. The first time any user complains about this, we'll
+             need to make LTWRAPPER_OPTION_PREFIX a configure-time option
+             or a configure.ac-settable value.
+           */
+          lt_fatal (__FILE__, __LINE__,
+		    "unrecognized %s option: '%s'",
+                    ltwrapper_option_prefix, argv[i]);
+        }
+      /* otherwise ... */
+      newargz[++newargc] = xstrdup (argv[i]);
+    }
+  newargz[++newargc] = NULL;
+
+EOF
+	    cat <<EOF
+  /* The GNU banner must be the first non-error debug message */
+  lt_debugprintf (__FILE__, __LINE__, "libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\n");
+EOF
+	    cat <<"EOF"
+  lt_debugprintf (__FILE__, __LINE__, "(main) argv[0]: %s\n", argv[0]);
+  lt_debugprintf (__FILE__, __LINE__, "(main) program_name: %s\n", program_name);
+
+  tmp_pathspec = find_executable (argv[0]);
+  if (tmp_pathspec == NULL)
+    lt_fatal (__FILE__, __LINE__, "couldn't find %s", argv[0]);
+  lt_debugprintf (__FILE__, __LINE__,
+                  "(main) found exe (before symlink chase) at: %s\n",
+		  tmp_pathspec);
+
+  actual_cwrapper_path = chase_symlinks (tmp_pathspec);
+  lt_debugprintf (__FILE__, __LINE__,
+                  "(main) found exe (after symlink chase) at: %s\n",
+		  actual_cwrapper_path);
+  XFREE (tmp_pathspec);
+
+  actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path));
+  strendzap (actual_cwrapper_path, actual_cwrapper_name);
+
+  /* wrapper name transforms */
+  strendzap (actual_cwrapper_name, ".exe");
+  tmp_pathspec = lt_extend_str (actual_cwrapper_name, ".exe", 1);
+  XFREE (actual_cwrapper_name);
+  actual_cwrapper_name = tmp_pathspec;
+  tmp_pathspec = 0;
+
+  /* target_name transforms -- use actual target program name; might have lt- prefix */
+  target_name = xstrdup (base_name (TARGET_PROGRAM_NAME));
+  strendzap (target_name, ".exe");
+  tmp_pathspec = lt_extend_str (target_name, ".exe", 1);
+  XFREE (target_name);
+  target_name = tmp_pathspec;
+  tmp_pathspec = 0;
+
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(main) libtool target name: %s\n",
+		  target_name);
+EOF
+
+	    cat <<EOF
+  newargz[0] =
+    XMALLOC (char, (strlen (actual_cwrapper_path) +
+		    strlen ("$objdir") + 1 + strlen (actual_cwrapper_name) + 1));
+  strcpy (newargz[0], actual_cwrapper_path);
+  strcat (newargz[0], "$objdir");
+  strcat (newargz[0], "/");
+EOF
+
+	    cat <<"EOF"
+  /* stop here, and copy so we don't have to do this twice */
+  tmp_pathspec = xstrdup (newargz[0]);
+
+  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */
+  strcat (newargz[0], actual_cwrapper_name);
+
+  /* DO want the lt- prefix here if it exists, so use target_name */
+  lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1);
+  XFREE (tmp_pathspec);
+  tmp_pathspec = NULL;
+EOF
+
+	    case $host_os in
+	      mingw*)
+	    cat <<"EOF"
+  {
+    char* p;
+    while ((p = strchr (newargz[0], '\\')) != NULL)
+      {
+	*p = '/';
+      }
+    while ((p = strchr (lt_argv_zero, '\\')) != NULL)
+      {
+	*p = '/';
+      }
+  }
+EOF
+	    ;;
+	    esac
+
+	    cat <<"EOF"
+  XFREE (target_name);
+  XFREE (actual_cwrapper_path);
+  XFREE (actual_cwrapper_name);
+
+  lt_setenv ("BIN_SH", "xpg4"); /* for Tru64 */
+  lt_setenv ("DUALCASE", "1");  /* for MSK sh */
+  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must
+     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath)
+     because on Windows, both *_VARNAMEs are PATH but uninstalled
+     libraries must come first. */
+  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);
+  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);
+
+  lt_debugprintf (__FILE__, __LINE__, "(main) lt_argv_zero: %s\n",
+		  nonnull (lt_argv_zero));
+  for (i = 0; i < newargc; i++)
+    {
+      lt_debugprintf (__FILE__, __LINE__, "(main) newargz[%d]: %s\n",
+		      i, nonnull (newargz[i]));
+    }
+
+EOF
+
+	    case $host_os in
+	      mingw*)
+		cat <<"EOF"
+  /* execv doesn't actually work on mingw as expected on unix */
+  newargz = prepare_spawn (newargz);
+  rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);
+  if (rval == -1)
+    {
+      /* failed to start process */
+      lt_debugprintf (__FILE__, __LINE__,
+		      "(main) failed to launch target \"%s\": %s\n",
+		      lt_argv_zero, nonnull (strerror (errno)));
+      return 127;
+    }
+  return rval;
+EOF
+		;;
+	      *)
+		cat <<"EOF"
+  execv (lt_argv_zero, newargz);
+  return rval; /* =127, but avoids unused variable warning */
+EOF
+		;;
+	    esac
+
+	    cat <<"EOF"
+}
+
+void *
+xmalloc (size_t num)
+{
+  void *p = (void *) malloc (num);
+  if (!p)
+    lt_fatal (__FILE__, __LINE__, "memory exhausted");
+
+  return p;
+}
+
+char *
+xstrdup (const char *string)
+{
+  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),
+			  string) : NULL;
+}
+
+const char *
+base_name (const char *name)
+{
+  const char *base;
+
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+  /* Skip over the disk name in MSDOS pathnames. */
+  if (isalpha ((unsigned char) name[0]) && name[1] == ':')
+    name += 2;
+#endif
+
+  for (base = name; *name; name++)
+    if (IS_DIR_SEPARATOR (*name))
+      base = name + 1;
+  return base;
+}
+
+int
+check_executable (const char *path)
+{
+  struct stat st;
+
+  lt_debugprintf (__FILE__, __LINE__, "(check_executable): %s\n",
+                  nonempty (path));
+  if ((!path) || (!*path))
+    return 0;
+
+  if ((stat (path, &st) >= 0)
+      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
+    return 1;
+  else
+    return 0;
+}
+
+int
+make_executable (const char *path)
+{
+  int rval = 0;
+  struct stat st;
+
+  lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n",
+                  nonempty (path));
+  if ((!path) || (!*path))
+    return 0;
+
+  if (stat (path, &st) >= 0)
+    {
+      rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);
+    }
+  return rval;
+}
+
+/* Searches for the full path of the wrapper.  Returns
+   newly allocated full path name if found, NULL otherwise
+   Does not chase symlinks, even on platforms that support them.
+*/
+char *
+find_executable (const char *wrapper)
+{
+  int has_slash = 0;
+  const char *p;
+  const char *p_next;
+  /* static buffer for getcwd */
+  char tmp[LT_PATHMAX + 1];
+  int tmp_len;
+  char *concat_name;
+
+  lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n",
+                  nonempty (wrapper));
+
+  if ((wrapper == NULL) || (*wrapper == '\0'))
+    return NULL;
+
+  /* Absolute path? */
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')
+    {
+      concat_name = xstrdup (wrapper);
+      if (check_executable (concat_name))
+	return concat_name;
+      XFREE (concat_name);
+    }
+  else
+    {
+#endif
+      if (IS_DIR_SEPARATOR (wrapper[0]))
+	{
+	  concat_name = xstrdup (wrapper);
+	  if (check_executable (concat_name))
+	    return concat_name;
+	  XFREE (concat_name);
+	}
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+    }
+#endif
+
+  for (p = wrapper; *p; p++)
+    if (*p == '/')
+      {
+	has_slash = 1;
+	break;
+      }
+  if (!has_slash)
+    {
+      /* no slashes; search PATH */
+      const char *path = getenv ("PATH");
+      if (path != NULL)
+	{
+	  for (p = path; *p; p = p_next)
+	    {
+	      const char *q;
+	      size_t p_len;
+	      for (q = p; *q; q++)
+		if (IS_PATH_SEPARATOR (*q))
+		  break;
+	      p_len = q - p;
+	      p_next = (*q == '\0' ? q : q + 1);
+	      if (p_len == 0)
+		{
+		  /* empty path: current directory */
+		  if (getcwd (tmp, LT_PATHMAX) == NULL)
+		    lt_fatal (__FILE__, __LINE__, "getcwd failed: %s",
+                              nonnull (strerror (errno)));
+		  tmp_len = strlen (tmp);
+		  concat_name =
+		    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);
+		  memcpy (concat_name, tmp, tmp_len);
+		  concat_name[tmp_len] = '/';
+		  strcpy (concat_name + tmp_len + 1, wrapper);
+		}
+	      else
+		{
+		  concat_name =
+		    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);
+		  memcpy (concat_name, p, p_len);
+		  concat_name[p_len] = '/';
+		  strcpy (concat_name + p_len + 1, wrapper);
+		}
+	      if (check_executable (concat_name))
+		return concat_name;
+	      XFREE (concat_name);
+	    }
+	}
+      /* not found in PATH; assume curdir */
+    }
+  /* Relative path | not found in path: prepend cwd */
+  if (getcwd (tmp, LT_PATHMAX) == NULL)
+    lt_fatal (__FILE__, __LINE__, "getcwd failed: %s",
+              nonnull (strerror (errno)));
+  tmp_len = strlen (tmp);
+  concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);
+  memcpy (concat_name, tmp, tmp_len);
+  concat_name[tmp_len] = '/';
+  strcpy (concat_name + tmp_len + 1, wrapper);
+
+  if (check_executable (concat_name))
+    return concat_name;
+  XFREE (concat_name);
+  return NULL;
+}
+
+char *
+chase_symlinks (const char *pathspec)
+{
+#ifndef S_ISLNK
+  return xstrdup (pathspec);
+#else
+  char buf[LT_PATHMAX];
+  struct stat s;
+  char *tmp_pathspec = xstrdup (pathspec);
+  char *p;
+  int has_symlinks = 0;
+  while (strlen (tmp_pathspec) && !has_symlinks)
+    {
+      lt_debugprintf (__FILE__, __LINE__,
+		      "checking path component for symlinks: %s\n",
+		      tmp_pathspec);
+      if (lstat (tmp_pathspec, &s) == 0)
+	{
+	  if (S_ISLNK (s.st_mode) != 0)
+	    {
+	      has_symlinks = 1;
+	      break;
+	    }
+
+	  /* search backwards for last DIR_SEPARATOR */
+	  p = tmp_pathspec + strlen (tmp_pathspec) - 1;
+	  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))
+	    p--;
+	  if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))
+	    {
+	      /* no more DIR_SEPARATORS left */
+	      break;
+	    }
+	  *p = '\0';
+	}
+      else
+	{
+	  lt_fatal (__FILE__, __LINE__,
+		    "error accessing file \"%s\": %s",
+		    tmp_pathspec, nonnull (strerror (errno)));
+	}
+    }
+  XFREE (tmp_pathspec);
+
+  if (!has_symlinks)
+    {
+      return xstrdup (pathspec);
+    }
+
+  tmp_pathspec = realpath (pathspec, buf);
+  if (tmp_pathspec == 0)
+    {
+      lt_fatal (__FILE__, __LINE__,
+		"could not follow symlinks for %s", pathspec);
+    }
+  return xstrdup (tmp_pathspec);
+#endif
+}
+
+char *
+strendzap (char *str, const char *pat)
+{
+  size_t len, patlen;
+
+  assert (str != NULL);
+  assert (pat != NULL);
+
+  len = strlen (str);
+  patlen = strlen (pat);
+
+  if (patlen <= len)
+    {
+      str += len - patlen;
+      if (strcmp (str, pat) == 0)
+	*str = '\0';
+    }
+  return str;
+}
+
+void
+lt_debugprintf (const char *file, int line, const char *fmt, ...)
+{
+  va_list args;
+  if (lt_debug)
+    {
+      (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line);
+      va_start (args, fmt);
+      (void) vfprintf (stderr, fmt, args);
+      va_end (args);
+    }
+}
+
+static void
+lt_error_core (int exit_status, const char *file,
+	       int line, const char *mode,
+	       const char *message, va_list ap)
+{
+  fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode);
+  vfprintf (stderr, message, ap);
+  fprintf (stderr, ".\n");
+
+  if (exit_status >= 0)
+    exit (exit_status);
+}
+
+void
+lt_fatal (const char *file, int line, const char *message, ...)
+{
+  va_list ap;
+  va_start (ap, message);
+  lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap);
+  va_end (ap);
+}
+
+static const char *
+nonnull (const char *s)
+{
+  return s ? s : "(null)";
+}
+
+static const char *
+nonempty (const char *s)
+{
+  return (s && !*s) ? "(empty)" : nonnull (s);
+}
+
+void
+lt_setenv (const char *name, const char *value)
+{
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_setenv) setting '%s' to '%s'\n",
+                  nonnull (name), nonnull (value));
+  {
+#ifdef HAVE_SETENV
+    /* always make a copy, for consistency with !HAVE_SETENV */
+    char *str = xstrdup (value);
+    setenv (name, str, 1);
+#else
+    int len = strlen (name) + 1 + strlen (value) + 1;
+    char *str = XMALLOC (char, len);
+    sprintf (str, "%s=%s", name, value);
+    if (putenv (str) != EXIT_SUCCESS)
+      {
+        XFREE (str);
+      }
+#endif
+  }
+}
+
+char *
+lt_extend_str (const char *orig_value, const char *add, int to_end)
+{
+  char *new_value;
+  if (orig_value && *orig_value)
+    {
+      int orig_value_len = strlen (orig_value);
+      int add_len = strlen (add);
+      new_value = XMALLOC (char, add_len + orig_value_len + 1);
+      if (to_end)
+        {
+          strcpy (new_value, orig_value);
+          strcpy (new_value + orig_value_len, add);
+        }
+      else
+        {
+          strcpy (new_value, add);
+          strcpy (new_value + add_len, orig_value);
+        }
+    }
+  else
+    {
+      new_value = xstrdup (add);
+    }
+  return new_value;
+}
+
+void
+lt_update_exe_path (const char *name, const char *value)
+{
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_update_exe_path) modifying '%s' by prepending '%s'\n",
+                  nonnull (name), nonnull (value));
+
+  if (name && *name && value && *value)
+    {
+      char *new_value = lt_extend_str (getenv (name), value, 0);
+      /* some systems can't cope with a ':'-terminated path #' */
+      int len = strlen (new_value);
+      while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1]))
+        {
+          new_value[len-1] = '\0';
+        }
+      lt_setenv (name, new_value);
+      XFREE (new_value);
+    }
+}
+
+void
+lt_update_lib_path (const char *name, const char *value)
+{
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_update_lib_path) modifying '%s' by prepending '%s'\n",
+                  nonnull (name), nonnull (value));
+
+  if (name && *name && value && *value)
+    {
+      char *new_value = lt_extend_str (getenv (name), value, 0);
+      lt_setenv (name, new_value);
+      XFREE (new_value);
+    }
+}
+
+EOF
+	    case $host_os in
+	      mingw*)
+		cat <<"EOF"
+
+/* Prepares an argument vector before calling spawn().
+   Note that spawn() does not by itself call the command interpreter
+     (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") :
+      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+         GetVersionEx(&v);
+         v.dwPlatformId == VER_PLATFORM_WIN32_NT;
+      }) ? "cmd.exe" : "command.com").
+   Instead it simply concatenates the arguments, separated by ' ', and calls
+   CreateProcess().  We must quote the arguments since Win32 CreateProcess()
+   interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a
+   special way:
+   - Space and tab are interpreted as delimiters. They are not treated as
+     delimiters if they are surrounded by double quotes: "...".
+   - Unescaped double quotes are removed from the input. Their only effect is
+     that within double quotes, space and tab are treated like normal
+     characters.
+   - Backslashes not followed by double quotes are not special.
+   - But 2*n+1 backslashes followed by a double quote become
+     n backslashes followed by a double quote (n >= 0):
+       \" -> "
+       \\\" -> \"
+       \\\\\" -> \\"
+ */
+#define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
+#define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
+char **
+prepare_spawn (char **argv)
+{
+  size_t argc;
+  char **new_argv;
+  size_t i;
+
+  /* Count number of arguments.  */
+  for (argc = 0; argv[argc] != NULL; argc++)
+    ;
+
+  /* Allocate new argument vector.  */
+  new_argv = XMALLOC (char *, argc + 1);
+
+  /* Put quoted arguments into the new argument vector.  */
+  for (i = 0; i < argc; i++)
+    {
+      const char *string = argv[i];
+
+      if (string[0] == '\0')
+	new_argv[i] = xstrdup ("\"\"");
+      else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)
+	{
+	  int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);
+	  size_t length;
+	  unsigned int backslashes;
+	  const char *s;
+	  char *quoted_string;
+	  char *p;
+
+	  length = 0;
+	  backslashes = 0;
+	  if (quote_around)
+	    length++;
+	  for (s = string; *s != '\0'; s++)
+	    {
+	      char c = *s;
+	      if (c == '"')
+		length += backslashes + 1;
+	      length++;
+	      if (c == '\\')
+		backslashes++;
+	      else
+		backslashes = 0;
+	    }
+	  if (quote_around)
+	    length += backslashes + 1;
+
+	  quoted_string = XMALLOC (char, length + 1);
+
+	  p = quoted_string;
+	  backslashes = 0;
+	  if (quote_around)
+	    *p++ = '"';
+	  for (s = string; *s != '\0'; s++)
+	    {
+	      char c = *s;
+	      if (c == '"')
+		{
+		  unsigned int j;
+		  for (j = backslashes + 1; j > 0; j--)
+		    *p++ = '\\';
+		}
+	      *p++ = c;
+	      if (c == '\\')
+		backslashes++;
+	      else
+		backslashes = 0;
+	    }
+	  if (quote_around)
+	    {
+	      unsigned int j;
+	      for (j = backslashes; j > 0; j--)
+		*p++ = '\\';
+	      *p++ = '"';
+	    }
+	  *p = '\0';
+
+	  new_argv[i] = quoted_string;
+	}
+      else
+	new_argv[i] = (char *) string;
+    }
+  new_argv[argc] = NULL;
+
+  return new_argv;
+}
+EOF
+		;;
+	    esac
+
+            cat <<"EOF"
+void lt_dump_script (FILE* f)
+{
+EOF
+	    func_emit_wrapper yes |
+	      $SED -n -e '
+s/^\(.\{79\}\)\(..*\)/\1\
+\2/
+h
+s/\([\\"]\)/\\\1/g
+s/$/\\n/
+s/\([^\n]*\).*/  fputs ("\1", f);/p
+g
+D'
+            cat <<"EOF"
+}
+EOF
+}
+# end: func_emit_cwrapperexe_src
+
+# func_win32_import_lib_p ARG
+# True if ARG is an import lib, as indicated by $file_magic_cmd
+func_win32_import_lib_p ()
+{
+    $opt_debug
+    case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in
+    *import*) : ;;
+    *) false ;;
+    esac
+}
+
+# func_mode_link arg...
+func_mode_link ()
+{
+    $opt_debug
+    case $host in
+    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+      # It is impossible to link a dll without this setting, and
+      # we shouldn't force the makefile maintainer to figure out
+      # which system we are compiling for in order to pass an extra
+      # flag for every libtool invocation.
+      # allow_undefined=no
+
+      # FIXME: Unfortunately, there are problems with the above when trying
+      # to make a dll which has undefined symbols, in which case not
+      # even a static library is built.  For now, we need to specify
+      # -no-undefined on the libtool link line when we can be certain
+      # that all symbols are satisfied, otherwise we get a static library.
+      allow_undefined=yes
+      ;;
+    *)
+      allow_undefined=yes
+      ;;
+    esac
+    libtool_args=$nonopt
+    base_compile="$nonopt $@"
+    compile_command=$nonopt
+    finalize_command=$nonopt
+
+    compile_rpath=
+    finalize_rpath=
+    compile_shlibpath=
+    finalize_shlibpath=
+    convenience=
+    old_convenience=
+    deplibs=
+    old_deplibs=
+    compiler_flags=
+    linker_flags=
+    dllsearchpath=
+    lib_search_path=`pwd`
+    inst_prefix_dir=
+    new_inherited_linker_flags=
+
+    avoid_version=no
+    bindir=
+    dlfiles=
+    dlprefiles=
+    dlself=no
+    export_dynamic=no
+    export_symbols=
+    export_symbols_regex=
+    generated=
+    libobjs=
+    ltlibs=
+    module=no
+    no_install=no
+    objs=
+    non_pic_objects=
+    precious_files_regex=
+    prefer_static_libs=no
+    preload=no
+    prev=
+    prevarg=
+    release=
+    rpath=
+    xrpath=
+    perm_rpath=
+    temp_rpath=
+    thread_safe=no
+    vinfo=
+    vinfo_number=no
+    weak_libs=
+    single_module="${wl}-single_module"
+    func_infer_tag $base_compile
+
+    # We need to know -static, to get the right output filenames.
+    for arg
+    do
+      case $arg in
+      -shared)
+	test "$build_libtool_libs" != yes && \
+	  func_fatal_configuration "can not build a shared library"
+	build_old_libs=no
+	break
+	;;
+      -all-static | -static | -static-libtool-libs)
+	case $arg in
+	-all-static)
+	  if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then
+	    func_warning "complete static linking is impossible in this configuration"
+	  fi
+	  if test -n "$link_static_flag"; then
+	    dlopen_self=$dlopen_self_static
+	  fi
+	  prefer_static_libs=yes
+	  ;;
+	-static)
+	  if test -z "$pic_flag" && test -n "$link_static_flag"; then
+	    dlopen_self=$dlopen_self_static
+	  fi
+	  prefer_static_libs=built
+	  ;;
+	-static-libtool-libs)
+	  if test -z "$pic_flag" && test -n "$link_static_flag"; then
+	    dlopen_self=$dlopen_self_static
+	  fi
+	  prefer_static_libs=yes
+	  ;;
+	esac
+	build_libtool_libs=no
+	build_old_libs=yes
+	break
+	;;
+      esac
+    done
+
+    # See if our shared archives depend on static archives.
+    test -n "$old_archive_from_new_cmds" && build_old_libs=yes
+
+    # Go through the arguments, transforming them on the way.
+    while test "$#" -gt 0; do
+      arg="$1"
+      shift
+      func_quote_for_eval "$arg"
+      qarg=$func_quote_for_eval_unquoted_result
+      func_append libtool_args " $func_quote_for_eval_result"
+
+      # If the previous option needs an argument, assign it.
+      if test -n "$prev"; then
+	case $prev in
+	output)
+	  func_append compile_command " @OUTPUT@"
+	  func_append finalize_command " @OUTPUT@"
+	  ;;
+	esac
+
+	case $prev in
+	bindir)
+	  bindir="$arg"
+	  prev=
+	  continue
+	  ;;
+	dlfiles|dlprefiles)
+	  if test "$preload" = no; then
+	    # Add the symbol object into the linking commands.
+	    func_append compile_command " @SYMFILE@"
+	    func_append finalize_command " @SYMFILE@"
+	    preload=yes
+	  fi
+	  case $arg in
+	  *.la | *.lo) ;;  # We handle these cases below.
+	  force)
+	    if test "$dlself" = no; then
+	      dlself=needless
+	      export_dynamic=yes
+	    fi
+	    prev=
+	    continue
+	    ;;
+	  self)
+	    if test "$prev" = dlprefiles; then
+	      dlself=yes
+	    elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then
+	      dlself=yes
+	    else
+	      dlself=needless
+	      export_dynamic=yes
+	    fi
+	    prev=
+	    continue
+	    ;;
+	  *)
+	    if test "$prev" = dlfiles; then
+	      func_append dlfiles " $arg"
+	    else
+	      func_append dlprefiles " $arg"
+	    fi
+	    prev=
+	    continue
+	    ;;
+	  esac
+	  ;;
+	expsyms)
+	  export_symbols="$arg"
+	  test -f "$arg" \
+	    || func_fatal_error "symbol file \`$arg' does not exist"
+	  prev=
+	  continue
+	  ;;
+	expsyms_regex)
+	  export_symbols_regex="$arg"
+	  prev=
+	  continue
+	  ;;
+	framework)
+	  case $host in
+	    *-*-darwin*)
+	      case "$deplibs " in
+		*" $qarg.ltframework "*) ;;
+		*) func_append deplibs " $qarg.ltframework" # this is fixed later
+		   ;;
+	      esac
+	      ;;
+	  esac
+	  prev=
+	  continue
+	  ;;
+	inst_prefix)
+	  inst_prefix_dir="$arg"
+	  prev=
+	  continue
+	  ;;
+	objectlist)
+	  if test -f "$arg"; then
+	    save_arg=$arg
+	    moreargs=
+	    for fil in `cat "$save_arg"`
+	    do
+#	      func_append moreargs " $fil"
+	      arg=$fil
+	      # A libtool-controlled object.
+
+	      # Check to see that this really is a libtool object.
+	      if func_lalib_unsafe_p "$arg"; then
+		pic_object=
+		non_pic_object=
+
+		# Read the .lo file
+		func_source "$arg"
+
+		if test -z "$pic_object" ||
+		   test -z "$non_pic_object" ||
+		   test "$pic_object" = none &&
+		   test "$non_pic_object" = none; then
+		  func_fatal_error "cannot find name of object for \`$arg'"
+		fi
+
+		# Extract subdirectory from the argument.
+		func_dirname "$arg" "/" ""
+		xdir="$func_dirname_result"
+
+		if test "$pic_object" != none; then
+		  # Prepend the subdirectory the object is found in.
+		  pic_object="$xdir$pic_object"
+
+		  if test "$prev" = dlfiles; then
+		    if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
+		      func_append dlfiles " $pic_object"
+		      prev=
+		      continue
+		    else
+		      # If libtool objects are unsupported, then we need to preload.
+		      prev=dlprefiles
+		    fi
+		  fi
+
+		  # CHECK ME:  I think I busted this.  -Ossama
+		  if test "$prev" = dlprefiles; then
+		    # Preload the old-style object.
+		    func_append dlprefiles " $pic_object"
+		    prev=
+		  fi
+
+		  # A PIC object.
+		  func_append libobjs " $pic_object"
+		  arg="$pic_object"
+		fi
+
+		# Non-PIC object.
+		if test "$non_pic_object" != none; then
+		  # Prepend the subdirectory the object is found in.
+		  non_pic_object="$xdir$non_pic_object"
+
+		  # A standard non-PIC object
+		  func_append non_pic_objects " $non_pic_object"
+		  if test -z "$pic_object" || test "$pic_object" = none ; then
+		    arg="$non_pic_object"
+		  fi
+		else
+		  # If the PIC object exists, use it instead.
+		  # $xdir was prepended to $pic_object above.
+		  non_pic_object="$pic_object"
+		  func_append non_pic_objects " $non_pic_object"
+		fi
+	      else
+		# Only an error if not doing a dry-run.
+		if $opt_dry_run; then
+		  # Extract subdirectory from the argument.
+		  func_dirname "$arg" "/" ""
+		  xdir="$func_dirname_result"
+
+		  func_lo2o "$arg"
+		  pic_object=$xdir$objdir/$func_lo2o_result
+		  non_pic_object=$xdir$func_lo2o_result
+		  func_append libobjs " $pic_object"
+		  func_append non_pic_objects " $non_pic_object"
+	        else
+		  func_fatal_error "\`$arg' is not a valid libtool object"
+		fi
+	      fi
+	    done
+	  else
+	    func_fatal_error "link input file \`$arg' does not exist"
+	  fi
+	  arg=$save_arg
+	  prev=
+	  continue
+	  ;;
+	precious_regex)
+	  precious_files_regex="$arg"
+	  prev=
+	  continue
+	  ;;
+	release)
+	  release="-$arg"
+	  prev=
+	  continue
+	  ;;
+	rpath | xrpath)
+	  # We need an absolute path.
+	  case $arg in
+	  [\\/]* | [A-Za-z]:[\\/]*) ;;
+	  *)
+	    func_fatal_error "only absolute run-paths are allowed"
+	    ;;
+	  esac
+	  if test "$prev" = rpath; then
+	    case "$rpath " in
+	    *" $arg "*) ;;
+	    *) func_append rpath " $arg" ;;
+	    esac
+	  else
+	    case "$xrpath " in
+	    *" $arg "*) ;;
+	    *) func_append xrpath " $arg" ;;
+	    esac
+	  fi
+	  prev=
+	  continue
+	  ;;
+	shrext)
+	  shrext_cmds="$arg"
+	  prev=
+	  continue
+	  ;;
+	weak)
+	  func_append weak_libs " $arg"
+	  prev=
+	  continue
+	  ;;
+	xcclinker)
+	  func_append linker_flags " $qarg"
+	  func_append compiler_flags " $qarg"
+	  prev=
+	  func_append compile_command " $qarg"
+	  func_append finalize_command " $qarg"
+	  continue
+	  ;;
+	xcompiler)
+	  func_append compiler_flags " $qarg"
+	  prev=
+	  func_append compile_command " $qarg"
+	  func_append finalize_command " $qarg"
+	  continue
+	  ;;
+	xlinker)
+	  func_append linker_flags " $qarg"
+	  func_append compiler_flags " $wl$qarg"
+	  prev=
+	  func_append compile_command " $wl$qarg"
+	  func_append finalize_command " $wl$qarg"
+	  continue
+	  ;;
+	*)
+	  eval "$prev=\"\$arg\""
+	  prev=
+	  continue
+	  ;;
+	esac
+      fi # test -n "$prev"
+
+      prevarg="$arg"
+
+      case $arg in
+      -all-static)
+	if test -n "$link_static_flag"; then
+	  # See comment for -static flag below, for more details.
+	  func_append compile_command " $link_static_flag"
+	  func_append finalize_command " $link_static_flag"
+	fi
+	continue
+	;;
+
+      -allow-undefined)
+	# FIXME: remove this flag sometime in the future.
+	func_fatal_error "\`-allow-undefined' must not be used because it is the default"
+	;;
+
+      -avoid-version)
+	avoid_version=yes
+	continue
+	;;
+
+      -bindir)
+	prev=bindir
+	continue
+	;;
+
+      -dlopen)
+	prev=dlfiles
+	continue
+	;;
+
+      -dlpreopen)
+	prev=dlprefiles
+	continue
+	;;
+
+      -export-dynamic)
+	export_dynamic=yes
+	continue
+	;;
+
+      -export-symbols | -export-symbols-regex)
+	if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
+	  func_fatal_error "more than one -exported-symbols argument is not allowed"
+	fi
+	if test "X$arg" = "X-export-symbols"; then
+	  prev=expsyms
+	else
+	  prev=expsyms_regex
+	fi
+	continue
+	;;
+
+      -framework)
+	prev=framework
+	continue
+	;;
+
+      -inst-prefix-dir)
+	prev=inst_prefix
+	continue
+	;;
+
+      # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*
+      # so, if we see these flags be careful not to treat them like -L
+      -L[A-Z][A-Z]*:*)
+	case $with_gcc/$host in
+	no/*-*-irix* | /*-*-irix*)
+	  func_append compile_command " $arg"
+	  func_append finalize_command " $arg"
+	  ;;
+	esac
+	continue
+	;;
+
+      -L*)
+	func_stripname "-L" '' "$arg"
+	if test -z "$func_stripname_result"; then
+	  if test "$#" -gt 0; then
+	    func_fatal_error "require no space between \`-L' and \`$1'"
+	  else
+	    func_fatal_error "need path for \`-L' option"
+	  fi
+	fi
+	func_resolve_sysroot "$func_stripname_result"
+	dir=$func_resolve_sysroot_result
+	# We need an absolute path.
+	case $dir in
+	[\\/]* | [A-Za-z]:[\\/]*) ;;
+	*)
+	  absdir=`cd "$dir" && pwd`
+	  test -z "$absdir" && \
+	    func_fatal_error "cannot determine absolute directory name of \`$dir'"
+	  dir="$absdir"
+	  ;;
+	esac
+	case "$deplibs " in
+	*" -L$dir "* | *" $arg "*)
+	  # Will only happen for absolute or sysroot arguments
+	  ;;
+	*)
+	  # Preserve sysroot, but never include relative directories
+	  case $dir in
+	    [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;;
+	    *) func_append deplibs " -L$dir" ;;
+	  esac
+	  func_append lib_search_path " $dir"
+	  ;;
+	esac
+	case $host in
+	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+	  testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'`
+	  case :$dllsearchpath: in
+	  *":$dir:"*) ;;
+	  ::) dllsearchpath=$dir;;
+	  *) func_append dllsearchpath ":$dir";;
+	  esac
+	  case :$dllsearchpath: in
+	  *":$testbindir:"*) ;;
+	  ::) dllsearchpath=$testbindir;;
+	  *) func_append dllsearchpath ":$testbindir";;
+	  esac
+	  ;;
+	esac
+	continue
+	;;
+
+      -l*)
+	if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then
+	  case $host in
+	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)
+	    # These systems don't actually have a C or math library (as such)
+	    continue
+	    ;;
+	  *-*-os2*)
+	    # These systems don't actually have a C library (as such)
+	    test "X$arg" = "X-lc" && continue
+	    ;;
+	  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+	    # Do not include libc due to us having libc/libc_r.
+	    test "X$arg" = "X-lc" && continue
+	    ;;
+	  *-*-rhapsody* | *-*-darwin1.[012])
+	    # Rhapsody C and math libraries are in the System framework
+	    func_append deplibs " System.ltframework"
+	    continue
+	    ;;
+	  *-*-sco3.2v5* | *-*-sco5v6*)
+	    # Causes problems with __ctype
+	    test "X$arg" = "X-lc" && continue
+	    ;;
+	  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
+	    # Compiler inserts libc in the correct place for threads to work
+	    test "X$arg" = "X-lc" && continue
+	    ;;
+	  esac
+	elif test "X$arg" = "X-lc_r"; then
+	 case $host in
+	 *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+	   # Do not include libc_r directly, use -pthread flag.
+	   continue
+	   ;;
+	 esac
+	fi
+	func_append deplibs " $arg"
+	continue
+	;;
+
+      -module)
+	module=yes
+	continue
+	;;
+
+      # Tru64 UNIX uses -model [arg] to determine the layout of C++
+      # classes, name mangling, and exception handling.
+      # Darwin uses the -arch flag to determine output architecture.
+      -model|-arch|-isysroot|--sysroot)
+	func_append compiler_flags " $arg"
+	func_append compile_command " $arg"
+	func_append finalize_command " $arg"
+	prev=xcompiler
+	continue
+	;;
+
+      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \
+      |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)
+	func_append compiler_flags " $arg"
+	func_append compile_command " $arg"
+	func_append finalize_command " $arg"
+	case "$new_inherited_linker_flags " in
+	    *" $arg "*) ;;
+	    * ) func_append new_inherited_linker_flags " $arg" ;;
+	esac
+	continue
+	;;
+
+      -multi_module)
+	single_module="${wl}-multi_module"
+	continue
+	;;
+
+      -no-fast-install)
+	fast_install=no
+	continue
+	;;
+
+      -no-install)
+	case $host in
+	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)
+	  # The PATH hackery in wrapper scripts is required on Windows
+	  # and Darwin in order for the loader to find any dlls it needs.
+	  func_warning "\`-no-install' is ignored for $host"
+	  func_warning "assuming \`-no-fast-install' instead"
+	  fast_install=no
+	  ;;
+	*) no_install=yes ;;
+	esac
+	continue
+	;;
+
+      -no-undefined)
+	allow_undefined=no
+	continue
+	;;
+
+      -objectlist)
+	prev=objectlist
+	continue
+	;;
+
+      -o) prev=output ;;
+
+      -precious-files-regex)
+	prev=precious_regex
+	continue
+	;;
+
+      -release)
+	prev=release
+	continue
+	;;
+
+      -rpath)
+	prev=rpath
+	continue
+	;;
+
+      -R)
+	prev=xrpath
+	continue
+	;;
+
+      -R*)
+	func_stripname '-R' '' "$arg"
+	dir=$func_stripname_result
+	# We need an absolute path.
+	case $dir in
+	[\\/]* | [A-Za-z]:[\\/]*) ;;
+	=*)
+	  func_stripname '=' '' "$dir"
+	  dir=$lt_sysroot$func_stripname_result
+	  ;;
+	*)
+	  func_fatal_error "only absolute run-paths are allowed"
+	  ;;
+	esac
+	case "$xrpath " in
+	*" $dir "*) ;;
+	*) func_append xrpath " $dir" ;;
+	esac
+	continue
+	;;
+
+      -shared)
+	# The effects of -shared are defined in a previous loop.
+	continue
+	;;
+
+      -shrext)
+	prev=shrext
+	continue
+	;;
+
+      -static | -static-libtool-libs)
+	# The effects of -static are defined in a previous loop.
+	# We used to do the same as -all-static on platforms that
+	# didn't have a PIC flag, but the assumption that the effects
+	# would be equivalent was wrong.  It would break on at least
+	# Digital Unix and AIX.
+	continue
+	;;
+
+      -thread-safe)
+	thread_safe=yes
+	continue
+	;;
+
+      -version-info)
+	prev=vinfo
+	continue
+	;;
+
+      -version-number)
+	prev=vinfo
+	vinfo_number=yes
+	continue
+	;;
+
+      -weak)
+        prev=weak
+	continue
+	;;
+
+      -Wc,*)
+	func_stripname '-Wc,' '' "$arg"
+	args=$func_stripname_result
+	arg=
+	save_ifs="$IFS"; IFS=','
+	for flag in $args; do
+	  IFS="$save_ifs"
+          func_quote_for_eval "$flag"
+	  func_append arg " $func_quote_for_eval_result"
+	  func_append compiler_flags " $func_quote_for_eval_result"
+	done
+	IFS="$save_ifs"
+	func_stripname ' ' '' "$arg"
+	arg=$func_stripname_result
+	;;
+
+      -Wl,*)
+	func_stripname '-Wl,' '' "$arg"
+	args=$func_stripname_result
+	arg=
+	save_ifs="$IFS"; IFS=','
+	for flag in $args; do
+	  IFS="$save_ifs"
+          func_quote_for_eval "$flag"
+	  func_append arg " $wl$func_quote_for_eval_result"
+	  func_append compiler_flags " $wl$func_quote_for_eval_result"
+	  func_append linker_flags " $func_quote_for_eval_result"
+	done
+	IFS="$save_ifs"
+	func_stripname ' ' '' "$arg"
+	arg=$func_stripname_result
+	;;
+
+      -Xcompiler)
+	prev=xcompiler
+	continue
+	;;
+
+      -Xlinker)
+	prev=xlinker
+	continue
+	;;
+
+      -XCClinker)
+	prev=xcclinker
+	continue
+	;;
+
+      # -msg_* for osf cc
+      -msg_*)
+	func_quote_for_eval "$arg"
+	arg="$func_quote_for_eval_result"
+	;;
+
+      # Flags to be passed through unchanged, with rationale:
+      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler
+      # -r[0-9][0-9]*        specify processor for the SGI compiler
+      # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler
+      # +DA*, +DD*           enable 64-bit mode for the HP compiler
+      # -q*                  compiler args for the IBM compiler
+      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC
+      # -F/path              path to uninstalled frameworks, gcc on darwin
+      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC
+      # @file                GCC response files
+      # -tp=*                Portland pgcc target processor selection
+      # --sysroot=*          for sysroot support
+      # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization
+      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \
+      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \
+      -O*|-flto*|-fwhopr*|-fuse-linker-plugin)
+        func_quote_for_eval "$arg"
+	arg="$func_quote_for_eval_result"
+        func_append compile_command " $arg"
+        func_append finalize_command " $arg"
+        func_append compiler_flags " $arg"
+        continue
+        ;;
+
+      # Some other compiler flag.
+      -* | +*)
+        func_quote_for_eval "$arg"
+	arg="$func_quote_for_eval_result"
+	;;
+
+      *.$objext)
+	# A standard object.
+	func_append objs " $arg"
+	;;
+
+      *.lo)
+	# A libtool-controlled object.
+
+	# Check to see that this really is a libtool object.
+	if func_lalib_unsafe_p "$arg"; then
+	  pic_object=
+	  non_pic_object=
+
+	  # Read the .lo file
+	  func_source "$arg"
+
+	  if test -z "$pic_object" ||
+	     test -z "$non_pic_object" ||
+	     test "$pic_object" = none &&
+	     test "$non_pic_object" = none; then
+	    func_fatal_error "cannot find name of object for \`$arg'"
+	  fi
+
+	  # Extract subdirectory from the argument.
+	  func_dirname "$arg" "/" ""
+	  xdir="$func_dirname_result"
+
+	  if test "$pic_object" != none; then
+	    # Prepend the subdirectory the object is found in.
+	    pic_object="$xdir$pic_object"
+
+	    if test "$prev" = dlfiles; then
+	      if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
+		func_append dlfiles " $pic_object"
+		prev=
+		continue
+	      else
+		# If libtool objects are unsupported, then we need to preload.
+		prev=dlprefiles
+	      fi
+	    fi
+
+	    # CHECK ME:  I think I busted this.  -Ossama
+	    if test "$prev" = dlprefiles; then
+	      # Preload the old-style object.
+	      func_append dlprefiles " $pic_object"
+	      prev=
+	    fi
+
+	    # A PIC object.
+	    func_append libobjs " $pic_object"
+	    arg="$pic_object"
+	  fi
+
+	  # Non-PIC object.
+	  if test "$non_pic_object" != none; then
+	    # Prepend the subdirectory the object is found in.
+	    non_pic_object="$xdir$non_pic_object"
+
+	    # A standard non-PIC object
+	    func_append non_pic_objects " $non_pic_object"
+	    if test -z "$pic_object" || test "$pic_object" = none ; then
+	      arg="$non_pic_object"
+	    fi
+	  else
+	    # If the PIC object exists, use it instead.
+	    # $xdir was prepended to $pic_object above.
+	    non_pic_object="$pic_object"
+	    func_append non_pic_objects " $non_pic_object"
+	  fi
+	else
+	  # Only an error if not doing a dry-run.
+	  if $opt_dry_run; then
+	    # Extract subdirectory from the argument.
+	    func_dirname "$arg" "/" ""
+	    xdir="$func_dirname_result"
+
+	    func_lo2o "$arg"
+	    pic_object=$xdir$objdir/$func_lo2o_result
+	    non_pic_object=$xdir$func_lo2o_result
+	    func_append libobjs " $pic_object"
+	    func_append non_pic_objects " $non_pic_object"
+	  else
+	    func_fatal_error "\`$arg' is not a valid libtool object"
+	  fi
+	fi
+	;;
+
+      *.$libext)
+	# An archive.
+	func_append deplibs " $arg"
+	func_append old_deplibs " $arg"
+	continue
+	;;
+
+      *.la)
+	# A libtool-controlled library.
+
+	func_resolve_sysroot "$arg"
+	if test "$prev" = dlfiles; then
+	  # This library was specified with -dlopen.
+	  func_append dlfiles " $func_resolve_sysroot_result"
+	  prev=
+	elif test "$prev" = dlprefiles; then
+	  # The library was specified with -dlpreopen.
+	  func_append dlprefiles " $func_resolve_sysroot_result"
+	  prev=
+	else
+	  func_append deplibs " $func_resolve_sysroot_result"
+	fi
+	continue
+	;;
+
+      # Some other compiler argument.
+      *)
+	# Unknown arguments in both finalize_command and compile_command need
+	# to be aesthetically quoted because they are evaled later.
+	func_quote_for_eval "$arg"
+	arg="$func_quote_for_eval_result"
+	;;
+      esac # arg
+
+      # Now actually substitute the argument into the commands.
+      if test -n "$arg"; then
+	func_append compile_command " $arg"
+	func_append finalize_command " $arg"
+      fi
+    done # argument parsing loop
+
+    test -n "$prev" && \
+      func_fatal_help "the \`$prevarg' option requires an argument"
+
+    if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then
+      eval arg=\"$export_dynamic_flag_spec\"
+      func_append compile_command " $arg"
+      func_append finalize_command " $arg"
+    fi
+
+    oldlibs=
+    # calculate the name of the file, without its directory
+    func_basename "$output"
+    outputname="$func_basename_result"
+    libobjs_save="$libobjs"
+
+    if test -n "$shlibpath_var"; then
+      # get the directories listed in $shlibpath_var
+      eval shlib_search_path=\`\$ECHO \"\${$shlibpath_var}\" \| \$SED \'s/:/ /g\'\`
+    else
+      shlib_search_path=
+    fi
+    eval sys_lib_search_path=\"$sys_lib_search_path_spec\"
+    eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\"
+
+    func_dirname "$output" "/" ""
+    output_objdir="$func_dirname_result$objdir"
+    func_to_tool_file "$output_objdir/"
+    tool_output_objdir=$func_to_tool_file_result
+    # Create the object directory.
+    func_mkdir_p "$output_objdir"
+
+    # Determine the type of output
+    case $output in
+    "")
+      func_fatal_help "you must specify an output file"
+      ;;
+    *.$libext) linkmode=oldlib ;;
+    *.lo | *.$objext) linkmode=obj ;;
+    *.la) linkmode=lib ;;
+    *) linkmode=prog ;; # Anything else should be a program.
+    esac
+
+    specialdeplibs=
+
+    libs=
+    # Find all interdependent deplibs by searching for libraries
+    # that are linked more than once (e.g. -la -lb -la)
+    for deplib in $deplibs; do
+      if $opt_preserve_dup_deps ; then
+	case "$libs " in
+	*" $deplib "*) func_append specialdeplibs " $deplib" ;;
+	esac
+      fi
+      func_append libs " $deplib"
+    done
+
+    if test "$linkmode" = lib; then
+      libs="$predeps $libs $compiler_lib_search_path $postdeps"
+
+      # Compute libraries that are listed more than once in $predeps
+      # $postdeps and mark them as special (i.e., whose duplicates are
+      # not to be eliminated).
+      pre_post_deps=
+      if $opt_duplicate_compiler_generated_deps; then
+	for pre_post_dep in $predeps $postdeps; do
+	  case "$pre_post_deps " in
+	  *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;;
+	  esac
+	  func_append pre_post_deps " $pre_post_dep"
+	done
+      fi
+      pre_post_deps=
+    fi
+
+    deplibs=
+    newdependency_libs=
+    newlib_search_path=
+    need_relink=no # whether we're linking any uninstalled libtool libraries
+    notinst_deplibs= # not-installed libtool libraries
+    notinst_path= # paths that contain not-installed libtool libraries
+
+    case $linkmode in
+    lib)
+	passes="conv dlpreopen link"
+	for file in $dlfiles $dlprefiles; do
+	  case $file in
+	  *.la) ;;
+	  *)
+	    func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file"
+	    ;;
+	  esac
+	done
+	;;
+    prog)
+	compile_deplibs=
+	finalize_deplibs=
+	alldeplibs=no
+	newdlfiles=
+	newdlprefiles=
+	passes="conv scan dlopen dlpreopen link"
+	;;
+    *)  passes="conv"
+	;;
+    esac
+
+    for pass in $passes; do
+      # The preopen pass in lib mode reverses $deplibs; put it back here
+      # so that -L comes before libs that need it for instance...
+      if test "$linkmode,$pass" = "lib,link"; then
+	## FIXME: Find the place where the list is rebuilt in the wrong
+	##        order, and fix it there properly
+        tmp_deplibs=
+	for deplib in $deplibs; do
+	  tmp_deplibs="$deplib $tmp_deplibs"
+	done
+	deplibs="$tmp_deplibs"
+      fi
+
+      if test "$linkmode,$pass" = "lib,link" ||
+	 test "$linkmode,$pass" = "prog,scan"; then
+	libs="$deplibs"
+	deplibs=
+      fi
+      if test "$linkmode" = prog; then
+	case $pass in
+	dlopen) libs="$dlfiles" ;;
+	dlpreopen) libs="$dlprefiles" ;;
+	link) libs="$deplibs %DEPLIBS% $dependency_libs" ;;
+	esac
+      fi
+      if test "$linkmode,$pass" = "lib,dlpreopen"; then
+	# Collect and forward deplibs of preopened libtool libs
+	for lib in $dlprefiles; do
+	  # Ignore non-libtool-libs
+	  dependency_libs=
+	  func_resolve_sysroot "$lib"
+	  case $lib in
+	  *.la)	func_source "$func_resolve_sysroot_result" ;;
+	  esac
+
+	  # Collect preopened libtool deplibs, except any this library
+	  # has declared as weak libs
+	  for deplib in $dependency_libs; do
+	    func_basename "$deplib"
+            deplib_base=$func_basename_result
+	    case " $weak_libs " in
+	    *" $deplib_base "*) ;;
+	    *) func_append deplibs " $deplib" ;;
+	    esac
+	  done
+	done
+	libs="$dlprefiles"
+      fi
+      if test "$pass" = dlopen; then
+	# Collect dlpreopened libraries
+	save_deplibs="$deplibs"
+	deplibs=
+      fi
+
+      for deplib in $libs; do
+	lib=
+	found=no
+	case $deplib in
+	-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \
+        |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)
+	  if test "$linkmode,$pass" = "prog,link"; then
+	    compile_deplibs="$deplib $compile_deplibs"
+	    finalize_deplibs="$deplib $finalize_deplibs"
+	  else
+	    func_append compiler_flags " $deplib"
+	    if test "$linkmode" = lib ; then
+		case "$new_inherited_linker_flags " in
+		    *" $deplib "*) ;;
+		    * ) func_append new_inherited_linker_flags " $deplib" ;;
+		esac
+	    fi
+	  fi
+	  continue
+	  ;;
+	-l*)
+	  if test "$linkmode" != lib && test "$linkmode" != prog; then
+	    func_warning "\`-l' is ignored for archives/objects"
+	    continue
+	  fi
+	  func_stripname '-l' '' "$deplib"
+	  name=$func_stripname_result
+	  if test "$linkmode" = lib; then
+	    searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path"
+	  else
+	    searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path"
+	  fi
+	  for searchdir in $searchdirs; do
+	    for search_ext in .la $std_shrext .so .a; do
+	      # Search the libtool library
+	      lib="$searchdir/lib${name}${search_ext}"
+	      if test -f "$lib"; then
+		if test "$search_ext" = ".la"; then
+		  found=yes
+		else
+		  found=no
+		fi
+		break 2
+	      fi
+	    done
+	  done
+	  if test "$found" != yes; then
+	    # deplib doesn't seem to be a libtool library
+	    if test "$linkmode,$pass" = "prog,link"; then
+	      compile_deplibs="$deplib $compile_deplibs"
+	      finalize_deplibs="$deplib $finalize_deplibs"
+	    else
+	      deplibs="$deplib $deplibs"
+	      test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
+	    fi
+	    continue
+	  else # deplib is a libtool library
+	    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,
+	    # We need to do some special things here, and not later.
+	    if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+	      case " $predeps $postdeps " in
+	      *" $deplib "*)
+		if func_lalib_p "$lib"; then
+		  library_names=
+		  old_library=
+		  func_source "$lib"
+		  for l in $old_library $library_names; do
+		    ll="$l"
+		  done
+		  if test "X$ll" = "X$old_library" ; then # only static version available
+		    found=no
+		    func_dirname "$lib" "" "."
+		    ladir="$func_dirname_result"
+		    lib=$ladir/$old_library
+		    if test "$linkmode,$pass" = "prog,link"; then
+		      compile_deplibs="$deplib $compile_deplibs"
+		      finalize_deplibs="$deplib $finalize_deplibs"
+		    else
+		      deplibs="$deplib $deplibs"
+		      test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
+		    fi
+		    continue
+		  fi
+		fi
+		;;
+	      *) ;;
+	      esac
+	    fi
+	  fi
+	  ;; # -l
+	*.ltframework)
+	  if test "$linkmode,$pass" = "prog,link"; then
+	    compile_deplibs="$deplib $compile_deplibs"
+	    finalize_deplibs="$deplib $finalize_deplibs"
+	  else
+	    deplibs="$deplib $deplibs"
+	    if test "$linkmode" = lib ; then
+		case "$new_inherited_linker_flags " in
+		    *" $deplib "*) ;;
+		    * ) func_append new_inherited_linker_flags " $deplib" ;;
+		esac
+	    fi
+	  fi
+	  continue
+	  ;;
+	-L*)
+	  case $linkmode in
+	  lib)
+	    deplibs="$deplib $deplibs"
+	    test "$pass" = conv && continue
+	    newdependency_libs="$deplib $newdependency_libs"
+	    func_stripname '-L' '' "$deplib"
+	    func_resolve_sysroot "$func_stripname_result"
+	    func_append newlib_search_path " $func_resolve_sysroot_result"
+	    ;;
+	  prog)
+	    if test "$pass" = conv; then
+	      deplibs="$deplib $deplibs"
+	      continue
+	    fi
+	    if test "$pass" = scan; then
+	      deplibs="$deplib $deplibs"
+	    else
+	      compile_deplibs="$deplib $compile_deplibs"
+	      finalize_deplibs="$deplib $finalize_deplibs"
+	    fi
+	    func_stripname '-L' '' "$deplib"
+	    func_resolve_sysroot "$func_stripname_result"
+	    func_append newlib_search_path " $func_resolve_sysroot_result"
+	    ;;
+	  *)
+	    func_warning "\`-L' is ignored for archives/objects"
+	    ;;
+	  esac # linkmode
+	  continue
+	  ;; # -L
+	-R*)
+	  if test "$pass" = link; then
+	    func_stripname '-R' '' "$deplib"
+	    func_resolve_sysroot "$func_stripname_result"
+	    dir=$func_resolve_sysroot_result
+	    # Make sure the xrpath contains only unique directories.
+	    case "$xrpath " in
+	    *" $dir "*) ;;
+	    *) func_append xrpath " $dir" ;;
+	    esac
+	  fi
+	  deplibs="$deplib $deplibs"
+	  continue
+	  ;;
+	*.la)
+	  func_resolve_sysroot "$deplib"
+	  lib=$func_resolve_sysroot_result
+	  ;;
+	*.$libext)
+	  if test "$pass" = conv; then
+	    deplibs="$deplib $deplibs"
+	    continue
+	  fi
+	  case $linkmode in
+	  lib)
+	    # Linking convenience modules into shared libraries is allowed,
+	    # but linking other static libraries is non-portable.
+	    case " $dlpreconveniencelibs " in
+	    *" $deplib "*) ;;
+	    *)
+	      valid_a_lib=no
+	      case $deplibs_check_method in
+		match_pattern*)
+		  set dummy $deplibs_check_method; shift
+		  match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
+		  if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \
+		    | $EGREP "$match_pattern_regex" > /dev/null; then
+		    valid_a_lib=yes
+		  fi
+		;;
+		pass_all)
+		  valid_a_lib=yes
+		;;
+	      esac
+	      if test "$valid_a_lib" != yes; then
+		echo
+		$ECHO "*** Warning: Trying to link with static lib archive $deplib."
+		echo "*** I have the capability to make that library automatically link in when"
+		echo "*** you link to this library.  But I can only do this if you have a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because the file extensions .$libext of this argument makes me believe"
+		echo "*** that it is just a static archive that I should not use here."
+	      else
+		echo
+		$ECHO "*** Warning: Linking the shared library $output against the"
+		$ECHO "*** static library $deplib is not portable!"
+		deplibs="$deplib $deplibs"
+	      fi
+	      ;;
+	    esac
+	    continue
+	    ;;
+	  prog)
+	    if test "$pass" != link; then
+	      deplibs="$deplib $deplibs"
+	    else
+	      compile_deplibs="$deplib $compile_deplibs"
+	      finalize_deplibs="$deplib $finalize_deplibs"
+	    fi
+	    continue
+	    ;;
+	  esac # linkmode
+	  ;; # *.$libext
+	*.lo | *.$objext)
+	  if test "$pass" = conv; then
+	    deplibs="$deplib $deplibs"
+	  elif test "$linkmode" = prog; then
+	    if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then
+	      # If there is no dlopen support or we're linking statically,
+	      # we need to preload.
+	      func_append newdlprefiles " $deplib"
+	      compile_deplibs="$deplib $compile_deplibs"
+	      finalize_deplibs="$deplib $finalize_deplibs"
+	    else
+	      func_append newdlfiles " $deplib"
+	    fi
+	  fi
+	  continue
+	  ;;
+	%DEPLIBS%)
+	  alldeplibs=yes
+	  continue
+	  ;;
+	esac # case $deplib
+
+	if test "$found" = yes || test -f "$lib"; then :
+	else
+	  func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'"
+	fi
+
+	# Check to see that this really is a libtool archive.
+	func_lalib_unsafe_p "$lib" \
+	  || func_fatal_error "\`$lib' is not a valid libtool archive"
+
+	func_dirname "$lib" "" "."
+	ladir="$func_dirname_result"
+
+	dlname=
+	dlopen=
+	dlpreopen=
+	libdir=
+	library_names=
+	old_library=
+	inherited_linker_flags=
+	# If the library was installed with an old release of libtool,
+	# it will not redefine variables installed, or shouldnotlink
+	installed=yes
+	shouldnotlink=no
+	avoidtemprpath=
+
+
+	# Read the .la file
+	func_source "$lib"
+
+	# Convert "-framework foo" to "foo.ltframework"
+	if test -n "$inherited_linker_flags"; then
+	  tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'`
+	  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do
+	    case " $new_inherited_linker_flags " in
+	      *" $tmp_inherited_linker_flag "*) ;;
+	      *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";;
+	    esac
+	  done
+	fi
+	dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	if test "$linkmode,$pass" = "lib,link" ||
+	   test "$linkmode,$pass" = "prog,scan" ||
+	   { test "$linkmode" != prog && test "$linkmode" != lib; }; then
+	  test -n "$dlopen" && func_append dlfiles " $dlopen"
+	  test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen"
+	fi
+
+	if test "$pass" = conv; then
+	  # Only check for convenience libraries
+	  deplibs="$lib $deplibs"
+	  if test -z "$libdir"; then
+	    if test -z "$old_library"; then
+	      func_fatal_error "cannot find name of link library for \`$lib'"
+	    fi
+	    # It is a libtool convenience library, so add in its objects.
+	    func_append convenience " $ladir/$objdir/$old_library"
+	    func_append old_convenience " $ladir/$objdir/$old_library"
+	  elif test "$linkmode" != prog && test "$linkmode" != lib; then
+	    func_fatal_error "\`$lib' is not a convenience library"
+	  fi
+	  tmp_libs=
+	  for deplib in $dependency_libs; do
+	    deplibs="$deplib $deplibs"
+	    if $opt_preserve_dup_deps ; then
+	      case "$tmp_libs " in
+	      *" $deplib "*) func_append specialdeplibs " $deplib" ;;
+	      esac
+	    fi
+	    func_append tmp_libs " $deplib"
+	  done
+	  continue
+	fi # $pass = conv
+
+
+	# Get the name of the library we link against.
+	linklib=
+	if test -n "$old_library" &&
+	   { test "$prefer_static_libs" = yes ||
+	     test "$prefer_static_libs,$installed" = "built,no"; }; then
+	  linklib=$old_library
+	else
+	  for l in $old_library $library_names; do
+	    linklib="$l"
+	  done
+	fi
+	if test -z "$linklib"; then
+	  func_fatal_error "cannot find name of link library for \`$lib'"
+	fi
+
+	# This library was specified with -dlopen.
+	if test "$pass" = dlopen; then
+	  if test -z "$libdir"; then
+	    func_fatal_error "cannot -dlopen a convenience library: \`$lib'"
+	  fi
+	  if test -z "$dlname" ||
+	     test "$dlopen_support" != yes ||
+	     test "$build_libtool_libs" = no; then
+	    # If there is no dlname, no dlopen support or we're linking
+	    # statically, we need to preload.  We also need to preload any
+	    # dependent libraries so libltdl's deplib preloader doesn't
+	    # bomb out in the load deplibs phase.
+	    func_append dlprefiles " $lib $dependency_libs"
+	  else
+	    func_append newdlfiles " $lib"
+	  fi
+	  continue
+	fi # $pass = dlopen
+
+	# We need an absolute path.
+	case $ladir in
+	[\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;;
+	*)
+	  abs_ladir=`cd "$ladir" && pwd`
+	  if test -z "$abs_ladir"; then
+	    func_warning "cannot determine absolute directory name of \`$ladir'"
+	    func_warning "passing it literally to the linker, although it might fail"
+	    abs_ladir="$ladir"
+	  fi
+	  ;;
+	esac
+	func_basename "$lib"
+	laname="$func_basename_result"
+
+	# Find the relevant object directory and library name.
+	if test "X$installed" = Xyes; then
+	  if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+	    func_warning "library \`$lib' was moved."
+	    dir="$ladir"
+	    absdir="$abs_ladir"
+	    libdir="$abs_ladir"
+	  else
+	    dir="$lt_sysroot$libdir"
+	    absdir="$lt_sysroot$libdir"
+	  fi
+	  test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
+	else
+	  if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+	    dir="$ladir"
+	    absdir="$abs_ladir"
+	    # Remove this search path later
+	    func_append notinst_path " $abs_ladir"
+	  else
+	    dir="$ladir/$objdir"
+	    absdir="$abs_ladir/$objdir"
+	    # Remove this search path later
+	    func_append notinst_path " $abs_ladir"
+	  fi
+	fi # $installed = yes
+	func_stripname 'lib' '.la' "$laname"
+	name=$func_stripname_result
+
+	# This library was specified with -dlpreopen.
+	if test "$pass" = dlpreopen; then
+	  if test -z "$libdir" && test "$linkmode" = prog; then
+	    func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'"
+	  fi
+	  case "$host" in
+	    # special handling for platforms with PE-DLLs.
+	    *cygwin* | *mingw* | *cegcc* )
+	      # Linker will automatically link against shared library if both
+	      # static and shared are present.  Therefore, ensure we extract
+	      # symbols from the import library if a shared library is present
+	      # (otherwise, the dlopen module name will be incorrect).  We do
+	      # this by putting the import library name into $newdlprefiles.
+	      # We recover the dlopen module name by 'saving' the la file
+	      # name in a special purpose variable, and (later) extracting the
+	      # dlname from the la file.
+	      if test -n "$dlname"; then
+	        func_tr_sh "$dir/$linklib"
+	        eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname"
+	        func_append newdlprefiles " $dir/$linklib"
+	      else
+	        func_append newdlprefiles " $dir/$old_library"
+	        # Keep a list of preopened convenience libraries to check
+	        # that they are being used correctly in the link pass.
+	        test -z "$libdir" && \
+	          func_append dlpreconveniencelibs " $dir/$old_library"
+	      fi
+	    ;;
+	    * )
+	      # Prefer using a static library (so that no silly _DYNAMIC symbols
+	      # are required to link).
+	      if test -n "$old_library"; then
+	        func_append newdlprefiles " $dir/$old_library"
+	        # Keep a list of preopened convenience libraries to check
+	        # that they are being used correctly in the link pass.
+	        test -z "$libdir" && \
+	          func_append dlpreconveniencelibs " $dir/$old_library"
+	      # Otherwise, use the dlname, so that lt_dlopen finds it.
+	      elif test -n "$dlname"; then
+	        func_append newdlprefiles " $dir/$dlname"
+	      else
+	        func_append newdlprefiles " $dir/$linklib"
+	      fi
+	    ;;
+	  esac
+	fi # $pass = dlpreopen
+
+	if test -z "$libdir"; then
+	  # Link the convenience library
+	  if test "$linkmode" = lib; then
+	    deplibs="$dir/$old_library $deplibs"
+	  elif test "$linkmode,$pass" = "prog,link"; then
+	    compile_deplibs="$dir/$old_library $compile_deplibs"
+	    finalize_deplibs="$dir/$old_library $finalize_deplibs"
+	  else
+	    deplibs="$lib $deplibs" # used for prog,scan pass
+	  fi
+	  continue
+	fi
+
+
+	if test "$linkmode" = prog && test "$pass" != link; then
+	  func_append newlib_search_path " $ladir"
+	  deplibs="$lib $deplibs"
+
+	  linkalldeplibs=no
+	  if test "$link_all_deplibs" != no || test -z "$library_names" ||
+	     test "$build_libtool_libs" = no; then
+	    linkalldeplibs=yes
+	  fi
+
+	  tmp_libs=
+	  for deplib in $dependency_libs; do
+	    case $deplib in
+	    -L*) func_stripname '-L' '' "$deplib"
+	         func_resolve_sysroot "$func_stripname_result"
+	         func_append newlib_search_path " $func_resolve_sysroot_result"
+		 ;;
+	    esac
+	    # Need to link against all dependency_libs?
+	    if test "$linkalldeplibs" = yes; then
+	      deplibs="$deplib $deplibs"
+	    else
+	      # Need to hardcode shared library paths
+	      # or/and link against static libraries
+	      newdependency_libs="$deplib $newdependency_libs"
+	    fi
+	    if $opt_preserve_dup_deps ; then
+	      case "$tmp_libs " in
+	      *" $deplib "*) func_append specialdeplibs " $deplib" ;;
+	      esac
+	    fi
+	    func_append tmp_libs " $deplib"
+	  done # for deplib
+	  continue
+	fi # $linkmode = prog...
+
+	if test "$linkmode,$pass" = "prog,link"; then
+	  if test -n "$library_names" &&
+	     { { test "$prefer_static_libs" = no ||
+	         test "$prefer_static_libs,$installed" = "built,yes"; } ||
+	       test -z "$old_library"; }; then
+	    # We need to hardcode the library path
+	    if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then
+	      # Make sure the rpath contains only unique directories.
+	      case "$temp_rpath:" in
+	      *"$absdir:"*) ;;
+	      *) func_append temp_rpath "$absdir:" ;;
+	      esac
+	    fi
+
+	    # Hardcode the library path.
+	    # Skip directories that are in the system default run-time
+	    # search path.
+	    case " $sys_lib_dlsearch_path " in
+	    *" $absdir "*) ;;
+	    *)
+	      case "$compile_rpath " in
+	      *" $absdir "*) ;;
+	      *) func_append compile_rpath " $absdir" ;;
+	      esac
+	      ;;
+	    esac
+	    case " $sys_lib_dlsearch_path " in
+	    *" $libdir "*) ;;
+	    *)
+	      case "$finalize_rpath " in
+	      *" $libdir "*) ;;
+	      *) func_append finalize_rpath " $libdir" ;;
+	      esac
+	      ;;
+	    esac
+	  fi # $linkmode,$pass = prog,link...
+
+	  if test "$alldeplibs" = yes &&
+	     { test "$deplibs_check_method" = pass_all ||
+	       { test "$build_libtool_libs" = yes &&
+		 test -n "$library_names"; }; }; then
+	    # We only need to search for static libraries
+	    continue
+	  fi
+	fi
+
+	link_static=no # Whether the deplib will be linked statically
+	use_static_libs=$prefer_static_libs
+	if test "$use_static_libs" = built && test "$installed" = yes; then
+	  use_static_libs=no
+	fi
+	if test -n "$library_names" &&
+	   { test "$use_static_libs" = no || test -z "$old_library"; }; then
+	  case $host in
+	  *cygwin* | *mingw* | *cegcc*)
+	      # No point in relinking DLLs because paths are not encoded
+	      func_append notinst_deplibs " $lib"
+	      need_relink=no
+	    ;;
+	  *)
+	    if test "$installed" = no; then
+	      func_append notinst_deplibs " $lib"
+	      need_relink=yes
+	    fi
+	    ;;
+	  esac
+	  # This is a shared library
+
+	  # Warn about portability, can't link against -module's on some
+	  # systems (darwin).  Don't bleat about dlopened modules though!
+	  dlopenmodule=""
+	  for dlpremoduletest in $dlprefiles; do
+	    if test "X$dlpremoduletest" = "X$lib"; then
+	      dlopenmodule="$dlpremoduletest"
+	      break
+	    fi
+	  done
+	  if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then
+	    echo
+	    if test "$linkmode" = prog; then
+	      $ECHO "*** Warning: Linking the executable $output against the loadable module"
+	    else
+	      $ECHO "*** Warning: Linking the shared library $output against the loadable module"
+	    fi
+	    $ECHO "*** $linklib is not portable!"
+	  fi
+	  if test "$linkmode" = lib &&
+	     test "$hardcode_into_libs" = yes; then
+	    # Hardcode the library path.
+	    # Skip directories that are in the system default run-time
+	    # search path.
+	    case " $sys_lib_dlsearch_path " in
+	    *" $absdir "*) ;;
+	    *)
+	      case "$compile_rpath " in
+	      *" $absdir "*) ;;
+	      *) func_append compile_rpath " $absdir" ;;
+	      esac
+	      ;;
+	    esac
+	    case " $sys_lib_dlsearch_path " in
+	    *" $libdir "*) ;;
+	    *)
+	      case "$finalize_rpath " in
+	      *" $libdir "*) ;;
+	      *) func_append finalize_rpath " $libdir" ;;
+	      esac
+	      ;;
+	    esac
+	  fi
+
+	  if test -n "$old_archive_from_expsyms_cmds"; then
+	    # figure out the soname
+	    set dummy $library_names
+	    shift
+	    realname="$1"
+	    shift
+	    libname=`eval "\\$ECHO \"$libname_spec\""`
+	    # use dlname if we got it. it's perfectly good, no?
+	    if test -n "$dlname"; then
+	      soname="$dlname"
+	    elif test -n "$soname_spec"; then
+	      # bleh windows
+	      case $host in
+	      *cygwin* | mingw* | *cegcc*)
+	        func_arith $current - $age
+		major=$func_arith_result
+		versuffix="-$major"
+		;;
+	      esac
+	      eval soname=\"$soname_spec\"
+	    else
+	      soname="$realname"
+	    fi
+
+	    # Make a new name for the extract_expsyms_cmds to use
+	    soroot="$soname"
+	    func_basename "$soroot"
+	    soname="$func_basename_result"
+	    func_stripname 'lib' '.dll' "$soname"
+	    newlib=libimp-$func_stripname_result.a
+
+	    # If the library has no export list, then create one now
+	    if test -f "$output_objdir/$soname-def"; then :
+	    else
+	      func_verbose "extracting exported symbol list from \`$soname'"
+	      func_execute_cmds "$extract_expsyms_cmds" 'exit $?'
+	    fi
+
+	    # Create $newlib
+	    if test -f "$output_objdir/$newlib"; then :; else
+	      func_verbose "generating import library for \`$soname'"
+	      func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?'
+	    fi
+	    # make sure the library variables are pointing to the new library
+	    dir=$output_objdir
+	    linklib=$newlib
+	  fi # test -n "$old_archive_from_expsyms_cmds"
+
+	  if test "$linkmode" = prog || test "$opt_mode" != relink; then
+	    add_shlibpath=
+	    add_dir=
+	    add=
+	    lib_linked=yes
+	    case $hardcode_action in
+	    immediate | unsupported)
+	      if test "$hardcode_direct" = no; then
+		add="$dir/$linklib"
+		case $host in
+		  *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;;
+		  *-*-sysv4*uw2*) add_dir="-L$dir" ;;
+		  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \
+		    *-*-unixware7*) add_dir="-L$dir" ;;
+		  *-*-darwin* )
+		    # if the lib is a (non-dlopened) module then we can not
+		    # link against it, someone is ignoring the earlier warnings
+		    if /usr/bin/file -L $add 2> /dev/null |
+			 $GREP ": [^:]* bundle" >/dev/null ; then
+		      if test "X$dlopenmodule" != "X$lib"; then
+			$ECHO "*** Warning: lib $linklib is a module, not a shared library"
+			if test -z "$old_library" ; then
+			  echo
+			  echo "*** And there doesn't seem to be a static archive available"
+			  echo "*** The link will probably fail, sorry"
+			else
+			  add="$dir/$old_library"
+			fi
+		      elif test -n "$old_library"; then
+			add="$dir/$old_library"
+		      fi
+		    fi
+		esac
+	      elif test "$hardcode_minus_L" = no; then
+		case $host in
+		*-*-sunos*) add_shlibpath="$dir" ;;
+		esac
+		add_dir="-L$dir"
+		add="-l$name"
+	      elif test "$hardcode_shlibpath_var" = no; then
+		add_shlibpath="$dir"
+		add="-l$name"
+	      else
+		lib_linked=no
+	      fi
+	      ;;
+	    relink)
+	      if test "$hardcode_direct" = yes &&
+	         test "$hardcode_direct_absolute" = no; then
+		add="$dir/$linklib"
+	      elif test "$hardcode_minus_L" = yes; then
+		add_dir="-L$absdir"
+		# Try looking first in the location we're being installed to.
+		if test -n "$inst_prefix_dir"; then
+		  case $libdir in
+		    [\\/]*)
+		      func_append add_dir " -L$inst_prefix_dir$libdir"
+		      ;;
+		  esac
+		fi
+		add="-l$name"
+	      elif test "$hardcode_shlibpath_var" = yes; then
+		add_shlibpath="$dir"
+		add="-l$name"
+	      else
+		lib_linked=no
+	      fi
+	      ;;
+	    *) lib_linked=no ;;
+	    esac
+
+	    if test "$lib_linked" != yes; then
+	      func_fatal_configuration "unsupported hardcode properties"
+	    fi
+
+	    if test -n "$add_shlibpath"; then
+	      case :$compile_shlibpath: in
+	      *":$add_shlibpath:"*) ;;
+	      *) func_append compile_shlibpath "$add_shlibpath:" ;;
+	      esac
+	    fi
+	    if test "$linkmode" = prog; then
+	      test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs"
+	      test -n "$add" && compile_deplibs="$add $compile_deplibs"
+	    else
+	      test -n "$add_dir" && deplibs="$add_dir $deplibs"
+	      test -n "$add" && deplibs="$add $deplibs"
+	      if test "$hardcode_direct" != yes &&
+		 test "$hardcode_minus_L" != yes &&
+		 test "$hardcode_shlibpath_var" = yes; then
+		case :$finalize_shlibpath: in
+		*":$libdir:"*) ;;
+		*) func_append finalize_shlibpath "$libdir:" ;;
+		esac
+	      fi
+	    fi
+	  fi
+
+	  if test "$linkmode" = prog || test "$opt_mode" = relink; then
+	    add_shlibpath=
+	    add_dir=
+	    add=
+	    # Finalize command for both is simple: just hardcode it.
+	    if test "$hardcode_direct" = yes &&
+	       test "$hardcode_direct_absolute" = no; then
+	      add="$libdir/$linklib"
+	    elif test "$hardcode_minus_L" = yes; then
+	      add_dir="-L$libdir"
+	      add="-l$name"
+	    elif test "$hardcode_shlibpath_var" = yes; then
+	      case :$finalize_shlibpath: in
+	      *":$libdir:"*) ;;
+	      *) func_append finalize_shlibpath "$libdir:" ;;
+	      esac
+	      add="-l$name"
+	    elif test "$hardcode_automatic" = yes; then
+	      if test -n "$inst_prefix_dir" &&
+		 test -f "$inst_prefix_dir$libdir/$linklib" ; then
+		add="$inst_prefix_dir$libdir/$linklib"
+	      else
+		add="$libdir/$linklib"
+	      fi
+	    else
+	      # We cannot seem to hardcode it, guess we'll fake it.
+	      add_dir="-L$libdir"
+	      # Try looking first in the location we're being installed to.
+	      if test -n "$inst_prefix_dir"; then
+		case $libdir in
+		  [\\/]*)
+		    func_append add_dir " -L$inst_prefix_dir$libdir"
+		    ;;
+		esac
+	      fi
+	      add="-l$name"
+	    fi
+
+	    if test "$linkmode" = prog; then
+	      test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs"
+	      test -n "$add" && finalize_deplibs="$add $finalize_deplibs"
+	    else
+	      test -n "$add_dir" && deplibs="$add_dir $deplibs"
+	      test -n "$add" && deplibs="$add $deplibs"
+	    fi
+	  fi
+	elif test "$linkmode" = prog; then
+	  # Here we assume that one of hardcode_direct or hardcode_minus_L
+	  # is not unsupported.  This is valid on all known static and
+	  # shared platforms.
+	  if test "$hardcode_direct" != unsupported; then
+	    test -n "$old_library" && linklib="$old_library"
+	    compile_deplibs="$dir/$linklib $compile_deplibs"
+	    finalize_deplibs="$dir/$linklib $finalize_deplibs"
+	  else
+	    compile_deplibs="-l$name -L$dir $compile_deplibs"
+	    finalize_deplibs="-l$name -L$dir $finalize_deplibs"
+	  fi
+	elif test "$build_libtool_libs" = yes; then
+	  # Not a shared library
+	  if test "$deplibs_check_method" != pass_all; then
+	    # We're trying link a shared library against a static one
+	    # but the system doesn't support it.
+
+	    # Just print a warning and add the library to dependency_libs so
+	    # that the program can be linked against the static library.
+	    echo
+	    $ECHO "*** Warning: This system can not link to static lib archive $lib."
+	    echo "*** I have the capability to make that library automatically link in when"
+	    echo "*** you link to this library.  But I can only do this if you have a"
+	    echo "*** shared version of the library, which you do not appear to have."
+	    if test "$module" = yes; then
+	      echo "*** But as you try to build a module library, libtool will still create "
+	      echo "*** a static module, that should work as long as the dlopening application"
+	      echo "*** is linked with the -dlopen flag to resolve symbols at runtime."
+	      if test -z "$global_symbol_pipe"; then
+		echo
+		echo "*** However, this would only work if libtool was able to extract symbol"
+		echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+		echo "*** not find such a program.  So, this module is probably useless."
+		echo "*** \`nm' from GNU binutils and a full rebuild may help."
+	      fi
+	      if test "$build_old_libs" = no; then
+		build_libtool_libs=module
+		build_old_libs=yes
+	      else
+		build_libtool_libs=no
+	      fi
+	    fi
+	  else
+	    deplibs="$dir/$old_library $deplibs"
+	    link_static=yes
+	  fi
+	fi # link shared/static library?
+
+	if test "$linkmode" = lib; then
+	  if test -n "$dependency_libs" &&
+	     { test "$hardcode_into_libs" != yes ||
+	       test "$build_old_libs" = yes ||
+	       test "$link_static" = yes; }; then
+	    # Extract -R from dependency_libs
+	    temp_deplibs=
+	    for libdir in $dependency_libs; do
+	      case $libdir in
+	      -R*) func_stripname '-R' '' "$libdir"
+	           temp_xrpath=$func_stripname_result
+		   case " $xrpath " in
+		   *" $temp_xrpath "*) ;;
+		   *) func_append xrpath " $temp_xrpath";;
+		   esac;;
+	      *) func_append temp_deplibs " $libdir";;
+	      esac
+	    done
+	    dependency_libs="$temp_deplibs"
+	  fi
+
+	  func_append newlib_search_path " $absdir"
+	  # Link against this library
+	  test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs"
+	  # ... and its dependency_libs
+	  tmp_libs=
+	  for deplib in $dependency_libs; do
+	    newdependency_libs="$deplib $newdependency_libs"
+	    case $deplib in
+              -L*) func_stripname '-L' '' "$deplib"
+                   func_resolve_sysroot "$func_stripname_result";;
+              *) func_resolve_sysroot "$deplib" ;;
+            esac
+	    if $opt_preserve_dup_deps ; then
+	      case "$tmp_libs " in
+	      *" $func_resolve_sysroot_result "*)
+                func_append specialdeplibs " $func_resolve_sysroot_result" ;;
+	      esac
+	    fi
+	    func_append tmp_libs " $func_resolve_sysroot_result"
+	  done
+
+	  if test "$link_all_deplibs" != no; then
+	    # Add the search paths of all dependency libraries
+	    for deplib in $dependency_libs; do
+	      path=
+	      case $deplib in
+	      -L*) path="$deplib" ;;
+	      *.la)
+	        func_resolve_sysroot "$deplib"
+	        deplib=$func_resolve_sysroot_result
+	        func_dirname "$deplib" "" "."
+		dir=$func_dirname_result
+		# We need an absolute path.
+		case $dir in
+		[\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;;
+		*)
+		  absdir=`cd "$dir" && pwd`
+		  if test -z "$absdir"; then
+		    func_warning "cannot determine absolute directory name of \`$dir'"
+		    absdir="$dir"
+		  fi
+		  ;;
+		esac
+		if $GREP "^installed=no" $deplib > /dev/null; then
+		case $host in
+		*-*-darwin*)
+		  depdepl=
+		  eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib`
+		  if test -n "$deplibrary_names" ; then
+		    for tmp in $deplibrary_names ; do
+		      depdepl=$tmp
+		    done
+		    if test -f "$absdir/$objdir/$depdepl" ; then
+		      depdepl="$absdir/$objdir/$depdepl"
+		      darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`
+                      if test -z "$darwin_install_name"; then
+                          darwin_install_name=`${OTOOL64} -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`
+                      fi
+		      func_append compiler_flags " ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}"
+		      func_append linker_flags " -dylib_file ${darwin_install_name}:${depdepl}"
+		      path=
+		    fi
+		  fi
+		  ;;
+		*)
+		  path="-L$absdir/$objdir"
+		  ;;
+		esac
+		else
+		  eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
+		  test -z "$libdir" && \
+		    func_fatal_error "\`$deplib' is not a valid libtool archive"
+		  test "$absdir" != "$libdir" && \
+		    func_warning "\`$deplib' seems to be moved"
+
+		  path="-L$absdir"
+		fi
+		;;
+	      esac
+	      case " $deplibs " in
+	      *" $path "*) ;;
+	      *) deplibs="$path $deplibs" ;;
+	      esac
+	    done
+	  fi # link_all_deplibs != no
+	fi # linkmode = lib
+      done # for deplib in $libs
+      if test "$pass" = link; then
+	if test "$linkmode" = "prog"; then
+	  compile_deplibs="$new_inherited_linker_flags $compile_deplibs"
+	  finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs"
+	else
+	  compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	fi
+      fi
+      dependency_libs="$newdependency_libs"
+      if test "$pass" = dlpreopen; then
+	# Link the dlpreopened libraries before other libraries
+	for deplib in $save_deplibs; do
+	  deplibs="$deplib $deplibs"
+	done
+      fi
+      if test "$pass" != dlopen; then
+	if test "$pass" != conv; then
+	  # Make sure lib_search_path contains only unique directories.
+	  lib_search_path=
+	  for dir in $newlib_search_path; do
+	    case "$lib_search_path " in
+	    *" $dir "*) ;;
+	    *) func_append lib_search_path " $dir" ;;
+	    esac
+	  done
+	  newlib_search_path=
+	fi
+
+	if test "$linkmode,$pass" != "prog,link"; then
+	  vars="deplibs"
+	else
+	  vars="compile_deplibs finalize_deplibs"
+	fi
+	for var in $vars dependency_libs; do
+	  # Add libraries to $var in reverse order
+	  eval tmp_libs=\"\$$var\"
+	  new_libs=
+	  for deplib in $tmp_libs; do
+	    # FIXME: Pedantically, this is the right thing to do, so
+	    #        that some nasty dependency loop isn't accidentally
+	    #        broken:
+	    #new_libs="$deplib $new_libs"
+	    # Pragmatically, this seems to cause very few problems in
+	    # practice:
+	    case $deplib in
+	    -L*) new_libs="$deplib $new_libs" ;;
+	    -R*) ;;
+	    *)
+	      # And here is the reason: when a library appears more
+	      # than once as an explicit dependence of a library, or
+	      # is implicitly linked in more than once by the
+	      # compiler, it is considered special, and multiple
+	      # occurrences thereof are not removed.  Compare this
+	      # with having the same library being listed as a
+	      # dependency of multiple other libraries: in this case,
+	      # we know (pedantically, we assume) the library does not
+	      # need to be listed more than once, so we keep only the
+	      # last copy.  This is not always right, but it is rare
+	      # enough that we require users that really mean to play
+	      # such unportable linking tricks to link the library
+	      # using -Wl,-lname, so that libtool does not consider it
+	      # for duplicate removal.
+	      case " $specialdeplibs " in
+	      *" $deplib "*) new_libs="$deplib $new_libs" ;;
+	      *)
+		case " $new_libs " in
+		*" $deplib "*) ;;
+		*) new_libs="$deplib $new_libs" ;;
+		esac
+		;;
+	      esac
+	      ;;
+	    esac
+	  done
+	  tmp_libs=
+	  for deplib in $new_libs; do
+	    case $deplib in
+	    -L*)
+	      case " $tmp_libs " in
+	      *" $deplib "*) ;;
+	      *) func_append tmp_libs " $deplib" ;;
+	      esac
+	      ;;
+	    *) func_append tmp_libs " $deplib" ;;
+	    esac
+	  done
+	  eval $var=\"$tmp_libs\"
+	done # for var
+      fi
+      # Last step: remove runtime libs from dependency_libs
+      # (they stay in deplibs)
+      tmp_libs=
+      for i in $dependency_libs ; do
+	case " $predeps $postdeps $compiler_lib_search_path " in
+	*" $i "*)
+	  i=""
+	  ;;
+	esac
+	if test -n "$i" ; then
+	  func_append tmp_libs " $i"
+	fi
+      done
+      dependency_libs=$tmp_libs
+    done # for pass
+    if test "$linkmode" = prog; then
+      dlfiles="$newdlfiles"
+    fi
+    if test "$linkmode" = prog || test "$linkmode" = lib; then
+      dlprefiles="$newdlprefiles"
+    fi
+
+    case $linkmode in
+    oldlib)
+      if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+	func_warning "\`-dlopen' is ignored for archives"
+      fi
+
+      case " $deplibs" in
+      *\ -l* | *\ -L*)
+	func_warning "\`-l' and \`-L' are ignored for archives" ;;
+      esac
+
+      test -n "$rpath" && \
+	func_warning "\`-rpath' is ignored for archives"
+
+      test -n "$xrpath" && \
+	func_warning "\`-R' is ignored for archives"
+
+      test -n "$vinfo" && \
+	func_warning "\`-version-info/-version-number' is ignored for archives"
+
+      test -n "$release" && \
+	func_warning "\`-release' is ignored for archives"
+
+      test -n "$export_symbols$export_symbols_regex" && \
+	func_warning "\`-export-symbols' is ignored for archives"
+
+      # Now set the variables for building old libraries.
+      build_libtool_libs=no
+      oldlibs="$output"
+      func_append objs "$old_deplibs"
+      ;;
+
+    lib)
+      # Make sure we only generate libraries of the form `libNAME.la'.
+      case $outputname in
+      lib*)
+	func_stripname 'lib' '.la' "$outputname"
+	name=$func_stripname_result
+	eval shared_ext=\"$shrext_cmds\"
+	eval libname=\"$libname_spec\"
+	;;
+      *)
+	test "$module" = no && \
+	  func_fatal_help "libtool library \`$output' must begin with \`lib'"
+
+	if test "$need_lib_prefix" != no; then
+	  # Add the "lib" prefix for modules if required
+	  func_stripname '' '.la' "$outputname"
+	  name=$func_stripname_result
+	  eval shared_ext=\"$shrext_cmds\"
+	  eval libname=\"$libname_spec\"
+	else
+	  func_stripname '' '.la' "$outputname"
+	  libname=$func_stripname_result
+	fi
+	;;
+      esac
+
+      if test -n "$objs"; then
+	if test "$deplibs_check_method" != pass_all; then
+	  func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs"
+	else
+	  echo
+	  $ECHO "*** Warning: Linking the shared library $output against the non-libtool"
+	  $ECHO "*** objects $objs is not portable!"
+	  func_append libobjs " $objs"
+	fi
+      fi
+
+      test "$dlself" != no && \
+	func_warning "\`-dlopen self' is ignored for libtool libraries"
+
+      set dummy $rpath
+      shift
+      test "$#" -gt 1 && \
+	func_warning "ignoring multiple \`-rpath's for a libtool library"
+
+      install_libdir="$1"
+
+      oldlibs=
+      if test -z "$rpath"; then
+	if test "$build_libtool_libs" = yes; then
+	  # Building a libtool convenience library.
+	  # Some compilers have problems with a `.al' extension so
+	  # convenience libraries should have the same extension an
+	  # archive normally would.
+	  oldlibs="$output_objdir/$libname.$libext $oldlibs"
+	  build_libtool_libs=convenience
+	  build_old_libs=yes
+	fi
+
+	test -n "$vinfo" && \
+	  func_warning "\`-version-info/-version-number' is ignored for convenience libraries"
+
+	test -n "$release" && \
+	  func_warning "\`-release' is ignored for convenience libraries"
+      else
+
+	# Parse the version information argument.
+	save_ifs="$IFS"; IFS=':'
+	set dummy $vinfo 0 0 0
+	shift
+	IFS="$save_ifs"
+
+	test -n "$7" && \
+	  func_fatal_help "too many parameters to \`-version-info'"
+
+	# convert absolute version numbers to libtool ages
+	# this retains compatibility with .la files and attempts
+	# to make the code below a bit more comprehensible
+
+	case $vinfo_number in
+	yes)
+	  number_major="$1"
+	  number_minor="$2"
+	  number_revision="$3"
+	  #
+	  # There are really only two kinds -- those that
+	  # use the current revision as the major version
+	  # and those that subtract age and use age as
+	  # a minor version.  But, then there is irix
+	  # which has an extra 1 added just for fun
+	  #
+	  case $version_type in
+	  # correct linux to gnu/linux during the next big refactor
+	  darwin|linux|osf|windows|none)
+	    func_arith $number_major + $number_minor
+	    current=$func_arith_result
+	    age="$number_minor"
+	    revision="$number_revision"
+	    ;;
+	  freebsd-aout|freebsd-elf|qnx|sunos)
+	    current="$number_major"
+	    revision="$number_minor"
+	    age="0"
+	    ;;
+	  irix|nonstopux)
+	    func_arith $number_major + $number_minor
+	    current=$func_arith_result
+	    age="$number_minor"
+	    revision="$number_minor"
+	    lt_irix_increment=no
+	    ;;
+	  esac
+	  ;;
+	no)
+	  current="$1"
+	  revision="$2"
+	  age="$3"
+	  ;;
+	esac
+
+	# Check that each of the things are valid numbers.
+	case $current in
+	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+	*)
+	  func_error "CURRENT \`$current' must be a nonnegative integer"
+	  func_fatal_error "\`$vinfo' is not valid version information"
+	  ;;
+	esac
+
+	case $revision in
+	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+	*)
+	  func_error "REVISION \`$revision' must be a nonnegative integer"
+	  func_fatal_error "\`$vinfo' is not valid version information"
+	  ;;
+	esac
+
+	case $age in
+	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+	*)
+	  func_error "AGE \`$age' must be a nonnegative integer"
+	  func_fatal_error "\`$vinfo' is not valid version information"
+	  ;;
+	esac
+
+	if test "$age" -gt "$current"; then
+	  func_error "AGE \`$age' is greater than the current interface number \`$current'"
+	  func_fatal_error "\`$vinfo' is not valid version information"
+	fi
+
+	# Calculate the version variables.
+	major=
+	versuffix=
+	verstring=
+	case $version_type in
+	none) ;;
+
+	darwin)
+	  # Like Linux, but with the current version available in
+	  # verstring for coding it into the library header
+	  func_arith $current - $age
+	  major=.$func_arith_result
+	  versuffix="$major.$age.$revision"
+	  # Darwin ld doesn't like 0 for these options...
+	  func_arith $current + 1
+	  minor_current=$func_arith_result
+	  xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision"
+	  verstring="-compatibility_version $minor_current -current_version $minor_current.$revision"
+	  ;;
+
+	freebsd-aout)
+	  major=".$current"
+	  versuffix=".$current.$revision";
+	  ;;
+
+	freebsd-elf)
+	  major=".$current"
+	  versuffix=".$current"
+	  ;;
+
+	irix | nonstopux)
+	  if test "X$lt_irix_increment" = "Xno"; then
+	    func_arith $current - $age
+	  else
+	    func_arith $current - $age + 1
+	  fi
+	  major=$func_arith_result
+
+	  case $version_type in
+	    nonstopux) verstring_prefix=nonstopux ;;
+	    *)         verstring_prefix=sgi ;;
+	  esac
+	  verstring="$verstring_prefix$major.$revision"
+
+	  # Add in all the interfaces that we are compatible with.
+	  loop=$revision
+	  while test "$loop" -ne 0; do
+	    func_arith $revision - $loop
+	    iface=$func_arith_result
+	    func_arith $loop - 1
+	    loop=$func_arith_result
+	    verstring="$verstring_prefix$major.$iface:$verstring"
+	  done
+
+	  # Before this point, $major must not contain `.'.
+	  major=.$major
+	  versuffix="$major.$revision"
+	  ;;
+
+	linux) # correct to gnu/linux during the next big refactor
+	  func_arith $current - $age
+	  major=.$func_arith_result
+	  versuffix="$major.$age.$revision"
+	  ;;
+
+	osf)
+	  func_arith $current - $age
+	  major=.$func_arith_result
+	  versuffix=".$current.$age.$revision"
+	  verstring="$current.$age.$revision"
+
+	  # Add in all the interfaces that we are compatible with.
+	  loop=$age
+	  while test "$loop" -ne 0; do
+	    func_arith $current - $loop
+	    iface=$func_arith_result
+	    func_arith $loop - 1
+	    loop=$func_arith_result
+	    verstring="$verstring:${iface}.0"
+	  done
+
+	  # Make executables depend on our current version.
+	  func_append verstring ":${current}.0"
+	  ;;
+
+	qnx)
+	  major=".$current"
+	  versuffix=".$current"
+	  ;;
+
+	sunos)
+	  major=".$current"
+	  versuffix=".$current.$revision"
+	  ;;
+
+	windows)
+	  # Use '-' rather than '.', since we only want one
+	  # extension on DOS 8.3 filesystems.
+	  func_arith $current - $age
+	  major=$func_arith_result
+	  versuffix="-$major"
+	  ;;
+
+	*)
+	  func_fatal_configuration "unknown library version type \`$version_type'"
+	  ;;
+	esac
+
+	# Clear the version info if we defaulted, and they specified a release.
+	if test -z "$vinfo" && test -n "$release"; then
+	  major=
+	  case $version_type in
+	  darwin)
+	    # we can't check for "0.0" in archive_cmds due to quoting
+	    # problems, so we reset it completely
+	    verstring=
+	    ;;
+	  *)
+	    verstring="0.0"
+	    ;;
+	  esac
+	  if test "$need_version" = no; then
+	    versuffix=
+	  else
+	    versuffix=".0.0"
+	  fi
+	fi
+
+	# Remove version info from name if versioning should be avoided
+	if test "$avoid_version" = yes && test "$need_version" = no; then
+	  major=
+	  versuffix=
+	  verstring=""
+	fi
+
+	# Check to see if the archive will have undefined symbols.
+	if test "$allow_undefined" = yes; then
+	  if test "$allow_undefined_flag" = unsupported; then
+	    func_warning "undefined symbols not allowed in $host shared libraries"
+	    build_libtool_libs=no
+	    build_old_libs=yes
+	  fi
+	else
+	  # Don't allow undefined symbols.
+	  allow_undefined_flag="$no_undefined_flag"
+	fi
+
+      fi
+
+      func_generate_dlsyms "$libname" "$libname" "yes"
+      func_append libobjs " $symfileobj"
+      test "X$libobjs" = "X " && libobjs=
+
+      if test "$opt_mode" != relink; then
+	# Remove our outputs, but don't remove object files since they
+	# may have been created when compiling PIC objects.
+	removelist=
+	tempremovelist=`$ECHO "$output_objdir/*"`
+	for p in $tempremovelist; do
+	  case $p in
+	    *.$objext | *.gcno)
+	       ;;
+	    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*)
+	       if test "X$precious_files_regex" != "X"; then
+		 if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1
+		 then
+		   continue
+		 fi
+	       fi
+	       func_append removelist " $p"
+	       ;;
+	    *) ;;
+	  esac
+	done
+	test -n "$removelist" && \
+	  func_show_eval "${RM}r \$removelist"
+      fi
+
+      # Now set the variables for building old libraries.
+      if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then
+	func_append oldlibs " $output_objdir/$libname.$libext"
+
+	# Transform .lo files to .o files.
+	oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; $lo2o" | $NL2SP`
+      fi
+
+      # Eliminate all temporary directories.
+      #for path in $notinst_path; do
+      #	lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"`
+      #	deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"`
+      #	dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"`
+      #done
+
+      if test -n "$xrpath"; then
+	# If the user specified any rpath flags, then add them.
+	temp_xrpath=
+	for libdir in $xrpath; do
+	  func_replace_sysroot "$libdir"
+	  func_append temp_xrpath " -R$func_replace_sysroot_result"
+	  case "$finalize_rpath " in
+	  *" $libdir "*) ;;
+	  *) func_append finalize_rpath " $libdir" ;;
+	  esac
+	done
+	if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then
+	  dependency_libs="$temp_xrpath $dependency_libs"
+	fi
+      fi
+
+      # Make sure dlfiles contains only unique files that won't be dlpreopened
+      old_dlfiles="$dlfiles"
+      dlfiles=
+      for lib in $old_dlfiles; do
+	case " $dlprefiles $dlfiles " in
+	*" $lib "*) ;;
+	*) func_append dlfiles " $lib" ;;
+	esac
+      done
+
+      # Make sure dlprefiles contains only unique files
+      old_dlprefiles="$dlprefiles"
+      dlprefiles=
+      for lib in $old_dlprefiles; do
+	case "$dlprefiles " in
+	*" $lib "*) ;;
+	*) func_append dlprefiles " $lib" ;;
+	esac
+      done
+
+      if test "$build_libtool_libs" = yes; then
+	if test -n "$rpath"; then
+	  case $host in
+	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)
+	    # these systems don't actually have a c library (as such)!
+	    ;;
+	  *-*-rhapsody* | *-*-darwin1.[012])
+	    # Rhapsody C library is in the System framework
+	    func_append deplibs " System.ltframework"
+	    ;;
+	  *-*-netbsd*)
+	    # Don't link with libc until the a.out ld.so is fixed.
+	    ;;
+	  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+	    # Do not include libc due to us having libc/libc_r.
+	    ;;
+	  *-*-sco3.2v5* | *-*-sco5v6*)
+	    # Causes problems with __ctype
+	    ;;
+	  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
+	    # Compiler inserts libc in the correct place for threads to work
+	    ;;
+	  *)
+	    # Add libc to deplibs on all other systems if necessary.
+	    if test "$build_libtool_need_lc" = "yes"; then
+	      func_append deplibs " -lc"
+	    fi
+	    ;;
+	  esac
+	fi
+
+	# Transform deplibs into only deplibs that can be linked in shared.
+	name_save=$name
+	libname_save=$libname
+	release_save=$release
+	versuffix_save=$versuffix
+	major_save=$major
+	# I'm not sure if I'm treating the release correctly.  I think
+	# release should show up in the -l (ie -lgmp5) so we don't want to
+	# add it in twice.  Is that correct?
+	release=""
+	versuffix=""
+	major=""
+	newdeplibs=
+	droppeddeps=no
+	case $deplibs_check_method in
+	pass_all)
+	  # Don't check for shared/static.  Everything works.
+	  # This might be a little naive.  We might want to check
+	  # whether the library exists or not.  But this is on
+	  # osf3 & osf4 and I'm not really sure... Just
+	  # implementing what was already the behavior.
+	  newdeplibs=$deplibs
+	  ;;
+	test_compile)
+	  # This code stresses the "libraries are programs" paradigm to its
+	  # limits. Maybe even breaks it.  We compile a program, linking it
+	  # against the deplibs as a proxy for the library.  Then we can check
+	  # whether they linked in statically or dynamically with ldd.
+	  $opt_dry_run || $RM conftest.c
+	  cat > conftest.c <<EOF
+	  int main() { return 0; }
+EOF
+	  $opt_dry_run || $RM conftest
+	  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then
+	    ldd_output=`ldd conftest`
+	    for i in $deplibs; do
+	      case $i in
+	      -l*)
+		func_stripname -l '' "$i"
+		name=$func_stripname_result
+		if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+		  case " $predeps $postdeps " in
+		  *" $i "*)
+		    func_append newdeplibs " $i"
+		    i=""
+		    ;;
+		  esac
+		fi
+		if test -n "$i" ; then
+		  libname=`eval "\\$ECHO \"$libname_spec\""`
+		  deplib_matches=`eval "\\$ECHO \"$library_names_spec\""`
+		  set dummy $deplib_matches; shift
+		  deplib_match=$1
+		  if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
+		    func_append newdeplibs " $i"
+		  else
+		    droppeddeps=yes
+		    echo
+		    $ECHO "*** Warning: dynamic linker does not accept needed library $i."
+		    echo "*** I have the capability to make that library automatically link in when"
+		    echo "*** you link to this library.  But I can only do this if you have a"
+		    echo "*** shared version of the library, which I believe you do not have"
+		    echo "*** because a test_compile did reveal that the linker did not use it for"
+		    echo "*** its dynamic dependency list that programs get resolved with at runtime."
+		  fi
+		fi
+		;;
+	      *)
+		func_append newdeplibs " $i"
+		;;
+	      esac
+	    done
+	  else
+	    # Error occurred in the first compile.  Let's try to salvage
+	    # the situation: Compile a separate program for each library.
+	    for i in $deplibs; do
+	      case $i in
+	      -l*)
+		func_stripname -l '' "$i"
+		name=$func_stripname_result
+		$opt_dry_run || $RM conftest
+		if $LTCC $LTCFLAGS -o conftest conftest.c $i; then
+		  ldd_output=`ldd conftest`
+		  if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+		    case " $predeps $postdeps " in
+		    *" $i "*)
+		      func_append newdeplibs " $i"
+		      i=""
+		      ;;
+		    esac
+		  fi
+		  if test -n "$i" ; then
+		    libname=`eval "\\$ECHO \"$libname_spec\""`
+		    deplib_matches=`eval "\\$ECHO \"$library_names_spec\""`
+		    set dummy $deplib_matches; shift
+		    deplib_match=$1
+		    if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
+		      func_append newdeplibs " $i"
+		    else
+		      droppeddeps=yes
+		      echo
+		      $ECHO "*** Warning: dynamic linker does not accept needed library $i."
+		      echo "*** I have the capability to make that library automatically link in when"
+		      echo "*** you link to this library.  But I can only do this if you have a"
+		      echo "*** shared version of the library, which you do not appear to have"
+		      echo "*** because a test_compile did reveal that the linker did not use this one"
+		      echo "*** as a dynamic dependency that programs can get resolved with at runtime."
+		    fi
+		  fi
+		else
+		  droppeddeps=yes
+		  echo
+		  $ECHO "*** Warning!  Library $i is needed by this library but I was not able to"
+		  echo "*** make it link in!  You will probably need to install it or some"
+		  echo "*** library that it depends on before this library will be fully"
+		  echo "*** functional.  Installing it before continuing would be even better."
+		fi
+		;;
+	      *)
+		func_append newdeplibs " $i"
+		;;
+	      esac
+	    done
+	  fi
+	  ;;
+	file_magic*)
+	  set dummy $deplibs_check_method; shift
+	  file_magic_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
+	  for a_deplib in $deplibs; do
+	    case $a_deplib in
+	    -l*)
+	      func_stripname -l '' "$a_deplib"
+	      name=$func_stripname_result
+	      if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+		case " $predeps $postdeps " in
+		*" $a_deplib "*)
+		  func_append newdeplibs " $a_deplib"
+		  a_deplib=""
+		  ;;
+		esac
+	      fi
+	      if test -n "$a_deplib" ; then
+		libname=`eval "\\$ECHO \"$libname_spec\""`
+		if test -n "$file_magic_glob"; then
+		  libnameglob=`func_echo_all "$libname" | $SED -e $file_magic_glob`
+		else
+		  libnameglob=$libname
+		fi
+		test "$want_nocaseglob" = yes && nocaseglob=`shopt -p nocaseglob`
+		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
+		  if test "$want_nocaseglob" = yes; then
+		    shopt -s nocaseglob
+		    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`
+		    $nocaseglob
+		  else
+		    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`
+		  fi
+		  for potent_lib in $potential_libs; do
+		      # Follow soft links.
+		      if ls -lLd "$potent_lib" 2>/dev/null |
+			 $GREP " -> " >/dev/null; then
+			continue
+		      fi
+		      # The statement above tries to avoid entering an
+		      # endless loop below, in case of cyclic links.
+		      # We might still enter an endless loop, since a link
+		      # loop can be closed while we follow links,
+		      # but so what?
+		      potlib="$potent_lib"
+		      while test -h "$potlib" 2>/dev/null; do
+			potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'`
+			case $potliblink in
+			[\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";;
+			*) potlib=`$ECHO "$potlib" | $SED 's,[^/]*$,,'`"$potliblink";;
+			esac
+		      done
+		      if eval $file_magic_cmd \"\$potlib\" 2>/dev/null |
+			 $SED -e 10q |
+			 $EGREP "$file_magic_regex" > /dev/null; then
+			func_append newdeplibs " $a_deplib"
+			a_deplib=""
+			break 2
+		      fi
+		  done
+		done
+	      fi
+	      if test -n "$a_deplib" ; then
+		droppeddeps=yes
+		echo
+		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
+		echo "*** I have the capability to make that library automatically link in when"
+		echo "*** you link to this library.  But I can only do this if you have a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because I did check the linker path looking for a file starting"
+		if test -z "$potlib" ; then
+		  $ECHO "*** with $libname but no candidates were found. (...for file magic test)"
+		else
+		  $ECHO "*** with $libname and none of the candidates passed a file format test"
+		  $ECHO "*** using a file magic. Last file checked: $potlib"
+		fi
+	      fi
+	      ;;
+	    *)
+	      # Add a -L argument.
+	      func_append newdeplibs " $a_deplib"
+	      ;;
+	    esac
+	  done # Gone through all deplibs.
+	  ;;
+	match_pattern*)
+	  set dummy $deplibs_check_method; shift
+	  match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
+	  for a_deplib in $deplibs; do
+	    case $a_deplib in
+	    -l*)
+	      func_stripname -l '' "$a_deplib"
+	      name=$func_stripname_result
+	      if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+		case " $predeps $postdeps " in
+		*" $a_deplib "*)
+		  func_append newdeplibs " $a_deplib"
+		  a_deplib=""
+		  ;;
+		esac
+	      fi
+	      if test -n "$a_deplib" ; then
+		libname=`eval "\\$ECHO \"$libname_spec\""`
+		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
+		  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
+		  for potent_lib in $potential_libs; do
+		    potlib="$potent_lib" # see symlink-check above in file_magic test
+		    if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \
+		       $EGREP "$match_pattern_regex" > /dev/null; then
+		      func_append newdeplibs " $a_deplib"
+		      a_deplib=""
+		      break 2
+		    fi
+		  done
+		done
+	      fi
+	      if test -n "$a_deplib" ; then
+		droppeddeps=yes
+		echo
+		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
+		echo "*** I have the capability to make that library automatically link in when"
+		echo "*** you link to this library.  But I can only do this if you have a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because I did check the linker path looking for a file starting"
+		if test -z "$potlib" ; then
+		  $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)"
+		else
+		  $ECHO "*** with $libname and none of the candidates passed a file format test"
+		  $ECHO "*** using a regex pattern. Last file checked: $potlib"
+		fi
+	      fi
+	      ;;
+	    *)
+	      # Add a -L argument.
+	      func_append newdeplibs " $a_deplib"
+	      ;;
+	    esac
+	  done # Gone through all deplibs.
+	  ;;
+	none | unknown | *)
+	  newdeplibs=""
+	  tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`
+	  if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+	    for i in $predeps $postdeps ; do
+	      # can't use Xsed below, because $i might contain '/'
+	      tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s,$i,,"`
+	    done
+	  fi
+	  case $tmp_deplibs in
+	  *[!\	\ ]*)
+	    echo
+	    if test "X$deplibs_check_method" = "Xnone"; then
+	      echo "*** Warning: inter-library dependencies are not supported in this platform."
+	    else
+	      echo "*** Warning: inter-library dependencies are not known to be supported."
+	    fi
+	    echo "*** All declared inter-library dependencies are being dropped."
+	    droppeddeps=yes
+	    ;;
+	  esac
+	  ;;
+	esac
+	versuffix=$versuffix_save
+	major=$major_save
+	release=$release_save
+	libname=$libname_save
+	name=$name_save
+
+	case $host in
+	*-*-rhapsody* | *-*-darwin1.[012])
+	  # On Rhapsody replace the C library with the System framework
+	  newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'`
+	  ;;
+	esac
+
+	if test "$droppeddeps" = yes; then
+	  if test "$module" = yes; then
+	    echo
+	    echo "*** Warning: libtool could not satisfy all declared inter-library"
+	    $ECHO "*** dependencies of module $libname.  Therefore, libtool will create"
+	    echo "*** a static module, that should work as long as the dlopening"
+	    echo "*** application is linked with the -dlopen flag."
+	    if test -z "$global_symbol_pipe"; then
+	      echo
+	      echo "*** However, this would only work if libtool was able to extract symbol"
+	      echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+	      echo "*** not find such a program.  So, this module is probably useless."
+	      echo "*** \`nm' from GNU binutils and a full rebuild may help."
+	    fi
+	    if test "$build_old_libs" = no; then
+	      oldlibs="$output_objdir/$libname.$libext"
+	      build_libtool_libs=module
+	      build_old_libs=yes
+	    else
+	      build_libtool_libs=no
+	    fi
+	  else
+	    echo "*** The inter-library dependencies that have been dropped here will be"
+	    echo "*** automatically added whenever a program is linked with this library"
+	    echo "*** or is declared to -dlopen it."
+
+	    if test "$allow_undefined" = no; then
+	      echo
+	      echo "*** Since this library must not contain undefined symbols,"
+	      echo "*** because either the platform does not support them or"
+	      echo "*** it was explicitly requested with -no-undefined,"
+	      echo "*** libtool will only create a static version of it."
+	      if test "$build_old_libs" = no; then
+		oldlibs="$output_objdir/$libname.$libext"
+		build_libtool_libs=module
+		build_old_libs=yes
+	      else
+		build_libtool_libs=no
+	      fi
+	    fi
+	  fi
+	fi
+	# Done checking deplibs!
+	deplibs=$newdeplibs
+      fi
+      # Time to change all our "foo.ltframework" stuff back to "-framework foo"
+      case $host in
+	*-*-darwin*)
+	  newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  ;;
+      esac
+
+      # move library search paths that coincide with paths to not yet
+      # installed libraries to the beginning of the library search list
+      new_libs=
+      for path in $notinst_path; do
+	case " $new_libs " in
+	*" -L$path/$objdir "*) ;;
+	*)
+	  case " $deplibs " in
+	  *" -L$path/$objdir "*)
+	    func_append new_libs " -L$path/$objdir" ;;
+	  esac
+	  ;;
+	esac
+      done
+      for deplib in $deplibs; do
+	case $deplib in
+	-L*)
+	  case " $new_libs " in
+	  *" $deplib "*) ;;
+	  *) func_append new_libs " $deplib" ;;
+	  esac
+	  ;;
+	*) func_append new_libs " $deplib" ;;
+	esac
+      done
+      deplibs="$new_libs"
+
+      # All the library-specific variables (install_libdir is set above).
+      library_names=
+      old_library=
+      dlname=
+
+      # Test again, we may have decided not to build it any more
+      if test "$build_libtool_libs" = yes; then
+	# Remove ${wl} instances when linking with ld.
+	# FIXME: should test the right _cmds variable.
+	case $archive_cmds in
+	  *\$LD\ *) wl= ;;
+        esac
+	if test "$hardcode_into_libs" = yes; then
+	  # Hardcode the library paths
+	  hardcode_libdirs=
+	  dep_rpath=
+	  rpath="$finalize_rpath"
+	  test "$opt_mode" != relink && rpath="$compile_rpath$rpath"
+	  for libdir in $rpath; do
+	    if test -n "$hardcode_libdir_flag_spec"; then
+	      if test -n "$hardcode_libdir_separator"; then
+		func_replace_sysroot "$libdir"
+		libdir=$func_replace_sysroot_result
+		if test -z "$hardcode_libdirs"; then
+		  hardcode_libdirs="$libdir"
+		else
+		  # Just accumulate the unique libdirs.
+		  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+		  *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+		    ;;
+		  *)
+		    func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
+		    ;;
+		  esac
+		fi
+	      else
+		eval flag=\"$hardcode_libdir_flag_spec\"
+		func_append dep_rpath " $flag"
+	      fi
+	    elif test -n "$runpath_var"; then
+	      case "$perm_rpath " in
+	      *" $libdir "*) ;;
+	      *) func_append perm_rpath " $libdir" ;;
+	      esac
+	    fi
+	  done
+	  # Substitute the hardcoded libdirs into the rpath.
+	  if test -n "$hardcode_libdir_separator" &&
+	     test -n "$hardcode_libdirs"; then
+	    libdir="$hardcode_libdirs"
+	    eval "dep_rpath=\"$hardcode_libdir_flag_spec\""
+	  fi
+	  if test -n "$runpath_var" && test -n "$perm_rpath"; then
+	    # We should set the runpath_var.
+	    rpath=
+	    for dir in $perm_rpath; do
+	      func_append rpath "$dir:"
+	    done
+	    eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var"
+	  fi
+	  test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs"
+	fi
+
+	shlibpath="$finalize_shlibpath"
+	test "$opt_mode" != relink && shlibpath="$compile_shlibpath$shlibpath"
+	if test -n "$shlibpath"; then
+	  eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var"
+	fi
+
+	# Get the real and link names of the library.
+	eval shared_ext=\"$shrext_cmds\"
+	eval library_names=\"$library_names_spec\"
+	set dummy $library_names
+	shift
+	realname="$1"
+	shift
+
+	if test -n "$soname_spec"; then
+	  eval soname=\"$soname_spec\"
+	else
+	  soname="$realname"
+	fi
+	if test -z "$dlname"; then
+	  dlname=$soname
+	fi
+
+	lib="$output_objdir/$realname"
+	linknames=
+	for link
+	do
+	  func_append linknames " $link"
+	done
+
+	# Use standard objects if they are pic
+	test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP`
+	test "X$libobjs" = "X " && libobjs=
+
+	delfiles=
+	if test -n "$export_symbols" && test -n "$include_expsyms"; then
+	  $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp"
+	  export_symbols="$output_objdir/$libname.uexp"
+	  func_append delfiles " $export_symbols"
+	fi
+
+	orig_export_symbols=
+	case $host_os in
+	cygwin* | mingw* | cegcc*)
+	  if test -n "$export_symbols" && test -z "$export_symbols_regex"; then
+	    # exporting using user supplied symfile
+	    if test "x`$SED 1q $export_symbols`" != xEXPORTS; then
+	      # and it's NOT already a .def file. Must figure out
+	      # which of the given symbols are data symbols and tag
+	      # them as such. So, trigger use of export_symbols_cmds.
+	      # export_symbols gets reassigned inside the "prepare
+	      # the list of exported symbols" if statement, so the
+	      # include_expsyms logic still works.
+	      orig_export_symbols="$export_symbols"
+	      export_symbols=
+	      always_export_symbols=yes
+	    fi
+	  fi
+	  ;;
+	esac
+
+	# Prepare the list of exported symbols
+	if test -z "$export_symbols"; then
+	  if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then
+	    func_verbose "generating symbol list for \`$libname.la'"
+	    export_symbols="$output_objdir/$libname.exp"
+	    $opt_dry_run || $RM $export_symbols
+	    cmds=$export_symbols_cmds
+	    save_ifs="$IFS"; IFS='~'
+	    for cmd1 in $cmds; do
+	      IFS="$save_ifs"
+	      # Take the normal branch if the nm_file_list_spec branch
+	      # doesn't work or if tool conversion is not needed.
+	      case $nm_file_list_spec~$to_tool_file_cmd in
+		*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)
+		  try_normal_branch=yes
+		  eval cmd=\"$cmd1\"
+		  func_len " $cmd"
+		  len=$func_len_result
+		  ;;
+		*)
+		  try_normal_branch=no
+		  ;;
+	      esac
+	      if test "$try_normal_branch" = yes \
+		 && { test "$len" -lt "$max_cmd_len" \
+		      || test "$max_cmd_len" -le -1; }
+	      then
+		func_show_eval "$cmd" 'exit $?'
+		skipped_export=false
+	      elif test -n "$nm_file_list_spec"; then
+		func_basename "$output"
+		output_la=$func_basename_result
+		save_libobjs=$libobjs
+		save_output=$output
+		output=${output_objdir}/${output_la}.nm
+		func_to_tool_file "$output"
+		libobjs=$nm_file_list_spec$func_to_tool_file_result
+		func_append delfiles " $output"
+		func_verbose "creating $NM input file list: $output"
+		for obj in $save_libobjs; do
+		  func_to_tool_file "$obj"
+		  $ECHO "$func_to_tool_file_result"
+		done > "$output"
+		eval cmd=\"$cmd1\"
+		func_show_eval "$cmd" 'exit $?'
+		output=$save_output
+		libobjs=$save_libobjs
+		skipped_export=false
+	      else
+		# The command line is too long to execute in one step.
+		func_verbose "using reloadable object file for export list..."
+		skipped_export=:
+		# Break out early, otherwise skipped_export may be
+		# set to false by a later but shorter cmd.
+		break
+	      fi
+	    done
+	    IFS="$save_ifs"
+	    if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then
+	      func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
+	      func_show_eval '$MV "${export_symbols}T" "$export_symbols"'
+	    fi
+	  fi
+	fi
+
+	if test -n "$export_symbols" && test -n "$include_expsyms"; then
+	  tmp_export_symbols="$export_symbols"
+	  test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
+	  $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"'
+	fi
+
+	if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then
+	  # The given exports_symbols file has to be filtered, so filter it.
+	  func_verbose "filter symbol list for \`$libname.la' to tag DATA exports"
+	  # FIXME: $output_objdir/$libname.filter potentially contains lots of
+	  # 's' commands which not all seds can handle. GNU sed should be fine
+	  # though. Also, the filter scales superlinearly with the number of
+	  # global variables. join(1) would be nice here, but unfortunately
+	  # isn't a blessed tool.
+	  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter
+	  func_append delfiles " $export_symbols $output_objdir/$libname.filter"
+	  export_symbols=$output_objdir/$libname.def
+	  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols
+	fi
+
+	tmp_deplibs=
+	for test_deplib in $deplibs; do
+	  case " $convenience " in
+	  *" $test_deplib "*) ;;
+	  *)
+	    func_append tmp_deplibs " $test_deplib"
+	    ;;
+	  esac
+	done
+	deplibs="$tmp_deplibs"
+
+	if test -n "$convenience"; then
+	  if test -n "$whole_archive_flag_spec" &&
+	    test "$compiler_needs_object" = yes &&
+	    test -z "$libobjs"; then
+	    # extract the archives, so we have objects to list.
+	    # TODO: could optimize this to just extract one archive.
+	    whole_archive_flag_spec=
+	  fi
+	  if test -n "$whole_archive_flag_spec"; then
+	    save_libobjs=$libobjs
+	    eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
+	    test "X$libobjs" = "X " && libobjs=
+	  else
+	    gentop="$output_objdir/${outputname}x"
+	    func_append generated " $gentop"
+
+	    func_extract_archives $gentop $convenience
+	    func_append libobjs " $func_extract_archives_result"
+	    test "X$libobjs" = "X " && libobjs=
+	  fi
+	fi
+
+	if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then
+	  eval flag=\"$thread_safe_flag_spec\"
+	  func_append linker_flags " $flag"
+	fi
+
+	# Make a backup of the uninstalled library when relinking
+	if test "$opt_mode" = relink; then
+	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?
+	fi
+
+	# Do each of the archive commands.
+	if test "$module" = yes && test -n "$module_cmds" ; then
+	  if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
+	    eval test_cmds=\"$module_expsym_cmds\"
+	    cmds=$module_expsym_cmds
+	  else
+	    eval test_cmds=\"$module_cmds\"
+	    cmds=$module_cmds
+	  fi
+	else
+	  if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
+	    eval test_cmds=\"$archive_expsym_cmds\"
+	    cmds=$archive_expsym_cmds
+	  else
+	    eval test_cmds=\"$archive_cmds\"
+	    cmds=$archive_cmds
+	  fi
+	fi
+
+	if test "X$skipped_export" != "X:" &&
+	   func_len " $test_cmds" &&
+	   len=$func_len_result &&
+	   test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+	  :
+	else
+	  # The command line is too long to link in one step, link piecewise
+	  # or, if using GNU ld and skipped_export is not :, use a linker
+	  # script.
+
+	  # Save the value of $output and $libobjs because we want to
+	  # use them later.  If we have whole_archive_flag_spec, we
+	  # want to use save_libobjs as it was before
+	  # whole_archive_flag_spec was expanded, because we can't
+	  # assume the linker understands whole_archive_flag_spec.
+	  # This may have to be revisited, in case too many
+	  # convenience libraries get linked in and end up exceeding
+	  # the spec.
+	  if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then
+	    save_libobjs=$libobjs
+	  fi
+	  save_output=$output
+	  func_basename "$output"
+	  output_la=$func_basename_result
+
+	  # Clear the reloadable object creation command queue and
+	  # initialize k to one.
+	  test_cmds=
+	  concat_cmds=
+	  objlist=
+	  last_robj=
+	  k=1
+
+	  if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then
+	    output=${output_objdir}/${output_la}.lnkscript
+	    func_verbose "creating GNU ld script: $output"
+	    echo 'INPUT (' > $output
+	    for obj in $save_libobjs
+	    do
+	      func_to_tool_file "$obj"
+	      $ECHO "$func_to_tool_file_result" >> $output
+	    done
+	    echo ')' >> $output
+	    func_append delfiles " $output"
+	    func_to_tool_file "$output"
+	    output=$func_to_tool_file_result
+	  elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then
+	    output=${output_objdir}/${output_la}.lnk
+	    func_verbose "creating linker input file list: $output"
+	    : > $output
+	    set x $save_libobjs
+	    shift
+	    firstobj=
+	    if test "$compiler_needs_object" = yes; then
+	      firstobj="$1 "
+	      shift
+	    fi
+	    for obj
+	    do
+	      func_to_tool_file "$obj"
+	      $ECHO "$func_to_tool_file_result" >> $output
+	    done
+	    func_append delfiles " $output"
+	    func_to_tool_file "$output"
+	    output=$firstobj\"$file_list_spec$func_to_tool_file_result\"
+	  else
+	    if test -n "$save_libobjs"; then
+	      func_verbose "creating reloadable object files..."
+	      output=$output_objdir/$output_la-${k}.$objext
+	      eval test_cmds=\"$reload_cmds\"
+	      func_len " $test_cmds"
+	      len0=$func_len_result
+	      len=$len0
+
+	      # Loop over the list of objects to be linked.
+	      for obj in $save_libobjs
+	      do
+		func_len " $obj"
+		func_arith $len + $func_len_result
+		len=$func_arith_result
+		if test "X$objlist" = X ||
+		   test "$len" -lt "$max_cmd_len"; then
+		  func_append objlist " $obj"
+		else
+		  # The command $test_cmds is almost too long, add a
+		  # command to the queue.
+		  if test "$k" -eq 1 ; then
+		    # The first file doesn't have a previous command to add.
+		    reload_objs=$objlist
+		    eval concat_cmds=\"$reload_cmds\"
+		  else
+		    # All subsequent reloadable object files will link in
+		    # the last one created.
+		    reload_objs="$objlist $last_robj"
+		    eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\"
+		  fi
+		  last_robj=$output_objdir/$output_la-${k}.$objext
+		  func_arith $k + 1
+		  k=$func_arith_result
+		  output=$output_objdir/$output_la-${k}.$objext
+		  objlist=" $obj"
+		  func_len " $last_robj"
+		  func_arith $len0 + $func_len_result
+		  len=$func_arith_result
+		fi
+	      done
+	      # Handle the remaining objects by creating one last
+	      # reloadable object file.  All subsequent reloadable object
+	      # files will link in the last one created.
+	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
+	      reload_objs="$objlist $last_robj"
+	      eval concat_cmds=\"\${concat_cmds}$reload_cmds\"
+	      if test -n "$last_robj"; then
+	        eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\"
+	      fi
+	      func_append delfiles " $output"
+
+	    else
+	      output=
+	    fi
+
+	    if ${skipped_export-false}; then
+	      func_verbose "generating symbol list for \`$libname.la'"
+	      export_symbols="$output_objdir/$libname.exp"
+	      $opt_dry_run || $RM $export_symbols
+	      libobjs=$output
+	      # Append the command to create the export file.
+	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
+	      eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\"
+	      if test -n "$last_robj"; then
+		eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\"
+	      fi
+	    fi
+
+	    test -n "$save_libobjs" &&
+	      func_verbose "creating a temporary reloadable object file: $output"
+
+	    # Loop through the commands generated above and execute them.
+	    save_ifs="$IFS"; IFS='~'
+	    for cmd in $concat_cmds; do
+	      IFS="$save_ifs"
+	      $opt_silent || {
+		  func_quote_for_expand "$cmd"
+		  eval "func_echo $func_quote_for_expand_result"
+	      }
+	      $opt_dry_run || eval "$cmd" || {
+		lt_exit=$?
+
+		# Restore the uninstalled library and exit
+		if test "$opt_mode" = relink; then
+		  ( cd "$output_objdir" && \
+		    $RM "${realname}T" && \
+		    $MV "${realname}U" "$realname" )
+		fi
+
+		exit $lt_exit
+	      }
+	    done
+	    IFS="$save_ifs"
+
+	    if test -n "$export_symbols_regex" && ${skipped_export-false}; then
+	      func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
+	      func_show_eval '$MV "${export_symbols}T" "$export_symbols"'
+	    fi
+	  fi
+
+          if ${skipped_export-false}; then
+	    if test -n "$export_symbols" && test -n "$include_expsyms"; then
+	      tmp_export_symbols="$export_symbols"
+	      test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
+	      $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"'
+	    fi
+
+	    if test -n "$orig_export_symbols"; then
+	      # The given exports_symbols file has to be filtered, so filter it.
+	      func_verbose "filter symbol list for \`$libname.la' to tag DATA exports"
+	      # FIXME: $output_objdir/$libname.filter potentially contains lots of
+	      # 's' commands which not all seds can handle. GNU sed should be fine
+	      # though. Also, the filter scales superlinearly with the number of
+	      # global variables. join(1) would be nice here, but unfortunately
+	      # isn't a blessed tool.
+	      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter
+	      func_append delfiles " $export_symbols $output_objdir/$libname.filter"
+	      export_symbols=$output_objdir/$libname.def
+	      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols
+	    fi
+	  fi
+
+	  libobjs=$output
+	  # Restore the value of output.
+	  output=$save_output
+
+	  if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then
+	    eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
+	    test "X$libobjs" = "X " && libobjs=
+	  fi
+	  # Expand the library linking commands again to reset the
+	  # value of $libobjs for piecewise linking.
+
+	  # Do each of the archive commands.
+	  if test "$module" = yes && test -n "$module_cmds" ; then
+	    if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
+	      cmds=$module_expsym_cmds
+	    else
+	      cmds=$module_cmds
+	    fi
+	  else
+	    if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
+	      cmds=$archive_expsym_cmds
+	    else
+	      cmds=$archive_cmds
+	    fi
+	  fi
+	fi
+
+	if test -n "$delfiles"; then
+	  # Append the command to remove temporary files to $cmds.
+	  eval cmds=\"\$cmds~\$RM $delfiles\"
+	fi
+
+	# Add any objects from preloaded convenience libraries
+	if test -n "$dlprefiles"; then
+	  gentop="$output_objdir/${outputname}x"
+	  func_append generated " $gentop"
+
+	  func_extract_archives $gentop $dlprefiles
+	  func_append libobjs " $func_extract_archives_result"
+	  test "X$libobjs" = "X " && libobjs=
+	fi
+
+	save_ifs="$IFS"; IFS='~'
+	for cmd in $cmds; do
+	  IFS="$save_ifs"
+	  eval cmd=\"$cmd\"
+	  $opt_silent || {
+	    func_quote_for_expand "$cmd"
+	    eval "func_echo $func_quote_for_expand_result"
+	  }
+	  $opt_dry_run || eval "$cmd" || {
+	    lt_exit=$?
+
+	    # Restore the uninstalled library and exit
+	    if test "$opt_mode" = relink; then
+	      ( cd "$output_objdir" && \
+	        $RM "${realname}T" && \
+		$MV "${realname}U" "$realname" )
+	    fi
+
+	    exit $lt_exit
+	  }
+	done
+	IFS="$save_ifs"
+
+	# Restore the uninstalled library and exit
+	if test "$opt_mode" = relink; then
+	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?
+
+	  if test -n "$convenience"; then
+	    if test -z "$whole_archive_flag_spec"; then
+	      func_show_eval '${RM}r "$gentop"'
+	    fi
+	  fi
+
+	  exit $EXIT_SUCCESS
+	fi
+
+	# Create links to the real library.
+	for linkname in $linknames; do
+	  if test "$realname" != "$linkname"; then
+	    func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?'
+	  fi
+	done
+
+	# If -module or -export-dynamic was specified, set the dlname.
+	if test "$module" = yes || test "$export_dynamic" = yes; then
+	  # On all known operating systems, these are identical.
+	  dlname="$soname"
+	fi
+      fi
+      ;;
+
+    obj)
+      if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+	func_warning "\`-dlopen' is ignored for objects"
+      fi
+
+      case " $deplibs" in
+      *\ -l* | *\ -L*)
+	func_warning "\`-l' and \`-L' are ignored for objects" ;;
+      esac
+
+      test -n "$rpath" && \
+	func_warning "\`-rpath' is ignored for objects"
+
+      test -n "$xrpath" && \
+	func_warning "\`-R' is ignored for objects"
+
+      test -n "$vinfo" && \
+	func_warning "\`-version-info' is ignored for objects"
+
+      test -n "$release" && \
+	func_warning "\`-release' is ignored for objects"
+
+      case $output in
+      *.lo)
+	test -n "$objs$old_deplibs" && \
+	  func_fatal_error "cannot build library object \`$output' from non-libtool objects"
+
+	libobj=$output
+	func_lo2o "$libobj"
+	obj=$func_lo2o_result
+	;;
+      *)
+	libobj=
+	obj="$output"
+	;;
+      esac
+
+      # Delete the old objects.
+      $opt_dry_run || $RM $obj $libobj
+
+      # Objects from convenience libraries.  This assumes
+      # single-version convenience libraries.  Whenever we create
+      # different ones for PIC/non-PIC, this we'll have to duplicate
+      # the extraction.
+      reload_conv_objs=
+      gentop=
+      # reload_cmds runs $LD directly, so let us get rid of
+      # -Wl from whole_archive_flag_spec and hope we can get by with
+      # turning comma into space..
+      wl=
+
+      if test -n "$convenience"; then
+	if test -n "$whole_archive_flag_spec"; then
+	  eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\"
+	  reload_conv_objs=$reload_objs\ `$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'`
+	else
+	  gentop="$output_objdir/${obj}x"
+	  func_append generated " $gentop"
+
+	  func_extract_archives $gentop $convenience
+	  reload_conv_objs="$reload_objs $func_extract_archives_result"
+	fi
+      fi
+
+      # If we're not building shared, we need to use non_pic_objs
+      test "$build_libtool_libs" != yes && libobjs="$non_pic_objects"
+
+      # Create the old-style object.
+      reload_objs="$objs$old_deplibs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; /\.lib$/d; $lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test
+
+      output="$obj"
+      func_execute_cmds "$reload_cmds" 'exit $?'
+
+      # Exit if we aren't doing a library object file.
+      if test -z "$libobj"; then
+	if test -n "$gentop"; then
+	  func_show_eval '${RM}r "$gentop"'
+	fi
+
+	exit $EXIT_SUCCESS
+      fi
+
+      if test "$build_libtool_libs" != yes; then
+	if test -n "$gentop"; then
+	  func_show_eval '${RM}r "$gentop"'
+	fi
+
+	# Create an invalid libtool object if no PIC, so that we don't
+	# accidentally link it into a program.
+	# $show "echo timestamp > $libobj"
+	# $opt_dry_run || eval "echo timestamp > $libobj" || exit $?
+	exit $EXIT_SUCCESS
+      fi
+
+      if test -n "$pic_flag" || test "$pic_mode" != default; then
+	# Only do commands if we really have different PIC objects.
+	reload_objs="$libobjs $reload_conv_objs"
+	output="$libobj"
+	func_execute_cmds "$reload_cmds" 'exit $?'
+      fi
+
+      if test -n "$gentop"; then
+	func_show_eval '${RM}r "$gentop"'
+      fi
+
+      exit $EXIT_SUCCESS
+      ;;
+
+    prog)
+      case $host in
+	*cygwin*) func_stripname '' '.exe' "$output"
+	          output=$func_stripname_result.exe;;
+      esac
+      test -n "$vinfo" && \
+	func_warning "\`-version-info' is ignored for programs"
+
+      test -n "$release" && \
+	func_warning "\`-release' is ignored for programs"
+
+      test "$preload" = yes \
+        && test "$dlopen_support" = unknown \
+	&& test "$dlopen_self" = unknown \
+	&& test "$dlopen_self_static" = unknown && \
+	  func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support."
+
+      case $host in
+      *-*-rhapsody* | *-*-darwin1.[012])
+	# On Rhapsody replace the C library is the System framework
+	compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'`
+	finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'`
+	;;
+      esac
+
+      case $host in
+      *-*-darwin*)
+	# Don't allow lazy linking, it breaks C++ global constructors
+	# But is supposedly fixed on 10.4 or later (yay!).
+	if test "$tagname" = CXX ; then
+	  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in
+	    10.[0123])
+	      func_append compile_command " ${wl}-bind_at_load"
+	      func_append finalize_command " ${wl}-bind_at_load"
+	    ;;
+	  esac
+	fi
+	# Time to change all our "foo.ltframework" stuff back to "-framework foo"
+	compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	;;
+      esac
+
+
+      # move library search paths that coincide with paths to not yet
+      # installed libraries to the beginning of the library search list
+      new_libs=
+      for path in $notinst_path; do
+	case " $new_libs " in
+	*" -L$path/$objdir "*) ;;
+	*)
+	  case " $compile_deplibs " in
+	  *" -L$path/$objdir "*)
+	    func_append new_libs " -L$path/$objdir" ;;
+	  esac
+	  ;;
+	esac
+      done
+      for deplib in $compile_deplibs; do
+	case $deplib in
+	-L*)
+	  case " $new_libs " in
+	  *" $deplib "*) ;;
+	  *) func_append new_libs " $deplib" ;;
+	  esac
+	  ;;
+	*) func_append new_libs " $deplib" ;;
+	esac
+      done
+      compile_deplibs="$new_libs"
+
+
+      func_append compile_command " $compile_deplibs"
+      func_append finalize_command " $finalize_deplibs"
+
+      if test -n "$rpath$xrpath"; then
+	# If the user specified any rpath flags, then add them.
+	for libdir in $rpath $xrpath; do
+	  # This is the magic to use -rpath.
+	  case "$finalize_rpath " in
+	  *" $libdir "*) ;;
+	  *) func_append finalize_rpath " $libdir" ;;
+	  esac
+	done
+      fi
+
+      # Now hardcode the library paths
+      rpath=
+      hardcode_libdirs=
+      for libdir in $compile_rpath $finalize_rpath; do
+	if test -n "$hardcode_libdir_flag_spec"; then
+	  if test -n "$hardcode_libdir_separator"; then
+	    if test -z "$hardcode_libdirs"; then
+	      hardcode_libdirs="$libdir"
+	    else
+	      # Just accumulate the unique libdirs.
+	      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+	      *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+		;;
+	      *)
+		func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
+		;;
+	      esac
+	    fi
+	  else
+	    eval flag=\"$hardcode_libdir_flag_spec\"
+	    func_append rpath " $flag"
+	  fi
+	elif test -n "$runpath_var"; then
+	  case "$perm_rpath " in
+	  *" $libdir "*) ;;
+	  *) func_append perm_rpath " $libdir" ;;
+	  esac
+	fi
+	case $host in
+	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+	  testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'`
+	  case :$dllsearchpath: in
+	  *":$libdir:"*) ;;
+	  ::) dllsearchpath=$libdir;;
+	  *) func_append dllsearchpath ":$libdir";;
+	  esac
+	  case :$dllsearchpath: in
+	  *":$testbindir:"*) ;;
+	  ::) dllsearchpath=$testbindir;;
+	  *) func_append dllsearchpath ":$testbindir";;
+	  esac
+	  ;;
+	esac
+      done
+      # Substitute the hardcoded libdirs into the rpath.
+      if test -n "$hardcode_libdir_separator" &&
+	 test -n "$hardcode_libdirs"; then
+	libdir="$hardcode_libdirs"
+	eval rpath=\" $hardcode_libdir_flag_spec\"
+      fi
+      compile_rpath="$rpath"
+
+      rpath=
+      hardcode_libdirs=
+      for libdir in $finalize_rpath; do
+	if test -n "$hardcode_libdir_flag_spec"; then
+	  if test -n "$hardcode_libdir_separator"; then
+	    if test -z "$hardcode_libdirs"; then
+	      hardcode_libdirs="$libdir"
+	    else
+	      # Just accumulate the unique libdirs.
+	      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+	      *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+		;;
+	      *)
+		func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
+		;;
+	      esac
+	    fi
+	  else
+	    eval flag=\"$hardcode_libdir_flag_spec\"
+	    func_append rpath " $flag"
+	  fi
+	elif test -n "$runpath_var"; then
+	  case "$finalize_perm_rpath " in
+	  *" $libdir "*) ;;
+	  *) func_append finalize_perm_rpath " $libdir" ;;
+	  esac
+	fi
+      done
+      # Substitute the hardcoded libdirs into the rpath.
+      if test -n "$hardcode_libdir_separator" &&
+	 test -n "$hardcode_libdirs"; then
+	libdir="$hardcode_libdirs"
+	eval rpath=\" $hardcode_libdir_flag_spec\"
+      fi
+      finalize_rpath="$rpath"
+
+      if test -n "$libobjs" && test "$build_old_libs" = yes; then
+	# Transform all the library objects into standard objects.
+	compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP`
+	finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP`
+      fi
+
+      func_generate_dlsyms "$outputname" "@PROGRAM@" "no"
+
+      # template prelinking step
+      if test -n "$prelink_cmds"; then
+	func_execute_cmds "$prelink_cmds" 'exit $?'
+      fi
+
+      wrappers_required=yes
+      case $host in
+      *cegcc* | *mingw32ce*)
+        # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.
+        wrappers_required=no
+        ;;
+      *cygwin* | *mingw* )
+        if test "$build_libtool_libs" != yes; then
+          wrappers_required=no
+        fi
+        ;;
+      *)
+        if test "$need_relink" = no || test "$build_libtool_libs" != yes; then
+          wrappers_required=no
+        fi
+        ;;
+      esac
+      if test "$wrappers_required" = no; then
+	# Replace the output file specification.
+	compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'`
+	link_command="$compile_command$compile_rpath"
+
+	# We have no uninstalled library dependencies, so finalize right now.
+	exit_status=0
+	func_show_eval "$link_command" 'exit_status=$?'
+
+	if test -n "$postlink_cmds"; then
+	  func_to_tool_file "$output"
+	  postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	  func_execute_cmds "$postlink_cmds" 'exit $?'
+	fi
+
+	# Delete the generated files.
+	if test -f "$output_objdir/${outputname}S.${objext}"; then
+	  func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"'
+	fi
+
+	exit $exit_status
+      fi
+
+      if test -n "$compile_shlibpath$finalize_shlibpath"; then
+	compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command"
+      fi
+      if test -n "$finalize_shlibpath"; then
+	finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command"
+      fi
+
+      compile_var=
+      finalize_var=
+      if test -n "$runpath_var"; then
+	if test -n "$perm_rpath"; then
+	  # We should set the runpath_var.
+	  rpath=
+	  for dir in $perm_rpath; do
+	    func_append rpath "$dir:"
+	  done
+	  compile_var="$runpath_var=\"$rpath\$$runpath_var\" "
+	fi
+	if test -n "$finalize_perm_rpath"; then
+	  # We should set the runpath_var.
+	  rpath=
+	  for dir in $finalize_perm_rpath; do
+	    func_append rpath "$dir:"
+	  done
+	  finalize_var="$runpath_var=\"$rpath\$$runpath_var\" "
+	fi
+      fi
+
+      if test "$no_install" = yes; then
+	# We don't need to create a wrapper script.
+	link_command="$compile_var$compile_command$compile_rpath"
+	# Replace the output file specification.
+	link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'`
+	# Delete the old output file.
+	$opt_dry_run || $RM $output
+	# Link the executable and exit
+	func_show_eval "$link_command" 'exit $?'
+
+	if test -n "$postlink_cmds"; then
+	  func_to_tool_file "$output"
+	  postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	  func_execute_cmds "$postlink_cmds" 'exit $?'
+	fi
+
+	exit $EXIT_SUCCESS
+      fi
+
+      if test "$hardcode_action" = relink; then
+	# Fast installation is not supported
+	link_command="$compile_var$compile_command$compile_rpath"
+	relink_command="$finalize_var$finalize_command$finalize_rpath"
+
+	func_warning "this platform does not like uninstalled shared libraries"
+	func_warning "\`$output' will be relinked during installation"
+      else
+	if test "$fast_install" != no; then
+	  link_command="$finalize_var$compile_command$finalize_rpath"
+	  if test "$fast_install" = yes; then
+	    relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'`
+	  else
+	    # fast_install is set to needless
+	    relink_command=
+	  fi
+	else
+	  link_command="$compile_var$compile_command$compile_rpath"
+	  relink_command="$finalize_var$finalize_command$finalize_rpath"
+	fi
+      fi
+
+      # Replace the output file specification.
+      link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'`
+
+      # Delete the old output files.
+      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname
+
+      func_show_eval "$link_command" 'exit $?'
+
+      if test -n "$postlink_cmds"; then
+	func_to_tool_file "$output_objdir/$outputname"
+	postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	func_execute_cmds "$postlink_cmds" 'exit $?'
+      fi
+
+      # Now create the wrapper script.
+      func_verbose "creating $output"
+
+      # Quote the relink command for shipping.
+      if test -n "$relink_command"; then
+	# Preserve any variables that may affect compiler behavior
+	for var in $variables_saved_for_relink; do
+	  if eval test -z \"\${$var+set}\"; then
+	    relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command"
+	  elif eval var_value=\$$var; test -z "$var_value"; then
+	    relink_command="$var=; export $var; $relink_command"
+	  else
+	    func_quote_for_eval "$var_value"
+	    relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command"
+	  fi
+	done
+	relink_command="(cd `pwd`; $relink_command)"
+	relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"`
+      fi
+
+      # Only actually do things if not in dry run mode.
+      $opt_dry_run || {
+	# win32 will think the script is a binary if it has
+	# a .exe suffix, so we strip it off here.
+	case $output in
+	  *.exe) func_stripname '' '.exe' "$output"
+	         output=$func_stripname_result ;;
+	esac
+	# test for cygwin because mv fails w/o .exe extensions
+	case $host in
+	  *cygwin*)
+	    exeext=.exe
+	    func_stripname '' '.exe' "$outputname"
+	    outputname=$func_stripname_result ;;
+	  *) exeext= ;;
+	esac
+	case $host in
+	  *cygwin* | *mingw* )
+	    func_dirname_and_basename "$output" "" "."
+	    output_name=$func_basename_result
+	    output_path=$func_dirname_result
+	    cwrappersource="$output_path/$objdir/lt-$output_name.c"
+	    cwrapper="$output_path/$output_name.exe"
+	    $RM $cwrappersource $cwrapper
+	    trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15
+
+	    func_emit_cwrapperexe_src > $cwrappersource
+
+	    # The wrapper executable is built using the $host compiler,
+	    # because it contains $host paths and files. If cross-
+	    # compiling, it, like the target executable, must be
+	    # executed on the $host or under an emulation environment.
+	    $opt_dry_run || {
+	      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource
+	      $STRIP $cwrapper
+	    }
+
+	    # Now, create the wrapper script for func_source use:
+	    func_ltwrapper_scriptname $cwrapper
+	    $RM $func_ltwrapper_scriptname_result
+	    trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15
+	    $opt_dry_run || {
+	      # note: this script will not be executed, so do not chmod.
+	      if test "x$build" = "x$host" ; then
+		$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result
+	      else
+		func_emit_wrapper no > $func_ltwrapper_scriptname_result
+	      fi
+	    }
+	  ;;
+	  * )
+	    $RM $output
+	    trap "$RM $output; exit $EXIT_FAILURE" 1 2 15
+
+	    func_emit_wrapper no > $output
+	    chmod +x $output
+	  ;;
+	esac
+      }
+      exit $EXIT_SUCCESS
+      ;;
+    esac
+
+    # See if we need to build an old-fashioned archive.
+    for oldlib in $oldlibs; do
+
+      if test "$build_libtool_libs" = convenience; then
+	oldobjs="$libobjs_save $symfileobj"
+	addlibs="$convenience"
+	build_libtool_libs=no
+      else
+	if test "$build_libtool_libs" = module; then
+	  oldobjs="$libobjs_save"
+	  build_libtool_libs=no
+	else
+	  oldobjs="$old_deplibs $non_pic_objects"
+	  if test "$preload" = yes && test -f "$symfileobj"; then
+	    func_append oldobjs " $symfileobj"
+	  fi
+	fi
+	addlibs="$old_convenience"
+      fi
+
+      if test -n "$addlibs"; then
+	gentop="$output_objdir/${outputname}x"
+	func_append generated " $gentop"
+
+	func_extract_archives $gentop $addlibs
+	func_append oldobjs " $func_extract_archives_result"
+      fi
+
+      # Do each command in the archive commands.
+      if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then
+	cmds=$old_archive_from_new_cmds
+      else
+
+	# Add any objects from preloaded convenience libraries
+	if test -n "$dlprefiles"; then
+	  gentop="$output_objdir/${outputname}x"
+	  func_append generated " $gentop"
+
+	  func_extract_archives $gentop $dlprefiles
+	  func_append oldobjs " $func_extract_archives_result"
+	fi
+
+	# POSIX demands no paths to be encoded in archives.  We have
+	# to avoid creating archives with duplicate basenames if we
+	# might have to extract them afterwards, e.g., when creating a
+	# static archive out of a convenience library, or when linking
+	# the entirety of a libtool archive into another (currently
+	# not supported by libtool).
+	if (for obj in $oldobjs
+	    do
+	      func_basename "$obj"
+	      $ECHO "$func_basename_result"
+	    done | sort | sort -uc >/dev/null 2>&1); then
+	  :
+	else
+	  echo "copying selected object files to avoid basename conflicts..."
+	  gentop="$output_objdir/${outputname}x"
+	  func_append generated " $gentop"
+	  func_mkdir_p "$gentop"
+	  save_oldobjs=$oldobjs
+	  oldobjs=
+	  counter=1
+	  for obj in $save_oldobjs
+	  do
+	    func_basename "$obj"
+	    objbase="$func_basename_result"
+	    case " $oldobjs " in
+	    " ") oldobjs=$obj ;;
+	    *[\ /]"$objbase "*)
+	      while :; do
+		# Make sure we don't pick an alternate name that also
+		# overlaps.
+		newobj=lt$counter-$objbase
+		func_arith $counter + 1
+		counter=$func_arith_result
+		case " $oldobjs " in
+		*[\ /]"$newobj "*) ;;
+		*) if test ! -f "$gentop/$newobj"; then break; fi ;;
+		esac
+	      done
+	      func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj"
+	      func_append oldobjs " $gentop/$newobj"
+	      ;;
+	    *) func_append oldobjs " $obj" ;;
+	    esac
+	  done
+	fi
+	func_to_tool_file "$oldlib" func_convert_file_msys_to_w32
+	tool_oldlib=$func_to_tool_file_result
+	eval cmds=\"$old_archive_cmds\"
+
+	func_len " $cmds"
+	len=$func_len_result
+	if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+	  cmds=$old_archive_cmds
+	elif test -n "$archiver_list_spec"; then
+	  func_verbose "using command file archive linking..."
+	  for obj in $oldobjs
+	  do
+	    func_to_tool_file "$obj"
+	    $ECHO "$func_to_tool_file_result"
+	  done > $output_objdir/$libname.libcmd
+	  func_to_tool_file "$output_objdir/$libname.libcmd"
+	  oldobjs=" $archiver_list_spec$func_to_tool_file_result"
+	  cmds=$old_archive_cmds
+	else
+	  # the command line is too long to link in one step, link in parts
+	  func_verbose "using piecewise archive linking..."
+	  save_RANLIB=$RANLIB
+	  RANLIB=:
+	  objlist=
+	  concat_cmds=
+	  save_oldobjs=$oldobjs
+	  oldobjs=
+	  # Is there a better way of finding the last object in the list?
+	  for obj in $save_oldobjs
+	  do
+	    last_oldobj=$obj
+	  done
+	  eval test_cmds=\"$old_archive_cmds\"
+	  func_len " $test_cmds"
+	  len0=$func_len_result
+	  len=$len0
+	  for obj in $save_oldobjs
+	  do
+	    func_len " $obj"
+	    func_arith $len + $func_len_result
+	    len=$func_arith_result
+	    func_append objlist " $obj"
+	    if test "$len" -lt "$max_cmd_len"; then
+	      :
+	    else
+	      # the above command should be used before it gets too long
+	      oldobjs=$objlist
+	      if test "$obj" = "$last_oldobj" ; then
+		RANLIB=$save_RANLIB
+	      fi
+	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
+	      eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\"
+	      objlist=
+	      len=$len0
+	    fi
+	  done
+	  RANLIB=$save_RANLIB
+	  oldobjs=$objlist
+	  if test "X$oldobjs" = "X" ; then
+	    eval cmds=\"\$concat_cmds\"
+	  else
+	    eval cmds=\"\$concat_cmds~\$old_archive_cmds\"
+	  fi
+	fi
+      fi
+      func_execute_cmds "$cmds" 'exit $?'
+    done
+
+    test -n "$generated" && \
+      func_show_eval "${RM}r$generated"
+
+    # Now create the libtool archive.
+    case $output in
+    *.la)
+      old_library=
+      test "$build_old_libs" = yes && old_library="$libname.$libext"
+      func_verbose "creating $output"
+
+      # Preserve any variables that may affect compiler behavior
+      for var in $variables_saved_for_relink; do
+	if eval test -z \"\${$var+set}\"; then
+	  relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command"
+	elif eval var_value=\$$var; test -z "$var_value"; then
+	  relink_command="$var=; export $var; $relink_command"
+	else
+	  func_quote_for_eval "$var_value"
+	  relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command"
+	fi
+      done
+      # Quote the link command for shipping.
+      relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)"
+      relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"`
+      if test "$hardcode_automatic" = yes ; then
+	relink_command=
+      fi
+
+      # Only create the output if not a dry run.
+      $opt_dry_run || {
+	for installed in no yes; do
+	  if test "$installed" = yes; then
+	    if test -z "$install_libdir"; then
+	      break
+	    fi
+	    output="$output_objdir/$outputname"i
+	    # Replace all uninstalled libtool libraries with the installed ones
+	    newdependency_libs=
+	    for deplib in $dependency_libs; do
+	      case $deplib in
+	      *.la)
+		func_basename "$deplib"
+		name="$func_basename_result"
+		func_resolve_sysroot "$deplib"
+		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result`
+		test -z "$libdir" && \
+		  func_fatal_error "\`$deplib' is not a valid libtool archive"
+		func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name"
+		;;
+	      -L*)
+		func_stripname -L '' "$deplib"
+		func_replace_sysroot "$func_stripname_result"
+		func_append newdependency_libs " -L$func_replace_sysroot_result"
+		;;
+	      -R*)
+		func_stripname -R '' "$deplib"
+		func_replace_sysroot "$func_stripname_result"
+		func_append newdependency_libs " -R$func_replace_sysroot_result"
+		;;
+	      *) func_append newdependency_libs " $deplib" ;;
+	      esac
+	    done
+	    dependency_libs="$newdependency_libs"
+	    newdlfiles=
+
+	    for lib in $dlfiles; do
+	      case $lib in
+	      *.la)
+	        func_basename "$lib"
+		name="$func_basename_result"
+		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
+		test -z "$libdir" && \
+		  func_fatal_error "\`$lib' is not a valid libtool archive"
+		func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name"
+		;;
+	      *) func_append newdlfiles " $lib" ;;
+	      esac
+	    done
+	    dlfiles="$newdlfiles"
+	    newdlprefiles=
+	    for lib in $dlprefiles; do
+	      case $lib in
+	      *.la)
+		# Only pass preopened files to the pseudo-archive (for
+		# eventual linking with the app. that links it) if we
+		# didn't already link the preopened objects directly into
+		# the library:
+		func_basename "$lib"
+		name="$func_basename_result"
+		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
+		test -z "$libdir" && \
+		  func_fatal_error "\`$lib' is not a valid libtool archive"
+		func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name"
+		;;
+	      esac
+	    done
+	    dlprefiles="$newdlprefiles"
+	  else
+	    newdlfiles=
+	    for lib in $dlfiles; do
+	      case $lib in
+		[\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
+		*) abs=`pwd`"/$lib" ;;
+	      esac
+	      func_append newdlfiles " $abs"
+	    done
+	    dlfiles="$newdlfiles"
+	    newdlprefiles=
+	    for lib in $dlprefiles; do
+	      case $lib in
+		[\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
+		*) abs=`pwd`"/$lib" ;;
+	      esac
+	      func_append newdlprefiles " $abs"
+	    done
+	    dlprefiles="$newdlprefiles"
+	  fi
+	  $RM $output
+	  # place dlname in correct position for cygwin
+	  # In fact, it would be nice if we could use this code for all target
+	  # systems that can't hard-code library paths into their executables
+	  # and that have no shared library path variable independent of PATH,
+	  # but it turns out we can't easily determine that from inspecting
+	  # libtool variables, so we have to hard-code the OSs to which it
+	  # applies here; at the moment, that means platforms that use the PE
+	  # object format with DLL files.  See the long comment at the top of
+	  # tests/bindir.at for full details.
+	  tdlname=$dlname
+	  case $host,$output,$installed,$module,$dlname in
+	    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)
+	      # If a -bindir argument was supplied, place the dll there.
+	      if test "x$bindir" != x ;
+	      then
+		func_relative_path "$install_libdir" "$bindir"
+		tdlname=$func_relative_path_result$dlname
+	      else
+		# Otherwise fall back on heuristic.
+		tdlname=../bin/$dlname
+	      fi
+	      ;;
+	  esac
+	  $ECHO > $output "\
+# $outputname - a libtool library file
+# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+#
+# Please DO NOT delete this file!
+# It is necessary for linking the library.
+
+# The name that we can dlopen(3).
+dlname='$tdlname'
+
+# Names of this library.
+library_names='$library_names'
+
+# The name of the static archive.
+old_library='$old_library'
+
+# Linker flags that can not go in dependency_libs.
+inherited_linker_flags='$new_inherited_linker_flags'
+
+# Libraries that this one depends upon.
+dependency_libs='$dependency_libs'
+
+# Names of additional weak libraries provided by this library
+weak_library_names='$weak_libs'
+
+# Version information for $libname.
+current=$current
+age=$age
+revision=$revision
+
+# Is this an already installed library?
+installed=$installed
+
+# Should we warn about portability when linking against -modules?
+shouldnotlink=$module
+
+# Files to dlopen/dlpreopen
+dlopen='$dlfiles'
+dlpreopen='$dlprefiles'
+
+# Directory that this library needs to be installed in:
+libdir='$install_libdir'"
+	  if test "$installed" = no && test "$need_relink" = yes; then
+	    $ECHO >> $output "\
+relink_command=\"$relink_command\""
+	  fi
+	done
+      }
+
+      # Do a symbolic link so that the libtool archive can be found in
+      # LD_LIBRARY_PATH before the program is installed.
+      func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?'
+      ;;
+    esac
+    exit $EXIT_SUCCESS
+}
+
+{ test "$opt_mode" = link || test "$opt_mode" = relink; } &&
+    func_mode_link ${1+"$@"}
+
+
+# func_mode_uninstall arg...
+func_mode_uninstall ()
+{
+    $opt_debug
+    RM="$nonopt"
+    files=
+    rmforce=
+    exit_status=0
+
+    # This variable tells wrapper scripts just to set variables rather
+    # than running their programs.
+    libtool_install_magic="$magic"
+
+    for arg
+    do
+      case $arg in
+      -f) func_append RM " $arg"; rmforce=yes ;;
+      -*) func_append RM " $arg" ;;
+      *) func_append files " $arg" ;;
+      esac
+    done
+
+    test -z "$RM" && \
+      func_fatal_help "you must specify an RM program"
+
+    rmdirs=
+
+    for file in $files; do
+      func_dirname "$file" "" "."
+      dir="$func_dirname_result"
+      if test "X$dir" = X.; then
+	odir="$objdir"
+      else
+	odir="$dir/$objdir"
+      fi
+      func_basename "$file"
+      name="$func_basename_result"
+      test "$opt_mode" = uninstall && odir="$dir"
+
+      # Remember odir for removal later, being careful to avoid duplicates
+      if test "$opt_mode" = clean; then
+	case " $rmdirs " in
+	  *" $odir "*) ;;
+	  *) func_append rmdirs " $odir" ;;
+	esac
+      fi
+
+      # Don't error if the file doesn't exist and rm -f was used.
+      if { test -L "$file"; } >/dev/null 2>&1 ||
+	 { test -h "$file"; } >/dev/null 2>&1 ||
+	 test -f "$file"; then
+	:
+      elif test -d "$file"; then
+	exit_status=1
+	continue
+      elif test "$rmforce" = yes; then
+	continue
+      fi
+
+      rmfiles="$file"
+
+      case $name in
+      *.la)
+	# Possibly a libtool archive, so verify it.
+	if func_lalib_p "$file"; then
+	  func_source $dir/$name
+
+	  # Delete the libtool libraries and symlinks.
+	  for n in $library_names; do
+	    func_append rmfiles " $odir/$n"
+	  done
+	  test -n "$old_library" && func_append rmfiles " $odir/$old_library"
+
+	  case "$opt_mode" in
+	  clean)
+	    case " $library_names " in
+	    *" $dlname "*) ;;
+	    *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;;
+	    esac
+	    test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i"
+	    ;;
+	  uninstall)
+	    if test -n "$library_names"; then
+	      # Do each command in the postuninstall commands.
+	      func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1'
+	    fi
+
+	    if test -n "$old_library"; then
+	      # Do each command in the old_postuninstall commands.
+	      func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1'
+	    fi
+	    # FIXME: should reinstall the best remaining shared library.
+	    ;;
+	  esac
+	fi
+	;;
+
+      *.lo)
+	# Possibly a libtool object, so verify it.
+	if func_lalib_p "$file"; then
+
+	  # Read the .lo file
+	  func_source $dir/$name
+
+	  # Add PIC object to the list of files to remove.
+	  if test -n "$pic_object" &&
+	     test "$pic_object" != none; then
+	    func_append rmfiles " $dir/$pic_object"
+	  fi
+
+	  # Add non-PIC object to the list of files to remove.
+	  if test -n "$non_pic_object" &&
+	     test "$non_pic_object" != none; then
+	    func_append rmfiles " $dir/$non_pic_object"
+	  fi
+	fi
+	;;
+
+      *)
+	if test "$opt_mode" = clean ; then
+	  noexename=$name
+	  case $file in
+	  *.exe)
+	    func_stripname '' '.exe' "$file"
+	    file=$func_stripname_result
+	    func_stripname '' '.exe' "$name"
+	    noexename=$func_stripname_result
+	    # $file with .exe has already been added to rmfiles,
+	    # add $file without .exe
+	    func_append rmfiles " $file"
+	    ;;
+	  esac
+	  # Do a test to see if this is a libtool program.
+	  if func_ltwrapper_p "$file"; then
+	    if func_ltwrapper_executable_p "$file"; then
+	      func_ltwrapper_scriptname "$file"
+	      relink_command=
+	      func_source $func_ltwrapper_scriptname_result
+	      func_append rmfiles " $func_ltwrapper_scriptname_result"
+	    else
+	      relink_command=
+	      func_source $dir/$noexename
+	    fi
+
+	    # note $name still contains .exe if it was in $file originally
+	    # as does the version of $file that was added into $rmfiles
+	    func_append rmfiles " $odir/$name $odir/${name}S.${objext}"
+	    if test "$fast_install" = yes && test -n "$relink_command"; then
+	      func_append rmfiles " $odir/lt-$name"
+	    fi
+	    if test "X$noexename" != "X$name" ; then
+	      func_append rmfiles " $odir/lt-${noexename}.c"
+	    fi
+	  fi
+	fi
+	;;
+      esac
+      func_show_eval "$RM $rmfiles" 'exit_status=1'
+    done
+
+    # Try to remove the ${objdir}s in the directories where we deleted files
+    for dir in $rmdirs; do
+      if test -d "$dir"; then
+	func_show_eval "rmdir $dir >/dev/null 2>&1"
+      fi
+    done
+
+    exit $exit_status
+}
+
+{ test "$opt_mode" = uninstall || test "$opt_mode" = clean; } &&
+    func_mode_uninstall ${1+"$@"}
+
+test -z "$opt_mode" && {
+  help="$generic_help"
+  func_fatal_help "you must specify a MODE"
+}
+
+test -z "$exec_cmd" && \
+  func_fatal_help "invalid operation mode \`$opt_mode'"
+
+if test -n "$exec_cmd"; then
+  eval exec "$exec_cmd"
+  exit $EXIT_FAILURE
+fi
+
+exit $exit_status
+
+
+# The TAGs below are defined such that we never get into a situation
+# in which we disable both kinds of libraries.  Given conflicting
+# choices, we go for a static library, that is the most portable,
+# since we can't tell whether shared libraries were disabled because
+# the user asked for that or because the platform doesn't support
+# them.  This is particularly important on AIX, because we don't
+# support having both static and shared libraries enabled at the same
+# time on that platform, so we default to a shared-only configuration.
+# If a disable-shared tag is given, we'll fallback to a static-only
+# configuration.  But we'll never go from static-only to shared-only.
+
+# ### BEGIN LIBTOOL TAG CONFIG: disable-shared
+build_libtool_libs=no
+build_old_libs=yes
+# ### END LIBTOOL TAG CONFIG: disable-shared
+
+# ### BEGIN LIBTOOL TAG CONFIG: disable-static
+build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`
+# ### END LIBTOOL TAG CONFIG: disable-static
+
+# Local Variables:
+# mode:shell-script
+# sh-indentation:2
+# End:
+# vi:sw=2
+
diff --git a/hdrl/admin/missing b/hdrl/admin/missing
new file mode 100755
index 0000000..cdea514
--- /dev/null
+++ b/hdrl/admin/missing
@@ -0,0 +1,215 @@
+#! /bin/sh
+# Common wrapper for a few potentially missing GNU programs.
+
+scriptversion=2012-06-26.16; # UTC
+
+# Copyright (C) 1996-2013 Free Software Foundation, Inc.
+# Originally written by Fran,cois Pinard <pinard at iro.umontreal.ca>, 1996.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2, or (at your option)
+# any later version.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+if test $# -eq 0; then
+  echo 1>&2 "Try '$0 --help' for more information"
+  exit 1
+fi
+
+case $1 in
+
+  --is-lightweight)
+    # Used by our autoconf macros to check whether the available missing
+    # script is modern enough.
+    exit 0
+    ;;
+
+  --run)
+    # Back-compat with the calling convention used by older automake.
+    shift
+    ;;
+
+  -h|--h|--he|--hel|--help)
+    echo "\
+$0 [OPTION]... PROGRAM [ARGUMENT]...
+
+Run 'PROGRAM [ARGUMENT]...', returning a proper advice when this fails due
+to PROGRAM being missing or too old.
+
+Options:
+  -h, --help      display this help and exit
+  -v, --version   output version information and exit
+
+Supported PROGRAM values:
+  aclocal   autoconf  autoheader   autom4te  automake  makeinfo
+  bison     yacc      flex         lex       help2man
+
+Version suffixes to PROGRAM as well as the prefixes 'gnu-', 'gnu', and
+'g' are ignored when checking the name.
+
+Send bug reports to <bug-automake at gnu.org>."
+    exit $?
+    ;;
+
+  -v|--v|--ve|--ver|--vers|--versi|--versio|--version)
+    echo "missing $scriptversion (GNU Automake)"
+    exit $?
+    ;;
+
+  -*)
+    echo 1>&2 "$0: unknown '$1' option"
+    echo 1>&2 "Try '$0 --help' for more information"
+    exit 1
+    ;;
+
+esac
+
+# Run the given program, remember its exit status.
+"$@"; st=$?
+
+# If it succeeded, we are done.
+test $st -eq 0 && exit 0
+
+# Also exit now if we it failed (or wasn't found), and '--version' was
+# passed; such an option is passed most likely to detect whether the
+# program is present and works.
+case $2 in --version|--help) exit $st;; esac
+
+# Exit code 63 means version mismatch.  This often happens when the user
+# tries to use an ancient version of a tool on a file that requires a
+# minimum version.
+if test $st -eq 63; then
+  msg="probably too old"
+elif test $st -eq 127; then
+  # Program was missing.
+  msg="missing on your system"
+else
+  # Program was found and executed, but failed.  Give up.
+  exit $st
+fi
+
+perl_URL=http://www.perl.org/
+flex_URL=http://flex.sourceforge.net/
+gnu_software_URL=http://www.gnu.org/software
+
+program_details ()
+{
+  case $1 in
+    aclocal|automake)
+      echo "The '$1' program is part of the GNU Automake package:"
+      echo "<$gnu_software_URL/automake>"
+      echo "It also requires GNU Autoconf, GNU m4 and Perl in order to run:"
+      echo "<$gnu_software_URL/autoconf>"
+      echo "<$gnu_software_URL/m4/>"
+      echo "<$perl_URL>"
+      ;;
+    autoconf|autom4te|autoheader)
+      echo "The '$1' program is part of the GNU Autoconf package:"
+      echo "<$gnu_software_URL/autoconf/>"
+      echo "It also requires GNU m4 and Perl in order to run:"
+      echo "<$gnu_software_URL/m4/>"
+      echo "<$perl_URL>"
+      ;;
+  esac
+}
+
+give_advice ()
+{
+  # Normalize program name to check for.
+  normalized_program=`echo "$1" | sed '
+    s/^gnu-//; t
+    s/^gnu//; t
+    s/^g//; t'`
+
+  printf '%s\n' "'$1' is $msg."
+
+  configure_deps="'configure.ac' or m4 files included by 'configure.ac'"
+  case $normalized_program in
+    autoconf*)
+      echo "You should only need it if you modified 'configure.ac',"
+      echo "or m4 files included by it."
+      program_details 'autoconf'
+      ;;
+    autoheader*)
+      echo "You should only need it if you modified 'acconfig.h' or"
+      echo "$configure_deps."
+      program_details 'autoheader'
+      ;;
+    automake*)
+      echo "You should only need it if you modified 'Makefile.am' or"
+      echo "$configure_deps."
+      program_details 'automake'
+      ;;
+    aclocal*)
+      echo "You should only need it if you modified 'acinclude.m4' or"
+      echo "$configure_deps."
+      program_details 'aclocal'
+      ;;
+   autom4te*)
+      echo "You might have modified some maintainer files that require"
+      echo "the 'automa4te' program to be rebuilt."
+      program_details 'autom4te'
+      ;;
+    bison*|yacc*)
+      echo "You should only need it if you modified a '.y' file."
+      echo "You may want to install the GNU Bison package:"
+      echo "<$gnu_software_URL/bison/>"
+      ;;
+    lex*|flex*)
+      echo "You should only need it if you modified a '.l' file."
+      echo "You may want to install the Fast Lexical Analyzer package:"
+      echo "<$flex_URL>"
+      ;;
+    help2man*)
+      echo "You should only need it if you modified a dependency" \
+           "of a man page."
+      echo "You may want to install the GNU Help2man package:"
+      echo "<$gnu_software_URL/help2man/>"
+    ;;
+    makeinfo*)
+      echo "You should only need it if you modified a '.texi' file, or"
+      echo "any other file indirectly affecting the aspect of the manual."
+      echo "You might want to install the Texinfo package:"
+      echo "<$gnu_software_URL/texinfo/>"
+      echo "The spurious makeinfo call might also be the consequence of"
+      echo "using a buggy 'make' (AIX, DU, IRIX), in which case you might"
+      echo "want to install GNU make:"
+      echo "<$gnu_software_URL/make/>"
+      ;;
+    *)
+      echo "You might have modified some files without having the proper"
+      echo "tools for further handling them.  Check the 'README' file, it"
+      echo "often tells you about the needed prerequisites for installing"
+      echo "this package.  You may also peek at any GNU archive site, in"
+      echo "case some other package contains this missing '$1' program."
+      ;;
+  esac
+}
+
+give_advice "$1" | sed -e '1s/^/WARNING: /' \
+                       -e '2,$s/^/         /' >&2
+
+# Propagate the correct exit status (expected to be 127 for a program
+# not found, 63 for a program that failed due to version mismatch).
+exit $st
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
+# End:
diff --git a/hdrl/admin/test-driver b/hdrl/admin/test-driver
new file mode 100755
index 0000000..32bf39e
--- /dev/null
+++ b/hdrl/admin/test-driver
@@ -0,0 +1,127 @@
+#! /bin/sh
+# test-driver - basic testsuite driver script.
+
+scriptversion=2012-06-27.10; # UTC
+
+# Copyright (C) 2011-2013 Free Software Foundation, Inc.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2, or (at your option)
+# any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# This file is maintained in Automake, please report
+# bugs to <bug-automake at gnu.org> or send patches to
+# <automake-patches at gnu.org>.
+
+# Make unconditional expansion of undefined variables an error.  This
+# helps a lot in preventing typo-related bugs.
+set -u
+
+usage_error ()
+{
+  echo "$0: $*" >&2
+  print_usage >&2
+  exit 2
+}
+
+print_usage ()
+{
+  cat <<END
+Usage:
+  test-driver --test-name=NAME --log-file=PATH --trs-file=PATH
+              [--expect-failure={yes|no}] [--color-tests={yes|no}]
+              [--enable-hard-errors={yes|no}] [--] TEST-SCRIPT
+The '--test-name', '--log-file' and '--trs-file' options are mandatory.
+END
+}
+
+# TODO: better error handling in option parsing (in particular, ensure
+# TODO: $log_file, $trs_file and $test_name are defined).
+test_name= # Used for reporting.
+log_file=  # Where to save the output of the test script.
+trs_file=  # Where to save the metadata of the test run.
+expect_failure=no
+color_tests=no
+enable_hard_errors=yes
+while test $# -gt 0; do
+  case $1 in
+  --help) print_usage; exit $?;;
+  --version) echo "test-driver $scriptversion"; exit $?;;
+  --test-name) test_name=$2; shift;;
+  --log-file) log_file=$2; shift;;
+  --trs-file) trs_file=$2; shift;;
+  --color-tests) color_tests=$2; shift;;
+  --expect-failure) expect_failure=$2; shift;;
+  --enable-hard-errors) enable_hard_errors=$2; shift;;
+  --) shift; break;;
+  -*) usage_error "invalid option: '$1'";;
+  esac
+  shift
+done
+
+if test $color_tests = yes; then
+  # Keep this in sync with 'lib/am/check.am:$(am__tty_colors)'.
+  red='' # Red.
+  grn='' # Green.
+  lgn='' # Light green.
+  blu='' # Blue.
+  mgn='' # Magenta.
+  std=''     # No color.
+else
+  red= grn= lgn= blu= mgn= std=
+fi
+
+do_exit='rm -f $log_file $trs_file; (exit $st); exit $st'
+trap "st=129; $do_exit" 1
+trap "st=130; $do_exit" 2
+trap "st=141; $do_exit" 13
+trap "st=143; $do_exit" 15
+
+# Test script is run here.
+"$@" >$log_file 2>&1
+estatus=$?
+if test $enable_hard_errors = no && test $estatus -eq 99; then
+  estatus=1
+fi
+
+case $estatus:$expect_failure in
+  0:yes) col=$red res=XPASS recheck=yes gcopy=yes;;
+  0:*)   col=$grn res=PASS  recheck=no  gcopy=no;;
+  77:*)  col=$blu res=SKIP  recheck=no  gcopy=yes;;
+  99:*)  col=$mgn res=ERROR recheck=yes gcopy=yes;;
+  *:yes) col=$lgn res=XFAIL recheck=no  gcopy=yes;;
+  *:*)   col=$red res=FAIL  recheck=yes gcopy=yes;;
+esac
+
+# Report outcome to console.
+echo "${col}${res}${std}: $test_name"
+
+# Register the test result, and other relevant metadata.
+echo ":test-result: $res" > $trs_file
+echo ":global-test-result: $res" >> $trs_file
+echo ":recheck: $recheck" >> $trs_file
+echo ":copy-in-global-log: $gcopy" >> $trs_file
+
+# Local Variables:
+# mode: shell-script
+# sh-indentation: 2
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
+# End:
diff --git a/hdrl/config.h.in b/hdrl/config.h.in
new file mode 100644
index 0000000..c49ba93
--- /dev/null
+++ b/hdrl/config.h.in
@@ -0,0 +1,124 @@
+/* config.h.in.  Generated from configure.ac by autoheader.  */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#undef HAVE_DLFCN_H
+
+/* Define to 1 if you have the `floor' function. */
+#undef HAVE_FLOOR
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#undef HAVE_INTTYPES_H
+
+/* Define to 1 if you have the <memory.h> header file. */
+#undef HAVE_MEMORY_H
+
+/* Define to 1 if you have the `pow' function. */
+#undef HAVE_POW
+
+/* Define to 1 if you have the `sqrt' function. */
+#undef HAVE_SQRT
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#undef HAVE_STDINT_H
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#undef HAVE_STDLIB_H
+
+/* Define if you have the `strdup' function */
+#undef HAVE_STRDUP
+
+/* Define to 1 if you have the <strings.h> header file. */
+#undef HAVE_STRINGS_H
+
+/* Define to 1 if you have the <string.h> header file. */
+#undef HAVE_STRING_H
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#undef HAVE_SYS_STAT_H
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#undef HAVE_SYS_TYPES_H
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#undef HAVE_UNISTD_H
+
+/* HDRL binary age */
+#undef HDRL_BINARY_AGE
+
+/* HDRL binary version number */
+#undef HDRL_BINARY_VERSION
+
+/* HDRL interface age */
+#undef HDRL_INTERFACE_AGE
+
+/* HDRL major version number */
+#undef HDRL_MAJOR_VERSION
+
+/* HDRL micro version number */
+#undef HDRL_MICRO_VERSION
+
+/* HDRL minor version number */
+#undef HDRL_MINOR_VERSION
+
+/* Define to the sub-directory in which libtool stores uninstalled libraries.
+   */
+#undef LT_OBJDIR
+
+/* Define to 1 if your C compiler doesn't accept -c and -o together. */
+#undef NO_MINUS_C_MINUS_O
+
+/* Name of package */
+#undef PACKAGE
+
+/* Define to the address where bug reports for this package should be sent. */
+#undef PACKAGE_BUGREPORT
+
+/* Define to the full name of this package. */
+#undef PACKAGE_NAME
+
+/* Define to the full name and version of this package. */
+#undef PACKAGE_STRING
+
+/* Define to the one symbol short name of this package. */
+#undef PACKAGE_TARNAME
+
+/* Define to the home page for this package. */
+#undef PACKAGE_URL
+
+/* Define to the version of this package. */
+#undef PACKAGE_VERSION
+
+/* Define to 1 if you have the ANSI C header files. */
+#undef STDC_HEADERS
+
+/* Version number of package */
+#undef VERSION
+
+/* Define if using the dmalloc debugging malloc package */
+#undef WITH_DMALLOC
+
+/* Enable large inode numbers on Mac OS X 10.5.  */
+#ifndef _DARWIN_USE_64_BIT_INODE
+# define _DARWIN_USE_64_BIT_INODE 1
+#endif
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+#undef _FILE_OFFSET_BITS
+
+/* Define for large files, on AIX-style hosts. */
+#undef _LARGE_FILES
+
+/* Define to empty if `const' does not conform to ANSI C. */
+#undef const
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+   calls it, or to nothing if 'inline' is not supported under any name.  */
+#ifndef __cplusplus
+#undef inline
+#endif
+
+
+#ifndef HAVE_STRDUP
+#  define strdup  cx_strdup
+#endif
+              
diff --git a/configure b/hdrl/configure
similarity index 90%
copy from configure
copy to hdrl/configure
index f0ce6ce..c0b07ee 100755
--- a/configure
+++ b/hdrl/configure
@@ -1,6 +1,6 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for X-shooter Instrument Pipeline 2.5.2.
+# Generated by GNU Autoconf 2.69 for HDRL Pipeline 0.1.5.
 #
 # Report bugs to <usd-help at eso.org>.
 #
@@ -588,15 +588,14 @@ MFLAGS=
 MAKEFLAGS=
 
 # Identity of this package.
-PACKAGE_NAME='X-shooter Instrument Pipeline'
-PACKAGE_TARNAME='xshoo'
-PACKAGE_VERSION='2.5.2'
-PACKAGE_STRING='X-shooter Instrument Pipeline 2.5.2'
+PACKAGE_NAME='HDRL Pipeline'
+PACKAGE_TARNAME='hdrl'
+PACKAGE_VERSION='0.1.5'
+PACKAGE_STRING='HDRL Pipeline 0.1.5'
 PACKAGE_BUGREPORT='usd-help at eso.org'
 PACKAGE_URL=''
 
 ac_unique_file="Makefile.am"
-ac_default_prefix=${PIPE_HOME:-/usr/local}
 # Factoring default headers for most tests.
 ac_includes_default="\
 #include <stdio.h>
@@ -637,23 +636,11 @@ ac_subst_vars='am__EXEEXT_FALSE
 am__EXEEXT_TRUE
 LTLIBOBJS
 LIBOBJS
-PURIFY_FALSE
-PURIFY_TRUE
-PURIFY_CMD
 all_ldflags
 all_includes
-IRPLIB_CPPFLAGS
-LIBIRPLIB
-LIBXSH
-XSH_LDFLAGS
-XSH_INCLUDES
-testsdir
-wkfcopydir
-wkfextradir
-configdir
-pipedocsdir
-privatelibdir
-plugindir
+LIBHDRL
+HDRL_LDFLAGS
+HDRL_INCLUDES
 CPL_LDFLAGS
 CPL_INCLUDES
 LIBCPLDFS
@@ -663,19 +650,7 @@ LIBCPLCORE
 LIBCEXT
 CX_LDFLAGS
 CX_INCLUDES
-LIBCFITSIO
-CFITSIO_LDFLAGS
-CFITSIO_INCLUDES
-LIBPTHREAD
-PTHREAD_CFLAGS
-LIBLAPACK
-LAPACK_LDFLAGS
-LAPACK_INCLUDES
-GSL_LIBS
-GSL_LDFLAGS
-GSL_INCLUDES
 LIBTOOL_DEPS
-CPP
 OTOOL64
 OTOOL
 LIPO
@@ -696,10 +671,16 @@ SED
 LIBTOOL
 LATEX
 DOXYGEN
+VLTSW_FALSE
+VLTSW_TRUE
 EGREP
 GREP
 ESO_DEBUG_FLAGS
+PURIFY_FALSE
+PURIFY_TRUE
+PURIFY_CMD
 LN_S
+CPP
 am__fastdepCC_FALSE
 am__fastdepCC_TRUE
 CCDEPMODE
@@ -720,13 +701,13 @@ CC
 LT_AGE
 LT_REVISION
 LT_CURRENT
-XSH_BINARY_AGE
-XSH_BINARY_VERSION
-XSH_INTERFACE_AGE
-XSH_MICRO_VERSION
-XSH_MINOR_VERSION
-XSH_MAJOR_VERSION
-XSH_VERSION
+HDRL_BINARY_AGE
+HDRL_BINARY_VERSION
+HDRL_INTERFACE_AGE
+HDRL_MICRO_VERSION
+HDRL_MINOR_VERSION
+HDRL_MAJOR_VERSION
+HDRL_VERSION
 MAINT
 MAINTAINER_MODE_FALSE
 MAINTAINER_MODE_TRUE
@@ -813,8 +794,12 @@ enable_option_checking
 enable_silent_rules
 enable_maintainer_mode
 enable_dependency_tracking
+enable_largefile
+enable_purify
 enable_debug
 enable_strict
+enable_openmp
+enable_standalone
 enable_static
 enable_shared
 with_pic
@@ -822,18 +807,6 @@ enable_fast_install
 with_gnu_ld
 with_sysroot
 enable_libtool_lock
-with_gsl
-with_gsl_includes
-with_gsl_libs
-enable_gsl_test
-with_lapack
-with_lapack_includes
-with_lapack_libs
-enable_lapack_test
-with_cfitsio
-with_cfitsio_includes
-with_cfitsio_libs
-enable_cfitsio_test
 with_cpl
 with_cpl_includes
 with_cpl_libs
@@ -842,10 +815,6 @@ with_cext
 with_cext_includes
 with_cext_libs
 enable_cext_test
-with_extra_includes
-with_extra_libs
-enable_purify
-enable_profile
 with_dmalloc
 '
       ac_precious_vars='build_alias
@@ -856,9 +825,9 @@ CFLAGS
 LDFLAGS
 LIBS
 CPPFLAGS
+CPP
 DOXYGEN
-LATEX
-CPP'
+LATEX'
 
 
 # Initialize some variables set by options.
@@ -1399,7 +1368,7 @@ if test "$ac_init_help" = "long"; then
   # Omit some internal or obsolete options to make the list less imposing.
   # This message is too long to be a string in the A/UX 3.1 sh.
   cat <<_ACEOF
-\`configure' configures X-shooter Instrument Pipeline 2.5.2 to adapt to many kinds of systems.
+\`configure' configures HDRL Pipeline 0.1.5 to adapt to many kinds of systems.
 
 Usage: $0 [OPTION]... [VAR=VALUE]...
 
@@ -1447,7 +1416,7 @@ Fine tuning of the installation directories:
   --infodir=DIR           info documentation [DATAROOTDIR/info]
   --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]
   --mandir=DIR            man documentation [DATAROOTDIR/man]
-  --docdir=DIR            documentation root [DATAROOTDIR/doc/xshoo]
+  --docdir=DIR            documentation root [DATAROOTDIR/doc/hdrl]
   --htmldir=DIR           html documentation [DOCDIR]
   --dvidir=DIR            dvi documentation [DOCDIR]
   --pdfdir=DIR            pdf documentation [DOCDIR]
@@ -1470,7 +1439,7 @@ fi
 
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of X-shooter Instrument Pipeline 2.5.2:";;
+     short | recursive ) echo "Configuration of HDRL Pipeline 0.1.5:";;
    esac
   cat <<\_ACEOF
 
@@ -1487,22 +1456,22 @@ Optional Features:
                           do not reject slow dependency extractors
   --disable-dependency-tracking
                           speeds up one-time build
+  --disable-largefile     omit support for large files
+  --disable-purify        disalbes the check for the PURIFY installation
   --enable-debug          creates debugging code [[default=no]]
   --enable-strict         compiles with strict compiler options (may not
                           work!) [[default=no]]
+  --enable-openmp         compiles with openmp compiler options (may not
+                          work!) [[default=yes]]
+  --enable-standalone     enable standalone installation for VLTSW
+                          [[default=no]]
   --enable-static[=PKGS]  build static libraries [default=no]
   --enable-shared[=PKGS]  build shared libraries [default=yes]
   --enable-fast-install[=PKGS]
                           optimize for fast installation [default=yes]
   --disable-libtool-lock  avoid locking (might break parallel builds)
-  --disable-gsl-test      disables checks for the GSL library and headers
-  --disable-lapack-test   disables checks for the lapack library and headers
-  --disable-cfitsio-test  disables checks for the cfitsio library and headers
   --disable-cpl-test      disables checks for the CPL library and headers
   --disable-cext-test     disables checks for the libcext library and headers
-  --disable-purify        disables the check for the PURIFY installation
-  --enable-profile        compiles with compiler options necessary for
-                          profiling (may not work!) [[default=no]]
 
 Optional Packages:
   --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
@@ -1512,24 +1481,12 @@ Optional Packages:
   --with-gnu-ld           assume the C compiler uses GNU ld [default=no]
   --with-sysroot=DIR Search for dependent libraries within DIR
                         (or the compiler's sysroot if not specified).
-  --with-gsl              location where GSL is installed
-  --with-gsl-includes     location of the GSL header files
-  --with-gsl-libs         location of the GSL library
-  --with-lapack           location where lapack is installed
-  --with-lapack-includes  location of the lapack header files
-  --with-lapack-libs      location of the lapack library
-  --with-cfitsio          location where cfitsio is installed
-  --with-cfitsio-includes location of the cfitsio header files
-  --with-cfitsio-libs     location of the cfitsio library
   --with-cpl              location where CPL is installed
   --with-cpl-includes     location of the CPL header files
   --with-cpl-libs         location of the CPL library
   --with-cext             location where libcext is installed
   --with-cext-includes    location of the libcext header files
   --with-cext-libs        location of the libcext library
-  --with-extra-includes=DIR
-                          adds non standard include paths
-  --with-extra-libs=DIR   adds non standard library paths
   --with-dmalloc          use dmalloc, as in http://www.dmalloc.com
 
 Some influential environment variables:
@@ -1540,9 +1497,9 @@ Some influential environment variables:
   LIBS        libraries to pass to the linker, e.g. -l<library>
   CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
               you have headers in a nonstandard directory <include dir>
+  CPP         C preprocessor
   DOXYGEN     doxygen command
   LATEX       latex command
-  CPP         C preprocessor
 
 Use these variables to override the choices made by `configure' or to help
 it to find libraries and programs with nonstandard names/locations.
@@ -1610,7 +1567,7 @@ fi
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-X-shooter Instrument Pipeline configure 2.5.2
+HDRL Pipeline configure 0.1.5
 generated by GNU Autoconf 2.69
 
 Copyright (C) 2012 Free Software Foundation, Inc.
@@ -1662,6 +1619,43 @@ fi
 
 } # ac_fn_c_try_compile
 
+# ac_fn_c_try_cpp LINENO
+# ----------------------
+# Try to preprocess conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_cpp ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if { { ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } > conftest.i && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+    ac_retval=1
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_cpp
+
 # ac_fn_c_try_link LINENO
 # -----------------------
 # Try to link conftest.$ac_ext, and return whether this succeeded.
@@ -1739,43 +1733,6 @@ $as_echo "$ac_res" >&6; }
 
 } # ac_fn_c_check_header_compile
 
-# ac_fn_c_try_cpp LINENO
-# ----------------------
-# Try to preprocess conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_cpp ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if { { ac_try="$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
-  ac_status=$?
-  if test -s conftest.err; then
-    grep -v '^ *+' conftest.err >conftest.er1
-    cat conftest.er1 >&5
-    mv -f conftest.er1 conftest.err
-  fi
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } > conftest.i && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then :
-  ac_retval=0
-else
-  $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-    ac_retval=1
-fi
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-  as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_cpp
-
 # ac_fn_c_try_run LINENO
 # ----------------------
 # Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
@@ -2025,7 +1982,7 @@ cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
-It was created by X-shooter Instrument Pipeline $as_me 2.5.2, which was
+It was created by HDRL Pipeline $as_me 0.1.5, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   $ $0 $@
@@ -2376,10 +2333,6 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
 
-
-
-
-
 ac_aux_dir=
 for ac_dir in admin "$srcdir"/admin; do
   if test -f "$ac_dir/install-sh"; then
@@ -2410,6 +2363,7 @@ ac_configure="$SHELL $ac_aux_dir/configure"  # Please don't use this var.
 
 
 
+
 # Make sure we can run config.sub.
 $SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 ||
   as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5
@@ -3006,8 +2960,8 @@ fi
 
 
 # Define the identity of the package.
- PACKAGE='xshoo'
- VERSION='2.5.2'
+ PACKAGE='hdrl'
+ VERSION='0.1.5'
 
 
 cat >>confdefs.h <<_ACEOF
@@ -3061,13 +3015,6 @@ am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'
 ac_config_headers="$ac_config_headers config.h"
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
-$as_echo "" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: *********** Configuring:  $PACKAGE $VERSION **********" >&5
-$as_echo "*********** Configuring:  $PACKAGE $VERSION **********" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
-$as_echo "" >&6; }
-
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable maintainer-specific portions of Makefiles" >&5
 $as_echo_n "checking whether to enable maintainer-specific portions of Makefiles... " >&6; }
@@ -3092,22 +3039,6 @@ fi
 
 
 
-
-    unset CDPATH
-    # make $PIPE_HOME the default for the installation
-
-
-    if test "x$prefix" = "xNONE"; then
-        prefix=$ac_default_prefix
-        ac_configure_args="$ac_configure_args --prefix $prefix"
-    fi
-
-    if test "x$exec_prefix" = "xNONE"; then
-        exec_prefix=$prefix
-    fi
-
-
-
 # Immediately before every release do:
 #-------------------------------------
 #   if (the interface is totally unchanged from previous release)
@@ -3122,37 +3053,38 @@ fi
 #           AGE = 0;
 #   }
 
+# Order of arguments: VERSION, CURRENT, REVISION, AGE
 
-    xsh_version=`echo "$VERSION" | sed -e 's/[a-z,A-Z].*$//'`
+    hdrldemo_version=`echo "$VERSION" | sed -e 's/[a-z,A-Z].*$//'`
 
-    xsh_major_version=`echo "$xsh_version" | \
+    hdrldemo_major_version=`echo "$hdrldemo_version" | \
         sed 's/\([0-9]*\).\(.*\)/\1/'`
-    xsh_minor_version=`echo "$xsh_version" | \
+    hdrldemo_minor_version=`echo "$hdrldemo_version" | \
         sed 's/\([0-9]*\).\([0-9]*\)\(.*\)/\2/'`
-    xsh_micro_version=`echo "$xsh_version" | \
+    hdrldemo_micro_version=`echo "$hdrldemo_version" | \
         sed 's/\([0-9]*\).\([0-9]*\).\([0-9]*\)/\3/'`
 
-    if test -z "$xsh_major_version"; then xsh_major_version=0
+    if test -z "$hdrldemo_major_version"; then hdrldemo_major_version=0
     fi
 
-    if test -z "$xsh_minor_version"; then xsh_minor_version=0
+    if test -z "$hdrldemo_minor_version"; then hdrldemo_minor_version=0
     fi
 
-    if test -z "$xsh_micro_version"; then xsh_micro_version=0
+    if test -z "$hdrldemo_micro_version"; then hdrldemo_micro_version=0
     fi
 
-    XSH_VERSION="$xsh_version"
-    XSH_MAJOR_VERSION=$xsh_major_version
-    XSH_MINOR_VERSION=$xsh_minor_version
-    XSH_MICRO_VERSION=$xsh_micro_version
+    HDRL_VERSION="$hdrldemo_version"
+    HDRL_MAJOR_VERSION=$hdrldemo_major_version
+    HDRL_MINOR_VERSION=$hdrldemo_minor_version
+    HDRL_MICRO_VERSION=$hdrldemo_micro_version
 
-    if test -z ""; then XSH_INTERFACE_AGE=0
-    else XSH_INTERFACE_AGE=""
+    if test -z "0"; then HDRL_INTERFACE_AGE=0
+    else HDRL_INTERFACE_AGE="0"
     fi
 
-    XSH_BINARY_AGE=`expr 100 '*' $XSH_MINOR_VERSION + $XSH_MICRO_VERSION`
-    XSH_BINARY_VERSION=`expr 10000 '*' $XSH_MAJOR_VERSION + \
-                          $XSH_BINARY_AGE`
+    HDRL_BINARY_AGE=`expr 100 '*' $HDRL_MINOR_VERSION + $HDRL_MICRO_VERSION`
+    HDRL_BINARY_VERSION=`expr 10000 '*' $HDRL_MAJOR_VERSION + \
+                          $HDRL_BINARY_AGE`
 
 
 
@@ -3164,53 +3096,53 @@ fi
 
 
 cat >>confdefs.h <<_ACEOF
-#define XSH_MAJOR_VERSION $XSH_MAJOR_VERSION
+#define HDRL_MAJOR_VERSION $HDRL_MAJOR_VERSION
 _ACEOF
 
 
 cat >>confdefs.h <<_ACEOF
-#define XSH_MINOR_VERSION $XSH_MINOR_VERSION
+#define HDRL_MINOR_VERSION $HDRL_MINOR_VERSION
 _ACEOF
 
 
 cat >>confdefs.h <<_ACEOF
-#define XSH_MICRO_VERSION $XSH_MICRO_VERSION
+#define HDRL_MICRO_VERSION $HDRL_MICRO_VERSION
 _ACEOF
 
 
 cat >>confdefs.h <<_ACEOF
-#define XSH_INTERFACE_AGE $XSH_INTERFACE_AGE
+#define HDRL_INTERFACE_AGE $HDRL_INTERFACE_AGE
 _ACEOF
 
 
 cat >>confdefs.h <<_ACEOF
-#define XSH_BINARY_VERSION $XSH_BINARY_VERSION
+#define HDRL_BINARY_VERSION $HDRL_BINARY_VERSION
 _ACEOF
 
 
 cat >>confdefs.h <<_ACEOF
-#define XSH_BINARY_AGE $XSH_BINARY_AGE
+#define HDRL_BINARY_AGE $HDRL_BINARY_AGE
 _ACEOF
 
 
 
 
-    if test -z ""; then
+    if test -z "0"; then
         LT_CURRENT=0
     else
-        LT_CURRENT=""
+        LT_CURRENT="0"
     fi
 
-    if test -z ""; then
+    if test -z "0"; then
         LT_REVISION=0
     else
-        LT_REVISION=""
+        LT_REVISION="0"
     fi
 
-    if test -z ""; then
+    if test -z "0"; then
         LT_AGE=0
     else
-        LT_AGE=""
+        LT_AGE="0"
     fi
 
 
@@ -3220,12 +3152,6 @@ _ACEOF
 
 
 # Checks for programs.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
-$as_echo "" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: *********** Checking programs ************************" >&5
-$as_echo "*********** Checking programs ************************" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
-$as_echo "" >&6; }
 ac_ext=c
 ac_cpp='$CPP $CPPFLAGS'
 ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
@@ -4206,6 +4132,143 @@ else
 fi
 
 
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
+$as_echo_n "checking how to run the C preprocessor... " >&6; }
+# On Suns, sometimes $CPP names a directory.
+if test -n "$CPP" && test -d "$CPP"; then
+  CPP=
+fi
+if test -z "$CPP"; then
+  if ${ac_cv_prog_CPP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+      # Double quotes because CPP needs to be expanded
+    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
+    do
+      ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+
+else
+  # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  # Broken: success on invalid input.
+continue
+else
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.i conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then :
+  break
+fi
+
+    done
+    ac_cv_prog_CPP=$CPP
+
+fi
+  CPP=$ac_cv_prog_CPP
+else
+  ac_cv_prog_CPP=$CPP
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
+$as_echo "$CPP" >&6; }
+ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+
+else
+  # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  # Broken: success on invalid input.
+continue
+else
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.i conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then :
+
+else
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
+See \`config.log' for more details" "$LINENO" 5; }
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
 if test "x$CC" != xcc; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC and cc understand -c and -o together" >&5
 $as_echo_n "checking whether $CC and cc understand -c and -o together... " >&6; }
@@ -4344,27 +4407,304 @@ $as_echo "no, using $LN_S" >&6; }
 fi
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: *********** Checking ESO *****************************" >&5
-$as_echo "*********** Checking ESO *****************************" >&6; }
-
 
-
-    # Check whether --enable-debug was given.
-if test "${enable_debug+set}" = set; then :
-  enableval=$enable_debug; eso_enable_debug=$enableval
-else
-  eso_enable_debug=no
+# Check whether --enable-largefile was given.
+if test "${enable_largefile+set}" = set; then :
+  enableval=$enable_largefile;
 fi
 
+if test "$enable_largefile" != no; then
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether debugging code should be created" >&5
-$as_echo_n "checking whether debugging code should be created... " >&6; }
-if ${eso_cv_enable_debug+:} false; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for special C compiler options needed for large files" >&5
+$as_echo_n "checking for special C compiler options needed for large files... " >&6; }
+if ${ac_cv_sys_largefile_CC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  eso_cv_enable_debug=$eso_enable_debug
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $eso_cv_enable_debug" >&5
+  ac_cv_sys_largefile_CC=no
+     if test "$GCC" != yes; then
+       ac_save_CC=$CC
+       while :; do
+	 # IRIX 6.2 and later do not support large files by default,
+	 # so use the C compiler's -n32 option if that helps.
+	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+ /* Check that off_t can represent 2**63 - 1 correctly.
+    We can't simply define LARGE_OFF_T to be 9223372036854775807,
+    since some C++ compilers masquerading as C compilers
+    incorrectly reject 9223372036854775807.  */
+#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
+		       && LARGE_OFF_T % 2147483647 == 1)
+		      ? 1 : -1];
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+	 if ac_fn_c_try_compile "$LINENO"; then :
+  break
+fi
+rm -f core conftest.err conftest.$ac_objext
+	 CC="$CC -n32"
+	 if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_sys_largefile_CC=' -n32'; break
+fi
+rm -f core conftest.err conftest.$ac_objext
+	 break
+       done
+       CC=$ac_save_CC
+       rm -f conftest.$ac_ext
+    fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_largefile_CC" >&5
+$as_echo "$ac_cv_sys_largefile_CC" >&6; }
+  if test "$ac_cv_sys_largefile_CC" != no; then
+    CC=$CC$ac_cv_sys_largefile_CC
+  fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _FILE_OFFSET_BITS value needed for large files" >&5
+$as_echo_n "checking for _FILE_OFFSET_BITS value needed for large files... " >&6; }
+if ${ac_cv_sys_file_offset_bits+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  while :; do
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+ /* Check that off_t can represent 2**63 - 1 correctly.
+    We can't simply define LARGE_OFF_T to be 9223372036854775807,
+    since some C++ compilers masquerading as C compilers
+    incorrectly reject 9223372036854775807.  */
+#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
+		       && LARGE_OFF_T % 2147483647 == 1)
+		      ? 1 : -1];
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_sys_file_offset_bits=no; break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#define _FILE_OFFSET_BITS 64
+#include <sys/types.h>
+ /* Check that off_t can represent 2**63 - 1 correctly.
+    We can't simply define LARGE_OFF_T to be 9223372036854775807,
+    since some C++ compilers masquerading as C compilers
+    incorrectly reject 9223372036854775807.  */
+#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
+		       && LARGE_OFF_T % 2147483647 == 1)
+		      ? 1 : -1];
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_sys_file_offset_bits=64; break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  ac_cv_sys_file_offset_bits=unknown
+  break
+done
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_file_offset_bits" >&5
+$as_echo "$ac_cv_sys_file_offset_bits" >&6; }
+case $ac_cv_sys_file_offset_bits in #(
+  no | unknown) ;;
+  *)
+cat >>confdefs.h <<_ACEOF
+#define _FILE_OFFSET_BITS $ac_cv_sys_file_offset_bits
+_ACEOF
+;;
+esac
+rm -rf conftest*
+  if test $ac_cv_sys_file_offset_bits = unknown; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _LARGE_FILES value needed for large files" >&5
+$as_echo_n "checking for _LARGE_FILES value needed for large files... " >&6; }
+if ${ac_cv_sys_large_files+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  while :; do
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+ /* Check that off_t can represent 2**63 - 1 correctly.
+    We can't simply define LARGE_OFF_T to be 9223372036854775807,
+    since some C++ compilers masquerading as C compilers
+    incorrectly reject 9223372036854775807.  */
+#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
+		       && LARGE_OFF_T % 2147483647 == 1)
+		      ? 1 : -1];
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_sys_large_files=no; break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#define _LARGE_FILES 1
+#include <sys/types.h>
+ /* Check that off_t can represent 2**63 - 1 correctly.
+    We can't simply define LARGE_OFF_T to be 9223372036854775807,
+    since some C++ compilers masquerading as C compilers
+    incorrectly reject 9223372036854775807.  */
+#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
+		       && LARGE_OFF_T % 2147483647 == 1)
+		      ? 1 : -1];
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_sys_large_files=1; break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  ac_cv_sys_large_files=unknown
+  break
+done
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_large_files" >&5
+$as_echo "$ac_cv_sys_large_files" >&6; }
+case $ac_cv_sys_large_files in #(
+  no | unknown) ;;
+  *)
+cat >>confdefs.h <<_ACEOF
+#define _LARGE_FILES $ac_cv_sys_large_files
+_ACEOF
+;;
+esac
+rm -rf conftest*
+  fi
+
+
+fi
+
+
+#
+# Check for purify
+#
+
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for PURIFY" >&5
+$as_echo_n "checking for PURIFY... " >&6; }
+
+    # Check whether --enable-purify was given.
+if test "${enable_purify+set}" = set; then :
+  enableval=$enable_purify; enable_purify=$enableval
+else
+  enable_purify=yes
+fi
+
+
+    if test "x$enable_purify" = xyes ; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: enabled" >&5
+$as_echo "enabled" >&6; }
+      # Extract the first word of "purify", so it can be a program name with args.
+set dummy purify; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_PURIFY_CMD+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$PURIFY_CMD"; then
+  ac_cv_prog_PURIFY_CMD="$PURIFY_CMD" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_PURIFY_CMD="purify"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  test -z "$ac_cv_prog_PURIFY_CMD" && ac_cv_prog_PURIFY_CMD="NONE"
+fi
+fi
+PURIFY_CMD=$ac_cv_prog_PURIFY_CMD
+if test -n "$PURIFY_CMD"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PURIFY_CMD" >&5
+$as_echo "$PURIFY_CMD" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+      if test "$PURIFY_CMD" = "NONE" ; then
+        { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Disabling purify support" >&5
+$as_echo "$as_me: WARNING: Disabling purify support" >&2;}
+        enable_purify=no
+      fi
+    else
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5
+$as_echo "disabled" >&6; }
+    fi
+
+     if test "x$enable_purify" = "xyes"; then
+  PURIFY_TRUE=
+  PURIFY_FALSE='#'
+else
+  PURIFY_TRUE='#'
+  PURIFY_FALSE=
+fi
+
+
+
+
+
+
+    # Check whether --enable-debug was given.
+if test "${enable_debug+set}" = set; then :
+  enableval=$enable_debug; eso_enable_debug=$enableval
+else
+  eso_enable_debug=no
+fi
+
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether debugging code should be created" >&5
+$as_echo_n "checking whether debugging code should be created... " >&6; }
+if ${eso_cv_enable_debug+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  eso_cv_enable_debug=$eso_enable_debug
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $eso_cv_enable_debug" >&5
 $as_echo "$eso_cv_enable_debug" >&6; }
 
     if test x"$eso_cv_enable_debug" = xyes; then
@@ -4964,12 +5304,13 @@ $as_echo "$ac_res" >&6; }
 
     fi
 
+#ESO_PROG_CC_FLAG([fno-builtin], [CFLAGS="$CFLAGS -fno-builtin"])
 
 
 
-    flag=`echo fno-builtin | sed 'y%.=/+-%___p_%'`
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -fno-builtin" >&5
-$as_echo_n "checking whether $CC supports -fno-builtin... " >&6; }
+    flag=`echo std=c99 | sed 'y%.=/+-%___p_%'`
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -std=c99" >&5
+$as_echo_n "checking whether $CC supports -std=c99... " >&6; }
 if eval \${eso_cv_prog_cc_$flag+:} false; then :
   $as_echo_n "(cached) " >&6
 else
@@ -4984,9 +5325,9 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
                        echo 'int main() { return 0; }' >conftest.$ac_ext
 
-                       try_compile="`$CC -fno-builtin -c conftest.$ac_ext 2>&1`"
+                       try_compile="`$CC -std=c99 -c conftest.$ac_ext 2>&1`"
                        if test -z "$try_compile"; then
-                           try_link="`$CC -fno-builtin -o conftest$ac_exeext \
+                           try_link="`$CC -std=c99 -o conftest$ac_exeext \
                                     conftest.$ac_ext 2>&1`"
                            if test -z "$try_link"; then
                                eval "eso_cv_prog_cc_$flag=yes"
@@ -5008,7 +5349,7 @@ $as_echo "$ac_res" >&6; }
 
     if eval "test \"`echo '$eso_cv_prog_cc_'$flag`\" = yes"; then
         :
-        CFLAGS="$CFLAGS -fno-builtin"
+        CFLAGS="$CFLAGS -std=c99"
     else
         :
 
@@ -5058,429 +5399,460 @@ $as_echo "$ac_res" >&6; }
 
     if eval "test \"`echo '$eso_cv_prog_cc_'$flag`\" = yes"; then
         :
-        CFLAGS="$CFLAGS -Wall"
+        CFLAGS="-Wall $CFLAGS"
     else
         :
 
     fi
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: *********** Checking doc *****************************" >&5
-$as_echo "*********** Checking doc *****************************" >&6; }
 
 
-    # Extract the first word of "doxygen", so it can be a program name with args.
-set dummy doxygen; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_DOXYGEN+:} false; then :
+    flag=`echo fvisibility=hidden | sed 'y%.=/+-%___p_%'`
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -fvisibility=hidden" >&5
+$as_echo_n "checking whether $CC supports -fvisibility=hidden... " >&6; }
+if eval \${eso_cv_prog_cc_$flag+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  case $DOXYGEN in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_DOXYGEN="$DOXYGEN" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_DOXYGEN="$as_dir/$ac_word$ac_exec_ext"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
 
-  ;;
-esac
-fi
-DOXYGEN=$ac_cv_path_DOXYGEN
-if test -n "$DOXYGEN"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DOXYGEN" >&5
-$as_echo "$DOXYGEN" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
+                       eval "eso_cv_prog_cc_$flag=no"
+                       ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
+                       echo 'int main() { return 0; }' >conftest.$ac_ext
 
+                       try_compile="`$CC -fvisibility=hidden -c conftest.$ac_ext 2>&1`"
+                       if test -z "$try_compile"; then
+                           try_link="`$CC -fvisibility=hidden -o conftest$ac_exeext \
+                                    conftest.$ac_ext 2>&1`"
+                           if test -z "$try_link"; then
+                               eval "eso_cv_prog_cc_$flag=yes"
+                           fi
+                       fi
+                       rm -f conftest*
 
-    # Extract the first word of "latex", so it can be a program name with args.
-set dummy latex; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_LATEX+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $LATEX in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_LATEX="$LATEX" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_LATEX="$as_dir/$ac_word$ac_exec_ext"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  ;;
-esac
-fi
-LATEX=$ac_cv_path_LATEX
-if test -n "$LATEX"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LATEX" >&5
-$as_echo "$LATEX" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
+                       ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
+fi
+eval ac_res=\$eso_cv_prog_cc_$flag
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
 
+    if eval "test \"`echo '$eso_cv_prog_cc_'$flag`\" = yes"; then
+        :
+        CFLAGS="-fvisibility=hidden $CFLAGS"
+    else
+        :
 
-    if test -z "${DOXYGEN}"; then
-        DOXYGEN=":"
     fi
 
-    if test -z "${LATEX}"; then
-        LATEX=":"
-    fi
 
 
 
-# Check whether --enable-static was given.
-if test "${enable_static+set}" = set; then :
-  enableval=$enable_static; p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_static=yes ;;
-    no) enable_static=no ;;
-    *)
-     enable_static=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_static=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac
+    flag=`echo Werror=implicit-function-declaration | sed 'y%.=/+-%___p_%'`
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -Werror=implicit-function-declaration" >&5
+$as_echo_n "checking whether $CC supports -Werror=implicit-function-declaration... " >&6; }
+if eval \${eso_cv_prog_cc_$flag+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  enable_static=no
-fi
 
+                       eval "eso_cv_prog_cc_$flag=no"
+                       ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
+                       echo 'int main() { return 0; }' >conftest.$ac_ext
 
+                       try_compile="`$CC -Werror=implicit-function-declaration -c conftest.$ac_ext 2>&1`"
+                       if test -z "$try_compile"; then
+                           try_link="`$CC -Werror=implicit-function-declaration -o conftest$ac_exeext \
+                                    conftest.$ac_ext 2>&1`"
+                           if test -z "$try_link"; then
+                               eval "eso_cv_prog_cc_$flag=yes"
+                           fi
+                       fi
+                       rm -f conftest*
 
+                       ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
+fi
+eval ac_res=\$eso_cv_prog_cc_$flag
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
 
+    if eval "test \"`echo '$eso_cv_prog_cc_'$flag`\" = yes"; then
+        :
+        CFLAGS="-Werror=implicit-function-declaration $CFLAGS"
+    else
+        :
 
-# Check whether --enable-shared was given.
-if test "${enable_shared+set}" = set; then :
-  enableval=$enable_shared; p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_shared=yes ;;
-    no) enable_shared=no ;;
-    *)
-      enable_shared=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_shared=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac
-else
-  enable_shared=yes
-fi
+    fi
 
 
+# simple openmp check, the one in eso.m4 is unnecessarily fragile
+# ESO_ENABLE_OPENMP(openmp=no)
+#-----------------------------
 
 
 
 
+    # Check whether --enable-openmp was given.
+if test "${enable_openmp+set}" = set; then :
+  enableval=$enable_openmp; eso_enable_openmp=$enableval
+else
+  eso_enable_openmp=yes
+fi
 
 
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether openmp compiler options should be used" >&5
+$as_echo_n "checking whether openmp compiler options should be used... " >&6; }
+if ${eso_cv_enable_openmp+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  eso_cv_enable_openmp=$eso_enable_openmp
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $eso_cv_enable_openmp" >&5
+$as_echo "$eso_cv_enable_openmp" >&6; }
 
 
-case `pwd` in
-  *\ * | *\	*)
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&5
-$as_echo "$as_me: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&2;} ;;
-esac
+    if test x"$eso_cv_enable_openmp" = xyes; then
 
 
 
-macro_version='2.4.2'
-macro_revision='1.3337'
+    flag=`echo fopenmp | sed 'y%.=/+-%___p_%'`
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -fopenmp" >&5
+$as_echo_n "checking whether $CC supports -fopenmp... " >&6; }
+if eval \${eso_cv_prog_cc_$flag+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
 
+                       eval "eso_cv_prog_cc_$flag=no"
+                       ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
+                       echo 'int main() { return 0; }' >conftest.$ac_ext
 
+                       try_compile="`$CC -fopenmp -c conftest.$ac_ext 2>&1`"
+                       if test -z "$try_compile"; then
+                           try_link="`$CC -fopenmp -o conftest$ac_exeext \
+                                    conftest.$ac_ext 2>&1`"
+                           if test -z "$try_link"; then
+                               eval "eso_cv_prog_cc_$flag=yes"
+                           fi
+                       fi
+                       rm -f conftest*
 
+                       ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
+fi
+eval ac_res=\$eso_cv_prog_cc_$flag
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
 
+    if eval "test \"`echo '$eso_cv_prog_cc_'$flag`\" = yes"; then
+        :
+        CFLAGS="$CFLAGS -fopenmp"
+                                     LDFLAGS="$LDFLAGS -fopenmp"
+    else
+        :
 
+    fi
 
 
 
 
-ltmain="$ac_aux_dir/ltmain.sh"
+    flag=`echo xopenmp | sed 'y%.=/+-%___p_%'`
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -xopenmp" >&5
+$as_echo_n "checking whether $CC supports -xopenmp... " >&6; }
+if eval \${eso_cv_prog_cc_$flag+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
 
-# Backslashify metacharacters that are still active within
-# double-quoted strings.
-sed_quote_subst='s/\(["`$\\]\)/\\\1/g'
+                       eval "eso_cv_prog_cc_$flag=no"
+                       ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
-# Same as above, but do not quote variable references.
-double_quote_subst='s/\(["`\\]\)/\\\1/g'
 
-# Sed substitution to delay expansion of an escaped shell variable in a
-# double_quote_subst'ed string.
-delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
+                       echo 'int main() { return 0; }' >conftest.$ac_ext
 
-# Sed substitution to delay expansion of an escaped single quote.
-delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g'
+                       try_compile="`$CC -xopenmp -c conftest.$ac_ext 2>&1`"
+                       if test -z "$try_compile"; then
+                           try_link="`$CC -xopenmp -o conftest$ac_exeext \
+                                    conftest.$ac_ext 2>&1`"
+                           if test -z "$try_link"; then
+                               eval "eso_cv_prog_cc_$flag=yes"
+                           fi
+                       fi
+                       rm -f conftest*
 
-# Sed substitution to avoid accidental globbing in evaled expressions
-no_glob_subst='s/\*/\\\*/g'
+                       ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
-ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
-ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to print strings" >&5
-$as_echo_n "checking how to print strings... " >&6; }
-# Test print first, because it will be a builtin if present.
-if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \
-   test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then
-  ECHO='print -r --'
-elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then
-  ECHO='printf %s\n'
-else
-  # Use this function as a fallback that always works.
-  func_fallback_echo ()
-  {
-    eval 'cat <<_LTECHO_EOF
-$1
-_LTECHO_EOF'
-  }
-  ECHO='func_fallback_echo'
 fi
+eval ac_res=\$eso_cv_prog_cc_$flag
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
 
-# func_echo_all arg...
-# Invoke $ECHO with all args, space-separated.
-func_echo_all ()
-{
-    $ECHO ""
-}
-
-case "$ECHO" in
-  printf*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: printf" >&5
-$as_echo "printf" >&6; } ;;
-  print*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: print -r" >&5
-$as_echo "print -r" >&6; } ;;
-  *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: cat" >&5
-$as_echo "cat" >&6; } ;;
-esac
+    if eval "test \"`echo '$eso_cv_prog_cc_'$flag`\" = yes"; then
+        :
+        CFLAGS="$CFLAGS -xopenmp"
+                                     LDFLAGS="$LDFLAGS -xopenmp"
+    else
+        :
 
+    fi
 
+    fi
 
 
 
 
 
+    # Check whether --enable-standalone was given.
+if test "${enable_standalone+set}" = set; then :
+  enableval=$enable_standalone; eso_enable_standalone=$enableval
+else
+  eso_enable_standalone=no
+fi
 
 
+     if test x"$eso_enable_standalone" = xyes; then
+  VLTSW_TRUE=
+  VLTSW_FALSE='#'
+else
+  VLTSW_TRUE='#'
+  VLTSW_FALSE=
+fi
 
 
 
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5
-$as_echo_n "checking for a sed that does not truncate output... " >&6; }
-if ${ac_cv_path_SED+:} false; then :
+    # Extract the first word of "doxygen", so it can be a program name with args.
+set dummy doxygen; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_DOXYGEN+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-            ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/
-     for ac_i in 1 2 3 4 5 6 7; do
-       ac_script="$ac_script$as_nl$ac_script"
-     done
-     echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed
-     { ac_script=; unset ac_script;}
-     if test -z "$SED"; then
-  ac_path_SED_found=false
-  # Loop through the user's path and test for each of PROGNAME-LIST
+  case $DOXYGEN in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_DOXYGEN="$DOXYGEN" # Let the user override the test with a path.
+  ;;
+  *)
   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-    for ac_prog in sed gsed; do
     for ac_exec_ext in '' $ac_executable_extensions; do
-      ac_path_SED="$as_dir/$ac_prog$ac_exec_ext"
-      as_fn_executable_p "$ac_path_SED" || continue
-# Check for GNU ac_path_SED and select it if it is found.
-  # Check for GNU $ac_path_SED
-case `"$ac_path_SED" --version 2>&1` in
-*GNU*)
-  ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;;
-*)
-  ac_count=0
-  $as_echo_n 0123456789 >"conftest.in"
-  while :
-  do
-    cat "conftest.in" "conftest.in" >"conftest.tmp"
-    mv "conftest.tmp" "conftest.in"
-    cp "conftest.in" "conftest.nl"
-    $as_echo '' >> "conftest.nl"
-    "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break
-    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
-    as_fn_arith $ac_count + 1 && ac_count=$as_val
-    if test $ac_count -gt ${ac_path_SED_max-0}; then
-      # Best one so far, save it but keep looking for a better one
-      ac_cv_path_SED="$ac_path_SED"
-      ac_path_SED_max=$ac_count
-    fi
-    # 10*(2^10) chars as input seems more than enough
-    test $ac_count -gt 10 && break
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_path_DOXYGEN="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
   done
-  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+IFS=$as_save_IFS
+
+  ;;
 esac
+fi
+DOXYGEN=$ac_cv_path_DOXYGEN
+if test -n "$DOXYGEN"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DOXYGEN" >&5
+$as_echo "$DOXYGEN" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
-      $ac_path_SED_found && break 3
-    done
-  done
+
+
+
+    # Extract the first word of "latex", so it can be a program name with args.
+set dummy latex; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_LATEX+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $LATEX in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_LATEX="$LATEX" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_path_LATEX="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
   done
 IFS=$as_save_IFS
-  if test -z "$ac_cv_path_SED"; then
-    as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5
-  fi
-else
-  ac_cv_path_SED=$SED
-fi
 
+  ;;
+esac
+fi
+LATEX=$ac_cv_path_LATEX
+if test -n "$LATEX"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LATEX" >&5
+$as_echo "$LATEX" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5
-$as_echo "$ac_cv_path_SED" >&6; }
- SED="$ac_cv_path_SED"
-  rm -f conftest.sed
 
-test -z "$SED" && SED=sed
-Xsed="$SED -e 1s/^X//"
 
 
 
+    if test -z "${DOXYGEN}"; then
+        DOXYGEN=":"
+    fi
 
+    if test -z "${LATEX}"; then
+        LATEX=":"
+    fi
 
 
+#
+# Check for purify
+#
 
 
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for PURIFY" >&5
+$as_echo_n "checking for PURIFY... " >&6; }
 
+    # Check whether --enable-purify was given.
+if test "${enable_purify+set}" = set; then :
+  enableval=$enable_purify; enable_purify=$enableval
+else
+  enable_purify=yes
+fi
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5
-$as_echo_n "checking for fgrep... " >&6; }
-if ${ac_cv_path_FGREP+:} false; then :
+    if test "x$enable_purify" = xyes ; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: enabled" >&5
+$as_echo "enabled" >&6; }
+      # Extract the first word of "purify", so it can be a program name with args.
+set dummy purify; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_PURIFY_CMD+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1
-   then ac_cv_path_FGREP="$GREP -F"
-   else
-     if test -z "$FGREP"; then
-  ac_path_FGREP_found=false
-  # Loop through the user's path and test for each of PROGNAME-LIST
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+  if test -n "$PURIFY_CMD"; then
+  ac_cv_prog_PURIFY_CMD="$PURIFY_CMD" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-    for ac_prog in fgrep; do
     for ac_exec_ext in '' $ac_executable_extensions; do
-      ac_path_FGREP="$as_dir/$ac_prog$ac_exec_ext"
-      as_fn_executable_p "$ac_path_FGREP" || continue
-# Check for GNU ac_path_FGREP and select it if it is found.
-  # Check for GNU $ac_path_FGREP
-case `"$ac_path_FGREP" --version 2>&1` in
-*GNU*)
-  ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;;
-*)
-  ac_count=0
-  $as_echo_n 0123456789 >"conftest.in"
-  while :
-  do
-    cat "conftest.in" "conftest.in" >"conftest.tmp"
-    mv "conftest.tmp" "conftest.in"
-    cp "conftest.in" "conftest.nl"
-    $as_echo 'FGREP' >> "conftest.nl"
-    "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || break
-    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
-    as_fn_arith $ac_count + 1 && ac_count=$as_val
-    if test $ac_count -gt ${ac_path_FGREP_max-0}; then
-      # Best one so far, save it but keep looking for a better one
-      ac_cv_path_FGREP="$ac_path_FGREP"
-      ac_path_FGREP_max=$ac_count
-    fi
-    # 10*(2^10) chars as input seems more than enough
-    test $ac_count -gt 10 && break
-  done
-  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
-esac
-
-      $ac_path_FGREP_found && break 3
-    done
-  done
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_PURIFY_CMD="purify"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
   done
 IFS=$as_save_IFS
-  if test -z "$ac_cv_path_FGREP"; then
-    as_fn_error $? "no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
-  fi
-else
-  ac_cv_path_FGREP=$FGREP
-fi
 
-   fi
+  test -z "$ac_cv_prog_PURIFY_CMD" && ac_cv_prog_PURIFY_CMD="NONE"
+fi
+fi
+PURIFY_CMD=$ac_cv_prog_PURIFY_CMD
+if test -n "$PURIFY_CMD"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PURIFY_CMD" >&5
+$as_echo "$PURIFY_CMD" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5
-$as_echo "$ac_cv_path_FGREP" >&6; }
- FGREP="$ac_cv_path_FGREP"
-
-
-test -z "$GREP" && GREP=grep
-
-
-
-
-
 
 
+      if test "$PURIFY_CMD" = "NONE" ; then
+        { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Disabling purify support" >&5
+$as_echo "$as_me: WARNING: Disabling purify support" >&2;}
+        enable_purify=no
+      fi
+    else
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5
+$as_echo "disabled" >&6; }
+    fi
 
+     if test "x$enable_purify" = "xyes"; then
+  PURIFY_TRUE=
+  PURIFY_FALSE='#'
+else
+  PURIFY_TRUE='#'
+  PURIFY_FALSE=
+fi
 
 
 
+# Check whether --enable-static was given.
+if test "${enable_static+set}" = set; then :
+  enableval=$enable_static; p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_static=yes ;;
+    no) enable_static=no ;;
+    *)
+     enable_static=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_static=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac
+else
+  enable_static=no
+fi
 
 
 
@@ -5489,108 +5861,30 @@ test -z "$GREP" && GREP=grep
 
 
 
-# Check whether --with-gnu-ld was given.
-if test "${with_gnu_ld+set}" = set; then :
-  withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes
-else
-  with_gnu_ld=no
-fi
 
-ac_prog=ld
-if test "$GCC" = yes; then
-  # Check if gcc -print-prog-name=ld gives a path.
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5
-$as_echo_n "checking for ld used by $CC... " >&6; }
-  case $host in
-  *-*-mingw*)
-    # gcc leaves a trailing carriage return which upsets mingw
-    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
-  *)
-    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
-  esac
-  case $ac_prog in
-    # Accept absolute paths.
-    [\\/]* | ?:[\\/]*)
-      re_direlt='/[^/][^/]*/\.\./'
-      # Canonicalize the pathname of ld
-      ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'`
-      while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
-	ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
+# Check whether --enable-shared was given.
+if test "${enable_shared+set}" = set; then :
+  enableval=$enable_shared; p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_shared=yes ;;
+    no) enable_shared=no ;;
+    *)
+      enable_shared=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_shared=yes
+	fi
       done
-      test -z "$LD" && LD="$ac_prog"
+      IFS="$lt_save_ifs"
       ;;
-  "")
-    # If it fails, then pretend we aren't using GCC.
-    ac_prog=ld
-    ;;
-  *)
-    # If it is relative, then search for the first ld in PATH.
-    with_gnu_ld=unknown
-    ;;
-  esac
-elif test "$with_gnu_ld" = yes; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5
-$as_echo_n "checking for GNU ld... " >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5
-$as_echo_n "checking for non-GNU ld... " >&6; }
-fi
-if ${lt_cv_path_LD+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -z "$LD"; then
-  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-  for ac_dir in $PATH; do
-    IFS="$lt_save_ifs"
-    test -z "$ac_dir" && ac_dir=.
-    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
-      lt_cv_path_LD="$ac_dir/$ac_prog"
-      # Check to see if the program is GNU ld.  I'd rather use --version,
-      # but apparently some variants of GNU ld only accept -v.
-      # Break only if it was the GNU/non-GNU ld that we prefer.
-      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
-      *GNU* | *'with BFD'*)
-	test "$with_gnu_ld" != no && break
-	;;
-      *)
-	test "$with_gnu_ld" != yes && break
-	;;
-      esac
-    fi
-  done
-  IFS="$lt_save_ifs"
+    esac
 else
-  lt_cv_path_LD="$LD" # Let the user override the test with a path.
-fi
+  enable_shared=yes
 fi
 
-LD="$lt_cv_path_LD"
-if test -n "$LD"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LD" >&5
-$as_echo "$LD" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5
-$as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; }
-if ${lt_cv_prog_gnu_ld+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  # I'd rather use --version here, but apparently some GNU lds only accept -v.
-case `$LD -v 2>&1 </dev/null` in
-*GNU* | *'with BFD'*)
-  lt_cv_prog_gnu_ld=yes
-  ;;
-*)
-  lt_cv_prog_gnu_ld=no
-  ;;
-esac
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_gnu_ld" >&5
-$as_echo "$lt_cv_prog_gnu_ld" >&6; }
-with_gnu_ld=$lt_cv_prog_gnu_ld
 
 
 
@@ -5600,403 +5894,171 @@ with_gnu_ld=$lt_cv_prog_gnu_ld
 
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatible name lister (nm)" >&5
-$as_echo_n "checking for BSD- or MS-compatible name lister (nm)... " >&6; }
-if ${lt_cv_path_NM+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$NM"; then
-  # Let the user override the test.
-  lt_cv_path_NM="$NM"
-else
-  lt_nm_to_check="${ac_tool_prefix}nm"
-  if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
-    lt_nm_to_check="$lt_nm_to_check nm"
-  fi
-  for lt_tmp_nm in $lt_nm_to_check; do
-    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
-      IFS="$lt_save_ifs"
-      test -z "$ac_dir" && ac_dir=.
-      tmp_nm="$ac_dir/$lt_tmp_nm"
-      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
-	# Check to see if the nm accepts a BSD-compat flag.
-	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
-	#   nm: unknown option "B" ignored
-	# Tru64's nm complains that /dev/null is an invalid object file
-	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
-	*/dev/null* | *'Invalid file or object type'*)
-	  lt_cv_path_NM="$tmp_nm -B"
-	  break
-	  ;;
-	*)
-	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
-	  */dev/null*)
-	    lt_cv_path_NM="$tmp_nm -p"
-	    break
-	    ;;
-	  *)
-	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
-	    continue # so that we can try to find one that supports BSD flags
-	    ;;
-	  esac
-	  ;;
-	esac
-      fi
-    done
-    IFS="$lt_save_ifs"
-  done
-  : ${lt_cv_path_NM=no}
-fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5
-$as_echo "$lt_cv_path_NM" >&6; }
-if test "$lt_cv_path_NM" != "no"; then
-  NM="$lt_cv_path_NM"
-else
-  # Didn't find any BSD compatible name lister, look for dumpbin.
-  if test -n "$DUMPBIN"; then :
-    # Let the user override the test.
-  else
-    if test -n "$ac_tool_prefix"; then
-  for ac_prog in dumpbin "link -dump"
-  do
-    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
-set dummy $ac_tool_prefix$ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_DUMPBIN+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$DUMPBIN"; then
-  ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_DUMPBIN="$ac_tool_prefix$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
+case `pwd` in
+  *\ * | *\	*)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&5
+$as_echo "$as_me: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&2;} ;;
+esac
 
-fi
-fi
-DUMPBIN=$ac_cv_prog_DUMPBIN
-if test -n "$DUMPBIN"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DUMPBIN" >&5
-$as_echo "$DUMPBIN" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
 
 
-    test -n "$DUMPBIN" && break
-  done
-fi
-if test -z "$DUMPBIN"; then
-  ac_ct_DUMPBIN=$DUMPBIN
-  for ac_prog in dumpbin "link -dump"
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_DUMPBIN+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_DUMPBIN"; then
-  ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_DUMPBIN="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
+macro_version='2.4.2'
+macro_revision='1.3337'
 
-fi
-fi
-ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN
-if test -n "$ac_ct_DUMPBIN"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DUMPBIN" >&5
-$as_echo "$ac_ct_DUMPBIN" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
 
 
-  test -n "$ac_ct_DUMPBIN" && break
-done
-
-  if test "x$ac_ct_DUMPBIN" = x; then
-    DUMPBIN=":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    DUMPBIN=$ac_ct_DUMPBIN
-  fi
-fi
-
-    case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in
-    *COFF*)
-      DUMPBIN="$DUMPBIN -symbols"
-      ;;
-    *)
-      DUMPBIN=:
-      ;;
-    esac
-  fi
-
-  if test "$DUMPBIN" != ":"; then
-    NM="$DUMPBIN"
-  fi
-fi
-test -z "$NM" && NM=nm
-
 
 
 
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) interface" >&5
-$as_echo_n "checking the name lister ($NM) interface... " >&6; }
-if ${lt_cv_nm_interface+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_nm_interface="BSD nm"
-  echo "int some_variable = 0;" > conftest.$ac_ext
-  (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&5)
-  (eval "$ac_compile" 2>conftest.err)
-  cat conftest.err >&5
-  (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&5)
-  (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out)
-  cat conftest.err >&5
-  (eval echo "\"\$as_me:$LINENO: output\"" >&5)
-  cat conftest.out >&5
-  if $GREP 'External.*some_variable' conftest.out > /dev/null; then
-    lt_cv_nm_interface="MS dumpbin"
-  fi
-  rm -f conftest*
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5
-$as_echo "$lt_cv_nm_interface" >&6; }
 
-# find the maximum length of command line arguments
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking the maximum length of command line arguments" >&5
-$as_echo_n "checking the maximum length of command line arguments... " >&6; }
-if ${lt_cv_sys_max_cmd_len+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-    i=0
-  teststring="ABCD"
 
-  case $build_os in
-  msdosdjgpp*)
-    # On DJGPP, this test can blow up pretty badly due to problems in libc
-    # (any single argument exceeding 2000 bytes causes a buffer overrun
-    # during glob expansion).  Even if it were fixed, the result of this
-    # check would be larger than it should be.
-    lt_cv_sys_max_cmd_len=12288;    # 12K is about right
-    ;;
 
-  gnu*)
-    # Under GNU Hurd, this test is not required because there is
-    # no limit to the length of command line arguments.
-    # Libtool will interpret -1 as no limit whatsoever
-    lt_cv_sys_max_cmd_len=-1;
-    ;;
 
-  cygwin* | mingw* | cegcc*)
-    # On Win9x/ME, this test blows up -- it succeeds, but takes
-    # about 5 minutes as the teststring grows exponentially.
-    # Worse, since 9x/ME are not pre-emptively multitasking,
-    # you end up with a "frozen" computer, even though with patience
-    # the test eventually succeeds (with a max line length of 256k).
-    # Instead, let's just punt: use the minimum linelength reported by
-    # all of the supported platforms: 8192 (on NT/2K/XP).
-    lt_cv_sys_max_cmd_len=8192;
-    ;;
 
-  mint*)
-    # On MiNT this can take a long time and run out of memory.
-    lt_cv_sys_max_cmd_len=8192;
-    ;;
+ltmain="$ac_aux_dir/ltmain.sh"
 
-  amigaos*)
-    # On AmigaOS with pdksh, this test takes hours, literally.
-    # So we just punt and use a minimum line length of 8192.
-    lt_cv_sys_max_cmd_len=8192;
-    ;;
+# Backslashify metacharacters that are still active within
+# double-quoted strings.
+sed_quote_subst='s/\(["`$\\]\)/\\\1/g'
 
-  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
-    # This has been around since 386BSD, at least.  Likely further.
-    if test -x /sbin/sysctl; then
-      lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
-    elif test -x /usr/sbin/sysctl; then
-      lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
-    else
-      lt_cv_sys_max_cmd_len=65536	# usable default for all BSDs
-    fi
-    # And add a safety zone
-    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
-    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
-    ;;
+# Same as above, but do not quote variable references.
+double_quote_subst='s/\(["`\\]\)/\\\1/g'
 
-  interix*)
-    # We know the value 262144 and hardcode it with a safety zone (like BSD)
-    lt_cv_sys_max_cmd_len=196608
-    ;;
+# Sed substitution to delay expansion of an escaped shell variable in a
+# double_quote_subst'ed string.
+delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
 
-  os2*)
-    # The test takes a long time on OS/2.
-    lt_cv_sys_max_cmd_len=8192
-    ;;
+# Sed substitution to delay expansion of an escaped single quote.
+delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g'
 
-  osf*)
-    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
-    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
-    # nice to cause kernel panics so lets avoid the loop below.
-    # First set a reasonable default.
-    lt_cv_sys_max_cmd_len=16384
-    #
-    if test -x /sbin/sysconfig; then
-      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
-        *1*) lt_cv_sys_max_cmd_len=-1 ;;
-      esac
-    fi
-    ;;
-  sco3.2v5*)
-    lt_cv_sys_max_cmd_len=102400
-    ;;
-  sysv5* | sco5v6* | sysv4.2uw2*)
-    kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
-    if test -n "$kargmax"; then
-      lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[	 ]//'`
-    else
-      lt_cv_sys_max_cmd_len=32768
-    fi
-    ;;
-  *)
-    lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null`
-    if test -n "$lt_cv_sys_max_cmd_len"; then
-      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
-      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
-    else
-      # Make teststring a little bigger before we do anything with it.
-      # a 1K string should be a reasonable start.
-      for i in 1 2 3 4 5 6 7 8 ; do
-        teststring=$teststring$teststring
-      done
-      SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
-      # If test is not a shell built-in, we'll probably end up computing a
-      # maximum length that is only half of the actual maximum length, but
-      # we can't tell.
-      while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \
-	         = "X$teststring$teststring"; } >/dev/null 2>&1 &&
-	      test $i != 17 # 1/2 MB should be enough
-      do
-        i=`expr $i + 1`
-        teststring=$teststring$teststring
-      done
-      # Only check the string length outside the loop.
-      lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1`
-      teststring=
-      # Add a significant safety factor because C++ compilers can tack on
-      # massive amounts of additional arguments before passing them to the
-      # linker.  It appears as though 1/2 is a usable value.
-      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
-    fi
-    ;;
-  esac
+# Sed substitution to avoid accidental globbing in evaled expressions
+no_glob_subst='s/\*/\\\*/g'
 
-fi
+ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
+ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
 
-if test -n $lt_cv_sys_max_cmd_len ; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len" >&5
-$as_echo "$lt_cv_sys_max_cmd_len" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to print strings" >&5
+$as_echo_n "checking how to print strings... " >&6; }
+# Test print first, because it will be a builtin if present.
+if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \
+   test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then
+  ECHO='print -r --'
+elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then
+  ECHO='printf %s\n'
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5
-$as_echo "none" >&6; }
+  # Use this function as a fallback that always works.
+  func_fallback_echo ()
+  {
+    eval 'cat <<_LTECHO_EOF
+$1
+_LTECHO_EOF'
+  }
+  ECHO='func_fallback_echo'
 fi
-max_cmd_len=$lt_cv_sys_max_cmd_len
 
+# func_echo_all arg...
+# Invoke $ECHO with all args, space-separated.
+func_echo_all ()
+{
+    $ECHO ""
+}
 
+case "$ECHO" in
+  printf*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: printf" >&5
+$as_echo "printf" >&6; } ;;
+  print*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: print -r" >&5
+$as_echo "print -r" >&6; } ;;
+  *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: cat" >&5
+$as_echo "cat" >&6; } ;;
+esac
 
 
 
 
-: ${CP="cp -f"}
-: ${MV="mv -f"}
-: ${RM="rm -f"}
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands some XSI constructs" >&5
-$as_echo_n "checking whether the shell understands some XSI constructs... " >&6; }
-# Try some XSI features
-xsi_shell=no
-( _lt_dummy="a/b/c"
-  test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \
-      = c,a/b,b/c, \
-    && eval 'test $(( 1 + 1 )) -eq 2 \
-    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
-  && xsi_shell=yes
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $xsi_shell" >&5
-$as_echo "$xsi_shell" >&6; }
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands \"+=\"" >&5
-$as_echo_n "checking whether the shell understands \"+=\"... " >&6; }
-lt_shell_append=no
-( foo=bar; set foo baz; eval "$1+=\$2" && test "$foo" = barbaz ) \
-    >/dev/null 2>&1 \
-  && lt_shell_append=yes
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_shell_append" >&5
-$as_echo "$lt_shell_append" >&6; }
 
 
-if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
-  lt_unset=unset
-else
-  lt_unset=false
-fi
 
 
 
 
 
-# test EBCDIC or ASCII
-case `echo X|tr X '\101'` in
- A) # ASCII based system
-    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
-  lt_SP2NL='tr \040 \012'
-  lt_NL2SP='tr \015\012 \040\040'
-  ;;
- *) # EBCDIC based system
-  lt_SP2NL='tr \100 \n'
-  lt_NL2SP='tr \r\n \100\100'
-  ;;
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5
+$as_echo_n "checking for a sed that does not truncate output... " >&6; }
+if ${ac_cv_path_SED+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+            ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/
+     for ac_i in 1 2 3 4 5 6 7; do
+       ac_script="$ac_script$as_nl$ac_script"
+     done
+     echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed
+     { ac_script=; unset ac_script;}
+     if test -z "$SED"; then
+  ac_path_SED_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_prog in sed gsed; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_SED="$as_dir/$ac_prog$ac_exec_ext"
+      as_fn_executable_p "$ac_path_SED" || continue
+# Check for GNU ac_path_SED and select it if it is found.
+  # Check for GNU $ac_path_SED
+case `"$ac_path_SED" --version 2>&1` in
+*GNU*)
+  ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;;
+*)
+  ac_count=0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo '' >> "conftest.nl"
+    "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_SED_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_SED="$ac_path_SED"
+      ac_path_SED_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
 esac
 
+      $ac_path_SED_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_SED"; then
+    as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5
+  fi
+else
+  ac_cv_path_SED=$SED
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5
+$as_echo "$ac_cv_path_SED" >&6; }
+ SED="$ac_cv_path_SED"
+  rm -f conftest.sed
+
+test -z "$SED" && SED=sed
+Xsed="$SED -e 1s/^X//"
 
 
 
@@ -6005,109 +6067,86 @@ esac
 
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to $host format" >&5
-$as_echo_n "checking how to convert $build file names to $host format... " >&6; }
-if ${lt_cv_to_host_file_cmd+:} false; then :
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5
+$as_echo_n "checking for fgrep... " >&6; }
+if ${ac_cv_path_FGREP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  case $host in
-  *-*-mingw* )
-    case $build in
-      *-*-mingw* ) # actually msys
-        lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32
-        ;;
-      *-*-cygwin* )
-        lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32
-        ;;
-      * ) # otherwise, assume *nix
-        lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32
-        ;;
-    esac
-    ;;
-  *-*-cygwin* )
-    case $build in
-      *-*-mingw* ) # actually msys
-        lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin
-        ;;
-      *-*-cygwin* )
-        lt_cv_to_host_file_cmd=func_convert_file_noop
-        ;;
-      * ) # otherwise, assume *nix
-        lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin
-        ;;
-    esac
-    ;;
-  * ) # unhandled hosts (and "normal" native builds)
-    lt_cv_to_host_file_cmd=func_convert_file_noop
-    ;;
+  if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1
+   then ac_cv_path_FGREP="$GREP -F"
+   else
+     if test -z "$FGREP"; then
+  ac_path_FGREP_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_prog in fgrep; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_FGREP="$as_dir/$ac_prog$ac_exec_ext"
+      as_fn_executable_p "$ac_path_FGREP" || continue
+# Check for GNU ac_path_FGREP and select it if it is found.
+  # Check for GNU $ac_path_FGREP
+case `"$ac_path_FGREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;;
+*)
+  ac_count=0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo 'FGREP' >> "conftest.nl"
+    "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_FGREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_FGREP="$ac_path_FGREP"
+      ac_path_FGREP_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
 esac
 
+      $ac_path_FGREP_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_FGREP"; then
+    as_fn_error $? "no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
+  fi
+else
+  ac_cv_path_FGREP=$FGREP
 fi
 
-to_host_file_cmd=$lt_cv_to_host_file_cmd
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_host_file_cmd" >&5
-$as_echo "$lt_cv_to_host_file_cmd" >&6; }
-
+   fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5
+$as_echo "$ac_cv_path_FGREP" >&6; }
+ FGREP="$ac_cv_path_FGREP"
 
 
+test -z "$GREP" && GREP=grep
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to toolchain format" >&5
-$as_echo_n "checking how to convert $build file names to toolchain format... " >&6; }
-if ${lt_cv_to_tool_file_cmd+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  #assume ordinary cross tools, or native build.
-lt_cv_to_tool_file_cmd=func_convert_file_noop
-case $host in
-  *-*-mingw* )
-    case $build in
-      *-*-mingw* ) # actually msys
-        lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32
-        ;;
-    esac
-    ;;
-esac
 
-fi
 
-to_tool_file_cmd=$lt_cv_to_tool_file_cmd
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_tool_file_cmd" >&5
-$as_echo "$lt_cv_to_tool_file_cmd" >&6; }
 
 
 
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload object files" >&5
-$as_echo_n "checking for $LD option to reload object files... " >&6; }
-if ${lt_cv_ld_reload_flag+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_ld_reload_flag='-r'
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5
-$as_echo "$lt_cv_ld_reload_flag" >&6; }
-reload_flag=$lt_cv_ld_reload_flag
-case $reload_flag in
-"" | " "*) ;;
-*) reload_flag=" $reload_flag" ;;
-esac
-reload_cmds='$LD$reload_flag -o $output$reload_objs'
-case $host_os in
-  cygwin* | mingw* | pw32* | cegcc*)
-    if test "$GCC" != yes; then
-      reload_cmds=false
-    fi
-    ;;
-  darwin*)
-    if test "$GCC" = yes; then
-      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
-    else
-      reload_cmds='$LD$reload_flag -o $output$reload_objs'
-    fi
-    ;;
-esac
 
 
 
@@ -6117,56 +6156,188 @@ esac
 
 
 
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args.
-set dummy ${ac_tool_prefix}objdump; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_OBJDUMP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$OBJDUMP"; then
-  ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
 
-fi
-fi
-OBJDUMP=$ac_cv_prog_OBJDUMP
-if test -n "$OBJDUMP"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5
-$as_echo "$OBJDUMP" >&6; }
+# Check whether --with-gnu-ld was given.
+if test "${with_gnu_ld+set}" = set; then :
+  withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  with_gnu_ld=no
 fi
 
-
+ac_prog=ld
+if test "$GCC" = yes; then
+  # Check if gcc -print-prog-name=ld gives a path.
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5
+$as_echo_n "checking for ld used by $CC... " >&6; }
+  case $host in
+  *-*-mingw*)
+    # gcc leaves a trailing carriage return which upsets mingw
+    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
+  *)
+    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
+  esac
+  case $ac_prog in
+    # Accept absolute paths.
+    [\\/]* | ?:[\\/]*)
+      re_direlt='/[^/][^/]*/\.\./'
+      # Canonicalize the pathname of ld
+      ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'`
+      while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
+	ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
+      done
+      test -z "$LD" && LD="$ac_prog"
+      ;;
+  "")
+    # If it fails, then pretend we aren't using GCC.
+    ac_prog=ld
+    ;;
+  *)
+    # If it is relative, then search for the first ld in PATH.
+    with_gnu_ld=unknown
+    ;;
+  esac
+elif test "$with_gnu_ld" = yes; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5
+$as_echo_n "checking for GNU ld... " >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5
+$as_echo_n "checking for non-GNU ld... " >&6; }
 fi
-if test -z "$ac_cv_prog_OBJDUMP"; then
-  ac_ct_OBJDUMP=$OBJDUMP
-  # Extract the first word of "objdump", so it can be a program name with args.
-set dummy objdump; ac_word=$2
+if ${lt_cv_path_LD+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -z "$LD"; then
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  for ac_dir in $PATH; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
+      lt_cv_path_LD="$ac_dir/$ac_prog"
+      # Check to see if the program is GNU ld.  I'd rather use --version,
+      # but apparently some variants of GNU ld only accept -v.
+      # Break only if it was the GNU/non-GNU ld that we prefer.
+      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
+      *GNU* | *'with BFD'*)
+	test "$with_gnu_ld" != no && break
+	;;
+      *)
+	test "$with_gnu_ld" != yes && break
+	;;
+      esac
+    fi
+  done
+  IFS="$lt_save_ifs"
+else
+  lt_cv_path_LD="$LD" # Let the user override the test with a path.
+fi
+fi
+
+LD="$lt_cv_path_LD"
+if test -n "$LD"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LD" >&5
+$as_echo "$LD" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5
+$as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; }
+if ${lt_cv_prog_gnu_ld+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  # I'd rather use --version here, but apparently some GNU lds only accept -v.
+case `$LD -v 2>&1 </dev/null` in
+*GNU* | *'with BFD'*)
+  lt_cv_prog_gnu_ld=yes
+  ;;
+*)
+  lt_cv_prog_gnu_ld=no
+  ;;
+esac
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_gnu_ld" >&5
+$as_echo "$lt_cv_prog_gnu_ld" >&6; }
+with_gnu_ld=$lt_cv_prog_gnu_ld
+
+
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatible name lister (nm)" >&5
+$as_echo_n "checking for BSD- or MS-compatible name lister (nm)... " >&6; }
+if ${lt_cv_path_NM+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$NM"; then
+  # Let the user override the test.
+  lt_cv_path_NM="$NM"
+else
+  lt_nm_to_check="${ac_tool_prefix}nm"
+  if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
+    lt_nm_to_check="$lt_nm_to_check nm"
+  fi
+  for lt_tmp_nm in $lt_nm_to_check; do
+    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
+      IFS="$lt_save_ifs"
+      test -z "$ac_dir" && ac_dir=.
+      tmp_nm="$ac_dir/$lt_tmp_nm"
+      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
+	# Check to see if the nm accepts a BSD-compat flag.
+	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
+	#   nm: unknown option "B" ignored
+	# Tru64's nm complains that /dev/null is an invalid object file
+	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
+	*/dev/null* | *'Invalid file or object type'*)
+	  lt_cv_path_NM="$tmp_nm -B"
+	  break
+	  ;;
+	*)
+	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
+	  */dev/null*)
+	    lt_cv_path_NM="$tmp_nm -p"
+	    break
+	    ;;
+	  *)
+	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
+	    continue # so that we can try to find one that supports BSD flags
+	    ;;
+	  esac
+	  ;;
+	esac
+      fi
+    done
+    IFS="$lt_save_ifs"
+  done
+  : ${lt_cv_path_NM=no}
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5
+$as_echo "$lt_cv_path_NM" >&6; }
+if test "$lt_cv_path_NM" != "no"; then
+  NM="$lt_cv_path_NM"
+else
+  # Didn't find any BSD compatible name lister, look for dumpbin.
+  if test -n "$DUMPBIN"; then :
+    # Let the user override the test.
+  else
+    if test -n "$ac_tool_prefix"; then
+  for ac_prog in dumpbin "link -dump"
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 $as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then :
+if ${ac_cv_prog_DUMPBIN+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  if test -n "$ac_ct_OBJDUMP"; then
-  ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test.
+  if test -n "$DUMPBIN"; then
+  ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test.
 else
 as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
@@ -6175,7 +6346,7 @@ do
   test -z "$as_dir" && as_dir=.
     for ac_exec_ext in '' $ac_executable_extensions; do
   if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_OBJDUMP="objdump"
+    ac_cv_prog_DUMPBIN="$ac_tool_prefix$ac_prog"
     $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
@@ -6185,17 +6356,65 @@ IFS=$as_save_IFS
 
 fi
 fi
-ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP
-if test -n "$ac_ct_OBJDUMP"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5
-$as_echo "$ac_ct_OBJDUMP" >&6; }
+DUMPBIN=$ac_cv_prog_DUMPBIN
+if test -n "$DUMPBIN"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DUMPBIN" >&5
+$as_echo "$DUMPBIN" >&6; }
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
 $as_echo "no" >&6; }
 fi
 
-  if test "x$ac_ct_OBJDUMP" = x; then
-    OBJDUMP="false"
+
+    test -n "$DUMPBIN" && break
+  done
+fi
+if test -z "$DUMPBIN"; then
+  ac_ct_DUMPBIN=$DUMPBIN
+  for ac_prog in dumpbin "link -dump"
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_DUMPBIN+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_DUMPBIN"; then
+  ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_ac_ct_DUMPBIN="$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN
+if test -n "$ac_ct_DUMPBIN"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DUMPBIN" >&5
+$as_echo "$ac_ct_DUMPBIN" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$ac_ct_DUMPBIN" && break
+done
+
+  if test "x$ac_ct_DUMPBIN" = x; then
+    DUMPBIN=":"
   else
     case $cross_compiling:$ac_tool_warned in
 yes:)
@@ -6203,257 +6422,360 @@ yes:)
 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
 ac_tool_warned=yes ;;
 esac
-    OBJDUMP=$ac_ct_OBJDUMP
+    DUMPBIN=$ac_ct_DUMPBIN
   fi
-else
-  OBJDUMP="$ac_cv_prog_OBJDUMP"
 fi
 
-test -z "$OBJDUMP" && OBJDUMP=objdump
-
-
-
-
+    case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in
+    *COFF*)
+      DUMPBIN="$DUMPBIN -symbols"
+      ;;
+    *)
+      DUMPBIN=:
+      ;;
+    esac
+  fi
 
+  if test "$DUMPBIN" != ":"; then
+    NM="$DUMPBIN"
+  fi
+fi
+test -z "$NM" && NM=nm
 
 
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to recognize dependent libraries" >&5
-$as_echo_n "checking how to recognize dependent libraries... " >&6; }
-if ${lt_cv_deplibs_check_method+:} false; then :
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) interface" >&5
+$as_echo_n "checking the name lister ($NM) interface... " >&6; }
+if ${lt_cv_nm_interface+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  lt_cv_file_magic_cmd='$MAGIC_CMD'
-lt_cv_file_magic_test_file=
-lt_cv_deplibs_check_method='unknown'
-# Need to set the preceding variable on all platforms that support
-# interlibrary dependencies.
-# 'none' -- dependencies not supported.
-# `unknown' -- same as none, but documents that we really don't know.
-# 'pass_all' -- all dependencies passed with no checks.
-# 'test_compile' -- check by making test program.
-# 'file_magic [[regex]]' -- check by looking for files in library path
-# which responds to the $file_magic_cmd with a given extended regex.
-# If you have `file' or equivalent on your system and you're not sure
-# whether `pass_all' will *always* work, you probably want this one.
-
-case $host_os in
-aix[4-9]*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
+  lt_cv_nm_interface="BSD nm"
+  echo "int some_variable = 0;" > conftest.$ac_ext
+  (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&5)
+  (eval "$ac_compile" 2>conftest.err)
+  cat conftest.err >&5
+  (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&5)
+  (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out)
+  cat conftest.err >&5
+  (eval echo "\"\$as_me:$LINENO: output\"" >&5)
+  cat conftest.out >&5
+  if $GREP 'External.*some_variable' conftest.out > /dev/null; then
+    lt_cv_nm_interface="MS dumpbin"
+  fi
+  rm -f conftest*
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5
+$as_echo "$lt_cv_nm_interface" >&6; }
 
-beos*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
+# find the maximum length of command line arguments
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking the maximum length of command line arguments" >&5
+$as_echo_n "checking the maximum length of command line arguments... " >&6; }
+if ${lt_cv_sys_max_cmd_len+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+    i=0
+  teststring="ABCD"
 
-bsdi[45]*)
-  lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)'
-  lt_cv_file_magic_cmd='/usr/bin/file -L'
-  lt_cv_file_magic_test_file=/shlib/libc.so
-  ;;
+  case $build_os in
+  msdosdjgpp*)
+    # On DJGPP, this test can blow up pretty badly due to problems in libc
+    # (any single argument exceeding 2000 bytes causes a buffer overrun
+    # during glob expansion).  Even if it were fixed, the result of this
+    # check would be larger than it should be.
+    lt_cv_sys_max_cmd_len=12288;    # 12K is about right
+    ;;
 
-cygwin*)
-  # func_win32_libid is a shell function defined in ltmain.sh
-  lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
-  lt_cv_file_magic_cmd='func_win32_libid'
-  ;;
+  gnu*)
+    # Under GNU Hurd, this test is not required because there is
+    # no limit to the length of command line arguments.
+    # Libtool will interpret -1 as no limit whatsoever
+    lt_cv_sys_max_cmd_len=-1;
+    ;;
 
-mingw* | pw32*)
-  # Base MSYS/MinGW do not provide the 'file' command needed by
-  # func_win32_libid shell function, so use a weaker test based on 'objdump',
-  # unless we find 'file', for example because we are cross-compiling.
-  # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin.
-  if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then
-    lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
-    lt_cv_file_magic_cmd='func_win32_libid'
-  else
-    # Keep this pattern in sync with the one in func_win32_libid.
-    lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)'
-    lt_cv_file_magic_cmd='$OBJDUMP -f'
-  fi
-  ;;
+  cygwin* | mingw* | cegcc*)
+    # On Win9x/ME, this test blows up -- it succeeds, but takes
+    # about 5 minutes as the teststring grows exponentially.
+    # Worse, since 9x/ME are not pre-emptively multitasking,
+    # you end up with a "frozen" computer, even though with patience
+    # the test eventually succeeds (with a max line length of 256k).
+    # Instead, let's just punt: use the minimum linelength reported by
+    # all of the supported platforms: 8192 (on NT/2K/XP).
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
 
-cegcc*)
-  # use the weaker test based on 'objdump'. See mingw*.
-  lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?'
-  lt_cv_file_magic_cmd='$OBJDUMP -f'
-  ;;
+  mint*)
+    # On MiNT this can take a long time and run out of memory.
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
 
-darwin* | rhapsody*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
+  amigaos*)
+    # On AmigaOS with pdksh, this test takes hours, literally.
+    # So we just punt and use a minimum line length of 8192.
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
 
-freebsd* | dragonfly*)
-  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
-    case $host_cpu in
-    i*86 )
-      # Not sure whether the presence of OpenBSD here was a mistake.
-      # Let's accept both of them until this is cleared up.
-      lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library'
-      lt_cv_file_magic_cmd=/usr/bin/file
-      lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
-      ;;
-    esac
-  else
-    lt_cv_deplibs_check_method=pass_all
-  fi
-  ;;
+  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
+    # This has been around since 386BSD, at least.  Likely further.
+    if test -x /sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
+    elif test -x /usr/sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
+    else
+      lt_cv_sys_max_cmd_len=65536	# usable default for all BSDs
+    fi
+    # And add a safety zone
+    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+    ;;
 
-gnu*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
+  interix*)
+    # We know the value 262144 and hardcode it with a safety zone (like BSD)
+    lt_cv_sys_max_cmd_len=196608
+    ;;
 
-haiku*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
+  os2*)
+    # The test takes a long time on OS/2.
+    lt_cv_sys_max_cmd_len=8192
+    ;;
 
-hpux10.20* | hpux11*)
-  lt_cv_file_magic_cmd=/usr/bin/file
-  case $host_cpu in
-  ia64*)
-    lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64'
-    lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
+  osf*)
+    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
+    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
+    # nice to cause kernel panics so lets avoid the loop below.
+    # First set a reasonable default.
+    lt_cv_sys_max_cmd_len=16384
+    #
+    if test -x /sbin/sysconfig; then
+      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
+        *1*) lt_cv_sys_max_cmd_len=-1 ;;
+      esac
+    fi
     ;;
-  hppa*64*)
-    lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]'
-    lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
+  sco3.2v5*)
+    lt_cv_sys_max_cmd_len=102400
+    ;;
+  sysv5* | sco5v6* | sysv4.2uw2*)
+    kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
+    if test -n "$kargmax"; then
+      lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[	 ]//'`
+    else
+      lt_cv_sys_max_cmd_len=32768
+    fi
     ;;
   *)
-    lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9]\.[0-9]) shared library'
-    lt_cv_file_magic_test_file=/usr/lib/libc.sl
+    lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null`
+    if test -n "$lt_cv_sys_max_cmd_len"; then
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+    else
+      # Make teststring a little bigger before we do anything with it.
+      # a 1K string should be a reasonable start.
+      for i in 1 2 3 4 5 6 7 8 ; do
+        teststring=$teststring$teststring
+      done
+      SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
+      # If test is not a shell built-in, we'll probably end up computing a
+      # maximum length that is only half of the actual maximum length, but
+      # we can't tell.
+      while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \
+	         = "X$teststring$teststring"; } >/dev/null 2>&1 &&
+	      test $i != 17 # 1/2 MB should be enough
+      do
+        i=`expr $i + 1`
+        teststring=$teststring$teststring
+      done
+      # Only check the string length outside the loop.
+      lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1`
+      teststring=
+      # Add a significant safety factor because C++ compilers can tack on
+      # massive amounts of additional arguments before passing them to the
+      # linker.  It appears as though 1/2 is a usable value.
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
+    fi
     ;;
   esac
-  ;;
 
-interix[3-9]*)
-  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
-  lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$'
-  ;;
+fi
 
-irix5* | irix6* | nonstopux*)
-  case $LD in
-  *-32|*"-32 ") libmagic=32-bit;;
-  *-n32|*"-n32 ") libmagic=N32;;
-  *-64|*"-64 ") libmagic=64-bit;;
-  *) libmagic=never-match;;
-  esac
-  lt_cv_deplibs_check_method=pass_all
-  ;;
+if test -n $lt_cv_sys_max_cmd_len ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len" >&5
+$as_echo "$lt_cv_sys_max_cmd_len" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5
+$as_echo "none" >&6; }
+fi
+max_cmd_len=$lt_cv_sys_max_cmd_len
 
-# This must be glibc/ELF.
-linux* | k*bsd*-gnu | kopensolaris*-gnu)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
 
-netbsd*)
-  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
-    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$'
-  else
-    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$'
-  fi
-  ;;
 
-newos6*)
-  lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)'
-  lt_cv_file_magic_cmd=/usr/bin/file
-  lt_cv_file_magic_test_file=/usr/lib/libnls.so
-  ;;
 
-*nto* | *qnx*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
 
-openbsd*)
-  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$'
-  else
-    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$'
-  fi
-  ;;
 
-osf3* | osf4* | osf5*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
+: ${CP="cp -f"}
+: ${MV="mv -f"}
+: ${RM="rm -f"}
 
-rdos*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands some XSI constructs" >&5
+$as_echo_n "checking whether the shell understands some XSI constructs... " >&6; }
+# Try some XSI features
+xsi_shell=no
+( _lt_dummy="a/b/c"
+  test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \
+      = c,a/b,b/c, \
+    && eval 'test $(( 1 + 1 )) -eq 2 \
+    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
+  && xsi_shell=yes
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $xsi_shell" >&5
+$as_echo "$xsi_shell" >&6; }
 
-solaris*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
 
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands \"+=\"" >&5
+$as_echo_n "checking whether the shell understands \"+=\"... " >&6; }
+lt_shell_append=no
+( foo=bar; set foo baz; eval "$1+=\$2" && test "$foo" = barbaz ) \
+    >/dev/null 2>&1 \
+  && lt_shell_append=yes
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_shell_append" >&5
+$as_echo "$lt_shell_append" >&6; }
 
-sysv4 | sysv4.3*)
-  case $host_vendor in
-  motorola)
-    lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]'
-    lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
-    ;;
-  ncr)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  sequent)
-    lt_cv_file_magic_cmd='/bin/file'
-    lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )'
-    ;;
-  sni)
-    lt_cv_file_magic_cmd='/bin/file'
-    lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib"
-    lt_cv_file_magic_test_file=/lib/libc.so
-    ;;
-  siemens)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  pc)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  esac
-  ;;
 
-tpf*)
-  lt_cv_deplibs_check_method=pass_all
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+  lt_unset=unset
+else
+  lt_unset=false
+fi
+
+
+
+
+
+# test EBCDIC or ASCII
+case `echo X|tr X '\101'` in
+ A) # ASCII based system
+    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
+  lt_SP2NL='tr \040 \012'
+  lt_NL2SP='tr \015\012 \040\040'
+  ;;
+ *) # EBCDIC based system
+  lt_SP2NL='tr \100 \n'
+  lt_NL2SP='tr \r\n \100\100'
   ;;
 esac
 
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_method" >&5
-$as_echo "$lt_cv_deplibs_check_method" >&6; }
 
-file_magic_glob=
-want_nocaseglob=no
-if test "$build" = "$host"; then
-  case $host_os in
-  mingw* | pw32*)
-    if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then
-      want_nocaseglob=yes
-    else
-      file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[\1]\/[\1]\/g;/g"`
-    fi
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to $host format" >&5
+$as_echo_n "checking how to convert $build file names to $host format... " >&6; }
+if ${lt_cv_to_host_file_cmd+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $host in
+  *-*-mingw* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32
+        ;;
+      *-*-cygwin* )
+        lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32
+        ;;
+      * ) # otherwise, assume *nix
+        lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32
+        ;;
+    esac
     ;;
-  esac
-fi
+  *-*-cygwin* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin
+        ;;
+      *-*-cygwin* )
+        lt_cv_to_host_file_cmd=func_convert_file_noop
+        ;;
+      * ) # otherwise, assume *nix
+        lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin
+        ;;
+    esac
+    ;;
+  * ) # unhandled hosts (and "normal" native builds)
+    lt_cv_to_host_file_cmd=func_convert_file_noop
+    ;;
+esac
 
-file_magic_cmd=$lt_cv_file_magic_cmd
-deplibs_check_method=$lt_cv_deplibs_check_method
-test -z "$deplibs_check_method" && deplibs_check_method=unknown
+fi
 
+to_host_file_cmd=$lt_cv_to_host_file_cmd
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_host_file_cmd" >&5
+$as_echo "$lt_cv_to_host_file_cmd" >&6; }
 
 
 
 
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to toolchain format" >&5
+$as_echo_n "checking how to convert $build file names to toolchain format... " >&6; }
+if ${lt_cv_to_tool_file_cmd+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  #assume ordinary cross tools, or native build.
+lt_cv_to_tool_file_cmd=func_convert_file_noop
+case $host in
+  *-*-mingw* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32
+        ;;
+    esac
+    ;;
+esac
 
+fi
 
+to_tool_file_cmd=$lt_cv_to_tool_file_cmd
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_tool_file_cmd" >&5
+$as_echo "$lt_cv_to_tool_file_cmd" >&6; }
 
 
 
 
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload object files" >&5
+$as_echo_n "checking for $LD option to reload object files... " >&6; }
+if ${lt_cv_ld_reload_flag+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_ld_reload_flag='-r'
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5
+$as_echo "$lt_cv_ld_reload_flag" >&6; }
+reload_flag=$lt_cv_ld_reload_flag
+case $reload_flag in
+"" | " "*) ;;
+*) reload_flag=" $reload_flag" ;;
+esac
+reload_cmds='$LD$reload_flag -o $output$reload_objs'
+case $host_os in
+  cygwin* | mingw* | pw32* | cegcc*)
+    if test "$GCC" != yes; then
+      reload_cmds=false
+    fi
+    ;;
+  darwin*)
+    if test "$GCC" = yes; then
+      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
+    else
+      reload_cmds='$LD$reload_flag -o $output$reload_objs'
+    fi
+    ;;
+esac
 
 
 
@@ -6464,15 +6786,15 @@ test -z "$deplibs_check_method" && deplibs_check_method=unknown
 
 
 if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args.
-set dummy ${ac_tool_prefix}dlltool; ac_word=$2
+  # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args.
+set dummy ${ac_tool_prefix}objdump; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 $as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_DLLTOOL+:} false; then :
+if ${ac_cv_prog_OBJDUMP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  if test -n "$DLLTOOL"; then
-  ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test.
+  if test -n "$OBJDUMP"; then
+  ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test.
 else
 as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
@@ -6481,7 +6803,7 @@ do
   test -z "$as_dir" && as_dir=.
     for ac_exec_ext in '' $ac_executable_extensions; do
   if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool"
+    ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump"
     $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
@@ -6491,10 +6813,10 @@ IFS=$as_save_IFS
 
 fi
 fi
-DLLTOOL=$ac_cv_prog_DLLTOOL
-if test -n "$DLLTOOL"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5
-$as_echo "$DLLTOOL" >&6; }
+OBJDUMP=$ac_cv_prog_OBJDUMP
+if test -n "$OBJDUMP"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5
+$as_echo "$OBJDUMP" >&6; }
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
 $as_echo "no" >&6; }
@@ -6502,17 +6824,17 @@ fi
 
 
 fi
-if test -z "$ac_cv_prog_DLLTOOL"; then
-  ac_ct_DLLTOOL=$DLLTOOL
-  # Extract the first word of "dlltool", so it can be a program name with args.
-set dummy dlltool; ac_word=$2
+if test -z "$ac_cv_prog_OBJDUMP"; then
+  ac_ct_OBJDUMP=$OBJDUMP
+  # Extract the first word of "objdump", so it can be a program name with args.
+set dummy objdump; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 $as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_DLLTOOL+:} false; then :
+if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  if test -n "$ac_ct_DLLTOOL"; then
-  ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test.
+  if test -n "$ac_ct_OBJDUMP"; then
+  ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test.
 else
 as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
@@ -6521,7 +6843,7 @@ do
   test -z "$as_dir" && as_dir=.
     for ac_exec_ext in '' $ac_executable_extensions; do
   if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_DLLTOOL="dlltool"
+    ac_cv_prog_ac_ct_OBJDUMP="objdump"
     $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
@@ -6531,17 +6853,17 @@ IFS=$as_save_IFS
 
 fi
 fi
-ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL
-if test -n "$ac_ct_DLLTOOL"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5
-$as_echo "$ac_ct_DLLTOOL" >&6; }
+ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP
+if test -n "$ac_ct_OBJDUMP"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5
+$as_echo "$ac_ct_OBJDUMP" >&6; }
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
 $as_echo "no" >&6; }
 fi
 
-  if test "x$ac_ct_DLLTOOL" = x; then
-    DLLTOOL="false"
+  if test "x$ac_ct_OBJDUMP" = x; then
+    OBJDUMP="false"
   else
     case $cross_compiling:$ac_tool_warned in
 yes:)
@@ -6549,14 +6871,13 @@ yes:)
 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
 ac_tool_warned=yes ;;
 esac
-    DLLTOOL=$ac_ct_DLLTOOL
+    OBJDUMP=$ac_ct_OBJDUMP
   fi
 else
-  DLLTOOL="$ac_cv_prog_DLLTOOL"
+  OBJDUMP="$ac_cv_prog_OBJDUMP"
 fi
 
-test -z "$DLLTOOL" && DLLTOOL=dlltool
-
+test -z "$OBJDUMP" && OBJDUMP=objdump
 
 
 
@@ -6566,148 +6887,228 @@ test -z "$DLLTOOL" && DLLTOOL=dlltool
 
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to associate runtime and link libraries" >&5
-$as_echo_n "checking how to associate runtime and link libraries... " >&6; }
-if ${lt_cv_sharedlib_from_linklib_cmd+:} false; then :
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to recognize dependent libraries" >&5
+$as_echo_n "checking how to recognize dependent libraries... " >&6; }
+if ${lt_cv_deplibs_check_method+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  lt_cv_sharedlib_from_linklib_cmd='unknown'
+  lt_cv_file_magic_cmd='$MAGIC_CMD'
+lt_cv_file_magic_test_file=
+lt_cv_deplibs_check_method='unknown'
+# Need to set the preceding variable on all platforms that support
+# interlibrary dependencies.
+# 'none' -- dependencies not supported.
+# `unknown' -- same as none, but documents that we really don't know.
+# 'pass_all' -- all dependencies passed with no checks.
+# 'test_compile' -- check by making test program.
+# 'file_magic [[regex]]' -- check by looking for files in library path
+# which responds to the $file_magic_cmd with a given extended regex.
+# If you have `file' or equivalent on your system and you're not sure
+# whether `pass_all' will *always* work, you probably want this one.
 
 case $host_os in
-cygwin* | mingw* | pw32* | cegcc*)
-  # two different shell functions defined in ltmain.sh
-  # decide which to use based on capabilities of $DLLTOOL
-  case `$DLLTOOL --help 2>&1` in
-  *--identify-strict*)
-    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib
-    ;;
-  *)
-    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback
-    ;;
-  esac
-  ;;
-*)
-  # fallback: assume linklib IS sharedlib
-  lt_cv_sharedlib_from_linklib_cmd="$ECHO"
+aix[4-9]*)
+  lt_cv_deplibs_check_method=pass_all
   ;;
-esac
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sharedlib_from_linklib_cmd" >&5
-$as_echo "$lt_cv_sharedlib_from_linklib_cmd" >&6; }
-sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd
-test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO
-
 
+beos*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
 
+bsdi[45]*)
+  lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)'
+  lt_cv_file_magic_cmd='/usr/bin/file -L'
+  lt_cv_file_magic_test_file=/shlib/libc.so
+  ;;
 
+cygwin*)
+  # func_win32_libid is a shell function defined in ltmain.sh
+  lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+  lt_cv_file_magic_cmd='func_win32_libid'
+  ;;
 
+mingw* | pw32*)
+  # Base MSYS/MinGW do not provide the 'file' command needed by
+  # func_win32_libid shell function, so use a weaker test based on 'objdump',
+  # unless we find 'file', for example because we are cross-compiling.
+  # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin.
+  if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then
+    lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+    lt_cv_file_magic_cmd='func_win32_libid'
+  else
+    # Keep this pattern in sync with the one in func_win32_libid.
+    lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)'
+    lt_cv_file_magic_cmd='$OBJDUMP -f'
+  fi
+  ;;
 
+cegcc*)
+  # use the weaker test based on 'objdump'. See mingw*.
+  lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?'
+  lt_cv_file_magic_cmd='$OBJDUMP -f'
+  ;;
 
+darwin* | rhapsody*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
 
-if test -n "$ac_tool_prefix"; then
-  for ac_prog in ar
-  do
-    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
-set dummy $ac_tool_prefix$ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_AR+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$AR"; then
-  ac_cv_prog_AR="$AR" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_AR="$ac_tool_prefix$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
+freebsd* | dragonfly*)
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
+    case $host_cpu in
+    i*86 )
+      # Not sure whether the presence of OpenBSD here was a mistake.
+      # Let's accept both of them until this is cleared up.
+      lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library'
+      lt_cv_file_magic_cmd=/usr/bin/file
+      lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
+      ;;
+    esac
+  else
+    lt_cv_deplibs_check_method=pass_all
   fi
-done
-  done
-IFS=$as_save_IFS
+  ;;
 
-fi
-fi
-AR=$ac_cv_prog_AR
-if test -n "$AR"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5
-$as_echo "$AR" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
+gnu*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
 
+haiku*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
 
-    test -n "$AR" && break
-  done
-fi
-if test -z "$AR"; then
-  ac_ct_AR=$AR
-  for ac_prog in ar
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_AR+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_AR"; then
-  ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_AR="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
+hpux10.20* | hpux11*)
+  lt_cv_file_magic_cmd=/usr/bin/file
+  case $host_cpu in
+  ia64*)
+    lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64'
+    lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
+    ;;
+  hppa*64*)
+    lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]'
+    lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
+    ;;
+  *)
+    lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9]\.[0-9]) shared library'
+    lt_cv_file_magic_test_file=/usr/lib/libc.sl
+    ;;
+  esac
+  ;;
 
-fi
-fi
-ac_ct_AR=$ac_cv_prog_ac_ct_AR
-if test -n "$ac_ct_AR"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5
-$as_echo "$ac_ct_AR" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
+interix[3-9]*)
+  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
+  lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$'
+  ;;
 
+irix5* | irix6* | nonstopux*)
+  case $LD in
+  *-32|*"-32 ") libmagic=32-bit;;
+  *-n32|*"-n32 ") libmagic=N32;;
+  *-64|*"-64 ") libmagic=64-bit;;
+  *) libmagic=never-match;;
+  esac
+  lt_cv_deplibs_check_method=pass_all
+  ;;
 
-  test -n "$ac_ct_AR" && break
-done
+# This must be glibc/ELF.
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
 
-  if test "x$ac_ct_AR" = x; then
-    AR="false"
+netbsd*)
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
+    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$'
   else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    AR=$ac_ct_AR
+    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$'
   fi
-fi
-
-: ${AR=ar}
-: ${AR_FLAGS=cru}
-
+  ;;
+
+newos6*)
+  lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)'
+  lt_cv_file_magic_cmd=/usr/bin/file
+  lt_cv_file_magic_test_file=/usr/lib/libnls.so
+  ;;
+
+*nto* | *qnx*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+openbsd*)
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$'
+  else
+    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$'
+  fi
+  ;;
+
+osf3* | osf4* | osf5*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+rdos*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+solaris*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+sysv4 | sysv4.3*)
+  case $host_vendor in
+  motorola)
+    lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]'
+    lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
+    ;;
+  ncr)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  sequent)
+    lt_cv_file_magic_cmd='/bin/file'
+    lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )'
+    ;;
+  sni)
+    lt_cv_file_magic_cmd='/bin/file'
+    lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib"
+    lt_cv_file_magic_test_file=/lib/libc.so
+    ;;
+  siemens)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  pc)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  esac
+  ;;
+
+tpf*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+esac
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_method" >&5
+$as_echo "$lt_cv_deplibs_check_method" >&6; }
+
+file_magic_glob=
+want_nocaseglob=no
+if test "$build" = "$host"; then
+  case $host_os in
+  mingw* | pw32*)
+    if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then
+      want_nocaseglob=yes
+    else
+      file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[\1]\/[\1]\/g;/g"`
+    fi
+    ;;
+  esac
+fi
+
+file_magic_cmd=$lt_cv_file_magic_cmd
+deplibs_check_method=$lt_cv_deplibs_check_method
+test -z "$deplibs_check_method" && deplibs_check_method=unknown
 
 
 
@@ -6718,57 +7119,11 @@ fi
 
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for archiver @FILE support" >&5
-$as_echo_n "checking for archiver @FILE support... " >&6; }
-if ${lt_cv_ar_at_file+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_ar_at_file=no
-   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
 
-int
-main ()
-{
 
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  echo conftest.$ac_objext > conftest.lst
-      lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&5'
-      { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5
-  (eval $lt_ar_try) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }
-      if test "$ac_status" -eq 0; then
-	# Ensure the archiver fails upon bogus file names.
-	rm -f conftest.$ac_objext libconftest.a
-	{ { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5
-  (eval $lt_ar_try) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }
-	if test "$ac_status" -ne 0; then
-          lt_cv_ar_at_file=@
-        fi
-      fi
-      rm -f conftest.* libconftest.a
 
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5
-$as_echo "$lt_cv_ar_at_file" >&6; }
 
-if test "x$lt_cv_ar_at_file" = xno; then
-  archiver_list_spec=
-else
-  archiver_list_spec=$lt_cv_ar_at_file
-fi
 
 
 
@@ -6777,15 +7132,15 @@ fi
 
 
 if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args.
-set dummy ${ac_tool_prefix}strip; ac_word=$2
+  # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args.
+set dummy ${ac_tool_prefix}dlltool; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 $as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_STRIP+:} false; then :
+if ${ac_cv_prog_DLLTOOL+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  if test -n "$STRIP"; then
-  ac_cv_prog_STRIP="$STRIP" # Let the user override the test.
+  if test -n "$DLLTOOL"; then
+  ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test.
 else
 as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
@@ -6794,7 +7149,7 @@ do
   test -z "$as_dir" && as_dir=.
     for ac_exec_ext in '' $ac_executable_extensions; do
   if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_STRIP="${ac_tool_prefix}strip"
+    ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool"
     $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
@@ -6804,10 +7159,10 @@ IFS=$as_save_IFS
 
 fi
 fi
-STRIP=$ac_cv_prog_STRIP
-if test -n "$STRIP"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5
-$as_echo "$STRIP" >&6; }
+DLLTOOL=$ac_cv_prog_DLLTOOL
+if test -n "$DLLTOOL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5
+$as_echo "$DLLTOOL" >&6; }
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
 $as_echo "no" >&6; }
@@ -6815,17 +7170,17 @@ fi
 
 
 fi
-if test -z "$ac_cv_prog_STRIP"; then
-  ac_ct_STRIP=$STRIP
-  # Extract the first word of "strip", so it can be a program name with args.
-set dummy strip; ac_word=$2
+if test -z "$ac_cv_prog_DLLTOOL"; then
+  ac_ct_DLLTOOL=$DLLTOOL
+  # Extract the first word of "dlltool", so it can be a program name with args.
+set dummy dlltool; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 $as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_STRIP+:} false; then :
+if ${ac_cv_prog_ac_ct_DLLTOOL+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  if test -n "$ac_ct_STRIP"; then
-  ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test.
+  if test -n "$ac_ct_DLLTOOL"; then
+  ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test.
 else
 as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
@@ -6834,7 +7189,7 @@ do
   test -z "$as_dir" && as_dir=.
     for ac_exec_ext in '' $ac_executable_extensions; do
   if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_STRIP="strip"
+    ac_cv_prog_ac_ct_DLLTOOL="dlltool"
     $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
@@ -6844,17 +7199,17 @@ IFS=$as_save_IFS
 
 fi
 fi
-ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP
-if test -n "$ac_ct_STRIP"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5
-$as_echo "$ac_ct_STRIP" >&6; }
+ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL
+if test -n "$ac_ct_DLLTOOL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5
+$as_echo "$ac_ct_DLLTOOL" >&6; }
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
 $as_echo "no" >&6; }
 fi
 
-  if test "x$ac_ct_STRIP" = x; then
-    STRIP=":"
+  if test "x$ac_ct_DLLTOOL" = x; then
+    DLLTOOL="false"
   else
     case $cross_compiling:$ac_tool_warned in
 yes:)
@@ -6862,13 +7217,55 @@ yes:)
 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
 ac_tool_warned=yes ;;
 esac
-    STRIP=$ac_ct_STRIP
+    DLLTOOL=$ac_ct_DLLTOOL
   fi
 else
-  STRIP="$ac_cv_prog_STRIP"
+  DLLTOOL="$ac_cv_prog_DLLTOOL"
 fi
 
-test -z "$STRIP" && STRIP=:
+test -z "$DLLTOOL" && DLLTOOL=dlltool
+
+
+
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to associate runtime and link libraries" >&5
+$as_echo_n "checking how to associate runtime and link libraries... " >&6; }
+if ${lt_cv_sharedlib_from_linklib_cmd+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_sharedlib_from_linklib_cmd='unknown'
+
+case $host_os in
+cygwin* | mingw* | pw32* | cegcc*)
+  # two different shell functions defined in ltmain.sh
+  # decide which to use based on capabilities of $DLLTOOL
+  case `$DLLTOOL --help 2>&1` in
+  *--identify-strict*)
+    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib
+    ;;
+  *)
+    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback
+    ;;
+  esac
+  ;;
+*)
+  # fallback: assume linklib IS sharedlib
+  lt_cv_sharedlib_from_linklib_cmd="$ECHO"
+  ;;
+esac
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sharedlib_from_linklib_cmd" >&5
+$as_echo "$lt_cv_sharedlib_from_linklib_cmd" >&6; }
+sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd
+test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO
+
 
 
 
@@ -6876,15 +7273,17 @@ test -z "$STRIP" && STRIP=:
 
 
 if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
-set dummy ${ac_tool_prefix}ranlib; ac_word=$2
+  for ac_prog in ar
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 $as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_RANLIB+:} false; then :
+if ${ac_cv_prog_AR+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  if test -n "$RANLIB"; then
-  ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
+  if test -n "$AR"; then
+  ac_cv_prog_AR="$AR" # Let the user override the test.
 else
 as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
@@ -6893,7 +7292,7 @@ do
   test -z "$as_dir" && as_dir=.
     for ac_exec_ext in '' $ac_executable_extensions; do
   if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
+    ac_cv_prog_AR="$ac_tool_prefix$ac_prog"
     $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
@@ -6903,28 +7302,32 @@ IFS=$as_save_IFS
 
 fi
 fi
-RANLIB=$ac_cv_prog_RANLIB
-if test -n "$RANLIB"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5
-$as_echo "$RANLIB" >&6; }
+AR=$ac_cv_prog_AR
+if test -n "$AR"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5
+$as_echo "$AR" >&6; }
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
 $as_echo "no" >&6; }
 fi
 
 
+    test -n "$AR" && break
+  done
 fi
-if test -z "$ac_cv_prog_RANLIB"; then
-  ac_ct_RANLIB=$RANLIB
-  # Extract the first word of "ranlib", so it can be a program name with args.
-set dummy ranlib; ac_word=$2
+if test -z "$AR"; then
+  ac_ct_AR=$AR
+  for ac_prog in ar
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 $as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_RANLIB+:} false; then :
+if ${ac_cv_prog_ac_ct_AR+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  if test -n "$ac_ct_RANLIB"; then
-  ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
+  if test -n "$ac_ct_AR"; then
+  ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test.
 else
 as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
@@ -6933,7 +7336,7 @@ do
   test -z "$as_dir" && as_dir=.
     for ac_exec_ext in '' $ac_executable_extensions; do
   if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_RANLIB="ranlib"
+    ac_cv_prog_ac_ct_AR="$ac_prog"
     $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
@@ -6943,17 +7346,21 @@ IFS=$as_save_IFS
 
 fi
 fi
-ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
-if test -n "$ac_ct_RANLIB"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5
-$as_echo "$ac_ct_RANLIB" >&6; }
+ac_ct_AR=$ac_cv_prog_ac_ct_AR
+if test -n "$ac_ct_AR"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5
+$as_echo "$ac_ct_AR" >&6; }
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
 $as_echo "no" >&6; }
 fi
 
-  if test "x$ac_ct_RANLIB" = x; then
-    RANLIB=":"
+
+  test -n "$ac_ct_AR" && break
+done
+
+  if test "x$ac_ct_AR" = x; then
+    AR="false"
   else
     case $cross_compiling:$ac_tool_warned in
 yes:)
@@ -6961,50 +7368,12 @@ yes:)
 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
 ac_tool_warned=yes ;;
 esac
-    RANLIB=$ac_ct_RANLIB
+    AR=$ac_ct_AR
   fi
-else
-  RANLIB="$ac_cv_prog_RANLIB"
-fi
-
-test -z "$RANLIB" && RANLIB=:
-
-
-
-
-
-
-# Determine commands to create old-style static archives.
-old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs'
-old_postinstall_cmds='chmod 644 $oldlib'
-old_postuninstall_cmds=
-
-if test -n "$RANLIB"; then
-  case $host_os in
-  openbsd*)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib"
-    ;;
-  *)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib"
-    ;;
-  esac
-  old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib"
 fi
 
-case $host_os in
-  darwin*)
-    lock_old_archive_extraction=yes ;;
-  *)
-    lock_old_archive_extraction=no ;;
-esac
-
-
-
-
-
-
-
-
+: ${AR=ar}
+: ${AR_FLAGS=cru}
 
 
 
@@ -7016,11 +7385,57 @@ esac
 
 
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for archiver @FILE support" >&5
+$as_echo_n "checking for archiver @FILE support... " >&6; }
+if ${lt_cv_ar_at_file+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_ar_at_file=no
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
 
+int
+main ()
+{
 
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  echo conftest.$ac_objext > conftest.lst
+      lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&5'
+      { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5
+  (eval $lt_ar_try) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+      if test "$ac_status" -eq 0; then
+	# Ensure the archiver fails upon bogus file names.
+	rm -f conftest.$ac_objext libconftest.a
+	{ { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5
+  (eval $lt_ar_try) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+	if test "$ac_status" -ne 0; then
+          lt_cv_ar_at_file=@
+        fi
+      fi
+      rm -f conftest.* libconftest.a
 
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5
+$as_echo "$lt_cv_ar_at_file" >&6; }
 
+if test "x$lt_cv_ar_at_file" = xno; then
+  archiver_list_spec=
+else
+  archiver_list_spec=$lt_cv_ar_at_file
+fi
 
 
 
@@ -7028,45 +7443,297 @@ esac
 
 
 
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args.
+set dummy ${ac_tool_prefix}strip; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_STRIP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$STRIP"; then
+  ac_cv_prog_STRIP="$STRIP" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_STRIP="${ac_tool_prefix}strip"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
+fi
+fi
+STRIP=$ac_cv_prog_STRIP
+if test -n "$STRIP"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5
+$as_echo "$STRIP" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
 
+fi
+if test -z "$ac_cv_prog_STRIP"; then
+  ac_ct_STRIP=$STRIP
+  # Extract the first word of "strip", so it can be a program name with args.
+set dummy strip; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_STRIP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_STRIP"; then
+  ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_ac_ct_STRIP="strip"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
+fi
+fi
+ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP
+if test -n "$ac_ct_STRIP"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5
+$as_echo "$ac_ct_STRIP" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
+  if test "x$ac_ct_STRIP" = x; then
+    STRIP=":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    STRIP=$ac_ct_STRIP
+  fi
+else
+  STRIP="$ac_cv_prog_STRIP"
+fi
 
+test -z "$STRIP" && STRIP=:
 
 
-# If no C compiler was specified, use CC.
-LTCC=${LTCC-"$CC"}
 
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
 
-# Allow CC to be a program name with arguments.
-compiler=$CC
 
 
-# Check for command to grab the raw symbol name followed by C symbol from nm.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking command to parse $NM output from $compiler object" >&5
-$as_echo_n "checking command to parse $NM output from $compiler object... " >&6; }
-if ${lt_cv_sys_global_symbol_pipe+:} false; then :
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
+set dummy ${ac_tool_prefix}ranlib; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_RANLIB+:} false; then :
   $as_echo_n "(cached) " >&6
 else
+  if test -n "$RANLIB"; then
+  ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-# These are sane defaults that work on at least a few old systems.
-# [They come from Ultrix.  What could be older than Ultrix?!! ;)]
-
-# Character class describing NM global symbol codes.
-symcode='[BCDEGRST]'
+fi
+fi
+RANLIB=$ac_cv_prog_RANLIB
+if test -n "$RANLIB"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5
+$as_echo "$RANLIB" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
-# Regexp to match symbols that can be accessed directly from C.
-sympat='\([_A-Za-z][_A-Za-z0-9]*\)'
 
-# Define system-specific variables.
-case $host_os in
-aix*)
-  symcode='[BCDT]'
-  ;;
+fi
+if test -z "$ac_cv_prog_RANLIB"; then
+  ac_ct_RANLIB=$RANLIB
+  # Extract the first word of "ranlib", so it can be a program name with args.
+set dummy ranlib; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_RANLIB+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_RANLIB"; then
+  ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_ac_ct_RANLIB="ranlib"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
+if test -n "$ac_ct_RANLIB"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5
+$as_echo "$ac_ct_RANLIB" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_RANLIB" = x; then
+    RANLIB=":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    RANLIB=$ac_ct_RANLIB
+  fi
+else
+  RANLIB="$ac_cv_prog_RANLIB"
+fi
+
+test -z "$RANLIB" && RANLIB=:
+
+
+
+
+
+
+# Determine commands to create old-style static archives.
+old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs'
+old_postinstall_cmds='chmod 644 $oldlib'
+old_postuninstall_cmds=
+
+if test -n "$RANLIB"; then
+  case $host_os in
+  openbsd*)
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib"
+    ;;
+  *)
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib"
+    ;;
+  esac
+  old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib"
+fi
+
+case $host_os in
+  darwin*)
+    lock_old_archive_extraction=yes ;;
+  *)
+    lock_old_archive_extraction=no ;;
+esac
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+
+
+# Check for command to grab the raw symbol name followed by C symbol from nm.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking command to parse $NM output from $compiler object" >&5
+$as_echo_n "checking command to parse $NM output from $compiler object... " >&6; }
+if ${lt_cv_sys_global_symbol_pipe+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+
+# These are sane defaults that work on at least a few old systems.
+# [They come from Ultrix.  What could be older than Ultrix?!! ;)]
+
+# Character class describing NM global symbol codes.
+symcode='[BCDEGRST]'
+
+# Regexp to match symbols that can be accessed directly from C.
+sympat='\([_A-Za-z][_A-Za-z0-9]*\)'
+
+# Define system-specific variables.
+case $host_os in
+aix*)
+  symcode='[BCDT]'
+  ;;
 cygwin* | mingw* | pw32* | cegcc*)
   symcode='[ABCDGISTW]'
   ;;
@@ -8314,200 +8981,63 @@ $as_echo "$lt_cv_ld_force_load" >&6; }
     ;;
   esac
 
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
-$as_echo_n "checking how to run the C preprocessor... " >&6; }
-# On Suns, sometimes $CPP names a directory.
-if test -n "$CPP" && test -d "$CPP"; then
-  CPP=
-fi
-if test -z "$CPP"; then
-  if ${ac_cv_prog_CPP+:} false; then :
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
+$as_echo_n "checking for ANSI C header files... " >&6; }
+if ${ac_cv_header_stdc+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-      # Double quotes because CPP needs to be expanded
-    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
-    do
-      ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
-do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-		     Syntax error
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <float.h>
+
+int
+main ()
+{
 
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_header_stdc=yes
 else
-  # Broken: fails on valid input.
-continue
+  ac_cv_header_stdc=no
 fi
-rm -f conftest.err conftest.i conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 
-  # OK, works on sane cases.  Now check whether nonexistent headers
-  # can be detected and how.
+if test $ac_cv_header_stdc = yes; then
+  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-#include <ac_nonexistent.h>
+#include <string.h>
+
 _ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-  # Broken: success on invalid input.
-continue
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "memchr" >/dev/null 2>&1; then :
+
 else
-  # Passes both tests.
-ac_preproc_ok=:
-break
+  ac_cv_header_stdc=no
 fi
-rm -f conftest.err conftest.i conftest.$ac_ext
+rm -f conftest*
 
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.i conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then :
-  break
 fi
 
-    done
-    ac_cv_prog_CPP=$CPP
+if test $ac_cv_header_stdc = yes; then
+  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "free" >/dev/null 2>&1; then :
 
-fi
-  CPP=$ac_cv_prog_CPP
 else
-  ac_cv_prog_CPP=$CPP
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
-$as_echo "$CPP" >&6; }
-ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
-do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-		     Syntax error
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-
-else
-  # Broken: fails on valid input.
-continue
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-  # OK, works on sane cases.  Now check whether nonexistent headers
-  # can be detected and how.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <ac_nonexistent.h>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-  # Broken: success on invalid input.
-continue
-else
-  # Passes both tests.
-ac_preproc_ok=:
-break
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.i conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then :
-
-else
-  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
-$as_echo_n "checking for ANSI C header files... " >&6; }
-if ${ac_cv_header_stdc+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <float.h>
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_header_stdc=yes
-else
-  ac_cv_header_stdc=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-if test $ac_cv_header_stdc = yes; then
-  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <string.h>
-
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "memchr" >/dev/null 2>&1; then :
-
-else
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdlib.h>
-
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "free" >/dev/null 2>&1; then :
-
-else
-  ac_cv_header_stdc=no
+  ac_cv_header_stdc=no
 fi
 rm -f conftest*
 
@@ -11381,3758 +11911,2062 @@ freebsd* | dragonfly*)
   esac
   ;;
 
-gnu*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
-
-haiku*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  dynamic_linker="$host_os runtime_loader"
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib'
-  hardcode_into_libs=yes
-  ;;
-
-hpux9* | hpux10* | hpux11*)
-  # Give a soname corresponding to the major version so that dld.sl refuses to
-  # link against other versions.
-  version_type=sunos
-  need_lib_prefix=no
-  need_version=no
-  case $host_cpu in
-  ia64*)
-    shrext_cmds='.so'
-    hardcode_into_libs=yes
-    dynamic_linker="$host_os dld.so"
-    shlibpath_var=LD_LIBRARY_PATH
-    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    if test "X$HPUX_IA64_MODE" = X32; then
-      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
-    else
-      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
-    fi
-    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
-    ;;
-  hppa*64*)
-    shrext_cmds='.sl'
-    hardcode_into_libs=yes
-    dynamic_linker="$host_os dld.sl"
-    shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
-    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
-    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
-    ;;
-  *)
-    shrext_cmds='.sl'
-    dynamic_linker="$host_os dld.sl"
-    shlibpath_var=SHLIB_PATH
-    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    ;;
-  esac
-  # HP-UX runs *really* slowly unless shared libraries are mode 555, ...
-  postinstall_cmds='chmod 555 $lib'
-  # or fails outright, so override atomically:
-  install_override_mode=555
-  ;;
-
-interix[3-9]*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
-
-irix5* | irix6* | nonstopux*)
-  case $host_os in
-    nonstopux*) version_type=nonstopux ;;
-    *)
-	if test "$lt_cv_prog_gnu_ld" = yes; then
-		version_type=linux # correct to gnu/linux during the next big refactor
-	else
-		version_type=irix
-	fi ;;
-  esac
-  need_lib_prefix=no
-  need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
-  case $host_os in
-  irix5* | nonstopux*)
-    libsuff= shlibsuff=
-    ;;
-  *)
-    case $LD in # libtool.m4 will add one of these switches to LD
-    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
-      libsuff= shlibsuff= libmagic=32-bit;;
-    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
-      libsuff=32 shlibsuff=N32 libmagic=N32;;
-    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
-      libsuff=64 shlibsuff=64 libmagic=64-bit;;
-    *) libsuff= shlibsuff= libmagic=never-match;;
-    esac
-    ;;
-  esac
-  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
-  shlibpath_overrides_runpath=no
-  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
-  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
-  hardcode_into_libs=yes
-  ;;
-
-# No shared lib support for Linux oldld, aout, or coff.
-linux*oldld* | linux*aout* | linux*coff*)
-  dynamic_linker=no
-  ;;
-
-# This must be glibc/ELF.
-linux* | k*bsd*-gnu | kopensolaris*-gnu)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-
-  # Some binutils ld are patched to set DT_RUNPATH
-  if ${lt_cv_shlibpath_overrides_runpath+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_shlibpath_overrides_runpath=no
-    save_LDFLAGS=$LDFLAGS
-    save_libdir=$libdir
-    eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \
-	 LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec\""
-    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  if  ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then :
-  lt_cv_shlibpath_overrides_runpath=yes
-fi
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-    LDFLAGS=$save_LDFLAGS
-    libdir=$save_libdir
-
-fi
-
-  shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath
-
-  # This implies no fast_install, which is unacceptable.
-  # Some rework will be needed to allow for fast_install
-  # before this can be enabled.
-  hardcode_into_libs=yes
-
-  # Add ABI-specific directories to the system library path.
-  sys_lib_dlsearch_path_spec="/lib64 /usr/lib64 /lib /usr/lib"
-
-  # Append ld.so.conf contents to the search path
-  if test -f /etc/ld.so.conf; then
-    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '`
-    sys_lib_dlsearch_path_spec="$sys_lib_dlsearch_path_spec $lt_ld_extra"
-
-  fi
-
-  # We used to test for /lib/ld.so.1 and disable shared libraries on
-  # powerpc, because MkLinux only supported shared libraries with the
-  # GNU dynamic linker.  Since this was broken with cross compilers,
-  # most powerpc-linux boxes support dynamic linking these days and
-  # people can always --disable-shared, the test was removed, and we
-  # assume the GNU/Linux dynamic linker is in use.
-  dynamic_linker='GNU/Linux ld.so'
-  ;;
-
-netbsd*)
-  version_type=sunos
-  need_lib_prefix=no
-  need_version=no
-  if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-    dynamic_linker='NetBSD (a.out) ld.so'
-  else
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    dynamic_linker='NetBSD ld.elf_so'
-  fi
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  ;;
-
-newsos6)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  ;;
-
-*nto* | *qnx*)
-  version_type=qnx
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  dynamic_linker='ldqnx.so'
-  ;;
-
-openbsd*)
-  version_type=sunos
-  sys_lib_dlsearch_path_spec="/usr/lib"
-  need_lib_prefix=no
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*)	need_version=yes ;;
-    *)				need_version=no  ;;
-  esac
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-    case $host_os in
-      openbsd2.[89] | openbsd2.[89].*)
-	shlibpath_overrides_runpath=no
-	;;
-      *)
-	shlibpath_overrides_runpath=yes
-	;;
-      esac
-  else
-    shlibpath_overrides_runpath=yes
-  fi
-  ;;
-
-os2*)
-  libname_spec='$name'
-  shrext_cmds=".dll"
-  need_lib_prefix=no
-  library_names_spec='$libname${shared_ext} $libname.a'
-  dynamic_linker='OS/2 ld.exe'
-  shlibpath_var=LIBPATH
-  ;;
-
-osf3* | osf4* | osf5*)
-  version_type=osf
-  need_lib_prefix=no
-  need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
-  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
-  ;;
-
-rdos*)
-  dynamic_linker=no
-  ;;
-
-solaris*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  # ldd complains unless libraries are executable
-  postinstall_cmds='chmod +x $lib'
-  ;;
-
-sunos4*)
-  version_type=sunos
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  if test "$with_gnu_ld" = yes; then
-    need_lib_prefix=no
-  fi
-  need_version=yes
-  ;;
-
-sysv4 | sysv4.3*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  case $host_vendor in
-    sni)
-      shlibpath_overrides_runpath=no
-      need_lib_prefix=no
-      runpath_var=LD_RUN_PATH
-      ;;
-    siemens)
-      need_lib_prefix=no
-      ;;
-    motorola)
-      need_lib_prefix=no
-      need_version=no
-      shlibpath_overrides_runpath=no
-      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
-      ;;
-  esac
-  ;;
-
-sysv4*MP*)
-  if test -d /usr/nec ;then
-    version_type=linux # correct to gnu/linux during the next big refactor
-    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
-    soname_spec='$libname${shared_ext}.$major'
-    shlibpath_var=LD_LIBRARY_PATH
-  fi
-  ;;
-
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=freebsd-elf
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  if test "$with_gnu_ld" = yes; then
-    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
-  else
-    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
-    case $host_os in
-      sco3.2v5*)
-        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
-	;;
-    esac
-  fi
-  sys_lib_dlsearch_path_spec='/usr/lib'
-  ;;
-
-tpf*)
-  # TPF is a cross-target only.  Preferred cross-host = GNU/Linux.
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
-
-uts4*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  ;;
-
-*)
-  dynamic_linker=no
-  ;;
-esac
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5
-$as_echo "$dynamic_linker" >&6; }
-test "$dynamic_linker" = no && can_build_shared=no
-
-variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
-if test "$GCC" = yes; then
-  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
-fi
-
-if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
-  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
-fi
-if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
-  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
-fi
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5
-$as_echo_n "checking how to hardcode library paths into programs... " >&6; }
-hardcode_action=
-if test -n "$hardcode_libdir_flag_spec" ||
-   test -n "$runpath_var" ||
-   test "X$hardcode_automatic" = "Xyes" ; then
-
-  # We can hardcode non-existent directories.
-  if test "$hardcode_direct" != no &&
-     # If the only mechanism to avoid hardcoding is shlibpath_var, we
-     # have to relink, otherwise we might link with an installed library
-     # when we should be linking with a yet-to-be-installed one
-     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, )" != no &&
-     test "$hardcode_minus_L" != no; then
-    # Linking always hardcodes the temporary library directory.
-    hardcode_action=relink
-  else
-    # We can link without hardcoding, and we can hardcode nonexisting dirs.
-    hardcode_action=immediate
-  fi
-else
-  # We cannot hardcode anything, or else we can only hardcode existing
-  # directories.
-  hardcode_action=unsupported
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5
-$as_echo "$hardcode_action" >&6; }
-
-if test "$hardcode_action" = relink ||
-   test "$inherit_rpath" = yes; then
-  # Fast installation is not supported
-  enable_fast_install=no
-elif test "$shlibpath_overrides_runpath" = yes ||
-     test "$enable_shared" = no; then
-  # Fast installation is not necessary
-  enable_fast_install=needless
-fi
-
-
-
-
-
-
-  if test "x$enable_dlopen" != xyes; then
-  enable_dlopen=unknown
-  enable_dlopen_self=unknown
-  enable_dlopen_self_static=unknown
-else
-  lt_cv_dlopen=no
-  lt_cv_dlopen_libs=
-
-  case $host_os in
-  beos*)
-    lt_cv_dlopen="load_add_on"
-    lt_cv_dlopen_libs=
-    lt_cv_dlopen_self=yes
-    ;;
-
-  mingw* | pw32* | cegcc*)
-    lt_cv_dlopen="LoadLibrary"
-    lt_cv_dlopen_libs=
-    ;;
-
-  cygwin*)
-    lt_cv_dlopen="dlopen"
-    lt_cv_dlopen_libs=
-    ;;
-
-  darwin*)
-  # if libdl is installed we need to link against it
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
-$as_echo_n "checking for dlopen in -ldl... " >&6; }
-if ${ac_cv_lib_dl_dlopen+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-ldl  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char dlopen ();
-int
-main ()
-{
-return dlopen ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_dl_dlopen=yes
-else
-  ac_cv_lib_dl_dlopen=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
-$as_echo "$ac_cv_lib_dl_dlopen" >&6; }
-if test "x$ac_cv_lib_dl_dlopen" = xyes; then :
-  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
-else
-
-    lt_cv_dlopen="dyld"
-    lt_cv_dlopen_libs=
-    lt_cv_dlopen_self=yes
-
-fi
-
-    ;;
-
-  *)
-    ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load"
-if test "x$ac_cv_func_shl_load" = xyes; then :
-  lt_cv_dlopen="shl_load"
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5
-$as_echo_n "checking for shl_load in -ldld... " >&6; }
-if ${ac_cv_lib_dld_shl_load+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-ldld  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char shl_load ();
-int
-main ()
-{
-return shl_load ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_dld_shl_load=yes
-else
-  ac_cv_lib_dld_shl_load=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5
-$as_echo "$ac_cv_lib_dld_shl_load" >&6; }
-if test "x$ac_cv_lib_dld_shl_load" = xyes; then :
-  lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"
-else
-  ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen"
-if test "x$ac_cv_func_dlopen" = xyes; then :
-  lt_cv_dlopen="dlopen"
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
-$as_echo_n "checking for dlopen in -ldl... " >&6; }
-if ${ac_cv_lib_dl_dlopen+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-ldl  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char dlopen ();
-int
-main ()
-{
-return dlopen ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_dl_dlopen=yes
-else
-  ac_cv_lib_dl_dlopen=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
-$as_echo "$ac_cv_lib_dl_dlopen" >&6; }
-if test "x$ac_cv_lib_dl_dlopen" = xyes; then :
-  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5
-$as_echo_n "checking for dlopen in -lsvld... " >&6; }
-if ${ac_cv_lib_svld_dlopen+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lsvld  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char dlopen ();
-int
-main ()
-{
-return dlopen ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_svld_dlopen=yes
-else
-  ac_cv_lib_svld_dlopen=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5
-$as_echo "$ac_cv_lib_svld_dlopen" >&6; }
-if test "x$ac_cv_lib_svld_dlopen" = xyes; then :
-  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5
-$as_echo_n "checking for dld_link in -ldld... " >&6; }
-if ${ac_cv_lib_dld_dld_link+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-ldld  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char dld_link ();
-int
-main ()
-{
-return dld_link ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_dld_dld_link=yes
-else
-  ac_cv_lib_dld_dld_link=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5
-$as_echo "$ac_cv_lib_dld_dld_link" >&6; }
-if test "x$ac_cv_lib_dld_dld_link" = xyes; then :
-  lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"
-fi
-
-
-fi
-
-
-fi
-
-
-fi
-
-
-fi
-
-
-fi
-
-    ;;
-  esac
-
-  if test "x$lt_cv_dlopen" != xno; then
-    enable_dlopen=yes
-  else
-    enable_dlopen=no
-  fi
-
-  case $lt_cv_dlopen in
-  dlopen)
-    save_CPPFLAGS="$CPPFLAGS"
-    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
-
-    save_LDFLAGS="$LDFLAGS"
-    wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
-
-    save_LIBS="$LIBS"
-    LIBS="$lt_cv_dlopen_libs $LIBS"
-
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5
-$as_echo_n "checking whether a program can dlopen itself... " >&6; }
-if ${lt_cv_dlopen_self+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  	  if test "$cross_compiling" = yes; then :
-  lt_cv_dlopen_self=cross
-else
-  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
-  lt_status=$lt_dlunknown
-  cat > conftest.$ac_ext <<_LT_EOF
-#line $LINENO "configure"
-#include "confdefs.h"
-
-#if HAVE_DLFCN_H
-#include <dlfcn.h>
-#endif
-
-#include <stdio.h>
-
-#ifdef RTLD_GLOBAL
-#  define LT_DLGLOBAL		RTLD_GLOBAL
-#else
-#  ifdef DL_GLOBAL
-#    define LT_DLGLOBAL		DL_GLOBAL
-#  else
-#    define LT_DLGLOBAL		0
-#  endif
-#endif
-
-/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
-   find out it does not work in some platform. */
-#ifndef LT_DLLAZY_OR_NOW
-#  ifdef RTLD_LAZY
-#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
-#  else
-#    ifdef DL_LAZY
-#      define LT_DLLAZY_OR_NOW		DL_LAZY
-#    else
-#      ifdef RTLD_NOW
-#        define LT_DLLAZY_OR_NOW	RTLD_NOW
-#      else
-#        ifdef DL_NOW
-#          define LT_DLLAZY_OR_NOW	DL_NOW
-#        else
-#          define LT_DLLAZY_OR_NOW	0
-#        endif
-#      endif
-#    endif
-#  endif
-#endif
-
-/* When -fvisbility=hidden is used, assume the code has been annotated
-   correspondingly for the symbols needed.  */
-#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
-int fnord () __attribute__((visibility("default")));
-#endif
-
-int fnord () { return 42; }
-int main ()
-{
-  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
-  int status = $lt_dlunknown;
-
-  if (self)
-    {
-      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
-      else
-        {
-	  if (dlsym( self,"_fnord"))  status = $lt_dlneed_uscore;
-          else puts (dlerror ());
-	}
-      /* dlclose (self); */
-    }
-  else
-    puts (dlerror ());
-
-  return status;
-}
-_LT_EOF
-  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5
-  (eval $ac_link) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then
-    (./conftest; exit; ) >&5 2>/dev/null
-    lt_status=$?
-    case x$lt_status in
-      x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;;
-      x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;;
-      x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;;
-    esac
-  else :
-    # compilation failed
-    lt_cv_dlopen_self=no
-  fi
-fi
-rm -fr conftest*
-
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5
-$as_echo "$lt_cv_dlopen_self" >&6; }
-
-    if test "x$lt_cv_dlopen_self" = xyes; then
-      wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
-      { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5
-$as_echo_n "checking whether a statically linked program can dlopen itself... " >&6; }
-if ${lt_cv_dlopen_self_static+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  	  if test "$cross_compiling" = yes; then :
-  lt_cv_dlopen_self_static=cross
-else
-  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
-  lt_status=$lt_dlunknown
-  cat > conftest.$ac_ext <<_LT_EOF
-#line $LINENO "configure"
-#include "confdefs.h"
-
-#if HAVE_DLFCN_H
-#include <dlfcn.h>
-#endif
-
-#include <stdio.h>
-
-#ifdef RTLD_GLOBAL
-#  define LT_DLGLOBAL		RTLD_GLOBAL
-#else
-#  ifdef DL_GLOBAL
-#    define LT_DLGLOBAL		DL_GLOBAL
-#  else
-#    define LT_DLGLOBAL		0
-#  endif
-#endif
-
-/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
-   find out it does not work in some platform. */
-#ifndef LT_DLLAZY_OR_NOW
-#  ifdef RTLD_LAZY
-#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
-#  else
-#    ifdef DL_LAZY
-#      define LT_DLLAZY_OR_NOW		DL_LAZY
-#    else
-#      ifdef RTLD_NOW
-#        define LT_DLLAZY_OR_NOW	RTLD_NOW
-#      else
-#        ifdef DL_NOW
-#          define LT_DLLAZY_OR_NOW	DL_NOW
-#        else
-#          define LT_DLLAZY_OR_NOW	0
-#        endif
-#      endif
-#    endif
-#  endif
-#endif
-
-/* When -fvisbility=hidden is used, assume the code has been annotated
-   correspondingly for the symbols needed.  */
-#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
-int fnord () __attribute__((visibility("default")));
-#endif
-
-int fnord () { return 42; }
-int main ()
-{
-  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
-  int status = $lt_dlunknown;
-
-  if (self)
-    {
-      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
-      else
-        {
-	  if (dlsym( self,"_fnord"))  status = $lt_dlneed_uscore;
-          else puts (dlerror ());
-	}
-      /* dlclose (self); */
-    }
-  else
-    puts (dlerror ());
-
-  return status;
-}
-_LT_EOF
-  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5
-  (eval $ac_link) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then
-    (./conftest; exit; ) >&5 2>/dev/null
-    lt_status=$?
-    case x$lt_status in
-      x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;;
-      x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;;
-      x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;;
-    esac
-  else :
-    # compilation failed
-    lt_cv_dlopen_self_static=no
-  fi
-fi
-rm -fr conftest*
-
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static" >&5
-$as_echo "$lt_cv_dlopen_self_static" >&6; }
-    fi
-
-    CPPFLAGS="$save_CPPFLAGS"
-    LDFLAGS="$save_LDFLAGS"
-    LIBS="$save_LIBS"
-    ;;
-  esac
-
-  case $lt_cv_dlopen_self in
-  yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
-  *) enable_dlopen_self=unknown ;;
-  esac
-
-  case $lt_cv_dlopen_self_static in
-  yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
-  *) enable_dlopen_self_static=unknown ;;
-  esac
-fi
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-striplib=
-old_striplib=
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stripping libraries is possible" >&5
-$as_echo_n "checking whether stripping libraries is possible... " >&6; }
-if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then
-  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
-  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
-# FIXME - insert some real tests, host_os isn't really good enough
-  case $host_os in
-  darwin*)
-    if test -n "$STRIP" ; then
-      striplib="$STRIP -x"
-      old_striplib="$STRIP -S"
-      { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-    else
-      { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-    fi
-    ;;
-  *)
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-    ;;
-  esac
-fi
-
-
-
-
-
-
-
-
-
-
-
-
-  # Report which library types will actually be built
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if libtool supports shared libraries" >&5
-$as_echo_n "checking if libtool supports shared libraries... " >&6; }
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5
-$as_echo "$can_build_shared" >&6; }
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries" >&5
-$as_echo_n "checking whether to build shared libraries... " >&6; }
-  test "$can_build_shared" = "no" && enable_shared=no
-
-  # On AIX, shared libraries and static libraries use the same namespace, and
-  # are all built from PIC.
-  case $host_os in
-  aix3*)
-    test "$enable_shared" = yes && enable_static=no
-    if test -n "$RANLIB"; then
-      archive_cmds="$archive_cmds~\$RANLIB \$lib"
-      postinstall_cmds='$RANLIB $lib'
-    fi
-    ;;
-
-  aix[4-9]*)
-    if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-      test "$enable_shared" = yes && enable_static=no
-    fi
-    ;;
-  esac
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5
-$as_echo "$enable_shared" >&6; }
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries" >&5
-$as_echo_n "checking whether to build static libraries... " >&6; }
-  # Make sure either enable_shared or enable_static is yes.
-  test "$enable_shared" = yes || enable_static=yes
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5
-$as_echo "$enable_static" >&6; }
-
-
-
-
-fi
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-CC="$lt_save_CC"
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-        ac_config_commands="$ac_config_commands libtool"
-
-
-
-
-# Only expand once:
-
-
-
-
-# Checks for libraries.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
-$as_echo "" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: *********** Checking libraries ***********************" >&5
-$as_echo "*********** Checking libraries ***********************" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
-$as_echo "" >&6; }
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for pow in -lm" >&5
-$as_echo_n "checking for pow in -lm... " >&6; }
-if ${ac_cv_lib_m_pow+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lm  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char pow ();
-int
-main ()
-{
-return pow ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_m_pow=yes
-else
-  ac_cv_lib_m_pow=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_m_pow" >&5
-$as_echo "$ac_cv_lib_m_pow" >&6; }
-if test "x$ac_cv_lib_m_pow" = xyes; then :
-  LIBS="$LIBS -lm"
-else
-  as_fn_error $? "Library math not found" "$LINENO" 5
-fi
-
-#AC_CHECK_LIB(socket, socket, [LIBS="$LIBS -lsocket"])
-#AC_CHECK_LIB(nsl, inet_ntoa, [LIBS="$LIBS -lnsl"])
-#AC_CHECK_LIB(gslcblas, main, [LIBS="$LIBS -lgslcblas"], AC_MSG_ERROR([Library gslcblas not found]))
-#AC_CHECK_LIB(main, [LIBS="$LIBS"], AC_MSG_ERROR([Library gslcblas not found]))
-
-
-
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GSL" >&5
-$as_echo_n "checking for GSL... " >&6; }
-
-    gsl_check_gsl_lib="-lgsl -lgslcblas"
-
-    gsl_includes=""
-    gsl_ldflags=""
-
-
-# Check whether --with-gsl was given.
-if test "${with_gsl+set}" = set; then :
-  withval=$with_gsl;
-                    gsl_with_gsl_includes=$withval/include
-                    # opensuse defaults also non systems installations to lib64 ...
-                    gsl_with_gsl_libs="-L$withval/lib -L$withval/lib64 -L$withval/lib32"
-
-fi
-
-
-
-# Check whether --with-gsl-includes was given.
-if test "${with_gsl_includes+set}" = set; then :
-  withval=$with_gsl_includes; gsl_with_gsl_includes=$withval
-fi
-
-
-
-# Check whether --with-gsl-libs was given.
-if test "${with_gsl_libs+set}" = set; then :
-  withval=$with_gsl_libs; gsl_with_gsl_libs=-L$withval
-fi
-
-
-    # Check whether --enable-gsl-test was given.
-if test "${enable_gsl_test+set}" = set; then :
-  enableval=$enable_gsl_test; gsl_enable_gsl_test=$enableval
-else
-  gsl_enable_gsl_test=yes
-fi
-
-
-
-    if test "x$gsl_enable_gsl_test" = xyes; then
-
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking checking for gsl" >&5
-$as_echo_n "checking checking for gsl... " >&6; }
-        save_LDFLAGS="$LDFLAGS"
-        save_LIBS="$LIBS"
-        save_CFLAGS="$CFLAGS"
-        if test -n "$gsl_with_gsl_libs"; then
-            LDFLAGS="$gsl_with_gsl_libs"
-        elif test -n "$GSLDIR"; then
-            LDFLAGS="-L$GSLDIR/lib -L$GSLDIR/lib64 -L$GSLDIR/lib32"
-        fi
-        if test -n "$gsl_with_gsl_includes"; then
-            CFLAGS="-I$gsl_with_gsl_includes"
-        elif test -n "$GSLDIR"; then
-            CFLAGS="-I$GSLDIR/include"
-        fi
-        LIBS=$gsl_check_gsl_lib
-
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <gsl/gsl_sf_bessel.h>
-int
-main ()
-{
-gsl_sf_bessel_J0(5.);
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-
-                        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-                        gsl_includes=$CFLAGS
-                        gsl_ldflags=$LDFLAGS
-
-else
-
-                        as_fn_error $? "GSL not found" "$LINENO" 5
-
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-
-        # Set up the symbols
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_GSL 1
-_ACEOF
-
-
-        GSL_INCLUDES="$gsl_includes"
-        GSL_LDFLAGS="$gsl_ldflags"
-        GSL_LIBS="$gsl_check_gsl_lib"
-        LDFLAGS="$save_LDFLAGS"
-        LIBS="$save_LIBS"
-        CFLAGS="$save_CFLAGS"
-    else
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5
-$as_echo "disabled" >&6; }
-        { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: GSL checks have been disabled! This package may not build!" >&5
-$as_echo "$as_me: WARNING: GSL checks have been disabled! This package may not build!" >&2;}
-        GSL_INCLUDES=""
-        GSL_LDFLAGS=""
-        GSL_LIBS=""
-    fi
-
-
-
-
-
-
-
-# Checks for header files.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: *********** Checking headers *************************" >&5
-$as_echo "*********** Checking headers *************************" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
-$as_echo_n "checking for ANSI C header files... " >&6; }
-if ${ac_cv_header_stdc+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <float.h>
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_header_stdc=yes
-else
-  ac_cv_header_stdc=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-if test $ac_cv_header_stdc = yes; then
-  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <string.h>
-
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "memchr" >/dev/null 2>&1; then :
-
-else
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdlib.h>
-
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "free" >/dev/null 2>&1; then :
-
-else
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
-  if test "$cross_compiling" = yes; then :
-  :
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <ctype.h>
-#include <stdlib.h>
-#if ((' ' & 0x0FF) == 0x020)
-# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
-# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
-#else
-# define ISLOWER(c) \
-		   (('a' <= (c) && (c) <= 'i') \
-		     || ('j' <= (c) && (c) <= 'r') \
-		     || ('s' <= (c) && (c) <= 'z'))
-# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
-#endif
-
-#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
-int
-main ()
-{
-  int i;
-  for (i = 0; i < 256; i++)
-    if (XOR (islower (i), ISLOWER (i))
-	|| toupper (i) != TOUPPER (i))
-      return 2;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
-
-else
-  ac_cv_header_stdc=no
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
-  conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
-
-fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
-$as_echo "$ac_cv_header_stdc" >&6; }
-if test $ac_cv_header_stdc = yes; then
-
-$as_echo "#define STDC_HEADERS 1" >>confdefs.h
-
-fi
-
-save_CPPFLAGS="$CPPFLAGS"
-CPPFLAGS="$CPPFLAGS $GSL_INCLUDES"
-for ac_header in gsl/gsl_multifit.h
-do :
-  ac_fn_c_check_header_mongrel "$LINENO" "gsl/gsl_multifit.h" "ac_cv_header_gsl_gsl_multifit_h" "$ac_includes_default"
-if test "x$ac_cv_header_gsl_gsl_multifit_h" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_GSL_GSL_MULTIFIT_H 1
-_ACEOF
-
-else
-  as_fn_error $? "gsl/gsl_multifit.h not found. This GSL header file is required to build" "$LINENO" 5
-fi
-
-done
-
-for ac_header in gsl/gsl_bspline.h
-do :
-  ac_fn_c_check_header_mongrel "$LINENO" "gsl/gsl_bspline.h" "ac_cv_header_gsl_gsl_bspline_h" "$ac_includes_default"
-if test "x$ac_cv_header_gsl_gsl_bspline_h" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_GSL_GSL_BSPLINE_H 1
-_ACEOF
-
-else
-  as_fn_error $? "gsl/gsl_bspline.h not found. This GSL header file is required to build" "$LINENO" 5
-fi
-
-done
-
-# Checks for typedefs, structures, and compiler characteristics.
-CPPFLAGS="$save_CPPFLAGS"
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5
-$as_echo_n "checking for an ANSI C-conforming const... " >&6; }
-if ${ac_cv_c_const+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-#ifndef __cplusplus
-  /* Ultrix mips cc rejects this sort of thing.  */
-  typedef int charset[2];
-  const charset cs = { 0, 0 };
-  /* SunOS 4.1.1 cc rejects this.  */
-  char const *const *pcpcc;
-  char **ppc;
-  /* NEC SVR4.0.2 mips cc rejects this.  */
-  struct point {int x, y;};
-  static struct point const zero = {0,0};
-  /* AIX XL C 1.02.0.0 rejects this.
-     It does not let you subtract one const X* pointer from another in
-     an arm of an if-expression whose if-part is not a constant
-     expression */
-  const char *g = "string";
-  pcpcc = &g + (g ? g-g : 0);
-  /* HPUX 7.0 cc rejects these. */
-  ++pcpcc;
-  ppc = (char**) pcpcc;
-  pcpcc = (char const *const *) ppc;
-  { /* SCO 3.2v4 cc rejects this sort of thing.  */
-    char tx;
-    char *t = &tx;
-    char const *s = 0 ? (char *) 0 : (char const *) 0;
-
-    *t++ = 0;
-    if (s) return 0;
-  }
-  { /* Someone thinks the Sun supposedly-ANSI compiler will reject this.  */
-    int x[] = {25, 17};
-    const int *foo = &x[0];
-    ++foo;
-  }
-  { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */
-    typedef const int *iptr;
-    iptr p = 0;
-    ++p;
-  }
-  { /* AIX XL C 1.02.0.0 rejects this sort of thing, saying
-       "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */
-    struct s { int j; const int *ap[3]; } bx;
-    struct s *b = &bx; b->j = 5;
-  }
-  { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
-    const int foo = 10;
-    if (!foo) return 0;
-  }
-  return !cs[0] && !zero.x;
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_c_const=yes
-else
-  ac_cv_c_const=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5
-$as_echo "$ac_cv_c_const" >&6; }
-if test $ac_cv_c_const = no; then
-
-$as_echo "#define const /**/" >>confdefs.h
-
-fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inline" >&5
-$as_echo_n "checking for inline... " >&6; }
-if ${ac_cv_c_inline+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_cv_c_inline=no
-for ac_kw in inline __inline__ __inline; do
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#ifndef __cplusplus
-typedef int foo_t;
-static $ac_kw foo_t static_foo () {return 0; }
-$ac_kw foo_t foo () {return 0; }
-#endif
-
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_c_inline=$ac_kw
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  test "$ac_cv_c_inline" != no && break
-done
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_inline" >&5
-$as_echo "$ac_cv_c_inline" >&6; }
-
-case $ac_cv_c_inline in
-  inline | yes) ;;
-  *)
-    case $ac_cv_c_inline in
-      no) ac_val=;;
-      *) ac_val=$ac_cv_c_inline;;
-    esac
-    cat >>confdefs.h <<_ACEOF
-#ifndef __cplusplus
-#define inline $ac_val
-#endif
-_ACEOF
-    ;;
-esac
-
-
-# Checks for library functions.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: *********** Checking functions ***********************" >&5
-$as_echo "*********** Checking functions ***********************" >&6; }
-for ac_func in floor pow sqrt
-do :
-  as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
-ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
-if eval test \"x\$"$as_ac_var"\" = x"yes"; then :
-  cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-done
-
-save_CPPFLAGS="$CPPFLAGS"
-CPPFLAGS="$CPPFLAGS $GSL_INCLUDES"
-save_LIBS="$LIBS"
-LIBS="$LIBS $GSL_LIBS"
-save_LDFLAGS="$LDFLAGS"
-LDFLAGS="$LDFLAGS $GSL_LDFLAGS"
-for ac_func in gsl_multifit_wlinear
-do :
-  ac_fn_c_check_func "$LINENO" "gsl_multifit_wlinear" "ac_cv_func_gsl_multifit_wlinear"
-if test "x$ac_cv_func_gsl_multifit_wlinear" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_GSL_MULTIFIT_WLINEAR 1
-_ACEOF
-
-else
-  as_fn_error $? "gsl_multifit_wlinear not found. This GSL function is required to build" "$LINENO" 5
-fi
-done
-
-for ac_func in gsl_bspline_eval
-do :
-  ac_fn_c_check_func "$LINENO" "gsl_bspline_eval" "ac_cv_func_gsl_bspline_eval"
-if test "x$ac_cv_func_gsl_bspline_eval" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_GSL_BSPLINE_EVAL 1
-_ACEOF
-
-else
-  as_fn_error $? "gsl_bspline not found. This GSL function is required to build" "$LINENO" 5
-fi
-done
-
-LIBS="$save_LIBS"
-LDFLAGS="$save_LDFLAGS"
-CPPFLAGS="$save_CPPFLAGS"
-
-
-
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for lapack" >&5
-$as_echo_n "checking for lapack... " >&6; }
-
-    xsh_lapack_check_header="clapack.h"
-    xsh_lapack_check_lib="libclapack.a"
-
-    xsh_lapack_includes=""
-    xsh_lapack_libraries=""
-
-
-# Check whether --with-lapack was given.
-if test "${with_lapack+set}" = set; then :
-  withval=$with_lapack;
-                    xsh_with_lapack_includes=$withval/include
-                    xsh_with_lapack_libs=$withval/lib
-
-fi
-
-
-
-# Check whether --with-lapack-includes was given.
-if test "${with_lapack_includes+set}" = set; then :
-  withval=$with_lapack_includes; xsh_with_lapack_includes=$withval
-fi
-
-
-
-# Check whether --with-lapack-libs was given.
-if test "${with_lapack_libs+set}" = set; then :
-  withval=$with_lapack_libs; xsh_with_lapack_libs=$withval
-fi
-
-
-    # Check whether --enable-lapack-test was given.
-if test "${enable_lapack_test+set}" = set; then :
-  enableval=$enable_lapack_test; xsh_enable_lapack_test=$enableval
-else
-  xsh_enable_lapack_test=yes
-fi
-
-
-
-    if test "x$xsh_enable_lapack_test" = xyes; then
-
-        # Check for the lapack includes
-
-        if test -z "$xsh_with_lapack_includes"; then
-            xsh_lapack_incdirs="/opt/clapack/include /usr/local/include /usr/include"
-
-            test -n "$CPLDIR" && xsh_lapack_incdirs="$CPLDIR/include \
-                $xsh_lapack_incdirs"
-
-            test -n "$LAPACKDIR" && xsh_lapack_incdirs="$LAPACKDIR/include \
-                $xsh_lapack_incdirs"
-        else
-            xsh_lapack_incdirs="$xsh_with_lapack_includes"
-        fi
-
-
-    xsh_lapack_includes=no
-
-    for i in $xsh_lapack_incdirs; do
-        for j in $xsh_lapack_check_header; do
-
-            echo "configure: 13112: $i/$j" >&5
-
-            if test -r "$i/$j"; then
-                echo "taking that" >&5
-                xsh_lapack_includes=$i
-                break 2
-            fi
-        done
-    done
-
-
-
-        # Check for the lapack library
-
-        if test -z "$xsh_with_lapack_libs"; then
-            xsh_lapack_libdirs="/opt/clapack/lib /usr/local/lib /usr/lib"
-
-            test -n "$CPLDIR" && xsh_lapack_libdirs="$CPLDIR/lib \
-                $xsh_lapack_libdirs"
-
-            test -n "$LAPACKDIR" && xsh_lapack_libdirs="$LAPACKDIR/lib \
-                $xsh_lapack_libdirs"
-        else
-            xsh_lapack_libdirs="$xsh_with_lapack_libs"
-        fi
-
-
-    xsh_lapack_libraries=no
-
-    for i in $xsh_lapack_libdirs; do
-        for j in $xsh_lapack_check_lib; do
-
-            echo "configure: 13144: $i/$j" >&5
-
-            if test -r "$i/$j"; then
-                echo "taking that" >&5
-                xsh_lapack_libraries=$i
-                break 2
-            fi
-        done
-    done
-
-
-
-        if test x"$xsh_lapack_includes" = xno || \
-            test x"$xsh_lapack_libraries" = xno; then
-            xsh_lapack_notfound=""
-
-            if test x"$xsh_lapack_includes" = xno; then
-                if test x"$xsh_lapack_libraries" = xno; then
-                    xsh_lapack_notfound="(headers and libraries)"
-                else
-                    xsh_lapack_notfound="(headers)"
-                fi
-            else
-                xsh_lapack_notfound="(libraries)"
-            fi
-
-            as_fn_error $? "lapack $xsh_lapack_notfound was not found on your system. Please check!" "$LINENO" 5
-        else
-            { $as_echo "$as_me:${as_lineno-$LINENO}: result: libraries $xsh_lapack_libraries, headers $xsh_lapack_includes" >&5
-$as_echo "libraries $xsh_lapack_libraries, headers $xsh_lapack_includes" >&6; }
-        fi
-
-        # Set up the symbols
-
-        LAPACK_INCLUDES="-I$xsh_lapack_includes"
-        LAPACK_LDFLAGS="-L$xsh_lapack_libraries"
-        LDFLAGS="$LDFLAGS $LAPACK_LDFLAGS"
-        CPPFLAGS="$CPPFLAGS $LAPACK_INCLUDES"
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -lclapack" >&5
-$as_echo_n "checking for main in -lclapack... " >&6; }
-if ${ac_cv_lib_clapack_main+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lclapack  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-
-int
-main ()
-{
-return main ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_clapack_main=yes
-else
-  ac_cv_lib_clapack_main=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_clapack_main" >&5
-$as_echo "$ac_cv_lib_clapack_main" >&6; }
-if test "x$ac_cv_lib_clapack_main" = xyes; then :
-  LIBLAPACKC="-lclapack"
-else
-  as_fn_error $? "Library clapack not found" "$LINENO" 5
-fi
-
-        LIBS="$LIBS $LIBLAPACKC"
-        LIBLAPACK="$LIBLAPACKC"
-    else
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5
-$as_echo "disabled" >&6; }
-        { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: lapack checks have been disabled! This package may not build!" >&5
-$as_echo "$as_me: WARNING: lapack checks have been disabled! This package may not build!" >&2;}
-        LAPACK_INCLUDES=""
-        LAPACK_LDFLAGS=""
-        LIBLAPACK=""
-    fi
-
-    # To be removed after CPL switched to lapack
-    LAPACK_INCLUDES="$LAPACK_INCLUDES"
-    LAPACK_LDFLAGS="$LAPACK_LDFLAGS"
-    LIBLAPACK="$LIBLAPACK"
-
-
-
-
-
-
-
-
-
-
-
-
-
-    ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-    ac_fn_c_check_decl "$LINENO" "strdup" "ac_cv_have_decl_strdup" "#include <string.h>
-"
-if test "x$ac_cv_have_decl_strdup" = xyes; then :
-
-fi
-
-
-    eso_save_CFLAGS="$CFLAGS"
-
-    if test x"$GCC" = xyes; then
-        CFLAGS="$CFLAGS -pedantic-errors"
-    fi
-
-    ac_fn_c_check_func "$LINENO" "strdup" "ac_cv_func_strdup"
-if test "x$ac_cv_func_strdup" = xyes; then :
-
-fi
-
-
-    CFLAGS="$eso_save_CFLAGS"
-
-    ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
+gnu*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
 
-    if test x"$ac_cv_have_decl_strdup" = xyes &&
-       test x"$ac_cv_func_strdup" = xyes; then
-        $as_echo "#define HAVE_STRDUP 1" >>confdefs.h
+haiku*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  dynamic_linker="$host_os runtime_loader"
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib'
+  hardcode_into_libs=yes
+  ;;
 
+hpux9* | hpux10* | hpux11*)
+  # Give a soname corresponding to the major version so that dld.sl refuses to
+  # link against other versions.
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  case $host_cpu in
+  ia64*)
+    shrext_cmds='.so'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.so"
+    shlibpath_var=LD_LIBRARY_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    if test "X$HPUX_IA64_MODE" = X32; then
+      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+    else
+      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
     fi
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  hppa*64*)
+    shrext_cmds='.sl'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  *)
+    shrext_cmds='.sl'
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=SHLIB_PATH
+    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    ;;
+  esac
+  # HP-UX runs *really* slowly unless shared libraries are mode 555, ...
+  postinstall_cmds='chmod 555 $lib'
+  # or fails outright, so override atomically:
+  install_override_mode=555
+  ;;
 
+interix[3-9]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
 
+irix5* | irix6* | nonstopux*)
+  case $host_os in
+    nonstopux*) version_type=nonstopux ;;
+    *)
+	if test "$lt_cv_prog_gnu_ld" = yes; then
+		version_type=linux # correct to gnu/linux during the next big refactor
+	else
+		version_type=irix
+	fi ;;
+  esac
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+  case $host_os in
+  irix5* | nonstopux*)
+    libsuff= shlibsuff=
+    ;;
+  *)
+    case $LD in # libtool.m4 will add one of these switches to LD
+    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+      libsuff= shlibsuff= libmagic=32-bit;;
+    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+      libsuff=32 shlibsuff=N32 libmagic=N32;;
+    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+      libsuff=64 shlibsuff=64 libmagic=64-bit;;
+    *) libsuff= shlibsuff= libmagic=never-match;;
+    esac
+    ;;
+  esac
+  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+  shlibpath_overrides_runpath=no
+  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+  hardcode_into_libs=yes
+  ;;
 
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+  dynamic_linker=no
+  ;;
 
+# This must be glibc/ELF.
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
 
-
-# Check for functions needed for plotting with irplib
-#AC_CHECK_FUNCS([popen])
-#AC_CHECK_FUNCS([pclose])
-#AC_CHECK_DECLS([popen])
-#AC_CHECK_DECLS([pclose])
-
-# Check for CPL presence and usability
-
-
-
-
-
-
-    flag=`echo pthread | sed 'y%.=/+-%___p_%'`
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -pthread" >&5
-$as_echo_n "checking whether $CC supports -pthread... " >&6; }
-if eval \${eso_cv_prog_cc_$flag+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-
-                       eval "eso_cv_prog_cc_$flag=no"
-                       ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-                       echo 'int main() { return 0; }' >conftest.$ac_ext
-
-                       try_compile="`$CC -pthread -c conftest.$ac_ext 2>&1`"
-                       if test -z "$try_compile"; then
-                           try_link="`$CC -pthread -o conftest$ac_exeext \
-                                    conftest.$ac_ext 2>&1`"
-                           if test -z "$try_link"; then
-                               eval "eso_cv_prog_cc_$flag=yes"
-                           fi
-                       fi
-                       rm -f conftest*
-
-                       ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-fi
-eval ac_res=\$eso_cv_prog_cc_$flag
-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-
-    if eval "test \"`echo '$eso_cv_prog_cc_'$flag`\" = yes"; then
-        :
-
-    else
-        :
-
-    fi
-
-
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthread" >&5
-$as_echo_n "checking for pthread_create in -lpthread... " >&6; }
-if ${ac_cv_lib_pthread_pthread_create+:} false; then :
+  # Some binutils ld are patched to set DT_RUNPATH
+  if ${lt_cv_shlibpath_overrides_runpath+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lpthread  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+  lt_cv_shlibpath_overrides_runpath=no
+    save_LDFLAGS=$LDFLAGS
+    save_libdir=$libdir
+    eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \
+	 LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec\""
+    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char pthread_create ();
 int
 main ()
 {
-return pthread_create ();
+
   ;
   return 0;
 }
 _ACEOF
 if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_pthread_pthread_create=yes
-else
-  ac_cv_lib_pthread_pthread_create=no
+  if  ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then :
+  lt_cv_shlibpath_overrides_runpath=yes
+fi
 fi
 rm -f core conftest.err conftest.$ac_objext \
     conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread_pthread_create" >&5
-$as_echo "$ac_cv_lib_pthread_pthread_create" >&6; }
-if test "x$ac_cv_lib_pthread_pthread_create" = xyes; then :
-  eso_threads_have_libpthread=yes
-else
-  eso_threads_have_libpthread=no
-fi
-
-
-    ac_fn_c_check_header_mongrel "$LINENO" "pthread.h" "ac_cv_header_pthread_h" "$ac_includes_default"
-if test "x$ac_cv_header_pthread_h" = xyes; then :
-  eso_threads_have_pthread_h=yes
-else
-  eso_threads_have_pthread_h=no
-fi
-
-
-
-    if test x"$eso_threads_have_pthread_h" != xyes; then
-        eso_threads_posix=no
-    else
-        if test x"$eso_threads_have_libpthread" != xyes && \
-          test x"$eso_cv_prog_cc_pthread" != xyes; then
-            eso_threads_posix=no
-        else
-            eso_threads_posix=yes
-        fi
-    fi
-
-
-    # Setup the POSIX thread symbols
-
-    if test x"$eso_threads_have_pthread_h" = xyes; then
-
-$as_echo "#define HAVE_PTHREAD_H 1" >>confdefs.h
-
-    fi
-
-    if test x"$eso_threads_posix" = xyes; then
-
-        if test x"$eso_cv_prog_cc_pthread" = xyes; then
-            PTHREAD_CFLAGS="-pthread"
-        else
-            PTHREAD_CFLAGS=""
-        fi
-
-        if test x"$eso_threads_have_libpthread" = xyes; then
-            LIBPTHREAD="-lpthread"
-        else
-            LIBPTHREAD=""
-        fi
-
-    fi
-
-    if ${eso_cv_threads_posix_header+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  eso_cv_threads_posix_header=$eso_threads_have_pthread_h
-fi
+    LDFLAGS=$save_LDFLAGS
+    libdir=$save_libdir
 
-    if ${eso_cv_threads_posix_lib+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  eso_cv_threads_posix_lib=$eso_threads_have_libpthread
 fi
 
-    if ${eso_cv_threads_posix_flags+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  eso_cv_threads_posix_flags=$eso_cv_prog_cc_pthread
-fi
+  shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath
 
-    if ${eso_cv_threads_posix+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  eso_cv_threads_posix=$eso_threads_posix
-fi
+  # This implies no fast_install, which is unacceptable.
+  # Some rework will be needed to allow for fast_install
+  # before this can be enabled.
+  hardcode_into_libs=yes
 
+  # Add ABI-specific directories to the system library path.
+  sys_lib_dlsearch_path_spec="/lib64 /usr/lib64 /lib /usr/lib"
 
+  # Append ld.so.conf contents to the search path
+  if test -f /etc/ld.so.conf; then
+    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '`
+    sys_lib_dlsearch_path_spec="$sys_lib_dlsearch_path_spec $lt_ld_extra"
 
+  fi
 
+  # We used to test for /lib/ld.so.1 and disable shared libraries on
+  # powerpc, because MkLinux only supported shared libraries with the
+  # GNU dynamic linker.  Since this was broken with cross compilers,
+  # most powerpc-linux boxes support dynamic linking these days and
+  # people can always --disable-shared, the test was removed, and we
+  # assume the GNU/Linux dynamic linker is in use.
+  dynamic_linker='GNU/Linux ld.so'
+  ;;
 
+netbsd*)
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+    dynamic_linker='NetBSD (a.out) ld.so'
+  else
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    dynamic_linker='NetBSD ld.elf_so'
+  fi
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  ;;
 
+newsos6)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  ;;
 
+*nto* | *qnx*)
+  version_type=qnx
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  dynamic_linker='ldqnx.so'
+  ;;
 
+openbsd*)
+  version_type=sunos
+  sys_lib_dlsearch_path_spec="/usr/lib"
+  need_lib_prefix=no
+  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
+  case $host_os in
+    openbsd3.3 | openbsd3.3.*)	need_version=yes ;;
+    *)				need_version=no  ;;
+  esac
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    case $host_os in
+      openbsd2.[89] | openbsd2.[89].*)
+	shlibpath_overrides_runpath=no
+	;;
+      *)
+	shlibpath_overrides_runpath=yes
+	;;
+      esac
+  else
+    shlibpath_overrides_runpath=yes
+  fi
+  ;;
 
+os2*)
+  libname_spec='$name'
+  shrext_cmds=".dll"
+  need_lib_prefix=no
+  library_names_spec='$libname${shared_ext} $libname.a'
+  dynamic_linker='OS/2 ld.exe'
+  shlibpath_var=LIBPATH
+  ;;
 
-    cpl_cfitsio_check_version=""
-    cpl_cfitsio_check_header="fitsio.h"
-    cpl_cfitsio_check_lib="libcfitsio.a"
+osf3* | osf4* | osf5*)
+  version_type=osf
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+  ;;
 
-    cpl_cfitsio_incdirs=""
-    cpl_cfitsio_libdirs=""
-    cpl_cfitsio_includes=""
-    cpl_cfitsio_libraries=""
+rdos*)
+  dynamic_linker=no
+  ;;
 
+solaris*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  # ldd complains unless libraries are executable
+  postinstall_cmds='chmod +x $lib'
+  ;;
 
-# Check whether --with-cfitsio was given.
-if test "${with_cfitsio+set}" = set; then :
-  withval=$with_cfitsio;
-                    cpl_with_cfitsio=$withval
+sunos4*)
+  version_type=sunos
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  if test "$with_gnu_ld" = yes; then
+    need_lib_prefix=no
+  fi
+  need_version=yes
+  ;;
 
-fi
+sysv4 | sysv4.3*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_vendor in
+    sni)
+      shlibpath_overrides_runpath=no
+      need_lib_prefix=no
+      runpath_var=LD_RUN_PATH
+      ;;
+    siemens)
+      need_lib_prefix=no
+      ;;
+    motorola)
+      need_lib_prefix=no
+      need_version=no
+      shlibpath_overrides_runpath=no
+      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+      ;;
+  esac
+  ;;
 
+sysv4*MP*)
+  if test -d /usr/nec ;then
+    version_type=linux # correct to gnu/linux during the next big refactor
+    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+    soname_spec='$libname${shared_ext}.$major'
+    shlibpath_var=LD_LIBRARY_PATH
+  fi
+  ;;
 
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  version_type=freebsd-elf
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  if test "$with_gnu_ld" = yes; then
+    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
+  else
+    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
+    case $host_os in
+      sco3.2v5*)
+        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
+	;;
+    esac
+  fi
+  sys_lib_dlsearch_path_spec='/usr/lib'
+  ;;
 
-# Check whether --with-cfitsio-includes was given.
-if test "${with_cfitsio_includes+set}" = set; then :
-  withval=$with_cfitsio_includes; cpl_with_cfitsio_includes=$withval
-fi
+tpf*)
+  # TPF is a cross-target only.  Preferred cross-host = GNU/Linux.
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
 
+uts4*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
 
+*)
+  dynamic_linker=no
+  ;;
+esac
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5
+$as_echo "$dynamic_linker" >&6; }
+test "$dynamic_linker" = no && can_build_shared=no
 
-# Check whether --with-cfitsio-libs was given.
-if test "${with_cfitsio_libs+set}" = set; then :
-  withval=$with_cfitsio_libs; cpl_with_cfitsio_libs=$withval
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
 fi
 
-
-    # Check whether --enable-cfitsio-test was given.
-if test "${enable_cfitsio_test+set}" = set; then :
-  enableval=$enable_cfitsio_test; cpl_enable_cfitsio_test=$enableval
-else
-  cpl_enable_cfitsio_test=yes
+if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
+  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
+fi
+if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
+  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
 fi
 
 
 
-    # We need libpthread for the folloing tests
-
-    if test -z "$LIBPTHREAD"; then
-        as_fn_error $? "POSIX thread library was not found on your system! Please check!" "$LINENO" 5
-    fi
-
-
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for cfitsio" >&5
-$as_echo_n "checking for cfitsio... " >&6; }
 
-    if test "x$cpl_enable_cfitsio_test" = xyes; then
 
-        # Check for the cfitsio includes
 
-        if test -z "$cpl_with_cfitsio_includes"; then
 
-            if test -z "$cpl_with_cfitsio"; then
 
-                # Try some known system locations
 
-                cpl_cfitsio_incdirs="/opt/cfitsio/include"
-                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs /usr/local/include/libcfitsio0"
-                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs /usr/local/include/cfitsio"
-                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs /usr/local/include"
-                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs /usr/include/libcfitsio0"
-                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs /usr/include/cfitsio"
-                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs /usr/include"
 
-                test -n "$CFITSIODIR" && \
-                    cpl_cfitsio_incdirs="$CFITSIODIR/include/libcfitsio0 \
-                                         $CFITSIODIR/include/cfitsio \
-                                         $CFITSIODIR/include \
-                                         $cpl_cfitsio_incdirs"
 
-                test -n "$CPLDIR" && \
-                    cpl_cfitsio_incdirs="$CPLDIR/include/libcfitsio0 \
-                                         $CPLDIR/include/cfitsio \
-                                         $CPLDIR/include \
-                                         $cpl_cfitsio_incdirs"
 
-            else
 
-                cpl_cfitsio_incdirs="$cpl_with_cfitsio/include/libcfitsio0"
-                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs $cpl_with_cfitsio/include/cfitsio"
-                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs $cpl_with_cfitsio/include"
 
-            fi
 
-        else
-            cpl_cfitsio_incdirs="$cpl_with_cfitsio_includes"
-        fi
 
 
-    cpl_cfitsio_includes=no
 
-    for i in $cpl_cfitsio_incdirs; do
-        for j in $cpl_cfitsio_check_header; do
 
-            echo "configure: 13574: $i/$j" >&5
 
-            if test -r "$i/$j"; then
-                echo "taking that" >&5
-                cpl_cfitsio_includes=$i
-                break 2
-            fi
-        done
-    done
 
 
 
-        # Check for the cfitsio library
 
-        if test -z "$cpl_with_cfitsio_libs"; then
 
-            if test -z "$cpl_with_cfitsio"; then
 
-                # Try some known system locations
 
-                cpl_cfitsio_libdirs="/opt/cfitsio/lib"
-                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs /usr/local/lib64"
-                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs /usr/local/lib"
-                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs /usr/local/lib32"
-                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs /usr/lib64"
-                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs /usr/lib"
-                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs /usr/lib32"
 
-                test -n "$CFITSIODIR" && \
-                    cpl_cfitsio_libdirs="$CFITSIODIR/lib64 $CFITSIODIR/lib \
-                                         $CFITSIODIR/lib32 $cpl_cfitsio_libdirs"
 
-                test -n "$CPLDIR" && \
-                    cpl_cfitsio_libdirs="$CPLDIR/lib64 $CPLDIR/lib $CPLDIR/lib32 \
-                                         $cpl_cfitsio_libdirs"
 
-            else
 
-                cpl_cfitsio_libdirs="$cpl_with_cfitsio/lib64"
-                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs $cpl_with_cfitsio/lib"
-                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs $cpl_with_cfitsio/lib32"
 
-            fi
 
-        else
-            cpl_cfitsio_libdirs="$cpl_with_cfitsio_libs"
-        fi
 
 
-    cpl_cfitsio_libraries=no
 
-    for i in $cpl_cfitsio_libdirs; do
-        for j in $cpl_cfitsio_check_lib; do
 
-            echo "configure: 13628: $i/$j" >&5
 
-            if test -r "$i/$j"; then
-                echo "taking that" >&5
-                cpl_cfitsio_libraries=$i
-                break 2
-            fi
-        done
-    done
 
 
 
-        if test x"$cpl_cfitsio_includes" = xno || \
-            test x"$cpl_cfitsio_libraries" = xno; then
-            cpl_cfitsio_notfound=""
 
-            if test x"$cpl_cfitsio_includes" = xno; then
-                if test x"$cpl_cfitsio_libraries" = xno; then
-                    cpl_cfitsio_notfound="(headers and libraries)"
-                else
-                    cpl_cfitsio_notfound="(headers)"
-                fi
-            else
-                cpl_cfitsio_notfound="(libraries)"
-            fi
 
-            as_fn_error $? "cfitsio $cpl_cfitsio_notfound was not found on your system. Please check!" "$LINENO" 5
-        else
-            { $as_echo "$as_me:${as_lineno-$LINENO}: result: libraries $cpl_cfitsio_libraries, headers $cpl_cfitsio_includes" >&5
-$as_echo "libraries $cpl_cfitsio_libraries, headers $cpl_cfitsio_includes" >&6; }
-        fi
 
-        # Set up the symbols
 
-        # Add '-lz' to the static library symbol, as distributors apparently
-        # remove the libz code from the cfitsio sources.
 
-        CFITSIO_INCLUDES="-I$cpl_cfitsio_includes"
-        CFITSIO_LDFLAGS="-L$cpl_cfitsio_libraries"
-        LIBCFITSIO="-lcfitsio"
-        LIBCFITSIO_STATIC="$cpl_cfitsio_libraries/$cpl_cfitsio_check_lib"
 
-        # Do not add redundant libraries
-        echo $LIBS | grep -q -e '-lm' || LIBS="-lm $LIBS"
 
 
-        # Check whether cfitsio can be used
 
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether cfitsio can be used" >&5
-$as_echo_n "checking whether cfitsio can be used... " >&6; }
-        ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
-        cpl_cfitsio_cflags_save="$CFLAGS"
-        cpl_cfitsio_ldflags_save="$LDFLAGS"
-        cpl_cfitsio_libs_save="$LIBS"
 
-        CFLAGS="$CFITSIO_INCLUDES $CFLAGS"
-        LDFLAGS="$CFITSIO_LDFLAGS $LDFLAGS"
-        LIBS="$LIBCFITSIO_STATIC $LIBPTHREAD -lm"
 
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
 
-                       #include <fitsio.h>
 
-int
-main ()
-{
 
-                       float v;
-                       fits_get_version(&v);
 
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  cpl_cfitsio_is_usable="yes"
-else
-  cpl_cfitsio_is_usable="no"
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
 
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cpl_cfitsio_is_usable" >&5
-$as_echo "$cpl_cfitsio_is_usable" >&6; }
 
-        ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
-        CFLAGS="$cpl_cfitsio_cflags_save"
-        LDFLAGS="$cpl_cfitsio_ldflags_save"
-        LIBS="$cpl_cfitsio_libs_save"
 
-        if test x"$cpl_cfitsio_is_usable" = xno; then
-            as_fn_error $? "Linking with cfitsio failed! Please check architecture!" "$LINENO" 5
-        fi
 
 
-        # Check cfitsio version
 
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a cfitsio version >= $cpl_cfitsio_check_version" >&5
-$as_echo_n "checking for a cfitsio version >= $cpl_cfitsio_check_version... " >&6; }
 
-        ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
-        cpl_cfitsio_cflags_save="$CFLAGS"
-        cpl_cfitsio_ldflags_save="$LDFLAGS"
-        cpl_cfitsio_libs_save="$LIBS"
 
-        CFLAGS="$CFITSIO_INCLUDES $CFLAGS"
-        LDFLAGS="$CFITSIO_LDFLAGS $LDFLAGS"
-        LIBS="$LIBCFITSIO_STATIC $LIBPTHREAD -lm"
 
-        if test "$cross_compiling" = yes; then :
-  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot run test program while cross compiling
-See \`config.log' for more details" "$LINENO" 5; }
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
 
-                      #include <stdio.h>
-                      #include <fitsio.h>
 
-int
-main ()
-{
 
-                      int vlib = 0;
-                      int vmin = (int)(1000. * $cpl_cfitsio_check_version + 0.5);
 
-                      float v;
 
-                      fits_get_version(&v);
-                      vlib = (int)(v * 1000 + 0.5);
 
-                      FILE* f = fopen("conftest.out", "w");
-                      fprintf(f, "%5.3f\n", v);
-                      fclose(f);
 
-                      if (vlib < vmin) {
-                          return 1;
-                      }
 
-                      return 0;
 
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
-  cpl_cfitsio_version="`cat conftest.out`"
-else
 
-                       cpl_cfitsio_version="no";
-                       cpl_cfitsio_version_found="`cat conftest.out`"
 
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
-  conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
 
 
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cpl_cfitsio_version" >&5
-$as_echo "$cpl_cfitsio_version" >&6; }
 
-        ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
-        CFLAGS="$cpl_cfitsio_cflags_save"
-        LDFLAGS="$cpl_cfitsio_ldflags_save"
-        LIBS="$cpl_cfitsio_libs_save"
 
-        if test x"$cpl_cfitsio_version" = xno; then
-            as_fn_error $? "Installed cfitsio ($cpl_cfitsio_version_found) is too old. Please update to version $cpl_cfitsio_check_version or newer." "$LINENO" 5
-        fi
 
 
-        # Check whether cfitsio has large file support
 
-        ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5
+$as_echo_n "checking how to hardcode library paths into programs... " >&6; }
+hardcode_action=
+if test -n "$hardcode_libdir_flag_spec" ||
+   test -n "$runpath_var" ||
+   test "X$hardcode_automatic" = "Xyes" ; then
+
+  # We can hardcode non-existent directories.
+  if test "$hardcode_direct" != no &&
+     # If the only mechanism to avoid hardcoding is shlibpath_var, we
+     # have to relink, otherwise we might link with an installed library
+     # when we should be linking with a yet-to-be-installed one
+     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, )" != no &&
+     test "$hardcode_minus_L" != no; then
+    # Linking always hardcodes the temporary library directory.
+    hardcode_action=relink
+  else
+    # We can link without hardcoding, and we can hardcode nonexisting dirs.
+    hardcode_action=immediate
+  fi
+else
+  # We cannot hardcode anything, or else we can only hardcode existing
+  # directories.
+  hardcode_action=unsupported
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5
+$as_echo "$hardcode_action" >&6; }
+
+if test "$hardcode_action" = relink ||
+   test "$inherit_rpath" = yes; then
+  # Fast installation is not supported
+  enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+     test "$enable_shared" = no; then
+  # Fast installation is not necessary
+  enable_fast_install=needless
+fi
 
-        cpl_cfitsio_cflags_save="$CFLAGS"
-        cpl_cfitsio_ldflags_save="$LDFLAGS"
-        cpl_cfitsio_libs_save="$LIBS"
 
-        CFLAGS="$CFITSIO_INCLUDES $CFLAGS"
-        LDFLAGS="$CFITSIO_LDFLAGS $LDFLAGS"
-        LIBS="$LIBCFITSIO_STATIC -lm $LIBPTHREAD"
 
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether cfitsio provides fits_hdu_getoff()" >&5
-$as_echo_n "checking whether cfitsio provides fits_hdu_getoff()... " >&6; }
 
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
 
-                          #include <fitsio.h>
 
+  if test "x$enable_dlopen" != xyes; then
+  enable_dlopen=unknown
+  enable_dlopen_self=unknown
+  enable_dlopen_self_static=unknown
+else
+  lt_cv_dlopen=no
+  lt_cv_dlopen_libs=
+
+  case $host_os in
+  beos*)
+    lt_cv_dlopen="load_add_on"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+    ;;
+
+  mingw* | pw32* | cegcc*)
+    lt_cv_dlopen="LoadLibrary"
+    lt_cv_dlopen_libs=
+    ;;
+
+  cygwin*)
+    lt_cv_dlopen="dlopen"
+    lt_cv_dlopen_libs=
+    ;;
+
+  darwin*)
+  # if libdl is installed we need to link against it
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
+$as_echo_n "checking for dlopen in -ldl... " >&6; }
+if ${ac_cv_lib_dl_dlopen+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldl  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char dlopen ();
 int
 main ()
 {
-
-                          fitsfile f;
-                          int sts;
-                          fits_get_hduoff(&f, NULL, NULL, NULL, &sts);
-
+return dlopen ();
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  cpl_cfitsio_have_fits_get_hduoff="yes"
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_dl_dlopen=yes
 else
-  cpl_cfitsio_have_fits_get_hduoff="no"
+  ac_cv_lib_dl_dlopen=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
+$as_echo "$ac_cv_lib_dl_dlopen" >&6; }
+if test "x$ac_cv_lib_dl_dlopen" = xyes; then :
+  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
+else
 
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cpl_cfitsio_have_fits_get_hduoff" >&5
-$as_echo "$cpl_cfitsio_have_fits_get_hduoff" >&6; }
+    lt_cv_dlopen="dyld"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
 
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether cfitsio provides fits_get_hduaddrll()" >&5
-$as_echo_n "checking whether cfitsio provides fits_get_hduaddrll()... " >&6; }
+fi
 
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
+    ;;
 
-                          #include <fitsio.h>
+  *)
+    ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load"
+if test "x$ac_cv_func_shl_load" = xyes; then :
+  lt_cv_dlopen="shl_load"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5
+$as_echo_n "checking for shl_load in -ldld... " >&6; }
+if ${ac_cv_lib_dld_shl_load+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldld  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
 
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char shl_load ();
 int
 main ()
 {
-
-                          fitsfile f;
-                          int sts;
-                          fits_get_hduaddrll(&f, NULL, NULL, NULL, &sts);
-
+return shl_load ();
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  cpl_cfitsio_have_fits_get_hduaddrll="yes"
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_dld_shl_load=yes
 else
-  cpl_cfitsio_have_fits_get_hduaddrll="no"
+  ac_cv_lib_dld_shl_load=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cpl_cfitsio_have_fits_get_hduaddrll" >&5
-$as_echo "$cpl_cfitsio_have_fits_get_hduaddrll" >&6; }
-
-        ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-        CFLAGS="$cpl_cfitsio_cflags_save"
-        LDFLAGS="$cpl_cfitsio_ldflags_save"
-        LIBS="$cpl_cfitsio_libs_save"
-
-
-        # Check whether cfitsio is thread-safe
-
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether cfitsio requires libpthread" >&5
-$as_echo_n "checking whether cfitsio requires libpthread... " >&6; }
-        ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-        cpl_cfitsio_cflags_save="$CFLAGS"
-        cpl_cfitsio_ldflags_save="$LDFLAGS"
-        cpl_cfitsio_libs_save="$LIBS"
-
-        CFLAGS="$CFITSIO_INCLUDES $CFLAGS"
-        LDFLAGS="$CFITSIO_LDFLAGS $LDFLAGS"
-        LIBS="$LIBCFITSIO_STATIC -lm"
-
-
-        cpl_cfitsio_provides_pthread="no"
-
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5
+$as_echo "$ac_cv_lib_dld_shl_load" >&6; }
+if test "x$ac_cv_lib_dld_shl_load" = xyes; then :
+  lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"
+else
+  ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen"
+if test "x$ac_cv_func_dlopen" = xyes; then :
+  lt_cv_dlopen="dlopen"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
+$as_echo_n "checking for dlopen in -ldl... " >&6; }
+if ${ac_cv_lib_dl_dlopen+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldl  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-                       #include <fitsio.h>
-
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char dlopen ();
 int
 main ()
 {
-
-                       float v;
-                       fits_get_version(&v);
-
+return dlopen ();
   ;
   return 0;
 }
 _ACEOF
 if ac_fn_c_try_link "$LINENO"; then :
-  cpl_cfitsio_requires_pthread="no"
+  ac_cv_lib_dl_dlopen=yes
 else
-  cpl_cfitsio_requires_pthread="undefined"
+  ac_cv_lib_dl_dlopen=no
 fi
 rm -f core conftest.err conftest.$ac_objext \
     conftest$ac_exeext conftest.$ac_ext
-
-		if test x"$cpl_cfitsio_requires_pthread" = xno; then
-
-	    	# If libpthread is not required this means either cfitsio is
-    		# not compiled with thread support, or the library dependencies
-    		# are compiled into cfitsio.
-
-			# Check whether shared library dependencies are present
-			# Don't use pthread_mutex_init/destroy here, since glibc
-			# provides these symbols too! Sigh!
-
-	        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
+$as_echo "$ac_cv_lib_dl_dlopen" >&6; }
+if test "x$ac_cv_lib_dl_dlopen" = xyes; then :
+  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5
+$as_echo_n "checking for dlopen in -lsvld... " >&6; }
+if ${ac_cv_lib_svld_dlopen+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lsvld  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-	    	               #include <pthread.h>
-    	    	           #include <fitsio.h>
-
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char dlopen ();
 int
 main ()
 {
-
-	                	   float v;
-    	            	   pthread_mutexattr_t attrb;
-    	            	   pthread_mutexattr_init(&attrb);
-            	           fits_get_version(&v);
-                		   pthread_mutexattr_destroy(&attrb);
-
+return dlopen ();
   ;
   return 0;
 }
 _ACEOF
 if ac_fn_c_try_link "$LINENO"; then :
-  cpl_cfitsio_provides_pthread="yes"
+  ac_cv_lib_svld_dlopen=yes
 else
-  cpl_cfitsio_provides_pthread="no"
+  ac_cv_lib_svld_dlopen=no
 fi
 rm -f core conftest.err conftest.$ac_objext \
     conftest$ac_exeext conftest.$ac_ext
-
-        else
-
-            LIBS="$LIBCFITSIO_STATIC -lm $LIBPTHREAD"
-
-            cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5
+$as_echo "$ac_cv_lib_svld_dlopen" >&6; }
+if test "x$ac_cv_lib_svld_dlopen" = xyes; then :
+  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5
+$as_echo_n "checking for dld_link in -ldld... " >&6; }
+if ${ac_cv_lib_dld_dld_link+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldld  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-                           #include <fitsio.h>
-
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char dld_link ();
 int
 main ()
 {
-
-                           float v;
-                           fits_get_version(&v);
-
+return dld_link ();
   ;
   return 0;
 }
 _ACEOF
 if ac_fn_c_try_link "$LINENO"; then :
-  cpl_cfitsio_requires_pthread="yes"
+  ac_cv_lib_dld_dld_link=yes
 else
-  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "Cannot link with cfitsio! Please check!
-See \`config.log' for more details" "$LINENO" 5; }
+  ac_cv_lib_dld_dld_link=no
 fi
 rm -f core conftest.err conftest.$ac_objext \
     conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5
+$as_echo "$ac_cv_lib_dld_dld_link" >&6; }
+if test "x$ac_cv_lib_dld_dld_link" = xyes; then :
+  lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"
+fi
 
-        fi
 
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cpl_cfitsio_requires_pthread" >&5
-$as_echo "$cpl_cfitsio_requires_pthread" >&6; }
+fi
 
-        ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
+fi
 
-        CFLAGS="$cpl_cfitsio_cflags_save"
-        LDFLAGS="$cpl_cfitsio_ldflags_save"
-        LIBS="$cpl_cfitsio_libs_save"
 
+fi
 
-		{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether cfitsio was compiled with thread support" >&5
-$as_echo_n "checking whether cfitsio was compiled with thread support... " >&6; }
 
-		if test x"$cpl_cfitsio_requires_pthread" = xyes || \
-			test x"$cpl_cfitsio_provides_pthread" = xyes; then
-			cpl_cfitsio_is_thread_safe=yes
-		else
-			cpl_cfitsio_is_thread_safe=no
-		fi
+fi
 
-		{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cpl_cfitsio_is_thread_safe" >&5
-$as_echo "$cpl_cfitsio_is_thread_safe" >&6; }
 
+fi
 
-        # Set compiler flags and libraries
+    ;;
+  esac
 
-        if test x"$cpl_cfitsio_have_fits_get_hduoff" = xyes || \
-          test x"$cpl_cfitsio_have_fits_get_hduaddrll" = xyes; then
+  if test "x$lt_cv_dlopen" != xno; then
+    enable_dlopen=yes
+  else
+    enable_dlopen=no
+  fi
 
-            CFLAGS="-D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64 $CFLAGS"
+  case $lt_cv_dlopen in
+  dlopen)
+    save_CPPFLAGS="$CPPFLAGS"
+    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
 
-            if test x"$cpl_cfitsio_have_fits_get_hduoff"; then
+    save_LDFLAGS="$LDFLAGS"
+    wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
 
-$as_echo "#define HAVE_FITS_GET_HDUOFF 1" >>confdefs.h
+    save_LIBS="$LIBS"
+    LIBS="$lt_cv_dlopen_libs $LIBS"
 
-            else
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5
+$as_echo_n "checking whether a program can dlopen itself... " >&6; }
+if ${lt_cv_dlopen_self+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  	  if test "$cross_compiling" = yes; then :
+  lt_cv_dlopen_self=cross
+else
+  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+  lt_status=$lt_dlunknown
+  cat > conftest.$ac_ext <<_LT_EOF
+#line $LINENO "configure"
+#include "confdefs.h"
 
-$as_echo "#define HAVE_FITS_GET_HDUADDRLL 1" >>confdefs.h
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
 
-            fi
+#include <stdio.h>
 
-        fi
+#ifdef RTLD_GLOBAL
+#  define LT_DLGLOBAL		RTLD_GLOBAL
+#else
+#  ifdef DL_GLOBAL
+#    define LT_DLGLOBAL		DL_GLOBAL
+#  else
+#    define LT_DLGLOBAL		0
+#  endif
+#endif
 
-        if test x"$cpl_cfitsio_requires_pthread" = xyes; then
-            echo $LIBS | grep -q -e "$LIBPTHREAD" || LIBS="$LIBPTHREAD $LIBS"
-        fi
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+   find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+#  ifdef RTLD_LAZY
+#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
+#  else
+#    ifdef DL_LAZY
+#      define LT_DLLAZY_OR_NOW		DL_LAZY
+#    else
+#      ifdef RTLD_NOW
+#        define LT_DLLAZY_OR_NOW	RTLD_NOW
+#      else
+#        ifdef DL_NOW
+#          define LT_DLLAZY_OR_NOW	DL_NOW
+#        else
+#          define LT_DLLAZY_OR_NOW	0
+#        endif
+#      endif
+#    endif
+#  endif
+#endif
 
-    else
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5
-$as_echo "disabled" >&6; }
-        { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cfitsio checks have been disabled! This package may not build!" >&5
-$as_echo "$as_me: WARNING: cfitsio checks have been disabled! This package may not build!" >&2;}
-        CFITSIO_INCLUDES=""
-        CFITSIO_LDFLAGS=""
-        LIBCFITSIO=""
-
-        cpl_cfitsio_is_thread_safe="undefined"
-        cpl_cfitsio_requires_pthread="undefined"
-    fi
+/* When -fvisbility=hidden is used, assume the code has been annotated
+   correspondingly for the symbols needed.  */
+#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
+int fnord () __attribute__((visibility("default")));
+#endif
 
-	if ${cpl_cv_cfitsio_requires_pthread+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cpl_cv_cfitsio_requires_pthread=$cpl_cfitsio_requires_pthread
-fi
+int fnord () { return 42; }
+int main ()
+{
+  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+  int status = $lt_dlunknown;
 
-	if ${cpl_cv_cfitsio_is_thread_safe+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cpl_cv_cfitsio_is_thread_safe=$cpl_cfitsio_is_thread_safe
-fi
+  if (self)
+    {
+      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
+      else
+        {
+	  if (dlsym( self,"_fnord"))  status = $lt_dlneed_uscore;
+          else puts (dlerror ());
+	}
+      /* dlclose (self); */
+    }
+  else
+    puts (dlerror ());
 
+  return status;
+}
+_LT_EOF
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5
+  (eval $ac_link) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then
+    (./conftest; exit; ) >&5 2>/dev/null
+    lt_status=$?
+    case x$lt_status in
+      x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;;
+      x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;;
+      x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;;
+    esac
+  else :
+    # compilation failed
+    lt_cv_dlopen_self=no
+  fi
+fi
+rm -fr conftest*
 
 
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5
+$as_echo "$lt_cv_dlopen_self" >&6; }
 
+    if test "x$lt_cv_dlopen_self" = xyes; then
+      wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5
+$as_echo_n "checking whether a statically linked program can dlopen itself... " >&6; }
+if ${lt_cv_dlopen_self_static+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  	  if test "$cross_compiling" = yes; then :
+  lt_cv_dlopen_self_static=cross
+else
+  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+  lt_status=$lt_dlunknown
+  cat > conftest.$ac_ext <<_LT_EOF
+#line $LINENO "configure"
+#include "confdefs.h"
 
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
 
+#include <stdio.h>
 
+#ifdef RTLD_GLOBAL
+#  define LT_DLGLOBAL		RTLD_GLOBAL
+#else
+#  ifdef DL_GLOBAL
+#    define LT_DLGLOBAL		DL_GLOBAL
+#  else
+#    define LT_DLGLOBAL		0
+#  endif
+#endif
 
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+   find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+#  ifdef RTLD_LAZY
+#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
+#  else
+#    ifdef DL_LAZY
+#      define LT_DLLAZY_OR_NOW		DL_LAZY
+#    else
+#      ifdef RTLD_NOW
+#        define LT_DLLAZY_OR_NOW	RTLD_NOW
+#      else
+#        ifdef DL_NOW
+#          define LT_DLLAZY_OR_NOW	DL_NOW
+#        else
+#          define LT_DLLAZY_OR_NOW	0
+#        endif
+#      endif
+#    endif
+#  endif
+#endif
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for CPL" >&5
-$as_echo_n "checking for CPL... " >&6; }
+/* When -fvisbility=hidden is used, assume the code has been annotated
+   correspondingly for the symbols needed.  */
+#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
+int fnord () __attribute__((visibility("default")));
+#endif
 
-    cpl_check_cpl_header="cpl.h"
-    cpl_check_cpl_lib="libcplcore.a"
+int fnord () { return 42; }
+int main ()
+{
+  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+  int status = $lt_dlunknown;
 
-    cpl_incdirs=""
-    cpl_libdirs=""
-    cpl_includes=""
-    cpl_libraries=""
+  if (self)
+    {
+      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
+      else
+        {
+	  if (dlsym( self,"_fnord"))  status = $lt_dlneed_uscore;
+          else puts (dlerror ());
+	}
+      /* dlclose (self); */
+    }
+  else
+    puts (dlerror ());
 
+  return status;
+}
+_LT_EOF
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5
+  (eval $ac_link) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then
+    (./conftest; exit; ) >&5 2>/dev/null
+    lt_status=$?
+    case x$lt_status in
+      x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;;
+      x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;;
+      x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;;
+    esac
+  else :
+    # compilation failed
+    lt_cv_dlopen_self_static=no
+  fi
+fi
+rm -fr conftest*
 
-# Check whether --with-cpl was given.
-if test "${with_cpl+set}" = set; then :
-  withval=$with_cpl;
-                    cpl_with_cpl=$withval
 
 fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static" >&5
+$as_echo "$lt_cv_dlopen_self_static" >&6; }
+    fi
 
+    CPPFLAGS="$save_CPPFLAGS"
+    LDFLAGS="$save_LDFLAGS"
+    LIBS="$save_LIBS"
+    ;;
+  esac
 
+  case $lt_cv_dlopen_self in
+  yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
+  *) enable_dlopen_self=unknown ;;
+  esac
 
-# Check whether --with-cpl-includes was given.
-if test "${with_cpl_includes+set}" = set; then :
-  withval=$with_cpl_includes; cpl_with_cpl_includes=$withval
+  case $lt_cv_dlopen_self_static in
+  yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
+  *) enable_dlopen_self_static=unknown ;;
+  esac
 fi
 
 
 
-# Check whether --with-cpl-libs was given.
-if test "${with_cpl_libs+set}" = set; then :
-  withval=$with_cpl_libs; cpl_with_cpl_libs=$withval
-fi
 
 
-    # Check whether --enable-cpl-test was given.
-if test "${enable_cpl_test+set}" = set; then :
-  enableval=$enable_cpl_test; cpl_enable_cpl_test=$enableval
-else
-  cpl_enable_cpl_test=yes
-fi
 
 
 
-    if test "x$cpl_enable_cpl_test" = xyes; then
 
-        # Check for the CPL includes
 
-        if test -z "$cpl_with_cpl_includes"; then
 
-            if test -z "$cpl_with_cpl"; then
 
-                # Try some known system locations
 
-                cpl_incdirs="/opt/cpl/include"
-                cpl_incdirs="$cpl_incdirs /usr/local/include"
-                cpl_incdirs="$cpl_incdirs /usr/include"
 
-                test -n "$CPLDIR" && \
-                    cpl_incdirs="$CPLDIR/include \
-                                 $cpl_incdirs"
 
-            else
 
-                cpl_incdirs="$cpl_with_cpl/include"
 
-            fi
+striplib=
+old_striplib=
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stripping libraries is possible" >&5
+$as_echo_n "checking whether stripping libraries is possible... " >&6; }
+if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then
+  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
+  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+# FIXME - insert some real tests, host_os isn't really good enough
+  case $host_os in
+  darwin*)
+    if test -n "$STRIP" ; then
+      striplib="$STRIP -x"
+      old_striplib="$STRIP -S"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+    else
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+    fi
+    ;;
+  *)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+    ;;
+  esac
+fi
 
-        else
-            cpl_incdirs="$cpl_with_cpl_includes"
-        fi
 
 
-    cpl_includes=no
 
-    for i in $cpl_incdirs; do
-        for j in $cpl_check_cpl_header; do
 
-            echo "configure: 14194: $i/$j" >&5
 
-            if test -r "$i/$j"; then
-                echo "taking that" >&5
-                cpl_includes=$i
-                break 2
-            fi
-        done
-    done
 
 
 
-        # Check for the CPL libraries
 
-        if test -z "$cpl_with_cpl_libs"; then
 
-            if test -z "$cpl_with_cpl"; then
 
-                # Try some known system locations
+  # Report which library types will actually be built
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if libtool supports shared libraries" >&5
+$as_echo_n "checking if libtool supports shared libraries... " >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5
+$as_echo "$can_build_shared" >&6; }
 
-                cpl_libdirs="/opt/cpl/lib"
-                cpl_libdirs="$cpl_libdirs /usr/local/lib64"
-                cpl_libdirs="$cpl_libdirs /usr/local/lib"
-                cpl_libdirs="$cpl_libdirs /usr/local/lib32"
-                cpl_libdirs="$cpl_libdirs /usr/lib64"
-                cpl_libdirs="$cpl_libdirs /usr/lib"
-                cpl_libdirs="$cpl_libdirs /usr/lib32"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries" >&5
+$as_echo_n "checking whether to build shared libraries... " >&6; }
+  test "$can_build_shared" = "no" && enable_shared=no
 
-                test -n "$CPLDIR" && \
-                    cpl_libdirs="$CPLDIR/lib64 $CPLDIR/lib $CPLDIR/lib32 \
-                                 $cpl_libdirs"
+  # On AIX, shared libraries and static libraries use the same namespace, and
+  # are all built from PIC.
+  case $host_os in
+  aix3*)
+    test "$enable_shared" = yes && enable_static=no
+    if test -n "$RANLIB"; then
+      archive_cmds="$archive_cmds~\$RANLIB \$lib"
+      postinstall_cmds='$RANLIB $lib'
+    fi
+    ;;
 
-            else
+  aix[4-9]*)
+    if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+      test "$enable_shared" = yes && enable_static=no
+    fi
+    ;;
+  esac
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5
+$as_echo "$enable_shared" >&6; }
 
-                cpl_libdirs="$cpl_with_cpl/lib64"
-                cpl_libdirs="$cpl_libdirs $cpl_with_cpl/lib"
-                cpl_libdirs="$cpl_libdirs $cpl_with_cpl/lib32"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries" >&5
+$as_echo_n "checking whether to build static libraries... " >&6; }
+  # Make sure either enable_shared or enable_static is yes.
+  test "$enable_shared" = yes || enable_static=yes
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5
+$as_echo "$enable_static" >&6; }
 
-            fi
 
-        else
-            cpl_libdirs="$cpl_with_cpl_libs"
-        fi
 
 
-    cpl_libraries=no
+fi
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
-    for i in $cpl_libdirs; do
-        for j in $cpl_check_cpl_lib; do
+CC="$lt_save_CC"
 
-            echo "configure: 14244: $i/$j" >&5
 
-            if test -r "$i/$j"; then
-                echo "taking that" >&5
-                cpl_libraries=$i
-                break 2
-            fi
-        done
-    done
 
 
 
-        if test x"$cpl_includes" = xno || test x"$cpl_libraries" = xno; then
-            cpl_notfound=""
 
-            if test x"$cpl_includes" = xno; then
-                if test x"$cpl_libraries" = xno; then
-                    cpl_notfound="(headers and libraries)"
-                else
-                    cpl_notfound="(headers)"
-                fi
-            else
-                cpl_notfound="(libraries)"
-            fi
 
-            as_fn_error $? "CPL $cpl_notfound was not found on your system. Please check!" "$LINENO" 5
-        else
-            { $as_echo "$as_me:${as_lineno-$LINENO}: result: libraries $cpl_libraries, headers $cpl_includes" >&5
-$as_echo "libraries $cpl_libraries, headers $cpl_includes" >&6; }
-        fi
 
-    	# The libcext headers are required. By default it part of the
-    	# CPL installation and it is assumed that the cext headers are
-    	# present in the same location as the CPL headers
 
 
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libcext" >&5
-$as_echo_n "checking for libcext... " >&6; }
 
-    cpl_cext_check_header="cxtypes.h"
-    cpl_cext_check_lib="libcext.a"
 
-    cpl_cext_incdirs=""
-    cpl_cext_libdirs=""
 
-    cpl_cext_includes=""
-    cpl_cext_libraries=""
 
+        ac_config_commands="$ac_config_commands libtool"
 
-	# Initialize directory search paths with the arguments provided
 
-	if test -n "$cpl_includes"; then
-		cpl_cext_incdirs="$cpl_includes"
-	fi
 
-	if test -n "$cpl_libraries"; then
-		cpl_cext_libdirs="$cpl_libraries"
-	fi
 
+# Only expand once:
 
 
-# Check whether --with-cext was given.
-if test "${with_cext+set}" = set; then :
-  withval=$with_cext;
-                    cpl_with_cext=$withval
 
-fi
 
+# Checks for header files.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
+$as_echo_n "checking for ANSI C header files... " >&6; }
+if ${ac_cv_header_stdc+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <float.h>
 
+int
+main ()
+{
 
-# Check whether --with-cext-includes was given.
-if test "${with_cext_includes+set}" = set; then :
-  withval=$with_cext_includes; cpl_with_cext_includes=$withval
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_header_stdc=yes
+else
+  ac_cv_header_stdc=no
 fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 
+if test $ac_cv_header_stdc = yes; then
+  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <string.h>
 
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "memchr" >/dev/null 2>&1; then :
 
-# Check whether --with-cext-libs was given.
-if test "${with_cext_libs+set}" = set; then :
-  withval=$with_cext_libs; cpl_with_cext_libs=$withval
-fi
-
-
-    # Check whether --enable-cext-test was given.
-if test "${enable_cext_test+set}" = set; then :
-  enableval=$enable_cext_test; cpl_enable_cext_test=$enableval
 else
-  cpl_enable_cext_test=yes
+  ac_cv_header_stdc=no
 fi
+rm -f conftest*
 
+fi
 
+if test $ac_cv_header_stdc = yes; then
+  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
 
-    if test "x$cpl_enable_cext_test" = xyes; then
-
-        # Check for the libcext includes
-
-        if test -z "$cpl_with_cext_includes"; then
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "free" >/dev/null 2>&1; then :
 
-            if test -z "$cpl_with_cext"; then
+else
+  ac_cv_header_stdc=no
+fi
+rm -f conftest*
 
-            	if test -z "$cpl_cext_incdirs"; then
+fi
 
-	                # Try some known system locations
+if test $ac_cv_header_stdc = yes; then
+  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
+  if test "$cross_compiling" = yes; then :
+  :
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ctype.h>
+#include <stdlib.h>
+#if ((' ' & 0x0FF) == 0x020)
+# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
+# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
+#else
+# define ISLOWER(c) \
+		   (('a' <= (c) && (c) <= 'i') \
+		     || ('j' <= (c) && (c) <= 'r') \
+		     || ('s' <= (c) && (c) <= 'z'))
+# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
+#endif
 
-    	            cpl_cext_incdirs="/opt/cext/include"
-        	        cpl_cext_incdirs="$cpl_cext_incdirs /usr/local/include/cext"
-            	    cpl_cext_incdirs="$cpl_cext_incdirs /usr/local/include"
-                	cpl_cext_incdirs="$cpl_cext_incdirs /usr/include/cext"
-                	cpl_cext_incdirs="$cpl_cext_incdirs /usr/include"
+#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
+int
+main ()
+{
+  int i;
+  for (i = 0; i < 256; i++)
+    if (XOR (islower (i), ISLOWER (i))
+	|| toupper (i) != TOUPPER (i))
+      return 2;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
 
-                	test -n "$CPLDIR" && \
-                    	cpl_cext_incdirs="$CPLDIR/include/cext \
-                        	              $CPLDIR/include \
-                            	          $cpl_cext_incdirs"
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
 
-				fi
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
+$as_echo "$ac_cv_header_stdc" >&6; }
+if test $ac_cv_header_stdc = yes; then
 
-            else
+$as_echo "#define STDC_HEADERS 1" >>confdefs.h
 
-                cpl_cext_incdirs="$cpl_with_cext/include/cext"
-                cpl_cext_incdirs="$cpl_cext_incdirs $cpl_with_cext/include"
+fi
 
-            fi
+for ac_header in string.h
+do :
+  ac_fn_c_check_header_mongrel "$LINENO" "string.h" "ac_cv_header_string_h" "$ac_includes_default"
+if test "x$ac_cv_header_string_h" = xyes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_STRING_H 1
+_ACEOF
 
-        else
-            cpl_cext_incdirs="$cpl_with_cext_includes"
-        fi
+fi
 
+done
 
-    cpl_cext_includes=no
 
-    for i in $cpl_cext_incdirs; do
-        for j in $cpl_cext_check_header; do
+# Checks for typedefs, structures, and compiler characteristics.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5
+$as_echo_n "checking for an ANSI C-conforming const... " >&6; }
+if ${ac_cv_c_const+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
 
-            echo "configure: 14379: $i/$j" >&5
+int
+main ()
+{
 
-            if test -r "$i/$j"; then
-                echo "taking that" >&5
-                cpl_cext_includes=$i
-                break 2
-            fi
-        done
-    done
+#ifndef __cplusplus
+  /* Ultrix mips cc rejects this sort of thing.  */
+  typedef int charset[2];
+  const charset cs = { 0, 0 };
+  /* SunOS 4.1.1 cc rejects this.  */
+  char const *const *pcpcc;
+  char **ppc;
+  /* NEC SVR4.0.2 mips cc rejects this.  */
+  struct point {int x, y;};
+  static struct point const zero = {0,0};
+  /* AIX XL C 1.02.0.0 rejects this.
+     It does not let you subtract one const X* pointer from another in
+     an arm of an if-expression whose if-part is not a constant
+     expression */
+  const char *g = "string";
+  pcpcc = &g + (g ? g-g : 0);
+  /* HPUX 7.0 cc rejects these. */
+  ++pcpcc;
+  ppc = (char**) pcpcc;
+  pcpcc = (char const *const *) ppc;
+  { /* SCO 3.2v4 cc rejects this sort of thing.  */
+    char tx;
+    char *t = &tx;
+    char const *s = 0 ? (char *) 0 : (char const *) 0;
 
+    *t++ = 0;
+    if (s) return 0;
+  }
+  { /* Someone thinks the Sun supposedly-ANSI compiler will reject this.  */
+    int x[] = {25, 17};
+    const int *foo = &x[0];
+    ++foo;
+  }
+  { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */
+    typedef const int *iptr;
+    iptr p = 0;
+    ++p;
+  }
+  { /* AIX XL C 1.02.0.0 rejects this sort of thing, saying
+       "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */
+    struct s { int j; const int *ap[3]; } bx;
+    struct s *b = &bx; b->j = 5;
+  }
+  { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
+    const int foo = 10;
+    if (!foo) return 0;
+  }
+  return !cs[0] && !zero.x;
+#endif
 
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_c_const=yes
+else
+  ac_cv_c_const=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5
+$as_echo "$ac_cv_c_const" >&6; }
+if test $ac_cv_c_const = no; then
 
-        # Check for the libcext library
+$as_echo "#define const /**/" >>confdefs.h
 
-        if test -z "$cpl_with_cext_libs"; then
+fi
 
-            if test -z "$cpl_with_cext"; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inline" >&5
+$as_echo_n "checking for inline... " >&6; }
+if ${ac_cv_c_inline+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_cv_c_inline=no
+for ac_kw in inline __inline__ __inline; do
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifndef __cplusplus
+typedef int foo_t;
+static $ac_kw foo_t static_foo () {return 0; }
+$ac_kw foo_t foo () {return 0; }
+#endif
 
-            	if test -z "$cpl_cext_libdirs"; then
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_c_inline=$ac_kw
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  test "$ac_cv_c_inline" != no && break
+done
 
-	                # Try some known system locations
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_inline" >&5
+$as_echo "$ac_cv_c_inline" >&6; }
 
-    	            cpl_cext_libdirs="/opt/cext/lib"
-                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/local/lib64"
-                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/local/lib"
-                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/local/lib32"
-                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/lib64"
-                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/lib"
-                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/lib32"
+case $ac_cv_c_inline in
+  inline | yes) ;;
+  *)
+    case $ac_cv_c_inline in
+      no) ac_val=;;
+      *) ac_val=$ac_cv_c_inline;;
+    esac
+    cat >>confdefs.h <<_ACEOF
+#ifndef __cplusplus
+#define inline $ac_val
+#endif
+_ACEOF
+    ;;
+esac
 
-                	test -n "$CPLDIR" && \
-                    	cpl_cext_libdirs="$CPLDIR/lib64 \
-                    					  $CPLDIR/lib \
-                    					  $CPLDIR/lib32 \
-                                          $cpl_cext_libdirs"
 
-				fi
+# Checks for library functions.
+for ac_func in floor pow sqrt
+do :
+  as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
+ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
+if eval test \"x\$"$as_ac_var"\" = x"yes"; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
 
-            else
+fi
+done
 
-                cpl_cext_libdirs="$cpl_with_cext/lib64"
-                cpl_cext_libdirs="$cpl_cext_libdirs $cpl_with_cext/lib"
-                cpl_cext_libdirs="$cpl_cext_libdirs $cpl_with_cext/lib32"
 
-            fi
 
-        else
-            cpl_cext_libdirs="$cpl_with_cext_libs"
-        fi
 
 
-    cpl_cext_libraries=no
 
-    for i in $cpl_cext_libdirs; do
-        for j in $cpl_cext_check_lib; do
 
-            echo "configure: 14435: $i/$j" >&5
+    ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
-            if test -r "$i/$j"; then
-                echo "taking that" >&5
-                cpl_cext_libraries=$i
-                break 2
-            fi
-        done
-    done
 
+    ac_fn_c_check_decl "$LINENO" "strdup" "ac_cv_have_decl_strdup" "#include <string.h>
+"
+if test "x$ac_cv_have_decl_strdup" = xyes; then :
 
+fi
 
-        if test x"$cpl_cext_includes" = xno || \
-            test x"$cpl_cext_libraries" = xno; then
-            cpl_cext_notfound=""
 
-            if test x"$cpl_cext_includes" = xno; then
-                if test x"$cpl_cext_libraries" = xno; then
-                    cpl_cext_notfound="(headers and libraries)"
-                else
-                    cpl_cext_notfound="(headers)"
-                fi
-            else
-                cpl_cext_notfound="(libraries)"
-            fi
+    eso_save_CFLAGS="$CFLAGS"
 
-            as_fn_error $? "libcext $cpl_cext_notfound was not found on your system. Please check!" "$LINENO" 5
-        else
-            { $as_echo "$as_me:${as_lineno-$LINENO}: result: libraries $cpl_cext_libraries, headers $cpl_cext_includes" >&5
-$as_echo "libraries $cpl_cext_libraries, headers $cpl_cext_includes" >&6; }
-        fi
+    if test x"$GCC" = xyes; then
+        CFLAGS="$CFLAGS -pedantic-errors"
+    fi
 
+    ac_fn_c_check_func "$LINENO" "strdup" "ac_cv_func_strdup"
+if test "x$ac_cv_func_strdup" = xyes; then :
 
-        # Set up the symbols
+fi
 
-        CX_INCLUDES="-I$cpl_cext_includes"
-        CX_LDFLAGS="-L$cpl_cext_libraries"
-        LIBCEXT="-lcext"
 
+    CFLAGS="$eso_save_CFLAGS"
 
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether libcext can be used" >&5
-$as_echo_n "checking whether libcext can be used... " >&6; }
-        ac_ext=c
+    ac_ext=c
 ac_cpp='$CPP $CPPFLAGS'
 ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
 ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
 ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
-        cpl_cext_cflags_save="$CFLAGS"
-        cpl_cext_ldflags_save="$LDFLAGS"
-        cpl_cext_libs_save="$LIBS"
-
-        CFLAGS="$CX_INCLUDES $CFLAGS"
-        LDFLAGS="$CX_LDFLAGS $LDFLAGS"
-        LIBS="$LIBCEXT"
+    if test x"$ac_cv_have_decl_strdup" = xyes &&
+       test x"$ac_cv_func_strdup" = xyes; then
+        $as_echo "#define HAVE_STRDUP 1" >>confdefs.h
 
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
+    fi
 
-                       #include <cxutils.h>
 
-int
-main ()
-{
 
-                       cx_program_set_name("MyProgram");
 
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  cpl_cext_is_usable="yes"
-else
-  cpl_cext_is_usable="no"
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
 
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cpl_cext_is_usable" >&5
-$as_echo "$cpl_cext_is_usable" >&6; }
 
-        ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
+# Check for CPL presence and usability
 
 
-        CFLAGS="$cpl_cext_cflags_save"
-        LDFLAGS="$cpl_cext_ldflags_save"
-        LIBS="$cpl_cext_libs_save"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for CPL" >&5
+$as_echo_n "checking for CPL... " >&6; }
 
-        if test x"$cpl_cext_is_usable" = xno; then
-            as_fn_error $? "Linking with libcext failed! Please check architecture!" "$LINENO" 5
-        fi
+    cpl_check_cpl_header="cpl.h"
+    cpl_check_cpl_lib="libcplcore.a"
 
-    else
+    cpl_incdirs=""
+    cpl_libdirs=""
+    cpl_includes=""
+    cpl_libraries=""
 
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5
-$as_echo "disabled" >&6; }
-        { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: libcext checks have been disabled! This package may not build!" >&5
-$as_echo "$as_me: WARNING: libcext checks have been disabled! This package may not build!" >&2;}
-        CX_INCLUDES=""
-        CX_LDFLAGS=""
-        LIBCEXT=""
 
-    fi
+# Check whether --with-cpl was given.
+if test "${with_cpl+set}" = set; then :
+  withval=$with_cpl;
+                    cpl_with_cpl=$withval
 
+fi
 
 
 
+# Check whether --with-cpl-includes was given.
+if test "${with_cpl_includes+set}" = set; then :
+  withval=$with_cpl_includes; cpl_with_cpl_includes=$withval
+fi
 
 
 
+# Check whether --with-cpl-libs was given.
+if test "${with_cpl_libs+set}" = set; then :
+  withval=$with_cpl_libs; cpl_with_cpl_libs=$withval
+fi
 
-        # Set up the symbols
 
-        CPL_INCLUDES="-I$cpl_includes $CX_INCLUDES $CFITSIO_INCLUDES"
-        CPL_LDFLAGS="-L$cpl_libraries $CX_LDFLAGS $CFITSIO_LDFLAGS"
+    # Check whether --enable-cpl-test was given.
+if test "${enable_cpl_test+set}" = set; then :
+  enableval=$enable_cpl_test; cpl_enable_cpl_test=$enableval
+else
+  cpl_enable_cpl_test=yes
+fi
 
 
-    if test -z ""; then
-        LIBCPLCORE='-lcplcore'
-        LIBCPLDRS='-lcpldrs'
-        LIBCPLUI='-lcplui'
-        LIBCPLDFS='-lcpldfs'
-    else
-        LIBCPLCORE='$(top_builddir)/cplcore/libcplcore.la'
-        LIBCPLDRS='$(top_builddir)/cpldrs/libcpldrs.la'
-        LIBCPLUI='$(top_builddir)/cplui/libcplui.la'
-        LIBCPLDFS='$(top_builddir)/cpldfs/libcpldfs.la'
-    fi
 
+    if test "x$cpl_enable_cpl_test" = xyes; then
 
+        # Check for the CPL includes
 
+        if test -z "$cpl_with_cpl_includes"; then
 
+            if test -z "$cpl_with_cpl"; then
 
+                # Try some known system locations
 
+                cpl_incdirs="/opt/cpl/include"
+                cpl_incdirs="$cpl_incdirs /usr/local/include"
+                cpl_incdirs="$cpl_incdirs /usr/include"
 
+                test -n "$CPLDIR" && \
+                    cpl_incdirs="$CPLDIR/include \
+                                 $cpl_incdirs"
 
+            else
 
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether CPL can be used" >&5
-$as_echo_n "checking whether CPL can be used... " >&6; }
-        ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
+                cpl_incdirs="$cpl_with_cpl/include"
 
+            fi
 
-        cpl_cflags_save="$CFLAGS"
-        cpl_ldflags_save="$LDFLAGS"
-        cpl_libs_save="$LIBS"
+        else
+            cpl_incdirs="$cpl_with_cpl_includes"
+        fi
 
-        CFLAGS="$CPL_INCLUDES $CFLAGS"
-        LDFLAGS="$CPL_LDFLAGS $LDFLAGS"
-        LIBS="$LIBCPLCORE $LIBCEXT $LIBS"
 
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
+    cpl_includes=no
 
-                       #include <cpl.h>
+    for i in $cpl_incdirs; do
+        for j in $cpl_check_cpl_header; do
 
-int
-main ()
-{
+            echo "configure: 13477: $i/$j" >&5
 
-                       cpl_init(CPL_INIT_DEFAULT);
+            if test -r "$i/$j"; then
+                echo "taking that" >&5
+                cpl_includes=$i
+                break 2
+            fi
+        done
+    done
 
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  cpl_is_usable="yes"
-else
-  cpl_is_usable="no"
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
 
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cpl_is_usable" >&5
-$as_echo "$cpl_is_usable" >&6; }
 
-        ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
+        # Check for the CPL libraries
 
+        if test -z "$cpl_with_cpl_libs"; then
 
-        CFLAGS="$cpl_cflags_save"
-        LDFLAGS="$cpl_ldflags_save"
-        LIBS="$cpl_libs_save"
+            if test -z "$cpl_with_cpl"; then
 
-        if test x"$cpl_is_usable" = xno; then
-            as_fn_error $? "Linking with CPL failed! Please check architecture!" "$LINENO" 5
-        fi
+                # Try some known system locations
 
-    else
+                cpl_libdirs="/opt/cpl/lib"
+                cpl_libdirs="$cpl_libdirs /usr/local/lib64"
+                cpl_libdirs="$cpl_libdirs /usr/local/lib"
+                cpl_libdirs="$cpl_libdirs /usr/local/lib32"
+                cpl_libdirs="$cpl_libdirs /usr/lib64"
+                cpl_libdirs="$cpl_libdirs /usr/lib"
+                cpl_libdirs="$cpl_libdirs /usr/lib32"
 
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5
-$as_echo "disabled" >&6; }
-        { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: CPL checks have been disabled! This package may not build!" >&5
-$as_echo "$as_me: WARNING: CPL checks have been disabled! This package may not build!" >&2;}
-        CPL_INCLUDES=""
-        CPL_LDFLAGS=""
-        LIBCPLCORE=""
-        LIBCPLDRS=""
-        LIBCPLUI=""
-        LIBCPLDFS=""
+                test -n "$CPLDIR" && \
+                    cpl_libdirs="$CPLDIR/lib64 $CPLDIR/lib $CPLDIR/lib32 \
+                                 $cpl_libdirs"
 
-    fi
+            else
 
+                cpl_libdirs="$cpl_with_cpl/lib64"
+                cpl_libdirs="$cpl_libdirs $cpl_with_cpl/lib"
+                cpl_libdirs="$cpl_libdirs $cpl_with_cpl/lib32"
 
+            fi
 
+        else
+            cpl_libdirs="$cpl_with_cpl_libs"
+        fi
 
 
+    cpl_libraries=no
 
+    for i in $cpl_libdirs; do
+        for j in $cpl_check_cpl_lib; do
 
+            echo "configure: 13527: $i/$j" >&5
 
+            if test -r "$i/$j"; then
+                echo "taking that" >&5
+                cpl_libraries=$i
+                break 2
+            fi
+        done
+    done
 
 
 
+        if test x"$cpl_includes" = xno || test x"$cpl_libraries" = xno; then
+            cpl_notfound=""
 
-    if test -z "$plugindir"; then
-        plugindir='${libdir}/esopipes-plugins/${PACKAGE}-${VERSION}'
-    fi
+            if test x"$cpl_includes" = xno; then
+                if test x"$cpl_libraries" = xno; then
+                    cpl_notfound="(headers and libraries)"
+                else
+                    cpl_notfound="(headers)"
+                fi
+            else
+                cpl_notfound="(libraries)"
+            fi
 
-    if test -z "$privatelibdir"; then
-        privatelibdir='${libdir}/${PACKAGE}-${VERSION}'
-    fi
+            as_fn_error $? "CPL $cpl_notfound was not found on your system. Please check!" "$LINENO" 5
+        else
+            { $as_echo "$as_me:${as_lineno-$LINENO}: result: libraries $cpl_libraries, headers $cpl_includes" >&5
+$as_echo "libraries $cpl_libraries, headers $cpl_includes" >&6; }
+        fi
 
-    if test -z "$pipedocsdir"; then
-        pipedocsdir='${datadir}/doc/esopipes/${PACKAGE}-${VERSION}'
-    fi
+    	# The libcext headers are required. By default it part of the
+    	# CPL installation and it is assumed that the cext headers are
+    	# present in the same location as the CPL headers
 
-    htmldir='${pipedocsdir}/html'
 
-    if test -z "$configdir"; then
-       configdir='${datadir}/${PACKAGE}/config'
-    fi
 
-    if test -z "$wkfextradir"; then
-        wkfextradir='${datadir}/esopipes/${PACKAGE}-${VERSION}/reflex'
-    fi
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libcext" >&5
+$as_echo_n "checking for libcext... " >&6; }
 
-    if test -z "$wkfcopydir"; then
-        wkfcopydir='${datadir}/reflex/workflows/${PACKAGE}-${VERSION}'
-    fi
+    cpl_cext_check_header="cxtypes.h"
+    cpl_cext_check_lib="libcext.a"
 
-    testpath=`cd $srcdir/xsh && pwd`/tests/data
+    cpl_cext_incdirs=""
+    cpl_cext_libdirs=""
+
+    cpl_cext_includes=""
+    cpl_cext_libraries=""
+
+
+	# Initialize directory search paths with the arguments provided
 
+	if test -n "$cpl_includes"; then
+		cpl_cext_incdirs="$cpl_includes"
+	fi
 
+	if test -n "$cpl_libraries"; then
+		cpl_cext_libdirs="$cpl_libraries"
+	fi
 
 
 
+# Check whether --with-cext was given.
+if test "${with_cext+set}" = set; then :
+  withval=$with_cext;
+                    cpl_with_cext=$withval
 
+fi
 
 
 
+# Check whether --with-cext-includes was given.
+if test "${with_cext_includes+set}" = set; then :
+  withval=$with_cext_includes; cpl_with_cext_includes=$withval
+fi
 
-    # Define a preprocesor symbol for the plugin search paths
 
 
-cat >>confdefs.h <<_ACEOF
-#define XSH_PLUGIN_DIR "esopipes-plugins"
-_ACEOF
+# Check whether --with-cext-libs was given.
+if test "${with_cext_libs+set}" = set; then :
+  withval=$with_cext_libs; cpl_with_cext_libs=$withval
+fi
 
 
-    eval plugin_dir="$plugindir"
-    plugin_path=`eval echo $plugin_dir | \
-                sed -e "s/\/${PACKAGE}-${VERSION}.*$//"`
+    # Check whether --enable-cext-test was given.
+if test "${enable_cext_test+set}" = set; then :
+  enableval=$enable_cext_test; cpl_enable_cext_test=$enableval
+else
+  cpl_enable_cext_test=yes
+fi
 
 
-cat >>confdefs.h <<_ACEOF
-#define XSH_PLUGIN_PATH "$plugin_path"
-_ACEOF
 
+    if test "x$cpl_enable_cext_test" = xyes; then
 
+        # Check for the libcext includes
 
-cat >>confdefs.h <<_ACEOF
-#define XSH_TEST_DATA_PATH "$testpath"
-_ACEOF
+        if test -z "$cpl_with_cext_includes"; then
 
+            if test -z "$cpl_with_cext"; then
 
+            	if test -z "$cpl_cext_incdirs"; then
 
+	                # Try some known system locations
 
+    	            cpl_cext_incdirs="/opt/cext/include"
+        	        cpl_cext_incdirs="$cpl_cext_incdirs /usr/local/include/cext"
+            	    cpl_cext_incdirs="$cpl_cext_incdirs /usr/local/include"
+                	cpl_cext_incdirs="$cpl_cext_incdirs /usr/include/cext"
+                	cpl_cext_incdirs="$cpl_cext_incdirs /usr/include"
 
-# Check whether --with-extra-includes was given.
-if test "${with_extra_includes+set}" = set; then :
-  withval=$with_extra_includes; eso_with_extra_includes=$withval
-else
-  eso_with_extra_includes=NONE
-fi
+                	test -n "$CPLDIR" && \
+                    	cpl_cext_incdirs="$CPLDIR/include/cext \
+                        	              $CPLDIR/include \
+                            	          $cpl_cext_incdirs"
 
+				fi
 
+            else
 
-# Check whether --with-extra-libs was given.
-if test "${with_extra_libs+set}" = set; then :
-  withval=$with_extra_libs; eso_with_extra_libs=$withval
-else
-  eso_with_extra_libs=NONE
-fi
+                cpl_cext_incdirs="$cpl_with_cext/include/cext"
+                cpl_cext_incdirs="$cpl_cext_incdirs $cpl_with_cext/include"
 
+            fi
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for extra includes" >&5
-$as_echo_n "checking for extra includes... " >&6; }
-    if ${eso_cv_with_extra_includes+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+        else
+            cpl_cext_incdirs="$cpl_with_cext_includes"
+        fi
 
-                     eso_cv_with_extra_includes=$eso_with_extra_includes
 
-fi
+    cpl_cext_includes=no
 
+    for i in $cpl_cext_incdirs; do
+        for j in $cpl_cext_check_header; do
 
-    if test x"$eso_cv_with_extra_includes" != xNONE; then
-        eso_save_IFS=$IFS
-        IFS=':'
+            echo "configure: 13662: $i/$j" >&5
 
-        for dir in $eso_cv_with_extra_includes; do
-            EXTRA_INCLUDES="$EXTRA_INCLUDES -I$dir"
+            if test -r "$i/$j"; then
+                echo "taking that" >&5
+                cpl_cext_includes=$i
+                break 2
+            fi
         done
+    done
 
-        IFS=$eso_save_IFS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: added" >&5
-$as_echo "added" >&6; }
-    else
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-    fi
 
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for extra libs" >&5
-$as_echo_n "checking for extra libs... " >&6; }
-    if ${eso_cv_with_extra_libs+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+        # Check for the libcext library
 
-                     eso_cv_with_extra_libs=$eso_with_extra_libs
+        if test -z "$cpl_with_cext_libs"; then
 
-fi
+            if test -z "$cpl_with_cext"; then
 
+            	if test -z "$cpl_cext_libdirs"; then
 
-    if test x"$eso_cv_with_extra_libs" != xNONE; then
-        eso_save_IFS=$IFS
-        IFS=':'
+	                # Try some known system locations
 
-        for dir in $eso_cv_with_extra_libs; do
-            EXTRA_LDFLAGS="$EXTRA_LDFLAGS -L$dir"
-        done
+    	            cpl_cext_libdirs="/opt/cext/lib"
+                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/local/lib64"
+                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/local/lib"
+                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/local/lib32"
+                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/lib64"
+                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/lib"
+                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/lib32"
 
-        IFS=$eso_save_IFS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: added" >&5
-$as_echo "added" >&6; }
-    else
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-    fi
+                	test -n "$CPLDIR" && \
+                    	cpl_cext_libdirs="$CPLDIR/lib64 \
+                    					  $CPLDIR/lib \
+                    					  $CPLDIR/lib32 \
+                                          $cpl_cext_libdirs"
 
+				fi
 
+            else
 
+                cpl_cext_libdirs="$cpl_with_cext/lib64"
+                cpl_cext_libdirs="$cpl_cext_libdirs $cpl_with_cext/lib"
+                cpl_cext_libdirs="$cpl_cext_libdirs $cpl_with_cext/lib32"
 
-    # Symbols for package include file and library search paths
+            fi
 
-    XSH_INCLUDES='-I$(top_srcdir)/xsh -I$(top_srcdir)/irplib'
-    XSH_LDFLAGS='-L$(top_builddir)/xsh'
+        else
+            cpl_cext_libdirs="$cpl_with_cext_libs"
+        fi
 
-    # Library aliases
-    LIBXSH='$(top_builddir)/xsh/libxsh.la'
-    LIBIRPLIB='$(top_builddir)/irplib/libirplib.la'
 
-    # Using irplib_fits_update_checksums function:
-    IRPLIB_CPPFLAGS='-DIRPLIB_USE_FITS_UPDATE_CHECKSUM'
+    cpl_cext_libraries=no
 
-    # Substitute the defined symbols
+    for i in $cpl_cext_libdirs; do
+        for j in $cpl_cext_check_lib; do
 
+            echo "configure: 13718: $i/$j" >&5
 
+            if test -r "$i/$j"; then
+                echo "taking that" >&5
+                cpl_cext_libraries=$i
+                break 2
+            fi
+        done
+    done
 
 
 
+        if test x"$cpl_cext_includes" = xno || \
+            test x"$cpl_cext_libraries" = xno; then
+            cpl_cext_notfound=""
 
+            if test x"$cpl_cext_includes" = xno; then
+                if test x"$cpl_cext_libraries" = xno; then
+                    cpl_cext_notfound="(headers and libraries)"
+                else
+                    cpl_cext_notfound="(headers)"
+                fi
+            else
+                cpl_cext_notfound="(libraries)"
+            fi
 
-    # Check for CPL and user defined libraries
+            as_fn_error $? "libcext $cpl_cext_notfound was not found on your system. Please check!" "$LINENO" 5
+        else
+            { $as_echo "$as_me:${as_lineno-$LINENO}: result: libraries $cpl_cext_libraries, headers $cpl_cext_includes" >&5
+$as_echo "libraries $cpl_cext_libraries, headers $cpl_cext_includes" >&6; }
+        fi
 
 
+        # Set up the symbols
 
-    all_includes='$(XSH_INCLUDES) $(CPL_INCLUDES)  $(GSL_INCLUDES) $(EXTRA_INCLUDES) $(CFITSIO_INCLUDES)  $(LAPACK_INCLUDES)'
-    all_ldflags='$(XSH_LDFLAGS) $(CPL_LDFLAGS) $(GSL_LDFLAGS) $(EXTRA_LDFLAGS)'
+        CX_INCLUDES="-I$cpl_cext_includes"
+        CX_LDFLAGS="-L$cpl_cext_libraries"
+        LIBCEXT="-lcext"
 
 
+        { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether libcext can be used" >&5
+$as_echo_n "checking whether libcext can be used... " >&6; }
+        ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
+        cpl_cext_cflags_save="$CFLAGS"
+        cpl_cext_ldflags_save="$LDFLAGS"
+        cpl_cext_libs_save="$LIBS"
 
+        CFLAGS="$CX_INCLUDES $CFLAGS"
+        LDFLAGS="$CX_LDFLAGS $LDFLAGS"
+        LIBS="$LIBCEXT"
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for PURIFY availability" >&5
-$as_echo_n "checking for PURIFY availability... " >&6; }
+        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
 
-    # Check whether --enable-purify was given.
-if test "${enable_purify+set}" = set; then :
-  enableval=$enable_purify; enable_purify=$enableval
-else
-  enable_purify=yes
-fi
+                       #include <cxutils.h>
 
+int
+main ()
+{
 
-    if test "x$enable_purify" = xyes ; then
-      # Extract the first word of "purify", so it can be a program name with args.
-set dummy purify; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_PURIFY_CMD+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$PURIFY_CMD"; then
-  ac_cv_prog_PURIFY_CMD="$PURIFY_CMD" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_PURIFY_CMD="purify"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
+                       cx_program_set_name("MyProgram");
 
-  test -z "$ac_cv_prog_PURIFY_CMD" && ac_cv_prog_PURIFY_CMD="NONE"
-fi
-fi
-PURIFY_CMD=$ac_cv_prog_PURIFY_CMD
-if test -n "$PURIFY_CMD"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PURIFY_CMD" >&5
-$as_echo "$PURIFY_CMD" >&6; }
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  cpl_cext_is_usable="yes"
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  cpl_cext_is_usable="no"
 fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cpl_cext_is_usable" >&5
+$as_echo "$cpl_cext_is_usable" >&6; }
+
+        ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+        CFLAGS="$cpl_cext_cflags_save"
+        LDFLAGS="$cpl_cext_ldflags_save"
+        LIBS="$cpl_cext_libs_save"
+
+        if test x"$cpl_cext_is_usable" = xno; then
+            as_fn_error $? "Linking with libcext failed! Please check architecture!" "$LINENO" 5
+        fi
 
-      if test "$PURIFY_CMD" = "NONE" ; then
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5
-$as_echo "disabled" >&6; }
-        enable_purify=no
-      else
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: enabled" >&5
-$as_echo "enabled" >&6; }
-      fi
     else
-      { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5
+
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5
 $as_echo "disabled" >&6; }
+        { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: libcext checks have been disabled! This package may not build!" >&5
+$as_echo "$as_me: WARNING: libcext checks have been disabled! This package may not build!" >&2;}
+        CX_INCLUDES=""
+        CX_LDFLAGS=""
+        LIBCEXT=""
+
     fi
 
-     if test "x$enable_purify" = "xyes"; then
-  PURIFY_TRUE=
-  PURIFY_FALSE='#'
-else
-  PURIFY_TRUE='#'
-  PURIFY_FALSE=
-fi
 
 
 
 
 
-    # Check whether --enable-profile was given.
-if test "${enable_profile+set}" = set; then :
-  enableval=$enable_profile; eso_enable_profile=$enableval
-else
-  eso_enable_profile=no
-fi
 
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether profiling compiler options should be used" >&5
-$as_echo_n "checking whether profiling compiler options should be used... " >&6; }
-if ${eso_cv_enable_profile+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  eso_cv_enable_profile=$eso_enable_profile
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $eso_cv_enable_profile" >&5
-$as_echo "$eso_cv_enable_profile" >&6; }
+        # Set up the symbols
 
+        CPL_INCLUDES="-I$cpl_includes $CX_INCLUDES $CFITSIO_INCLUDES"
+        CPL_LDFLAGS="-L$cpl_libraries $CX_LDFLAGS $CFITSIO_LDFLAGS"
+
+
+    if test -z ""; then
+        LIBCPLCORE='-lcplcore'
+        LIBCPLDRS='-lcpldrs'
+        LIBCPLUI='-lcplui'
+        LIBCPLDFS='-lcpldfs'
+    else
+        LIBCPLCORE='$(top_builddir)/cplcore/libcplcore.la'
+        LIBCPLDRS='$(top_builddir)/cpldrs/libcpldrs.la'
+        LIBCPLUI='$(top_builddir)/cplui/libcplui.la'
+        LIBCPLDFS='$(top_builddir)/cpldfs/libcpldfs.la'
+    fi
 
-    if test x"$eso_cv_enable_profile" = xyes; then
 
 
 
-    flag=`echo pg | sed 'y%.=/+-%___p_%'`
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -pg" >&5
-$as_echo_n "checking whether $CC supports -pg... " >&6; }
-if eval \${eso_cv_prog_cc_$flag+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
 
-                       eval "eso_cv_prog_cc_$flag=no"
-                       ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
-                       echo 'int main() { return 0; }' >conftest.$ac_ext
 
-                       try_compile="`$CC -pg -c conftest.$ac_ext 2>&1`"
-                       if test -z "$try_compile"; then
-                           try_link="`$CC -pg -o conftest$ac_exeext \
-                                    conftest.$ac_ext 2>&1`"
-                           if test -z "$try_link"; then
-                               eval "eso_cv_prog_cc_$flag=yes"
-                           fi
-                       fi
-                       rm -f conftest*
 
-                       ac_ext=c
+        { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether CPL can be used" >&5
+$as_echo_n "checking whether CPL can be used... " >&6; }
+        ac_ext=c
 ac_cpp='$CPP $CPPFLAGS'
 ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
 ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
 ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
-fi
-eval ac_res=\$eso_cv_prog_cc_$flag
-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
+        cpl_cflags_save="$CFLAGS"
+        cpl_ldflags_save="$LDFLAGS"
+        cpl_libs_save="$LIBS"
 
-    if eval "test \"`echo '$eso_cv_prog_cc_'$flag`\" = yes"; then
-        :
-        CFLAGS="$CFLAGS -pg"
-    else
-        :
+        CFLAGS="$CPL_INCLUDES $CFLAGS"
+        LDFLAGS="$CPL_LDFLAGS $LDFLAGS"
+        LIBS="$LIBCPLCORE $LIBCEXT $LIBS"
 
-    fi
+        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
 
+                       #include <cpl.h>
 
+int
+main ()
+{
 
+                       cpl_init(CPL_INIT_DEFAULT);
 
-    flag=`echo g | sed 'y%.=/+-%___p_%'`
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -g" >&5
-$as_echo_n "checking whether $CC supports -g... " >&6; }
-if eval \${eso_cv_prog_cc_$flag+:} false; then :
-  $as_echo_n "(cached) " >&6
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  cpl_is_usable="yes"
 else
+  cpl_is_usable="no"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 
-                       eval "eso_cv_prog_cc_$flag=no"
-                       ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-                       echo 'int main() { return 0; }' >conftest.$ac_ext
-
-                       try_compile="`$CC -g -c conftest.$ac_ext 2>&1`"
-                       if test -z "$try_compile"; then
-                           try_link="`$CC -g -o conftest$ac_exeext \
-                                    conftest.$ac_ext 2>&1`"
-                           if test -z "$try_link"; then
-                               eval "eso_cv_prog_cc_$flag=yes"
-                           fi
-                       fi
-                       rm -f conftest*
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cpl_is_usable" >&5
+$as_echo "$cpl_is_usable" >&6; }
 
-                       ac_ext=c
+        ac_ext=c
 ac_cpp='$CPP $CPPFLAGS'
 ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
 ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
 ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
-fi
-eval ac_res=\$eso_cv_prog_cc_$flag
-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
+        CFLAGS="$cpl_cflags_save"
+        LDFLAGS="$cpl_ldflags_save"
+        LIBS="$cpl_libs_save"
+
+        if test x"$cpl_is_usable" = xno; then
+            as_fn_error $? "Linking with CPL failed! Please check architecture!" "$LINENO" 5
+        fi
 
-    if eval "test \"`echo '$eso_cv_prog_cc_'$flag`\" = yes"; then
-        :
-        CFLAGS="$CFLAGS -g"
     else
-        :
+
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5
+$as_echo "disabled" >&6; }
+        { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: CPL checks have been disabled! This package may not build!" >&5
+$as_echo "$as_me: WARNING: CPL checks have been disabled! This package may not build!" >&2;}
+        CPL_INCLUDES=""
+        CPL_LDFLAGS=""
+        LIBCPLCORE=""
+        LIBCPLDRS=""
+        LIBCPLUI=""
+        LIBCPLDFS=""
 
     fi
 
 
 
 
-    flag=`echo static-libgcc | sed 'y%.=/+-%___p_%'`
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -static-libgcc" >&5
-$as_echo_n "checking whether $CC supports -static-libgcc... " >&6; }
-if eval \${eso_cv_prog_cc_$flag+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
 
-                       eval "eso_cv_prog_cc_$flag=no"
-                       ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
-                       echo 'int main() { return 0; }' >conftest.$ac_ext
 
-                       try_compile="`$CC -static-libgcc -c conftest.$ac_ext 2>&1`"
-                       if test -z "$try_compile"; then
-                           try_link="`$CC -static-libgcc -o conftest$ac_exeext \
-                                    conftest.$ac_ext 2>&1`"
-                           if test -z "$try_link"; then
-                               eval "eso_cv_prog_cc_$flag=yes"
-                           fi
-                       fi
-                       rm -f conftest*
 
-                       ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
-fi
-eval ac_res=\$eso_cv_prog_cc_$flag
-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
 
-    if eval "test \"`echo '$eso_cv_prog_cc_'$flag`\" = yes"; then
-        :
-        CFLAGS="$CFLAGS -static-libgcc"
-    else
-        :
+    # Symbols for package include file and library search paths
 
-    fi
+    HDRL_INCLUDES='-I$(top_srcdir)'
+    HDRL_LDFLAGS='-L$(top_builddir)'
 
+    # Library aliases
 
-        # Check whether --enable-shared was given.
-if test "${enable_shared+set}" = set; then :
-  enableval=$enable_shared; p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_shared=yes ;;
-    no) enable_shared=no ;;
-    *)
-      enable_shared=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_shared=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac
-else
-  enable_shared=no
-fi
+    LIBHDRL='$(top_builddir)/libhdrl.la'
 
+    # Substitute the defined symbols
 
 
 
 
 
-        # Check whether --enable-static was given.
-if test "${enable_static+set}" = set; then :
-  enableval=$enable_static; p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_static=yes ;;
-    no) enable_static=no ;;
-    *)
-     enable_static=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_static=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac
-else
-  enable_static=yes
-fi
 
 
+    # Check for CPL and user defined libraries
 
 
+    all_includes='$(HDRL_INCLUDES) $(CPL_INCLUDES)'
+    all_ldflags='$(HDRL_LDFLAGS) $(CPL_LDFLAGS)'
+
 
 
-    fi
 
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking if malloc debugging is wanted" >&5
@@ -15159,10 +13993,11 @@ fi
 
 
 
-ac_config_files="$ac_config_files Makefile Makefile.purify doxygen/Doxyfile xsh/Makefile recipes/Makefile xsh/tests/Makefile irplib/Makefile irplib/tests/Makefile reflex/Makefile reflex/xshooter.xml regtests/Makefile regtests/tests/Makefile"
+#AC_CONFIG_SUBDIRS(external/fftw external/sextractor external/swarp)
+#AC_CONFIG_SUBDIRS(external/sextractor external/swarp)
+
+ac_config_files="$ac_config_files Makefile tests/Makefile"
 
-#                recipes/tests/Makefile
-#		reflex/Xshooter.xml
 cat >confcache <<\_ACEOF
 # This file is a shell script that caches the results of configure
 # tests run on this system so they can be shared between configure
@@ -15304,6 +14139,14 @@ if test -z "${PURIFY_TRUE}" && test -z "${PURIFY_FALSE}"; then
   as_fn_error $? "conditional \"PURIFY\" was never defined.
 Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
+if test -z "${VLTSW_TRUE}" && test -z "${VLTSW_FALSE}"; then
+  as_fn_error $? "conditional \"VLTSW\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${PURIFY_TRUE}" && test -z "${PURIFY_FALSE}"; then
+  as_fn_error $? "conditional \"PURIFY\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
 
 : "${CONFIG_STATUS=./config.status}"
 ac_write_fail=0
@@ -15701,7 +14544,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log="
-This file was extended by X-shooter Instrument Pipeline $as_me 2.5.2, which was
+This file was extended by HDRL Pipeline $as_me 0.1.5, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
@@ -15767,7 +14610,7 @@ _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 ac_cs_version="\\
-X-shooter Instrument Pipeline config.status 2.5.2
+HDRL Pipeline config.status 0.1.5
 configured by $0, generated by GNU Autoconf 2.69,
   with options \\"\$ac_cs_config\\"
 
@@ -16177,17 +15020,7 @@ do
     "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;;
     "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;;
     "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
-    "Makefile.purify") CONFIG_FILES="$CONFIG_FILES Makefile.purify" ;;
-    "doxygen/Doxyfile") CONFIG_FILES="$CONFIG_FILES doxygen/Doxyfile" ;;
-    "xsh/Makefile") CONFIG_FILES="$CONFIG_FILES xsh/Makefile" ;;
-    "recipes/Makefile") CONFIG_FILES="$CONFIG_FILES recipes/Makefile" ;;
-    "xsh/tests/Makefile") CONFIG_FILES="$CONFIG_FILES xsh/tests/Makefile" ;;
-    "irplib/Makefile") CONFIG_FILES="$CONFIG_FILES irplib/Makefile" ;;
-    "irplib/tests/Makefile") CONFIG_FILES="$CONFIG_FILES irplib/tests/Makefile" ;;
-    "reflex/Makefile") CONFIG_FILES="$CONFIG_FILES reflex/Makefile" ;;
-    "reflex/xshooter.xml") CONFIG_FILES="$CONFIG_FILES reflex/xshooter.xml" ;;
-    "regtests/Makefile") CONFIG_FILES="$CONFIG_FILES regtests/Makefile" ;;
-    "regtests/tests/Makefile") CONFIG_FILES="$CONFIG_FILES regtests/tests/Makefile" ;;
+    "tests/Makefile") CONFIG_FILES="$CONFIG_FILES tests/Makefile" ;;
 
   *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
   esac
diff --git a/hdrl/configure.ac b/hdrl/configure.ac
new file mode 100644
index 0000000..cd6593d
--- /dev/null
+++ b/hdrl/configure.ac
@@ -0,0 +1,131 @@
+# Process this file with autoconf to produce a configure script.
+
+AC_INIT([HDRL Pipeline], [0.1.5], [usd-help at eso.org], [hdrl])
+AC_PREREQ([2.59])
+
+AC_CONFIG_SRCDIR([Makefile.am])
+AC_CONFIG_AUX_DIR([admin])
+AC_CONFIG_MACRO_DIR([m4macros])
+
+AC_CANONICAL_HOST
+AC_CANONICAL_TARGET
+
+AM_INIT_AUTOMAKE
+AC_CONFIG_HEADERS([config.h])
+
+AM_MAINTAINER_MODE([enable])
+
+# Immediately before every release do:
+#-------------------------------------
+#   if (the interface is totally unchanged from previous release)
+#       REVISION++;
+#   else {
+#       /* interfaces have been added, removed or changed */
+#       REVISION = 0;
+#       CURRENT++;
+#       if (any interfaces have been _added_ since last release)
+#           AGE++;
+#       if (any interfaces have been _removed_ or incompatibly changed)
+#           AGE = 0;
+#   }
+
+# Order of arguments: VERSION, CURRENT, REVISION, AGE
+HDRL_SET_VERSION_INFO([$VERSION], [0], [0], [0])
+
+# Checks for programs.
+AC_PROG_CC
+AC_PROG_CPP
+AM_PROG_CC_C_O
+AC_PROG_LN_S
+
+AC_SYS_LARGEFILE
+
+#
+# Check for purify
+#
+CHECK_PURIFY
+
+ESO_ENABLE_DEBUG(no)
+ESO_ENABLE_STRICT(no)
+#ESO_PROG_CC_FLAG([fno-builtin], [CFLAGS="$CFLAGS -fno-builtin"])
+ESO_PROG_CC_FLAG([std=c99], [CFLAGS="$CFLAGS -std=c99"])
+ESO_PROG_CC_FLAG([Wall], [CFLAGS="-Wall $CFLAGS"])
+ESO_PROG_CC_FLAG([fvisibility=hidden], [CFLAGS="-fvisibility=hidden $CFLAGS"])
+ESO_PROG_CC_FLAG([Werror=implicit-function-declaration],
+                 [CFLAGS="-Werror=implicit-function-declaration $CFLAGS"])
+
+# simple openmp check, the one in eso.m4 is unnecessarily fragile
+# ESO_ENABLE_OPENMP(openmp=no)
+#-----------------------------
+AC_DEFUN([ESO_ENABLE_OPENMP],
+[
+    AC_REQUIRE([AC_PROG_CC])
+
+    AC_ARG_ENABLE(openmp,
+                  AS_HELP_STRING([--enable-openmp],
+                                 [compiles with openmp compiler options (may not work!) [[default=$1]]]),
+                  eso_enable_openmp=$enableval, eso_enable_openmp=$1)
+
+    AC_CACHE_CHECK([whether openmp compiler options should be used],
+                   eso_cv_enable_openmp,
+                   eso_cv_enable_openmp=$eso_enable_openmp)
+
+
+    if test x"$eso_cv_enable_openmp" = xyes; then
+        ESO_PROG_CC_FLAG([fopenmp], [CFLAGS="$CFLAGS -fopenmp"
+                                     LDFLAGS="$LDFLAGS -fopenmp"])
+        ESO_PROG_CC_FLAG([xopenmp], [CFLAGS="$CFLAGS -xopenmp"
+                                     LDFLAGS="$LDFLAGS -xopenmp"])
+    fi
+])
+ESO_ENABLE_OPENMP([yes])
+
+AC_DEFUN([ESO_ENABLE_STANDALONE],
+[
+    AC_ARG_ENABLE(standalone,
+                  AS_HELP_STRING([--enable-standalone],
+                                 [enable standalone installation for VLTSW [[default=$1]]]),
+                  eso_enable_standalone=$enableval, eso_enable_standalone=$1)
+
+    AM_CONDITIONAL([VLTSW], [test x"$eso_enable_standalone" = xyes])
+])
+
+ESO_ENABLE_STANDALONE([no])
+
+ESO_CHECK_DOCTOOLS
+#
+# Check for purify
+#
+CHECK_PURIFY
+
+AC_ENABLE_STATIC(no)
+AC_ENABLE_SHARED(yes)
+
+AC_PROG_LIBTOOL
+AC_SUBST(LIBTOOL_DEPS)
+
+# Checks for header files.
+AC_HEADER_STDC
+AC_CHECK_HEADERS([string.h])
+
+# Checks for typedefs, structures, and compiler characteristics.
+AC_C_CONST
+AC_C_INLINE
+
+# Checks for library functions.
+AC_CHECK_FUNCS([floor pow sqrt])
+ESO_FUNC_STRDUP
+
+# Check for CPL presence and usability
+CPL_CHECK_LIBS
+
+HDRL_CREATE_SYMBOLS
+
+AM_WITH_DMALLOC
+
+#AC_CONFIG_SUBDIRS(external/fftw external/sextractor external/swarp)
+#AC_CONFIG_SUBDIRS(external/sextractor external/swarp)
+
+AC_CONFIG_FILES(Makefile
+                tests/Makefile)
+AC_OUTPUT
diff --git a/hdrl/hdrl.h b/hdrl/hdrl.h
new file mode 100644
index 0000000..679bc11
--- /dev/null
+++ b/hdrl/hdrl.h
@@ -0,0 +1,65 @@
+/* $Id: hdrl.h,v 1.4 2013-10-23 09:42:14 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*----------------------------------------------------------------------------*/
+/* Documentation here is used in the reference manual Main Page */
+/** @mainpage HDRL Introduction
+  
+    TEXT
+ 
+    \section releases Releases
+
+    List of release notes for diff releases
+
+    \section usage Usage
+
+    Externals Defintions description
+    
+    \section hdrldemop
+
+    Offered recipes
+    
+    \section links Links
+    CPL page
+    Pipelines page
+  
+*/
+/*----------------------------------------------------------------------------*/
+
+
+#ifndef HDRL_H
+#define HDRL_H
+
+#include "hdrl_image.h"
+#include "hdrl_imagelist.h"
+#include "hdrl_parameter.h"
+#include "hdrl_imagelist_view.h"
+#include "hdrl_overscan.h"
+#include "hdrl_buffer.h"
+#include "hdrl_collapse.h"
+#include "hdrl_lacosmics.h"
+#include "hdrl_bpm_2d.h"
+#include "hdrl_bpm_3d.h"
+#include "hdrl_bpm_fit.h"
+#include "hdrl_bpm_utils.h"
+#include "hdrl_fit.h"
+#include "hdrl_strehl.h"
+
+#endif 
diff --git a/hdrl/hdrl_bpm_2d.c b/hdrl/hdrl_bpm_2d.c
new file mode 100644
index 0000000..fba0110
--- /dev/null
+++ b/hdrl/hdrl_bpm_2d.c
@@ -0,0 +1,1289 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013,2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+-----------------------------------------------------------------------------*/
+
+#include "hdrl_types.h"
+#include "hdrl_image.h"
+#include "hdrl_imagelist.h"
+#include "hdrl_utils.h"
+
+#include "hdrl_bpm_2d.h"
+#include "hdrl_prototyping.h"
+
+#include <cpl.h>
+#include <string.h>
+#include <math.h>
+
+/*-----------------------------------------------------------------------------
+                                   Static
+ -----------------------------------------------------------------------------*/
+
+
+/**
+ * @defgroup hdrl_bpm Bad Pixel Detection
+ *
+ * @brief
+ *  This module contains functions to detect bad pixels on single images, on a
+ *  stack of identical images and on a sequence of images.
+ *
+ */
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_bpm_2d     Bad Pixel Mask 2D Computation
+  @ingroup hdrl_bpm
+
+ @brief
+   Algorithms to detect bad pixels on a single image
+
+ The routines in this module can be used to detect bad pixels on a single image.
+ The algorithm first smoothes the image by applying different methods.
+ Then it subtracts the smoothed image and derives bad
+ pixels by thresholding the residual image, i.e. all pixels exceeding
+ the threshold are considered as bad.
+
+ The calculation is performed by calling the top-level function
+ hdrl_bpm_2d_compute() and the parameters passed to this function can be created
+ by calling hdrl_bpm_2d_parameter_create_filtersmooth() \b or
+ hdrl_bpm_2d_parameter_create_legendresmooth(), depending on the method one
+ would like to use.
+
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+
+/** @cond PRIVATE */
+
+static cpl_image * hdrl_get_residuals_filtersmooth(cpl_size, cpl_size,
+        cpl_filter_mode, cpl_border_mode, cpl_image *, cpl_mask *);
+static cpl_image * hdrl_get_residuals_legendresmooth(const cpl_image *, int,
+        int, int, int, int, int) ;
+
+/*-----------------------------------------------------------------------------
+                        BPM Parameters Definition
+ -----------------------------------------------------------------------------*/
+typedef struct {
+    HDRL_PARAMETER_HEAD;
+    cpl_filter_mode     filter ;
+    cpl_border_mode     border ;
+    double              kappa_low ;
+    double              kappa_high ;
+    int                 maxiter ;
+    int                 steps_x ;
+    int                 steps_y ;
+    int                 filter_size_x ;
+    int                 filter_size_y ;
+    int                 order_x ;
+    int                 order_y ;
+    int                 smooth_x ;
+    int                 smooth_y ;
+    hdrl_bpm_2d_method  method ;
+} hdrl_bpm_2d_parameter;
+
+/* Parameter type */
+static hdrl_parameter_typeobj hdrl_bpm_2d_parameter_type = {
+    HDRL_PARAMETER_BPM_2D,                  /* type */
+    (hdrl_alloc *)&cpl_malloc,              /* fp_alloc */
+    (hdrl_free *)&cpl_free,                 /* fp_free */
+    NULL,                                   /* fp_destroy */
+    sizeof(hdrl_bpm_2d_parameter),          /* obj_size */
+};
+/** @endcond */
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Creates BPM_2D Parameters object for HDRL_BPM_2D_FILTERSMOOTH
+  @param    kappa_low       Low kappa factor for thresholding algorithm
+  @param    kappa_high      High kappa factor for thresholding algorithm
+  @param    maxiter         Maximum number of iterations
+  @param    filter          filter mode
+  @param    border          border mode
+  @param    smooth_x        Smoothing kernel X size
+  @param    smooth_y        Smoothing kernel Y size
+  @return   The BPM_2D parameters object. It needs to be deallocated with
+            hdrl_parameter_delete()
+
+  The method creates a parameter for the method HDRL_BPM_2D_FILTERSMOOTH
+
+  @see      hdrl_parameter_delete()
+  @see      hdrl_bpm_2d_compute()
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_bpm_2d_parameter_create_filtersmooth(
+        double              kappa_low,
+        double              kappa_high,
+        int                 maxiter,
+        cpl_filter_mode     filter,
+        cpl_border_mode     border,
+        int                 smooth_x,
+        int                 smooth_y)
+{
+    hdrl_bpm_2d_parameter * p = (hdrl_bpm_2d_parameter *)
+               hdrl_parameter_new(&hdrl_bpm_2d_parameter_type);
+    p->kappa_low = kappa_low ;
+    p->kappa_high = kappa_high ;
+    p->maxiter = maxiter ;
+    p->filter = filter ;
+    p->border = border ;
+    p->smooth_x = smooth_x ;
+    p->smooth_y = smooth_y ;
+    p->steps_x = 0 ;
+    p->steps_y = 0 ;
+    p->filter_size_x = 0 ;
+    p->filter_size_y = 0 ;
+    p->order_x = 0 ;
+    p->order_y = 0 ;
+    p->method = HDRL_BPM_2D_FILTERSMOOTH ;
+
+    if (hdrl_bpm_2d_parameter_verify((hdrl_parameter*)p) != CPL_ERROR_NONE) {
+        cpl_free(p);
+        return NULL;
+    }
+    return (hdrl_parameter *)p;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Creates BPM_2D Parameters object for HDRL_BPM_2D_LEGENDRESMOOTH
+  @param    kappa_low       Low kappa factor for thresholding algorithm
+  @param    kappa_high      High kappa factor for thresholding algorithm
+  @param    maxiter         Maximum number of iterations
+  @param    steps_x         Number of sampling coordinates in x-dir
+  @param    steps_y         Number of sampling coordinates in y-dir
+  @param    filter_size_x   size of the median box in x-dir
+  @param    filter_size_y   size of the median box in y-dir
+  @param    order_x         order of polynomial in x-dir
+  @param    order_y         order of polynomial in y-dir
+  @return   The BPM_2D parameters object. It needs to be deallocated with
+            hdrl_parameter_delete().
+
+  The method creates a hdrl parameter for the method HDRL_BPM_2D_LEGENDRESMOOTH
+
+  @see      hdrl_parameter_delete()
+  @see      hdrl_bpm_2d_compute()
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_bpm_2d_parameter_create_legendresmooth(
+        double              kappa_low,
+        double              kappa_high,
+        int                 maxiter,
+        int                 steps_x,
+        int                 steps_y,
+        int                 filter_size_x,
+        int                 filter_size_y,
+        int                 order_x,
+        int                 order_y)
+{
+    hdrl_bpm_2d_parameter * p = (hdrl_bpm_2d_parameter *)
+               hdrl_parameter_new(&hdrl_bpm_2d_parameter_type);
+    p->kappa_low = kappa_low ;
+    p->kappa_high = kappa_high ;
+    p->maxiter = maxiter ;
+    p->filter = CPL_FILTER_MEDIAN ;
+    p->border = CPL_BORDER_FILTER ;
+    p->smooth_x = 0 ;
+    p->smooth_y = 0 ;
+    p->steps_x = steps_x ;
+    p->steps_y = steps_y ;
+    p->filter_size_x = filter_size_x ;
+    p->filter_size_y = filter_size_y ;
+    p->order_x = order_x ;
+    p->order_y = order_y ;
+    p->method = HDRL_BPM_2D_LEGENDRESMOOTH ;
+    if (hdrl_bpm_2d_parameter_verify((hdrl_parameter*)p) != CPL_ERROR_NONE) {
+        cpl_free(p);
+        return NULL;
+    }
+    return (hdrl_parameter *)p;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Verify basic correctness of the BPM_2D parameters
+  @param    param   BPM_2D parameters
+  @return   CPL_ERROR_NONE if everything is ok, an error code otherwise
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_bpm_2d_parameter_verify(
+        const hdrl_parameter    *   param)
+{
+    const hdrl_bpm_2d_parameter * param_loc = (hdrl_bpm_2d_parameter *)param ;
+
+    cpl_error_ensure(param != NULL, CPL_ERROR_NULL_INPUT,
+            return CPL_ERROR_NULL_INPUT, "NULL Input Parameters");
+    cpl_error_ensure(hdrl_bpm_2d_parameter_check(param),
+            CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+            "Expected BPM_2d parameter") ;
+
+    cpl_error_ensure(param_loc->method == HDRL_BPM_2D_LEGENDRESMOOTH || 
+            param_loc->method == HDRL_BPM_2D_FILTERSMOOTH, 
+            CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT, 
+            "Unsupported method");
+    
+    switch (param_loc->method) {
+    case HDRL_BPM_2D_FILTERSMOOTH:
+        cpl_error_ensure(param_loc->smooth_x >= 0, CPL_ERROR_ILLEGAL_INPUT,
+                        return CPL_ERROR_ILLEGAL_INPUT, "smooth-x must be >=0");
+        cpl_error_ensure(param_loc->smooth_y >= 0, CPL_ERROR_ILLEGAL_INPUT,
+                         return CPL_ERROR_ILLEGAL_INPUT, "smooth-y must be >=0");
+        /* Only odd-sized kernel are allowed */
+        cpl_error_ensure(((param_loc->smooth_x)&1) == 1, CPL_ERROR_ILLEGAL_INPUT,
+                         return CPL_ERROR_ILLEGAL_INPUT, "smooth-x must be odd");
+        cpl_error_ensure(((param_loc->smooth_y)&1) == 1, CPL_ERROR_ILLEGAL_INPUT,
+                         return CPL_ERROR_ILLEGAL_INPUT, "smooth-y must be odd");
+        if (param_loc->filter != CPL_FILTER_AVERAGE &&
+            param_loc->filter != CPL_FILTER_AVERAGE_FAST &&
+            param_loc->filter != CPL_FILTER_MEDIAN) {
+            cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_INPUT,
+                          "Function only supports filters: "
+                          "CPL_FILTER_AVERAGE, CPL_FILTER_AVERAGE_FAST "
+                          "and CPL_FILTER_MEDIAN");
+            return CPL_ERROR_ILLEGAL_INPUT;
+        }
+        break ;
+    case HDRL_BPM_2D_LEGENDRESMOOTH:
+        cpl_error_ensure(param_loc->order_x >= 0, CPL_ERROR_ILLEGAL_INPUT,
+                        return CPL_ERROR_ILLEGAL_INPUT, "order-x must be >= 0");
+        cpl_error_ensure(param_loc->order_y >= 0, CPL_ERROR_ILLEGAL_INPUT,
+                         return CPL_ERROR_ILLEGAL_INPUT, "order-y must be >= 0");
+        cpl_error_ensure(param_loc->steps_x > param_loc->order_x, CPL_ERROR_ILLEGAL_INPUT,
+                         return CPL_ERROR_ILLEGAL_INPUT, "stepx_x must be > order-x");
+        cpl_error_ensure(param_loc->steps_y > param_loc->order_y, CPL_ERROR_ILLEGAL_INPUT,
+                         return CPL_ERROR_ILLEGAL_INPUT, "stepx_y must be > order-y");
+        cpl_error_ensure(param_loc->filter_size_x > 0, CPL_ERROR_ILLEGAL_INPUT,
+                         return CPL_ERROR_ILLEGAL_INPUT, "filter-size-x must be > 0");
+        cpl_error_ensure(param_loc->filter_size_y > 0, CPL_ERROR_ILLEGAL_INPUT,
+                         return CPL_ERROR_ILLEGAL_INPUT, "filter-size-y must be > 0");
+        break ;
+    }
+
+    cpl_error_ensure(param_loc->kappa_low >= 0, CPL_ERROR_ILLEGAL_INPUT,
+            return CPL_ERROR_ILLEGAL_INPUT, "kappa-low must be >=0");
+    cpl_error_ensure(param_loc->kappa_high >= 0, CPL_ERROR_ILLEGAL_INPUT,
+            return CPL_ERROR_ILLEGAL_INPUT, "kappa-high must be >=0");
+    cpl_error_ensure(param_loc->maxiter >= 0, CPL_ERROR_ILLEGAL_INPUT,
+            return CPL_ERROR_ILLEGAL_INPUT, "maxiter must be >=0");
+    return CPL_ERROR_NONE ;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Check that the parameter is a BPM_2D parameter
+  @param    self The parameter to check
+  @return   True or False
+ */
+/*----------------------------------------------------------------------------*/
+cpl_boolean hdrl_bpm_2d_parameter_check(const hdrl_parameter * self)
+{
+    return hdrl_parameter_check_type(self, &hdrl_bpm_2d_parameter_type);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the filter in the BPM_2D parameter
+  @param    p   The BPM_2D parameter
+  @return   The filter
+ */
+/*----------------------------------------------------------------------------*/
+cpl_filter_mode hdrl_bpm_2d_parameter_get_filter(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, CPL_FILTER_EROSION);
+    return ((hdrl_bpm_2d_parameter *)p)->filter;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the border in the BPM_2D parameter
+  @param    p   The BPM_2D parameter
+  @return   The border
+ */
+/*----------------------------------------------------------------------------*/
+cpl_border_mode hdrl_bpm_2d_parameter_get_border(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, CPL_BORDER_FILTER);
+    return ((hdrl_bpm_2d_parameter *)p)->border;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the kappa_low in the BPM_2D parameter
+  @param    p   The BPM_2D parameter
+  @return   The kappa_low
+ */
+/*----------------------------------------------------------------------------*/
+double hdrl_bpm_2d_parameter_get_kappa_low(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0);
+    return ((hdrl_bpm_2d_parameter *)p)->kappa_low;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the kappa_high in the BPM_2D parameter
+  @param    p   The BPM_2D parameter
+  @return   The kappa_high
+ */
+/*----------------------------------------------------------------------------*/
+double hdrl_bpm_2d_parameter_get_kappa_high(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0);
+    return ((hdrl_bpm_2d_parameter *)p)->kappa_high;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the maxiter in the BPM_2D parameter
+  @param    p   The BPM_2D parameter
+  @return   The maxiter
+ */
+/*----------------------------------------------------------------------------*/
+int hdrl_bpm_2d_parameter_get_maxiter(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    return ((hdrl_bpm_2d_parameter *)p)->maxiter;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the steps_x in the BPM_2D parameter
+  @param    p   The BPM_2D parameter
+  @return   The steps_x
+ */
+/*----------------------------------------------------------------------------*/
+int hdrl_bpm_2d_parameter_get_steps_x(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    return ((hdrl_bpm_2d_parameter *)p)->steps_x;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the steps_y in the BPM_2D parameter
+  @param    p   The BPM_2D parameter
+  @return   The steps_y
+ */
+/*----------------------------------------------------------------------------*/
+int hdrl_bpm_2d_parameter_get_steps_y(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    return ((hdrl_bpm_2d_parameter *)p)->steps_y;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the filter_size_x in the BPM_2D parameter
+  @param    p   The BPM_2D parameter
+  @return   The filter_size_x
+ */
+/*----------------------------------------------------------------------------*/
+int hdrl_bpm_2d_parameter_get_filter_size_x(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    return ((hdrl_bpm_2d_parameter *)p)->filter_size_x;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the filter_size_y in the BPM_2D parameter
+  @param    p   The BPM_2D parameter
+  @return   The filter_size_y
+ */
+/*----------------------------------------------------------------------------*/
+int hdrl_bpm_2d_parameter_get_filter_size_y(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    return ((hdrl_bpm_2d_parameter *)p)->filter_size_y;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the order_x in the BPM_2D parameter
+  @param    p   The BPM_2D parameter
+  @return   The order_x
+ */
+/*----------------------------------------------------------------------------*/
+int hdrl_bpm_2d_parameter_get_order_x(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    return ((hdrl_bpm_2d_parameter *)p)->order_x;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the order_y in the BPM_2D parameter
+  @param    p   The BPM_2D parameter
+  @return   The order_y
+ */
+/*----------------------------------------------------------------------------*/
+int hdrl_bpm_2d_parameter_get_order_y(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    return ((hdrl_bpm_2d_parameter *)p)->order_y;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the smooth_y in the BPM_2D parameter
+  @param    p   The BPM_2D parameter
+  @return   The smooth_y
+ */
+/*----------------------------------------------------------------------------*/
+int hdrl_bpm_2d_parameter_get_smooth_y(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    return ((hdrl_bpm_2d_parameter *)p)->smooth_y;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the smooth_x in the BPM_2D parameter
+  @param    p   The BPM_2D parameter
+  @return   The smooth_x
+ */
+/*----------------------------------------------------------------------------*/
+int hdrl_bpm_2d_parameter_get_smooth_x(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    return ((hdrl_bpm_2d_parameter *)p)->smooth_x;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the method in the BPM_2D parameter
+  @param    p   The BPM_2D parameter
+  @return   The method
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_bpm_2d_method hdrl_bpm_2d_parameter_get_method(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    return ((hdrl_bpm_2d_parameter *)p)->method;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief Create parameter list for the BPM_2D legendresmooth computation
+  @param base_context    base context of parameter (e.g. recipe name)
+  @param prefix          prefix of parameter, may be an empty string
+  @param deflt           defaults
+  Creates a parameter list with the BPM_2D parameters:
+    - base_context.prefix.method
+    - base_context.prefix.legendre.kappa_low
+    - base_context.prefix.legendre.kappa_high
+    - base_context.prefix.legendre.maxiter
+    - base_context.prefix.legendre.steps_x
+    - base_context.prefix.legendre.steps_y
+    - base_context.prefix.legendre.filter_size_x
+    - base_context.prefix.legendre.filter_size_y
+    - base_context.prefix.legendre.order_x
+    - base_context.prefix.legendre.order_y
+  The CLI aliases omit the base_context.
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_parameterlist * hdrl_bpm_2d_legendresmooth_parameter_create_parlist(
+        const char      *   base_context,
+        const char      *   prefix,
+        const hdrl_parameter * deflt)
+{
+    cpl_ensure(prefix && base_context, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(deflt, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_parameterlist   *   parlist = cpl_parameterlist_new();
+    char                *   context =
+        hdrl_join_string(".", 2, base_context, prefix);
+
+    double kappa_low_def = hdrl_bpm_2d_parameter_get_kappa_low(deflt);
+    double kappa_high_def = hdrl_bpm_2d_parameter_get_kappa_high(deflt);
+    int maxiter_def = hdrl_bpm_2d_parameter_get_maxiter(deflt);
+
+    /* --prefix.kappa_low */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "kappa-low", base_context,
+            "Low RMS scaling factor for image thresholding", CPL_TYPE_DOUBLE,
+            kappa_low_def) ;
+
+    /* --prefix.kappa_high */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "kappa-high", base_context,
+            "High RMS scaling factor for image thresholding", CPL_TYPE_DOUBLE,
+            kappa_high_def) ;
+
+    /* --prefix.maxiter */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "maxiter", base_context,
+            "Maximum number of algorithm iterations", CPL_TYPE_INT, maxiter_def);
+
+    /* --prefix.steps_x */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "steps-x",
+            base_context, "Number of image sampling points in x-dir for fitting",
+            CPL_TYPE_INT, hdrl_bpm_2d_parameter_get_steps_x(deflt));
+
+    /* --prefix.steps_y */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "steps-y",
+            base_context, "Number of image sampling points in y-dir for fitting",
+            CPL_TYPE_INT, hdrl_bpm_2d_parameter_get_steps_y(deflt)) ;
+
+    /* --prefix.filter_size_x */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "filter-size-x",
+            base_context, "X size of the median box around sampling points", CPL_TYPE_INT,
+            hdrl_bpm_2d_parameter_get_filter_size_x(deflt)) ;
+
+    /* --prefix.filter_size_y */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "filter-size-y",
+            base_context, "Y size of the median box around sampling points", CPL_TYPE_INT,
+            hdrl_bpm_2d_parameter_get_filter_size_y(deflt));
+
+    /* --prefix.order_x */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "order-x",
+            base_context, "Order of x polynomial for the fit", CPL_TYPE_INT,
+            hdrl_bpm_2d_parameter_get_order_x(deflt));
+
+    /* --prefix.order_y */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "order-y",
+            base_context, "Order of y polynomial for the fit", CPL_TYPE_INT,
+            hdrl_bpm_2d_parameter_get_order_y(deflt)) ;
+
+
+    cpl_free(context);
+    if (cpl_error_get_code()) {
+        cpl_parameterlist_delete(parlist);
+        return NULL;
+    }
+    return parlist;
+}
+
+
+static const char * filter_to_string(cpl_filter_mode filter)
+{
+    switch (filter) {
+        case CPL_FILTER_EROSION:
+            return "EROSION";
+        case CPL_FILTER_DILATION:
+            return "DILATION";
+        case CPL_FILTER_OPENING:
+            return "OPENING";
+        case CPL_FILTER_CLOSING:
+            return "CLOSING";
+        case CPL_FILTER_LINEAR:
+            return "LINEAR";
+        case CPL_FILTER_LINEAR_SCALE:
+            return "LINEAR_SCALE";
+        case CPL_FILTER_AVERAGE:
+            return "AVERAGE";
+        case CPL_FILTER_AVERAGE_FAST:
+            return "AVERAGE_FAST";
+        case CPL_FILTER_MEDIAN:
+            return "MEDIAN";
+        case CPL_FILTER_STDEV:
+            return "STDEV";
+        case CPL_FILTER_STDEV_FAST:
+            return "STDEV_FAST";
+        case CPL_FILTER_MORPHO:
+            return "MORPHO";
+        case CPL_FILTER_MORPHO_SCALE:
+            return "MORPHO_SCALE";
+    }
+    abort();
+}
+
+static const char * border_to_string(cpl_border_mode border)
+{
+    switch (border) {
+        case CPL_BORDER_FILTER:
+            return "FILTER";
+        case CPL_BORDER_ZERO:
+            return "ZERO";
+        case CPL_BORDER_CROP:
+            return "CROP";
+        case CPL_BORDER_NOP:
+            return "NOP";
+        case CPL_BORDER_COPY:
+            return "COPY";
+    }
+    abort();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief Create parameter list for the BPM_2D filtersmooth computation
+  @param base_context    base context of parameter (e.g. recipe name)
+  @param prefix          prefix of parameter, may be an empty string
+  @param deflt           defaults
+  Creates a parameter list with the BPM_2D parameters:
+    - base_context.prefix.method
+    - base_context.prefix.filter.kappa-low
+    - base_context.prefix.filter.kappa-high
+    - base_context.prefix.filter.maxiter
+    - base_context.prefix.filter.filter
+    - base_context.prefix.filter.border
+    - base_context.prefix.filter.smooth-x
+    - base_context.prefix.filter.smooth-y
+  The CLI aliases omit the base_context.
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_parameterlist * hdrl_bpm_2d_filtersmooth_parameter_create_parlist(
+        const char      *   base_context,
+        const char      *   prefix,
+        const hdrl_parameter * deflt)
+{
+    cpl_ensure(prefix && base_context, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(deflt, CPL_ERROR_NULL_INPUT, NULL);
+    char                *   name ;
+    cpl_parameterlist   *   parlist = cpl_parameterlist_new();
+    cpl_parameter       *   par ;
+    char                *   context =
+        hdrl_join_string(".", 2, base_context, prefix);
+
+    double kappa_low_def = hdrl_bpm_2d_parameter_get_kappa_low(deflt);
+    double kappa_high_def = hdrl_bpm_2d_parameter_get_kappa_high(deflt);
+    int maxiter_def = hdrl_bpm_2d_parameter_get_maxiter(deflt);
+
+    /* --prefix.kappa_low */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "kappa-low", base_context,
+            "Low RMS scaling factor for image thresholding", CPL_TYPE_DOUBLE, kappa_low_def) ;
+
+    /* --prefix.kappa_high */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "kappa-high", base_context,
+            "High RMS scaling factor for image thresholding", CPL_TYPE_DOUBLE, kappa_high_def) ;
+
+    /* --prefix.maxiter */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "maxiter", base_context,
+            "Maximum number of algorithm iterations", CPL_TYPE_INT, maxiter_def);
+
+    /* --prefix.filter */
+    cpl_filter_mode filter = hdrl_bpm_2d_parameter_get_filter(deflt);
+    const char * filter_def = filter_to_string(filter);
+    name = hdrl_join_string(".", 2, context, "filter");
+    par = cpl_parameter_new_enum(name, CPL_TYPE_STRING, "Filter mode for image smooting",
+            context, filter_def, 3, "AVERAGE", "AVERAGE_FAST", "MEDIAN");
+    cpl_free(name);
+    name = hdrl_join_string(".", 2, prefix, "filter");
+    cpl_parameter_set_alias(par, CPL_PARAMETER_MODE_CLI, name);
+    cpl_parameter_disable(par, CPL_PARAMETER_MODE_ENV);
+    cpl_free(name);
+    cpl_parameterlist_append(parlist, par);
+
+    /* --prefix.border */
+    cpl_border_mode border = hdrl_bpm_2d_parameter_get_border(deflt);
+    const char * border_def = border_to_string(border);
+    name = hdrl_join_string(".", 2, context, "border");
+    par = cpl_parameter_new_enum(name, CPL_TYPE_STRING,
+            "Border mode to use for the image smooting filter "
+            "(only for MEDIAN filter)",
+            context, border_def, 4, "FILTER", "CROP", "NOP", "COPY");
+    cpl_free(name);
+    name = hdrl_join_string(".", 2, prefix, "border");
+    cpl_parameter_set_alias(par, CPL_PARAMETER_MODE_CLI, name);
+    cpl_parameter_disable(par, CPL_PARAMETER_MODE_ENV);
+    cpl_free(name);
+    cpl_parameterlist_append(parlist, par);
+
+    /* --prefix.smooth_x */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "smooth-x",
+            base_context, "Kernel y size of the smoothing filter", CPL_TYPE_INT,
+            hdrl_bpm_2d_parameter_get_smooth_x(deflt));
+
+    /* --prefix.smooth_y */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "smooth-y",
+            base_context, "Kernel y size of the image smoothing filter", CPL_TYPE_INT,
+            hdrl_bpm_2d_parameter_get_smooth_y(deflt));
+
+    cpl_free(context);
+    if (cpl_error_get_code()) {
+        cpl_parameterlist_delete(parlist);
+        return NULL;
+    }
+    return parlist;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Create parameter list for the BPM_2D computation
+  @param base_context    base context of parameter (e.g. recipe name)
+  @param prefix          prefix of parameter, may be an empty string
+  @param method_def         default used method
+  @param filtersmooth_def   defaults for filtersmooth method
+  @param legendresmooth_def defaults for legendresmooth method
+  Creates a parameter list with the BPM_2D parameters:
+    - base_context.prefix.method
+    - base_context.prefix.legendre.kappa-low
+    - base_context.prefix.legendre.kappa-high
+    - base_context.prefix.legendre.maxiter
+    - base_context.prefix.legendre.steps-x
+    - base_context.prefix.legendre.steps-y
+    - base_context.prefix.legendre.filter-size-x
+    - base_context.prefix.legendre.filter-size-y
+    - base_context.prefix.legendre.order-x
+    - base_context.prefix.legendre.order-y
+    - base_context.prefix.filter.kappa-low
+    - base_context.prefix.filter.kappa-high
+    - base_context.prefix.filter.maxiter
+    - base_context.prefix.filter.filter
+    - base_context.prefix.filter.border
+    - base_context.prefix.filter.smooth-x
+    - base_context.prefix.filter.smooth-y
+  The CLI aliases omit the base_context.
+ */
+/*----------------------------------------------------------------------------*/
+cpl_parameterlist * hdrl_bpm_2d_parameter_create_parlist(
+        const char      *   base_context,
+        const char      *   prefix,
+        const char      *   method_def,
+        const hdrl_parameter * filtersmooth_def,
+        const hdrl_parameter * legendresmooth_def)
+{
+    cpl_ensure(prefix && base_context, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(filtersmooth_def || legendresmooth_def,
+               CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(method_def, CPL_ERROR_NULL_INPUT, NULL);
+    char                *   name ;
+    cpl_parameterlist   *   parlist = cpl_parameterlist_new();
+    cpl_parameter       *   par ;
+    char                *   context =
+        hdrl_join_string(".", 2, base_context, prefix);
+
+    /* --prefix.method */
+    name = hdrl_join_string(".", 2, context, "method");
+    par = cpl_parameter_new_enum(name, CPL_TYPE_STRING, "Method used", context,
+            method_def, 2, "FILTER", "LEGENDRE");
+    cpl_free(name);
+    name = hdrl_join_string(".", 2, prefix, "method");
+    cpl_parameter_set_alias(par, CPL_PARAMETER_MODE_CLI, name);
+    cpl_free(name);
+    cpl_parameter_disable(par, CPL_PARAMETER_MODE_ENV);
+    cpl_parameterlist_append(parlist, par);
+
+    /* --prefix.legendre */
+    name = hdrl_join_string(".", 2, prefix, "legendre");
+    cpl_parameterlist * pleg = hdrl_bpm_2d_legendresmooth_parameter_create_parlist(
+            base_context, name, legendresmooth_def);
+    cpl_free(name);
+    for (cpl_parameter * p = cpl_parameterlist_get_first(pleg) ;
+            p != NULL; p = cpl_parameterlist_get_next(pleg))
+        cpl_parameterlist_append(parlist, cpl_parameter_duplicate(p));
+    cpl_parameterlist_delete(pleg);
+
+    /* --prefix.filter */
+    name = hdrl_join_string(".", 2, prefix, "filter");
+    cpl_parameterlist * pfil = hdrl_bpm_2d_filtersmooth_parameter_create_parlist(
+            base_context, name, filtersmooth_def);
+    cpl_free(name);
+    for (cpl_parameter * p = cpl_parameterlist_get_first(pfil) ;
+            p != NULL; p = cpl_parameterlist_get_next(pfil))
+        cpl_parameterlist_append(parlist, cpl_parameter_duplicate(p));
+    cpl_parameterlist_delete(pfil);
+
+    cpl_free(context);
+    if (cpl_error_get_code()) {
+        cpl_parameterlist_delete(parlist);
+        return NULL;
+    }
+    return parlist;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Parse parameter list to create input parameters for the BPM_2D
+  @param parlist        parameter list to parse
+  @param prefix         prefix of parameter name
+  @return   Input parameters for the BPM_2D computation
+
+  Reads a parameter list in order to create BPM_2D parameters.
+
+  Expects a parameter list containing:
+  - prefix.method
+  - prefix.legendre.kappa-low
+  - prefix.legendre.kappa-high
+  - prefix.legendre.maxiter
+  - prefix.legendre.steps-x
+  - prefix.legendre.steps-y
+  - prefix.legendre.filter-size-x
+  - prefix.legendre.filter-size-y
+  - prefix.legendre.order-x
+  - prefix.legendre.order-y
+  - prefix.filter.kappa-low
+  - prefix.filter.kappa-high
+  - prefix.filter.maxiter
+  - prefix.filter.filter
+  - prefix.filter.border
+  - prefix.filter.smooth-x
+  - prefix.filter.smooth-y
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_bpm_2d_parameter_parse_parlist(
+        const cpl_parameterlist *   parlist,
+        const char              *   prefix)
+{
+    cpl_ensure(prefix && parlist, CPL_ERROR_NULL_INPUT, NULL);
+    char                *   name ;
+    const cpl_parameter *   par = NULL;
+    const char          *   tmp_str = NULL;
+    cpl_filter_mode         filter = CPL_FILTER_EROSION ;
+    cpl_border_mode         border = CPL_BORDER_FILTER ;
+    double                  kappa_low = -1.0 ;
+    double                  kappa_high = -1.0 ;
+    int                     maxiter = -1;
+    int                     steps_x = -1 ;
+    int                     steps_y = -1  ;
+    int                     filter_size_x = -1 ;
+    int                     filter_size_y = -1 ;
+    int                     order_x = -1 ;
+    int                     order_y = -1 ;
+    cpl_size                smooth_x = -1 ;
+    cpl_size                smooth_y = -1 ;
+    hdrl_bpm_2d_method      method ;
+  
+    /* --method */
+    name = hdrl_join_string(".", 2, prefix, "method");
+    par = cpl_parameterlist_find_const(parlist, name) ;
+    tmp_str = cpl_parameter_get_string(par);
+    if (tmp_str == NULL) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                "Parameter %s not found", name);
+        cpl_free(name);
+        return NULL;
+    }
+    cpl_free(name) ;
+    if(!strcmp(tmp_str, "FILTER")) {
+        method = HDRL_BPM_2D_FILTERSMOOTH ;
+    } else if(!strcmp(tmp_str, "LEGENDRE")) {
+        method = HDRL_BPM_2D_LEGENDRESMOOTH ;
+    } else {
+        cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_INPUT,
+                "Invalid method: %s", tmp_str);
+        return NULL;
+    }
+
+    char * kappa_prefix = hdrl_join_string(".", 2, prefix,
+                       method == HDRL_BPM_2D_FILTERSMOOTH ?
+                       "filter" : "legendre" );
+
+    /* --kappa_low */
+    name = hdrl_join_string(".", 2, kappa_prefix, "kappa-low");
+    par=cpl_parameterlist_find_const(parlist, name);
+    kappa_low = cpl_parameter_get_double(par);
+    cpl_free(name) ;
+
+    /* --kappa_high */
+    name = hdrl_join_string(".", 2, kappa_prefix, "kappa-high");
+    par=cpl_parameterlist_find_const(parlist, name);
+    kappa_high = cpl_parameter_get_double(par);
+    cpl_free(name) ;
+
+    /* --maxiter */
+    name = hdrl_join_string(".", 2, kappa_prefix, "maxiter");
+    par=cpl_parameterlist_find_const(parlist, name);
+    maxiter = cpl_parameter_get_int(par);
+    cpl_free(name) ;
+
+    cpl_free(kappa_prefix);
+
+    /* --steps_x */
+    name = hdrl_join_string(".", 2, prefix, "legendre.steps-x");
+    par=cpl_parameterlist_find_const(parlist, name);
+    steps_x = cpl_parameter_get_int(par);
+    cpl_free(name) ;
+
+    /* --steps_y */
+    name = hdrl_join_string(".", 2, prefix, "legendre.steps-y");
+    par=cpl_parameterlist_find_const(parlist, name);
+    steps_y = cpl_parameter_get_int(par);
+    cpl_free(name) ;
+
+    /* --filter_size_x */
+    name = hdrl_join_string(".", 2, prefix, "legendre.filter-size-x");
+    par=cpl_parameterlist_find_const(parlist, name);
+    filter_size_x = cpl_parameter_get_int(par);
+    cpl_free(name) ;
+
+    /* --filter_size_y */
+    name = hdrl_join_string(".", 2, prefix, "legendre.filter-size-y");
+    par=cpl_parameterlist_find_const(parlist, name);
+    filter_size_y = cpl_parameter_get_int(par);
+    cpl_free(name) ;
+
+    /* --order_x */
+    name = hdrl_join_string(".", 2, prefix, "legendre.order-x");
+    par=cpl_parameterlist_find_const(parlist, name);
+    order_x = cpl_parameter_get_int(par);
+    cpl_free(name) ;
+
+    /* --order_y */
+    name = hdrl_join_string(".", 2, prefix, "legendre.order-y");
+    par=cpl_parameterlist_find_const(parlist, name);
+    order_y = cpl_parameter_get_int(par);
+    cpl_free(name) ;
+
+    /* --filter */
+    name = hdrl_join_string(".", 2, prefix, "filter.filter");
+    par = cpl_parameterlist_find_const(parlist, name) ;
+    tmp_str = cpl_parameter_get_string(par);
+    if (tmp_str == NULL) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                "Parameter %s not found", name);
+        cpl_free(name);
+        return NULL;
+    }
+    if(!strcmp(tmp_str, "erosion")) {
+        filter = CPL_FILTER_EROSION ;
+    } else if(!strcmp(tmp_str, "DILATION")) {
+        filter = CPL_FILTER_DILATION ;
+    } else if(!strcmp(tmp_str, "OPENING")) {
+        filter = CPL_FILTER_OPENING ;
+    } else if(!strcmp(tmp_str, "CLOSING")) {
+        filter = CPL_FILTER_CLOSING ;
+    } else if(!strcmp(tmp_str, "LINEAR")) {
+        filter = CPL_FILTER_LINEAR ;
+    } else if(!strcmp(tmp_str, "LINEAR_SCALE")) {
+        filter = CPL_FILTER_LINEAR_SCALE ;
+    } else if(!strcmp(tmp_str, "AVERAGE")) {
+        filter = CPL_FILTER_AVERAGE ;
+    } else if(!strcmp(tmp_str, "AVERAGE_FAST")) {
+        filter = CPL_FILTER_AVERAGE_FAST ;
+    } else if(!strcmp(tmp_str, "MEDIAN")) {
+        filter = CPL_FILTER_MEDIAN ;
+    } else if(!strcmp(tmp_str, "STDEV")) {
+        filter = CPL_FILTER_STDEV ;
+    } else if(!strcmp(tmp_str, "STDEV_FAST")) {
+        filter = CPL_FILTER_STDEV_FAST ;
+    } else if(!strcmp(tmp_str, "MORPHO")) {
+        filter = CPL_FILTER_MORPHO ;
+    } else if(!strcmp(tmp_str, "MORPHO_SCALE")) {
+        filter = CPL_FILTER_MORPHO_SCALE ;
+    }
+    cpl_free(name) ;
+    
+    /* --border */
+    name = hdrl_join_string(".", 2, prefix, "filter.border");
+    par = cpl_parameterlist_find_const(parlist, name) ;
+    tmp_str = cpl_parameter_get_string(par);
+    if (tmp_str == NULL) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                "Parameter %s not found", name);
+        cpl_free(name);
+        return NULL;
+    }
+    if(!strcmp(tmp_str, "filter")) {
+        border = CPL_BORDER_FILTER ;
+    } else if(!strcmp(tmp_str, "ZERO")) {
+        border = CPL_BORDER_ZERO ;
+    } else if(!strcmp(tmp_str, "CROP")) {
+        border = CPL_BORDER_CROP ;
+    } else if(!strcmp(tmp_str, "NOP")) {
+        border = CPL_BORDER_NOP ;
+    } else if(!strcmp(tmp_str, "COPY")) {
+        border = CPL_BORDER_COPY ;
+    } 
+    cpl_free(name) ;
+
+    /* --smooth_x */
+    name = hdrl_join_string(".", 2, prefix, "filter.smooth-x");
+    par=cpl_parameterlist_find_const(parlist, name);
+    smooth_x = cpl_parameter_get_int(par);
+    cpl_free(name) ;
+
+    /* --smooth_y */
+    name = hdrl_join_string(".", 2, prefix, "filter.smooth-y");
+    par=cpl_parameterlist_find_const(parlist, name);
+    smooth_y = cpl_parameter_get_int(par);
+    cpl_free(name) ;
+
+    /* Return */
+    if (cpl_error_get_code()) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                "Error while parsing parameterlist with prefix %s", prefix);
+        return NULL;
+    } else {
+        if (method == HDRL_BPM_2D_FILTERSMOOTH) {
+            return hdrl_bpm_2d_parameter_create_filtersmooth(kappa_low, 
+                    kappa_high, maxiter, filter, border, smooth_x, smooth_y) ;
+        } else if (method == HDRL_BPM_2D_LEGENDRESMOOTH) {
+            return hdrl_bpm_2d_parameter_create_legendresmooth(kappa_low, 
+                    kappa_high, maxiter, steps_x, steps_y, filter_size_x, 
+                    filter_size_y, order_x, order_y) ;
+        } else {
+            return NULL ;
+        }
+    }
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Detect bad pixels on a single image with an iterative process
+  @param img_in     input hdrl image
+  @param params     BPM_2D computation parameters - see below
+  @return Bad pixel mask with the newly found bad pixels
+
+
+ The algorithm first smoothes the image by applying the methods
+ described below. Then it subtracts the smoothed image and derives bad
+ pixels by thresholding the residual image, i.e. all pixels exceeding
+ the threshold are considered as bad. To compute the upper and lower
+ threshold, it measures a robust rms (a properly scaled Median Absolute
+ Deviation), which is then scaled by the parameter \e kappa_low and \e
+ kappa_high. Furthermore, the algorithm is applied iteratively
+ controlled by \e maxiter. During each iteration the newly found bad
+ pixels are ignored. Please note, that the thresholding values are
+ applied as median(residual-image) \f$\pm\f$ thresholds. This makes the
+ algorithm more robust in the case that the methods listed below are
+ not able to completely remove the background level, e.g due to an
+ exceeding number of bad pixels in the first iteration.
+
+Two methods are currently available to derive a smoothed version of
+the image:
+
+\li \c Applying a filter like e.g. a median filter to the image. The
+  filtering can be done by all modes currently supported by cpl and is
+  controlled by the filter-type \e filter, the border-type \e border
+  and by the kernel size in x and y, i.e.  \e smooth_x and \e
+  smooth_y. The corresponding BPM_2D parameter is created by
+  hdrl_bpm_2d_parameter_create_filtersmooth()
+
+\li \c Fitting a Legendre polynomial to the image of order \e order_x,
+  in x and \e order_y in y direction.  This method allows you to
+  define \e steps_x \f$\times\f$ \e steps_y sampling points (the
+  latter are computed as the median within a box of \e filter_size_x
+  and \e filter_size_y) where the polynomial is fitted. This
+  substantially decreases the fitting time for the Legendre
+  polynomial. The corresponding BPM_2D parameter is created by
+  hdrl_bpm_2d_parameter_create_legendresmooth()
+
+ */
+/*----------------------------------------------------------------------------*/
+cpl_mask * hdrl_bpm_2d_compute(
+        const hdrl_image        *   img_in,
+        const hdrl_parameter    *   params)
+{
+    cpl_image   *   img;
+    cpl_mask    *   mask_iter, * img_mask;
+
+    /* Check Entries */
+    cpl_error_ensure(img_in && params, CPL_ERROR_NULL_INPUT,
+            return NULL, "NULL input");
+   if (hdrl_bpm_2d_parameter_verify(params) != CPL_ERROR_NONE) return NULL;
+
+    /* Local Usage Parameters */
+    const hdrl_bpm_2d_parameter * p_loc = (hdrl_bpm_2d_parameter *)params ;
+
+    img = cpl_image_duplicate(hdrl_image_get_image_const(img_in));
+    img_mask = cpl_mask_duplicate(cpl_image_get_bpm(img));
+
+    /* The first iteration contains the passed mask */
+    mask_iter = cpl_mask_duplicate(img_mask);
+
+
+    for (int var = 0; var < p_loc->maxiter; ++var) {
+        cpl_image   * img_res = NULL;
+        cpl_mask * mask_iter_startloop = cpl_mask_duplicate(mask_iter);
+        double median, mad, std_mad, std_mad_low, std_mad_high ;
+
+        /*Add original bad pixels to previous iteration*/
+        cpl_mask_or(mask_iter, img_mask);
+
+        /* Filter the image */
+        if (p_loc->method == HDRL_BPM_2D_FILTERSMOOTH){
+            img_res = hdrl_get_residuals_filtersmooth(p_loc->smooth_x, 
+                    p_loc->smooth_y, p_loc->filter, p_loc->border, img, 
+                    mask_iter);
+        } else if (p_loc->method == HDRL_BPM_2D_LEGENDRESMOOTH) {
+            img_res = hdrl_get_residuals_legendresmooth(img, p_loc->steps_x,
+                    p_loc->steps_y, p_loc->filter_size_x, p_loc->filter_size_y,
+                    p_loc->order_x, p_loc->order_y);
+        }
+
+         /*
+         For a Gaussian distribution the Median Absolute Deviation (MAD) is a
+         robust and consistent estimate of the Standard Deviation (STD) in the
+         sense that the STD is approximately K * MAD, where K is a constant
+         equal to approximately 1.4826 == CPL_MATH_STD_MAD
+         */
+
+        /* Calculating the mad and assuming that after subtraction image has a
+           mean of Zero */
+
+        median = cpl_image_get_mad(img_res, &mad);
+        //mad = cpl_image_get_stdev(img_res);
+        if(mad <= 0){
+            mad=nextafter(0,1.0);
+        }
+        std_mad = CPL_MATH_STD_MAD * mad;
+        std_mad_low = median -(std_mad * p_loc->kappa_low);
+        std_mad_high = median + (std_mad * p_loc->kappa_high);
+
+        /*restore the original mask as we only want to add the new bad pixels
+         * to the originally passed mask - done by the threshold function*/
+
+        cpl_image_reject_from_mask(img_res, img_mask);
+
+        /*Reset all pixels to good in the mask as we only want the new bad
+         * pixels  */
+        cpl_mask_xor(mask_iter, mask_iter);
+
+        cpl_mask_threshold_image(mask_iter, img_res, std_mad_low, std_mad_high,
+                CPL_BINARY_0);
+
+        /* Currently the cpl function assigns the "outside" value
+         * also to the bad pixels - thus if one only wants to have the new bad
+         * pixel, one has to do the bitwise or */
+        cpl_mask_xor(mask_iter, img_mask);
+        cpl_image_delete(img_res);
+
+        if (!hdrl_check_maskequality(mask_iter, mask_iter_startloop)) {
+            cpl_mask_delete(mask_iter_startloop);
+            cpl_msg_debug(cpl_func, "iter: %d", var);
+            break;
+        }
+        cpl_mask_delete(mask_iter_startloop);
+        cpl_msg_debug(cpl_func, "iter: %d", var);
+    }
+    cpl_mask_delete(img_mask);
+    cpl_image_delete(img);
+
+    return mask_iter ;
+}
+
+/**@}*/
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief calculates the residual of an image by fitting a Legendre polynomial
+  @param img             Input image where the residuals are calculated
+  @param steps_x         Number of sampling points in x for the polyfit
+  @param steps_y         Number of sampling points in y for the polyfit
+  @param filter_size_x   x-size of the median filter to calc the sampling points
+  @param filter_size_y   y-size of the median filter to calc the sampling points
+  @param order_x         x-degree of the fitted Legendre polynomial
+  @param order_y         y-degree of the fitted Legendre polynomial
+  @return                The residual image derived as (data - fit)
+
+  The function interpolates the image onto a grid steps_x, steps_y using the
+  median. The size of the median box can by controlled by filter_size_x,
+  filter_size_y. On this image a Legendre polynomial of degree order_x, order_y
+  is fitted and subtracted from the original image
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_image * hdrl_get_residuals_legendresmooth(
+        const cpl_image *   img, 
+        int                 steps_x,
+        int                 steps_y,
+        int                 filter_size_x, 
+        int                 filter_size_y,
+        int                 order_x, 
+        int                 order_y)
+{
+    cpl_image * img_res = NULL;
+    cpl_image * img_filtered = NULL;
+    cpl_size nx = cpl_image_get_size_x(img);
+    cpl_size ny = cpl_image_get_size_y(img);
+    cpl_size sx = CX_MAX(nx / steps_x, 1);
+    cpl_size sy = CX_MAX(ny / steps_y, 1);
+
+    /* fit to stepped grid */
+    cpl_matrix * x = hdrl_matrix_linspace(sx / 2, nx, sx);
+    cpl_matrix * y = hdrl_matrix_linspace(sy / 2, ny, sy);
+    cpl_image * imgtmp_mod =
+        hdrl_medianfilter_image_grid(img, x, y,
+                                     filter_size_x,
+                                     filter_size_y);
+    cpl_matrix * coeffs = hdrl_fit_legendre(imgtmp_mod,
+                                            order_x, order_y,
+                                            x, y, nx, ny);
+    /* TODO: naming conventions: hdrl_matrix_legendre_to_image() */
+    img_filtered = hdrl_legendre_to_image(coeffs, order_x, order_y, nx, ny);
+    img_res = cpl_image_subtract_create(img, img_filtered);
+    if (cpl_msg_get_level() == CPL_MSG_DEBUG)
+        cpl_matrix_dump(coeffs, stdout);
+    cpl_matrix_delete(coeffs);
+    cpl_matrix_delete(x);
+    cpl_matrix_delete(y);
+    cpl_image_delete(imgtmp_mod);
+    cpl_image_delete(img_filtered);
+    return img_res;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief calculates the residual of an image by smoothing the image
+  @param kernel_size_x x-size of the smoothing kernel
+  @param kernel_size_y y-size of the smoothing kernel
+  @param filter,       Filter type to be applied (all cpl filters)
+  @param border,       Border-mode to be applied (all cpl border)
+  @param img,          Input image where to apply the filtering
+  @param mask_iter,    Input mask do determine the bad pixels
+  @return              The residual image derived as (data - data_smoothed)
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_image * hdrl_get_residuals_filtersmooth(
+        cpl_size            kernel_size_x, 
+        cpl_size            kernel_size_y, 
+        cpl_filter_mode     filter,
+        cpl_border_mode     border, 
+        cpl_image       *   img,
+        cpl_mask        *   mask_iter)
+{
+    cpl_mask    *   kernel ;
+    cpl_image   *   img_res = NULL;
+    cpl_image   *   img_filtered = NULL;
+
+    cpl_size nx = cpl_image_get_size_x(img);
+    cpl_size ny = cpl_image_get_size_y(img);
+
+
+    /* Create the kernel */
+    kernel = cpl_mask_new(kernel_size_x, kernel_size_y) ;
+    cpl_mask_not(kernel); 
+    if (kernel == NULL) return NULL ;
+
+    /* Filter the image */
+    cpl_image_reject_from_mask(img, mask_iter);
+    if (border == CPL_BORDER_FILTER) {
+        img_filtered = hdrl_parallel_filter_image(img, NULL, kernel, filter);
+    }
+    else {
+        img_filtered = cpl_image_new(nx, ny, HDRL_TYPE_DATA);
+        cpl_image_filter_mask(img_filtered, img, kernel, filter, border);
+    }
+    cpl_mask_delete(kernel) ;
+    img_res = cpl_image_subtract_create(img, img_filtered);
+    cpl_image_delete(img_filtered);
+
+    return img_res;
+}
+
diff --git a/hdrl/hdrl_bpm_2d.h b/hdrl/hdrl_bpm_2d.h
new file mode 100644
index 0000000..27f124f
--- /dev/null
+++ b/hdrl/hdrl_bpm_2d.h
@@ -0,0 +1,101 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_BPM_2D_H
+#define HDRL_BPM_2D_H
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include <cpl.h>
+#include <stdint.h>
+#include "hdrl_image.h"
+#include "hdrl_imagelist.h"
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                                Defines
+ -----------------------------------------------------------------------------*/
+
+typedef enum {
+    HDRL_BPM_2D_LEGENDRESMOOTH,
+    HDRL_BPM_2D_FILTERSMOOTH
+} hdrl_bpm_2d_method ;
+
+/*-----------------------------------------------------------------------------
+                            Functions prototypes
+ -----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+                            BPM_2D Parameters
+  ----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_bpm_2d_parameter_create_legendresmooth(double, double, 
+        int, int, int, int, int, int, int) ;
+hdrl_parameter * hdrl_bpm_2d_parameter_create_filtersmooth(double, double, 
+        int, cpl_filter_mode, cpl_border_mode, int, int) ;
+cpl_error_code hdrl_bpm_2d_parameter_verify(const hdrl_parameter *) ;
+cpl_boolean hdrl_bpm_2d_parameter_check(const hdrl_parameter *) ;
+
+/* Accessors */
+cpl_filter_mode hdrl_bpm_2d_parameter_get_filter(const hdrl_parameter *) ;
+cpl_border_mode hdrl_bpm_2d_parameter_get_border(const hdrl_parameter *) ;
+double hdrl_bpm_2d_parameter_get_kappa_low(const hdrl_parameter *) ;
+double hdrl_bpm_2d_parameter_get_kappa_high(const hdrl_parameter *) ;
+int hdrl_bpm_2d_parameter_get_maxiter(const hdrl_parameter *) ;
+int hdrl_bpm_2d_parameter_get_steps_x(const hdrl_parameter *) ;
+int hdrl_bpm_2d_parameter_get_steps_y(const hdrl_parameter *) ;
+int hdrl_bpm_2d_parameter_get_filter_size_x(const hdrl_parameter *) ;
+int hdrl_bpm_2d_parameter_get_filter_size_y(const hdrl_parameter *) ;
+int hdrl_bpm_2d_parameter_get_order_x(const hdrl_parameter *) ;
+int hdrl_bpm_2d_parameter_get_order_y(const hdrl_parameter *) ;
+int hdrl_bpm_2d_parameter_get_smooth_x(const hdrl_parameter *) ;
+int hdrl_bpm_2d_parameter_get_smooth_y(const hdrl_parameter *) ;
+hdrl_bpm_2d_method hdrl_bpm_2d_parameter_get_method(const hdrl_parameter *) ;
+
+/* Parameter Lists */
+cpl_parameterlist * hdrl_bpm_2d_parameter_create_parlist(
+        const char      *   base_context,
+        const char      *   prefix,
+        const char      *   method_def,
+        const hdrl_parameter * filtersmooth_def,
+        const hdrl_parameter * legendresmooth_def);
+hdrl_parameter * hdrl_bpm_2d_parameter_parse_parlist(const cpl_parameterlist *, 
+        const char *) ; 
+
+/*----------------------------------------------------------------------------
+                            BPM_2D Computation
+  ----------------------------------------------------------------------------*/
+
+cpl_mask * hdrl_bpm_2d_compute(
+        const hdrl_image        *   img_in,
+        const hdrl_parameter    *   params) ;
+
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+ -----------------------------------------------------------------------------*/
+
+#ifdef HDRL_USE_PRIVATE
+
+#endif
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_bpm_3d.c b/hdrl/hdrl_bpm_3d.c
new file mode 100644
index 0000000..1cfb62d
--- /dev/null
+++ b/hdrl/hdrl_bpm_3d.c
@@ -0,0 +1,511 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013,2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+-----------------------------------------------------------------------------*/
+
+#include "hdrl_types.h"
+#include "hdrl_image.h"
+#include "hdrl_imagelist.h"
+#include "hdrl_utils.h"
+
+#include "hdrl_bpm_3d.h"
+#include "hdrl_prototyping.h"
+
+#include <cpl.h>
+#include <string.h>
+#include <math.h>
+
+/*-----------------------------------------------------------------------------
+                                   Static
+ -----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_bpm_3d     Bad Pixel Mask 3D Computation
+  @ingroup hdrl_bpm
+
+  @brief
+   Algorithms to detect bad pixels on a stack of identical images like e.g.
+   bias images
+
+ The routines in this module can be used to detect bad pixels on a stack of
+ identical images like bias or dark images. The algorithm first collapses
+ the stack of images by using the median in order to generate a master-image.
+ Then it subtracts the master image from each individual image and derives the
+ bad pixels on the residual-images by thresholding, i.e. all pixels exceeding
+ the threshold are considered as bad. Please note, that the algorithm assumes
+ that the mean level of the different images is the same, if this is not the
+ case, the master-image as described above will be biased.
+
+ The calculation is performed by calling the top-level function
+ hdrl_bpm_3d_compute() and the parameters passed to this function can be created
+ by calling hdrl_bpm_3d_parameter_create().
+
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+/** @cond PRIVATE */
+
+
+/*-----------------------------------------------------------------------------
+                        BPM Parameters Definition
+ -----------------------------------------------------------------------------*/
+typedef struct {
+    HDRL_PARAMETER_HEAD;
+    double              kappa_low ;
+    double              kappa_high ;
+    hdrl_bpm_3d_method  method ;
+} hdrl_bpm_3d_parameter;
+
+/* Parameter type */
+static hdrl_parameter_typeobj hdrl_bpm_3d_parameter_type = {
+    HDRL_PARAMETER_BPM_3D,                  /* type */
+    (hdrl_alloc *)&cpl_malloc,              /* fp_alloc */
+    (hdrl_free *)&cpl_free,                 /* fp_free */
+    NULL,                                   /* fp_destroy */
+    sizeof(hdrl_bpm_3d_parameter),          /* obj_size */
+};
+/** @endcond */
+
+/* ---------------------------------------------------------------------------*/
+/**
+  @brief    Creates BPM Parameters object for the imagelist method
+  @param    kappa_low       Low kappa factor for thresholding algorithm
+  @param    kappa_high      High kappa factor for thresholding algorithm
+  @param    method          used method
+  @return   The BPM_3D parameters object.
+
+            It needs to be deallocated with hdrl_parameter_delete()
+
+  @see      hdrl_parameter_delete()
+  @see      hdrl_bpm_3d_compute()
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_bpm_3d_parameter_create(
+        double              kappa_low,
+        double              kappa_high,
+        hdrl_bpm_3d_method  method)
+{
+    hdrl_bpm_3d_parameter * p = (hdrl_bpm_3d_parameter *)
+               hdrl_parameter_new(&hdrl_bpm_3d_parameter_type);
+    p->kappa_low = kappa_low ;
+    p->kappa_high = kappa_high ;
+    p->method = method ;
+    return (hdrl_parameter *)p;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Verify basic correctness of the BPM_3D parameters
+  @param    param   BPM image parameters
+  @return   CPL_ERROR_NONE if everything is ok, an error code otherwise
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_bpm_3d_parameter_verify(
+        const hdrl_parameter    *   param)
+{
+    const hdrl_bpm_3d_parameter * param_loc = (hdrl_bpm_3d_parameter *)param ;
+
+    cpl_error_ensure(param != NULL, CPL_ERROR_NULL_INPUT,
+            return CPL_ERROR_NULL_INPUT, "NULL Input Parameters");
+    cpl_error_ensure(hdrl_bpm_3d_parameter_check(param),
+            CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+            "Expected BPM image parameter") ;
+
+    cpl_error_ensure(param_loc->method == HDRL_BPM_3D_THRESHOLD_ABSOLUTE || 
+            param_loc->method == HDRL_BPM_3D_THRESHOLD_RELATIVE ||
+            param_loc->method == HDRL_BPM_3D_THRESHOLD_ERROR,
+            CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT, 
+            "Unsupported method");
+    switch (param_loc->method) {
+        case HDRL_BPM_3D_THRESHOLD_ABSOLUTE:
+            cpl_error_ensure(param_loc->kappa_high >= param_loc->kappa_low, 
+                    CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                    "kappa_high must be larger than kappa_low");
+            break;
+        case HDRL_BPM_3D_THRESHOLD_RELATIVE:
+        case HDRL_BPM_3D_THRESHOLD_ERROR:
+            cpl_error_ensure(param_loc->kappa_low >= 0, 
+                    CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                    "kappa_low must be >=0");
+            cpl_error_ensure(param_loc->kappa_high >= 0, 
+                    CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                    "kappa_high must be >=0");
+            break;
+    }
+    return CPL_ERROR_NONE ;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Check that the parameter is a BPM_3D parameter
+  @param    self The parameter to check
+  @return   True or False
+ */
+/*----------------------------------------------------------------------------*/
+cpl_boolean hdrl_bpm_3d_parameter_check(const hdrl_parameter * self)
+{
+    return hdrl_parameter_check_type(self, &hdrl_bpm_3d_parameter_type);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the kappa_low in the BPM_3D parameter
+  @param    p   The BPM_3D parameter
+  @return   The kappa_low
+ */
+/*----------------------------------------------------------------------------*/
+double hdrl_bpm_3d_parameter_get_kappa_low(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0);
+    return ((hdrl_bpm_3d_parameter *)p)->kappa_low;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the kappa_high in the BPM_3D parameter
+  @param    p   The BPM_3D parameter
+  @return   The kappa_high
+ */
+/*----------------------------------------------------------------------------*/
+double hdrl_bpm_3d_parameter_get_kappa_high(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0);
+    return ((hdrl_bpm_3d_parameter *)p)->kappa_high;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the method in the BPM_3D parameter
+  @param    p   The BPM_3D parameter
+  @return   The method
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_bpm_3d_method hdrl_bpm_3d_parameter_get_method(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    return ((hdrl_bpm_3d_parameter *)p)->method;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Create a parameter list for the BPM_3D computation
+  @param base_context    base context of parameter (e.g. recipe name)
+  @param prefix          prefix of parameter, may be empty string
+  @param defaults        default values
+
+  Creates a parameterlist with the BPM_3D parameters:
+    - base_context.prefix.kappa_low
+    - base_context.prefix.kappa_high
+    - base_context.prefix.method
+  The CLI aliases omit the base_context.
+ */
+/*----------------------------------------------------------------------------*/
+cpl_parameterlist * hdrl_bpm_3d_parameter_create_parlist(
+        const char              *   base_context,
+        const char              *   prefix,
+        const hdrl_parameter    *   defaults)
+{
+    cpl_ensure(prefix && base_context && defaults, CPL_ERROR_NULL_INPUT, NULL);
+    char                *   name ;
+    cpl_parameterlist   *   parlist = cpl_parameterlist_new();
+    cpl_parameter       *   par ;
+    const char          *   method_str ;
+    char                *   context =
+        hdrl_join_string(".", 2, base_context, prefix);
+    double kappa_low_def = hdrl_bpm_3d_parameter_get_kappa_low(defaults) ;
+    double kappa_high_def = hdrl_bpm_3d_parameter_get_kappa_high(defaults) ;
+    hdrl_bpm_3d_method method_def =hdrl_bpm_3d_parameter_get_method(defaults);
+    if (method_def == HDRL_BPM_3D_THRESHOLD_ABSOLUTE) {
+        method_str = "absolute" ;
+    } else if (method_def == HDRL_BPM_3D_THRESHOLD_RELATIVE) {
+        method_str = "relative" ;
+    } else if (method_def == HDRL_BPM_3D_THRESHOLD_ERROR) {
+        method_str = "error" ;
+    } else {
+        cpl_ensure(0==1,  CPL_ERROR_ILLEGAL_INPUT, NULL) ;
+    }
+
+    /* --prefix.kappa_low */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "kappa-low", base_context,
+            "Low RMS scaling factor for image thresholding.", CPL_TYPE_DOUBLE, 
+            kappa_low_def) ;
+
+    /* --prefix.kappa_high */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "kappa-high", base_context,
+            "High RMS scaling factor for image thresholding.", CPL_TYPE_DOUBLE,
+            kappa_high_def) ;
+
+    /* --prefix.method */
+    name = hdrl_join_string(".", 2, context, "method");
+    par = cpl_parameter_new_enum(name, CPL_TYPE_STRING, 
+            "Thresholdig method to use for bpm detection", context, method_str,
+            3, "absolute", "relative", "error");
+    cpl_free(name);
+    name = hdrl_join_string(".", 2, prefix, "method");
+    cpl_parameter_set_alias(par, CPL_PARAMETER_MODE_CLI, name);
+    cpl_parameter_disable(par, CPL_PARAMETER_MODE_ENV);
+    cpl_free(name);
+    cpl_parameterlist_append(parlist, par);
+
+    cpl_free(context);
+
+    if (cpl_error_get_code()) {
+        cpl_parameterlist_delete(parlist);
+        return NULL;
+    }
+    return parlist;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Parse a parameterlist to create input parameters for the BPM_3D
+  @param parlist        parameter list to parse
+  @param prefix         prefix of parameter name
+  @return   Input parameters for the BPM_3D computation
+
+  Reads a parameterlist in order to create BPM image parameters.
+  Expects a parameterlist containing:
+   - prefix.kappa_low
+   - prefix.kappa_high
+   - prefix.method
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_bpm_3d_parameter_parse_parlist(
+        const cpl_parameterlist *   parlist,
+        const char              *   prefix)
+{
+    cpl_ensure(prefix && parlist, CPL_ERROR_NULL_INPUT, NULL);
+    char                *   name;
+    const cpl_parameter *   par;
+    const char          *   tmp_str ;
+    double                  kappa_low;
+    double                  kappa_high;
+    hdrl_bpm_3d_method      method;
+   
+    /* --kappa_low */
+    name = hdrl_join_string(".", 2, prefix, "kappa-low");
+    par=cpl_parameterlist_find_const(parlist, name);
+    kappa_low = cpl_parameter_get_double(par);
+    cpl_free(name) ;
+
+    /* --kappa_high */
+    name = hdrl_join_string(".", 2, prefix, "kappa-high");
+    par=cpl_parameterlist_find_const(parlist, name);
+    kappa_high = cpl_parameter_get_double(par);
+    cpl_free(name) ;
+
+    /* --method */
+    name = hdrl_join_string(".", 2, prefix, "method");
+    par = cpl_parameterlist_find_const(parlist, name) ;
+    tmp_str = cpl_parameter_get_string(par);
+    if (tmp_str == NULL) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                "Parameter %s not found", name);
+        cpl_free(name);
+        return NULL;
+    }
+    cpl_free(name) ;
+    if(!strcmp(tmp_str, "absolute")) {
+        method = HDRL_BPM_3D_THRESHOLD_ABSOLUTE ;
+    } else if(!strcmp(tmp_str, "relative")) {
+        method = HDRL_BPM_3D_THRESHOLD_RELATIVE ;
+    } else if(!strcmp(tmp_str, "error")) {
+        method = HDRL_BPM_3D_THRESHOLD_ERROR ;
+    } else {
+        cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_INPUT,
+                "Invalid method: %s", tmp_str);
+        return NULL;
+    }
+
+    if (cpl_error_get_code()) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                "Error while parsing parameterlist with prefix %s", prefix);
+        return NULL;
+    } else {
+        return hdrl_bpm_3d_parameter_create(kappa_low, kappa_high, method) ;
+    }
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief detect bad pixels on a stack of identical images
+  @param imglist   input hdrl imagelist
+  @param params    BPM_3D computation parameters
+  @return cpl_imagelist where the newly rejected pixels are marked as unity.
+
+The algorithm first collapses the stack of images by using the median to
+generate a master-image. Then it subtracts the master image from each individual
+image and derives the bad pixels on the residual-images by thresholding,
+i.e. all pixels strictly exceeding the threshold are considered as bad.
+
+Three methods are currently available to derive the bad pixels on the
+residual images and can be set when creating the BPM_3D parameter via
+hdrl_bpm_3d_parameter_create():
+
+\li \c method = HDRL_BPM_3D_THRESHOLD_ABSOLUTE: It uses
+  \e kappa_low and \e kappa_high as absolute threshold
+
+\li \c method = HDRL_BPM_3D_THRESHOLD_RELATIVE: It scales the
+  measured rms on the residual-image with \e kappa_low and
+  \e kappa_high and uses it as threshold. For the rms a properly
+  scaled Median Absolute Deviation (MAD) is used.
+
+\li \c method = HDRL_BPM_3D_THRESHOLD_ERROR: It scales the
+  propagated error of each individual pixel with \e kappa_low and
+  \e kappa_high and uses it as threshold.
+
+
+  @note We assume that the images are already scaled outside this routine, i.e.
+  their absolute levels match.
+
+  @details For a Gaussian distribution the Median Absolute Deviation (MAD) is a
+  robust and consistent estimate of the Standard Deviation (STD) in the sense
+  that the STD is approximately K * MAD, where K is a constant equal to
+  approximately 1.4826
+
+ */
+/*----------------------------------------------------------------------------*/
+cpl_imagelist * hdrl_bpm_3d_compute(
+        const hdrl_imagelist    *   imglist,
+        const hdrl_parameter    *   params)
+{
+
+/*     This routine assumes that the images are already scaled outside ! */
+
+    cpl_imagelist * imglist_out =  NULL;
+    hdrl_imagelist * masterlist = NULL;
+    hdrl_parameter *  collapse_params = NULL;
+
+    /* Check Entries */
+    cpl_error_ensure(imglist && params, CPL_ERROR_NULL_INPUT,
+            return NULL, "NULL input");
+   if (hdrl_bpm_3d_parameter_verify(params) != CPL_ERROR_NONE) return NULL;
+
+    /* Local Usage Parameters */
+    const hdrl_bpm_3d_parameter * p_loc = (hdrl_bpm_3d_parameter *)params ;
+
+    collapse_params = hdrl_collapse_median_parameter_create();
+
+    imglist_out = cpl_imagelist_new();
+    masterlist = hdrl_imagelist_new();
+
+
+    /* Here we have correlated errors */
+    hdrl_image * master;
+    cpl_image * contrib_map;
+
+    /* Get the proper collapse function and perform frames combination */
+    hdrl_imagelist_collapse(imglist, collapse_params, &master,&contrib_map);
+    /* broadcasted same master over list */
+    for (int var = 0; var < hdrl_imagelist_get_size(imglist); ++var) {
+        hdrl_imagelist_set(masterlist, master,
+                        hdrl_imagelist_get_size(masterlist));
+    }
+    cpl_image_delete(contrib_map);
+
+
+    for (int var = 0; var < hdrl_imagelist_get_size(imglist); ++var) {
+        /* subtract master */
+        hdrl_image * tmp_hdrlimg = hdrl_image_sub_image_create(
+                hdrl_imagelist_get_const(imglist, var),
+                hdrl_imagelist_get(masterlist, var));
+        cpl_mask * tmp_cplimg_mask = hdrl_image_get_mask(tmp_hdrlimg);
+        cpl_mask * mask_out = NULL;
+
+        if (p_loc->method == HDRL_BPM_3D_THRESHOLD_ABSOLUTE) { 
+            /* Absolute values */
+            mask_out = cpl_mask_threshold_image_create(
+                    hdrl_image_get_image(tmp_hdrlimg), p_loc->kappa_low,
+                    p_loc->kappa_high);
+            cpl_mask_not(mask_out);
+            /*Here we use the bpm from the image after master frame subtraction
+             *  - this is not 100 percent clean but a good approximation*/
+            cpl_mask_xor(mask_out, tmp_cplimg_mask);
+        } else if (p_loc->method == HDRL_BPM_3D_THRESHOLD_RELATIVE) { 
+            /* Scaled residual from image using scaled mad*/
+            double mad, std_mad;
+            cpl_image_get_mad(hdrl_image_get_image(tmp_hdrlimg), &mad);
+            if (mad <= 0){
+                mad = nextafter(0, 1.0);
+            }
+            std_mad = CPL_MATH_STD_MAD * mad;
+            mask_out = cpl_mask_threshold_image_create(
+                    hdrl_image_get_image(tmp_hdrlimg),
+                    -(p_loc->kappa_low * std_mad), 
+                    (p_loc->kappa_high * std_mad));
+            cpl_mask_not(mask_out);
+            /*Here we use the bpm from the image after master frame subtraction
+             *  - this is not 100 percent clean but a good approximation*/
+            cpl_mask_xor(mask_out, tmp_cplimg_mask);
+        } else if (p_loc->method == HDRL_BPM_3D_THRESHOLD_ERROR) {
+            /* Using scaled pixel error bars to detect bp -
+             * we use the propagated error */
+            cpl_size nx = hdrl_image_get_size_x(tmp_hdrlimg);
+            cpl_size ny = hdrl_image_get_size_y(tmp_hdrlimg);
+            mask_out = cpl_mask_new(nx, ny); /*All pixels are now good*/
+
+            for (cpl_size x = 1; x <= nx; ++x) {
+                for (cpl_size y = 1; y <= ny; ++y) {
+                    int bad_data;
+                    hdrl_value v = hdrl_image_get_pixel(tmp_hdrlimg, x, y,
+                                                        &bad_data);
+
+                    if (v.data < -(v.error * p_loc->kappa_low) ||
+                        v.data > (v.error * p_loc->kappa_high) || bad_data) {
+                        cpl_mask_set(mask_out, x, y, CPL_BINARY_1);
+                    }
+                }
+            }
+            /*Here we use the bpm from the image after master frame subtraction
+             *  - this is not 100 percent clean but a good approximation */
+            cpl_mask_xor(mask_out, tmp_cplimg_mask);
+        }
+        cpl_imagelist_set(imglist_out, cpl_image_new_from_mask(mask_out), var);
+        cpl_mask_delete(mask_out);
+        hdrl_image_delete(tmp_hdrlimg);
+    }
+
+    if (cpl_error_get_code() != CPL_ERROR_NONE) {
+        cpl_imagelist_delete(imglist_out);
+        imglist_out = NULL;
+    }
+
+    hdrl_parameter_delete(collapse_params);
+
+    /* single master broadcasted over list */
+    hdrl_image_delete(hdrl_imagelist_unset(masterlist, 0));
+    hdrl_imagelist_unwrap(masterlist);
+
+    return imglist_out;
+}
+
+/**@}*/
+
diff --git a/hdrl/hdrl_bpm_3d.h b/hdrl/hdrl_bpm_3d.h
new file mode 100644
index 0000000..819838b
--- /dev/null
+++ b/hdrl/hdrl_bpm_3d.h
@@ -0,0 +1,84 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_BPM_3D_H
+#define HDRL_BPM_3D_H
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include <cpl.h>
+#include <stdint.h>
+#include "hdrl_image.h"
+#include "hdrl_imagelist.h"
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                                Defines
+ -----------------------------------------------------------------------------*/
+
+typedef enum {
+    HDRL_BPM_3D_THRESHOLD_ABSOLUTE,
+    HDRL_BPM_3D_THRESHOLD_RELATIVE,
+    HDRL_BPM_3D_THRESHOLD_ERROR
+} hdrl_bpm_3d_method ;
+
+/*-----------------------------------------------------------------------------
+                            Functions prototypes
+ -----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+                            BPM Parameters
+  ----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_bpm_3d_parameter_create(double,double,hdrl_bpm_3d_method);
+cpl_error_code hdrl_bpm_3d_parameter_verify(const hdrl_parameter *) ;
+cpl_boolean hdrl_bpm_3d_parameter_check(const hdrl_parameter *) ;
+
+/* Accessors */
+double hdrl_bpm_3d_parameter_get_kappa_low(const hdrl_parameter *) ;
+double hdrl_bpm_3d_parameter_get_kappa_high(const hdrl_parameter *) ;
+hdrl_bpm_3d_method hdrl_bpm_3d_parameter_get_method(const hdrl_parameter *) ;
+
+/* Parameter Lists */
+cpl_parameterlist * hdrl_bpm_3d_parameter_create_parlist(const char *, 
+        const char *, const hdrl_parameter *) ;
+hdrl_parameter * hdrl_bpm_3d_parameter_parse_parlist(const cpl_parameterlist *, 
+        const char *) ; 
+
+/*----------------------------------------------------------------------------
+                            BPM_3D Computation
+  ----------------------------------------------------------------------------*/
+
+cpl_imagelist * hdrl_bpm_3d_compute(
+        const hdrl_imagelist    *   imglist,
+        const hdrl_parameter    *   params) ;
+
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+ -----------------------------------------------------------------------------*/
+
+#ifdef HDRL_USE_PRIVATE
+
+#endif
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_bpm_fit.c b/hdrl/hdrl_bpm_fit.c
new file mode 100644
index 0000000..a146716
--- /dev/null
+++ b/hdrl/hdrl_bpm_fit.c
@@ -0,0 +1,665 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+-----------------------------------------------------------------------------*/
+
+#include "hdrl_types.h"
+#include "hdrl_image.h"
+#include "hdrl_imagelist.h"
+#include "hdrl_utils.h"
+#include "hdrl_fit.h"
+
+#include <cpl.h>
+#include <string.h>
+#include <math.h>
+
+/*-----------------------------------------------------------------------------
+                                   Static
+ -----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_bpm_fit     Bad Pixel Mask via fitting
+  @ingroup hdrl_bpm
+
+  @brief
+   Algorithms to detect bad-pixels on a sequence of images like e.g. domeflats
+
+ The routine in this module derives bad pixels on a sequence of images (e.g.
+ domeflats with differend exposure time). The algorithm fits a polynomial to each
+ pixel-sequence and determinates bad pixels based on this fit and various
+ thresholding methods.
+
+ The calculation is performed by calling the top-level function
+ hdrl_bpm_fit_compute() and the parameters passed to this function can be created
+ by calling
+ hdrl_bpm_fit_parameter_create_rel_chi(), \b or
+ hdrl_bpm_fit_parameter_create_rel_coef(), \b or
+ hdrl_bpm_fit_parameter_create_pval(), depending on the method one would like
+ to use.
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+/** @cond PRIVATE */
+
+double igamc(double, double);
+
+/*-----------------------------------------------------------------------------
+                        BPM Parameters Definition
+ -----------------------------------------------------------------------------*/
+typedef struct {
+    HDRL_PARAMETER_HEAD;
+    int        degree;
+    double     pval;
+    double     rel_chi_l;
+    double     rel_chi_h;
+    double     rel_coef_l;
+    double     rel_coef_h;
+} hdrl_bpm_fit_parameter;
+
+/* Parameter type */
+static hdrl_parameter_typeobj hdrl_bpm_fit_parameter_type = {
+    HDRL_PARAMETER_BPM_FIT,                 /* type */
+    (hdrl_alloc *)&cpl_malloc,              /* fp_alloc */
+    (hdrl_free *)&cpl_free,                 /* fp_free */
+    NULL,                                   /* fp_destroy */
+    sizeof(hdrl_bpm_fit_parameter),         /* obj_size */
+};
+
+cpl_error_code hdrl_bpm_fit_parameter_verify(const hdrl_parameter * p);
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief create general bpm_fit parameter only one cut must be > 0
+ * @param degree   degree of fit
+ * @param pval     p-value bpm cutoff
+ * @param rel_chi  relative chi bpm cutoff
+ * @param rel_coef relative coefficient bpm cutoff
+ *
+ * @return  valud hdrl_parameter or NULL on error
+ */
+/* ---------------------------------------------------------------------------*/
+static hdrl_parameter *
+hdrl_bpm_fit_parameter_create_all(int degree, double pval,
+                                  double rel_chi_l, double rel_chi_h,
+                                  double rel_coef_l, double rel_coef_h)
+{
+    hdrl_bpm_fit_parameter * p = (hdrl_bpm_fit_parameter *)
+               hdrl_parameter_new(&hdrl_bpm_fit_parameter_type);
+    p->degree = degree;
+    p->pval = pval;
+    p->rel_chi_l = rel_chi_l;
+    p->rel_chi_h = rel_chi_h;
+    p->rel_coef_l = rel_coef_l;
+    p->rel_coef_h = rel_coef_h;
+    if (hdrl_bpm_fit_parameter_verify((const hdrl_parameter *)p) ==
+        CPL_ERROR_NONE) {
+        return (hdrl_parameter *)p;
+    }
+    else {
+        hdrl_parameter_delete((hdrl_parameter*)p);
+        return NULL;
+    }
+}
+
+/** @endcond */
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create bpm_fit parameter with p-value bpm treshold
+ * @param degree  degree of fit
+ * @param pval    p-value of bpm threshold
+ * @return hdrl_parameter or NULL on error
+ * @see hdrl_bpm_fit_compute()
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_parameter *
+hdrl_bpm_fit_parameter_create_pval(int degree, double pval)
+{
+    return hdrl_bpm_fit_parameter_create_all(degree, pval, -1, -1, -1, -1);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create bpm_fit parameter with relative chi bpm treshold
+ * @param degree  degree of fit
+ * @param rel_chi_low relative chi distribution bpm lower threshold
+ * @param rel_chi_high relative chi distribution bpm upper threshold
+ * @return hdrl_parameter or NULL on error
+ * @see hdrl_bpm_fit_compute()
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_parameter *
+hdrl_bpm_fit_parameter_create_rel_chi(int degree,
+                                      double rel_chi_low, double rel_chi_high)
+{
+    return hdrl_bpm_fit_parameter_create_all(degree, -1,
+                                         rel_chi_low, rel_chi_high, -1, -1);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create bpm_fit parameter with relative coefficient bpm treshold
+ * @param degree   degree of fit
+ * @param rel_coef_low relative fit coefficient distribution bpm lower threshold
+ * @param rel_coef_high relative fit coefficient distribution bpm upper threshold
+ * @return hdrl_parameter or NULL on error
+ * @see hdrl_bpm_fit_compute()
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_parameter *
+hdrl_bpm_fit_parameter_create_rel_coef(int degree,
+                                   double rel_coef_low, double rel_coef_high)
+{
+    return hdrl_bpm_fit_parameter_create_all(degree, -1,
+                                         -1, -1, rel_coef_low, rel_coef_high);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Check that the parameter is a bpm_fit parameter
+  @param    self The parameter to check
+  @return   True or False
+ */
+/*----------------------------------------------------------------------------*/
+cpl_boolean hdrl_bpm_fit_parameter_check(const hdrl_parameter * self)
+{
+    return hdrl_parameter_check_type(self, &hdrl_bpm_fit_parameter_type);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief verify that the parameter is a valid bpm_fit_parameter
+ * @param p parameter
+ * @return error code
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_bpm_fit_parameter_verify(const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, 0);
+    cpl_ensure(hdrl_bpm_fit_parameter_check(p),
+               CPL_ERROR_INCOMPATIBLE_INPUT, 0);
+    const hdrl_bpm_fit_parameter * par = (const hdrl_bpm_fit_parameter *)p;
+    int have_par = 0;
+    if (par->degree < 0) {
+        return cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_INPUT,
+                                     "degree must be positive");
+    }
+
+    if (par->pval >= 0) {
+        if (par->pval > 100.) {
+            return cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_INPUT,
+                                     "pval must be between 0 and 100%%");
+        }
+        have_par = 1;
+    }
+
+    if (par->rel_chi_l >= 0 || par->rel_chi_h >= 0) {
+        if (have_par) {
+            return cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_INPUT,
+                                     "Only one rejection criteria is allowed, "
+                                     "set the others to negative values");
+        }
+        if (!(par->rel_chi_l >= 0 && par->rel_chi_h >= 0)) {
+            return cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_INPUT,
+                         "Upper and lower rejection criteria must be >= 0");
+        }
+        have_par = 1;
+    }
+
+    if (par->rel_coef_l >= 0 || par->rel_coef_h >= 0) {
+        if (have_par) {
+            return cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_INPUT,
+                                     "Only one rejection criteria is allowed, "
+                                     "set the others to negative values");
+        }
+        if (!(par->rel_coef_l >= 0 && par->rel_coef_h >= 0)) {
+            return cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_INPUT,
+                         "Upper and lower rejection criteria must be >= 0");
+        }
+        have_par = 1;
+    }
+
+    if (!have_par) {
+        return cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_INPUT,
+                 "Only no bad pixel parameter given, the chosen threshold "
+                 "must have a value larger than zero");
+    }
+    return CPL_ERROR_NONE;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get degree of polynomial fit of parameter
+ * @param p parameter
+ * @return degree of polynomial fit
+ */
+/* ---------------------------------------------------------------------------*/
+int hdrl_bpm_fit_parameter_get_degree(const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, 0);
+    cpl_ensure(hdrl_bpm_fit_parameter_check(p),
+               CPL_ERROR_INCOMPATIBLE_INPUT, 0);
+    return ((hdrl_bpm_fit_parameter *)p)->degree;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get p-value bpm treshold
+ * @param p parameter
+ * @return p-value
+ */
+/* ---------------------------------------------------------------------------*/
+double hdrl_bpm_fit_parameter_get_pval( const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.);
+    cpl_ensure(hdrl_bpm_fit_parameter_check(p),
+               CPL_ERROR_INCOMPATIBLE_INPUT, -1.);
+    return ((hdrl_bpm_fit_parameter *)p)->pval;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get relative chi distribution lower threshold
+ * @param p parameter
+ * @return relative chi distribution lower threshold
+ */
+/* ---------------------------------------------------------------------------*/
+double hdrl_bpm_fit_parameter_get_rel_chi_low(const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.);
+    cpl_ensure(hdrl_bpm_fit_parameter_check(p),
+               CPL_ERROR_INCOMPATIBLE_INPUT, -1.);
+    return ((hdrl_bpm_fit_parameter *)p)->rel_chi_l;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get relative chi distribution upper threshold
+ * @param p parameter
+ * @return relative chi distribution upper threshold
+ */
+/* ---------------------------------------------------------------------------*/
+double hdrl_bpm_fit_parameter_get_rel_chi_high(const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.);
+    cpl_ensure(hdrl_bpm_fit_parameter_check(p),
+               CPL_ERROR_INCOMPATIBLE_INPUT, -1.);
+    return ((hdrl_bpm_fit_parameter *)p)->rel_chi_h;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get relative fit coefficient distribution lower threshold
+ * @param p parameter
+ * @return relative fit coefficient distribution lower threshold
+ */
+/* ---------------------------------------------------------------------------*/
+double hdrl_bpm_fit_parameter_get_rel_coef_low(const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.);
+    cpl_ensure(hdrl_bpm_fit_parameter_check(p),
+               CPL_ERROR_INCOMPATIBLE_INPUT, -1.);
+    return ((hdrl_bpm_fit_parameter *)p)->rel_coef_l;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get relative fit coefficient distribution upper threshold
+ * @param p parameter
+ * @return relative fit coefficient distribution upper threshold
+ */
+/* ---------------------------------------------------------------------------*/
+double hdrl_bpm_fit_parameter_get_rel_coef_high(const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.);
+    cpl_ensure(hdrl_bpm_fit_parameter_check(p),
+               CPL_ERROR_INCOMPATIBLE_INPUT, -1.);
+    return ((hdrl_bpm_fit_parameter *)p)->rel_coef_h;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Create a parameter list for the BPM_FIT computation
+  @param base_context    base context of parameter (e.g. recipe name)
+  @param prefix          prefix of parameter, may be empty string
+  @param defaults        default values
+
+  Creates a parameterlist with the BPM_FIT parameters:
+    - base_context.prefix.degree
+    - base_context.prefix.pval
+    - base_context.prefix.rel-chi-low
+    - base_context.prefix.rel-chi-high
+    - base_context.prefix.rel-coef-low
+    - base_context.prefix.rel-coef-high
+  The CLI aliases omit the base_context.
+ */
+/*----------------------------------------------------------------------------*/
+cpl_parameterlist * hdrl_bpm_fit_parameter_create_parlist(
+        const char              *   base_context,
+        const char              *   prefix,
+        const hdrl_parameter    *   defaults)
+{
+    cpl_ensure(prefix && base_context && defaults, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_parameterlist   *   parlist = cpl_parameterlist_new();
+        
+    int  degree_default = hdrl_bpm_fit_parameter_get_degree(defaults);
+    double pval_default = hdrl_bpm_fit_parameter_get_pval(defaults) ;
+    double rel_chi_low_default = 
+        hdrl_bpm_fit_parameter_get_rel_chi_low(defaults) ;
+    double rel_chi_high_default =
+        hdrl_bpm_fit_parameter_get_rel_chi_high(defaults) ;
+    double rel_coef_low_default =
+        hdrl_bpm_fit_parameter_get_rel_coef_low(defaults) ;
+    double rel_coef_high_default =
+        hdrl_bpm_fit_parameter_get_rel_coef_high(defaults);
+
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "degree", base_context,
+            "Degree of polynomial to fit.", CPL_TYPE_INT, degree_default);
+
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "pval", base_context,
+          "p-value threshold (in percent). Fits with a p-value below "
+          "this threshold are considered bad pixels.",
+          CPL_TYPE_DOUBLE, pval_default);
+
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "rel-chi-low", base_context,
+        "Relative chi threshold. Pixels with with a chi value "
+        "smaller than mean - rel-threshold * stdev-of-chi are "
+        "considered bad pixels.", CPL_TYPE_DOUBLE, rel_chi_low_default);
+
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "rel-chi-high", base_context,
+        "Relative chi threshold. Pixels with with a chi value larger "
+        "than mean + rel-threshold * stdev-of-chi are "
+        "considered bad pixels.", CPL_TYPE_DOUBLE, rel_chi_high_default);
+
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "rel-coef-low", base_context,
+              "Relative fit coefficient threshold. Pixels with with a "
+              "coefficient value smaller than "
+              "mean +- rel-threshold * stdev-of-coeff are "
+              "considered bad pixels.", CPL_TYPE_DOUBLE, rel_coef_low_default);
+
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "rel-coef-high", base_context,
+              "Relative fit coefficient threshold. Pixels with with a "
+              "coefficient value larger than "
+              "mean +- rel-threshold * stdev-of-coeff are "
+              "considered bad pixels.", CPL_TYPE_DOUBLE, rel_coef_high_default);
+
+    if (cpl_error_get_code()) {
+        cpl_parameterlist_delete(parlist);
+        return NULL;
+    }
+    return parlist;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Parse a parameterlist to create input parameters for the BPM_FIT
+  @param parlist        parameter list to parse
+  @param prefix         prefix of parameter name
+  @return   Input parameter for the BPM_FIT computation
+
+  Reads a parameterlist in order to create BPM image parameters.
+  Expects a parameterlist containing:
+   - prefix.degree
+   - prefix.pval
+   - prefix.rel-chi-low
+   - prefix.rel-chi-high
+   - prefix.rel-coef-low
+   - prefix.rel-coef-high
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_bpm_fit_parameter_parse_parlist(
+        const cpl_parameterlist *   parlist,
+        const char              *   prefix)
+{
+    cpl_ensure(prefix && parlist, CPL_ERROR_NULL_INPUT, NULL);
+    char                *   name;
+    const cpl_parameter *   par;
+    double                  pval = -1;
+    double                  rel_chi_l = -1;
+    double                  rel_chi_h = -1;
+    double                  rel_coef_l = -1;
+    double                  rel_coef_h = -1;
+    int                     degree;
+
+    name = hdrl_join_string(".", 2, prefix, "degree");
+    par = cpl_parameterlist_find_const(parlist, name);
+    if (par == NULL) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                              "Parameter %s not found", name);
+        cpl_free(name);
+        return NULL;
+    }
+    degree = cpl_parameter_get_int(par);
+    cpl_free(name);
+
+    name = hdrl_join_string(".", 2, prefix, "pval");
+    par = cpl_parameterlist_find_const(parlist, name);
+    if (par) {
+        pval = cpl_parameter_get_double(par);
+    }
+    cpl_free(name) ;
+
+    name = hdrl_join_string(".", 2, prefix, "rel-chi-low");
+    par = cpl_parameterlist_find_const(parlist, name);
+    if (par) {
+        rel_chi_l = cpl_parameter_get_double(par);
+    }
+    cpl_free(name) ;
+
+    name = hdrl_join_string(".", 2, prefix, "rel-chi-high");
+    par = cpl_parameterlist_find_const(parlist, name);
+    if (par) {
+        rel_chi_h = cpl_parameter_get_double(par);
+    }
+    cpl_free(name) ;
+
+    name = hdrl_join_string(".", 2, prefix, "rel-coef-low");
+    par = cpl_parameterlist_find_const(parlist, name);
+    if (par) {
+        rel_coef_l = cpl_parameter_get_double(par);
+    }
+    cpl_free(name);
+
+    name = hdrl_join_string(".", 2, prefix, "rel-coef-high");
+    par = cpl_parameterlist_find_const(parlist, name);
+    if (par) {
+        rel_coef_h = cpl_parameter_get_double(par);
+    }
+    cpl_free(name);
+
+    if (cpl_error_get_code()) {
+        return NULL;
+    }
+    /* does verification */
+    return hdrl_bpm_fit_parameter_create_all(degree, pval,
+                                 rel_chi_l, rel_chi_h, rel_coef_l, rel_coef_h);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief Utility to get a integer mask from a (stdev) relative threshold
+ * @param img    image to threshold
+ * @param kappa_low (stdev) relative threshold
+ * @param kappa_high  (stdev) relative threshold
+ * @param mad   if true estimate stdev via mad
+ * @return integer mask where threshold is exceeded
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_image *
+bpm_from_rel(cpl_image * img, double kappa_low, double kappa_high, int mad)
+{
+    cpl_image * r;
+    double m, s;
+    if (mad) {
+        m = cpl_image_get_mad(img, &s);
+        s *= CPL_MATH_STD_MAD;
+        s = CX_MAX(DBL_EPSILON, s);
+    }
+    else {
+        m = cpl_image_get_mean(img);
+        s = cpl_image_get_stdev(img);
+    }
+    cpl_mask * bpm = cpl_mask_threshold_image_create(img, m - s * kappa_low,
+                                                     m + s * kappa_high);
+    cpl_mask_not(bpm);
+    r = cpl_image_new_from_mask(bpm);
+    cpl_mask_delete(bpm);
+    return r;
+}
+
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+  @brief compute bad pixel map based on fitting a stack of images
+  @param par         input bpm_fit_parameter
+  @param data        hdrl_imagelist to fit
+  @param sample_pos  cpl_vector of sampling position of the images in data,
+                     e.g. exposure time
+  @param out_mask    output bad pixel mask as integer image
+  @return CPL_ERROR_NONE if everything is ok, an error code otherwise
+
+The function fits a polynomial of degree \e degree to
+the imagelist at the sampling positions defined in \e sample_pos.
+
+Three methods are available to convert the information from the fit
+into a bad pixel map:
+
+
+\li \c Relative cutoff on the chi distribution of all fits. Pixels
+       with chi values strictly outside the interval \f$ mean(\chi) -
+       stdev(\chi) \times rel\_chi\_low \f$ and \f$ mean(\chi) +
+       stdev(\chi) \times rel\_chi\_high \f$ are considered bad. The
+       corresponding hdrl parameter is created by
+       hdrl_bpm_fit_parameter_create_rel_chi()
+
+\li \c Relative cutoff on the distribution of the fit
+       coefficients. Pixels with fit coefficients strictly outside the
+       interval \f$ mean(coef) - stdev(coef) \times rel\_coef\_low
+       \f$ and \f$ mean(coef) + stdev(coef) \times rel\_coef\_high
+       \f$ are considered bad.  The coefficient numbers that caused
+       the pixel to be marked as bad are encoded as powers of two of
+       their degree (starting from 0). The corresponding hdrl
+       parameter is created by
+       hdrl_bpm_fit_parameter_create_rel_coef()
+
+\li \c Pixels with low \e p-value. When the errors of the pixels are
+       correct the \e p-value can be interpreted as the probability
+       with which the pixel response fits the chosen model. The
+       corresponding hdrl parameter is created by
+       hdrl_bpm_fit_parameter_create_pval()
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_bpm_fit_compute(const hdrl_parameter * par,
+                     const hdrl_imagelist * data,
+                     const cpl_vector * sample_pos,
+                     cpl_image ** out_mask)
+{
+    cpl_image * out_chi2 = NULL, * out_dof = NULL;
+    hdrl_imagelist * out_coef = NULL;
+    if (hdrl_bpm_fit_parameter_verify(par) != CPL_ERROR_NONE)
+        return cpl_error_get_code();
+
+    int degree = hdrl_bpm_fit_parameter_get_degree(par);
+
+    /* TODO check for 0 error,
+     * in that case set to 1 and do not allow pval */
+
+    cpl_error_code err = hdrl_fit_polynomial_imagelist(data, sample_pos, degree,
+                                               &out_coef, &out_chi2, &out_dof);
+    if (err) {
+        return cpl_error_set_message(cpl_func, CPL_ERROR_FILE_NOT_FOUND,
+                                     "Fit failed");
+    }
+
+    if (cpl_image_count_rejected(out_chi2) ==
+        (cpl_image_get_size_x(out_chi2) * cpl_image_get_size_y(out_chi2))) {
+        cpl_msg_error(cpl_func, "Too few good pixels to fit polynomial of "
+                      "degree %d in all pixels", degree);
+        goto end;
+    }
+
+    {
+        cpl_image * bpm = NULL;
+        double pval = hdrl_bpm_fit_parameter_get_pval(par);
+        double rel_chi_l = hdrl_bpm_fit_parameter_get_rel_chi_low(par);
+        double rel_chi_h = hdrl_bpm_fit_parameter_get_rel_chi_high(par);
+        double rel_coef_l = hdrl_bpm_fit_parameter_get_rel_coef_low(par);
+        double rel_coef_h = hdrl_bpm_fit_parameter_get_rel_coef_high(par);
+
+        if (rel_chi_l >= 0) {
+            /* chi is symmetric */
+            cpl_image_power(out_chi2, 0.5);
+            bpm = bpm_from_rel(out_chi2, rel_chi_l, rel_chi_h, 1);
+        }
+        else if (rel_coef_l >= 0) {
+            for (cpl_size i = 0; i < hdrl_imagelist_get_size(out_coef); i++) {
+                hdrl_image * coef = hdrl_imagelist_get(out_coef, i);
+                cpl_image * b = bpm_from_rel(hdrl_image_get_image(coef),
+                                             rel_coef_l, rel_coef_h, 0);
+
+                /* bits of bpm defines which coefficient "bad" */
+                if (bpm) {
+                    cpl_image_multiply_scalar(b, pow(2, i));
+                    cpl_image_add(bpm, b);
+                    cpl_image_delete(b);
+                }
+                else {
+                    bpm = b;
+                }
+            }
+        }
+        else if (pval >= 0) {
+            pval /= 100.;
+            bpm = cpl_image_new(cpl_image_get_size_x(out_chi2),
+                                cpl_image_get_size_y(out_chi2),
+                                CPL_TYPE_INT);
+            int * md = cpl_image_get_data_int(bpm);
+            hdrl_data_t * cd = cpl_image_get_data(out_chi2);
+            hdrl_data_t * dd = cpl_image_get_data(out_dof);
+            for (size_t i = 0; i < (size_t)cpl_image_get_size_x(out_chi2) *
+                 cpl_image_get_size_y(out_chi2); i++) {
+                double pv = igamc(dd[i] / 2., cd[i] / 2.);
+                md[i] = (pv < pval);
+            }
+        }
+        *out_mask = bpm;
+    }
+
+end:
+    hdrl_imagelist_delete(out_coef);
+    cpl_image_delete(out_chi2);
+    cpl_image_delete(out_dof);
+
+    return cpl_error_get_code();
+}
+
+/**@}*/
diff --git a/hdrl/hdrl_bpm_fit.h b/hdrl/hdrl_bpm_fit.h
new file mode 100644
index 0000000..08f7275
--- /dev/null
+++ b/hdrl/hdrl_bpm_fit.h
@@ -0,0 +1,81 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_BPM_FIT_H
+#define HDRL_BPM_FIT_H
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_parameter.h"
+#include "hdrl_image.h"
+#include "hdrl_imagelist.h"
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                            Functions prototypes
+ -----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+                            BPM Parameters
+  ----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_bpm_fit_parameter_create_pval(int, double);
+hdrl_parameter * hdrl_bpm_fit_parameter_create_rel_chi(int, double, double);
+hdrl_parameter * hdrl_bpm_fit_parameter_create_rel_coef(int, double, double);
+cpl_error_code hdrl_bpm_fit_parameter_verify(const hdrl_parameter *) ;
+
+/* Accessors */
+int hdrl_bpm_fit_parameter_get_degree(const hdrl_parameter *);
+double hdrl_bpm_fit_parameter_get_pval(const hdrl_parameter *);
+double hdrl_bpm_fit_parameter_get_rel_chi_low(const hdrl_parameter *);
+double hdrl_bpm_fit_parameter_get_rel_chi_high(const hdrl_parameter *);
+double hdrl_bpm_fit_parameter_get_rel_coef_low(const hdrl_parameter *);
+double hdrl_bpm_fit_parameter_get_rel_coef_high(const hdrl_parameter *);
+
+/* Parameter Lists */
+cpl_parameterlist * hdrl_bpm_fit_parameter_create_parlist(const char *,
+        const char *, const hdrl_parameter *);
+hdrl_parameter * hdrl_bpm_fit_parameter_parse_parlist(
+                                              const cpl_parameterlist *,
+                                              const char *);
+
+/*----------------------------------------------------------------------------
+                            BPM_FIT Computation
+  ----------------------------------------------------------------------------*/
+
+cpl_error_code
+hdrl_bpm_fit_compute(const hdrl_parameter * par,
+                     const hdrl_imagelist * data,
+                     const cpl_vector * sample_pos,
+                     cpl_image ** out_mask);
+
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+ -----------------------------------------------------------------------------*/
+
+#ifdef HDRL_USE_PRIVATE
+
+#endif
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_bpm_utils.c b/hdrl/hdrl_bpm_utils.c
new file mode 100644
index 0000000..e750cb0
--- /dev/null
+++ b/hdrl/hdrl_bpm_utils.c
@@ -0,0 +1,318 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+-----------------------------------------------------------------------------*/
+
+#include "hdrl_types.h"
+#include "hdrl_image.h"
+#include "hdrl_imagelist.h"
+#include "hdrl_utils.h"
+
+#include "hdrl_bpm_utils.h"
+#include "hdrl_prototyping.h"
+
+#include <cpl.h>
+#include <string.h>
+#include <math.h>
+
+/*-----------------------------------------------------------------------------
+                                   Static
+ -----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_bpm_utils     Bad Pixel Utilities
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Wrapper around hdrl_bpm_filter() to filter list of images
+  @param inlist     input image list
+  @param kernel_nx  size in x-direction of the filtering kernel
+  @param kernel_ny  size in y-direction of the filtering kernel
+  @param filter     filter modes as defined in cpl
+  @return   The filtered image list
+  @see hdrl_bpm_filter()
+ */
+/*----------------------------------------------------------------------------*/
+cpl_imagelist * hdrl_bpm_filter_list(
+        const cpl_imagelist   *   inlist,
+        cpl_size            kernel_nx,
+        cpl_size            kernel_ny,
+        cpl_filter_mode     filter)
+{
+    cpl_imagelist   *   out ;
+    cpl_size            nima;
+    
+    /* Check Entries */
+    cpl_ensure(inlist != NULL, CPL_ERROR_NULL_INPUT, NULL);
+    nima = cpl_imagelist_get_size(inlist) ;
+
+    /* Create Output list */
+    out = cpl_imagelist_new() ;
+
+    /* Loop over the imagelist */
+    for (cpl_size i = 0 ; i < nima ; i++) {
+        cpl_mask * mask_in, * mask_out;
+        /* Convert input image to mask */
+        mask_in = cpl_mask_threshold_image_create(
+                      cpl_imagelist_get_const(inlist, i), -0.5, 0.5);
+        cpl_mask_not(mask_in);
+
+        /* Filter mask */
+        mask_out = hdrl_bpm_filter(mask_in, kernel_nx, kernel_ny, filter) ;
+        cpl_mask_delete(mask_in) ;
+        if (mask_out == NULL) {
+            cpl_imagelist_delete(out) ;
+            return NULL ;
+        }
+
+        /* Convert mask to image and store it in the list */
+        cpl_imagelist_set(out, cpl_image_new_from_mask(mask_out), i);
+        cpl_mask_delete(mask_out) ;
+    }
+    return out ;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Allows the growing and shrinking of bad pixel masks. It can be used to
+  e.g. set pixels to bad if the pixel is surrounded by other bad pixels.
+  @param input_mask input mask
+  @param kernel_nx  size in x-direction of the filtering kernel
+  @param kernel_ny  size in y-direction of the filtering kernel
+  @param filter     filter modes as defined in cpl - see below
+  Supported modes:
+  CPL_FILTER_EROSION, CPL_FILTER_DILATION, CPL_FILTER_OPENING,
+  CPL_FILTER_CLOSING
+ 
+  The returned mask must be deallocated using cpl_mask_delete().
+  The algorithm assumes, that all pixels outside the mask are good, i.e. it
+  enlarges the mask by the kernel size and marks this border as good. It
+  applies on the enlarged mask the operation and extract the original-size
+  mask at the very end.
+ */
+/*----------------------------------------------------------------------------*/
+cpl_mask * hdrl_bpm_filter(
+        const cpl_mask    *   input_mask,
+        cpl_size        kernel_nx,
+        cpl_size        kernel_ny, 
+        cpl_filter_mode filter)
+{
+    cpl_mask * kernel = NULL;
+    cpl_mask * filtered_mask = NULL;
+    cpl_mask * expanded_mask = NULL;
+    cpl_mask * expanded_filtered_mask = NULL;
+    
+    /* Check Entries */
+    cpl_ensure(input_mask != NULL, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(kernel_nx >= 1, CPL_ERROR_ILLEGAL_INPUT, NULL);
+    cpl_ensure(kernel_ny >= 1, CPL_ERROR_ILLEGAL_INPUT, NULL);
+    cpl_ensure(filter == CPL_FILTER_EROSION || filter == CPL_FILTER_DILATION ||
+            filter == CPL_FILTER_OPENING || filter == CPL_FILTER_CLOSING, 
+            CPL_ERROR_ILLEGAL_INPUT, NULL);
+
+    /* Only odd-sized masks allowed */
+    cpl_ensure((kernel_nx&1) == 1, CPL_ERROR_ILLEGAL_INPUT, NULL);
+    cpl_ensure((kernel_ny&1) == 1, CPL_ERROR_ILLEGAL_INPUT, NULL);
+
+    kernel = cpl_mask_new(kernel_nx, kernel_ny);
+    cpl_mask_not(kernel); /* All values set to unity*/
+
+    /* Enlarge the original mask with the kernel size and assume that outside
+     * all pixels are good */
+    expanded_mask = cpl_mask_new(
+            cpl_mask_get_size_x(input_mask) + 2 * kernel_nx,
+            cpl_mask_get_size_y(input_mask) + 2 * kernel_ny);
+
+    cpl_mask_copy(expanded_mask, input_mask, kernel_nx + 1, kernel_ny +1 );
+
+    expanded_filtered_mask = cpl_mask_new(cpl_mask_get_size_x(expanded_mask),
+            cpl_mask_get_size_y(expanded_mask));
+
+    if(cpl_mask_filter(expanded_filtered_mask, expanded_mask, kernel, filter,
+                    CPL_BORDER_ZERO) != CPL_ERROR_NONE) {
+
+        cpl_mask_delete(kernel);
+        cpl_mask_delete(expanded_filtered_mask);
+        cpl_mask_delete(expanded_mask);
+        return NULL;
+    }
+
+    /* Extract the original mask from the expanded mask */
+    filtered_mask = cpl_mask_extract(expanded_filtered_mask,
+            kernel_nx+1, kernel_ny + 1,
+            cpl_mask_get_size_x(input_mask) + kernel_nx,
+            cpl_mask_get_size_y(input_mask) + kernel_ny);
+
+
+    /* Free memory */
+    cpl_mask_delete(kernel);
+    cpl_mask_delete(expanded_filtered_mask);
+    cpl_mask_delete(expanded_mask);
+
+    return filtered_mask;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief convert bad pixel information mask to a cpl_mask
+  @param bpm        integer image containing the bad pixel information
+  @param selection  bit-mask selecting which values to set to bad
+  @return cpl_mask
+  @note as cpl only supports 32 bit integer images the top 32 bit of the
+        selection mask must be zero
+ */
+/*----------------------------------------------------------------------------*/
+cpl_mask * hdrl_bpm_to_mask(const cpl_image * bpm, uint64_t selection)
+{
+    cpl_ensure(bpm, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(cpl_image_get_type(bpm) == CPL_TYPE_INT,
+               CPL_ERROR_ILLEGAL_INPUT, NULL);
+    /* cpl currently only has int images, but use 64 for forward compat */
+    cpl_ensure(selection <= CX_MAXUINT, CPL_ERROR_UNSUPPORTED_MODE, NULL);
+    unsigned int iselection = (unsigned int)selection;
+    const unsigned int * data=(unsigned int *)cpl_image_get_data_int_const(bpm);
+    const size_t nx = cpl_image_get_size_x(bpm);
+    const size_t ny = cpl_image_get_size_y(bpm);
+    cpl_mask * msk = cpl_mask_new(nx, ny);
+    cpl_binary * dmsk = cpl_mask_get_data(msk);
+    for (size_t i = 0; i < ny * nx; i++) {
+        dmsk[i] = (data[i] & iselection) ? 1 : 0;
+    }
+    return msk;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief convert cpl_mask to bad pixel information mask
+  @param mask       cpl_mask to be converted
+  @param flag       bit-mask selecting which values to set the bad pixels to
+  @return integer cpl_image
+  @note as cpl only supports 32 bit integer images the top 32 bit of the
+        selection mask must be zero
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_mask_to_bpm(const cpl_mask * mask, uint64_t flag)
+{
+    cpl_ensure(mask, CPL_ERROR_NULL_INPUT, NULL);
+    /* cpl currently only has int images, but use 64 for forward compatibility */
+    cpl_ensure(flag <= CX_MAXUINT, CPL_ERROR_UNSUPPORTED_MODE, NULL);
+    unsigned int iflag = (unsigned int)flag;
+    const size_t nx = cpl_mask_get_size_x(mask);
+    const size_t ny = cpl_mask_get_size_y(mask);
+    cpl_image * bpm = cpl_image_new(nx, ny, CPL_TYPE_INT);
+    const cpl_binary * dmsk = cpl_mask_get_data_const(mask);
+    unsigned int * data = (unsigned int *)cpl_image_get_data_int(bpm);
+    for (size_t i = 0; i < ny * nx; i++) {
+        data[i] = dmsk[i] ? iflag : 0;
+    }
+    return bpm;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief apply array of masks to an image list
+  @param list  image list where the masks should be applied
+  @param masks array of masks, must have same length as the image list
+ 
+  already existing masks will be overwritten
+  can be used to re-apply the original mask array returned by
+  hdrl_join_mask_on_imagelist
+
+  Example:\code{.c}
+  cpl_mask ** orig_masks;
+  // change mask to get partial statistics from the list
+  hdrl_join_mask_on_imagelist(list, echelle_mask, &orig_masks);
+  stats = get_stats_from_echelle_orders();
+  // restore original mask
+  hdrl_set_masks_on_imagelist(list, orig_masks);
+  // free memory
+  for (i = 0; i < cpl_imagelist_get_size(list); i++) {
+    cpl_mask_free(orig_masks[i]);
+  }
+  cpl_free(orig_masks);
+  \endcode
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_set_masks_on_imagelist(
+        cpl_imagelist   *   list, 
+        cpl_mask        **  masks)
+{
+    cpl_ensure_code(list, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(masks, CPL_ERROR_NULL_INPUT);
+
+    for (size_t i = 0; i < (size_t)cpl_imagelist_get_size(list); i++) {
+        cpl_image * img = cpl_imagelist_get(list, i);
+        cpl_mask * img_mask = cpl_image_get_bpm(img);
+        /* zero mask */
+        cpl_mask_xor(img_mask, img_mask);
+        /* add new mask */
+        cpl_mask_or(img_mask, masks[i]);
+    }
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief join mask with existing masks in an imagelist
+  @param list      imagelist where the new mask should be joined on
+  @param new_mask  new mask joined with the masks in the images
+  @param pold_mask pointer to array pointer to store a copy of the original
+                   masks, array and masks contained in it must be deleted by
+                   the user, may be NULL in which case no copy is stored
+  @see hdrl_set_masks_on_imagelist
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_join_mask_on_imagelist(
+        cpl_imagelist   *   list, 
+        cpl_mask        *   new_mask,
+        cpl_mask        *** pold_mask)
+{
+    cpl_ensure_code(list, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(new_mask, CPL_ERROR_NULL_INPUT);
+
+    if (pold_mask) {
+        *pold_mask = cpl_malloc(sizeof(*pold_mask) *
+                                cpl_imagelist_get_size(list));
+    }
+
+    for (size_t i = 0; i < (size_t)cpl_imagelist_get_size(list); i++) {
+        cpl_image * img = cpl_imagelist_get(list, i);
+        cpl_mask * img_mask = cpl_image_get_bpm(img);
+        if (pold_mask) {
+            (*pold_mask)[i] = cpl_mask_duplicate(img_mask);
+        }
+
+        cpl_mask_or(img_mask, new_mask);
+    }
+    return cpl_error_get_code();
+}
+
+/**@}*/
+
diff --git a/hdrl/hdrl_bpm_utils.h b/hdrl/hdrl_bpm_utils.h
new file mode 100644
index 0000000..f4a7313
--- /dev/null
+++ b/hdrl/hdrl_bpm_utils.h
@@ -0,0 +1,56 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_BPM_UTILS_H
+#define HDRL_BPM_UTILS_H
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include <cpl.h>
+#include <stdint.h>
+#include "hdrl_image.h"
+#include "hdrl_imagelist.h"
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                            Functions prototypes
+ -----------------------------------------------------------------------------*/
+
+cpl_mask * hdrl_bpm_filter(const cpl_mask *, cpl_size, cpl_size, cpl_filter_mode) ;
+cpl_imagelist * hdrl_bpm_filter_list(const cpl_imagelist *, cpl_size, cpl_size,
+        cpl_filter_mode) ;
+
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+ -----------------------------------------------------------------------------*/
+
+#ifdef HDRL_USE_PRIVATE
+cpl_mask * hdrl_bpm_to_mask(const cpl_image *, uint64_t) ;
+cpl_image * hdrl_mask_to_bpm(const cpl_mask *, uint64_t) ;
+cpl_error_code hdrl_set_masks_on_imagelist(cpl_imagelist *, cpl_mask **) ;
+cpl_error_code hdrl_join_mask_on_imagelist(cpl_imagelist *, cpl_mask *, 
+        cpl_mask ***);
+#endif
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_buffer.c b/hdrl/hdrl_buffer.c
new file mode 100644
index 0000000..20510c7
--- /dev/null
+++ b/hdrl/hdrl_buffer.c
@@ -0,0 +1,331 @@
+/* $Id: hdrl_buffer.c,v 1.1 2013-10-23 09:13:56 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-23 09:13:56 $
+ * $Revision: 1.1 $
+ * $Name: not supported by cvs2svn $
+ */
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+ -----------------------------------------------------------------------------*/
+
+#ifndef _POSIX_C_SOURCE
+#define _POSIX_C_SOURCE 200112L /* posix_fallocate, ftruncate */
+/* posix 2001 not enough for ftruncate on glibc 2.12 (SL6.3) */
+#define _XOPEN_SOURCE 600
+#endif
+#include "hdrl_buffer.h"
+#include "hdrl_types.h"
+#include "hdrl_utils.h"
+
+#include <cpl.h>
+#include <cxlist.h>
+
+#include <unistd.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <sys/mman.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#include <string.h>
+
+/*-----------------------------------------------------------------------------
+                                   Functions
+ -----------------------------------------------------------------------------*/
+
+static int hdrl_fallocate(int fd, off_t offset, off_t len)
+{
+#ifdef __APPLE__
+    /* could be improved via fcntl(fd, F_PREALLOCATE, ...); */
+    return ftruncate(fd, offset + len);
+#else
+    return posix_fallocate(fd, offset, len);
+#endif
+}
+
+static const size_t hdrl_pool_minsize = 2<<20;
+
+struct _hdrl_buffer_ {
+    cx_list * pools;
+    cx_list * freelist;
+    size_t pool_size;
+    size_t total_size;
+    size_t malloc_thresh;
+};
+
+typedef struct {
+    char * base;
+    char * free_offset;
+    size_t size;
+    hdrl_free * destructor;
+} hdrl_pool_base;
+
+typedef struct {
+    hdrl_pool_base p;
+    int fd;
+} hdrl_pool_mmap;
+
+typedef struct {
+    hdrl_pool_base p;
+} hdrl_pool_malloc;
+
+typedef hdrl_pool_base hdrl_pool;
+
+static void hdrl_pool_mmap_delete(void * pool)
+{
+    if (!pool)
+        return;
+    hdrl_pool_mmap * p = pool;
+    /* truncate temp file to stop writeback of dirty pages */
+    if (ftruncate(p->fd, 0)) {}
+    munmap(p->p.base, p->p.size);
+    close(p->fd);
+}
+
+static hdrl_pool * hdrl_pool_mmap_new(size_t pool_size)
+{
+    hdrl_pool_mmap * pool = cpl_malloc(sizeof(*pool));
+    pool_size = CX_MAX(pool_size, hdrl_pool_minsize);
+    pool->p.destructor = &hdrl_pool_mmap_delete;
+
+    /* try TMPDIR first as it usually is a fast disk */
+    pool->fd = hdrl_get_tempfile(NULL, CPL_TRUE);
+    int err = hdrl_fallocate(pool->fd, 0, pool_size);
+    if (err != 0) {
+        char * cwd = hdrl_get_cwd();
+        /* TODO: move min size logic into get_tempfile? */
+        cpl_msg_info(cpl_func, "Not enough free disk space in TMPDIR, "
+                     "trying current working directory %s", cwd);
+        close(pool->fd);
+        pool->fd = hdrl_get_tempfile(cwd, CPL_TRUE);
+        cpl_free(cwd);
+        err = hdrl_fallocate(pool->fd, 0, pool_size);
+        if (err != 0) {
+            close(pool->fd);
+            cpl_free(pool);
+            cpl_error_set_message(cpl_func, CPL_ERROR_FILE_IO,
+                                  "Allocation of %zu bytes failed: %s, "
+                                  "try changing TMPDIR", pool_size,
+                                  strerror(err));
+            return NULL;
+        }
+    }
+
+    pool->p.base = mmap(NULL, pool_size, PROT_READ | PROT_WRITE, MAP_SHARED,
+                      pool->fd, 0);
+    if (pool->p.base == MAP_FAILED) {
+        close(pool->fd);
+        cpl_free(pool);
+        cpl_error_set_message(cpl_func, CPL_ERROR_FILE_IO,
+                              "Allocation of %zu bytes failed", pool_size);
+        return NULL;
+    }
+    pool->p.size = pool_size;
+    pool->p.free_offset = pool->p.base;
+    cpl_msg_debug(cpl_func, "Creating mmap pool %p of size %zu",
+                  pool, pool_size);
+    return (hdrl_pool*)pool;
+}
+
+static void hdrl_pool_malloc_delete(void * pool)
+{
+    if (!pool)
+        return;
+    cpl_free(((hdrl_pool*)pool)->base);
+}
+
+static hdrl_pool * hdrl_pool_malloc_new(size_t pool_size)
+{
+    hdrl_pool_mmap * pool = cpl_malloc(sizeof(*pool));
+    pool->p.size = CX_MAX(pool_size, hdrl_pool_minsize);
+    pool->p.destructor = &hdrl_pool_malloc_delete;
+
+    pool->p.base = cpl_malloc(pool_size);
+    pool->p.free_offset = pool->p.base;
+    cpl_msg_debug(cpl_func, "Creating malloc pool %p of size %zu",
+                  pool, pool_size);
+    return (hdrl_pool*)pool;
+}
+
+static void hdrl_pool_delete(hdrl_pool * pool)
+{
+    if (!pool) {
+        return;
+    }
+
+    cpl_msg_debug(cpl_func, "Deleting pool %p", pool);
+    pool->destructor(pool);
+    cpl_free(pool);
+}
+
+static size_t hdrl_pool_available(hdrl_pool * p)
+{
+    return (p->base + p->size - p->free_offset);
+}
+
+static char * hdrl_pool_alloc(hdrl_pool * p, size_t n)
+{
+    if (hdrl_pool_available(p) < n) {
+        return NULL;
+    }
+    char * b = p->free_offset;
+    p->free_offset += n;
+    cpl_msg_debug(cpl_func, "Allocating %zu from pool of size %zu (%zu)",
+                  n, p->size, hdrl_pool_available(p));
+    return b;
+}
+
+static hdrl_pool * hdrl_pool_get_from_ptr(char * HDRL_UNUSED(p))
+{
+    return NULL;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief Create buffer object
+ * @param pool_size  size of each memory pool
+ * @return buffer object useable to obtain memory mapped memory
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_buffer * hdrl_buffer_new(void)
+{
+    /* TODO pool_size probably does not need to be in api */
+    hdrl_buffer * buf = cpl_malloc(sizeof(*buf));
+    buf->pools = cx_list_new();
+    buf->freelist = cx_list_new();
+    buf->pool_size = 128ul * (1ul << 20ul);
+    buf->total_size = 0;
+    buf->malloc_thresh = 0;
+
+    return buf;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief set total amount of memory the buffer can malloc
+ *
+ * @param buf  buffer object
+ * @param t    amount of memory in MiB
+ *
+ * @return old amount in wMiB
+ * @note changing threshold will only affect future allocation
+ */
+/* ---------------------------------------------------------------------------*/
+size_t hdrl_buffer_set_malloc_threshold(hdrl_buffer * buf, size_t t)
+{
+    size_t o = buf->malloc_thresh;
+    buf->malloc_thresh = t * (1ul << 20ul);
+    return o;
+}
+
+void hdrl_buffer_readonly(hdrl_buffer * buf, cpl_boolean ro)
+{
+    /* TODO page alignment for malloc pool */
+    for (cx_list_iterator it = cx_list_begin(buf->pools);
+         it != cx_list_end(buf->pools);
+         it = cx_list_next(buf->pools, it)) {
+        hdrl_pool * pool = cx_list_get(buf->pools, it);
+        if (ro) {
+            mprotect(pool->base, pool->size, PROT_READ);
+        }
+        else {
+            mprotect(pool->base, pool->size, PROT_READ | PROT_WRITE);
+        }
+    }
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief Allocate memory block from buffer
+ *
+ * @param buf  buffer object
+ * @param size size of memory to allocate
+ *
+ * @return writable memory block, or NULL on failure
+ */
+/* ---------------------------------------------------------------------------*/
+char * hdrl_buffer_allocate(hdrl_buffer * buf, size_t size)
+{
+    hdrl_pool * p = NULL;
+    char * m;
+    for (cx_list_iterator it = cx_list_begin(buf->freelist);
+         it != cx_list_end(buf->freelist);
+         it = cx_list_next(buf->freelist, it)) {
+       hdrl_pool * _p = cx_list_get(buf->freelist, it);
+       if (hdrl_pool_available(_p) >= size) {
+           p = _p;
+           cpl_msg_debug(cpl_func, "Found free available in pool.");
+           break;
+       }
+    }
+
+    if (p == NULL) {
+        /* no free pool, clear freelist (TODO clear full pools earlier) */
+        cx_list_empty(buf->freelist);
+        if (buf->total_size + size < buf->malloc_thresh ||
+            getenv("HDRL_BUFFER_MALLOC")) {
+            p = hdrl_pool_malloc_new(CX_MAX(size, buf->pool_size));
+        }
+        else {
+            p = hdrl_pool_mmap_new(CX_MAX(size, buf->pool_size));
+        }
+        cx_list_push_back(buf->pools, p);
+        /* add new pool to freelist if it has free available left */
+        if (size < buf->pool_size / 2) {
+            cx_list_push_back(buf->freelist, p);
+        }
+    }
+
+    m = hdrl_pool_alloc(p, size);
+    buf->total_size += size;
+    return m;
+}
+
+void hdrl_buffer_free(hdrl_buffer * HDRL_UNUSED(buf), char * p)
+{
+    hdrl_pool * pool = hdrl_pool_get_from_ptr(p);
+    if (pool) {}
+    /* TODO add free, only from top of pool should be simple,
+     * MADV_DONTNEED may be enough */
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief delete buffer
+ * @param buf buffer
+ *
+ * Invalidates memory of all objects contained in the buffer
+ */
+/* ---------------------------------------------------------------------------*/
+void hdrl_buffer_delete(hdrl_buffer * buf)
+{
+    if (!buf) {
+        return;
+    }
+
+    cpl_msg_debug(cpl_func, "Deleting buffer with %zu pools",
+                  cx_list_size(buf->pools));
+    cx_list_destroy(buf->pools, (hdrl_free*)&hdrl_pool_delete);
+    cx_list_delete(buf->freelist);
+    cpl_free(buf);
+}
diff --git a/hdrl/hdrl_buffer.h b/hdrl/hdrl_buffer.h
new file mode 100644
index 0000000..f34183f
--- /dev/null
+++ b/hdrl/hdrl_buffer.h
@@ -0,0 +1,51 @@
+/* $Id: hdrl_buffer.h,v 1.2 2013-10-23 09:42:14 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-23 09:42:14 $
+ * $Revision: 1.2 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifndef HDRL_BUFFER_H
+#define HDRL_BUFFER_H
+
+#include <cpl.h>
+#include <stddef.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+  Experimental declarations - can be used, but no guarantees on api stability
+ -----------------------------------------------------------------------------*/
+#if defined HDRL_USE_EXPERIMENTAL || defined HDRL_USE_PRIVATE
+typedef struct _hdrl_buffer_ hdrl_buffer;
+
+hdrl_buffer * hdrl_buffer_new(void);
+size_t hdrl_buffer_set_malloc_threshold(hdrl_buffer * buf, size_t t);
+char * hdrl_buffer_allocate(hdrl_buffer *, size_t);
+void hdrl_buffer_free(hdrl_buffer *, char *);
+void hdrl_buffer_delete(hdrl_buffer *);
+#endif
+
+CPL_END_DECLS
+
+#endif 
diff --git a/hdrl/hdrl_collapse.c b/hdrl/hdrl_collapse.c
new file mode 100644
index 0000000..c9d8630
--- /dev/null
+++ b/hdrl/hdrl_collapse.c
@@ -0,0 +1,1991 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+-----------------------------------------------------------------------------*/
+
+#include "hdrl_collapse.h"
+#include "hdrl_parameter.h"
+#include "hdrl_parameter_defs.h"
+#include "hdrl_sigclip.h"
+#include "hdrl_utils.h"
+#include "hdrl_types.h"
+#include <cpl.h>
+
+#include <string.h>
+#include <math.h>
+/*-----------------------------------------------------------------------------
+                                   Types
+-----------------------------------------------------------------------------*/
+
+/* function performing imglist -> image reduction */
+typedef cpl_error_code (hdrl_collapse_imagelist_to_image_f)(
+    const cpl_imagelist * data,
+    const cpl_imagelist * errors,
+    cpl_image ** out,
+    cpl_image ** err,
+    cpl_image ** contrib,
+    void * parameters,
+    void * extra_out);
+
+struct hdrl_collapse_imagelist_to_image_s {
+    /* function performing imglist -> image reduction */
+    hdrl_collapse_imagelist_to_image_f * func;
+    /* create extra out storage */
+    void * (*create_eout)(const cpl_image *);
+    /* move extra out storage */
+    cpl_error_code (*move_eout)(void *, void *, const cpl_size);
+    /* unwrap extra out storage */
+    hdrl_free * unwrap_eout;
+    /* parameters the reduction function requires */
+    hdrl_parameter * parameters;
+};
+
+/* function performing imglist -> image reduction */
+typedef cpl_error_code (hdrl_collapse_imagelist_to_vector_f)(
+    const cpl_imagelist * data,
+    const cpl_imagelist * errors,
+    cpl_vector ** out,
+    cpl_vector ** err,
+    cpl_array ** contrib,
+    void * parameters,
+    void * extra_out);
+
+struct hdrl_collapse_imagelist_to_vector_s {
+    /* function performing imglist -> vector reduction */
+    hdrl_collapse_imagelist_to_vector_f * func;
+    /* create extra out storage */
+    void * (*create_eout)(cpl_size);
+    /* move extra out storage */
+    cpl_error_code (*move_eout)(void *, void *, const cpl_size);
+    /* unwrap extra out storage */
+    hdrl_free * unwrap_eout;
+    /* parameters the reduction function requires */
+    hdrl_parameter * parameters;
+};
+
+static cpl_error_code
+hdrl_collapse_mean(const cpl_imagelist * data,
+                   const cpl_imagelist * errors,
+                   cpl_image ** out, cpl_image ** err,
+                   cpl_image ** contrib, void * parameters,
+                   void * extra_out);
+static cpl_error_code
+hdrl_collapse_median(const cpl_imagelist * data,
+                     const cpl_imagelist * errors,
+                     cpl_image ** out, cpl_image ** err,
+                     cpl_image ** contrib, void * parameters,
+                     void * extra_out);
+static cpl_error_code
+hdrl_collapse_sigclip(const cpl_imagelist * data,
+                      const cpl_imagelist * errors,
+                      cpl_image ** out, cpl_image ** err,
+                      cpl_image ** contrib,void * parameters,
+                      void * extra_out);
+
+static cpl_error_code
+hdrl_collapse_minmax(const cpl_imagelist * data,
+                      const cpl_imagelist * errors,
+                      cpl_image ** out, cpl_image ** err,
+                      cpl_image ** contrib,void * parameters,
+                      void * extra_out);
+
+static cpl_error_code
+hdrl_collapse_weighted_mean(const cpl_imagelist * data_,
+                            const cpl_imagelist * errors_,
+                            cpl_image ** out, cpl_image ** err,
+                            cpl_image ** contrib, void * parameters,
+                            void * extra_out);
+
+/*-----------------------------------------------------------------------------
+                                   Static
+ -----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_collapse Collapse Parameters
+
+  This module provides collapse parameters to be used by hdrl_image and
+  hdrl_imagelist objects.
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+/** @cond PRIVATE */
+
+
+/*-----------------------------------------------------------------------------
+                            Collapse Parameters
+ -----------------------------------------------------------------------------*/
+static void hdrl_nop_free(void * HDRL_UNUSED(x))
+{
+    return;
+}
+
+static void * hdrl_mean_alloc(size_t n);
+static void * hdrl_median_alloc(size_t n);
+static void * hdrl_weighted_mean_alloc(size_t n);
+
+/* Mean COLLAPSE */
+typedef hdrl_parameter_empty hdrl_collapse_mean_parameter;
+static hdrl_parameter_typeobj hdrl_collapse_mean_parameter_type = {
+    HDRL_PARAMETER_COLLAPSE_MEAN,           /* type */
+    (hdrl_alloc *)&hdrl_mean_alloc,         /* fp_alloc */
+    (hdrl_free *)&hdrl_nop_free,            /* fp_free */
+    NULL,                                   /* fp_destroy */
+    sizeof(hdrl_collapse_mean_parameter),   /* obj_size */
+};
+
+HDRL_PARAMETER_SINGLETON(HDRL_COLLAPSE_MEAN, hdrl_collapse_mean_parameter_type,
+                         hdrl_mean_alloc);
+
+/* Median COLLAPSE */
+typedef hdrl_parameter_empty hdrl_collapse_median_parameter;
+static hdrl_parameter_typeobj hdrl_collapse_median_parameter_type = {
+    HDRL_PARAMETER_COLLAPSE_MEDIAN,         /* type */
+    (hdrl_alloc *)&hdrl_median_alloc,       /* fp_alloc */
+    (hdrl_free *)&hdrl_nop_free,            /* fp_free */
+    NULL,                                   /* fp_destroy */
+    sizeof(hdrl_collapse_median_parameter), /* obj_size */
+};
+
+HDRL_PARAMETER_SINGLETON(HDRL_COLLAPSE_MEDIAN,
+                         hdrl_collapse_median_parameter_type,
+                         hdrl_median_alloc);
+
+/* Weighted Mean COLLAPSE */
+typedef hdrl_parameter_empty hdrl_collapse_weighted_mean_parameter;
+static hdrl_parameter_typeobj hdrl_collapse_weighted_mean_parameter_type = {
+    HDRL_PARAMETER_COLLAPSE_WEIGHTED_MEAN,          /* type */
+    (hdrl_alloc *)&hdrl_weighted_mean_alloc,        /* fp_alloc */
+    (hdrl_free *)&hdrl_nop_free,                    /* fp_free */
+    NULL,                                           /* fp_destroy */
+    sizeof(hdrl_collapse_weighted_mean_parameter),  /* obj_size */
+};
+
+HDRL_PARAMETER_SINGLETON(HDRL_COLLAPSE_WEIGHTED_MEAN,
+                         hdrl_collapse_weighted_mean_parameter_type,
+                         hdrl_weighted_mean_alloc);
+
+/* Sigma-Clipping COLLAPSE */
+typedef struct {
+    HDRL_PARAMETER_HEAD;
+    double kappa_low;
+    double kappa_high;
+    int niter;
+} hdrl_collapse_sigclip_parameter;
+static hdrl_parameter_typeobj hdrl_collapse_sigclip_parameter_type = {
+    HDRL_PARAMETER_COLLAPSE_SIGCLIP,            /* type */
+    (hdrl_alloc *)&cpl_malloc,                  /* fp_alloc */
+    (hdrl_free *)&cpl_free,                     /* fp_free */
+    NULL,                                       /* fp_destroy */
+    sizeof(hdrl_collapse_sigclip_parameter),    /* obj_size */
+};
+
+
+/* Minmax-Clipping COLLAPSE */
+typedef struct {
+    HDRL_PARAMETER_HEAD;
+    double nlow;
+    double nhigh;
+} hdrl_collapse_minmax_parameter;
+static hdrl_parameter_typeobj hdrl_collapse_minmax_parameter_type = {
+    HDRL_PARAMETER_COLLAPSE_MINMAX,            /* type */
+    (hdrl_alloc *)&cpl_malloc,                 /* fp_alloc */
+    (hdrl_free *)&cpl_free,                    /* fp_free */
+    NULL,                                      /* fp_destroy */
+    sizeof(hdrl_collapse_minmax_parameter),    /* obj_size */
+};
+
+
+/** @endcond */
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create a parameter object for mean
+ * @return hdrl_parameter
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_collapse_mean_parameter_create(void)
+{
+    hdrl_parameter_empty * p = (hdrl_parameter_empty *)
+       hdrl_parameter_new(&hdrl_collapse_mean_parameter_type);
+    return (hdrl_parameter *)p;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief check if parameter is a mean parameter
+ * @return boolean
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_boolean hdrl_collapse_parameter_is_mean(const hdrl_parameter * self)
+{
+    return hdrl_parameter_check_type(self, &hdrl_collapse_mean_parameter_type);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create a parameter object for median
+ * @return hdrl_parameter
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_collapse_median_parameter_create(void)
+{
+    hdrl_parameter_empty * p = (hdrl_parameter_empty *)
+       hdrl_parameter_new(&hdrl_collapse_median_parameter_type);
+    return (hdrl_parameter *)p;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief check if parameter is a median parameter
+ * @return boolean
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_boolean hdrl_collapse_parameter_is_median(const hdrl_parameter * self)
+{
+    return hdrl_parameter_check_type(self, &hdrl_collapse_median_parameter_type);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create a parameter object for weighted mean
+ * @return hdrl_parameter
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_collapse_weighted_mean_parameter_create(void)
+{
+    hdrl_parameter_empty * p = (hdrl_parameter_empty *)
+       hdrl_parameter_new(&hdrl_collapse_weighted_mean_parameter_type);
+    return (hdrl_parameter *)p;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief check if parameter is a weighted mean parameter
+ * @return boolean
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_boolean hdrl_collapse_parameter_is_weighted_mean(
+        const hdrl_parameter * self)
+{
+    return hdrl_parameter_check_type(self, 
+            &hdrl_collapse_weighted_mean_parameter_type);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create a parameter object for sigclipped mean
+ *
+ * @param kappa_low   low kappa multiplier
+ * @param kappa_high  high kappa multiplier
+ * @param niter       maximum number of clipping iterations
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_parameter *
+hdrl_collapse_sigclip_parameter_create(double kappa_low, double kappa_high, int niter)
+{
+    hdrl_collapse_sigclip_parameter * p = (hdrl_collapse_sigclip_parameter *)
+       hdrl_parameter_new(&hdrl_collapse_sigclip_parameter_type);
+    p->kappa_low = kappa_low;
+    p->kappa_high = kappa_high;
+    p->niter = niter;
+
+    if (hdrl_collapse_sigclip_parameter_verify((hdrl_parameter*)p) !=
+        CPL_ERROR_NONE) {
+        hdrl_parameter_delete((hdrl_parameter*)p);
+        return NULL;
+    }
+    return (hdrl_parameter *)p;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief check if parameter is a sigclip mean parameter
+ * @return boolean
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_boolean hdrl_collapse_parameter_is_sigclip(const hdrl_parameter * self)
+{
+    return hdrl_parameter_check_type(self, 
+            &hdrl_collapse_sigclip_parameter_type);
+}
+
+/** @cond PRIVATE */
+
+/*----------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief    Verify basic correctness of the parameters
+  @param    param   Collapse siglip parameters
+  @return   CPL_ERROR_NONE if everything is ok, an error code otherwise
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_collapse_sigclip_parameter_verify(
+        const hdrl_parameter    *   param) 
+{
+    cpl_error_ensure(param != NULL, CPL_ERROR_NULL_INPUT,
+            return CPL_ERROR_NULL_INPUT,
+            "NULL Collapse Sigclip Parameters");
+
+    cpl_error_ensure(hdrl_collapse_parameter_is_sigclip(param),
+                     CPL_ERROR_INCOMPATIBLE_INPUT, return
+                     CPL_ERROR_INCOMPATIBLE_INPUT,
+                     "Not a Sigclip parameter");
+
+    const hdrl_collapse_sigclip_parameter * param_loc =
+            (hdrl_collapse_sigclip_parameter *)param ;
+
+    cpl_error_ensure(param_loc->niter >= 0, CPL_ERROR_ILLEGAL_INPUT,
+            return CPL_ERROR_ILLEGAL_INPUT,
+            "sigma-clipping iter (%d) value must be >= 0", 
+            param_loc->niter);
+
+    return CPL_ERROR_NONE ;
+}
+
+/** @endcond */
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get low kappa
+ * @param p  parameter
+ * @return kappa_low if p is of sigclip type
+ */
+/* ---------------------------------------------------------------------------*/
+double hdrl_collapse_sigclip_parameter_get_kappa_high(const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    cpl_ensure(hdrl_collapse_parameter_is_sigclip(p), 
+            CPL_ERROR_INCOMPATIBLE_INPUT, -1);
+
+    return ((hdrl_collapse_sigclip_parameter *)p)->kappa_high;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get high kappa
+ * @param p  parameter
+ * @return kappa_high if p is of sigclip type
+ */
+/* ---------------------------------------------------------------------------*/
+double hdrl_collapse_sigclip_parameter_get_kappa_low(const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    cpl_ensure(hdrl_collapse_parameter_is_sigclip(p), 
+            CPL_ERROR_INCOMPATIBLE_INPUT, -1);
+
+    return ((hdrl_collapse_sigclip_parameter *)p)->kappa_low;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get maximum number of clipping iterations
+ * @param p  parameter
+ * @return n if p is of sigclip type
+ */
+/* ---------------------------------------------------------------------------*/
+int hdrl_collapse_sigclip_parameter_get_niter(const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    cpl_ensure(hdrl_collapse_parameter_is_sigclip(p), 
+            CPL_ERROR_INCOMPATIBLE_INPUT, -1);
+
+    return ((hdrl_collapse_sigclip_parameter *)p)->niter;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create a parameter object for min-max rejected mean
+ *
+ * @param nlow  number of low pixels to be rejected
+ * @param nhigh  number of high pixels to be rejected
+ * @return minmax collapse parameter or NULL on error
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_parameter *
+hdrl_collapse_minmax_parameter_create(double nlow, double nhigh)
+{
+    hdrl_collapse_minmax_parameter * p = (hdrl_collapse_minmax_parameter *)
+       hdrl_parameter_new(&hdrl_collapse_minmax_parameter_type);
+    p->nlow = nlow;
+    p->nhigh = nhigh;
+
+    if (hdrl_collapse_minmax_parameter_verify((hdrl_parameter*)p) !=
+        CPL_ERROR_NONE) {
+        hdrl_parameter_delete((hdrl_parameter*)p);
+        return NULL;
+    }
+    return (hdrl_parameter *)p;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief check if parameter is a minmax mean parameter
+ * @return boolean
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_boolean hdrl_collapse_parameter_is_minmax(const hdrl_parameter * self)
+{
+    return hdrl_parameter_check_type(self,
+            &hdrl_collapse_minmax_parameter_type);
+}
+
+/** @cond PRIVATE */
+
+/*----------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief    Verify basic correctness of the parameters
+  @param    param   Collapse minmax parameters
+  @return   CPL_ERROR_NONE if everything is ok, an error code otherwise
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_collapse_minmax_parameter_verify(
+        const hdrl_parameter    *   param)
+{
+
+    cpl_error_ensure(param != NULL, CPL_ERROR_NULL_INPUT,
+                     return CPL_ERROR_NULL_INPUT,
+                     "NULL Collapse Minmax Parameters");
+
+    cpl_error_ensure(hdrl_collapse_parameter_is_minmax(param),
+                     CPL_ERROR_INCOMPATIBLE_INPUT, return
+                     CPL_ERROR_INCOMPATIBLE_INPUT,
+                     "Not a minmax parameter");
+
+    const hdrl_collapse_minmax_parameter * param_loc =
+            (hdrl_collapse_minmax_parameter *)param ;
+
+    cpl_error_ensure(param_loc->nlow >= 0, CPL_ERROR_ILLEGAL_INPUT,
+            return CPL_ERROR_ILLEGAL_INPUT,
+            "nlow value (%g) must be >= 0",
+            param_loc->nlow);
+
+    cpl_error_ensure(param_loc->nhigh >= 0, CPL_ERROR_ILLEGAL_INPUT,
+            return CPL_ERROR_ILLEGAL_INPUT,
+            "nhigh value (%g) must be >= 0",
+            param_loc->nlow);
+
+    return CPL_ERROR_NONE ;
+}
+
+/** @endcond */
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get low value
+ * @param p  parameter
+ * @return nlow if p is of minmax type
+ */
+/* ---------------------------------------------------------------------------*/
+double hdrl_collapse_minmax_parameter_get_nhigh(const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    cpl_ensure(hdrl_collapse_parameter_is_minmax(p),
+            CPL_ERROR_INCOMPATIBLE_INPUT, -1);
+
+    return ((hdrl_collapse_minmax_parameter *)p)->nhigh;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get high value
+ * @param p  parameter
+ * @return nhigh if p is of minmax type
+ */
+/* ---------------------------------------------------------------------------*/
+double hdrl_collapse_minmax_parameter_get_nlow(const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    cpl_ensure(hdrl_collapse_parameter_is_minmax(p),
+            CPL_ERROR_INCOMPATIBLE_INPUT, -1);
+
+    return ((hdrl_collapse_minmax_parameter *)p)->nlow;
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+  @brief Create parameters for the collapse
+  @param base_context    base context of parameter (e.g. recipe name)
+  @param prefix          prefix of parameter, may be empty string
+  @param method_def      default collapse method
+  @param sigclip_def     default sigclip parameters
+  @param minmax_def      default minmax parameters
+  @return The created parameter list
+  Creates a parameterlist containing
+      base_context.prefix.method
+      base_context.prefix.sigclip.*
+  The CLI aliases omit the base_context.
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_parameterlist * hdrl_collapse_parameter_create_parlist(
+        const char      *   base_context,
+        const char      *   prefix,
+        const char      *   method_def,
+        hdrl_parameter  *   sigclip_def,
+        hdrl_parameter  *   minmax_def)
+{
+    cpl_ensure(base_context && prefix, CPL_ERROR_NULL_INPUT, NULL);
+    char                *   name ;
+    cpl_parameterlist   *   parlist = cpl_parameterlist_new();
+    cpl_parameter       *   p ;
+    char                *   context = hdrl_join_string(".", 2, base_context, prefix);
+
+    /* --prefix.method */
+    name = hdrl_join_string(".", 2, context, "method");
+    p = cpl_parameter_new_enum(name, CPL_TYPE_STRING, 
+            "Method used for collapsing the data", context,
+            method_def, 5, "MEAN", "WEIGHTED_MEAN", "MEDIAN", "SIGCLIP",
+            "MINMAX");
+    cpl_free(name) ;
+    name = hdrl_join_string(".", 2, prefix, "method");
+    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, name);
+    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
+    cpl_free(name) ;
+    cpl_parameterlist_append(parlist, p);
+
+    /* --prefix.sigclip.xxx */
+    name = hdrl_join_string(".", 2, prefix, "sigclip");
+    cpl_parameterlist * psigclip = hdrl_sigclip_parameter_create_parlist(
+            base_context, name, sigclip_def);
+    cpl_free(name) ;
+
+    for (cpl_parameter * par = cpl_parameterlist_get_first(psigclip);
+         par != NULL;
+         par = cpl_parameterlist_get_next(psigclip)) {
+        cpl_parameterlist_append(parlist, cpl_parameter_duplicate(par));
+    }
+    cpl_parameterlist_delete(psigclip);
+
+
+
+    /* --prefix.minmax.xxx */
+    name = hdrl_join_string(".", 2, prefix, "minmax");
+    cpl_parameterlist * pminmax = hdrl_minmax_parameter_create_parlist(
+            base_context, name, minmax_def);
+    cpl_free(name) ;
+
+
+    for (cpl_parameter * par = cpl_parameterlist_get_first(pminmax);
+         par != NULL;
+         par = cpl_parameterlist_get_next(pminmax)) {
+        cpl_parameterlist_append(parlist, cpl_parameter_duplicate(par));
+    }
+    cpl_parameterlist_delete(pminmax);
+
+
+    cpl_free(context);
+
+    if (cpl_error_get_code()) {
+        cpl_parameterlist_delete(parlist);
+        return NULL;
+    }
+
+    return parlist;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+  @brief parse parameterlist for imagelist reduction method
+  @param parlist    parameter list to parse
+  @param prefix     prefix of parameter name
+  @return hdrl_parameter 
+  Reads a Parameterlist in order to create collapse parameters.
+  Expects a parameterlist containing
+      prefix.method
+      prefix.sigclip.*
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_collapse_parameter_parse_parlist(
+        const cpl_parameterlist     *   parlist,
+        const char                  *   prefix)
+{
+    cpl_ensure(prefix && parlist, CPL_ERROR_NULL_INPUT, NULL);
+    hdrl_parameter * p = NULL;
+
+    /* Get the Method parameter */
+    char * name = hdrl_join_string(".", 2, prefix, "method");
+    const cpl_parameter * par = cpl_parameterlist_find_const(parlist, name);
+    const char          * value = cpl_parameter_get_string(par);
+    if (value == NULL) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                              "Parameter %s not found", name);
+        cpl_free(name);
+        return NULL;
+    }
+    
+    /* Switch on the methods */
+    if(!strcmp(value, "MEDIAN")) {
+        p = hdrl_collapse_median_parameter_create();
+    } else if (!strcmp(value, "WEIGHTED_MEAN")) {
+        p = hdrl_collapse_weighted_mean_parameter_create();
+    } else if (!strcmp(value, "MEAN")) {
+        p = hdrl_collapse_mean_parameter_create();
+    } else if (!strcmp(value, "SIGCLIP")) {
+        double kappa_low, kappa_high;
+        int niter;
+        hdrl_sigclip_parameter_parse_parlist(parlist, prefix, &kappa_low, 
+                &kappa_high, &niter);
+        p = hdrl_collapse_sigclip_parameter_create(kappa_low,kappa_high,niter);
+    } else if (!strcmp(value, "MINMAX")) {
+        double nlow, nhigh;
+        hdrl_minmax_parameter_parse_parlist(parlist, prefix, &nlow,
+                &nhigh);
+        p = hdrl_collapse_minmax_parameter_create(nlow,nhigh);
+    } else {
+        cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_INPUT,
+                "%s not a valid method for %s", value, name);
+        cpl_free(name);
+        return NULL;
+    }
+    cpl_free(name);
+    return p;
+}
+
+/** @cond PRIVATE */
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create a new imagelist wrapping errors with same bpm as data
+ *
+ * @param data   data list
+ * @param errors error list
+ * @returns cpl_imagelist which needs deleted with unwrap_synced_errlist
+ *
+ * Creates a new imagelist containing the wrapped data from the error list but
+ * the bad pixel map from the data list.
+ * This avoids issues with desynchronized bad pixel maps and avoids modifiying
+ * the inputs for collapse operations.
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_imagelist *
+wrap_synced_errlist(const cpl_imagelist * data, const cpl_imagelist * errors)
+{
+
+    cpl_imagelist * nerrors = cpl_imagelist_new();
+    for (size_t i = 0; i < (size_t)cpl_imagelist_get_size(errors); i++) {
+        const cpl_image * img = cpl_imagelist_get_const(data, i);
+        const cpl_image * err = cpl_imagelist_get_const(errors, i);
+        cpl_image * nerr = cpl_image_wrap(cpl_image_get_size_x(err),
+                                          cpl_image_get_size_y(err),
+                                          cpl_image_get_type(err),
+                                          (void*)cpl_image_get_data_const(err));
+        cpl_mask_delete(hcpl_image_set_bpm(nerr,
+                                  (cpl_mask*)cpl_image_get_bpm_const(img)));
+        cpl_imagelist_set(nerrors, nerr, i);
+    }
+    return nerrors;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief unwrap imagelist created with wrap_synced_errlist
+ *
+ * @param nerrors  imagelist from wrap_synced_errlist
+ */
+/* ---------------------------------------------------------------------------*/
+static void
+unwrap_synced_errlist(cpl_imagelist * nerrors)
+{
+    for (size_t i = 0; i < (size_t)cpl_imagelist_get_size(nerrors); i++) {
+        cpl_image * err = (cpl_image*)cpl_imagelist_get_const(nerrors, i);
+
+        cpl_image_unset_bpm(err);
+        cpl_image_unwrap(err);
+    }
+    cpl_imagelist_unwrap(nerrors);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief calculate sum of squares of an imagelist
+  @param data     imagelist
+  @param contrib  if not NULL contribution map of reduction is stored
+  @return image containing the sum of squares along the imagelist axis
+  equivalent to:
+    cpl_imagelist_power(data, 2.)
+    sqlist = cpl_imagelist_collapse_create(data)
+    cpl_image_multiply(sqlist, contrib);
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_image * imagelist_sqsum(
+        const cpl_imagelist     *   data, 
+        cpl_image               **  pcontrib)
+{
+    cpl_image * contrib = cpl_image_new_from_accepted(data);
+    cpl_image * res = NULL;
+
+    for (cpl_size i = 0; i < cpl_imagelist_get_size(data); i++) {
+        const cpl_image * img = cpl_imagelist_get_const(data, i);
+        cpl_image * sqerr = cpl_image_multiply_create(img, img);
+        if (cpl_image_get_bpm_const(sqerr)) {
+            cpl_image_fill_rejected(sqerr, 0.0);
+            cpl_image_accept_all(sqerr);
+        }
+
+        if (i == 0) {
+            res = sqerr;
+        } else {
+            cpl_image_add(res, sqerr);
+            cpl_image_delete(sqerr);
+        }
+    }
+    cpl_mask * allbad = cpl_mask_threshold_image_create(contrib, 0, 0);
+    cpl_image_reject_from_mask(res, allbad);
+    cpl_mask_delete(allbad);
+
+    if (pcontrib)
+        *pcontrib = contrib;
+    else
+        cpl_image_delete(contrib);
+
+    return res;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief implements mean combination on input image list
+ *
+ * @param data    input data images
+ * @param errors  input errors images
+ * @param out     output combined images
+ * @param err     output combined errors
+ * @param contrib output contribution mask
+ * @param parameters parameters to control, not used
+ * @param extra_out  optional extra output, not used
+ *
+ *
+ * @return cpl_error_code
+ *
+ * @doc
+ * Mean and associated error are computed with standard formulae
+ *
+ * \f$
+ *   x_{mean}=\frac{(\sum_{i}^{n} x_{i})} { n }
+ * \f$
+ *
+ * \f$
+ *   \sigma_{x}=\sqrt{ \frac{ \sum_{i}^{n} x_{i}^{2} }{ n } }
+ * \f$
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code
+hdrl_collapse_mean(const cpl_imagelist * data,
+                             const cpl_imagelist * errors,
+                             cpl_image ** out, cpl_image ** err,
+                             cpl_image ** contrib,
+                             void * HDRL_UNUSED(parameters),
+                             void * HDRL_UNUSED(extra_out))
+{
+    /* (\Sum_i^n x_i) / n */
+    /* \sqrt(\Sum_i^n x_i^2) / n */
+    *out = cpl_imagelist_collapse_create(data);
+    *err = imagelist_sqsum(errors, contrib);
+    cpl_image_power(*err, 0.5);
+    cpl_image_divide(*err, *contrib);
+    cpl_image_fill_rejected(*out, NAN);
+    cpl_image_fill_rejected(*err, NAN);
+
+    return cpl_error_get_code();
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief implements weighted mean combination on input image list
+ *
+ * @param data    input data images
+ * @param errors_ input errors images
+ * @param out     output combined images
+ * @param err     output combined errors
+ * @param contrib output contribution mask
+ * @param parameters parameters to control, not used
+ * @param extra_out  optional extra output, not used
+ *
+ * @return cpl_error_code
+ *
+ * @doc
+ * weighted mean and associated error are computed with standard formulae
+ *
+ * \f$
+ *   x_{mean}=\frac{(\sum_{i}^{n} w_{i} \cdot x_{i})} { \sum_{i}^{n} w_{i} }
+ * \f$
+ *
+ * \f$
+ *   \sigma_{x}=\frac{ 1 } { \sqrt{  \sum_{i}^{n} w_{i}^{2} } }
+ * \f$
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code
+hdrl_collapse_weighted_mean(const cpl_imagelist * data_,
+                                      const cpl_imagelist * errors_,
+                                      cpl_image ** out, cpl_image ** err,
+                                      cpl_image ** contrib,
+                                      void * HDRL_UNUSED(parameters),
+                                      void * HDRL_UNUSED(extra_out))
+{
+    /* (\Sum_i^n w_i * x_i) / (\Sum_i^n w_i) */
+    /* 1 / \sqrt(\Sum_i^n w_i^2) */
+    cpl_imagelist * data = cpl_imagelist_duplicate(data_);
+    cpl_imagelist * errors = cpl_imagelist_new();
+    cpl_image * tmperr;
+    cpl_imagelist_cast(errors, errors_,
+                       cpl_image_get_type(cpl_imagelist_get(data, 0)));
+    *contrib = cpl_image_new_from_accepted(data);
+    cpl_imagelist_power(errors, -2);
+    cpl_imagelist_multiply(data, errors);
+    *out = cpl_imagelist_collapse_create(data);
+    tmperr = cpl_imagelist_collapse_create(errors);
+    cpl_imagelist_delete(data);
+    cpl_imagelist_delete(errors);
+    cpl_image_multiply(*out, *contrib);
+    cpl_image_multiply(tmperr, *contrib);
+    cpl_image_divide(*out, tmperr);
+    cpl_image_power(tmperr, -0.5);
+    if (cpl_image_get_type(cpl_imagelist_get_const(errors_, 0)) ==
+        cpl_image_get_type(cpl_imagelist_get_const(data_, 0))) {
+        *err = tmperr;
+    }
+    else {
+        *err = cpl_image_cast(tmperr,
+                  cpl_image_get_type(cpl_imagelist_get_const(errors_, 0)));
+        cpl_image_delete(tmperr);
+    }
+
+    cpl_image_fill_rejected(*out, NAN);
+    cpl_image_fill_rejected(*err, NAN);
+
+    return cpl_error_get_code();
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief implements median combination on input image list
+ *
+ * @param data    input data images
+ * @param errors  input errors images
+ * @param out     output combined images
+ * @param err     output combined errors
+ * @param contrib output contribution mask
+ * @param parameters parameters to control, not used
+ * @param extra_out  optional extra output, not used
+ *
+ * @return cpl_error_code
+ *
+ * @doc
+ * Median and associated error are computed similarly as for mean but
+ * scaling by \f$ \sqrt{ \frac{ \pi } { 2 } } \f$
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code
+hdrl_collapse_median(const cpl_imagelist * data,
+                               const cpl_imagelist * errors,
+                               cpl_image ** out, cpl_image ** err,
+                               cpl_image ** contrib,
+                               void * HDRL_UNUSED(parameters),
+                               void * HDRL_UNUSED(extra_out))
+{
+    /* same as mean with scaling by \sqrt(\pi / 2) */
+    *out = cpl_imagelist_collapse_median_create(data);
+    *err = imagelist_sqsum(errors, contrib);
+    cpl_image_power(*err, 0.5);
+    cpl_image_divide(*err, *contrib);
+    /* scale error so it estimates stdev of normal distribution */
+    cpl_image_multiply_scalar(*err, sqrt(CPL_MATH_PI_2));
+    /* revert scaling for contrib <= 2 as median == mean in this case */
+    cpl_image * tmp = cpl_image_cast(*contrib, CPL_TYPE_DOUBLE);
+    cpl_image_threshold(tmp, 2.1, 2.1,  1. / sqrt(CPL_MATH_PI_2), 1.);
+    cpl_image_multiply(*err, tmp);
+    cpl_image_delete(tmp);
+    cpl_image_fill_rejected(*out, NAN);
+    cpl_image_fill_rejected(*err, NAN);
+
+    return cpl_error_get_code();
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief implements sigma-clipped combination on input image list
+ *
+ * @param data    input data images
+ * @param errors  input errors images
+ * @param out     output combined images
+ * @param err     output combined errors
+ * @param contrib output contribution mask
+ * @param parameters parameters to control, not used
+ * @param extra_out  optional extra output, not used
+ *
+ * @return cpl_error_code
+ *
+ * @doc
+ * sigma-clipped mean and associated error, computed similarly as for mean but
+ * without taking the clipped values into account.
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code
+hdrl_collapse_sigclip(const cpl_imagelist * data,
+                      const cpl_imagelist * errors,
+                      cpl_image ** out, cpl_image ** err,
+                      cpl_image ** contrib, void * parameters,
+                      void * extra_out)
+{
+    /* same as mean but working on the not-clipped values only */
+    hdrl_collapse_sigclip_parameter * par = parameters;
+    hdrl_sigclip_image_output * eout =
+        (hdrl_sigclip_image_output *)extra_out;
+    cpl_ensure_code(par, CPL_ERROR_NULL_INPUT);
+    const cpl_image * img = cpl_imagelist_get_const(data, 0);
+    size_t nx = cpl_image_get_size_x(img);
+    size_t ny = cpl_image_get_size_y(img);
+    *out = cpl_image_new(nx, ny, HDRL_TYPE_DATA);
+    *err = cpl_image_new(nx, ny, HDRL_TYPE_ERROR);
+    *contrib = cpl_image_new(nx, ny, CPL_TYPE_INT);
+
+    /* sigmaclip along imagelist axis */
+    for (size_t y = 1; y < ny + 1; y++) {
+        cpl_vector * vdv[nx];
+        cpl_vector * vev[nx];
+        hdrl_imagelist_to_vector_row(data, y, vdv);
+        hdrl_imagelist_to_vector_row(errors, y, vev);
+        for (size_t x = 1; x < nx + 1; x++) {
+            cpl_vector * vd = vdv[x - 1];
+            cpl_vector * ve = vev[x - 1];
+            if (vd && ve) {
+                double m, e, rej_low, rej_high;
+                cpl_size naccepted;
+                hdrl_kappa_sigma_clip(vd, ve,
+                                     par->kappa_low, par->kappa_high,
+                                     par->niter, CPL_TRUE,
+                                     &m, &e, &naccepted,
+                                     &rej_low, &rej_high);
+                cpl_image_set(*out, x, y, m);
+                cpl_image_set(*err, x, y, e);
+                cpl_image_set(*contrib, x, y, naccepted);
+                if (eout) {
+                    cpl_image_set(eout->reject_low, x, y, rej_low);
+                    cpl_image_set(eout->reject_high, x, y, rej_high);
+                }
+            }
+            else {
+                cpl_image_set(*out, x, y, NAN);
+                cpl_image_set(*err, x, y, NAN);
+                cpl_image_reject(*out, x, y);
+                cpl_image_reject(*err, x, y);
+                cpl_image_set(*contrib, x, y, 0);
+                if (eout) {
+                    cpl_image_set(eout->reject_low, x, y, 0.);
+                    cpl_image_set(eout->reject_high, x, y, 0.);
+                }
+            }
+            cpl_vector_delete(vd);
+            cpl_vector_delete(ve);
+        }
+    }
+
+    return cpl_error_get_code();
+}
+
+
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief implements minmax-clipped combination on input image list
+ *
+ * @param data    input data images
+ * @param errors  input errors images
+ * @param out     output combined images
+ * @param err     output combined errors
+ * @param contrib output contribution mask
+ * @param parameters parameters to control, not used
+ * @param extra_out  optional extra output, not used
+ *
+ * @return cpl_error_code
+ *
+ * @doc minmax-clipped mean and associated error, computed similarly
+ * as for mean but without taking the clipped values into account
+ * 
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code
+hdrl_collapse_minmax(const cpl_imagelist * data,
+                     const cpl_imagelist * errors,
+                     cpl_image ** out, cpl_image ** err,
+                     cpl_image ** contrib, void * parameters,
+                     void * extra_out)
+{
+    /* same as mean but working on the not-clipped values only */
+    hdrl_collapse_minmax_parameter * par = parameters;
+    cpl_ensure_code(par, CPL_ERROR_NULL_INPUT);
+    hdrl_minmax_image_output * eout =
+        (hdrl_minmax_image_output *)extra_out;
+    const cpl_image * img = cpl_imagelist_get_const(data, 0);
+    size_t nx = cpl_image_get_size_x(img);
+    size_t ny = cpl_image_get_size_y(img);
+    *out = cpl_image_new(nx, ny, HDRL_TYPE_DATA);
+    *err = cpl_image_new(nx, ny, HDRL_TYPE_ERROR);
+    *contrib = cpl_image_new(nx, ny, CPL_TYPE_INT);
+
+    /* minmaxclip along imagelist axis */
+    for (size_t y = 1; y < ny + 1; y++) {
+        cpl_vector * vdv[nx];
+        cpl_vector * vev[nx];
+        hdrl_imagelist_to_vector_row(data, y, vdv);
+        hdrl_imagelist_to_vector_row(errors, y, vev);
+        for (size_t x = 1; x < nx + 1; x++) {
+            cpl_vector * vd = vdv[x - 1];
+            cpl_vector * ve = vev[x - 1];
+            if (vd && ve) {
+                double m, e, rej_low, rej_high;
+                cpl_size naccepted;
+                hdrl_minmax_clip(vd, ve,
+                                 par->nlow, par->nhigh, CPL_FALSE,
+                                 &m, &e, &naccepted,
+                                 &rej_low, &rej_high);
+                cpl_image_set(*out, x, y, m);
+                cpl_image_set(*err, x, y, e);
+                cpl_image_set(*contrib, x, y, naccepted);
+                if (eout) {
+                    cpl_image_set(eout->reject_low, x, y, rej_low);
+                    cpl_image_set(eout->reject_high, x, y, rej_high);
+                }
+            }
+            else {
+                cpl_image_set(*out, x, y, NAN);
+                cpl_image_set(*err, x, y, NAN);
+                cpl_image_reject(*out, x, y);
+                cpl_image_reject(*err, x, y);
+                cpl_image_set(*contrib, x, y, 0);
+                if (eout) {
+                    cpl_image_set(eout->reject_low, x, y, 0.);
+                    cpl_image_set(eout->reject_high, x, y, 0.);
+                }
+            }
+            cpl_vector_delete(vd);
+            cpl_vector_delete(ve);
+        }
+    }
+
+    return cpl_error_get_code();
+}
+
+static void *
+hdrl_nop_create_eout_vec(cpl_size HDRL_UNUSED(size))
+{
+    return NULL;
+}
+
+static void *
+hdrl_nop_create_eout_img(const cpl_image * HDRL_UNUSED(img))
+{
+    return NULL;
+}
+
+static cpl_error_code
+hdrl_nop_move_eout(void * HDRL_UNUSED(dst_),
+                   void * HDRL_UNUSED(src_), const cpl_size HDRL_UNUSED(y))
+{
+    return CPL_ERROR_NONE;
+}
+
+static void
+hdrl_nop_unwrap_eout(void * HDRL_UNUSED(dst))
+{
+    return;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief reduction object to reduce imagelist via mean
+ * @return mean reduction object
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_collapse_imagelist_to_image_t * 
+    hdrl_collapse_imagelist_to_image_mean(void)
+{
+    hdrl_collapse_imagelist_to_image_t * s = cpl_calloc(1, sizeof(*s));
+    s->func = &hdrl_collapse_mean;
+    s->create_eout = &hdrl_nop_create_eout_img;
+    s->move_eout = &hdrl_nop_move_eout;
+    s->unwrap_eout = &hdrl_nop_unwrap_eout;
+    return s;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief reduction object to reduce imagelist via weighted mean
+ * @return weighted mean reduction object
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_collapse_imagelist_to_image_t *
+    hdrl_collapse_imagelist_to_image_weighted_mean(void)
+{
+    hdrl_collapse_imagelist_to_image_t * s = cpl_calloc(1, sizeof(*s));
+    s->func = &hdrl_collapse_weighted_mean;
+    s->create_eout = &hdrl_nop_create_eout_img;
+    s->move_eout = &hdrl_nop_move_eout;
+    s->unwrap_eout = &hdrl_nop_unwrap_eout;
+    return s;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief reduction object to reduce imagelist via median
+ * @return median reduction object
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_collapse_imagelist_to_image_t *
+    hdrl_collapse_imagelist_to_image_median(void)
+{
+    hdrl_collapse_imagelist_to_image_t * s = cpl_calloc(1, sizeof(*s));
+    s->func = &hdrl_collapse_median;
+    s->create_eout = &hdrl_nop_create_eout_img;
+    s->move_eout = &hdrl_nop_move_eout;
+    s->unwrap_eout = &hdrl_nop_unwrap_eout;
+    return s;
+}
+
+static void *
+hdrl_sigclip_create_eout_img(const cpl_image * img)
+{
+    cpl_ensure(img, CPL_ERROR_NULL_INPUT, NULL);
+    hdrl_sigclip_image_output * eout = cpl_calloc(sizeof(*eout), 1);
+    eout->reject_low = cpl_image_new(cpl_image_get_size_x(img),
+                                     cpl_image_get_size_y(img),
+                                     cpl_image_get_type(img));
+    eout->reject_high = cpl_image_new(cpl_image_get_size_x(img),
+                                      cpl_image_get_size_y(img),
+                                      cpl_image_get_type(img));
+    /* add masks for thread safety on move */
+    cpl_image_get_bpm(eout->reject_low);
+    cpl_image_get_bpm(eout->reject_high);
+    return eout;
+}
+
+static cpl_error_code
+hdrl_sigclip_move_eout_img(void * dst_, void * src_, const cpl_size y)
+{
+    hdrl_sigclip_image_output * dst = dst_;
+    hdrl_sigclip_image_output * src = src_;
+    cpl_ensure_code(dst, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(src, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(y > 0, CPL_ERROR_ACCESS_OUT_OF_RANGE);
+    cpl_ensure_code(y <= cpl_image_get_size_y(dst->reject_low),
+                    CPL_ERROR_ACCESS_OUT_OF_RANGE);
+
+    cpl_image_copy(dst->reject_low, src->reject_low, 1, y);
+    cpl_image_copy(dst->reject_high, src->reject_high, 1, y);
+    cpl_image_delete(src->reject_low);
+    cpl_image_delete(src->reject_high);
+    cpl_free(src);
+    return cpl_error_get_code();
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief reduction object to reduce imagelist via kappa sigma clipped mean
+ *
+ * @param kappa_low  low sigma bound
+ * @param kappa_high high sigma bound
+ * @param niter      number of clipping iterators
+ *
+ * @return sigma clip reduction object
+ * @see  hdrl_kappa_sigma_clip()
+ *
+ * the high and low reject values are stored in extra_out if applicable
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_collapse_imagelist_to_image_t *
+hdrl_collapse_imagelist_to_image_sigclip(double kappa_low,
+                                       double kappa_high,
+                                       int niter)
+{
+    hdrl_collapse_imagelist_to_image_t * s = cpl_calloc(1, sizeof(*s));
+    hdrl_parameter * sp =
+        hdrl_collapse_sigclip_parameter_create(kappa_low, kappa_high, niter);
+    s->func = &hdrl_collapse_sigclip;
+    s->create_eout = &hdrl_sigclip_create_eout_img;
+    s->move_eout = &hdrl_sigclip_move_eout_img;
+    s->unwrap_eout = &cpl_free;
+    s->parameters = sp;
+    return s;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief reduction object to reduce imagelist via minmax clipped mean
+ *
+ * @param nlow  number of low pixel to reject
+ * @param nhigh number of high pixel to reject
+ *
+ * @return minmax cliped reduction object
+ * @see  hdrl_minmax_clip()
+ *
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_collapse_imagelist_to_image_t *
+hdrl_collapse_imagelist_to_image_minmax(double nlow,
+                                       double nhigh)
+{
+    hdrl_collapse_imagelist_to_image_t * s = cpl_calloc(1, sizeof(*s));
+    hdrl_parameter * sp =
+        hdrl_collapse_minmax_parameter_create(nlow, nhigh);
+    s->func = &hdrl_collapse_minmax;
+    s->create_eout = &hdrl_sigclip_create_eout_img;
+    s->move_eout = &hdrl_sigclip_move_eout_img;
+    s->unwrap_eout = &cpl_free;
+    s->parameters = sp;
+    return s;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief Call the associated reduction function
+ *
+ * @param f       reduction function object
+ * @param data    data to apply function on
+ * @param errors  errors to use for propagation
+ * @param out     pointer which will contain reduced data image, type double
+ * @param err     pointer which will contain reduced error image, type double
+ * @param contrib pointer which will contain contribution map, type integer
+ * @param eout    storage for extra output, may be NULL
+ *
+ * @return cpl_error_code
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_collapse_imagelist_to_image_call(hdrl_collapse_imagelist_to_image_t * f,
+                                    const cpl_imagelist * data,
+                                    const cpl_imagelist * errors,
+                                    cpl_image ** out,
+                                    cpl_image ** err,
+                                    cpl_image ** contrib,
+                                    void ** eout)
+{
+    cpl_ensure_code(f, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(data, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(errors, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(out, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(err, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(contrib, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(cpl_imagelist_get_size(data) ==
+                    cpl_imagelist_get_size(errors),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    if (eout) {
+        *eout = f->create_eout(cpl_imagelist_get_const(data, 0));
+    }
+
+    cpl_imagelist * nerrors = wrap_synced_errlist(data, errors);
+    if (nerrors == NULL) {
+        return cpl_error_get_code();
+    }
+
+    cpl_error_code errcode = f->func(data, nerrors, out, err, contrib,
+                                     f->parameters, eout ? *eout :  NULL);
+
+    unwrap_synced_errlist(nerrors);
+
+    return errcode;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief call extra output creation function
+ *
+ * @param f     reduction function object
+ * @param data  an image of same size and type as the intended reductee
+ *
+ * @return reduction objects extra output function, its entries must be deleted
+ *         by the caller and the structure unwraped with the unwrap_eout
+ *         function
+ */
+/* ---------------------------------------------------------------------------*/
+void *
+hdrl_collapse_imagelist_to_image_create_eout(
+                         hdrl_collapse_imagelist_to_image_t * f,
+                         const cpl_image * data)
+{
+    cpl_ensure(f, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(data, CPL_ERROR_NULL_INPUT, NULL);
+
+    return f->create_eout(data);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief call extra output unwrap function
+ *
+ * @param f     reduction function object
+ *
+ * @note does not delete the members
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+void
+hdrl_collapse_imagelist_to_image_unwrap_eout(
+                         hdrl_collapse_imagelist_to_image_t * f,
+                         void * eout)
+{
+    if (f != NULL) {
+        return f->unwrap_eout(eout);
+    }
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief call function to move extra output do destination with offset
+ *
+ * @param f     reduction function object
+ * @param dst   destination output
+ * @param src   source output
+ * @param y     offset in y, see cpl_image_copy
+ *
+ * @return cpl_error_code
+ *
+ * @note deletes the source after the content is copied
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_collapse_imagelist_to_image_move_eout(
+                       hdrl_collapse_imagelist_to_image_t * f,
+                       void * dst,
+                       void * src,
+                       cpl_size y)
+{
+    cpl_ensure_code(f, CPL_ERROR_NULL_INPUT);
+
+    return f->move_eout(dst, src, y);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief delete imagelist reduction object
+ *
+ * @param p  imagelist reduction object or NULL
+ */
+/* ---------------------------------------------------------------------------*/
+void hdrl_collapse_imagelist_to_image_delete(hdrl_collapse_imagelist_to_image_t * p)
+{
+    if (p) {
+        hdrl_parameter_delete(p->parameters);
+    }
+    cpl_free(p);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief call extra output creation function
+ *
+ * @param f     reduction function object
+ * @param size  size of the imagelist which should be reduced
+ *
+ * @return reduction objects extra output function, its entries must be deleted
+ *         by the caller and the structure unwraped with the unwrap_eout
+ *         function
+ */
+/* ---------------------------------------------------------------------------*/
+void *
+hdrl_collapse_imagelist_to_vector_create_eout(
+                         hdrl_collapse_imagelist_to_vector_t * f,
+                         const cpl_size size)
+{
+    cpl_ensure(f, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(size > 0, CPL_ERROR_ILLEGAL_INPUT, NULL);
+
+    return f->create_eout(size);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief call extra output unwrap function
+ *
+ * @param f     reduction function object
+ *
+ * @note does not delete the members
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+void
+hdrl_collapse_imagelist_to_vector_unwrap_eout(
+                         hdrl_collapse_imagelist_to_vector_t * f,
+                         void * eout)
+{
+    if (f != NULL) {
+        return f->unwrap_eout(eout);
+    }
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief call function to move extra output do destination with offset
+ *
+ * @param f     reduction function object
+ * @param dst   destination output
+ * @param src   source output
+ * @param y     offset in y, see cpl_image_copy
+ *
+ * @return cpl_error_code
+ *
+ * @note deletes the source after the content is copied
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_collapse_imagelist_to_vector_move_eout(
+                       hdrl_collapse_imagelist_to_vector_t * f,
+                       void * dst,
+                       void * src,
+                       cpl_size y)
+{
+    cpl_ensure_code(f, CPL_ERROR_NULL_INPUT);
+
+    return f->move_eout(dst, src, y);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief implements mean reduction on each image of an imagelist
+ *
+ * @param data    input data images
+ * @param errors  input errors images
+ * @param out     vector of median of each image
+ * @param err     vector of errors of median of each image
+ * @param contrib array of contributions
+ * @param parameters parameters to control, not used
+ * @param extra_out  optional extra output, not used
+ *
+ * @return cpl_error_code
+ *
+ * @doc
+ * The mean value on all good pixels of each image of an imagelist, the
+ * associated error and the number of good pixels are stored as elements
+ * of the corresponding output vectors.
+ * If all pixels of an image in the list are bad the contribution is 0 and the
+ * out and err are set to NAN.
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code
+reduce_imagelist_to_vector_mean(const cpl_imagelist * data,
+                                const cpl_imagelist * errors,
+                                cpl_vector ** out, cpl_vector ** err,
+                                cpl_array ** contrib,
+                                void * HDRL_UNUSED(parameters),
+                                void * HDRL_UNUSED(extra_out))
+{
+    size_t nz = cpl_imagelist_get_size(data);
+    *out = cpl_vector_new(nz);
+    *err = cpl_vector_new(nz);
+    *contrib = cpl_array_new(nz, CPL_TYPE_INT);
+
+    for (size_t i = 0; i < nz; i++) {
+        const cpl_image * img = cpl_imagelist_get_const(data, i);
+        const cpl_image * ierr = cpl_imagelist_get_const(errors, i);
+        size_t naccepted = hdrl_get_image_good_npix(img);
+
+        if (naccepted != 0) {
+            double error = sqrt(cpl_image_get_sqflux(ierr)) / naccepted;
+
+            cpl_vector_set(*out, i, cpl_image_get_mean(img));
+            cpl_vector_set(*err, i, error);
+        }
+        else {
+            cpl_vector_set(*out, i, NAN);
+            cpl_vector_set(*err, i, NAN);
+        }
+        cpl_array_set_int(*contrib, i, naccepted);
+    }
+
+    return cpl_error_get_code();
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief reduction object to reduce imagelist via mean
+ * @return mean reduction object
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_collapse_imagelist_to_vector_t *
+    hdrl_collapse_imagelist_to_vector_mean(void)
+{
+    hdrl_collapse_imagelist_to_vector_t * s = cpl_calloc(1, sizeof(*s));
+    s->create_eout = &hdrl_nop_create_eout_vec;
+    s->move_eout = &hdrl_nop_move_eout;
+    s->unwrap_eout = &hdrl_nop_unwrap_eout;
+    s->func = &reduce_imagelist_to_vector_mean;
+    return s;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief implements weighted mean reduction on each image of an imagelist
+ *
+ * @param data    input data images
+ * @param errors  input errors images
+ * @param out     vector of median of each image
+ * @param err     vector of errors of median of each image
+ * @param contrib array of contributions
+ * @param parameters parameters to control, not used
+ * @param extra_out  optional extra output, not used
+ *
+ * @return cpl_error_code
+ *
+ * @doc
+ * weighted mean and associated error are computed with standard formulae
+ *
+ * \f$
+ *   x_{mean}=\frac{(\sum_{i}^{n} w_{i} \cdot x_{i})} { \sum_{i}^{n} w_{i} }
+ * \f$
+ *
+ * \f$
+ *   \sigma_{x}=\frac{ 1 } { \sqrt{  \sum_{i}^{n} w_{i}^{2} } }
+ * \f$
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code
+reduce_imagelist_to_vector_weighted_mean(const cpl_imagelist * data,
+                                         const cpl_imagelist * errors,
+                                         cpl_vector ** out, cpl_vector ** err,
+                                         cpl_array ** contrib,
+                                         void * HDRL_UNUSED(parameters),
+                                         void * HDRL_UNUSED(extra_out))
+{
+    size_t nz = cpl_imagelist_get_size(data);
+    *out = cpl_vector_new(nz);
+    *err = cpl_vector_new(nz);
+    *contrib = cpl_array_new(nz, CPL_TYPE_INT);
+
+    for (size_t i = 0; i < nz; i++) {
+        cpl_image * img =
+            cpl_image_duplicate(cpl_imagelist_get_const(data, i));
+        cpl_image * ierr =
+            cpl_image_duplicate(cpl_imagelist_get_const(errors, i));
+        size_t naccepted = hdrl_get_image_good_npix(img);
+
+        if (naccepted != 0) {
+            /* (\Sum_i^n w_i * x_i) / (\Sum_i^n w_i) */
+            /* 1 / \sqrt(\Sum_i^n w_i^2) */
+            cpl_image_power(ierr, -2);
+            /* ierr = weights now */
+            cpl_image_multiply(img, ierr);
+            double sum_v = cpl_image_get_mean(img) * naccepted;
+            double sum_w = cpl_image_get_mean(ierr) * naccepted;
+            double wmean = sum_v / sum_w;
+            double error = 1. / sqrt(sum_w);
+
+            cpl_vector_set(*out, i, wmean);
+            cpl_vector_set(*err, i, error);
+        }
+        else {
+            cpl_vector_set(*out, i, NAN);
+            cpl_vector_set(*err, i, NAN);
+        }
+        cpl_array_set_int(*contrib, i, naccepted);
+        cpl_image_delete(img);
+        cpl_image_delete(ierr);
+    }
+
+    return cpl_error_get_code();
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief reduction object to reduce imagelist via weighted mean
+ * @return weighted mean reduction object
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_collapse_imagelist_to_vector_t *
+    hdrl_collapse_imagelist_to_vector_weighted_mean(void)
+{
+    hdrl_collapse_imagelist_to_vector_t * s = cpl_calloc(1, sizeof(*s));
+    s->create_eout = &hdrl_nop_create_eout_vec;
+    s->move_eout = &hdrl_nop_move_eout;
+    s->unwrap_eout = &hdrl_nop_unwrap_eout;
+    s->func = &reduce_imagelist_to_vector_weighted_mean;
+    return s;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief implements median reduction on each image of an imagelist
+ *
+ * @param data    input data images
+ * @param errors  input errors images
+ * @param out     vector of median of each image
+ * @param err     vector of errors of median of each image
+ * @param contrib array of contributions
+ * @param parameters parameters to control, not used
+ * @param extra_out  optional extra output, not used
+ * @return cpl_error_code
+ *
+ * @doc
+ * The median value on all good pixels of each image of an imagelist, the
+ * associated error and the number of good pixels are stored as elements
+ * of the corresponding output vectors.
+ * If all pixels of an image in the list are bad the contribution is 0 and the
+ * out and err are set to NAN.
+ * The errors are scaled by the sqrt of the statistical efficiency of the
+ * median on normal distributed data which is \f$ \frac{ \pi }{ 2 } \f$
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code
+reduce_imagelist_to_vector_median(const cpl_imagelist * data,
+                                  const cpl_imagelist * errors,
+                                  cpl_vector ** out, cpl_vector ** err,
+                                  cpl_array ** contrib,
+                                  void * HDRL_UNUSED(parameters),
+                                  void * HDRL_UNUSED(extra_out))
+{
+    size_t nz = cpl_imagelist_get_size(data);
+    *out = cpl_vector_new(nz);
+    *err = cpl_vector_new(nz);
+    *contrib = cpl_array_new(nz, CPL_TYPE_INT);
+
+    for (size_t i = 0; i < nz; i++) {
+        const cpl_image * img = cpl_imagelist_get_const(data, i);
+        const cpl_image * ierr = cpl_imagelist_get_const(errors, i);
+        size_t naccepted = hdrl_get_image_good_npix(img);
+
+        if (naccepted != 0) {
+            double error = sqrt(cpl_image_get_sqflux(ierr)) / naccepted;
+            /* sqrt(statistical efficiency on normal data)*/
+            if (naccepted > 2) {
+                error *= sqrt(CPL_MATH_PI_2);
+            }
+
+            cpl_vector_set(*out, i, cpl_image_get_median(img));
+            cpl_vector_set(*err, i, error);
+        }
+        else {
+            cpl_vector_set(*out, i, NAN);
+            cpl_vector_set(*err, i, NAN);
+        }
+        cpl_array_set_int(*contrib, i, naccepted);
+    }
+
+    return cpl_error_get_code();
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief reduction object to reduce imagelist via median
+ * @return median reduction object
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_collapse_imagelist_to_vector_t *
+    hdrl_collapse_imagelist_to_vector_median(void)
+{
+    hdrl_collapse_imagelist_to_vector_t * s = cpl_calloc(1, sizeof(*s));
+    s->create_eout = &hdrl_nop_create_eout_vec;
+    s->move_eout = &hdrl_nop_move_eout;
+    s->unwrap_eout = &hdrl_nop_unwrap_eout;
+    s->func = &reduce_imagelist_to_vector_median;
+    return s;
+}
+
+static void *
+hdrl_sigclip_create_eout_vec(cpl_size size)
+{
+    hdrl_sigclip_vector_output * eout = cpl_calloc(sizeof(*eout), 1);
+    eout->reject_low = cpl_vector_new(size);
+    eout->reject_high = cpl_vector_new(size);
+    return eout;
+}
+
+static cpl_error_code
+hdrl_sigclip_move_eout_vec(void * dst_, void * src_, const cpl_size y)
+{
+    hdrl_sigclip_vector_output * dst = dst_;
+    hdrl_sigclip_vector_output * src = src_;
+    cpl_ensure_code(dst, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(src, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(y >= 0, CPL_ERROR_ACCESS_OUT_OF_RANGE);
+    cpl_ensure_code(y < cpl_vector_get_size(dst->reject_low),
+                    CPL_ERROR_ACCESS_OUT_OF_RANGE);
+
+    double * ddst = cpl_vector_get_data(dst->reject_low);
+    double * dsrc = cpl_vector_get_data(src->reject_low);
+    memcpy(ddst + y, dsrc, cpl_vector_get_size(src->reject_low));
+    ddst = cpl_vector_get_data(dst->reject_high);
+    dsrc = cpl_vector_get_data(src->reject_high);
+    memcpy(ddst + y, dsrc, cpl_vector_get_size(src->reject_high));
+    cpl_vector_delete(src->reject_low);
+    cpl_vector_delete(src->reject_high);
+    cpl_free(src);
+    return cpl_error_get_code();
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief implements sigma-clipped combination on input image list into a vector
+ *
+ * @param data    input data imagelist
+ * @param errors  input errors imagelist
+ * @param out     output vector
+ * @param err     output vector errors
+ * @param contrib output contribution vector
+ *
+ * @return cpl_error_code
+ *
+ * If all pixels of an image in the list are rejected the contribution is 0 and
+ * the out and err are set to NAN.
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code
+reduce_imagelist_to_vector_sigclip(const cpl_imagelist * data,
+                                   const cpl_imagelist * errors,
+                                   cpl_vector ** out, cpl_vector ** err,
+                                   cpl_array ** contrib, void * parameters,
+                                   void * extra_out)
+{
+    hdrl_collapse_sigclip_parameter * par = parameters;
+    hdrl_minmax_vector_output * eout =
+        (hdrl_minmax_vector_output *)extra_out;
+
+    cpl_size nz = cpl_imagelist_get_size(data);
+    *out = cpl_vector_new(nz);
+    *err = cpl_vector_new(nz);
+    *contrib = cpl_array_new(nz, CPL_TYPE_INT);
+
+    /* sigmaclip on each image of the imagelist */
+    for (cpl_size z = 0; z < nz ; z++) {
+        double corr, error, low, high;
+        cpl_size contribution;
+        if (hdrl_kappa_sigma_clip_image(cpl_imagelist_get_const(data, z),
+                                        cpl_imagelist_get_const(errors, z),
+                                        par->kappa_low,
+                                        par->kappa_high,
+                                        par->niter,
+                                        &corr,
+                                        &error,
+                                        &contribution,
+                                        &low,
+                                        &high) != CPL_ERROR_NONE) {
+            break;
+        }
+        cpl_vector_set(*out, z, corr);
+        cpl_vector_set(*err, z, error);
+        cpl_array_set_int(*contrib, z, contribution);
+
+        if (eout) {
+            cpl_vector_set(eout->reject_low, z, low);
+            cpl_vector_set(eout->reject_high, z, high);
+        }
+    }
+
+    return cpl_error_get_code();
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief reduction object to reduce imagelist to a vector via kappa sigma
+ * clipped mean
+ *
+ * @param kappa_low  low sigma bound
+ * @param kappa_high high sigma bound
+ * @param niter      maximum number of clipping iterations
+ *
+ * @return sigma clip reduction object
+ * @see  hdrl_kappa_sigma_clip()
+ *
+ * the high and low reject values are stored in extra_out if applicable
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_collapse_imagelist_to_vector_t *
+hdrl_collapse_imagelist_to_vector_sigclip(double kappa_low, double kappa_high,
+                                          int niter)
+{
+    hdrl_collapse_imagelist_to_vector_t * s = cpl_calloc(1, sizeof(*s));
+    hdrl_parameter * sp =
+        hdrl_collapse_sigclip_parameter_create(kappa_low, kappa_high, niter);
+    s->func = &reduce_imagelist_to_vector_sigclip;
+    s->create_eout = &hdrl_sigclip_create_eout_vec;
+    s->move_eout = &hdrl_sigclip_move_eout_vec;
+    s->unwrap_eout = &cpl_free;
+    s->parameters = sp;
+    return s;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief implements minmax-clipped combination on input image list into a vector
+ *
+ * @param data    input data imagelist
+ * @param errors  input errors imagelist
+ * @param out     output vector
+ * @param err     output vector errors
+ *
+ * @return cpl_error_code
+ *
+ * If all pixels of an image in the list are rejected the contribution is 0 and
+ * the out and err are set to NAN.
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code
+reduce_imagelist_to_vector_minmax(const cpl_imagelist * data,
+                                   const cpl_imagelist * errors,
+                                   cpl_vector ** out, cpl_vector ** err,
+                                   cpl_array ** contrib, void * parameters,
+                                   void * extra_out)
+{
+    hdrl_collapse_minmax_parameter * par = parameters;
+    hdrl_sigclip_vector_output * eout =
+        (hdrl_sigclip_vector_output *)extra_out;
+    cpl_size nz = cpl_imagelist_get_size(data);
+    *out = cpl_vector_new(nz);
+    *err = cpl_vector_new(nz);
+    *contrib = cpl_array_new(nz, CPL_TYPE_INT);
+
+    /* minmax on each image of the imagelist */
+    for (cpl_size z = 0; z < nz ; z++) {
+        double corr, error, low, high;
+        cpl_size contribution;
+        if (hdrl_minmax_clip_image(cpl_imagelist_get_const(data, z),
+                                        cpl_imagelist_get_const(errors, z),
+                                        par->nlow,
+                                        par->nhigh,
+                                        &corr,
+                                        &error,
+                                        &contribution,
+                                        &low, &high) != CPL_ERROR_NONE) {
+            break;
+        }
+        cpl_vector_set(*out, z, corr);
+        cpl_vector_set(*err, z, error);
+        cpl_array_set_int(*contrib, z, contribution);
+
+        if (eout) {
+            cpl_vector_set(eout->reject_low, z, low);
+            cpl_vector_set(eout->reject_high, z, high);
+        }
+    }
+
+    return cpl_error_get_code();
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief reduction object to reduce imagelist to a vector via min-max rejection
+ *
+ * @param nlow  low bound
+ * @param nhigh  high bound
+ *
+ * @return minmax rejected reduction object
+ * @see  hdrl_minmax()
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_collapse_imagelist_to_vector_t *
+hdrl_collapse_imagelist_to_vector_minmax(double nlow, double nhigh)
+{
+    hdrl_collapse_imagelist_to_vector_t * s = cpl_calloc(1, sizeof(*s));
+    hdrl_parameter * sp =
+        hdrl_collapse_minmax_parameter_create(nlow, nhigh);
+    s->func = &reduce_imagelist_to_vector_minmax;
+    s->create_eout = &hdrl_sigclip_create_eout_vec;
+    s->move_eout = &hdrl_sigclip_move_eout_vec;
+    s->unwrap_eout = &cpl_free;
+    s->parameters = sp;
+    return s;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief Call the associated reduction function
+ *
+ * @param f       reduction function object
+ * @param data    data to apply function on
+ * @param errors  errors to use for propagation
+ * @param out     pointer which will contain reduced data image, type double
+ * @param err     pointer which will contain reduced error image, type double
+ * @param contrib pointer which will contain contribution map, type integer
+ * @param eout    storage for extra output, may be NULL
+ *
+ * @return cpl_error_code
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_collapse_imagelist_to_vector_call(hdrl_collapse_imagelist_to_vector_t * f,
+                                     const cpl_imagelist * data,
+                                     const cpl_imagelist * errors,
+                                     cpl_vector ** out,
+                                     cpl_vector ** err,
+                                     cpl_array ** contrib,
+                                     void ** eout)
+{
+    cpl_ensure_code(f, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(data, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(errors, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(out, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(err, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(contrib, CPL_ERROR_NULL_INPUT);
+    if (eout) {
+        *eout = f->create_eout(cpl_imagelist_get_size(data));
+    }
+
+    cpl_imagelist * nerrors = wrap_synced_errlist(data, errors);
+    if (nerrors == NULL) {
+        return cpl_error_get_code();
+    }
+
+    cpl_error_code errcode = f->func(data, errors, out, err, contrib,
+                                     f->parameters, eout ? *eout :  NULL);
+
+    unwrap_synced_errlist(nerrors);
+
+    return errcode;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief delete imagelist reduction object
+ *
+ * @param p  imagelist reduction object or NULL
+ */
+/* ---------------------------------------------------------------------------*/
+void
+hdrl_collapse_imagelist_to_vector_delete(hdrl_collapse_imagelist_to_vector_t * p)
+{
+    if (p) {
+        cpl_free(p->parameters);
+    }
+    cpl_free(p);
+}
+
+/** @endcond */
+
+/**@}*/
diff --git a/hdrl/hdrl_collapse.h b/hdrl/hdrl_collapse.h
new file mode 100644
index 0000000..4f09430
--- /dev/null
+++ b/hdrl/hdrl_collapse.h
@@ -0,0 +1,174 @@
+/* $Id: hdrl_collapse.h,v 1.11 2013-10-17 15:44:14 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-17 15:44:14 $
+ * $Revision: 1.11 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifndef HDRL_COLLAPSE_H
+#define HDRL_COLLAPSE_H
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_parameter.h"
+
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                                Define
+ -----------------------------------------------------------------------------*/
+
+/*-----------------------------------------------------------------------------
+                            Functions prototypes
+ -----------------------------------------------------------------------------*/
+
+hdrl_parameter * hdrl_collapse_mean_parameter_create(void);
+cpl_boolean hdrl_collapse_parameter_is_mean(const hdrl_parameter *);
+extern hdrl_parameter * HDRL_COLLAPSE_MEAN;
+hdrl_parameter * hdrl_collapse_median_parameter_create(void);
+cpl_boolean hdrl_collapse_parameter_is_median(const hdrl_parameter *);
+extern hdrl_parameter * HDRL_COLLAPSE_MEDIAN;
+hdrl_parameter * hdrl_collapse_weighted_mean_parameter_create(void);
+cpl_boolean hdrl_collapse_parameter_is_weighted_mean(const hdrl_parameter *);
+extern hdrl_parameter * HDRL_COLLAPSE_WEIGHTED_MEAN;
+hdrl_parameter * hdrl_collapse_sigclip_parameter_create(double, double, int);
+cpl_boolean hdrl_collapse_parameter_is_sigclip(const hdrl_parameter *);
+double hdrl_collapse_sigclip_parameter_get_kappa_high(const hdrl_parameter *);
+double hdrl_collapse_sigclip_parameter_get_kappa_low(const hdrl_parameter *);
+int hdrl_collapse_sigclip_parameter_get_niter(const hdrl_parameter *);
+
+hdrl_parameter * hdrl_collapse_minmax_parameter_create(double, double);
+cpl_boolean hdrl_collapse_parameter_is_minmax(const hdrl_parameter *);
+double hdrl_collapse_minmax_parameter_get_nhigh(const hdrl_parameter *);
+double hdrl_collapse_minmax_parameter_get_nlow(const hdrl_parameter *);
+
+
+hdrl_parameter * hdrl_collapse_parameter_parse_parlist(
+        const cpl_parameterlist *, const char *);
+cpl_parameterlist * hdrl_collapse_parameter_create_parlist(const char *,
+        const char *, const char *, hdrl_parameter *, hdrl_parameter *) ;
+
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+ -----------------------------------------------------------------------------*/
+
+#ifdef HDRL_USE_PRIVATE
+cpl_error_code hdrl_collapse_minmax_parameter_verify(const hdrl_parameter *);
+cpl_error_code hdrl_collapse_sigclip_parameter_verify(const hdrl_parameter *);
+
+typedef struct hdrl_collapse_imagelist_to_image_s
+    hdrl_collapse_imagelist_to_image_t;
+typedef struct hdrl_collapse_imagelist_to_vector_s
+    hdrl_collapse_imagelist_to_vector_t;
+
+typedef struct {
+    cpl_image * reject_low;
+    cpl_image * reject_high;
+} hdrl_sigclip_image_output;
+typedef hdrl_sigclip_image_output hdrl_minmax_image_output;
+
+typedef struct {
+    cpl_vector * reject_low;
+    cpl_vector * reject_high;
+} hdrl_sigclip_vector_output;
+typedef hdrl_sigclip_vector_output hdrl_minmax_vector_output;
+
+hdrl_collapse_imagelist_to_image_t *
+    hdrl_collapse_imagelist_to_image_mean(void);
+hdrl_collapse_imagelist_to_image_t *
+    hdrl_collapse_imagelist_to_image_weighted_mean(void);
+hdrl_collapse_imagelist_to_image_t * 
+    hdrl_collapse_imagelist_to_image_median(void);
+hdrl_collapse_imagelist_to_image_t *
+    hdrl_collapse_imagelist_to_image_sigclip(double, double, int);
+hdrl_collapse_imagelist_to_image_t *
+    hdrl_collapse_imagelist_to_image_minmax(double, double);
+cpl_error_code hdrl_collapse_imagelist_to_image_call(
+    hdrl_collapse_imagelist_to_image_t * f,
+    const cpl_imagelist * data,
+    const cpl_imagelist * errors,
+    cpl_image ** out,
+    cpl_image ** err,
+    cpl_image ** contrib,
+    void ** eout);
+void *
+hdrl_collapse_imagelist_to_image_create_eout(
+                         hdrl_collapse_imagelist_to_image_t * f,
+                         const cpl_image * data);
+void
+hdrl_collapse_imagelist_to_image_unwrap_eout(
+                         hdrl_collapse_imagelist_to_image_t * f,
+                         void * eout);
+cpl_error_code
+hdrl_collapse_imagelist_to_image_move_eout(
+                       hdrl_collapse_imagelist_to_image_t * f,
+                       void * dst,
+                       void * src,
+                       cpl_size y);
+void hdrl_collapse_imagelist_to_image_delete(hdrl_collapse_imagelist_to_image_t *);
+
+hdrl_collapse_imagelist_to_vector_t * 
+    hdrl_collapse_imagelist_to_vector_mean(void);
+hdrl_collapse_imagelist_to_vector_t *
+    hdrl_collapse_imagelist_to_vector_weighted_mean(void);
+hdrl_collapse_imagelist_to_vector_t * 
+    hdrl_collapse_imagelist_to_vector_median(void);
+hdrl_collapse_imagelist_to_vector_t *
+    hdrl_collapse_imagelist_to_vector_sigclip(double, double, int);
+hdrl_collapse_imagelist_to_vector_t *
+hdrl_collapse_imagelist_to_vector_minmax(double, double);
+
+cpl_error_code hdrl_collapse_imagelist_to_vector_call(
+    hdrl_collapse_imagelist_to_vector_t * f,
+    const cpl_imagelist * data,
+    const cpl_imagelist * errors,
+    cpl_vector ** out,
+    cpl_vector ** err,
+    cpl_array ** contrib,
+    void ** eout);
+void *
+hdrl_collapse_imagelist_to_vector_create_eout(
+                         hdrl_collapse_imagelist_to_vector_t * f,
+                         cpl_size);
+void
+hdrl_collapse_imagelist_to_vector_unwrap_eout(
+                         hdrl_collapse_imagelist_to_vector_t * f,
+                         void * eout);
+cpl_error_code
+hdrl_collapse_imagelist_to_vector_move_eout(
+                       hdrl_collapse_imagelist_to_vector_t * f,
+                       void * dst,
+                       void * src,
+                       cpl_size y);
+void hdrl_collapse_imagelist_to_vector_delete(
+    hdrl_collapse_imagelist_to_vector_t *);
+
+#endif
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_combine.c b/hdrl/hdrl_combine.c
new file mode 100644
index 0000000..f6db999
--- /dev/null
+++ b/hdrl/hdrl_combine.c
@@ -0,0 +1,100 @@
+/* $Id: hdrl_combine.c,v 1.15 2013-09-24 14:58:54 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-09-24 14:58:54 $
+ * $Revision: 1.15 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+-----------------------------------------------------------------------------*/
+
+#include "hdrl_combine.h"
+#include "hdrl_iter.h"
+#include "hdrl_utils.h"
+#include "hdrl_sigclip.h"
+#include <cpl.h>
+#include <math.h>
+#include <string.h>
+#include <assert.h>
+
+/*-----------------------------------------------------------------------------
+                                   Static
+ -----------------------------------------------------------------------------*/
+
+/** @cond PRIVATE */
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_combine   COMBINE Module
+
+  This module allows the combination of imagelists with error propagation.
+  If input images size is large the user should use hdrl_imagelist_combine_it()
+  for efficient RAM usage. Else can be used hdrl_imagelist_combine()
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief combine imagelist with error propagation
+ *
+ * @param data     input data imagelist
+ * @param errors   input imagelist containing errors of data
+ * @param method   reduction method applied to the imagelists
+ * @param out      pointer to storage for a pointer to the allocated
+ *                 combined data image
+ * @param out      pointer to storage for a pointer to the allocated
+ *                 combined error image
+ * @param contrib  pointer to storage for a pointer to the allocated
+ *                 contribution map
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_imagelist_combine(const cpl_imagelist * data,
+                       const cpl_imagelist * errors,
+                       hdrl_collapse_imagelist_to_image_t * method,
+                       cpl_image ** out,
+                       cpl_image ** err,
+                       cpl_image ** contrib)
+{
+    cpl_ensure_code(data && errors, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(out && err && contrib, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(cpl_imagelist_get_size(data) > 0, CPL_ERROR_ILLEGAL_INPUT);
+    cpl_ensure_code(cpl_imagelist_get_size(data) ==
+                    cpl_imagelist_get_size(errors), CPL_ERROR_ILLEGAL_INPUT);
+
+    hdrl_collapse_imagelist_to_image_call(method, data, errors,
+                                        out, err, contrib, NULL);
+
+    return cpl_error_get_code();
+}
+
+/**@}*/
+
+/** @endcond */
diff --git a/hdrl/hdrl_combine.h b/hdrl/hdrl_combine.h
new file mode 100644
index 0000000..46c676c
--- /dev/null
+++ b/hdrl/hdrl_combine.h
@@ -0,0 +1,64 @@
+/* $Id: hdrl_combine.h,v 1.6 2013-10-17 15:44:14 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-17 15:44:14 $
+ * $Revision: 1.6 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifndef HDRL_COMBINE_H
+#define HDRL_COMBINE_H
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_iter.h"
+#include "hdrl_collapse.h"
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                                Define
+ -----------------------------------------------------------------------------*/
+
+/*-----------------------------------------------------------------------------
+                            Functions prototypes
+ -----------------------------------------------------------------------------*/
+
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+ -----------------------------------------------------------------------------*/
+
+#ifdef HDRL_USE_PRIVATE
+
+cpl_error_code
+hdrl_imagelist_combine(const cpl_imagelist * data, const cpl_imagelist * errors,
+                      hdrl_collapse_imagelist_to_image_t * method,
+                      cpl_image ** out, cpl_image ** err, cpl_image ** contrib);
+
+#endif
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_elemop.c b/hdrl/hdrl_elemop.c
new file mode 100644
index 0000000..12000f6
--- /dev/null
+++ b/hdrl/hdrl_elemop.c
@@ -0,0 +1,835 @@
+/* $Id: hdrl_elemop.c,v 1.4 2013-10-04 08:03:14 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-04 08:03:14 $
+ * $Revision: 1.4 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_utils.h"
+#include "hdrl_types.h"
+
+#include <cpl.h>
+#include <math.h>
+
+#ifndef SQR
+#define SQR(a) ((a) * (a))
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Functions
+ -----------------------------------------------------------------------------*/
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief add two arrays of with error propagation in place
+ *
+ * @param a   array of values of size na
+ * @param ea  array of errors of a
+ * @param na  size of a arrays
+ * @param b   array of values of size nb
+ * @param eb  array of errors of b
+ * @param nb  size of b array, must be equal to na or 1
+ * @param mask  bad pixel mask, positions where it is true are not modified
+ *
+ * a = a + b
+ * e = hypot(ea, eb)
+ * error propagation of first order, correlations not considered
+ * except for the a === b case (correlation = 1)
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_elemop_add(hdrl_data_t * a, hdrl_error_t * ea, size_t na,
+                               const hdrl_data_t * b, const hdrl_error_t * eb, size_t nb,
+                               const cpl_binary * mask)
+{
+    if (a == b && ea == eb) {
+        for (size_t i = 0; i < na; i++) {
+            if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                a[i] += a[i];
+                ea[i] *= 2;
+            }
+        }
+    }
+    else {
+        cpl_ensure_code(na == nb || nb == 1, CPL_ERROR_ILLEGAL_INPUT);
+
+        if (nb == 1) {
+            for (size_t i = 0; i < na; i++) {
+                if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                    a[i] += b[0];
+                    ea[i] = hypot(ea[i], eb[0]);
+                }
+            }
+        }
+        else {
+            for (size_t i = 0; i < na; i++) {
+                if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                    a[i] += b[i];
+                    ea[i] = hypot(ea[i], eb[i]);
+                }
+            }
+        }
+    }
+
+    return CPL_ERROR_NONE;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief subtract two arrays of with error propagation in place
+ *
+ * @param a   array of values of size na
+ * @param ea  array of errors of a
+ * @param na  size of a arrays
+ * @param b   array of values of size nb
+ * @param eb  array of errors of b
+ * @param nb  size of b array, must be equal to na or 1
+ * @param mask  bad pixel mask, positions where it is true are not modified
+ *
+ * a = a - b
+ * e = hypot(ea, eb)
+ * error propagation of first order, correlations not considered
+ * except for the a === b case (correlation = 1)
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_elemop_sub(hdrl_data_t * a, hdrl_error_t * ea, size_t na,
+                               const hdrl_data_t * b, const hdrl_error_t * eb, size_t nb,
+                               const cpl_binary * mask)
+{
+    if (a == b && ea == eb) {
+        for (size_t i = 0; i < na; i++) {
+            if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                a[i] = 0.;
+                ea[i] = 0.;
+            }
+        }
+    }
+    else {
+        cpl_ensure_code(na == nb || nb == 1, CPL_ERROR_ILLEGAL_INPUT);
+
+        if (nb == 1) {
+            for (size_t i = 0; i < na; i++) {
+                if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                    a[i] -= b[0];
+                    ea[i] = hypot(ea[i], eb[0]);
+                }
+            }
+        }
+        else {
+            for (size_t i = 0; i < na; i++) {
+                if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                    a[i] -= b[i];
+                    ea[i] = hypot(ea[i], eb[i]);
+                }
+            }
+        }
+    }
+
+    return CPL_ERROR_NONE;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief multiply two arrays of with error propagation in place
+ *
+ * @param a   array of values of size na
+ * @param ea  array of errors of a
+ * @param na  size of a arrays
+ * @param b   array of values of size nb
+ * @param eb  array of errors of b
+ * @param nb  size of b array, must be equal to na or 1
+ * @param mask  bad pixel mask, positions where it is true are not modified
+ *
+ * a = a * b
+ * e = hypot(a * eb, b * ea)
+ * error propagation of first order, correlations not considered
+ * except for the a === b case (correlation = 1)
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_elemop_mul(hdrl_data_t * a, hdrl_error_t * ea, size_t na,
+                               const hdrl_data_t * b, const hdrl_error_t * eb, size_t nb,
+                               const cpl_binary * mask)
+{
+    if (a == b && ea == eb) {
+        for (size_t i = 0; i < na; i++) {
+            if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                const hdrl_data_t a_ = a[i] * a[i];
+                ea[i] = 2 * fabs(a[i]) * ea[i];
+                a[i] = a_;
+            }
+        }
+    }
+    else {
+        cpl_ensure_code(na == nb || nb == 1, CPL_ERROR_ILLEGAL_INPUT);
+
+        if (nb == 1) {
+            const hdrl_data_t b0 = b[0];
+            const hdrl_error_t eb0 = eb[0];
+            for (size_t i = 0; i < na; i++) {
+                if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                    const hdrl_data_t a_ = a[i] * b0;
+                    ea[i] = hypot(eb0 * a[i], ea[i] * b0);
+                    a[i] = a_;
+                }
+            }
+        }
+        else {
+            for (size_t i = 0; i < na; i++) {
+                if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                    const hdrl_data_t a_ = a[i] * b[i];
+                    ea[i] = hypot(eb[i] * a[i], ea[i] * b[i]);
+                    a[i] = a_;
+                }
+            }
+        }
+    }
+
+    return CPL_ERROR_NONE;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief divide two arrays of with error propagation in place
+ *
+ * @param a   array of values of size na
+ * @param ea  array of errors of a
+ * @param na  size of a arrays
+ * @param b   array of values of size nb
+ * @param eb  array of errors of b
+ * @param nb  size of b array, must be equal to na or 1
+ * @param mask  bad pixel mask, positions where it is true are not modified
+ *
+ * a = a / b
+ * e = hypot(ea / b, eb * a / (b * b))
+ * error propagation of first order, correlations not considered
+ * except for the a === b case (correlation = 1)
+ *
+ * unlike cpl_image_divide pixels which are divided by zero are set to NAN and
+ * not marked as bad.
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_elemop_div(hdrl_data_t * a, hdrl_error_t * ea, size_t na,
+                               const hdrl_data_t * b, const hdrl_error_t * eb, size_t nb,
+                               const cpl_binary * mask)
+{
+    if (a == b && ea == eb) {
+        for (size_t i = 0; i < na; i++) {
+            if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                ea[i] = 0.;
+                a[i] = 1.;
+            }
+        }
+    }
+    else {
+        cpl_ensure_code(na == nb || nb == 1, CPL_ERROR_ILLEGAL_INPUT);
+
+        if (nb == 1) {
+            const hdrl_data_t rb0 = 1. / b[0];
+            const hdrl_error_t eb0 = eb[0];
+            for (size_t i = 0; i < na; i++) {
+                if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                    const hdrl_data_t a_ = a[i] * rb0;
+                    if (b[0] == 0.) {
+                        a[i] = NAN;
+                        ea[i] = NAN;
+                    }
+                    else {
+                        /* sqrt((ea / b)^2 + (eb * a / b^2)^2) */
+                        ea[i] = sqrt(SQR(ea[i] * rb0) +
+                                     SQR(eb0 * a_ * rb0));
+                        a[i] = a_;
+                    }
+                }
+            }
+        }
+        else {
+            for (size_t i = 0; i < na; i++) {
+                if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                    const hdrl_data_t rb = 1. / b[i];
+                    const hdrl_data_t a_ = a[i] * rb;
+                    if (b[i] == 0.) {
+                        a[i] = NAN;
+                        ea[i] = NAN;
+                    }
+                    else {
+                        /* sqrt((ea / b)^2 + (eb * a / b^2)^2) */
+                        ea[i] = sqrt(SQR(ea[i] * rb) +
+                                     SQR(eb[i] * a_ * rb));
+                        a[i] = a_;
+                    }
+                }
+            }
+        }
+    }
+
+    return CPL_ERROR_NONE;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief power of two arrays of with error propagation in place
+ *
+ * @param a   array of values of size na
+ * @param ea  array of errors of a
+ * @param na  size of a arrays
+ * @param b   array of values of size nb
+ * @param eb  array of errors of b
+ * @param nb  size of b array, must be equal to na or 1
+ * @param mask  bad pixel mask, positions where it is true are not modified
+ *
+ * a = pow(a, b)
+ * e = pow(a, b) * sqrt((a / b * ea)^2 + (ln(a) * eb)^2)
+ * error propagation of first order, correlations not considered
+ * except for the a === b case (correlation = 1)
+ *
+ * if b < 0 and a == 0 the result is NAN
+ * for a < 0 and eb != 0 the error is not well defined
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_elemop_pow(hdrl_data_t * a, hdrl_error_t * ea, size_t na,
+                               const hdrl_data_t * b, const hdrl_error_t * eb, size_t nb,
+                               const cpl_binary * mask)
+{
+    if (a == b && ea == eb) {
+        for (size_t i = 0; i < na; i++) {
+            if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                hdrl_data_t loga = log(fabs(a[i]));
+                a[i] = pow(a[i], a[i]);
+                ea[i] = fabs(a[i]) *
+                    sqrt(SQR(ea[i]) * (1. + SQR(loga) + 2 * loga));
+            }
+        }
+    }
+    else {
+        cpl_ensure_code(na == nb || nb == 1, CPL_ERROR_ILLEGAL_INPUT);
+
+        if (nb == 1) {
+            const hdrl_data_t rb0 = b[0];
+            const hdrl_error_t eb0 = eb[0];
+            /* square optimization */
+            if (rb0 == 2. && eb0 == 0.) {
+                return hdrl_elemop_mul(a, ea, na, a, ea, na, mask);
+            }
+            /* no exponent error */
+            else if (eb0 == 0.) {
+                for (size_t i = 0; i < na; i++) {
+                    if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                        if (a[i] == 0. && rb0 < 0.) {
+                            a[i] = NAN;
+                            ea[i] = NAN;
+                        }
+                        else {
+                            const hdrl_data_t a_ = pow(a[i], rb0);
+                            ea[i] = fabs(a_ * (rb0 / a[i] * ea[i]));
+                            a[i] = a_;
+                        }
+                    }
+                }
+            }
+            else {
+                for (size_t i = 0; i < na; i++) {
+                    if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                        if (a[i] == 0. && rb0 < 0.) {
+                            a[i] = NAN;
+                            ea[i] = NAN;
+                        }
+                        else {
+                            const hdrl_data_t a_ = pow(a[i], rb0);
+                            hdrl_data_t loga = log(fabs(a[i]));
+                            ea[i] = fabs(a_) * sqrt(SQR(rb0 / a[i] * ea[i]) +
+                                                    SQR(loga * eb0));
+                            a[i] = a_;
+                        }
+                    }
+                }
+            }
+        }
+        else {
+            for (size_t i = 0; i < na; i++) {
+                if (mask == NULL || mask[i] == CPL_BINARY_0) {
+                    if (a[i] == 0. && b[0] < 0.) {
+                        a[i] = NAN;
+                        ea[i] = NAN;
+                    }
+                    else {
+                        const hdrl_data_t a_ = pow(a[i], b[i]);
+                            hdrl_data_t loga = log(fabs(a[i]));
+                        ea[i] = fabs(a_) * sqrt(SQR(b[i] / a[i] * ea[i]) +
+                                                SQR(loga * eb[i]));
+                        a[i] = a_;
+                    }
+                }
+            }
+        }
+    }
+
+    return CPL_ERROR_NONE;
+}
+
+
+typedef cpl_error_code (hdrl_math_op_f)(
+                                        hdrl_data_t * a, hdrl_error_t * ea, size_t na,
+                                        const hdrl_data_t * b, const hdrl_error_t * eb, size_t nb,
+                                        const cpl_binary * mask);
+
+typedef cpl_error_code (hdrl_math_op_image_f)(
+                                              cpl_image * a, cpl_image * ae,
+                                              const cpl_image * b, const cpl_image * be);
+
+typedef cpl_error_code (hdrl_math_op_image_scalar_f)(
+                                                     cpl_image * a, cpl_image * ae,
+                                                     const hdrl_data_t b, const hdrl_error_t be);
+
+static cpl_error_code
+check_input(cpl_image * a, cpl_image * ae,
+            const cpl_image * b, const cpl_image * be)
+{
+    cpl_ensure_code(a, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(ae, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(b, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(be, CPL_ERROR_NULL_INPUT);
+
+    cpl_ensure_code(cpl_image_get_size_x(a) == cpl_image_get_size_x(ae),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(cpl_image_get_size_y(a) == cpl_image_get_size_y(ae),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(cpl_image_get_size_x(b) == cpl_image_get_size_x(be),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(cpl_image_get_size_y(b) == cpl_image_get_size_y(be),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(cpl_image_get_size_x(a) == cpl_image_get_size_x(b),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(cpl_image_get_size_y(a) == cpl_image_get_size_y(b),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(cpl_image_get_type(a) == HDRL_TYPE_DATA,
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(cpl_image_get_type(ae) == HDRL_TYPE_ERROR,
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(cpl_image_get_type(b) == HDRL_TYPE_DATA,
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(cpl_image_get_type(be) == HDRL_TYPE_ERROR,
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+
+    return CPL_ERROR_NONE;
+}
+
+
+static cpl_error_code
+hdrl_elemop_image_scalar(cpl_image * a, cpl_image * ae,
+                         const hdrl_data_t b, const hdrl_error_t be,
+                         hdrl_math_op_f * f)
+{
+    const cpl_binary * dmask = NULL;
+    cpl_ensure_code(a, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(ae, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(cpl_image_get_type(a) == HDRL_TYPE_DATA,
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(cpl_image_get_type(ae) == HDRL_TYPE_ERROR,
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    const cpl_mask * bpm = cpl_image_get_bpm_const(a);
+
+    if (bpm != NULL) {
+        dmask = cpl_mask_get_data_const(bpm);
+    }
+
+    if (f == hdrl_elemop_div && b == 0.) {
+        cpl_msg_warning(cpl_func, "dividing image by scalar zero");
+        cpl_image_add_scalar(a, NAN);
+        cpl_image_add_scalar(ae, NAN);
+        cpl_image_reject_value(a, CPL_VALUE_NAN);
+        cpl_image_reject_value(ae, CPL_VALUE_NAN);
+        return cpl_error_get_code();
+    }
+    else {
+        cpl_error_code err = f(hdrl_get_image_data(a),
+                               hdrl_get_image_error(ae),
+                               hdrl_get_image_npix(a),
+                               &b, &be, 1,
+                               dmask);
+        if (f == hdrl_elemop_pow) {
+            cpl_image_reject_value(a, CPL_VALUE_NAN);
+            cpl_image_reject_from_mask(ae, cpl_image_get_bpm(a));
+        }
+        return err;
+    }
+}
+
+/* doxygen in header */
+cpl_error_code
+hdrl_elemop_image_add_scalar(cpl_image * a, cpl_image * ae,
+                             const hdrl_data_t b, const hdrl_error_t be)
+{
+    return hdrl_elemop_image_scalar(a, ae, b, be, hdrl_elemop_add);
+}
+
+cpl_error_code
+hdrl_elemop_image_sub_scalar(cpl_image * a, cpl_image * ae,
+                             const hdrl_data_t b, const hdrl_error_t be)
+{
+    return hdrl_elemop_image_scalar(a, ae, b, be, hdrl_elemop_sub);
+}
+
+cpl_error_code
+hdrl_elemop_image_mul_scalar(cpl_image * a, cpl_image * ae,
+                             const hdrl_data_t b, const hdrl_error_t be)
+{
+    return hdrl_elemop_image_scalar(a, ae, b, be, hdrl_elemop_mul);
+}
+
+cpl_error_code
+hdrl_elemop_image_div_scalar(cpl_image * a, cpl_image * ae,
+                             const hdrl_data_t b, const hdrl_error_t be)
+{
+    return hdrl_elemop_image_scalar(a, ae, b, be, hdrl_elemop_div);
+}
+
+cpl_error_code
+hdrl_elemop_image_pow_scalar(cpl_image * a, cpl_image * ae,
+                             const hdrl_data_t b, const hdrl_error_t be)
+{
+    return hdrl_elemop_image_scalar(a, ae, b, be, hdrl_elemop_pow);
+}
+
+static cpl_error_code
+hdrl_elemop_image(cpl_image * a, cpl_image * ae,
+                  const cpl_image * b, const cpl_image * be,
+                  hdrl_math_op_f * f)
+{
+    cpl_error_code r = check_input(a, ae, b, be);
+    const cpl_binary * dmask = NULL;
+    cpl_ensure_code(r == CPL_ERROR_NONE, r);
+    const cpl_mask * bbpm = cpl_image_get_bpm_const(b);
+
+    if (bbpm != NULL) {
+        if (cpl_image_get_bpm_const(a)) {
+            /* a and b have bpm, merge them */
+            cpl_mask * abpm = cpl_image_get_bpm(a);
+            cpl_mask_or(abpm, bbpm);
+            dmask = cpl_mask_get_data_const(abpm);
+        }
+        else {
+            /* a has no bpm, copy from b */
+            cpl_image_reject_from_mask(a, bbpm);
+            dmask = cpl_mask_get_data_const(bbpm);
+        }
+    }
+    else {
+        const cpl_mask * abpm = cpl_image_get_bpm_const(a);
+        if (abpm) {
+            dmask = cpl_mask_get_data_const(abpm);
+        }
+    }
+
+    r = f(hdrl_get_image_data(a),
+          hdrl_get_image_error(ae),
+          hdrl_get_image_npix(a),
+          hdrl_get_image_data_const(b),
+          hdrl_get_image_error_const(be),
+          hdrl_get_image_npix(a),
+          dmask);
+
+    if (f == hdrl_elemop_div || f == hdrl_elemop_pow) {
+        cpl_image_reject_value(a, CPL_VALUE_NAN);
+        cpl_image_reject_from_mask(ae, cpl_image_get_bpm(a));
+    }
+
+    return r;
+}
+
+cpl_error_code
+hdrl_elemop_image_add_image(cpl_image * a, cpl_image * ae,
+                      const cpl_image * b, const cpl_image * be)
+{
+    return hdrl_elemop_image(a, ae, b, be, hdrl_elemop_add);
+}
+
+cpl_error_code
+hdrl_elemop_image_sub_image(cpl_image * a, cpl_image * ae,
+                      const cpl_image * b, const cpl_image * be)
+{
+    return hdrl_elemop_image(a, ae, b, be, hdrl_elemop_sub);
+}
+
+cpl_error_code
+hdrl_elemop_image_mul_image(cpl_image * a, cpl_image * ae,
+                      const cpl_image * b, const cpl_image * be)
+{
+    return hdrl_elemop_image(a, ae, b, be, hdrl_elemop_mul);
+}
+
+cpl_error_code
+hdrl_elemop_image_div_image(cpl_image * a, cpl_image * ae,
+                      const cpl_image * b, const cpl_image * be)
+{
+    return hdrl_elemop_image(a, ae, b, be, hdrl_elemop_div);
+}
+
+cpl_error_code
+hdrl_elemop_image_pow_image(cpl_image * a, cpl_image * ae,
+                      const cpl_image * b, const cpl_image * be)
+{
+    return hdrl_elemop_image(a, ae, b, be, hdrl_elemop_pow);
+}
+
+static cpl_error_code
+hdrl_elemop_imagelist_vector(cpl_imagelist * self_d,
+                             cpl_imagelist * self_e,
+                             const cpl_vector * other_d,
+                             const cpl_vector * other_e,
+                             hdrl_math_op_image_scalar_f * f)
+{
+    cpl_ensure_code(self_d, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(self_e, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(other_d, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(other_e, CPL_ERROR_NULL_INPUT);
+    const size_t nz = cpl_imagelist_get_size(self_d);
+    cpl_ensure_code(nz == (size_t)cpl_imagelist_get_size(self_e),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(nz == (size_t)cpl_vector_get_size(other_d),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(nz == (size_t)cpl_vector_get_size(other_e),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+
+    for (size_t i = 0; i < nz; i++) {
+        cpl_image * ad = cpl_imagelist_get(self_d, i);
+        cpl_image * ae = cpl_imagelist_get(self_e, i);
+        const double bd = cpl_vector_get(other_d, i);
+        const double be = cpl_vector_get(other_e, i);
+        f(ad, ae, bd, be);
+    }
+
+    return cpl_error_get_code();
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_add_vector(cpl_imagelist * self_d,
+                                 cpl_imagelist * self_e,
+                                 const cpl_vector * other_d,
+                                 const cpl_vector * other_e)
+{
+    return hdrl_elemop_imagelist_vector(self_d, self_e, other_d, other_e,
+                                        hdrl_elemop_image_add_scalar);
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_sub_vector(cpl_imagelist * self_d,
+                                 cpl_imagelist * self_e,
+                                 const cpl_vector * other_d,
+                                 const cpl_vector * other_e)
+{
+    return hdrl_elemop_imagelist_vector(self_d, self_e, other_d, other_e,
+                                        hdrl_elemop_image_sub_scalar);
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_mul_vector(cpl_imagelist * self_d,
+                                 cpl_imagelist * self_e,
+                                 const cpl_vector * other_d,
+                                 const cpl_vector * other_e)
+{
+    return hdrl_elemop_imagelist_vector(self_d, self_e, other_d, other_e,
+                                        hdrl_elemop_image_mul_scalar);
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_div_vector(cpl_imagelist * self_d,
+                                 cpl_imagelist * self_e,
+                                 const cpl_vector * other_d,
+                                 const cpl_vector * other_e)
+{
+    return hdrl_elemop_imagelist_vector(self_d, self_e, other_d, other_e,
+                                        hdrl_elemop_image_div_scalar);
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_pow_vector(cpl_imagelist * self_d,
+                                 cpl_imagelist * self_e,
+                                 const cpl_vector * other_d,
+                                 const cpl_vector * other_e)
+{
+    return hdrl_elemop_imagelist_vector(self_d, self_e, other_d, other_e,
+                                        hdrl_elemop_image_pow_scalar);
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_image(cpl_imagelist * self_d,
+                            cpl_imagelist * self_e,
+                            const cpl_image * other_d,
+                            const cpl_image * other_e,
+                            hdrl_math_op_image_f * f)
+{
+    cpl_ensure_code(self_d, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(self_e, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(other_d, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(other_e, CPL_ERROR_NULL_INPUT);
+    const size_t nz = cpl_imagelist_get_size(self_d);
+    cpl_ensure_code(nz == (size_t)cpl_imagelist_get_size(self_e),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+
+    for (size_t i = 0; i < nz; i++) {
+        cpl_image * ad = cpl_imagelist_get(self_d, i);
+        cpl_image * ae = cpl_imagelist_get(self_e, i);
+        f(ad, ae, other_d, other_e);
+    }
+
+    return cpl_error_get_code();
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_add_image(cpl_imagelist * self_d,
+                                cpl_imagelist * self_e,
+                                const cpl_image * other_d,
+                                const cpl_image * other_e)
+{
+    return hdrl_elemop_imagelist_image(self_d, self_e, other_d, other_e,
+                                       hdrl_elemop_image_add_image);
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_sub_image(cpl_imagelist * self_d,
+                                cpl_imagelist * self_e,
+                                const cpl_image * other_d,
+                                const cpl_image * other_e)
+{
+    return hdrl_elemop_imagelist_image(self_d, self_e, other_d, other_e,
+                                       hdrl_elemop_image_sub_image);
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_mul_image(cpl_imagelist * self_d,
+                                cpl_imagelist * self_e,
+                                const cpl_image * other_d,
+                                const cpl_image * other_e)
+{
+    return hdrl_elemop_imagelist_image(self_d, self_e, other_d, other_e,
+                                       hdrl_elemop_image_mul_image);
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_div_image(cpl_imagelist * self_d,
+                                cpl_imagelist * self_e,
+                                const cpl_image * other_d,
+                                const cpl_image * other_e)
+{
+    return hdrl_elemop_imagelist_image(self_d, self_e, other_d, other_e,
+                                       hdrl_elemop_image_div_image);
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_pow_image(cpl_imagelist * self_d,
+                                cpl_imagelist * self_e,
+                                const cpl_image * other_d,
+                                const cpl_image * other_e)
+{
+    return hdrl_elemop_imagelist_image(self_d, self_e, other_d, other_e,
+                                       hdrl_elemop_image_pow_image);
+}
+
+static cpl_error_code
+hdrl_elemop_imagelist(cpl_imagelist * self_d,
+                      cpl_imagelist * self_e,
+                      const cpl_imagelist * other_d,
+                      const cpl_imagelist * other_e,
+                      hdrl_math_op_image_f * f)
+{
+    cpl_ensure_code(self_d, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(other_d, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(self_e, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(other_e, CPL_ERROR_NULL_INPUT);
+    const size_t nz = cpl_imagelist_get_size(self_d);
+    cpl_ensure_code(nz == (size_t)cpl_imagelist_get_size(self_e),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(nz == (size_t)cpl_imagelist_get_size(other_d),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(nz == (size_t)cpl_imagelist_get_size(other_e),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+
+    for (size_t i = 0; i < nz; i++) {
+        cpl_image * ad = cpl_imagelist_get(self_d, i);
+        cpl_image * ae = cpl_imagelist_get(self_e, i);
+        const cpl_image * bd = cpl_imagelist_get_const(other_d, i);
+        const cpl_image * be = cpl_imagelist_get_const(other_e, i);
+        f(ad, ae, bd, be);
+    }
+
+    return cpl_error_get_code();
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_add_imagelist(cpl_imagelist * self_d,
+                                    cpl_imagelist * self_e,
+                                    const cpl_imagelist * other_d,
+                                    const cpl_imagelist * other_e)
+{
+    return hdrl_elemop_imagelist(self_d, self_e, other_d, other_e,
+                                 hdrl_elemop_image_add_image);
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_sub_imagelist(cpl_imagelist * self_d,
+                                    cpl_imagelist * self_e,
+                                    const cpl_imagelist * other_d,
+                                    const cpl_imagelist * other_e)
+{
+    return hdrl_elemop_imagelist(self_d, self_e, other_d, other_e,
+                                 hdrl_elemop_image_sub_image);
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_mul_imagelist(cpl_imagelist * self_d,
+                                    cpl_imagelist * self_e,
+                                    const cpl_imagelist * other_d,
+                                    const cpl_imagelist * other_e)
+{
+    return hdrl_elemop_imagelist(self_d, self_e, other_d, other_e,
+                                 hdrl_elemop_image_mul_image);
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_div_imagelist(cpl_imagelist * self_d,
+                                    cpl_imagelist * self_e,
+                                    const cpl_imagelist * other_d,
+                                    const cpl_imagelist * other_e)
+{
+    return hdrl_elemop_imagelist(self_d, self_e, other_d, other_e,
+                                 hdrl_elemop_image_div_image);
+}
+
+cpl_error_code
+hdrl_elemop_imagelist_pow_imagelist(cpl_imagelist * self_d,
+                                    cpl_imagelist * self_e,
+                                    const cpl_imagelist * other_d,
+                                    const cpl_imagelist * other_e)
+{
+    return hdrl_elemop_imagelist(self_d, self_e, other_d, other_e,
+                                 hdrl_elemop_image_pow_image);
+}
diff --git a/hdrl/hdrl_elemop.h b/hdrl/hdrl_elemop.h
new file mode 100644
index 0000000..dc64eca
--- /dev/null
+++ b/hdrl/hdrl_elemop.h
@@ -0,0 +1,231 @@
+/* $Id: hdrl_elemop.h,v 1.4 2013-10-17 15:44:14 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-17 15:44:14 $
+ * $Revision: 1.4 $
+ */
+
+#ifndef HDRL_ELEMOP_H
+#define HDRL_ELEMOP_H
+
+#ifndef HDRL_USE_PRIVATE
+#error This file is not allowed to be included outside of hdrl
+#endif
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_types.h"
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                                Define
+ -----------------------------------------------------------------------------*/
+
+
+/*-----------------------------------------------------------------------------
+                            Functions prototypes
+ -----------------------------------------------------------------------------*/
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief add/subtract/multiply/divide two images with error propagation
+ *
+ * @param a   image, modified in place
+ * @param ae  errors of image a, modified in place
+ * @param b   image
+ * @param be  errors of image b
+ *
+ * Gaussian error propagation of first order, no accounting correlation
+ * besides a == b.
+ * Divisions by zero will be marked as bad pixels and set to NAN
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_elemop_image_add_image(cpl_image * a, cpl_image * ae,
+                            const cpl_image * b, const cpl_image * be);
+cpl_error_code
+hdrl_elemop_image_sub_image(cpl_image * a, cpl_image * ae,
+                            const cpl_image * b, const cpl_image * be);
+cpl_error_code
+hdrl_elemop_image_mul_image(cpl_image * a, cpl_image * ae,
+                            const cpl_image * b, const cpl_image * be);
+cpl_error_code
+hdrl_elemop_image_div_image(cpl_image * a, cpl_image * ae,
+                            const cpl_image * b, const cpl_image * be);
+cpl_error_code
+hdrl_elemop_image_pow_image(cpl_image * a, cpl_image * ae,
+                            const cpl_image * b, const cpl_image * be);
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief add/subtract/multiply/divide image and scalar with error propagation
+ *
+ * @param a   image, modified in place
+ * @param ae  errors of image a, modified in place
+ * @param b   scalar
+ * @param be  error of scalar b
+ *
+ * Gaussian error propagation of first order, no accounting correlation
+ * besides a == b.
+ * Divisions by zero will be marked as bad pixels and set to NAN
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_elemop_image_add_scalar(cpl_image * a, cpl_image * ae,
+                          const hdrl_data_t b, const hdrl_error_t be);
+cpl_error_code
+hdrl_elemop_image_sub_scalar(cpl_image * a, cpl_image * ae,
+                          const hdrl_data_t b, const hdrl_error_t be);
+cpl_error_code
+hdrl_elemop_image_mul_scalar(cpl_image * a, cpl_image * ae,
+                          const hdrl_data_t b, const hdrl_error_t be);
+cpl_error_code
+hdrl_elemop_image_div_scalar(cpl_image * a, cpl_image * ae,
+                          const hdrl_data_t b, const hdrl_error_t be);
+cpl_error_code
+hdrl_elemop_image_pow_scalar(cpl_image * a, cpl_image * ae,
+                          const hdrl_data_t b, const hdrl_error_t be);
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief add/subtract/multiply/divide two imagelists and scalar with error
+ *        propagation
+ *
+ * @param a   imagelist, modified in place
+ * @param ae  errors of imagelist a, modified in place
+ * @param b   imagelist
+ * @param be  error of imagelist b
+ *
+ * Gaussian error propagation of first order, no accounting correlation
+ * besides a == b.
+ * Divisions by zero will be marked as bad pixels and set to NAN
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_elemop_imagelist_add_imagelist(cpl_imagelist * a, cpl_imagelist * ae,
+                   const cpl_imagelist * b, const cpl_imagelist * be);
+cpl_error_code
+hdrl_elemop_imagelist_sub_imagelist(cpl_imagelist * a, cpl_imagelist * ae,
+                   const cpl_imagelist * b, const cpl_imagelist * be);
+cpl_error_code
+hdrl_elemop_imagelist_mul_imagelist(cpl_imagelist * a, cpl_imagelist * ae,
+                   const cpl_imagelist * b, const cpl_imagelist * be);
+cpl_error_code
+hdrl_elemop_imagelist_div_imagelist(cpl_imagelist * a, cpl_imagelist * ae,
+                   const cpl_imagelist * b, const cpl_imagelist * be);
+cpl_error_code
+hdrl_elemop_imagelist_pow_imagelist(cpl_imagelist * a, cpl_imagelist * ae,
+                   const cpl_imagelist * b, const cpl_imagelist * be);
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief add/subtract/multiply/divide each image of an imagelist and a
+ *        scalar from a vector with error propagation
+ *
+ * @param a   imagelist, modified in place
+ * @param ae  errors of imagelist a, modified in place
+ * @param b   vector
+ * @param be  error of vector b
+ *
+ * Gaussian error propagation of first order, no accounting correlation
+ * besides a == b.
+ * Divisions by zero will be marked as bad pixels and set to NAN
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_elemop_imagelist_add_vector(cpl_imagelist * a, cpl_imagelist * ae,
+                              const cpl_vector * b, const cpl_vector * be);
+cpl_error_code
+hdrl_elemop_imagelist_sub_vector(cpl_imagelist * a, cpl_imagelist * ae,
+                              const cpl_vector * b, const cpl_vector * be);
+cpl_error_code
+hdrl_elemop_imagelist_mul_vector(cpl_imagelist * a, cpl_imagelist * ae,
+                              const cpl_vector * b, const cpl_vector * be);
+cpl_error_code
+hdrl_elemop_imagelist_div_vector(cpl_imagelist * a, cpl_imagelist * ae,
+                              const cpl_vector * b, const cpl_vector * be);
+cpl_error_code
+hdrl_elemop_imagelist_pow_vector(cpl_imagelist * a, cpl_imagelist * ae,
+                              const cpl_vector * b, const cpl_vector * be);
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief add/subtract/multiply/divide each image of an imagelist and an image
+ *        with error propagation
+ *
+ * @param a   imagelist, modified in place
+ * @param ae  errors of imagelist a, modified in place
+ * @param b   image
+ * @param be  error of image b
+ *
+ * Gaussian error propagation of first order, no accounting correlation
+ * besides a == b.
+ * Divisions by zero will be marked as bad pixels and set to NAN
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_elemop_imagelist_add_image(cpl_imagelist * a, cpl_imagelist * ae,
+                             const cpl_image * b, const cpl_image * be);
+cpl_error_code
+hdrl_elemop_imagelist_sub_image(cpl_imagelist * a, cpl_imagelist * ae,
+                             const cpl_image * b, const cpl_image * be);
+cpl_error_code
+hdrl_elemop_imagelist_mul_image(cpl_imagelist * a, cpl_imagelist * ae,
+                             const cpl_image * b, const cpl_image * be);
+cpl_error_code
+hdrl_elemop_imagelist_div_image(cpl_imagelist * a, cpl_imagelist * ae,
+                             const cpl_image * b, const cpl_image * be);
+cpl_error_code
+hdrl_elemop_imagelist_pow_image(cpl_imagelist * a, cpl_imagelist * ae,
+                             const cpl_image * b, const cpl_image * be);
+
+/* see hdrl_elemop.c for doc strings */
+cpl_error_code hdrl_elemop_add(hdrl_data_t * a, hdrl_error_t * ea, size_t na,
+                            const hdrl_data_t * b, const hdrl_error_t * eb, size_t nb,
+                            const cpl_binary * mask);
+cpl_error_code hdrl_elemop_sub(hdrl_data_t * a, hdrl_error_t * ea, size_t na,
+                            const hdrl_data_t * b, const hdrl_error_t * eb, size_t nb,
+                            const cpl_binary * mask);
+cpl_error_code hdrl_elemop_mul(hdrl_data_t * a, hdrl_error_t * ea, size_t na,
+                            const hdrl_data_t * b, const hdrl_error_t * eb, size_t nb,
+                            const cpl_binary * mask);
+cpl_error_code hdrl_elemop_div(hdrl_data_t * a, hdrl_error_t * ea, size_t na,
+                            const hdrl_data_t * b, const hdrl_error_t * eb, size_t nb,
+                            const cpl_binary * mask);
+cpl_error_code hdrl_elemop_pow(hdrl_data_t * a, hdrl_error_t * ea, size_t na,
+                            const hdrl_data_t * b, const hdrl_error_t * eb, size_t nb,
+                            const cpl_binary * mask);
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+ -----------------------------------------------------------------------------*/
+
+#ifdef HDRL_USE_PRIVATE
+
+#endif
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_fit.c b/hdrl/hdrl_fit.c
new file mode 100644
index 0000000..599f4bd
--- /dev/null
+++ b/hdrl/hdrl_fit.c
@@ -0,0 +1,501 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+-----------------------------------------------------------------------------*/
+
+#include "hdrl_types.h"
+#include "hdrl_image.h"
+#include "hdrl_imagelist.h"
+#include "hdrl_utils.h"
+
+#include <cpl.h>
+#include <math.h>
+#include <assert.h>
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_fit     Fitting
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+
+/*-----------------------------------------------------------------------------
+                                   Static
+ -----------------------------------------------------------------------------*/
+
+/** @cond PRIVATE */
+
+cpl_matrix * cpl_matrix_product_normal_create(const cpl_matrix * self);
+cpl_error_code cpl_matrix_product_transpose(cpl_matrix * self,
+                                            const cpl_matrix * ma,
+                                            const cpl_matrix * mb);
+
+typedef struct {
+    /* input design matrix of fit */
+    cpl_matrix * design;
+    /* coefficient row matrix */
+    cpl_matrix * coef;
+    /* covariance matrix of coefficients */
+    cpl_matrix * cov;
+} hdrl_ls_fit_result;
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create least squares fit result structure
+ * @return  fit result structure
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_ls_fit_result * hdrl_ls_fit_result_create(void)
+{
+    return cpl_calloc(1, sizeof(hdrl_ls_fit_result));
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief delete least squares fit result structure
+ * @param fit result structure, may be NULL
+ */
+/* ---------------------------------------------------------------------------*/
+void hdrl_ls_fit_result_delete(hdrl_ls_fit_result * r)
+{
+    if (r == NULL)
+        return;
+    cpl_matrix_delete(r->design);
+    cpl_matrix_delete(r->coef);
+    cpl_matrix_delete(r->cov);
+    cpl_free(r);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get fitted values from a least squares fit result
+ * @param r fit result structure
+ * @return vector containing the fitted values
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_vector * hdrl_ls_fit_result_get_fitted_values(
+      const hdrl_ls_fit_result * r)
+{
+    cpl_matrix * fvalues = cpl_matrix_product_create(r->design, r->coef);
+    cpl_vector * res = cpl_vector_wrap(cpl_matrix_get_nrow(fvalues),
+                                       cpl_matrix_get_data(fvalues));
+    cpl_matrix_unwrap(fvalues);
+    return res;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get fit residuals from a least squares fit result
+ * @param r    fit result structure
+ * @param data data which from which the fitted values are subtracted
+ * @return vector of residuals
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_vector * hdrl_ls_fit_result_get_residuals(
+      const hdrl_ls_fit_result * r,
+      const cpl_vector * data)
+{
+    cpl_vector * fval = hdrl_ls_fit_result_get_fitted_values(r);
+    cpl_vector * res = cpl_vector_duplicate(data);
+    cpl_vector_subtract(res, fval);
+    cpl_vector_delete(fval);
+    return res;
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get squared chi of a least squares fit result
+ * @param r      fit result structure
+ * @param data   data of the fit
+ * @param errors errors of the fit
+ * @return  squared chi statistic of the fit
+ *
+ * the chi square is computed as:
+ * sum_i(1/sigma_i^2 * residual_i ^ 2)
+ */
+/* ---------------------------------------------------------------------------*/
+double hdrl_ls_fit_result_get_chi2(
+      const hdrl_ls_fit_result * r,
+      const cpl_vector * data,
+      cpl_vector * errors)
+{
+    cpl_vector * fval = hdrl_ls_fit_result_get_residuals(r, data);
+    /* mse = sum(sqrt(weights) * residuals ** 2) / df */
+    cpl_vector_divide(fval, errors);
+    cpl_vector_multiply(fval, fval);
+    double mswd = cpl_vector_get_sum(fval);
+
+    cpl_vector_delete(fval);
+    return mswd;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get degrees of freedom of a least squares fit
+ * @param r fit result structure
+ * @return degrees of freedom
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_size hdrl_ls_fit_result_get_residual_dof(const hdrl_ls_fit_result * r)
+{
+    return cpl_matrix_get_nrow(r->design) - cpl_matrix_get_ncol(r->design);
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief return prediction interval for the data
+ *
+ * @param r       fit result
+ * @param data    data
+ * @param errors  errors
+ * @return        vector of symmetric prediction interval for data
+ *
+ * The prediction interval is the one sigma area in which new measurements from
+ * the same setup are going to lie. It is not the error of the fitted
+ * coefficients which is much smaller due to the use of all values from data to
+ * compute them.
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_vector * hdrl_ls_fit_result_get_fit_interval(
+      const hdrl_ls_fit_result * r,
+      const cpl_vector * data,
+      cpl_vector * errors)
+{
+    /* mse = sum(sqrt(weights) * residuals ** 2) / df */
+    double mse = hdrl_ls_fit_result_get_chi2(r, data, errors) /
+        hdrl_ls_fit_result_get_residual_dof(r);
+    /* var = mse / weights */
+    cpl_vector  * serror = cpl_vector_duplicate(errors);
+    cpl_vector_multiply(serror, serror);
+    cpl_vector_multiply_scalar(serror, mse);
+    cpl_vector_power(serror, 0.5);
+
+    /* TODO: accounting for covariance missing
+     * + (exog * np.dot(covb, exog.T).T).sum(axis=1) */
+
+    return serror;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+* @brief generic 1d vandermonde matrix
+*
+* @param sample  sampling positions
+* @param degree  degree of polynomial
+* @param func    function evaluating polynomials from [0, degree] at
+*                sampling point
+* @return matrix containing the vandermonde matrix
+*/
+/* ---------------------------------------------------------------------------*/
+static cpl_matrix * vander1d(
+          const cpl_vector * sample,
+          cpl_size           degree,
+          void (*func)(double, double *, size_t))
+{
+    const size_t nr = cpl_vector_get_size(sample);
+    const size_t nc = degree + 1;
+    cpl_matrix * V = cpl_matrix_new(nr, nc);
+    double * v = cpl_matrix_get_data(V);
+    const double * d = cpl_vector_get_data_const(sample);
+    for (size_t i = 0; i < nr; i++) {
+        func(d[i], &v[i*nc], nc);
+    }
+
+    return V;
+}
+
+static void polynomial(double x, double * p, size_t ncoefs)
+{
+    p[0] = 1.;
+    for (size_t i = 1; i < ncoefs; i++) {
+        p[i] = pow(x, i);
+    }
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief get vandermonde matrix for a 1d polynomial
+ * @param sample  sampling positions
+ * @param degree  degree of polynomial
+ * @return matrix containing the vandermonde matrix
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_matrix * polyvander1d(
+        const cpl_vector * sample,
+        cpl_size           degree)
+{
+    return vander1d(sample, degree, &polynomial);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief perform a least squares fit
+ * @param design  design matrix
+ * @param values  data to fit
+ * @param errors  errors of data
+ * @return fit result structure
+ *         must be deleted with hdrl_ls_fit_result_delete()
+ */
+/* ---------------------------------------------------------------------------*/
+static hdrl_ls_fit_result * fit(
+         const cpl_matrix * design,
+         const cpl_vector * values,
+         const cpl_vector * errors)
+{
+    hdrl_ls_fit_result * r = hdrl_ls_fit_result_create();
+    r->design = cpl_matrix_duplicate(design);
+    if (errors) {
+        assert(cpl_matrix_get_nrow(design) == cpl_vector_get_size(errors));
+        /* weight response and design */
+        cpl_vector * vrhs = cpl_vector_duplicate(errors);
+        cpl_vector_power(vrhs, -1);
+        cpl_matrix * wdesign = cpl_matrix_duplicate(design);
+        for (size_t i = 0; i < (size_t)cpl_vector_get_size(errors); i++) {
+            double w = cpl_vector_get(vrhs, i);
+            for (size_t j = 0; j < (size_t)cpl_matrix_get_ncol(wdesign); j++) {
+                cpl_matrix_set(wdesign, i, j,
+                               cpl_matrix_get(wdesign, i, j) * w);
+            }
+        }
+
+        cpl_vector_multiply(vrhs, values);
+        cpl_matrix * rhs = cpl_matrix_wrap(cpl_vector_get_size(vrhs), 1,
+                                           cpl_vector_get_data(vrhs));
+
+        /* solve Ax = b */
+        /* cpl_matrix_solve_normal(design, rhs) + covariance */
+        {
+            cpl_matrix * At  = cpl_matrix_transpose_create(wdesign);
+            cpl_matrix * AtA = cpl_matrix_product_normal_create(At);
+
+            /* RRt = AtA */
+            cpl_matrix_decomp_chol(AtA);
+            /* solve for pseudo inverse: (RRt)P=At*/
+            cpl_matrix_solve_chol(AtA, At);
+            /* compute solution to system Ax=b -> x=Pb */
+            r->coef = cpl_matrix_product_create(At, rhs);
+            /* compute covariance matrix cov(b) = PPt */
+            r->cov = cpl_matrix_new(cpl_matrix_get_ncol(At),
+                                    cpl_matrix_get_ncol(At));
+            cpl_matrix_product_transpose(r->cov, At, At);
+
+            cpl_matrix_delete(At);
+            cpl_matrix_delete(AtA);
+        }
+
+        cpl_matrix_unwrap(rhs);
+        cpl_vector_delete(vrhs);
+        cpl_matrix_delete(wdesign);
+    }
+    else {
+        cpl_vector * vrhs = cpl_vector_duplicate(values);
+        cpl_matrix * rhs = cpl_matrix_wrap(cpl_vector_get_size(vrhs), 1,
+                                           cpl_vector_get_data(vrhs));
+        r->coef = cpl_matrix_solve_normal(design, rhs);
+        cpl_matrix_unwrap(rhs);
+        cpl_vector_delete(vrhs);
+    }
+    return r;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief perform 1d polynomial least squares fit
+ *
+ * @param sample  sampling points
+ * @param values  values to fit
+ * @param errors  errors to fit
+ * @param degree  degree of polynomial to fit
+ * @return fit result structure
+ *         must be deleted with hdrl_ls_fit_result_delete()
+ * @see fit, polyvander1d
+ */
+/* ---------------------------------------------------------------------------*/
+static hdrl_ls_fit_result * polyfit1d(
+         const cpl_vector * sample,
+         const cpl_vector * values,
+         const cpl_vector * errors,
+         int degree)
+{
+    cpl_matrix * design = polyvander1d(sample, degree);
+    hdrl_ls_fit_result * r = fit(design, values, errors);
+    cpl_matrix_delete(design);
+    return r;
+}
+/** @endcond */
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief weighted least squares polynomial fit of each pixel of a imagelist
+ *
+ * @param list      imagelist to fit, the 1/errors^2 are used as the weights of
+ *                  the fit
+ * @param samplepos vector of sample position of each image in the list
+ * @param degree    degree of the fit starting from 0
+ * @param coef      output coefficient hdrl_imagelist, the data contains the
+ *                  coefficient the error contains the diagonal element of the
+ *                  covariance matrix
+ * @param chi2      output double cpl_image, contains the chi2 of the fit
+ * @param dof       output double cpl_image, contains the degrees of freedom of
+ *                  the residuals
+ *
+ *  @note the errors only need to be relative correct, if the are wrong by a
+ *        constant the real errors of the data points can be estimated by
+ *        multiplying the squared errors with chi2/dof
+ *        The fitting method uses normal equation so the function should not be
+ *        used for badly conditioned data.
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_fit_polynomial_imagelist(const hdrl_imagelist * list,
+                              const cpl_vector * samplepos,
+                              const int degree,
+                              hdrl_imagelist ** coef,
+                              cpl_image ** chi2,
+                              cpl_image ** dof)
+{
+    cpl_ensure_code(degree >= 0, CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(list && samplepos && coef, CPL_ERROR_NULL_INPUT);
+    // TODO test
+    cpl_ensure_code(cpl_vector_get_size(samplepos) ==
+                    hdrl_imagelist_get_size(list),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(cpl_vector_get_size(samplepos) ==
+                    hdrl_imagelist_get_size(list),
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_ensure_code(hdrl_imagelist_get_size(list) > 0,
+                    CPL_ERROR_INCOMPATIBLE_INPUT);
+    intptr_t nx = hdrl_imagelist_get_size_x(list);
+    intptr_t ny = hdrl_imagelist_get_size_y(list);
+    size_t noz = degree + 1;
+
+    *coef = hdrl_imagelist_new();
+    if (chi2) {
+        *chi2 = cpl_image_new(nx, ny, HDRL_TYPE_DATA);
+    }
+    if (dof) {
+        *dof = cpl_image_new(nx, ny, HDRL_TYPE_DATA);
+    }
+    for (size_t z = 0; z < noz; z++) {
+        hdrl_imagelist_set(*coef, hdrl_image_new(nx, ny), z);
+    }
+    cpl_imagelist * datal, *errorl;
+    if (hdrl_imagelist_to_cplwrap(list, &datal, &errorl)) {
+        goto fail;
+    }
+HDRL_OMP(omp parallel for shared(coef, chi2, dof))
+    for (intptr_t y = 0; y < ny; y++) {
+        cpl_vector * datav[nx];
+        cpl_vector * errsv[nx];
+        hdrl_imagelist_to_vector_row(datal, y + 1, datav);
+        hdrl_imagelist_to_vector_row(errorl, y + 1, errsv);
+        for (intptr_t x = 0; x < nx; x++) {
+            /* all bad or less good than fit degrees */
+            cpl_vector * data = datav[x];
+            cpl_vector * errs = errsv[x];
+            if (data == NULL || (size_t)cpl_vector_get_size(data) < noz) {
+                for (size_t z = 0; z < noz; z++) {
+                    hdrl_image * oimg = hdrl_imagelist_get(*coef, z);
+                    hdrl_image_set_pixel(oimg, x + 1, y + 1,
+                                         (hdrl_value){NAN, NAN});
+                    hdrl_image_reject(oimg, x + 1, y + 1);
+                }
+                if (chi2) {
+                    cpl_image_set(*chi2, x + 1, y + 1, NAN);
+                    cpl_image_reject(*chi2, x + 1, y + 1);
+                }
+                if (dof) {
+                    int n = data ? cpl_vector_get_size(data) - noz : -noz;
+                    cpl_image_set(*dof, x + 1, y + 1, n);
+                    cpl_image_reject(*dof, x + 1, y + 1);
+                }
+                continue;
+            }
+
+            /* remove bad pixelse from sample positions, TODO, cleanup */
+            cpl_vector * nsamppos;
+            if (cpl_vector_get_size(data) != cpl_vector_get_size(samplepos)) {
+                size_t j = 0;
+                nsamppos = cpl_vector_new(cpl_vector_get_size(data));
+                for (size_t i = 0; i < (size_t)hdrl_imagelist_get_size(list); i++) {
+                    hdrl_image * img = hdrl_imagelist_get(list, i);
+                    if (hdrl_image_is_rejected(img, x + 1, y + 1))
+                        continue;
+                    cpl_vector_set(nsamppos, j++, cpl_vector_get(samplepos, i));
+                }
+            }
+            else {
+                nsamppos = cpl_vector_duplicate(samplepos);
+            }
+            hdrl_ls_fit_result * r = polyfit1d(nsamppos, data, errs, degree);
+            // TODO handle failure
+            for (size_t z = 0; z < noz; z++) {
+                hdrl_image * oimg = hdrl_imagelist_get(*coef, z);
+                hdrl_image_set_pixel(oimg, x + 1, y + 1,
+                         (hdrl_value){cpl_matrix_get(r->coef, z, 0),
+                                      sqrt(cpl_matrix_get(r->cov, z, z))});
+            }
+            if (chi2) {
+                cpl_image_set(*chi2, x + 1, y + 1,
+                              hdrl_ls_fit_result_get_chi2(r, data, errs));
+            }
+            if (dof) {
+                cpl_image_set(*dof, x + 1, y + 1,
+                              hdrl_ls_fit_result_get_residual_dof(r));
+            }
+            hdrl_ls_fit_result_delete(r);
+            cpl_vector_delete(data);
+            cpl_vector_delete(errs);
+            cpl_vector_delete(nsamppos);
+        }
+    }
+
+    cpl_imagelist_unwrap(datal);
+    cpl_imagelist_unwrap(errorl);
+
+    return cpl_error_get_code();
+fail:
+    hdrl_imagelist_delete(*coef);
+    *coef = NULL;
+    if (chi2) {
+        cpl_image_delete(*chi2);
+        *chi2 = NULL;
+    }
+    if (dof) {
+        cpl_image_delete(*dof);
+        *dof = NULL;
+    }
+    return cpl_error_get_code();
+}
+/**@}*/
+
diff --git a/hdrl/hdrl_fit.h b/hdrl/hdrl_fit.h
new file mode 100644
index 0000000..50adc3b
--- /dev/null
+++ b/hdrl/hdrl_fit.h
@@ -0,0 +1,57 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_FIT_H
+#define HDRL_FIT_H
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+#include "hdrl_imagelist.h"
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                                Define
+ -----------------------------------------------------------------------------*/
+
+/*-----------------------------------------------------------------------------
+                            Functions prototypes
+ -----------------------------------------------------------------------------*/
+
+cpl_error_code
+hdrl_fit_polynomial_imagelist(const hdrl_imagelist * list,
+                              const cpl_vector * samplepos,
+                              const int degree,
+                              hdrl_imagelist ** coef,
+                              cpl_image ** chi2,
+                              cpl_image ** dof);
+
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+ -----------------------------------------------------------------------------*/
+
+#ifdef HDRL_USE_PRIVATE
+
+#endif
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_flat.c b/hdrl/hdrl_flat.c
new file mode 100644
index 0000000..a65be5c
--- /dev/null
+++ b/hdrl/hdrl_flat.c
@@ -0,0 +1,561 @@
+/* $Id: hdrl_flat.c,v 1.29 2013-09-25 11:04:29 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-09-25 11:04:29 $
+ * $Revision: 1.29 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+-----------------------------------------------------------------------------*/
+
+#include "hdrl_flat.h"
+
+#include "hdrl_collapse.h"
+#include "hdrl_combine.h"
+#include "hdrl_elemop.h"
+#include "hdrl_prototyping.h"
+#include "hdrl_utils.h"
+
+#include <cpl.h>
+
+#include <assert.h>
+#include <stdint.h>
+
+/*-----------------------------------------------------------------------------
+                                   Static
+ -----------------------------------------------------------------------------*/
+
+typedef enum {
+    _HDRL_MEDIAN_SMOOTH,
+    _HDRL_GAUSS_SMOOTH,
+    _HDRL_MEDIAN_STEP_FIT
+} _hdrl_internal_method;
+
+static cpl_error_code hdrl_compute_flat(const cpl_imagelist *, 
+        const cpl_imagelist *, hdrl_collapse_imagelist_to_image_t *,
+        cpl_image *, cpl_image *, cpl_image **, cpl_image **, cpl_image **, 
+        _hdrl_internal_method, void *);
+static cpl_image * hdrl_medianclean_image(cpl_image *, cpl_size, cpl_size, 
+        cpl_size, cpl_size);
+static cpl_image * hdrl_smooth_image_median(const cpl_image *, int);
+
+/** @cond PRIVATE */
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_flat   Flat Module
+  This module provides functionality to compute a master flat frame out of
+  several inputs. Several methods are available to deal with different flat
+  characteristics
+
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+typedef struct {
+    cpl_size filter_size;
+} _hdrl_median_smooth_par;
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief compute master flat with median filtering on exposure map
+ *
+ * @param data               input flats
+ * @param errs               input flats errors
+ * @param collapse_mode      method to collapse to master flat
+ * @param filter_size        size of median filter
+ * @param master_shape       optional initial master shape
+ * @param master_shape_err   optional initial master shape error
+ * @param flat_img           output flat
+ * @param flat_err           output flat error
+ * @param flat_ctr           output flat contribution map
+ *
+ * TODO describe algorithm (refer to called lower level function)
+ * iterative + median filter on exposure map (= flat / masterflat)
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_compute_flat_median_smooth(
+        const cpl_imagelist                 *   data,
+        const cpl_imagelist                 *   errs,
+        hdrl_collapse_imagelist_to_image_t  *   collapse_mode,
+        cpl_size                                filter_size,
+        cpl_image                           *   master_shape,
+        cpl_image                           *   master_shape_err,
+        cpl_image                           **  flat_img, 
+        cpl_image                           **  flat_err,
+        cpl_image                           **  flat_ctr)
+{
+    _hdrl_median_smooth_par par;
+    par.filter_size = filter_size;
+    return hdrl_compute_flat(data, errs, collapse_mode, master_shape,
+                             master_shape_err, flat_img, flat_err, flat_ctr,
+                             _HDRL_MEDIAN_SMOOTH, &par);
+}
+
+typedef struct {
+    cpl_size filter_size;
+    cpl_size mirror_x;
+    cpl_size mirror_y;
+} _hdrl_gauss_smooth_par;
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief compute master flat with Gauss smoothing on exposure map
+ *
+ * @param data               input flats
+ * @param errs               input flats errors
+ * @param collapse_mode      method to collapse to master flat
+ * @param filter_size        size of median filter
+ * @param mirror_x           implemented as FFT with mirroring
+ * @param mirror_y           implemented as FFT with mirroring
+ * @param master_shape       optional initial master shape
+ * @param master_shape_err   optional initial master shape error
+ * @param flat_img           output flat
+ * @param flat_err           output flat error
+ * @param flat_ctr           output flat contribution map
+ *
+ * TODO describe algorithm (refer to called lower level function)
+ * iterative + Gauss filter on exposure map (= flat / masterflat)
+ * implemented as FFT thus needs mirroring values
+ * should probably be implemented in normal space with decomposed Gauss instead
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_compute_flat_gauss_smooth(
+        const cpl_imagelist                 *   data,
+        const cpl_imagelist                 *   errs,
+        hdrl_collapse_imagelist_to_image_t  *   collapse_mode,
+        cpl_size                                filter_size,
+        cpl_size                                mirror_x,
+        cpl_size                                mirror_y,
+        cpl_image                           *   master_shape,
+        cpl_image                           *   master_shape_err,
+        cpl_image                           **  flat_img, 
+        cpl_image                           **  flat_err,
+        cpl_image                           **  flat_ctr)
+{
+    _hdrl_gauss_smooth_par par;
+    par.filter_size = filter_size;
+    par.mirror_x = mirror_x;
+    par.mirror_y = mirror_y;
+    return hdrl_compute_flat(data, errs, collapse_mode, master_shape,
+                             master_shape_err, flat_img, flat_err, flat_ctr,
+                             _HDRL_GAUSS_SMOOTH, &par);
+}
+
+typedef struct {
+    cpl_size    filter_size_x;
+    cpl_size    filter_size_y;
+    cpl_size    steps_x;
+    cpl_size    steps_y;
+    int         order_x;
+    int         order_y;
+} _hdrl_step_fit_par;
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief compute master flat with polynomial fit to exposure map
+ *
+ * @param data               input flats
+ * @param errs               input flats errors
+ * @param collapse_mode      method to collapse to master flat
+ * @param filter_size_x      size of median filter in x
+ * @param filter_size_y      size of median filter in y
+ * @param steps_x            number of steps in x to evaluate median on
+ * @param steps_y            number of steps in y to evaluate median on
+ * @param order_x            order of the polynomial in x
+ * @param order_y            order of the polynomial in y
+ * @param master_shape       optional initial master shape
+ * @param master_shape_err   optional initial master shape error
+ * @param flat_img           output flat
+ * @param flat_err           output flat error
+ * @param flat_ctr           output flat contribution map
+ *
+ * TODO describe algorithm (refer to called lower level function)
+ * iterative + strided median filter on exposure map (= flat / masterflat) +
+ * polyfit to filtered image
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_compute_flat_median_step_fit(
+        const cpl_imagelist                 *   data,
+        const cpl_imagelist                 *   errs,
+        hdrl_collapse_imagelist_to_image_t  *   collapse_mode,
+        cpl_size                                filter_size_x,
+        cpl_size                                filter_size_y,
+        cpl_size                                steps_x,
+        cpl_size                                steps_y,
+        int                                     order_x,
+        int                                     order_y,
+        cpl_image                           *   master_shape,
+        cpl_image                           *   master_shape_err,
+        cpl_image                           **  flat_img,
+        cpl_image                           **  flat_err,
+        cpl_image                           **  flat_ctr)
+{
+    _hdrl_step_fit_par par;
+    /* TODO: should we check that input have proper input values ? */
+    /* TODO: add proper comment, for example
+     * init par structure parameters
+     */
+    par.filter_size_x = filter_size_x;
+    par.filter_size_y = filter_size_y;
+    par.steps_x = steps_x;
+    par.steps_y = steps_y;
+    par.order_x = order_x;
+    par.order_y = order_y;
+    return hdrl_compute_flat(data, errs, collapse_mode, master_shape, 
+            master_shape_err, flat_img, flat_err, flat_ctr, 
+            _HDRL_MEDIAN_STEP_FIT, &par);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief compute master flat
+ * @param data             bias and dark corrected image data
+ * @param errs             errors of data
+ * @param collapse_mode    method to collapse data to flag
+ * @param master_shape     shape where the single flats are bend towards
+ * @param master_shape_err error of the shape where each flat is bend towards
+ * @param flat_img         resulting flat
+ * @param flat_err         error of flat
+ * @param flat_ctr         contribution map of flat
+ * @param method           method switch to choose image smoothing algorithm
+ * @param par              image smoothing algorithm parameters
+ * 
+ * DONE (AMO): describe algorithm
+ *
+ * -check input frames are proper
+ *
+ * -before the final master frame is generate make sure each flat component
+ * has the same level and shape. In order to compute properly each flat level
+ * its shape need to be removed. As the shape information is contained in the
+ * master flat that is also a product of this data reduction step we need to
+ * perform iterations. The user may decide to provide an input shape (if
+ * available) or let the function to find one. In this last case a master flat
+ * is computed by simple mean-stack of each input frame (without error
+ * propagation, as the error information is actually needed only from the last
+ * iteration).
+ *
+ * For each iteration:
+ *
+ * -we divide each flat frame for the current master flat to remove the shape of
+ * the flat (at last iteration the division is performed with error propagation)
+ *
+ * -we compute the flat estimator (a single number) using one of the possible
+ * criteria (median-smooth over a rectangular box with interpolation of rejected
+ * pixels, median-step over a rectangular box with fit of a Legendre polynomial
+ * in each box, Gaussian smooth over rectangular box)
+ *
+ * Finally we divide each imagelist by the final master with variance
+ * propagation and combine them into the final master flat using any of the
+ * available methods(mean, weighted mean, median, sigma-clip)
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code hdrl_compute_flat(
+        const cpl_imagelist                 *   data, 
+        const cpl_imagelist                 *   errs,
+        hdrl_collapse_imagelist_to_image_t  *   collapse_mode,
+        cpl_image                           *   master_shape, 
+        cpl_image                           *   master_shape_err,
+        cpl_image                           **  flat_img, 
+        cpl_image                           **  flat_err,
+        cpl_image                           **  flat_ctr, 
+        _hdrl_internal_method                   method,
+        void                                *   par)
+{
+    cpl_image * comb_img = NULL;
+    cpl_image * comb_err = NULL;
+    cpl_image * comb_ctr = NULL;
+    /* TODO: should we check that input have proper input values ? */
+    /* TODO: quite long function implementation. Should we re-factor it */
+    /* TODO should the following niter_max a hard-coded variable?
+     * better a const or a define if not an algorithm parameter
+     */
+    size_t niter_max = 3;
+
+    /* TODO: check that the size of the master_shape and master_shape_err
+     * is the same as the size of the image in the imagelists*/
+
+    cpl_msg_info(cpl_func, "Creating first Master Flat");
+    cpl_msg_indent_more();
+
+    /*If we pass a master-shape image to the function use this as
+     * first master flat*/
+    if (master_shape != NULL) {
+        comb_img = cpl_image_duplicate(master_shape);
+        /*If we pass a master-shape image to the function do only one
+         * iteration*/
+        niter_max = 1;
+        /* optional error of the shape */
+        if (master_shape_err != NULL) {
+            comb_err = cpl_image_duplicate(master_shape_err);
+        }
+    } else {
+        /* Generate 1st master flat */
+        /*No error propagation needed in the first iteration*/
+        cpl_imagelist * data_loc = cpl_imagelist_duplicate(data);
+        cpl_msg_info(cpl_func, "Scale all flats to unity by the mean");
+        cpl_imagelist_normalise(data_loc, CPL_NORM_MEAN);
+        cpl_msg_info(cpl_func, "Combining all scaled flats by the median");
+        comb_img = cpl_imagelist_collapse_median_create(data_loc);
+        cpl_imagelist_delete(data_loc);
+        comb_err = cpl_image_duplicate(comb_img);
+        cpl_image_multiply_scalar(comb_err, 0);
+    }
+    cpl_msg_indent_less();
+
+    cpl_msg_info(cpl_func, "Start iterative process");
+    cpl_msg_indent_more();
+    /* TODO: should we factor-out the following long loop ? May be not as it is
+     * de facto the full job of this function */
+    /* Here we perform several iterations to optimize the master flat shape */
+    for (size_t i = 0; i < niter_max; i++) {
+        cpl_msg_indent_less();
+        cpl_msg_info(cpl_func, "Iteration %zu out of %zu", i + 1, niter_max);
+        cpl_msg_indent_more();
+
+        /*Restore original flat-fields but use the new master-flat*/
+        cpl_msg_info(cpl_func, "Restore the original flatfields");
+        cpl_imagelist * imglist = cpl_imagelist_duplicate(data);
+        cpl_imagelist * errlist = cpl_imagelist_duplicate(errs);
+
+        /*Divide flat-fields through the masterflat -> esposure-time map*/
+        cpl_msg_info(cpl_func, "Divide single flatfields through the (new) "
+                        "masterflat to get an exposure-time map for each "
+                        "flatfield");
+        /* only propagate error of master flat in last iteration */
+        if (i == niter_max - 1) {
+            /* TODO: function name. Here we perform division of two imagelists
+             * with proper error (and bad pixel) propagation. This is done via
+             * auxilliary arrays. If we follow cpl naming convention may be
+             * better (clear but long) name is:
+             * hdrl_imagelist_divide_errorpropagate ?
+             */
+            hdrl_elemop_imagelist_div_image(imglist, errlist, comb_img, comb_err);
+        } else {
+            cpl_imagelist_divide_image(imglist, comb_img);
+        }
+
+        /*  delete old masterframe and compute the new master frame */
+        cpl_image_delete(comb_img);
+        cpl_image_delete(comb_err);
+        cpl_image_delete(comb_ctr);
+
+        /* smooth residuals  */
+        cpl_msg_info(cpl_func, "Smooth the exposure-time maps");
+
+        for(cpl_size j = 0; j < cpl_imagelist_get_size(imglist); j++){
+            cpl_msg_info(cpl_func, "working on image %d", (int)j+1);
+            cpl_image * imgtmp = cpl_imagelist_get(imglist, j);
+            cpl_image * r;
+            if (method == _HDRL_MEDIAN_SMOOTH) {
+                /* Method 1*/
+                /* removing bad pixels allows use of a much faster algorithm */
+                cpl_size fsize = ((_hdrl_median_smooth_par *)par)->filter_size;
+                cpl_detector_interpolate_rejected(imgtmp);
+                /* TODO: naming conventions. Should we name functions as
+                 * hdrl_object_operation_specifier or
+                 * hdrl_operation_object_specifier?
+                 */
+                r = hdrl_smooth_image_median(imgtmp, fsize);
+            } else if (method == _HDRL_GAUSS_SMOOTH) {
+                _hdrl_gauss_smooth_par * p = (_hdrl_gauss_smooth_par *)par;
+                /* TODO: naming convention should the function name contain the
+                 * object it operates on==>hdrl_image_get_spatial_freq()
+                 */
+                r = hdrl_get_spatial_freq(imgtmp, p->filter_size,
+                                          p->mirror_x, p->mirror_y);
+            } else if (method == _HDRL_MEDIAN_STEP_FIT) {
+                _hdrl_step_fit_par * p = (_hdrl_step_fit_par *)par;
+                cpl_size nx = cpl_image_get_size_x(imgtmp);
+                cpl_size ny = cpl_image_get_size_y(imgtmp);
+                cpl_size sx = CX_MAX(nx / p->steps_x, 1);
+                cpl_size sy = CX_MAX(ny / p->steps_y, 1);
+
+                /* fit to stepped grid */
+                cpl_matrix * x = hdrl_matrix_linspace(sx / 2, nx, sx);
+                cpl_matrix * y = hdrl_matrix_linspace(sy / 2, ny, sy);
+                cpl_image * imgtmp_mod =
+                    hdrl_medianfilter_image_grid(imgtmp, x, y,
+                                                 p->filter_size_x,
+                                                 p->filter_size_y);
+                cpl_matrix * coeffs = hdrl_fit_legendre(imgtmp_mod,
+                                                        p->order_x, p->order_y,
+                                                        x, y, nx, ny);
+                /* TODO: naming conventions: hdrl_matrix_legendre_to_image() */
+                r = hdrl_legendre_to_image(coeffs,
+                                           p->order_x, p->order_y,
+                                           nx, ny);
+
+                if (cpl_msg_get_level() == CPL_MSG_DEBUG)
+                    cpl_matrix_dump(coeffs, stdout);
+
+                cpl_matrix_delete(coeffs);
+                cpl_matrix_delete(x);
+                cpl_matrix_delete(y);
+                cpl_image_delete(imgtmp_mod);
+            } else {
+                abort();
+            }
+            cpl_imagelist_set(imglist, r, j);
+        }
+
+        cpl_msg_info(cpl_func, "Divide the original flatfields by the smoothed "
+                        "exposure-time map");
+
+        /* Divide flatfields through the smoothed exposure-time map*/
+        cpl_imagelist * div_imglist = cpl_imagelist_duplicate(data);
+        cpl_imagelist * div_errlist = cpl_imagelist_duplicate(errs);
+        hdrl_elemop_imagelist_div_imagelist(div_imglist, div_errlist,
+                                            imglist, errlist);
+        cpl_imagelist_delete(imglist);
+        cpl_imagelist_delete(errlist);
+
+        cpl_msg_info(cpl_func, "Combine the resulting normalized flatfields by "
+                        "your preferred algorithm and generate a new(!)"
+                        " masterflat");
+
+        hdrl_imagelist_combine(div_imglist, div_errlist, collapse_mode,
+                               &comb_img, &comb_err, &comb_ctr);
+
+        cpl_imagelist_delete(div_imglist);
+        cpl_imagelist_delete(div_errlist);
+
+        if (cpl_error_get_code()) break;
+    }
+
+    if (cpl_error_get_code()) {
+        cpl_image_delete(comb_img);
+        cpl_image_delete(comb_err);
+        cpl_image_delete(comb_ctr);
+    } else {
+        *flat_img = comb_img;
+        *flat_err = comb_err;
+        *flat_ctr = comb_ctr;
+    }
+
+    cpl_msg_indent_less();
+    return cpl_error_get_code();
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief computes the median in predefined regions
+ *
+ * @param ima           image with the data
+ * @param steps_x       number of steps in x where the median is calculated
+ * @param steps_y       number of steps in y where the median is calculated
+ * @param filtersize_x  half-size median-box in x where the median is calculated
+ * @param filtersize_y  half-size median-box in y where the median is calculated
+ *
+ * @return  median filtered image
+ *
+ * DONE (AMo): describe algorithm
+ * This function computes an image where each pixel value is obtained by a median
+ * every x and y steps in an image of half-box size filtersize_x, filtersize_y.
+ * It is assumed that the resulting bad pixel is good.
+ * TODO: what happens if some of the full boxes over which the median is
+ * computed is full of bad pixels?
+ */
+/* ---------------------------------------------------------------------------*/
+static inline cpl_image * hdrl_medianclean_image(
+        cpl_image   *   ima, 
+        cpl_size        steps_x, 
+        cpl_size        steps_y,
+        cpl_size        filtersize_x, 
+        cpl_size        filtersize_y) 
+{
+    cpl_error_ensure(ima != NULL, CPL_ERROR_NULL_INPUT,
+            return NULL, "NULL input image");
+    cpl_error_ensure(steps_x > 0 && steps_y > 0 && filtersize_x > 0 &&
+            filtersize_y > 0 , CPL_ERROR_INCOMPATIBLE_INPUT,
+            return NULL, "All function parameters must be greater then Zero");
+
+    const cpl_size nx = cpl_image_get_size_x(ima);
+    const cpl_size ny = cpl_image_get_size_y(ima);
+    const cpl_size stepsize_x = (cpl_size)(nx / steps_x);
+    cpl_size stepsize_y = (cpl_size)(ny / steps_y);
+    cpl_image * ima_local = cpl_image_new(nx, ny, CPL_TYPE_DOUBLE);
+    cpl_mask_not(cpl_image_get_bpm(ima_local));
+
+    for (cpl_size iy = 0; iy < steps_y; iy++) {
+        for (cpl_size ix = 0; ix < steps_x; ix++) {
+            cpl_size middlep_x = (cpl_size)(stepsize_x * ix + stepsize_x / 2.);
+            cpl_size middlep_y = (cpl_size)(stepsize_y * iy + stepsize_y / 2.);
+
+            cpl_size lowerlimit_x = CX_MAX(middlep_x - filtersize_x, 1);
+            cpl_size lowerlimit_y = CX_MAX(middlep_y - filtersize_y, 1);
+            cpl_size upperlimit_x = CX_MIN(middlep_x + filtersize_x, nx);
+            cpl_size upperlimit_y = CX_MIN(middlep_y + filtersize_y, ny);
+
+            double median = cpl_image_get_median_window(ima, lowerlimit_x,
+                            lowerlimit_y, upperlimit_x, upperlimit_y);
+
+            cpl_image_set(ima_local, middlep_x, middlep_y, median);
+            cpl_image_accept(ima_local, middlep_x, middlep_y);
+
+            cpl_msg_debug(cpl_func, "middlep_x: %lld, middlep_y: %lld, median: "
+                          "%g", middlep_x, middlep_y, median);
+        }
+    }
+    return ima_local;
+}
+
+/*---------------------------------------------------------------------------*/
+/**
+  @brief    Smooth an image using a median filter
+  @param    in      image to be smoothed
+  @param    size    size of kernel matrix to use in filtering
+  @return   out     smoothed image
+ */
+/*---------------------------------------------------------------------------*/
+static cpl_image * hdrl_smooth_image_median(
+        const cpl_image     *   in, 
+        int                     size)
+{
+    cpl_image * out = cpl_image_duplicate(in);
+    cpl_mask * kernel = cpl_mask_new(size, size); 
+    cpl_mask_not(kernel);
+
+    if(cpl_image_filter_mask(out, in, kernel, CPL_FILTER_MEDIAN,
+                             CPL_BORDER_FILTER) != CPL_ERROR_NONE) {
+        cpl_image_delete(out);
+        cpl_mask_delete(kernel);
+        return NULL;
+    }
+
+    cpl_mask_delete(kernel);
+    return (out);
+}
+
+
+
+/**@}*/
+
+/** @endcond */
diff --git a/hdrl/hdrl_flat.h b/hdrl/hdrl_flat.h
new file mode 100644
index 0000000..4414d3f
--- /dev/null
+++ b/hdrl/hdrl_flat.h
@@ -0,0 +1,72 @@
+/* $Id: hdrl_flat.h,v 1.7 2013-10-17 15:44:14 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-17 15:44:14 $
+ * $Revision: 1.7 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifndef HDRL_FLAT_H
+#define HDRL_FLAT_H
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_collapse.h"
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                                Define
+ -----------------------------------------------------------------------------*/
+
+/*-----------------------------------------------------------------------------
+                            Functions prototypes
+ -----------------------------------------------------------------------------*/
+cpl_error_code hdrl_compute_flat_median_smooth(const cpl_imagelist *, 
+        const cpl_imagelist *, hdrl_collapse_imagelist_to_image_t *, cpl_size, 
+        cpl_image *, cpl_image *, cpl_image **, cpl_image **, cpl_image **);
+
+cpl_error_code hdrl_compute_flat_gauss_smooth(const cpl_imagelist *, 
+        const cpl_imagelist *, hdrl_collapse_imagelist_to_image_t *, cpl_size, 
+        cpl_size, cpl_size, cpl_image *, cpl_image *, cpl_image **, 
+        cpl_image **, cpl_image **);
+
+cpl_error_code hdrl_compute_flat_median_step_fit(const cpl_imagelist *, 
+        const cpl_imagelist *, hdrl_collapse_imagelist_to_image_t *, cpl_size, 
+        cpl_size, cpl_size, cpl_size, int, int, cpl_image *, cpl_image *, 
+        cpl_image **, cpl_image **, cpl_image **);
+
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+ -----------------------------------------------------------------------------*/
+
+#ifdef HDRL_USE_PRIVATE
+
+#endif
+
+CPL_END_DECLS
+
+#endif
+
diff --git a/hdrl/hdrl_image.c b/hdrl/hdrl_image.c
new file mode 100644
index 0000000..eecb1c3
--- /dev/null
+++ b/hdrl/hdrl_image.c
@@ -0,0 +1,801 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013,2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_elemop.h"
+#include "hdrl_image.h"
+#include "hdrl_image_defs.h"
+#include "hdrl_utils.h"
+#include "hdrl_buffer.h"
+
+#include <cpl.h>
+#include <string.h>
+#include <math.h>
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_image   Image object
+ *
+ * hdrl_image is a two dimensional array object containing data and its
+ * associated errors. It provides a similar api to cpl_image and performs
+ * linear error propagation where it makes sense.
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+/*-----------------------------------------------------------------------------
+                                   Functions
+ -----------------------------------------------------------------------------*/
+
+static void _hdrl_image_delete(hdrl_image * himg);
+static void _hdrl_image_delete_buffer(hdrl_image * himg);
+static void _hdrl_image_sync_mask(hdrl_image * himg);
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief check data and its errors for consistency
+ *
+ * will warn if error has a different bpm than image
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code
+hdrl_image_check_consistent(const cpl_image * image,
+                            const cpl_image * error)
+{
+    cpl_ensure_code(image, CPL_ERROR_NULL_INPUT);
+    if (error) {
+        cpl_size inx = cpl_image_get_size_x(image);
+        cpl_size iny = cpl_image_get_size_y(image);
+        cpl_size enx = cpl_image_get_size_x(error);
+        cpl_size eny = cpl_image_get_size_y(error);
+        const cpl_mask * ibpm = cpl_image_get_bpm_const(image);
+        const cpl_mask * ebpm = cpl_image_get_bpm_const(error);
+        cpl_ensure_code(inx == enx, CPL_ERROR_INCOMPATIBLE_INPUT);
+        cpl_ensure_code(iny == eny, CPL_ERROR_INCOMPATIBLE_INPUT);
+
+        if (ibpm && ebpm) {
+            const cpl_binary * dibpm = cpl_mask_get_data_const(ibpm);
+            const cpl_binary * debpm = cpl_mask_get_data_const(ebpm);
+            if (memcmp(dibpm, debpm, inx * iny) != 0) {
+                cpl_msg_warning(cpl_func, "Image and error bad pixel mask "
+                                "not equal, ignoring mask of error image");
+            }
+        }
+        else if (ibpm == NULL && ebpm) {
+            cpl_msg_warning(cpl_func, "Image and error bad pixel mask "
+                            "not equal, ignoring mask of error image");
+        }
+    }
+
+    return CPL_ERROR_NONE;
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get data as cpl image
+ * @param himg  hdrl image
+ * @return cpl_image
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_image * hdrl_image_get_image(hdrl_image * himg)
+{
+    cpl_ensure(himg, CPL_ERROR_NULL_INPUT, NULL);
+    return himg->image;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get data as cpl image
+ * @param himg  hdrl image
+ * @return const cpl_image
+ */
+/* ---------------------------------------------------------------------------*/
+const cpl_image * hdrl_image_get_image_const(const hdrl_image * himg)
+{
+    cpl_ensure(himg, CPL_ERROR_NULL_INPUT, NULL);
+    return himg->image;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get error as cpl image
+ * @param himg  hdrl image
+ * @return cpl_image
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_image * hdrl_image_get_error(hdrl_image * himg)
+{
+    cpl_ensure(himg, CPL_ERROR_NULL_INPUT, NULL);
+    return himg->error;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get error as cpl image
+ * @param himg  hdrl image
+ * @return cpl_image
+ */
+/* ---------------------------------------------------------------------------*/
+const cpl_image * hdrl_image_get_error_const(const hdrl_image * himg)
+{
+    cpl_ensure(himg, CPL_ERROR_NULL_INPUT, NULL);
+    return himg->error;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get cpl bad pixel mask from image
+ * @param himg  hdrl image
+ * @return cpl_mask, created when it does not exist
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_mask * hdrl_image_get_mask(hdrl_image * himg)
+{
+    cpl_ensure(himg, CPL_ERROR_NULL_INPUT, NULL);
+    if (cpl_image_get_bpm_const(hdrl_image_get_image(himg)) == NULL) {
+        /* call adds mask, also add a mask to the errors */
+        cpl_image_get_bpm(hdrl_image_get_error(himg));
+    }
+
+    return cpl_image_get_bpm(hdrl_image_get_image(himg));
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get cpl bad pixel mask from image
+ * @param himg  hdrl image
+ * @return cpl_mask or NULL if no mask exists
+ */
+/* ---------------------------------------------------------------------------*/
+const cpl_mask * hdrl_image_get_mask_const(const hdrl_image * himg)
+{
+    cpl_ensure(himg, CPL_ERROR_NULL_INPUT, NULL);
+    return cpl_image_get_bpm_const(hdrl_image_get_image_const(himg));
+}
+
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief create hdrl image by wrapping two cpl images
+ * @note beside typecheck no consistency checks on the two images
+ * @see hdrl_image_check_consistent
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_image *
+hdrl_image_wrap(cpl_image * img, cpl_image * err, hdrl_free * destructor,
+                cpl_boolean sync_mask)
+{
+    hdrl_image * himg;
+    cpl_ensure(img, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(err, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(cpl_image_get_type(img) == HDRL_TYPE_DATA,
+               CPL_ERROR_INCOMPATIBLE_INPUT, NULL);
+    cpl_ensure(cpl_image_get_type(err) == HDRL_TYPE_ERROR,
+               CPL_ERROR_INCOMPATIBLE_INPUT, NULL);
+
+    himg = cpl_malloc(sizeof(*himg));
+    himg->image = img;
+    himg->error = err;
+
+    if (destructor) {
+        himg->fp_free = destructor;
+    }
+    else {
+        himg->fp_free = (hdrl_free*)_hdrl_image_delete;
+    }
+
+    if (sync_mask) {
+        _hdrl_image_sync_mask(himg);
+    }
+
+    return himg;
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief unwrap hdrl image, will not delete wrapped cpl images
+ */
+/* ---------------------------------------------------------------------------*/
+void hdrl_image_unwrap(hdrl_image * himg)
+{
+    cpl_free(himg);
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief create a new hdrl_image from to existing images by copying them
+ *
+ * @param image  data to copy
+ * @param error  errors to copy
+ * @param check_consistent check consistency
+ *
+ * @return hdrl_image
+ * @see hdrl_image_create
+ */
+/* ---------------------------------------------------------------------------*/
+static hdrl_image * _hdrl_image_create(const cpl_image * image,
+                                       const cpl_image * error,
+                                       cpl_boolean check_consistent)
+{
+    cpl_image * himage = NULL, * herror = NULL;
+
+    if (check_consistent && hdrl_image_check_consistent(image, error)) {
+        return NULL;
+    }
+
+    himage = cpl_image_cast(image, HDRL_TYPE_DATA);
+    if (error) {
+        herror = cpl_image_cast(error, HDRL_TYPE_ERROR);
+    }
+    else {
+        /* set error to zero */
+        herror = cpl_image_new(cpl_image_get_size_x(image),
+                               cpl_image_get_size_y(image),
+                               HDRL_TYPE_ERROR);
+    }
+
+    /* sync image and error bpm ignoring what is in error before */
+    if (cpl_image_get_bpm_const(image)) {
+        cpl_image_reject_from_mask(herror,
+                                   cpl_image_get_bpm_const(image));
+    }
+    else {
+        cpl_image_accept_all(herror);
+    }
+
+    return hdrl_image_wrap(himage, herror, NULL, CPL_FALSE);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create a new hdrl_image from to existing images by copying them
+ *
+ * @param image  data to copy
+ * @param error  errors to copy
+ *
+ * @return hdrl_image
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_image * hdrl_image_create(const cpl_image * image,
+                               const cpl_image * error)
+{
+    return _hdrl_image_create(image, error, CPL_TRUE);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create new zero filled hdrl image
+ *
+ * @param nx  size in x
+ * @param ny  size in y
+ *
+ * @return hdrl_image or NULL on error
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_image * hdrl_image_new(cpl_size nx, cpl_size ny)
+{
+    cpl_image * himage = cpl_image_new(nx, ny, HDRL_TYPE_DATA);
+    cpl_image * herror = cpl_image_new(nx, ny, HDRL_TYPE_ERROR);
+
+    if (cpl_error_get_code()) {
+        cpl_image_delete(himage);
+        cpl_image_delete(herror);
+        return NULL;
+    }
+
+    return hdrl_image_wrap(himage, herror, NULL, CPL_FALSE);
+}
+
+hdrl_image *
+hdrl_image_new_from_buffer(cpl_size nx, cpl_size ny, hdrl_buffer * buf)
+{
+    char * p = hdrl_buffer_allocate(buf, nx * ny * (sizeof(hdrl_data_t) +
+                                                    sizeof(hdrl_error_t)));
+    cpl_image * himage = cpl_image_wrap(nx, ny, HDRL_TYPE_DATA, p);
+    cpl_image * herror = cpl_image_wrap(nx, ny, HDRL_TYPE_ERROR,
+                                        p + nx * ny * sizeof(hdrl_data_t));
+
+    if (cpl_error_get_code()) {
+        cpl_image_delete(himage);
+        cpl_image_delete(herror);
+        return NULL;
+    }
+
+    return hdrl_image_wrap(himage, herror,
+                           (hdrl_free*)&_hdrl_image_delete_buffer,
+                           CPL_FALSE);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief delete hdrl_image
+ */
+/* ---------------------------------------------------------------------------*/
+static void _hdrl_image_delete(hdrl_image * himg)
+{
+    if (himg) {
+        cpl_image_delete(himg->image);
+        cpl_image_delete(himg->error);
+        cpl_free(himg);
+    }
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief delete buffered hdrl_image
+ */
+/* ---------------------------------------------------------------------------*/
+static void _hdrl_image_delete_buffer(hdrl_image * himg)
+{
+    if (himg) {
+        cpl_image_unwrap(himg->image);
+        cpl_image_unwrap(himg->error);
+        cpl_free(himg);
+    }
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief delete hdrl_image
+ * @note may be used on views in which case the original memory is kept
+ */
+/* ---------------------------------------------------------------------------*/
+void hdrl_image_delete(hdrl_image * himg)
+{
+    if (himg) {
+        himg->fp_free(himg);
+    }
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief copy hdrl_image
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_image * hdrl_image_duplicate(const hdrl_image * himg)
+{
+    return _hdrl_image_create(hdrl_image_get_image_const(himg),
+                              hdrl_image_get_error_const(himg), CPL_FALSE);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief set bpm of hdrl_image
+ *
+ * @param self  image on which to set bpm
+ * @param map   bpm to set
+ * @see cpl_image_reject_from_mask
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_image_reject_from_mask(hdrl_image * self,
+                                           const cpl_mask * map)
+{
+    if (hdrl_image_get_mask_const(self) != map) {
+        cpl_image_reject_from_mask(hdrl_image_get_image(self), map);
+    }
+    return cpl_image_reject_from_mask(hdrl_image_get_error(self), map);
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief mark pixel as bad
+ *
+ * @param self          image
+ * @param xpos          x coordinate (FITS CONVENTION)
+ * @param ypos          y coordinate (FITS CONVENTION)
+ * @see cpl_image_reject
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_image_reject(hdrl_image * self,
+                                 cpl_size xpos, cpl_size ypos)
+{
+    cpl_image_reject(hdrl_image_get_image(self), xpos, ypos);
+    return cpl_image_reject(hdrl_image_get_error(self), xpos, ypos);
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief return if pixel is marked bad
+ *
+ * @param self          image
+ * @param xpos          x coordinate (FITS CONVENTION)
+ * @param ypos          y coordinate (FITS CONVENTION)
+ * @see cpl_image_is_rejected
+ */
+/* ---------------------------------------------------------------------------*/
+int hdrl_image_is_rejected(hdrl_image * self, cpl_size xpos, cpl_size ypos)
+{
+    cpl_ensure(self, CPL_ERROR_NULL_INPUT, -1);
+    return cpl_image_is_rejected(hdrl_image_get_image(self), xpos, ypos);
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief return number of rejected pixels
+ *
+ * @param self          image
+ * @return number of rejected pixels
+ * @see cpl_image_count_rejected
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_size hdrl_image_count_rejected(const hdrl_image * self)
+{
+    cpl_ensure(self, CPL_ERROR_NULL_INPUT, -1);
+    return cpl_image_count_rejected(hdrl_image_get_image_const(self));
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief    Reject pixels with the specified special value(s)
+ *
+ * @param self   Input image to modify
+ * @param mode   Bit field specifying which special value(s) to reject
+ * @see cpl_image_reject_value
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_image_reject_value(hdrl_image * self, cpl_value mode)
+{
+    return cpl_image_reject_value(hdrl_image_get_image(self), mode);
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief mark pixel as good
+ *
+ * @param self          image
+ * @param xpos          x coordinate (FITS CONVENTION)
+ * @param ypos          y coordinate (FITS CONVENTION)
+ * @see cpl_image_accept
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_image_accept(hdrl_image * self,
+                                 cpl_size xpos, cpl_size ypos)
+{
+    cpl_image_accept(hdrl_image_get_image(self), xpos, ypos);
+    return cpl_image_accept(hdrl_image_get_error(self), xpos, ypos);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief Accept all pixels in an image
+ *
+ * @param self input image
+ * @see cpl_image_accept_all
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_image_accept_all(hdrl_image * self)
+{
+    cpl_image_accept_all(hdrl_image_get_image(self));
+    cpl_image_accept_all(hdrl_image_get_error(self));
+    return cpl_error_get_code();
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief return size of X dimension of image
+ *
+ * @param self  image
+ * @return size of X dimension of image
+ * @see cpl_image_get_size_x
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_size hdrl_image_get_size_x(const hdrl_image * self)
+{
+    return cpl_image_get_size_x(hdrl_image_get_image_const(self));
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief return size of Y dimension of image
+ *
+ * @param self  image
+ * @return size of Y dimension of image
+ * @see cpl_image_get_size_y
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_size hdrl_image_get_size_y(const hdrl_image * self)
+{
+    return cpl_image_get_size_y(hdrl_image_get_image_const(self));
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get pixel values of hdrl_image
+ *
+ * @param self          image
+ * @param xpos          x coordinate (FITS CONVENTION)
+ * @param ypos          y coordinate (FITS CONVENTION)
+ * @param pis_rejected  int pointer to store if pixel is bad, may be NULL
+ *
+ * @return data value of the pixel
+ * @see cpl_image_get
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_value hdrl_image_get_pixel(const hdrl_image * self,
+                                cpl_size xpos, cpl_size ypos,
+                                int * pis_rejected)
+{
+    int d;
+    hdrl_value v;
+    v.data = cpl_image_get(hdrl_image_get_image_const(self), xpos, ypos, &d);
+
+    /* NULL allowed, different than CPL */
+    if (pis_rejected) {
+        *pis_rejected = d;
+    }
+    if (d) {
+        v.data = NAN;
+        v.error = NAN;
+    }
+    else {
+        v.error = cpl_image_get(hdrl_image_get_error_const(self),
+                                xpos, ypos, &d);
+    }
+
+    return v;
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief set pixel values of hdrl_image
+ *
+ * @param self          image
+ * @param xpos          x coordinate (FITS CONVENTION)
+ * @param ypos          y coordinate (FITS CONVENTION)
+ * @param value         data value to set
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_image_set_pixel(hdrl_image * self,
+                                    cpl_size xpos, cpl_size ypos,
+                                    hdrl_value value)
+{
+    /* nan may be used as a bad pixel value */
+    cpl_ensure_code(value.error >= 0 || isnan(value.error), CPL_ERROR_ILLEGAL_INPUT);
+
+    if (cpl_image_set(hdrl_image_get_image(self), xpos, ypos, value.data)) {
+        return cpl_error_get_code();
+    }
+
+    return cpl_image_set(hdrl_image_get_error(self), xpos, ypos, value.error);
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ @brief extract copy of window from image
+ @param self  image to extract from
+ @param llx   lower left x coordinate of window (FITS convention)
+ @param lly   lower left y coordinate of window (FITS convention)
+ @param urx   upper right x coordinate of window (FITS convention)
+ @param ury   upper right y coordinate of window (FITS convention)
+ 
+ @return newly allocated hdrl_image containing the window
+ @see cpl_image_extract
+
+ If the coordinates are < 1 the dimension of the image is added to them.
+ So llx = 0 wraps to hdrl_image_get_size_x(self).
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_image * hdrl_image_extract(
+        const hdrl_image        *   self,
+        cpl_size                    llx,
+        cpl_size                    lly,
+        cpl_size                    urx,
+        cpl_size                    ury)
+{
+    const cpl_size nx = hdrl_image_get_size_x(self);
+    const cpl_size ny = hdrl_image_get_size_y(self);
+    if (llx < 1) llx += nx;
+    if (lly < 1) lly += ny;
+    if (urx < 1) urx += nx;
+    if (ury < 1) ury += ny;
+
+    cpl_image * img = cpl_image_extract(hdrl_image_get_image_const(self),
+                                        llx, lly, urx, ury);
+    cpl_image * err = cpl_image_extract(hdrl_image_get_error_const(self),
+                                        llx, lly, urx, ury);
+
+    if (cpl_error_get_code()) {
+        cpl_image_delete(img);
+        cpl_image_delete(err);
+        return NULL;
+    }
+
+    return hdrl_image_wrap(img, err, NULL, CPL_FALSE);
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+  @brief    Rotate an image by a multiple of 90 degrees clockwise.
+  @param    self    The image to rotate in place.
+  @param    rot     The multiple: -1 is a rotation of 90 deg counterclockwise.
+  @return   CPL_ERROR_NONE on success, otherwise the relevant cpl_error_code
+  @see cpl_image_turn
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_image_turn(hdrl_image * self, int rot)
+{
+    cpl_ensure_code(self, CPL_ERROR_NULL_INPUT);
+    cpl_image_turn(hdrl_image_get_image(self), rot);
+    cpl_image_turn(hdrl_image_get_error(self), rot);
+    return cpl_error_get_code();
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+  @brief    Copy one image into another
+  @param    dst     the image in which im2 is inserted
+  @param    src     the inserted image
+  @param    xpos    the x pixel position in im1 where the lower left pixel of
+                    im2 should go (from 1 to the x size of im1)
+  @param    ypos    the y pixel position in im1 where the lower left pixel of
+                    im2 should go (from 1 to the y size of im1)
+  @return   CPL_ERROR_NONE or the relevant cpl_error_code on error.
+  @see cpl_image_copy
+  @note The two pixel buffers may not overlap
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_image_copy(hdrl_image * dst, const hdrl_image * src,
+                               cpl_size xpos, cpl_size ypos)
+{
+    cpl_ensure_code(dst, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(src, CPL_ERROR_NULL_INPUT);
+    cpl_image_copy(hdrl_image_get_image(dst), hdrl_image_get_image_const(src),
+                   xpos, ypos);
+    cpl_image_copy(hdrl_image_get_error(dst), hdrl_image_get_error_const(src),
+                   xpos, ypos);
+
+    return cpl_error_get_code();
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+  @brief    Copy cpl images into an hdrl image
+  @param    self    the image in which the cpl images are inserted
+  @param    image   the inserted image
+  @param    error   the inserted error, may be NULL
+  @param    xpos    the x pixel position in im1 where the lower left pixel of
+                    im2 should go (from 1 to the x size of im1)
+  @param    ypos    the y pixel position in im1 where the lower left pixel of
+                    im2 should go (from 1 to the y size of im1)
+  @return   CPL_ERROR_NONE or the relevant cpl_error_code on error.
+  @see hdrl_image_copy
+  @note The pixel buffers may not overlap
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_image_insert(hdrl_image * self,
+                                 const cpl_image * image,
+                                 const cpl_image * error,
+                                 cpl_size xpos, cpl_size ypos)
+{
+    cpl_ensure_code(self, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(image, CPL_ERROR_NULL_INPUT);
+    cpl_image_copy(hdrl_image_get_image(self), image, xpos, ypos);
+    if (error) {
+        cpl_image_copy(hdrl_image_get_error(self), error, xpos, ypos);
+    }
+    /* sync error mask */
+    if (cpl_image_get_bpm_const(image)) {
+        const cpl_mask * msrc = cpl_image_get_bpm_const(image);
+        cpl_mask * mdst = cpl_image_get_bpm(hdrl_image_get_error(self));
+        cpl_mask_copy(mdst, msrc, xpos, ypos);
+    }
+
+    return cpl_error_get_code();
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief synchronize mask
+ */
+/* ---------------------------------------------------------------------------*/
+
+static void _hdrl_image_sync_mask(hdrl_image * self)
+{
+    const cpl_mask * m = hdrl_image_get_mask_const(self);
+    if (m) {
+        hdrl_image_reject_from_mask(self, m);
+    }
+    else {
+        cpl_image_accept_all(hdrl_image_get_error(self));
+    }
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    Dump structural information of a HDRL image
+  @param    himg    Image to dump
+  @param    stream  Output stream, accepts @c stdout or @c stderr
+  @return   CPL_ERROR_NONE or the relevant cpl-error-code on error
+
+  Possible cpl-error-code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+  - CPL_ERROR_FILE_IO if a write operation fails
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_image_dump_structure(
+        const hdrl_image    *   himg,
+        FILE                *   stream)
+{
+    return cpl_image_dump_structure(hdrl_image_get_image_const(himg), stream);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    Dump pixel values in a HDRL image
+  @param    himg    Image to dump
+  @param    llx     Lower left x position (FITS convention, 1 for leftmost)
+  @param    lly     Lower left y position (FITS convention, 1 for lowest)
+  @param    urx     Specifies the window position
+  @param    ury     Specifies the window position
+  @param    stream  Output stream, accepts @c stdout or @c stderr
+  @return   CPL_ERROR_NONE or the relevant cpl-error-code on error
+
+  Possible cpl-error-code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+  - CPL_ERROR_FILE_IO if a write operation fails
+  - CPL_ERROR_ACCESS_OUT_OF_RANGE if the defined window is not in the image
+  - CPL_ERROR_ILLEGAL_INPUT if the window definition is wrong (e.g llx > urx)
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_image_dump_window(
+        const hdrl_image    *   himg,
+        cpl_size                llx,
+        cpl_size                lly,
+        cpl_size                urx,
+        cpl_size                ury,
+        FILE *                  stream)
+{
+    return cpl_image_dump_window(hdrl_image_get_image_const(himg),
+                    llx, lly, urx, ury, stream);
+
+}
+
+/**@}*/
diff --git a/hdrl/hdrl_image.h b/hdrl/hdrl_image.h
new file mode 100644
index 0000000..429f7bd
--- /dev/null
+++ b/hdrl/hdrl_image.h
@@ -0,0 +1,131 @@
+/* $Id: hdrl_image.h,v 1.18 2013-10-23 09:42:14 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-23 09:42:14 $
+ * $Revision: 1.18 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifndef HDRL_IMAGE_H
+#define HDRL_IMAGE_H
+
+/*-----------------------------------------------------------------------------
+                                   New types
+ -----------------------------------------------------------------------------*/
+
+typedef struct _hdrl_image_ hdrl_image;
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_image_math.h"
+#include "hdrl_utils.h"
+#include "hdrl_buffer.h"
+#include "hdrl_types.h"
+
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                                   Functions
+ -----------------------------------------------------------------------------*/
+
+hdrl_image * hdrl_image_new(cpl_size nx, cpl_size ny);
+
+hdrl_image * hdrl_image_create(const cpl_image * image,
+                               const cpl_image * error);
+
+hdrl_image * hdrl_image_duplicate(const hdrl_image * himg);
+
+void hdrl_image_delete(hdrl_image * himg);
+
+cpl_image * hdrl_image_get_image(hdrl_image * himg);
+const cpl_image * hdrl_image_get_image_const(const hdrl_image * himg);
+
+cpl_image * hdrl_image_get_error(hdrl_image * himg);
+const cpl_image * hdrl_image_get_error_const(const hdrl_image * himg);
+
+cpl_mask * hdrl_image_get_mask(hdrl_image * himg);
+const cpl_mask * hdrl_image_get_mask_const(const hdrl_image * himg);
+
+hdrl_value hdrl_image_get_pixel(const hdrl_image * self,
+                                cpl_size xpos, cpl_size ypos,
+                                int * pis_rejected);
+
+cpl_error_code hdrl_image_set_pixel(hdrl_image * self,
+                                    cpl_size xpos, cpl_size ypos,
+                                    hdrl_value value);
+
+cpl_size hdrl_image_get_size_x(const hdrl_image * self) ;
+cpl_size hdrl_image_get_size_y(const hdrl_image * self) ;
+
+hdrl_image * hdrl_image_extract(const hdrl_image *,
+                                cpl_size, cpl_size, cpl_size, cpl_size) ;
+
+cpl_error_code hdrl_image_reject(hdrl_image * self,
+                                 cpl_size xpos, cpl_size ypos);
+cpl_error_code hdrl_image_reject_value(hdrl_image * self, cpl_value mode);
+cpl_error_code hdrl_image_reject_from_mask(hdrl_image * self,
+                                           const cpl_mask * map);
+int hdrl_image_is_rejected(hdrl_image * self, cpl_size xpos, cpl_size ypos);
+cpl_size hdrl_image_count_rejected(const hdrl_image * self);
+cpl_error_code hdrl_image_accept(hdrl_image * self,
+                                 cpl_size xpos, cpl_size ypos);
+cpl_error_code hdrl_image_accept_all(hdrl_image * self);
+
+cpl_error_code hdrl_image_turn(hdrl_image * self, int rot);
+
+cpl_error_code hdrl_image_copy(hdrl_image * other, const hdrl_image * self,
+                               cpl_size xpos, cpl_size ypos);
+
+cpl_error_code hdrl_image_insert(hdrl_image * self,
+                                 const cpl_image * image,
+                                 const cpl_image * error,
+                                 cpl_size xpos, cpl_size ypos);
+
+cpl_error_code hdrl_image_dump_structure(const hdrl_image *, FILE *) ;
+
+cpl_error_code hdrl_image_dump_window(const hdrl_image *,
+        cpl_size, cpl_size, cpl_size, cpl_size, FILE *) ;
+
+/*-----------------------------------------------------------------------------
+  Experimental declarations - can be used, but no guarantees on api stability
+ -----------------------------------------------------------------------------*/
+#if defined HDRL_USE_EXPERIMENTAL || defined HDRL_USE_PRIVATE
+hdrl_image *
+hdrl_image_new_from_buffer(cpl_size nx, cpl_size ny, hdrl_buffer * buf);
+#endif
+
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+ -----------------------------------------------------------------------------*/
+#ifdef HDRL_USE_PRIVATE
+hdrl_image * hdrl_image_wrap(cpl_image *, cpl_image *, hdrl_free *,
+                             cpl_boolean);
+void hdrl_image_unwrap(hdrl_image * himg);
+#endif
+
+CPL_END_DECLS
+
+#endif 
diff --git a/hdrl/hdrl_image_defs.h b/hdrl/hdrl_image_defs.h
new file mode 100644
index 0000000..23de404
--- /dev/null
+++ b/hdrl/hdrl_image_defs.h
@@ -0,0 +1,48 @@
+/* $Id: hdrl_image_defs.h,v 1.4 2013-10-17 15:44:14 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-17 15:44:14 $
+ * $Revision: 1.4 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifndef HDRL_IMAGE_DEFS_H
+#define HDRL_IMAGE_DEFS_H
+
+#ifndef HDRL_USE_PRIVATE
+#error This file is not allowed to be included outside of hdrl
+#endif
+
+#include "hdrl_types.h"
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+struct _hdrl_image_ {
+    cpl_image * image;
+    cpl_image * error;
+    hdrl_free * fp_free;
+};
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_image_math.c b/hdrl/hdrl_image_math.c
new file mode 100644
index 0000000..cf90950
--- /dev/null
+++ b/hdrl/hdrl_image_math.c
@@ -0,0 +1,609 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013,2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_elemop.h"
+#include "hdrl_image.h"
+#include "hdrl_collapse.h"
+
+#include <cpl.h>
+#include <math.h>
+
+/*-----------------------------------------------------------------------------
+                                   Functions
+ -----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    Add two images, store the result in the first image.
+  @param    self      first operand.
+  @param    other     second operand.
+  @return   the cpl-error-code or CPL_ERROR_NONE
+  
+  The first input image is modified to contain the result of the operation.
+
+  The bad pixel map of the first image becomes the union of the bad pixel 
+  maps of the input images.
+  
+  Possible cpl-error-code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+  - CPL_ERROR_INCOMPATIBLE_INPUT if the input images have different sizes
+
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_image_add_image(hdrl_image * self, const hdrl_image * other)
+{
+    cpl_ensure_code(self, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(other, CPL_ERROR_NULL_INPUT);
+    /* size check included in elemop */
+    return hdrl_elemop_image_add_image(hdrl_image_get_image(self), hdrl_image_get_error(self),
+                                         hdrl_image_get_image_const(other),
+                                         hdrl_image_get_error_const(other));
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    Add two images.
+  @param    self  first operand
+  @param    other  second operand
+  @return   1 newly allocated image or NULL on error
+
+  Creates a new image, being the result of the operation, and returns it to
+  the caller. The returned image must be deallocated using hdrl_image_delete().
+
+  The bad pixels map of the result is the union of the bad pixels maps of
+  the input images.
+  
+  Possible cpl-error-code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+  - CPL_ERROR_INCOMPATIBLE_INPUT if the input images have different sizes
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_image *
+hdrl_image_add_image_create(const hdrl_image * self, const hdrl_image * other)
+{
+    hdrl_image * n = hdrl_image_duplicate(self);
+
+    if (hdrl_image_add_image(n, other)) {
+        hdrl_image_delete(n);
+        return NULL;
+    }
+
+    return n;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    Elementwise addition of a scalar to an image
+  @param    self    Image to be modified in place.
+  @param    value   Number to add
+  @return   CPL_ERROR_NONE or the relevant the cpl-error-code on error
+ 
+  Modifies the image by adding a number to each of its pixels with error 
+  propagation.
+  
+  Possible cpl-error-code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_image_add_scalar(hdrl_image * self, hdrl_value value)
+{
+    cpl_ensure_code(self, CPL_ERROR_NULL_INPUT);
+    /* size check included in elemop */
+    return hdrl_elemop_image_add_scalar(hdrl_image_get_image(self),
+                                        hdrl_image_get_error(self),
+                                        value.data, value.error);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    Subtract two images, store the result in the first image.
+  @param    self     first operand.
+  @param    other    second operand.
+  @return   the cpl-error-code or CPL_ERROR_NONE
+  @see      hdrl_image_add_image()
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_image_sub_image(hdrl_image * self, const hdrl_image * other)
+{
+    cpl_ensure_code(self, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(other, CPL_ERROR_NULL_INPUT);
+    /* size check included in elemop */
+    return hdrl_elemop_image_sub_image(hdrl_image_get_image(self), hdrl_image_get_error(self),
+                                         hdrl_image_get_image_const(other),
+                                         hdrl_image_get_error_const(other));
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    Subtract two images.
+  @param    self   first operand
+  @param    other  second operand
+  @return   1 newly allocated image or NULL on error
+  @see      hdrl_image_add_image_create()
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_image *
+hdrl_image_sub_image_create(const hdrl_image * self, const hdrl_image * other)
+{
+    hdrl_image * n = hdrl_image_duplicate(self);
+
+    if (hdrl_image_sub_image(n, other)) {
+        hdrl_image_delete(n);
+        return NULL;
+    }
+
+    return n;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    Elementwise subtraction of a scalar from an image
+  @param    self    Image to be modified in place.
+  @param    value  Number to subtract
+  @return   CPL_ERROR_NONE or the relevant the cpl-error-code on error
+  @see      hdrl_image_add_scalar()
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_image_sub_scalar(hdrl_image * self, hdrl_value value)
+{
+    cpl_ensure_code(self, CPL_ERROR_NULL_INPUT);
+    /* size check included in elemop */
+    return hdrl_elemop_image_sub_scalar(hdrl_image_get_image(self),
+                                        hdrl_image_get_error(self),
+                                        value.data, value.error);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    Multiply two images, store the result in the first image.
+  @param    self      first operand.
+  @param    other     second operand.
+  @return   the cpl-error-code or CPL_ERROR_NONE
+  @see      hdrl_image_add_image()
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_image_mul_image(hdrl_image * self, const hdrl_image * other)
+{
+    cpl_ensure_code(self, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(other, CPL_ERROR_NULL_INPUT);
+    /* size check included in elemop */
+    return hdrl_elemop_image_mul_image(hdrl_image_get_image(self), hdrl_image_get_error(self),
+                                         hdrl_image_get_image_const(other),
+                                         hdrl_image_get_error_const(other));
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    Multiply two images.
+  @param    self   first operand
+  @param    other  second operand
+  @return   1 newly allocated image or NULL on error
+  @see      hdrl_image_add_image_create()
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_image *
+hdrl_image_mul_image_create(const hdrl_image * self, const hdrl_image * other)
+{
+    hdrl_image * n = hdrl_image_duplicate(self);
+
+    if (hdrl_image_mul_image(n, other)) {
+        hdrl_image_delete(n);
+        return NULL;
+    }
+
+    return n;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    Elementwise multiplication of an image with a scalar
+  @param    self    Image to be modified in place.
+  @param    value   Number to multiply with
+  @return   CPL_ERROR_NONE or the relevant the cpl-error-code on error
+  @see      hdrl_image_add_scalar()
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_image_mul_scalar(hdrl_image * self, hdrl_value value)
+{
+    cpl_ensure_code(self, CPL_ERROR_NULL_INPUT);
+    /* size check included in elemop */
+    return hdrl_elemop_image_mul_scalar(hdrl_image_get_image(self),
+                                        hdrl_image_get_error(self),
+                                        value.data, value.error);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    Divide two images, store the result in the first image.
+  @param    self   first operand
+  @param    other  second operand
+  @return   the cpl-error-code or CPL_ERROR_NONE
+  @see      hdrl_image_add_image()
+
+  @note The result of division with a zero-valued pixel is marked as a bad
+  pixel. Additionally, the value and the error are set to NAN
+
+
+  Possible cpl-error-code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+  - CPL_ERROR_INCOMPATIBLE_INPUT if the input images have different sizes
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_image_div_image(hdrl_image * self, const hdrl_image * other)
+{
+    cpl_ensure_code(self, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(other, CPL_ERROR_NULL_INPUT);
+    /* size check included in elemop */
+    return hdrl_elemop_image_div_image(hdrl_image_get_image(self), hdrl_image_get_error(self),
+                                         hdrl_image_get_image_const(other),
+                                         hdrl_image_get_error_const(other));
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    Divide two images and return the resulting image
+  @param    self   first operand
+  @param    other  second operand
+  @return   1 newly allocated image or NULL on error
+  @see      hdrl_image_add_image_create()
+
+  @note The result of division with a zero-valued pixel is marked as a bad
+  pixel. Additionally, the value and the error are set to NAN
+
+
+  Possible cpl-error-code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+  - CPL_ERROR_INCOMPATIBLE_INPUT if the input images have different sizes
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_image *
+hdrl_image_div_image_create(const hdrl_image * self, const hdrl_image * other)
+{
+    hdrl_image * n = hdrl_image_duplicate(self);
+
+    if (hdrl_image_div_image(n, other)) {
+        hdrl_image_delete(n);
+        return NULL;
+    }
+
+    return n;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    Elementwise division of an image with a scalar
+  @param    self   Image to be modified in place.
+  @param    value  Non-zero number to divide with
+  @return   CPL_ERROR_NONE or the relevant the cpl-error-code on error
+  @see      cpl_image_add_image_scalar()
+
+  Possible cpl-error-code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_image_div_scalar(hdrl_image * self, hdrl_value value)
+{
+    cpl_ensure_code(self, CPL_ERROR_NULL_INPUT);
+    /* size check included in elemop */
+    return hdrl_elemop_image_div_scalar(hdrl_image_get_image(self),
+                                        hdrl_image_get_error(self),
+                                        value.data, value.error);
+}
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    Collapse the image
+\todo copy from overscan
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code
+hdrl_image_collapse(hdrl_collapse_imagelist_to_vector_t * red,
+                    const hdrl_image * self,
+                    hdrl_data_t * result, hdrl_error_t * error,
+                    int * contrib, void * eout)
+{
+    cpl_imagelist * ld = cpl_imagelist_new();
+    cpl_imagelist * le = cpl_imagelist_new();
+    cpl_vector * od = NULL, * oe = NULL;
+    cpl_array * oc = NULL;
+    cpl_error_code fail;
+    cpl_imagelist_set(ld, hdrl_image_get_image((hdrl_image * )self), 0);
+    cpl_imagelist_set(le, hdrl_image_get_error((hdrl_image * )self), 0);
+
+
+    fail = hdrl_collapse_imagelist_to_vector_call(red, ld, le, &od, &oe, &oc,
+                                                  eout);
+    cpl_imagelist_unwrap(ld);
+    cpl_imagelist_unwrap(le);
+
+    if (fail == CPL_ERROR_NONE) {
+        if (result) {
+            *result = cpl_vector_get(od, 0);
+        }
+        if (error) {
+            *error = cpl_vector_get(oe, 0);
+        }
+        if (contrib) {
+            *contrib = cpl_array_get_int(oc, 0, NULL);
+        }
+    }
+    else {
+        if (result) {
+            *result = NAN;
+        }
+        if (error) {
+            *error = NAN;
+        }
+    }
+
+    cpl_vector_delete(od);
+    cpl_vector_delete(oe);
+    cpl_array_delete(oc);
+
+    return fail;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    computes mean pixel value and associated error of an image.
+  @param    self       input image
+  @return   mean and its error in a hdrl_value structure
+ */ 
+/*----------------------------------------------------------------------------*/
+hdrl_value
+hdrl_image_get_mean(const hdrl_image * self)
+{
+    hdrl_collapse_imagelist_to_vector_t * red =
+        hdrl_collapse_imagelist_to_vector_mean();
+    hdrl_value res;
+    hdrl_image_collapse(red, self, &res.data, &res.error, NULL, NULL);
+    hdrl_collapse_imagelist_to_vector_delete(red);
+    return res;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief computes the sigma-clipped mean and associated error of an image.
+  @param self         input image
+  @param kappa_low    low sigma bound
+  @param kappa_high   high sigma bound
+  @param niter        maximum number of clipping iterators
+  @return   clipped mean and its error in a hdrl_value structure
+  @see hdrl_kappa_sigma_clip() for the algorithm
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_value
+hdrl_image_get_sigclip_mean(const hdrl_image * self, double kappa_low,
+                            double kappa_high, int niter)
+{
+    hdrl_collapse_imagelist_to_vector_t * red =
+        hdrl_collapse_imagelist_to_vector_sigclip(kappa_low, kappa_high, niter);
+    hdrl_value res;
+    hdrl_image_collapse(red, self, &res.data, &res.error, NULL, NULL);
+    hdrl_collapse_imagelist_to_vector_delete(red);
+    return res;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief computes the minmax rejected mean and the associated error of an image.
+  @param self         input image
+  @param nlow         number of low pixels to reject
+  @param nhigh        number of high pixels to reject
+  @return   minmax rejected mean and its error in a hdrl_value structure
+  @see hdrl_minmax_clip() for the algorithm
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_value
+hdrl_image_get_minmax_mean(const hdrl_image * self, double nlow,
+                           double nhigh)
+{
+    hdrl_collapse_imagelist_to_vector_t * red =
+        hdrl_collapse_imagelist_to_vector_minmax(nlow, nhigh);
+    hdrl_value res;
+    hdrl_image_collapse(red, self, &res.data, &res.error, NULL, NULL);
+    hdrl_collapse_imagelist_to_vector_delete(red);
+    return res;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief computes the median and associated error of an image.
+  @param self         input image
+  @return   median and its error in a hdrl_value structure
+
+  This function computes the median and the associated error of the image. For
+  the error propagation the error is scaled by the sqrt of the statistical
+  efficiency of the median on normal distributed data which is
+  \f$ \frac{\pi}{ 2 } \f$
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_value
+hdrl_image_get_median(const hdrl_image * self)
+{
+    hdrl_collapse_imagelist_to_vector_t * red =
+        hdrl_collapse_imagelist_to_vector_median();
+    hdrl_value res;
+    hdrl_image_collapse(red, self, &res.data, &res.error, NULL, NULL);
+    hdrl_collapse_imagelist_to_vector_delete(red);
+    return res;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief computes the weighted mean and associated error of an image.
+  @param self         input image
+  @return   weighted mean and its error in a hdrl_value structure
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_value
+hdrl_image_get_weighted_mean(const hdrl_image * self)
+{
+    hdrl_collapse_imagelist_to_vector_t * red =
+        hdrl_collapse_imagelist_to_vector_weighted_mean();
+    hdrl_value res;
+    hdrl_image_collapse(red, self, &res.data, &res.error, NULL, NULL);
+    hdrl_collapse_imagelist_to_vector_delete(red);
+    return res;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief computes the standard deviation of the data of an image
+  @param self         input image
+  @return   CPL_ERROR_NONE or the relevant the cpl-error-code on error
+  @see cpl_image_get_stdev
+ */
+/*----------------------------------------------------------------------------*/
+double
+hdrl_image_get_stdev(const hdrl_image * self)
+{
+    return cpl_image_get_stdev(hdrl_image_get_image_const(self));
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    computes the sum of all pixel values and the associated error of an
+            image.
+  @param    self       input image
+  @return   sum and its error in a hdrl_value structure
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_value
+hdrl_image_get_sum(const hdrl_image * self)
+{
+    int contrib;
+    hdrl_value res;
+    hdrl_collapse_imagelist_to_vector_t * red =
+        hdrl_collapse_imagelist_to_vector_mean();
+    cpl_error_code err = hdrl_image_collapse(red, self, &res.data, &res.error,
+                                             &contrib, NULL);
+    if (err == CPL_ERROR_NONE) {
+        res.data *= contrib;
+        res.error *= contrib;
+    }
+    else {
+        res.data = NAN;
+        res.error = NAN;
+    }
+    hdrl_collapse_imagelist_to_vector_delete(red);
+    return res;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    computes the sum of all pixel values and the error of a squared
+            image.
+  @param    self       input image
+  @return   squared sum and its error in a hdrl_value structure
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_value
+hdrl_image_get_sqsum(const hdrl_image * self)
+{
+    /* TODO could be a specialized collapse method for better performance */
+    hdrl_image * tmp = hdrl_image_pow_scalar_create(self, (hdrl_value){2, 0.});
+    hdrl_value res = hdrl_image_get_sum(tmp);
+    hdrl_image_delete(tmp);
+    return res;
+}
+
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    computes the power of an image by a scalar
+  @param    self       input image
+  @param    exponent   exponent of the power
+  @return   CPL_ERROR_NONE or the relevant the cpl-error-code on error
+
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_image_pow_scalar(hdrl_image * self, const hdrl_value exponent)
+{
+    cpl_ensure_code(self, CPL_ERROR_NULL_INPUT);
+    /* size check included in elemop */
+    return hdrl_elemop_image_pow_scalar(hdrl_image_get_image(self),
+                                        hdrl_image_get_error(self),
+                                        exponent.data, exponent.error);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @ingroup hdrl_image
+  @brief    computes the power of an image by a scalar creating a new image
+  @param    self       input image
+  @param    exponent   exponent of the power
+  @return   new image containing the powered data or NULL on error
+  @see hdrl_image_pow_scalar
+
+  @note the function currently only supports integer power of two exponents
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_image *
+hdrl_image_pow_scalar_create(const hdrl_image * self, const hdrl_value exponent)
+{
+    hdrl_image * n = hdrl_image_duplicate(self);
+
+    if (hdrl_image_pow_scalar(n, exponent)) {
+        hdrl_image_delete(n);
+        return NULL;
+    }
+
+    return n;
+}
+
diff --git a/hdrl/hdrl_image_math.h b/hdrl/hdrl_image_math.h
new file mode 100644
index 0000000..9578d20
--- /dev/null
+++ b/hdrl/hdrl_image_math.h
@@ -0,0 +1,64 @@
+/* $Id: hdrl_image_math.h,v 1.6 2013-10-17 15:44:14 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-17 15:44:14 $
+ * $Revision: 1.6 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifndef HDRL_IMAGE_MATH_H
+#define HDRL_IMAGE_MATH_H
+#include "hdrl_image.h"
+#include "hdrl_types.h"
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+hdrl_value hdrl_image_get_sqsum(const hdrl_image *self);
+hdrl_value hdrl_image_get_sum(const hdrl_image *self);
+double hdrl_image_get_stdev(const hdrl_image *self);
+hdrl_value hdrl_image_get_median(const hdrl_image *self);
+hdrl_value hdrl_image_get_mean(const hdrl_image *self);
+hdrl_value hdrl_image_get_weighted_mean(const hdrl_image *self);
+hdrl_value hdrl_image_get_sigclip_mean(const hdrl_image * self,
+                                       double kappa_low, double kappa_high,
+                                       int niter);
+hdrl_value hdrl_image_get_minmax_mean(const hdrl_image * self, double nlow,
+                                      double nhigh);
+cpl_error_code hdrl_image_div_scalar(hdrl_image *self, hdrl_value);
+hdrl_image *hdrl_image_div_image_create(const hdrl_image *self,const hdrl_image *other);
+cpl_error_code hdrl_image_div_image(hdrl_image *self,const hdrl_image *other);
+cpl_error_code hdrl_image_mul_scalar(hdrl_image *self, hdrl_value);
+hdrl_image *hdrl_image_mul_image_create(const hdrl_image *self,const hdrl_image *other);
+cpl_error_code hdrl_image_mul_image(hdrl_image *self,const hdrl_image *other);
+cpl_error_code hdrl_image_sub_scalar(hdrl_image *self, hdrl_value);
+hdrl_image *hdrl_image_sub_image_create(const hdrl_image *self,const hdrl_image *other);
+cpl_error_code hdrl_image_sub_image(hdrl_image *self,const hdrl_image *other);
+cpl_error_code hdrl_image_add_scalar(hdrl_image *self, hdrl_value);
+hdrl_image *hdrl_image_add_image_create(const hdrl_image *self,const hdrl_image *other);
+cpl_error_code hdrl_image_add_image(hdrl_image *self,const hdrl_image *other);
+hdrl_image *hdrl_image_pow_scalar_create(const hdrl_image *self, const hdrl_value);
+cpl_error_code hdrl_image_pow_scalar(hdrl_image *self, const hdrl_value);
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_imagelist.h b/hdrl/hdrl_imagelist.h
new file mode 100644
index 0000000..b90a766
--- /dev/null
+++ b/hdrl/hdrl_imagelist.h
@@ -0,0 +1,37 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_IMAGELIST_H
+#define HDRL_IMAGELIST_H
+
+/*-----------------------------------------------------------------------------
+                                   New types
+ -----------------------------------------------------------------------------*/
+
+typedef struct _hdrl_imagelist_ hdrl_imagelist;
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_imagelist_io.h"
+#include "hdrl_imagelist_basic.h"
+#include "hdrl_imagelist_view.h"
+
+#endif 
diff --git a/hdrl/hdrl_imagelist_basic.c b/hdrl/hdrl_imagelist_basic.c
new file mode 100644
index 0000000..a639f6d
--- /dev/null
+++ b/hdrl/hdrl_imagelist_basic.c
@@ -0,0 +1,722 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_imagelist.h"
+#include "hdrl_imagelist_view.h"
+#include "hdrl_imagelist_defs.h"
+#include "hdrl_image.h"
+#include "hdrl_collapse.h"
+
+#include <cpl.h>
+#include <assert.h>
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_imagelist   Imagelist object
+ *
+ * hdrl_imagelist is similiar to cpl_imagelist but for hdrl_image.
+ * Its reduction methods (mean, median, ...) provide linear error propagation.
+ *
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+/*-----------------------------------------------------------------------------
+                                   Define
+ -----------------------------------------------------------------------------*/
+
+#define HDRL_IMLIST_BASIC_IMLIST    0
+#define HDRL_IMLIST_BASIC_IMAGE     1
+#define HDRL_IMLIST_BASIC_SCALAR    2
+
+/*-----------------------------------------------------------------------------
+                            Static Prototypes
+ -----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_imagelist_collapse_interface(const
+        hdrl_imagelist *, hdrl_collapse_imagelist_to_image_t *,
+        hdrl_image **, cpl_image **, void **);
+
+
+/*-----------------------------------------------------------------------------
+                            Function codes
+ -----------------------------------------------------------------------------*/
+
+#define HDRL_OPERATION HDRL_IMLIST_BASIC_IMLIST
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Add two image lists, the first one is replaced by the result.
+  @param    himlist1   first input image list (modified)
+  @param    himlist2   image list to add
+  @return   the cpl_error_code or CPL_ERROR_NONE
+  @see      hdrl_image_add_image()
+
+  The two input lists must have the same size, the image number n in the
+  list himlist2 is added to the image number n in the list himlist1.
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+  - CPL_ERROR_ILLEGAL_INPUT if the input images have different sizes
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_add_imagelist(
+        hdrl_imagelist        *    himlist1,
+        const hdrl_imagelist  *    himlist2)
+{
+#define HDRL_OPERATOR hdrl_image_add_image
+#include "hdrl_imagelist_basic_body.h"
+#undef HDRL_OPERATOR
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Subtract two image lists, the first one is replaced by the result.
+  @param    himlist1  first input image list (modified)
+  @param    himlist2  image list to subtract
+  @return   the cpl_error_code or CPL_ERROR_NONE
+  @see      hdrl_image_sub_image()
+  @see      hdrl_imagelist_add_imagelist
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_sub_imagelist(
+        hdrl_imagelist        *    himlist1,
+        const hdrl_imagelist  *    himlist2)
+{
+#define HDRL_OPERATOR hdrl_image_sub_image
+#include "hdrl_imagelist_basic_body.h"
+#undef HDRL_OPERATOR
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Multiply two image lists, the first one is replaced by the result.
+  @param    himlist1  first input image list (modified)
+  @param    himlist2  image list to multiply
+  @return   the cpl_error_code or CPL_ERROR_NONE
+  @see      hdrl_image_mul_image()
+  @see      hdrl_imagelist_add_imagelist
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_mul_imagelist(
+        hdrl_imagelist        *    himlist1,
+        const hdrl_imagelist  *    himlist2)
+{
+#define HDRL_OPERATOR hdrl_image_mul_image
+#include "hdrl_imagelist_basic_body.h"
+#undef HDRL_OPERATOR
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Divide two image lists, the first one is replaced by the result.
+  @param    himlist1  first input image list (modified)
+  @param    himlist2  image list to divide
+  @return   the cpl_error_code or CPL_ERROR_NONE
+  @see      hdrl_image_div_image()
+  @see      hdrl_imagelist_add_imagelist
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_div_imagelist(
+        hdrl_imagelist        *    himlist1,
+        const hdrl_imagelist  *    himlist2)
+{
+#define HDRL_OPERATOR hdrl_image_div_image
+#include "hdrl_imagelist_basic_body.h"
+#undef HDRL_OPERATOR
+}
+#undef HDRL_OPERATION
+
+#define HDRL_OPERATION HDRL_IMLIST_BASIC_IMAGE
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Add an image to an image list.
+  @param    himlist input image list (modified)
+  @param    himg    image to add
+  @return   the cpl_error_code or CPL_ERROR_NONE
+  @see      hdrl_image_add_image()
+
+  The passed image is added to each image of the passed image list.
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_add_image(
+        hdrl_imagelist      *    himlist,
+        const hdrl_image    *    himg)
+{
+#define HDRL_OPERATOR hdrl_image_add_image
+#include "hdrl_imagelist_basic_body.h"
+#undef HDRL_OPERATOR
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Subtract an image from an image list.
+  @param    himlist input image list (modified)
+  @param    himg    image to subtract
+  @return   the cpl_error_code or CPL_ERROR_NONE
+  @see      hdrl_image_sub_image()
+  @see      hdrl_imagelist_add_image()
+
+  The passed image is subtracted from each image of the passed image list.
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_sub_image(
+        hdrl_imagelist      *    himlist,
+        const hdrl_image    *    himg)
+{
+#define HDRL_OPERATOR hdrl_image_sub_image
+#include "hdrl_imagelist_basic_body.h"
+#undef HDRL_OPERATOR
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Multiply an image by an image list.
+  @param    himlist input image list (modified)
+  @param    himg    image to multiply
+  @return   the cpl_error_code or CPL_ERROR_NONE
+  @see      hdrl_image_mul_image()
+  @see      hdrl_imagelist_add_image()
+
+  The passed image is multiplied by each image of the passed image list.
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_mul_image(
+        hdrl_imagelist      *    himlist,
+        const hdrl_image    *    himg)
+{
+#define HDRL_OPERATOR hdrl_image_mul_image
+#include "hdrl_imagelist_basic_body.h"
+#undef HDRL_OPERATOR
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Divide an image from an image list.
+  @param    himlist input image list (modified)
+  @param    himg    image to divide
+  @return   the cpl_error_code or CPL_ERROR_NONE
+  @see      hdrl_image_div_image()
+  @see      hdrl_imagelist_add_image()
+
+  The passed image is used to divide each image of the passed image list.
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_div_image(
+        hdrl_imagelist      *    himlist,
+        const hdrl_image    *    himg)
+{
+#define HDRL_OPERATOR hdrl_image_div_image
+#include "hdrl_imagelist_basic_body.h"
+#undef HDRL_OPERATOR
+}
+#undef HDRL_OPERATION
+
+#define HDRL_OPERATION HDRL_IMLIST_BASIC_SCALAR
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Elementwise addition of a scalar to each image in the himlist
+  @param    himlist Imagelist to be modified in place.
+  @param    value   Value to add to the images
+  @return   the cpl_error_code or CPL_ERROR_NONE
+  @see      hdrl_image_add_scalar()
+ 
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_add_scalar(
+        hdrl_imagelist  *   himlist,
+        hdrl_value          value)
+{
+#define HDRL_OPERATOR hdrl_image_add_scalar
+#include "hdrl_imagelist_basic_body.h"
+#undef HDRL_OPERATOR
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Elementwise subtraction of a scalar to each image in the himlist
+  @param    himlist Imagelist to be modified in place.
+  @param    value   Value to subtract to the images
+  @return   the cpl_error_code or CPL_ERROR_NONE
+  @see      hdrl_image_sub_scalar()
+  @see      hdrl_imagelist_add_scalar()
+ 
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_sub_scalar(
+        hdrl_imagelist  *   himlist,
+        hdrl_value          value)
+{
+#define HDRL_OPERATOR hdrl_image_sub_scalar
+#include "hdrl_imagelist_basic_body.h"
+#undef HDRL_OPERATOR
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Elementwise multiplication of a scalar to each image in the himlist
+  @param    himlist Imagelist to be modified in place.
+  @param    value   Value to multiply to the images
+  @return   the cpl_error_code or CPL_ERROR_NONE
+  @see      hdrl_image_mul_scalar()
+  @see      hdrl_imagelist_add_scalar()
+ 
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_mul_scalar(
+        hdrl_imagelist  *   himlist,
+        hdrl_value          value)
+{
+#define HDRL_OPERATOR hdrl_image_mul_scalar
+#include "hdrl_imagelist_basic_body.h"
+#undef HDRL_OPERATOR
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Elementwise division by a scalar to each image in the himlist
+  @param    himlist Imagelist to be modified in place.
+  @param    value   Value to divide to the images
+  @return   the cpl_error_code or CPL_ERROR_NONE
+  @see      hdrl_image_div_scalar()
+  @see      hdrl_imagelist_add_scalar()
+ 
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_div_scalar(
+        hdrl_imagelist  *   himlist,
+        hdrl_value          value)
+{
+#define HDRL_OPERATOR hdrl_image_div_scalar
+#include "hdrl_imagelist_basic_body.h"
+#undef HDRL_OPERATOR
+}
+#undef HDRL_OPERATION
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Compute the elementwise power of each image in the himlist
+  @param    himlist     Imagelist to be modified in place.
+  @param    exponent    Scalar exponent
+  @return   CPL_ERROR_NONE or the relevant the cpl_error_code on error
+  @see      hdrl_image_power()
+ 
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_pow_scalar(
+        hdrl_imagelist  *   himlist,
+        hdrl_value          exponent)
+{
+    cpl_size    nima ;
+    cpl_size    i ;
+
+    /* Check inputs */
+    cpl_ensure_code(himlist != NULL, CPL_ERROR_NULL_INPUT);
+
+    nima = hdrl_imagelist_get_size(himlist) ;
+
+    for (i=0 ; i<nima ; i++) {
+        hdrl_image  *   himg = hdrl_imagelist_get(himlist, i) ;
+        cpl_ensure_code(!hdrl_image_pow_scalar(himg, exponent),
+                        cpl_error_get_code());
+    }
+    return CPL_ERROR_NONE;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief collapsing of image list
+  @param himlist    input image list
+  @param param      collapse parameters defining the type of collapse
+  @param out        output combined image
+                    pointer filled with pointer to allocated result object
+  @param contrib    output contribution mask
+                    pointer filled with pointer to allocated result object
+  @return   CPL_ERROR_NONE or the relevant the cpl_error_code on error
+  @see hdrl_collapse_mean_parameter_create()
+
+  Collapse an imagelist according to the type of collapse parameter used as
+  input. It only supports collapse methods with the two outputs, the combined
+  image and the contribution map.
+  For collapse functions with additional output the specialized collapse
+  functions must be used.
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+  - CPL_ERROR_UNSUPPORTED_MODE parameter is not a know collapse parameter
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_collapse(
+        const hdrl_imagelist    *   himlist,
+        const hdrl_parameter    *   param,
+        hdrl_image              **  out,
+        cpl_image               **  contrib)
+{
+    cpl_ensure_code(himlist, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(param, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(out, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(contrib, CPL_ERROR_NULL_INPUT);
+
+    if (hdrl_collapse_parameter_is_mean(param)) {
+        hdrl_imagelist_collapse_mean(himlist, out, contrib);
+    }
+    else if (hdrl_collapse_parameter_is_weighted_mean(param)) {
+        hdrl_imagelist_collapse_weighted_mean(himlist, out, contrib);
+    }
+    else if (hdrl_collapse_parameter_is_median(param)) {
+        hdrl_imagelist_collapse_median(himlist, out, contrib);
+    }
+    else if (hdrl_collapse_parameter_is_sigclip(param)) {
+        hdrl_imagelist_collapse_sigclip(himlist,
+                hdrl_collapse_sigclip_parameter_get_kappa_low(param),
+                hdrl_collapse_sigclip_parameter_get_kappa_high(param),
+                hdrl_collapse_sigclip_parameter_get_niter(param),
+                out, contrib, NULL, NULL);
+    }
+    else if (hdrl_collapse_parameter_is_minmax(param)) {
+        hdrl_imagelist_collapse_minmax(himlist,
+                hdrl_collapse_minmax_parameter_get_nlow(param),
+                hdrl_collapse_minmax_parameter_get_nhigh(param),
+                out, contrib, NULL, NULL);
+    }
+    else {
+        return cpl_error_set_message(cpl_func, CPL_ERROR_UNSUPPORTED_MODE,
+                                     "Invalid parameter input for "
+                                     "hdrl_imagelist_collapse");
+    }
+
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Mean collapsing of image list
+  @param himlist    input image list
+  @param out        output combined image
+  @param contrib    output contribution mask
+  @return   CPL_ERROR_NONE or the relevant the cpl_error_code on error
+ 
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_collapse_mean(
+        const hdrl_imagelist    *   himlist,
+        hdrl_image              **  out,
+        cpl_image               **  contrib) 
+{
+    hdrl_collapse_imagelist_to_image_t * method =
+        hdrl_collapse_imagelist_to_image_mean();
+    hdrl_imagelist_collapse_interface(himlist, method, out, contrib, NULL) ;
+    hdrl_collapse_imagelist_to_image_delete(method) ;
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Weighted Mean collapsing of image list
+  @param himlist    input image list
+  @param out        output combined image
+  @param contrib    output contribution mask
+  @return   CPL_ERROR_NONE or the relevant the cpl_error_code on error
+ 
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_collapse_weighted_mean(
+        const hdrl_imagelist    *   himlist,
+        hdrl_image              **  out,
+        cpl_image               **  contrib) 
+{
+    hdrl_collapse_imagelist_to_image_t * method =
+        hdrl_collapse_imagelist_to_image_weighted_mean();
+    hdrl_imagelist_collapse_interface(himlist, method, out, contrib, NULL) ;
+    hdrl_collapse_imagelist_to_image_delete(method) ;
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Median collapsing of image list
+  @param himlist    input image list
+  @param out        output combined image
+  @param contrib    output contribution mask
+  @return   CPL_ERROR_NONE or the relevant the cpl_error_code on error
+ 
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_collapse_median(
+        const hdrl_imagelist    *   himlist,
+        hdrl_image              **  out,
+        cpl_image               **  contrib) 
+{
+    hdrl_collapse_imagelist_to_image_t * method =
+        hdrl_collapse_imagelist_to_image_median();
+    hdrl_imagelist_collapse_interface(himlist, method, out, contrib, NULL) ;
+    hdrl_collapse_imagelist_to_image_delete(method) ;
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Sigma-clipped collapsing of image list
+  @param himlist      input image list
+  @param kappa_low    low sigma bound
+  @param kappa_high   high sigma bound
+  @param niter        number of clipping iterators
+  @param out          output combined image
+  @param contrib      output contribution mask
+  @param reject_low   output low rejection thresholds, may be NULL
+  @param reject_high  output high rejection thresholds, may be NULL
+  @return   CPL_ERROR_NONE or the relevant the cpl_error_code on error
+  @see hdrl_imagelist_collapse()
+ 
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_collapse_sigclip(
+        const hdrl_imagelist    *   himlist,
+        double                      kappa_low,
+        double                      kappa_high,
+        int                         niter,
+        hdrl_image              **  out,
+        cpl_image               **  contrib,
+        cpl_image               **  reject_low,
+        cpl_image               **  reject_high)
+{
+    hdrl_sigclip_image_output * sigclipout;
+    hdrl_collapse_imagelist_to_image_t * method =
+        hdrl_collapse_imagelist_to_image_sigclip(kappa_low, kappa_high, niter);
+    hdrl_imagelist_collapse_interface(himlist, method, out, contrib,
+                                      (void**)&sigclipout);
+    if (reject_low) {
+        *reject_low = sigclipout->reject_low;
+    }
+    else {
+        cpl_image_delete(sigclipout->reject_low);
+    }
+    if (reject_high) {
+        *reject_high = sigclipout->reject_high;
+    }
+    else {
+        cpl_image_delete(sigclipout->reject_high);
+    }
+    hdrl_collapse_imagelist_to_image_unwrap_eout(method, sigclipout);
+    hdrl_collapse_imagelist_to_image_delete(method);
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Minmax-clipped collapsing of image list
+  @param himlist      input image list
+  @param nlow         low number of pixels to reject
+  @param nhigh        high number of pixels to reject
+  @param out          output combined image
+  @param contrib      output contribution mask
+  @param reject_low   output low rejection thresholds, may be NULL
+  @param reject_high  output high rejection thresholds, may be NULL
+  @return   CPL_ERROR_NONE or the relevant the cpl_error_code on error
+  @see hdrl_imagelist_collapse()
+ 
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_collapse_minmax(
+        const hdrl_imagelist    *   himlist,
+        double                      nlow,
+        double                      nhigh,
+        hdrl_image              **  out,
+        cpl_image               **  contrib,
+        cpl_image               **  reject_low,
+        cpl_image               **  reject_high)
+{
+    hdrl_minmax_image_output * minmaxout;
+    hdrl_collapse_imagelist_to_image_t * method =
+        hdrl_collapse_imagelist_to_image_minmax(nlow, nhigh);
+    hdrl_imagelist_collapse_interface(himlist, method, out, contrib,
+                                      (void**)&minmaxout);
+    if (reject_low) {
+        *reject_low = minmaxout->reject_low;
+    }
+    else {
+        cpl_image_delete(minmaxout->reject_low);
+    }
+    if (reject_high) {
+        *reject_high = minmaxout->reject_high;
+    }
+    else {
+        cpl_image_delete(minmaxout->reject_high);
+    }
+    hdrl_collapse_imagelist_to_image_unwrap_eout(method, minmaxout);
+    hdrl_collapse_imagelist_to_image_delete(method);
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Generic hdrl_imagelist_collapse interface to hdrl_collapse
+  @param himlist    input image list
+  @param niter      number of clipping iterators
+  @param out        output combined image
+  @param contrib    output contribution mask
+  @param eout       storage for extra output, may be NULL
+  @return   CPL_ERROR_NONE or the relevant the cpl_error_code on error
+ 
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code hdrl_imagelist_collapse_interface(
+        const hdrl_imagelist                *   himlist,
+        hdrl_collapse_imagelist_to_image_t  *   collapse_method,
+        hdrl_image                          **  out,
+        cpl_image                           **  contrib,
+        void                                **  eout)
+{
+    /* Check inputs */
+    cpl_ensure_code(himlist != NULL, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(out != NULL, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(contrib != NULL, CPL_ERROR_NULL_INPUT);
+
+    cpl_size nz = hdrl_imagelist_get_size(himlist);
+    cpl_size nx = hdrl_imagelist_get_size_x(himlist);
+    cpl_size ny = hdrl_imagelist_get_size_y(himlist);
+    if (cpl_error_get_code() != CPL_ERROR_NONE) {
+        return cpl_error_get_code();
+    }
+
+    *out = hdrl_image_new(nx, ny);
+    *contrib = cpl_image_new(nx, ny, CPL_TYPE_INT);
+    /* make sure we have masks else the copy into these is not threadsafe */
+    cpl_image_get_bpm(*contrib);
+    hdrl_image_get_mask(*out);
+    /* create full extra output */
+    if (eout) {
+        *eout = hdrl_collapse_imagelist_to_image_create_eout(collapse_method,
+                     hdrl_image_get_image(hdrl_imagelist_get(himlist, 0)));
+    }
+
+    /* get blocks that can be processed in parallel
+     * small blocksize better for cache but currently excessive malloc/free
+     * prevents making it smaller */
+    cpl_size blocksize = 16ul * (1ul<<20ul) / (nz * nx * sizeof(double));
+    hdrl_iter * it = hdrl_imagelist_get_iter_row_slices(himlist, blocksize,
+                                                        HDRL_ITER_CONST);
+    cpl_size nit = hdrl_iter_length(it);
+    hdrl_imagelist * vl[nit];
+    cpl_size yl[nit];
+    {
+        cpl_size i = 0;
+        cpl_size y = 1;
+        for (hdrl_imagelist * v = hdrl_iter_next(it);
+             v != NULL;
+             v = hdrl_iter_next(it)) {
+            vl[i] = v;
+            yl[i++] = y;
+            y += hdrl_imagelist_get_size_y(v);
+        }
+    }
+    hdrl_iter_delete(it);
+    if (cpl_error_get_code() != CPL_ERROR_NONE) {
+        for (cpl_size i = 0; i < nit; i++) {
+            hdrl_imagelist_delete(vl[i]);
+        }
+        return cpl_error_get_code();
+    }
+
+HDRL_OMP(omp parallel for)
+    for (cpl_size i = 0; i < nit; i++) {
+        cpl_image * out_data ;
+        cpl_image * out_errors ;
+        cpl_image * out_contrib ;
+        cpl_imagelist * data ;
+        cpl_imagelist * errors ;
+        void * out_eout;
+        hdrl_imagelist *v = vl[i];
+        cpl_size y = yl[i];
+        /* Build the Inputs Interface */
+        hdrl_imagelist_to_cplwrap(v, &data, &errors);
+
+        /* Call the actual collapsing */
+        hdrl_collapse_imagelist_to_image_call(collapse_method, data, errors,
+                                              &out_data, &out_errors,
+                                              &out_contrib, &out_eout);
+        cpl_msg_debug(cpl_func, "Collapsed block %lld to %lld", y,
+                      y + cpl_image_get_size_y(out_data) - 1);
+
+        /* TODO make use of output image views to avoid copying */
+        assert(hdrl_image_get_mask_const(*out));
+        assert(cpl_image_get_bpm_const(*contrib));
+        hdrl_image_insert(*out, out_data, out_errors, 1, y);
+        cpl_image_copy(*contrib, out_contrib, 1, y);
+        /* copy and delete slice extra out */
+        if (out_eout) {
+            hdrl_collapse_imagelist_to_image_move_eout(collapse_method,
+                                                       *eout, out_eout, y);
+        }
+
+        /* Destroy the Inputs Interface */
+        cpl_image_delete(out_data);
+        cpl_image_delete(out_errors);
+        cpl_image_delete(out_contrib);
+        cpl_imagelist_unwrap(data) ;
+        cpl_imagelist_unwrap(errors) ;
+        hdrl_imagelist_delete(v);
+    }
+
+    return cpl_error_get_code();
+}
+
+/**@}*/
diff --git a/hdrl/hdrl_imagelist_basic.h b/hdrl/hdrl_imagelist_basic.h
new file mode 100644
index 0000000..bb38671
--- /dev/null
+++ b/hdrl/hdrl_imagelist_basic.h
@@ -0,0 +1,79 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_IMAGELIST_BASIC_H
+#define HDRL_IMAGELIST_BASIC_H
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_collapse.h"
+#include "hdrl_parameter.h"
+#include "hdrl_imagelist.h"
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                            Function prototypes
+ -----------------------------------------------------------------------------*/
+
+/* Imagelist Basic Operations */
+cpl_error_code hdrl_imagelist_add_imagelist(hdrl_imagelist *, 
+        const hdrl_imagelist *);
+cpl_error_code hdrl_imagelist_sub_imagelist(hdrl_imagelist *, 
+        const hdrl_imagelist *);
+cpl_error_code hdrl_imagelist_mul_imagelist(hdrl_imagelist *, 
+        const hdrl_imagelist *);
+cpl_error_code hdrl_imagelist_div_imagelist(hdrl_imagelist *, 
+        const hdrl_imagelist *);
+
+cpl_error_code hdrl_imagelist_add_image(hdrl_imagelist *, const hdrl_image *);
+cpl_error_code hdrl_imagelist_sub_image(hdrl_imagelist *, const hdrl_image *);
+cpl_error_code hdrl_imagelist_mul_image(hdrl_imagelist *, const hdrl_image *);
+cpl_error_code hdrl_imagelist_div_image(hdrl_imagelist *, const hdrl_image *);
+
+cpl_error_code hdrl_imagelist_add_scalar(hdrl_imagelist *, hdrl_value);
+cpl_error_code hdrl_imagelist_sub_scalar(hdrl_imagelist *, hdrl_value);
+cpl_error_code hdrl_imagelist_mul_scalar(hdrl_imagelist *, hdrl_value);
+cpl_error_code hdrl_imagelist_div_scalar(hdrl_imagelist *, hdrl_value);
+cpl_error_code hdrl_imagelist_pow_scalar(hdrl_imagelist *, hdrl_value);
+
+/* Collapsing functions */
+cpl_error_code hdrl_imagelist_collapse(
+        const hdrl_imagelist    *   himlist,
+        const hdrl_parameter    *   param,
+        hdrl_image              **  out,
+        cpl_image               **  contrib);
+cpl_error_code hdrl_imagelist_collapse_mean(const hdrl_imagelist *, 
+        hdrl_image **, cpl_image **) ;
+cpl_error_code hdrl_imagelist_collapse_weighted_mean(const hdrl_imagelist *, 
+        hdrl_image **, cpl_image **) ;
+cpl_error_code hdrl_imagelist_collapse_median(const hdrl_imagelist *, 
+        hdrl_image **, cpl_image **) ;
+cpl_error_code hdrl_imagelist_collapse_sigclip(const hdrl_imagelist *, 
+        double, double, int, hdrl_image **, cpl_image **,
+        cpl_image **, cpl_image **) ;
+cpl_error_code hdrl_imagelist_collapse_minmax(const hdrl_imagelist *,
+        double, double, hdrl_image **, cpl_image **,
+        cpl_image **, cpl_image **) ;
+
+CPL_END_DECLS
+
+#endif 
diff --git a/hdrl/hdrl_imagelist_basic_body.h b/hdrl/hdrl_imagelist_basic_body.h
new file mode 100644
index 0000000..edda6f2
--- /dev/null
+++ b/hdrl/hdrl_imagelist_basic_body.h
@@ -0,0 +1,83 @@
+/* $Id: hdrl_imagelist_basic_body.h,v 1.2 2013-09-30 09:08:57 yjung Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: yjung $
+ * $Date: 2013-09-30 09:08:57 $
+ * $Revision: 1.2 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#if HDRL_OPERATION == HDRL_IMLIST_BASIC_IMLIST
+
+    cpl_size i;
+
+    /* Check input */
+    cpl_ensure_code(himlist1, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(himlist2, CPL_ERROR_NULL_INPUT);
+
+    /* Check image sets compatibility     */
+    cpl_ensure_code( himlist1->ni == himlist2->ni, CPL_ERROR_ILLEGAL_INPUT);
+
+    /* Loop on the planes and apply the operation */
+    for (i=0; i<himlist1->ni; i++) {
+        const cpl_error_code error_code = 
+            HDRL_OPERATOR(himlist1->images[i], himlist2->images[i]);
+        cpl_ensure_code(!error_code, error_code);
+    }
+
+    return CPL_ERROR_NONE;
+
+#elif HDRL_OPERATION == HDRL_IMLIST_BASIC_IMAGE
+
+    cpl_size i;
+
+    /* Check input */
+    cpl_ensure_code(himlist, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(himg, CPL_ERROR_NULL_INPUT);
+
+    /* Loop on the planes and apply the operation */
+    for (i=0; i<himlist->ni; i++) {
+        const cpl_error_code error_code = HDRL_OPERATOR(himlist->images[i], 
+                himg);
+        cpl_ensure_code(!error_code, error_code);
+    }
+
+    return CPL_ERROR_NONE;
+
+#elif HDRL_OPERATION == HDRL_IMLIST_BASIC_SCALAR
+
+    cpl_size i;
+
+    /* Check input */
+    cpl_ensure_code(himlist, CPL_ERROR_NULL_INPUT);
+
+    /* Loop on the planes and apply the operation */
+    for (i=0; i<himlist->ni; i++) {
+        const cpl_error_code error_code = HDRL_OPERATOR(himlist->images[i],
+                                                        value);
+        cpl_ensure_code(!error_code, error_code);
+    }
+
+    return CPL_ERROR_NONE;
+
+
+#endif
+
diff --git a/hdrl/hdrl_imagelist_defs.h b/hdrl/hdrl_imagelist_defs.h
new file mode 100644
index 0000000..300aa4c
--- /dev/null
+++ b/hdrl/hdrl_imagelist_defs.h
@@ -0,0 +1,51 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013,2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_IMAGELIST_DEFS_H
+#define HDRL_IMAGELIST_DEFS_H
+
+#ifndef HDRL_USE_PRIVATE
+#error This file is not allowed to be included outside of hdrl
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_imagelist.h"
+#include "hdrl_image.h"
+
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                                   New types
+ -----------------------------------------------------------------------------*/
+
+struct _hdrl_imagelist_ {
+    cpl_size        ni;
+    cpl_size        capacity;
+    hdrl_image  **  images;
+};
+
+
+CPL_END_DECLS
+
+#endif 
diff --git a/hdrl/hdrl_imagelist_io.c b/hdrl/hdrl_imagelist_io.c
new file mode 100644
index 0000000..cecf804
--- /dev/null
+++ b/hdrl/hdrl_imagelist_io.c
@@ -0,0 +1,660 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013,2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_image.h"
+#include "hdrl_imagelist.h"
+#include "hdrl_imagelist_defs.h"
+#include "hdrl_imagelist_view.h"
+#include "hdrl_iter.h"
+
+#include <cpl.h>
+#include <assert.h>
+#include <string.h>
+
+/*-----------------------------------------------------------------------------
+                            Static Prototypes
+ -----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @addtogroup hdrl_imagelist
+ * @{
+ */
+/*----------------------------------------------------------------------------*/
+
+/*-----------------------------------------------------------------------------
+                            Function codes
+ -----------------------------------------------------------------------------*/
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief resize buffer to set size
+ * @param h    imagelist to update
+ * @param size capacity the buffer should have, minimum 128
+ *
+ * only changes the buffer size, not the number of contained images
+ */
+/* ---------------------------------------------------------------------------*/
+static void hdrl_imagelist_set_capacity(hdrl_imagelist * h, cpl_size size)
+{
+    h->capacity = CX_MAX(h->ni, CX_MAX(128, size));
+    h->images = cpl_realloc(h->images, h->capacity * sizeof(h->images[0]));
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Create an empty imagelist
+  @return   1 newly allocated hdrl_imagelist
+  @see      hdrl_imagelist_set()
+  The returned hdrl_imagelist must be deallocated using hdrl_imagelist_delete()
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_imagelist * hdrl_imagelist_new(void)
+{
+    hdrl_imagelist * h = cpl_calloc(1, sizeof(hdrl_imagelist));
+    hdrl_imagelist_set_capacity(h, 128);
+    return h;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Create an hdrl_imagelist out of 2 cpl_imagelist 
+  @param    imlist    the list of image
+  @param    errlist   the list of errors
+  @return   The new hdrl_imagelist
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_imagelist * hdrl_imagelist_create(
+        cpl_imagelist   *   imlist,
+        cpl_imagelist   *   errlist)
+{
+    hdrl_imagelist  *   himlist ;
+    cpl_image       *   error ;
+    
+    /* Check Entries */
+    cpl_ensure(imlist != NULL, CPL_ERROR_NULL_INPUT, NULL);
+    if (errlist) {
+        cpl_ensure(cpl_imagelist_get_size(imlist) == 
+                cpl_imagelist_get_size(errlist), CPL_ERROR_ILLEGAL_INPUT, NULL);
+    }
+    
+    /* Create the new HDRL image list */
+    himlist = hdrl_imagelist_new() ;
+    
+    /* Loop on the input image list */
+    for (cpl_size i = 0; i < cpl_imagelist_get_size(imlist); i++) {
+        /* Get the error image */
+        hdrl_image * tmp ;
+        if (errlist) {
+            error = cpl_imagelist_get(errlist, i) ;
+        } else {
+            error = NULL ;
+        }
+        /* Create the HDRL image */
+        tmp = hdrl_image_create(cpl_imagelist_get_const(imlist, i), error) ;
+
+        /* Fill the HDRL image list */
+        hdrl_imagelist_set(himlist, tmp, i);
+
+    }
+    return himlist ;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Get the number of images in the imagelist
+  @param    himlist     the list of images
+  @return   The number of images or -1 on error
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/*----------------------------------------------------------------------------*/
+cpl_size hdrl_imagelist_get_size(const hdrl_imagelist * himlist)
+{
+    cpl_ensure(himlist != NULL, CPL_ERROR_NULL_INPUT, -1);
+    assert( himlist->ni >= 0 );
+    return himlist->ni;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Get number of colums of  images in the imagelist
+  @param    himlist     the list of images
+  @return   The number of columns of images or -1 on error
+
+  assumes the imagelist is uniform (cpl_imagelist_is_uniform)
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+  - CPL_ERROR_ILLEGAL_INPUT if the list is empty
+ */
+/*----------------------------------------------------------------------------*/
+cpl_size hdrl_imagelist_get_size_x(const hdrl_imagelist * himlist)
+{
+    cpl_ensure(himlist != NULL, CPL_ERROR_NULL_INPUT, -1);
+    cpl_ensure(himlist->ni > 0, CPL_ERROR_ILLEGAL_INPUT, -1);
+    return hdrl_image_get_size_x(hdrl_imagelist_get_const(himlist, 0));
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Get number of rows of  images in the imagelist
+  @param    himlist     the list of images
+  @return   The number of rows of images or -1 on error
+
+  assumes the imagelist is uniform (cpl_imagelist_is_uniform)
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+  - CPL_ERROR_ILLEGAL_INPUT if the list is empty
+ */
+/*----------------------------------------------------------------------------*/
+cpl_size hdrl_imagelist_get_size_y(const hdrl_imagelist * himlist)
+{
+    cpl_ensure(himlist != NULL, CPL_ERROR_NULL_INPUT, -1);
+    cpl_ensure(himlist->ni > 0, CPL_ERROR_ILLEGAL_INPUT, -1);
+    return hdrl_image_get_size_y(hdrl_imagelist_get_const(himlist, 0));
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Get an image from a list of images
+  @param    himlist the image list
+  @param    inum    the image id (from 0 to number of images-1)
+  @return   A pointer to the image or NULL in error case.
+
+  The returned pointer refers to already allocated data.
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+  - CPL_ERROR_ACCESS_OUT_OF_RANGE if inum is bigger thant the list size
+  - CPL_ERROR_ILLEGAL_INPUT if inum is negative
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_image * hdrl_imagelist_get(
+        const hdrl_imagelist  *   himlist,
+        cpl_size                  inum)
+{
+    cpl_ensure(himlist != NULL, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(inum >= 0, CPL_ERROR_ILLEGAL_INPUT, NULL);
+    cpl_ensure(inum < himlist->ni, CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+    return himlist->images[inum];
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Get an image from a list of images
+  @param    himlist the image list
+  @param    inum    the image id (from 0 to number of images-1)
+  @return   A pointer to the image or NULL in error case.
+  @see hdrl_imagelist_get
+ */
+/*----------------------------------------------------------------------------*/
+const hdrl_image * hdrl_imagelist_get_const(
+        const hdrl_imagelist    *   himlist,
+        cpl_size                    inum)
+{
+    cpl_ensure(himlist != NULL, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(inum >= 0, CPL_ERROR_ILLEGAL_INPUT, NULL);
+    cpl_ensure(inum < himlist->ni, CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+    return himlist->images[inum];
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Insert an image into an imagelist
+  @param    himlist  The imagelist
+  @param    himg     The image to insert
+  @param    pos      The list position (from 0 to number of images)
+  @return   CPL_ERROR_NONE or the relevant cpl_error_code on error
+
+  It is allowed to specify the position equal to the number of images in the
+  list. This will increment the size of the imagelist.
+
+  No action occurs if an image is inserted more than once into the same
+  position. It is allowed to insert the same image into two different
+  positions in a list.
+
+  The image is inserted at the position pos in the image list. If the image
+  already there is only present in that one location in the list, then the
+  image is deallocated.
+
+  It is not allowed to insert images of different size into a list.
+
+  The added image is owned by the imagelist object, which deallocates it
+  hdrl_imagelist_delete is called. Other option is to use 
+  hdrl_imagelist_unset to recover ownership of the image, in which case 
+  the hdrl_imagelist object is not longer responsible for deallocating it.
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+  - CPL_ERROR_ILLEGAL_INPUT if pos is negative
+  - CPL_ERROR_TYPE_MISMATCH if himg and himlist are of different types
+  - CPL_ERROR_INCOMPATIBLE_INPUT if himg and himlist have different sizes
+  - CPL_ERROR_ACCESS_OUT_OF_RANGE if pos is bigger than the number of
+    images in himlist
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_set(
+        hdrl_imagelist  *   himlist,
+        hdrl_image      *   himg,
+        cpl_size            pos)
+{
+    cpl_ensure_code(himlist,            CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(himg,                CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(pos >= 0,          CPL_ERROR_ILLEGAL_INPUT);
+    cpl_ensure_code(pos <= himlist->ni, CPL_ERROR_ACCESS_OUT_OF_RANGE);
+
+    /* Do nothing if the image is already there */
+    if (pos < himlist->ni && himg == himlist->images[pos]) 
+        return CPL_ERROR_NONE;
+
+    if (pos > 0 || himlist->ni > 1) {
+        /* Require images to have the same size and type */
+        cpl_ensure_code(hdrl_image_get_size_x(himg) ==
+                        hdrl_image_get_size_x(himlist->images[0]),
+                        CPL_ERROR_INCOMPATIBLE_INPUT);
+        cpl_ensure_code(hdrl_image_get_size_y(himg) ==
+                        hdrl_image_get_size_y(himlist->images[0]),
+                        CPL_ERROR_INCOMPATIBLE_INPUT);
+        // TODO : type of hdrl_image ??
+        //cpl_ensure_code(hdrl_image_get_type(himg) ==
+        //                hdrl_image_get_type(himlist->images[0]),
+        //                CPL_ERROR_TYPE_MISMATCH);
+    }
+
+    if (pos == himlist->ni) {
+        /* double buffer if required */
+        if (pos >= himlist->capacity) {
+            hdrl_imagelist_set_capacity(himlist, 2 * pos);
+        }
+        himlist->ni++;
+    } else {
+        /* Check if the image at the position to be overwritten
+           is present in only one position */
+        int i;
+
+        for (i = 0; i < himlist->ni; i++) {
+            if (i != pos && himlist->images[i] == himlist->images[pos]) break;
+        }
+        if (i == himlist->ni) {
+            /* The image at the position to be overwritten
+               is present in only one position, so delete it */
+            hdrl_image_delete(himlist->images[pos]);
+        }
+    }
+
+    himlist->images[pos] = himg;
+
+    return CPL_ERROR_NONE;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Remove an image from an imagelist
+  @param    himlist The imagelist
+  @param    pos     The list position (from 0 to number of images-1)
+  @return   The pointer to the removed image or NULL in error case
+
+  The specified image is not deallocated, it is simply removed from the
+  list. The pointer to the image is returned to let the user decide to
+  deallocate it or not.
+  Eventually, the image will have to be deallocated with hdrl_image_delete().
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+  - CPL_ERROR_ILLEGAL_INPUT if pos is negative
+  - CPL_ERROR_ACCESS_OUT_OF_RANGE if pos is bigger than the number of
+    images in himlist
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_image * hdrl_imagelist_unset(
+        hdrl_imagelist  *   himlist,
+        cpl_size            pos)
+{
+    hdrl_image  *   out;
+    cpl_size        i;
+
+    cpl_ensure(himlist, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(pos >= 0, CPL_ERROR_ILLEGAL_INPUT, NULL);
+    cpl_ensure(pos < himlist->ni, CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+
+    /* Get pointer to image to be removed */
+    out = himlist->images[pos];
+
+    /* Move the following images one position towards zero */
+    for (i=pos + 1; i < himlist->ni; i++) {
+        himlist->images[i-1] = himlist->images[i];
+    }
+
+    /* Decrement of the size */
+    himlist->ni--;
+
+    /* shrink the buffer if its significantly too large */
+    if (himlist->ni < himlist->capacity / 2) {
+        hdrl_imagelist_set_capacity(himlist, himlist->ni / 2);
+    }
+
+    return out;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Free all memory used by a hdrl_imagelist object including the images
+  @param    himlist    The image list or NULL
+  @return   Nothing
+  @see      hdrl_imagelist_empty(), hdrl_imagelist_unwrap()
+ */
+/*----------------------------------------------------------------------------*/
+void hdrl_imagelist_delete(hdrl_imagelist * himlist)
+{
+    if (himlist != NULL) {
+        hdrl_imagelist_empty(himlist);
+        hdrl_imagelist_unwrap(himlist);
+    }
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Empty an imagelist and deallocate all its images
+  @param    himlist  The image list or NULL
+  @return   Nothing
+  @see  hdrl_imagelist_empty(), hdrl_imagelist_delete()
+  @note If @em himlist is @c NULL nothing is done and no error is set.
+
+  After the call the image list can be populated again. It must eventually
+  be deallocated with a call to hdrl_imagelist_delete().
+ */
+/*----------------------------------------------------------------------------*/
+void hdrl_imagelist_empty(hdrl_imagelist * himlist)
+{
+    if (himlist != NULL) {
+        while (himlist->ni > 0) { /* An iteration may unset more than 1 image */
+            cpl_size i = himlist->ni - 1;
+            hdrl_image * del = hdrl_imagelist_unset(himlist, i);
+            hdrl_image_delete(del);
+
+            /* If this image was inserted more than once into the list,
+               the other insertions must be unset without a delete. */
+            while (--i >= 0) {
+                if (himlist->images[i] == del) {
+                    /* This image was inserted more than once in the list */
+                    (void)hdrl_imagelist_unset(himlist, i);
+                }
+            }
+        }
+    }
+    return;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Duplicate an image list
+  @param    himlist Source image list.
+  @return   1 newly allocated image list, or NULL on error.
+
+  Copy an image list into a new image list object.
+  The returned image list must be deallocated using hdrl_imagelist_delete().
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_imagelist * hdrl_imagelist_duplicate(const hdrl_imagelist * himlist)
+{
+    hdrl_imagelist *   out;
+    cpl_size          i;
+
+    cpl_ensure(himlist != NULL, CPL_ERROR_NULL_INPUT, NULL);
+
+    /* Create the new imagelist */
+    out = hdrl_imagelist_new();
+
+    /* Duplicate the images */
+    for (i=0; i<himlist->ni; i++) {
+        hdrl_imagelist_set(out, hdrl_image_duplicate(himlist->images[i]), i);
+    }
+
+    return out;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Determine if an imagelist contains images of equal size and type
+  @param    himlist The imagelist to check
+  @return   Zero if ok, positive if not consistent and negative on error.
+
+  The function returns 1 if the list is empty.
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+ */
+/*----------------------------------------------------------------------------*/
+int hdrl_imagelist_is_consistent(const hdrl_imagelist * himlist)
+{
+    cpl_ensure(himlist != NULL, CPL_ERROR_NULL_INPUT, -1);
+    if (himlist->ni == 0) return 1;
+
+    /* Check the images */
+    // TODO
+    return 0;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Dump structural information of images in an imagelist
+  @param    himlist Imagelist to dump
+  @param    stream  Output stream, accepts @c stdout or @c stderr
+  @return   CPL_ERROR_NONE or the relevant cpl_error_code on error
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+  - CPL_ERROR_FILE_IO if a write operation fails
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_dump_structure(
+        const hdrl_imagelist    *   himlist,
+        FILE                    *   stream)
+{
+    const char * msg    = "Imagelist with %d image(s)\n";
+    const int    msgmin = (int)strlen(msg) - 5;
+
+    int i;
+
+    cpl_ensure_code(himlist   != NULL, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(stream != NULL, CPL_ERROR_NULL_INPUT);
+
+    cpl_ensure_code( fprintf(stream,  msg, himlist->ni) >= msgmin,
+             CPL_ERROR_FILE_IO );
+
+    for (i = 0; i < himlist -> ni; i++) {
+    const hdrl_image    *   image   = hdrl_imagelist_get_const(himlist, i);
+    const char          *   imsg    = "Image nb %d of %d in imagelist\n";
+    const int               imsgmin = (int)strlen(imsg) - 5;
+
+    cpl_ensure_code( fprintf(stream,  imsg, i, himlist->ni) >= imsgmin,
+             CPL_ERROR_FILE_IO );
+
+    cpl_ensure_code( !hdrl_image_dump_structure(image, stream),
+             cpl_error_get_code() );
+    }
+
+    return CPL_ERROR_NONE;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Dump pixel values of images in a imagelist
+  @param    himlist    Imagelist to dump
+  @param    llx     Specifies the window position
+  @param    lly     Specifies the window position
+  @param    urx     Specifies the window position
+  @param    ury     Specifies the window position
+  @param    stream  Output stream, accepts @c stdout or @c stderr
+  @return   CPL_ERROR_NONE or the relevant cpl_error_code on error
+
+  Possible cpl_error_code set in this function:
+  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
+  - CPL_ERROR_FILE_IO if a write operation fails
+  - CPL_ERROR_ACCESS_OUT_OF_RANGE if the defined window is not in the image
+  - CPL_ERROR_ILLEGAL_INPUT if the window definition is wrong (e.g llx > urx)
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_dump_window(
+        const hdrl_imagelist    *   himlist,
+        cpl_size                    llx,
+        cpl_size                    lly,
+        cpl_size                    urx, 
+        cpl_size                    ury,
+        FILE *                      stream)
+{
+    cpl_size i;
+
+    cpl_ensure_code(himlist   != NULL, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(stream != NULL, CPL_ERROR_NULL_INPUT);
+
+    for (i = 0; i < himlist -> ni; i++) {
+    const hdrl_image    *   image   = hdrl_imagelist_get_const(himlist, i);
+    const char          *   imsg    = "Image nb %d of %d in imagelist\n";
+    const int               imsgmin = (int)strlen(imsg) - 5;
+
+    cpl_ensure_code( fprintf(stream,  imsg, i, himlist->ni) >= imsgmin,
+             CPL_ERROR_FILE_IO );
+
+    cpl_ensure_code( !hdrl_image_dump_window(image, llx, lly, urx, ury,
+                           stream),
+             cpl_error_get_code() );
+    }
+    return CPL_ERROR_NONE;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief    Free memory used by a hdrl_imagelist object, except the images
+  @param    himlist    The image list or NULL
+  @return   Nothing
+  @see hdrl_imagelist_empty()
+  @note The caller must have pointers to all images in the list and is
+        reponsible for their deallocation. If @em himlist is @c NULL nothing is
+        done and no error is set.
+ */
+/*----------------------------------------------------------------------------*/
+void hdrl_imagelist_unwrap(hdrl_imagelist * himlist)
+{
+    if (himlist != NULL) {
+        cpl_free(himlist->images);
+        cpl_free(himlist);
+    }
+    return;
+}
+
+typedef struct {
+    const hdrl_imagelist * hlist;
+    cpl_size ny;
+    cpl_size pos;
+    cpl_size nrows;
+    hdrl_imagelist * last_view;
+} hdrl_imagelist_row_slices_iter;
+
+static void * hdrl_imagelist_row_slices_next(hdrl_iter * it)
+{
+    hdrl_imagelist_row_slices_iter * s = hdrl_iter_state(it);
+    if (s->pos > s->ny) {
+        return NULL;
+    }
+    cpl_size upper = CX_MIN(s->pos + s->nrows - 1, s->ny);
+    /* const iterator means you cannot modify the data but the created views
+     * can have a NULL bpm which can be faster e.g. when calling
+     * cpl_image_new_from_accepted on the view */
+    /* TODO could set memory readonly? */
+    hdrl_imagelist * view;
+    if (hdrl_iter_check(it, HDRL_ITER_CONST)) {
+        view = (hdrl_imagelist*)
+            hdrl_imagelist_const_row_view((hdrl_imagelist*)s->hlist,
+                                          s->pos, upper);
+    }
+    else {
+        view = hdrl_imagelist_row_view((hdrl_imagelist*)s->hlist,
+                                       s->pos, upper);
+    }
+
+    s->pos = upper + 1;
+    if (hdrl_iter_check(it, HDRL_ITER_OWN_OUTPUT)) {
+        hdrl_imagelist_delete(s->last_view);
+        s->last_view = view;
+    }
+    return view;
+}
+
+static cpl_size hdrl_imagelist_row_slices_length(hdrl_iter * it)
+{
+    hdrl_imagelist_row_slices_iter * s = hdrl_iter_state(it);
+    return s->ny / s->nrows + ((s->ny % s->nrows) != 0);
+}
+
+static void hdrl_imagelist_iter_delete(void * state)
+{
+    if (!state)
+        return;
+    hdrl_imagelist_row_slices_iter * s = state;
+    hdrl_imagelist_delete(s->last_view);
+    cpl_free(s);
+}
+
+/* TODO, add offset and stride for parallel processing? or imagelist_split? */
+hdrl_iter * hdrl_imagelist_get_iter_row_slices(const hdrl_imagelist * hlist,
+                                                 cpl_size nrows,
+                                                 hdrl_iter_type_t flags)
+{
+    cpl_ensure(hlist, CPL_ERROR_NULL_INPUT, NULL);
+    /* 0 accepted for now, could mean choosen by function */
+    cpl_ensure(nrows >= 0, CPL_ERROR_ILLEGAL_INPUT, NULL);
+    cpl_ensure(hdrl_imagelist_get_size(hlist) > 0,
+               CPL_ERROR_ILLEGAL_INPUT, NULL);
+
+    hdrl_imagelist_row_slices_iter * state = cpl_malloc(sizeof(*state));
+    state->hlist = hlist;
+    state->ny = hdrl_imagelist_get_size_y(hlist);
+    state->pos = 1;
+    state->nrows = CX_MAX(nrows, 1);
+    state->last_view = NULL;
+
+    return hdrl_iter_init(hdrl_imagelist_row_slices_next, NULL,
+                          hdrl_imagelist_row_slices_length,
+                          hdrl_imagelist_iter_delete,
+                          HDRL_ITER_INPUT | HDRL_ITER_IMAGELIST | flags,
+                          state);
+}
+
+
+/**@}*/
diff --git a/hdrl/hdrl_imagelist_io.h b/hdrl/hdrl_imagelist_io.h
new file mode 100644
index 0000000..fee8b13
--- /dev/null
+++ b/hdrl/hdrl_imagelist_io.h
@@ -0,0 +1,91 @@
+/* $Id: hdrl_imagelist_io.h,v 1.8 2013-10-17 15:44:14 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-17 15:44:14 $
+ * $Revision: 1.8 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifndef HDRL_IMAGELIST_IO_H
+#define HDRL_IMAGELIST_IO_H
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_image.h"
+#include "hdrl_imagelist.h"
+#include "hdrl_iter.h"
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                            Function prototypes
+ -----------------------------------------------------------------------------*/
+
+/* Imagelist constructors */
+hdrl_imagelist * hdrl_imagelist_new(void) CPL_ATTR_ALLOC;
+hdrl_imagelist * hdrl_imagelist_create(cpl_imagelist *, 
+        cpl_imagelist *) CPL_ATTR_ALLOC;
+
+/* Imagelist accessors */
+cpl_size hdrl_imagelist_get_size(const hdrl_imagelist *);
+cpl_size hdrl_imagelist_get_size_x(const hdrl_imagelist * himlist);
+cpl_size hdrl_imagelist_get_size_y(const hdrl_imagelist * himlist);
+hdrl_image * hdrl_imagelist_get(const hdrl_imagelist *, cpl_size);
+const hdrl_image * hdrl_imagelist_get_const(const hdrl_imagelist *, cpl_size);
+cpl_error_code hdrl_imagelist_set(hdrl_imagelist *, hdrl_image *, cpl_size);
+hdrl_image * hdrl_imagelist_unset(hdrl_imagelist *, cpl_size);
+
+/* Imagelist destructor */
+void hdrl_imagelist_delete(hdrl_imagelist *);
+void hdrl_imagelist_empty(hdrl_imagelist *);
+
+/* Others */
+hdrl_imagelist * hdrl_imagelist_duplicate(
+        const hdrl_imagelist *) CPL_ATTR_ALLOC;
+int hdrl_imagelist_is_consistent(const hdrl_imagelist *) ;
+
+cpl_error_code hdrl_imagelist_dump_structure(const hdrl_imagelist *, FILE *);
+cpl_error_code hdrl_imagelist_dump_window(const hdrl_imagelist *,
+                     cpl_size, cpl_size, cpl_size, cpl_size, FILE *);
+
+
+/*-----------------------------------------------------------------------------
+  Experimental declarations - can be used, but no guarantees on api stability
+ -----------------------------------------------------------------------------*/
+#if defined HDRL_USE_EXPERIMENTAL || defined HDRL_USE_PRIVATE
+hdrl_iter * hdrl_imagelist_get_iter_row_slices(const hdrl_imagelist * hlist,
+                                                 cpl_size nrows,
+                                                 hdrl_iter_type_t flags);
+#endif
+
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+ -----------------------------------------------------------------------------*/
+#ifdef HDRL_USE_PRIVATE
+void hdrl_imagelist_unwrap(hdrl_imagelist * himlist);
+#endif
+
+CPL_END_DECLS
+
+#endif 
diff --git a/hdrl/hdrl_imagelist_view.c b/hdrl/hdrl_imagelist_view.c
new file mode 100644
index 0000000..88f4be8
--- /dev/null
+++ b/hdrl/hdrl_imagelist_view.c
@@ -0,0 +1,461 @@
+/* $Id: hdrl_imagelist_view.c,v 1.8 2013-10-23 09:13:56 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-23 09:13:56 $
+ * $Revision: 1.8 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_imagelist.h"
+#include "hdrl_imagelist_defs.h"
+#include "hdrl_imagelist_view.h"
+#include "hdrl_image_defs.h"
+#include "hdrl_image.h"
+
+#include <cpl.h>
+#include <assert.h>
+#include <string.h>
+
+/*-----------------------------------------------------------------------------
+                                   Define
+ -----------------------------------------------------------------------------*/
+
+/*-----------------------------------------------------------------------------
+                            Static Prototypes
+ -----------------------------------------------------------------------------*/
+
+/* destructor unwrapping data and error */
+static void hdrl_image_view_delete(hdrl_image * view)
+{
+    if (view) {
+        hdrl_image * himg = (hdrl_image*)view;
+        cpl_mask_unwrap(cpl_image_unset_bpm(hdrl_image_get_image(himg)));
+        cpl_mask_unwrap(cpl_image_unset_bpm(hdrl_image_get_error(himg)));
+        cpl_image_unwrap(hdrl_image_get_image(himg));
+        cpl_image_unwrap(hdrl_image_get_error(himg));
+        hdrl_image_unwrap(himg);
+    }
+}
+
+/* destructor unwrapping data and deleting error */
+static void hdrl_image_imgview_delete(hdrl_image * view)
+{
+    if (view) {
+        hdrl_image * himg = (hdrl_image*)view;
+        cpl_mask_unwrap(cpl_image_unset_bpm(hdrl_image_get_image(himg)));
+        cpl_image_unwrap(hdrl_image_get_image(himg));
+        cpl_image_delete(hdrl_image_get_error(himg));
+        hdrl_image_unwrap(himg);
+    }
+}
+
+
+/**@{*/
+
+/*-----------------------------------------------------------------------------
+                            Function codes
+ -----------------------------------------------------------------------------*/
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create a row view of an image
+ *
+ * @param himg input image
+ * @param ly   lower row (FITS)
+ * @param uy   upper row (FITS)
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+static hdrl_image *
+hdrl_image_row_view_create(hdrl_image * himg,
+                           cpl_size ly,
+                           cpl_size uy)
+{
+    cpl_image * oimg = hdrl_image_get_image(himg);
+    cpl_image * oerr = hdrl_image_get_error(himg);
+    const size_t dsz = cpl_type_get_sizeof(cpl_image_get_type(oimg));
+    const size_t esz = cpl_type_get_sizeof(cpl_image_get_type(oerr));
+    const cpl_size nx = hdrl_image_get_size_x(himg);
+    char * d = cpl_image_get_data(oimg);
+    char * e = cpl_image_get_data(oerr);
+    size_t offset = (ly - 1) * nx;
+    cpl_size nny = uy - ly + 1;
+    cpl_image * img = cpl_image_wrap(nx, nny, cpl_image_get_type(oimg),
+                                     d + offset * dsz);
+    cpl_image * err = cpl_image_wrap(nx, nny, cpl_image_get_type(oerr),
+                                     e + offset * esz);
+
+    /* we must create a mask in the original in order for views to work */
+    cpl_mask * omask = hdrl_image_get_mask(himg);
+    cpl_mask * mask = cpl_mask_wrap(nx, nny, cpl_mask_get_data(omask) + offset);
+    cpl_mask_delete(hcpl_image_set_bpm(img, mask));
+    omask = cpl_image_get_bpm(himg->error);
+    mask = cpl_mask_wrap(nx, nny, cpl_mask_get_data(omask) + offset);
+    cpl_mask_delete(hcpl_image_set_bpm(err, mask));
+
+    return hdrl_image_wrap(img, err, (hdrl_free*)&hdrl_image_view_delete,
+                           CPL_FALSE);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief create a constant row view of an image
+ *
+ * @param himg input image
+ * @param ly   lower row (FITS)
+ * @param uy   upper row (FITS)
+ * @param uy   upper row (FITS)
+ * @param destructor destructor function pointer
+ *
+ * compared to the non-const row version this does not force a bad pixel map
+ * onto the image which can improve performance a lot when the data is only
+ * read.
+ * As bad pixel information cannot be propagated in this case the view must not
+ * be modified.
+ */
+/* ---------------------------------------------------------------------------*/
+static const hdrl_image *
+hdrl_image_const_row_view_create(const hdrl_image * himg,
+                                 cpl_size ly,
+                                 cpl_size uy,
+                                 hdrl_free * destructor)
+{
+    const cpl_image * oimg = hdrl_image_get_image_const(himg);
+    const cpl_image * oerr = hdrl_image_get_error_const(himg);
+    const size_t dsz = cpl_type_get_sizeof(cpl_image_get_type(oimg));
+    const size_t esz = cpl_type_get_sizeof(cpl_image_get_type(oerr));
+    const cpl_size nx = hdrl_image_get_size_x(himg);
+    const char * d = cpl_image_get_data_const(oimg);
+    const char * e = cpl_image_get_data_const(oerr);
+    size_t offset = (ly - 1) * nx;
+    cpl_size nny = uy - ly + 1;
+    cpl_image * img = cpl_image_wrap(nx, nny, cpl_image_get_type(oimg),
+                                     (char*)d + offset * dsz);
+    cpl_image * err = cpl_image_wrap(nx, nny, cpl_image_get_type(oerr),
+                                     (char *)e + offset * esz);
+
+    /* we must create a mask in the original in order for views to work */
+    const cpl_mask * omask = hdrl_image_get_mask_const(himg);
+    if (omask) {
+        cpl_mask * mask = cpl_mask_wrap(nx, nny,
+                        (cpl_binary*)cpl_mask_get_data_const(omask) + offset);
+        cpl_mask_delete(hcpl_image_set_bpm(img, mask));
+    }
+    else {
+        if (cpl_image_get_bpm_const(himg->error) != NULL) {
+            cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_INPUT,
+                                  "Inconsistent HDRL image, data image has no"
+                                  " BPM but error image does");
+            cpl_image_unwrap(img);
+            cpl_image_unwrap(err);
+            return NULL;
+        }
+    }
+    omask = cpl_image_get_bpm_const(himg->error);
+    if (omask) {
+        cpl_mask * mask = cpl_mask_wrap(nx, nny,
+                        (cpl_binary*)cpl_mask_get_data_const(omask) + offset);
+        cpl_mask_delete(hcpl_image_set_bpm(err, mask));
+    }
+
+    return hdrl_image_wrap(img, err, destructor, CPL_FALSE);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create view of subset of image rows in an imagelist
+ *
+ * @param hl source imagelist to create view of
+ * @param ly lower y row to view (FITS convention)
+ * @param uy upper y row to view (FITS convention)
+ *
+ * @return imagelist view
+ *
+ * The imagelist will contain the same number of images but they will have
+ * uy - ly + 1 rows. Modifiying the view will modify the selected rows of the
+ * original imagelist.
+ * The view can be deleted with hdrl_imagelist_delete.
+ * Deleting the original imagelist will invalidate all views, they must not be
+ * used anymore besides being deleted.
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_imagelist * hdrl_imagelist_row_view(
+    hdrl_imagelist * hl,
+    cpl_size ly,
+    cpl_size uy)
+{
+    cpl_ensure(hl, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(uy >= ly, CPL_ERROR_ILLEGAL_INPUT, NULL);
+    cpl_ensure(ly > 0, CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+    size_t n = hdrl_imagelist_get_size(hl);
+    cpl_ensure(n > 0, CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+    cpl_ensure(uy <= hdrl_imagelist_get_size_y(hl),
+               CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+
+    hdrl_imagelist * viewlist = hdrl_imagelist_new();
+    for (size_t i = 0; i < n; i++) {
+        hdrl_image * img = hdrl_imagelist_get(hl, i);
+        hdrl_image * view = hdrl_image_row_view_create(img, ly, uy);
+        if (view == NULL) {
+            hdrl_imagelist_delete(viewlist);
+            return NULL;
+        }
+        hdrl_imagelist_set(viewlist, view, i);
+    }
+
+    return viewlist;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create const view of subset of image rows in an imagelist
+ *
+ * @param hl source imagelist to create view of
+ * @param ly lower y row to view (FITS convention)
+ * @param uy upper y row to view (FITS convention)
+ *
+ * @return constant imagelist view
+ *
+ * The imagelist will contain the same number of images but they will have
+ * uy - ly + 1 rows. Modifiying the view will modify the selected rows of the
+ * original imagelist.
+ * The view can be deleted with hdrl_imagelist_delete.
+ * Deleting the original imagelist will invalidate all views, they must not be
+ * used anymore besides being deleted.
+ * The view must not be modified as bad pixel information cannot be propagated
+ * to the original image if it did not have a bad pixel map to begin with.
+ */
+/* ---------------------------------------------------------------------------*/
+const hdrl_imagelist * hdrl_imagelist_const_row_view(
+    const hdrl_imagelist * hl,
+    cpl_size ly,
+    cpl_size uy)
+{
+    cpl_ensure(hl, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(uy >= ly, CPL_ERROR_ILLEGAL_INPUT, NULL);
+    cpl_ensure(ly > 0, CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+    size_t n = hdrl_imagelist_get_size(hl);
+    cpl_ensure(n > 0, CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+    cpl_ensure(uy <= hdrl_imagelist_get_size_y(hl),
+               CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+
+    hdrl_imagelist * viewlist = hdrl_imagelist_new();
+    for (size_t i = 0; i < n; i++) {
+        hdrl_image * img = hdrl_imagelist_get(hl, i);
+        const hdrl_image * view = hdrl_image_const_row_view_create(img, ly, uy,
+                                       (hdrl_free*)&hdrl_image_view_delete);
+        if (view == NULL) {
+            hdrl_imagelist_delete(viewlist);
+            return NULL;
+        }
+        hdrl_imagelist_set(viewlist, (hdrl_image*)view, i);
+    }
+
+    return viewlist;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create view of subset of images in an imagelist
+ *
+ * @param hl source imagelist to create view of
+ * @param lz lower image index to view, starting from 0
+ * @param uz upper bound exclusive
+ *
+ * @return imagelist view
+ *
+ * The imagelist will contain uz - lz images of the same size as the original
+ * imagelist. Modifiying the view is not allowed
+ * The view must be deleted with hdrl_imagelist_delete.
+ * Deleting the original imagelist will invalidate all views, they must not be
+ * used anymore besides being deleted.
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_imagelist * hdrl_imagelist_image_view(
+    hdrl_imagelist * hl,
+    cpl_size lz,
+    cpl_size uz)
+{
+    cpl_ensure(hl, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(uz > lz, CPL_ERROR_ILLEGAL_INPUT, NULL);
+    size_t n = hdrl_imagelist_get_size(hl);
+    cpl_ensure(lz >= 0, CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+    cpl_ensure(uz <= (cpl_size)n, CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+
+    hdrl_imagelist * viewlist = hdrl_imagelist_new();
+    for (size_t i = lz; i < (size_t)uz; i++) {
+        hdrl_image * img = hdrl_imagelist_get(hl, i);
+        size_t ny = hdrl_image_get_size_y(img);
+        hdrl_image * view = hdrl_image_row_view_create(img, 1, ny);
+        if (view == NULL) {
+            hdrl_imagelist_delete(viewlist);
+            return NULL;
+        }
+        hdrl_imagelist_set(viewlist, view, i - lz);
+    }
+
+    return viewlist;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create const view of subset of image rows in cpl imagelists
+ *
+ * @param imglist source imagelist to create view of
+ * @param errlist source error imagelist to create view of, may be NULL
+ * @param ly lower y row to view (FITS convention)
+ * @param uy upper y row to view (FITS convention)
+ *
+ * @return constant imagelist view
+ *
+ * The imagelist will contain the same number of images but they will have
+ * uy - ly + 1 rows. Modifiying the view is not allowed
+ * The view can be deleted with hdrl_imagelist_delete.
+ * Deleting the original imagelist will invalidate all views, they must not be
+ * used anymore besides being deleted.
+ * The images and errors in the lists must contain equal bad pixel maps.
+ */
+/* ---------------------------------------------------------------------------*/
+const hdrl_imagelist * hdrl_imagelist_const_cpl_row_view(
+    const cpl_imagelist * imglist,
+    const cpl_imagelist * errlist,
+    cpl_size ly,
+    cpl_size uy)
+{
+    cpl_ensure(imglist, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(uy >= ly, CPL_ERROR_ILLEGAL_INPUT, NULL);
+    cpl_ensure(ly > 0, CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+    size_t n = cpl_imagelist_get_size(imglist);
+    cpl_ensure(n > 0, CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+    cpl_ensure(uy <= cpl_image_get_size_y(cpl_imagelist_get_const(imglist, 0)),
+               CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+    cpl_ensure(errlist == NULL || n <= (size_t)cpl_imagelist_get_size(errlist),
+               CPL_ERROR_INCOMPATIBLE_INPUT, NULL);
+
+    hdrl_imagelist * viewlist = hdrl_imagelist_new();
+    if (errlist) {
+        const cpl_image * img = cpl_imagelist_get_const(imglist, 0);
+        const cpl_image * err = cpl_imagelist_get_const(errlist, 0);
+
+        if (cpl_image_get_type(img) != HDRL_TYPE_DATA ||
+            cpl_image_get_type(err) != HDRL_TYPE_ERROR) {
+            hdrl_imagelist_delete(viewlist);
+            cpl_error_set_message(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT,
+                                  "Can only view image pairs with type "
+                                  "HDRL_TYPE_DATA and HDRL_TYPE_ERROR");
+            return NULL;
+        }
+        if (cpl_image_get_size_x(img) != cpl_image_get_size_x(err) ||
+            cpl_image_get_size_y(img) != cpl_image_get_size_y(err)) {
+            hdrl_imagelist_delete(viewlist);
+            cpl_error_set_message(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT,
+                                  "Image and Error not consistent");
+            return NULL;
+        }
+        for (size_t i = 0; i < n; i++) {
+            img = cpl_imagelist_get_const(imglist, i);
+            err = cpl_imagelist_get_const(errlist, i);
+            if ((cpl_image_get_bpm_const(img) && !cpl_image_get_bpm_const(err)) ||
+                (!cpl_image_get_bpm_const(img) && cpl_image_get_bpm_const(err))) {
+                    hdrl_imagelist_delete(viewlist);
+                    cpl_error_set_message(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT,
+                                          "Image and error bad pixel mask "
+                                          "not equal");
+                    return NULL;
+            }
+            if (cpl_image_get_bpm_const(img) && cpl_image_get_bpm_const(err)) {
+                const cpl_binary * dibpm =
+                    cpl_mask_get_data_const(cpl_image_get_bpm_const(img));
+                const cpl_binary * debpm =
+                    cpl_mask_get_data_const(cpl_image_get_bpm_const(err));
+                if (memcmp(dibpm, debpm, hdrl_get_image_npix(img)) != 0) {
+                    hdrl_imagelist_delete(viewlist);
+                    cpl_error_set_message(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT,
+                                          "Image and error bad pixel mask "
+                                          "not equal");
+                    return NULL;
+                }
+            }
+            /* TODO could wrap directly */
+            hdrl_image * himg = hdrl_image_wrap((cpl_image*)img, (cpl_image*)err,
+                                            (hdrl_free*)&hdrl_image_view_delete,
+                                            CPL_FALSE);
+            const hdrl_image * view =
+                hdrl_image_const_row_view_create(himg, ly, uy,
+                                         (hdrl_free*)&hdrl_image_view_delete);
+            if (view == NULL) {
+                hdrl_imagelist_delete(viewlist);
+                return NULL;
+            }
+            hdrl_image_unwrap(himg);
+            hdrl_imagelist_set(viewlist, (hdrl_image*)view, i);
+        }
+    }
+    else {
+        const cpl_image * img = cpl_imagelist_get_const(imglist, 0);
+        if (cpl_image_get_type(img) != HDRL_TYPE_DATA) {
+            hdrl_imagelist_delete(viewlist);
+            cpl_error_set_message(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT,
+                                  "Can only view images with type "
+                                  "HDRL_TYPE_DATA");
+            return NULL;
+        }
+         for (size_t i = 0; i < n; i++) {
+            img = cpl_imagelist_get_const(imglist, i);
+            /* can't share a single image as it needs the same bpm as img
+             * TODO the bpm of img could probably be shared */
+            cpl_image * err = cpl_image_new(cpl_image_get_size_x(img),
+                                            cpl_image_get_size_y(img),
+                                            HDRL_TYPE_ERROR);
+            if (cpl_image_get_bpm_const(img)) {
+                cpl_image_reject_from_mask(err, cpl_image_get_bpm_const(img));
+            }
+            /* TODO could wrap directly */
+            hdrl_image * himg = hdrl_image_wrap((cpl_image*)img, err,
+                                            (hdrl_free*)&hdrl_image_imgview_delete,
+                                            CPL_FALSE);
+            const hdrl_image * view = hdrl_image_const_row_view_create(himg, ly, uy,
+                                           (hdrl_free*)&hdrl_image_imgview_delete);
+            if (view == NULL) {
+                hdrl_imagelist_delete(viewlist);
+                return NULL;
+            }
+            hdrl_image_unwrap(himg);
+            cpl_mask_unwrap(cpl_image_unset_bpm(err));
+            cpl_image_unwrap(err);
+            hdrl_imagelist_set(viewlist, (hdrl_image*)view, i);
+         }
+    }
+
+    return viewlist;
+}
+
+/**@}*/
diff --git a/hdrl/hdrl_imagelist_view.h b/hdrl/hdrl_imagelist_view.h
new file mode 100644
index 0000000..1e4fcbf
--- /dev/null
+++ b/hdrl/hdrl_imagelist_view.h
@@ -0,0 +1,61 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_IMAGELIST_VIEW_H
+#define HDRL_IMAGELIST_VIEW_H
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_imagelist.h"
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                            Function prototypes
+ -----------------------------------------------------------------------------*/
+#if defined HDRL_USE_EXPERIMENTAL || defined HDRL_USE_PRIVATE
+
+hdrl_imagelist * hdrl_imagelist_row_view(
+    hdrl_imagelist * hlist,
+    cpl_size lly,
+    cpl_size ury);
+
+const hdrl_imagelist * hdrl_imagelist_const_row_view(
+    const hdrl_imagelist * hl,
+    cpl_size ly,
+    cpl_size uy);
+
+hdrl_imagelist * hdrl_imagelist_image_view(
+    hdrl_imagelist * hl,
+    cpl_size lz,
+    cpl_size uz);
+
+const hdrl_imagelist * hdrl_imagelist_const_cpl_row_view(
+    const cpl_imagelist * imglist,
+    const cpl_imagelist * errlist,
+    cpl_size ly,
+    cpl_size uy);
+
+#endif
+
+CPL_END_DECLS
+
+#endif 
diff --git a/hdrl/hdrl_iter.c b/hdrl/hdrl_iter.c
new file mode 100644
index 0000000..56de10b
--- /dev/null
+++ b/hdrl/hdrl_iter.c
@@ -0,0 +1,219 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+-----------------------------------------------------------------------------*/
+
+#include "hdrl_iter.h"
+#include "hdrl_types.h"
+#include <cpl.h>
+
+/*-----------------------------------------------------------------------------
+                                   Static
+ -----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_iter   Iterator
+
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+/** @cond EXPERIMENTAL */
+
+/** @cond PRIVATE */
+
+struct _hdrl_iter_ {
+    /* returns next value in sequence iterated on (e.g. image, imagelist) */
+    hdrl_iter_next_f * next;
+    /* optional, resets the iteration to the first element */
+    hdrl_iter_reset_f * reset;
+    /* optional, returns length of the iterator */
+    hdrl_iter_length_f * length;
+    /* state destructor */
+    hdrl_free * destructor;
+    /* iterator type */
+    hdrl_iter_type_t type;
+    /* state structure of iterator */
+    void * state;
+};
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief initialize an iterator
+ *
+ * @param next   function pointer returning next value in sequence iterated on
+ * @param reset  function pointer or NULL, reseting iteration to first element
+ * @param length function pointer or NULL, returning length of sequence
+ * @param type   type of iterator
+ * @param state  state structure of iterator
+ *
+ * An iterator iterates on a sequence of data (e.g. imagelist, files on
+ * disk, ...) and returns an element of that sequence on each call to the
+ * next function. When the sequence is exhausted it returns NULL.
+ *
+ * Each member function is called with the iterator as first argument, from
+ * this the state can be received with hdrl_iter_state(it), the state is a
+ * user defined structure typically containing the current position in the
+ * sequence.
+ *
+ * The iterator type defines what kind of data is returned by each next call.
+ * The options are:
+ * HDRL_ITER_INPUT: data provided is input data to be processed, it will be
+                   freed by the caller of next. (FIXME: add flag to not free?)
+ * HDRL_ITER_OUTPUT: data is an empty output buffer for the caller of next
+ *                  to place its results into. Its memory is managed by the
+ *                  iterator.
+ * HDRL_ITER_IMAGE: the return of next is a cpl_image
+ * HDRL_ITER_IMAGELIST: the return of next is a cpl_imagelist
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_iter *
+hdrl_iter_init(hdrl_iter_next_f * next,
+                  hdrl_iter_reset_f * reset,
+                  hdrl_iter_length_f * length,
+                  hdrl_free * destructor,
+                  hdrl_iter_type_t type,
+                  void * state)
+{
+    /* exactly one each set */
+    hdrl_iter_type_t inout = (HDRL_ITER_INPUT | HDRL_ITER_OUTPUT);
+    hdrl_iter_type_t rettype = (HDRL_ITER_IMAGE | HDRL_ITER_IMAGELIST);
+    cpl_ensure(((type & inout) == HDRL_ITER_INPUT) ||
+               ((type & inout) == HDRL_ITER_OUTPUT),
+               CPL_ERROR_ILLEGAL_INPUT, NULL);
+    cpl_ensure(((type & rettype) == HDRL_ITER_IMAGE) ||
+               ((type & rettype) == HDRL_ITER_IMAGELIST),
+               CPL_ERROR_ILLEGAL_INPUT, NULL);
+    cpl_ensure(state, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(next, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(type != 0, CPL_ERROR_NULL_INPUT, NULL);
+    hdrl_iter * it = cpl_malloc(sizeof(*it));
+    it->next = next;
+    it->length = length;
+    it->reset = reset;
+    it->destructor = destructor ? destructor : &cpl_free;
+    it->type = type;
+    it->state = state;
+    return it;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief return the state structure of the iterator
+ * @param it iterator
+ * @return state structure
+ */
+/* ---------------------------------------------------------------------------*/
+void * hdrl_iter_state(hdrl_iter * it)
+{
+    return it->state;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief check if iterator has a certain flag
+ * @param it iterator
+ * @param type flag to check
+ * @return true or false depending wheter iterator has flags set
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_boolean hdrl_iter_check(hdrl_iter * it, hdrl_iter_type_t type)
+{
+    return (it->type & type) == type;
+}
+
+/** @endcond */
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief delete iterator structure
+ * @param it iterator
+ * @note will not delete the state structure, typically this is called in the
+ *       user iterator destructor
+ */
+/* ---------------------------------------------------------------------------*/
+void hdrl_iter_delete(hdrl_iter * it)
+{
+    if (it) {
+        if (it->destructor) {
+            it->destructor(it->state);
+        }
+        cpl_free(it);
+    }
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief return next element in sequence or NULL if done
+ * @param it iterator
+ * @return object or NULL, type of object depends on iterator type
+ */
+/* ---------------------------------------------------------------------------*/
+void * hdrl_iter_next(hdrl_iter * it)
+{
+    return it->next(it);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief reset iterator to beginning of sequence
+ * @param it iterator
+ */
+/* ---------------------------------------------------------------------------*/
+void hdrl_iter_reset(hdrl_iter * it)
+{
+    if (it->reset == NULL) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_UNSUPPORTED_MODE,
+                              "Iterator has no reset method");
+        return;
+    }
+    return it->reset(it);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief return length of sequence
+ * @param it iterator
+ * @return length of sequence
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_size hdrl_iter_length(hdrl_iter * it)
+{
+    if (it->length == NULL) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_UNSUPPORTED_MODE,
+                              "Iterator has no length method");
+        return -1;
+    }
+    return it->length(it);
+}
+
+/**@}*/
+
+/** @endcond */
diff --git a/hdrl/hdrl_iter.h b/hdrl/hdrl_iter.h
new file mode 100644
index 0000000..ceb0a1c
--- /dev/null
+++ b/hdrl/hdrl_iter.h
@@ -0,0 +1,98 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_ITER_H
+#define HDRL_ITER_H
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_types.h"
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                                Define
+ -----------------------------------------------------------------------------*/
+
+/*-----------------------------------------------------------------------------
+                            Functions prototypes
+ -----------------------------------------------------------------------------*/
+
+/*-----------------------------------------------------------------------------
+  Experimental declarations - can be used, but no guarantees on api stability
+ -----------------------------------------------------------------------------*/
+#if defined HDRL_USE_EXPERIMENTAL || defined HDRL_USE_PRIVATE
+/** @cond EXPERIMENTAL */
+
+typedef struct _hdrl_iter_ hdrl_iter;
+typedef enum {
+    /* next returns a imagelist */
+    HDRL_ITER_IMAGELIST = 1<<0,
+    /* next returns a image */
+    HDRL_ITER_IMAGE = 1<<1,
+    /* next returns an initialized input buffer */
+    HDRL_ITER_INPUT = 1<<2,
+    /* next returns an uninitialized output buffer */
+    HDRL_ITER_OUTPUT = 1<<3,
+    /* iterator owns its next output and will deallocate it */
+    HDRL_ITER_OWN_OUTPUT = 1<<4,
+    /* iterating over const data, views make have NULL bpms */
+    HDRL_ITER_CONST = 1<<5,
+} hdrl_iter_type_t;
+
+void * hdrl_iter_next(hdrl_iter * it);
+cpl_size hdrl_iter_length(hdrl_iter * it);
+void hdrl_iter_reset(hdrl_iter * it);
+void hdrl_iter_delete(hdrl_iter * it);
+
+/** @endcond */
+#endif
+
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+------------------------------------------------------------------------------*/
+
+#ifdef HDRL_USE_PRIVATE
+/** @cond PRIVATE */
+
+typedef void * (hdrl_iter_next_f)(hdrl_iter * it);
+typedef void (hdrl_iter_reset_f)(hdrl_iter * it);
+typedef cpl_size (hdrl_iter_length_f)(hdrl_iter * it);
+
+hdrl_iter *
+hdrl_iter_init(hdrl_iter_next_f * next,
+                  hdrl_iter_reset_f * reset,
+                  hdrl_iter_length_f * length,
+                  hdrl_free * destructor,
+                  hdrl_iter_type_t type,
+                  void * state);
+
+void * hdrl_iter_state(hdrl_iter * it);
+
+cpl_boolean hdrl_iter_check(hdrl_iter * it, hdrl_iter_type_t type);
+
+/** @endcond */
+#endif
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_lacosmics.c b/hdrl/hdrl_lacosmics.c
new file mode 100644
index 0000000..71a2285
--- /dev/null
+++ b/hdrl/hdrl_lacosmics.c
@@ -0,0 +1,727 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013,2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * Originated from xshoop/xsh/xsh_remove_crh_single.c r154351
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/* This should be defined in a more clever way, a parameter for example */
+#define REGDEBUG_FULL 0
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_lacosmics.h"
+#include "hdrl_utils.h"
+
+#include <math.h>
+#include <string.h>
+#include <stdint.h>
+
+/*-----------------------------------------------------------------------------
+                                Define
+ -----------------------------------------------------------------------------*/
+
+/*-----------------------------------------------------------------------------
+                                   Static
+ -----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_lacosmic   Bad Pixel Mask via edge detection
+  @ingroup hdrl_bpm
+
+  @brief
+   Algorithm to detect bad-pixels and cosmic-rays hits on a single image like
+   e.g. science frames
+
+This routine determines bad-pixels on a single image via edge detection
+following the algorithm (LA-Cosmic) describe in van Dokkum,
+PASP,113,2001,p1420-27. The HDRL implementation does not use use error model
+as described in the paper but the error image passed to the function. Moreover
+we do several iterations and replace the detected bad pixels in each iteration
+by the information of the surrounding pixels.
+
+The calculation is performed by calling the top-level function
+hdrl_lacosmic_edgedetect() and the parameters passed to this function can be
+created by calling hdrl_lacosmic_parameter_create().
+
+
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+/*-----------------------------------------------------------------------------
+                        LaCosmic parameters Definition
+ -----------------------------------------------------------------------------*/
+typedef struct {
+    HDRL_PARAMETER_HEAD;
+    double              sigma_lim ;
+    double              f_lim ;
+    int                 max_iter ;
+} hdrl_lacosmic_parameter;
+
+/* parameter type */
+static hdrl_parameter_typeobj hdrl_lacosmic_parameter_type = {
+    HDRL_PARAMETER_LACOSMIC,                /* type */
+    (hdrl_alloc *)&cpl_malloc,              /* fp_alloc */
+    (hdrl_free *)&cpl_free,                 /* fp_free */
+    NULL,                                   /* fp_destroy */
+    sizeof(hdrl_lacosmic_parameter),             /* obj_size */
+};
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief   Creates LaCosmic parameters object
+  @param   sigma_lim  Limiting sigma for detection on the sampling image
+  @param   f_lim      Limiting f factor for detection on the modified Laplacian
+                      image.
+  @param    max_iter  Maximum number of iterations
+  @return   The LaCosmic parameters object. It needs to be deallocated with
+            hdrl_parameter_delete()
+  @see      hdrl_lacosmic_edgedetect()
+
+  @note For the algorithm see the paper of
+  <a href="http://arxiv.org/abs/astro-ph/0108003"> van Dokkum,
+  PASP,113,2001,p1420-27</a>.
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_lacosmic_parameter_create(
+        double              sigma_lim,
+        double              f_lim,
+        int                 max_iter)
+{
+    hdrl_lacosmic_parameter * p = (hdrl_lacosmic_parameter *)
+               hdrl_parameter_new(&hdrl_lacosmic_parameter_type);
+    p->sigma_lim = sigma_lim ;
+    p->f_lim = f_lim ;
+    p->max_iter = max_iter ;
+    return (hdrl_parameter *)p;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Verify basic correctness of the LaCosmic parameters
+  @param    param       LaCosmic parameters
+  @return   CPL_ERROR_NONE if everything is ok, an error code otherwise
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_lacosmic_parameter_verify(
+                const hdrl_parameter    *   param)
+{
+    const hdrl_lacosmic_parameter * param_loc = (hdrl_lacosmic_parameter *)param;
+
+    cpl_error_ensure(param != NULL, CPL_ERROR_NULL_INPUT,
+                     return CPL_ERROR_NULL_INPUT, "NULL Input Parameters");
+    cpl_error_ensure(hdrl_lacosmic_parameter_check(param),
+                     CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                                     "Expected LaCosmic parameter") ;
+
+    cpl_error_ensure(param_loc->max_iter > 0, CPL_ERROR_ILLEGAL_INPUT,
+                    return CPL_ERROR_ILLEGAL_INPUT, "max_iter must be >0");
+    cpl_error_ensure(param_loc->f_lim >= 0, CPL_ERROR_ILLEGAL_INPUT,
+                    return CPL_ERROR_ILLEGAL_INPUT, "f_lim must be >=0");
+    cpl_error_ensure(param_loc->sigma_lim >= 0, CPL_ERROR_ILLEGAL_INPUT,
+                    return CPL_ERROR_ILLEGAL_INPUT, "sigma_lim must be >=0");
+
+    return CPL_ERROR_NONE ;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Check that the parameter is an LaCosmic parameter
+  @param    self The parameter to check
+  @return   True or False
+ */
+/*----------------------------------------------------------------------------*/
+cpl_boolean hdrl_lacosmic_parameter_check(const hdrl_parameter * self)
+{
+    return hdrl_parameter_check_type(self, &hdrl_lacosmic_parameter_type);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the sigma_lim in the LaCosmic parameter
+  @param    p   The LaCosmic parameter
+  @return   The sigma_lim value
+ */
+/*----------------------------------------------------------------------------*/
+double hdrl_lacosmic_parameter_get_sigma_lim(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0);
+    return ((hdrl_lacosmic_parameter *)p)->sigma_lim;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the f_lim in the LaCosmic parameter
+  @param    p   The LaCosmic parameter
+  @return   The f_lim value
+ */
+/*----------------------------------------------------------------------------*/
+double hdrl_lacosmic_parameter_get_f_lim(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0);
+    return ((hdrl_lacosmic_parameter *)p)->f_lim;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the max_iter in the LaCosmic parameter
+  @param    p   The LaCosmic parameter
+  @return   The max_iter value
+ */
+/*----------------------------------------------------------------------------*/
+int hdrl_lacosmic_parameter_get_max_iter(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1);
+    return ((hdrl_lacosmic_parameter *)p)->max_iter;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Create parameter list for the LaCosmic computation
+  @param base_context   base context of parameter (e.g. recipe name)
+  @param prefix         prefix of parameter, may be empty string
+  @param defaults        default values
+
+  @return  parameterlist controlling the LaCosmic algorithm
+
+    base_context.prefix.sigma_lim
+    base_context.prefix.f_lim
+    base_context.prefix.max_iter
+    The CLI aliases omit the base_context.
+ */
+/*----------------------------------------------------------------------------*/
+cpl_parameterlist * hdrl_lacosmic_parameter_create_parlist(
+        const char              *   base_context,
+        const char              *   prefix,
+        const hdrl_parameter    *   defaults)
+{
+    cpl_ensure(prefix && base_context && defaults, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_parameterlist   *   parlist = cpl_parameterlist_new();
+
+    double sigma_lim_def = hdrl_lacosmic_parameter_get_sigma_lim(defaults) ;
+    double f_lim_def = hdrl_lacosmic_parameter_get_f_lim(defaults) ;
+    int max_iter_def = hdrl_lacosmic_parameter_get_max_iter(defaults) ; 
+
+    /* --prefix.sigma_lim */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "sigma_lim", base_context,
+            "Poisson fluctuation threshold to flag cosmics"
+            "(see van Dokkum, PASP,113,2001,p1420-27).",
+            CPL_TYPE_DOUBLE, sigma_lim_def) ;
+
+    /* --prefix.f_lim */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "f_lim", base_context,
+            "Minimum contrast between the Laplacian image and the fine "
+            "structure image that a point must have to be flagged as cosmics"
+            , CPL_TYPE_DOUBLE, f_lim_def) ;
+
+    /* --prefix.max_iter */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "max_iter", base_context,
+            "Maximum number of alghoritm iterations", CPL_TYPE_INT, max_iter_def) ;
+
+    if (cpl_error_get_code()) {
+        cpl_parameterlist_delete(parlist);
+        return NULL;
+    }
+    return parlist;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Parse parameterlist to create input parameters for the LaCosmic
+  @param parlist        parameter list to parse
+  @param prefix         prefix of parameter name
+  @return   Input parameters for the LaCosmic Computation
+
+  Reads a parameterlist in order to create LaCosmic parameters.
+  Expects a parameterlist containing:
+  - prefix.sigma_lim
+  - prefix.f_lim
+  - prefix.max_iter
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_lacosmic_parameter_parse_parlist(
+        const cpl_parameterlist *   parlist,
+        const char              *   prefix)
+{
+    cpl_ensure(prefix && parlist, CPL_ERROR_NULL_INPUT, NULL);
+    char                *   name ;
+    const cpl_parameter *   par = NULL;
+    double                  sigma_lim, f_lim;
+    int                     max_iter;
+
+    /* --sigma_lim */
+    name = hdrl_join_string(".", 2, prefix, "sigma_lim");
+    par=cpl_parameterlist_find_const(parlist, name);
+    sigma_lim = cpl_parameter_get_double(par);
+    cpl_free(name) ;
+
+    /* --f_lim */
+    name = hdrl_join_string(".", 2, prefix, "f_lim");
+    par=cpl_parameterlist_find_const(parlist, name);
+    f_lim = cpl_parameter_get_double(par);
+    cpl_free(name) ;
+
+    /* --max_iter */
+    name = hdrl_join_string(".", 2, prefix, "max_iter");
+    par=cpl_parameterlist_find_const(parlist, name);
+    max_iter = cpl_parameter_get_int(par);
+    cpl_free(name) ;
+
+    if (cpl_error_get_code()) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                "Error while parsing parameterlist with prefix %s", prefix);
+        return NULL;
+    } else {
+        return hdrl_lacosmic_parameter_create(sigma_lim, f_lim, max_iter) ;
+    }
+}
+
+
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Detect bad-pixels  / cosmic-rays on a single image.
+  @param ima_in    The input image
+  @param params    LaCosmic computation parameters
+
+  @return Mask where all detected bad-pixels/cosmics-rays are marked
+          as bad or NULL on error
+
+This routine determines bad-pixels on a single image via edge
+detection following the algorithm (LA-Cosmic) describe in van Dokkum,
+PASP,113,2001,p1420-27. It was originally developed to detect cosmic
+ray hits but can also be used in the more general context of detecting
+bad pixels.  The HDRL implementation does not use use error model as
+described in the paper but the error image passed to the
+function. Moreover we do several iterations with \e max_iter defining
+an upper limit for the number of iterations, i.e. the iteration stops
+if no new bad pixels are found or \e max_iter is reached. In each
+iteration we replace the detected cosmic ray hits by the median of the
+surroundings 5x5 pixels taking into account the pixel quality
+information. The input parameter \e sigma_lim and \e f_lim refer to
+\f$\sigma_{lim}\f$ and \f$f_{lim}\f$ as described in the paper
+mentioned above. The hdrl parameter passed to this routine is created
+by hdrl_lacosmic_parameter_create().
+
+ at note Be aware that the implementation only detects positive bad
+pixels / cosmic ray hits, i.e. no "holes" in the image are detected,
+but in such a case the pixels surrounding the whole are marked as
+bad. Holes in the image can be introduced, if e.g. one subtracts a not
+cosmic-ray-cleaned image from another image.
+
+*/
+/*----------------------------------------------------------------------------*/
+cpl_mask * hdrl_lacosmic_edgedetect(
+        const hdrl_image        *   ima_in,
+        const hdrl_parameter    *   params)
+{
+    cpl_image * sci_data = NULL;
+    cpl_image * sci_error = NULL;
+    cpl_mask  * sci_mask = NULL;
+    cpl_image * laplacian_data = NULL;
+    cpl_image * laplacian_redu_data = NULL; /* re-binned Laplacian */
+    cpl_image * subs2_data = NULL; /* Sub-sampled image by a factor of 2 */
+    cpl_image * s_median_data = NULL;
+    cpl_image * s_data = NULL;
+    cpl_image * f_data = NULL;
+    cpl_image * r_data = NULL;
+
+    cpl_image * sci_median3_data = NULL;
+    cpl_image * sci_median3_7_data = NULL;
+
+    intptr_t subs2_nx = 0;
+    intptr_t subs2_ny = 0;
+
+    cpl_binary * psci_mask = NULL;
+    cpl_binary * pout_mask = NULL;
+
+    cpl_matrix * laplacian_kernel = NULL;
+
+    cpl_mask * median3_kernel = NULL;
+    cpl_mask * median5_kernel = NULL;
+    cpl_mask * median7_kernel = NULL;
+    cpl_mask * lastiter_mask = NULL;
+    cpl_mask * out_mask = NULL;
+
+    double * psci_data = NULL;
+    double * psci_error = NULL;
+    double * psubs2_data = NULL;
+    double * plaplacian_data = NULL;
+    double * plaplacian_redu_data = NULL;
+    double * psci_median3_data = NULL;
+    double * ps_data = NULL;
+    double * pf_data = NULL;
+    double * pr_data = NULL;
+
+    int nbiter = 1;
+
+    intptr_t nx = 0;
+    intptr_t ny = 0;
+
+    /* Check Entries */
+    cpl_ensure(ima_in, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(hdrl_lacosmic_parameter_verify(params) == CPL_ERROR_NONE,
+            CPL_ERROR_ILLEGAL_INPUT, NULL) ;
+
+    cpl_ensure(hdrl_image_get_size_x(ima_in) >= 7,
+               CPL_ERROR_INCOMPATIBLE_INPUT, NULL);
+    cpl_ensure(hdrl_image_get_size_y(ima_in) >= 7,
+               CPL_ERROR_INCOMPATIBLE_INPUT, NULL);
+
+    /* Local Usage parameters */
+    const hdrl_lacosmic_parameter * p_loc = (hdrl_lacosmic_parameter *)params ;
+
+    sci_data = cpl_image_cast(hdrl_image_get_image_const(ima_in),
+            CPL_TYPE_DOUBLE);
+    if (hdrl_image_get_mask_const(ima_in)) {
+        sci_mask = cpl_mask_duplicate(hdrl_image_get_mask_const(ima_in));
+    } else {
+        sci_mask = cpl_mask_new(cpl_image_get_size_x(sci_data),
+                cpl_image_get_size_y(sci_data));
+    }
+    sci_error = cpl_image_cast(hdrl_image_get_error_const(ima_in),
+            CPL_TYPE_DOUBLE);
+
+    /* Laplacian */
+    laplacian_kernel = cpl_matrix_new(3, 3);
+    cpl_matrix_set(laplacian_kernel, 0, 0, 0.0);
+    cpl_matrix_set(laplacian_kernel, 0, 1, -1.0);
+    cpl_matrix_set(laplacian_kernel, 0, 2, 0.0);
+    cpl_matrix_set(laplacian_kernel, 1, 0, -1.0);
+    cpl_matrix_set(laplacian_kernel, 1, 1, 4.0);
+    cpl_matrix_set(laplacian_kernel, 1, 2, -1.0);
+    cpl_matrix_set(laplacian_kernel, 2, 0, 0.0);
+    cpl_matrix_set(laplacian_kernel, 2, 1, -1.0);
+    cpl_matrix_set(laplacian_kernel, 2, 2, 0.0);
+
+    /* Median 3x3*/
+    median3_kernel = cpl_mask_new(3, 3);
+    cpl_mask_not(median3_kernel); /* All values set to unity */
+
+    /* Median 5x5 */
+    median5_kernel = cpl_mask_new(5, 5);
+    cpl_mask_not(median5_kernel); /* All values set to unity */
+
+    /* Median 7x7 */
+    median7_kernel = cpl_mask_new(7, 7);
+    cpl_mask_not(median7_kernel); /* All values set to unity */
+
+    out_mask = cpl_mask_new(cpl_mask_get_size_x(sci_mask),
+                    cpl_mask_get_size_y(sci_mask));
+
+    nx = cpl_image_get_size_x(sci_data);
+    ny = cpl_image_get_size_y(sci_data);
+
+    /* Preparing different kernels */
+    psci_data = cpl_image_get_data_double(sci_data);
+    psci_error = cpl_image_get_data_double(sci_error);
+
+    psci_mask = cpl_mask_get_data(sci_mask);
+    pout_mask = cpl_mask_get_data(out_mask);
+
+    subs2_nx = nx * 2;
+    subs2_ny = ny * 2;
+
+    subs2_data = cpl_image_new(subs2_nx, subs2_ny, CPL_TYPE_DOUBLE);
+    psubs2_data = cpl_image_get_data_double( subs2_data);
+
+    laplacian_redu_data = cpl_image_new(nx, ny, CPL_TYPE_DOUBLE);
+    plaplacian_redu_data = cpl_image_get_data_double( laplacian_redu_data);
+
+    s_data = cpl_image_new(nx, ny, CPL_TYPE_DOUBLE);
+    ps_data = cpl_image_get_data_double( s_data);
+
+    f_data = cpl_image_new(nx, ny, CPL_TYPE_DOUBLE);
+    pf_data = cpl_image_get_data_double( f_data);
+
+    r_data = cpl_image_new(nx, ny, CPL_TYPE_DOUBLE);
+    pr_data = cpl_image_get_data_double( r_data);
+
+    /* mask needed to stop the loop if the pixel-replacements is not propperly
+     * working */
+    lastiter_mask = cpl_mask_duplicate(out_mask);
+
+    /* The actual cosmic ray search is done here.
+     * stop if no new cosmic are found or max iter is reached */
+    while (nbiter <= p_loc->max_iter) {
+        cpl_vector * median;
+        double * psci_median3_7_data;
+        double * ps_median_data;
+
+        /* Stopping if the detections of the previus run are identical to
+         *  the last run */
+        if (nbiter > 1 && !hdrl_check_maskequality(lastiter_mask, out_mask)) {
+            cpl_msg_debug(cpl_func, "Detections of iteration %d and %d are "
+                            "identical - stopping here", nbiter-1, nbiter );
+            break;
+        }
+        cpl_mask_delete(lastiter_mask);
+        lastiter_mask = cpl_mask_duplicate(out_mask);
+
+        /* Super sample data:
+           Create a 2n x 2n images like this
+         | 1 | 2 |  =>  | 1 | 1 | 2 | 2 |
+         | 3 | 4 |      | 1 | 1 | 2 | 2 |
+                        | 3 | 3 | 4 | 4 |
+                        | 3 | 3 | 4 | 4 | */
+
+        for (intptr_t j = 0; j < ny; j++) {
+            intptr_t j_2_subs2_nx = j * 2 * subs2_nx;
+            intptr_t j_nx = j * nx;
+            for (intptr_t i = 0; i < nx; i++) {
+                double val = psci_data[i + j_nx];
+                intptr_t pix = i * 2 + j_2_subs2_nx;
+                psubs2_data[pix] = val;
+                psubs2_data[pix + subs2_nx] = val;
+                pix++;
+                psubs2_data[pix] = val;
+                psubs2_data[pix + subs2_nx] = val;
+            }
+        }
+
+        /* Doing the Laplacian convolution and set negative pixels to
+           0 in the Laplacian image
+          0  -1   0
+         -1   4  -1
+          0  -1   0 */
+
+        laplacian_data = hdrl_parallel_filter_image(subs2_data,
+                                                    laplacian_kernel, NULL,
+                                                    CPL_FILTER_LINEAR);
+
+        plaplacian_data = cpl_image_get_data_double(laplacian_data);
+        for (intptr_t i = 0; i < subs2_nx * subs2_ny; i++) {
+            if (plaplacian_data[i] < 0.0) {
+                plaplacian_data[i] = 0.0;
+            } else {
+                /*TODO Where does this factor of 8 come from???*/
+                plaplacian_data[i] *= 8.0;
+            }
+        }
+
+        /* fix discontinuity at edges due to incomplete laplace kernel by
+         * mirroring the neighbouring pixel */
+        for (intptr_t i = 0; i < subs2_ny; i++) {
+            plaplacian_data[i * subs2_nx + 0] = plaplacian_data[i * subs2_nx + 1];
+            plaplacian_data[i * subs2_nx + subs2_nx - 1] =
+                plaplacian_data[i * subs2_nx +  + subs2_nx - 2];
+        }
+        for (intptr_t j = 0; j < subs2_nx; j++) {
+            plaplacian_data[0 * subs2_nx + j] = plaplacian_data[1 * subs2_nx + j];
+            plaplacian_data[(subs2_ny - 1) * subs2_nx + j] =
+                plaplacian_data[(subs2_ny - 2) * subs2_nx + j];
+        }
+
+#if REGDEBUG_FULL
+        cpl_image_save(laplacian_data, "Lpositive.fits", CPL_BPP_IEEE_DOUBLE, 
+                NULL, CPL_IO_DEFAULT);
+#endif
+
+        /* resample to the original size
+         | 1 | 1 | 2 | 2 |    | 1 | 2 |
+         | 1 | 1 | 2 | 2 |    | 3 | 4 |
+         | 3 | 3 | 4 | 4 | =>
+         | 3 | 3 | 4 | 4 |               */
+
+HDRL_OMP(omp parallel for)
+        for (intptr_t j = 0; j < ny; j++) {
+            intptr_t j_2_subs2_nx = j * 2 * subs2_nx;
+            intptr_t j_nx = j * nx;
+            for (intptr_t i = 0; i < nx; i++) {
+                intptr_t pix = i * 2 + j_2_subs2_nx;
+                plaplacian_redu_data[i + j_nx] =
+                    (plaplacian_data[pix] +
+                     plaplacian_data[pix + 1] +
+                     plaplacian_data[pix + subs2_nx] +
+                     plaplacian_data[pix + subs2_nx + 1]) * 0.25;
+                /* A) Compute S image */
+                ps_data[i + j_nx] =
+                   0.5 * plaplacian_redu_data[i + j_nx] / psci_error[i + j_nx];
+            }
+        }
+
+#if REGDEBUG_FULL
+        cpl_image_save(laplacian_redu_data, "Lplus.fits", CPL_BPP_IEEE_DOUBLE,
+                       NULL, CPL_IO_DEFAULT);
+#endif
+
+        /* A) compute S median image */
+        s_median_data = hdrl_parallel_filter_image(s_data, NULL,
+                                                   median5_kernel,
+                                                   CPL_FILTER_MEDIAN);
+        ps_median_data = cpl_image_get_data_double( s_median_data);
+
+
+        /* B) Compute s2 -> denoted S' in the original paper */
+        for (intptr_t i = 0; i < nx * ny; i++) {
+            ps_data[i] -= ps_median_data[i];
+        }
+
+#if REGDEBUG_FULL
+        cpl_image_save( s_data, "S2.fits", CPL_BPP_IEEE_DOUBLE, NULL,
+                CPL_IO_DEFAULT);
+#endif
+
+        /* Apply 3x3 median filter on data */
+        sci_median3_data = hdrl_parallel_filter_image(sci_data, NULL,
+                                                      median3_kernel,
+                                                      CPL_FILTER_MEDIAN);
+        psci_median3_data = cpl_image_get_data_double(sci_median3_data);
+
+        /* Apply 7x7 median filter */
+
+        sci_median3_7_data = hdrl_parallel_filter_image(sci_median3_data, NULL,
+                                                        median7_kernel,
+                                                        CPL_FILTER_MEDIAN);
+        psci_median3_7_data = cpl_image_get_data_double(sci_median3_7_data);
+
+        /* C) Compute F, i.e. the fine structure image */
+        for (intptr_t i = 0; i < nx * ny; i++) {
+            pf_data[i] = psci_median3_data[i] - psci_median3_7_data[i];
+            /* TODO: why this setting?
+             * why one use an absolute number?
+             * pf_data may span on different ranges as it depends on the value
+             * of the difference psci_median3_data[i] - psci_median3_7_data[i]
+             */
+            if (pf_data[i] < 0.01) {
+                pf_data[i] = 0.01;
+            }
+        }
+
+#if REGDEBUG_FULL
+        cpl_image_save( f_data, "F.fits", CPL_BPP_IEEE_DOUBLE, NULL,
+                       CPL_IO_DEFAULT);
+#endif
+
+        /* D) Compute R, i.e. the ratio of Laplacian and fine structure image */
+        for (intptr_t i = 0; i < nx * ny; i++) {
+            pr_data[i] = plaplacian_redu_data[i] / pf_data[i];
+        }
+
+#if REGDEBUG_FULL
+        cpl_image_save( r_data, "R.fits", CPL_BPP_IEEE_DOUBLE, NULL,
+                       CPL_IO_DEFAULT);
+#endif
+
+        /* E) Search for cosmics */
+        median = cpl_vector_new(24);
+        for (intptr_t j = 0; j < ny - 1; j++) {
+            intptr_t j_nx = j * nx;
+            for (intptr_t i = 0; i < nx - 1; i++) {
+                intptr_t i_plus_j_nx = i + j_nx;
+                if (ps_data[i_plus_j_nx] > p_loc->sigma_lim &&
+                    pr_data[i_plus_j_nx] > p_loc->f_lim &&
+                    /* check for bad pixels added here */
+                    psci_mask[i_plus_j_nx] == CPL_BINARY_0) {
+                    double *data = NULL;
+                    cpl_vector* med_vect = NULL;
+                    intptr_t li, lj, ui, uj, m;
+                    /* we flag the CRH in the science frame */
+                    pout_mask[i_plus_j_nx] = CPL_BINARY_1;
+                    cpl_msg_debug(cpl_func, "Detection found at x=%zd y=%zd with "
+                                    "value=%g", i+1, j+1, psci_data[i_plus_j_nx]);
+
+                    /* we replace the CRH with median of the surroundings 
+                       pixels in a box 5x5 pixels */
+                    m = 0;
+                    li = CX_MAX(i - 2, 0);
+                    lj = CX_MAX(j - 2, 0);
+                    ui = CX_MIN(nx, i + 3);
+                    uj = CX_MIN(ny, j + 3);
+
+                    for (intptr_t k = lj; k < uj; k++) {
+                        intptr_t k_nx = k * nx;
+                        for (intptr_t l = li; l < ui; l++) {
+                            intptr_t l_plus_k_nx = l + k_nx;
+                            if (ps_data[l_plus_k_nx] <= p_loc->sigma_lim &&
+                                    /* check for bad pixels added here */
+                                    psci_mask[l_plus_k_nx] == CPL_BINARY_0) {
+                                cpl_vector_set(median,m,psci_data[l_plus_k_nx]);
+                                m++;
+                                continue;
+                            }
+                            if (pr_data[l_plus_k_nx] <= p_loc->f_lim &&
+                                    /* check for bad pixels added here */
+                                    psci_mask[l_plus_k_nx] == CPL_BINARY_0) {
+                                cpl_vector_set(median,m,psci_data[l_plus_k_nx]);
+                                m++;
+                            }
+                        }
+                    }
+                    /* if no good pixel has been found skip pixel value
+                       replacement */
+                    if(m == 0) continue;
+                    /* Replace CRH value with median of computed values on
+                       good pixels */
+                    data = cpl_vector_get_data( median);
+                    med_vect = cpl_vector_wrap( m, data);
+                    psci_data[i_plus_j_nx] = cpl_vector_get_median(med_vect);
+                    cpl_msg_debug(cpl_func, "Detection replaced with value=%g",
+                                  psci_data[i_plus_j_nx]);
+                    cpl_vector_unwrap(med_vect);
+                } /* end check on thresholds */
+            } /* end loop over image columns */
+        } /* end loop over image rows */
+
+        cpl_vector_delete(median); median = NULL;
+
+        nbiter++;
+        cpl_image_delete(laplacian_data);
+        cpl_image_delete(sci_median3_7_data);
+        cpl_image_delete(sci_median3_data);
+        cpl_image_delete(s_median_data);
+    }
+
+#if REGDEBUG_FULL
+    cpl_mask_save( *out_mask, "CRH_SINGLE.fits", NULL, CPL_IO_DEFAULT);
+#endif
+
+    /* Free memory */
+    cpl_matrix_delete(laplacian_kernel);
+    cpl_mask_delete(median3_kernel);
+    cpl_mask_delete(median5_kernel);
+    cpl_mask_delete(median7_kernel);
+    cpl_mask_delete(lastiter_mask);
+    cpl_image_delete(laplacian_redu_data);
+    cpl_image_delete(subs2_data);
+    cpl_image_delete(s_data);
+    cpl_image_delete(f_data);
+    cpl_image_delete(r_data);
+    cpl_image_delete(sci_data);
+    cpl_image_delete(sci_error);
+    cpl_mask_delete(sci_mask);
+
+    return out_mask;
+}
+
+/**@}*/
+
diff --git a/hdrl/hdrl_lacosmics.h b/hdrl/hdrl_lacosmics.h
new file mode 100644
index 0000000..40d6348
--- /dev/null
+++ b/hdrl/hdrl_lacosmics.h
@@ -0,0 +1,73 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_LACOSMICS_H_
+#define HDRL_LACOSMICS_H_
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_types.h"
+#include "hdrl_image.h"
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                            Functions prototypes
+ -----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+                            LaCosmic Parameters
+  ----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_lacosmic_parameter_create(double, double, int);
+cpl_error_code hdrl_lacosmic_parameter_verify(const hdrl_parameter *) ;
+cpl_boolean hdrl_lacosmic_parameter_check(const hdrl_parameter *) ;
+
+/* Accessors */
+double hdrl_lacosmic_parameter_get_sigma_lim(const hdrl_parameter *) ;
+double hdrl_lacosmic_parameter_get_f_lim(const hdrl_parameter *) ;
+int hdrl_lacosmic_parameter_get_max_iter(const hdrl_parameter *) ;
+
+/* Parameter Lists */
+cpl_parameterlist * hdrl_lacosmic_parameter_create_parlist(const char *, 
+        const char *, const hdrl_parameter *);
+hdrl_parameter * hdrl_lacosmic_parameter_parse_parlist(
+        const cpl_parameterlist *, const char *) ;
+
+/*----------------------------------------------------------------------------
+                            LaCosmic Computation
+  ----------------------------------------------------------------------------*/
+
+cpl_mask * hdrl_lacosmic_edgedetect(
+        const hdrl_image        *   ima_in,
+        const hdrl_parameter    *   params) ;
+
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+ -----------------------------------------------------------------------------*/
+
+#ifdef HDRL_USE_PRIVATE
+
+#endif
+
+CPL_END_DECLS
+
+#endif /* HDRL_LACOSMICS_H_ */
diff --git a/hdrl/hdrl_overscan.c b/hdrl/hdrl_overscan.c
new file mode 100644
index 0000000..e19252d
--- /dev/null
+++ b/hdrl/hdrl_overscan.c
@@ -0,0 +1,1721 @@
+/* 
+ * This file is part of the HDRL
+ * Copyright (C) 2012,2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_overscan.h"
+#include "hdrl_overscan_defs.h"
+#include "hdrl_sigclip.h"
+#include "hdrl_utils.h"
+#include "hdrl_collapse.h"
+#include <assert.h>
+
+#include <cpl.h>
+#include <math.h>
+#include <string.h>
+
+/*-----------------------------------------------------------------------------
+                                   Static
+ -----------------------------------------------------------------------------*/
+
+static hdrl_overscan_compute_result * hdrl_overscan_compute_result_create(
+        void);
+static cpl_error_code hdrl_overscan_compute_result_verify(
+        const hdrl_overscan_compute_result *);
+static hdrl_overscan_correct_result * hdrl_overscan_correct_result_create(
+        void);
+static cpl_error_code  hdrl_overscan_compute_chi_square(const cpl_image *,
+        const cpl_image *, const double, double *, double *);
+static cpl_error_code hdrl_overscan_reduce_image_to_scalar(
+        hdrl_collapse_imagelist_to_vector_t *, cpl_image *, cpl_image *, 
+        double *, double *, cpl_size *, void **) ;
+static void hdrl_overscan_parameter_destroy(void * param);
+
+/*----------------------------------------------------------------------------*/
+/* INCLUDED FROM doc/Func_Overscan.tex */
+/**
+  @defgroup hdrl_overscan   Overscan Computation and Correction
+ 
+The overscan (or prescan) region on a CCD can consist of physical
+pixels on the detector that are not illuminated, or it can consist of a set
+of virtual pixels created by reading out the serial register either before or
+after transferring the charge from the CCD for each column/row.
+A detector may have multiple regions (amplifiers) and each one usually has
+an associated overscan region.
+
+This module is intended to be applied to a single overscan region.
+
+The key parameter is box_hsize. When box_hsize is zero, then the
+overscan correction is calculated without smoothing over adjacent rows/columns.
+However, this may lead to a noisy overscan correction vector.
+Increasing box_hsize will increase the S/N of the values in the overscan
+correction vector, but will decrease the ability of the overscan correction
+to correct for rapid spatial changes in the bias level.
+A balance must be reached which will likely depend on the detector under
+consideration.
+
+A typical overscan correction may be essentially independent of row/column,
+or it may vary smoothly or with abrupt gradient changes. Hence the
+implementation of a smoothing method as opposed to the fitting of an
+analytical function.
+
+When choosing the overscan region, note that the first few rows/columns
+that are read out after the image area will have an artificially high bias
+level due to the charge transfer efficiency not being 100%. It is
+recommended therefore to not include the 2-3 rows/columns right next
+to the image region in the overscan region.
+
+An interesting phenomenon is that a very bright star/object may increase the
+bias level for the few rows/columns that it covers. Hence it is not advisable
+to set box_hsize to a value that is much larger than the image
+point-spread-function FWHM.
+
+An overscan correction is the correct way to correct for the detector bias
+level. It is preferable to do an overscan correction instead of using
+bias frames to determine a bias level.
+
+This module allows the computation of the overscan correction for an image
+from a predefined overscan region. It also provides a function that applies
+the overscan correction to the image, using the result of the overscan
+computation.
+  
+    \image html overscan_example.png
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+/*-----------------------------------------------------------------------------
+                        Overscan Parameters Definition
+ -----------------------------------------------------------------------------*/
+typedef struct {
+    HDRL_PARAMETER_HEAD;
+    hdrl_direction              correction_direction; 
+    double                      ccd_ron;
+    int                         box_hsize;
+    hdrl_parameter          *   collapse;
+    hdrl_parameter          *   rect_region;
+} hdrl_overscan_parameter;
+
+/* Parameter type */
+static hdrl_parameter_typeobj hdrl_overscan_parameter_type = {
+    HDRL_PARAMETER_OVERSCAN,                        /* type */
+    (hdrl_alloc *)&cpl_malloc,                      /* fp_alloc */
+    (hdrl_free *)&cpl_free,                         /* fp_free */
+    (hdrl_free *)&hdrl_overscan_parameter_destroy,  /* fp_destroy */
+    sizeof(hdrl_overscan_parameter),                /* obj_size */
+};
+
+/* ---------------------------------------------------------------------------*/
+/**
+  @brief    Creates Overscan Parameters object
+  @param    correction_direction    HDRL_X_AXIS or HDRL_Y_AXIS
+  @param    ccd_ron                 The CCD read out noise
+  @param    box_hsize               The running box half size
+  @param    collapse                The collpase method parameters
+  @param    rect_region             The overscan computation region
+  @return   The overscan parameters object. It needs to be deallocated
+            with hdrl_parameter_delete() or _destroy()
+  @see      hdrl_parameter_delete()
+  @see      hdrl_parameter_destroy()
+  @see      hdrl_overscan_compute()
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_overscan_parameter_create(
+        hdrl_direction      correction_direction,
+        double              ccd_ron,
+        int                 box_hsize,
+        hdrl_parameter  *   collapse,
+        hdrl_parameter  *   rect_region)
+{
+    hdrl_overscan_parameter * p = (hdrl_overscan_parameter *)
+               hdrl_parameter_new(&hdrl_overscan_parameter_type);
+    p->correction_direction = correction_direction ;
+    p->ccd_ron = ccd_ron ;
+    p->box_hsize = box_hsize ;
+    p->collapse = collapse ;
+    p->rect_region = rect_region ;
+    return (hdrl_parameter *)p;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Verify basic correctness of the Overscan parameters
+  @param    param   Overscan parameters
+  @param    nx      required X region size, set to < 0 to skip check
+  @param    ny      required Y region size, set to < 0 to skip check
+  @return   CPL_ERROR_NONE if everything is ok, an error code otherwise
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_overscan_parameter_verify(
+        const hdrl_parameter    *   param,
+        cpl_size                    nx,
+        cpl_size                    ny) 
+{
+    const hdrl_overscan_parameter * param_loc = 
+        (hdrl_overscan_parameter *)param ;
+
+    cpl_error_ensure(param != NULL, CPL_ERROR_NULL_INPUT,
+            return CPL_ERROR_NULL_INPUT, "NULL Input Parameters");
+    cpl_error_ensure(hdrl_overscan_parameter_check(param),
+            CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+            "Expected Overscan parameter") ;
+    
+    cpl_error_ensure(param_loc->ccd_ron >= 0, CPL_ERROR_ILLEGAL_INPUT,
+            return CPL_ERROR_ILLEGAL_INPUT,
+            "CCD read out noise (%g) must be >= 0", param_loc->ccd_ron);
+    cpl_error_ensure(param_loc->box_hsize >= 0 ||
+                     param_loc->box_hsize == HDRL_OVERSCAN_FULL_BOX,
+                     CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                     "half box size (%d) must be >= 0 or -1", 
+                     param_loc->box_hsize);
+    cpl_error_ensure(param_loc->correction_direction == HDRL_X_AXIS ||
+                     param_loc->correction_direction == HDRL_Y_AXIS,
+                     CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                     "correction_direction must be HDRL_X_AXIS or HDRL_Y_AXIS");
+    
+    if (hdrl_collapse_parameter_is_sigclip(param_loc->collapse)) {
+        cpl_error_ensure(
+                hdrl_collapse_sigclip_parameter_verify(param_loc->collapse)
+                == CPL_ERROR_NONE, CPL_ERROR_ILLEGAL_INPUT,
+                return CPL_ERROR_ILLEGAL_INPUT,
+                "Illegal Collapse Sigclip parameters");
+    } 
+    if (hdrl_collapse_parameter_is_minmax(param_loc->collapse)) {
+        cpl_error_ensure(
+                hdrl_collapse_minmax_parameter_verify(param_loc->collapse)
+                == CPL_ERROR_NONE, CPL_ERROR_ILLEGAL_INPUT,
+                return CPL_ERROR_ILLEGAL_INPUT,
+                "Illegal Collapse Minmax parameters");
+    } 
+    cpl_error_ensure(
+            hdrl_rect_region_parameter_verify(param_loc->rect_region, -1, -1)
+            == CPL_ERROR_NONE, CPL_ERROR_ILLEGAL_INPUT,
+            return CPL_ERROR_ILLEGAL_INPUT,
+            "Illegal Rect Region parameters");
+
+    cpl_error_ensure(hdrl_collapse_parameter_is_mean(param_loc->collapse) ||
+            hdrl_collapse_parameter_is_weighted_mean(param_loc->collapse) ||
+            hdrl_collapse_parameter_is_median(param_loc->collapse) ||
+            hdrl_collapse_parameter_is_sigclip(param_loc->collapse) ||
+            hdrl_collapse_parameter_is_minmax(param_loc->collapse),
+            CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+            "Only supported methods are MEAN, WEIGHTED_MEAN, MEDIAN, SIGCLIP,"
+            " and MINMAX");
+
+    /* The region must be contained in the image */
+    if (nx > 0) {
+        cpl_size region_llx = hdrl_rect_region_get_llx(param_loc->rect_region);
+        cpl_size region_urx = hdrl_rect_region_get_urx(param_loc->rect_region);
+        cpl_error_ensure(
+                region_llx>=1 && region_urx <= nx,
+                CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT, 
+                "Region (%d) exceeds source (%d) size in the X dir.",
+                (int)region_urx, (int)nx);
+    }
+    if (ny > 0) {
+        cpl_size region_lly = hdrl_rect_region_get_lly(param_loc->rect_region);
+        cpl_size region_ury = hdrl_rect_region_get_ury(param_loc->rect_region);
+        cpl_error_ensure(
+                region_lly>=1 && region_ury <= ny,
+                CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT, 
+                "Region (%d) exceeds source (%d) size in the Y dir.",
+                (int)region_ury, (int)ny);
+    }
+    return CPL_ERROR_NONE;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Check that the parameter is an Overscan parameter
+  @param    self The parameter to check
+  @return   True or False
+ */
+/*----------------------------------------------------------------------------*/
+cpl_boolean hdrl_overscan_parameter_check(const hdrl_parameter * self)
+{
+    return hdrl_parameter_check_type(self, &hdrl_overscan_parameter_type);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the Correction Direction in the Overscan Parameter
+  @param    p The Overscan parameter
+  @return   The correction direction
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_direction hdrl_overscan_parameter_get_correction_direction(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, HDRL_UNDEFINED_AXIS);
+    return ((hdrl_overscan_parameter *)p)->correction_direction;
+}
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the CCD read out noise in the Overscan Parameter
+  @param    p The Overscan parameter
+  @return   The CCD read out noise
+ */
+/*----------------------------------------------------------------------------*/
+double hdrl_overscan_parameter_get_ccd_ron(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0) ;
+    return ((hdrl_overscan_parameter *)p)->ccd_ron ;
+}
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the Box Half Size in the Overscan Parameter
+  @param    p The Overscan parameter
+  @return   The box half size
+ */
+/*----------------------------------------------------------------------------*/
+int hdrl_overscan_parameter_get_box_hsize(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0) ;
+    return ((hdrl_overscan_parameter *)p)->box_hsize ;
+}
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the collapse method parameters in the Overscan Parameter
+  @param    p The Overscan parameter
+  @return   The collapse method parameters
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_overscan_parameter_get_collapse(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, NULL) ;
+    return ((hdrl_overscan_parameter *)p)->collapse;
+}
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the Overscan Region parameters in the Overscan Parameter
+  @param    p The Overscan parameter
+  @return   The Overscan region parameters
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_overscan_parameter_get_rect_region(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, NULL) ;
+    return ((hdrl_overscan_parameter *)p)->rect_region;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+  @brief Create parameter list for the Overscan computation
+  @param base_context    base context of parameter (e.g. recipe name)
+  @param prefix          prefix of parameter, may be empty string
+  @param corr_dir_def    default correction direction value
+  @param box_hsize_def   default box hsize value
+  @param ccd_ron_def     default ccd ron value
+  @param rect_region_def default overscan region parameters
+  @param method_def      default collapse method value
+  @param sigclip_def     default sigma-clipping parameters 
+  @param minmax_def      default minmax-clipping parameters 
+
+  @see hdrl_rect_region_parameter_create_parlist()
+  @see hdrl_collapse_parameter_create_parlist()
+  Creates a parameterlist with the overscan computation parameters:
+
+    - base_context.prefix.correction-direction
+    - base_context.prefix.box-hsize
+    - base_context.prefix.ccd-ron
+    - base_context.prefix.calc-*
+    - base_context.prefix.collapse.*
+
+  The CLI aliases omit the base_context.
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_parameterlist * hdrl_overscan_parameter_create_parlist(
+        const char      *   base_context,
+        const char      *   prefix,
+        const char      *   corr_dir_def,
+        int                 box_hsize_def,
+        double              ccd_ron_def,
+        hdrl_parameter  *   rect_region_def,
+        const char      *   method_def,
+        hdrl_parameter  *   sigclip_def,
+        hdrl_parameter  *   minmax_def)
+{
+    cpl_ensure(prefix && base_context, CPL_ERROR_NULL_INPUT, NULL);
+    char                *   name ;
+    cpl_parameterlist   *   parlist = cpl_parameterlist_new();
+    cpl_parameter       *   par ;
+    char                *   context = 
+        hdrl_join_string(".", 2, base_context, prefix);
+
+    /* --prefix.correction_direction */
+    name = hdrl_join_string(".", 2, context, "correction-direction");
+    par = cpl_parameter_new_enum(name, CPL_TYPE_STRING, "Correction Direction", 
+            context, corr_dir_def, 2, "alongX", "alongY");
+    cpl_free(name);
+    name = hdrl_join_string(".", 2, prefix, "correction-direction");
+    cpl_parameter_set_alias(par, CPL_PARAMETER_MODE_CLI, name);
+    cpl_parameter_disable(par, CPL_PARAMETER_MODE_ENV);
+    cpl_free(name);
+    cpl_parameterlist_append(parlist, par);
+ 
+    /* --prefix.box-hsize */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "box-hsize", base_context,
+            "Half size of running box in pixel, -1 for full overscan region", 
+            CPL_TYPE_INT, box_hsize_def) ;
+
+    /* --prefix.ccd-ron */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "ccd-ron", base_context,
+            "Readout noise in ADU", CPL_TYPE_DOUBLE, ccd_ron_def) ;
+
+    /* Create Overscan Computation Region parameters */
+    /* --prefix.overscan.calc-xxx */
+    cpl_parameterlist * os_comp_reg = hdrl_rect_region_parameter_create_parlist(
+                base_context, prefix, "calc-", rect_region_def);
+    for (cpl_parameter * p = cpl_parameterlist_get_first(os_comp_reg) ;       
+            p != NULL; p = cpl_parameterlist_get_next(os_comp_reg)) 
+        cpl_parameterlist_append(parlist,cpl_parameter_duplicate(p));
+    cpl_parameterlist_delete(os_comp_reg);
+    
+    /* Overscan Collapsing related parameters */
+    /* --prefix.collapse.xxx */
+    name = hdrl_join_string(".", 2, prefix, "collapse");
+    cpl_parameterlist * pcollapse = hdrl_collapse_parameter_create_parlist(
+            base_context, name, method_def, sigclip_def, minmax_def) ;
+    cpl_free(name);
+    for (cpl_parameter * p = cpl_parameterlist_get_first(pcollapse) ;
+            p != NULL; p = cpl_parameterlist_get_next(pcollapse))
+        cpl_parameterlist_append(parlist,cpl_parameter_duplicate(p));
+    cpl_parameterlist_delete(pcollapse);
+
+    cpl_free(context);
+
+    if (cpl_error_get_code()) {
+        cpl_parameterlist_delete(parlist);
+        return NULL;
+    }
+
+    return parlist;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+  @brief Parse parameterlist to create input parameters for the Overscan method
+  @param parlist    parameter list to parse
+  @param prefix     prefix of parameter name
+  @return   Input parameters for the Overscan Computation
+  Reads a Parameterlist in order to create overscan parameters.
+  Expects a parameterlist containing:
+  - prefix.correction-direction
+  - prefix.box-hsize
+  - prefix.ccd-ron
+  - prefix.calc-llx
+  - prefix.calc-lly
+  - prefix.calc-urx
+  - prefix.calc-ury
+  - prefix.collapse.method
+  - prefix.collapse.sigclip.kappa-low
+  - prefix.collapse.sigclip.kappa-high
+  - prefix.collapse.sigclip.niter
+  - prefix.collapse.minmax.nlow
+  - prefix.collapse.sigclip.nhigh
+
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_overscan_parameter_parse_parlist(
+        const cpl_parameterlist *   parlist,
+        const char              *   prefix)
+{
+    cpl_ensure(prefix && parlist, CPL_ERROR_NULL_INPUT, NULL);
+    const cpl_parameter *   par = NULL;
+    hdrl_direction          corr_dir_param = HDRL_UNDEFINED_AXIS ;
+    const char          *   correction_direction = NULL;
+    int                     box_hsize = 0 ;
+    double                  ccd_ron = 0. ;
+    hdrl_parameter      *   os_collapse_params = NULL;
+    hdrl_parameter      *   os_region_params = NULL;
+    char                *   name ;
+
+    /* --correction-direction */
+    name = hdrl_join_string(".", 2, prefix, "correction-direction");
+    par = cpl_parameterlist_find_const(parlist, name) ;
+    correction_direction = cpl_parameter_get_string(par);
+    if (correction_direction == NULL) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                              "Parameter %s not found", name);
+        cpl_free(name);
+        return NULL;
+    }
+    if(!strcmp(correction_direction, "alongX")) {
+        corr_dir_param = HDRL_X_AXIS;
+    } else if(!strcmp(correction_direction, "alongY")) {
+        corr_dir_param = HDRL_Y_AXIS;
+    }
+    cpl_free(name) ;
+ 
+    /* --box-hsize */
+    name = hdrl_join_string(".", 2, prefix, "box-hsize");
+    par=cpl_parameterlist_find_const(parlist, name);
+    box_hsize = cpl_parameter_get_int(par);
+    cpl_free(name) ;
+
+    /* --ccd-ron */
+    name = hdrl_join_string(".", 2, prefix, "ccd-ron");
+    par=cpl_parameterlist_find_const(parlist, name);
+    ccd_ron = cpl_parameter_get_double(par);
+    cpl_free(name) ;
+
+    if (cpl_error_get_code()) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                              "Error while parsing parameterlist "
+                              "with prefix %s", prefix);
+        return NULL;
+    }
+
+    /* --calc-* */
+    os_region_params = hdrl_rect_region_parameter_parse_parlist(parlist,
+            prefix, "calc-");
+
+    /* --collapse.* */
+    name = hdrl_join_string(".", 2, prefix, "collapse");
+    os_collapse_params = hdrl_collapse_parameter_parse_parlist(parlist, name) ;
+    cpl_free(name) ;
+
+    if (cpl_error_get_code()) {
+        hdrl_parameter_destroy(os_region_params);
+        hdrl_parameter_destroy(os_collapse_params);
+        return NULL;
+    }
+    else {
+        return hdrl_overscan_parameter_create(corr_dir_param, ccd_ron,
+                                              box_hsize, os_collapse_params,
+                                              os_region_params);
+    }
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief get imagelist to vector reduction object
+ *
+ * @param cpse              parameter that determines the reduction type
+ * @param overscan_sub_ima  overscan image for default parameters
+ * @param reduce            pointer to reduction object storage
+ * @return cpl_error_code
+ *
+ * pointer stored in reduce must be deleted with
+ * hdrl_collapse_imagelist_to_vector_delete()
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code
+get_reduction(const hdrl_parameter * cpse,
+              const cpl_image * overscan_sub_ima,
+              hdrl_collapse_imagelist_to_vector_t ** reduce)
+{
+    if (hdrl_collapse_parameter_is_mean(cpse)) {
+        *reduce = hdrl_collapse_imagelist_to_vector_mean();
+    } else if (hdrl_collapse_parameter_is_weighted_mean(cpse)) {
+        *reduce = hdrl_collapse_imagelist_to_vector_weighted_mean();
+    } else if (hdrl_collapse_parameter_is_median(cpse)) {
+        *reduce = hdrl_collapse_imagelist_to_vector_median();
+    } else if (hdrl_collapse_parameter_is_sigclip(cpse)) {
+        double kappa =
+            sqrt(log(CX_MAX(hdrl_get_image_good_npix(overscan_sub_ima), 1)));
+        double kappa_low = hdrl_collapse_sigclip_parameter_get_kappa_low(cpse);
+        double kappa_high =
+            hdrl_collapse_sigclip_parameter_get_kappa_high(cpse);
+        int niter = hdrl_collapse_sigclip_parameter_get_niter(cpse);
+        if (kappa_low <= 0)     kappa_low = kappa;
+        if (kappa_high <= 0)    kappa_high = kappa;
+        *reduce = hdrl_collapse_imagelist_to_vector_sigclip(kappa_low,
+                                                            kappa_high, niter);
+    } else if (hdrl_collapse_parameter_is_minmax(cpse)) {
+        double nlow = hdrl_collapse_minmax_parameter_get_nlow(cpse);
+        double nhigh = hdrl_collapse_minmax_parameter_get_nhigh(cpse);
+        if (nlow <= 0)     nlow = 0;
+        if (nhigh <= 0)    nhigh = 0;
+        *reduce = hdrl_collapse_imagelist_to_vector_minmax(nlow, nhigh);
+    }
+
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Overscan correction computation
+  @param    source  input image containing the Overscan region
+  @param    params  Overscan computation parameters
+  @return   hdrl_overscan_compute_result structure containing the results
+  of the computation. It must be de-allocated by the caller using 
+  hdrl_overscan_compute_result_delete().
+  In case of error, NULL is returned and an error code is set.
+  @see      hdrl_overscan_compute_result_delete()
+
+  The source image may contain more than the overscan region that is
+  actually needed by the computation.
+
+  params->rect_region defines the overscan region in the source image. The 
+  bad pixels that might be present in the image are taken into account (i.e.
+  excluded from the computations).
+  
+  params->correction_direction is HDRL_X_AXIS (resp. HDRL_Y_AXIS) if the
+  overscan region has to be collapsed along the X (resp. Y) axis in
+  order to create the 1D resulting images (correction, error, contribution, the
+  \f$\chi^{2}\f$ (chi2) and
+  the reduced \f$\chi^{2}\f$ (red_chi2), additionally sigclip_reject_low and 
+  _high if the sigma-clipping collapsing is used).
+
+  Each pixel of the resulting 1D images are computed from a running
+  sub-window of the overscan region. params->box_hsize defines the half size
+  of the sub-window used for the computation (in the direction orthogonal to 
+  params->correction_direction). If params->box_hsize value is 
+  HDRL_OVERSCAN_FULL_BOX, the calculation is done on the whole overscan 
+  region instead of a running sub-window. In this case, all pixels of the 
+  resulting 1D images will be identical.
+
+  params->collapse methods can be mean, weighted mean, median or sigclip, 
+  i.e. the
+  collapse parameter can be created with
+  hdrl_collapse_mean_parameter_create(),
+  hdrl_collapse_weighted_mean_parameter_create(),
+  hdrl_collapse_median_parameter_create() or 
+  hdrl_collapse_sigclip_parameter_create().
+
+  params->ccd_ron is the CCD read-out noise. The parameter is mandatory,
+  must be strictly non-negative. It is used for the error, the chi2 and the
+  red_chi2 computation.
+
+  In case the sigma-clipping collapsing method is used, a sigma clipping
+  iterative rejection is applied in the overscan sub-window before the 
+  computation of the results.
+
+  The output hdrl_overscan_compute_result structure (in the following
+  named 'out') contains the following members:
+
+  out.correction is a 1D HDRL image of type double.
+  Its image contains the overscan correction values computed from the good
+  pixels of the running sub-window (mean, median or mean after rejection, 
+  depending on the used collapsing method)
+
+  Its error contains \f$\frac{ccd\_ron}{\sqrt{contribution}}\f$ for the
+  mean, weighted mean and sigma-cliping methods.
+  In case the method is the median one, it would contain 
+  \f$\sqrt{\frac{\pi}{2}}\times\frac{ccd\_ron}{\sqrt{contribution}}\f$
+  if contribution is strictly greater than 2 pixels and 
+  \f$\frac{ccd\_ron}{\sqrt{contribution}}\f$ when the contribution is 1 or 
+  2 pixels. 
+
+  out.contribution is a 1D CPL image of type integer.
+  It contains the number of good pixels of the input running sub-window
+  for the mean and median methods, and the remaining good pixels after the 
+  rejection for the sigma-clipping method.
+
+  out.chi2 and out.red_chi2 are 1D CPL images of type double.
+
+  out.chi2 contains the sum over the good pixels of the region to correct, i.e.
+  of \f$\frac{source - out.correction}{ccd\_ron}^2\f$
+
+  out.red_chi2 contains the reduced chi2, i.e. the chi2 divided by the number 
+  of contributing pixels.
+
+  out.sigclip_reject_low and _high are 1D CPL images of type double.
+  They are only returned for the sigma-clipping method. They
+  indicate the final thresholds of the sigma-clipping rejection.
+
+  \image html overscan_computation_algorithm.png
+
+  @see hdrl_kappa_sigma_clip
+  @see hdrl_overscan_correct
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_overscan_compute_result * hdrl_overscan_compute(
+        const cpl_image         *   source,
+        const hdrl_parameter    *   params)
+{
+    cpl_image   *   correction_img = NULL;
+    cpl_image   *   correction_err_img = NULL;
+    cpl_image   *   contribution_img = NULL;
+    cpl_image   *   chi2_img = NULL;
+    cpl_image   *   red_chi2_img = NULL;
+    cpl_image   *   reject_low = NULL;
+    cpl_image   *   reject_high = NULL;
+    cpl_size        llx = 0;
+    cpl_size        lly = 0;
+    cpl_size        urx = 0;
+    cpl_size        ury = 0;
+    cpl_image   *   overscan_ima = NULL;
+
+     /*TODO add minmax description to the doxygen */
+
+    /* Check Entries */
+    cpl_error_ensure(source != NULL, CPL_ERROR_NULL_INPUT, 
+            return NULL, "NULL input image");
+    cpl_error_ensure(params != NULL, CPL_ERROR_NULL_INPUT, 
+            return NULL, "NULL input parameters");
+    if (hdrl_overscan_parameter_verify(
+                params,
+                cpl_image_get_size_x(source),
+                cpl_image_get_size_y(source)) != CPL_ERROR_NONE)
+        return NULL;
+
+    /* Local Usage Parameters */
+    const hdrl_overscan_parameter * p_loc = 
+        (hdrl_overscan_parameter *)params ;
+    const hdrl_parameter * cpse = p_loc->collapse ;
+    const hdrl_parameter * rr = p_loc->rect_region ;
+
+    /* Extract Overscan region */
+    overscan_ima = cpl_image_extract(source, 
+            hdrl_rect_region_get_llx(rr),
+            hdrl_rect_region_get_lly(rr),
+            hdrl_rect_region_get_urx(rr),
+            hdrl_rect_region_get_ury(rr)) ;
+
+    /* Handle Orientation */
+    if(p_loc->correction_direction == HDRL_Y_AXIS) {
+        /* rotate the image 90 degree counter-clockwise */
+        cpl_image_turn(overscan_ima, -1);
+    }
+
+    /* Redefine the boundaries to extracted image */
+    llx = 1;
+    lly = 1;
+    urx = cpl_image_get_size_x(overscan_ima);
+    ury = cpl_image_get_size_y(overscan_ima);
+
+    /* Create output images  */
+    correction_img = cpl_image_new(1, ury, HDRL_TYPE_DATA);
+    correction_err_img = cpl_image_new(1, ury, HDRL_TYPE_ERROR);
+    contribution_img = cpl_image_new(1, ury, CPL_TYPE_INT);
+    chi2_img = cpl_image_new(1, ury, CPL_TYPE_DOUBLE);
+    red_chi2_img = cpl_image_new(1, ury, CPL_TYPE_DOUBLE);
+
+    if (hdrl_collapse_parameter_is_sigclip(cpse) ||
+                    hdrl_collapse_parameter_is_minmax(cpse)) {
+        reject_low = cpl_image_new(1, ury, CPL_TYPE_DOUBLE);
+        reject_high = cpl_image_new(1, ury, CPL_TYPE_DOUBLE);
+    }
+
+
+    /* Loop along Y direction */
+    /* only 1 iteration if hbox == HDRL_OVERSCAN_FULL_BOX */
+HDRL_OMP(omp parallel for)
+    for (long ipixel = 1;
+         ipixel <= (p_loc->box_hsize == HDRL_OVERSCAN_FULL_BOX ? 1 : ury);
+         ipixel++) {
+        cpl_size contribution;
+        double corr, error, chi2, red_chi2;
+        const int box_hsize = p_loc->box_hsize;
+        const double ccd_ron = p_loc->ccd_ron;
+        cpl_size upperlimit;
+        cpl_size lowerlimit;
+        cpl_image * overscan_sub_ima, * ccd_ron_ima;
+        /* Switch on the different methods */
+        hdrl_collapse_imagelist_to_vector_t * reduce = NULL;
+        void * collapse_eout = NULL;
+
+        /* define proper extraction limits */
+        if (box_hsize == HDRL_OVERSCAN_FULL_BOX) {
+            /* take full region as box */
+            lowerlimit = lly;
+            upperlimit = ury;
+        }
+        else if (ipixel + box_hsize > ury) {
+            /* Shrink the window if you are approaching the image boundaries */
+            upperlimit = CX_MIN(ipixel + box_hsize, ury);
+            lowerlimit = 2 * ipixel - upperlimit;
+        }
+        else {
+            /* Shrink the window if you are approaching the image boundaries */
+            lowerlimit = CX_MAX(ipixel - box_hsize, 1);
+            upperlimit = 2 * ipixel - lowerlimit;
+        }
+
+        /* Extract the current running sub-window */
+        overscan_sub_ima = cpl_image_extract(overscan_ima, llx, lowerlimit, 
+                urx, upperlimit);
+
+        /* Fill an image with the ccd_ron constant */
+        ccd_ron_ima = cpl_image_duplicate(overscan_sub_ima);
+        cpl_image_multiply_scalar(ccd_ron_ima, 0.0);
+        cpl_image_add_scalar(ccd_ron_ima, ccd_ron);
+
+        get_reduction(cpse, overscan_sub_ima, &reduce);
+
+        /* Compute the over-scan correction, error, and contribution  */
+        hdrl_overscan_reduce_image_to_scalar(reduce, overscan_sub_ima, 
+                ccd_ron_ima, &corr, &error, &contribution, &collapse_eout);
+        /* handle additional sigclip and minmax output */
+        if (collapse_eout && (hdrl_collapse_parameter_is_sigclip(cpse) ||
+            hdrl_collapse_parameter_is_minmax(cpse))) {
+            assert(sizeof(hdrl_sigclip_vector_output) ==
+                   sizeof(hdrl_minmax_vector_output));
+            hdrl_sigclip_vector_output * eout = collapse_eout;
+            double low = cpl_vector_get(eout->reject_low, 0);
+            double high = cpl_vector_get(eout->reject_high, 0);
+            cpl_image_set(reject_low, 1, ipixel, low);
+            cpl_image_set(reject_high, 1, ipixel, high);
+            cpl_vector_delete(eout->reject_low);
+            cpl_vector_delete(eout->reject_high);
+        }
+        hdrl_collapse_imagelist_to_vector_unwrap_eout(reduce, collapse_eout);
+
+        /* Compute the chi2 - Independent of the method */
+        if (contribution == 0) {
+            chi2 = NAN;
+            red_chi2 = NAN;
+        } else if (p_loc->box_hsize == HDRL_OVERSCAN_FULL_BOX) {
+            hdrl_overscan_compute_chi_square(overscan_sub_ima,
+                    ccd_ron_ima, corr, &chi2, &red_chi2);
+        } else {
+            /*Calculate the chi2 only in the central slice of the image
+             * TODO very inefficient - restructure */
+            cpl_size nx = cpl_image_get_size_x(overscan_sub_ima);
+            cpl_size ny = cpl_image_get_size_y(overscan_sub_ima);
+
+            cpl_image * overscan_sub_ima_slice =
+                cpl_image_extract(overscan_sub_ima, 1, (cpl_size)((ny+1)/2), 
+                        nx, (cpl_size)((ny+1)/2));
+            cpl_image * ccd_ron_ima_slice = 
+                cpl_image_extract(ccd_ron_ima, 1, (cpl_size)((ny+1)/2), nx,
+                        (cpl_size)((ny+1)/2));
+
+            hdrl_overscan_compute_chi_square(overscan_sub_ima_slice, 
+                    ccd_ron_ima_slice, corr, &chi2, &red_chi2);
+
+            cpl_image_delete(overscan_sub_ima_slice);
+            cpl_image_delete(ccd_ron_ima_slice);
+        }
+
+        /* Fill the result images with the current result */
+        cpl_image_set(correction_img,     1, ipixel, corr);
+        cpl_image_set(correction_err_img, 1, ipixel, error);
+        cpl_image_set(contribution_img, 1, ipixel, contribution);
+        cpl_image_set(chi2_img, 1, ipixel, chi2);
+        cpl_image_set(red_chi2_img, 1, ipixel, red_chi2);
+
+        cpl_image_delete(overscan_sub_ima);
+        cpl_image_delete(ccd_ron_ima);
+
+        hdrl_collapse_imagelist_to_vector_delete(reduce);
+    }
+
+    /* broadcast the full box result to the full result row/col */
+    if (p_loc->box_hsize == HDRL_OVERSCAN_FULL_BOX) {
+        int rej;
+        const double ccd_ron = p_loc->ccd_ron;
+        const double correction_value =
+                        cpl_image_get(correction_img, 1, 1, &rej);
+        const double correction_err_value =
+                        cpl_image_get(correction_err_img, 1, 1, &rej);
+        const cpl_size contribution_value =
+                        cpl_image_get(contribution_img, 1, 1, &rej);
+        cpl_size loopmax = cpl_image_get_size_y(correction_img);
+HDRL_OMP(omp parallel for private(rej))
+        for (cpl_size i = 1; i <= loopmax; i++) {
+            double chi2, red_chi2;
+            cpl_image * overscan_sub_ima, * ccd_ron_ima;
+
+            if (i < loopmax) {
+                /*Here we broadcast*/
+                cpl_image_set(correction_img, 1, i + 1, correction_value);
+                cpl_image_set(correction_err_img, 1, i + 1, 
+                        correction_err_value);
+                cpl_image_set(contribution_img, 1, i + 1,contribution_value);
+                if (hdrl_collapse_parameter_is_sigclip(cpse) ||
+                                hdrl_collapse_parameter_is_minmax(cpse)) {
+                    cpl_image_set(reject_low, 1, i + 1,
+                            cpl_image_get(reject_low, 1, 1, &rej));
+                    cpl_image_set(reject_high, 1, i + 1,
+                            cpl_image_get(reject_high, 1, 1, &rej));
+                }
+            }
+            /* Here we do additional chi2 calculation */
+
+            /* Extract the current running sub-window */
+            overscan_sub_ima = cpl_image_extract(overscan_ima, llx, i, urx, i);
+
+            /* Fill an image with the ccd_ron constant */
+            ccd_ron_ima = cpl_image_duplicate(overscan_sub_ima);
+            cpl_image_multiply_scalar(ccd_ron_ima, 0.0);
+            cpl_image_add_scalar(ccd_ron_ima, ccd_ron);
+
+            hdrl_overscan_compute_chi_square(overscan_sub_ima,
+                                             ccd_ron_ima, correction_value,
+                                             &chi2, &red_chi2);
+
+            cpl_image_set(chi2_img, 1, i, chi2);
+            cpl_image_set(red_chi2_img, 1, i, red_chi2);
+            cpl_image_delete(overscan_sub_ima);
+            cpl_image_delete(ccd_ron_ima);
+        }
+    }
+
+    cpl_image_delete(overscan_ima);
+    /* flag bad pixels */
+    cpl_image_reject_value(correction_img, CPL_VALUE_NAN);
+    cpl_image_reject_value(correction_err_img, CPL_VALUE_NAN);
+    cpl_image_reject_value(chi2_img, CPL_VALUE_NAN);
+    cpl_image_reject_value(red_chi2_img, CPL_VALUE_NAN);
+    if (hdrl_collapse_parameter_is_sigclip(cpse) ||
+                    hdrl_collapse_parameter_is_minmax(cpse)) {
+        cpl_image_reject_value(reject_low, CPL_VALUE_NAN);
+        cpl_image_reject_value(reject_high, CPL_VALUE_NAN);
+    }
+
+    /* Handle Orientation */
+    if(p_loc->correction_direction == HDRL_Y_AXIS) {
+        cpl_image_turn(correction_img, +1);
+        cpl_image_turn(correction_err_img, +1);
+        cpl_image_turn(contribution_img, +1);
+        cpl_image_turn(chi2_img, +1);
+        cpl_image_turn(red_chi2_img, +1);
+        if (hdrl_collapse_parameter_is_sigclip(cpse) ||
+                        hdrl_collapse_parameter_is_minmax(cpse)) {
+            cpl_image_turn(reject_low, +1);
+            cpl_image_turn(reject_high, +1);
+        }
+    }
+
+    /* Create the Overscan resulting structure */
+    {
+        hdrl_overscan_compute_result * result =
+            hdrl_overscan_compute_result_create();
+        hdrl_image * res = hdrl_image_create(correction_img,
+                                             correction_err_img);
+        cpl_image_delete(correction_img);
+        cpl_image_delete(correction_err_img);
+        result->correction_direction = p_loc->correction_direction;
+        result->correction = res;
+        result->contribution = contribution_img;
+        result->chi2 = chi2_img;
+        result->red_chi2 = red_chi2_img;
+        result->sigclip_reject_low = reject_low;
+        result->sigclip_reject_high = reject_high;
+        return result;
+    }
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the correction in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The correction HDRL image
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_image * hdrl_overscan_compute_result_get_correction(
+        const hdrl_overscan_compute_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    return res->correction;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Unset the correction in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The correction HDRL image that has been unset
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_image * hdrl_overscan_compute_result_unset_correction(
+        hdrl_overscan_compute_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    hdrl_image * r = res->correction;
+    res->correction = NULL;
+    return r;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the contribution in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The contribution CPL image
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_compute_result_get_contribution(
+        const hdrl_overscan_compute_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    return res->contribution;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Unset the contribution in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The contribution CPL image that has been unset
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_compute_result_unset_contribution(
+        hdrl_overscan_compute_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_image * r = res->contribution;
+    res->contribution = NULL;
+    return r;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the CHI2 in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The CHI2 CPL image
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_compute_result_get_chi2(
+        const hdrl_overscan_compute_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    return res->chi2;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Unset the CHI2 in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The CHI2 CPL image that has been unset
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_compute_result_unset_chi2(
+        hdrl_overscan_compute_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_image * r = res->chi2;
+    res->chi2 = NULL;
+    return r;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the reduced CHI2 in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The reduced CHI2 CPL image
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_compute_result_get_red_chi2(
+        const hdrl_overscan_compute_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    return res->red_chi2;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Unset the reduced CHI2 in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The reduced CHI2 CPL image that has been unset
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_compute_result_unset_red_chi2(
+        hdrl_overscan_compute_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_image * r = res->red_chi2;
+    res->red_chi2 = NULL;
+    return r;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the low threshold in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The low threshold CPL image
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_compute_result_get_sigclip_reject_low(
+        const hdrl_overscan_compute_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    if (!res->sigclip_reject_low) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT,
+                              "rejection parameters are only "
+                              "available if collapse mode of overscan is set "
+                              "to sigclip or minmax");
+    }
+    return res->sigclip_reject_low;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Unset the low threshold in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The low threshold CPL image that has been unset
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_compute_result_unset_sigclip_reject_low(
+        hdrl_overscan_compute_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_image * r = res->sigclip_reject_low;
+    if (!res->sigclip_reject_low) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT,
+                              "rejection parameters are only "
+                              "available if collapse mode of overscan is set "
+                              "to sigclip or minmax");
+    }
+    res->sigclip_reject_low = NULL;
+    return r;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the high threshold in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The high threshold CPL image
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_compute_result_get_sigclip_reject_high(
+        const hdrl_overscan_compute_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    if (!res->sigclip_reject_high) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT,
+                              "rejection parameters are only "
+                              "available if collapse mode of overscan is set "
+                              "to sigclip or minmax");
+    }
+    return res->sigclip_reject_high;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Unset the high threshold in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The high threshold CPL image that has been unset
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_compute_result_unset_sigclip_reject_high(
+        hdrl_overscan_compute_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_image * r = res->sigclip_reject_high;
+    res->sigclip_reject_high = NULL;
+    return r;
+}
+
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the low threshold in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The low threshold CPL image
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_compute_result_get_minmax_reject_low(
+        const hdrl_overscan_compute_result * res)
+{
+   return hdrl_overscan_compute_result_get_sigclip_reject_low(res);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Unset the low threshold in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The low threshold CPL image that has been unset
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_compute_result_unset_minmax_reject_low(
+        hdrl_overscan_compute_result * res)
+{
+    return hdrl_overscan_compute_result_unset_sigclip_reject_low(res);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the high threshold in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The high threshold CPL image
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_compute_result_get_minmax_reject_high(
+        const hdrl_overscan_compute_result * res)
+{
+    return hdrl_overscan_compute_result_get_sigclip_reject_high(res);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Unset the high threshold in the Overscan Computation result object
+  @param    res The Overscan Computation result object
+  @return   The high threshold CPL image that has been unset
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_compute_result_unset_minmax_reject_high(
+        hdrl_overscan_compute_result * res)
+{
+    return hdrl_overscan_compute_result_unset_sigclip_reject_high(res);
+}
+
+
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Deletes the Overscan Computation Result Structure
+  @param    result  The computation result structure to delete
+ */
+/*----------------------------------------------------------------------------*/
+void hdrl_overscan_compute_result_delete(
+        hdrl_overscan_compute_result   *   result)
+{
+    if (result == NULL) return;
+    hdrl_image_delete(result->correction);
+    cpl_image_delete(result->contribution);
+    cpl_image_delete(result->chi2);
+    cpl_image_delete(result->red_chi2);
+    cpl_image_delete(result->sigclip_reject_low);
+    cpl_image_delete(result->sigclip_reject_high);
+    cpl_free(result);
+    return;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Overscan correction 
+  @param    hsource         Input HDRL image that needs to be corrected
+  @param    region          Region from source that needs correction
+  @param    os_computation  Results of the Overscan computation
+  @return  hdrl_overscan_correct_result structure containing the
+  results of the correction. It must be freed with 
+  hdrl_overscan_correct_result_delete()
+  On error, NULL is returned and an error code is set.
+
+  source is the input CPL image that needs to be corrected. It is a required
+  input.
+  Usually the same image is passed to hdrl_overscan_compute() to compute 
+  the overscan correction parameters. 
+
+  source_error is the error used for error propagation. It is a required input.
+
+  region specifies which region of the source image must be corrected.
+  If NULL or invalid, the whole image is corrected.
+  The region size must fit the sixe of the os_computation.
+
+  os_computation contains all the parameters for the overscan
+  correction. It has been produced by hdrl_overscan_compute().
+
+  Following results are available from the return value:
+
+  hdrl_overscan_correct_result_get_corrected(result):
+  returns the HDRL image of type double of the same size as source.
+  
+  Its image part contains the corrected values where all the pixels
+  within the specified region were subtracted using the proper correction 
+  obtained in os_computation.correction.
+  The pixels outside the specified region remain unchanged.
+  Pixels for which a overscan value could not be determined (e.g. because all
+  pixels in the overscan region are bad) are set to zero.
+
+  Its error part contains the error where all the pixels within the specified 
+  region are set to: \f$\sqrt{(os\_computation.error^2 + source\_error^2)}\f$, which is
+  the standard Gaussian error propagation.
+  The pixels outside the specified region remain unchanged.
+  Pixels for which a overscan value could not be determined (e.g. because all
+  pixels in the overscan region are bad) are set to zero.
+
+  hdrl_overscan_correct_result_get_badmask(result):
+  returns an integer cpl_image of the same size as the input that contains a
+  value of 1 for pixels that have not been corrected due to the overscan data
+  being bad in that row/column.
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_overscan_correct_result * hdrl_overscan_correct(
+        const hdrl_image                    *   hsource,
+        const hdrl_parameter                *   region,
+        const hdrl_overscan_compute_result  *   os_computation)
+{
+    cpl_size            llx = 0, lly = 0, urx = 0, ury = 0;
+    /* local pointers to source image and its error */
+    cpl_image       *   source_loc = NULL;
+    cpl_image       *   source_error_loc = NULL;
+    long                xsize_overscan = 0;
+    long                ysize_overscan = 0;
+    size_t              nx;
+    cpl_mask        *   orig_mask = NULL;
+    hdrl_image      *   hoverscan;
+    /* value to use in mask for pixels rejected by algorithm */
+    hdrl_bitmask_t      reject_code = 1;
+
+    /* Check Entries */
+    cpl_error_ensure(hsource != NULL, CPL_ERROR_NULL_INPUT,
+            return NULL, "NULL input source image");
+    cpl_error_ensure(os_computation != NULL, CPL_ERROR_NULL_INPUT,
+            return NULL, "NULL overscan computation result");
+
+    cpl_error_ensure(hdrl_int_is_power_of_two(reject_code),
+                     CPL_ERROR_ILLEGAL_INPUT, return NULL,
+                     "reject_code must be a power of two");
+
+    if (hdrl_overscan_compute_result_verify(os_computation) != CPL_ERROR_NONE)
+        return NULL;
+
+    hoverscan = os_computation->correction;
+
+    /* Initialise Region parameters */
+    if (region != NULL) {
+        if (hdrl_rect_region_parameter_verify(region, 
+                    hdrl_image_get_size_x(hsource),
+                    hdrl_image_get_size_y(hsource)) != CPL_ERROR_NONE)
+            return NULL;
+        llx = hdrl_rect_region_get_llx(region);
+        lly = hdrl_rect_region_get_lly(region);
+        urx = hdrl_rect_region_get_urx(region);
+        ury = hdrl_rect_region_get_ury(region);
+    } else {
+        llx = lly = 1;
+        urx = hdrl_image_get_size_x(hsource);
+        ury = hdrl_image_get_size_y(hsource);
+    }
+
+    source_loc =
+        cpl_image_cast(hdrl_image_get_image_const(hsource), HDRL_TYPE_DATA);
+    source_error_loc =
+        cpl_image_cast(hdrl_image_get_error_const(hsource), HDRL_TYPE_ERROR);
+    nx = cpl_image_get_size_x(source_loc);
+
+    xsize_overscan = hdrl_image_get_size_x(hoverscan);
+    ysize_overscan = hdrl_image_get_size_y(hoverscan);
+    
+    /* Check if the overscan image has an appropriate size */
+    if (os_computation->correction_direction == HDRL_X_AXIS &&
+            ury-lly+1 != ysize_overscan) {
+        cpl_image_delete(source_loc);
+        cpl_image_delete(source_error_loc);
+        cpl_error_set_message(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT,
+                "Correction region Y size does not match overscan Y size");
+        return NULL;
+    }
+    if (os_computation->correction_direction == HDRL_Y_AXIS &&
+            urx-llx+1 != xsize_overscan) {
+        cpl_image_delete(source_loc);
+        cpl_image_delete(source_error_loc);
+        cpl_error_set_message(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT,
+                "Correction region X size does not match overscan X size");
+        return NULL;
+    }
+
+    cpl_ensure(xsize_overscan == 1 || ysize_overscan == 1,
+               CPL_ERROR_INCOMPATIBLE_INPUT, NULL);
+
+    /* store original mask to later separate it from newly created bpms */
+    orig_mask = hdrl_copy_image_mask(source_loc);
+
+    {
+        hdrl_data_t * psource_loc = cpl_image_get_data(source_loc);
+        hdrl_error_t * psource_err_loc = cpl_image_get_data(source_error_loc);
+        const cpl_mask * bpm = hdrl_image_get_mask_const(hoverscan);
+        /* os image is one dimensional, so just get the data */
+        const cpl_binary * rej = bpm ?  cpl_mask_get_data_const(bpm) : NULL;
+        const hdrl_data_t * pos_val = hdrl_get_image_data_const(
+                                     hdrl_image_get_image_const(hoverscan));
+        const hdrl_error_t * pos_e = hdrl_get_image_error_const(
+                                     hdrl_image_get_error_const(hoverscan));
+        /* make sure we have a bpm before the parallel loop */
+        cpl_image_get_bpm(source_loc);
+
+        /* corrects extracted image for over-scan value, compute associated
+         * error, flag bad pixels */
+HDRL_OMP(omp parallel for)
+        for (long j = lly - 1; j < ury; j++) {
+            for (long i = llx - 1; i < urx; i++) {
+                const size_t idx = 
+                    os_computation->correction_direction == HDRL_X_AXIS ? 
+                    j-lly+1 : i-llx+1;
+                double ima_e = psource_err_loc[j * nx + i];
+
+                if (rej && rej[idx]) {
+                    /* set to zero as per requirements */
+                    cpl_image_reject(source_loc, i + 1, j + 1);
+                    psource_loc[j * nx + i] = 0;
+                    psource_err_loc[j * nx + i] = 0;
+                } else {
+                    psource_loc[j * nx + i] -= pos_val[idx];
+                    psource_err_loc[j * nx + i] =
+                        sqrt(pos_e[idx] * pos_e[idx] + ima_e * ima_e);
+                }
+            }
+        }
+    }
+
+    {
+        hdrl_overscan_correct_result * res;
+        cpl_mask * new_mask = hdrl_copy_image_mask(source_loc);
+        cpl_image * badmask = cpl_image_new(cpl_image_get_size_x(source_loc),
+                                            cpl_image_get_size_y(source_loc),
+                                            CPL_TYPE_INT);
+        /* get the new bad pixels */
+        cpl_mask_xor(new_mask, orig_mask);
+        /* fill them with the code */
+        cpl_image_reject_from_mask(badmask, new_mask);
+        cpl_image_fill_rejected(badmask, reject_code);
+
+        cpl_mask_delete(new_mask);
+        cpl_mask_delete(orig_mask);
+
+        /* Create, fill and return the returned structure */
+        res = hdrl_overscan_correct_result_create();
+        res->corrected = hdrl_image_wrap(source_loc, source_error_loc, NULL,
+                                         CPL_TRUE);
+        res->badmask = badmask;
+        return res;
+    }
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Delete the Overscan Correction Result Structure
+  @param    result  The correction result structure to delete
+ */
+/*----------------------------------------------------------------------------*/
+void hdrl_overscan_correct_result_delete(
+        hdrl_overscan_correct_result   *   result)
+{
+    if (result == NULL) return; 
+    hdrl_image_delete(result->corrected);
+    cpl_image_delete(result->badmask);
+    cpl_free(result);
+    return;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the corrected image in the Overscan Correction result object
+  @param    res The Overscan Correction result object
+  @return   The HDLR corrected image
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_image * hdrl_overscan_correct_result_get_corrected(
+        const hdrl_overscan_correct_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    return res->corrected;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Unset the corrected image in the Overscan Correction result object
+  @param    res The Overscan Correction result object
+  @return   The HDLR corrected image that was unset
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_image * hdrl_overscan_correct_result_unset_corrected(
+        hdrl_overscan_correct_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    hdrl_image * r = res->corrected;
+    res->corrected = NULL;
+    return r;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Access the bad pixels mask in the Overscan Correction result object
+  @param    res The Overscan Correction result object
+  @return   The bad pixels mask as a CPL image
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_correct_result_get_badmask(
+        const hdrl_overscan_correct_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    return res->badmask;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Unset the bad pixels mask in the Overscan Correction result object
+  @param    res The Overscan Correction result object
+  @return   The bad pixels mask as a CPL image that was unset
+ */
+/*----------------------------------------------------------------------------*/
+cpl_image * hdrl_overscan_correct_result_unset_badmask(
+        hdrl_overscan_correct_result * res)
+{
+    cpl_ensure(res, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_image * r = res->badmask;
+    res->badmask = NULL;
+    return r;
+}
+
+/**@}*/
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Destroys Overscan Parameters objects
+  @param    param   The parameter to destroy
+ */
+/*----------------------------------------------------------------------------*/
+static void hdrl_overscan_parameter_destroy(void * param)
+{
+    hdrl_overscan_parameter * p = (hdrl_overscan_parameter *)param ;
+    hdrl_parameter_destroy(p->collapse) ;
+    hdrl_parameter_destroy(p->rect_region) ;
+    hdrl_parameter_delete((hdrl_parameter*)param) ;
+    return ;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Creates Overscan Computation Result Structure 
+  @return   A structure that needs to be de-allocated with
+  hdrl_overscan_compute_result_delete()
+  @see hdrl_overscan_compute_result_delete()
+ */
+/*----------------------------------------------------------------------------*/
+static hdrl_overscan_compute_result * hdrl_overscan_compute_result_create(
+        void)
+{
+    hdrl_overscan_compute_result * self = 
+        cpl_malloc(sizeof(hdrl_overscan_compute_result));
+
+    self->correction_direction = HDRL_UNDEFINED_AXIS;
+    self->correction = NULL;
+    self->contribution = NULL;
+    self->chi2 = NULL;
+    self->red_chi2 = NULL;
+    self->sigclip_reject_low = NULL;
+    self->sigclip_reject_high = NULL;
+    return self;
+}
+
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Verify basic correctness of the result structure
+  @param    result      Overscan result structure
+  @return   CPL_ERROR_NONE if eveything is ok, an error code otherwise
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_overscan_compute_result_verify(
+        const hdrl_overscan_compute_result * result)
+{
+    cpl_error_ensure(result != NULL, CPL_ERROR_NULL_INPUT,
+            return CPL_ERROR_NULL_INPUT,
+            "NULL input overscan result structure");
+    cpl_error_ensure(result->correction_direction == HDRL_X_AXIS ||
+            result->correction_direction == HDRL_Y_AXIS, 
+            CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+            "The specified collapse direction is unknown");
+
+    if (result->correction_direction == HDRL_X_AXIS) {
+        cpl_error_ensure(hdrl_image_get_size_x(result->correction) == 1, 
+                CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                "The Correction image X size should be 1");
+        cpl_error_ensure(cpl_image_get_size_x(result->contribution) == 1, 
+                CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                "The Contribution image X size should be 1");
+        cpl_error_ensure(cpl_image_get_size_x(result->chi2) == 1,
+                CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                "The Chi Square image X size should be 1");
+        cpl_error_ensure(cpl_image_get_size_x(result->red_chi2) == 1, 
+                CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                "The reduced Chi Square image X size should be 1");
+        if (result->sigclip_reject_low != NULL) {
+            cpl_error_ensure(cpl_image_get_size_x(result->sigclip_reject_low) 
+                    == 1, 
+                    CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                    "The SIGCLIP low rejection image X size should be 1");
+
+        }
+        if (result->sigclip_reject_high != NULL) {
+            cpl_error_ensure(cpl_image_get_size_x(result->sigclip_reject_high) 
+                    == 1, 
+                    CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                    "The SIGCLIP high rejection image X size should be 1");
+        }
+    }
+    else if (result->correction_direction == HDRL_Y_AXIS) {
+        cpl_error_ensure(hdrl_image_get_size_y(result->correction) == 1, 
+                CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                "The Correction image Y size should be 1");
+        cpl_error_ensure(cpl_image_get_size_y(result->contribution) == 1, 
+                CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                "The Contribution image Y size should be 1");
+        cpl_error_ensure(cpl_image_get_size_y(result->chi2) == 1,
+                CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                "The Chi Square image Y size should be 1");
+        cpl_error_ensure(cpl_image_get_size_y(result->red_chi2) == 1, 
+                CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                "The reduced Chi Square image Y size should be 1");
+        if (result->sigclip_reject_low != NULL) {
+            cpl_error_ensure(cpl_image_get_size_y(result->sigclip_reject_low) 
+                    == 1, 
+                    CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                    "The SIGCLIP low rejection image Y size should be 1");
+
+        }
+        if (result->sigclip_reject_high != NULL) {
+            cpl_error_ensure(cpl_image_get_size_y(result->sigclip_reject_high) 
+                    == 1, 
+                    CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                    "The SIGCLIP high rejection image Y size should be 1");
+        }
+    }
+    else return cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_INPUT,
+            "correction_direction must be HDRL_X_AXIS or HDRL_Y_AXIS");
+    return CPL_ERROR_NONE;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Creates Overscan Correction result structure
+  @return   A structure holding the Overscan Correction Results, that
+  needs to be de-allocated with hdrl_overscan_correct_result_delete()
+  @see hdrl_overscan_correct_result_delete() 
+ */
+/*----------------------------------------------------------------------------*/
+static hdrl_overscan_correct_result * hdrl_overscan_correct_result_create(
+        void)
+{
+    hdrl_overscan_correct_result * self = cpl_malloc(sizeof(*self));
+    self->corrected = NULL;
+    self->badmask = NULL;
+    return self;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Calculate chi square as well as the reduced chi square
+  @param data          Measured data image
+  @param error         Error of measured data image
+  @param expect        Expected value of data
+  @param[out] chi2     Weighted sum of squared deviations
+  @param[out] red_chi2 Reduced weighted sum of squared deviations
+  @return CPL_ERROR_NONE if everything is ok, an error code otherwise
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code  hdrl_overscan_compute_chi_square(
+        const cpl_image *   data,
+        const cpl_image *   error,
+        const double        expect,
+        double          *   chi2,
+        double          *   red_chi2)
+{
+    cpl_image * s;
+    cpl_size nrej, nerej;
+    cpl_image * e = NULL;
+    cpl_size nepix = 0;
+    cpl_size npix = 0;
+
+    nrej = cpl_image_count_rejected(data);
+    npix = cpl_image_get_size_x(data) * cpl_image_get_size_y(data);
+
+    if (nrej == npix) {
+        *chi2 = NAN;
+        *red_chi2 = NAN;
+        return CPL_ERROR_NONE;
+    }
+
+    e = cpl_image_duplicate(error);
+    nepix = cpl_image_get_size_x(e) * cpl_image_get_size_y(e);
+
+    /*TODO handle pre-existing Zero's marked as bad */
+    /* check if error image contains zeros */
+    cpl_image_accept_all(e);
+    cpl_image_reject_value(e, CPL_VALUE_ZERO);
+    nerej = cpl_image_count_rejected(e);
+    /* all errors zero allowed */
+    if (nerej == nepix) {
+        cpl_image_delete(e);
+        *chi2 = NAN;
+        *red_chi2 = NAN;
+        return CPL_ERROR_NONE;
+    }
+    /* partial zero errors make no sense */
+    else if (nerej != 0) {
+        cpl_image_delete(e);
+        cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_INPUT,
+                              "Error image can't contain zeros");
+        *chi2 = NAN;
+        *red_chi2 = NAN;
+        return CPL_ERROR_ILLEGAL_INPUT;
+    }
+
+    s = cpl_image_duplicate(data);
+    /* computes chi squared defined as:
+     * \Sum_i[ (x_i - expect)^2 / sigma_i^2 ] */
+    cpl_image_subtract_scalar(s, expect);
+    cpl_image_divide(s, e);
+    *chi2 = cpl_image_get_sqflux(s); /* = squared sum */
+    *red_chi2 = *chi2 / npix; /* reduced chi2 */
+    cpl_image_delete(s);
+    cpl_image_delete(e);
+    return CPL_ERROR_NONE;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief reduce image to scalar
+  @param red          imagelist to vector reduction method
+  @param data         image to reduce
+  @param data_error   error of image
+  @param result       data reduction result
+  @param error        propagated error
+  @param contribution number of pixels that contributed
+  @param eout         extra output for sigclip
+  @return A CPL error code
+
+  this is just a single image wrapper over hdrl_collapse_imagelist_to_vector
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_error_code hdrl_overscan_reduce_image_to_scalar(
+        hdrl_collapse_imagelist_to_vector_t *   red,
+        cpl_image                           *   data,
+        cpl_image                           *   data_error,
+        double                              *   result, 
+        double                              *   error,
+        cpl_size                            *   contribution,
+        void                                **  eout)
+{
+    cpl_imagelist * ld = cpl_imagelist_new();
+    cpl_imagelist * le = cpl_imagelist_new();
+    cpl_vector * od = NULL, * oe = NULL;
+    cpl_array * oc = NULL;
+    cpl_error_code fail;
+    cpl_imagelist_set(ld, data, 0);
+    cpl_imagelist_set(le, data_error, 0);
+
+
+    fail = hdrl_collapse_imagelist_to_vector_call(red, ld, le, &od, &oe, &oc,
+                                                  eout);
+    cpl_imagelist_unwrap(ld);
+    cpl_imagelist_unwrap(le);
+
+    if (fail == CPL_ERROR_NONE) {
+        *result = cpl_vector_get(od, 0);
+        *error = cpl_vector_get(oe, 0);
+        *contribution = cpl_array_get_int(oc, 0, NULL);
+    }
+    else {
+        *result = NAN;
+        *error = NAN;
+        *contribution = 0;
+    }
+
+    cpl_vector_delete(od);
+    cpl_vector_delete(oe);
+    cpl_array_delete(oc);
+
+    return fail;
+}
diff --git a/hdrl/hdrl_overscan.h b/hdrl/hdrl_overscan.h
new file mode 100644
index 0000000..2385572
--- /dev/null
+++ b/hdrl/hdrl_overscan.h
@@ -0,0 +1,146 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2012,2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_OVERSCAN_H
+#define HDRL_OVERSCAN_H
+
+/*-----------------------------------------------------------------------------
+                                Include
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_utils.h"
+#include "hdrl_image.h"
+
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                                Define
+ -----------------------------------------------------------------------------*/
+
+#define HDRL_OVERSCAN_FULL_BOX -1
+typedef struct _hdrl_overscan_compute_result_ hdrl_overscan_compute_result;
+typedef struct _hdrl_overscan_correct_result_ hdrl_overscan_correct_result;
+
+/*-----------------------------------------------------------------------------
+                            Functions prototypes
+ -----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+                           Overscan Computation Parameters
+  ----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_overscan_parameter_create(hdrl_direction, double, int, 
+        hdrl_parameter *, hdrl_parameter *) ;
+cpl_error_code hdrl_overscan_parameter_verify(const hdrl_parameter *,
+        cpl_size, cpl_size) ;
+cpl_boolean hdrl_overscan_parameter_check(const hdrl_parameter *) ;
+
+/* Accessors */
+hdrl_direction hdrl_overscan_parameter_get_correction_direction(
+        const hdrl_parameter *) ;
+double hdrl_overscan_parameter_get_ccd_ron(const hdrl_parameter *) ;
+int hdrl_overscan_parameter_get_box_hsize(const hdrl_parameter *) ;
+hdrl_parameter * hdrl_overscan_parameter_get_collapse(const hdrl_parameter *) ;
+hdrl_parameter * hdrl_overscan_parameter_get_rect_region(const hdrl_parameter*);
+
+/* Parameter Lists */
+cpl_parameterlist * hdrl_overscan_parameter_create_parlist(const char *, 
+        const char *, const char *, int, double,
+        hdrl_parameter *, const char *, hdrl_parameter *, hdrl_parameter *) ;
+hdrl_parameter * hdrl_overscan_parameter_parse_parlist(
+        const cpl_parameterlist *, const char *) ;
+
+/*----------------------------------------------------------------------------
+                           Overscan Computation
+  ----------------------------------------------------------------------------*/
+hdrl_overscan_compute_result * hdrl_overscan_compute(
+        const cpl_image         *   source,
+        const hdrl_parameter    *   params) ;
+
+/*----------------------------------------------------------------------------
+                           Overscan Computation Result
+  ----------------------------------------------------------------------------*/
+hdrl_image * hdrl_overscan_compute_result_get_correction( 
+        const hdrl_overscan_compute_result *);
+hdrl_image * hdrl_overscan_compute_result_unset_correction( 
+        hdrl_overscan_compute_result *); 
+
+cpl_image * hdrl_overscan_compute_result_get_contribution(
+        const hdrl_overscan_compute_result *);
+cpl_image * hdrl_overscan_compute_result_unset_contribution(
+        hdrl_overscan_compute_result *); 
+
+cpl_image * hdrl_overscan_compute_result_get_chi2(
+        const hdrl_overscan_compute_result *);
+cpl_image * hdrl_overscan_compute_result_unset_chi2(
+        hdrl_overscan_compute_result *); 
+
+cpl_image * hdrl_overscan_compute_result_get_red_chi2(
+        const hdrl_overscan_compute_result *);
+cpl_image * hdrl_overscan_compute_result_unset_red_chi2(
+        hdrl_overscan_compute_result *); 
+
+cpl_image * hdrl_overscan_compute_result_get_sigclip_reject_low(
+        const hdrl_overscan_compute_result *);
+cpl_image * hdrl_overscan_compute_result_unset_sigclip_reject_low(
+        hdrl_overscan_compute_result *); 
+
+cpl_image * hdrl_overscan_compute_result_get_sigclip_reject_high(
+        const hdrl_overscan_compute_result *);
+cpl_image * hdrl_overscan_compute_result_unset_sigclip_reject_high(
+        hdrl_overscan_compute_result *); 
+
+cpl_image * hdrl_overscan_compute_result_get_minmax_reject_low(
+        const hdrl_overscan_compute_result *);
+cpl_image * hdrl_overscan_compute_result_unset_minmax_reject_low(
+        hdrl_overscan_compute_result *); 
+
+cpl_image * hdrl_overscan_compute_result_get_minmax_reject_high(
+        const hdrl_overscan_compute_result *);
+cpl_image * hdrl_overscan_compute_result_unset_minmax_reject_high(
+        hdrl_overscan_compute_result *); 
+
+void hdrl_overscan_compute_result_delete(hdrl_overscan_compute_result *);
+
+/*----------------------------------------------------------------------------
+                           Overscan Correction
+  ----------------------------------------------------------------------------*/
+hdrl_overscan_correct_result * hdrl_overscan_correct(
+        const hdrl_image                        *   source,
+        const hdrl_parameter                    *   region,
+        const hdrl_overscan_compute_result      *   os_computation) ;
+
+/*----------------------------------------------------------------------------
+                           Overscan Correction Result
+  ----------------------------------------------------------------------------*/
+hdrl_image * hdrl_overscan_correct_result_get_corrected(
+        const hdrl_overscan_correct_result *);
+hdrl_image * hdrl_overscan_correct_result_unset_corrected(
+        hdrl_overscan_correct_result *);
+
+cpl_image * hdrl_overscan_correct_result_get_badmask(
+        const hdrl_overscan_correct_result *);
+cpl_image * hdrl_overscan_correct_result_unset_badmask(
+        hdrl_overscan_correct_result *);
+void hdrl_overscan_correct_result_delete(hdrl_overscan_correct_result *);
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_overscan_defs.h b/hdrl/hdrl_overscan_defs.h
new file mode 100644
index 0000000..5e9506f
--- /dev/null
+++ b/hdrl/hdrl_overscan_defs.h
@@ -0,0 +1,79 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_OVERSCAN_DEFS_H
+#define HDRL_OVERSCAN_DEFS_H
+
+#ifndef HDRL_USE_PRIVATE
+#error This file is not allowed to be included outside of hdrl
+#endif
+
+#include "hdrl_types.h"
+#include "hdrl_image.h"
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/** @cond PRIVATE */
+
+/*----------------------------------------------------------------------------*/
+/**
+  @struct _hdrl_overscan_compute_result_
+  @brief Contains the Overscan Computation results
+ */
+/*----------------------------------------------------------------------------*/
+struct _hdrl_overscan_compute_result_
+{
+    /** The direction in which the image were collapsed in the computation */
+    hdrl_direction      correction_direction;     
+    /** The overscan correction as a 1D double image */
+    hdrl_image       *   correction;
+    /** The number of good pixels that contributed as a 1D double image */
+    cpl_image       *   contribution;
+    /** The \f$\chi^{2}\f$ as a 1D double image */
+    cpl_image       *   chi2;
+    /** The reduced \f$\chi^{2}\f$ as a 1D double image */
+    cpl_image       *   red_chi2;
+    /** The low threshold below which the pixels are rejected 
+        as a 1D double image. Only for sigma-clipping collapsing method */
+    cpl_image       *   sigclip_reject_low;
+    /** The high threshold above which the pixels are rejected 
+        as a 1D double image. Only for sigma-clipping collapsing method */
+    cpl_image       *   sigclip_reject_high;
+};
+
+/*----------------------------------------------------------------------------*/
+/**
+  @struct _hdrl_overscan_correct_result_
+  @brief Contains the Overscan Correction results
+ */
+/*----------------------------------------------------------------------------*/
+struct _hdrl_overscan_correct_result_
+{
+    /** The Overscan corrected image */
+    hdrl_image   *   corrected;
+    /** Pixels marked as bad by algorithm, encoded by user choice */
+    cpl_image   *   badmask;
+};
+
+/** @endcond */
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_parameter.c b/hdrl/hdrl_parameter.c
new file mode 100644
index 0000000..fda21e0
--- /dev/null
+++ b/hdrl/hdrl_parameter.c
@@ -0,0 +1,163 @@
+/* $Id: hdrl_parameter.c,v 1.3 2013-10-10 13:47:35 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-10 13:47:35 $
+ * $Revision: 1.3 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_parameter.h"
+#include "hdrl_parameter_defs.h"
+#include <cpl.h>
+
+#include <stddef.h>
+#include <assert.h>
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_parameter   Parameter object
+ *
+ * The hdrl_parameter is the base object to store various hierarchical
+ * parameters. It only provides the deletion functions, the parameters
+ * themselves are implemented in their respective modules.
+ *
+ * @internal
+ * see hdrl_parameter-test.c for an example usage
+ */
+/*----------------------------------------------------------------------------*/
+
+/*-----------------------------------------------------------------------------
+                                   Functions
+ -----------------------------------------------------------------------------*/
+
+/**@{*/
+
+/** @cond PRIVATE */
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief create new parameter of certain type
+ *
+ * @param type  type object which defines the type of the parameter
+ *
+ * @return hdrl_parameter of type 'typeobj'
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_parameter_new(const hdrl_parameter_typeobj * typeobj)
+{
+    hdrl_parameter * p = typeobj->fp_alloc(typeobj->obj_size);
+    p->base = typeobj;
+    return p;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief check if a parameter is of a certain type
+ *
+ * @param self  parameter to check
+ * @param type  type required
+ *
+ * @return true iff parameter is of type "type"
+ */
+/* ---------------------------------------------------------------------------*/
+int hdrl_parameter_check_type(const hdrl_parameter * self,
+                              const hdrl_parameter_typeobj * type)
+{
+    /* we can't compare the base pointers as they may be different in recipes
+     * and libraries when static linking */
+    if (self) {
+        return ((hdrl_parameter_typeobj *)self->base)->type == type->type;
+    }
+    else {
+        return 0;
+    }
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief get typeobject of parameter
+ *
+ * @param self  parameter to check
+ * @return pointer to type object
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+const hdrl_parameter_typeobj * hdrl_parameter_get_type(const hdrl_parameter * self)
+{
+    return self->base;
+}
+
+/** @endcond */
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief shallow delete of a parameter
+ *
+ * @param obj parameter to delete, may be NULL
+ *
+ * will not delete sub parameters
+ * @see hdrl_parameter_destroy
+ */
+/* ---------------------------------------------------------------------------*/
+void hdrl_parameter_delete(hdrl_parameter * obj)
+{
+    if (obj) {
+        obj->base->fp_free(obj);
+    }
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief deep delete of a parameter
+ *
+ * @param obj parameter to delete, may be NULL
+ *
+ * deletes all sub parameters via the registered deep destructor
+ */
+/* ---------------------------------------------------------------------------*/
+void hdrl_parameter_destroy(hdrl_parameter * obj)
+{
+    if (obj == NULL) {
+        return;
+    }
+
+    if (obj->base->fp_destroy) {
+        obj->base->fp_destroy(obj);
+    }
+    else {
+        obj->base->fp_free(obj);
+    }
+}
+
+/**@}*/
diff --git a/hdrl/hdrl_parameter.h b/hdrl/hdrl_parameter.h
new file mode 100644
index 0000000..21d9c02
--- /dev/null
+++ b/hdrl/hdrl_parameter.h
@@ -0,0 +1,139 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_PARAMETER_H
+#define HDRL_PARAMETER_H
+
+/*-----------------------------------------------------------------------------
+                                   New types
+ -----------------------------------------------------------------------------*/
+
+typedef struct _hdrl_parameter_ hdrl_parameter;
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_types.h"
+#include "hdrl_utils.h"
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                                   Functions
+ -----------------------------------------------------------------------------*/
+
+void hdrl_parameter_delete(hdrl_parameter * obj);
+void hdrl_parameter_destroy(hdrl_parameter * obj);
+
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+ -----------------------------------------------------------------------------*/
+#ifdef HDRL_USE_PRIVATE
+
+/**
+ * @brief parameter registry
+ * required as typeobject pointer is not unique when doing static linking
+ */
+typedef enum {
+    HDRL_PARAMETER_COLLAPSE_MEAN,
+    HDRL_PARAMETER_COLLAPSE_MEDIAN,
+    HDRL_PARAMETER_COLLAPSE_WEIGHTED_MEAN,
+    HDRL_PARAMETER_COLLAPSE_SIGCLIP,
+    HDRL_PARAMETER_COLLAPSE_MINMAX,
+    HDRL_PARAMETER_RECT_REGION,
+    HDRL_PARAMETER_OVERSCAN,
+    HDRL_PARAMETER_BPM_2D,
+    HDRL_PARAMETER_BPM_3D,
+    HDRL_PARAMETER_BPM_FIT,
+    HDRL_PARAMETER_LACOSMIC,
+    HDRL_PARAMETER_STREHL
+} hdrl_parameter_enum;
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief required first member of each parameter object
+ *
+ *   struct {
+ *     HDRL_PARAMETER_HEAD;
+ *     int val;
+ *   } my_parameter;
+ */
+/* ---------------------------------------------------------------------------*/
+#define HDRL_PARAMETER_HEAD void * base
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief Base type object / object metadata
+ *
+ * Defines required object meta data of the parameter.
+ * Each object contains a reference to one of these so it can determine which
+ * functions to call on certain operations.
+ * Usually a single statically allocated type object shared between multiple
+ * hdrl_parameter objects of the same type.
+ * @see hdrl_parameter_new
+ */
+/* ---------------------------------------------------------------------------*/
+typedef struct {
+    /* enum defining type */
+    hdrl_parameter_enum type;
+    /* base parameter structure allocation, e.g. cpl_malloc */
+    hdrl_alloc * fp_alloc;
+    /* shallow destructor of the parameter */
+    hdrl_free  * fp_free;
+    /* deep destructor of the parameter, deletes all childs
+     * may be NULL in which case fp_free is used */
+    hdrl_free  * fp_destroy;
+    /* size of the base parameter structure, argument to fp_alloc */
+    size_t obj_size;
+} hdrl_parameter_typeobj;
+
+
+/* empty parameter, e.g. for collapse_mean */
+typedef struct {
+    HDRL_PARAMETER_HEAD;
+} hdrl_parameter_empty;
+
+hdrl_parameter *
+hdrl_parameter_new(const hdrl_parameter_typeobj * typeobj);
+
+const hdrl_parameter_typeobj *
+hdrl_parameter_get_type(const hdrl_parameter * self);
+
+int
+hdrl_parameter_check_type(const hdrl_parameter * self,
+                              const hdrl_parameter_typeobj * type);
+
+/* create a singleton parameter which does not need allocating or deleting a
+ * comon use case are enum like parameters */
+#define HDRL_PARAMETER_SINGLETON(name, type, alloc) \
+hdrl_parameter * name = &(hdrl_parameter){ &type }; \
+static void * alloc(size_t HDRL_UNUSED(n)) \
+{ \
+    return name; \
+}
+
+#endif
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_parameter_defs.h b/hdrl/hdrl_parameter_defs.h
new file mode 100644
index 0000000..f7b38a3
--- /dev/null
+++ b/hdrl/hdrl_parameter_defs.h
@@ -0,0 +1,51 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_PARAMETER_DEFS_H
+#define HDRL_PARAMETER_DEFS_H
+
+#ifndef HDRL_USE_PRIVATE
+#error This file is not allowed to be included outside of hdrl
+#endif
+
+#include "hdrl_parameter.h"
+
+#include <stdint.h>
+
+/** @cond PRIVATE */
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief base class of hdrl_parameter
+ *
+ * needs to be the first element of each child class structure, e.g:
+ *   struct {
+ *     HDRL_PARAMETER_HEAD;
+ *     int val;
+ *   } child_class;
+ */
+/* ---------------------------------------------------------------------------*/
+struct _hdrl_parameter_  {
+    const hdrl_parameter_typeobj * base;
+};
+
+/** @endcond */
+
+#endif
diff --git a/hdrl/hdrl_prototyping.c b/hdrl/hdrl_prototyping.c
new file mode 100644
index 0000000..da091d3
--- /dev/null
+++ b/hdrl/hdrl_prototyping.c
@@ -0,0 +1,1269 @@
+/*
+ * hdrl_prototyping.c
+ *
+ *  Created on: Aug 29, 2013
+ *      Author: agabasch
+ */
+
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include <errno.h>
+#include <complex.h>
+#include <hdrl_prototyping.h>
+
+/*-----------------------------------------------------------------------------
+                                Defines
+ -----------------------------------------------------------------------------*/
+#define freeimage(_p) if (_p != NULL) {cpl_image_delete(_p); _p = NULL;}
+
+
+/*-----------------------------------------------------------------------------
+                                   Static
+ -----------------------------------------------------------------------------*/
+
+
+static cpl_image *hdrl_mirror_edges(cpl_image *image, int dx, int dy);
+static cpl_image *hdrl_gen_lowpass(int xs, int ys, double sigma_x,
+                                   double sigma_y);
+
+
+
+/**      Function to calculate the low spatial frequency
+*
+* @brief      Get low spatial frequency componenets from an image using the FFTW
+* @param    ima         image
+* @param    gausfilt   Gaussian Fourier filter size
+* @param    mirrorx    for mirroring edges (ocfft continuity)
+* @param    mirrory    for mirroring edges (ocfft continuity)
+*
+* @return       1 newly allocated image.
+*/
+cpl_image * hdrl_get_spatial_freq(cpl_image *ima, double gausfilt, int mirrorx,
+                                  int mirrory){
+
+    int xsize=0, ysize=0;
+
+    double sigma_x = 0.;
+    double sigma_y = 0.;
+
+    cpl_image *clean_flat=NULL;
+    cpl_image *eflat=NULL;
+    cpl_image *eflat_complex=NULL;
+    cpl_image *eflat_real=NULL;
+
+    cpl_image *filter_image=NULL;
+    cpl_image *filter_image_complex=NULL;
+    cpl_image *flat_real;
+
+
+    /*Clean flat from bad pixels if bpm exists*/
+    //clean_flat = cpl_image_duplicate(flat);
+
+    /*The algorithm uses float, so we have to cast here or change the algo...*/
+    cpl_type ima_type = cpl_image_get_type(ima);
+
+    clean_flat = cpl_image_cast(ima, CPL_TYPE_FLOAT);
+        cpl_detector_interpolate_rejected(clean_flat);
+
+
+    /* Expand the flat image using the mirror edges function */
+    eflat = hdrl_mirror_edges(clean_flat, mirrorx, mirrory);
+    if(eflat == NULL){
+        freeimage(clean_flat);
+        cpl_msg_error(cpl_func,"Filter image is NULL");
+        return NULL;
+    }
+
+    freeimage(clean_flat);
+
+    xsize = cpl_image_get_size_x(eflat);
+    ysize = cpl_image_get_size_y(eflat);
+
+    sigma_x = gausfilt;
+    sigma_y = (double)(sigma_x * ysize) / xsize;
+
+
+    /* Generate a lowpass filter to be used in the FFT convolution */
+    filter_image = hdrl_gen_lowpass(xsize, ysize, sigma_x, sigma_y);
+    if(filter_image == NULL){
+        cpl_msg_error(cpl_func,"Filter image is NULL");
+        return NULL;
+    }
+
+    eflat_complex = cpl_image_new(xsize,ysize, CPL_TYPE_FLOAT_COMPLEX);
+    eflat_real = cpl_image_new(xsize,ysize, CPL_TYPE_FLOAT);
+    filter_image_complex =cpl_image_cast(filter_image,CPL_TYPE_FLOAT_COMPLEX);
+
+    /*Free memory*/
+    cpl_image_delete(filter_image);
+
+
+    /* Apply a forward FFT on the images  */
+    cpl_fft_image(eflat_complex, eflat, CPL_FFT_FORWARD);
+    /*Free memory*/
+    cpl_image_delete(eflat);
+
+    /*Multiply the filter with the the FFT image */
+    cpl_image_multiply(eflat_complex,filter_image_complex);
+
+
+    /* Apply a backward FFT on the images  */
+    cpl_fft_image(eflat_real, eflat_complex,CPL_FFT_BACKWARD);
+    /*Free memory*/
+    cpl_image_delete(eflat_complex);
+    cpl_image_delete(filter_image_complex);
+
+    /*  Extract original image from the expanded image.  */
+    flat_real = cpl_image_extract(eflat_real, mirrorx+1, mirrory+1,
+            xsize-mirrorx, ysize-mirrory);
+
+    if (flat_real == NULL) {
+        cpl_msg_error (cpl_func,"Real extracted image is NULL. <%s>", cpl_error_get_message());
+        return NULL;
+    }
+    cpl_image_delete(eflat_real);
+
+    cpl_image * out_double = cpl_image_cast(flat_real, ima_type);
+    cpl_image_delete(flat_real);
+    return out_double;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+ at brief	Generate a low pass filter for FFT convolution .
+ at param	xs	x size of the generated image.
+ at param	ys	y size of the generated image.
+ at param	sigma_x	Sigma for the gaussian distribution.
+ at param	sigma_y      Sigma for the gaussian distribution.
+ at return	1 newly allocated image.
+
+This function generates an image of a 2d gaussian, modified in such
+a way that the different quadrants have a quadrants of the gaussian
+in the corner. This image is suitable for FFT convolution.
+Copied from eclipse, src/iproc/generate.c
+
+The returned image must be deallocated.
+*/
+/*--------------------------------------------------------------------------*/
+static cpl_image * hdrl_gen_lowpass(int xs, int ys, double sigma_x,
+                                    double sigma_y)
+{
+
+	int i= 0.0;
+	int j= 0.0;
+	int hlx= 0.0;
+	int hly = 0.0;
+	double x= 0.0;
+	double y= 0.0;
+	double gaussval= 0.0;
+	float *data;
+
+	cpl_image 	*lowpass_image;
+
+
+	lowpass_image = cpl_image_new (xs, ys, CPL_TYPE_FLOAT);
+	if (lowpass_image == NULL) {
+		cpl_msg_error (cpl_func, "Cannot generate lowpass filter <%s>",cpl_error_get_message());
+		return NULL;
+	}
+
+	hlx = xs/2;
+	hly = ys/2;
+
+	data = cpl_image_get_data_float(lowpass_image);
+
+	/* Given an image with pixels 0<=i<N, 0<=j<M then the convolution image
+   has the following properties:
+
+   ima[0][0] = 1
+   ima[i][0] = ima[N-i][0] = exp (-0.5 * (i/sig_i)^2)   1<=i<N/2
+   ima[0][j] = ima[0][M-j] = exp (-0.5 * (j/sig_j)^2)   1<=j<M/2
+   ima[i][j] = ima[N-i][j] = ima[i][M-j] = ima[N-i][M-j]
+             = exp (-0.5 * ((i/sig_i)^2 + (j/sig_j)^2))
+	 */
+
+	data[0] = (float)1.0;
+
+	/* first row */
+	for (i=1 ; i<=hlx ; i++) {
+		x = (double)i / sigma_x;
+		gaussval = (double)exp(-0.5*x*x);
+		data[i] = gaussval;
+		data[xs-i] = gaussval;
+	}
+
+	for (j=1; j<=hly ; j++) {
+		y = (double)j / sigma_y;
+		/* first column */
+		data[j*xs] = (double)exp(-0.5*y*y);
+		data[(ys-j)*xs] = (double)exp(-0.5*y*y);
+
+		for (i=1 ; i<=hlx ; i++) {
+			/* Use internal symetries */
+			x = (double) i / sigma_x;
+			gaussval = (double)exp (-0.5*(x*x+y*y));
+			data[j*xs+i] = gaussval;
+			data[(j+1)*xs-i] = gaussval;
+			data[(ys-j)*xs+i] = gaussval;
+			data[(ys+1-j)*xs-i] = gaussval;
+
+		}
+	}
+
+	/* FIXME: for the moment, reset errno which is coming from exp()
+            in first for-loop at i=348. This is causing cfitsio to
+            fail when loading an extension image (bug in cfitsio too).
+	 */
+	if(errno != 0)
+		errno = 0;
+
+	return lowpass_image;
+}
+
+
+
+/**
+ at brief    expand image by mirroring edges
+ at param    image_in      Image.
+ at param    x_size        the number of pixels in x to expand
+ at param    y_size        the number of pixels in y to expand
+
+*/
+/*--------------------------------------------------------------------------*/
+cpl_image *hdrl_mirror_edges(cpl_image *image, int dx, int dy)
+{
+
+	intptr_t xs = cpl_image_get_size_x(image);
+	intptr_t ys = cpl_image_get_size_y(image);
+	intptr_t xx = xs+(2*dx);
+	intptr_t yy = ys+(2*dy);
+	float * data = cpl_image_get_data_float(image);
+	cpl_image * big_image = cpl_image_new(xx, yy, CPL_TYPE_FLOAT);
+	float * out_data = cpl_image_get_data_float(big_image);
+
+	for (intptr_t j=0; j<ys ; j++){
+		intptr_t inrow = j*xs;
+		intptr_t outrow = (j+dy)*xx;
+
+		for (intptr_t i=0; i<xs ; i++){
+			out_data[outrow+dx+i] = data[inrow+i];
+		}
+
+		for (intptr_t i=0; i<dx; i++){
+			out_data[outrow+i] = data[inrow+dx-i-1];
+			out_data[outrow+xs+dx+i] = data[inrow+xs-i-1];
+
+		}
+	}
+
+	for (intptr_t j=0; j<dy ; j++) {
+
+		for (intptr_t i=0; i<xx; i++) {
+			out_data[j*xx+i] = out_data[(2*dy-j-1)*xx+i];
+			out_data[(yy-j-1)*xx+i] = out_data[(yy-2*dy+j)*xx+i];
+		}
+	}
+
+	return big_image;
+}
+
+
+
+cpl_image * hdrl_mime_image_polynomial_bkg(cpl_image * image,
+                                             int dim_X, int dim_Y,
+                                             cpl_matrix ** coeffs){
+    cpl_imagelist * imlist;
+    cpl_imagelist * bkg_imlist;
+    cpl_image * bkg_image;
+    cpl_image * bkg_image_origtype;
+
+    cpl_type ima_type;
+    if (image == NULL){
+        cpl_error_set_message(cpl_func,
+                              CPL_ERROR_NULL_INPUT,
+                              "Null input image provided");
+        return NULL;
+    }
+
+    ima_type = cpl_image_get_type(image);
+
+    imlist = cpl_imagelist_new();
+    bkg_imlist = cpl_imagelist_new();
+    cpl_imagelist_set(imlist, image, 0);
+
+    hdrl_mime_compute_polynomial_bkg(imlist, bkg_imlist, dim_X, dim_Y, coeffs);
+
+    cpl_imagelist_unwrap(imlist);
+    bkg_image = cpl_imagelist_unset(bkg_imlist, 0);
+    cpl_imagelist_delete(bkg_imlist);
+
+    bkg_image_origtype=cpl_image_cast(bkg_image, ima_type);
+    cpl_image_delete(bkg_image);
+
+    return bkg_image_origtype;
+
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @brief    Fit smooth background for a list of images.
+ *
+ * @param      images      List of images.
+ * @param[out] bkg_images  Smooth background images.
+ * @param      dim_X,dim_Y dimensions of polynomials in @f$x at f$ and @f$y at f$.
+ * @param[out] coeffs      Polynomial coefficients.
+ *
+ * @return   @c CPL_ERROR_NONE or the appropriate error code.
+ *
+ * This function computes smooth background images by fitting
+ * polynomial surfaces to the input images. Bad-pixel masks for the
+ * images are taken into account.
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_mime_compute_polynomial_bkg(
+    const cpl_imagelist       * images,
+          cpl_imagelist       * bkg_images,
+          int                   dim_X,
+          int                   dim_Y,
+          cpl_matrix         ** coeffs
+    )
+{
+
+    int         n_images;
+    int         n_x;
+    int         n_y;
+    cpl_matrix * poly_tensors;
+    int          n_tensor;
+    int             im;
+    cpl_matrix    * weights;
+
+    cpl_msg_debug(cpl_func, "Polynomial with X, Y dimensions %2d, %2d.",
+                  dim_X, dim_Y);
+
+    /* Sanity Check of input data, and parameters */
+
+    if (images == NULL) {
+        cpl_msg_error(cpl_func, "list of dithered images is empty") ;
+        return cpl_error_set(cpl_func, CPL_ERROR_DATA_NOT_FOUND);
+    }
+
+    if (cpl_imagelist_is_uniform(images) != 0) {
+        cpl_msg_error(cpl_func, "input image list have non uniform data") ;
+        return cpl_error_set(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT);
+    }
+
+
+    /*
+       Compute Dimensions
+    */
+    n_images = cpl_imagelist_get_size(images);
+    n_x      = cpl_image_get_size_x(cpl_imagelist_get_const(images, 0));
+    n_y      = cpl_image_get_size_y(cpl_imagelist_get_const(images, 0));
+
+    /*
+      Create tensor products of polynomials
+    */
+    poly_tensors  = hdrl_mime_legendre_tensors_create(n_x, n_y, dim_X, dim_Y);
+    n_tensor      = cpl_matrix_get_ncol(poly_tensors);
+    *coeffs        = cpl_matrix_new(n_tensor, n_images);
+
+    weights = hdrl_mime_tensor_weights_create(n_x, n_y);
+
+    /*
+       Loop over each image to find the corresponding
+       sky background
+    */
+
+    for (im = 0; im < n_images; im++){
+        cpl_matrix    * image_data;
+        cpl_matrix    * bkg_image_data;
+        cpl_matrix    * masked_tensors;
+        cpl_matrix    * masked_image;
+        cpl_matrix    * image_double_wrap;
+        cpl_matrix    * coeff;
+        cpl_image     * image;
+        cpl_image     * bkg_image;
+        cpl_image     * image_double;
+        cpl_image     * bkg_image_float;
+        cpl_mask      * mask_bin;
+        double          alpha = 1.0e-10;
+
+        image_data     = cpl_matrix_new(n_x*n_y, 1);
+        bkg_image_data = cpl_matrix_new(n_x*n_y, 1);
+        masked_image   = cpl_matrix_new(n_x * n_y, 1);
+        masked_tensors = cpl_matrix_new(n_x * n_y, n_tensor);
+
+
+        /*
+          Load image, and mask
+        */
+
+        image      = cpl_image_duplicate(cpl_imagelist_get_const(images, im));
+        mask_bin   = cpl_image_get_bpm(image);
+        if (mask_bin == NULL) {
+            cpl_msg_info(cpl_func, "mask not available");
+            cpl_matrix_delete(poly_tensors);
+            cpl_matrix_delete(image_data);
+            cpl_matrix_delete(bkg_image_data);
+            cpl_matrix_delete(masked_image);
+            cpl_matrix_delete(masked_tensors);
+            cpl_image_delete(image);
+            cpl_error_set(cpl_func, CPL_ERROR_DATA_NOT_FOUND);
+        }
+
+        image_double = cpl_image_cast(image, CPL_TYPE_DOUBLE);
+        image_double_wrap = cpl_matrix_wrap(n_x*n_y, 1,
+                             cpl_image_get_data_double(image_double));
+        cpl_matrix_copy(image_data, image_double_wrap, 0, 0);
+
+        /*
+          Loop over all pixels, to reject from mask.
+        */
+        cpl_matrix_copy(masked_tensors, poly_tensors, 0, 0);
+        hdrl_mime_matrix_mask_rows(masked_tensors, mask_bin);
+        hdrl_mime_matrix_rescale_rows(masked_tensors, weights, masked_tensors);
+
+        cpl_matrix_copy(masked_image, image_data, 0, 0);
+        hdrl_mime_matrix_mask_rows(masked_image, mask_bin);
+        hdrl_mime_matrix_rescale_rows(masked_image, weights, masked_image);
+
+        /*
+          Find coefficients, agument the matrix of coefficients
+        */
+        coeff = hdrl_mime_linalg_solve_tikhonov(masked_tensors, masked_image,
+                                              alpha);
+        cpl_matrix_copy(*coeffs, coeff, 0, im);
+
+
+        /* hdrl_mime_matrix_formatted_dump(coeff, NULL); */
+
+        /*
+          Synthesize background, copy to image, and then to return imagelist
+        */
+        hdrl_mime_matrix_product(poly_tensors, coeff, bkg_image_data);
+        bkg_image = cpl_image_wrap_double(n_x, n_y,
+                    cpl_matrix_get_data(bkg_image_data));
+        bkg_image_float = cpl_image_cast(bkg_image, CPL_TYPE_FLOAT);
+        cpl_imagelist_set(bkg_images, bkg_image_float, im);
+
+        cpl_matrix_delete(image_data);
+        cpl_matrix_delete(bkg_image_data);
+        cpl_matrix_delete(masked_image);
+        cpl_matrix_delete(masked_tensors);
+        cpl_matrix_delete(coeff);
+        cpl_image_delete(image);
+        cpl_image_delete(image_double);
+        cpl_matrix_unwrap(image_double_wrap);
+        cpl_image_unwrap(bkg_image);
+
+    }
+
+    /* save results, destroy whatever is not necessary, return */
+
+    cpl_matrix_delete(weights);
+    cpl_matrix_delete(poly_tensors);
+    return CPL_ERROR_NONE;
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * @brief Create tensor products of Legendre polynomials.
+ *
+ * @param nx    Number of nodes in the x-direction.
+ * @param ny    Number of x nodes in the y-direction.
+ * @param npx   Number of tensor products of functions of x.
+ * @param npy   Number of tensor products of functions of y.
+ *
+ * @return The tensor products of Legendre polynomials.
+ *
+ * The returned matrix must be deallocated using cpl_matrix_delete().
+ */
+/*---------------------------------------------------------------------------*/
+cpl_matrix *hdrl_mime_legendre_tensors_create(int nx, int ny, int npx, int npy)
+{
+    cpl_matrix *x;
+    cpl_matrix *y;
+    cpl_matrix *xpolys;
+    cpl_matrix *ypolys;
+    cpl_matrix *tensors;
+
+    double    ax, ay, bx, by;
+
+/* testing input */
+    if (nx < 2 || ny < 2 || npx < 1 || npy < 1)
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_ILLEGAL_INPUT);
+        return NULL;
+    }
+
+/* setting parameters:
+   nx, ny          numbers of the nodes in the x- and y-direction
+   ax, ay, bx, by  endpoints of the intervals with nodes
+ */
+    ax = 0.0;
+    bx = nx - 1.0;
+
+    ay = 0.0;
+    by = ny - 1.0;
+
+/* creating equally spaced nodes */
+    x = hdrl_mime_matrix_linspace_create(nx, ax, bx);
+    y = hdrl_mime_matrix_linspace_create(ny, ay, by);
+
+/* creating the tensor products */
+    xpolys = hdrl_mime_legendre_polynomials_create(npx, ax, bx, x);
+    ypolys = hdrl_mime_legendre_polynomials_create(npy, ay, by, y);
+    tensors = hdrl_mime_linalg_pairwise_column_tensor_products_create(ypolys,
+              xpolys);
+
+/* cleaning up */
+    cpl_matrix_delete(x);
+    cpl_matrix_delete(y);
+    cpl_matrix_delete(xpolys);
+    cpl_matrix_delete(ypolys);
+
+    return tensors;
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * @brief Create equally spaced nodes.
+ *
+ * @param n   The number of nodes,
+ * @param a   The leftmost node,
+ * @param b   The rightmost node.
+ *
+ * @return A column matrix with the equally spaced nodes.
+ *
+ * The number of nodes @a n must be at least 2.
+ */
+/*---------------------------------------------------------------------------*/
+cpl_matrix *hdrl_mime_matrix_linspace_create(int n, double a, double b)
+{
+    cpl_matrix *nodes;
+    double   *data;
+    double    h;
+    int       i;
+
+/* testing input */
+    if (n < 2)
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_ILLEGAL_INPUT);
+        return NULL;
+    }
+
+/* allocating memory */
+    nodes = cpl_matrix_new(n, 1);
+    data = cpl_matrix_get_data(nodes);
+
+/* creating the nodes */
+    h = (b - a) / (n - 1);
+    for (i = 0; i < n; i++)
+        data[i] = a + i * h;
+    data[n - 1] = b;
+
+    return nodes;
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * @brief    Create the Legendre polynomial basis on the interval (@a a, at a b).
+ *
+ * @param    npoly Number of polynomials.
+ * @param    a     Left endpoint of the interval.
+ * @param    b     Right endpoint of the interval.
+ * @param    x     Nodes, at which the polynomials are evaluated.
+ *
+ * @return   A matrix with the values of the polynomials at @a x.
+ *
+ * The i-th column contains the values of the i-th polynomial at the
+ * given nodes.  The polynomials have degrees 0, 1, ..., npoly-1.  The
+ * nodes must lie on the interval [@a a, @a b].  The specific dimensions of
+ * the matrix @a x are not used, only its size.
+ *
+ * The returned matrix must be deallocated using cpl_matrix_delete().
+ */
+/*---------------------------------------------------------------------------*/
+cpl_matrix *hdrl_mime_legendre_polynomials_create(int npoly, double a, double b,
+          const cpl_matrix * x)
+{
+    cpl_matrix *polys;
+    double   *m;
+    const double *mx;
+    double    midpoint, scale;
+    int       i, j, nr;
+
+/* testing input */
+    if (x == NULL)
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_NULL_INPUT);
+        return NULL;
+    }
+
+    if (npoly < 1 || a == b)
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_ILLEGAL_INPUT);
+        return NULL;
+    }
+
+/* The specific dimensions of the matrix x are not used, only its size. */
+    nr = cpl_matrix_get_nrow(x) * cpl_matrix_get_ncol(x);
+
+/* allocating memory */
+    polys = cpl_matrix_new(nr, npoly);
+
+/* initializing */
+    midpoint = 0.5 * (a + b);
+    scale = 2.0 / (b - a);
+
+/* filling the first column */
+    m = cpl_matrix_get_data(polys);
+    for (i = 0; i < nr; i++, m += npoly)
+        m[0] = 1.0;
+
+/* filling the second column */
+    m = cpl_matrix_get_data(polys);
+    mx = cpl_matrix_get_data_const(x);
+    if (npoly >= 2)
+        for (i = 0; i < nr; i++, m += npoly)
+            m[1] = scale * (mx[i] - midpoint);
+
+/* filling the remaining columns by recursion
+ * j P'_j(x) = (2j-1)xP'_{j-1}(x) - (j-1)P'_{j-2}(x)
+ * with P'(x) = P((2x - b - a)/(b - a)) for orthogonality in [-1, 1]->[a, b] */
+    m = cpl_matrix_get_data(polys);
+    for (i = 0; i < nr; i++, m += npoly)
+    {
+        double xi = scale * (mx[i] - midpoint);
+        for (j = 2; j < npoly; j++)
+        {
+            double alpha = (2.0 * j - 1.0) / j;
+            double beta = (j - 1.0) / j;
+            m[j] = alpha * xi * m[j - 1] - beta * m[j - 2];
+        }
+    }
+
+    return polys;
+}
+/*---------------------------------------------------------------------------*/
+ /**
+  * @brief    Create selected pairwise tensor products of the columns of two
+  *           matrices.
+  *
+  * @param    mat1        A matrix,
+  * @param    mat2        A matrix.
+  *
+  * @return   The tensor product of pairs the columns of the two matrices.
+  *
+  * The tensor product of the j1-th and j2-th columns is created iff
+  * j1*(nc2-1) + j2*(nc1-1) <= (nc1-1)*(nc2-1).  The two matrices may
+  * have different dimensions.
+  */
+/*---------------------------------------------------------------------------*/
+cpl_matrix *hdrl_mime_linalg_pairwise_column_tensor_products_create(const
+          cpl_matrix * mat1, const cpl_matrix * mat2)
+{
+    cpl_matrix *tensor;
+    cpl_matrix *repl1;
+    cpl_matrix *repl2;
+
+    int       nc1, nc2;
+    int       j1, j2, nc, col_count;
+
+/* testing input */
+    if (mat1 == NULL || mat2 == NULL)
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_NULL_INPUT);
+        return NULL;
+    }
+
+/* initializing */
+    nc1 = cpl_matrix_get_ncol(mat1);
+    nc2 = cpl_matrix_get_ncol(mat2);
+
+/* counting the admissible pairs */
+    nc = 0;
+    for (j1 = 0; j1 < nc1; j1++)
+    {
+        for (j2 = 0; j2 < nc2; j2++)
+            nc += (j1 * (nc2 - 1) + j2 * (nc1 - 1) <=
+                      (nc1 - 1) * (nc2 - 1) ? 1 : 0);
+    }
+
+/* replicating the columns */
+    repl1 = cpl_matrix_new(cpl_matrix_get_nrow(mat1), nc);
+    repl2 = cpl_matrix_new(cpl_matrix_get_nrow(mat2), nc);
+    col_count = 0;
+
+    for (j1 = 0; j1 < nc1; j1++)
+    {
+        for (j2 = 0; j2 < nc2; j2++)
+        {
+            if (j1 * (nc2 - 1) + j2 * (nc1 - 1) <= (nc1 - 1) * (nc2 - 1))
+            {
+                hdrl_mime_matrix_copy_column(mat1, j1, repl1, col_count);
+                hdrl_mime_matrix_copy_column(mat2, j2, repl2, col_count);
+                col_count++;
+            }
+        }
+    }
+
+/* filling the matrix with the tensor products */
+    tensor = hdrl_mime_linalg_tensor_products_columns_create(repl1, repl2);
+    cpl_matrix_delete(repl1);
+    cpl_matrix_delete(repl2);
+
+    return tensor;
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * @brief    Copy a column from one matrix to another matrix.
+ *
+ * @param    mat1        The matrix whose column is copied,
+ * @param    j_1         The index of the column to be copied,
+ * @param[in,out]  mat2        The matrix whose column is overwritten,
+ * @param[in,out]  j_2         The index of the column to be overwritten.
+ *
+ * @return   @c CPL_ERROR_NONE or the appropriate error code.
+ *
+ * Both matrices must have the same number of rows.
+ */
+/*---------------------------------------------------------------------------*/
+cpl_error_code hdrl_mime_matrix_copy_column(const cpl_matrix * mat1, int j_1,
+          cpl_matrix * mat2, int j_2)
+{
+    const double *m1;
+    double   *m2;
+    int       i, nr, nc1, nc2;
+
+/* testing input */
+    if (mat1 == NULL || mat2 == NULL)
+        return cpl_error_set(cpl_func, CPL_ERROR_NULL_INPUT);
+
+    if (cpl_matrix_get_nrow(mat1) != cpl_matrix_get_nrow(mat2))
+        return cpl_error_set(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT);
+
+    if (j_1 < 0 || j_1 >= cpl_matrix_get_ncol(mat1) || j_2 < 0 ||
+              j_2 >= cpl_matrix_get_ncol(mat2))
+        return cpl_error_set(cpl_func, CPL_ERROR_ILLEGAL_INPUT);
+
+/* initializing */
+    nr = cpl_matrix_get_nrow(mat1);
+    nc1 = cpl_matrix_get_ncol(mat1);
+    nc2 = cpl_matrix_get_ncol(mat2);
+    m1 = cpl_matrix_get_data_const(mat1) + j_1;
+    m2 = cpl_matrix_get_data(mat2) + j_2;
+
+/* filling the column */
+    for (i = 0; i < nr; i++, m1 += nc1, m2 += nc2)
+        *m2 = *m1;
+
+    return CPL_ERROR_NONE;
+}
+/*---------------------------------------------------------------------------*/
+ /**
+  * @brief    Create the tensor products of the columns of two matrices.
+  *
+  * @param    mat1        A matrix,
+  * @param    mat2        A matrix.
+  *
+  * @return   The tensor product of the columns of the two matrices.
+  *
+  * The two matrices must have the same number of columns.  The result
+  * has dimensions (nr1*nr2) x nc.
+  */
+/*---------------------------------------------------------------------------*/
+cpl_matrix *hdrl_mime_linalg_tensor_products_columns_create(const cpl_matrix *
+          mat1, const cpl_matrix * mat2)
+{
+    cpl_matrix *tensor;
+
+    const double *m1;
+    double   *t;
+    int       nr1, nr2, nc;
+    int       i1;
+
+/* testing input */
+    if (mat1 == NULL || mat2 == NULL)
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_NULL_INPUT);
+        return NULL;
+    }
+
+    if (cpl_matrix_get_ncol(mat1) != cpl_matrix_get_ncol(mat2))
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT);
+        return NULL;
+    }
+
+/* initializing */
+    nr1 = cpl_matrix_get_nrow(mat1);
+    nr2 = cpl_matrix_get_nrow(mat2);
+    nc = cpl_matrix_get_ncol(mat1);     /* nc = cpl_matrix_get_ncol(mat2); */
+
+/* allocating memory */
+    tensor = cpl_matrix_new(nr1 * nr2, nc);
+
+/* filling the matrix with the tensor products */
+    m1 = cpl_matrix_get_data_const(mat1);
+    t = cpl_matrix_get_data(tensor);
+    for (i1 = 0; i1 < nr1; i1++, m1 += nc)
+    {
+        int           i2;
+        const double *m2;
+        m2 = cpl_matrix_get_data_const(mat2);
+        for (i2 = 0; i2 < nr2; i2++, m2 += nc, t += nc)
+        {
+            int j;
+            for (j = 0; j < nc; j++)
+                t[j] = m1[j] * m2[j];
+        }
+    }
+
+    return tensor;
+}
+
+/*---------------------------------------------------------------------------*/
+/**
+ * @brief Create tensor product weights.
+ *
+ * @param nx    Number of nodes in the x-direction,
+ * @param ny    Number of x nodes in the y-direction,
+ *
+ * @return The tensor weights
+ *
+ * The returned matrix must be deallocated using cpl_matrix_delete().
+ */
+/*---------------------------------------------------------------------------*/
+cpl_matrix *hdrl_mime_tensor_weights_create(int nx, int ny)
+{
+    cpl_matrix *x;
+    cpl_matrix *y;
+    cpl_matrix *weights;
+
+    double   *m;
+    double    ax, ay, bx, by, v;
+    int       i;
+
+/* testing input */
+    if (nx < 2 || ny < 2)
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_ILLEGAL_INPUT);
+        return NULL;
+    }
+
+/* setting parameters:
+   nx, ny          numbers of the nodes in the x- and y-direction
+ */
+    bx = 1.0 - 1.0 / nx;
+    ax = -bx;
+
+    by = 1.0 - 1.0 / ny;
+    ay = -by;
+
+/* creating equally spaced nodes */
+    x = hdrl_mime_matrix_linspace_create(nx, ax, bx);
+    y = hdrl_mime_matrix_linspace_create(ny, ay, by);
+
+/* creating the weights as the tensor product */
+    m = cpl_matrix_get_data(x);
+    for (i = 0; i < nx; i++)
+    {
+        v = m[i];
+        v = 1.0 / sqrt(1.0 - v * v);
+        m[i] = sqrt(v);
+    }
+
+    m = cpl_matrix_get_data(y);
+    for (i = 0; i < ny; i++)
+    {
+        v = m[i];
+        v = 1.0 / sqrt(1.0 - v * v);
+        m[i] = sqrt(v);
+    }
+
+/* switch
+     no weights: 1
+     with weights: 0  */
+    if (1)
+    {
+        cpl_matrix_fill(x, 1.0);
+        cpl_matrix_fill(y, 1.0);
+    }
+
+    weights = hdrl_mime_linalg_pairwise_column_tensor_products_create(y, x);
+
+/* cleaning up */
+    cpl_matrix_delete(x);
+    cpl_matrix_delete(y);
+
+    return weights;
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * @brief    Fill matrix rows with zeros as indicated by a mask.
+ *
+ * @param    mat        A matrix,
+ * @param    mask        A mask flagging rows to be filled with 0.0s,
+ *
+ * @return   @c CPL_ERROR_NONE or the appropriate error code.
+ *
+ * The size of @a mask must be equal to the number of rows of @a
+ * mat.  The rows corresponding to @c CPL_BINARY_1 are set to 0.0.
+ */
+/*---------------------------------------------------------------------------*/
+cpl_error_code hdrl_mime_matrix_mask_rows(cpl_matrix * mat, const cpl_mask * mask)
+{
+    double   *m;
+    const cpl_binary *mk;
+    int       i, j, nr, nc;
+
+/* testing input */
+    if (mat == NULL || mask == NULL)
+        return cpl_error_set(cpl_func, CPL_ERROR_NULL_INPUT);
+
+    if (cpl_matrix_get_nrow(mat) !=
+              cpl_mask_get_size_x(mask) * cpl_mask_get_size_y(mask))
+        return cpl_error_set(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT);
+
+/* initializing */
+    nr = cpl_matrix_get_nrow(mat);
+    nc = cpl_matrix_get_ncol(mat);
+    m = cpl_matrix_get_data(mat);
+    mk = cpl_mask_get_data_const(mask);
+
+/* updating the rows */
+    for (i = 0; i < nr; i++, mk++, m += nc)
+    {
+        if (*mk == CPL_BINARY_1)
+        {
+            for (j = 0; j < nc; j++)
+                m[j] = 0.0;
+        }
+    }
+
+    return CPL_ERROR_NONE;
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * @brief    Multiply the rows of a matrix by given factors.
+ *
+ * @param    mat        A matrix,
+ * @param    d          The factors.
+ * @param[out]   dmat   The  matrix with rescaled rows.
+ *
+ * @return @c CPL_ERROR_NONE or the appropriate error code.
+ *
+ * The number of rows must be equal to the size of @a d. The matrix
+ * @a dmat must be allocated before calling this function.
+ */
+/*---------------------------------------------------------------------------*/
+cpl_error_code hdrl_mime_matrix_rescale_rows(const cpl_matrix * mat,
+          const cpl_matrix * d, cpl_matrix * dmat)
+{
+    const double *m;
+    const double *di;
+    double *dm;
+    int       i, j, nr, nc;
+
+/* testing input */
+    if (mat == NULL || d == NULL || dmat == NULL)
+    {
+        return cpl_error_set(cpl_func, CPL_ERROR_NULL_INPUT);
+    }
+
+    if (cpl_matrix_get_nrow(mat) !=
+              cpl_matrix_get_nrow(d) * cpl_matrix_get_ncol(d))
+    {
+        return cpl_error_set(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT);
+    }
+
+    if (cpl_matrix_get_ncol(mat) != cpl_matrix_get_ncol(dmat) ||
+              cpl_matrix_get_nrow(mat) != cpl_matrix_get_nrow(dmat))
+    {
+        return cpl_error_set(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT);
+    }
+
+/* initializing */
+    nr = cpl_matrix_get_nrow(mat);
+    nc = cpl_matrix_get_ncol(mat);
+
+    m = cpl_matrix_get_data_const(mat);
+    di = cpl_matrix_get_data_const(d);
+    dm = cpl_matrix_get_data(dmat);
+
+/* multiplying the rows by the d[i]'s */
+    for (i = 0; i < nr; i++, m += nc, dm += nc)
+    {
+        for (j = 0; j < nc; j++)
+            dm[j] = di[i] * m[j];
+    }
+
+    return CPL_ERROR_NONE;
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * @brief Solve an overdetermined linear system in the least-squares sense.
+ *
+ * @param mat   A matrix.
+ * @param rhs   A matrix containing right-hand-side vectors.
+ * @param alpha The regularization parameter of the Tikhonov method.
+ *
+ * @return A matrix with solutions of the least-squares problem.
+ *
+ * Typically, this method is used for overdetermined systems, where
+ * the matrix has more rows than columns, but it can also be used for
+ * square and underdetermined systems.  Several right-hand-sides can
+ * be provided.  The regularization parameter increases with the noise
+ * level.
+ */
+/*---------------------------------------------------------------------------*/
+cpl_matrix *hdrl_mime_linalg_solve_tikhonov(const cpl_matrix * mat,
+          const cpl_matrix * rhs, double alpha)
+{
+    cpl_matrix *normal;
+    cpl_matrix *solution;
+    cpl_error_code error;
+
+/* testing input */
+    if (mat == NULL || rhs == NULL)
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_NULL_INPUT);
+        return NULL;
+    }
+
+    if (cpl_matrix_get_nrow(mat) != cpl_matrix_get_nrow(rhs))
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT);
+        return NULL;
+    }
+
+/* creating the normal equations and computing the Cholesky decomposition */
+    normal = hdrl_mime_linalg_normal_equations_create(mat, alpha);
+    error = cpl_matrix_decomp_chol(normal);
+
+    if (error != CPL_ERROR_NONE)
+    {
+        cpl_matrix_delete(normal);
+        return NULL;
+    }
+
+/* solving the normal equations and cleaning up */
+    solution = hdrl_mime_matrix_product_left_transpose_create(mat, rhs);
+    error = cpl_matrix_solve_chol(normal, solution);
+    cpl_matrix_delete(normal);
+
+    if (error != CPL_ERROR_NONE)
+    {
+        cpl_matrix_delete(solution);
+        return NULL;
+    }
+
+    return solution;
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * @brief Create the matrix transpose(A) * A  + alpha for given A and alpha.
+ *
+ * @param mat     Matrix,
+ * @param alpha   The regularization parameter.
+ *
+ * @return The matrix transpose(@a mat) * @a mat  + @a alpha.
+ *
+ * @note Only the upper triangle is computed, since cpl_matrix_decomp_chol()
+ *  only requires the upper triangle.
+ */
+/*---------------------------------------------------------------------------*/
+cpl_matrix *hdrl_mime_linalg_normal_equations_create(const cpl_matrix * mat,
+          double alpha)
+{
+    cpl_matrix *normal;
+    const double *m;
+    double   *p;
+    double    sum;
+    int       nr, nc;
+    int       i, j, k;
+
+/* testing input */
+    if (mat == NULL)
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_NULL_INPUT);
+        return NULL;
+    }
+
+    if (alpha < 0.0)
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_ILLEGAL_INPUT);
+        return NULL;
+    }
+
+/* initializing */
+    nr = cpl_matrix_get_nrow(mat);
+    nc = cpl_matrix_get_ncol(mat);
+
+/* allocating memory */
+    normal = cpl_matrix_new(nc, nc);
+
+/* filling the normal matrix */
+    p = cpl_matrix_get_data(normal);
+    for (i = 0; i < nc; i++, p += nc)
+    {
+        for (j = i; j < nc; j++)
+        {
+            m = cpl_matrix_get_data_const(mat);
+            sum = 0.0;
+            for (k = 0; k < nr; k++, m += nc)
+                sum += m[i] * m[j];
+            p[j] = sum;
+        }
+    }
+
+/* updating the diagonal */
+    p = cpl_matrix_get_data(normal);
+    for (i = 0; i < nc; i++)
+        p[nc * i + i] += alpha;
+
+    return normal;
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * @brief    Create the product of the transpose of a matrix with
+ * another matrix.
+ *
+ * @param    mat1       A matrix,
+ * @param    mat2       A matrix.
+ *
+ * @return   The product of the transpose of the first matrix with the second
+ *           matrix.
+ *
+ * The two matrices must have the same number of rows. The product
+ * matrix must be deallocated with cpl_matrix_delete().
+ */
+/*---------------------------------------------------------------------------*/
+cpl_matrix *hdrl_mime_matrix_product_left_transpose_create(const cpl_matrix *
+          mat1, const cpl_matrix * mat2)
+{
+    cpl_matrix *product;
+
+    const double *m1;
+    const double *m2;
+    double   *p;
+    double    sum;
+
+    int       nr, nc, common;
+    int       i, j, k;
+
+/* testing input */
+    if (mat1 == NULL || mat2 == NULL)
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_NULL_INPUT);
+        return NULL;
+    }
+
+    if (cpl_matrix_get_nrow(mat1) != cpl_matrix_get_nrow(mat2))
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT);
+        return NULL;
+    }
+
+/* initializing */
+    nr = cpl_matrix_get_ncol(mat1);
+    nc = cpl_matrix_get_ncol(mat2);
+    common = cpl_matrix_get_nrow(mat1);
+    /* common = cpl_matrix_get_nrow(mat2); */
+
+/* allocating memory */
+    product = cpl_matrix_new(nr, nc);
+    p = cpl_matrix_get_data(product);
+
+/* filling the product matrix */
+    for (i = 0; i < nr; i++, p += nc)
+    {
+        for (j = 0; j < nc; j++)
+        {
+            m1 = cpl_matrix_get_data_const(mat1);
+            m2 = cpl_matrix_get_data_const(mat2);
+            sum = 0.0;
+            for (k = 0; k < common; k++, m1 += nr, m2 += nc)
+                sum += m1[i] * m2[j];
+            p[j] = sum;
+        }
+    }
+
+    return product;
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * @brief    Fill a matrix with the product of two given matrices.
+ *
+ * @param    mat1        A matrix,
+ * @param    mat2        A matrix,
+ * @param[out]    product    The product of the matrices.
+ *
+ * @return   @c CPL_ERROR_NONE or the appropriate error code.
+ *
+ * The number of rows of @a mat1 must be equal to the number of rows
+ * of @a product.  The number of columns of @a mat2 must be equal to
+ * the number of columns of @a product.  The number of columns of @a
+ * mat1 must be equal to the number of rows of @a mat2.
+ */
+/*---------------------------------------------------------------------------*/
+cpl_error_code hdrl_mime_matrix_product(const cpl_matrix * mat1,
+          const cpl_matrix * mat2, cpl_matrix * product)
+{
+    const double *m1;
+    const double *m2;
+    double   *p;
+    double    sum;
+
+    int       nr, nc, common;
+    int       i, j, k;
+
+/* testing input */
+    if (mat1 == NULL || mat2 == NULL || product == NULL)
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_NULL_INPUT);
+        return CPL_ERROR_NONE;
+    }
+
+    if (cpl_matrix_get_ncol(mat1) != cpl_matrix_get_nrow(mat2) ||
+              cpl_matrix_get_nrow(mat1) != cpl_matrix_get_nrow(product) ||
+              cpl_matrix_get_ncol(mat2) != cpl_matrix_get_ncol(product))
+    {
+        cpl_error_set(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT);
+        return CPL_ERROR_NONE;
+    }
+
+/* initializing */
+    nr = cpl_matrix_get_nrow(mat1);
+    nc = cpl_matrix_get_ncol(mat2);
+    common = cpl_matrix_get_ncol(mat1); /* common = cpl_matrix_get_nrow(mat2); */
+
+/* filling the product matrix */
+    m1 = cpl_matrix_get_data_const(mat1);
+    p = cpl_matrix_get_data(product);
+    for (i = 0; i < nr; i++, m1 += cpl_matrix_get_ncol(mat1), p += nc)
+    {
+        for (j = 0; j < nc; j++)
+        {
+            m2 = cpl_matrix_get_data_const(mat2);
+            sum = 0.0;
+            for (k = 0; k < common; k++, m2 += cpl_matrix_get_ncol(mat2))
+                sum += m1[k] * m2[j];
+            p[j] = sum;
+        }
+    }
+
+    return CPL_ERROR_NONE;
+}
+
+
+
+/**@}*/
diff --git a/hdrl/hdrl_prototyping.h b/hdrl/hdrl_prototyping.h
new file mode 100644
index 0000000..efdd51f
--- /dev/null
+++ b/hdrl/hdrl_prototyping.h
@@ -0,0 +1,65 @@
+/*
+ * hdrl_prototyping.h
+ *
+ *  Created on: Aug 29, 2013
+ *      Author: agabasch
+ */
+
+#ifndef HDRL_PROTOTYPING_H_
+#define HDRL_PROTOTYPING_H_
+
+#include <cpl.h>
+
+cpl_image * hdrl_get_spatial_freq(cpl_image *ima, double gausfilt, int mirrorx,
+                                  int mirrory);
+
+cpl_image * hdrl_mime_image_polynomial_bkg(cpl_image * image,
+                                            int dim_X, int dim_Y,
+                                            cpl_matrix ** coeffs);
+
+
+cpl_error_code hdrl_mime_compute_polynomial_bkg(
+    const cpl_imagelist       * images,
+          cpl_imagelist       * bkg_images,
+          int                   dim_X,
+          int                   dim_Y,
+          cpl_matrix         ** coeffs
+   );
+cpl_matrix *hdrl_mime_legendre_tensors_create(int nx, int ny, int npx, int npy);
+
+cpl_matrix *hdrl_mime_matrix_linspace_create(int n, double a, double b);
+
+cpl_matrix *hdrl_mime_legendre_polynomials_create(int npoly, double a, double b,
+                                             const cpl_matrix * x);
+
+cpl_matrix *hdrl_mime_linalg_pairwise_column_tensor_products_create(const
+          cpl_matrix * mat1, const cpl_matrix * mat2);
+
+cpl_error_code hdrl_mime_matrix_copy_column(const cpl_matrix * mat1, int j_1,
+          cpl_matrix * mat2, int j_2);
+
+cpl_matrix *hdrl_mime_linalg_tensor_products_columns_create(const cpl_matrix *
+                                                       mat1, const cpl_matrix * mat2);
+cpl_matrix *hdrl_mime_tensor_weights_create(int nx, int ny);
+
+cpl_error_code hdrl_mime_matrix_rescale_rows(const cpl_matrix * mat,
+          const cpl_matrix * d, cpl_matrix * dmat);
+
+cpl_error_code hdrl_mime_matrix_mask_rows(cpl_matrix * mat, const cpl_mask * mask);
+
+cpl_matrix *hdrl_mime_linalg_solve_tikhonov(const cpl_matrix * mat,
+          const cpl_matrix * rhs, double alpha);
+
+cpl_matrix *hdrl_mime_linalg_normal_equations_create(const cpl_matrix * mat,
+          double alpha);
+cpl_matrix *hdrl_mime_matrix_product_left_transpose_create(const cpl_matrix *
+          mat1, const cpl_matrix * mat2);
+
+cpl_error_code hdrl_mime_matrix_product(const cpl_matrix * mat1,
+          const cpl_matrix * mat2, cpl_matrix * product);
+
+
+#endif /* HDRL_PROTOTYPING_H_ */
+
+
+
diff --git a/hdrl/hdrl_sigclip.c b/hdrl/hdrl_sigclip.c
new file mode 100644
index 0000000..1886e28
--- /dev/null
+++ b/hdrl/hdrl_sigclip.c
@@ -0,0 +1,882 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2012,2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+-----------------------------------------------------------------------------*/
+
+#include "hdrl_sigclip.h"
+#include "hdrl_utils.h"
+#include "hdrl_collapse.h"
+
+#include <cpl.h>
+#include <string.h>
+#include <math.h>
+
+
+/*-----------------------------------------------------------------------------
+                                   Static
+ -----------------------------------------------------------------------------*/
+
+static cpl_error_code hdrl_sort_double_pairs(cpl_vector *, cpl_vector *) ;
+static long get_lower_bound_d(double * vec, long n, double val);
+static long get_upper_bound_d(double * vec, long n, double val);
+static long get_lower_bound(cpl_vector * vec, double val);
+static long get_upper_bound(cpl_vector * vec, double val);
+
+/** @cond PRIVATE */
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_sigclip   Clipping module
+ 
+  This module provides parameters for iterative \f$\kappa-\sigma\f$ clipping and
+  minmax rejection.
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+/* ---------------------------------------------------------------------------*/
+/**
+  @brief Create parameters for the sigma-clip collapse
+  @param base_context    base context of parameter (e.g. recipe name)
+  @param prefix          prefix of parameter, may be empty string
+  @param defaults        default sigclip parameters
+  @return The created parameter list
+  Creates a parameterlist containing
+      base_context.prefix.kappa-low
+      base_context.prefix.kappa-high
+      base_context.prefix.niter
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_parameterlist * hdrl_sigclip_parameter_create_parlist(
+        const char              *   base_context,
+        const char              *   prefix,
+        const hdrl_parameter    *   defaults)
+{
+    cpl_ensure(base_context && prefix && defaults, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_parameterlist * parlist = cpl_parameterlist_new();
+
+    /* --prefix.kappa-low */
+    hdrl_setup_vparameter(parlist, prefix, ".", "",
+            "kappa-low", base_context,
+            "Low kappa factor for kappa-sigma clipping algorithm",
+            CPL_TYPE_DOUBLE,
+            hdrl_collapse_sigclip_parameter_get_kappa_low(defaults));
+    
+     /* --prefix.kappa-high */
+    hdrl_setup_vparameter(parlist, prefix, ".", "",
+            "kappa-high", base_context,
+            "High kappa factor for kappa-sigma clipping algorithm",
+            CPL_TYPE_DOUBLE,
+            hdrl_collapse_sigclip_parameter_get_kappa_high(defaults));
+ 
+    /* --prefix.niter */
+    hdrl_setup_vparameter(parlist, prefix, ".", "",
+            "niter", base_context,
+            "Maximum number of clipping iterations for kappa-sigma clipping",
+            CPL_TYPE_INT,
+            hdrl_collapse_sigclip_parameter_get_niter(defaults));
+    
+    if (cpl_error_get_code()) {
+        cpl_parameterlist_delete(parlist);
+        return NULL;
+    }
+
+    return parlist;
+}
+/* ---------------------------------------------------------------------------*/
+/**
+  @brief Create parameters for the minmax-clip collapse
+  @param base_context    base context of parameter (e.g. recipe name)
+  @param prefix          prefix of parameter, may be empty string
+  @param defaults        default minmax parameters
+  @return The created parameter list
+  Creates a parameterlist containing
+      base_context.prefix.nlow
+      base_context.prefix.nhigh
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_parameterlist * hdrl_minmax_parameter_create_parlist(
+        const char              *   base_context,
+        const char              *   prefix,
+        const hdrl_parameter    *   defaults)
+{
+    cpl_ensure(base_context && prefix && defaults, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_parameterlist * parlist = cpl_parameterlist_new();
+
+    /* --prefix.nlow */
+    hdrl_setup_vparameter(parlist, prefix, ".", "",
+            "nlow", base_context,
+            "Low number of pixels to reject for the minmax clipping algorithm",
+            CPL_TYPE_DOUBLE,
+            hdrl_collapse_minmax_parameter_get_nlow(defaults));
+    
+     /* --prefix.nhigh */
+    hdrl_setup_vparameter(parlist, prefix, ".", "",
+            "nhigh", base_context,
+            "High number of pixels to reject for the minmax clipping algorithm",
+            CPL_TYPE_DOUBLE,
+            hdrl_collapse_minmax_parameter_get_nhigh(defaults));
+     
+    if (cpl_error_get_code()) {
+        cpl_parameterlist_delete(parlist);
+        return NULL;
+    }
+
+    return parlist;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief parse parameterlist for sigclip parameters to init corresponding hdrl
+ * structure parameters
+ *
+ * @param parlist    parameter list to parse
+ * @param prefix     prefix of parameter name
+ * @param kappa_low  pointer to storage to save kappa_low or NULL
+ * @param kappa_high pointer to storage to save kappa_high or NULL
+ * @param niter      pointer to storage to save niter or NULL
+ * @see   hdrl_kappa_sigma_clip_get_parlist()
+ * @return cpl_error_code
+ *
+ * parameterlist should have been created with
+ * hdrl_kappa_sigma_clip_get_parlist or have the same name hierachy
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_sigclip_parameter_parse_parlist(
+        const cpl_parameterlist *   parlist,
+        const char              *   prefix,
+        double                  *   kappa_low,
+        double                  *   kappa_high,
+        int                     *   niter)
+{
+    cpl_ensure_code(prefix && parlist, CPL_ERROR_NULL_INPUT);
+    char * name;
+
+    if (kappa_low) {
+        name = hdrl_join_string(".", 2, prefix, "sigclip.kappa-low");
+        const cpl_parameter * par = cpl_parameterlist_find_const(parlist, name);
+        *kappa_low = cpl_parameter_get_double(par);
+        cpl_free(name);
+    }
+
+    if (kappa_high) {
+        name = hdrl_join_string(".", 2, prefix, "sigclip.kappa-high");
+        const cpl_parameter * par = cpl_parameterlist_find_const(parlist, name);
+        *kappa_high = cpl_parameter_get_double(par);
+        cpl_free(name);
+    }
+
+    if (niter) {
+        name = hdrl_join_string(".", 2, prefix, "sigclip.niter");
+        const cpl_parameter * par = cpl_parameterlist_find_const(parlist, name);
+        *niter = cpl_parameter_get_int(par);
+        cpl_free(name);
+    }
+
+    if (cpl_error_get_code()) {
+        return cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                                     "Error while parsing parameterlist "
+                                     "with prefix %s", prefix);
+    }
+
+    return CPL_ERROR_NONE;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief parse parameterlist for minmax parameters to init corresponding hdrl
+ * structure parameters
+ *
+ * @param parlist    parameter list to parse
+ * @param prefix     prefix of parameter name
+ * @param nlow       pointer to storage to save nlow or NULL
+ * @param nhigh      pointer to storage to save nhigh or NULL
+ * @see   hdrl_minmax_clip_get_parlist()
+ * @return cpl_error_code
+ *
+ * parameterlist should have been created with
+ * hdrl_minmax_clip_get_parlist or have the same name hierachy
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code hdrl_minmax_parameter_parse_parlist(
+        const cpl_parameterlist *   parlist,
+        const char              *   prefix,
+        double                  *   nlow,
+        double                  *   nhigh)
+{
+    cpl_ensure_code(prefix && parlist, CPL_ERROR_NULL_INPUT);
+    char * name;
+
+    if (nlow) {
+        name = hdrl_join_string(".", 2, prefix, "minmax.nlow");
+        const cpl_parameter * par = cpl_parameterlist_find_const(parlist, name);
+        *nlow = cpl_parameter_get_double(par);
+        cpl_free(name);
+    }
+
+    if (nhigh) {
+        name = hdrl_join_string(".", 2, prefix, "minmax.nhigh");
+        const cpl_parameter * par = cpl_parameterlist_find_const(parlist, name);
+        *nhigh = cpl_parameter_get_double(par);
+        cpl_free(name);
+    }
+
+    if (cpl_error_get_code()) {
+        return cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                                     "Error while parsing parameterlist "
+                                     "with prefix %s", prefix);
+    }
+
+    return CPL_ERROR_NONE;
+}
+
+ 
+/*----------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief    Compute mean image value using min-max rejection method
+  @param source         Input image
+  @param error          Input error image
+  @param nlow         Absolute number of low pixels to reject
+  @param nhigh         Absolute number of high pixels to reject
+  @param mean_mm        The min-max clipped mean
+  @param mean_mm_err    The propagated error of the min-max clipped mean
+  @param naccepted      Number of accepted values
+  @return   @c CPL_ERROR_NONE or the appropriate error code.
+  @see hdrl_minmax_clip()
+
+  This function converts the image inputs into the proper data types in
+  order to call the hdrl_minmax_clip() function.
+  If the error values at the rejection boundaries are ambigous, e.g. when you
+  have multiple pixels with the same value but different error and the
+  rejection boundary would only select a subset of these, the algorithm assigns
+  the smallest error values of the equal value range to the selected pixels.
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_minmax_clip_image(
+        const cpl_image   * source,
+        const cpl_image   * error,
+        const double        nlow,
+        const double        nhigh,
+        double            * mean_mm,
+        double            * mean_mm_err,
+        cpl_size          * naccepted,
+        double            * reject_low,
+        double            * reject_high)
+{
+    cpl_vector * vec_source = NULL;
+    cpl_vector * vec_error = NULL;
+
+    /* Check Entries */
+    cpl_error_ensure(source != NULL, CPL_ERROR_NULL_INPUT,
+            return CPL_ERROR_NULL_INPUT, "Null input source image!");
+    cpl_error_ensure(error != NULL, CPL_ERROR_NULL_INPUT,
+            return CPL_ERROR_NULL_INPUT, "Null input error image!");
+    cpl_error_ensure(cpl_image_get_size_x(source)==cpl_image_get_size_x(error),
+            CPL_ERROR_INCOMPATIBLE_INPUT, return CPL_ERROR_INCOMPATIBLE_INPUT,
+            "source and error image musty have same X size");
+    cpl_error_ensure(cpl_image_get_size_y(source)==cpl_image_get_size_y(error),
+            CPL_ERROR_INCOMPATIBLE_INPUT, return CPL_ERROR_INCOMPATIBLE_INPUT,
+            "source and error image musty have same Y size");
+
+    /* compress images to vectors excluding the bad pixels */
+    vec_source = hdrl_image_to_vector(source, NULL);
+    vec_error = hdrl_image_to_vector(error, cpl_image_get_bpm_const(source));
+
+    if (vec_source != NULL && vec_error != NULL) {
+        /* Call here the real clipping function */
+        hdrl_minmax_clip(vec_source, vec_error, nlow, nhigh, CPL_TRUE, mean_mm,
+                         mean_mm_err, naccepted, reject_low, reject_high);
+    }
+    /* no good pixels */
+    else {
+        *mean_mm = NAN;
+        *mean_mm_err = NAN;
+        *naccepted = 0;
+        *reject_low = NAN;
+        *reject_high = NAN;
+    }
+
+    cpl_msg_debug(cpl_func, "mean_mm, mean_mm_err, naccepted:  %g, %g, %ld",
+                  *mean_mm, *mean_mm_err, (long)*naccepted);
+
+    cpl_vector_delete(vec_source);
+    cpl_vector_delete(vec_error);
+    return cpl_error_get_code();
+}
+
+
+/*----------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief   Compute mean using min-max clipping.
+  @param   vec         The vector for which the clipped mean is computed.
+  @param   vec_err     The error of vec.
+  @param   nlow        The number of low pixels to be rejected by the algorithm
+  @param   nhigh       The number of high pixels to be rejected by the algorithm
+  @param   inplace     If true the input vectors are modified
+  @param   mean_mm     The min-max clipped mean.
+  @param   mean_mm_err The propagated error of the min-max clipped mean.
+  @param   naccepted   Number of accepted values.
+  @param   reject_low  The lowest value that is rejected
+  @param   reject_high The highest value that is rejected
+  @return   @c CPL_ERROR_NONE or the appropriate error code.
+
+  This function computes the mean after sorting the elements and rejecting nlow
+  and nhigh values. The remaining pixels are then used to compute the mean and
+  the associated error. Please note that, if multiple equal elements are
+  present, the error propagation uses the value with the smallest error.
+
+
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_minmax_clip(
+                const cpl_vector  * vec,
+                const cpl_vector  * vec_err,
+                const double        nlow,
+                const double        nhigh,
+                cpl_boolean         inplace,
+                double            * mean_mm,
+                double            * mean_mm_err,
+                cpl_size          * naccepted,
+                double            * reject_low,
+                double            * reject_high)
+{
+    /*    VARIABLES ON THE FUNCTION SCOPE:
+
+          vec_image       a deep copy of the input vector vec.
+          mean_mm         min-max clip mean (return variable).
+     */
+
+    cpl_vector   * vec_image = NULL;
+    cpl_vector   * vec_image_err = NULL;
+
+    cpl_size       vec_size;
+    cpl_size nlow_int, nhigh_int;
+    cpl_vector * vec_trunc;
+
+    cpl_size trunc_size;
+    double * d, * e;
+
+    /*In the future minmax rejection could also use relative values therefore
+     * we pass a double to the function - nevertheless the code as it is now
+     * expects an integer - thus we need to do the  rounding */
+
+    nlow_int = (cpl_size)round(nlow);
+    nhigh_int = (cpl_size)round(nhigh);
+
+    cpl_error_ensure(vec != NULL, CPL_ERROR_NULL_INPUT,
+                     return CPL_ERROR_NULL_INPUT, "Null input vector data");
+    cpl_error_ensure(vec_err != NULL, CPL_ERROR_NULL_INPUT,
+                     return CPL_ERROR_NULL_INPUT, "Null input vector errors");
+    cpl_error_ensure(cpl_vector_get_size(vec) == cpl_vector_get_size(vec_err),
+                     CPL_ERROR_INCOMPATIBLE_INPUT,
+                     return CPL_ERROR_INCOMPATIBLE_INPUT,
+                                     "input data and error vectors must have same sizes");
+    cpl_error_ensure(mean_mm != NULL, CPL_ERROR_NULL_INPUT,
+                     return CPL_ERROR_NULL_INPUT, "Null input mean storage");
+
+    cpl_error_ensure(nlow_int >=0 && nhigh_int>=0, CPL_ERROR_INCOMPATIBLE_INPUT,
+                     return CPL_ERROR_INCOMPATIBLE_INPUT, "nlow and nhigh must "
+                                     "be strictly positive");
+
+    if (inplace) {
+        vec_image = (cpl_vector *)vec;
+        vec_image_err = (cpl_vector *)vec_err;
+    }
+    else {
+        vec_image = cpl_vector_duplicate(vec);
+        vec_image_err = cpl_vector_duplicate(vec_err);
+    }
+    vec_size = cpl_vector_get_size(vec_image);
+
+    /* Nothing to do if only one data point */
+    if(vec_size <= (nlow_int+nhigh_int)) {
+        *mean_mm=NAN;
+        *mean_mm_err=NAN;
+        *naccepted=0;
+        cpl_vector_delete(vec_image);
+        cpl_vector_delete(vec_image_err);
+        return cpl_error_get_code();
+    }
+
+    hdrl_sort_double_pairs(vec_image, vec_image_err);
+
+    trunc_size = (vec_size - nhigh_int) - nlow_int;
+    d = cpl_vector_get_data(vec_image);
+    e = cpl_vector_get_data(vec_image_err);
+    vec_trunc = cpl_vector_wrap(trunc_size, d + nlow_int);
+
+    /*    COMPUTE THE MIN-MAX CLIP MEAN */
+    *mean_mm  = cpl_vector_get_mean(vec_trunc);
+
+    if (naccepted) {
+        *naccepted = trunc_size;
+    }
+
+    if (reject_low) {
+        *reject_low = d[nlow_int];
+    }
+    if (reject_high) {
+        *reject_high = d[vec_size - nhigh_int - 1];
+    }
+
+    if (mean_mm_err) {
+        cpl_vector * vec_trunc_err;
+        /* if multiple equal elements use the one with the smallest error
+         * get the equal range, sort the errors and write the smallest into the
+         * valid array ends */
+        intptr_t l = get_lower_bound(vec_image, d[nlow_int]);
+        intptr_t h = get_upper_bound(vec_image, d[nlow_int]);
+        if (h - l > 1 && h - l != vec_size) {
+            cpl_vector * e_vec = cpl_vector_extract(vec_image_err, l, h - 1, 1);
+            cpl_vector_sort(e_vec, CPL_SORT_ASCENDING);
+            for (intptr_t i = nlow_int; i < h; i++) {
+                cpl_vector_set(vec_image_err, i,
+                               cpl_vector_get(e_vec, i - nlow_int));
+            }
+            cpl_vector_delete(e_vec);
+        }
+
+        l = get_lower_bound(vec_image, d[vec_size - nhigh_int - 1]);
+        h = get_upper_bound(vec_image, d[vec_size - nhigh_int - 1]);
+        if (h - l > 1 && h - l != vec_size) {
+            cpl_vector * e_vec = cpl_vector_extract(vec_image_err, l, h - 1, 1);
+            cpl_vector_sort(e_vec, CPL_SORT_ASCENDING);
+            for (intptr_t i = l; i < vec_size - nhigh; i++) {
+                cpl_vector_set(vec_image_err, i,
+                               cpl_vector_get(e_vec, i - l));
+            }
+            cpl_vector_delete(e_vec);
+        }
+
+        vec_trunc_err = cpl_vector_wrap(trunc_size, e + nlow_int);
+        /*Propagate the errors (cpl_vector_power is very slow PIPE-4330) */
+        cpl_vector_multiply(vec_trunc_err, vec_trunc_err);
+        *mean_mm_err = sqrt(cpl_vector_get_mean(vec_trunc_err) /
+                            cpl_vector_get_size(vec_trunc_err));
+        cpl_vector_unwrap(vec_trunc_err);
+    }
+    /* CLEAN, AND RETURN */
+    cpl_vector_unwrap(vec_trunc);
+    if (!inplace) {
+        cpl_vector_delete(vec_image);
+        cpl_vector_delete(vec_image_err);
+    }
+    return cpl_error_get_code();
+}
+
+
+
+/*----------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief    Compute mean image value using kappa-sigma clipping method
+  @param source         Input image 
+  @param error          Input error image
+  @param kappa_low      Number of sigmas for lower threshold
+  @param kappa_high     Number of sigmas for upper threshold        
+  @param iter           Number of iterations
+  @param mean_ks        The kappa-sigma clipped mean
+  @param mean_ks_err    The propagated error of the kappa-sigma clipped mean
+  @param naccepted      Number of accepted values
+  @param reject_low     Values lower than this have been rejected
+  @param reject_high    Values higher than this have been rejected
+  @return   @c CPL_ERROR_NONE or the appropriate error code.
+  @see hdrl_kappa_sigma_clip()
+  
+  This function converts the image inputs into the proper data types in
+  order to call the hdrl_kappa_sigma_clip() function.
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_kappa_sigma_clip_image(
+        const cpl_image   * source,
+        const cpl_image   * error,
+        const double        kappa_low,
+        const double        kappa_high,
+        const int           iter,
+        double            * mean_ks,
+        double            * mean_ks_err,
+        cpl_size          * naccepted,
+        double            * reject_low,
+        double            * reject_high)
+{
+    cpl_vector * vec_source = NULL;
+    cpl_vector * vec_error = NULL;
+
+    /* Check Entries */
+    cpl_error_ensure(source != NULL, CPL_ERROR_NULL_INPUT,
+            return CPL_ERROR_NULL_INPUT, "Null input source image!");
+    cpl_error_ensure(error != NULL, CPL_ERROR_NULL_INPUT,
+            return CPL_ERROR_NULL_INPUT, "Null input error image!");
+    cpl_error_ensure(cpl_image_get_size_x(source)==cpl_image_get_size_x(error),
+            CPL_ERROR_INCOMPATIBLE_INPUT, return CPL_ERROR_INCOMPATIBLE_INPUT,
+            "source and error image musty have same X size");
+    cpl_error_ensure(cpl_image_get_size_y(source)==cpl_image_get_size_y(error),
+            CPL_ERROR_INCOMPATIBLE_INPUT, return CPL_ERROR_INCOMPATIBLE_INPUT,
+            "source and error image musty have same Y size");
+
+    /* compress images to vectors excluding the bad pixels */
+    vec_source = hdrl_image_to_vector(source, NULL);
+    vec_error = hdrl_image_to_vector(error, cpl_image_get_bpm_const(source));
+
+    if (vec_source != NULL && vec_error != NULL) {
+        /* Call here the real sigma-clipping function */
+        hdrl_kappa_sigma_clip(vec_source, vec_error, kappa_low, kappa_high,
+                             iter, CPL_TRUE, mean_ks, mean_ks_err, naccepted,
+                             reject_low, reject_high);
+    }
+    /* no good pixels */
+    else {
+        *mean_ks = NAN;
+        *mean_ks_err = NAN;
+        *naccepted = 0;
+        *reject_low = NAN;
+        *reject_high = NAN;
+    }
+
+    cpl_msg_debug(cpl_func, "mean_ks, mean_ks_err, naccepted:  %g, %g, %ld",
+                  *mean_ks, *mean_ks_err, (long)*naccepted);
+
+    cpl_vector_delete(vec_source);
+    cpl_vector_delete(vec_error);
+    return cpl_error_get_code();
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief get first index that compares greater than value
+ * @param vec vector to check
+ * @param count size of vector
+ * @param val upper bound to check
+ */
+/* ---------------------------------------------------------------------------*/
+static long get_upper_bound_d(double * d, long count, double val)
+{
+    long first = 0;
+    while (count > 0)
+    {
+        long step = count / 2;
+        long it = first + step;
+        if (!(val < d[it])) {
+            first = it + 1;
+            count -= step + 1;
+        }
+        else
+            count = step;
+    }
+    return first;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief get first index that compares greater than value
+ * @param vec vector to check
+ * @param val upper bound to check
+ */
+/* ---------------------------------------------------------------------------*/
+static long get_upper_bound(cpl_vector * vec, double val)
+{
+    double * d = cpl_vector_get_data(vec);
+    long count = cpl_vector_get_size(vec);
+    return get_upper_bound_d(d, count, val);
+}
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief get index that compares does not compare less than value
+ * @param vec vector to check
+ * @param count size of vector
+ * @param val upper bound to check
+ */
+/* ---------------------------------------------------------------------------*/
+static long get_lower_bound_d(double * d, long count, double val)
+{
+    long first = 0;
+    while (count > 0)
+    {
+        long step = count / 2;
+        long it = first + step;
+        if (d[it] < val) {
+            first = it + 1;
+            count -= step + 1;
+        }
+        else
+            count = step;
+    }
+    return first;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief get index that compares does not compare less than value
+ * @param vec vector to check
+ * @param val upper bound to check
+ */
+/* ---------------------------------------------------------------------------*/
+static long get_lower_bound(cpl_vector * vec, double val)
+{
+    double * d = cpl_vector_get_data(vec);
+    long count = cpl_vector_get_size(vec);
+    return get_lower_bound_d(d, count, val);
+}
+
+/* compute mean and error without needing to wrap a vector, the allocation can
+ * be very expensive for small stacks of images */
+static void get_mean_err(const double * d, const double * e, long count,
+                         double * rm, double * re)
+{
+    double m = 0.;
+    for (long i = 0; i < count; i++) {
+        m += (d[i] - m) / (double)(i + 1);
+    }
+    *rm = m;
+
+    if (re) {
+        double se = 0;
+        for (long i = 0; i < count; i++) {
+            se += e[i] * e[i];
+        }
+        *re = sqrt(se) / count;
+    }
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief   Compute mean using kappa-sigma clipping.
+  @param   vec         The vector for which mean is to be computed.
+  @param   vec_err     The error of vec. 
+  @param   kappa_low   Number of sigmas for lower threshold.
+  @param   kappa_high  Number of sigmas for upper threshold.
+  @param   iter        Number of iterations.
+  @param   inplace     if true the vectors input are modified
+  @param   mean_ks     The kappa-sigma clipped mean.
+  @param   mean_ks_err The propagated error of the kappa-sigma clipped mean.
+  @param   naccepted   Number of accepted values.
+  @param   reject_low  Values lower than this have been rejected.
+  @param   reject_high Values higher than this have been rejected
+  @return   @c CPL_ERROR_NONE or the appropriate error code.
+
+  The function computes the arithmetic mean of a vector after rejecting 
+  outliers using kappa-sigma clipping. Robust estimates of the mean and 
+  standard deviation are used to derive the interval within which values in 
+  the vector are considered good.
+
+  The sigma-clipping is applied on the vec vector data. The vec_err vector 
+  is used for the error computation.
+
+  An iterative process of rejection of the outlier elements of vec is
+  applied. iter specifies the maximum number of iterations.
+
+  At each iteration, the median and sigma values of the vector are computed and
+  used to derive low and high thresholds (\f$median-kappa\_low \times sigma\f$
+  and \f$median+kappa\_low \times sigma\f$). The values of vec outside those
+  bounds are rejected and the remaining values are passed to the next
+  iteration.
+
+  The mean value of the remaining elements is stored into mean_ks.
+  mean_ks_err contains \f$\frac{\sum_i{val_i^{2}}}{N}\f$ where \f$val_i\f$
+  are the remaining elements of vec_err and N the number of those elements. 
+  The N value is stored in naccepted.
+
+  reject_low and reject_high are the final thresholds differenciating the 
+  rejected pixels from the others.
+
+  The iterative process is illustrated here:
+  \image html sigclip_algorithm.png
+
+  Note that the \f$\sigma\f$ used for the thresholding in the different
+  iterations is not the standard deviation but the scaled
+  Median Absolute Deviation (MAD). The scaling is
+  \f$\sigma = MAD \times CPL_MATH_STD_MAD\f$.
+
+  The MAD is a more robust estimate of the scale of the distribution than the
+  standard deviation but only has ??% of the asymptotic statistical efficiency
+  for normal distributed data. This higher error in scale parameter only has
+  limited influence on the result as it is only used determination of clipping
+  thresholds.
+
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_kappa_sigma_clip(
+        const cpl_vector  * vec,
+        const cpl_vector  * vec_err,
+        const double        kappa_low,
+        const double        kappa_high,
+        const int           iter,
+        cpl_boolean         inplace,
+        double            * mean_ks,
+        double            * mean_ks_err,
+        cpl_size          * naccepted,
+        double            * reject_low,
+        double            * reject_high)
+{
+    /*    VARIABLES ON THE FUNCTION SCOPE:
+
+          vec_image       a deep copy of the input vector vec.
+          mean_ks         kappa-sigma clip mean (return variable).
+          mean_ks         kappa-sigma clip mean (return variable).
+    */
+
+    cpl_vector   * vec_image = NULL;
+    cpl_vector   * vec_image_err = NULL;
+
+    cpl_size       vec_size;
+    double lower_bound = 0.;
+    double upper_bound = 0.;
+
+    cpl_error_ensure(vec != NULL, CPL_ERROR_NULL_INPUT,
+                     return CPL_ERROR_NULL_INPUT, "Null input vector data");
+    cpl_error_ensure(vec_err != NULL, CPL_ERROR_NULL_INPUT,
+                     return CPL_ERROR_NULL_INPUT, "Null input vector errors");
+    cpl_error_ensure(cpl_vector_get_size(vec) == cpl_vector_get_size(vec_err),
+                     CPL_ERROR_INCOMPATIBLE_INPUT,
+                     return CPL_ERROR_INCOMPATIBLE_INPUT,
+                     "input data and error vectors must have same sizes");
+    cpl_error_ensure(mean_ks != NULL, CPL_ERROR_NULL_INPUT,
+                     return CPL_ERROR_NULL_INPUT, "Null input mean storage");
+    cpl_error_ensure(iter > 0, CPL_ERROR_ILLEGAL_INPUT,
+                     return CPL_ERROR_ILLEGAL_INPUT,
+                     "iter must be larger than 0");
+
+    if (inplace) {
+        vec_image = (cpl_vector *)vec;
+        vec_image_err = (cpl_vector *)vec_err;
+    }
+    else {
+        vec_image = cpl_vector_duplicate(vec);
+        vec_image_err = cpl_vector_duplicate(vec_err);
+    }
+    double * vec_data = cpl_vector_get_data(vec_image);
+    double * vec_data_err = cpl_vector_get_data(vec_image_err);
+    vec_size = cpl_vector_get_size(vec_image);
+
+    /* sort the two vectors by the data */
+    hdrl_sort_double_pairs(vec_image, vec_image_err);
+
+    for(int it = 0; it < iter; it++) {
+        double median, sigma;
+        cpl_size lower_index, upper_index;
+
+        /* Nothing to do if only one data point */
+        if(vec_size == 1) {
+            lower_bound = vec_data[0];
+            upper_bound = lower_bound;
+            break;
+        }
+
+        /*  STEPS OF KAPPA SIGMA CLIP
+            1. Sort the vector.
+            2. Find mean, and standard deviation (sigma).
+            3. Find lower, and upper bound after kappa-sigma clip.
+            4. Find index which corresponds to lower and upper bound
+            5. Extract the vector within the index bound.
+        */
+
+        /* Use median as a robust estimator of the mean */
+
+        /* standard deviation from Median Absolute Deviation (MAD) as appropriate
+           for a Gaussian distribution */
+
+       /* TODO remove image wrapper once a cpl_vector_get_mad() exists */
+        cpl_image * ima_vectorwrap = cpl_image_wrap_double(vec_size, 1,vec_data);
+        median = cpl_image_get_mad(ima_vectorwrap, &sigma);
+        cpl_image_unwrap(ima_vectorwrap);
+
+        if(sigma <= 0){
+            sigma=nextafter(0,1.0);
+        }
+        sigma *= CPL_MATH_STD_MAD;
+
+        lower_bound = median - kappa_low * sigma;
+        upper_bound = median + kappa_high * sigma;
+
+        lower_index = get_lower_bound_d(vec_data, vec_size, lower_bound);
+        upper_index = get_upper_bound_d(vec_data, vec_size, upper_bound);
+        upper_index = CX_MAX(upper_index - 1, 0);
+
+        /* Stop if no outliers were found */
+        if ((lower_index == 0) && (upper_index == vec_size - 1))
+            break;
+
+        /* truncate vector */
+        vec_data = vec_data + lower_index;
+        vec_data_err = vec_data_err + lower_index;
+        vec_size = upper_index - lower_index + 1;
+    }
+
+    /*    COMPUTE THE KAPPA-SIGMA CLIP MEAN */
+    get_mean_err(vec_data, vec_data_err, vec_size, mean_ks, mean_ks_err);
+
+    if (naccepted) *naccepted = vec_size;
+
+    if (reject_low) *reject_low = lower_bound;
+    if (reject_high) *reject_high = upper_bound;
+
+    /* CLEAN, AND RETURN */
+    if (!inplace) {
+        cpl_vector_delete(vec_image);
+        cpl_vector_delete(vec_image_err);
+    }
+    return cpl_error_get_code();
+}
+
+
+/*---------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief   Sort an array @a u1 of doubles, and permute an array @a u2
+           in the same way as @a u1 is permuted.
+  @param   u1   Pointer to the first array.
+  @param   u2   Pointer to the second array.
+  @return   @c CPL_ERROR_NONE or the appropriate error code.
+ */
+/*---------------------------------------------------------------------------*/
+static cpl_error_code hdrl_sort_double_pairs(cpl_vector *u1, cpl_vector *u2)
+{
+    cpl_bivector * bi_all = NULL;
+
+    cpl_error_ensure(u1 != NULL, CPL_ERROR_NULL_INPUT,
+                     return CPL_ERROR_NULL_INPUT, "NULL pointer to 1st array");
+    cpl_error_ensure(u2 != NULL, CPL_ERROR_NULL_INPUT,
+                     return CPL_ERROR_NULL_INPUT, "NULL pointer to 2nd array");
+
+    bi_all = cpl_bivector_wrap_vectors(u1, u2);
+    cpl_bivector_sort(bi_all, bi_all, CPL_SORT_ASCENDING, CPL_SORT_BY_X);
+
+    /* cleaning up */
+    cpl_bivector_unwrap_vectors(bi_all);
+
+    return CPL_ERROR_NONE;
+}
+
+
+/**@}*/
+/** @endcond */
diff --git a/hdrl/hdrl_sigclip.h b/hdrl/hdrl_sigclip.h
new file mode 100644
index 0000000..1bbfdc7
--- /dev/null
+++ b/hdrl/hdrl_sigclip.h
@@ -0,0 +1,108 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2012,2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_SIGCLIP_H_
+#define HDRL_SIGCLIP_H_
+
+/*-----------------------------------------------------------------------------
+                                Include
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_parameter.h" 
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                            Functions prototypes
+ -----------------------------------------------------------------------------*/
+
+cpl_parameterlist * hdrl_sigclip_parameter_create_parlist(
+        const char              *   recipe,
+        const char              *   prefix,
+        const hdrl_parameter    *   defaults) ;
+cpl_error_code hdrl_sigclip_parameter_parse_parlist(
+        const cpl_parameterlist *   parlist,
+        const char              *   prefix,
+        double                  *   kappa_low,
+        double                  *   kappa_high,
+        int                     *   nclip) ;
+cpl_parameterlist * hdrl_minmax_parameter_create_parlist(
+        const char              *   recipe,
+        const char              *   prefix,
+        const hdrl_parameter    *   defaults) ;
+cpl_error_code hdrl_minmax_parameter_parse_parlist(
+        const cpl_parameterlist *   parlist,
+        const char              *   prefix,
+        double                  *   nlow,
+        double                  *   high) ;
+
+cpl_error_code hdrl_kappa_sigma_clip_image(
+        const cpl_image   * source,
+        const cpl_image   * error,
+        const double        kappa_low,
+        const double        kappa_high,
+        const int           iter,
+        double            * mean_ks,
+        double            * mean_ks_err,
+        cpl_size          * naccepted,
+        double            * reject_low,
+        double            * reject_high) ;
+
+cpl_error_code hdrl_kappa_sigma_clip(
+        const cpl_vector  * vec,
+        const cpl_vector  * vec_err,
+        const double        kappa_low,
+        const double        kappa_high,
+        const int           iter,
+        cpl_boolean         inplace,
+        double            * mean_ks,
+        double            * mean_ks_err,
+        cpl_size          * naccepted,
+        double            * reject_low,
+        double            * reject_high) ;
+
+
+cpl_error_code hdrl_minmax_clip_image(
+        const cpl_image   * source,
+        const cpl_image   * error,
+        const double        nlow,
+        const double        nhigh,
+        double            * mean_mm,
+        double            * mean_mm_err,
+        cpl_size          * naccepted,
+        double            * reject_low,
+        double            * reject_high);
+
+cpl_error_code hdrl_minmax_clip(
+                const cpl_vector  * vec,
+                const cpl_vector  * vec_err,
+                const double        nlow,
+                const double        nhigh,
+                cpl_boolean         inplace,
+                double            * mean_mm,
+                double            * mean_mm_err,
+                cpl_size          * naccepted,
+                double            * reject_low,
+                double            * reject_high);
+
+
+CPL_END_DECLS
+
+#endif /* HDRL_SIGCLIP_H_ */
diff --git a/hdrl/hdrl_strehl.c b/hdrl/hdrl_strehl.c
new file mode 100644
index 0000000..b739e2d
--- /dev/null
+++ b/hdrl/hdrl_strehl.c
@@ -0,0 +1,1335 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+-----------------------------------------------------------------------------*/
+/* for j1 */
+#define _XOPEN_SOURCE 600
+
+#include "hdrl_strehl.h"
+#include "hdrl_image.h"
+#include "hdrl_types.h"
+#include "hdrl_utils.h"
+
+#include <cpl.h>
+#include <assert.h>
+#include <math.h>
+#include <stdint.h>
+
+/*-----------------------------------------------------------------------------
+                                   Static
+ -----------------------------------------------------------------------------*/
+
+
+static hdrl_strehl_result bad_result = {
+    {NAN, NAN},
+    NAN, NAN,
+    {NAN, NAN},
+    {NAN, NAN},
+    {NAN, NAN},
+    NAN,
+    0
+};
+
+/**
+ *
+ * @defgroup hdrl_strehl     Strehl Computation
+ *
+ * @brief
+ *   Function to compute the Strehl ratio on an image.
+ *
+ * The most commonly used metrics for evaluating the AO correction is the Strehl
+ * ratio. The Strehl ratio is defined as the ratio of the peak image intensity
+ * from a point source compared to the maximum attainable intensity using an
+ * ideal optical system limited only by diffraction over the telescope aperture.
+ * The Strehl ratio is very frequently used to perform the quality control of
+ * the scientific data obtained with the AO assisted instrumentation.
+ *
+ * The calculation is performed by calling the top-level function
+ * hdrl_strehl_compute() and the parameters passed to this function can be
+ * created by calling hdrl_strehl_parameter_create().
+ *
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+
+/*-----------------------------------------------------------------------------
+                        Strehl parameters Definition
+ -----------------------------------------------------------------------------*/
+
+/** @cond PRIVATE */
+
+typedef struct {
+    HDRL_PARAMETER_HEAD;
+    double wavelength ;
+    double m1 ;
+    double m2 ;
+    double pixel_scale_x;
+    double pixel_scale_y;
+    double flux_radius;
+    double bkg_radius_low;
+    double bkg_radius_high;
+} hdrl_strehl_parameter;
+
+/* parameter type */
+static hdrl_parameter_typeobj hdrl_strehl_parameter_type = {
+    HDRL_PARAMETER_STREHL,                /* type */
+    (hdrl_alloc *)&cpl_malloc,            /* fp_alloc */
+    (hdrl_free *)&cpl_free,               /* fp_free */
+    NULL,                                 /* fp_destroy */
+    sizeof(hdrl_strehl_parameter),        /* obj_size */
+};
+
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief    Verify basic correctness of the Strehl parameters
+ * @param    param      Strehl parameters
+ * @return   CPL_ERROR_NONE if everything is ok, an error code otherwise
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code
+hdrl_strehl_parameter_verify(const hdrl_parameter    *   param)
+{
+    cpl_error_ensure(param != NULL, CPL_ERROR_NULL_INPUT,
+                    return CPL_ERROR_NULL_INPUT, "NULL Input Parameters");
+    cpl_error_ensure(hdrl_strehl_parameter_check(param),
+                     CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                                     "Expected Strehl parameter") ;
+
+    const hdrl_strehl_parameter * param_loc = (hdrl_strehl_parameter *)param ;
+
+    cpl_error_ensure(param_loc->wavelength >= 0, CPL_ERROR_ILLEGAL_INPUT,
+                     return CPL_ERROR_ILLEGAL_INPUT, "wavelength must be >=0");
+    cpl_error_ensure(param_loc->m1 >= 0, CPL_ERROR_ILLEGAL_INPUT,
+                     return CPL_ERROR_ILLEGAL_INPUT, "m1 radius must be >=0");
+    cpl_error_ensure(param_loc->m2 >= 0, CPL_ERROR_ILLEGAL_INPUT,
+                     return CPL_ERROR_ILLEGAL_INPUT, "m2 radius must be >=0");
+    cpl_error_ensure(param_loc->m1 > param_loc->m2, CPL_ERROR_ILLEGAL_INPUT,
+                     return CPL_ERROR_ILLEGAL_INPUT,
+                     "m1 radius must be larger than m2 radius");
+    cpl_error_ensure(param_loc->pixel_scale_x >= 0, CPL_ERROR_ILLEGAL_INPUT,
+                     return CPL_ERROR_ILLEGAL_INPUT, "pixel_scale_x must be >=0");
+    cpl_error_ensure(param_loc->pixel_scale_y >= 0, CPL_ERROR_ILLEGAL_INPUT,
+                     return CPL_ERROR_ILLEGAL_INPUT, "pixel_scale_y must be >=0");
+
+    cpl_error_ensure(param_loc->flux_radius >= 0, CPL_ERROR_ILLEGAL_INPUT,
+                     return CPL_ERROR_ILLEGAL_INPUT, "flux_radius must be >=0");
+
+    cpl_error_ensure(param_loc->m1 >= param_loc->m2, CPL_ERROR_ILLEGAL_INPUT,
+                     return CPL_ERROR_ILLEGAL_INPUT, "m1 must be >=m2");
+    if (param_loc->bkg_radius_low > 0) {
+        cpl_error_ensure(param_loc->bkg_radius_low >= param_loc->flux_radius,
+                         CPL_ERROR_ILLEGAL_INPUT,return CPL_ERROR_ILLEGAL_INPUT,
+                         "bkg_radius_low must be >=flux_radius");
+        cpl_error_ensure(param_loc->bkg_radius_high > param_loc->bkg_radius_low,
+                         CPL_ERROR_ILLEGAL_INPUT,return CPL_ERROR_ILLEGAL_INPUT,
+                         "bkg_radius_high must be >bkg_radius_low");
+    }
+    else {
+        cpl_error_ensure(param_loc->bkg_radius_high < 0,
+                 CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+                 "bkg_radius_high must be < 0 if bkg_radius_low is < 0");
+    }
+
+    return CPL_ERROR_NONE ;
+
+}
+
+/** @endcond */
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @brief    Creates Strehl Parameters object
+ *
+ * @param    wavelength      Nominal filter wavelength [m]
+ * @param    m1_radius       primary mirror radius [m]
+ * @param    m2_radius       obstruction radius [m]
+ * @param    pixel_scale_x   image X pixel scale in [arcsec]
+ * @param    pixel_scale_y   image Y pixel scale in [arcsec]
+ * @param    flux_radius     radius used to sum the flux [arcsec]
+ * @param    bkg_radius_low  radius used to determine the background [arcsec]
+ * @param    bkg_radius_high radius used to determine the background [arcsec]
+ *
+ * @return   The Strehl parameters object.
+ *           It needs to be deallocated with hdrl_parameter_delete()
+ * @see      hdrl_parameter_delete()
+ * @see      hdrl_strehl_compute()
+ * The method creates a parameter to compute the Strehl
+ */
+
+hdrl_parameter * hdrl_strehl_parameter_create(double wavelength,
+        double m1_radius, double m2_radius,
+        double pixel_scale_x, double pixel_scale_y, double flux_radius,
+        double bkg_radius_low, double bkg_radius_high) {
+
+
+    hdrl_strehl_parameter * p = (hdrl_strehl_parameter *)
+    hdrl_parameter_new(&hdrl_strehl_parameter_type);
+
+    p->wavelength = wavelength ;
+    p->m1 = m1_radius;
+    p->m2 = m2_radius;
+    p->pixel_scale_x = pixel_scale_x;
+    p->pixel_scale_y = pixel_scale_y;
+    p->flux_radius = flux_radius;
+    p->bkg_radius_low = bkg_radius_low;
+    p->bkg_radius_high = bkg_radius_high;
+
+    if (hdrl_strehl_parameter_verify((hdrl_parameter *)p)) {
+        cpl_free(p);
+        return NULL;
+    }
+    return (hdrl_parameter *)p;
+
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @brief    Check that the parameter is a Strehl parameter
+ * @param    self The parameter to check
+ * @return   True or False
+ */
+/*----------------------------------------------------------------------------*/
+cpl_boolean hdrl_strehl_parameter_check(const hdrl_parameter * self)
+{
+    return hdrl_parameter_check_type(self, &hdrl_strehl_parameter_type);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @brief    Access the wavelength in the Strehl parameter
+ * @param    p   The Strehl parameter
+ * @return   The wavelength value
+ */
+/*----------------------------------------------------------------------------*/
+double hdrl_strehl_parameter_get_wavelength(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0);
+    return ((hdrl_strehl_parameter *)p)->wavelength;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @brief    Access the primary mirror radius in the Strehl parameter
+ * @param    p   The Strehl parameter
+ * @return   The primary mirror radius value
+ */
+/*----------------------------------------------------------------------------*/
+double hdrl_strehl_parameter_get_m1(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0);
+    return ((hdrl_strehl_parameter *)p)->m1;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @brief    Access the obstruction radius in the Strehl parameter
+ * @param    p   The Strehl parameter
+ * @return   The obstruction radius value
+ */
+/*----------------------------------------------------------------------------*/
+double hdrl_strehl_parameter_get_m2(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0);
+    return ((hdrl_strehl_parameter *)p)->m2;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @brief    Access the image X pixel scale in the Strehl parameter
+ * @param    p   The Strehl parameter
+ * @return   The image X pixel scale value
+ */
+/*----------------------------------------------------------------------------*/
+double hdrl_strehl_parameter_get_pixel_scale_x(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0);
+    return ((hdrl_strehl_parameter *)p)->pixel_scale_x;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @brief    Access the image Y pixel scale in the Strehl parameter
+ * @param    p   The Strehl parameter
+ * @return   The image Y pixel scale value
+ */
+/*----------------------------------------------------------------------------*/
+double hdrl_strehl_parameter_get_pixel_scale_y(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0);
+    return ((hdrl_strehl_parameter *)p)->pixel_scale_y;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @brief    Access the total flux radius in the Strehl parameter
+ * @param    p   The Strehl parameter
+ * @return   The total flux radius value
+ */
+/*----------------------------------------------------------------------------*/
+double hdrl_strehl_parameter_get_flux_radius(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0);
+    return ((hdrl_strehl_parameter *)p)->flux_radius;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @brief    Access the background region internal radius in the Strehl parameter
+ * @param    p   The Strehl parameter
+ * @return   The background region internal radius value
+ */
+/*----------------------------------------------------------------------------*/
+double hdrl_strehl_parameter_get_bkg_radius_low(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0);
+    return ((hdrl_strehl_parameter *)p)->bkg_radius_low;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @brief    Access the background region external radius in the Strehl parameter
+ * @param    p   The Strehl parameter
+ * @return   The background region external radius value
+ */
+/*----------------------------------------------------------------------------*/
+double hdrl_strehl_parameter_get_bkg_radius_high(
+        const hdrl_parameter * p)
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1.0);
+    return ((hdrl_strehl_parameter *)p)->bkg_radius_high;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @brief Create parameter list for the Strehl computation
+ * @param base_context        base context of parameter (e.g. recipe name)
+ * @param prefix              prefix of parameter, may be an empty string
+ * @param par                 hdrl_parameter defining the defaults
+ * @see hdrl_strehl_parameter_create()
+ *
+ *
+ * Creates a parameter list with the Strehl parameters:
+ *   - base_context.prefix.wavelength
+ *   - base_context.prefix.m1
+ *   - base_context.prefix.m2
+ *   - base_context.prefix.pixel-scale-x
+ *   - base_context.prefix.pixel-scale-y
+ *   - base_context.prefix.flux-radius
+ *   - base_context.prefix.bkg-radius-low
+ *   - base_context.prefix.bkg-radius-high
+ *
+ * The CLI aliases omit the base_context.
+ */
+/*----------------------------------------------------------------------------*/
+cpl_parameterlist * hdrl_strehl_parameter_create_parlist(
+        const char      *   base_context,
+        const char      *   prefix,
+        hdrl_parameter  *   par)
+{
+
+    cpl_ensure(prefix && base_context, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_parameterlist   *   parlist = cpl_parameterlist_new();
+
+    /* --prefix.wavelength */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "wavelength", base_context,
+                          "Wavelength [m].", CPL_TYPE_DOUBLE,
+                          hdrl_strehl_parameter_get_wavelength(par));
+
+    /* --prefix.m1 */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "m1", base_context,
+                          "Telescope radius [m].", CPL_TYPE_DOUBLE,
+                          hdrl_strehl_parameter_get_m1(par));
+
+    /* --prefix.m2 */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "m2", base_context,
+                          "Telescope obstruction radius [m].", CPL_TYPE_DOUBLE,
+                          hdrl_strehl_parameter_get_m2(par));
+
+    /* --prefix.pixscale_x */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "pixel-scale-x", base_context,
+                          "Detector X pixel scale on sky [arcsec].",
+                          CPL_TYPE_DOUBLE,
+                          hdrl_strehl_parameter_get_pixel_scale_x(par));
+
+    /* --prefix.pixscale_y */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "pixel-scale-y", base_context,
+                          "Detector Y pixel scale on sky [arcsec].",
+                          CPL_TYPE_DOUBLE,
+                          hdrl_strehl_parameter_get_pixel_scale_y(par));
+
+    /* --prefix.flux_radius */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "flux-radius", base_context,
+                           "PSF Flux integration radius [arcsec].",
+                           CPL_TYPE_DOUBLE,
+                           hdrl_strehl_parameter_get_flux_radius(par));
+
+    /* --prefix.bkg_radius_low_def */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "bkg-radius-low", base_context,
+                            "PSF background inner radii [arcsec].",
+                            CPL_TYPE_DOUBLE,
+                            hdrl_strehl_parameter_get_bkg_radius_low(par));
+
+    /* --prefix.bkg_radius_high_def */
+    hdrl_setup_vparameter(parlist, prefix, ".", "", "bkg-radius-high", base_context,
+                            "PSF background outer radius [arcsec].",
+                            CPL_TYPE_DOUBLE,
+                            hdrl_strehl_parameter_get_bkg_radius_high(par));
+
+    if (cpl_error_get_code()) {
+        cpl_parameterlist_delete(parlist);
+        return NULL;
+    }
+
+
+    return parlist;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @brief Parse parameter list to create input parameters for the Strehl
+ * @param parlist        parameter list to parse
+ * @param prefix         prefix of parameter name
+ * @return   Input parameters for the Strehl computation
+ *
+ * Reads a parameter list in order to create Strehl parameters.
+ *
+ * Expects a parameter list containing:
+ *   - base_context.prefix.wavelength
+ *   - base_context.prefix.m1
+ *   - base_context.prefix.m2
+ *   - base_context.prefix.pixel-scale-x
+ *   - base_context.prefix.pixel-scale-y
+ *   - base_context.prefix.flux-radius
+ *   - base_context.prefix.bkg-radius-low
+ *   - base_context.prefix.bkg-radius-high
+ *
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_strehl_parameter_parse_parlist(
+        const cpl_parameterlist *   parlist,
+        const char              *   prefix)
+{
+    cpl_ensure(prefix && parlist, CPL_ERROR_NULL_INPUT, NULL);
+    char                *   name ;
+    const cpl_parameter *   par = NULL;
+    double                  wavelength, m1, m2, pixel_scale_x, pixel_scale_y,
+                            flux_radius, bkg_radius_low,bkg_radius_high;
+
+
+    /* --wavelength */
+    name = hdrl_join_string(".", 2, prefix, "wavelength");
+    par=cpl_parameterlist_find_const(parlist, name);
+    wavelength = cpl_parameter_get_double(par);
+    cpl_free(name) ;
+
+    /* --m1 */
+    name = hdrl_join_string(".", 2, prefix, "m1");
+    par=cpl_parameterlist_find_const(parlist, name);
+    m1 = cpl_parameter_get_double(par);
+    cpl_free(name) ;
+
+    /* --m2 */
+    name = hdrl_join_string(".", 2, prefix, "m2");
+    par=cpl_parameterlist_find_const(parlist, name);
+    m2 = cpl_parameter_get_double(par);
+    cpl_free(name) ;
+
+    /* --pixel_scale_x */
+    name = hdrl_join_string(".", 2, prefix, "pixel-scale-x");
+    par=cpl_parameterlist_find_const(parlist, name);
+    pixel_scale_x = cpl_parameter_get_double(par);
+    cpl_free(name) ;
+
+    /* --pixel_scale_y */
+    name = hdrl_join_string(".", 2, prefix, "pixel-scale-y");
+    par=cpl_parameterlist_find_const(parlist, name);
+    pixel_scale_y = cpl_parameter_get_double(par);
+    cpl_free(name) ;
+
+    /* --flux_radius */
+    name = hdrl_join_string(".", 2, prefix, "flux-radius");
+    par=cpl_parameterlist_find_const(parlist, name);
+    flux_radius = cpl_parameter_get_double(par);
+    cpl_free(name) ;
+
+    /* --bkg_radius_low */
+    name = hdrl_join_string(".", 2, prefix, "bkg-radius-low");
+    par=cpl_parameterlist_find_const(parlist, name);
+    bkg_radius_low = cpl_parameter_get_double(par);
+    cpl_free(name) ;
+
+    /* --bkg_radius_high */
+    name = hdrl_join_string(".", 2, prefix, "bkg-radius-high");
+    par=cpl_parameterlist_find_const(parlist, name);
+    bkg_radius_high = cpl_parameter_get_double(par);
+    cpl_free(name) ;
+
+
+    if (cpl_error_get_code()) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                        "Error while parsing parameterlist with prefix %s", prefix);
+        return NULL;
+    } else {
+        return hdrl_strehl_parameter_create(wavelength, m1,m2,
+                        pixel_scale_x, pixel_scale_y,
+                        flux_radius, bkg_radius_low, bkg_radius_high) ;
+    }
+
+}
+
+
+/** @cond PRIVATE */
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief mask where mask is valid
+ * @param himg  hdrl image
+ * @param mask mask defining where to find max
+ * @return max and its error
+ */
+/* ---------------------------------------------------------------------------*/
+static hdrl_value
+hdrl_image_max_where(const hdrl_image * himg, cpl_mask * mask)
+{
+    hdrl_image * tmpimg = hdrl_image_duplicate(himg);
+    cpl_size px, py;
+    hdrl_value mx;
+    hdrl_image_reject_from_mask(tmpimg, mask);
+    cpl_image_get_maxpos(hdrl_image_get_image(tmpimg), &px, &py);
+    mx = hdrl_image_get_pixel(tmpimg, px, py, NULL);
+    hdrl_image_delete(tmpimg);
+    return mx;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief sum where mask is valid
+ * @param himg  hdrl image
+ * @param mask mask defining where to sum
+ * @return sum and its error
+ */
+/* ---------------------------------------------------------------------------*/
+static hdrl_value
+hdrl_image_sum_where(const hdrl_image * himg, cpl_mask * mask)
+{
+    hdrl_image * tmpimg = hdrl_image_duplicate(himg);
+    hdrl_value flux;
+    hdrl_image_reject_from_mask(tmpimg, mask);
+    flux = hdrl_image_get_sum(tmpimg);
+    hdrl_image_delete(tmpimg);
+    return flux;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief median where mask is valid
+ * @param himg  hdrl image
+ * @param mask mask defining where to sum
+ * @return sum and its error
+ */
+/* ---------------------------------------------------------------------------*/
+static hdrl_value
+hdrl_image_median_where(const hdrl_image * himg, cpl_mask * mask)
+{
+    hdrl_image * tmpimg = hdrl_image_duplicate(himg);
+    hdrl_value flux;
+    hdrl_image_reject_from_mask(tmpimg, mask);
+    flux = hdrl_image_get_median(tmpimg);
+    hdrl_image_delete(tmpimg);
+    return flux;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief stdev where mask is valid
+ * @param himg  hdrl image
+ * @param mask mask defining where to compute
+ * @return computed standard deviation
+ */
+/* ---------------------------------------------------------------------------*/
+static double
+hdrl_image_stdev_where(const hdrl_image * himg, cpl_mask * mask)
+{
+    hdrl_image * tmpimg = hdrl_image_duplicate(himg);
+    double mad;
+    hdrl_image_reject_from_mask(tmpimg, mask);
+    cpl_image_get_mad(hdrl_image_get_image_const(himg), &mad);
+    hdrl_image_delete(tmpimg);
+    return mad * CPL_MATH_STD_MAD;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief compute obstructed Airy disk
+ *
+ * @param lam         wavelength [m]
+ * @param m1          radius of primary mirror [m]
+ * @param m2          radius of secondary mirror [m]
+ * @param pixscale_x  pixel scale in x direction [arcseconds]
+ * @param pixscale_y  pixel scale in y direction [arcseconds]
+ * @param cx          position of center in x direction (FITS) [pixel]
+ * @param cy          position of center in y direction (FITS) [pixel]
+ * @param nx          size of image in x direction [pixel]
+ * @param ny          size of image in y direction [pixel]
+ *
+ * Computes an obstructed Airy for one wavelength from following formula:
+ *
+ * \f$
+ * I(r) = \frac{1}{1 - e^2} \left(\frac{2 j_1(r)}{r} - \frac{2 e j_1(er)}{r}\right)^2
+ * \f$
+ * with:
+ * \f$
+ * e = \frac{m_2}{m_2}
+ * \;
+ * r = k m_1 \sin{\theta} = \frac{2 \pi m_1}{\lambda} \sqrt{x^2 + y^2}
+ * \f$
+ * See Wikipedia.
+ *
+ * The parameters cx and cy define the center of the Airy disk.
+ * E.g. a value of nx // 2 means the disk will be centered exactly at the
+ * middle of the central pixel while a value of nx // 2 - 0.5 means the peak of
+ * the disk will be at the origin and the flux evenly distributed among the
+ * four neighboring pixels.
+ */
+/* ---------------------------------------------------------------------------*/
+static cpl_image *
+compute_psf(double lam, double m1, double m2,
+            double pixscale_x, double pixscale_y,
+            double cx, double cy,
+            size_t nx, size_t ny)
+{
+    cpl_image * psf = cpl_image_new(nx, ny, CPL_TYPE_DOUBLE);
+    double * data = cpl_image_get_data(psf);
+    double e = m2 / m1;
+    double as_2_rad = CPL_MATH_2PI / (360. * 3600);
+    /* inclusive linear space with pixel center at the middle. integer cx and cy
+     * will result in a psf exactly centered around the middle of the central
+     * pixel, cx/cy are in fits convention [1,nx/ny] with pixel origin in the
+     * middle */
+    double centerx = (-(nx / 2.) + cx - 1 + 0.5) * pixscale_x;
+    double centery = (-(ny / 2.) + cy - 1 + 0.5) * pixscale_y;
+    double xhigh = ((nx - 1) * pixscale_x / 2) - centerx;
+    double yhigh = ((ny - 1) * pixscale_y / 2) - centery;
+    double xlow = -((nx - 1) * pixscale_x / 2) - centerx;
+    double ylow = -((ny - 1) * pixscale_y / 2) - centery;
+    double step_x = (xhigh - xlow) / (nx - 1);
+    double step_y = (yhigh - ylow) / (ny - 1);
+HDRL_OMP(omp parallel for)
+    for (size_t iy = 0; iy < ny; iy++) {
+        double y = iy == ny - 1 ? yhigh : ylow + iy * step_y;
+        for (size_t ix = 0; ix < nx; ix++) {
+            double x = ix == nx - 1 ? xhigh : xlow + ix * step_x;
+            double r = sqrt(x*x + y*y) * as_2_rad * CPL_MATH_2PI * m1 / lam;
+            if (r == 0.) {
+                data[iy * nx + ix] = 1.;
+            }
+            else {
+                double airy = (2 * j1(r) / r - 2 * e * j1(e * r) / r);
+                double c = (1 - e * e);
+                data[iy * nx + ix] = 1 / (c * c) * airy * airy;
+            }
+        }
+    }
+    return psf;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief    Find the aperture(s) with the greatest flux
+ * @param    self   The aperture object
+ * @param    ind  The aperture-indices in order of decreasing flux
+ * @param    nfind  Number of indices to find
+ * @return   CPL_ERROR_NONE or the relevant _cpl_error_code_ on error
+ *
+ * nfind must be at least 1 and at most the size of the aperture object.
+ *
+ * The ind array must be able to hold (at least) nfind integers.
+ * On success the first nfind elements of ind point to indices of the
+ * aperture object.
+ *
+ * To find the single ind of the aperture with the maximum flux use simply:
+ * int ind;
+ * apertures_find_max_flux(self, &ind, 1);
+ *
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code apertures_find_max_flux(const cpl_apertures * self,
+                                              int * ind, int nfind)
+{
+    const int    nsize = cpl_apertures_get_size(self);
+    int          ifind;
+
+
+    cpl_ensure_code(nsize > 0,      cpl_error_get_code());
+    cpl_ensure_code(ind,          CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(nfind > 0,      CPL_ERROR_ILLEGAL_INPUT);
+    cpl_ensure_code(nfind <= nsize, CPL_ERROR_ILLEGAL_INPUT);
+
+    for (ifind=0; ifind < nfind; ifind++) {
+        double maxflux = -1;
+        int maxind = -1;
+        int i;
+        for (i=1; i <= nsize; i++) {
+            int k;
+
+            /* The flux has to be the highest among those not already found */
+            for (k=0; k < ifind; k++) if (ind[k] == i) break;
+
+            if (k == ifind) {
+                /* i has not been inserted into ind */
+                const double flux = cpl_apertures_get_flux(self, i);
+
+                if (maxind < 0 || flux > maxflux) {
+                    maxind = i;
+                    maxflux = flux;
+                }
+            }
+        }
+        ind[ifind] = maxind;
+    }
+
+    return CPL_ERROR_NONE;
+
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief    Find the peak flux, peak sum and position of a Gaussian
+ * @param    self        Image to process
+ * @param    sigma       The initial detection level  [ADU]
+ * @param    pxpos       On success, the refined X-position [pixel]
+ * @param    pypos       On success, the refined Y-position [pixel]
+ * @param    ppeak       On success, the refined peak flux  [ADU]
+ * @return CPL_ERROR_NONE or the relevant CPL error code on error
+ *
+ * The routine initially determines the approximate position and flux value of
+ * the PSF with a robust Gaussian fit: first are identified all sources that lie
+ * 5 sigmas above the median of the image, then is determined the position of
+ * the barycenter of the region with highest peak. Finally is performed the fit
+ * of a Gaussian centered on the found barycenter position.
+ *
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code
+gaussian_maxpos(const cpl_image * self,
+                double sigma,
+                double  * pxpos,
+                double  * pypos,
+                double  * ppeak)
+{
+    /* copied from irplib_strehl.c r163170 */
+    const cpl_size  nx = cpl_image_get_size_x(self);
+    const cpl_size  ny = cpl_image_get_size_y(self);
+    int             iretry = 3; /* Number retries with decreasing sigma */
+    int             ifluxapert = 0;
+    double          med_dist;
+    const double    median = cpl_image_get_median_dev(self, &med_dist);
+    cpl_mask      * selection;
+    cpl_size        nlabels = 0;
+    cpl_image     * labels = NULL;
+    cpl_apertures * aperts;
+    cpl_size        npixobj;
+    double          objradius;
+    cpl_size        winsize;
+    cpl_size        xposmax, yposmax;
+    double          xposcen, yposcen;
+    double          valmax, valfit = -1.0;
+    cpl_array     * gauss_parameters = NULL;
+    cpl_errorstate  prestate = cpl_errorstate_get();
+    cpl_error_code  code = CPL_ERROR_NONE;
+
+
+    cpl_ensure_code( sigma > 0.0, CPL_ERROR_ILLEGAL_INPUT);
+
+    selection = cpl_mask_new(nx, ny);
+
+    /* find aperture with signal larger than sigma * median deviation */
+    for (; iretry > 0 && nlabels == 0; iretry--, sigma *= 0.5) {
+
+        /* Compute the threshold */
+        const double threshold = median + sigma * med_dist;
+
+
+        /* Select the pixel above the threshold */
+        code = cpl_mask_threshold_image(selection, self, threshold, DBL_MAX,
+                                        CPL_BINARY_1);
+
+        if (code) break;
+
+        /* Labelise the thresholded selection */
+        cpl_image_delete(labels);
+        labels = cpl_image_labelise_mask_create(selection, &nlabels);
+    }
+    sigma *= 2.0; /* reverse last iteration that found no labels */
+
+    cpl_mask_delete(selection);
+
+    if (code) {
+        cpl_image_delete(labels);
+        return cpl_error_set_where(cpl_func);
+    } else if (nlabels == 0) {
+        cpl_image_delete(labels);
+        return cpl_error_set(cpl_func, CPL_ERROR_DATA_NOT_FOUND);
+    }
+
+    aperts = cpl_apertures_new_from_image(self, labels);
+
+    /* Find the aperture with the greatest flux */
+    code = apertures_find_max_flux(aperts, &ifluxapert, 1);
+
+    if (code) {
+        cpl_apertures_delete(aperts);
+        cpl_image_delete(labels);
+        return cpl_error_set(cpl_func, CPL_ERROR_DATA_NOT_FOUND);
+    }
+
+    npixobj = cpl_apertures_get_npix(aperts, ifluxapert);
+    objradius = sqrt((double)npixobj * CPL_MATH_1_PI);
+    winsize = CX_MIN(CX_MIN(nx, ny), (3.0 * objradius));
+
+    xposmax = cpl_apertures_get_maxpos_x(aperts, ifluxapert);
+    yposmax = cpl_apertures_get_maxpos_y(aperts, ifluxapert);
+    xposcen = cpl_apertures_get_centroid_x(aperts, ifluxapert);
+    yposcen = cpl_apertures_get_centroid_y(aperts, ifluxapert);
+    valmax  = cpl_apertures_get_max(aperts, ifluxapert);
+
+    cpl_apertures_delete(aperts);
+    cpl_image_delete(labels);
+
+    cpl_msg_debug(cpl_func, "Object radius at S/R=%g: %g (window-size=%u)",
+                  sigma, objradius, (unsigned)winsize);
+    cpl_msg_debug(cpl_func, "Object-peak @ (%d, %d) = %g", (int)xposmax,
+                  (int)yposmax, valmax);
+
+    /* fit gaussian to get subpixel peak position */
+
+    gauss_parameters = cpl_array_new(7, CPL_TYPE_DOUBLE);
+    cpl_array_set_double(gauss_parameters, 0, median);
+
+    code = cpl_fit_image_gaussian(self, NULL, xposmax, yposmax,
+                                  winsize, winsize, gauss_parameters,
+                                  NULL, NULL, NULL,
+                                  NULL, NULL, NULL, 
+                                  NULL, NULL, NULL);
+    if (!code) {
+        const double M_x = cpl_array_get_double(gauss_parameters, 3, NULL);
+        const double M_y = cpl_array_get_double(gauss_parameters, 4, NULL);
+
+        valfit = hcpl_gaussian_eval_2d(gauss_parameters, M_x, M_y);
+
+        if (!cpl_errorstate_is_equal(prestate)) {
+            code = cpl_error_get_code();
+        } else {
+            *pxpos        = M_x;
+            *pypos        = M_y;
+            *ppeak        = valfit;
+
+            cpl_msg_debug(cpl_func, "Gauss-fit @ (%g, %g) = %g",
+                          M_x, M_y, valfit);
+        }
+    }
+    cpl_array_delete(gauss_parameters);
+
+    if (code || valfit < valmax) {
+        cpl_errorstate_set(prestate);
+        *pxpos   = xposcen;
+        *pypos   = yposcen;
+        *ppeak   = valmax;
+    }
+
+    return code ? cpl_error_set_where(cpl_func) : CPL_ERROR_NONE;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief    create a disk mask
+  @param    im          Image to compute from
+  @param    xpos        the x position of the disk center [pixel, C indexing]
+  @param    ypos        the y position of the disk center [pixel, C indexing]
+  @param    rad         the radius [pixel]
+  @return   a mask with valid pixels inside the disk
+  @note     (xpos, ypos) and may be outside the image, if so then a sufficiently
+            small rad will cause no pixels to be encircled
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_mask *
+strehl_disk_mask(const cpl_image * im,
+                 double            xpos,
+                 double            ypos,
+                 double            rad)
+{
+    const intptr_t       nx = cpl_image_get_size_x(im);
+    const intptr_t       ny = cpl_image_get_size_y(im);
+    /* Round down */
+    const intptr_t       lx = (intptr_t)(xpos - rad);
+    const intptr_t       ly = (intptr_t)(ypos - rad);
+    /* Round up */
+    const intptr_t       ux = (intptr_t)(xpos + rad) + 1;
+    const intptr_t       uy = (intptr_t)(ypos + rad) + 1;
+
+    const double    sqr = rad * rad;
+    cpl_mask * m;
+
+
+    /* Check entries */
+    cpl_ensure(im != NULL, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(rad > 0.0, CPL_ERROR_ILLEGAL_INPUT, NULL);
+
+    m = cpl_mask_new(nx, ny);
+
+    for (intptr_t j = CX_MAX(ly, 0); j < CX_MIN(uy, ny); j++) {
+        const double yj = (double)j - ypos;
+        for (intptr_t i = CX_MAX(lx, 0); i < CX_MIN(ux, nx); i++) {
+            const double xi   = (double)i - xpos;
+            const double dist = yj * yj + xi * xi;
+            if (dist <= sqr) {
+                if (!cpl_image_is_rejected(im, i + 1, j + 1)) {
+                    cpl_mask_set(m, i + 1, j + 1, CPL_BINARY_1);
+                }
+            }
+        }
+    }
+    cpl_mask_not(m);
+
+    return m;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief rebin image
+ * @param img       image to rebin, size must be a multiple of sampling
+ * @param sampling  rebin factor
+ * @return rebinned image
+ */
+/* ---------------------------------------------------------------------------*/
+static inline cpl_image * hdrl_rebin(cpl_image * img, size_t sampling)
+{
+    cpl_size lnx = cpl_image_get_size_x(img);
+    cpl_size lny = cpl_image_get_size_y(img);
+    cpl_size nx = lnx / sampling;
+    cpl_size ny = lny / sampling;
+    cpl_image * n = cpl_image_new(nx, ny, CPL_TYPE_DOUBLE);
+    double * ld = cpl_image_get_data_double(img);
+    double * nd = cpl_image_get_data_double(n);
+    for (size_t iy = 0; iy < (size_t)ny; iy++) {
+        for (size_t ix = 0; ix < (size_t)nx; ix++) {
+            for (size_t ly = 0; ly < sampling; ly++) {
+                for (size_t lx = 0; lx < sampling; lx++) {
+                    nd[iy * nx + ix] += ld[((iy*sampling) + ly) * lnx + lx + (ix*sampling)];
+                }
+            }
+        }
+    }
+    return n;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief compute encircled energy of psf
+ * @param lam  wavelength
+ * @param m1   primary mirror radius
+ * @param m2   obstruction radius
+ * @param r    integration radius
+ *
+ *
+ * \f[
+ * EE(v_{0}) = \frac{1}{1 - \epsilon^2} \left(1 - J_{0}^{2}(v_{0}) - J_{1}^{2}(v_{0})
+ * + \epsilon^{2} (1- J_{0}^{2}(v_{0}) - J_{1}^{2}(\epsilon v_{0}))
+ * -2\epsilon\int_{0}^{v_{0}} J_{1}(\epsilon v) \frac{2J_{1}(v)}{v}dv \right)
+ * \f]
+ *
+ * where
+ * \f$J_{1}\f$ is the Bessel function or order \f$0\f$,
+ * \f$J_{1}\f$ is the Bessel function or order \f$1\f$,
+ * \f$\epsilon = \frac{m_2}{m_2}\f$ is the telescope central obstruction
+ * (fraction of telescope diameter),
+ * v is the radial distance from Airy function center (2 * Nyquist/ units), and
+ * \f$v_{0}\f$ is the maximum radial distance from Airy function center for EE
+ * calculation (2 * Nyquist/ units). During \f$EE\f$ computation we neglect
+ * the integral term.
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+static inline double
+compute_psf_flux(double lam, double m1, double m2, double r)
+{
+    /* currently unused */
+    double e = m2 / m1;
+    r *= CPL_MATH_2PI * m1 / lam;
+    double E = 1 - j0(r) * j0(r) - j1(r) * j1(r) + e*e *
+        (1 - j0(e*r)*j0(e*r) - j1(e*r)*j1(e*r));
+    E *= 1 / (1 - e * e);
+    /* Note compared to analytical formula iof the encircled energy, here we 
+       neglect the contribute from integral term: -2*e*integral(j1*j1*2/v dv) */
+    return E;
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @internal
+ * @brief compute Strehl parameter
+ * @param himg background corrected image
+ * @param lam  wavelength [m]
+ * @param m1_radius   primary mirror radius [m]
+ * @param m2_radius   obstruction radius [m]
+ * @param pixscale_x    image X pixel scale in [arcsec]
+ * @param pixscale_y    image Y pixel scale in [arcsec]
+ * @param flux_radius   radius used to sum the flux [arcsec]
+ *
+ * @return an hdrl_value containing the computed Strehl value and its error
+ * or NAN in case of error.
+ *
+ * @note  strehl function, assumes background corrected image with peak at
+ * peak_x/peak_y
+ *
+ * @note
+ * This function assumes that the input image is background corrected.
+ *
+ * Initially a synthetic PSF is generated with parameters:
+ *  - base_context.prefix.wavelength
+ *  - base_context.prefix.m1
+ *  - base_context.prefix.m2
+ *  - base_context.prefix.pixel-scale-x
+ *  - base_context.prefix.pixel-scale-y
+ *  and pixel scale upsampling factor 16.
+ * @see compute_psf()
+ *
+ * The synthetic PSF is shifted of an arbitrary value equal to 7 pixels
+ * (determined ad hoc) and then the synthetic PSF is down-sampled to the
+ * original PSF sampling. Then synthetic PSF is normalized dividing it by a
+ * value equal to the ratio of the synthetic PSF peak and the observed PSF peak
+ * values.
+ *
+ * Then the position and the peak of the PSF are determined by a robust fit of
+ * a 2D Gaussian. @see gaussian_maxpos()
+ *
+ * Then an approximate position of the maximum on the observed PSF standard
+ * is determined, later refined using the associated error (and bad pixel)
+ * information. This define the value of PSFo_peak
+ *
+ * Then is determined the observed PSF flux, PSFo_flux, within the ring centered
+ * on the peak and user set radius. This is used to compute the ratio
+ * Ro=PSFo_peak/PSFo_flux
+ *
+ * The same ratio is also determined similarly for the synthetic PSF.
+ * Rt=PSFt_peak/PSFt_flux
+ *
+ * Finally the strehl is computed as
+ * strehl=Ro/Rt
+ *
+ * along with its associated error:
+ * strehl_err=strehl*sqrt((peak_err/peak_val^2)+(flux_err/flux_val^2))
+ *
+ */
+
+static hdrl_strehl_result
+compute_strehl2(const hdrl_image * himg, double lam,
+                double m1_radius, double m2_radius,
+                double pixscale_x, double pixscale_y,
+                double peak_x, double peak_y,
+                double radius_arcsec)
+{
+    const cpl_image * img = hdrl_image_get_image_const(himg);
+    double min_pscale = CX_MIN(pixscale_x, pixscale_y);
+    double radius_pix = (radius_arcsec / min_pscale);
+    /* could be shrunk for better performance as flux beyond a few rings is negligible
+     * using analytic encircled energy would probably also work */
+    cpl_size wins = 2 * radius_pix;
+    cpl_msg_debug(cpl_func, "strehl psf window size %d", (int)wins);
+    double smallx = peak_x - (floor(peak_x) - wins/2);
+    double smally = peak_y - (floor(peak_y) - wins/2);
+    /* sample psf on larger grid for a primitive integration of the flux */
+    size_t sampling = 16;
+    intptr_t nnx = wins * sampling;
+    intptr_t nny = wins * sampling;
+    cpl_image * lpsf = compute_psf(lam, m1_radius, m2_radius,
+                                   pixscale_x / sampling, pixscale_y / sampling,
+                                   smallx*sampling,smally*sampling,
+                                   nnx, nny);
+    /* Note: o is a hard-coded offset to get the peak in same position as in data 
+     * after down-sampling, 7 seems to work reasonably well for sampling 16 */
+    int o = 7;
+    cpl_image * epsf = cpl_image_extract(lpsf, 1 + o, 1 + o, nnx - o, nny - o);
+    cpl_image * psf = hdrl_rebin(epsf, sampling);
+    cpl_image_delete(epsf);
+    cpl_image_delete(lpsf);
+    /* normalize for easier comparison, not required */
+    cpl_image_divide_scalar(psf, cpl_image_get_max(psf)/cpl_image_get_max(img));
+    cpl_msg_debug(cpl_func, "position/peak of data: %g %g", peak_x, peak_y);
+    {
+        /* fit not required, just for debugging */
+        double xposfit, yposfit, peak;
+        gaussian_maxpos(psf, 5, &xposfit, &yposfit, &peak);
+        cpl_msg_debug(cpl_func, "position/peak of psf: %g %g", xposfit, yposfit);
+    }
+    
+    /* computes ratio peak/flux over the observed PSF standard */
+    cpl_mask  * im = strehl_disk_mask(img, peak_x, peak_y, radius_pix);
+    hdrl_value ipeak = hdrl_image_max_where(himg, im);
+    cpl_msg_debug(cpl_func, "Computing flux on %d pixel radius, total pixels %ld",
+                  (int)(radius_pix),
+                  (long)(cpl_mask_get_size_x(im) * cpl_mask_get_size_y(im) -
+                         cpl_mask_count(im)));
+    hdrl_value iflux = hdrl_image_sum_where(himg, im);
+    cpl_msg_debug(cpl_func, "flux ring/total data: %g (%g) %g", iflux.data,
+                  iflux.error, cpl_image_get_flux(img));
+    cpl_mask_delete(im);
+    
+    double ratio_img = ipeak.data / iflux.data;
+
+    /* computes ratio peak/flux over the synthetic PSF */
+    double ppeak = cpl_image_get_max(psf);
+    cpl_mask * pm =
+        strehl_disk_mask(psf, wins / 2 - 1, wins / 2 - 1, radius_pix);
+    hdrl_image * tmpimg = hdrl_image_create(psf, NULL);
+    hdrl_value pflux = hdrl_image_sum_where(tmpimg, pm);
+    hdrl_image_delete(tmpimg);
+    cpl_msg_debug(cpl_func, "flux ring/total psf: %g %g", pflux.data,
+                 cpl_image_get_flux(psf));
+    cpl_mask_delete(pm);
+
+    double ratio_psf = ppeak / pflux.data;
+
+    cpl_msg_debug(cpl_func, "data peak,flux,ratio: %g %g: %g",
+                  ipeak.data, iflux.data, ratio_img);
+    cpl_msg_debug(cpl_func, "psf peak,flux,ratio:  %g %g: %g",
+                  ppeak, pflux.data, ratio_psf);
+
+    double strehl = ratio_img / ratio_psf;
+    double strehl_err = strehl *
+        sqrt(ipeak.error * ipeak.error / (ipeak.data * ipeak.data) +
+             iflux.error * iflux.error / (iflux.data * iflux.data));
+
+    cpl_msg_debug(cpl_func, "Strehl ratio %g +/- %g", strehl, strehl_err);
+    cpl_image_delete(psf);
+
+    hdrl_strehl_result r;
+    r.strehl_value = (hdrl_value){strehl, strehl_err};
+    r.star_peak = ipeak;
+    r.star_flux = iflux;
+    r.star_background = (hdrl_value){0, 0};
+    /* TODO:
+     * error on negative flux, error on disk max position != fit position */
+    return r;
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief compute image Strehl
+ * @param himg background corrected image
+ * @param lam  wavelength [m]
+ * @param m1_radius   primary mirror radius [m]
+ * @param m2_radius   obstruction radius [m]
+ * @param pixscale_x    image X pixel scale in [arcsec]
+ * @param pixscale_y    image Y pixel scale in [arcsec]
+ * @param flux_radius   radius used to sum the flux [arcsec]
+ * @param bkg_radius_low_def  radius used to determine the background [arcsec]
+ * @param bkg_radius_high_def radius used to determine the background [arcsec]
+ *
+ * @return an hdrl_strehl_result containing the computed Strehl value and its error
+ * or NAN in case of error.
+ *
+ * @doc
+ * This function assumes that the input image is pre-processed to remove
+ * instrument signatures (flag bad pixels, etc.) and correct for the natural
+ * noise sources (sky background, etc.). Bad pixels are interpolated.
+ *
+ * The routine initially determines the approximate position and flux value of
+ * the PSF with a Gaussian fit.
+ * @see gaussian_maxpos()
+ *
+ * If the user sets the parameters bkg_radius_low, bkg_radius_high to -1, the
+ * routine assumes that the input image has zero background level.
+ * Else if the user set the parameters bkg_radius_low, bkg_radius_high to proper
+ * values the routine measure the background in the corresponding annular
+ * region and subtract it. This second option is recommended.
+ *
+ * Then the strehl ratio and its associated error are computed.
+ * @see compute_streh2()
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+static hdrl_strehl_result
+compute_strehl(const hdrl_image * himg_, double lam,
+               double m1_radius, double m2_radius,
+               double pixscale_x, double pixscale_y, double flux_radius,
+               double bkg_radius_low, double bkg_radius_high)
+{
+    hdrl_image * himg = hdrl_image_duplicate(himg_);
+    double xposfit, yposfit, peak;
+    double min_pscale = CX_MIN(pixscale_x, pixscale_y);
+    const cpl_image * img = hdrl_image_get_image_const(himg);
+    /* interpolate bad pixels, */
+    if (hdrl_image_count_rejected(himg) != 0) {
+        cpl_msg_warning(cpl_func,
+                        "%zu bad pixels in strehl input, interpolating.",
+                        (size_t)hdrl_image_count_rejected(himg) );
+        cpl_detector_interpolate_rejected(hdrl_image_get_image(himg));
+        /* should have error propagation here .. */
+        cpl_detector_interpolate_rejected(hdrl_image_get_error(himg));
+    }
+
+    if (gaussian_maxpos(img, 5, &xposfit, &yposfit, &peak) != CPL_ERROR_NONE) {
+        goto error;
+    }
+    if (peak <= 0) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                              "detected peak of star smaller than zero, "
+                              "gaussian fit likely failed to fit the star");
+        goto error;
+    }
+    hdrl_value bkg = {0, 0};
+    double comp_bkg_error = -1;
+    size_t nbkg_pix = 0;
+    if ((bkg_radius_low < 0 && bkg_radius_high >= 0) ||
+        (bkg_radius_low >= 0 && bkg_radius_high < 0)) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT,
+                              "background radius parameters must be larger "
+                              "zero or both negative");
+        goto error;
+    }
+    else if (bkg_radius_low >= 0 && bkg_radius_high >= 0) {
+        if (bkg_radius_low >= bkg_radius_high) {
+            cpl_error_set_message(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT,
+                          "low background radius parameters must be smaller "
+                          "than large background radius");
+            goto error;
+        }
+        /* compute mask of background ring */
+        cpl_mask * high = strehl_disk_mask(img, xposfit, yposfit,
+                                           bkg_radius_high / min_pscale);
+        cpl_mask * low = strehl_disk_mask(img, xposfit, yposfit,
+                                          bkg_radius_low / min_pscale);
+        cpl_mask_xor(low, high);
+        nbkg_pix = cpl_mask_count(low);
+        if (nbkg_pix == 0) {
+            cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_INPUT,
+                          "No valid pixels in background");
+            cpl_mask_delete(low);
+            cpl_mask_delete(high);
+            goto error;
+        }
+
+        cpl_mask_not(low);
+        bkg = hdrl_image_median_where(himg, low);
+        comp_bkg_error = hdrl_image_stdev_where(himg, low) / sqrt(nbkg_pix);
+        /* expected difference sqrt(pi / 2)  due to median */
+        cpl_msg_debug(cpl_func, "Median estimated background: %g +- %g "
+                      "(computed error %g)", bkg.data, bkg.error,
+                      comp_bkg_error);
+        cpl_mask_delete(low);
+        cpl_mask_delete(high);
+
+        hdrl_image_sub_scalar(himg, bkg);
+    }
+
+    hdrl_strehl_result r = compute_strehl2(himg, lam, m1_radius, m2_radius,
+                                   pixscale_x, pixscale_y, xposfit, yposfit,
+                                   flux_radius);
+    hdrl_image_delete(himg);
+    r.star_background = bkg;
+    r.star_x = xposfit;
+    r.star_y = yposfit;
+    r.computed_background_error = comp_bkg_error;
+    r.nbackground_pixels = nbkg_pix;
+    return r;
+
+error:
+    hdrl_image_delete(himg);
+    return bad_result;
+}
+/** @endcond */
+
+/* TODO: missing doxygen, add more comments */
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief This function computes the Strehl ratio.
+ * @param himg input hdrl image
+ * @param params input hdrl parameters
+ *
+ * @see hdrl_strehl_parameter_create()
+ *
+ * The raw image is assumed to be pre-processed to remove the instrument
+ * signatures (bad pixels, etc.) and the natural noise sources (sky background,
+ * etc.). Nethertheless this function allows also the user to correct a residual
+ * background by setting the parameters \e bkg_radius\_low, \e bkg_radius_high.
+ * The PSF is identified and its integrated flux (controlled by the parameter
+ * \e flux_radius) is normalized to 1. The
+ * PSF baricenter is computed and used to generate the ideal PSF (with
+ * integrated flux normalized to 1) which takes into account the telescope pupil
+ * characteristics (radius \e m1, central obstruction, \e m2, .…), the
+ * wavelength \e wavelength, at which the image has been obtained and the
+ * related pixel scale (\e pixel_scale_x, \e pixel_scale_y,). Finally the Strehl
+ * ratio is computed dividing the maximum intensity of the image PSF by the
+ * maximum intensity of the ideal PSF and the associated error is also computed.
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_strehl_result
+hdrl_strehl_compute(const hdrl_image * himg, hdrl_parameter* params)
+{
+    hdrl_strehl_result r;
+    /* Check Entries */
+
+    cpl_error_ensure(himg && params, CPL_ERROR_NULL_INPUT,
+                     return bad_result,
+                                     "NULL input");
+    if (hdrl_strehl_parameter_verify(params) != CPL_ERROR_NONE) {
+        return bad_result;
+    }
+
+    /* Local Usage Parameters */
+    const hdrl_strehl_parameter * p_loc = (hdrl_strehl_parameter *)params ;
+
+    r = compute_strehl(himg,p_loc->wavelength, p_loc->m1, p_loc->m2,
+                    p_loc->pixel_scale_x, p_loc->pixel_scale_y,
+                    p_loc->flux_radius, p_loc->bkg_radius_low,
+                    p_loc->bkg_radius_high);
+    return r;
+}
+
+/**@}*/
+
diff --git a/hdrl/hdrl_strehl.h b/hdrl/hdrl_strehl.h
new file mode 100644
index 0000000..2760cae
--- /dev/null
+++ b/hdrl/hdrl_strehl.h
@@ -0,0 +1,99 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef HDRL_STREHL_H
+#define HDRL_STREHL_H
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+#include "hdrl_types.h"
+#include "hdrl_image.h"
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                                Define
+ -----------------------------------------------------------------------------*/
+
+/*-----------------------------------------------------------------------------
+                            Functions prototypes
+ -----------------------------------------------------------------------------*/
+
+#if defined HDRL_USE_EXPERIMENTAL || defined HDRL_USE_PRIVATE
+
+typedef struct {
+    /* computed strehl value and its propagated error */
+    hdrl_value strehl_value;
+    /* computed x and y position of the star peak */
+    double star_x, star_y;
+    /* star peak and its propagated error */
+    hdrl_value star_peak;
+    /* star flux and its propagated error */
+    hdrl_value star_flux;
+    /* star background and its propagated error */
+    hdrl_value star_background;
+    /* star background error estimated from image
+     * on normal data sqrt(pi / 2) larger that star_background error as it is
+     * estimated via a median */
+    double computed_background_error;
+    /* number of pixels used for background estimation */
+    size_t nbackground_pixels;
+} hdrl_strehl_result;
+
+hdrl_parameter * hdrl_strehl_parameter_create(double lam, double m1,
+        double m2, double pixscale_x, double pixscale_y, double flux_radius,
+        double bkg_radius_low, double bkg_radius_high) ;
+
+cpl_boolean hdrl_strehl_parameter_check(const hdrl_parameter *) ;
+cpl_parameterlist * hdrl_strehl_parameter_create_parlist(
+        const char      *   base_context,
+        const char      *   prefix,
+        hdrl_parameter  *   par);
+
+hdrl_parameter * hdrl_strehl_parameter_parse_parlist(
+        const cpl_parameterlist *   parlist,
+        const char              *   prefix);
+
+double hdrl_strehl_parameter_get_wavelength(const hdrl_parameter * p);
+double hdrl_strehl_parameter_get_m1(const hdrl_parameter * p);
+double hdrl_strehl_parameter_get_m2(const hdrl_parameter * p);
+double hdrl_strehl_parameter_get_pixel_scale_x(const hdrl_parameter * p);
+double hdrl_strehl_parameter_get_pixel_scale_y(const hdrl_parameter * p);
+double hdrl_strehl_parameter_get_flux_radius(const hdrl_parameter * p);
+double hdrl_strehl_parameter_get_bkg_radius_low(const hdrl_parameter * p);
+double hdrl_strehl_parameter_get_bkg_radius_high(const hdrl_parameter * p);
+
+hdrl_strehl_result
+hdrl_strehl_compute(const hdrl_image * himg, hdrl_parameter* params);
+
+#endif
+
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+ -----------------------------------------------------------------------------*/
+
+#ifdef HDRL_USE_PRIVATE
+
+#endif
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_test.h b/hdrl/hdrl_test.h
new file mode 100644
index 0000000..9683ed1
--- /dev/null
+++ b/hdrl/hdrl_test.h
@@ -0,0 +1,54 @@
+/* $Id: hdrl_test.h,v 1.1 2013-10-22 08:26:11 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-22 08:26:11 $
+ * $Revision: 1.1 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifndef HDRL_TEST_H
+#define HDRL_TEST_H
+
+#include "hdrl_image.h"
+#include "hdrl_types.h"
+
+#include <cpl.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                                   Macros
+ -----------------------------------------------------------------------------*/
+
+#define hdrl_test_image_abs(himg1, himg2, tol) \
+{ \
+    cpl_test_image_abs(hdrl_image_get_image_const(himg1), \
+                       hdrl_image_get_image_const(himg2), tol * \
+                       HDRL_EPS_ERROR / HDRL_EPS_DATA); \
+    cpl_test_image_abs(hdrl_image_get_error_const(himg1), \
+                       hdrl_image_get_error_const(himg2), tol * \
+                       HDRL_EPS_ERROR / HDRL_EPS_DATA); \
+}
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/hdrl_types.h b/hdrl/hdrl_types.h
new file mode 100644
index 0000000..c9c4c91
--- /dev/null
+++ b/hdrl/hdrl_types.h
@@ -0,0 +1,82 @@
+/* $Id: hdrl_types.h,v 1.2 2013-10-11 13:46:00 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-11 13:46:00 $
+ * $Revision: 1.2 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifndef HDRL_TYPES_H
+#define HDRL_TYPES_H
+
+#include <float.h> /* for epsilon */
+#include <stddef.h> /* for size_t */
+
+/*-----------------------------------------------------------------------------
+                                   Generic types
+ -----------------------------------------------------------------------------*/
+
+typedef void * (hdrl_alloc)(size_t);
+typedef void (hdrl_free)(void *);
+
+/* basic type for bit mask values, e.g. bad pixel classifications */
+typedef unsigned int hdrl_bitmask_t;
+
+#ifndef HDRL_SIZEOF_DATA
+#define HDRL_SIZEOF_DATA 8
+#endif
+#ifndef HDRL_SIZEOF_ERROR
+#define HDRL_SIZEOF_ERROR 8
+#endif
+
+/* makes little sense and causes problems when error propagation
+ * mixes the two types (mul/div) */
+#if HDRL_SIZEOF_ERROR > HDRL_SIZEOF_DATA
+#error HDRL_SIZEOF_ERROR must not be larger than HDRL_SIZEOF_DATA
+#endif
+
+#if HDRL_SIZEOF_DATA == 4
+typedef float hdrl_data_t;
+#define HDRL_TYPE_DATA CPL_TYPE_FLOAT
+#define HDRL_EPS_DATA FLT_EPSILON
+#else
+typedef double hdrl_data_t;
+#define HDRL_TYPE_DATA CPL_TYPE_DOUBLE
+#define HDRL_EPS_DATA DBL_EPSILON
+#endif
+
+#if HDRL_SIZEOF_ERROR == 4
+typedef float hdrl_error_t;
+#define HDRL_TYPE_ERROR CPL_TYPE_FLOAT
+#define HDRL_EPS_ERROR FLT_EPSILON
+#else
+typedef double hdrl_error_t;
+#define HDRL_TYPE_ERROR CPL_TYPE_DOUBLE
+#define HDRL_EPS_ERROR DBL_EPSILON
+#endif
+
+typedef struct {
+    hdrl_data_t data;
+    hdrl_error_t error;
+} hdrl_value;
+
+#endif 
diff --git a/hdrl/hdrl_utils.c b/hdrl/hdrl_utils.c
new file mode 100644
index 0000000..d5ad98f
--- /dev/null
+++ b/hdrl/hdrl_utils.c
@@ -0,0 +1,1394 @@
+/*
+ * This file is part of the HDRL 
+ * Copyright (C) 2012,2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                   Includes
+-----------------------------------------------------------------------------*/
+
+#ifndef _XOPEN_SOURCE
+#define _XOPEN_SOURCE 500 /* posix 2001, mkstemp */
+#endif
+
+#include "hdrl_utils.h"
+#include "hdrl_types.h"
+#include "hdrl_elemop.h"
+#include "hdrl_prototyping.h"
+#include "hdrl_imagelist.h"
+#include <string.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <errno.h>
+#include <math.h>
+#include <stdarg.h>
+
+/*-----------------------------------------------------------------------------
+                                   Static
+ -----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_utils   General Utility Functions
+  
+  This module contain various utilities functions that might be used in several
+  of the HDRL modules.
+ */
+/*----------------------------------------------------------------------------*/
+
+/**@{*/
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Get the pipeline copyright and license
+  @return   The copyright and license string
+
+  The function returns a pointer to the statically allocated license string.
+  This string should not be modified using the returned pointer.
+ */
+/*----------------------------------------------------------------------------*/
+const char * hdrl_get_license(void)
+{
+    static const char  *   hdrl_license =
+        "This file is part of the HDRL Instrument Pipeline\n"
+        "Copyright (C) 2012,2013 European Southern Observatory\n"
+        "\n"
+        "This program is free software; you can redistribute it and/or modify\n"
+        "it under the terms of the GNU General Public License as published by\n"
+        "the Free Software Foundation; either version 2 of the License, or\n"
+        "(at your option) any later version.\n"
+        "\n"
+        "This program is distributed in the hope that it will be useful,\n"
+        "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
+        "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
+        "GNU General Public License for more details.\n"
+        "\n"
+        "You should have received a copy of the GNU General Public License\n"
+        "along with this program; if not, write to the Free Software\n"
+        "Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, \n"
+        "MA  02110-1301  USA";
+
+    return hdrl_license;
+}
+
+/*-----------------------------------------------------------------------------
+                Rectangular Region Parameters Definition
+ -----------------------------------------------------------------------------*/
+
+/** @cond PRIVATE */
+typedef struct {
+    HDRL_PARAMETER_HEAD;
+    cpl_size    llx ;
+    cpl_size    lly ;
+    cpl_size    urx ;
+    cpl_size    ury ;
+} hdrl_rect_region_parameter;
+
+/* Parameter type */
+static hdrl_parameter_typeobj hdrl_rect_region_parameter_type = {
+    HDRL_PARAMETER_RECT_REGION,     /* type */
+    (hdrl_alloc *)&cpl_malloc,      /* fp_alloc */
+    (hdrl_free *)&cpl_free,         /* fp_free */
+    NULL,                           /* fp_destroy */
+    sizeof(hdrl_rect_region_parameter), /* obj_size */
+};
+
+/** @endcond */
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Creates Rect Region Parameters object
+  @param    llx
+  @param    lly
+  @param    urx
+  @param    ury
+  @return   the Rect Region parameters
+ */
+/*----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_rect_region_parameter_create(
+        cpl_size    llx,
+        cpl_size    lly,
+        cpl_size    urx,
+        cpl_size    ury)
+{
+    hdrl_rect_region_parameter * p = (hdrl_rect_region_parameter *)
+               hdrl_parameter_new(&hdrl_rect_region_parameter_type);
+    p->llx = llx ;
+    p->lly = lly ;
+    p->urx = urx ;
+    p->ury = ury ;
+    return (hdrl_parameter *)p;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Update Rect Region Parameters object
+  @param    rect_region     The region to update
+  @param    llx
+  @param    lly
+  @param    urx
+  @param    ury
+  @return   the error code in case of error or CPL_ERROR_NONE
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_rect_region_parameter_update(
+        hdrl_parameter  *   rect_region,
+        cpl_size            llx,
+        cpl_size            lly,
+        cpl_size            urx,
+        cpl_size            ury)
+{
+    hdrl_rect_region_parameter * p = (hdrl_rect_region_parameter *)rect_region ;
+    p->llx = llx ;
+    p->lly = lly ;
+    p->urx = urx ;
+    p->ury = ury ;
+    return hdrl_rect_region_parameter_verify(rect_region, -1, -1);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Check that the parameter is hdrl_rect_region parameter
+  @return   the parameter to check
+ */
+/*----------------------------------------------------------------------------*/
+cpl_boolean hdrl_rect_region_parameter_check(const hdrl_parameter * self)
+{
+    return hdrl_parameter_check_type(self, &hdrl_rect_region_parameter_type);
+}
+
+/*-----------------------------------------------------------------------------
+                        Rect Region Parameters Accessors
+ -----------------------------------------------------------------------------*/
+
+/**
+ * @brief get lower left x coordinate of rectangual region
+ */
+cpl_size hdrl_rect_region_get_llx(const hdrl_parameter * p) 
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1) ;
+    return ((hdrl_rect_region_parameter *)p)->llx;
+}
+
+/**
+ * @brief get lower left y coordinate of rectangual region
+ */
+cpl_size hdrl_rect_region_get_lly(const hdrl_parameter * p) 
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1) ;
+    return ((hdrl_rect_region_parameter *)p)->lly;
+}
+
+/**
+ * @brief get upper right x coordinate of rectangular region
+ */
+cpl_size hdrl_rect_region_get_urx(const hdrl_parameter * p) 
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1) ;
+    return ((hdrl_rect_region_parameter *)p)->urx;
+}
+
+/**
+ * @brief get upper right y coordinate of rectangual region
+ */
+cpl_size hdrl_rect_region_get_ury(const hdrl_parameter * p) 
+{
+    cpl_ensure(p, CPL_ERROR_NULL_INPUT, -1) ;
+    return ((hdrl_rect_region_parameter *)p)->ury;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    Verify basic correctness of the parameters
+  @param    param   rect region parameters
+  @param    max_x   max value for upper x bound, set to < 0 to skip check
+  @param    max_y   max value for upper y bound, set to < 0 to skip check
+  @return   CPL_ERROR_NONE if everything is ok, an error code otherwise
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_rect_region_parameter_verify(
+        const hdrl_parameter    *   param,
+        const cpl_size              max_x,
+        const cpl_size              max_y)
+{
+    const hdrl_rect_region_parameter * param_loc =
+        (hdrl_rect_region_parameter *)param ;
+
+    cpl_error_ensure(param != NULL, CPL_ERROR_NULL_INPUT,
+            return CPL_ERROR_NULL_INPUT, "NULL Input Parameters");
+    cpl_error_ensure(hdrl_rect_region_parameter_check(param),
+            CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT, 
+            "Expected Rect Region parameter") ;
+    cpl_error_ensure(param_loc->llx >= 1 && param_loc->lly >= 1 &&
+            param_loc->urx >= 1 && param_loc->ury >= 1, CPL_ERROR_ILLEGAL_INPUT,
+            return CPL_ERROR_ILLEGAL_INPUT,
+            "Coordinates must be strictly positive");
+
+    cpl_error_ensure(param_loc->urx >= param_loc->llx, CPL_ERROR_ILLEGAL_INPUT,
+                     return CPL_ERROR_ILLEGAL_INPUT,
+                     "urx (%ld) must be larger equal than llx (%ld)",
+                     (long)param_loc->urx, (long)param_loc->llx);
+    cpl_error_ensure(param_loc->ury >= param_loc->lly, CPL_ERROR_ILLEGAL_INPUT,
+                     return CPL_ERROR_ILLEGAL_INPUT,
+                     "ury (%ld) must be larger equal than lly (%ld)",
+                     (long)param_loc->ury, (long)param_loc->lly);
+    if (max_x > 0)
+        cpl_error_ensure(param_loc->urx <= max_x, CPL_ERROR_ILLEGAL_INPUT,
+                         return CPL_ERROR_ILLEGAL_INPUT,
+                         "urx %zu larger than maximum %zu",
+                         (size_t)param_loc->urx, (size_t)max_x);
+    if (max_y > 0)
+        cpl_error_ensure(param_loc->urx <= max_x, CPL_ERROR_ILLEGAL_INPUT,
+                         return CPL_ERROR_ILLEGAL_INPUT,
+                         "ury %zu larger than maximum %zu",
+                         (size_t)param_loc->ury, (size_t)max_y);
+    return CPL_ERROR_NONE;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+  @brief Create parameter list for hdrl_rect_region
+  @param base_context   base context of parameter (e.g. recipe name)
+  @param prefix         prefix of parameter, may be empty string
+  @param name_prefix    prefix for the parameter names, may be empty string
+  @param defaults       default parameters values
+  @return cpl_parameterlist
+  Creates a parameterlist containing
+      base_context.prefix.name-prefixllx
+      base_context.prefix.name-prefixlly
+      base_context.prefix.name-prefixurx
+      base_context.prefix.name-prefixury
+  The CLI aliases omit the base_context.
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_parameterlist * hdrl_rect_region_parameter_create_parlist(
+        const char              *   base_context,
+        const char              *   prefix,
+        const char              *   name_prefix,
+        const hdrl_parameter    *   defaults)
+{
+    cpl_ensure(base_context && prefix && name_prefix && defaults,
+               CPL_ERROR_NULL_INPUT, NULL);
+    cpl_parameterlist * parlist = cpl_parameterlist_new();
+
+    /* --prefix.llx */
+    hdrl_setup_vparameter(parlist, prefix, ".", name_prefix,
+                         "llx", base_context,
+                         "Lower left x pos. (FITS) defining the region",
+                         CPL_TYPE_INT, (int)hdrl_rect_region_get_llx(defaults));
+    /* --prefix.lly */
+    hdrl_setup_vparameter(parlist, prefix, ".", name_prefix,
+                         "lly", base_context,
+                         "Lower left y pos. (FITS) defining the region",
+                         CPL_TYPE_INT, (int)hdrl_rect_region_get_lly(defaults));
+
+    /* --prefix.urx */
+    hdrl_setup_vparameter(parlist, prefix, ".", name_prefix,
+                         "urx", base_context,
+                         "Upper right x pos. (FITS) defining the region",
+                         CPL_TYPE_INT, (int)hdrl_rect_region_get_urx(defaults));
+
+    /* --prefix.ury */
+    hdrl_setup_vparameter(parlist, prefix, ".", name_prefix,
+                         "ury", base_context,
+                         "Upper right y pos. (FITS) defining the region",
+                         CPL_TYPE_INT, (int)hdrl_rect_region_get_ury(defaults));
+
+    if (cpl_error_get_code()) {
+        cpl_parameterlist_delete(parlist);
+        return NULL;
+    }
+
+    return parlist;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ @brief parse parameterlist for rectangle parameters
+ @param parlist      parameter list to parse
+ @param prefix       prefix of parameter
+ @param name_prefix  prefix of parameter name, may be empty string
+ @see   hdrl_rect_get_parlist()
+ @return A newly allocated hdrl_rect_region parameter or NULL in error case
+    
+ The returned object must be deallocated with hdrl_parameter_delete()
+ parameterlist should have been created with hdrl_rect_get_parlist or have the 
+ same name hierachy
+ */
+/* ---------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_rect_region_parameter_parse_parlist(
+        const cpl_parameterlist *   parlist,
+        const char              *   prefix,
+        const char              *   name_prefix)
+{
+    cpl_size llx, lly, urx, ury ;
+    cpl_error_ensure(prefix && parlist, CPL_ERROR_NULL_INPUT,
+            return NULL, "NULL Input Parameters");
+    const char * sep = strlen(prefix) > 0 ? "." : "";
+    const char * points[] = {"llx", "lly", "urx", "ury"};
+    cpl_size * dest[] = {&llx, &lly, &urx, &ury};
+    for (size_t i = 0; i < 4; i++) {
+        char * name = cpl_sprintf("%s%s%s%s", prefix, sep,
+                                  name_prefix, points[i]);
+        const cpl_parameter * par = cpl_parameterlist_find_const(parlist, name);
+        *(dest[i]) = cpl_parameter_get_int(par);
+        cpl_free(name);
+    }
+
+    if (cpl_error_get_code()) {
+        cpl_error_set_message(cpl_func, CPL_ERROR_DATA_NOT_FOUND,
+                              "Error while parsing parameterlist "
+                              "with prefix %s", prefix);
+        return NULL;
+    }
+
+    return hdrl_rect_region_parameter_create(llx, lly, urx, ury) ;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief join strings together
+ *
+ * @param sep_ separator to place between strings, NULL equals empty string
+ * @param n    number of strings to join
+ *
+ * The input strings may be empty or NULL in which case it skips the entry
+ * adding no extra separator.
+ *
+ * @return joined string, must be deallocated by user with cpl_free
+ */
+/* ---------------------------------------------------------------------------*/
+char * hdrl_join_string(const char * sep_, int n, ...)
+{
+    va_list vl;
+    char * res = NULL;
+    const char * sep = sep_ ? sep_ : "";
+    cpl_ensure(n > 0, CPL_ERROR_ILLEGAL_INPUT, NULL);
+
+    va_start(vl, n);
+    for (int i = 0; i < n; i++) {
+        char * tmp = res;
+        char * val = va_arg(vl, char *);
+        if (val == NULL || strlen(val) == 0) {
+            continue;
+        }
+        if (!res) {
+            res = cpl_strdup(val);
+        }
+        else {
+            res = cpl_sprintf("%s%s%s", res, sep, val);
+        }
+        cpl_free(tmp);
+    }
+    va_end(vl);
+
+    return res;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief    wrap negative or zero coordinates around full image size
+  @param    rect_region  rect region to wrap
+  @param    nx   image size in x, nx is added to entries < 1
+  @param    ny   image size in y, ny is added to entries < 1
+  @return  cpl_error_code
+
+  allows reverse indexing: 0 would be nx, -2 would be nx - 2 etc
+  Wrapping is based in FITS convention: 1 first pixel, nx last pixel inclusive
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_rect_region_fix_negatives(
+        hdrl_parameter    *     rect_region,
+        const cpl_size          nx,
+        const cpl_size          ny)
+{
+    hdrl_rect_region_parameter * rr_loc =
+        (hdrl_rect_region_parameter *)rect_region ;
+
+    cpl_error_ensure(rect_region != 0, CPL_ERROR_NULL_INPUT,
+            return CPL_ERROR_NULL_INPUT, "region input must not be NULL");
+    cpl_error_ensure(hdrl_rect_region_parameter_check(rect_region),
+            CPL_ERROR_ILLEGAL_INPUT, return CPL_ERROR_ILLEGAL_INPUT,
+            "Expected Rect Region parameter") ;
+
+    if (nx > 0 && rr_loc->llx < 1) rr_loc->llx += nx;
+    if (ny > 0 && rr_loc->lly < 1) rr_loc->lly += ny;
+    if (nx > 0 && rr_loc->urx < 1) rr_loc->urx += nx;
+    if (ny > 0 && rr_loc->ury < 1) rr_loc->ury += ny;
+
+    return hdrl_rect_region_parameter_verify(rect_region, nx, ny);
+}
+
+
+/** @cond EXPERIMENTAL */
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief return file descriptor of a temporary file
+ * @param dir     directory prefix to place the file in, may be NULL
+ * @param unlink  unlink the file from the filesystem immediately
+ * @return file descriptor or -1 on error
+ * @note if dir is NULL or not writable it tries to create a file in following
+ *       directories in decreasing order of preference:
+ *       $TMPDIR, /var/tmp, /tmp, $PWD
+ */
+/* ---------------------------------------------------------------------------*/
+int hdrl_get_tempfile(const char * dir, cpl_boolean unlink)
+{
+    /* options in decreasing preference */
+    const char * tmpdirs[] = {
+        /* user override */
+        getenv("TMPDIR"),
+        /* large file temp */
+        "/var/tmp/",
+        /* small file temp, may be tmpfs */
+        "/tmp/"
+    };
+    const size_t ndirs = sizeof(tmpdirs) / sizeof(tmpdirs[0]);
+    const char * tmpdir = NULL;
+
+    if (dir && access(dir, W_OK) == 0) {
+        tmpdir = dir;
+    }
+    else {
+        for (size_t i = 0; i < ndirs; i++) {
+            if (tmpdirs[i] && access(tmpdirs[i], W_OK) == 0) {
+                tmpdir = tmpdirs[i];
+                break;
+            }
+        }
+    }
+
+    {
+        /* try $PWD if no tmpdir found */
+        char * template = hdrl_join_string("/", 2, tmpdir, "hdrl_tmp_XXXXXX");
+        int fd = mkstemp(template);
+        if (fd == -1) {
+            cpl_error_set_message(cpl_func, CPL_ERROR_FILE_IO,
+                                  "Temporary file creation failed: %s",
+                                  strerror(errno));
+            cpl_free(template);
+            return -1;
+        }
+
+        cpl_msg_debug(cpl_func, "Created tempfile %s", template);
+
+        if (unlink) {
+            remove(template);
+        }
+        cpl_free(template);
+
+        return fd;
+    }
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ @brief get the absoluet current working directory
+ @return char string, must be deleted by the user with cpl_free
+ */
+/* ---------------------------------------------------------------------------*/
+char * hdrl_get_cwd(void)
+{
+    size_t n = 4096;
+    char * buf;
+    errno = 0;
+    /* if only we could use sane GNU functions instead of this posix crap */
+    while (1) {
+        buf = cpl_malloc(n);
+        if (getcwd(buf, n) != 0) {
+            break;
+        }
+        else if (errno == ERANGE) {
+            /* increase buffer, repeat */
+            errno = 0;
+            n *= 2;
+            cpl_free(buf);
+        }
+        else {
+            cpl_free(buf);
+            cpl_error_set_message(cpl_func, CPL_ERROR_FILE_IO,
+                                  "Could not determine current working "
+                                  "directory: %s", strerror(errno));
+            return NULL;
+        }
+    }
+
+    return buf;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief scale a imagelist using scaling factors in a vector
+ *
+ * @param scale      vector containing scaling factors, the first element
+ *                   defines the value to scale to
+ * @param scale_e    errors of the scaling factors
+ * @param scale_type scale type, additive or multiplicative
+ * @param data       imagelist to be scaled
+ * @param errors     errors of imagelist to be scaled
+ *
+ * If scale_type is HDRL_SCALE_ADDITIVE the difference of each value in the
+ * scaling vector is subtracted from the first element of the vector and added
+ * to each image in the imagelist.
+ *
+ * for i in vector.size:
+ *   data[i] += vector[0] - vector[i]
+ *
+ * If scale_type is HDRL_SCALE_MULTIPLICATIVE the quotient of each value in
+ * the scaling vector to the first element of the vector is multiplied
+ * to each image in the imagelist.
+ * If an element of the scaling vector is zero the image will have all its
+ * pixels marked as bad in its bad pixel map.
+ *
+ * for i in vector.size:
+ *   data[i] *= vector[0] / vector[i]
+ *
+ * The errors are propagated using error propagation of first order
+ * and assuming no correlations between the values.
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_normalize_imagelist_by_vector(const cpl_vector * scale,
+                                   const cpl_vector * scale_e,
+                                   const hdrl_scale_type scale_type,
+                                   cpl_imagelist * data,
+                                   cpl_imagelist * errors)
+{
+    cpl_ensure_code(scale, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(scale_e, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(data, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(errors, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(cpl_vector_get_size(scale) == cpl_imagelist_get_size(data),
+                    CPL_ERROR_ILLEGAL_INPUT);
+    cpl_ensure_code(cpl_vector_get_size(scale_e) == cpl_vector_get_size(scale),
+                    CPL_ERROR_ILLEGAL_INPUT);
+    cpl_ensure_code(cpl_imagelist_get_size(errors) ==
+                    cpl_imagelist_get_size(data), CPL_ERROR_ILLEGAL_INPUT);
+
+    for (size_t i = 1; i < (size_t)cpl_imagelist_get_size(data); i++) {
+        const hdrl_data_t dfirst = cpl_vector_get(scale, 0);
+        const hdrl_error_t efirst = cpl_vector_get(scale_e, 0);
+        cpl_image * dimg = cpl_imagelist_get(data, i);
+        cpl_image * eimg = cpl_imagelist_get(errors, i);
+        if (scale_type == HDRL_SCALE_ADDITIVE) {
+            hdrl_data_t dscale_o = cpl_vector_get(scale, i);
+            hdrl_error_t escale_o =  cpl_vector_get(scale_e, i);
+
+            /* dscale = dfirst - dscale_o */
+            hdrl_data_t dscale = dfirst;
+            hdrl_error_t escale = efirst;
+            hdrl_elemop_sub(&dscale, &escale, 1, &dscale_o, &escale_o, 1, NULL);
+
+            /* dimg = dimg + dscale */
+            hdrl_elemop_image_add_scalar(dimg, eimg, dscale, escale);
+        }
+        else if (scale_type == HDRL_SCALE_MULTIPLICATIVE) {
+            hdrl_data_t dscale_o = cpl_vector_get(scale, i);
+            hdrl_error_t escale_o = cpl_vector_get(scale_e, i);
+
+            if (dscale_o == 0.) {
+                cpl_msg_warning(cpl_func, "scale factor of image %zu is "
+                                "not a number", i);
+                cpl_image_add_scalar(dimg, NAN);
+                cpl_image_add_scalar(eimg, NAN);
+                cpl_image_reject_value(dimg, CPL_VALUE_NAN);
+                cpl_image_reject_value(eimg, CPL_VALUE_NAN);
+                continue;
+            }
+
+            /* dscale = dfirst / dscale_o */
+            hdrl_data_t dscale = dfirst;
+            hdrl_error_t escale = efirst;
+            hdrl_elemop_div(&dscale, &escale, 1, &dscale_o, &escale_o, 1, NULL);
+
+            /* dimg = dimg * dscale */
+            hdrl_elemop_image_mul_scalar(dimg, eimg, dscale, escale);
+        }
+        else {
+            return cpl_error_set_message(cpl_func, CPL_ERROR_UNSUPPORTED_MODE,
+                                         "Unsupported scale type");
+        }
+
+        if (cpl_error_get_code())
+            break;
+    }
+
+    return cpl_error_get_code();
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief scale a imagelist using scaling images
+ *
+ * @param scale      imagelist containing scaling factors, the first element
+ *                   defines the value to scale to
+ * @param scale_e    errors of the scaling factors
+ * @param scale_type scale type, additive or multiplicative
+ * @param data       imagelist to be scaled
+ * @param errors     errors of imagelist to be scaled
+ *
+ * If scale_type is HDRL_SCALE_ADDITIVE the difference of each value in the
+ * scaling imagelist is subtracted from the first element of the vector and
+ * added to each image in the imagelist.
+ *
+ * for i in vector.size:
+ *   data[i] += scale[0] - scale[i]
+ *
+ * If scale_type is HDRL_SCALE_MULTIPLICATIVE the quotient of each value in
+ * the scaling vector to the first element of the imagelist is multiplied
+ * to each image in the imagelist.
+ * If an element of the scaling vector is zero the image will have all its
+ * pixels marked as bad in its bad pixel map.
+ *
+ * for i in vector.size:
+ *   data[i] *= scale[0] / scale[i]
+ *
+ * The errors are propagated using error propagation of first order
+ * and assuming no correlations between the values.
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_normalize_imagelist_by_imagelist(const cpl_imagelist * scale,
+                                      const cpl_imagelist * scale_e,
+                                      const hdrl_scale_type scale_type,
+                                      cpl_imagelist * data,
+                                      cpl_imagelist * errors)
+{
+    cpl_ensure_code(scale, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(scale_e, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(data, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(errors, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(cpl_imagelist_get_size(scale) ==
+                    cpl_imagelist_get_size(data), CPL_ERROR_ILLEGAL_INPUT);
+    cpl_ensure_code(cpl_imagelist_get_size(scale_e) ==
+                    cpl_imagelist_get_size(scale), CPL_ERROR_ILLEGAL_INPUT);
+    cpl_ensure_code(cpl_imagelist_get_size(errors) ==
+                    cpl_imagelist_get_size(data), CPL_ERROR_ILLEGAL_INPUT);
+
+    for (size_t i = 1; i < (size_t)cpl_imagelist_get_size(data); i++) {
+        cpl_image * dscale =
+            cpl_image_duplicate(cpl_imagelist_get_const(scale, 0));
+        cpl_image * escale =
+            cpl_image_duplicate(cpl_imagelist_get_const(scale_e, 0));
+        cpl_image * dimg = cpl_imagelist_get(data, i);
+        cpl_image * eimg = cpl_imagelist_get(errors, i);
+        const cpl_image * dscale_o = cpl_imagelist_get_const(scale, i);
+        const cpl_image * escale_o = cpl_imagelist_get_const(scale_e, i);
+
+        if (scale_type == HDRL_SCALE_ADDITIVE) {
+            /* dscale = dfirst - dscale_o */
+            hdrl_elemop_image_sub_image(dscale, escale, dscale_o, escale_o);
+
+            /* dimg = dimg + dscale */
+            hdrl_elemop_image_add_image(dimg, eimg, dscale, escale);
+        }
+        else if (scale_type == HDRL_SCALE_MULTIPLICATIVE) {
+            /* dscale = dfirst / dscale_o */
+            hdrl_elemop_image_div_image(dscale, escale, dscale_o, escale_o);
+
+            /* dimg = dimg * dscale */
+            hdrl_elemop_image_mul_image(dimg, eimg, dscale, escale);
+        }
+        else {
+            cpl_image_delete(dscale);
+            cpl_image_delete(escale);
+            return cpl_error_set_message(cpl_func, CPL_ERROR_UNSUPPORTED_MODE,
+                                         "Unsupported scale type");
+        }
+
+        cpl_image_delete(dscale);
+        cpl_image_delete(escale);
+
+        if (cpl_error_get_code())
+            break;
+    }
+
+    return cpl_error_get_code();
+}
+
+/** @endcond */
+
+
+/** @cond PRIVATE */
+
+/*----------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief    compress an image to a vector removing bad pixels
+  @param    source     image to compress
+  @param    bpm        optional bpm to use instead of the one in the image
+  @return  cpl_vector or NULL if no good pixels or error
+  @note    vector can't have size 0 so NULL is returned if all pixels are bad
+ */
+/*----------------------------------------------------------------------------*/
+cpl_vector * hdrl_image_to_vector(
+        const cpl_image     *   source, 
+        const cpl_mask      *   bpm)
+{
+    cpl_ensure(source != NULL, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_vector * vec_source = NULL;
+    /* only cast if required, extra copying of non double data is still
+     * faster than a loop with cpl_image_get */
+    cpl_image * d_img = cpl_image_get_type(source) == CPL_TYPE_DOUBLE ?
+        (cpl_image *)source : cpl_image_cast(source, CPL_TYPE_DOUBLE);
+
+    const cpl_size naxis1 = cpl_image_get_size_x(source);
+    const cpl_size naxis2 = cpl_image_get_size_y(source);
+
+    /* get raw data */
+    const double * restrict sdata = cpl_image_get_data_double_const(d_img);
+    const cpl_binary * restrict bpmd = NULL;
+
+    /* allocate output buffer */
+    double * restrict ddata = cpl_malloc(naxis1 * naxis2 *
+                                         sizeof(ddata[0]));
+    long j = 0;
+
+    if (bpm)
+        bpmd = cpl_mask_get_data_const(bpm);
+    else if (cpl_image_get_bpm_const(source) != NULL)
+        bpmd = cpl_mask_get_data_const(cpl_image_get_bpm_const(source));
+
+    if (bpmd == NULL) {
+        memcpy(ddata, sdata, naxis1 * naxis2 * sizeof(ddata[0]));
+        j = naxis1 * naxis2;
+    }
+    else {
+        /* copy only good pixels */
+        for (long i = 0; i < naxis1 * naxis2; i++) {
+            if (bpmd[i] == CPL_BINARY_0) {
+                ddata[j] = sdata[i];
+                j++;
+            }
+        }
+    }
+
+    assert(j == naxis1 * naxis2 -
+           (bpm ? cpl_mask_count(bpm) : cpl_image_count_rejected(source)));
+
+    if (j > 0) {
+        vec_source = cpl_vector_wrap(j, ddata);
+    }
+    else {
+        cpl_free(ddata);
+    }
+
+    if (d_img != source) cpl_image_delete(d_img);
+
+    return vec_source;
+}
+
+
+/* internal if imgdatabuf and maskbuf are not NULL they are assumed to hold the
+ * data buffers of the image in the list in order to save on cpl_image_get
+ * calls, error and type checking must be done by caller */
+static cpl_vector * imagelist_to_vector(const cpl_imagelist * list,
+                                        const cpl_size nx,
+                                        const cpl_size x,
+                                        const cpl_size y,
+                                        const double ** imgdatabuf,
+                                        const cpl_binary ** maskbuf)
+{
+    const long nz  = list ? cpl_imagelist_get_size(list) : -1;
+    cpl_vector * vec = NULL;
+    double * restrict ddata = NULL;
+    unsigned long j = 0;
+
+    ddata = cpl_malloc(nz * sizeof(ddata[0]));
+
+    if (imgdatabuf && maskbuf) {
+        for (long k = 0; k < nz; k++) {
+            double v = imgdatabuf[k][(y - 1) * nx + (x  - 1)];
+            cpl_binary rej = maskbuf[k] ?
+                maskbuf[k][(y - 1) * nx + (x  - 1)] : 0;
+
+            if (!rej) {
+                ddata[j] = v;
+                j++;
+            }
+        }
+    }
+    else {
+        for (long k = 0; k < nz; k++) {
+            int rej;
+            const cpl_image * img = cpl_imagelist_get_const(list, k);
+            double v = cpl_image_get(img, x, y, &rej);
+
+            if (!rej) {
+                ddata[j] = v;
+                j++;
+            }
+        }
+    }
+
+    if (j > 0) {
+        vec = cpl_vector_wrap(j, ddata);
+    }
+    else {
+        cpl_free(ddata);
+    }
+
+    return vec;
+}
+
+
+/*----------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief    compress an imagelist to a vector via z axis, removing bad pixels
+  @param    list     imagelist to compress
+  @param    x        x coordinate to compress over (FITS convention)
+  @param    y        y coordinate to compress over (FITS convention)
+  @return  cpl_vector or NULL if no good pixels or error
+  @note    vector can't have size 0 so NULL is returned if all pixels are bad
+ */
+/*----------------------------------------------------------------------------*/
+cpl_vector * hdrl_imagelist_to_vector(const cpl_imagelist * list,
+                                      const cpl_size x,
+                                      const cpl_size y)
+{
+    cpl_size nx;
+    const cpl_size nz  = list ? cpl_imagelist_get_size(list) : -1;
+    cpl_ensure(list != NULL, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(nz > 0, CPL_ERROR_ILLEGAL_INPUT, NULL);
+    cpl_ensure(x > 0, CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+    cpl_ensure(y > 0, CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+
+    {
+        const cpl_image  * img = cpl_imagelist_get_const(list, 0);
+        const cpl_size ny = cpl_image_get_size_y(img);
+        nx = cpl_image_get_size_x(img);
+        cpl_ensure(x <= nx, CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+        cpl_ensure(y <= ny, CPL_ERROR_ACCESS_OUT_OF_RANGE, NULL);
+    }
+    return imagelist_to_vector(list, nx, x, y, NULL, NULL);
+}
+
+
+/*----------------------------------------------------------------------------*/
+/**
+  @internal
+  @brief    compress an imagelist to a vector via z axis for a row
+  @param    list     imagelist to compress
+  @param    y        y coordinate to compress over (FITS convention)
+  @param    out      output array of vector pointers of size nx
+  @return  cpl_error_code
+  @note    vector can't have size 0 so NULL is returned if all pixels are bad
+
+  more efficient than hdrl_imagelist_to_vector for double images as it will
+  call cpl_image_get less often by caching the data buffers
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code hdrl_imagelist_to_vector_row(const cpl_imagelist * list,
+                                            const cpl_size y,
+                                            cpl_vector ** out)
+{
+    long nx;
+    int isdouble;
+    const long nz  = list ? (long)cpl_imagelist_get_size(list) : -1;
+    cpl_ensure_code(list != NULL, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(nz > 0, CPL_ERROR_ILLEGAL_INPUT);
+    cpl_ensure_code(y > 0, CPL_ERROR_ACCESS_OUT_OF_RANGE);
+
+    {
+        const cpl_image  * img = cpl_imagelist_get_const(list, 0);
+        const cpl_size ny = cpl_image_get_size_y(img);
+        cpl_ensure_code(y <= ny, CPL_ERROR_ACCESS_OUT_OF_RANGE);
+        nx = (long)cpl_image_get_size_x(img);
+        isdouble = cpl_image_get_type(img) == CPL_TYPE_DOUBLE;
+    }
+
+    const double * imgdatabuf[nz];
+    const cpl_binary * maskbuf[nz];
+    for (long i = 0; i < nz && isdouble; i++) {
+        const cpl_image * img = cpl_imagelist_get_const(list, i);
+        const cpl_mask * bpm = cpl_image_get_bpm_const(img);
+        imgdatabuf[i] = cpl_image_get_data_double_const(img);
+        if (bpm) {
+            maskbuf[i] = cpl_mask_get_data_const(bpm);
+        }
+        else {
+            maskbuf[i] = NULL;
+        }
+    }
+    for (long x = 0; x < nx; x++) {
+        if (isdouble) {
+            out[x] = imagelist_to_vector(list, nx, x + 1, y,
+                                         imgdatabuf, maskbuf);
+        }
+        else {
+            out[x] = imagelist_to_vector(list, nx, x + 1, y, NULL, NULL);
+        }
+    }
+    return cpl_error_get_code();
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief wrap two cpl_imagelist around data and errors in hdrl_imagelist
+ *
+ * @param list input hdrl_imagelist
+ * @param data output data cpl_imagelist (may be NULL)
+ * @param errs output error cpl_imagelist (may be NULL)
+ * @return cpl_error_code
+ *
+ * @note the imagelists only wrap the images and must be deleted with
+ * cpl_imagelist_unwrap
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_error_code
+hdrl_imagelist_to_cplwrap(const hdrl_imagelist * list,
+                          cpl_imagelist ** data,
+                          cpl_imagelist ** errs)
+{
+    cpl_ensure_code(list, CPL_ERROR_NULL_INPUT);
+    if (data) {
+        *data = cpl_imagelist_new();
+    }
+    if (errs) {
+        *errs = cpl_imagelist_new();
+    }
+    for (cpl_size i = 0; i < hdrl_imagelist_get_size(list); i++) {
+        hdrl_image * img = hdrl_imagelist_get(list, i);
+        if (data) {
+            cpl_imagelist_set(*data, hdrl_image_get_image(img), i);
+        }
+        if (errs) {
+            cpl_imagelist_set(*errs, hdrl_image_get_error(img), i);
+        }
+    }
+
+    if (cpl_error_get_code()) {
+        if (data) {
+            cpl_imagelist_unwrap(*data);
+            *data = NULL;
+        }
+        if (errs) {
+            cpl_imagelist_unwrap(*errs);
+            *errs = NULL;
+        }
+    }
+    return cpl_error_get_code();
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief filter image on a grid
+ *
+ * @param ima           image to filter
+ * @param x             row vector of coordinates to filter on
+ * @param y             row vector of coordinates to filter on
+ * @param filtersize_x  size of the median filter
+ * @param filtersize_y  size of the median filter
+ * @return filtered image of size of the grid
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_image *
+hdrl_medianfilter_image_grid(const cpl_image * ima, cpl_matrix * x, cpl_matrix * y,
+                             cpl_size  filtersize_x, cpl_size filtersize_y)
+{
+    cpl_error_ensure(ima != NULL, CPL_ERROR_NULL_INPUT, return NULL,
+            "NULL input image");
+    cpl_error_ensure(filtersize_x > 0 && filtersize_y > 0 ,
+            CPL_ERROR_INCOMPATIBLE_INPUT, return NULL,
+            "All function parameters must be greater then Zero");
+
+    const cpl_size nx = cpl_image_get_size_x(ima);
+    const cpl_size ny = cpl_image_get_size_y(ima);
+    const cpl_size steps_x = cpl_matrix_get_nrow(x);
+    const cpl_size steps_y = cpl_matrix_get_nrow(y);
+
+    cpl_image * ima_local = cpl_image_new(steps_x, steps_y, CPL_TYPE_DOUBLE);
+
+    for (cpl_size iy = 0; iy < steps_y; iy++) {
+        cpl_size middlep_y = cpl_matrix_get(y, iy, 0);
+        for (cpl_size ix = 0; ix < steps_x; ix++) {
+            cpl_size middlep_x = cpl_matrix_get(x, ix, 0);
+
+            cpl_size lowerlimit_x = CX_MAX(middlep_x - filtersize_x, 1);
+            cpl_size lowerlimit_y = CX_MAX(middlep_y - filtersize_y, 1);
+            cpl_size upperlimit_x = CX_MIN(middlep_x + filtersize_x, nx);
+            cpl_size upperlimit_y = CX_MIN(middlep_y + filtersize_y, ny);
+
+            double median = cpl_image_get_median_window(ima, lowerlimit_x,
+                            lowerlimit_y, upperlimit_x, upperlimit_y);
+
+            cpl_image_set(ima_local, ix + 1, iy + 1, median);
+
+            cpl_msg_debug(cpl_func, "middlep_x: %lld, middlep_y: %lld, median: "
+                          "%g", middlep_x, middlep_y, median);
+        }
+    }
+    return ima_local;
+}
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief create linear space row vector
+ * @param start  starting point
+ * @param stop   end point, exclusive
+ * @param step   step size
+ *
+ * @returns matrix with one row filled equally spaced points from start to end
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_matrix * hdrl_matrix_linspace(
+        cpl_size    start,
+        cpl_size    stop,
+        cpl_size    step)
+{
+    cpl_matrix * x = cpl_matrix_new(stop / step, 1);
+    for (intptr_t i = 0; start + i * step < stop && i < stop / step; i++) {
+        cpl_matrix_set(x, i, 0, start + i * step);
+    }
+    return x;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief fit 2D legendre polynomials to img
+ *
+ * @param img      image to be fitted
+ * @param order_x  order of x polynomial
+ * @param order_y  order of y polynomial
+ * @param grid_x   x grid to evaluate on
+ * @param grid_y   y grid to evaluate on
+ * @param orig_nx  upper limit in x, exclusive
+ * @param orig_ny  upper limit in y, exclusive
+ *
+ * @return coefficient matrix of the fitted 2-D polynomial
+ * @see hdrl_mime_linalg_pairwise_column_tensor_products_create,
+ *      hdrl_legendre_to_image
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_matrix * hdrl_fit_legendre(
+        cpl_image   *   img,
+        int             order_x,
+        int             order_y,
+        cpl_matrix  *   grid_x,
+        cpl_matrix  *   grid_y,
+        cpl_size        orig_nx,
+        cpl_size        orig_ny)
+{
+    cpl_size nx2 = cpl_matrix_get_nrow(grid_x);
+    cpl_size ny2 = cpl_matrix_get_nrow(grid_y);
+    cpl_matrix * xpolys =
+        hdrl_mime_legendre_polynomials_create(order_x + 1, 0, orig_nx - 1, grid_x);
+    cpl_matrix * ypolys =
+        hdrl_mime_legendre_polynomials_create(order_y + 1, 0, orig_ny - 1, grid_y);
+    cpl_matrix * tensors =
+        hdrl_mime_linalg_pairwise_column_tensor_products_create(ypolys,
+                                                                xpolys);
+    cpl_matrix * mimage = cpl_matrix_wrap(nx2 * ny2, 1, cpl_image_get_data(img));
+    cpl_matrix * coeffs = cpl_matrix_solve_normal(tensors, mimage);
+    cpl_matrix_unwrap(mimage);
+    cpl_matrix_delete(xpolys);
+    cpl_matrix_delete(ypolys);
+    cpl_matrix_delete(tensors);
+
+    return coeffs;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief evaluate 2D legendre polynomials on image
+ *
+ * @param coeffs   legendre coefficients
+ * @param order_x  order of x polynomial
+ * @param order_y  order of y polynomial
+ * @param nx       x size of image
+ * @param ny       y size of image
+ * @return legendre polynomial evaluated on an image
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_image * hdrl_legendre_to_image(
+        cpl_matrix  *   coeffs,
+        int             order_x,
+        int             order_y,
+        cpl_size        nx,
+        cpl_size        ny)
+{
+    /* evaluate on full image */
+    /* TODO need grid of original fit here? */
+    cpl_matrix * x = hdrl_matrix_linspace(0, nx, 1);
+    cpl_matrix * y = hdrl_matrix_linspace(0, ny, 1);
+    cpl_matrix * xpolys =
+        hdrl_mime_legendre_polynomials_create(order_x + 1, 0, nx - 1, x);
+    cpl_matrix  * ypolys =
+        hdrl_mime_legendre_polynomials_create(order_y + 1, 0, ny - 1, y);
+    cpl_matrix * tensors =
+        hdrl_mime_linalg_pairwise_column_tensor_products_create(ypolys,
+                                                                xpolys);
+    cpl_matrix * result = cpl_matrix_product_create(tensors, coeffs);
+    cpl_image * iresult = cpl_image_wrap(nx, ny, CPL_TYPE_DOUBLE,
+                                         cpl_matrix_get_data(result));
+    cpl_matrix_delete(x);
+    cpl_matrix_delete(y);
+    cpl_matrix_delete(xpolys);
+    cpl_matrix_delete(ypolys);
+    cpl_matrix_delete(tensors);
+    cpl_matrix_unwrap(result);
+
+    return iresult;
+}
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief check if bad pixel masks are identical.
+ * @param mask1   input mask 1 to be compared with input mask 2
+ * @param mask2   input mask 2 to be compared with input mask 1
+ *
+ * @return  0 if the masks are identical - in all other cases 1
+ */
+/* ---------------------------------------------------------------------------*/
+int hdrl_check_maskequality(const cpl_mask * mask1, const cpl_mask * mask2)
+{
+    cpl_ensure(mask1, CPL_ERROR_NULL_INPUT, 1);
+    cpl_ensure(mask2, CPL_ERROR_NULL_INPUT, 1);
+
+    cpl_size m1nx = cpl_mask_get_size_x(mask1);
+    cpl_size m1ny = cpl_mask_get_size_y(mask1);
+    cpl_size m2nx = cpl_mask_get_size_x(mask2);
+    cpl_size m2ny = cpl_mask_get_size_y(mask2);
+    cpl_ensure(m1nx == m2nx, CPL_ERROR_NONE, 1);
+    cpl_ensure(m1ny == m2ny, CPL_ERROR_NONE, 1);
+
+    const cpl_binary * dm1bpm = cpl_mask_get_data_const(mask1);
+    const cpl_binary * dm2bpm = cpl_mask_get_data_const(mask2);
+    if (memcmp(dm1bpm, dm2bpm, m1nx * m1ny) != 0) {
+        return 1;
+    }
+    else {
+        return 0;
+    }
+}
+
+static const cpl_image *
+image_const_row_view_create(const cpl_image * img,
+                            cpl_size ly,
+                            cpl_size uy)
+{
+    const size_t dsz = cpl_type_get_sizeof(cpl_image_get_type(img));
+    const cpl_size nx = cpl_image_get_size_x(img);
+    const char * d = cpl_image_get_data_const(img);
+    size_t offset = (ly - 1) * nx;
+    cpl_size nny = uy - ly + 1;
+    cpl_image * wimg = cpl_image_wrap(nx, nny, cpl_image_get_type(img),
+                                     (char*)d + offset * dsz);
+
+    const cpl_mask * omask = cpl_image_get_bpm_const(img);
+    if (omask) {
+        cpl_mask * mask = cpl_mask_wrap(nx, nny,
+                        (cpl_binary*)cpl_mask_get_data_const(omask) + offset);
+        cpl_mask_delete(hcpl_image_set_bpm(wimg, mask));
+    }
+
+    return wimg;
+}
+
+static void
+image_const_row_view_delete(const cpl_image * img)
+{
+    cpl_mask_unwrap(cpl_image_unset_bpm((cpl_image*)(img)));
+    cpl_image_unwrap((cpl_image *)img);
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief compute a filter in parallel
+ *
+ * @param img     image to filter
+ * @param kernel  filter kernel (mutually exclusive with mask)
+ * @param mask    filter mask (mutually exclusive with kernel)
+ * @param mode   filter mode
+ * @return filtered image, must be deleted with cpl_image_delete
+ *
+ * if kernel is not NULL and mask is NULL cpl_image_filter is used
+ * if mask is not NULL and kernel is NULL cpl_image_filter_mask is used
+ *
+ * the kernel or mask size must be odd and less equal to the image size
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_image *
+hdrl_parallel_filter_image(const cpl_image * img,
+                           const cpl_matrix * kernel,
+                           const cpl_mask * mask,
+                           const cpl_filter_mode mode)
+{
+    cpl_ensure(img, CPL_ERROR_NULL_INPUT, NULL);
+    intptr_t nx = cpl_image_get_size_x(img);
+    intptr_t ny = cpl_image_get_size_y(img);
+    intptr_t ky, kx;
+    /* TODO probably one can use all except COPY */
+    const cpl_border_mode border = CPL_BORDER_FILTER;
+    cpl_ensure((kernel && !mask) || (!kernel && mask),
+               CPL_ERROR_INCOMPATIBLE_INPUT, NULL);
+    if (kernel) {
+        ky = cpl_matrix_get_nrow(kernel);
+        kx = cpl_matrix_get_ncol(kernel);
+    }
+    else {
+        ky = cpl_mask_get_size_y(mask);
+        kx = cpl_mask_get_size_x(mask);
+    }
+    intptr_t hk = (ky / 2);
+    cpl_image * res = cpl_image_new(nx, ny, cpl_image_get_type(img));
+
+    cpl_ensure(ky % 2 == 1, CPL_ERROR_INCOMPATIBLE_INPUT, NULL);
+    cpl_ensure(ny >= ky, CPL_ERROR_INCOMPATIBLE_INPUT, NULL);
+    cpl_ensure(nx >= kx, CPL_ERROR_INCOMPATIBLE_INPUT, NULL);
+    /* filter first half-kernel rows (needs full kernel image) */
+    {
+        const cpl_image * slice = image_const_row_view_create(img, 1, ky);
+        cpl_image * slres = cpl_image_duplicate(slice);
+        if (kernel) {
+            cpl_image_filter(slres, slice, kernel, mode, border);
+        }
+        else {
+            cpl_image_filter_mask(slres, slice, mask, mode, border);
+        }
+
+        const cpl_image * slice2 = image_const_row_view_create(slres, 1, hk);
+        cpl_image_copy(res, slice2, 1, 1);
+        image_const_row_view_delete(slice2);
+        image_const_row_view_delete(slice);
+        cpl_image_delete(slres);
+    }
+    intptr_t y;
+    const intptr_t s = 200;
+    /* filter s sized row chunks needs one kernel overlap */
+HDRL_OMP(omp parallel for lastprivate(y) if (ny > s + ky))
+    for (y = hk; y < ny - ky - (ny - ky) % s; y+=s) {
+        intptr_t l = (y + 1) - hk;
+        intptr_t u = (y + 1 + s) + hk;
+        const cpl_image * slice = image_const_row_view_create(img, l, u);
+        cpl_image * slres = cpl_image_new(nx, u - l + 1,
+                                          cpl_image_get_type(slice));
+        if (kernel) {
+            cpl_image_filter(slres, slice, kernel, mode, border);
+        }
+        else {
+            cpl_image_filter_mask(slres, slice, mask, mode, border);
+        }
+        const cpl_image * slice2 =
+            image_const_row_view_create(slres, hk + 1, u - l - hk);
+        cpl_image_copy(res, slice2, 1, y + 1);
+        image_const_row_view_delete(slice);
+        image_const_row_view_delete(slice2);
+        cpl_image_delete(slres);
+    }
+    /* filter remainder, needs half kernel overlap */
+    {
+        const cpl_image * slice = image_const_row_view_create(img, y + 1 - hk, ny);
+        cpl_image * slres = cpl_image_duplicate(slice);
+        if (kernel) {
+            cpl_image_filter(slres, slice, kernel, mode, border);
+        }
+        else {
+            cpl_image_filter_mask(slres, slice, mask, mode, border);
+        }
+        const cpl_image * slice2 =
+            image_const_row_view_create(slres, hk + 1, cpl_image_get_size_y(slice));
+        cpl_image_copy(res, slice2, 1, y + 1);
+        image_const_row_view_delete(slice);
+        image_const_row_view_delete(slice2);
+        cpl_image_delete(slres);
+    }
+    return res;
+}
+
+/* cpl_image_set_bpm from cpl 6.4 which we can't require yet for VLTSW 2014 */
+struct _cpl_image_ {
+    /* Size of the image in x and y */
+    cpl_size            nx, ny;
+    /* Type of the pixels used for the cpl_image */
+    cpl_type            type;
+    /* Pointer to pixel buffer as a 1d buffer */
+    void            *   pixels;
+    /* Bad Pixels mask */
+    cpl_mask        *   bpm;
+};
+
+cpl_mask * hcpl_image_set_bpm(cpl_image * self, cpl_mask * bpm) 
+{
+#if CPL_VERSION_CODE < CPL_VERSION(6, 4, 0)
+    cpl_mask * oldbpm;
+
+    cpl_ensure(self != NULL, CPL_ERROR_NULL_INPUT, NULL);
+
+    oldbpm = self->bpm;
+    self->bpm = bpm; 
+ 
+    return oldbpm;
+#else
+    return cpl_image_set_bpm(self, bpm);
+#endif
+}
+
+double hcpl_gaussian_eval_2d(const cpl_array * self, double x, double y)
+{
+#if CPL_VERSION_CODE < CPL_VERSION(6, 4, 0)
+    cpl_errorstate prestate = cpl_errorstate_get();
+    const double B    = cpl_array_get_double(self, 0, NULL);
+    const double A    = cpl_array_get_double(self, 1, NULL);
+    const double R    = cpl_array_get_double(self, 2, NULL);
+    const double M_x  = cpl_array_get_double(self, 3, NULL);
+    const double M_y  = cpl_array_get_double(self, 4, NULL);
+    const double S_x  = cpl_array_get_double(self, 5, NULL);
+    const double S_y  = cpl_array_get_double(self, 6, NULL);
+
+    double value = 0.0; 
+
+    if (!cpl_errorstate_is_equal(prestate)) {
+        (void)cpl_error_set_where(cpl_func);
+    } else if (cpl_array_get_size(self) != 7) { 
+        (void)cpl_error_set(cpl_func, CPL_ERROR_ILLEGAL_INPUT);
+    } else if (fabs(R) < 1.0 && S_x != 0.0 && S_y != 0.0) {
+        const double x_n  = (x - M_x) / S_x; 
+        const double y_n  = (y - M_y) / S_y; 
+
+        value = B + A / (CPL_MATH_2PI * S_x * S_y * sqrt(1 - R * R)) *
+            exp(-0.5 / (1 - R * R) * ( x_n * x_n + y_n * y_n
+                                       - 2.0 * R * x_n * y_n));
+    } else if (fabs(R) > 1.0) {
+        (void)cpl_error_set_message(cpl_func, CPL_ERROR_ILLEGAL_OUTPUT,
+                                     "fabs(R=%g) > 1", R);
+    } else {
+        (void)cpl_error_set_message(cpl_func, CPL_ERROR_DIVISION_BY_ZERO,
+                                     "R=%g. Sigma=(%g, %g)", R, S_x, S_y);
+    }    
+
+    return value;
+#else
+    return cpl_gaussian_eval_2d(self, x, y);
+#endif
+}
+
+
+/** @endcond */
+
+/**@}*/
diff --git a/hdrl/hdrl_utils.h b/hdrl/hdrl_utils.h
new file mode 100644
index 0000000..8eaccf9
--- /dev/null
+++ b/hdrl/hdrl_utils.h
@@ -0,0 +1,281 @@
+/* $Id: hdrl_utils.h,v 1.32 2013-10-23 09:13:12 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2012,2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-23 09:13:12 $
+ * $Revision: 1.32 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifndef HDRL_UTILS_H
+#define HDRL_UTILS_H
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_parameter.h"
+#include "hdrl_image.h"
+#include "hdrl_imagelist.h"
+#include <cpl.h>
+
+#include <stdlib.h>
+#include <stdarg.h>
+
+CPL_BEGIN_DECLS
+
+/*-----------------------------------------------------------------------------
+                                Define
+ -----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------*/
+/**
+  @enum hdrl_direction
+  @brief Define an image direction e.g along X or Y
+ */
+/*----------------------------------------------------------------------------*/
+typedef enum {
+
+    /** X axis, equivalent to NAXIS1 in FITS convention */ 
+    HDRL_X_AXIS,
+    /** Y axis, equivalent to NAXIS2 in FITS convention */ 
+    HDRL_Y_AXIS,
+    /** Reserved value for undefined direction */ 
+    HDRL_UNDEFINED_AXIS
+} hdrl_direction;
+
+/*-----------------------------------------------------------------------------
+                            Functions prototypes
+ -----------------------------------------------------------------------------*/
+
+const char * hdrl_get_license(void);
+
+/*----------------------------------------------------------------------------
+                           Rect region Parameters
+  ----------------------------------------------------------------------------*/
+hdrl_parameter * hdrl_rect_region_parameter_create(cpl_size, cpl_size,
+        cpl_size, cpl_size) ;
+cpl_error_code hdrl_rect_region_parameter_update(hdrl_parameter *, cpl_size, 
+        cpl_size, cpl_size, cpl_size) ;
+cpl_boolean hdrl_rect_region_parameter_check(const hdrl_parameter *) ;
+cpl_size hdrl_rect_region_get_llx(const hdrl_parameter *) ;
+cpl_size hdrl_rect_region_get_lly(const hdrl_parameter *) ;
+cpl_size hdrl_rect_region_get_urx(const hdrl_parameter *) ;
+cpl_size hdrl_rect_region_get_ury(const hdrl_parameter *) ;
+cpl_error_code hdrl_rect_region_parameter_verify(const hdrl_parameter *,
+        const cpl_size, const cpl_size) ;
+cpl_parameterlist * hdrl_rect_region_parameter_create_parlist(const char *, 
+        const char *, const char *, const hdrl_parameter *) ;
+hdrl_parameter * hdrl_rect_region_parameter_parse_parlist(
+        const cpl_parameterlist *, const char *, const char *) ;
+
+/*-----------------------------------------------------------------------------
+  Experimental declarations - can be used, but no guarantees on api stability
+ -----------------------------------------------------------------------------*/
+#if defined HDRL_USE_EXPERIMENTAL || defined HDRL_USE_PRIVATE
+typedef enum {
+    HDRL_SCALE_ADDITIVE,
+    HDRL_SCALE_MULTIPLICATIVE
+} hdrl_scale_type;
+
+cpl_error_code
+hdrl_normalize_imagelist_by_vector(const cpl_vector * vector,
+                                   const cpl_vector * evector,
+                                   hdrl_scale_type scale_type,
+                                   cpl_imagelist * data,
+                                   cpl_imagelist * errors);
+
+cpl_error_code
+hdrl_normalize_imagelist_by_imagelist(const cpl_imagelist * scale,
+                                      const cpl_imagelist * scale_e,
+                                      const hdrl_scale_type scale_type,
+                                      cpl_imagelist * data,
+                                      cpl_imagelist * errors);
+
+int hdrl_get_tempfile(const char * dir, cpl_boolean unlink);
+char * hdrl_get_cwd(void);
+cpl_error_code hdrl_rect_region_fix_negatives(hdrl_parameter *, const cpl_size,
+                                              const cpl_size) ;
+#endif
+
+/*-----------------------------------------------------------------------------
+             Private declarations - must not be used outside of hdrl
+ -----------------------------------------------------------------------------*/
+#ifdef HDRL_USE_PRIVATE
+
+cpl_image *
+hdrl_medianfilter_image_grid(const cpl_image * ima, cpl_matrix * x, cpl_matrix * y,
+                             cpl_size  filtersize_x, cpl_size filtersize_y);
+
+cpl_matrix * hdrl_matrix_linspace(cpl_size start, cpl_size stop, cpl_size step);
+
+cpl_matrix * hdrl_fit_legendre(cpl_image * img, int order_x, int order_y,
+                               cpl_matrix * grid_x, cpl_matrix * grid_y,
+                               cpl_size orig_nx, cpl_size  orig_ny);
+
+cpl_image * hdrl_legendre_to_image(cpl_matrix * coeffs, int order_x,
+                                   int order_y, cpl_size nx, cpl_size ny);
+
+int hdrl_check_maskequality(const cpl_mask * mask1, const cpl_mask * mask2);
+
+/* must not be followed by a semicolon!
+ * gcc on mac has omp but it doesn't work for nontrivial cases as libc lacks
+ * alloca */
+#if defined (_OPENMP) && !defined( __APPLE__)
+#define HDRL_OMP(x) _Pragma (#x)
+#else
+#define HDRL_OMP(x)
+#endif
+
+/* setup a value parameter and append it into parlist */
+#define hdrl_setup_vparameter(parlist, \
+                              prefix, \
+                              sep, \
+                              name_prefix, \
+                              pname, \
+                              context, \
+                              descr, \
+                              type, \
+                              pdefault) \
+do { \
+        char * fname = cpl_sprintf("%s%s", name_prefix, pname); \
+        char * setup_name = hdrl_join_string(sep, 3, context, prefix, fname); \
+        cpl_parameter * setup_p = cpl_parameter_new_value(setup_name, type, \
+                descr, context, pdefault) ; \
+        cpl_free(setup_name); \
+        setup_name = hdrl_join_string(sep, 2, prefix, fname); \
+        cpl_parameter_set_alias(setup_p, CPL_PARAMETER_MODE_CLI, setup_name); \
+        cpl_parameter_disable(setup_p, CPL_PARAMETER_MODE_ENV); \
+        cpl_free(setup_name); \
+        cpl_free(fname); \
+        cpl_parameterlist_append(parlist, setup_p); \
+    } while (0)
+
+cpl_vector * hdrl_image_to_vector(const cpl_image * source, const
+        cpl_mask * bpm);
+cpl_vector * hdrl_imagelist_to_vector(const cpl_imagelist * source, 
+        const cpl_size x, const cpl_size y);
+cpl_error_code hdrl_imagelist_to_vector_row(const cpl_imagelist * list,
+                                            const cpl_size y,
+                                            cpl_vector ** out);
+
+cpl_error_code
+hdrl_imagelist_to_cplwrap(const hdrl_imagelist * list,
+                          cpl_imagelist ** data,
+                          cpl_imagelist ** errs);
+
+cpl_image *
+hdrl_parallel_filter_image(const cpl_image * img,
+                           const cpl_matrix * kernel,
+                           const cpl_mask * mask,
+                           const cpl_filter_mode mode);
+
+cpl_mask * hcpl_image_set_bpm(cpl_image * self, cpl_mask * bpm) ;
+double hcpl_gaussian_eval_2d(const cpl_array * self, double x, double y);
+
+static inline int hdrl_int_is_power_of_two(unsigned long long x)
+{
+    return (x & (x - 1)) == 0;
+}
+
+static inline size_t hdrl_get_image_npix(const cpl_image * img)
+{
+    return cpl_image_get_size_x(img) * cpl_image_get_size_y(img);
+}
+
+static inline size_t hdrl_get_image_good_npix(const cpl_image * img)
+{
+    return (cpl_image_get_size_x(img) * cpl_image_get_size_y(img)) -
+        cpl_image_count_rejected(img);
+}
+
+static inline cpl_mask * hdrl_copy_image_mask(const cpl_image * img)
+{
+    /* always returns a mask even it image has none */
+    const cpl_mask * bpm = cpl_image_get_bpm_const(img);
+
+    if (bpm) {
+        return cpl_mask_duplicate(bpm);
+    }
+    else {
+        return cpl_mask_new(cpl_image_get_size_x(img),
+                            cpl_image_get_size_y(img));
+    }
+}
+
+char * hdrl_join_string(const char * sep_, int n, ...);
+
+static inline hdrl_data_t * hdrl_get_image_data(cpl_image * image)
+{
+#if HDRL_SIZEOF_DATA == 8
+    return cpl_image_get_data_double(image);
+#else
+    return cpl_image_get_data_float(image);
+#endif
+}
+
+static inline hdrl_error_t * hdrl_get_image_error(cpl_image * image)
+{
+#if HDRL_SIZEOF_ERROR == 8
+    return cpl_image_get_data_double(image);
+#else
+    return cpl_image_get_data_float(image);
+#endif
+}
+
+
+static inline const
+hdrl_data_t * hdrl_get_image_data_const(const cpl_image * image)
+{
+#if HDRL_SIZEOF_DATA == 8
+    return cpl_image_get_data_double_const(image);
+#else
+    return cpl_image_get_data_float_const(image);
+#endif
+}
+
+static inline const
+hdrl_error_t * hdrl_get_image_error_const(const cpl_image * image)
+{
+#if HDRL_SIZEOF_ERROR == 8
+    return cpl_image_get_data_double_const(image);
+#else
+    return cpl_image_get_data_float_const(image);
+#endif
+}
+
+#ifndef HDRL_ATTR_UNUSED
+    #if defined(__GNUC__) || defined(__ICC)
+        #define HDRL_ATTR_UNUSED __attribute__ ((__unused__))
+    #else
+        #define HDRL_ATTR_UNUSED
+    #endif
+#endif
+
+/* Use this to tag a variable as not used. It will remove unused variable
+ * warning and mangle the variable to avoid accidental use */
+#define HDRL_UNUSED(x) (__HDRL_UNUSED_TAGGED ## x) HDRL_ATTR_UNUSED
+
+#endif
+
+CPL_END_DECLS
+
+#endif
diff --git a/hdrl/igam.c b/hdrl/igam.c
new file mode 100644
index 0000000..05e2041
--- /dev/null
+++ b/hdrl/igam.c
@@ -0,0 +1,247 @@
+/*
+igam.c from torch-cephes which is a BSD licensed redistribution of cephes [0]
+Minor modifications to use C99 lgamma and removed K&R syntax.
+
+[0] https://github.com/jucor/torch-cephes/blob/master/LICENSE.txt
+
+Copyright 1984, 1987, 1995, 2000 by Stephen L. Moshier
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright
+      notice, this list of conditions and the following disclaimer in the
+      documentation and/or other materials provided with the distribution.
+    * Neither the name of the organization nor the
+      names of its contributors may be used to endorse or promote products
+      derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+*/
+
+/*                                                      igam.c
+ *
+ *      Incomplete gamma integral
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, x, y, igam();
+ *
+ * y = igam( a, x );
+ *
+ * DESCRIPTION:
+ *
+ * The function is defined by
+ *
+ *                           x
+ *                            -
+ *                   1       | |  -t  a-1
+ *  igam(a,x)  =   -----     |   e   t   dt.
+ *                  -      | |
+ *                 | (a)    -
+ *                           0
+ *
+ *
+ * In this implementation both arguments must be positive.
+ * The integral is evaluated by either a power series or
+ * continued fraction expansion, depending on the relative
+ * values of a and x.
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30       200000       3.6e-14     2.9e-15
+ *    IEEE      0,100      300000       9.9e-14     1.5e-14
+ */
+
/*                                                    igamc()
+ *
+ *      Complemented incomplete gamma integral
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, x, y, igamc();
+ *
+ * y = igamc( a, x );
+ *
+ * DESCRIPTION:
+ *
+ * The function is defined by
+ *
+ *
+ *  igamc(a,x)   =   1 - igam(a,x)
+ *
+ *                            inf.
+ *                              -
+ *                     1       | |  -t  a-1
+ *               =   -----     |   e   t   dt.
+ *                    -      | |
+ *                   | (a)    -
+ *                             x
+ *
+ *
+ * In this implementation both arguments must be positive.
+ * The integral is evaluated by either a power series or
+ * continued fraction expansion, depending on the relative
+ * values of a and x.
+ *
+ * ACCURACY:
+ *
+ * Tested at random a, x.
+ *                a         x                      Relative error:
+ * arithmetic   domain   domain     # trials      peak         rms
+ *    IEEE     0.5,100   0,100      200000       1.9e-14     1.7e-15
+ *    IEEE     0.01,0.5  0,100      200000       1.4e-13     1.6e-15
+ */
+

+/*
+Cephes Math Library Release 2.8:  June, 2000
+Copyright 1985, 1987, 2000 by Stephen L. Moshier
+*/
+
+#include <math.h>
+#include <float.h>
+double igam(double, double);
+double igamc(double, double);
+
+#define MACHEP DBL_EPSILON
+#define MAXLOG log(FLT_MAX)
+#define mtherr(x, y)
+static double big = 4.503599627370496e15;
+static double biginv =  2.22044604925031308085e-16;
+
+double igamc(double a, double x)
+{
+double ans, ax, c, yc, r, t, y, z;
+double pk, pkm1, pkm2, qk, qkm1, qkm2;
+
+if( (x < 0) || ( a <= 0) )
+    {
+    mtherr("igamc", DOMAIN);
+	return( NAN );
+    }
+
+if( (x < 1.0) || (x < a) )
+        return( 1.0 - igam(a,x) );
+
+ax = a * log(x) - x - lgamma(a);
+if( ax < -MAXLOG )
+        {
+        mtherr( "igamc", UNDERFLOW );
+        return( 0.0 );
+        }
+ax = exp(ax);
+
+/* continued fraction */
+y = 1.0 - a;
+z = x + y + 1.0;
+c = 0.0;
+pkm2 = 1.0;
+qkm2 = x;
+pkm1 = x + 1.0;
+qkm1 = z * x;
+ans = pkm1/qkm1;
+
+do
+        {
+        c += 1.0;
+        y += 1.0;
+        z += 2.0;
+        yc = y * c;
+        pk = pkm1 * z  -  pkm2 * yc;
+        qk = qkm1 * z  -  qkm2 * yc;
+        if( qk != 0 )
+                {
+                r = pk/qk;
+                t = fabs( (ans - r)/r );
+                ans = r;
+                }
+        else
+                t = 1.0;
+        pkm2 = pkm1;
+        pkm1 = pk;
+        qkm2 = qkm1;
+        qkm1 = qk;
+        if( fabs(pk) > big )
+                {
+                pkm2 *= biginv;
+                pkm1 *= biginv;
+                qkm2 *= biginv;
+                qkm1 *= biginv;
+                }
+        }
+while( t > MACHEP );
+
+return( ans * ax );
+}
+
+
+
+/* left tail of incomplete gamma function:
+ *
+ *          inf.      k
+ *   a  -x   -       x
+ *  x  e     >   ----------
+ *           -     -
+ *          k=0   | (a+k+1)
+ *
+ */
+
+double igam(double a, double x)
+{
+double ans, ax, c, r;
+
+/* Check zero integration limit first */
+if( x == 0 )
+        return( 0.0 );
+
+if( (x < 0) || ( a <= 0) )
+    {
+    mtherr("igam", DOMAIN);
+	return( NAN );
+    }
+
+if( (x > 1.0) && (x > a ) )
+        return( 1.0 - igamc(a,x) );
+
+/* Compute  x**a * exp(-x) / gamma(a)  */
+ax = a * log(x) - x - lgamma(a);
+if( ax < -MAXLOG )
+        {
+        mtherr( "igam", UNDERFLOW );
+        return( 0.0 );
+        }
+ax = exp(ax);
+
+/* power series */
+r = a;
+c = 1.0;
+ans = 1.0;
+
+do
+        {
+        r += 1.0;
+        c *= x/r;
+        ans += c;
+        }
+while( c/ans > MACHEP );
+
+return( ans * ax/a );
+}
diff --git a/hdrl/m4macros/cpl.m4 b/hdrl/m4macros/cpl.m4
new file mode 100644
index 0000000..956b580
--- /dev/null
+++ b/hdrl/m4macros/cpl.m4
@@ -0,0 +1,1435 @@
+# CPL_CHECK_CFITSIO(version)
+#---------------------------
+# Checks for the cfitsio library and header files.
+AC_DEFUN([CPL_CHECK_CFITSIO],
+[
+
+	AC_REQUIRE([AC_SYS_LARGEFILE])
+    AC_REQUIRE([ESO_CHECK_THREADS_POSIX])
+        
+    cpl_cfitsio_check_version="$1"
+    cpl_cfitsio_check_header="fitsio.h"
+    cpl_cfitsio_check_lib="libcfitsio.a"
+
+    cpl_cfitsio_incdirs=""
+    cpl_cfitsio_libdirs=""
+    cpl_cfitsio_includes=""
+    cpl_cfitsio_libraries=""
+
+    AC_ARG_WITH(cfitsio,
+                AC_HELP_STRING([--with-cfitsio],
+                               [location where cfitsio is installed]),
+                [
+                    cpl_with_cfitsio=$withval
+                ])
+
+    AC_ARG_WITH(cfitsio-includes,
+                AC_HELP_STRING([--with-cfitsio-includes],
+                               [location of the cfitsio header files]),
+                cpl_with_cfitsio_includes=$withval)
+
+    AC_ARG_WITH(cfitsio-libs,
+                AC_HELP_STRING([--with-cfitsio-libs],
+                               [location of the cfitsio library]),
+                cpl_with_cfitsio_libs=$withval)
+
+    AC_ARG_ENABLE(cfitsio-test,
+                  AC_HELP_STRING([--disable-cfitsio-test],
+                                 [disables checks for the cfitsio library and headers]),
+                  cpl_enable_cfitsio_test=$enableval,
+                  cpl_enable_cfitsio_test=yes)
+
+
+    # We need libpthread for the folloing tests
+
+    if test -z "$LIBPTHREAD"; then
+        AC_MSG_ERROR([POSIX thread library was not found on your system! Please check!])
+    fi
+
+    
+    AC_MSG_CHECKING([for cfitsio])
+
+    if test "x$cpl_enable_cfitsio_test" = xyes; then
+
+        # Check for the cfitsio includes
+
+        if test -z "$cpl_with_cfitsio_includes"; then
+        
+            if test -z "$cpl_with_cfitsio"; then
+            
+                # Try some known system locations
+                
+                cpl_cfitsio_incdirs="/opt/cfitsio/include"
+                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs /usr/local/include/libcfitsio0"
+                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs /usr/local/include/cfitsio"
+                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs /usr/local/include"
+                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs /usr/include/libcfitsio0"
+                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs /usr/include/cfitsio"
+                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs /usr/include"
+
+                test -n "$CFITSIODIR" && \ 
+                    cpl_cfitsio_incdirs="$CFITSIODIR/include/libcfitsio0 \
+                                         $CFITSIODIR/include/cfitsio \
+                                         $CFITSIODIR/include \
+                                         $cpl_cfitsio_incdirs"
+
+                test -n "$CPLDIR" && \
+                    cpl_cfitsio_incdirs="$CPLDIR/include/libcfitsio0 \
+                                         $CPLDIR/include/cfitsio \
+                                         $CPLDIR/include \
+                                         $cpl_cfitsio_incdirs"
+
+            else
+
+                cpl_cfitsio_incdirs="$cpl_with_cfitsio/include/libcfitsio0"
+                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs $cpl_with_cfitsio/include/cfitsio"
+                cpl_cfitsio_incdirs="$cpl_cfitsio_incdirs $cpl_with_cfitsio/include"
+
+            fi
+            
+        else
+            cpl_cfitsio_incdirs="$cpl_with_cfitsio_includes"
+        fi
+
+        ESO_FIND_FILE($cpl_cfitsio_check_header, $cpl_cfitsio_incdirs,
+                      cpl_cfitsio_includes)
+
+
+        # Check for the cfitsio library
+
+        if test -z "$cpl_with_cfitsio_libs"; then
+
+            if test -z "$cpl_with_cfitsio"; then
+            
+                # Try some known system locations
+
+                cpl_cfitsio_libdirs="/opt/cfitsio/lib"
+                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs /usr/local/lib64"
+                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs /usr/local/lib"
+                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs /usr/local/lib32"
+                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs /usr/lib64"
+                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs /usr/lib"
+                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs /usr/lib32"
+
+                test -n "$CFITSIODIR" && \
+                    cpl_cfitsio_libdirs="$CFITSIODIR/lib64 $CFITSIODIR/lib \
+                                         $CFITSIODIR/lib32 $cpl_cfitsio_libdirs"
+
+                test -n "$CPLDIR" && \
+                    cpl_cfitsio_libdirs="$CPLDIR/lib64 $CPLDIR/lib $CPLDIR/lib32 \
+                                         $cpl_cfitsio_libdirs"
+
+            else
+
+                cpl_cfitsio_libdirs="$cpl_with_cfitsio/lib64"
+                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs $cpl_with_cfitsio/lib"
+                cpl_cfitsio_libdirs="$cpl_cfitsio_libdirs $cpl_with_cfitsio/lib32"
+
+            fi
+            
+        else
+            cpl_cfitsio_libdirs="$cpl_with_cfitsio_libs"
+        fi
+
+        ESO_FIND_FILE($cpl_cfitsio_check_lib, $cpl_cfitsio_libdirs,
+                      cpl_cfitsio_libraries)
+
+
+        if test x"$cpl_cfitsio_includes" = xno || \
+            test x"$cpl_cfitsio_libraries" = xno; then
+            cpl_cfitsio_notfound=""
+
+            if test x"$cpl_cfitsio_includes" = xno; then
+                if test x"$cpl_cfitsio_libraries" = xno; then
+                    cpl_cfitsio_notfound="(headers and libraries)"
+                else
+                    cpl_cfitsio_notfound="(headers)"
+                fi
+            else
+                cpl_cfitsio_notfound="(libraries)"
+            fi
+
+            AC_MSG_ERROR([cfitsio $cpl_cfitsio_notfound was not found on your system. Please check!])
+        else
+            AC_MSG_RESULT([libraries $cpl_cfitsio_libraries, headers $cpl_cfitsio_includes])
+        fi
+
+        # Set up the symbols
+
+        # Add '-lz' to the static library symbol, as distributors apparently
+        # remove the libz code from the cfitsio sources.
+        
+        CFITSIO_INCLUDES="-I$cpl_cfitsio_includes"
+        CFITSIO_LDFLAGS="-L$cpl_cfitsio_libraries"
+        LIBCFITSIO="-lcfitsio"
+        LIBCFITSIO_STATIC="$cpl_cfitsio_libraries/$cpl_cfitsio_check_lib"
+        
+        # Do not add redundant libraries        
+        echo $LIBS | grep -q -e '-lm' || LIBS="-lm $LIBS" 
+        
+
+        # Check whether cfitsio can be used
+
+        AC_MSG_CHECKING([whether cfitsio can be used])
+        AC_LANG_PUSH(C)
+        
+        cpl_cfitsio_cflags_save="$CFLAGS"
+        cpl_cfitsio_ldflags_save="$LDFLAGS"
+        cpl_cfitsio_libs_save="$LIBS"
+
+        CFLAGS="$CFITSIO_INCLUDES $CFLAGS"
+        LDFLAGS="$CFITSIO_LDFLAGS $LDFLAGS"
+        LIBS="$LIBCFITSIO_STATIC $LIBPTHREAD -lm"
+        
+        AC_LINK_IFELSE([AC_LANG_PROGRAM(
+                       [[
+                       #include <fitsio.h>
+                       ]],
+                       [
+                       float v;
+                       fits_get_version(&v);
+                       ])],
+                       [cpl_cfitsio_is_usable="yes"],
+                       [cpl_cfitsio_is_usable="no"])
+
+        AC_MSG_RESULT([$cpl_cfitsio_is_usable])
+        
+        AC_LANG_POP(C)
+        
+        CFLAGS="$cpl_cfitsio_cflags_save"
+        LDFLAGS="$cpl_cfitsio_ldflags_save"
+        LIBS="$cpl_cfitsio_libs_save"
+
+        if test x"$cpl_cfitsio_is_usable" = xno; then
+            AC_MSG_ERROR([Linking with cfitsio failed! Please check architecture!])
+        fi
+ 
+        
+        # Check cfitsio version
+
+        AC_MSG_CHECKING([for a cfitsio version >= $cpl_cfitsio_check_version])
+        
+        AC_LANG_PUSH(C)
+        
+        cpl_cfitsio_cflags_save="$CFLAGS"
+        cpl_cfitsio_ldflags_save="$LDFLAGS"
+        cpl_cfitsio_libs_save="$LIBS"
+
+        CFLAGS="$CFITSIO_INCLUDES $CFLAGS"
+        
+        AC_RUN_IFELSE([AC_LANG_PROGRAM(
+                      [[
+                      #include <stdio.h>
+                      #include <fitsio.h>
+                      ]],
+                      [
+                      int vlib = 0;
+                      int vmin = (int)(1000. * $cpl_cfitsio_check_version + 0.5);
+                       
+                      float v = CFITSIO_VERSION;
+
+                      vlib = (int)(v * 1000 + 0.5);
+                                            
+                      FILE* f = fopen("conftest.out", "w");
+                      fprintf(f, "%5.3f\n", v);
+                      fclose(f);
+                      
+                      if (vlib < vmin) {
+                          return 1;
+                      }
+
+                      return 0;
+                      ])],
+                      [cpl_cfitsio_version="`cat conftest.out`"],
+                      [
+                       cpl_cfitsio_version="no";
+                       cpl_cfitsio_version_found="`cat conftest.out`"
+                      ])
+
+        AC_MSG_RESULT([$cpl_cfitsio_version])
+        
+        AC_LANG_POP(C)
+        
+        CFLAGS="$cpl_cfitsio_cflags_save"
+        LDFLAGS="$cpl_cfitsio_ldflags_save"
+        LIBS="$cpl_cfitsio_libs_save"
+
+        if test x"$cpl_cfitsio_version" = xno; then
+            AC_MSG_ERROR([Installed cfitsio ($cpl_cfitsio_version_found) is too old. Please update to version $cpl_cfitsio_check_version or newer.])
+        fi
+ 
+        
+        # Check whether cfitsio has large file support
+        
+        AC_LANG_PUSH(C)
+        
+        cpl_cfitsio_cflags_save="$CFLAGS"
+        cpl_cfitsio_ldflags_save="$LDFLAGS"
+        cpl_cfitsio_libs_save="$LIBS"
+
+        CFLAGS="$CFITSIO_INCLUDES $CFLAGS"
+        LDFLAGS="$CFITSIO_LDFLAGS $LDFLAGS"
+        LIBS="$LIBCFITSIO_STATIC -lm $LIBPTHREAD"
+        
+        AC_MSG_CHECKING([whether cfitsio provides fits_hdu_getoff()])
+
+        AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
+                          [[
+                          #include <fitsio.h>
+                          ]],
+                          [
+                          fitsfile f;
+                          int sts;
+                          fits_get_hduoff(&f, NULL, NULL, NULL, &sts);
+                          ])],
+                          [cpl_cfitsio_have_fits_get_hduoff="yes"],
+                          [cpl_cfitsio_have_fits_get_hduoff="no"])
+
+        AC_MSG_RESULT([$cpl_cfitsio_have_fits_get_hduoff])
+        
+        AC_MSG_CHECKING([whether cfitsio provides fits_get_hduaddrll()])
+
+        AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
+                          [[
+                          #include <fitsio.h>
+                          ]],
+                          [
+                          fitsfile f;
+                          int sts;
+                          fits_get_hduaddrll(&f, NULL, NULL, NULL, &sts);
+                          ])],
+                          [cpl_cfitsio_have_fits_get_hduaddrll="yes"],
+                          [cpl_cfitsio_have_fits_get_hduaddrll="no"])
+
+        AC_MSG_RESULT([$cpl_cfitsio_have_fits_get_hduaddrll])
+
+        AC_LANG_POP(C)
+        
+        CFLAGS="$cpl_cfitsio_cflags_save"
+        LDFLAGS="$cpl_cfitsio_ldflags_save"
+        LIBS="$cpl_cfitsio_libs_save"
+
+
+        # Check whether cfitsio is thread-safe
+        
+		AC_MSG_CHECKING([whether cfitsio was compiled with thread support])
+
+        AC_LANG_PUSH(C)
+        
+        cpl_cfitsio_cflags_save="$CFLAGS"
+        cpl_cfitsio_ldflags_save="$LDFLAGS"
+        cpl_cfitsio_libs_save="$LIBS"
+
+        CFLAGS="$CFITSIO_INCLUDES $CFLAGS"
+        LDFLAGS="$CFITSIO_LDFLAGS $LDFLAGS"
+        LIBS="$LIBCFITSIO_STATIC -lm"
+
+        AC_RUN_IFELSE([AC_LANG_PROGRAM(
+                      [[
+                      #include <fitsio.h>
+                      ]],
+                      [
+                      if (fits_is_reentrant() == 0) {
+                          return 1;
+                      }
+
+                      return 0;
+                      ])],
+                      [cpl_cfitsio_is_thread_safe=yes],
+                      [cpl_cfitsio_is_thread_safe=no])
+
+		AC_MSG_RESULT([$cpl_cfitsio_is_thread_safe])
+
+        AC_LANG_POP(C)
+        
+        CFLAGS="$cpl_cfitsio_cflags_save"
+        LDFLAGS="$cpl_cfitsio_ldflags_save"
+        LIBS="$cpl_cfitsio_libs_save"
+
+		
+        # Set compiler flags and libraries
+        
+        if test x"$cpl_cfitsio_have_fits_get_hduoff" = xyes || \
+          test x"$cpl_cfitsio_have_fits_get_hduaddrll" = xyes; then
+
+            if test x"$cpl_cfitsio_have_fits_get_hduoff"; then
+                AC_DEFINE([HAVE_FITS_GET_HDUOFF], [1],
+                          [Define if you have the `fits_get_hduoff' function])
+            else
+                AC_DEFINE([HAVE_FITS_GET_HDUADDRLL],  [1],
+                          [Define if you have the `fits_get_hduaddrll' function])
+            fi
+                    
+        fi
+                
+    else
+        AC_MSG_RESULT([disabled])
+        AC_MSG_WARN([cfitsio checks have been disabled! This package may not build!])
+        CFITSIO_INCLUDES=""
+        CFITSIO_LDFLAGS=""
+        LIBCFITSIO=""
+        
+        cpl_cfitsio_is_thread_safe="undefined"
+    fi
+
+	AC_CACHE_VAL(cpl_cv_cfitsio_is_thread_safe,
+	             cpl_cv_cfitsio_is_thread_safe=$cpl_cfitsio_is_thread_safe)
+	             
+    AC_SUBST(CFITSIO_INCLUDES)
+    AC_SUBST(CFITSIO_LDFLAGS)
+    AC_SUBST(LIBCFITSIO)
+
+])
+
+
+# CPL_CHECK_CEXT(incdirs=[], libdirs=[])
+#---------------------------------------
+# Checks for the C extension library and header files.
+AC_DEFUN([CPL_CHECK_CEXT],
+[
+
+    AC_MSG_CHECKING([for libcext])
+
+    cpl_cext_check_header="cxtypes.h"
+    cpl_cext_check_lib="libcext.a"
+
+    cpl_cext_incdirs=""
+    cpl_cext_libdirs=""
+
+    cpl_cext_includes=""
+    cpl_cext_libraries=""
+
+
+	# Initialize directory search paths with the arguments provided
+	
+	if test -n "$1"; then
+		cpl_cext_incdirs="$1"
+	fi
+
+	if test -n "$2"; then
+		cpl_cext_libdirs="$2"
+	fi
+
+
+    AC_ARG_WITH(cext,
+                AC_HELP_STRING([--with-cext],
+                               [location where libcext is installed]),
+                [
+                    cpl_with_cext=$withval
+                ])
+
+    AC_ARG_WITH(cext-includes,
+                AC_HELP_STRING([--with-cext-includes],
+                               [location of the libcext header files]),
+                cpl_with_cext_includes=$withval)
+
+    AC_ARG_WITH(cext-libs,
+                AC_HELP_STRING([--with-cext-libs],
+                               [location of the libcext library]),
+                cpl_with_cext_libs=$withval)
+
+    AC_ARG_ENABLE(cext-test,
+                  AC_HELP_STRING([--disable-cext-test],
+                                 [disables checks for the libcext library and headers]),
+                  cpl_enable_cext_test=$enableval,
+                  cpl_enable_cext_test=yes)
+
+
+    if test "x$cpl_enable_cext_test" = xyes; then
+    
+        # Check for the libcext includes
+
+        if test -z "$cpl_with_cext_includes"; then
+        
+            if test -z "$cpl_with_cext"; then
+            
+            	if test -z "$cpl_cext_incdirs"; then
+            
+	                # Try some known system locations
+                
+    	            cpl_cext_incdirs="/opt/cext/include"
+        	        cpl_cext_incdirs="$cpl_cext_incdirs /usr/local/include/cext"
+            	    cpl_cext_incdirs="$cpl_cext_incdirs /usr/local/include"
+                	cpl_cext_incdirs="$cpl_cext_incdirs /usr/include/cext"
+                	cpl_cext_incdirs="$cpl_cext_incdirs /usr/include"
+
+                	test -n "$CPLDIR" && \
+                    	cpl_cext_incdirs="$CPLDIR/include/cext \
+                        	              $CPLDIR/include \
+                            	          $cpl_cext_incdirs"
+
+				fi
+				
+            else
+
+                cpl_cext_incdirs="$cpl_with_cext/include/cext"
+                cpl_cext_incdirs="$cpl_cext_incdirs $cpl_with_cext/include"
+
+            fi
+            
+        else
+            cpl_cext_incdirs="$cpl_with_cext_includes"
+        fi
+
+        ESO_FIND_FILE($cpl_cext_check_header, $cpl_cext_incdirs,
+                      cpl_cext_includes)
+
+
+        # Check for the libcext library
+
+        if test -z "$cpl_with_cext_libs"; then
+
+            if test -z "$cpl_with_cext"; then
+            
+            	if test -z "$cpl_cext_libdirs"; then
+
+	                # Try some known system locations
+
+    	            cpl_cext_libdirs="/opt/cext/lib"
+                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/local/lib64"
+                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/local/lib"
+                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/local/lib32"
+                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/lib64"
+                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/lib"
+                	cpl_cext_libdirs="$cpl_cext_libdirs /usr/lib32"
+
+                	test -n "$CPLDIR" && \
+                    	cpl_cext_libdirs="$CPLDIR/lib64 \
+                    					  $CPLDIR/lib \
+                    					  $CPLDIR/lib32 \
+                                          $cpl_cext_libdirs"
+                                          
+				fi
+				
+            else
+
+                cpl_cext_libdirs="$cpl_with_cext/lib64"
+                cpl_cext_libdirs="$cpl_cext_libdirs $cpl_with_cext/lib"
+                cpl_cext_libdirs="$cpl_cext_libdirs $cpl_with_cext/lib32"
+
+            fi
+            
+        else
+            cpl_cext_libdirs="$cpl_with_cext_libs"
+        fi
+
+        ESO_FIND_FILE($cpl_cext_check_lib, $cpl_cext_libdirs,
+                      cpl_cext_libraries)
+
+
+        if test x"$cpl_cext_includes" = xno || \
+            test x"$cpl_cext_libraries" = xno; then
+            cpl_cext_notfound=""
+
+            if test x"$cpl_cext_includes" = xno; then
+                if test x"$cpl_cext_libraries" = xno; then
+                    cpl_cext_notfound="(headers and libraries)"
+                else
+                    cpl_cext_notfound="(headers)"
+                fi
+            else
+                cpl_cext_notfound="(libraries)"
+            fi
+
+            AC_MSG_ERROR([libcext $cpl_cext_notfound was not found on your system. Please check!])
+        else
+            AC_MSG_RESULT([libraries $cpl_cext_libraries, headers $cpl_cext_includes])
+        fi
+
+
+        # Set up the symbols
+
+        CX_INCLUDES="-I$cpl_cext_includes"
+        CX_LDFLAGS="-L$cpl_cext_libraries"
+        LIBCEXT="-lcext"
+        
+        
+        AC_MSG_CHECKING([whether libcext can be used])
+        AC_LANG_PUSH(C)
+        
+        cpl_cext_cflags_save="$CFLAGS"
+        cpl_cext_ldflags_save="$LDFLAGS"
+        cpl_cext_libs_save="$LIBS"
+
+        CFLAGS="$CX_INCLUDES $CFLAGS"
+        LDFLAGS="$CX_LDFLAGS $LDFLAGS"
+        LIBS="$LIBCEXT"
+        
+        AC_LINK_IFELSE([AC_LANG_PROGRAM(
+                       [[
+                       #include <cxutils.h>
+                       ]],
+                       [
+                       cx_program_set_name("MyProgram");
+                       ])],
+                       [cpl_cext_is_usable="yes"],
+                       [cpl_cext_is_usable="no"])
+
+        AC_MSG_RESULT([$cpl_cext_is_usable])
+        
+        AC_LANG_POP(C)
+        
+        CFLAGS="$cpl_cext_cflags_save"
+        LDFLAGS="$cpl_cext_ldflags_save"
+        LIBS="$cpl_cext_libs_save"
+
+        if test x"$cpl_cext_is_usable" = xno; then
+            AC_MSG_ERROR([Linking with libcext failed! Please check architecture!])
+        fi
+        
+    else
+    
+        AC_MSG_RESULT([disabled])
+        AC_MSG_WARN([libcext checks have been disabled! This package may not build!])
+        CX_INCLUDES=""
+        CX_LDFLAGS=""
+        LIBCEXT=""
+        
+    fi
+
+    AC_SUBST(CX_INCLUDES)
+    AC_SUBST(CX_LDFLAGS)
+    AC_SUBST(LIBCEXT)
+
+])
+
+
+# CPL_CHECK_WCS(version)
+#-----------------------
+# Checks for the wcs library and header files.
+AC_DEFUN([CPL_CHECK_WCS],
+[
+    AC_MSG_CHECKING([for libwcs])
+
+
+    cpl_wcs_check_version="$1"
+    cpl_wcs_check_header="wcslib/wcslib.h"
+    cpl_wcs_check_lib="libwcs.a"
+
+    cpl_wcs_includes=""
+    cpl_wcs_libraries=""
+
+
+    AC_ARG_WITH(wcs,
+                AC_HELP_STRING([--with-wcs],
+                               [location where wcs is installed]),
+                [
+                    cpl_with_wcs=$withval
+                ])
+
+    AC_ARG_WITH(wcs-includes,
+                AC_HELP_STRING([--with-wcs-includes],
+                               [location of the libwcs header files]),
+                cpl_with_wcs_includes=$withval)
+
+    AC_ARG_WITH(wcs-libs,
+                AC_HELP_STRING([--with-wcs-libs],
+                               [location of the libwcs library]),
+                cpl_with_wcs_libs=$withval)
+
+
+    # Check for the wcs includes
+
+	if test -z "$cpl_with_wcs_includes"; then    
+    	
+    	if test -z "$cpl_with_wcs"; then
+    
+    		# Try some known system locations
+    	
+    		cpl_wcs_incdirs="/opt/wcslib/include/wcslib"
+    		cpl_wcs_incdirs="$cpl_wcs_incdirs /usr/local/include/wcslib"
+    		cpl_wcs_incdirs="$cpl_wcs_incdirs /usr/local/include"
+    		cpl_wcs_incdirs="$cpl_wcs_incdirs /usr/include/wcslib"
+    		cpl_wcs_incdirs="$cpl_wcs_incdirs /usr/include"
+    	
+        	test -n "$WCSDIR" && \
+        		cpl_wcs_incdirs="$WCSDIR/include \
+        					     $cpl_wcs_incdirs"
+        	
+    	else
+    	
+        	cpl_wcs_incdirs="$cpl_with_wcs/include"
+        	
+    	fi
+    
+    else
+    
+    	cpl_wcs_incdirs="$cpl_with_wcs_includes"
+    	
+    fi
+    
+    ESO_FIND_FILE($cpl_wcs_check_header, $cpl_wcs_incdirs, cpl_wcs_includes)
+
+
+    # Check for the wcs library
+    
+    if test -z "$cpl_with_wcs_libs"; then
+    
+    	if test -z "$cpl_with_wcs"; then
+    	
+    		# Try some known system locations
+    		
+    		cpl_wcs_libdirs="/opt/wcslib/lib64"
+    		cpl_wcs_libdirs="$cpl_wcs_libdirs /opt/wcslib/lib"
+    		cpl_wcs_libdirs="$cpl_wcs_libdirs /opt/wcslib/lib32"
+    		cpl_wcs_libdirs="$cpl_wcs_libdirs /usr/local/lib64"
+    		cpl_wcs_libdirs="$cpl_wcs_libdirs /usr/local/lib"
+    		cpl_wcs_libdirs="$cpl_wcs_libdirs /usr/local/lib32"
+    		cpl_wcs_libdirs="$cpl_wcs_libdirs /usr/lib64"
+    		cpl_wcs_libdirs="$cpl_wcs_libdirs /usr/lib"
+    		cpl_wcs_libdirs="$cpl_wcs_libdirs /usr/lib32"
+    		
+	        test -n "$WCSDIR" && \
+    	    	cpl_wcs_libdirs="$WCSDIR/lib64 \
+    	    	                 $WCSDIR/lib \
+    	    	                 $WCSDIR/lib32 \
+    	    	                 $cpl_wcs_libdirs"
+
+        else
+
+        	cpl_wcs_libdirs="$cpl_with_wcs/lib64"
+        	cpl_wcs_libdirs="$cpl_wcs_libdirs $cpl_with_wcs/lib"
+        	cpl_wcs_libdirs="$cpl_wcs_libdirs $cpl_with_wcs/lib32"
+
+        fi
+        	
+    else
+
+        cpl_wcs_libdirs="$cpl_with_wcs_libs"
+
+    fi
+    
+    ESO_FIND_FILE($cpl_wcs_check_lib, $cpl_wcs_libdirs, cpl_wcs_libraries)
+
+
+    if test x"$cpl_wcs_includes" = xno || \
+    	test x"$cpl_wcs_libraries" = xno; then
+    	cpl_wcs_notfound=""
+    	
+        if test x"$cpl_wcs_includes" = xno; then
+            if test x"$cpl_wcs_libraries" = xno; then
+                cpl_wcs_notfound="(headers and libraries)"
+            else
+                cpl_wcs_notfound="(headers)"
+            fi
+        else
+            cpl_wcs_notfound="(libraries)"
+        fi
+
+        AC_MSG_WARN([libwcs $cpl_wcs_notfound was not found on your system. WCS support will be disabled!])
+        
+    else
+    
+        AC_MSG_RESULT([libraries $cpl_wcs_libraries, headers $cpl_wcs_includes])
+        
+        
+        # Setup the symbols
+
+        WCS_INCLUDES="-I$cpl_wcs_includes/wcslib"
+        WCS_LDFLAGS="-L$cpl_wcs_libraries"
+        LIBWCS="-lwcs -lm"
+        LIBWCS_STATIC="$cpl_wcs_libraries/$cpl_wcs_check_lib -lm"
+
+        
+        # Check wcs library version
+
+        AC_MSG_CHECKING([for a libwcs version >= $cpl_wcs_check_version])
+        
+        AC_LANG_PUSH(C)
+        
+        cpl_wcs_cflags_save="$CFLAGS"
+        cpl_wcs_ldflags_save="$LDFLAGS"
+        cpl_wcs_libs_save="$LIBS"
+
+        CFLAGS="$WCS_INCLUDES $CFLAGS"
+        LDFLAGS="$WCS_LDFLAGS $LDFLAGS"
+        LIBS="$LIBWCS_STATIC"
+        
+        AC_RUN_IFELSE([AC_LANG_PROGRAM(
+                      [[
+                      #include <stdio.h>
+                      #include <wcslib.h>
+                      
+                      #define stringify(v) stringify_arg(v)
+                      #define stringify_arg(v) #v
+                      ]],
+                      [
+                      char vmin[[]] = "$cpl_wcs_check_version";
+                      char vlib[[]] = stringify(WCSLIB_VERSION);
+
+                      int min_major = 0;
+                      int min_minor = 0;
+                      int min_micro = 0;
+
+                      int lib_major = 0;
+                      int lib_minor = 0;
+                      int lib_micro = 0;
+
+                      sscanf(vmin, "%d.%d.%d", &min_major, &min_minor, &min_micro);
+                      sscanf(vlib, "%d.%d.%d", &lib_major, &lib_minor, &lib_micro);
+                     
+                      FILE* f = fopen("conftest.out", "w");
+                      fprintf(f, "%s\n", vlib);
+                      fclose(f);
+                                          
+                      if (lib_major < min_major) {
+                          return 1;
+                      }
+                      else {
+                          if (lib_major == min_major) {
+                              if (lib_minor <  min_minor) {
+                                  return 1;
+                              }
+                              else {
+                                  if (lib_minor == min_minor) {
+                                      if (lib_micro < min_micro) {
+                                          return 1;
+                                      }
+                                  }
+                              }
+                          }
+                      }
+
+                      return 0;                      
+                      ])],
+                      [cpl_wcs_version="`cat conftest.out`"],
+                      [
+                       cpl_wcs_version="no";
+                       cpl_wcs_version_found="`cat conftest.out`"
+                      ])
+
+        AC_MSG_RESULT([$cpl_wcs_version])
+        
+        AC_LANG_POP(C)
+        
+        CFLAGS="$cpl_wcs_cflags_save"
+        LDFLAGS="$cpl_wcs_ldflags_save"
+        LIBS="$cpl_wcs_libs_save"
+
+
+        if test x"$cpl_wcs_version" = xno; then
+        
+            AC_MSG_WARN([Installed libwcs ($cpl_wcs_version_found) is too old. WCS support will not be available!])
+            
+            WCS_INCLUDES=""
+            WCS_LDFLAGS=""
+            LIBWCS=""
+            
+        else	         
+    	    AC_DEFINE_UNQUOTED(CPL_WCS_INSTALLED, 1, [Defined if WCS is available])
+ 		fi
+ 
+        AC_SUBST(WCS_INCLUDES)
+        AC_SUBST(WCS_LDFLAGS)
+        AC_SUBST(LIBWCS)
+ 
+    fi
+
+])
+
+
+# CPL_CHECK_FFTW(version)
+#------------------------
+# Checks for the FFTW library and header files.
+AC_DEFUN([CPL_CHECK_FFTW],
+[
+
+	cpl_fftw_check_version="$1"
+    cpl_fftw_check_header="fftw3.h"
+    cpl_fftw_check_lib="libfftw3.a"
+    cpl_fftwf_check_lib="libfftw3f.a"
+
+    cpl_fftw_includes=""
+    cpl_fftw_libraries=""
+    cpl_fftwf_libraries=""
+
+    AC_ARG_WITH(fftw,
+                AC_HELP_STRING([--with-fftw],
+                               [location where fftw is installed]),
+                [
+                    cpl_with_fftw=$withval
+                ])
+
+    AC_ARG_WITH(fftw-includes,
+                AC_HELP_STRING([--with-fftw-includes],
+                               [location of the fftw header files]),
+                cpl_with_fftw_includes=$withval)
+
+    AC_ARG_WITH(fftw-libs,
+                AC_HELP_STRING([--with-fftw-libs],
+                               [location of the fftw libraries]),
+                cpl_with_fftw_libs=$withval)
+
+
+    AC_MSG_CHECKING([for fftw (normal-precision)])
+
+
+    # Check for the fftw includes
+
+	if test -z "$cpl_with_fftw_includes"; then    
+    	
+    	if test -z "$cpl_with_fftw"; then
+    
+    		# Try some known system locations
+    	
+    		cpl_fftw_incdirs="/opt/fftw/include"
+    		cpl_fftw_incdirs="$cpl_fftw_incdirs /usr/local/include"
+    		cpl_fftw_incdirs="$cpl_fftw_incdirs /usr/include"
+    	
+        	test -n "$FFTWDIR" && \
+        		cpl_fftw_incdirs="$FFTWDIR/include \
+        					     $cpl_fftw_incdirs"
+        	
+    	else
+    	
+        	cpl_fftw_incdirs="$cpl_with_fftw/include"
+        	
+    	fi
+    
+    else
+    
+    	cpl_fftw_incdirs="$cpl_with_fftw_includes"
+    	
+    fi
+    
+    ESO_FIND_FILE($cpl_fftw_check_header, $cpl_fftw_incdirs, cpl_fftw_includes)
+
+
+    # Check for normal-precision fftw library
+    
+    if test -z "$cpl_with_fftw_libs"; then
+    
+    	if test -z "$cpl_with_fftw"; then
+    	
+    		# Try some known system locations
+    		
+    		cpl_fftw_libdirs="/opt/fftw/lib64"
+    		cpl_fftw_libdirs="$cpl_fftw_libdirs /opt/fftw/lib"
+    		cpl_fftw_libdirs="$cpl_fftw_libdirs /opt/fftw/lib32"
+    		cpl_fftw_libdirs="$cpl_fftw_libdirs /usr/local/lib64"
+    		cpl_fftw_libdirs="$cpl_fftw_libdirs /usr/local/lib"
+    		cpl_fftw_libdirs="$cpl_fftw_libdirs /usr/local/lib32"
+    		cpl_fftw_libdirs="$cpl_fftw_libdirs /usr/lib64"
+    		cpl_fftw_libdirs="$cpl_fftw_libdirs /usr/lib"
+    		cpl_fftw_libdirs="$cpl_fftw_libdirs /usr/lib32"
+    		
+	        test -n "$FFTWDIR" && \
+    	    	cpl_fftw_libdirs="$FFTWDIR/lib64 \
+    	    	                  $FFTWDIR/lib \
+    	    	                  $FFTWDIR/lib32 \
+    	    	                  $cpl_fftw_libdirs"
+
+        else
+
+        	cpl_fftw_libdirs="$cpl_with_fftw/lib64"
+        	cpl_fftw_libdirs="$cpl_fftw_libdirs $cpl_with_fftw/lib"
+        	cpl_fftw_libdirs="$cpl_fftw_libdirs $cpl_with_fftw/lib32"
+
+        fi
+        	
+    else
+
+        cpl_fftw_libdirs="$cpl_with_fftw_libs"
+
+    fi
+    
+    ESO_FIND_FILE($cpl_fftw_check_lib, $cpl_fftw_libdirs, cpl_fftw_libraries)
+
+    if test x"$cpl_fftw_includes" = xno || \
+    	test x"$cpl_fftw_libraries" = xno; then
+    	cpl_fftw_notfound=""
+    	
+        if test x"$cpl_fftw_includes" = xno; then
+            if test x"$cpl_fftw_libraries" = xno; then
+                cpl_fftw_notfound="(headers and libraries)"
+            else
+                cpl_fftw_notfound="(headers)"
+            fi
+        else
+            cpl_fftw_notfound="(libraries)"
+        fi
+
+		AC_MSG_RESULT([no])
+        AC_MSG_WARN([fftw (normal-precision) $cpl_fftw_notfound was not found on your system.])
+        
+    else
+    
+        AC_MSG_RESULT([libraries $cpl_fftw_libraries, headers $cpl_fftw_includes])
+
+	
+		# Set up the symbols
+	
+        FFTW_INCLUDES="-I$cpl_fftw_includes"
+        FFTW_LDFLAGS="-L$cpl_fftw_libraries"
+        LIBFFTW="-lfftw3 -lm"
+        LIBFFTW_STATIC="$cpl_fftw_libraries/$cpl_fftw_check_lib -lm"
+
+
+        # Check fftw (normal-precision) library version
+
+        AC_MSG_CHECKING([for a fftw (normal-precision) version >= $cpl_fftw_check_version])
+        
+        AC_LANG_PUSH(C)
+        
+        cpl_fftw_cflags_save="$CFLAGS"
+        cpl_fftw_ldflags_save="$LDFLAGS"
+        cpl_fftw_libs_save="$LIBS"
+
+        CFLAGS="$FFTW_INCLUDES $CFLAGS"
+        LDFLAGS="$FFTW_LDFLAGS $LDFLAGS"
+        LIBS="$LIBFFTW_STATIC"
+        
+        AC_RUN_IFELSE([AC_LANG_PROGRAM(
+                      [[
+                      #include <stdio.h>
+                      #include <stdlib.h>
+                      #include <string.h>
+                      #include <fftw3.h>
+                      ]],
+                      [
+                      char vmin[[]] = "$cpl_fftw_check_version";
+                      char *vstr    = strdup(fftw_version);
+                      char *vlib    = vstr;
+                      char *suffix  = NULL;
+
+                      int min_major = 0;
+                      int min_minor = 0;
+                      int min_micro = 0;
+
+                      int lib_major = 0;
+                      int lib_minor = 0;
+                      int lib_micro = 0;
+
+                      vlib = strchr(vstr, '-') + 1;
+                      suffix = strrchr(vlib, '-');
+					  
+					  if (suffix) {
+                          *suffix = '\0';
+					  }
+					  
+                      sscanf(vmin, "%d.%d.%d", &min_major, &min_minor, &min_micro);
+                      sscanf(vlib, "%d.%d.%d", &lib_major, &lib_minor, &lib_micro);
+                     
+                      FILE* f = fopen("conftest.out", "w");
+                      fprintf(f, "%s\n", vlib);
+                      fclose(f);
+                      
+                      free(vstr);
+                                          
+                      if (lib_major < min_major) {
+                          return 1;
+                      }
+                      else {
+                          if (lib_major == min_major) {
+                              if (lib_minor <  min_minor) {
+                                  return 1;
+                              }
+                              else {
+                                  if (lib_minor == min_minor) {
+                                      if (lib_micro < min_micro) {
+                                          return 1;
+                                      }
+                                  }
+                              }
+                          }
+                      }
+
+                      return 0;                      
+                      ])],
+                      [cpl_fftw_version="`cat conftest.out`"],
+                      [
+                       cpl_fftw_version="no";
+                       cpl_fftw_version_found="`cat conftest.out`"
+                      ])
+
+        AC_MSG_RESULT([$cpl_fftw_version])
+        
+        AC_LANG_POP(C)
+        
+        CFLAGS="$cpl_fftw_cflags_save"
+        LDFLAGS="$cpl_fftw_ldflags_save"
+        LIBS="$cpl_fftw_libs_save"
+
+        if test x"$cpl_fftw_version" = xno; then
+        
+            AC_MSG_WARN([Installed normal-precision fftw ($cpl_fftw_version_found) is too old])
+            
+            FFTW_INCLUDES=""
+            FFTW_LDFLAGS=""
+            LIBFFTW=""
+            
+        else	         
+	        AC_DEFINE_UNQUOTED(CPL_FFTW_INSTALLED, 1, [Defined if FFTW (normal-precision) is available])
+ 		fi
+ 
+        AC_SUBST(FFTW_INCLUDES)
+        AC_SUBST(FFTW_LDFLAGS)
+        AC_SUBST(LIBFFTW)
+			
+	fi
+	
+	
+	# Check for single-precision fftw
+	
+    AC_MSG_CHECKING([for fftw (single-precision)])
+
+    ESO_FIND_FILE($cpl_fftwf_check_lib, $cpl_fftw_libdirs, cpl_fftwf_libraries)
+
+    if test x"$cpl_fftw_includes" = xno || \
+    	test x"$cpl_fftwf_libraries" = xno; then
+    	cpl_fftw_notfound=""
+    	
+        if test x"$cpl_fftw_includes" = xno; then
+            if test x"$cpl_fftwf_libraries" = xno; then
+                cpl_fftw_notfound="(headers and libraries)"
+            else
+                cpl_fftw_notfound="(headers)"
+            fi
+        else
+            cpl_fftw_notfound="(libraries)"
+        fi
+
+		AC_MSG_RESULT([no])
+        AC_MSG_WARN([fftw (single-precision) $cpl_fftw_notfound was not found on your system.])
+        
+    else
+    
+        AC_MSG_RESULT([libraries $cpl_fftwf_libraries, headers $cpl_fftw_includes])
+
+	
+		# Set up the symbols
+	
+        FFTWF_INCLUDES="-I$cpl_fftw_includes"
+        FFTWF_LDFLAGS="-L$cpl_fftwf_libraries"
+        LIBFFTWF="-lfftw3f -lm"
+        LIBFFTWF_STATIC="$cpl_fftwf_libraries/$cpl_fftwf_check_lib -lm"
+
+
+        # Check fftw (single-precision) library version
+
+        AC_MSG_CHECKING([for a fftw (single-precision) version >= $cpl_fftw_check_version])
+        
+        AC_LANG_PUSH(C)
+        
+        cpl_fftw_cflags_save="$CFLAGS"
+        cpl_fftw_ldflags_save="$LDFLAGS"
+        cpl_fftw_libs_save="$LIBS"
+
+        CFLAGS="$FFTWF_INCLUDES $CFLAGS"
+        LDFLAGS="$FFTWF_LDFLAGS $LDFLAGS"
+        LIBS="$LIBFFTWF"
+        
+        AC_RUN_IFELSE([AC_LANG_PROGRAM(
+                      [[
+                      #include <stdio.h>
+                      #include <stdlib.h>
+                      #include <string.h>
+                      #include <fftw3.h>
+                      ]],
+                      [
+                      char vmin[[]] = "$cpl_fftw_check_version";
+                      char *vstr    = strdup(fftwf_version);
+                      char *vlib    = vstr;
+                      char *suffix  = NULL;
+
+                      int min_major = 0;
+                      int min_minor = 0;
+                      int min_micro = 0;
+
+                      int lib_major = 0;
+                      int lib_minor = 0;
+                      int lib_micro = 0;
+
+                      vlib = strchr(vstr, '-') + 1;
+                      suffix = strrchr(vlib, '-');
+					  
+					  if (suffix) {
+                          *suffix = '\0';
+					  }
+					  
+                      sscanf(vmin, "%d.%d.%d", &min_major, &min_minor, &min_micro);
+                      sscanf(vlib, "%d.%d.%d", &lib_major, &lib_minor, &lib_micro);
+                     
+                      FILE* f = fopen("conftest.out", "w");
+                      fprintf(f, "%s\n", vlib);
+                      fclose(f);
+                      
+                      free(vstr);
+                                          
+                      if (lib_major < min_major) {
+                          return 1;
+                      }
+                      else {
+                          if (lib_major == min_major) {
+                              if (lib_minor <  min_minor) {
+                                  return 1;
+                              }
+                              else {
+                                  if (lib_minor == min_minor) {
+                                      if (lib_micro < min_micro) {
+                                          return 1;
+                                      }
+                                  }
+                              }
+                          }
+                      }
+
+                      return 0;                      
+                      ])],
+                      [cpl_fftwf_version="`cat conftest.out`"],
+                      [
+                       cpl_fftwf_version="no";
+                       cpl_fftwf_version_found="`cat conftest.out`"
+                      ])
+
+        AC_MSG_RESULT([$cpl_fftwf_version])
+        
+        AC_LANG_POP(C)
+        
+        CFLAGS="$cpl_fftw_cflags_save"
+        LDFLAGS="$cpl_fftw_ldflags_save"
+        LIBS="$cpl_fftw_libs_save"
+
+        if test x"$cpl_fftwf_version" = xno; then
+        
+            AC_MSG_WARN([Installed single-precision fftw ($cpl_fftw_version_found) is too old!])
+            
+            FFTWF_INCLUDES=""
+            FFTWF_LDFLAGS=""
+            LIBFFTWF=""
+            
+        else	         
+	        AC_DEFINE_UNQUOTED(CPL_FFTWF_INSTALLED, 1, [Defined if FFTW (single-precision) is available])
+ 		fi
+ 
+        AC_SUBST(FFTWF_INCLUDES)
+        AC_SUBST(FFTWF_LDFLAGS)
+        AC_SUBST(LIBFFTWF)
+			
+	fi
+
+])
+
+
+#
+# CPL_CREATE_SYMBOLS(build=[])
+#-----------------------------
+# Sets the Makefile symbols for the CPL libraries. If an argument is
+# provided the symbols are setup for building CPL, if no argument is
+# given (default) the symbols are set for using the libraries
+# for external package development.
+AC_DEFUN([CPL_CREATE_SYMBOLS],
+[
+
+    if test -z "$1"; then
+        LIBCPLCORE='-lcplcore'
+        LIBCPLDRS='-lcpldrs'
+        LIBCPLUI='-lcplui'
+        LIBCPLDFS='-lcpldfs'
+    else
+        LIBCPLCORE='$(top_builddir)/cplcore/libcplcore.la'
+        LIBCPLDRS='$(top_builddir)/cpldrs/libcpldrs.la'
+        LIBCPLUI='$(top_builddir)/cplui/libcplui.la'
+        LIBCPLDFS='$(top_builddir)/cpldfs/libcpldfs.la'
+    fi
+
+   AC_SUBST(LIBCPLCORE)
+   AC_SUBST(LIBCPLDRS)
+   AC_SUBST(LIBCPLUI)
+   AC_SUBST(LIBCPLDFS)
+
+])
+
+
+# CPL_CHECK_LIBS
+#---------------
+# Checks for the CPL libraries and header files.
+AC_DEFUN([CPL_CHECK_LIBS],
+[
+
+    AC_MSG_CHECKING([for CPL])
+
+    cpl_check_cpl_header="cpl.h"
+    cpl_check_cpl_lib="libcplcore.a"
+
+    cpl_incdirs=""
+    cpl_libdirs=""
+    cpl_includes=""
+    cpl_libraries=""
+
+    AC_ARG_WITH(cpl,
+                AC_HELP_STRING([--with-cpl],
+                               [location where CPL is installed]),
+                [
+                    cpl_with_cpl=$withval
+                ])
+
+    AC_ARG_WITH(cpl-includes,
+                AC_HELP_STRING([--with-cpl-includes],
+                               [location of the CPL header files]),
+                cpl_with_cpl_includes=$withval)
+
+    AC_ARG_WITH(cpl-libs,
+                AC_HELP_STRING([--with-cpl-libs],
+                               [location of the CPL library]),
+                cpl_with_cpl_libs=$withval)
+
+    AC_ARG_ENABLE(cpl-test,
+                  AC_HELP_STRING([--disable-cpl-test],
+                                 [disables checks for the CPL library and headers]),
+                  cpl_enable_cpl_test=$enableval,
+                  cpl_enable_cpl_test=yes)
+
+
+    if test "x$cpl_enable_cpl_test" = xyes; then
+    
+        # Check for the CPL includes
+
+        if test -z "$cpl_with_cpl_includes"; then
+        
+            if test -z "$cpl_with_cpl"; then
+            
+                # Try some known system locations
+                
+                cpl_incdirs="/opt/cpl/include"
+                cpl_incdirs="$cpl_incdirs /usr/local/include"
+                cpl_incdirs="$cpl_incdirs /usr/include"
+
+                test -n "$CPLDIR" && \
+                    cpl_incdirs="$CPLDIR/include \
+                                 $cpl_incdirs"
+
+            else
+
+                cpl_incdirs="$cpl_with_cpl/include"
+
+            fi
+            
+        else
+            cpl_incdirs="$cpl_with_cpl_includes"
+        fi
+
+        ESO_FIND_FILE($cpl_check_cpl_header, $cpl_incdirs, cpl_includes)
+
+
+        # Check for the CPL libraries
+
+        if test -z "$cpl_with_cpl_libs"; then
+
+            if test -z "$cpl_with_cpl"; then
+            
+                # Try some known system locations
+
+                cpl_libdirs="/opt/cpl/lib"
+                cpl_libdirs="$cpl_libdirs /usr/local/lib64"
+                cpl_libdirs="$cpl_libdirs /usr/local/lib"
+                cpl_libdirs="$cpl_libdirs /usr/local/lib32"
+                cpl_libdirs="$cpl_libdirs /usr/lib64"
+                cpl_libdirs="$cpl_libdirs /usr/lib"
+                cpl_libdirs="$cpl_libdirs /usr/lib32"
+
+                test -n "$CPLDIR" && \
+                    cpl_libdirs="$CPLDIR/lib64 $CPLDIR/lib $CPLDIR/lib32 \
+                                 $cpl_libdirs"
+
+            else
+
+                cpl_libdirs="$cpl_with_cpl/lib64"
+                cpl_libdirs="$cpl_libdirs $cpl_with_cpl/lib"
+                cpl_libdirs="$cpl_libdirs $cpl_with_cpl/lib32"
+
+            fi
+            
+        else
+            cpl_libdirs="$cpl_with_cpl_libs"
+        fi
+
+        ESO_FIND_FILE($cpl_check_cpl_lib, $cpl_libdirs, cpl_libraries)
+
+
+        if test x"$cpl_includes" = xno || test x"$cpl_libraries" = xno; then
+            cpl_notfound=""
+
+            if test x"$cpl_includes" = xno; then
+                if test x"$cpl_libraries" = xno; then
+                    cpl_notfound="(headers and libraries)"
+                else
+                    cpl_notfound="(headers)"
+                fi
+            else
+                cpl_notfound="(libraries)"
+            fi
+
+            AC_MSG_ERROR([CPL $cpl_notfound was not found on your system. Please check!])
+        else
+            AC_MSG_RESULT([libraries $cpl_libraries, headers $cpl_includes])
+        fi
+
+    	# The libcext headers are required. By default it part of the
+    	# CPL installation and it is assumed that the cext headers are
+    	# present in the same location as the CPL headers
+   	      	   
+   	    CPL_CHECK_CEXT($cpl_includes, $cpl_libraries) 
+
+
+        # Set up the symbols
+
+        CPL_INCLUDES="-I$cpl_includes $CX_INCLUDES $CFITSIO_INCLUDES"
+        CPL_LDFLAGS="-L$cpl_libraries $CX_LDFLAGS $CFITSIO_LDFLAGS"
+        CPL_CREATE_SYMBOLS
+ 
+ 
+        AC_MSG_CHECKING([whether CPL can be used])
+        AC_LANG_PUSH(C)
+        
+        cpl_cflags_save="$CFLAGS"
+        cpl_ldflags_save="$LDFLAGS"
+        cpl_libs_save="$LIBS"
+
+        CFLAGS="$CPL_INCLUDES $CFLAGS"
+        LDFLAGS="$CPL_LDFLAGS $LDFLAGS"
+        LIBS="$LIBCPLCORE $LIBCEXT $LIBS"
+        
+        AC_LINK_IFELSE([AC_LANG_PROGRAM(
+                       [[
+                       #include <cpl.h>
+                       ]],
+                       [
+                       cpl_init(CPL_INIT_DEFAULT);
+                       ])],
+                       [cpl_is_usable="yes"],
+                       [cpl_is_usable="no"])
+
+        AC_MSG_RESULT([$cpl_is_usable])
+        
+        AC_LANG_POP(C)
+        
+        CFLAGS="$cpl_cflags_save"
+        LDFLAGS="$cpl_ldflags_save"
+        LIBS="$cpl_libs_save"
+
+        if test x"$cpl_is_usable" = xno; then
+            AC_MSG_ERROR([Linking with CPL failed! Please check architecture!])
+        fi
+        
+    else
+    
+        AC_MSG_RESULT([disabled])
+        AC_MSG_WARN([CPL checks have been disabled! This package may not build!])
+        CPL_INCLUDES=""
+        CPL_LDFLAGS=""
+        LIBCPLCORE=""
+        LIBCPLDRS=""
+        LIBCPLUI=""
+        LIBCPLDFS=""
+        
+    fi
+
+    AC_SUBST(CPL_INCLUDES)
+    AC_SUBST(CPL_LDFLAGS)
+    AC_SUBST(LIBCPLCORE)
+    AC_SUBST(LIBCPLDRS)
+    AC_SUBST(LIBCPLUI)
+    AC_SUBST(LIBCPLDFS)
+
+])
diff --git a/hdrl/m4macros/eso.m4 b/hdrl/m4macros/eso.m4
new file mode 100644
index 0000000..6b1410f
--- /dev/null
+++ b/hdrl/m4macros/eso.m4
@@ -0,0 +1,1116 @@
+# ESO_PROG_CC_FLAG(FLAG, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
+#-----------------------------------------------------------------
+AC_DEFUN([ESO_PROG_CC_FLAG],
+[
+    AC_REQUIRE([AC_PROG_CC])
+
+    flag=`echo $1 | sed 'y%.=/+-%___p_%'`
+    AC_CACHE_CHECK([whether $CC supports -$1],
+                   [eso_cv_prog_cc_$flag],
+                   [
+                       eval "eso_cv_prog_cc_$flag=no"
+                       AC_LANG_PUSH(C)
+
+                       echo 'int main() { return 0; }' >conftest.$ac_ext
+
+                       try_compile="`$CC -$1 -c conftest.$ac_ext 2>&1`"
+                       if test -z "$try_compile"; then
+                           try_link="`$CC -$1 -o conftest$ac_exeext \
+                                    conftest.$ac_ext 2>&1`"
+                           if test -z "$try_link"; then
+                               eval "eso_cv_prog_cc_$flag=yes"
+                           fi
+                       fi
+                       rm -f conftest*
+
+                       AC_LANG_POP(C)
+                   ])
+
+    if eval "test \"`echo '$eso_cv_prog_cc_'$flag`\" = yes"; then
+        :
+        $2
+    else
+        :
+        $3
+    fi
+])
+
+
+# ESO_PROG_CC_ATTRIBUTE(VARIANT1, [VARIANT2], [CODE], [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
+#----------------------------------------------------------------------------------------------
+AC_DEFUN([ESO_PROG_CC_ATTRIBUTE],
+[
+
+    AC_CACHE_CHECK([if $CC supports __attribute__(( ifelse([$2], , [$1], [$2]) ))],
+                   AS_TR_SH([eso_cv_prog_cc_attribute_$1]),
+                   [
+                       eso_save_CFLAGS="$CFLAGS"
+                       CFLAGS="$CFLAGS"
+                   
+                       AC_COMPILE_IFELSE([AC_LANG_SOURCE([$3])],
+                                         [eval "AS_TR_SH([eso_cv_prog_cc_attribute_$1])='yes'"],
+                                         [eval "AS_TR_SH([eso_cv_prog_cc_attribute_$1])='no'"])
+                       CFLAGS="$eso_save_CFLAGS"
+                   ])
+                   
+    if eval "test x\$AS_TR_SH([eso_cv_prog_cc_attribute_$1]) = xyes"; then
+        :
+        $4
+    else
+        :
+        $5
+    fi
+               
+])
+
+
+# ESO_PROG_CC_ATTRIBUTE_VISIBILITY(ARG, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
+#--------------------------------------------------------------------------------
+AC_DEFUN([ESO_PROG_CC_ATTRIBUTE_VISIBILITY],
+[
+
+    ESO_PROG_CC_ATTRIBUTE([visibility_$1], [visibility("$1")],
+                          [void __attribute__((visibility("$1"))) $1_function() { }],
+                          [$2], [$3])
+
+])
+
+
+# ESO_ENABLE_DEBUG(debug=no)
+#---------------------------
+AC_DEFUN([ESO_ENABLE_DEBUG],
+[
+    AC_REQUIRE([AC_PROG_CC])
+
+    AC_ARG_ENABLE(debug,
+                  AC_HELP_STRING([--enable-debug],
+                                 [creates debugging code [[default=$1]]]),
+                  eso_enable_debug=$enableval, eso_enable_debug=$1)
+
+    AC_CACHE_CHECK([whether debugging code should be created],
+                   eso_cv_enable_debug,
+                   eso_cv_enable_debug=$eso_enable_debug)
+
+    if test x"$eso_cv_enable_debug" = xyes; then
+
+        eso_clean_CFLAGS="`echo $CFLAGS | sed -e 's/-O[[0-9]]//g' \
+                                              -e 's/-g[[0-9]]//g' \
+                                              -e 's/-g[[a-z,A-Z]]* / /g' \
+                                              -e 's/-[[Og]]//g'`"
+
+        ESO_PROG_CC_FLAG([g3], [CFLAGS="$CFLAGS -g3"])
+
+        if test x"$eso_cv_prog_cc_g3" = xyes; then
+            CFLAGS="-g3"
+        else
+            if test x"$ac_cv_prog_cc_g" = xyes; then
+                CFLAGS="-g"
+            else
+                CFLAGS=""
+            fi
+        fi
+
+        ESO_PROG_CC_FLAG([ggdb], [CFLAGS="$CFLAGS -ggdb"])
+        ESO_PROG_CC_FLAG([O0], [CFLAGS="$CFLAGS -O0"])
+        ESO_PROG_CC_FLAG([rdynamic], [CFLAGS="$CFLAGS -rdynamic"])
+        ESO_PROG_CC_FLAG([Wall], [CFLAGS="$CFLAGS -Wall"])
+        ESO_PROG_CC_FLAG([W], [CFLAGS="$CFLAGS -W"])
+
+        CFLAGS="$CFLAGS $eso_clean_CFLAGS"
+        ESO_DEBUG_FLAGS="-DESO_ENABLE_DEBUG"
+    else
+        ESO_DEBUG_FLAGS="-DNDEBUG"
+    fi
+
+    AC_SUBST(ESO_DEBUG_FLAGS)
+])
+
+
+# ESO_ENABLE_STRICT(strict=no)
+#-----------------------------
+AC_DEFUN([ESO_ENABLE_STRICT],
+[
+	AC_REQUIRE([AC_PROG_EGREP])
+    AC_REQUIRE([AC_PROG_CC])
+
+    AC_ARG_ENABLE(strict,
+                  AC_HELP_STRING([--enable-strict],
+                                 [compiles with strict compiler options (may not work!) [[default=$1]]]),
+                  eso_enable_strict=$enableval, eso_enable_strict=$1)
+
+    AC_CACHE_CHECK([whether strict compiler options should be used],
+                   eso_cv_enable_strict,
+                   eso_cv_enable_strict=$eso_enable_strict)
+
+
+    if test x"$eso_cv_enable_strict" = xyes; then
+    
+    	eso_enable_strict_std_set=no
+    	
+        if test -n "$CFLAGS"; then
+            echo $CFLAGS | $EGREP '(\-std=|-ansi)' >/dev/null 2>&1
+            if test x"$?" = x0; then
+            	eso_enable_strict_std_set=yes
+            fi
+        fi
+        
+        if test x"$eso_enable_strict_std_set" = xno; then
+        	ESO_PROG_CC_FLAG([std=c99], [CFLAGS="$CFLAGS -std=c99"])
+        fi
+        
+        ESO_PROG_CC_FLAG([pedantic], [CFLAGS="$CFLAGS -pedantic"])
+        
+    fi
+])
+
+
+# ESO_ENABLE_PROFILE(profile=no)
+#-----------------------------
+AC_DEFUN([ESO_ENABLE_PROFILE],
+[
+    AC_REQUIRE([AC_PROG_CC])
+
+    AC_ARG_ENABLE(profile,
+                  AC_HELP_STRING([--enable-profile],
+                                 [compiles with compiler options necessary for profiling (may not work!) [[default=$1]]]),
+                  eso_enable_profile=$enableval, eso_enable_profile=$1)
+
+    AC_CACHE_CHECK([whether profiling compiler options should be used],
+                   eso_cv_enable_profile,
+                   eso_cv_enable_profile=$eso_enable_profile)
+
+
+    if test x"$eso_cv_enable_profile" = xyes; then
+        ESO_PROG_CC_FLAG([pg], [CFLAGS="$CFLAGS -pg"])
+        ESO_PROG_CC_FLAG([g], [CFLAGS="$CFLAGS -g"])
+        ESO_PROG_CC_FLAG([static-libgcc], [CFLAGS="$CFLAGS -static-libgcc"])
+
+        AC_ENABLE_SHARED(no)
+        AC_ENABLE_STATIC(yes)
+    fi
+])
+
+
+# ESO_CHECK_DOCTOOLS
+#-------------------
+AC_DEFUN([ESO_CHECK_DOCTOOLS],
+[
+    AC_ARG_VAR([DOXYGEN], [doxygen command])
+    AC_PATH_PROG([DOXYGEN], [doxygen])
+
+    AC_ARG_VAR([LATEX], [latex command])
+    AC_PATH_PROG([LATEX], [latex])
+
+
+    if test -z "${DOXYGEN}"; then
+        DOXYGEN=":"
+    fi
+
+    if test -z "${LATEX}"; then
+        LATEX=":"
+    fi
+
+])
+
+
+# ESO_PROG_AR
+#------------
+# Checks if ar is in the path
+AC_DEFUN([ESO_PROG_AR],
+[
+    AC_CHECK_PROG(AR, ar, ar, NONE)
+
+    if test x"$AR" = xNONE; then
+        AC_MSG_ERROR([Cannot find \'ar\'])
+    fi
+
+])
+
+
+# ESO_PROG_PKGCONFIG
+#-------------------
+# Checks if pkg-config is in the path
+AC_DEFUN([ESO_PROG_PKGCONFIG],
+[
+	AC_ARG_VAR([PKGCONFIG], [pkg-config command])
+	AC_CHECK_PROG([PKGCONFIG], [pkg-config], [pkg-config])
+
+])
+
+
+# ESO_CHECK_EXTRA_LIBS
+#---------------------
+# Check for non-standard headers and libraries
+AC_DEFUN([ESO_CHECK_EXTRA_LIBS],
+[
+
+    AC_ARG_WITH(extra-includes,
+                AC_HELP_STRING([--with-extra-includes=DIR],
+                               [adds non standard include paths]),
+                eso_with_extra_includes=$withval, eso_with_extra_includes=NONE)
+
+    AC_ARG_WITH(extra-libs,
+                AC_HELP_STRING([--with-extra-libs=DIR],
+                              [adds non standard library paths]),
+                eso_with_extra_libs=$withval, eso_with_extra_libs=NONE)
+
+    AC_MSG_CHECKING([for extra includes])
+    AC_CACHE_VAL([eso_cv_with_extra_includes],
+                 [
+                     eso_cv_with_extra_includes=$eso_with_extra_includes
+                 ])
+
+    if test x"$eso_cv_with_extra_includes" != xNONE; then
+        eso_save_IFS=$IFS
+        IFS=':'
+
+        for dir in $eso_cv_with_extra_includes; do
+            EXTRA_INCLUDES="$EXTRA_INCLUDES -I$dir"
+        done
+
+        IFS=$eso_save_IFS
+        AC_MSG_RESULT(added)
+    else
+        AC_MSG_RESULT(no)
+    fi
+
+
+    AC_MSG_CHECKING([for extra libs])
+    AC_CACHE_VAL([eso_cv_with_extra_libs],
+                 [
+                     eso_cv_with_extra_libs=$eso_with_extra_libs
+                 ])
+
+    if test x"$eso_cv_with_extra_libs" != xNONE; then
+        eso_save_IFS=$IFS
+        IFS=':'
+
+        for dir in $eso_cv_with_extra_libs; do
+            EXTRA_LDFLAGS="$EXTRA_LDFLAGS -L$dir"
+        done
+
+        IFS=$eso_save_IFS
+        AC_MSG_RESULT(added)
+    else
+        AC_MSG_RESULT(no)
+    fi
+
+])
+
+
+# ESO_CHECK_THREADS_POSIX
+#------------------------
+# Check whether the POSIX threads are available. The cached result is
+# set to 'yes' if either the compiler supports the '-pthread' flag, or linking
+# with the POSIX thread library works, and the header file defining the POSIX
+# threads symbols is present. If POSIX threads are not supported, the
+# result is set to 'no'. Whether the compiler supports POSIX threads,
+# or whether the library, and the header are available is stored in cache
+# variables.  
+AC_DEFUN([ESO_CHECK_THREADS_POSIX],
+[
+    AC_REQUIRE([AC_PROG_CC])
+
+    ESO_PROG_CC_FLAG([pthread], [], [])
+    
+    AC_CHECK_LIB([pthread], [pthread_create],
+                 [eso_threads_have_libpthread=yes],
+                 [eso_threads_have_libpthread=no])
+
+    AC_CHECK_HEADER([pthread.h],
+                    [eso_threads_have_pthread_h=yes],
+                    [eso_threads_have_pthread_h=no])
+
+    if test x"$eso_threads_have_pthread_h" != xyes; then
+        eso_threads_posix=no
+    else
+        if test x"$eso_threads_have_libpthread" != xyes && \
+          test x"$eso_cv_prog_cc_pthread" != xyes; then
+            eso_threads_posix=no
+        else
+            eso_threads_posix=yes
+        fi
+    fi
+    
+    
+    # Setup the POSIX thread symbols
+
+    if test x"$eso_threads_have_pthread_h" = xyes; then
+        AC_DEFINE([HAVE_PTHREAD_H], [1],
+                  [Define to 1 if you have <pthread.h>.])
+    fi
+    
+    if test x"$eso_threads_posix" = xyes; then
+    
+        if test x"$eso_cv_prog_cc_pthread" = xyes; then
+            PTHREAD_CFLAGS="-pthread"
+        else
+            PTHREAD_CFLAGS=""
+        fi
+        
+        if test x"$eso_threads_have_libpthread" = xyes; then
+            LIBPTHREAD="-lpthread"
+        else
+            LIBPTHREAD=""
+        fi
+        
+    fi  
+
+    AC_CACHE_VAL(eso_cv_threads_posix_header,
+                 eso_cv_threads_posix_header=$eso_threads_have_pthread_h)          
+    AC_CACHE_VAL(eso_cv_threads_posix_lib,
+                 eso_cv_threads_posix_lib=$eso_threads_have_libpthread)          
+    AC_CACHE_VAL(eso_cv_threads_posix_flags,
+                 eso_cv_threads_posix_flags=$eso_cv_prog_cc_pthread)          
+    AC_CACHE_VAL(eso_cv_threads_posix,
+                 eso_cv_threads_posix=$eso_threads_posix)
+
+    AC_SUBST(PTHREAD_CFLAGS)
+    AC_SUBST(LIBPTHREAD)
+    
+])
+
+
+# ESO_CHECK_FUNC(FUNCTION, INCLUDES, SYMBOL)
+#-------------------------------------------
+# Checks whether a function is available and declared.
+AC_DEFUN([ESO_CHECK_FUNC],
+[
+
+    AC_LANG_PUSH(C)
+
+    AC_CHECK_DECL($1, [], [], [$2])
+
+    eso_save_CFLAGS="$CFLAGS"
+
+    if test x"$GCC" = xyes; then
+        CFLAGS="$CFLAGS -pedantic-errors"
+    fi
+
+    AC_CHECK_FUNC($1)
+
+    CFLAGS="$eso_save_CFLAGS"
+
+    AC_LANG_POP(C)
+
+    if test x"$ac_cv_have_decl_$1" = xyes &&
+       test x"$ac_cv_func_$1" = xyes; then
+        AC_DEFINE($3)
+    fi
+
+])
+
+
+# ESO_FUNC_VSNPRINTF_C99
+#-----------------------
+# Check whether vsnprintf() has C99 semantics.
+AC_DEFUN([ESO_FUNC_VSNPRINTF_C99],
+[
+
+    AH_TEMPLATE([HAVE_VSNPRINTF_C99],
+                [Define if you have the C99 `vsnprintf' function.])
+
+    AC_CACHE_CHECK([whether vsnprintf has C99 semantics],
+                   [eso_cv_func_vsnprintf_c99],
+                   [
+                       AC_LANG_PUSH(C)
+
+                       eso_cppflags_save="$CPPFLAGS"
+                       eso_cflags_save="$CFLAGS"
+                       eso_ldflags_save="$LDFLAGS"
+                       eso_libs_save="$LIBS"
+
+                       if test x$GCC = xyes; then
+                           CFLAGS="$CFLAGS -pedantic-errors"
+                           CPPFLAGS="$CPPFLAGS $CFLAGS"
+                       fi
+
+                       AC_RUN_IFELSE(
+                       [
+AC_LANG_PROGRAM(
+[[
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+
+int
+doit(char * s, ...)
+{
+    char buffer[32];
+    va_list args;
+    int q, r;
+
+    va_start(args, s);
+    q = vsnprintf(NULL, 0, s, args);
+    r = vsnprintf(buffer, 5, s, args);
+    va_end(args);
+
+    if (q != 7 || r != 7)
+      exit(1);
+
+    exit(0);
+}
+]],
+[[
+    doit((char*)"1234567");
+    exit(1);
+]])
+                       ],
+                       [eso_cv_func_vsnprintf_c99=yes],
+                       [eso_cv_func_vsnprintf_c99=no],
+                       [eso_cv_func_vsnprintf_c99=no])
+
+                       CPPFLAGS="$eso_cppflags_save"
+                       CFLAGS="$eso_cflags_save"
+                       LDFLAGS="$eso_ldflags_save"
+                       LIBS="$eso_libs_save"
+
+                       AC_LANG_POP(C)
+                   ])
+
+# Note that the default is to be pessimistic in the case of cross compilation.
+# If you know that the target has a C99 vsnprintf(), you can get around this
+# by setting eso_func_vsnprintf_c99 to yes, as described in the Autoconf
+# manual.
+
+    if test x$eso_cv_func_vsnprintf_c99 = xyes; then
+        AC_DEFINE(HAVE_VSNPRINTF_C99)
+    fi
+
+])
+
+
+# ESO_CHECK_PRINTF_FORMATS
+#-------------------------
+# Checks for printf() format peculiarities.
+AC_DEFUN([ESO_CHECK_PRINTF_FORMATS],
+[
+
+    # Check if string format for NULL is `(null)'
+
+    AH_TEMPLATE([HAVE_PRINTF_STR_FMT_NULL],
+                [Define if printf outputs `(null)' when printing NULL using
+                 `%s'])
+
+    AC_RUN_IFELSE(
+    [
+AC_LANG_PROGRAM(
+[[
+#include <stdio.h>
+#include <string.h>
+]],
+[[
+    char s[128];
+
+    sprintf(s, "%s", NULL);
+    return strncmp(s, "(null)", 6) ? 1 : 0;
+]])
+    ],
+    [eso_have_printf_str_format_null=yes],
+    [eso_have_printf_str_format_null=no],
+    [eso_have_printf_str_format_null=no])
+
+    if test x$eso_have_printf_str_format_null = xyes; then
+        AC_DEFINE(HAVE_PRINTF_STR_FMT_NULL)
+    fi
+
+
+    # Check if pointer format for NULL is `(nil)'
+
+    AH_TEMPLATE([HAVE_PRINTF_PTR_FMT_NIL],
+                [Define if printf outputs `(nil)' when printing NULL using
+                 `%p'])
+
+    AC_RUN_IFELSE(
+    [
+AC_LANG_PROGRAM(
+[[
+#include <stdio.h>
+#include <string.h>
+]],
+[[
+    char s[128];
+
+    sprintf(s, "%p", NULL);
+    return strncmp(s, "(nil)", 5) ? 1 : 0;
+]])
+    ],
+    [eso_have_printf_ptr_format_nil=yes],
+    [eso_have_printf_ptr_format_nil=no],
+    [eso_have_printf_ptr_format_nil=no])
+
+    if test x$eso_have_printf_ptr_format_nil = xyes; then
+        AC_DEFINE(HAVE_PRINTF_PTR_FMT_NIL)
+    fi
+
+
+    # Check if output for `%p' is the same as `%#x'
+
+    AH_TEMPLATE([HAVE_PRINTF_PTR_FMT_ALTERNATE],
+                [Define if printf format `%p' produces the same output as
+                 `%#x' or `%#lx'])
+
+    AC_RUN_IFELSE(
+    [
+AC_LANG_PROGRAM(
+[[
+#include <stdio.h>
+#include <string.h>
+]],
+[[
+    char s1[128], s2[128];
+
+    sprintf(s1, "%p", s1);
+    sprintf(s2, "%#x", s1);
+    return strncmp(s1, s2, 3) ? 1 : 0;
+]])
+    ],
+    [eso_have_printf_ptr_format_alternate=yes],
+    [eso_have_printf_ptr_format_alternate=no],
+    [eso_have_printf_ptr_format_alternate=no])
+
+    if test x$eso_have_printf_ptr_format_alternate = xyes; then
+        AC_DEFINE(HAVE_PRINTF_PTR_FMT_ALTERNATE)
+    fi
+
+
+    # Check if pointers are treated as signed
+
+    AH_TEMPLATE([HAVE_PRINTF_PTR_FMT_SIGNED],
+                [Define if printf treats pointers as signed when using a sign
+                 flag])
+
+    AC_RUN_IFELSE(
+    [
+AC_LANG_PROGRAM(
+[[
+#include <stdio.h>
+]],
+[[
+    char s[128];
+
+    sprintf(s, "%+p", s);
+    return s[0] == '+' ? 0 : 1;
+]])
+    ],
+    [eso_have_printf_ptr_format_signed=yes],
+    [eso_have_printf_ptr_format_signed=no],
+    [eso_have_printf_ptr_format_signed=no])
+
+    if test x$eso_have_printf_ptr_format_signed = xyes; then
+        AC_DEFINE(HAVE_PRINTF_PTR_FMT_SIGNED)
+    fi
+
+
+    # Check if default precision for conversion specifier `g' is 1 (as
+    # required by ISO C) or 6.
+
+    AH_TEMPLATE([HAVE_PRINTF_FLT_FMT_G_STD],
+                [Define if printf default precision for format `g' is 1
+                 (ISO C standard) or 6])
+
+    AC_RUN_IFELSE(
+    [
+AC_LANG_PROGRAM(
+[[
+#include <stdio.h>
+]],
+[[
+    char s1[128], s2[128];
+    int n1, n2;
+
+    sprintf(s1, "%g%n", 1.123456, &n1);
+    sprintf(s2, "%.1g%n", 1.123456, &n2);
+    return n1 > n2 ? 1 : 0;
+]])
+    ],
+    [eso_have_printf_flt_format_g_std=yes],
+    [eso_have_printf_flt_format_g_std=no],
+    [eso_have_printf_flt_format_g_std=no])
+
+    if test x$eso_have_printf_flt_format_g_std = xyes; then
+        AC_DEFINE(HAVE_PRINTF_FLT_FMT_G_STD)
+    fi
+
+])
+
+
+# ESO_FUNC_VSNPRINTF
+#-------------------
+# Checks for vsnprintf and snprintf declaration and function.
+AC_DEFUN([ESO_FUNC_VSNPRINTF],
+[
+
+    eso_compile_snprintf=no
+
+    AH_TEMPLATE([HAVE_VSNPRINTF],
+                [Define if you have the `vsnprintf' function])
+    ESO_CHECK_FUNC(vsnprintf, [
+#include <stdio.h>
+#include <stdarg.h>
+                              ], HAVE_VSNPRINTF)
+
+    if test x$ac_cv_func_vsnprintf = xyes &&
+       test x$ac_cv_have_decl_vsnprintf = xyes; then
+
+        ESO_FUNC_VSNPRINTF_C99
+
+        if test x$eso_cv_func_vsnprintf_c99 != xyes; then
+            eso_compile_snprintf=yes
+        fi
+
+    else
+        eso_compile_snprintf=yes
+    fi
+
+    if test x$eso_compile_snprintf = xyes; then
+        if test -n "$LIBTOOL"; then
+            SNPRINTF=snprintf.lo
+        else
+            SNPRINTF=snprintf.$ac_objext
+        fi
+    fi
+
+    AC_SUBST(SNPRINTF)
+
+    # The symbols defined by the following macro are only needed to setup the
+    # vsnprintf() replacement. May be useless if the vsnprintf implementation
+    # changes.
+    ESO_CHECK_PRINTF_FORMATS
+
+    AH_TEMPLATE([HAVE_SNPRINTF],
+                [Define if you have the `snprintf' function])
+    ESO_CHECK_FUNC(snprintf, [#include <stdio.h>], HAVE_SNPRINTF)
+
+])
+
+
+# ESO_FUNC_VASPRINTF
+#-------------------
+# Checks for vasprintf and asprintf declaration and function.
+AC_DEFUN([ESO_FUNC_VASPRINTF],
+[
+
+    AH_TEMPLATE([HAVE_VASPRINTF],
+                [Define if you have the `vasprintf' function])
+    ESO_CHECK_FUNC(vasprintf, [
+#include <stdio.h>
+#include <stdarg.h>
+                              ], HAVE_VASPRINTF)
+
+    AH_TEMPLATE([HAVE_ASPRINTF],
+                [Define if you have the `asprintf' function])
+    ESO_CHECK_FUNC(asprintf, [
+#include <stdio.h>
+                             ], HAVE_ASPRINTF)
+
+])
+
+
+# ESO_FUNC_FPATHCONF
+#-------------------
+# Checks for fpathconf declaration and function.
+AC_DEFUN([ESO_FUNC_FPATHCONF],
+[
+
+    AH_TEMPLATE([HAVE_FPATHCONF],
+                [Define if you have the `fpathconf' function])
+    ESO_CHECK_FUNC(fpathconf, [#include <unistd.h>], HAVE_FPATHCONF)
+
+    # If we have fpathconf we should also have pathconf, but who knows.
+    AH_TEMPLATE([HAVE_PATHCONF],
+                [Define if you have the `pathconf' function])
+    ESO_CHECK_FUNC(pathconf, [#include <unistd.h>], HAVE_PATHCONF)
+
+])
+
+
+# ESO_FUNC_SYSCONF
+#-----------------
+# Checks for sysconf declaration and function.
+AC_DEFUN([ESO_FUNC_SYSCONF],
+[
+
+    AH_TEMPLATE([HAVE_SYSCONF],
+                [Define if you have the `sysconf' function])
+    ESO_CHECK_FUNC(sysconf, [#include <unistd.h>], HAVE_SYSCONF)
+
+])
+
+
+# ESO_FUNC_GETOPT
+#----------------
+# Checks for GNU getopt_long declaration and function.
+AC_DEFUN([ESO_FUNC_GETOPT],
+[
+
+    AH_TEMPLATE([HAVE_GETOPT_LONG],
+                [Define if you have the `getopt_long' function])
+
+    ESO_CHECK_FUNC(getopt_long, [#include <getopt.h>], HAVE_GETOPT_LONG)
+
+    if test x"$ac_cv_func_getopt_long" = xno ||
+       test x"$eso_cv_have_decl_getopt_long" = xno; then
+        if test -n "$LIBTOOL"; then
+            GETOPT="getopt.lo getopt1.lo"
+        else
+            GETOPT="getopt.$ac_objext getopt1.$ac_objext"
+        fi
+    fi
+
+    AC_SUBST(GETOPT)
+
+
+])
+
+
+# ESO_FUNC_GETPWUID
+#------------------
+# Checks for getpwuid declaration and function.
+AC_DEFUN([ESO_FUNC_GETPWUID],
+[
+
+    AH_TEMPLATE([HAVE_GETPWUID],
+                [Define if you have the `getpwuid' function])
+
+    ESO_CHECK_FUNC(getpwuid, [#include <pwd.h>], HAVE_GETPWUID)
+
+])
+
+
+# ESO_FUNC_GETUID
+#----------------
+AC_DEFUN([ESO_FUNC_GETUID],
+[
+
+    AH_TEMPLATE([HAVE_GETUID],
+                [Define if you have the `getuid' function])
+
+    ESO_CHECK_FUNC(getuid, [#include <unistd.h>], HAVE_GETUID)
+
+])
+
+
+# ESO_FUNC_LSTAT
+#---------------
+AC_DEFUN([ESO_FUNC_LSTAT],
+[
+
+    AH_TEMPLATE([HAVE_LSTAT],
+                [Define if you have the `lstat' function])
+
+    ESO_CHECK_FUNC(lstat, [#include <sys/stat.h>], HAVE_LSTAT)
+
+])
+
+
+# ESO_FUNC_STRDUP
+#----------------
+AC_DEFUN([ESO_FUNC_STRDUP],
+[
+
+    AH_TEMPLATE([HAVE_STRDUP],
+                [Define if you have the `strdup' function])
+
+    ESO_CHECK_FUNC(strdup, [#include <string.h>], HAVE_STRDUP)
+
+    AH_BOTTOM([
+#ifndef HAVE_STRDUP
+#  define strdup  cx_strdup
+#endif
+              ])
+])
+
+
+# ESO_FUNC_STPCPY
+#----------------
+AC_DEFUN([ESO_FUNC_STPCPY],
+[
+
+    AH_TEMPLATE([HAVE_STPCPY],
+                [Define if you have the `stpcpy' function])
+
+    ESO_CHECK_FUNC(stpcpy, [#include <stpcpy.h>], HAVE_STPCPY)
+
+])
+
+
+# ESO_FUNC_SYMLINK
+#-----------------
+AC_DEFUN([ESO_FUNC_SYMLINK],
+[
+
+    AH_TEMPLATE([HAVE_SYMLINK],
+                [Define if you have the `symlink' function])
+
+    ESO_CHECK_FUNC(symlink, [#include <unistd.h>], HAVE_SYMLINK)
+
+])
+
+
+# ESO_FUNC_WORDEXP
+#-----------------
+AC_DEFUN([ESO_FUNC_WORDEXP],
+[
+
+    AH_TEMPLATE([HAVE_WORDEXP],
+                [Define if you have the `wordexp' function])
+
+    ESO_CHECK_FUNC(wordexp, [#include <wordexp.h>], HAVE_WORDEXP)
+
+])
+
+
+# ESO_FUNC_GETTIMEOFDAY
+#----------------------
+AC_DEFUN([ESO_FUNC_GETTIMEOFDAY],
+[
+
+    AH_TEMPLATE([HAVE_GETTIMEOFDAY],
+                [Define if you have the `gettimeofday' function])
+
+    ESO_CHECK_FUNC(gettimeofday,
+                   [
+                       #include <unistd.h>
+                       #include <sys/time.h>
+                   ],
+                   HAVE_GETTIMEOFDAY)
+])
+
+
+# ESO_FUNC_VA_COPY(symbol)
+#-------------------------
+# Check for an implementation of va_copy(). The argument which must be
+# given is the preprocessor symbol that is defined to be either va_copy
+# or __va_copy depending on the available function, provided that an
+# implementation of va_copy is available at all.
+AC_DEFUN([ESO_FUNC_VA_COPY],
+[
+
+    # Check for all three va_copy possibilities, so we get
+    # all results in config.log for bug reports.
+
+    # Check for availability of va_copy(). This is ISO C. Available with
+    # gcc since version 3.0.
+    AC_CACHE_CHECK([for an implementation of va_copy()],
+                   [eso_cv_have_va_copy],
+                   [
+                       AC_RUN_IFELSE(
+                       [
+AC_LANG_PROGRAM(
+[[
+#ifdef HAVE_STDARG_H
+#include <stdarg.h>
+#endif
+
+void f(int i, ...)
+{
+  va_list args1, args2;
+  va_start (args1, i);
+  va_copy (args2, args1);
+   
+  if (va_arg (args2, int) != 42 || va_arg (args1, int) != 42)
+    exit (1);
+   
+  va_end (args1);
+  va_end (args2);
+}
+]],
+[[
+  f(0, 42);
+]])
+                       ],
+                       [eso_cv_have_va_copy=yes],
+                       [eso_cv_have_va_copy=no],
+                       [eso_cv_have_va_copy=no])
+                   ])
+
+
+    # Check for availability of __va_copy(). Some compilers provide
+    # this. Available with gcc since version 2.8.1.
+    AC_CACHE_CHECK([for an implementation of __va_copy()],
+                   [eso_cv_have__va_copy],
+                   [
+                       AC_RUN_IFELSE(
+                       [
+AC_LANG_PROGRAM(
+[[
+#ifdef HAVE_STDARG_H
+#include <stdarg.h>
+#endif
+
+void f(int i, ...)
+{
+  va_list args1, args2;
+
+  va_start (args1, i);
+  __va_copy (args2, args1);
+
+  if (va_arg (args2, int) != 42 || va_arg (args1, int) != 42)
+    exit (1);
+
+  va_end (args1);
+  va_end (args2);
+}
+]],
+[[
+  f(0, 42);
+]])
+                       ],
+                       [eso_cv_have__va_copy=yes],
+                       [eso_cv_have__va_copy=no],
+                       [eso_cv_have__va_copy=no])
+                   ])
+
+    AH_TEMPLATE([HAVE_VA_COPY],
+                [Define if you have an implementation of `va_copy()'.])
+    AH_TEMPLATE([HAVE___VA_COPY],
+                [Define if you have an implementation of `__va_copy()'.])
+
+    if test "x$eso_cv_have_va_copy" = "xyes"; then
+        eso_func_va_copy=va_copy
+        AC_DEFINE(HAVE_VA_COPY)
+    else
+        if test "x$eso_cv_have__va_copy" = "xyes"; then
+            eso_func_va_copy=__va_copy
+            AC_DEFINE(HAVE___VA_COPY)
+        fi
+    fi
+
+    AH_TEMPLATE([HAVE_VA_COPY_STYLE_FUNCTION],
+                [Define if you have an implementation of a `va_copy()' style
+                 function.])
+    AH_TEMPLATE([$1], [A `va_copy()' style function])
+
+    if test -n "$eso_func_va_copy"; then
+        AC_DEFINE_UNQUOTED([$1], $eso_func_va_copy)
+        AC_DEFINE(HAVE_VA_COPY_STYLE_FUNCTION)
+    fi
+
+    # Check whether va_lists can be copied by value
+    AC_CACHE_CHECK([whether va_lists can be copied by value],
+                   [eso_cv_have_va_value_copy],
+                   [
+                       AC_RUN_IFELSE(
+                       [
+AC_LANG_PROGRAM(
+[[                            
+#ifdef HAVE_STDARG_H
+#include <stdarg.h>
+#endif
+
+void f(int i, ...)
+{
+  va_list args1, args2;
+  va_start (args1, i);
+  args2 = args1;
+    
+  if (va_arg (args2, int) != 42 || va_arg (args1, int) != 42)
+    exit (1);
+    
+  va_end (args1);
+  va_end (args2);
+}
+]],
+[[
+  f(0, 42);
+]])
+                       ],
+                       [eso_cv_have_va_value_copy=yes],
+                       [eso_cv_have_va_value_copy=no],
+                       [eso_cv_have_va_value_copy=no])
+                   ])
+
+    AH_TEMPLATE([HAVE_VA_LIST_COPY_BY_VALUE],
+                [Define if `va_lists' can be copied by value])
+    if test "x$eso_cv_have_va_value_copy" = "xyes"; then
+        AC_DEFINE(HAVE_VA_LIST_COPY_BY_VALUE)
+    fi
+
+])
+
+
+# ESO_FUNC_REALLOC_SANITY
+#-------------------------
+# Check whether realloc(NULL,) works.
+AC_DEFUN([ESO_FUNC_REALLOC_SANITY],
+[
+    AC_CACHE_CHECK([whether realloc(NULL,) works],
+                   [eso_cv_have_sane_realloc],
+                   [
+                       AC_RUN_IFELSE(
+                       [
+AC_LANG_PROGRAM(
+[[
+#include <stdlib.h>
+]],
+[[
+  return realloc (0, sizeof (int)) == 0;
+]])
+                       ],
+                       [eso_cv_have_sane_realloc=yes],
+                       [eso_cv_have_sane_realloc=no],
+                       [eso_cv_have_sane_realloc=no])
+                   ])
+
+    AH_TEMPLATE([HAVE_WORKING_REALLOC],
+                [Define if realloc(NULL,) works])
+
+    if test x$eso_cv_have_sane_realloc = xyes; then
+        AC_DEFINE(HAVE_WORKING_REALLOC)
+    fi
+
+])
+
+
+# ESO_FIND_FILE(file, directories, variable)
+#------------------------------------------
+# Search for file in directories. Set variable to the first location
+# where file was found, if file is not found at all variable is set to NO.
+AC_DEFUN([ESO_FIND_FILE],
+[
+    $3=no
+
+    for i in $2; do
+        for j in $1; do
+
+            echo "configure: __oline__: $i/$j" >&AC_FD_CC
+
+            if test -r "$i/$j"; then
+                echo "taking that" >&AC_FD_CC
+                $3=$i
+                break 2
+            fi
+        done
+    done
+])
+
+
+# ESO_SET_LIBRARY_VERSION([CURRENT], [REVISION], [AGE])
+#------------------------------------------------------
+# Sets the libtool versioning symbols LT_CURRENT, LT_REVISION, LT_AGE.
+AC_DEFUN([ESO_SET_LIBRARY_VERSION],
+[
+
+    if test -z "$1"; then
+        LT_CURRENT=0
+    else
+        LT_CURRENT="$1"
+    fi
+
+    if test -z "$2"; then
+        LT_REVISION=0
+    else
+        LT_REVISION="$2"
+    fi
+
+    if test -z "$3"; then
+        LT_AGE=0
+    else
+        LT_AGE="$3"
+    fi
+
+    AC_SUBST(LT_CURRENT)
+    AC_SUBST(LT_REVISION)
+    AC_SUBST(LT_AGE)
+])
diff --git a/hdrl/m4macros/libtool.m4 b/hdrl/m4macros/libtool.m4
new file mode 100644
index 0000000..f12cfdf
--- /dev/null
+++ b/hdrl/m4macros/libtool.m4
@@ -0,0 +1,7992 @@
+# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*-
+#
+#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
+#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
+#                 Foundation, Inc.
+#   Written by Gordon Matzigkeit, 1996
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+m4_define([_LT_COPYING], [dnl
+#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
+#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
+#                 Foundation, Inc.
+#   Written by Gordon Matzigkeit, 1996
+#
+#   This file is part of GNU Libtool.
+#
+# GNU Libtool is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation; either version 2 of
+# the License, or (at your option) any later version.
+#
+# As a special exception to the GNU General Public License,
+# if you distribute this file as part of a program or library that
+# is built using GNU Libtool, you may include this file under the
+# same distribution terms that you use for the rest of that program.
+#
+# GNU Libtool is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GNU Libtool; see the file COPYING.  If not, a copy
+# can be downloaded from http://www.gnu.org/licenses/gpl.html, or
+# obtained by writing to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+])
+
+# serial 57 LT_INIT
+
+
+# LT_PREREQ(VERSION)
+# ------------------
+# Complain and exit if this libtool version is less that VERSION.
+m4_defun([LT_PREREQ],
+[m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1,
+       [m4_default([$3],
+		   [m4_fatal([Libtool version $1 or higher is required],
+		             63)])],
+       [$2])])
+
+
+# _LT_CHECK_BUILDDIR
+# ------------------
+# Complain if the absolute build directory name contains unusual characters
+m4_defun([_LT_CHECK_BUILDDIR],
+[case `pwd` in
+  *\ * | *\	*)
+    AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;;
+esac
+])
+
+
+# LT_INIT([OPTIONS])
+# ------------------
+AC_DEFUN([LT_INIT],
+[AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT
+AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl
+AC_BEFORE([$0], [LT_LANG])dnl
+AC_BEFORE([$0], [LT_OUTPUT])dnl
+AC_BEFORE([$0], [LTDL_INIT])dnl
+m4_require([_LT_CHECK_BUILDDIR])dnl
+
+dnl Autoconf doesn't catch unexpanded LT_ macros by default:
+m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl
+m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl
+dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4
+dnl unless we require an AC_DEFUNed macro:
+AC_REQUIRE([LTOPTIONS_VERSION])dnl
+AC_REQUIRE([LTSUGAR_VERSION])dnl
+AC_REQUIRE([LTVERSION_VERSION])dnl
+AC_REQUIRE([LTOBSOLETE_VERSION])dnl
+m4_require([_LT_PROG_LTMAIN])dnl
+
+_LT_SHELL_INIT([SHELL=${CONFIG_SHELL-/bin/sh}])
+
+dnl Parse OPTIONS
+_LT_SET_OPTIONS([$0], [$1])
+
+# This can be used to rebuild libtool when needed
+LIBTOOL_DEPS="$ltmain"
+
+# Always use our own libtool.
+LIBTOOL='$(SHELL) $(top_builddir)/libtool'
+AC_SUBST(LIBTOOL)dnl
+
+_LT_SETUP
+
+# Only expand once:
+m4_define([LT_INIT])
+])# LT_INIT
+
+# Old names:
+AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT])
+AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_PROG_LIBTOOL], [])
+dnl AC_DEFUN([AM_PROG_LIBTOOL], [])
+
+
+# _LT_CC_BASENAME(CC)
+# -------------------
+# Calculate cc_basename.  Skip known compiler wrappers and cross-prefix.
+m4_defun([_LT_CC_BASENAME],
+[for cc_temp in $1""; do
+  case $cc_temp in
+    compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;;
+    distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;;
+    \-*) ;;
+    *) break;;
+  esac
+done
+cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
+])
+
+
+# _LT_FILEUTILS_DEFAULTS
+# ----------------------
+# It is okay to use these file commands and assume they have been set
+# sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'.
+m4_defun([_LT_FILEUTILS_DEFAULTS],
+[: ${CP="cp -f"}
+: ${MV="mv -f"}
+: ${RM="rm -f"}
+])# _LT_FILEUTILS_DEFAULTS
+
+
+# _LT_SETUP
+# ---------
+m4_defun([_LT_SETUP],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+AC_REQUIRE([_LT_PREPARE_SED_QUOTE_VARS])dnl
+AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl
+
+_LT_DECL([], [PATH_SEPARATOR], [1], [The PATH separator for the build system])dnl
+dnl
+_LT_DECL([], [host_alias], [0], [The host system])dnl
+_LT_DECL([], [host], [0])dnl
+_LT_DECL([], [host_os], [0])dnl
+dnl
+_LT_DECL([], [build_alias], [0], [The build system])dnl
+_LT_DECL([], [build], [0])dnl
+_LT_DECL([], [build_os], [0])dnl
+dnl
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([LT_PATH_LD])dnl
+AC_REQUIRE([LT_PATH_NM])dnl
+dnl
+AC_REQUIRE([AC_PROG_LN_S])dnl
+test -z "$LN_S" && LN_S="ln -s"
+_LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl
+dnl
+AC_REQUIRE([LT_CMD_MAX_LEN])dnl
+_LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl
+_LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl
+dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_CHECK_SHELL_FEATURES])dnl
+m4_require([_LT_PATH_CONVERSION_FUNCTIONS])dnl
+m4_require([_LT_CMD_RELOAD])dnl
+m4_require([_LT_CHECK_MAGIC_METHOD])dnl
+m4_require([_LT_CHECK_SHAREDLIB_FROM_LINKLIB])dnl
+m4_require([_LT_CMD_OLD_ARCHIVE])dnl
+m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
+m4_require([_LT_WITH_SYSROOT])dnl
+
+_LT_CONFIG_LIBTOOL_INIT([
+# See if we are running on zsh, and set the options which allow our
+# commands through without removal of \ escapes INIT.
+if test -n "\${ZSH_VERSION+set}" ; then
+   setopt NO_GLOB_SUBST
+fi
+])
+if test -n "${ZSH_VERSION+set}" ; then
+   setopt NO_GLOB_SUBST
+fi
+
+_LT_CHECK_OBJDIR
+
+m4_require([_LT_TAG_COMPILER])dnl
+
+case $host_os in
+aix3*)
+  # AIX sometimes has problems with the GCC collect2 program.  For some
+  # reason, if we set the COLLECT_NAMES environment variable, the problems
+  # vanish in a puff of smoke.
+  if test "X${COLLECT_NAMES+set}" != Xset; then
+    COLLECT_NAMES=
+    export COLLECT_NAMES
+  fi
+  ;;
+esac
+
+# Global variables:
+ofile=libtool
+can_build_shared=yes
+
+# All known linkers require a `.a' archive for static linking (except MSVC,
+# which needs '.lib').
+libext=a
+
+with_gnu_ld="$lt_cv_prog_gnu_ld"
+
+old_CC="$CC"
+old_CFLAGS="$CFLAGS"
+
+# Set sane defaults for various variables
+test -z "$CC" && CC=cc
+test -z "$LTCC" && LTCC=$CC
+test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
+test -z "$LD" && LD=ld
+test -z "$ac_objext" && ac_objext=o
+
+_LT_CC_BASENAME([$compiler])
+
+# Only perform the check for file, if the check method requires it
+test -z "$MAGIC_CMD" && MAGIC_CMD=file
+case $deplibs_check_method in
+file_magic*)
+  if test "$file_magic_cmd" = '$MAGIC_CMD'; then
+    _LT_PATH_MAGIC
+  fi
+  ;;
+esac
+
+# Use C for the default configuration in the libtool script
+LT_SUPPORTED_TAG([CC])
+_LT_LANG_C_CONFIG
+_LT_LANG_DEFAULT_CONFIG
+_LT_CONFIG_COMMANDS
+])# _LT_SETUP
+
+
+# _LT_PREPARE_SED_QUOTE_VARS
+# --------------------------
+# Define a few sed substitution that help us do robust quoting.
+m4_defun([_LT_PREPARE_SED_QUOTE_VARS],
+[# Backslashify metacharacters that are still active within
+# double-quoted strings.
+sed_quote_subst='s/\([["`$\\]]\)/\\\1/g'
+
+# Same as above, but do not quote variable references.
+double_quote_subst='s/\([["`\\]]\)/\\\1/g'
+
+# Sed substitution to delay expansion of an escaped shell variable in a
+# double_quote_subst'ed string.
+delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
+
+# Sed substitution to delay expansion of an escaped single quote.
+delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g'
+
+# Sed substitution to avoid accidental globbing in evaled expressions
+no_glob_subst='s/\*/\\\*/g'
+])
+
+# _LT_PROG_LTMAIN
+# ---------------
+# Note that this code is called both from `configure', and `config.status'
+# now that we use AC_CONFIG_COMMANDS to generate libtool.  Notably,
+# `config.status' has no value for ac_aux_dir unless we are using Automake,
+# so we pass a copy along to make sure it has a sensible value anyway.
+m4_defun([_LT_PROG_LTMAIN],
+[m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl
+_LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir'])
+ltmain="$ac_aux_dir/ltmain.sh"
+])# _LT_PROG_LTMAIN
+
+
+## ------------------------------------- ##
+## Accumulate code for creating libtool. ##
+## ------------------------------------- ##
+
+# So that we can recreate a full libtool script including additional
+# tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS
+# in macros and then make a single call at the end using the `libtool'
+# label.
+
+
+# _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS])
+# ----------------------------------------
+# Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later.
+m4_define([_LT_CONFIG_LIBTOOL_INIT],
+[m4_ifval([$1],
+          [m4_append([_LT_OUTPUT_LIBTOOL_INIT],
+                     [$1
+])])])
+
+# Initialize.
+m4_define([_LT_OUTPUT_LIBTOOL_INIT])
+
+
+# _LT_CONFIG_LIBTOOL([COMMANDS])
+# ------------------------------
+# Register COMMANDS to be passed to AC_CONFIG_COMMANDS later.
+m4_define([_LT_CONFIG_LIBTOOL],
+[m4_ifval([$1],
+          [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS],
+                     [$1
+])])])
+
+# Initialize.
+m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS])
+
+
+# _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS])
+# -----------------------------------------------------
+m4_defun([_LT_CONFIG_SAVE_COMMANDS],
+[_LT_CONFIG_LIBTOOL([$1])
+_LT_CONFIG_LIBTOOL_INIT([$2])
+])
+
+
+# _LT_FORMAT_COMMENT([COMMENT])
+# -----------------------------
+# Add leading comment marks to the start of each line, and a trailing
+# full-stop to the whole comment if one is not present already.
+m4_define([_LT_FORMAT_COMMENT],
+[m4_ifval([$1], [
+m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])],
+              [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.])
+)])
+
+
+
+## ------------------------ ##
+## FIXME: Eliminate VARNAME ##
+## ------------------------ ##
+
+
+# _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?])
+# -------------------------------------------------------------------
+# CONFIGNAME is the name given to the value in the libtool script.
+# VARNAME is the (base) name used in the configure script.
+# VALUE may be 0, 1 or 2 for a computed quote escaped value based on
+# VARNAME.  Any other value will be used directly.
+m4_define([_LT_DECL],
+[lt_if_append_uniq([lt_decl_varnames], [$2], [, ],
+    [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name],
+	[m4_ifval([$1], [$1], [$2])])
+    lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3])
+    m4_ifval([$4],
+	[lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])])
+    lt_dict_add_subkey([lt_decl_dict], [$2],
+	[tagged?], [m4_ifval([$5], [yes], [no])])])
+])
+
+
+# _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION])
+# --------------------------------------------------------
+m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])])
+
+
+# lt_decl_tag_varnames([SEPARATOR], [VARNAME1...])
+# ------------------------------------------------
+m4_define([lt_decl_tag_varnames],
+[_lt_decl_filter([tagged?], [yes], $@)])
+
+
+# _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..])
+# ---------------------------------------------------------
+m4_define([_lt_decl_filter],
+[m4_case([$#],
+  [0], [m4_fatal([$0: too few arguments: $#])],
+  [1], [m4_fatal([$0: too few arguments: $#: $1])],
+  [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)],
+  [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)],
+  [lt_dict_filter([lt_decl_dict], $@)])[]dnl
+])
+
+
+# lt_decl_quote_varnames([SEPARATOR], [VARNAME1...])
+# --------------------------------------------------
+m4_define([lt_decl_quote_varnames],
+[_lt_decl_filter([value], [1], $@)])
+
+
+# lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...])
+# ---------------------------------------------------
+m4_define([lt_decl_dquote_varnames],
+[_lt_decl_filter([value], [2], $@)])
+
+
+# lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...])
+# ---------------------------------------------------
+m4_define([lt_decl_varnames_tagged],
+[m4_assert([$# <= 2])dnl
+_$0(m4_quote(m4_default([$1], [[, ]])),
+    m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]),
+    m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))])
+m4_define([_lt_decl_varnames_tagged],
+[m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])])
+
+
+# lt_decl_all_varnames([SEPARATOR], [VARNAME1...])
+# ------------------------------------------------
+m4_define([lt_decl_all_varnames],
+[_$0(m4_quote(m4_default([$1], [[, ]])),
+     m4_if([$2], [],
+	   m4_quote(lt_decl_varnames),
+	m4_quote(m4_shift($@))))[]dnl
+])
+m4_define([_lt_decl_all_varnames],
+[lt_join($@, lt_decl_varnames_tagged([$1],
+			lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl
+])
+
+
+# _LT_CONFIG_STATUS_DECLARE([VARNAME])
+# ------------------------------------
+# Quote a variable value, and forward it to `config.status' so that its
+# declaration there will have the same value as in `configure'.  VARNAME
+# must have a single quote delimited value for this to work.
+m4_define([_LT_CONFIG_STATUS_DECLARE],
+[$1='`$ECHO "$][$1" | $SED "$delay_single_quote_subst"`'])
+
+
+# _LT_CONFIG_STATUS_DECLARATIONS
+# ------------------------------
+# We delimit libtool config variables with single quotes, so when
+# we write them to config.status, we have to be sure to quote all
+# embedded single quotes properly.  In configure, this macro expands
+# each variable declared with _LT_DECL (and _LT_TAGDECL) into:
+#
+#    <var>='`$ECHO "$<var>" | $SED "$delay_single_quote_subst"`'
+m4_defun([_LT_CONFIG_STATUS_DECLARATIONS],
+[m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames),
+    [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])])
+
+
+# _LT_LIBTOOL_TAGS
+# ----------------
+# Output comment and list of tags supported by the script
+m4_defun([_LT_LIBTOOL_TAGS],
+[_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl
+available_tags="_LT_TAGS"dnl
+])
+
+
+# _LT_LIBTOOL_DECLARE(VARNAME, [TAG])
+# -----------------------------------
+# Extract the dictionary values for VARNAME (optionally with TAG) and
+# expand to a commented shell variable setting:
+#
+#    # Some comment about what VAR is for.
+#    visible_name=$lt_internal_name
+m4_define([_LT_LIBTOOL_DECLARE],
+[_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1],
+					   [description])))[]dnl
+m4_pushdef([_libtool_name],
+    m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl
+m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])),
+    [0], [_libtool_name=[$]$1],
+    [1], [_libtool_name=$lt_[]$1],
+    [2], [_libtool_name=$lt_[]$1],
+    [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl
+m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl
+])
+
+
+# _LT_LIBTOOL_CONFIG_VARS
+# -----------------------
+# Produce commented declarations of non-tagged libtool config variables
+# suitable for insertion in the LIBTOOL CONFIG section of the `libtool'
+# script.  Tagged libtool config variables (even for the LIBTOOL CONFIG
+# section) are produced by _LT_LIBTOOL_TAG_VARS.
+m4_defun([_LT_LIBTOOL_CONFIG_VARS],
+[m4_foreach([_lt_var],
+    m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)),
+    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])])
+
+
+# _LT_LIBTOOL_TAG_VARS(TAG)
+# -------------------------
+m4_define([_LT_LIBTOOL_TAG_VARS],
+[m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames),
+    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])])
+
+
+# _LT_TAGVAR(VARNAME, [TAGNAME])
+# ------------------------------
+m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])])
+
+
+# _LT_CONFIG_COMMANDS
+# -------------------
+# Send accumulated output to $CONFIG_STATUS.  Thanks to the lists of
+# variables for single and double quote escaping we saved from calls
+# to _LT_DECL, we can put quote escaped variables declarations
+# into `config.status', and then the shell code to quote escape them in
+# for loops in `config.status'.  Finally, any additional code accumulated
+# from calls to _LT_CONFIG_LIBTOOL_INIT is expanded.
+m4_defun([_LT_CONFIG_COMMANDS],
+[AC_PROVIDE_IFELSE([LT_OUTPUT],
+	dnl If the libtool generation code has been placed in $CONFIG_LT,
+	dnl instead of duplicating it all over again into config.status,
+	dnl then we will have config.status run $CONFIG_LT later, so it
+	dnl needs to know what name is stored there:
+        [AC_CONFIG_COMMANDS([libtool],
+            [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])],
+    dnl If the libtool generation code is destined for config.status,
+    dnl expand the accumulated commands and init code now:
+    [AC_CONFIG_COMMANDS([libtool],
+        [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])])
+])#_LT_CONFIG_COMMANDS
+
+
+# Initialize.
+m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT],
+[
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+sed_quote_subst='$sed_quote_subst'
+double_quote_subst='$double_quote_subst'
+delay_variable_subst='$delay_variable_subst'
+_LT_CONFIG_STATUS_DECLARATIONS
+LTCC='$LTCC'
+LTCFLAGS='$LTCFLAGS'
+compiler='$compiler_DEFAULT'
+
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+\$[]1
+_LTECHO_EOF'
+}
+
+# Quote evaled strings.
+for var in lt_decl_all_varnames([[ \
+]], lt_decl_quote_varnames); do
+    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
+    *[[\\\\\\\`\\"\\\$]]*)
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\""
+      ;;
+    *)
+      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
+      ;;
+    esac
+done
+
+# Double-quote double-evaled strings.
+for var in lt_decl_all_varnames([[ \
+]], lt_decl_dquote_varnames); do
+    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
+    *[[\\\\\\\`\\"\\\$]]*)
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\""
+      ;;
+    *)
+      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
+      ;;
+    esac
+done
+
+_LT_OUTPUT_LIBTOOL_INIT
+])
+
+# _LT_GENERATED_FILE_INIT(FILE, [COMMENT])
+# ------------------------------------
+# Generate a child script FILE with all initialization necessary to
+# reuse the environment learned by the parent script, and make the
+# file executable.  If COMMENT is supplied, it is inserted after the
+# `#!' sequence but before initialization text begins.  After this
+# macro, additional text can be appended to FILE to form the body of
+# the child script.  The macro ends with non-zero status if the
+# file could not be fully written (such as if the disk is full).
+m4_ifdef([AS_INIT_GENERATED],
+[m4_defun([_LT_GENERATED_FILE_INIT],[AS_INIT_GENERATED($@)])],
+[m4_defun([_LT_GENERATED_FILE_INIT],
+[m4_require([AS_PREPARE])]dnl
+[m4_pushdef([AS_MESSAGE_LOG_FD])]dnl
+[lt_write_fail=0
+cat >$1 <<_ASEOF || lt_write_fail=1
+#! $SHELL
+# Generated by $as_me.
+$2
+SHELL=\${CONFIG_SHELL-$SHELL}
+export SHELL
+_ASEOF
+cat >>$1 <<\_ASEOF || lt_write_fail=1
+AS_SHELL_SANITIZE
+_AS_PREPARE
+exec AS_MESSAGE_FD>&1
+_ASEOF
+test $lt_write_fail = 0 && chmod +x $1[]dnl
+m4_popdef([AS_MESSAGE_LOG_FD])])])# _LT_GENERATED_FILE_INIT
+
+# LT_OUTPUT
+# ---------
+# This macro allows early generation of the libtool script (before
+# AC_OUTPUT is called), incase it is used in configure for compilation
+# tests.
+AC_DEFUN([LT_OUTPUT],
+[: ${CONFIG_LT=./config.lt}
+AC_MSG_NOTICE([creating $CONFIG_LT])
+_LT_GENERATED_FILE_INIT(["$CONFIG_LT"],
+[# Run this file to recreate a libtool stub with the current configuration.])
+
+cat >>"$CONFIG_LT" <<\_LTEOF
+lt_cl_silent=false
+exec AS_MESSAGE_LOG_FD>>config.log
+{
+  echo
+  AS_BOX([Running $as_me.])
+} >&AS_MESSAGE_LOG_FD
+
+lt_cl_help="\
+\`$as_me' creates a local libtool stub from the current configuration,
+for use in further configure time tests before the real libtool is
+generated.
+
+Usage: $[0] [[OPTIONS]]
+
+  -h, --help      print this help, then exit
+  -V, --version   print version number, then exit
+  -q, --quiet     do not print progress messages
+  -d, --debug     don't remove temporary files
+
+Report bugs to <bug-libtool at gnu.org>."
+
+lt_cl_version="\
+m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl
+m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION])
+configured by $[0], generated by m4_PACKAGE_STRING.
+
+Copyright (C) 2011 Free Software Foundation, Inc.
+This config.lt script is free software; the Free Software Foundation
+gives unlimited permision to copy, distribute and modify it."
+
+while test $[#] != 0
+do
+  case $[1] in
+    --version | --v* | -V )
+      echo "$lt_cl_version"; exit 0 ;;
+    --help | --h* | -h )
+      echo "$lt_cl_help"; exit 0 ;;
+    --debug | --d* | -d )
+      debug=: ;;
+    --quiet | --q* | --silent | --s* | -q )
+      lt_cl_silent=: ;;
+
+    -*) AC_MSG_ERROR([unrecognized option: $[1]
+Try \`$[0] --help' for more information.]) ;;
+
+    *) AC_MSG_ERROR([unrecognized argument: $[1]
+Try \`$[0] --help' for more information.]) ;;
+  esac
+  shift
+done
+
+if $lt_cl_silent; then
+  exec AS_MESSAGE_FD>/dev/null
+fi
+_LTEOF
+
+cat >>"$CONFIG_LT" <<_LTEOF
+_LT_OUTPUT_LIBTOOL_COMMANDS_INIT
+_LTEOF
+
+cat >>"$CONFIG_LT" <<\_LTEOF
+AC_MSG_NOTICE([creating $ofile])
+_LT_OUTPUT_LIBTOOL_COMMANDS
+AS_EXIT(0)
+_LTEOF
+chmod +x "$CONFIG_LT"
+
+# configure is writing to config.log, but config.lt does its own redirection,
+# appending to config.log, which fails on DOS, as config.log is still kept
+# open by configure.  Here we exec the FD to /dev/null, effectively closing
+# config.log, so it can be properly (re)opened and appended to by config.lt.
+lt_cl_success=:
+test "$silent" = yes &&
+  lt_config_lt_args="$lt_config_lt_args --quiet"
+exec AS_MESSAGE_LOG_FD>/dev/null
+$SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false
+exec AS_MESSAGE_LOG_FD>>config.log
+$lt_cl_success || AS_EXIT(1)
+])# LT_OUTPUT
+
+
+# _LT_CONFIG(TAG)
+# ---------------
+# If TAG is the built-in tag, create an initial libtool script with a
+# default configuration from the untagged config vars.  Otherwise add code
+# to config.status for appending the configuration named by TAG from the
+# matching tagged config vars.
+m4_defun([_LT_CONFIG],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+_LT_CONFIG_SAVE_COMMANDS([
+  m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl
+  m4_if(_LT_TAG, [C], [
+    # See if we are running on zsh, and set the options which allow our
+    # commands through without removal of \ escapes.
+    if test -n "${ZSH_VERSION+set}" ; then
+      setopt NO_GLOB_SUBST
+    fi
+
+    cfgfile="${ofile}T"
+    trap "$RM \"$cfgfile\"; exit 1" 1 2 15
+    $RM "$cfgfile"
+
+    cat <<_LT_EOF >> "$cfgfile"
+#! $SHELL
+
+# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
+# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+# NOTE: Changes made to this file will be lost: look at ltmain.sh.
+#
+_LT_COPYING
+_LT_LIBTOOL_TAGS
+
+# ### BEGIN LIBTOOL CONFIG
+_LT_LIBTOOL_CONFIG_VARS
+_LT_LIBTOOL_TAG_VARS
+# ### END LIBTOOL CONFIG
+
+_LT_EOF
+
+  case $host_os in
+  aix3*)
+    cat <<\_LT_EOF >> "$cfgfile"
+# AIX sometimes has problems with the GCC collect2 program.  For some
+# reason, if we set the COLLECT_NAMES environment variable, the problems
+# vanish in a puff of smoke.
+if test "X${COLLECT_NAMES+set}" != Xset; then
+  COLLECT_NAMES=
+  export COLLECT_NAMES
+fi
+_LT_EOF
+    ;;
+  esac
+
+  _LT_PROG_LTMAIN
+
+  # We use sed instead of cat because bash on DJGPP gets confused if
+  # if finds mixed CR/LF and LF-only lines.  Since sed operates in
+  # text mode, it properly converts lines to CR/LF.  This bash problem
+  # is reportedly fixed, but why not run on old versions too?
+  sed '$q' "$ltmain" >> "$cfgfile" \
+     || (rm -f "$cfgfile"; exit 1)
+
+  _LT_PROG_REPLACE_SHELLFNS
+
+   mv -f "$cfgfile" "$ofile" ||
+    (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
+  chmod +x "$ofile"
+],
+[cat <<_LT_EOF >> "$ofile"
+
+dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded
+dnl in a comment (ie after a #).
+# ### BEGIN LIBTOOL TAG CONFIG: $1
+_LT_LIBTOOL_TAG_VARS(_LT_TAG)
+# ### END LIBTOOL TAG CONFIG: $1
+_LT_EOF
+])dnl /m4_if
+],
+[m4_if([$1], [], [
+    PACKAGE='$PACKAGE'
+    VERSION='$VERSION'
+    TIMESTAMP='$TIMESTAMP'
+    RM='$RM'
+    ofile='$ofile'], [])
+])dnl /_LT_CONFIG_SAVE_COMMANDS
+])# _LT_CONFIG
+
+
+# LT_SUPPORTED_TAG(TAG)
+# ---------------------
+# Trace this macro to discover what tags are supported by the libtool
+# --tag option, using:
+#    autoconf --trace 'LT_SUPPORTED_TAG:$1'
+AC_DEFUN([LT_SUPPORTED_TAG], [])
+
+
+# C support is built-in for now
+m4_define([_LT_LANG_C_enabled], [])
+m4_define([_LT_TAGS], [])
+
+
+# LT_LANG(LANG)
+# -------------
+# Enable libtool support for the given language if not already enabled.
+AC_DEFUN([LT_LANG],
+[AC_BEFORE([$0], [LT_OUTPUT])dnl
+m4_case([$1],
+  [C],			[_LT_LANG(C)],
+  [C++],		[_LT_LANG(CXX)],
+  [Go],			[_LT_LANG(GO)],
+  [Java],		[_LT_LANG(GCJ)],
+  [Fortran 77],		[_LT_LANG(F77)],
+  [Fortran],		[_LT_LANG(FC)],
+  [Windows Resource],	[_LT_LANG(RC)],
+  [m4_ifdef([_LT_LANG_]$1[_CONFIG],
+    [_LT_LANG($1)],
+    [m4_fatal([$0: unsupported language: "$1"])])])dnl
+])# LT_LANG
+
+
+# _LT_LANG(LANGNAME)
+# ------------------
+m4_defun([_LT_LANG],
+[m4_ifdef([_LT_LANG_]$1[_enabled], [],
+  [LT_SUPPORTED_TAG([$1])dnl
+  m4_append([_LT_TAGS], [$1 ])dnl
+  m4_define([_LT_LANG_]$1[_enabled], [])dnl
+  _LT_LANG_$1_CONFIG($1)])dnl
+])# _LT_LANG
+
+
+m4_ifndef([AC_PROG_GO], [
+############################################################
+# NOTE: This macro has been submitted for inclusion into   #
+#  GNU Autoconf as AC_PROG_GO.  When it is available in    #
+#  a released version of Autoconf we should remove this    #
+#  macro and use it instead.                               #
+############################################################
+m4_defun([AC_PROG_GO],
+[AC_LANG_PUSH(Go)dnl
+AC_ARG_VAR([GOC],     [Go compiler command])dnl
+AC_ARG_VAR([GOFLAGS], [Go compiler flags])dnl
+_AC_ARG_VAR_LDFLAGS()dnl
+AC_CHECK_TOOL(GOC, gccgo)
+if test -z "$GOC"; then
+  if test -n "$ac_tool_prefix"; then
+    AC_CHECK_PROG(GOC, [${ac_tool_prefix}gccgo], [${ac_tool_prefix}gccgo])
+  fi
+fi
+if test -z "$GOC"; then
+  AC_CHECK_PROG(GOC, gccgo, gccgo, false)
+fi
+])#m4_defun
+])#m4_ifndef
+
+
+# _LT_LANG_DEFAULT_CONFIG
+# -----------------------
+m4_defun([_LT_LANG_DEFAULT_CONFIG],
+[AC_PROVIDE_IFELSE([AC_PROG_CXX],
+  [LT_LANG(CXX)],
+  [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])])
+
+AC_PROVIDE_IFELSE([AC_PROG_F77],
+  [LT_LANG(F77)],
+  [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])])
+
+AC_PROVIDE_IFELSE([AC_PROG_FC],
+  [LT_LANG(FC)],
+  [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])])
+
+dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal
+dnl pulling things in needlessly.
+AC_PROVIDE_IFELSE([AC_PROG_GCJ],
+  [LT_LANG(GCJ)],
+  [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],
+    [LT_LANG(GCJ)],
+    [AC_PROVIDE_IFELSE([LT_PROG_GCJ],
+      [LT_LANG(GCJ)],
+      [m4_ifdef([AC_PROG_GCJ],
+	[m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])])
+       m4_ifdef([A][M_PROG_GCJ],
+	[m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])])
+       m4_ifdef([LT_PROG_GCJ],
+	[m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])])
+
+AC_PROVIDE_IFELSE([AC_PROG_GO],
+  [LT_LANG(GO)],
+  [m4_define([AC_PROG_GO], defn([AC_PROG_GO])[LT_LANG(GO)])])
+
+AC_PROVIDE_IFELSE([LT_PROG_RC],
+  [LT_LANG(RC)],
+  [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])])
+])# _LT_LANG_DEFAULT_CONFIG
+
+# Obsolete macros:
+AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)])
+AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)])
+AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)])
+AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)])
+AU_DEFUN([AC_LIBTOOL_RC], [LT_LANG(Windows Resource)])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_CXX], [])
+dnl AC_DEFUN([AC_LIBTOOL_F77], [])
+dnl AC_DEFUN([AC_LIBTOOL_FC], [])
+dnl AC_DEFUN([AC_LIBTOOL_GCJ], [])
+dnl AC_DEFUN([AC_LIBTOOL_RC], [])
+
+
+# _LT_TAG_COMPILER
+# ----------------
+m4_defun([_LT_TAG_COMPILER],
+[AC_REQUIRE([AC_PROG_CC])dnl
+
+_LT_DECL([LTCC], [CC], [1], [A C compiler])dnl
+_LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl
+_LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl
+_LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+])# _LT_TAG_COMPILER
+
+
+# _LT_COMPILER_BOILERPLATE
+# ------------------------
+# Check for compiler boilerplate output or warnings with
+# the simple compiler test code.
+m4_defun([_LT_COMPILER_BOILERPLATE],
+[m4_require([_LT_DECL_SED])dnl
+ac_outfile=conftest.$ac_objext
+echo "$lt_simple_compile_test_code" >conftest.$ac_ext
+eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_compiler_boilerplate=`cat conftest.err`
+$RM conftest*
+])# _LT_COMPILER_BOILERPLATE
+
+
+# _LT_LINKER_BOILERPLATE
+# ----------------------
+# Check for linker boilerplate output or warnings with
+# the simple link test code.
+m4_defun([_LT_LINKER_BOILERPLATE],
+[m4_require([_LT_DECL_SED])dnl
+ac_outfile=conftest.$ac_objext
+echo "$lt_simple_link_test_code" >conftest.$ac_ext
+eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_linker_boilerplate=`cat conftest.err`
+$RM -r conftest*
+])# _LT_LINKER_BOILERPLATE
+
+# _LT_REQUIRED_DARWIN_CHECKS
+# -------------------------
+m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[
+  case $host_os in
+    rhapsody* | darwin*)
+    AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:])
+    AC_CHECK_TOOL([NMEDIT], [nmedit], [:])
+    AC_CHECK_TOOL([LIPO], [lipo], [:])
+    AC_CHECK_TOOL([OTOOL], [otool], [:])
+    AC_CHECK_TOOL([OTOOL64], [otool64], [:])
+    _LT_DECL([], [DSYMUTIL], [1],
+      [Tool to manipulate archived DWARF debug symbol files on Mac OS X])
+    _LT_DECL([], [NMEDIT], [1],
+      [Tool to change global to local symbols on Mac OS X])
+    _LT_DECL([], [LIPO], [1],
+      [Tool to manipulate fat objects and archives on Mac OS X])
+    _LT_DECL([], [OTOOL], [1],
+      [ldd/readelf like tool for Mach-O binaries on Mac OS X])
+    _LT_DECL([], [OTOOL64], [1],
+      [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4])
+
+    AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod],
+      [lt_cv_apple_cc_single_mod=no
+      if test -z "${LT_MULTI_MODULE}"; then
+	# By default we will add the -single_module flag. You can override
+	# by either setting the environment variable LT_MULTI_MODULE
+	# non-empty at configure time, or by adding -multi_module to the
+	# link flags.
+	rm -rf libconftest.dylib*
+	echo "int foo(void){return 1;}" > conftest.c
+	echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
+-dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD
+	$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
+	  -dynamiclib -Wl,-single_module conftest.c 2>conftest.err
+        _lt_result=$?
+	# If there is a non-empty error log, and "single_module"
+	# appears in it, assume the flag caused a linker warning
+        if test -s conftest.err && $GREP single_module conftest.err; then
+	  cat conftest.err >&AS_MESSAGE_LOG_FD
+	# Otherwise, if the output was created with a 0 exit code from
+	# the compiler, it worked.
+	elif test -f libconftest.dylib && test $_lt_result -eq 0; then
+	  lt_cv_apple_cc_single_mod=yes
+	else
+	  cat conftest.err >&AS_MESSAGE_LOG_FD
+	fi
+	rm -rf libconftest.dylib*
+	rm -f conftest.*
+      fi])
+
+    AC_CACHE_CHECK([for -exported_symbols_list linker flag],
+      [lt_cv_ld_exported_symbols_list],
+      [lt_cv_ld_exported_symbols_list=no
+      save_LDFLAGS=$LDFLAGS
+      echo "_main" > conftest.sym
+      LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym"
+      AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
+	[lt_cv_ld_exported_symbols_list=yes],
+	[lt_cv_ld_exported_symbols_list=no])
+	LDFLAGS="$save_LDFLAGS"
+    ])
+
+    AC_CACHE_CHECK([for -force_load linker flag],[lt_cv_ld_force_load],
+      [lt_cv_ld_force_load=no
+      cat > conftest.c << _LT_EOF
+int forced_loaded() { return 2;}
+_LT_EOF
+      echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&AS_MESSAGE_LOG_FD
+      $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&AS_MESSAGE_LOG_FD
+      echo "$AR cru libconftest.a conftest.o" >&AS_MESSAGE_LOG_FD
+      $AR cru libconftest.a conftest.o 2>&AS_MESSAGE_LOG_FD
+      echo "$RANLIB libconftest.a" >&AS_MESSAGE_LOG_FD
+      $RANLIB libconftest.a 2>&AS_MESSAGE_LOG_FD
+      cat > conftest.c << _LT_EOF
+int main() { return 0;}
+_LT_EOF
+      echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&AS_MESSAGE_LOG_FD
+      $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err
+      _lt_result=$?
+      if test -s conftest.err && $GREP force_load conftest.err; then
+	cat conftest.err >&AS_MESSAGE_LOG_FD
+      elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then
+	lt_cv_ld_force_load=yes
+      else
+	cat conftest.err >&AS_MESSAGE_LOG_FD
+      fi
+        rm -f conftest.err libconftest.a conftest conftest.c
+        rm -rf conftest.dSYM
+    ])
+    case $host_os in
+    rhapsody* | darwin1.[[012]])
+      _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;;
+    darwin1.*)
+      _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+    darwin*) # darwin 5.x on
+      # if running on 10.5 or later, the deployment target defaults
+      # to the OS version, if on x86, and 10.4, the deployment
+      # target defaults to 10.4. Don't you love it?
+      case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in
+	10.0,*86*-darwin8*|10.0,*-darwin[[91]]*)
+	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
+	10.[[012]]*)
+	  _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+	10.*)
+	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
+      esac
+    ;;
+  esac
+    if test "$lt_cv_apple_cc_single_mod" = "yes"; then
+      _lt_dar_single_mod='$single_module'
+    fi
+    if test "$lt_cv_ld_exported_symbols_list" = "yes"; then
+      _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym'
+    else
+      _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}'
+    fi
+    if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then
+      _lt_dsymutil='~$DSYMUTIL $lib || :'
+    else
+      _lt_dsymutil=
+    fi
+    ;;
+  esac
+])
+
+
+# _LT_DARWIN_LINKER_FEATURES([TAG])
+# ---------------------------------
+# Checks for linker and compiler features on darwin
+m4_defun([_LT_DARWIN_LINKER_FEATURES],
+[
+  m4_require([_LT_REQUIRED_DARWIN_CHECKS])
+  _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+  _LT_TAGVAR(hardcode_direct, $1)=no
+  _LT_TAGVAR(hardcode_automatic, $1)=yes
+  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+  if test "$lt_cv_ld_force_load" = "yes"; then
+    _LT_TAGVAR(whole_archive_flag_spec, $1)='`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`'
+    m4_case([$1], [F77], [_LT_TAGVAR(compiler_needs_object, $1)=yes],
+                  [FC],  [_LT_TAGVAR(compiler_needs_object, $1)=yes])
+  else
+    _LT_TAGVAR(whole_archive_flag_spec, $1)=''
+  fi
+  _LT_TAGVAR(link_all_deplibs, $1)=yes
+  _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined"
+  case $cc_basename in
+     ifort*) _lt_dar_can_shared=yes ;;
+     *) _lt_dar_can_shared=$GCC ;;
+  esac
+  if test "$_lt_dar_can_shared" = "yes"; then
+    output_verbose_link_cmd=func_echo_all
+    _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
+    _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
+    _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
+    _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
+    m4_if([$1], [CXX],
+[   if test "$lt_cv_apple_cc_single_mod" != "yes"; then
+      _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}"
+      _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}"
+    fi
+],[])
+  else
+  _LT_TAGVAR(ld_shlibs, $1)=no
+  fi
+])
+
+# _LT_SYS_MODULE_PATH_AIX([TAGNAME])
+# ----------------------------------
+# Links a minimal program and checks the executable
+# for the system default hardcoded library path. In most cases,
+# this is /usr/lib:/lib, but when the MPI compilers are used
+# the location of the communication and MPI libs are included too.
+# If we don't find anything, use the default library path according
+# to the aix ld manual.
+# Store the results from the different compilers for each TAGNAME.
+# Allow to override them for all tags through lt_cv_aix_libpath.
+m4_defun([_LT_SYS_MODULE_PATH_AIX],
+[m4_require([_LT_DECL_SED])dnl
+if test "${lt_cv_aix_libpath+set}" = set; then
+  aix_libpath=$lt_cv_aix_libpath
+else
+  AC_CACHE_VAL([_LT_TAGVAR([lt_cv_aix_libpath_], [$1])],
+  [AC_LINK_IFELSE([AC_LANG_PROGRAM],[
+  lt_aix_libpath_sed='[
+      /Import File Strings/,/^$/ {
+	  /^0/ {
+	      s/^0  *\([^ ]*\) *$/\1/
+	      p
+	  }
+      }]'
+  _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  # Check for a 64-bit object if we didn't find anything.
+  if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then
+    _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  fi],[])
+  if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then
+    _LT_TAGVAR([lt_cv_aix_libpath_], [$1])="/usr/lib:/lib"
+  fi
+  ])
+  aix_libpath=$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])
+fi
+])# _LT_SYS_MODULE_PATH_AIX
+
+
+# _LT_SHELL_INIT(ARG)
+# -------------------
+m4_define([_LT_SHELL_INIT],
+[m4_divert_text([M4SH-INIT], [$1
+])])# _LT_SHELL_INIT
+
+
+
+# _LT_PROG_ECHO_BACKSLASH
+# -----------------------
+# Find how we can fake an echo command that does not interpret backslash.
+# In particular, with Autoconf 2.60 or later we add some code to the start
+# of the generated configure script which will find a shell with a builtin
+# printf (which we can use as an echo command).
+m4_defun([_LT_PROG_ECHO_BACKSLASH],
+[ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
+ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
+
+AC_MSG_CHECKING([how to print strings])
+# Test print first, because it will be a builtin if present.
+if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \
+   test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then
+  ECHO='print -r --'
+elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then
+  ECHO='printf %s\n'
+else
+  # Use this function as a fallback that always works.
+  func_fallback_echo ()
+  {
+    eval 'cat <<_LTECHO_EOF
+$[]1
+_LTECHO_EOF'
+  }
+  ECHO='func_fallback_echo'
+fi
+
+# func_echo_all arg...
+# Invoke $ECHO with all args, space-separated.
+func_echo_all ()
+{
+    $ECHO "$*" 
+}
+
+case "$ECHO" in
+  printf*) AC_MSG_RESULT([printf]) ;;
+  print*) AC_MSG_RESULT([print -r]) ;;
+  *) AC_MSG_RESULT([cat]) ;;
+esac
+
+m4_ifdef([_AS_DETECT_SUGGESTED],
+[_AS_DETECT_SUGGESTED([
+  test -n "${ZSH_VERSION+set}${BASH_VERSION+set}" || (
+    ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+    ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
+    ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
+    PATH=/empty FPATH=/empty; export PATH FPATH
+    test "X`printf %s $ECHO`" = "X$ECHO" \
+      || test "X`print -r -- $ECHO`" = "X$ECHO" )])])
+
+_LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts])
+_LT_DECL([], [ECHO], [1], [An echo program that protects backslashes])
+])# _LT_PROG_ECHO_BACKSLASH
+
+
+# _LT_WITH_SYSROOT
+# ----------------
+AC_DEFUN([_LT_WITH_SYSROOT],
+[AC_MSG_CHECKING([for sysroot])
+AC_ARG_WITH([sysroot],
+[  --with-sysroot[=DIR] Search for dependent libraries within DIR
+                        (or the compiler's sysroot if not specified).],
+[], [with_sysroot=no])
+
+dnl lt_sysroot will always be passed unquoted.  We quote it here
+dnl in case the user passed a directory name.
+lt_sysroot=
+case ${with_sysroot} in #(
+ yes)
+   if test "$GCC" = yes; then
+     lt_sysroot=`$CC --print-sysroot 2>/dev/null`
+   fi
+   ;; #(
+ /*)
+   lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"`
+   ;; #(
+ no|'')
+   ;; #(
+ *)
+   AC_MSG_RESULT([${with_sysroot}])
+   AC_MSG_ERROR([The sysroot must be an absolute path.])
+   ;;
+esac
+
+ AC_MSG_RESULT([${lt_sysroot:-no}])
+_LT_DECL([], [lt_sysroot], [0], [The root where to search for ]dnl
+[dependent libraries, and in which our libraries should be installed.])])
+
+# _LT_ENABLE_LOCK
+# ---------------
+m4_defun([_LT_ENABLE_LOCK],
+[AC_ARG_ENABLE([libtool-lock],
+  [AS_HELP_STRING([--disable-libtool-lock],
+    [avoid locking (might break parallel builds)])])
+test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
+
+# Some flags need to be propagated to the compiler or linker for good
+# libtool support.
+case $host in
+ia64-*-hpux*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.$ac_objext` in
+      *ELF-32*)
+	HPUX_IA64_MODE="32"
+	;;
+      *ELF-64*)
+	HPUX_IA64_MODE="64"
+	;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+*-*-irix6*)
+  # Find out which ABI we are using.
+  echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    if test "$lt_cv_prog_gnu_ld" = yes; then
+      case `/usr/bin/file conftest.$ac_objext` in
+	*32-bit*)
+	  LD="${LD-ld} -melf32bsmip"
+	  ;;
+	*N32*)
+	  LD="${LD-ld} -melf32bmipn32"
+	  ;;
+	*64-bit*)
+	  LD="${LD-ld} -melf64bmip"
+	;;
+      esac
+    else
+      case `/usr/bin/file conftest.$ac_objext` in
+	*32-bit*)
+	  LD="${LD-ld} -32"
+	  ;;
+	*N32*)
+	  LD="${LD-ld} -n32"
+	  ;;
+	*64-bit*)
+	  LD="${LD-ld} -64"
+	  ;;
+      esac
+    fi
+  fi
+  rm -rf conftest*
+  ;;
+
+x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \
+s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.o` in
+      *32-bit*)
+	case $host in
+	  x86_64-*kfreebsd*-gnu)
+	    LD="${LD-ld} -m elf_i386_fbsd"
+	    ;;
+	  x86_64-*linux*)
+	    LD="${LD-ld} -m elf_i386"
+	    ;;
+	  powerpc64le-*linux*)
+	    LD="${LD-ld} -m elf32lppclinux"
+	    ;;
+	  powerpc64-*linux*)
+	    LD="${LD-ld} -m elf32ppclinux"
+	    ;;
+	  s390x-*linux*)
+	    LD="${LD-ld} -m elf_s390"
+	    ;;
+	  sparc64-*linux*)
+	    LD="${LD-ld} -m elf32_sparc"
+	    ;;
+	esac
+	;;
+      *64-bit*)
+	case $host in
+	  x86_64-*kfreebsd*-gnu)
+	    LD="${LD-ld} -m elf_x86_64_fbsd"
+	    ;;
+	  x86_64-*linux*)
+	    LD="${LD-ld} -m elf_x86_64"
+	    ;;
+	  powerpcle-*linux*)
+	    LD="${LD-ld} -m elf64lppc"
+	    ;;
+	  powerpc-*linux*)
+	    LD="${LD-ld} -m elf64ppc"
+	    ;;
+	  s390*-*linux*|s390*-*tpf*)
+	    LD="${LD-ld} -m elf64_s390"
+	    ;;
+	  sparc*-*linux*)
+	    LD="${LD-ld} -m elf64_sparc"
+	    ;;
+	esac
+	;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+
+*-*-sco3.2v5*)
+  # On SCO OpenServer 5, we need -belf to get full-featured binaries.
+  SAVE_CFLAGS="$CFLAGS"
+  CFLAGS="$CFLAGS -belf"
+  AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf,
+    [AC_LANG_PUSH(C)
+     AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no])
+     AC_LANG_POP])
+  if test x"$lt_cv_cc_needs_belf" != x"yes"; then
+    # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
+    CFLAGS="$SAVE_CFLAGS"
+  fi
+  ;;
+*-*solaris*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.o` in
+    *64-bit*)
+      case $lt_cv_prog_gnu_ld in
+      yes*)
+        case $host in
+        i?86-*-solaris*)
+          LD="${LD-ld} -m elf_x86_64"
+          ;;
+        sparc*-*-solaris*)
+          LD="${LD-ld} -m elf64_sparc"
+          ;;
+        esac
+        # GNU ld 2.21 introduced _sol2 emulations.  Use them if available.
+        if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then
+          LD="${LD-ld}_sol2"
+        fi
+        ;;
+      *)
+	if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then
+	  LD="${LD-ld} -64"
+	fi
+	;;
+      esac
+      ;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+esac
+
+need_locks="$enable_libtool_lock"
+])# _LT_ENABLE_LOCK
+
+
+# _LT_PROG_AR
+# -----------
+m4_defun([_LT_PROG_AR],
+[AC_CHECK_TOOLS(AR, [ar], false)
+: ${AR=ar}
+: ${AR_FLAGS=cru}
+_LT_DECL([], [AR], [1], [The archiver])
+_LT_DECL([], [AR_FLAGS], [1], [Flags to create an archive])
+
+AC_CACHE_CHECK([for archiver @FILE support], [lt_cv_ar_at_file],
+  [lt_cv_ar_at_file=no
+   AC_COMPILE_IFELSE([AC_LANG_PROGRAM],
+     [echo conftest.$ac_objext > conftest.lst
+      lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&AS_MESSAGE_LOG_FD'
+      AC_TRY_EVAL([lt_ar_try])
+      if test "$ac_status" -eq 0; then
+	# Ensure the archiver fails upon bogus file names.
+	rm -f conftest.$ac_objext libconftest.a
+	AC_TRY_EVAL([lt_ar_try])
+	if test "$ac_status" -ne 0; then
+          lt_cv_ar_at_file=@
+        fi
+      fi
+      rm -f conftest.* libconftest.a
+     ])
+  ])
+
+if test "x$lt_cv_ar_at_file" = xno; then
+  archiver_list_spec=
+else
+  archiver_list_spec=$lt_cv_ar_at_file
+fi
+_LT_DECL([], [archiver_list_spec], [1],
+  [How to feed a file listing to the archiver])
+])# _LT_PROG_AR
+
+
+# _LT_CMD_OLD_ARCHIVE
+# -------------------
+m4_defun([_LT_CMD_OLD_ARCHIVE],
+[_LT_PROG_AR
+
+AC_CHECK_TOOL(STRIP, strip, :)
+test -z "$STRIP" && STRIP=:
+_LT_DECL([], [STRIP], [1], [A symbol stripping program])
+
+AC_CHECK_TOOL(RANLIB, ranlib, :)
+test -z "$RANLIB" && RANLIB=:
+_LT_DECL([], [RANLIB], [1],
+    [Commands used to install an old-style archive])
+
+# Determine commands to create old-style static archives.
+old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs'
+old_postinstall_cmds='chmod 644 $oldlib'
+old_postuninstall_cmds=
+
+if test -n "$RANLIB"; then
+  case $host_os in
+  openbsd*)
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib"
+    ;;
+  *)
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib"
+    ;;
+  esac
+  old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib"
+fi
+
+case $host_os in
+  darwin*)
+    lock_old_archive_extraction=yes ;;
+  *)
+    lock_old_archive_extraction=no ;;
+esac
+_LT_DECL([], [old_postinstall_cmds], [2])
+_LT_DECL([], [old_postuninstall_cmds], [2])
+_LT_TAGDECL([], [old_archive_cmds], [2],
+    [Commands used to build an old-style archive])
+_LT_DECL([], [lock_old_archive_extraction], [0],
+    [Whether to use a lock for old archive extraction])
+])# _LT_CMD_OLD_ARCHIVE
+
+
+# _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
+#		[OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE])
+# ----------------------------------------------------------------
+# Check whether the given compiler option works
+AC_DEFUN([_LT_COMPILER_OPTION],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_SED])dnl
+AC_CACHE_CHECK([$1], [$2],
+  [$2=no
+   m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4])
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+   lt_compiler_flag="$3"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   # The option is referenced via a variable to avoid confusing sed.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+   (eval "$lt_compile" 2>conftest.err)
+   ac_status=$?
+   cat conftest.err >&AS_MESSAGE_LOG_FD
+   echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+   if (exit $ac_status) && test -s "$ac_outfile"; then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings other than the usual output.
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp
+     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+       $2=yes
+     fi
+   fi
+   $RM conftest*
+])
+
+if test x"[$]$2" = xyes; then
+    m4_if([$5], , :, [$5])
+else
+    m4_if([$6], , :, [$6])
+fi
+])# _LT_COMPILER_OPTION
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], [])
+
+
+# _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
+#                  [ACTION-SUCCESS], [ACTION-FAILURE])
+# ----------------------------------------------------
+# Check whether the given linker option works
+AC_DEFUN([_LT_LINKER_OPTION],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_SED])dnl
+AC_CACHE_CHECK([$1], [$2],
+  [$2=no
+   save_LDFLAGS="$LDFLAGS"
+   LDFLAGS="$LDFLAGS $3"
+   echo "$lt_simple_link_test_code" > conftest.$ac_ext
+   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+     # The linker can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     if test -s conftest.err; then
+       # Append any errors to the config.log.
+       cat conftest.err 1>&AS_MESSAGE_LOG_FD
+       $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp
+       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+       if diff conftest.exp conftest.er2 >/dev/null; then
+         $2=yes
+       fi
+     else
+       $2=yes
+     fi
+   fi
+   $RM -r conftest*
+   LDFLAGS="$save_LDFLAGS"
+])
+
+if test x"[$]$2" = xyes; then
+    m4_if([$4], , :, [$4])
+else
+    m4_if([$5], , :, [$5])
+fi
+])# _LT_LINKER_OPTION
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], [])
+
+
+# LT_CMD_MAX_LEN
+#---------------
+AC_DEFUN([LT_CMD_MAX_LEN],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+# find the maximum length of command line arguments
+AC_MSG_CHECKING([the maximum length of command line arguments])
+AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
+  i=0
+  teststring="ABCD"
+
+  case $build_os in
+  msdosdjgpp*)
+    # On DJGPP, this test can blow up pretty badly due to problems in libc
+    # (any single argument exceeding 2000 bytes causes a buffer overrun
+    # during glob expansion).  Even if it were fixed, the result of this
+    # check would be larger than it should be.
+    lt_cv_sys_max_cmd_len=12288;    # 12K is about right
+    ;;
+
+  gnu*)
+    # Under GNU Hurd, this test is not required because there is
+    # no limit to the length of command line arguments.
+    # Libtool will interpret -1 as no limit whatsoever
+    lt_cv_sys_max_cmd_len=-1;
+    ;;
+
+  cygwin* | mingw* | cegcc*)
+    # On Win9x/ME, this test blows up -- it succeeds, but takes
+    # about 5 minutes as the teststring grows exponentially.
+    # Worse, since 9x/ME are not pre-emptively multitasking,
+    # you end up with a "frozen" computer, even though with patience
+    # the test eventually succeeds (with a max line length of 256k).
+    # Instead, let's just punt: use the minimum linelength reported by
+    # all of the supported platforms: 8192 (on NT/2K/XP).
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  mint*)
+    # On MiNT this can take a long time and run out of memory.
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  amigaos*)
+    # On AmigaOS with pdksh, this test takes hours, literally.
+    # So we just punt and use a minimum line length of 8192.
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
+    # This has been around since 386BSD, at least.  Likely further.
+    if test -x /sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
+    elif test -x /usr/sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
+    else
+      lt_cv_sys_max_cmd_len=65536	# usable default for all BSDs
+    fi
+    # And add a safety zone
+    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+    ;;
+
+  interix*)
+    # We know the value 262144 and hardcode it with a safety zone (like BSD)
+    lt_cv_sys_max_cmd_len=196608
+    ;;
+
+  os2*)
+    # The test takes a long time on OS/2.
+    lt_cv_sys_max_cmd_len=8192
+    ;;
+
+  osf*)
+    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
+    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
+    # nice to cause kernel panics so lets avoid the loop below.
+    # First set a reasonable default.
+    lt_cv_sys_max_cmd_len=16384
+    #
+    if test -x /sbin/sysconfig; then
+      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
+        *1*) lt_cv_sys_max_cmd_len=-1 ;;
+      esac
+    fi
+    ;;
+  sco3.2v5*)
+    lt_cv_sys_max_cmd_len=102400
+    ;;
+  sysv5* | sco5v6* | sysv4.2uw2*)
+    kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
+    if test -n "$kargmax"; then
+      lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[	 ]]//'`
+    else
+      lt_cv_sys_max_cmd_len=32768
+    fi
+    ;;
+  *)
+    lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null`
+    if test -n "$lt_cv_sys_max_cmd_len"; then
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+    else
+      # Make teststring a little bigger before we do anything with it.
+      # a 1K string should be a reasonable start.
+      for i in 1 2 3 4 5 6 7 8 ; do
+        teststring=$teststring$teststring
+      done
+      SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
+      # If test is not a shell built-in, we'll probably end up computing a
+      # maximum length that is only half of the actual maximum length, but
+      # we can't tell.
+      while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \
+	         = "X$teststring$teststring"; } >/dev/null 2>&1 &&
+	      test $i != 17 # 1/2 MB should be enough
+      do
+        i=`expr $i + 1`
+        teststring=$teststring$teststring
+      done
+      # Only check the string length outside the loop.
+      lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1`
+      teststring=
+      # Add a significant safety factor because C++ compilers can tack on
+      # massive amounts of additional arguments before passing them to the
+      # linker.  It appears as though 1/2 is a usable value.
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
+    fi
+    ;;
+  esac
+])
+if test -n $lt_cv_sys_max_cmd_len ; then
+  AC_MSG_RESULT($lt_cv_sys_max_cmd_len)
+else
+  AC_MSG_RESULT(none)
+fi
+max_cmd_len=$lt_cv_sys_max_cmd_len
+_LT_DECL([], [max_cmd_len], [0],
+    [What is the maximum length of a command?])
+])# LT_CMD_MAX_LEN
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], [])
+
+
+# _LT_HEADER_DLFCN
+# ----------------
+m4_defun([_LT_HEADER_DLFCN],
+[AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl
+])# _LT_HEADER_DLFCN
+
+
+# _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE,
+#                      ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING)
+# ----------------------------------------------------------------
+m4_defun([_LT_TRY_DLOPEN_SELF],
+[m4_require([_LT_HEADER_DLFCN])dnl
+if test "$cross_compiling" = yes; then :
+  [$4]
+else
+  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+  lt_status=$lt_dlunknown
+  cat > conftest.$ac_ext <<_LT_EOF
+[#line $LINENO "configure"
+#include "confdefs.h"
+
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+#include <stdio.h>
+
+#ifdef RTLD_GLOBAL
+#  define LT_DLGLOBAL		RTLD_GLOBAL
+#else
+#  ifdef DL_GLOBAL
+#    define LT_DLGLOBAL		DL_GLOBAL
+#  else
+#    define LT_DLGLOBAL		0
+#  endif
+#endif
+
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+   find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+#  ifdef RTLD_LAZY
+#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
+#  else
+#    ifdef DL_LAZY
+#      define LT_DLLAZY_OR_NOW		DL_LAZY
+#    else
+#      ifdef RTLD_NOW
+#        define LT_DLLAZY_OR_NOW	RTLD_NOW
+#      else
+#        ifdef DL_NOW
+#          define LT_DLLAZY_OR_NOW	DL_NOW
+#        else
+#          define LT_DLLAZY_OR_NOW	0
+#        endif
+#      endif
+#    endif
+#  endif
+#endif
+
+/* When -fvisbility=hidden is used, assume the code has been annotated
+   correspondingly for the symbols needed.  */
+#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
+int fnord () __attribute__((visibility("default")));
+#endif
+
+int fnord () { return 42; }
+int main ()
+{
+  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+  int status = $lt_dlunknown;
+
+  if (self)
+    {
+      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
+      else
+        {
+	  if (dlsym( self,"_fnord"))  status = $lt_dlneed_uscore;
+          else puts (dlerror ());
+	}
+      /* dlclose (self); */
+    }
+  else
+    puts (dlerror ());
+
+  return status;
+}]
+_LT_EOF
+  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then
+    (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null
+    lt_status=$?
+    case x$lt_status in
+      x$lt_dlno_uscore) $1 ;;
+      x$lt_dlneed_uscore) $2 ;;
+      x$lt_dlunknown|x*) $3 ;;
+    esac
+  else :
+    # compilation failed
+    $3
+  fi
+fi
+rm -fr conftest*
+])# _LT_TRY_DLOPEN_SELF
+
+
+# LT_SYS_DLOPEN_SELF
+# ------------------
+AC_DEFUN([LT_SYS_DLOPEN_SELF],
+[m4_require([_LT_HEADER_DLFCN])dnl
+if test "x$enable_dlopen" != xyes; then
+  enable_dlopen=unknown
+  enable_dlopen_self=unknown
+  enable_dlopen_self_static=unknown
+else
+  lt_cv_dlopen=no
+  lt_cv_dlopen_libs=
+
+  case $host_os in
+  beos*)
+    lt_cv_dlopen="load_add_on"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+    ;;
+
+  mingw* | pw32* | cegcc*)
+    lt_cv_dlopen="LoadLibrary"
+    lt_cv_dlopen_libs=
+    ;;
+
+  cygwin*)
+    lt_cv_dlopen="dlopen"
+    lt_cv_dlopen_libs=
+    ;;
+
+  darwin*)
+  # if libdl is installed we need to link against it
+    AC_CHECK_LIB([dl], [dlopen],
+		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[
+    lt_cv_dlopen="dyld"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+    ])
+    ;;
+
+  *)
+    AC_CHECK_FUNC([shl_load],
+	  [lt_cv_dlopen="shl_load"],
+      [AC_CHECK_LIB([dld], [shl_load],
+	    [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"],
+	[AC_CHECK_FUNC([dlopen],
+	      [lt_cv_dlopen="dlopen"],
+	  [AC_CHECK_LIB([dl], [dlopen],
+		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],
+	    [AC_CHECK_LIB([svld], [dlopen],
+		  [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"],
+	      [AC_CHECK_LIB([dld], [dld_link],
+		    [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"])
+	      ])
+	    ])
+	  ])
+	])
+      ])
+    ;;
+  esac
+
+  if test "x$lt_cv_dlopen" != xno; then
+    enable_dlopen=yes
+  else
+    enable_dlopen=no
+  fi
+
+  case $lt_cv_dlopen in
+  dlopen)
+    save_CPPFLAGS="$CPPFLAGS"
+    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
+
+    save_LDFLAGS="$LDFLAGS"
+    wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
+
+    save_LIBS="$LIBS"
+    LIBS="$lt_cv_dlopen_libs $LIBS"
+
+    AC_CACHE_CHECK([whether a program can dlopen itself],
+	  lt_cv_dlopen_self, [dnl
+	  _LT_TRY_DLOPEN_SELF(
+	    lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes,
+	    lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross)
+    ])
+
+    if test "x$lt_cv_dlopen_self" = xyes; then
+      wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
+      AC_CACHE_CHECK([whether a statically linked program can dlopen itself],
+	  lt_cv_dlopen_self_static, [dnl
+	  _LT_TRY_DLOPEN_SELF(
+	    lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes,
+	    lt_cv_dlopen_self_static=no,  lt_cv_dlopen_self_static=cross)
+      ])
+    fi
+
+    CPPFLAGS="$save_CPPFLAGS"
+    LDFLAGS="$save_LDFLAGS"
+    LIBS="$save_LIBS"
+    ;;
+  esac
+
+  case $lt_cv_dlopen_self in
+  yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
+  *) enable_dlopen_self=unknown ;;
+  esac
+
+  case $lt_cv_dlopen_self_static in
+  yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
+  *) enable_dlopen_self_static=unknown ;;
+  esac
+fi
+_LT_DECL([dlopen_support], [enable_dlopen], [0],
+	 [Whether dlopen is supported])
+_LT_DECL([dlopen_self], [enable_dlopen_self], [0],
+	 [Whether dlopen of programs is supported])
+_LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0],
+	 [Whether dlopen of statically linked programs is supported])
+])# LT_SYS_DLOPEN_SELF
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], [])
+
+
+# _LT_COMPILER_C_O([TAGNAME])
+# ---------------------------
+# Check to see if options -c and -o are simultaneously supported by compiler.
+# This macro does not hard code the compiler like AC_PROG_CC_C_O.
+m4_defun([_LT_COMPILER_C_O],
+[m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_TAG_COMPILER])dnl
+AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext],
+  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)],
+  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no
+   $RM -r conftest 2>/dev/null
+   mkdir conftest
+   cd conftest
+   mkdir out
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+   lt_compiler_flag="-o out/conftest2.$ac_objext"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+   (eval "$lt_compile" 2>out/conftest.err)
+   ac_status=$?
+   cat out/conftest.err >&AS_MESSAGE_LOG_FD
+   echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+   if (exit $ac_status) && test -s out/conftest2.$ac_objext
+   then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp
+     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+       _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
+     fi
+   fi
+   chmod u+w . 2>&AS_MESSAGE_LOG_FD
+   $RM conftest*
+   # SGI C++ compiler will create directory out/ii_files/ for
+   # template instantiation
+   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
+   $RM out/* && rmdir out
+   cd ..
+   $RM -r conftest
+   $RM conftest*
+])
+_LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1],
+	[Does compiler simultaneously support -c and -o options?])
+])# _LT_COMPILER_C_O
+
+
+# _LT_COMPILER_FILE_LOCKS([TAGNAME])
+# ----------------------------------
+# Check to see if we can do hard links to lock some files if needed
+m4_defun([_LT_COMPILER_FILE_LOCKS],
+[m4_require([_LT_ENABLE_LOCK])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+_LT_COMPILER_C_O([$1])
+
+hard_links="nottested"
+if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then
+  # do not overwrite the value of need_locks provided by the user
+  AC_MSG_CHECKING([if we can lock with hard links])
+  hard_links=yes
+  $RM conftest*
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  touch conftest.a
+  ln conftest.a conftest.b 2>&5 || hard_links=no
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  AC_MSG_RESULT([$hard_links])
+  if test "$hard_links" = no; then
+    AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe])
+    need_locks=warn
+  fi
+else
+  need_locks=no
+fi
+_LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?])
+])# _LT_COMPILER_FILE_LOCKS
+
+
+# _LT_CHECK_OBJDIR
+# ----------------
+m4_defun([_LT_CHECK_OBJDIR],
+[AC_CACHE_CHECK([for objdir], [lt_cv_objdir],
+[rm -f .libs 2>/dev/null
+mkdir .libs 2>/dev/null
+if test -d .libs; then
+  lt_cv_objdir=.libs
+else
+  # MS-DOS does not allow filenames that begin with a dot.
+  lt_cv_objdir=_libs
+fi
+rmdir .libs 2>/dev/null])
+objdir=$lt_cv_objdir
+_LT_DECL([], [objdir], [0],
+         [The name of the directory that contains temporary libtool files])dnl
+m4_pattern_allow([LT_OBJDIR])dnl
+AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/",
+  [Define to the sub-directory in which libtool stores uninstalled libraries.])
+])# _LT_CHECK_OBJDIR
+
+
+# _LT_LINKER_HARDCODE_LIBPATH([TAGNAME])
+# --------------------------------------
+# Check hardcoding attributes.
+m4_defun([_LT_LINKER_HARDCODE_LIBPATH],
+[AC_MSG_CHECKING([how to hardcode library paths into programs])
+_LT_TAGVAR(hardcode_action, $1)=
+if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" ||
+   test -n "$_LT_TAGVAR(runpath_var, $1)" ||
+   test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then
+
+  # We can hardcode non-existent directories.
+  if test "$_LT_TAGVAR(hardcode_direct, $1)" != no &&
+     # If the only mechanism to avoid hardcoding is shlibpath_var, we
+     # have to relink, otherwise we might link with an installed library
+     # when we should be linking with a yet-to-be-installed one
+     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no &&
+     test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then
+    # Linking always hardcodes the temporary library directory.
+    _LT_TAGVAR(hardcode_action, $1)=relink
+  else
+    # We can link without hardcoding, and we can hardcode nonexisting dirs.
+    _LT_TAGVAR(hardcode_action, $1)=immediate
+  fi
+else
+  # We cannot hardcode anything, or else we can only hardcode existing
+  # directories.
+  _LT_TAGVAR(hardcode_action, $1)=unsupported
+fi
+AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)])
+
+if test "$_LT_TAGVAR(hardcode_action, $1)" = relink ||
+   test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then
+  # Fast installation is not supported
+  enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+     test "$enable_shared" = no; then
+  # Fast installation is not necessary
+  enable_fast_install=needless
+fi
+_LT_TAGDECL([], [hardcode_action], [0],
+    [How to hardcode a shared library path into an executable])
+])# _LT_LINKER_HARDCODE_LIBPATH
+
+
+# _LT_CMD_STRIPLIB
+# ----------------
+m4_defun([_LT_CMD_STRIPLIB],
+[m4_require([_LT_DECL_EGREP])
+striplib=
+old_striplib=
+AC_MSG_CHECKING([whether stripping libraries is possible])
+if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then
+  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
+  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
+  AC_MSG_RESULT([yes])
+else
+# FIXME - insert some real tests, host_os isn't really good enough
+  case $host_os in
+  darwin*)
+    if test -n "$STRIP" ; then
+      striplib="$STRIP -x"
+      old_striplib="$STRIP -S"
+      AC_MSG_RESULT([yes])
+    else
+      AC_MSG_RESULT([no])
+    fi
+    ;;
+  *)
+    AC_MSG_RESULT([no])
+    ;;
+  esac
+fi
+_LT_DECL([], [old_striplib], [1], [Commands to strip libraries])
+_LT_DECL([], [striplib], [1])
+])# _LT_CMD_STRIPLIB
+
+
+# _LT_SYS_DYNAMIC_LINKER([TAG])
+# -----------------------------
+# PORTME Fill in your ld.so characteristics
+m4_defun([_LT_SYS_DYNAMIC_LINKER],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_OBJDUMP])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_CHECK_SHELL_FEATURES])dnl
+AC_MSG_CHECKING([dynamic linker characteristics])
+m4_if([$1],
+	[], [
+if test "$GCC" = yes; then
+  case $host_os in
+    darwin*) lt_awk_arg="/^libraries:/,/LR/" ;;
+    *) lt_awk_arg="/^libraries:/" ;;
+  esac
+  case $host_os in
+    mingw* | cegcc*) lt_sed_strip_eq="s,=\([[A-Za-z]]:\),\1,g" ;;
+    *) lt_sed_strip_eq="s,=/,/,g" ;;
+  esac
+  lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq`
+  case $lt_search_path_spec in
+  *\;*)
+    # if the path contains ";" then we assume it to be the separator
+    # otherwise default to the standard path separator (i.e. ":") - it is
+    # assumed that no part of a normal pathname contains ";" but that should
+    # okay in the real world where ";" in dirpaths is itself problematic.
+    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'`
+    ;;
+  *)
+    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"`
+    ;;
+  esac
+  # Ok, now we have the path, separated by spaces, we can step through it
+  # and add multilib dir if necessary.
+  lt_tmp_lt_search_path_spec=
+  lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null`
+  for lt_sys_path in $lt_search_path_spec; do
+    if test -d "$lt_sys_path/$lt_multi_os_dir"; then
+      lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir"
+    else
+      test -d "$lt_sys_path" && \
+	lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path"
+    fi
+  done
+  lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk '
+BEGIN {RS=" "; FS="/|\n";} {
+  lt_foo="";
+  lt_count=0;
+  for (lt_i = NF; lt_i > 0; lt_i--) {
+    if ($lt_i != "" && $lt_i != ".") {
+      if ($lt_i == "..") {
+        lt_count++;
+      } else {
+        if (lt_count == 0) {
+          lt_foo="/" $lt_i lt_foo;
+        } else {
+          lt_count--;
+        }
+      }
+    }
+  }
+  if (lt_foo != "") { lt_freq[[lt_foo]]++; }
+  if (lt_freq[[lt_foo]] == 1) { print lt_foo; }
+}'`
+  # AWK program above erroneously prepends '/' to C:/dos/paths
+  # for these hosts.
+  case $host_os in
+    mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\
+      $SED 's,/\([[A-Za-z]]:\),\1,g'` ;;
+  esac
+  sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP`
+else
+  sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+fi])
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+shrext_cmds=".so"
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+shlibpath_overrides_runpath=unknown
+version_type=none
+dynamic_linker="$host_os ld.so"
+sys_lib_dlsearch_path_spec="/lib /usr/lib"
+need_lib_prefix=unknown
+hardcode_into_libs=no
+
+# when you set need_version to no, make sure it does not cause -set_version
+# flags to be left without arguments
+need_version=unknown
+
+case $host_os in
+aix3*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+  shlibpath_var=LIBPATH
+
+  # AIX 3 has no versioning support, so we append a major version to the name.
+  soname_spec='${libname}${release}${shared_ext}$major'
+  ;;
+
+aix[[4-9]]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  hardcode_into_libs=yes
+  if test "$host_cpu" = ia64; then
+    # AIX 5 supports IA64
+    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+    shlibpath_var=LD_LIBRARY_PATH
+  else
+    # With GCC up to 2.95.x, collect2 would create an import file
+    # for dependence libraries.  The import file would start with
+    # the line `#! .'.  This would cause the generated library to
+    # depend on `.', always an invalid library.  This was fixed in
+    # development snapshots of GCC prior to 3.0.
+    case $host_os in
+      aix4 | aix4.[[01]] | aix4.[[01]].*)
+      if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
+	   echo ' yes '
+	   echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then
+	:
+      else
+	can_build_shared=no
+      fi
+      ;;
+    esac
+    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+    # soname into executable. Probably we can add versioning support to
+    # collect2, so additional links can be useful in future.
+    if test "$aix_use_runtimelinking" = yes; then
+      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
+      # instead of lib<name>.a to let people know that these are not
+      # typical AIX shared libraries.
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    else
+      # We preserve .a as extension for shared libraries through AIX4.2
+      # and later when we are not doing run time linking.
+      library_names_spec='${libname}${release}.a $libname.a'
+      soname_spec='${libname}${release}${shared_ext}$major'
+    fi
+    shlibpath_var=LIBPATH
+  fi
+  ;;
+
+amigaos*)
+  case $host_cpu in
+  powerpc)
+    # Since July 2007 AmigaOS4 officially supports .so libraries.
+    # When compiling the executable, add -use-dynld -Lsobjs: to the compileline.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    ;;
+  m68k)
+    library_names_spec='$libname.ixlibrary $libname.a'
+    # Create ${libname}_ixlibrary.a entries in /sys/libs.
+    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+    ;;
+  esac
+  ;;
+
+beos*)
+  library_names_spec='${libname}${shared_ext}'
+  dynamic_linker="$host_os ld.so"
+  shlibpath_var=LIBRARY_PATH
+  ;;
+
+bsdi[[45]]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
+  sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
+  # the default ld.so.conf also contains /usr/contrib/lib and
+  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
+  # libtool to hard-code these into programs
+  ;;
+
+cygwin* | mingw* | pw32* | cegcc*)
+  version_type=windows
+  shrext_cmds=".dll"
+  need_version=no
+  need_lib_prefix=no
+
+  case $GCC,$cc_basename in
+  yes,*)
+    # gcc
+    library_names_spec='$libname.dll.a'
+    # DLL is installed to $(libdir)/../bin by postinstall_cmds
+    postinstall_cmds='base_file=`basename \${file}`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+      dldir=$destdir/`dirname \$dlpath`~
+      test -d \$dldir || mkdir -p \$dldir~
+      $install_prog $dir/$dlname \$dldir/$dlname~
+      chmod a+x \$dldir/$dlname~
+      if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then
+        eval '\''$striplib \$dldir/$dlname'\'' || exit \$?;
+      fi'
+    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+      dlpath=$dir/\$dldll~
+       $RM \$dlpath'
+    shlibpath_overrides_runpath=yes
+
+    case $host_os in
+    cygwin*)
+      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+      soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+m4_if([$1], [],[
+      sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"])
+      ;;
+    mingw* | cegcc*)
+      # MinGW DLLs use traditional 'lib' prefix
+      soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+      ;;
+    pw32*)
+      # pw32 DLLs use 'pw' prefix rather than 'lib'
+      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+      ;;
+    esac
+    dynamic_linker='Win32 ld.exe'
+    ;;
+
+  *,cl*)
+    # Native MSVC
+    libname_spec='$name'
+    soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+    library_names_spec='${libname}.dll.lib'
+
+    case $build_os in
+    mingw*)
+      sys_lib_search_path_spec=
+      lt_save_ifs=$IFS
+      IFS=';'
+      for lt_path in $LIB
+      do
+        IFS=$lt_save_ifs
+        # Let DOS variable expansion print the short 8.3 style file name.
+        lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"`
+        sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path"
+      done
+      IFS=$lt_save_ifs
+      # Convert to MSYS style.
+      sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([[a-zA-Z]]\\):| /\\1|g' -e 's|^ ||'`
+      ;;
+    cygwin*)
+      # Convert to unix form, then to dos form, then back to unix form
+      # but this time dos style (no spaces!) so that the unix form looks
+      # like /cygdrive/c/PROGRA~1:/cygdr...
+      sys_lib_search_path_spec=`cygpath --path --unix "$LIB"`
+      sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null`
+      sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+      ;;
+    *)
+      sys_lib_search_path_spec="$LIB"
+      if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then
+        # It is most probably a Windows format PATH.
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+      else
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+      fi
+      # FIXME: find the short name or the path components, as spaces are
+      # common. (e.g. "Program Files" -> "PROGRA~1")
+      ;;
+    esac
+
+    # DLL is installed to $(libdir)/../bin by postinstall_cmds
+    postinstall_cmds='base_file=`basename \${file}`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+      dldir=$destdir/`dirname \$dlpath`~
+      test -d \$dldir || mkdir -p \$dldir~
+      $install_prog $dir/$dlname \$dldir/$dlname'
+    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+      dlpath=$dir/\$dldll~
+       $RM \$dlpath'
+    shlibpath_overrides_runpath=yes
+    dynamic_linker='Win32 link.exe'
+    ;;
+
+  *)
+    # Assume MSVC wrapper
+    library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib'
+    dynamic_linker='Win32 ld.exe'
+    ;;
+  esac
+  # FIXME: first we should search . and the directory the executable is in
+  shlibpath_var=PATH
+  ;;
+
+darwin* | rhapsody*)
+  dynamic_linker="$host_os dyld"
+  version_type=darwin
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext'
+  soname_spec='${libname}${release}${major}$shared_ext'
+  shlibpath_overrides_runpath=yes
+  shlibpath_var=DYLD_LIBRARY_PATH
+  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+m4_if([$1], [],[
+  sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"])
+  sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
+  ;;
+
+dgux*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+freebsd* | dragonfly*)
+  # DragonFly does not have aout.  When/if they implement a new
+  # versioning mechanism, adjust this.
+  if test -x /usr/bin/objformat; then
+    objformat=`/usr/bin/objformat`
+  else
+    case $host_os in
+    freebsd[[23]].*) objformat=aout ;;
+    *) objformat=elf ;;
+    esac
+  fi
+  version_type=freebsd-$objformat
+  case $version_type in
+    freebsd-elf*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+      need_version=no
+      need_lib_prefix=no
+      ;;
+    freebsd-*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+      need_version=yes
+      ;;
+  esac
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_os in
+  freebsd2.*)
+    shlibpath_overrides_runpath=yes
+    ;;
+  freebsd3.[[01]]* | freebsdelf3.[[01]]*)
+    shlibpath_overrides_runpath=yes
+    hardcode_into_libs=yes
+    ;;
+  freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \
+  freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1)
+    shlibpath_overrides_runpath=no
+    hardcode_into_libs=yes
+    ;;
+  *) # from 4.6 on, and DragonFly
+    shlibpath_overrides_runpath=yes
+    hardcode_into_libs=yes
+    ;;
+  esac
+  ;;
+
+gnu*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+haiku*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  dynamic_linker="$host_os runtime_loader"
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib'
+  hardcode_into_libs=yes
+  ;;
+
+hpux9* | hpux10* | hpux11*)
+  # Give a soname corresponding to the major version so that dld.sl refuses to
+  # link against other versions.
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  case $host_cpu in
+  ia64*)
+    shrext_cmds='.so'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.so"
+    shlibpath_var=LD_LIBRARY_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    if test "X$HPUX_IA64_MODE" = X32; then
+      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+    else
+      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+    fi
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  hppa*64*)
+    shrext_cmds='.sl'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  *)
+    shrext_cmds='.sl'
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=SHLIB_PATH
+    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    ;;
+  esac
+  # HP-UX runs *really* slowly unless shared libraries are mode 555, ...
+  postinstall_cmds='chmod 555 $lib'
+  # or fails outright, so override atomically:
+  install_override_mode=555
+  ;;
+
+interix[[3-9]]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+irix5* | irix6* | nonstopux*)
+  case $host_os in
+    nonstopux*) version_type=nonstopux ;;
+    *)
+	if test "$lt_cv_prog_gnu_ld" = yes; then
+		version_type=linux # correct to gnu/linux during the next big refactor
+	else
+		version_type=irix
+	fi ;;
+  esac
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+  case $host_os in
+  irix5* | nonstopux*)
+    libsuff= shlibsuff=
+    ;;
+  *)
+    case $LD in # libtool.m4 will add one of these switches to LD
+    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+      libsuff= shlibsuff= libmagic=32-bit;;
+    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+      libsuff=32 shlibsuff=N32 libmagic=N32;;
+    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+      libsuff=64 shlibsuff=64 libmagic=64-bit;;
+    *) libsuff= shlibsuff= libmagic=never-match;;
+    esac
+    ;;
+  esac
+  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+  shlibpath_overrides_runpath=no
+  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+  hardcode_into_libs=yes
+  ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+  dynamic_linker=no
+  ;;
+
+# This must be glibc/ELF.
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+
+  # Some binutils ld are patched to set DT_RUNPATH
+  AC_CACHE_VAL([lt_cv_shlibpath_overrides_runpath],
+    [lt_cv_shlibpath_overrides_runpath=no
+    save_LDFLAGS=$LDFLAGS
+    save_libdir=$libdir
+    eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \
+	 LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\""
+    AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
+      [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null],
+	 [lt_cv_shlibpath_overrides_runpath=yes])])
+    LDFLAGS=$save_LDFLAGS
+    libdir=$save_libdir
+    ])
+  shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath
+
+  # This implies no fast_install, which is unacceptable.
+  # Some rework will be needed to allow for fast_install
+  # before this can be enabled.
+  hardcode_into_libs=yes
+
+  # Add ABI-specific directories to the system library path.
+  sys_lib_dlsearch_path_spec="/lib64 /usr/lib64 /lib /usr/lib"
+
+  # Append ld.so.conf contents to the search path
+  if test -f /etc/ld.so.conf; then
+    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '`
+    sys_lib_dlsearch_path_spec="$sys_lib_dlsearch_path_spec $lt_ld_extra"
+
+  fi
+
+  # We used to test for /lib/ld.so.1 and disable shared libraries on
+  # powerpc, because MkLinux only supported shared libraries with the
+  # GNU dynamic linker.  Since this was broken with cross compilers,
+  # most powerpc-linux boxes support dynamic linking these days and
+  # people can always --disable-shared, the test was removed, and we
+  # assume the GNU/Linux dynamic linker is in use.
+  dynamic_linker='GNU/Linux ld.so'
+  ;;
+
+netbsd*)
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+    dynamic_linker='NetBSD (a.out) ld.so'
+  else
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    dynamic_linker='NetBSD ld.elf_so'
+  fi
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  ;;
+
+newsos6)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  ;;
+
+*nto* | *qnx*)
+  version_type=qnx
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  dynamic_linker='ldqnx.so'
+  ;;
+
+openbsd*)
+  version_type=sunos
+  sys_lib_dlsearch_path_spec="/usr/lib"
+  need_lib_prefix=no
+  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
+  case $host_os in
+    openbsd3.3 | openbsd3.3.*)	need_version=yes ;;
+    *)				need_version=no  ;;
+  esac
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    case $host_os in
+      openbsd2.[[89]] | openbsd2.[[89]].*)
+	shlibpath_overrides_runpath=no
+	;;
+      *)
+	shlibpath_overrides_runpath=yes
+	;;
+      esac
+  else
+    shlibpath_overrides_runpath=yes
+  fi
+  ;;
+
+os2*)
+  libname_spec='$name'
+  shrext_cmds=".dll"
+  need_lib_prefix=no
+  library_names_spec='$libname${shared_ext} $libname.a'
+  dynamic_linker='OS/2 ld.exe'
+  shlibpath_var=LIBPATH
+  ;;
+
+osf3* | osf4* | osf5*)
+  version_type=osf
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+  ;;
+
+rdos*)
+  dynamic_linker=no
+  ;;
+
+solaris*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  # ldd complains unless libraries are executable
+  postinstall_cmds='chmod +x $lib'
+  ;;
+
+sunos4*)
+  version_type=sunos
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  if test "$with_gnu_ld" = yes; then
+    need_lib_prefix=no
+  fi
+  need_version=yes
+  ;;
+
+sysv4 | sysv4.3*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_vendor in
+    sni)
+      shlibpath_overrides_runpath=no
+      need_lib_prefix=no
+      runpath_var=LD_RUN_PATH
+      ;;
+    siemens)
+      need_lib_prefix=no
+      ;;
+    motorola)
+      need_lib_prefix=no
+      need_version=no
+      shlibpath_overrides_runpath=no
+      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+      ;;
+  esac
+  ;;
+
+sysv4*MP*)
+  if test -d /usr/nec ;then
+    version_type=linux # correct to gnu/linux during the next big refactor
+    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+    soname_spec='$libname${shared_ext}.$major'
+    shlibpath_var=LD_LIBRARY_PATH
+  fi
+  ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  version_type=freebsd-elf
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  if test "$with_gnu_ld" = yes; then
+    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
+  else
+    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
+    case $host_os in
+      sco3.2v5*)
+        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
+	;;
+    esac
+  fi
+  sys_lib_dlsearch_path_spec='/usr/lib'
+  ;;
+
+tpf*)
+  # TPF is a cross-target only.  Preferred cross-host = GNU/Linux.
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+uts4*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+*)
+  dynamic_linker=no
+  ;;
+esac
+AC_MSG_RESULT([$dynamic_linker])
+test "$dynamic_linker" = no && can_build_shared=no
+
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
+if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
+  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
+fi
+if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
+  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
+fi
+
+_LT_DECL([], [variables_saved_for_relink], [1],
+    [Variables whose values should be saved in libtool wrapper scripts and
+    restored at link time])
+_LT_DECL([], [need_lib_prefix], [0],
+    [Do we need the "lib" prefix for modules?])
+_LT_DECL([], [need_version], [0], [Do we need a version for libraries?])
+_LT_DECL([], [version_type], [0], [Library versioning type])
+_LT_DECL([], [runpath_var], [0],  [Shared library runtime path variable])
+_LT_DECL([], [shlibpath_var], [0],[Shared library path variable])
+_LT_DECL([], [shlibpath_overrides_runpath], [0],
+    [Is shlibpath searched before the hard-coded library search path?])
+_LT_DECL([], [libname_spec], [1], [Format of library name prefix])
+_LT_DECL([], [library_names_spec], [1],
+    [[List of archive names.  First name is the real one, the rest are links.
+    The last name is the one that the linker finds with -lNAME]])
+_LT_DECL([], [soname_spec], [1],
+    [[The coded name of the library, if different from the real name]])
+_LT_DECL([], [install_override_mode], [1],
+    [Permission mode override for installation of shared libraries])
+_LT_DECL([], [postinstall_cmds], [2],
+    [Command to use after installation of a shared archive])
+_LT_DECL([], [postuninstall_cmds], [2],
+    [Command to use after uninstallation of a shared archive])
+_LT_DECL([], [finish_cmds], [2],
+    [Commands used to finish a libtool library installation in a directory])
+_LT_DECL([], [finish_eval], [1],
+    [[As "finish_cmds", except a single script fragment to be evaled but
+    not shown]])
+_LT_DECL([], [hardcode_into_libs], [0],
+    [Whether we should hardcode library paths into libraries])
+_LT_DECL([], [sys_lib_search_path_spec], [2],
+    [Compile-time system search path for libraries])
+_LT_DECL([], [sys_lib_dlsearch_path_spec], [2],
+    [Run-time system search path for libraries])
+])# _LT_SYS_DYNAMIC_LINKER
+
+
+# _LT_PATH_TOOL_PREFIX(TOOL)
+# --------------------------
+# find a file program which can recognize shared library
+AC_DEFUN([_LT_PATH_TOOL_PREFIX],
+[m4_require([_LT_DECL_EGREP])dnl
+AC_MSG_CHECKING([for $1])
+AC_CACHE_VAL(lt_cv_path_MAGIC_CMD,
+[case $MAGIC_CMD in
+[[\\/*] |  ?:[\\/]*])
+  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
+  ;;
+*)
+  lt_save_MAGIC_CMD="$MAGIC_CMD"
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+dnl $ac_dummy forces splitting on constant user-supplied paths.
+dnl POSIX.2 word splitting is done only on the output of word expansions,
+dnl not every word.  This closes a longstanding sh security hole.
+  ac_dummy="m4_if([$2], , $PATH, [$2])"
+  for ac_dir in $ac_dummy; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    if test -f $ac_dir/$1; then
+      lt_cv_path_MAGIC_CMD="$ac_dir/$1"
+      if test -n "$file_magic_test_file"; then
+	case $deplibs_check_method in
+	"file_magic "*)
+	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
+	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
+	    $EGREP "$file_magic_regex" > /dev/null; then
+	    :
+	  else
+	    cat <<_LT_EOF 1>&2
+
+*** Warning: the command libtool uses to detect shared libraries,
+*** $file_magic_cmd, produces output that libtool cannot recognize.
+*** The result is that libtool may fail to recognize shared libraries
+*** as such.  This will affect the creation of libtool libraries that
+*** depend on shared libraries, but programs linked with such libtool
+*** libraries will work regardless of this problem.  Nevertheless, you
+*** may want to report the problem to your system manager and/or to
+*** bug-libtool at gnu.org
+
+_LT_EOF
+	  fi ;;
+	esac
+      fi
+      break
+    fi
+  done
+  IFS="$lt_save_ifs"
+  MAGIC_CMD="$lt_save_MAGIC_CMD"
+  ;;
+esac])
+MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+if test -n "$MAGIC_CMD"; then
+  AC_MSG_RESULT($MAGIC_CMD)
+else
+  AC_MSG_RESULT(no)
+fi
+_LT_DECL([], [MAGIC_CMD], [0],
+	 [Used to examine libraries when file_magic_cmd begins with "file"])dnl
+])# _LT_PATH_TOOL_PREFIX
+
+# Old name:
+AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], [])
+
+
+# _LT_PATH_MAGIC
+# --------------
+# find a file program which can recognize a shared library
+m4_defun([_LT_PATH_MAGIC],
+[_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH)
+if test -z "$lt_cv_path_MAGIC_CMD"; then
+  if test -n "$ac_tool_prefix"; then
+    _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH)
+  else
+    MAGIC_CMD=:
+  fi
+fi
+])# _LT_PATH_MAGIC
+
+
+# LT_PATH_LD
+# ----------
+# find the pathname to the GNU or non-GNU linker
+AC_DEFUN([LT_PATH_LD],
+[AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_PROG_ECHO_BACKSLASH])dnl
+
+AC_ARG_WITH([gnu-ld],
+    [AS_HELP_STRING([--with-gnu-ld],
+	[assume the C compiler uses GNU ld @<:@default=no@:>@])],
+    [test "$withval" = no || with_gnu_ld=yes],
+    [with_gnu_ld=no])dnl
+
+ac_prog=ld
+if test "$GCC" = yes; then
+  # Check if gcc -print-prog-name=ld gives a path.
+  AC_MSG_CHECKING([for ld used by $CC])
+  case $host in
+  *-*-mingw*)
+    # gcc leaves a trailing carriage return which upsets mingw
+    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
+  *)
+    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
+  esac
+  case $ac_prog in
+    # Accept absolute paths.
+    [[\\/]]* | ?:[[\\/]]*)
+      re_direlt='/[[^/]][[^/]]*/\.\./'
+      # Canonicalize the pathname of ld
+      ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'`
+      while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
+	ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
+      done
+      test -z "$LD" && LD="$ac_prog"
+      ;;
+  "")
+    # If it fails, then pretend we aren't using GCC.
+    ac_prog=ld
+    ;;
+  *)
+    # If it is relative, then search for the first ld in PATH.
+    with_gnu_ld=unknown
+    ;;
+  esac
+elif test "$with_gnu_ld" = yes; then
+  AC_MSG_CHECKING([for GNU ld])
+else
+  AC_MSG_CHECKING([for non-GNU ld])
+fi
+AC_CACHE_VAL(lt_cv_path_LD,
+[if test -z "$LD"; then
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  for ac_dir in $PATH; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
+      lt_cv_path_LD="$ac_dir/$ac_prog"
+      # Check to see if the program is GNU ld.  I'd rather use --version,
+      # but apparently some variants of GNU ld only accept -v.
+      # Break only if it was the GNU/non-GNU ld that we prefer.
+      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
+      *GNU* | *'with BFD'*)
+	test "$with_gnu_ld" != no && break
+	;;
+      *)
+	test "$with_gnu_ld" != yes && break
+	;;
+      esac
+    fi
+  done
+  IFS="$lt_save_ifs"
+else
+  lt_cv_path_LD="$LD" # Let the user override the test with a path.
+fi])
+LD="$lt_cv_path_LD"
+if test -n "$LD"; then
+  AC_MSG_RESULT($LD)
+else
+  AC_MSG_RESULT(no)
+fi
+test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH])
+_LT_PATH_LD_GNU
+AC_SUBST([LD])
+
+_LT_TAGDECL([], [LD], [1], [The linker used to build libraries])
+])# LT_PATH_LD
+
+# Old names:
+AU_ALIAS([AM_PROG_LD], [LT_PATH_LD])
+AU_ALIAS([AC_PROG_LD], [LT_PATH_LD])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_PROG_LD], [])
+dnl AC_DEFUN([AC_PROG_LD], [])
+
+
+# _LT_PATH_LD_GNU
+#- --------------
+m4_defun([_LT_PATH_LD_GNU],
+[AC_CACHE_CHECK([if the linker ($LD) is GNU ld], lt_cv_prog_gnu_ld,
+[# I'd rather use --version here, but apparently some GNU lds only accept -v.
+case `$LD -v 2>&1 </dev/null` in
+*GNU* | *'with BFD'*)
+  lt_cv_prog_gnu_ld=yes
+  ;;
+*)
+  lt_cv_prog_gnu_ld=no
+  ;;
+esac])
+with_gnu_ld=$lt_cv_prog_gnu_ld
+])# _LT_PATH_LD_GNU
+
+
+# _LT_CMD_RELOAD
+# --------------
+# find reload flag for linker
+#   -- PORTME Some linkers may need a different reload flag.
+m4_defun([_LT_CMD_RELOAD],
+[AC_CACHE_CHECK([for $LD option to reload object files],
+  lt_cv_ld_reload_flag,
+  [lt_cv_ld_reload_flag='-r'])
+reload_flag=$lt_cv_ld_reload_flag
+case $reload_flag in
+"" | " "*) ;;
+*) reload_flag=" $reload_flag" ;;
+esac
+reload_cmds='$LD$reload_flag -o $output$reload_objs'
+case $host_os in
+  cygwin* | mingw* | pw32* | cegcc*)
+    if test "$GCC" != yes; then
+      reload_cmds=false
+    fi
+    ;;
+  darwin*)
+    if test "$GCC" = yes; then
+      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
+    else
+      reload_cmds='$LD$reload_flag -o $output$reload_objs'
+    fi
+    ;;
+esac
+_LT_TAGDECL([], [reload_flag], [1], [How to create reloadable object files])dnl
+_LT_TAGDECL([], [reload_cmds], [2])dnl
+])# _LT_CMD_RELOAD
+
+
+# _LT_CHECK_MAGIC_METHOD
+# ----------------------
+# how to check for library dependencies
+#  -- PORTME fill in with the dynamic library characteristics
+m4_defun([_LT_CHECK_MAGIC_METHOD],
+[m4_require([_LT_DECL_EGREP])
+m4_require([_LT_DECL_OBJDUMP])
+AC_CACHE_CHECK([how to recognize dependent libraries],
+lt_cv_deplibs_check_method,
+[lt_cv_file_magic_cmd='$MAGIC_CMD'
+lt_cv_file_magic_test_file=
+lt_cv_deplibs_check_method='unknown'
+# Need to set the preceding variable on all platforms that support
+# interlibrary dependencies.
+# 'none' -- dependencies not supported.
+# `unknown' -- same as none, but documents that we really don't know.
+# 'pass_all' -- all dependencies passed with no checks.
+# 'test_compile' -- check by making test program.
+# 'file_magic [[regex]]' -- check by looking for files in library path
+# which responds to the $file_magic_cmd with a given extended regex.
+# If you have `file' or equivalent on your system and you're not sure
+# whether `pass_all' will *always* work, you probably want this one.
+
+case $host_os in
+aix[[4-9]]*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+beos*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+bsdi[[45]]*)
+  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib)'
+  lt_cv_file_magic_cmd='/usr/bin/file -L'
+  lt_cv_file_magic_test_file=/shlib/libc.so
+  ;;
+
+cygwin*)
+  # func_win32_libid is a shell function defined in ltmain.sh
+  lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+  lt_cv_file_magic_cmd='func_win32_libid'
+  ;;
+
+mingw* | pw32*)
+  # Base MSYS/MinGW do not provide the 'file' command needed by
+  # func_win32_libid shell function, so use a weaker test based on 'objdump',
+  # unless we find 'file', for example because we are cross-compiling.
+  # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin.
+  if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then
+    lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+    lt_cv_file_magic_cmd='func_win32_libid'
+  else
+    # Keep this pattern in sync with the one in func_win32_libid.
+    lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)'
+    lt_cv_file_magic_cmd='$OBJDUMP -f'
+  fi
+  ;;
+
+cegcc*)
+  # use the weaker test based on 'objdump'. See mingw*.
+  lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?'
+  lt_cv_file_magic_cmd='$OBJDUMP -f'
+  ;;
+
+darwin* | rhapsody*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+freebsd* | dragonfly*)
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
+    case $host_cpu in
+    i*86 )
+      # Not sure whether the presence of OpenBSD here was a mistake.
+      # Let's accept both of them until this is cleared up.
+      lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library'
+      lt_cv_file_magic_cmd=/usr/bin/file
+      lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
+      ;;
+    esac
+  else
+    lt_cv_deplibs_check_method=pass_all
+  fi
+  ;;
+
+gnu*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+haiku*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+hpux10.20* | hpux11*)
+  lt_cv_file_magic_cmd=/usr/bin/file
+  case $host_cpu in
+  ia64*)
+    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64'
+    lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
+    ;;
+  hppa*64*)
+    [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]']
+    lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
+    ;;
+  *)
+    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]]\.[[0-9]]) shared library'
+    lt_cv_file_magic_test_file=/usr/lib/libc.sl
+    ;;
+  esac
+  ;;
+
+interix[[3-9]]*)
+  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
+  lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$'
+  ;;
+
+irix5* | irix6* | nonstopux*)
+  case $LD in
+  *-32|*"-32 ") libmagic=32-bit;;
+  *-n32|*"-n32 ") libmagic=N32;;
+  *-64|*"-64 ") libmagic=64-bit;;
+  *) libmagic=never-match;;
+  esac
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+# This must be glibc/ELF.
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+netbsd*)
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
+  else
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$'
+  fi
+  ;;
+
+newos6*)
+  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)'
+  lt_cv_file_magic_cmd=/usr/bin/file
+  lt_cv_file_magic_test_file=/usr/lib/libnls.so
+  ;;
+
+*nto* | *qnx*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+openbsd*)
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$'
+  else
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
+  fi
+  ;;
+
+osf3* | osf4* | osf5*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+rdos*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+solaris*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+sysv4 | sysv4.3*)
+  case $host_vendor in
+  motorola)
+    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]'
+    lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
+    ;;
+  ncr)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  sequent)
+    lt_cv_file_magic_cmd='/bin/file'
+    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )'
+    ;;
+  sni)
+    lt_cv_file_magic_cmd='/bin/file'
+    lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib"
+    lt_cv_file_magic_test_file=/lib/libc.so
+    ;;
+  siemens)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  pc)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  esac
+  ;;
+
+tpf*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+esac
+])
+
+file_magic_glob=
+want_nocaseglob=no
+if test "$build" = "$host"; then
+  case $host_os in
+  mingw* | pw32*)
+    if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then
+      want_nocaseglob=yes
+    else
+      file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[[\1]]\/[[\1]]\/g;/g"`
+    fi
+    ;;
+  esac
+fi
+
+file_magic_cmd=$lt_cv_file_magic_cmd
+deplibs_check_method=$lt_cv_deplibs_check_method
+test -z "$deplibs_check_method" && deplibs_check_method=unknown
+
+_LT_DECL([], [deplibs_check_method], [1],
+    [Method to check whether dependent libraries are shared objects])
+_LT_DECL([], [file_magic_cmd], [1],
+    [Command to use when deplibs_check_method = "file_magic"])
+_LT_DECL([], [file_magic_glob], [1],
+    [How to find potential files when deplibs_check_method = "file_magic"])
+_LT_DECL([], [want_nocaseglob], [1],
+    [Find potential files using nocaseglob when deplibs_check_method = "file_magic"])
+])# _LT_CHECK_MAGIC_METHOD
+
+
+# LT_PATH_NM
+# ----------
+# find the pathname to a BSD- or MS-compatible name lister
+AC_DEFUN([LT_PATH_NM],
+[AC_REQUIRE([AC_PROG_CC])dnl
+AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM,
+[if test -n "$NM"; then
+  # Let the user override the test.
+  lt_cv_path_NM="$NM"
+else
+  lt_nm_to_check="${ac_tool_prefix}nm"
+  if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
+    lt_nm_to_check="$lt_nm_to_check nm"
+  fi
+  for lt_tmp_nm in $lt_nm_to_check; do
+    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
+      IFS="$lt_save_ifs"
+      test -z "$ac_dir" && ac_dir=.
+      tmp_nm="$ac_dir/$lt_tmp_nm"
+      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
+	# Check to see if the nm accepts a BSD-compat flag.
+	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
+	#   nm: unknown option "B" ignored
+	# Tru64's nm complains that /dev/null is an invalid object file
+	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
+	*/dev/null* | *'Invalid file or object type'*)
+	  lt_cv_path_NM="$tmp_nm -B"
+	  break
+	  ;;
+	*)
+	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
+	  */dev/null*)
+	    lt_cv_path_NM="$tmp_nm -p"
+	    break
+	    ;;
+	  *)
+	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
+	    continue # so that we can try to find one that supports BSD flags
+	    ;;
+	  esac
+	  ;;
+	esac
+      fi
+    done
+    IFS="$lt_save_ifs"
+  done
+  : ${lt_cv_path_NM=no}
+fi])
+if test "$lt_cv_path_NM" != "no"; then
+  NM="$lt_cv_path_NM"
+else
+  # Didn't find any BSD compatible name lister, look for dumpbin.
+  if test -n "$DUMPBIN"; then :
+    # Let the user override the test.
+  else
+    AC_CHECK_TOOLS(DUMPBIN, [dumpbin "link -dump"], :)
+    case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in
+    *COFF*)
+      DUMPBIN="$DUMPBIN -symbols"
+      ;;
+    *)
+      DUMPBIN=:
+      ;;
+    esac
+  fi
+  AC_SUBST([DUMPBIN])
+  if test "$DUMPBIN" != ":"; then
+    NM="$DUMPBIN"
+  fi
+fi
+test -z "$NM" && NM=nm
+AC_SUBST([NM])
+_LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl
+
+AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface],
+  [lt_cv_nm_interface="BSD nm"
+  echo "int some_variable = 0;" > conftest.$ac_ext
+  (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&AS_MESSAGE_LOG_FD)
+  (eval "$ac_compile" 2>conftest.err)
+  cat conftest.err >&AS_MESSAGE_LOG_FD
+  (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD)
+  (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out)
+  cat conftest.err >&AS_MESSAGE_LOG_FD
+  (eval echo "\"\$as_me:$LINENO: output\"" >&AS_MESSAGE_LOG_FD)
+  cat conftest.out >&AS_MESSAGE_LOG_FD
+  if $GREP 'External.*some_variable' conftest.out > /dev/null; then
+    lt_cv_nm_interface="MS dumpbin"
+  fi
+  rm -f conftest*])
+])# LT_PATH_NM
+
+# Old names:
+AU_ALIAS([AM_PROG_NM], [LT_PATH_NM])
+AU_ALIAS([AC_PROG_NM], [LT_PATH_NM])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_PROG_NM], [])
+dnl AC_DEFUN([AC_PROG_NM], [])
+
+# _LT_CHECK_SHAREDLIB_FROM_LINKLIB
+# --------------------------------
+# how to determine the name of the shared library
+# associated with a specific link library.
+#  -- PORTME fill in with the dynamic library characteristics
+m4_defun([_LT_CHECK_SHAREDLIB_FROM_LINKLIB],
+[m4_require([_LT_DECL_EGREP])
+m4_require([_LT_DECL_OBJDUMP])
+m4_require([_LT_DECL_DLLTOOL])
+AC_CACHE_CHECK([how to associate runtime and link libraries],
+lt_cv_sharedlib_from_linklib_cmd,
+[lt_cv_sharedlib_from_linklib_cmd='unknown'
+
+case $host_os in
+cygwin* | mingw* | pw32* | cegcc*)
+  # two different shell functions defined in ltmain.sh
+  # decide which to use based on capabilities of $DLLTOOL
+  case `$DLLTOOL --help 2>&1` in
+  *--identify-strict*)
+    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib
+    ;;
+  *)
+    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback
+    ;;
+  esac
+  ;;
+*)
+  # fallback: assume linklib IS sharedlib
+  lt_cv_sharedlib_from_linklib_cmd="$ECHO"
+  ;;
+esac
+])
+sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd
+test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO
+
+_LT_DECL([], [sharedlib_from_linklib_cmd], [1],
+    [Command to associate shared and link libraries])
+])# _LT_CHECK_SHAREDLIB_FROM_LINKLIB
+
+
+# _LT_PATH_MANIFEST_TOOL
+# ----------------------
+# locate the manifest tool
+m4_defun([_LT_PATH_MANIFEST_TOOL],
+[AC_CHECK_TOOL(MANIFEST_TOOL, mt, :)
+test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt
+AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_mainfest_tool],
+  [lt_cv_path_mainfest_tool=no
+  echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&AS_MESSAGE_LOG_FD
+  $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out
+  cat conftest.err >&AS_MESSAGE_LOG_FD
+  if $GREP 'Manifest Tool' conftest.out > /dev/null; then
+    lt_cv_path_mainfest_tool=yes
+  fi
+  rm -f conftest*])
+if test "x$lt_cv_path_mainfest_tool" != xyes; then
+  MANIFEST_TOOL=:
+fi
+_LT_DECL([], [MANIFEST_TOOL], [1], [Manifest tool])dnl
+])# _LT_PATH_MANIFEST_TOOL
+
+
+# LT_LIB_M
+# --------
+# check for math library
+AC_DEFUN([LT_LIB_M],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+LIBM=
+case $host in
+*-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*)
+  # These system don't have libm, or don't need it
+  ;;
+*-ncr-sysv4.3*)
+  AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw")
+  AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm")
+  ;;
+*)
+  AC_CHECK_LIB(m, cos, LIBM="-lm")
+  ;;
+esac
+AC_SUBST([LIBM])
+])# LT_LIB_M
+
+# Old name:
+AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_CHECK_LIBM], [])
+
+
+# _LT_COMPILER_NO_RTTI([TAGNAME])
+# -------------------------------
+m4_defun([_LT_COMPILER_NO_RTTI],
+[m4_require([_LT_TAG_COMPILER])dnl
+
+_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
+
+if test "$GCC" = yes; then
+  case $cc_basename in
+  nvcc*)
+    _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -Xcompiler -fno-builtin' ;;
+  *)
+    _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' ;;
+  esac
+
+  _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions],
+    lt_cv_prog_compiler_rtti_exceptions,
+    [-fno-rtti -fno-exceptions], [],
+    [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"])
+fi
+_LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1],
+	[Compiler flag to turn off builtin functions])
+])# _LT_COMPILER_NO_RTTI
+
+
+# _LT_CMD_GLOBAL_SYMBOLS
+# ----------------------
+m4_defun([_LT_CMD_GLOBAL_SYMBOLS],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_PROG_AWK])dnl
+AC_REQUIRE([LT_PATH_NM])dnl
+AC_REQUIRE([LT_PATH_LD])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_TAG_COMPILER])dnl
+
+# Check for command to grab the raw symbol name followed by C symbol from nm.
+AC_MSG_CHECKING([command to parse $NM output from $compiler object])
+AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe],
+[
+# These are sane defaults that work on at least a few old systems.
+# [They come from Ultrix.  What could be older than Ultrix?!! ;)]
+
+# Character class describing NM global symbol codes.
+symcode='[[BCDEGRST]]'
+
+# Regexp to match symbols that can be accessed directly from C.
+sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)'
+
+# Define system-specific variables.
+case $host_os in
+aix*)
+  symcode='[[BCDT]]'
+  ;;
+cygwin* | mingw* | pw32* | cegcc*)
+  symcode='[[ABCDGISTW]]'
+  ;;
+hpux*)
+  if test "$host_cpu" = ia64; then
+    symcode='[[ABCDEGRST]]'
+  fi
+  ;;
+irix* | nonstopux*)
+  symcode='[[BCDEGRST]]'
+  ;;
+osf*)
+  symcode='[[BCDEGQRST]]'
+  ;;
+solaris*)
+  symcode='[[BDRT]]'
+  ;;
+sco3.2v5*)
+  symcode='[[DT]]'
+  ;;
+sysv4.2uw2*)
+  symcode='[[DT]]'
+  ;;
+sysv5* | sco5v6* | unixware* | OpenUNIX*)
+  symcode='[[ABDT]]'
+  ;;
+sysv4)
+  symcode='[[DFNSTU]]'
+  ;;
+esac
+
+# If we're using GNU nm, then use its standard symbol codes.
+case `$NM -V 2>&1` in
+*GNU* | *'with BFD'*)
+  symcode='[[ABCDGIRSTW]]' ;;
+esac
+
+# Transform an extracted symbol line into a proper C declaration.
+# Some systems (esp. on ia64) link data and code symbols differently,
+# so use this general approach.
+lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+
+# Transform an extracted symbol line into symbol name and symbol address
+lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p'"
+lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"lib\2\", (void *) \&\2},/p'"
+
+# Handle CRLF in mingw tool chain
+opt_cr=
+case $build_os in
+mingw*)
+  opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp
+  ;;
+esac
+
+# Try without a prefix underscore, then with it.
+for ac_symprfx in "" "_"; do
+
+  # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol.
+  symxfrm="\\1 $ac_symprfx\\2 \\2"
+
+  # Write the raw and C identifiers.
+  if test "$lt_cv_nm_interface" = "MS dumpbin"; then
+    # Fake it for dumpbin and say T for any non-static function
+    # and D for any global variable.
+    # Also find C++ and __fastcall symbols from MSVC++,
+    # which start with @ or ?.
+    lt_cv_sys_global_symbol_pipe="$AWK ['"\
+"     {last_section=section; section=\$ 3};"\
+"     /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\
+"     /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\
+"     \$ 0!~/External *\|/{next};"\
+"     / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\
+"     {if(hide[section]) next};"\
+"     {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\
+"     {split(\$ 0, a, /\||\r/); split(a[2], s)};"\
+"     s[1]~/^[@?]/{print s[1], s[1]; next};"\
+"     s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\
+"     ' prfx=^$ac_symprfx]"
+  else
+    lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[	 ]]\($symcode$symcode*\)[[	 ]][[	 ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
+  fi
+  lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'"
+
+  # Check to see that the pipe works correctly.
+  pipe_works=no
+
+  rm -f conftest*
+  cat > conftest.$ac_ext <<_LT_EOF
+#ifdef __cplusplus
+extern "C" {
+#endif
+char nm_test_var;
+void nm_test_func(void);
+void nm_test_func(void){}
+#ifdef __cplusplus
+}
+#endif
+int main(){nm_test_var='a';nm_test_func();return(0);}
+_LT_EOF
+
+  if AC_TRY_EVAL(ac_compile); then
+    # Now try to grab the symbols.
+    nlist=conftest.nm
+    if AC_TRY_EVAL(NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) && test -s "$nlist"; then
+      # Try sorting and uniquifying the output.
+      if sort "$nlist" | uniq > "$nlist"T; then
+	mv -f "$nlist"T "$nlist"
+      else
+	rm -f "$nlist"T
+      fi
+
+      # Make sure that we snagged all the symbols we need.
+      if $GREP ' nm_test_var$' "$nlist" >/dev/null; then
+	if $GREP ' nm_test_func$' "$nlist" >/dev/null; then
+	  cat <<_LT_EOF > conftest.$ac_ext
+/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
+/* DATA imports from DLLs on WIN32 con't be const, because runtime
+   relocations are performed -- see ld's documentation on pseudo-relocs.  */
+# define LT@&t at _DLSYM_CONST
+#elif defined(__osf__)
+/* This system does not cope well with relocations in const data.  */
+# define LT@&t at _DLSYM_CONST
+#else
+# define LT@&t at _DLSYM_CONST const
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+_LT_EOF
+	  # Now generate the symbol file.
+	  eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext'
+
+	  cat <<_LT_EOF >> conftest.$ac_ext
+
+/* The mapping between symbol names and symbols.  */
+LT@&t at _DLSYM_CONST struct {
+  const char *name;
+  void       *address;
+}
+lt__PROGRAM__LTX_preloaded_symbols[[]] =
+{
+  { "@PROGRAM@", (void *) 0 },
+_LT_EOF
+	  $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext
+	  cat <<\_LT_EOF >> conftest.$ac_ext
+  {0, (void *) 0}
+};
+
+/* This works around a problem in FreeBSD linker */
+#ifdef FREEBSD_WORKAROUND
+static const void *lt_preloaded_setup() {
+  return lt__PROGRAM__LTX_preloaded_symbols;
+}
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+_LT_EOF
+	  # Now try linking the two files.
+	  mv conftest.$ac_objext conftstm.$ac_objext
+	  lt_globsym_save_LIBS=$LIBS
+	  lt_globsym_save_CFLAGS=$CFLAGS
+	  LIBS="conftstm.$ac_objext"
+	  CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)"
+	  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then
+	    pipe_works=yes
+	  fi
+	  LIBS=$lt_globsym_save_LIBS
+	  CFLAGS=$lt_globsym_save_CFLAGS
+	else
+	  echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD
+	fi
+      else
+	echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD
+      fi
+    else
+      echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD
+    fi
+  else
+    echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD
+    cat conftest.$ac_ext >&5
+  fi
+  rm -rf conftest* conftst*
+
+  # Do not use the global_symbol_pipe unless it works.
+  if test "$pipe_works" = yes; then
+    break
+  else
+    lt_cv_sys_global_symbol_pipe=
+  fi
+done
+])
+if test -z "$lt_cv_sys_global_symbol_pipe"; then
+  lt_cv_sys_global_symbol_to_cdecl=
+fi
+if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
+  AC_MSG_RESULT(failed)
+else
+  AC_MSG_RESULT(ok)
+fi
+
+# Response file support.
+if test "$lt_cv_nm_interface" = "MS dumpbin"; then
+  nm_file_list_spec='@'
+elif $NM --help 2>/dev/null | grep '[[@]]FILE' >/dev/null; then
+  nm_file_list_spec='@'
+fi
+
+_LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1],
+    [Take the output of nm and produce a listing of raw symbols and C names])
+_LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1],
+    [Transform the output of nm in a proper C declaration])
+_LT_DECL([global_symbol_to_c_name_address],
+    [lt_cv_sys_global_symbol_to_c_name_address], [1],
+    [Transform the output of nm in a C name address pair])
+_LT_DECL([global_symbol_to_c_name_address_lib_prefix],
+    [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1],
+    [Transform the output of nm in a C name address pair when lib prefix is needed])
+_LT_DECL([], [nm_file_list_spec], [1],
+    [Specify filename containing input files for $NM])
+]) # _LT_CMD_GLOBAL_SYMBOLS
+
+
+# _LT_COMPILER_PIC([TAGNAME])
+# ---------------------------
+m4_defun([_LT_COMPILER_PIC],
+[m4_require([_LT_TAG_COMPILER])dnl
+_LT_TAGVAR(lt_prog_compiler_wl, $1)=
+_LT_TAGVAR(lt_prog_compiler_pic, $1)=
+_LT_TAGVAR(lt_prog_compiler_static, $1)=
+
+m4_if([$1], [CXX], [
+  # C++ specific cases for pic, static, wl, etc.
+  if test "$GXX" = yes; then
+    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+
+    case $host_os in
+    aix*)
+      # All AIX code is PIC.
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+        ;;
+      m68k)
+            # FIXME: we need at least 68020 code to build shared libraries, but
+            # adding the `-m68020' flag to GCC prevents building anything better,
+            # like `-m68040'.
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
+        ;;
+      esac
+      ;;
+
+    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+      # PIC is the default for these OSes.
+      ;;
+    mingw* | cygwin* | os2* | pw32* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      # Although the cygwin gcc ignores -fPIC, still need this for old-style
+      # (--disable-auto-import) libraries
+      m4_if([$1], [GCJ], [],
+	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      ;;
+    darwin* | rhapsody*)
+      # PIC is the default on this platform
+      # Common symbols not allowed in MH_DYLIB files
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
+      ;;
+    *djgpp*)
+      # DJGPP does not support shared libraries at all
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+      ;;
+    haiku*)
+      # PIC is the default for Haiku.
+      # The "-static" flag exists, but is broken.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)=
+      ;;
+    interix[[3-9]]*)
+      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+      # Instead, we relocate shared libraries at runtime.
+      ;;
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
+      fi
+      ;;
+    hpux*)
+      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
+      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
+      # sets the default TLS model and affects inlining.
+      case $host_cpu in
+      hppa*64*)
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	;;
+      esac
+      ;;
+    *qnx* | *nto*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+      ;;
+    *)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+      ;;
+    esac
+  else
+    case $host_os in
+      aix[[4-9]]*)
+	# All AIX code is PIC.
+	if test "$host_cpu" = ia64; then
+	  # AIX 5 now supports IA64 processor
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	else
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
+	fi
+	;;
+      chorus*)
+	case $cc_basename in
+	cxch68*)
+	  # Green Hills C++ Compiler
+	  # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
+	  ;;
+	esac
+	;;
+      mingw* | cygwin* | os2* | pw32* | cegcc*)
+	# This hack is so that the source file can tell whether it is being
+	# built for inclusion in a dll (and should export symbols for example).
+	m4_if([$1], [GCJ], [],
+	  [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+	;;
+      dgux*)
+	case $cc_basename in
+	  ec++*)
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    ;;
+	  ghcx*)
+	    # Green Hills C++ Compiler
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      freebsd* | dragonfly*)
+	# FreeBSD uses GNU C++
+	;;
+      hpux9* | hpux10* | hpux11*)
+	case $cc_basename in
+	  CC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+	    if test "$host_cpu" != ia64; then
+	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+	    fi
+	    ;;
+	  aCC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+	    case $host_cpu in
+	    hppa*64*|ia64*)
+	      # +Z the default
+	      ;;
+	    *)
+	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+	      ;;
+	    esac
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      interix*)
+	# This is c89, which is MS Visual C++ (no shared libs)
+	# Anyone wants to do a port?
+	;;
+      irix5* | irix6* | nonstopux*)
+	case $cc_basename in
+	  CC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+	    # CC pic flag -KPIC is the default.
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      linux* | k*bsd*-gnu | kopensolaris*-gnu)
+	case $cc_basename in
+	  KCC*)
+	    # KAI C++ Compiler
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	    ;;
+	  ecpc* )
+	    # old Intel C++ for x86_64 which still supported -KPIC.
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+	    ;;
+	  icpc* )
+	    # Intel C++, used to be incompatible with GCC.
+	    # ICC 10 doesn't accept -KPIC any more.
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+	    ;;
+	  pgCC* | pgcpp*)
+	    # Portland Group C++ compiler
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    ;;
+	  cxx*)
+	    # Compaq C++
+	    # Make sure the PIC flag is empty.  It appears that all Alpha
+	    # Linux and Compaq Tru64 Unix objects are PIC.
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+	    ;;
+	  xlc* | xlC* | bgxl[[cC]]* | mpixl[[cC]]*)
+	    # IBM XL 8.0, 9.0 on PPC and BlueGene
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
+	    ;;
+	  *)
+	    case `$CC -V 2>&1 | sed 5q` in
+	    *Sun\ C*)
+	      # Sun C++ 5.9
+	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+	      ;;
+	    esac
+	    ;;
+	esac
+	;;
+      lynxos*)
+	;;
+      m88k*)
+	;;
+      mvs*)
+	case $cc_basename in
+	  cxx*)
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      netbsd*)
+	;;
+      *qnx* | *nto*)
+        # QNX uses GNU C++, but need to define -shared option too, otherwise
+        # it will coredump.
+        _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+        ;;
+      osf3* | osf4* | osf5*)
+	case $cc_basename in
+	  KCC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
+	    ;;
+	  RCC*)
+	    # Rational C++ 2.4.1
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    ;;
+	  cxx*)
+	    # Digital/Compaq C++
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    # Make sure the PIC flag is empty.  It appears that all Alpha
+	    # Linux and Compaq Tru64 Unix objects are PIC.
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      psos*)
+	;;
+      solaris*)
+	case $cc_basename in
+	  CC* | sunCC*)
+	    # Sun C++ 4.2, 5.x and Centerline C++
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+	    ;;
+	  gcx*)
+	    # Green Hills C++ Compiler
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      sunos4*)
+	case $cc_basename in
+	  CC*)
+	    # Sun C++ 4.x
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    ;;
+	  lcc*)
+	    # Lucid
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+	case $cc_basename in
+	  CC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    ;;
+	esac
+	;;
+      tandem*)
+	case $cc_basename in
+	  NCC*)
+	    # NonStop-UX NCC 3.20
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      vxworks*)
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+	;;
+    esac
+  fi
+],
+[
+  if test "$GCC" = yes; then
+    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+
+    case $host_os in
+      aix*)
+      # All AIX code is PIC.
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+        ;;
+      m68k)
+            # FIXME: we need at least 68020 code to build shared libraries, but
+            # adding the `-m68020' flag to GCC prevents building anything better,
+            # like `-m68040'.
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
+        ;;
+      esac
+      ;;
+
+    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+      # PIC is the default for these OSes.
+      ;;
+
+    mingw* | cygwin* | pw32* | os2* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      # Although the cygwin gcc ignores -fPIC, still need this for old-style
+      # (--disable-auto-import) libraries
+      m4_if([$1], [GCJ], [],
+	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      ;;
+
+    darwin* | rhapsody*)
+      # PIC is the default on this platform
+      # Common symbols not allowed in MH_DYLIB files
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
+      ;;
+
+    haiku*)
+      # PIC is the default for Haiku.
+      # The "-static" flag exists, but is broken.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)=
+      ;;
+
+    hpux*)
+      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
+      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
+      # sets the default TLS model and affects inlining.
+      case $host_cpu in
+      hppa*64*)
+	# +Z the default
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	;;
+      esac
+      ;;
+
+    interix[[3-9]]*)
+      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+      # Instead, we relocate shared libraries at runtime.
+      ;;
+
+    msdosdjgpp*)
+      # Just because we use GCC doesn't mean we suddenly get shared libraries
+      # on systems that don't support them.
+      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+      enable_shared=no
+      ;;
+
+    *nto* | *qnx*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
+      fi
+      ;;
+
+    *)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+      ;;
+    esac
+
+    case $cc_basename in
+    nvcc*) # Cuda Compiler Driver 2.2
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Xlinker '
+      if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then
+        _LT_TAGVAR(lt_prog_compiler_pic, $1)="-Xcompiler $_LT_TAGVAR(lt_prog_compiler_pic, $1)"
+      fi
+      ;;
+    esac
+  else
+    # PORTME Check for flag to pass linker flags through the system compiler.
+    case $host_os in
+    aix*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      else
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
+      fi
+      ;;
+
+    mingw* | cygwin* | pw32* | os2* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      m4_if([$1], [GCJ], [],
+	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      ;;
+
+    hpux9* | hpux10* | hpux11*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+      # not for PA HP-UX.
+      case $host_cpu in
+      hppa*64*|ia64*)
+	# +Z the default
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+	;;
+      esac
+      # Is there a better lt_prog_compiler_static that works with the bundled CC?
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+      ;;
+
+    irix5* | irix6* | nonstopux*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      # PIC (with -KPIC) is the default.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+      ;;
+
+    linux* | k*bsd*-gnu | kopensolaris*-gnu)
+      case $cc_basename in
+      # old Intel for x86_64 which still supported -KPIC.
+      ecc*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+        ;;
+      # icc used to be incompatible with GCC.
+      # ICC 10 doesn't accept -KPIC any more.
+      icc* | ifort*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+        ;;
+      # Lahey Fortran 8.1.
+      lf95*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='--static'
+	;;
+      nagfor*)
+	# NAG Fortran compiler
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	;;
+      pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*)
+        # Portland Group compilers (*not* the Pentium gcc compiler,
+	# which looks to be a dead project)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+        ;;
+      ccc*)
+        _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+        # All Alpha code is PIC.
+        _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+        ;;
+      xl* | bgxl* | bgf* | mpixl*)
+	# IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
+	;;
+      *)
+	case `$CC -V 2>&1 | sed 5q` in
+	*Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [[1-7]].* | *Sun*Fortran*\ 8.[[0-3]]*)
+	  # Sun Fortran 8.3 passes all unrecognized flags to the linker
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)=''
+	  ;;
+	*Sun\ F* | *Sun*Fortran*)
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+	  ;;
+	*Sun\ C*)
+	  # Sun C 5.9
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	  ;;
+        *Intel*\ [[CF]]*Compiler*)
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+	  ;;
+	*Portland\ Group*)
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  ;;
+	esac
+	;;
+      esac
+      ;;
+
+    newsos6)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    *nto* | *qnx*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+      ;;
+
+    osf3* | osf4* | osf5*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      # All OSF/1 code is PIC.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+      ;;
+
+    rdos*)
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+      ;;
+
+    solaris*)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      case $cc_basename in
+      f77* | f90* | f95* | sunf77* | sunf90* | sunf95*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';;
+      esac
+      ;;
+
+    sunos4*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    sysv4 | sysv4.2uw2* | sysv4.3*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec ;then
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      fi
+      ;;
+
+    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    unicos*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+      ;;
+
+    uts4*)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    *)
+      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+      ;;
+    esac
+  fi
+])
+case $host_os in
+  # For platforms which do not support PIC, -DPIC is meaningless:
+  *djgpp*)
+    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+    ;;
+  *)
+    _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t at m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])"
+    ;;
+esac
+
+AC_CACHE_CHECK([for $compiler option to produce PIC],
+  [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)],
+  [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_prog_compiler_pic, $1)])
+_LT_TAGVAR(lt_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)
+
+#
+# Check to make sure the PIC flag actually works.
+#
+if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then
+  _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works],
+    [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)],
+    [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t at m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [],
+    [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in
+     "" | " "*) ;;
+     *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;;
+     esac],
+    [_LT_TAGVAR(lt_prog_compiler_pic, $1)=
+     _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no])
+fi
+_LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1],
+	[Additional compiler flags for building library objects])
+
+_LT_TAGDECL([wl], [lt_prog_compiler_wl], [1],
+	[How to pass a linker flag through the compiler])
+#
+# Check to make sure the static flag actually works.
+#
+wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\"
+_LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works],
+  _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1),
+  $lt_tmp_static_flag,
+  [],
+  [_LT_TAGVAR(lt_prog_compiler_static, $1)=])
+_LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1],
+	[Compiler flag to prevent dynamic linking])
+])# _LT_COMPILER_PIC
+
+
+# _LT_LINKER_SHLIBS([TAGNAME])
+# ----------------------------
+# See if the linker supports building shared libraries.
+m4_defun([_LT_LINKER_SHLIBS],
+[AC_REQUIRE([LT_PATH_LD])dnl
+AC_REQUIRE([LT_PATH_NM])dnl
+m4_require([_LT_PATH_MANIFEST_TOOL])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
+m4_require([_LT_TAG_COMPILER])dnl
+AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
+m4_if([$1], [CXX], [
+  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
+  case $host_os in
+  aix[[4-9]]*)
+    # If we're using GNU nm, then we don't want the "-C" option.
+    # -C means demangle to AIX nm, but means don't demangle with GNU nm
+    # Also, AIX nm treats weak defined symbols like other global defined
+    # symbols, whereas GNU nm marks them as "W".
+    if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+    else
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+    fi
+    ;;
+  pw32*)
+    _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds"
+    ;;
+  cygwin* | mingw* | cegcc*)
+    case $cc_basename in
+    cl*)
+      _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
+      ;;
+    *)
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
+      _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname']
+      ;;
+    esac
+    ;;
+  *)
+    _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+    ;;
+  esac
+], [
+  runpath_var=
+  _LT_TAGVAR(allow_undefined_flag, $1)=
+  _LT_TAGVAR(always_export_symbols, $1)=no
+  _LT_TAGVAR(archive_cmds, $1)=
+  _LT_TAGVAR(archive_expsym_cmds, $1)=
+  _LT_TAGVAR(compiler_needs_object, $1)=no
+  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+  _LT_TAGVAR(export_dynamic_flag_spec, $1)=
+  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  _LT_TAGVAR(hardcode_automatic, $1)=no
+  _LT_TAGVAR(hardcode_direct, $1)=no
+  _LT_TAGVAR(hardcode_direct_absolute, $1)=no
+  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+  _LT_TAGVAR(hardcode_libdir_separator, $1)=
+  _LT_TAGVAR(hardcode_minus_L, $1)=no
+  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+  _LT_TAGVAR(inherit_rpath, $1)=no
+  _LT_TAGVAR(link_all_deplibs, $1)=unknown
+  _LT_TAGVAR(module_cmds, $1)=
+  _LT_TAGVAR(module_expsym_cmds, $1)=
+  _LT_TAGVAR(old_archive_from_new_cmds, $1)=
+  _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)=
+  _LT_TAGVAR(thread_safe_flag_spec, $1)=
+  _LT_TAGVAR(whole_archive_flag_spec, $1)=
+  # include_expsyms should be a list of space-separated symbols to be *always*
+  # included in the symbol list
+  _LT_TAGVAR(include_expsyms, $1)=
+  # exclude_expsyms can be an extended regexp of symbols to exclude
+  # it will be wrapped by ` (' and `)$', so one must not match beginning or
+  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
+  # as well as any symbol that contains `d'.
+  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
+  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
+  # platforms (ab)use it in PIC code, but their linkers get confused if
+  # the symbol is explicitly referenced.  Since portable code cannot
+  # rely on this symbol name, it's probably fine to never include it in
+  # preloaded symbol tables.
+  # Exclude shared library initialization/finalization symbols.
+dnl Note also adjust exclude_expsyms for C++ above.
+  extract_expsyms_cmds=
+
+  case $host_os in
+  cygwin* | mingw* | pw32* | cegcc*)
+    # FIXME: the MSVC++ port hasn't been tested in a loooong time
+    # When not using gcc, we currently assume that we are using
+    # Microsoft Visual C++.
+    if test "$GCC" != yes; then
+      with_gnu_ld=no
+    fi
+    ;;
+  interix*)
+    # we just hope/assume this is gcc and not c89 (= MSVC++)
+    with_gnu_ld=yes
+    ;;
+  openbsd*)
+    with_gnu_ld=no
+    ;;
+  esac
+
+  _LT_TAGVAR(ld_shlibs, $1)=yes
+
+  # On some targets, GNU ld is compatible enough with the native linker
+  # that we're better off using the native interface for both.
+  lt_use_gnu_ld_interface=no
+  if test "$with_gnu_ld" = yes; then
+    case $host_os in
+      aix*)
+	# The AIX port of GNU ld has always aspired to compatibility
+	# with the native linker.  However, as the warning in the GNU ld
+	# block says, versions before 2.19.5* couldn't really create working
+	# shared libraries, regardless of the interface used.
+	case `$LD -v 2>&1` in
+	  *\ \(GNU\ Binutils\)\ 2.19.5*) ;;
+	  *\ \(GNU\ Binutils\)\ 2.[[2-9]]*) ;;
+	  *\ \(GNU\ Binutils\)\ [[3-9]]*) ;;
+	  *)
+	    lt_use_gnu_ld_interface=yes
+	    ;;
+	esac
+	;;
+      *)
+	lt_use_gnu_ld_interface=yes
+	;;
+    esac
+  fi
+
+  if test "$lt_use_gnu_ld_interface" = yes; then
+    # If archive_cmds runs LD, not CC, wlarc should be empty
+    wlarc='${wl}'
+
+    # Set some defaults for GNU ld with shared library support. These
+    # are reset later if shared libraries are not supported. Putting them
+    # here allows them to be overridden if necessary.
+    runpath_var=LD_RUN_PATH
+    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+    # ancient GNU ld didn't support --whole-archive et. al.
+    if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then
+      _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+    else
+      _LT_TAGVAR(whole_archive_flag_spec, $1)=
+    fi
+    supports_anon_versioning=no
+    case `$LD -v 2>&1` in
+      *GNU\ gold*) supports_anon_versioning=yes ;;
+      *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
+      *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
+      *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
+      *\ 2.11.*) ;; # other 2.11 versions
+      *) supports_anon_versioning=yes ;;
+    esac
+
+    # See if GNU ld supports shared libraries.
+    case $host_os in
+    aix[[3-9]]*)
+      # On AIX/PPC, the GNU linker is very broken
+      if test "$host_cpu" != ia64; then
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	cat <<_LT_EOF 1>&2
+
+*** Warning: the GNU linker, at least up to release 2.19, is reported
+*** to be unable to reliably create shared libraries on AIX.
+*** Therefore, libtool is disabling shared libraries support.  If you
+*** really care for shared libraries, you may want to install binutils
+*** 2.20 or above, or modify your PATH so that a non-GNU linker is found.
+*** You will then need to restart the configuration process.
+
+_LT_EOF
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            _LT_TAGVAR(archive_expsym_cmds, $1)=''
+        ;;
+      m68k)
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+            _LT_TAGVAR(hardcode_minus_L, $1)=yes
+        ;;
+      esac
+      ;;
+
+    beos*)
+      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	# Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
+	# support --undefined.  This deserves some investigation.  FIXME
+	_LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    cygwin* | mingw* | pw32* | cegcc*)
+      # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+      # as there is no search path for DLLs.
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols'
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      _LT_TAGVAR(always_export_symbols, $1)=no
+      _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
+      _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname']
+
+      if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	# If the export-symbols file already is a .def file (1st line
+	# is EXPORTS), use it as is; otherwise, prepend...
+	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	  cp $export_symbols $output_objdir/$soname.def;
+	else
+	  echo EXPORTS > $output_objdir/$soname.def;
+	  cat $export_symbols >> $output_objdir/$soname.def;
+	fi~
+	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    haiku*)
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      ;;
+
+    interix[[3-9]]*)
+      _LT_TAGVAR(hardcode_direct, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+      # Instead, shared libraries are loaded at an image base (0x10000000 by
+      # default) and relocated if they conflict, which is a slow very memory
+      # consuming and fragmenting process.  To avoid this, we pick a random,
+      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      ;;
+
+    gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu)
+      tmp_diet=no
+      if test "$host_os" = linux-dietlibc; then
+	case $cc_basename in
+	  diet\ *) tmp_diet=yes;;	# linux-dietlibc with static linking (!diet-dyn)
+	esac
+      fi
+      if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \
+	 && test "$tmp_diet" = no
+      then
+	tmp_addflag=' $pic_flag'
+	tmp_sharedflag='-shared'
+	case $cc_basename,$host_cpu in
+        pgcc*)				# Portland Group C compiler
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  tmp_addflag=' $pic_flag'
+	  ;;
+	pgf77* | pgf90* | pgf95* | pgfortran*)
+					# Portland Group f77 and f90 compilers
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  tmp_addflag=' $pic_flag -Mnomain' ;;
+	ecc*,ia64* | icc*,ia64*)	# Intel C compiler on ia64
+	  tmp_addflag=' -i_dynamic' ;;
+	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
+	  tmp_addflag=' -i_dynamic -nofor_main' ;;
+	ifc* | ifort*)			# Intel Fortran compiler
+	  tmp_addflag=' -nofor_main' ;;
+	lf95*)				# Lahey Fortran 8.1
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)=
+	  tmp_sharedflag='--shared' ;;
+	xl[[cC]]* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below)
+	  tmp_sharedflag='-qmkshrobj'
+	  tmp_addflag= ;;
+	nvcc*)	# Cuda Compiler Driver 2.2
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  _LT_TAGVAR(compiler_needs_object, $1)=yes
+	  ;;
+	esac
+	case `$CC -V 2>&1 | sed 5q` in
+	*Sun\ C*)			# Sun C 5.9
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  _LT_TAGVAR(compiler_needs_object, $1)=yes
+	  tmp_sharedflag='-G' ;;
+	*Sun\ F*)			# Sun Fortran 8.3
+	  tmp_sharedflag='-G' ;;
+	esac
+	_LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+
+        if test "x$supports_anon_versioning" = xyes; then
+          _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
+	    cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+	    echo "local: *; };" >> $output_objdir/$libname.ver~
+	    $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+        fi
+
+	case $cc_basename in
+	xlf* | bgf* | bgxlf* | mpixlf*)
+	  # IBM XL Fortran 10.1 on PPC cannot create shared libs itself
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib'
+	  if test "x$supports_anon_versioning" = xyes; then
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
+	      cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+	      echo "local: *; };" >> $output_objdir/$libname.ver~
+	      $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
+	  fi
+	  ;;
+	esac
+      else
+        _LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    netbsd*)
+      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
+	wlarc=
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      fi
+      ;;
+
+    solaris*)
+      if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	cat <<_LT_EOF 1>&2
+
+*** Warning: The releases 2.8.* of the GNU linker cannot reliably
+*** create shared libraries on Solaris systems.  Therefore, libtool
+*** is disabling shared libraries support.  We urge you to upgrade GNU
+*** binutils to release 2.9.1 or newer.  Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+      elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
+      case `$LD -v 2>&1` in
+        *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*)
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	cat <<_LT_EOF 1>&2
+
+*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
+*** reliably create shared libraries on SCO systems.  Therefore, libtool
+*** is disabling shared libraries support.  We urge you to upgrade GNU
+*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+	;;
+	*)
+	  # For security reasons, it is highly recommended that you always
+	  # use absolute paths for naming shared libraries, and exclude the
+	  # DT_RUNPATH tag from executables and libraries.  But doing so
+	  # requires that you compile everything twice, which is a pain.
+	  if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	  else
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	  fi
+	;;
+      esac
+      ;;
+
+    sunos4*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+      wlarc=
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    *)
+      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+    esac
+
+    if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then
+      runpath_var=
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)=
+      _LT_TAGVAR(whole_archive_flag_spec, $1)=
+    fi
+  else
+    # PORTME fill in a description of your system's linker (not GNU ld)
+    case $host_os in
+    aix3*)
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      _LT_TAGVAR(always_export_symbols, $1)=yes
+      _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
+      # Note: this linker hardcodes the directories in LIBPATH if there
+      # are no directories specified by -L.
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+	# Neither direct hardcoding nor static linking is supported with a
+	# broken collect2.
+	_LT_TAGVAR(hardcode_direct, $1)=unsupported
+      fi
+      ;;
+
+    aix[[4-9]]*)
+      if test "$host_cpu" = ia64; then
+	# On IA64, the linker does run time linking by default, so we don't
+	# have to do anything special.
+	aix_use_runtimelinking=no
+	exp_sym_flag='-Bexport'
+	no_entry_flag=""
+      else
+	# If we're using GNU nm, then we don't want the "-C" option.
+	# -C means demangle to AIX nm, but means don't demangle with GNU nm
+	# Also, AIX nm treats weak defined symbols like other global
+	# defined symbols, whereas GNU nm marks them as "W".
+	if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
+	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+	else
+	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+	fi
+	aix_use_runtimelinking=no
+
+	# Test if we are trying to use run time linking or normal
+	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
+	# need to do runtime linking.
+	case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
+	  for ld_flag in $LDFLAGS; do
+	  if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
+	    aix_use_runtimelinking=yes
+	    break
+	  fi
+	  done
+	  ;;
+	esac
+
+	exp_sym_flag='-bexport'
+	no_entry_flag='-bnoentry'
+      fi
+
+      # When large executables or shared objects are built, AIX ld can
+      # have problems creating the table of contents.  If linking a library
+      # or program results in "error TOC overflow" add -mminimal-toc to
+      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
+      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+      _LT_TAGVAR(archive_cmds, $1)=''
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
+
+      if test "$GCC" = yes; then
+	case $host_os in aix4.[[012]]|aix4.[[012]].*)
+	# We only want to do this on AIX 4.2 and lower, the check
+	# below for broken collect2 doesn't work under 4.3+
+	  collect2name=`${CC} -print-prog-name=collect2`
+	  if test -f "$collect2name" &&
+	   strings "$collect2name" | $GREP resolve_lib_name >/dev/null
+	  then
+	  # We have reworked collect2
+	  :
+	  else
+	  # We have old collect2
+	  _LT_TAGVAR(hardcode_direct, $1)=unsupported
+	  # It fails to find uninstalled libraries when the uninstalled
+	  # path is not listed in the libpath.  Setting hardcode_minus_L
+	  # to unsupported forces relinking
+	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+	  _LT_TAGVAR(hardcode_libdir_separator, $1)=
+	  fi
+	  ;;
+	esac
+	shared_flag='-shared'
+	if test "$aix_use_runtimelinking" = yes; then
+	  shared_flag="$shared_flag "'${wl}-G'
+	fi
+      else
+	# not using gcc
+	if test "$host_cpu" = ia64; then
+	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+	# chokes on -Wl,-G. The following line is correct:
+	  shared_flag='-G'
+	else
+	  if test "$aix_use_runtimelinking" = yes; then
+	    shared_flag='${wl}-G'
+	  else
+	    shared_flag='${wl}-bM:SRE'
+	  fi
+	fi
+      fi
+
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
+      # It seems that -bexpall does not export symbols beginning with
+      # underscore (_), so it is better to generate a list of symbols to export.
+      _LT_TAGVAR(always_export_symbols, $1)=yes
+      if test "$aix_use_runtimelinking" = yes; then
+	# Warning - without using the other runtime loading flags (-brtl),
+	# -berok will link without error, but may produce a broken library.
+	_LT_TAGVAR(allow_undefined_flag, $1)='-berok'
+        # Determine the default libpath from the value encoded in an
+        # empty executable.
+        _LT_SYS_MODULE_PATH_AIX([$1])
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+      else
+	if test "$host_cpu" = ia64; then
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+	  _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
+	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+	else
+	 # Determine the default libpath from the value encoded in an
+	 # empty executable.
+	 _LT_SYS_MODULE_PATH_AIX([$1])
+	 _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+	  # Warning - without using the other run time loading flags,
+	  # -berok will link without error, but may produce a broken library.
+	  _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
+	  _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+	  if test "$with_gnu_ld" = yes; then
+	    # We only use this code for GNU lds that support --whole-archive.
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	  else
+	    # Exported symbols can be pulled into shared objects from archives
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+	  fi
+	  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+	  # This is similar to how AIX traditionally builds its shared libraries.
+	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+	fi
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            _LT_TAGVAR(archive_expsym_cmds, $1)=''
+        ;;
+      m68k)
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+            _LT_TAGVAR(hardcode_minus_L, $1)=yes
+        ;;
+      esac
+      ;;
+
+    bsdi[[45]]*)
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic
+      ;;
+
+    cygwin* | mingw* | pw32* | cegcc*)
+      # When not using gcc, we currently assume that we are using
+      # Microsoft Visual C++.
+      # hardcode_libdir_flag_spec is actually meaningless, as there is
+      # no search path for DLLs.
+      case $cc_basename in
+      cl*)
+	# Native MSVC
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	_LT_TAGVAR(always_export_symbols, $1)=yes
+	_LT_TAGVAR(file_list_spec, $1)='@'
+	# Tell ltmain to make .lib files, not .a files.
+	libext=lib
+	# Tell ltmain to make .dll files, not .so files.
+	shrext_cmds=".dll"
+	# FIXME: Setting linknames here is a bad hack.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
+	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	    sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
+	  else
+	    sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
+	  fi~
+	  $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
+	  linknames='
+	# The linker will not automatically build a static lib if we build a DLL.
+	# _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
+	_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+	_LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
+	_LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1,DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols'
+	# Don't use ranlib
+	_LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib'
+	_LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~
+	  lt_tool_outputfile="@TOOL_OUTPUT@"~
+	  case $lt_outputfile in
+	    *.exe|*.EXE) ;;
+	    *)
+	      lt_outputfile="$lt_outputfile.exe"
+	      lt_tool_outputfile="$lt_tool_outputfile.exe"
+	      ;;
+	  esac~
+	  if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
+	    $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
+	    $RM "$lt_outputfile.manifest";
+	  fi'
+	;;
+      *)
+	# Assume MSVC wrapper
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	# Tell ltmain to make .lib files, not .a files.
+	libext=lib
+	# Tell ltmain to make .dll files, not .so files.
+	shrext_cmds=".dll"
+	# FIXME: Setting linknames here is a bad hack.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames='
+	# The linker will automatically build a .lib file if we build a DLL.
+	_LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
+	# FIXME: Should let the user specify the lib program.
+	_LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs'
+	_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+	;;
+      esac
+      ;;
+
+    darwin* | rhapsody*)
+      _LT_DARWIN_LINKER_FEATURES($1)
+      ;;
+
+    dgux*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
+    # support.  Future versions do this automatically, but an explicit c++rt0.o
+    # does not break anything, and helps significantly (at the cost of a little
+    # extra space).
+    freebsd2.2*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
+    freebsd2.*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
+    freebsd* | dragonfly*)
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    hpux9*)
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+
+      # hardcode_minus_L: Not really in the search PATH,
+      # but as the default location of the library.
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+      ;;
+
+    hpux10*)
+      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
+      fi
+      if test "$with_gnu_ld" = no; then
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
+	_LT_TAGVAR(hardcode_direct, $1)=yes
+	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	# hardcode_minus_L: Not really in the search PATH,
+	# but as the default location of the library.
+	_LT_TAGVAR(hardcode_minus_L, $1)=yes
+      fi
+      ;;
+
+    hpux11*)
+      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
+	case $host_cpu in
+	hppa*64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	ia64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	esac
+      else
+	case $host_cpu in
+	hppa*64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	ia64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+	m4_if($1, [], [
+	  # Older versions of the 11.00 compiler do not understand -b yet
+	  # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does)
+	  _LT_LINKER_OPTION([if $CC understands -b],
+	    _LT_TAGVAR(lt_cv_prog_compiler__b, $1), [-b],
+	    [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'],
+	    [_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'])],
+	  [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'])
+	  ;;
+	esac
+      fi
+      if test "$with_gnu_ld" = no; then
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	case $host_cpu in
+	hppa*64*|ia64*)
+	  _LT_TAGVAR(hardcode_direct, $1)=no
+	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	  ;;
+	*)
+	  _LT_TAGVAR(hardcode_direct, $1)=yes
+	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+
+	  # hardcode_minus_L: Not really in the search PATH,
+	  # but as the default location of the library.
+	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
+	  ;;
+	esac
+      fi
+      ;;
+
+    irix5* | irix6* | nonstopux*)
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	# Try to use the -exported_symbol ld option, if it does not
+	# work, assume that -exports_file does not work either and
+	# implicitly export all symbols.
+	# This should be the same for all languages, so no per-tag cache variable.
+	AC_CACHE_CHECK([whether the $host_os linker accepts -exported_symbol],
+	  [lt_cv_irix_exported_symbol],
+	  [save_LDFLAGS="$LDFLAGS"
+	   LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null"
+	   AC_LINK_IFELSE(
+	     [AC_LANG_SOURCE(
+	        [AC_LANG_CASE([C], [[int foo (void) { return 0; }]],
+			      [C++], [[int foo (void) { return 0; }]],
+			      [Fortran 77], [[
+      subroutine foo
+      end]],
+			      [Fortran], [[
+      subroutine foo
+      end]])])],
+	      [lt_cv_irix_exported_symbol=yes],
+	      [lt_cv_irix_exported_symbol=no])
+           LDFLAGS="$save_LDFLAGS"])
+	if test "$lt_cv_irix_exported_symbol" = yes; then
+          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib'
+	fi
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib'
+      fi
+      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      _LT_TAGVAR(inherit_rpath, $1)=yes
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      ;;
+
+    netbsd*)
+      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'  # a.out
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags'      # ELF
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    newsos6)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    *nto* | *qnx*)
+      ;;
+
+    openbsd*)
+      if test -f /usr/libexec/ld.so; then
+	_LT_TAGVAR(hardcode_direct, $1)=yes
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	else
+	  case $host_os in
+	   openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*)
+	     _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	     ;;
+	   *)
+	     _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	     ;;
+	  esac
+	fi
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    os2*)
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
+      _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
+      ;;
+
+    osf3*)
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+      else
+	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+      fi
+      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      ;;
+
+    osf4* | osf5*)	# as osf3* with the addition of -msym flag
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      else
+	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~
+	$CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp'
+
+	# Both c and cxx compiler support -rpath directly
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+      fi
+      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      ;;
+
+    solaris*)
+      _LT_TAGVAR(no_undefined_flag, $1)=' -z defs'
+      if test "$GCC" = yes; then
+	wlarc='${wl}'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+      else
+	case `$CC -V 2>&1` in
+	*"Compilers 5.0"*)
+	  wlarc=''
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp'
+	  ;;
+	*)
+	  wlarc='${wl}'
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+	  ;;
+	esac
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      case $host_os in
+      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+      *)
+	# The compiler driver will combine and reorder linker options,
+	# but understands `-z linker_flag'.  GCC discards it without `$wl',
+	# but is careful enough not to reorder.
+	# Supported since Solaris 2.6 (maybe 2.5.1?)
+	if test "$GCC" = yes; then
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
+	else
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
+	fi
+	;;
+      esac
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      ;;
+
+    sunos4*)
+      if test "x$host_vendor" = xsequent; then
+	# Use $CC to link under sequent, because it throws in some extra .o
+	# files that make .init and .fini sections work.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    sysv4)
+      case $host_vendor in
+	sni)
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true???
+	;;
+	siemens)
+	  ## LD is ld it makes a PLAMLIB
+	  ## CC just makes a GrossModule.
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs'
+	  _LT_TAGVAR(hardcode_direct, $1)=no
+        ;;
+	motorola)
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie
+	;;
+      esac
+      runpath_var='LD_RUN_PATH'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    sysv4.3*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	_LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	runpath_var=LD_RUN_PATH
+	hardcode_runpath_var=yes
+	_LT_TAGVAR(ld_shlibs, $1)=yes
+      fi
+      ;;
+
+    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
+      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      runpath_var='LD_RUN_PATH'
+
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      fi
+      ;;
+
+    sysv5* | sco3.2v5* | sco5v6*)
+      # Note: We can NOT use -z defs as we might desire, because we do not
+      # link with -lc, and that would cause any symbols used from libc to
+      # always be unresolved, which means just about no library would
+      # ever link correctly.  If we're not using GNU ld we use -z text
+      # though, which does catch some bad symbols but isn't as heavy-handed
+      # as -z defs.
+      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+      runpath_var='LD_RUN_PATH'
+
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      fi
+      ;;
+
+    uts4*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    *)
+      _LT_TAGVAR(ld_shlibs, $1)=no
+      ;;
+    esac
+
+    if test x$host_vendor = xsni; then
+      case $host in
+      sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym'
+	;;
+      esac
+    fi
+  fi
+])
+AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
+test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+
+_LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld
+
+_LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl
+_LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl
+_LT_DECL([], [extract_expsyms_cmds], [2],
+    [The commands to extract the exported symbol list from a shared archive])
+
+#
+# Do we need to explicitly link libc?
+#
+case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in
+x|xyes)
+  # Assume -lc should be added
+  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+
+  if test "$enable_shared" = yes && test "$GCC" = yes; then
+    case $_LT_TAGVAR(archive_cmds, $1) in
+    *'~'*)
+      # FIXME: we may have to deal with multi-command sequences.
+      ;;
+    '$CC '*)
+      # Test whether the compiler implicitly links with -lc since on some
+      # systems, -lgcc has to come before -lc. If gcc already passes -lc
+      # to ld, don't add -lc before -lgcc.
+      AC_CACHE_CHECK([whether -lc should be explicitly linked in],
+	[lt_cv_]_LT_TAGVAR(archive_cmds_need_lc, $1),
+	[$RM conftest*
+	echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+	if AC_TRY_EVAL(ac_compile) 2>conftest.err; then
+	  soname=conftest
+	  lib=conftest
+	  libobjs=conftest.$ac_objext
+	  deplibs=
+	  wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1)
+	  pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1)
+	  compiler_flags=-v
+	  linker_flags=-v
+	  verstring=
+	  output_objdir=.
+	  libname=conftest
+	  lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1)
+	  _LT_TAGVAR(allow_undefined_flag, $1)=
+	  if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1)
+	  then
+	    lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+	  else
+	    lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+	  fi
+	  _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag
+	else
+	  cat conftest.err 1>&5
+	fi
+	$RM conftest*
+	])
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=$lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)
+      ;;
+    esac
+  fi
+  ;;
+esac
+
+_LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0],
+    [Whether or not to add -lc for building shared libraries])
+_LT_TAGDECL([allow_libtool_libs_with_static_runtimes],
+    [enable_shared_with_static_runtimes], [0],
+    [Whether or not to disallow shared libs when runtime libs are static])
+_LT_TAGDECL([], [export_dynamic_flag_spec], [1],
+    [Compiler flag to allow reflexive dlopens])
+_LT_TAGDECL([], [whole_archive_flag_spec], [1],
+    [Compiler flag to generate shared objects directly from archives])
+_LT_TAGDECL([], [compiler_needs_object], [1],
+    [Whether the compiler copes with passing no objects directly])
+_LT_TAGDECL([], [old_archive_from_new_cmds], [2],
+    [Create an old-style archive from a shared archive])
+_LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2],
+    [Create a temporary old-style archive to link instead of a shared archive])
+_LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive])
+_LT_TAGDECL([], [archive_expsym_cmds], [2])
+_LT_TAGDECL([], [module_cmds], [2],
+    [Commands used to build a loadable module if different from building
+    a shared archive.])
+_LT_TAGDECL([], [module_expsym_cmds], [2])
+_LT_TAGDECL([], [with_gnu_ld], [1],
+    [Whether we are building with GNU ld or not])
+_LT_TAGDECL([], [allow_undefined_flag], [1],
+    [Flag that allows shared libraries with undefined symbols to be built])
+_LT_TAGDECL([], [no_undefined_flag], [1],
+    [Flag that enforces no undefined symbols])
+_LT_TAGDECL([], [hardcode_libdir_flag_spec], [1],
+    [Flag to hardcode $libdir into a binary during linking.
+    This must work even if $libdir does not exist])
+_LT_TAGDECL([], [hardcode_libdir_separator], [1],
+    [Whether we need a single "-rpath" flag with a separated argument])
+_LT_TAGDECL([], [hardcode_direct], [0],
+    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
+    DIR into the resulting binary])
+_LT_TAGDECL([], [hardcode_direct_absolute], [0],
+    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
+    DIR into the resulting binary and the resulting library dependency is
+    "absolute", i.e impossible to change by setting ${shlibpath_var} if the
+    library is relocated])
+_LT_TAGDECL([], [hardcode_minus_L], [0],
+    [Set to "yes" if using the -LDIR flag during linking hardcodes DIR
+    into the resulting binary])
+_LT_TAGDECL([], [hardcode_shlibpath_var], [0],
+    [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR
+    into the resulting binary])
+_LT_TAGDECL([], [hardcode_automatic], [0],
+    [Set to "yes" if building a shared library automatically hardcodes DIR
+    into the library and all subsequent libraries and executables linked
+    against it])
+_LT_TAGDECL([], [inherit_rpath], [0],
+    [Set to yes if linker adds runtime paths of dependent libraries
+    to runtime path list])
+_LT_TAGDECL([], [link_all_deplibs], [0],
+    [Whether libtool must link a program against all its dependency libraries])
+_LT_TAGDECL([], [always_export_symbols], [0],
+    [Set to "yes" if exported symbols are required])
+_LT_TAGDECL([], [export_symbols_cmds], [2],
+    [The commands to list exported symbols])
+_LT_TAGDECL([], [exclude_expsyms], [1],
+    [Symbols that should not be listed in the preloaded symbols])
+_LT_TAGDECL([], [include_expsyms], [1],
+    [Symbols that must always be exported])
+_LT_TAGDECL([], [prelink_cmds], [2],
+    [Commands necessary for linking programs (against libraries) with templates])
+_LT_TAGDECL([], [postlink_cmds], [2],
+    [Commands necessary for finishing linking programs])
+_LT_TAGDECL([], [file_list_spec], [1],
+    [Specify filename containing input files])
+dnl FIXME: Not yet implemented
+dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1],
+dnl    [Compiler flag to generate thread safe objects])
+])# _LT_LINKER_SHLIBS
+
+
+# _LT_LANG_C_CONFIG([TAG])
+# ------------------------
+# Ensure that the configuration variables for a C compiler are suitably
+# defined.  These variables are subsequently used by _LT_CONFIG to write
+# the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_C_CONFIG],
+[m4_require([_LT_DECL_EGREP])dnl
+lt_save_CC="$CC"
+AC_LANG_PUSH(C)
+
+# Source file extension for C test sources.
+ac_ext=c
+
+# Object file extension for compiled C test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="int some_variable = 0;"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='int main(){return(0);}'
+
+_LT_TAG_COMPILER
+# Save the default compiler, since it gets overwritten when the other
+# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP.
+compiler_DEFAULT=$CC
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+## CAVEAT EMPTOR:
+## There is no encapsulation within the following macros, do not change
+## the running order or otherwise move them around unless you know exactly
+## what you are doing...
+if test -n "$compiler"; then
+  _LT_COMPILER_NO_RTTI($1)
+  _LT_COMPILER_PIC($1)
+  _LT_COMPILER_C_O($1)
+  _LT_COMPILER_FILE_LOCKS($1)
+  _LT_LINKER_SHLIBS($1)
+  _LT_SYS_DYNAMIC_LINKER($1)
+  _LT_LINKER_HARDCODE_LIBPATH($1)
+  LT_SYS_DLOPEN_SELF
+  _LT_CMD_STRIPLIB
+
+  # Report which library types will actually be built
+  AC_MSG_CHECKING([if libtool supports shared libraries])
+  AC_MSG_RESULT([$can_build_shared])
+
+  AC_MSG_CHECKING([whether to build shared libraries])
+  test "$can_build_shared" = "no" && enable_shared=no
+
+  # On AIX, shared libraries and static libraries use the same namespace, and
+  # are all built from PIC.
+  case $host_os in
+  aix3*)
+    test "$enable_shared" = yes && enable_static=no
+    if test -n "$RANLIB"; then
+      archive_cmds="$archive_cmds~\$RANLIB \$lib"
+      postinstall_cmds='$RANLIB $lib'
+    fi
+    ;;
+
+  aix[[4-9]]*)
+    if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+      test "$enable_shared" = yes && enable_static=no
+    fi
+    ;;
+  esac
+  AC_MSG_RESULT([$enable_shared])
+
+  AC_MSG_CHECKING([whether to build static libraries])
+  # Make sure either enable_shared or enable_static is yes.
+  test "$enable_shared" = yes || enable_static=yes
+  AC_MSG_RESULT([$enable_static])
+
+  _LT_CONFIG($1)
+fi
+AC_LANG_POP
+CC="$lt_save_CC"
+])# _LT_LANG_C_CONFIG
+
+
+# _LT_LANG_CXX_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for a C++ compiler are suitably
+# defined.  These variables are subsequently used by _LT_CONFIG to write
+# the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_CXX_CONFIG],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_PATH_MANIFEST_TOOL])dnl
+if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
+    ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
+    (test "X$CXX" != "Xg++"))) ; then
+  AC_PROG_CXXCPP
+else
+  _lt_caught_CXX_error=yes
+fi
+
+AC_LANG_PUSH(C++)
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_TAGVAR(allow_undefined_flag, $1)=
+_LT_TAGVAR(always_export_symbols, $1)=no
+_LT_TAGVAR(archive_expsym_cmds, $1)=
+_LT_TAGVAR(compiler_needs_object, $1)=no
+_LT_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_TAGVAR(hardcode_direct, $1)=no
+_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_TAGVAR(hardcode_minus_L, $1)=no
+_LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+_LT_TAGVAR(hardcode_automatic, $1)=no
+_LT_TAGVAR(inherit_rpath, $1)=no
+_LT_TAGVAR(module_cmds, $1)=
+_LT_TAGVAR(module_expsym_cmds, $1)=
+_LT_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+_LT_TAGVAR(no_undefined_flag, $1)=
+_LT_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for C++ test sources.
+ac_ext=cpp
+
+# Object file extension for compiled C++ test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# No sense in running all these tests if we already determined that
+# the CXX compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_caught_CXX_error" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="int some_variable = 0;"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }'
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+  _LT_TAG_COMPILER
+
+  # save warnings/boilerplate of simple test code
+  _LT_COMPILER_BOILERPLATE
+  _LT_LINKER_BOILERPLATE
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC=$CC
+  lt_save_CFLAGS=$CFLAGS
+  lt_save_LD=$LD
+  lt_save_GCC=$GCC
+  GCC=$GXX
+  lt_save_with_gnu_ld=$with_gnu_ld
+  lt_save_path_LD=$lt_cv_path_LD
+  if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
+    lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx
+  else
+    $as_unset lt_cv_prog_gnu_ld
+  fi
+  if test -n "${lt_cv_path_LDCXX+set}"; then
+    lt_cv_path_LD=$lt_cv_path_LDCXX
+  else
+    $as_unset lt_cv_path_LD
+  fi
+  test -z "${LDCXX+set}" || LD=$LDCXX
+  CC=${CXX-"c++"}
+  CFLAGS=$CXXFLAGS
+  compiler=$CC
+  _LT_TAGVAR(compiler, $1)=$CC
+  _LT_CC_BASENAME([$compiler])
+
+  if test -n "$compiler"; then
+    # We don't want -fno-exception when compiling C++ code, so set the
+    # no_builtin_flag separately
+    if test "$GXX" = yes; then
+      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
+    else
+      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
+    fi
+
+    if test "$GXX" = yes; then
+      # Set up default GNU C++ configuration
+
+      LT_PATH_LD
+
+      # Check if GNU C++ uses GNU ld as the underlying linker, since the
+      # archiving commands below assume that GNU ld is being used.
+      if test "$with_gnu_ld" = yes; then
+        _LT_TAGVAR(archive_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+
+        # If archive_cmds runs LD, not CC, wlarc should be empty
+        # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
+        #     investigate it a little bit more. (MM)
+        wlarc='${wl}'
+
+        # ancient GNU ld didn't support --whole-archive et. al.
+        if eval "`$CC -print-prog-name=ld` --help 2>&1" |
+	  $GREP 'no-whole-archive' > /dev/null; then
+          _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+        else
+          _LT_TAGVAR(whole_archive_flag_spec, $1)=
+        fi
+      else
+        with_gnu_ld=no
+        wlarc=
+
+        # A generic and very simple default shared library creation
+        # command for GNU C++ for the case where it uses the native
+        # linker, instead of GNU ld.  If possible, this setting should
+        # overridden to take advantage of the native linker features on
+        # the platform it is being used on.
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+      fi
+
+      # Commands to make compiler produce verbose output that lists
+      # what "hidden" libraries, object files and flags are used when
+      # linking a shared library.
+      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+
+    else
+      GXX=no
+      with_gnu_ld=no
+      wlarc=
+    fi
+
+    # PORTME: fill in a description of your system's C++ link characteristics
+    AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
+    _LT_TAGVAR(ld_shlibs, $1)=yes
+    case $host_os in
+      aix3*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+      aix[[4-9]]*)
+        if test "$host_cpu" = ia64; then
+          # On IA64, the linker does run time linking by default, so we don't
+          # have to do anything special.
+          aix_use_runtimelinking=no
+          exp_sym_flag='-Bexport'
+          no_entry_flag=""
+        else
+          aix_use_runtimelinking=no
+
+          # Test if we are trying to use run time linking or normal
+          # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+          # need to do runtime linking.
+          case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
+	    for ld_flag in $LDFLAGS; do
+	      case $ld_flag in
+	      *-brtl*)
+	        aix_use_runtimelinking=yes
+	        break
+	        ;;
+	      esac
+	    done
+	    ;;
+          esac
+
+          exp_sym_flag='-bexport'
+          no_entry_flag='-bnoentry'
+        fi
+
+        # When large executables or shared objects are built, AIX ld can
+        # have problems creating the table of contents.  If linking a library
+        # or program results in "error TOC overflow" add -mminimal-toc to
+        # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
+        # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+        _LT_TAGVAR(archive_cmds, $1)=''
+        _LT_TAGVAR(hardcode_direct, $1)=yes
+        _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+        _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+        _LT_TAGVAR(link_all_deplibs, $1)=yes
+        _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
+
+        if test "$GXX" = yes; then
+          case $host_os in aix4.[[012]]|aix4.[[012]].*)
+          # We only want to do this on AIX 4.2 and lower, the check
+          # below for broken collect2 doesn't work under 4.3+
+	  collect2name=`${CC} -print-prog-name=collect2`
+	  if test -f "$collect2name" &&
+	     strings "$collect2name" | $GREP resolve_lib_name >/dev/null
+	  then
+	    # We have reworked collect2
+	    :
+	  else
+	    # We have old collect2
+	    _LT_TAGVAR(hardcode_direct, $1)=unsupported
+	    # It fails to find uninstalled libraries when the uninstalled
+	    # path is not listed in the libpath.  Setting hardcode_minus_L
+	    # to unsupported forces relinking
+	    _LT_TAGVAR(hardcode_minus_L, $1)=yes
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=
+	  fi
+          esac
+          shared_flag='-shared'
+	  if test "$aix_use_runtimelinking" = yes; then
+	    shared_flag="$shared_flag "'${wl}-G'
+	  fi
+        else
+          # not using gcc
+          if test "$host_cpu" = ia64; then
+	  # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+	  # chokes on -Wl,-G. The following line is correct:
+	  shared_flag='-G'
+          else
+	    if test "$aix_use_runtimelinking" = yes; then
+	      shared_flag='${wl}-G'
+	    else
+	      shared_flag='${wl}-bM:SRE'
+	    fi
+          fi
+        fi
+
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
+        # It seems that -bexpall does not export symbols beginning with
+        # underscore (_), so it is better to generate a list of symbols to
+	# export.
+        _LT_TAGVAR(always_export_symbols, $1)=yes
+        if test "$aix_use_runtimelinking" = yes; then
+          # Warning - without using the other runtime loading flags (-brtl),
+          # -berok will link without error, but may produce a broken library.
+          _LT_TAGVAR(allow_undefined_flag, $1)='-berok'
+          # Determine the default libpath from the value encoded in an empty
+          # executable.
+          _LT_SYS_MODULE_PATH_AIX([$1])
+          _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+
+          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+        else
+          if test "$host_cpu" = ia64; then
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+	    _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
+	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+          else
+	    # Determine the default libpath from the value encoded in an
+	    # empty executable.
+	    _LT_SYS_MODULE_PATH_AIX([$1])
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+	    # Warning - without using the other run time loading flags,
+	    # -berok will link without error, but may produce a broken library.
+	    _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
+	    _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+	    if test "$with_gnu_ld" = yes; then
+	      # We only use this code for GNU lds that support --whole-archive.
+	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	    else
+	      # Exported symbols can be pulled into shared objects from archives
+	      _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+	    fi
+	    _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+	    # This is similar to how AIX traditionally builds its shared
+	    # libraries.
+	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+          fi
+        fi
+        ;;
+
+      beos*)
+	if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	  # Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
+	  # support --undefined.  This deserves some investigation.  FIXME
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	else
+	  _LT_TAGVAR(ld_shlibs, $1)=no
+	fi
+	;;
+
+      chorus*)
+        case $cc_basename in
+          *)
+	  # FIXME: insert proper C++ library support
+	  _LT_TAGVAR(ld_shlibs, $1)=no
+	  ;;
+        esac
+        ;;
+
+      cygwin* | mingw* | pw32* | cegcc*)
+	case $GXX,$cc_basename in
+	,cl* | no,cl*)
+	  # Native MSVC
+	  # hardcode_libdir_flag_spec is actually meaningless, as there is
+	  # no search path for DLLs.
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	  _LT_TAGVAR(always_export_symbols, $1)=yes
+	  _LT_TAGVAR(file_list_spec, $1)='@'
+	  # Tell ltmain to make .lib files, not .a files.
+	  libext=lib
+	  # Tell ltmain to make .dll files, not .so files.
+	  shrext_cmds=".dll"
+	  # FIXME: Setting linknames here is a bad hack.
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	      $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
+	    else
+	      $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
+	    fi~
+	    $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
+	    linknames='
+	  # The linker will not automatically build a static lib if we build a DLL.
+	  # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
+	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+	  # Don't use ranlib
+	  _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib'
+	  _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~
+	    lt_tool_outputfile="@TOOL_OUTPUT@"~
+	    case $lt_outputfile in
+	      *.exe|*.EXE) ;;
+	      *)
+		lt_outputfile="$lt_outputfile.exe"
+		lt_tool_outputfile="$lt_tool_outputfile.exe"
+		;;
+	    esac~
+	    func_to_tool_file "$lt_outputfile"~
+	    if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
+	      $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
+	      $RM "$lt_outputfile.manifest";
+	    fi'
+	  ;;
+	*)
+	  # g++
+	  # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+	  # as there is no search path for DLLs.
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols'
+	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	  _LT_TAGVAR(always_export_symbols, $1)=no
+	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+
+	  if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	    # If the export-symbols file already is a .def file (1st line
+	    # is EXPORTS), use it as is; otherwise, prepend...
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	      cp $export_symbols $output_objdir/$soname.def;
+	    else
+	      echo EXPORTS > $output_objdir/$soname.def;
+	      cat $export_symbols >> $output_objdir/$soname.def;
+	    fi~
+	    $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	  else
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	  fi
+	  ;;
+	esac
+	;;
+      darwin* | rhapsody*)
+        _LT_DARWIN_LINKER_FEATURES($1)
+	;;
+
+      dgux*)
+        case $cc_basename in
+          ec++*)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          ghcx*)
+	    # Green Hills C++ Compiler
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+        esac
+        ;;
+
+      freebsd2.*)
+        # C++ shared libraries reported to be fairly broken before
+	# switch to ELF
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+
+      freebsd-elf*)
+        _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+        ;;
+
+      freebsd* | dragonfly*)
+        # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF
+        # conventions
+        _LT_TAGVAR(ld_shlibs, $1)=yes
+        ;;
+
+      gnu*)
+        ;;
+
+      haiku*)
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+        _LT_TAGVAR(link_all_deplibs, $1)=yes
+        ;;
+
+      hpux9*)
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+        _LT_TAGVAR(hardcode_direct, $1)=yes
+        _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
+				             # but as the default
+				             # location of the library.
+
+        case $cc_basename in
+          CC*)
+            # FIXME: insert proper C++ library support
+            _LT_TAGVAR(ld_shlibs, $1)=no
+            ;;
+          aCC*)
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+            # Commands to make compiler produce verbose output that lists
+            # what "hidden" libraries, object files and flags are used when
+            # linking a shared library.
+            #
+            # There doesn't appear to be a way to prevent this compiler from
+            # explicitly linking system object files so we need to strip them
+            # from the output so that they don't get included in the library
+            # dependencies.
+            output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+            ;;
+          *)
+            if test "$GXX" = yes; then
+              _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+            else
+              # FIXME: insert proper C++ library support
+              _LT_TAGVAR(ld_shlibs, $1)=no
+            fi
+            ;;
+        esac
+        ;;
+
+      hpux10*|hpux11*)
+        if test $with_gnu_ld = no; then
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+	  _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+          case $host_cpu in
+            hppa*64*|ia64*)
+              ;;
+            *)
+	      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+              ;;
+          esac
+        fi
+        case $host_cpu in
+          hppa*64*|ia64*)
+            _LT_TAGVAR(hardcode_direct, $1)=no
+            _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+            ;;
+          *)
+            _LT_TAGVAR(hardcode_direct, $1)=yes
+            _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+            _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
+					         # but as the default
+					         # location of the library.
+            ;;
+        esac
+
+        case $cc_basename in
+          CC*)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          aCC*)
+	    case $host_cpu in
+	      hppa*64*)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        ;;
+	      ia64*)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        ;;
+	      *)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        ;;
+	    esac
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+	    ;;
+          *)
+	    if test "$GXX" = yes; then
+	      if test $with_gnu_ld = no; then
+	        case $host_cpu in
+	          hppa*64*)
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            ;;
+	          ia64*)
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            ;;
+	          *)
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            ;;
+	        esac
+	      fi
+	    else
+	      # FIXME: insert proper C++ library support
+	      _LT_TAGVAR(ld_shlibs, $1)=no
+	    fi
+	    ;;
+        esac
+        ;;
+
+      interix[[3-9]]*)
+	_LT_TAGVAR(hardcode_direct, $1)=no
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	# Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+	# Instead, shared libraries are loaded at an image base (0x10000000 by
+	# default) and relocated if they conflict, which is a slow very memory
+	# consuming and fragmenting process.  To avoid this, we pick a random,
+	# 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+	# time.  Moving up from 0x10000000 also allows more sbrk(2) space.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+	;;
+      irix5* | irix6*)
+        case $cc_basename in
+          CC*)
+	    # SGI C++
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+
+	    # Archives containing C++ object files must be created using
+	    # "CC -ar", where "CC" is the IRIX C++ compiler.  This is
+	    # necessary to make sure instantiated templates are included
+	    # in the archive.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs'
+	    ;;
+          *)
+	    if test "$GXX" = yes; then
+	      if test "$with_gnu_ld" = no; then
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	      else
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib'
+	      fi
+	    fi
+	    _LT_TAGVAR(link_all_deplibs, $1)=yes
+	    ;;
+        esac
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+        _LT_TAGVAR(inherit_rpath, $1)=yes
+        ;;
+
+      linux* | k*bsd*-gnu | kopensolaris*-gnu)
+        case $cc_basename in
+          KCC*)
+	    # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+	    # KCC will only create a shared library if the output file
+	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
+	    # to its proper name (with version) after linking.
+	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib'
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+
+	    # Archives containing C++ object files must be created using
+	    # "CC -Bstatic", where "CC" is the KAI C++ compiler.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs'
+	    ;;
+	  icpc* | ecpc* )
+	    # Intel C++
+	    with_gnu_ld=yes
+	    # version 8.0 and above of icpc choke on multiply defined symbols
+	    # if we add $predep_objects and $postdep_objects, however 7.1 and
+	    # earlier do not add the objects themselves.
+	    case `$CC -V 2>&1` in
+	      *"Version 7."*)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+		;;
+	      *)  # Version 8.0 or newer
+	        tmp_idyn=
+	        case $host_cpu in
+		  ia64*) tmp_idyn=' -i_dynamic';;
+		esac
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+		;;
+	    esac
+	    _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	    ;;
+          pgCC* | pgcpp*)
+            # Portland Group C++ compiler
+	    case `$CC -V` in
+	    *pgCC\ [[1-5]].* | *pgcpp\ [[1-5]].*)
+	      _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~
+		compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"'
+	      _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~
+		$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~
+		$RANLIB $oldlib'
+	      _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
+		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
+		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+	      ;;
+	    *) # Version 6 and above use weak symbols
+	      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+	      ;;
+	    esac
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+            ;;
+	  cxx*)
+	    # Compaq C++
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname  -o $lib ${wl}-retain-symbols-file $wl$export_symbols'
+
+	    runpath_var=LD_RUN_PATH
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed'
+	    ;;
+	  xl* | mpixl* | bgxl*)
+	    # IBM XL 8.0 on PPC, with GNU ld
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	    if test "x$supports_anon_versioning" = xyes; then
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
+		cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+		echo "local: *; };" >> $output_objdir/$libname.ver~
+		$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+	    fi
+	    ;;
+	  *)
+	    case `$CC -V 2>&1 | sed 5q` in
+	    *Sun\ C*)
+	      # Sun C++ 5.9
+	      _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
+	      _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols'
+	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	      _LT_TAGVAR(compiler_needs_object, $1)=yes
+
+	      # Not sure whether something based on
+	      # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1
+	      # would be better.
+	      output_verbose_link_cmd='func_echo_all'
+
+	      # Archives containing C++ object files must be created using
+	      # "CC -xar", where "CC" is the Sun C++ compiler.  This is
+	      # necessary to make sure instantiated templates are included
+	      # in the archive.
+	      _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
+	      ;;
+	    esac
+	    ;;
+	esac
+	;;
+
+      lynxos*)
+        # FIXME: insert proper C++ library support
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	;;
+
+      m88k*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+	;;
+
+      mvs*)
+        case $cc_basename in
+          cxx*)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+	  *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+	esac
+	;;
+
+      netbsd*)
+        if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable  -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags'
+	  wlarc=
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	  _LT_TAGVAR(hardcode_direct, $1)=yes
+	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	fi
+	# Workaround some broken pre-1.5 toolchains
+	output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"'
+	;;
+
+      *nto* | *qnx*)
+        _LT_TAGVAR(ld_shlibs, $1)=yes
+	;;
+
+      openbsd2*)
+        # C++ shared libraries are fairly broken
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	;;
+
+      openbsd*)
+	if test -f /usr/libexec/ld.so; then
+	  _LT_TAGVAR(hardcode_direct, $1)=yes
+	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+	  fi
+	  output_verbose_link_cmd=func_echo_all
+	else
+	  _LT_TAGVAR(ld_shlibs, $1)=no
+	fi
+	;;
+
+      osf3* | osf4* | osf5*)
+        case $cc_basename in
+          KCC*)
+	    # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+	    # KCC will only create a shared library if the output file
+	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
+	    # to its proper name (with version) after linking.
+	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	    # Archives containing C++ object files must be created using
+	    # the KAI C++ compiler.
+	    case $host in
+	      osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;;
+	      *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;;
+	    esac
+	    ;;
+          RCC*)
+	    # Rational C++ 2.4.1
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          cxx*)
+	    case $host in
+	      osf3*)
+	        _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+		;;
+	      *)
+	        _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	        _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
+	          echo "-hidden">> $lib.exp~
+	          $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp  `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~
+	          $RM $lib.exp'
+	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+		;;
+	    esac
+
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+	    ;;
+	  *)
+	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+	      _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	      case $host in
+	        osf3*)
+	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+		  ;;
+	        *)
+	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+		  ;;
+	      esac
+
+	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	      # Commands to make compiler produce verbose output that lists
+	      # what "hidden" libraries, object files and flags are used when
+	      # linking a shared library.
+	      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+
+	    else
+	      # FIXME: insert proper C++ library support
+	      _LT_TAGVAR(ld_shlibs, $1)=no
+	    fi
+	    ;;
+        esac
+        ;;
+
+      psos*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+
+      sunos4*)
+        case $cc_basename in
+          CC*)
+	    # Sun C++ 4.x
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          lcc*)
+	    # Lucid
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+        esac
+        ;;
+
+      solaris*)
+        case $cc_basename in
+          CC* | sunCC*)
+	    # Sun C++ 4.2, 5.x and Centerline C++
+            _LT_TAGVAR(archive_cmds_need_lc,$1)=yes
+	    _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag}  -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	      $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	    _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	    case $host_os in
+	      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+	      *)
+		# The compiler driver will combine and reorder linker options,
+		# but understands `-z linker_flag'.
+	        # Supported since Solaris 2.6 (maybe 2.5.1?)
+		_LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
+	        ;;
+	    esac
+	    _LT_TAGVAR(link_all_deplibs, $1)=yes
+
+	    output_verbose_link_cmd='func_echo_all'
+
+	    # Archives containing C++ object files must be created using
+	    # "CC -xar", where "CC" is the Sun C++ compiler.  This is
+	    # necessary to make sure instantiated templates are included
+	    # in the archive.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
+	    ;;
+          gcx*)
+	    # Green Hills C++ Compiler
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+
+	    # The C++ compiler must be used to create the archive.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs'
+	    ;;
+          *)
+	    # GNU C++ compiler with Solaris linker
+	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+	      _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs'
+	      if $CC --version | $GREP -v '^2\.7' > /dev/null; then
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+		  $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+	        # Commands to make compiler produce verbose output that lists
+	        # what "hidden" libraries, object files and flags are used when
+	        # linking a shared library.
+	        output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+	      else
+	        # g++ 2.7 appears to require `-G' NOT `-shared' on this
+	        # platform.
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+		  $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+	        # Commands to make compiler produce verbose output that lists
+	        # what "hidden" libraries, object files and flags are used when
+	        # linking a shared library.
+	        output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+	      fi
+
+	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir'
+	      case $host_os in
+		solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+		*)
+		  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
+		  ;;
+	      esac
+	    fi
+	    ;;
+        esac
+        ;;
+
+    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
+      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      runpath_var='LD_RUN_PATH'
+
+      case $cc_basename in
+        CC*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+      esac
+      ;;
+
+      sysv5* | sco3.2v5* | sco5v6*)
+	# Note: We can NOT use -z defs as we might desire, because we do not
+	# link with -lc, and that would cause any symbols used from libc to
+	# always be unresolved, which means just about no library would
+	# ever link correctly.  If we're not using GNU ld we use -z text
+	# though, which does catch some bad symbols but isn't as heavy-handed
+	# as -z defs.
+	_LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+	_LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+	_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
+	_LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+	_LT_TAGVAR(link_all_deplibs, $1)=yes
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+	runpath_var='LD_RUN_PATH'
+
+	case $cc_basename in
+          CC*)
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -Tprelink_objects $oldobjs~
+	      '"$_LT_TAGVAR(old_archive_cmds, $1)"
+	    _LT_TAGVAR(reload_cmds, $1)='$CC -Tprelink_objects $reload_objs~
+	      '"$_LT_TAGVAR(reload_cmds, $1)"
+	    ;;
+	  *)
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    ;;
+	esac
+      ;;
+
+      tandem*)
+        case $cc_basename in
+          NCC*)
+	    # NonStop-UX NCC 3.20
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+        esac
+        ;;
+
+      vxworks*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+
+      *)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+    esac
+
+    AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
+    test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+
+    _LT_TAGVAR(GCC, $1)="$GXX"
+    _LT_TAGVAR(LD, $1)="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    _LT_SYS_HIDDEN_LIBDEPS($1)
+    _LT_COMPILER_PIC($1)
+    _LT_COMPILER_C_O($1)
+    _LT_COMPILER_FILE_LOCKS($1)
+    _LT_LINKER_SHLIBS($1)
+    _LT_SYS_DYNAMIC_LINKER($1)
+    _LT_LINKER_HARDCODE_LIBPATH($1)
+
+    _LT_CONFIG($1)
+  fi # test -n "$compiler"
+
+  CC=$lt_save_CC
+  CFLAGS=$lt_save_CFLAGS
+  LDCXX=$LD
+  LD=$lt_save_LD
+  GCC=$lt_save_GCC
+  with_gnu_ld=$lt_save_with_gnu_ld
+  lt_cv_path_LDCXX=$lt_cv_path_LD
+  lt_cv_path_LD=$lt_save_path_LD
+  lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
+  lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
+fi # test "$_lt_caught_CXX_error" != yes
+
+AC_LANG_POP
+])# _LT_LANG_CXX_CONFIG
+
+
+# _LT_FUNC_STRIPNAME_CNF
+# ----------------------
+# func_stripname_cnf prefix suffix name
+# strip PREFIX and SUFFIX off of NAME.
+# PREFIX and SUFFIX must not contain globbing or regex special
+# characters, hashes, percent signs, but SUFFIX may contain a leading
+# dot (in which case that matches only a dot).
+#
+# This function is identical to the (non-XSI) version of func_stripname,
+# except this one can be used by m4 code that may be executed by configure,
+# rather than the libtool script.
+m4_defun([_LT_FUNC_STRIPNAME_CNF],[dnl
+AC_REQUIRE([_LT_DECL_SED])
+AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])
+func_stripname_cnf ()
+{
+  case ${2} in
+  .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;;
+  *)  func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;;
+  esac
+} # func_stripname_cnf
+])# _LT_FUNC_STRIPNAME_CNF
+
+# _LT_SYS_HIDDEN_LIBDEPS([TAGNAME])
+# ---------------------------------
+# Figure out "hidden" library dependencies from verbose
+# compiler output when linking a shared library.
+# Parse the compiler output and extract the necessary
+# objects, libraries and library flags.
+m4_defun([_LT_SYS_HIDDEN_LIBDEPS],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+AC_REQUIRE([_LT_FUNC_STRIPNAME_CNF])dnl
+# Dependencies to place before and after the object being linked:
+_LT_TAGVAR(predep_objects, $1)=
+_LT_TAGVAR(postdep_objects, $1)=
+_LT_TAGVAR(predeps, $1)=
+_LT_TAGVAR(postdeps, $1)=
+_LT_TAGVAR(compiler_lib_search_path, $1)=
+
+dnl we can't use the lt_simple_compile_test_code here,
+dnl because it contains code intended for an executable,
+dnl not a library.  It's possible we should let each
+dnl tag define a new lt_????_link_test_code variable,
+dnl but it's only used here...
+m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF
+int a;
+void foo (void) { a = 0; }
+_LT_EOF
+], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF
+class Foo
+{
+public:
+  Foo (void) { a = 0; }
+private:
+  int a;
+};
+_LT_EOF
+], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF
+      subroutine foo
+      implicit none
+      integer*4 a
+      a=0
+      return
+      end
+_LT_EOF
+], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF
+      subroutine foo
+      implicit none
+      integer a
+      a=0
+      return
+      end
+_LT_EOF
+], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF
+public class foo {
+  private int a;
+  public void bar (void) {
+    a = 0;
+  }
+};
+_LT_EOF
+], [$1], [GO], [cat > conftest.$ac_ext <<_LT_EOF
+package foo
+func foo() {
+}
+_LT_EOF
+])
+
+_lt_libdeps_save_CFLAGS=$CFLAGS
+case "$CC $CFLAGS " in #(
+*\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;;
+*\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;;
+*\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;;
+esac
+
+dnl Parse the compiler output and extract the necessary
+dnl objects, libraries and library flags.
+if AC_TRY_EVAL(ac_compile); then
+  # Parse the compiler output and extract the necessary
+  # objects, libraries and library flags.
+
+  # Sentinel used to keep track of whether or not we are before
+  # the conftest object file.
+  pre_test_object_deps_done=no
+
+  for p in `eval "$output_verbose_link_cmd"`; do
+    case ${prev}${p} in
+
+    -L* | -R* | -l*)
+       # Some compilers place space between "-{L,R}" and the path.
+       # Remove the space.
+       if test $p = "-L" ||
+          test $p = "-R"; then
+	 prev=$p
+	 continue
+       fi
+
+       # Expand the sysroot to ease extracting the directories later.
+       if test -z "$prev"; then
+         case $p in
+         -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;;
+         -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;;
+         -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;;
+         esac
+       fi
+       case $p in
+       =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;;
+       esac
+       if test "$pre_test_object_deps_done" = no; then
+	 case ${prev} in
+	 -L | -R)
+	   # Internal compiler library paths should come after those
+	   # provided the user.  The postdeps already come after the
+	   # user supplied libs so there is no need to process them.
+	   if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then
+	     _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}"
+	   else
+	     _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}"
+	   fi
+	   ;;
+	 # The "-l" case would never come before the object being
+	 # linked, so don't bother handling this case.
+	 esac
+       else
+	 if test -z "$_LT_TAGVAR(postdeps, $1)"; then
+	   _LT_TAGVAR(postdeps, $1)="${prev}${p}"
+	 else
+	   _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}"
+	 fi
+       fi
+       prev=
+       ;;
+
+    *.lto.$objext) ;; # Ignore GCC LTO objects
+    *.$objext)
+       # This assumes that the test object file only shows up
+       # once in the compiler output.
+       if test "$p" = "conftest.$objext"; then
+	 pre_test_object_deps_done=yes
+	 continue
+       fi
+
+       if test "$pre_test_object_deps_done" = no; then
+	 if test -z "$_LT_TAGVAR(predep_objects, $1)"; then
+	   _LT_TAGVAR(predep_objects, $1)="$p"
+	 else
+	   _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p"
+	 fi
+       else
+	 if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then
+	   _LT_TAGVAR(postdep_objects, $1)="$p"
+	 else
+	   _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p"
+	 fi
+       fi
+       ;;
+
+    *) ;; # Ignore the rest.
+
+    esac
+  done
+
+  # Clean up.
+  rm -f a.out a.exe
+else
+  echo "libtool.m4: error: problem compiling $1 test program"
+fi
+
+$RM -f confest.$objext
+CFLAGS=$_lt_libdeps_save_CFLAGS
+
+# PORTME: override above test on systems where it is broken
+m4_if([$1], [CXX],
+[case $host_os in
+interix[[3-9]]*)
+  # Interix 3.5 installs completely hosed .la files for C++, so rather than
+  # hack all around it, let's just trust "g++" to DTRT.
+  _LT_TAGVAR(predep_objects,$1)=
+  _LT_TAGVAR(postdep_objects,$1)=
+  _LT_TAGVAR(postdeps,$1)=
+  ;;
+
+linux*)
+  case `$CC -V 2>&1 | sed 5q` in
+  *Sun\ C*)
+    # Sun C++ 5.9
+
+    # The more standards-conforming stlport4 library is
+    # incompatible with the Cstd library. Avoid specifying
+    # it if it's in CXXFLAGS. Ignore libCrun as
+    # -library=stlport4 depends on it.
+    case " $CXX $CXXFLAGS " in
+    *" -library=stlport4 "*)
+      solaris_use_stlport4=yes
+      ;;
+    esac
+
+    if test "$solaris_use_stlport4" != yes; then
+      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
+    fi
+    ;;
+  esac
+  ;;
+
+solaris*)
+  case $cc_basename in
+  CC* | sunCC*)
+    # The more standards-conforming stlport4 library is
+    # incompatible with the Cstd library. Avoid specifying
+    # it if it's in CXXFLAGS. Ignore libCrun as
+    # -library=stlport4 depends on it.
+    case " $CXX $CXXFLAGS " in
+    *" -library=stlport4 "*)
+      solaris_use_stlport4=yes
+      ;;
+    esac
+
+    # Adding this requires a known-good setup of shared libraries for
+    # Sun compiler versions before 5.6, else PIC objects from an old
+    # archive will be linked into the output, leading to subtle bugs.
+    if test "$solaris_use_stlport4" != yes; then
+      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
+    fi
+    ;;
+  esac
+  ;;
+esac
+])
+
+case " $_LT_TAGVAR(postdeps, $1) " in
+*" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;;
+esac
+ _LT_TAGVAR(compiler_lib_search_dirs, $1)=
+if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then
+ _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'`
+fi
+_LT_TAGDECL([], [compiler_lib_search_dirs], [1],
+    [The directories searched by this compiler when creating a shared library])
+_LT_TAGDECL([], [predep_objects], [1],
+    [Dependencies to place before and after the objects being linked to
+    create a shared library])
+_LT_TAGDECL([], [postdep_objects], [1])
+_LT_TAGDECL([], [predeps], [1])
+_LT_TAGDECL([], [postdeps], [1])
+_LT_TAGDECL([], [compiler_lib_search_path], [1],
+    [The library search path used internally by the compiler when linking
+    a shared library])
+])# _LT_SYS_HIDDEN_LIBDEPS
+
+
+# _LT_LANG_F77_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for a Fortran 77 compiler are
+# suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_F77_CONFIG],
+[AC_LANG_PUSH(Fortran 77)
+if test -z "$F77" || test "X$F77" = "Xno"; then
+  _lt_disable_F77=yes
+fi
+
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_TAGVAR(allow_undefined_flag, $1)=
+_LT_TAGVAR(always_export_symbols, $1)=no
+_LT_TAGVAR(archive_expsym_cmds, $1)=
+_LT_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_TAGVAR(hardcode_direct, $1)=no
+_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_TAGVAR(hardcode_minus_L, $1)=no
+_LT_TAGVAR(hardcode_automatic, $1)=no
+_LT_TAGVAR(inherit_rpath, $1)=no
+_LT_TAGVAR(module_cmds, $1)=
+_LT_TAGVAR(module_expsym_cmds, $1)=
+_LT_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+_LT_TAGVAR(no_undefined_flag, $1)=
+_LT_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for f77 test sources.
+ac_ext=f
+
+# Object file extension for compiled f77 test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# No sense in running all these tests if we already determined that
+# the F77 compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_disable_F77" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="\
+      subroutine t
+      return
+      end
+"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code="\
+      program t
+      end
+"
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+  _LT_TAG_COMPILER
+
+  # save warnings/boilerplate of simple test code
+  _LT_COMPILER_BOILERPLATE
+  _LT_LINKER_BOILERPLATE
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC="$CC"
+  lt_save_GCC=$GCC
+  lt_save_CFLAGS=$CFLAGS
+  CC=${F77-"f77"}
+  CFLAGS=$FFLAGS
+  compiler=$CC
+  _LT_TAGVAR(compiler, $1)=$CC
+  _LT_CC_BASENAME([$compiler])
+  GCC=$G77
+  if test -n "$compiler"; then
+    AC_MSG_CHECKING([if libtool supports shared libraries])
+    AC_MSG_RESULT([$can_build_shared])
+
+    AC_MSG_CHECKING([whether to build shared libraries])
+    test "$can_build_shared" = "no" && enable_shared=no
+
+    # On AIX, shared libraries and static libraries use the same namespace, and
+    # are all built from PIC.
+    case $host_os in
+      aix3*)
+        test "$enable_shared" = yes && enable_static=no
+        if test -n "$RANLIB"; then
+          archive_cmds="$archive_cmds~\$RANLIB \$lib"
+          postinstall_cmds='$RANLIB $lib'
+        fi
+        ;;
+      aix[[4-9]]*)
+	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+	  test "$enable_shared" = yes && enable_static=no
+	fi
+        ;;
+    esac
+    AC_MSG_RESULT([$enable_shared])
+
+    AC_MSG_CHECKING([whether to build static libraries])
+    # Make sure either enable_shared or enable_static is yes.
+    test "$enable_shared" = yes || enable_static=yes
+    AC_MSG_RESULT([$enable_static])
+
+    _LT_TAGVAR(GCC, $1)="$G77"
+    _LT_TAGVAR(LD, $1)="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    _LT_COMPILER_PIC($1)
+    _LT_COMPILER_C_O($1)
+    _LT_COMPILER_FILE_LOCKS($1)
+    _LT_LINKER_SHLIBS($1)
+    _LT_SYS_DYNAMIC_LINKER($1)
+    _LT_LINKER_HARDCODE_LIBPATH($1)
+
+    _LT_CONFIG($1)
+  fi # test -n "$compiler"
+
+  GCC=$lt_save_GCC
+  CC="$lt_save_CC"
+  CFLAGS="$lt_save_CFLAGS"
+fi # test "$_lt_disable_F77" != yes
+
+AC_LANG_POP
+])# _LT_LANG_F77_CONFIG
+
+
+# _LT_LANG_FC_CONFIG([TAG])
+# -------------------------
+# Ensure that the configuration variables for a Fortran compiler are
+# suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_FC_CONFIG],
+[AC_LANG_PUSH(Fortran)
+
+if test -z "$FC" || test "X$FC" = "Xno"; then
+  _lt_disable_FC=yes
+fi
+
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_TAGVAR(allow_undefined_flag, $1)=
+_LT_TAGVAR(always_export_symbols, $1)=no
+_LT_TAGVAR(archive_expsym_cmds, $1)=
+_LT_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_TAGVAR(hardcode_direct, $1)=no
+_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_TAGVAR(hardcode_minus_L, $1)=no
+_LT_TAGVAR(hardcode_automatic, $1)=no
+_LT_TAGVAR(inherit_rpath, $1)=no
+_LT_TAGVAR(module_cmds, $1)=
+_LT_TAGVAR(module_expsym_cmds, $1)=
+_LT_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+_LT_TAGVAR(no_undefined_flag, $1)=
+_LT_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for fc test sources.
+ac_ext=${ac_fc_srcext-f}
+
+# Object file extension for compiled fc test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# No sense in running all these tests if we already determined that
+# the FC compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_disable_FC" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="\
+      subroutine t
+      return
+      end
+"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code="\
+      program t
+      end
+"
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+  _LT_TAG_COMPILER
+
+  # save warnings/boilerplate of simple test code
+  _LT_COMPILER_BOILERPLATE
+  _LT_LINKER_BOILERPLATE
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC="$CC"
+  lt_save_GCC=$GCC
+  lt_save_CFLAGS=$CFLAGS
+  CC=${FC-"f95"}
+  CFLAGS=$FCFLAGS
+  compiler=$CC
+  GCC=$ac_cv_fc_compiler_gnu
+
+  _LT_TAGVAR(compiler, $1)=$CC
+  _LT_CC_BASENAME([$compiler])
+
+  if test -n "$compiler"; then
+    AC_MSG_CHECKING([if libtool supports shared libraries])
+    AC_MSG_RESULT([$can_build_shared])
+
+    AC_MSG_CHECKING([whether to build shared libraries])
+    test "$can_build_shared" = "no" && enable_shared=no
+
+    # On AIX, shared libraries and static libraries use the same namespace, and
+    # are all built from PIC.
+    case $host_os in
+      aix3*)
+        test "$enable_shared" = yes && enable_static=no
+        if test -n "$RANLIB"; then
+          archive_cmds="$archive_cmds~\$RANLIB \$lib"
+          postinstall_cmds='$RANLIB $lib'
+        fi
+        ;;
+      aix[[4-9]]*)
+	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+	  test "$enable_shared" = yes && enable_static=no
+	fi
+        ;;
+    esac
+    AC_MSG_RESULT([$enable_shared])
+
+    AC_MSG_CHECKING([whether to build static libraries])
+    # Make sure either enable_shared or enable_static is yes.
+    test "$enable_shared" = yes || enable_static=yes
+    AC_MSG_RESULT([$enable_static])
+
+    _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu"
+    _LT_TAGVAR(LD, $1)="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    _LT_SYS_HIDDEN_LIBDEPS($1)
+    _LT_COMPILER_PIC($1)
+    _LT_COMPILER_C_O($1)
+    _LT_COMPILER_FILE_LOCKS($1)
+    _LT_LINKER_SHLIBS($1)
+    _LT_SYS_DYNAMIC_LINKER($1)
+    _LT_LINKER_HARDCODE_LIBPATH($1)
+
+    _LT_CONFIG($1)
+  fi # test -n "$compiler"
+
+  GCC=$lt_save_GCC
+  CC=$lt_save_CC
+  CFLAGS=$lt_save_CFLAGS
+fi # test "$_lt_disable_FC" != yes
+
+AC_LANG_POP
+])# _LT_LANG_FC_CONFIG
+
+
+# _LT_LANG_GCJ_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for the GNU Java Compiler compiler
+# are suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_GCJ_CONFIG],
+[AC_REQUIRE([LT_PROG_GCJ])dnl
+AC_LANG_SAVE
+
+# Source file extension for Java test sources.
+ac_ext=java
+
+# Object file extension for compiled Java test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="class foo {}"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }'
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_TAG_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC=$CC
+lt_save_CFLAGS=$CFLAGS
+lt_save_GCC=$GCC
+GCC=yes
+CC=${GCJ-"gcj"}
+CFLAGS=$GCJFLAGS
+compiler=$CC
+_LT_TAGVAR(compiler, $1)=$CC
+_LT_TAGVAR(LD, $1)="$LD"
+_LT_CC_BASENAME([$compiler])
+
+# GCJ did not exist at the time GCC didn't implicitly link libc in.
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+
+## CAVEAT EMPTOR:
+## There is no encapsulation within the following macros, do not change
+## the running order or otherwise move them around unless you know exactly
+## what you are doing...
+if test -n "$compiler"; then
+  _LT_COMPILER_NO_RTTI($1)
+  _LT_COMPILER_PIC($1)
+  _LT_COMPILER_C_O($1)
+  _LT_COMPILER_FILE_LOCKS($1)
+  _LT_LINKER_SHLIBS($1)
+  _LT_LINKER_HARDCODE_LIBPATH($1)
+
+  _LT_CONFIG($1)
+fi
+
+AC_LANG_RESTORE
+
+GCC=$lt_save_GCC
+CC=$lt_save_CC
+CFLAGS=$lt_save_CFLAGS
+])# _LT_LANG_GCJ_CONFIG
+
+
+# _LT_LANG_GO_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for the GNU Go compiler
+# are suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_GO_CONFIG],
+[AC_REQUIRE([LT_PROG_GO])dnl
+AC_LANG_SAVE
+
+# Source file extension for Go test sources.
+ac_ext=go
+
+# Object file extension for compiled Go test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="package main; func main() { }"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='package main; func main() { }'
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_TAG_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC=$CC
+lt_save_CFLAGS=$CFLAGS
+lt_save_GCC=$GCC
+GCC=yes
+CC=${GOC-"gccgo"}
+CFLAGS=$GOFLAGS
+compiler=$CC
+_LT_TAGVAR(compiler, $1)=$CC
+_LT_TAGVAR(LD, $1)="$LD"
+_LT_CC_BASENAME([$compiler])
+
+# Go did not exist at the time GCC didn't implicitly link libc in.
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+
+## CAVEAT EMPTOR:
+## There is no encapsulation within the following macros, do not change
+## the running order or otherwise move them around unless you know exactly
+## what you are doing...
+if test -n "$compiler"; then
+  _LT_COMPILER_NO_RTTI($1)
+  _LT_COMPILER_PIC($1)
+  _LT_COMPILER_C_O($1)
+  _LT_COMPILER_FILE_LOCKS($1)
+  _LT_LINKER_SHLIBS($1)
+  _LT_LINKER_HARDCODE_LIBPATH($1)
+
+  _LT_CONFIG($1)
+fi
+
+AC_LANG_RESTORE
+
+GCC=$lt_save_GCC
+CC=$lt_save_CC
+CFLAGS=$lt_save_CFLAGS
+])# _LT_LANG_GO_CONFIG
+
+
+# _LT_LANG_RC_CONFIG([TAG])
+# -------------------------
+# Ensure that the configuration variables for the Windows resource compiler
+# are suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_RC_CONFIG],
+[AC_REQUIRE([LT_PROG_RC])dnl
+AC_LANG_SAVE
+
+# Source file extension for RC test sources.
+ac_ext=rc
+
+# Object file extension for compiled RC test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }'
+
+# Code to be used in simple link tests
+lt_simple_link_test_code="$lt_simple_compile_test_code"
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_TAG_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+lt_save_CFLAGS=$CFLAGS
+lt_save_GCC=$GCC
+GCC=
+CC=${RC-"windres"}
+CFLAGS=
+compiler=$CC
+_LT_TAGVAR(compiler, $1)=$CC
+_LT_CC_BASENAME([$compiler])
+_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
+
+if test -n "$compiler"; then
+  :
+  _LT_CONFIG($1)
+fi
+
+GCC=$lt_save_GCC
+AC_LANG_RESTORE
+CC=$lt_save_CC
+CFLAGS=$lt_save_CFLAGS
+])# _LT_LANG_RC_CONFIG
+
+
+# LT_PROG_GCJ
+# -----------
+AC_DEFUN([LT_PROG_GCJ],
+[m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ],
+  [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ],
+    [AC_CHECK_TOOL(GCJ, gcj,)
+      test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2"
+      AC_SUBST(GCJFLAGS)])])[]dnl
+])
+
+# Old name:
+AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([LT_AC_PROG_GCJ], [])
+
+
+# LT_PROG_GO
+# ----------
+AC_DEFUN([LT_PROG_GO],
+[AC_CHECK_TOOL(GOC, gccgo,)
+])
+
+
+# LT_PROG_RC
+# ----------
+AC_DEFUN([LT_PROG_RC],
+[AC_CHECK_TOOL(RC, windres,)
+])
+
+# Old name:
+AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([LT_AC_PROG_RC], [])
+
+
+# _LT_DECL_EGREP
+# --------------
+# If we don't have a new enough Autoconf to choose the best grep
+# available, choose the one first in the user's PATH.
+m4_defun([_LT_DECL_EGREP],
+[AC_REQUIRE([AC_PROG_EGREP])dnl
+AC_REQUIRE([AC_PROG_FGREP])dnl
+test -z "$GREP" && GREP=grep
+_LT_DECL([], [GREP], [1], [A grep program that handles long lines])
+_LT_DECL([], [EGREP], [1], [An ERE matcher])
+_LT_DECL([], [FGREP], [1], [A literal string matcher])
+dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too
+AC_SUBST([GREP])
+])
+
+
+# _LT_DECL_OBJDUMP
+# --------------
+# If we don't have a new enough Autoconf to choose the best objdump
+# available, choose the one first in the user's PATH.
+m4_defun([_LT_DECL_OBJDUMP],
+[AC_CHECK_TOOL(OBJDUMP, objdump, false)
+test -z "$OBJDUMP" && OBJDUMP=objdump
+_LT_DECL([], [OBJDUMP], [1], [An object symbol dumper])
+AC_SUBST([OBJDUMP])
+])
+
+# _LT_DECL_DLLTOOL
+# ----------------
+# Ensure DLLTOOL variable is set.
+m4_defun([_LT_DECL_DLLTOOL],
+[AC_CHECK_TOOL(DLLTOOL, dlltool, false)
+test -z "$DLLTOOL" && DLLTOOL=dlltool
+_LT_DECL([], [DLLTOOL], [1], [DLL creation program])
+AC_SUBST([DLLTOOL])
+])
+
+# _LT_DECL_SED
+# ------------
+# Check for a fully-functional sed program, that truncates
+# as few characters as possible.  Prefer GNU sed if found.
+m4_defun([_LT_DECL_SED],
+[AC_PROG_SED
+test -z "$SED" && SED=sed
+Xsed="$SED -e 1s/^X//"
+_LT_DECL([], [SED], [1], [A sed program that does not truncate output])
+_LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"],
+    [Sed that helps us avoid accidentally triggering echo(1) options like -n])
+])# _LT_DECL_SED
+
+m4_ifndef([AC_PROG_SED], [
+############################################################
+# NOTE: This macro has been submitted for inclusion into   #
+#  GNU Autoconf as AC_PROG_SED.  When it is available in   #
+#  a released version of Autoconf we should remove this    #
+#  macro and use it instead.                               #
+############################################################
+
+m4_defun([AC_PROG_SED],
+[AC_MSG_CHECKING([for a sed that does not truncate output])
+AC_CACHE_VAL(lt_cv_path_SED,
+[# Loop through the user's path and test for sed and gsed.
+# Then use that list of sed's as ones to test for truncation.
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for lt_ac_prog in sed gsed; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then
+        lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext"
+      fi
+    done
+  done
+done
+IFS=$as_save_IFS
+lt_ac_max=0
+lt_ac_count=0
+# Add /usr/xpg4/bin/sed as it is typically found on Solaris
+# along with /bin/sed that truncates output.
+for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
+  test ! -f $lt_ac_sed && continue
+  cat /dev/null > conftest.in
+  lt_ac_count=0
+  echo $ECHO_N "0123456789$ECHO_C" >conftest.in
+  # Check for GNU sed and select it if it is found.
+  if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then
+    lt_cv_path_SED=$lt_ac_sed
+    break
+  fi
+  while true; do
+    cat conftest.in conftest.in >conftest.tmp
+    mv conftest.tmp conftest.in
+    cp conftest.in conftest.nl
+    echo >>conftest.nl
+    $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break
+    cmp -s conftest.out conftest.nl || break
+    # 10000 chars as input seems more than enough
+    test $lt_ac_count -gt 10 && break
+    lt_ac_count=`expr $lt_ac_count + 1`
+    if test $lt_ac_count -gt $lt_ac_max; then
+      lt_ac_max=$lt_ac_count
+      lt_cv_path_SED=$lt_ac_sed
+    fi
+  done
+done
+])
+SED=$lt_cv_path_SED
+AC_SUBST([SED])
+AC_MSG_RESULT([$SED])
+])#AC_PROG_SED
+])#m4_ifndef
+
+# Old name:
+AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([LT_AC_PROG_SED], [])
+
+
+# _LT_CHECK_SHELL_FEATURES
+# ------------------------
+# Find out whether the shell is Bourne or XSI compatible,
+# or has some other useful features.
+m4_defun([_LT_CHECK_SHELL_FEATURES],
+[AC_MSG_CHECKING([whether the shell understands some XSI constructs])
+# Try some XSI features
+xsi_shell=no
+( _lt_dummy="a/b/c"
+  test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \
+      = c,a/b,b/c, \
+    && eval 'test $(( 1 + 1 )) -eq 2 \
+    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
+  && xsi_shell=yes
+AC_MSG_RESULT([$xsi_shell])
+_LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell'])
+
+AC_MSG_CHECKING([whether the shell understands "+="])
+lt_shell_append=no
+( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \
+    >/dev/null 2>&1 \
+  && lt_shell_append=yes
+AC_MSG_RESULT([$lt_shell_append])
+_LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append'])
+
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+  lt_unset=unset
+else
+  lt_unset=false
+fi
+_LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl
+
+# test EBCDIC or ASCII
+case `echo X|tr X '\101'` in
+ A) # ASCII based system
+    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
+  lt_SP2NL='tr \040 \012'
+  lt_NL2SP='tr \015\012 \040\040'
+  ;;
+ *) # EBCDIC based system
+  lt_SP2NL='tr \100 \n'
+  lt_NL2SP='tr \r\n \100\100'
+  ;;
+esac
+_LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl
+_LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl
+])# _LT_CHECK_SHELL_FEATURES
+
+
+# _LT_PROG_FUNCTION_REPLACE (FUNCNAME, REPLACEMENT-BODY)
+# ------------------------------------------------------
+# In `$cfgfile', look for function FUNCNAME delimited by `^FUNCNAME ()$' and
+# '^} FUNCNAME ', and replace its body with REPLACEMENT-BODY.
+m4_defun([_LT_PROG_FUNCTION_REPLACE],
+[dnl {
+sed -e '/^$1 ()$/,/^} # $1 /c\
+$1 ()\
+{\
+m4_bpatsubsts([$2], [$], [\\], [^\([	 ]\)], [\\\1])
+} # Extended-shell $1 implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
+])
+
+
+# _LT_PROG_REPLACE_SHELLFNS
+# -------------------------
+# Replace existing portable implementations of several shell functions with
+# equivalent extended shell implementations where those features are available..
+m4_defun([_LT_PROG_REPLACE_SHELLFNS],
+[if test x"$xsi_shell" = xyes; then
+  _LT_PROG_FUNCTION_REPLACE([func_dirname], [dnl
+    case ${1} in
+      */*) func_dirname_result="${1%/*}${2}" ;;
+      *  ) func_dirname_result="${3}" ;;
+    esac])
+
+  _LT_PROG_FUNCTION_REPLACE([func_basename], [dnl
+    func_basename_result="${1##*/}"])
+
+  _LT_PROG_FUNCTION_REPLACE([func_dirname_and_basename], [dnl
+    case ${1} in
+      */*) func_dirname_result="${1%/*}${2}" ;;
+      *  ) func_dirname_result="${3}" ;;
+    esac
+    func_basename_result="${1##*/}"])
+
+  _LT_PROG_FUNCTION_REPLACE([func_stripname], [dnl
+    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are
+    # positional parameters, so assign one to ordinary parameter first.
+    func_stripname_result=${3}
+    func_stripname_result=${func_stripname_result#"${1}"}
+    func_stripname_result=${func_stripname_result%"${2}"}])
+
+  _LT_PROG_FUNCTION_REPLACE([func_split_long_opt], [dnl
+    func_split_long_opt_name=${1%%=*}
+    func_split_long_opt_arg=${1#*=}])
+
+  _LT_PROG_FUNCTION_REPLACE([func_split_short_opt], [dnl
+    func_split_short_opt_arg=${1#??}
+    func_split_short_opt_name=${1%"$func_split_short_opt_arg"}])
+
+  _LT_PROG_FUNCTION_REPLACE([func_lo2o], [dnl
+    case ${1} in
+      *.lo) func_lo2o_result=${1%.lo}.${objext} ;;
+      *)    func_lo2o_result=${1} ;;
+    esac])
+
+  _LT_PROG_FUNCTION_REPLACE([func_xform], [    func_xform_result=${1%.*}.lo])
+
+  _LT_PROG_FUNCTION_REPLACE([func_arith], [    func_arith_result=$(( $[*] ))])
+
+  _LT_PROG_FUNCTION_REPLACE([func_len], [    func_len_result=${#1}])
+fi
+
+if test x"$lt_shell_append" = xyes; then
+  _LT_PROG_FUNCTION_REPLACE([func_append], [    eval "${1}+=\\${2}"])
+
+  _LT_PROG_FUNCTION_REPLACE([func_append_quoted], [dnl
+    func_quote_for_eval "${2}"
+dnl m4 expansion turns \\\\ into \\, and then the shell eval turns that into \
+    eval "${1}+=\\\\ \\$func_quote_for_eval_result"])
+
+  # Save a `func_append' function call where possible by direct use of '+='
+  sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \
+    && mv -f "$cfgfile.tmp" "$cfgfile" \
+      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+  test 0 -eq $? || _lt_function_replace_fail=:
+else
+  # Save a `func_append' function call even when '+=' is not available
+  sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \
+    && mv -f "$cfgfile.tmp" "$cfgfile" \
+      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+  test 0 -eq $? || _lt_function_replace_fail=:
+fi
+
+if test x"$_lt_function_replace_fail" = x":"; then
+  AC_MSG_WARN([Unable to substitute extended shell functions in $ofile])
+fi
+])
+
+# _LT_PATH_CONVERSION_FUNCTIONS
+# -----------------------------
+# Determine which file name conversion functions should be used by
+# func_to_host_file (and, implicitly, by func_to_host_path).  These are needed
+# for certain cross-compile configurations and native mingw.
+m4_defun([_LT_PATH_CONVERSION_FUNCTIONS],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+AC_MSG_CHECKING([how to convert $build file names to $host format])
+AC_CACHE_VAL(lt_cv_to_host_file_cmd,
+[case $host in
+  *-*-mingw* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32
+        ;;
+      *-*-cygwin* )
+        lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32
+        ;;
+      * ) # otherwise, assume *nix
+        lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32
+        ;;
+    esac
+    ;;
+  *-*-cygwin* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin
+        ;;
+      *-*-cygwin* )
+        lt_cv_to_host_file_cmd=func_convert_file_noop
+        ;;
+      * ) # otherwise, assume *nix
+        lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin
+        ;;
+    esac
+    ;;
+  * ) # unhandled hosts (and "normal" native builds)
+    lt_cv_to_host_file_cmd=func_convert_file_noop
+    ;;
+esac
+])
+to_host_file_cmd=$lt_cv_to_host_file_cmd
+AC_MSG_RESULT([$lt_cv_to_host_file_cmd])
+_LT_DECL([to_host_file_cmd], [lt_cv_to_host_file_cmd],
+         [0], [convert $build file names to $host format])dnl
+
+AC_MSG_CHECKING([how to convert $build file names to toolchain format])
+AC_CACHE_VAL(lt_cv_to_tool_file_cmd,
+[#assume ordinary cross tools, or native build.
+lt_cv_to_tool_file_cmd=func_convert_file_noop
+case $host in
+  *-*-mingw* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32
+        ;;
+    esac
+    ;;
+esac
+])
+to_tool_file_cmd=$lt_cv_to_tool_file_cmd
+AC_MSG_RESULT([$lt_cv_to_tool_file_cmd])
+_LT_DECL([to_tool_file_cmd], [lt_cv_to_tool_file_cmd],
+         [0], [convert $build files to toolchain format])dnl
+])# _LT_PATH_CONVERSION_FUNCTIONS
diff --git a/hdrl/m4macros/ltoptions.m4 b/hdrl/m4macros/ltoptions.m4
new file mode 100644
index 0000000..5d9acd8
--- /dev/null
+++ b/hdrl/m4macros/ltoptions.m4
@@ -0,0 +1,384 @@
+# Helper functions for option handling.                    -*- Autoconf -*-
+#
+#   Copyright (C) 2004, 2005, 2007, 2008, 2009 Free Software Foundation,
+#   Inc.
+#   Written by Gary V. Vaughan, 2004
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# serial 7 ltoptions.m4
+
+# This is to help aclocal find these macros, as it can't see m4_define.
+AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])])
+
+
+# _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME)
+# ------------------------------------------
+m4_define([_LT_MANGLE_OPTION],
+[[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])])
+
+
+# _LT_SET_OPTION(MACRO-NAME, OPTION-NAME)
+# ---------------------------------------
+# Set option OPTION-NAME for macro MACRO-NAME, and if there is a
+# matching handler defined, dispatch to it.  Other OPTION-NAMEs are
+# saved as a flag.
+m4_define([_LT_SET_OPTION],
+[m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl
+m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]),
+        _LT_MANGLE_DEFUN([$1], [$2]),
+    [m4_warning([Unknown $1 option `$2'])])[]dnl
+])
+
+
+# _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET])
+# ------------------------------------------------------------
+# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise.
+m4_define([_LT_IF_OPTION],
+[m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])])
+
+
+# _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET)
+# -------------------------------------------------------
+# Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME
+# are set.
+m4_define([_LT_UNLESS_OPTIONS],
+[m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
+	    [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option),
+		      [m4_define([$0_found])])])[]dnl
+m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3
+])[]dnl
+])
+
+
+# _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST)
+# ----------------------------------------
+# OPTION-LIST is a space-separated list of Libtool options associated
+# with MACRO-NAME.  If any OPTION has a matching handler declared with
+# LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about
+# the unknown option and exit.
+m4_defun([_LT_SET_OPTIONS],
+[# Set options
+m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
+    [_LT_SET_OPTION([$1], _LT_Option)])
+
+m4_if([$1],[LT_INIT],[
+  dnl
+  dnl Simply set some default values (i.e off) if boolean options were not
+  dnl specified:
+  _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no
+  ])
+  _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no
+  ])
+  dnl
+  dnl If no reference was made to various pairs of opposing options, then
+  dnl we run the default mode handler for the pair.  For example, if neither
+  dnl `shared' nor `disable-shared' was passed, we enable building of shared
+  dnl archives by default:
+  _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED])
+  _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC])
+  _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC])
+  _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install],
+  		   [_LT_ENABLE_FAST_INSTALL])
+  ])
+])# _LT_SET_OPTIONS
+
+
+## --------------------------------- ##
+## Macros to handle LT_INIT options. ##
+## --------------------------------- ##
+
+# _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME)
+# -----------------------------------------
+m4_define([_LT_MANGLE_DEFUN],
+[[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])])
+
+
+# LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE)
+# -----------------------------------------------
+m4_define([LT_OPTION_DEFINE],
+[m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl
+])# LT_OPTION_DEFINE
+
+
+# dlopen
+# ------
+LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes
+])
+
+AU_DEFUN([AC_LIBTOOL_DLOPEN],
+[_LT_SET_OPTION([LT_INIT], [dlopen])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you
+put the `dlopen' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], [])
+
+
+# win32-dll
+# ---------
+# Declare package support for building win32 dll's.
+LT_OPTION_DEFINE([LT_INIT], [win32-dll],
+[enable_win32_dll=yes
+
+case $host in
+*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*)
+  AC_CHECK_TOOL(AS, as, false)
+  AC_CHECK_TOOL(DLLTOOL, dlltool, false)
+  AC_CHECK_TOOL(OBJDUMP, objdump, false)
+  ;;
+esac
+
+test -z "$AS" && AS=as
+_LT_DECL([], [AS],      [1], [Assembler program])dnl
+
+test -z "$DLLTOOL" && DLLTOOL=dlltool
+_LT_DECL([], [DLLTOOL], [1], [DLL creation program])dnl
+
+test -z "$OBJDUMP" && OBJDUMP=objdump
+_LT_DECL([], [OBJDUMP], [1], [Object dumper program])dnl
+])# win32-dll
+
+AU_DEFUN([AC_LIBTOOL_WIN32_DLL],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+_LT_SET_OPTION([LT_INIT], [win32-dll])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you
+put the `win32-dll' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], [])
+
+
+# _LT_ENABLE_SHARED([DEFAULT])
+# ----------------------------
+# implement the --enable-shared flag, and supports the `shared' and
+# `disable-shared' LT_INIT options.
+# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
+m4_define([_LT_ENABLE_SHARED],
+[m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl
+AC_ARG_ENABLE([shared],
+    [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@],
+	[build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])],
+    [p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_shared=yes ;;
+    no) enable_shared=no ;;
+    *)
+      enable_shared=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_shared=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
+    [enable_shared=]_LT_ENABLE_SHARED_DEFAULT)
+
+    _LT_DECL([build_libtool_libs], [enable_shared], [0],
+	[Whether or not to build shared libraries])
+])# _LT_ENABLE_SHARED
+
+LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])])
+LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])])
+
+# Old names:
+AC_DEFUN([AC_ENABLE_SHARED],
+[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared])
+])
+
+AC_DEFUN([AC_DISABLE_SHARED],
+[_LT_SET_OPTION([LT_INIT], [disable-shared])
+])
+
+AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)])
+AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_ENABLE_SHARED], [])
+dnl AC_DEFUN([AM_DISABLE_SHARED], [])
+
+
+
+# _LT_ENABLE_STATIC([DEFAULT])
+# ----------------------------
+# implement the --enable-static flag, and support the `static' and
+# `disable-static' LT_INIT options.
+# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
+m4_define([_LT_ENABLE_STATIC],
+[m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl
+AC_ARG_ENABLE([static],
+    [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@],
+	[build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])],
+    [p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_static=yes ;;
+    no) enable_static=no ;;
+    *)
+     enable_static=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_static=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
+    [enable_static=]_LT_ENABLE_STATIC_DEFAULT)
+
+    _LT_DECL([build_old_libs], [enable_static], [0],
+	[Whether or not to build static libraries])
+])# _LT_ENABLE_STATIC
+
+LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])])
+LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])])
+
+# Old names:
+AC_DEFUN([AC_ENABLE_STATIC],
+[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static])
+])
+
+AC_DEFUN([AC_DISABLE_STATIC],
+[_LT_SET_OPTION([LT_INIT], [disable-static])
+])
+
+AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)])
+AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_ENABLE_STATIC], [])
+dnl AC_DEFUN([AM_DISABLE_STATIC], [])
+
+
+
+# _LT_ENABLE_FAST_INSTALL([DEFAULT])
+# ----------------------------------
+# implement the --enable-fast-install flag, and support the `fast-install'
+# and `disable-fast-install' LT_INIT options.
+# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
+m4_define([_LT_ENABLE_FAST_INSTALL],
+[m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl
+AC_ARG_ENABLE([fast-install],
+    [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@],
+    [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])],
+    [p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_fast_install=yes ;;
+    no) enable_fast_install=no ;;
+    *)
+      enable_fast_install=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_fast_install=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
+    [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT)
+
+_LT_DECL([fast_install], [enable_fast_install], [0],
+	 [Whether or not to optimize for fast installation])dnl
+])# _LT_ENABLE_FAST_INSTALL
+
+LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])])
+LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])])
+
+# Old names:
+AU_DEFUN([AC_ENABLE_FAST_INSTALL],
+[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you put
+the `fast-install' option into LT_INIT's first parameter.])
+])
+
+AU_DEFUN([AC_DISABLE_FAST_INSTALL],
+[_LT_SET_OPTION([LT_INIT], [disable-fast-install])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you put
+the `disable-fast-install' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], [])
+dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], [])
+
+
+# _LT_WITH_PIC([MODE])
+# --------------------
+# implement the --with-pic flag, and support the `pic-only' and `no-pic'
+# LT_INIT options.
+# MODE is either `yes' or `no'.  If omitted, it defaults to `both'.
+m4_define([_LT_WITH_PIC],
+[AC_ARG_WITH([pic],
+    [AS_HELP_STRING([--with-pic@<:@=PKGS@:>@],
+	[try to use only PIC/non-PIC objects @<:@default=use both@:>@])],
+    [lt_p=${PACKAGE-default}
+    case $withval in
+    yes|no) pic_mode=$withval ;;
+    *)
+      pic_mode=default
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for lt_pkg in $withval; do
+	IFS="$lt_save_ifs"
+	if test "X$lt_pkg" = "X$lt_p"; then
+	  pic_mode=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
+    [pic_mode=default])
+
+test -z "$pic_mode" && pic_mode=m4_default([$1], [default])
+
+_LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl
+])# _LT_WITH_PIC
+
+LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])])
+LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])])
+
+# Old name:
+AU_DEFUN([AC_LIBTOOL_PICMODE],
+[_LT_SET_OPTION([LT_INIT], [pic-only])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you
+put the `pic-only' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_PICMODE], [])
+
+## ----------------- ##
+## LTDL_INIT Options ##
+## ----------------- ##
+
+m4_define([_LTDL_MODE], [])
+LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive],
+		 [m4_define([_LTDL_MODE], [nonrecursive])])
+LT_OPTION_DEFINE([LTDL_INIT], [recursive],
+		 [m4_define([_LTDL_MODE], [recursive])])
+LT_OPTION_DEFINE([LTDL_INIT], [subproject],
+		 [m4_define([_LTDL_MODE], [subproject])])
+
+m4_define([_LTDL_TYPE], [])
+LT_OPTION_DEFINE([LTDL_INIT], [installable],
+		 [m4_define([_LTDL_TYPE], [installable])])
+LT_OPTION_DEFINE([LTDL_INIT], [convenience],
+		 [m4_define([_LTDL_TYPE], [convenience])])
diff --git a/hdrl/m4macros/ltsugar.m4 b/hdrl/m4macros/ltsugar.m4
new file mode 100644
index 0000000..9000a05
--- /dev/null
+++ b/hdrl/m4macros/ltsugar.m4
@@ -0,0 +1,123 @@
+# ltsugar.m4 -- libtool m4 base layer.                         -*-Autoconf-*-
+#
+# Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
+# Written by Gary V. Vaughan, 2004
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# serial 6 ltsugar.m4
+
+# This is to help aclocal find these macros, as it can't see m4_define.
+AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])])
+
+
+# lt_join(SEP, ARG1, [ARG2...])
+# -----------------------------
+# Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their
+# associated separator.
+# Needed until we can rely on m4_join from Autoconf 2.62, since all earlier
+# versions in m4sugar had bugs.
+m4_define([lt_join],
+[m4_if([$#], [1], [],
+       [$#], [2], [[$2]],
+       [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])])
+m4_define([_lt_join],
+[m4_if([$#$2], [2], [],
+       [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])])
+
+
+# lt_car(LIST)
+# lt_cdr(LIST)
+# ------------
+# Manipulate m4 lists.
+# These macros are necessary as long as will still need to support
+# Autoconf-2.59 which quotes differently.
+m4_define([lt_car], [[$1]])
+m4_define([lt_cdr],
+[m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])],
+       [$#], 1, [],
+       [m4_dquote(m4_shift($@))])])
+m4_define([lt_unquote], $1)
+
+
+# lt_append(MACRO-NAME, STRING, [SEPARATOR])
+# ------------------------------------------
+# Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'.
+# Note that neither SEPARATOR nor STRING are expanded; they are appended
+# to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked).
+# No SEPARATOR is output if MACRO-NAME was previously undefined (different
+# than defined and empty).
+#
+# This macro is needed until we can rely on Autoconf 2.62, since earlier
+# versions of m4sugar mistakenly expanded SEPARATOR but not STRING.
+m4_define([lt_append],
+[m4_define([$1],
+	   m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])])
+
+
+
+# lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...])
+# ----------------------------------------------------------
+# Produce a SEP delimited list of all paired combinations of elements of
+# PREFIX-LIST with SUFFIX1 through SUFFIXn.  Each element of the list
+# has the form PREFIXmINFIXSUFFIXn.
+# Needed until we can rely on m4_combine added in Autoconf 2.62.
+m4_define([lt_combine],
+[m4_if(m4_eval([$# > 3]), [1],
+       [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl
+[[m4_foreach([_Lt_prefix], [$2],
+	     [m4_foreach([_Lt_suffix],
+		]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[,
+	[_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])])
+
+
+# lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ])
+# -----------------------------------------------------------------------
+# Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited
+# by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ.
+m4_define([lt_if_append_uniq],
+[m4_ifdef([$1],
+	  [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1],
+		 [lt_append([$1], [$2], [$3])$4],
+		 [$5])],
+	  [lt_append([$1], [$2], [$3])$4])])
+
+
+# lt_dict_add(DICT, KEY, VALUE)
+# -----------------------------
+m4_define([lt_dict_add],
+[m4_define([$1($2)], [$3])])
+
+
+# lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE)
+# --------------------------------------------
+m4_define([lt_dict_add_subkey],
+[m4_define([$1($2:$3)], [$4])])
+
+
+# lt_dict_fetch(DICT, KEY, [SUBKEY])
+# ----------------------------------
+m4_define([lt_dict_fetch],
+[m4_ifval([$3],
+	m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]),
+    m4_ifdef([$1($2)], [m4_defn([$1($2)])]))])
+
+
+# lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE])
+# -----------------------------------------------------------------
+m4_define([lt_if_dict_fetch],
+[m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4],
+	[$5],
+    [$6])])
+
+
+# lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...])
+# --------------------------------------------------------------
+m4_define([lt_dict_filter],
+[m4_if([$5], [], [],
+  [lt_join(m4_quote(m4_default([$4], [[, ]])),
+           lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]),
+		      [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl
+])
diff --git a/hdrl/m4macros/ltversion.m4 b/hdrl/m4macros/ltversion.m4
new file mode 100644
index 0000000..07a8602
--- /dev/null
+++ b/hdrl/m4macros/ltversion.m4
@@ -0,0 +1,23 @@
+# ltversion.m4 -- version numbers			-*- Autoconf -*-
+#
+#   Copyright (C) 2004 Free Software Foundation, Inc.
+#   Written by Scott James Remnant, 2004
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# @configure_input@
+
+# serial 3337 ltversion.m4
+# This file is part of GNU Libtool
+
+m4_define([LT_PACKAGE_VERSION], [2.4.2])
+m4_define([LT_PACKAGE_REVISION], [1.3337])
+
+AC_DEFUN([LTVERSION_VERSION],
+[macro_version='2.4.2'
+macro_revision='1.3337'
+_LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?])
+_LT_DECL(, macro_revision, 0)
+])
diff --git a/hdrl/m4macros/lt~obsolete.m4 b/hdrl/m4macros/lt~obsolete.m4
new file mode 100644
index 0000000..c573da9
--- /dev/null
+++ b/hdrl/m4macros/lt~obsolete.m4
@@ -0,0 +1,98 @@
+# lt~obsolete.m4 -- aclocal satisfying obsolete definitions.    -*-Autoconf-*-
+#
+#   Copyright (C) 2004, 2005, 2007, 2009 Free Software Foundation, Inc.
+#   Written by Scott James Remnant, 2004.
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# serial 5 lt~obsolete.m4
+
+# These exist entirely to fool aclocal when bootstrapping libtool.
+#
+# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN)
+# which have later been changed to m4_define as they aren't part of the
+# exported API, or moved to Autoconf or Automake where they belong.
+#
+# The trouble is, aclocal is a bit thick.  It'll see the old AC_DEFUN
+# in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us
+# using a macro with the same name in our local m4/libtool.m4 it'll
+# pull the old libtool.m4 in (it doesn't see our shiny new m4_define
+# and doesn't know about Autoconf macros at all.)
+#
+# So we provide this file, which has a silly filename so it's always
+# included after everything else.  This provides aclocal with the
+# AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything
+# because those macros already exist, or will be overwritten later.
+# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. 
+#
+# Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here.
+# Yes, that means every name once taken will need to remain here until
+# we give up compatibility with versions before 1.7, at which point
+# we need to keep only those names which we still refer to.
+
+# This is to help aclocal find these macros, as it can't see m4_define.
+AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])])
+
+m4_ifndef([AC_LIBTOOL_LINKER_OPTION],	[AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])])
+m4_ifndef([AC_PROG_EGREP],		[AC_DEFUN([AC_PROG_EGREP])])
+m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH],	[AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])])
+m4_ifndef([_LT_AC_SHELL_INIT],		[AC_DEFUN([_LT_AC_SHELL_INIT])])
+m4_ifndef([_LT_AC_SYS_LIBPATH_AIX],	[AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])])
+m4_ifndef([_LT_PROG_LTMAIN],		[AC_DEFUN([_LT_PROG_LTMAIN])])
+m4_ifndef([_LT_AC_TAGVAR],		[AC_DEFUN([_LT_AC_TAGVAR])])
+m4_ifndef([AC_LTDL_ENABLE_INSTALL],	[AC_DEFUN([AC_LTDL_ENABLE_INSTALL])])
+m4_ifndef([AC_LTDL_PREOPEN],		[AC_DEFUN([AC_LTDL_PREOPEN])])
+m4_ifndef([_LT_AC_SYS_COMPILER],	[AC_DEFUN([_LT_AC_SYS_COMPILER])])
+m4_ifndef([_LT_AC_LOCK],		[AC_DEFUN([_LT_AC_LOCK])])
+m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE],	[AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])])
+m4_ifndef([_LT_AC_TRY_DLOPEN_SELF],	[AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])])
+m4_ifndef([AC_LIBTOOL_PROG_CC_C_O],	[AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])])
+m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])])
+m4_ifndef([AC_LIBTOOL_OBJDIR],		[AC_DEFUN([AC_LIBTOOL_OBJDIR])])
+m4_ifndef([AC_LTDL_OBJDIR],		[AC_DEFUN([AC_LTDL_OBJDIR])])
+m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])])
+m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP],	[AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])])
+m4_ifndef([AC_PATH_MAGIC],		[AC_DEFUN([AC_PATH_MAGIC])])
+m4_ifndef([AC_PROG_LD_GNU],		[AC_DEFUN([AC_PROG_LD_GNU])])
+m4_ifndef([AC_PROG_LD_RELOAD_FLAG],	[AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])])
+m4_ifndef([AC_DEPLIBS_CHECK_METHOD],	[AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])])
+m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])])
+m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])])
+m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])])
+m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS],	[AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])])
+m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP],	[AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])])
+m4_ifndef([LT_AC_PROG_EGREP],		[AC_DEFUN([LT_AC_PROG_EGREP])])
+m4_ifndef([LT_AC_PROG_SED],		[AC_DEFUN([LT_AC_PROG_SED])])
+m4_ifndef([_LT_CC_BASENAME],		[AC_DEFUN([_LT_CC_BASENAME])])
+m4_ifndef([_LT_COMPILER_BOILERPLATE],	[AC_DEFUN([_LT_COMPILER_BOILERPLATE])])
+m4_ifndef([_LT_LINKER_BOILERPLATE],	[AC_DEFUN([_LT_LINKER_BOILERPLATE])])
+m4_ifndef([_AC_PROG_LIBTOOL],		[AC_DEFUN([_AC_PROG_LIBTOOL])])
+m4_ifndef([AC_LIBTOOL_SETUP],		[AC_DEFUN([AC_LIBTOOL_SETUP])])
+m4_ifndef([_LT_AC_CHECK_DLFCN],		[AC_DEFUN([_LT_AC_CHECK_DLFCN])])
+m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER],	[AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])])
+m4_ifndef([_LT_AC_TAGCONFIG],		[AC_DEFUN([_LT_AC_TAGCONFIG])])
+m4_ifndef([AC_DISABLE_FAST_INSTALL],	[AC_DEFUN([AC_DISABLE_FAST_INSTALL])])
+m4_ifndef([_LT_AC_LANG_CXX],		[AC_DEFUN([_LT_AC_LANG_CXX])])
+m4_ifndef([_LT_AC_LANG_F77],		[AC_DEFUN([_LT_AC_LANG_F77])])
+m4_ifndef([_LT_AC_LANG_GCJ],		[AC_DEFUN([_LT_AC_LANG_GCJ])])
+m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])])
+m4_ifndef([_LT_AC_LANG_C_CONFIG],	[AC_DEFUN([_LT_AC_LANG_C_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])])
+m4_ifndef([_LT_AC_LANG_CXX_CONFIG],	[AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])])
+m4_ifndef([_LT_AC_LANG_F77_CONFIG],	[AC_DEFUN([_LT_AC_LANG_F77_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])])
+m4_ifndef([_LT_AC_LANG_GCJ_CONFIG],	[AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])])
+m4_ifndef([_LT_AC_LANG_RC_CONFIG],	[AC_DEFUN([_LT_AC_LANG_RC_CONFIG])])
+m4_ifndef([AC_LIBTOOL_CONFIG],		[AC_DEFUN([AC_LIBTOOL_CONFIG])])
+m4_ifndef([_LT_AC_FILE_LTDLL_C],	[AC_DEFUN([_LT_AC_FILE_LTDLL_C])])
+m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS],	[AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])])
+m4_ifndef([_LT_AC_PROG_CXXCPP],		[AC_DEFUN([_LT_AC_PROG_CXXCPP])])
+m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS],	[AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])])
+m4_ifndef([_LT_PROG_ECHO_BACKSLASH],	[AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])])
+m4_ifndef([_LT_PROG_F77],		[AC_DEFUN([_LT_PROG_F77])])
+m4_ifndef([_LT_PROG_FC],		[AC_DEFUN([_LT_PROG_FC])])
+m4_ifndef([_LT_PROG_CXX],		[AC_DEFUN([_LT_PROG_CXX])])
diff --git a/hdrl/m4macros/purify.m4 b/hdrl/m4macros/purify.m4
new file mode 100644
index 0000000..0d080bf
--- /dev/null
+++ b/hdrl/m4macros/purify.m4
@@ -0,0 +1,27 @@
+# PURIFY
+#------------------------
+# Checks for the INTROOT area
+AC_DEFUN([CHECK_PURIFY],
+[
+
+    AC_MSG_CHECKING([for PURIFY])
+
+    AC_ARG_ENABLE(purify,
+      AC_HELP_STRING([--disable-purify],
+        [disalbes the check for the PURIFY installation]),
+        enable_purify=$enableval,
+        enable_purify=yes)
+
+    if test "x$enable_purify" = xyes ; then
+      AC_MSG_RESULT([enabled])
+      AC_CHECK_PROG([PURIFY_CMD], [purify], [purify],[NONE])
+      if test "$PURIFY_CMD" = "NONE" ; then
+        AC_MSG_WARN([Disabling purify support])
+        enable_purify=no
+      fi
+    else
+      AC_MSG_RESULT([disabled])
+    fi
+
+    AM_CONDITIONAL([PURIFY], [test "x$enable_purify" = "xyes"])
+])
diff --git a/hdrl/tests/Makefile.am b/hdrl/tests/Makefile.am
new file mode 100644
index 0000000..0ce8c9a
--- /dev/null
+++ b/hdrl/tests/Makefile.am
@@ -0,0 +1,94 @@
+## Process this file with automake to produce Makefile.in
+
+##   This file is part of the ESO Common Pipeline Library
+##   Copyright (C) 2012,2013 European Southern Observatory
+
+##   This program is free software; you can redistribute it and/or modify
+##   it under the terms of the GNU General Public License as published by
+##   the Free Software Foundation; either version 2 of the License, or
+##   (at your option) any later version.
+
+##   This program is distributed in the hope that it will be useful,
+##   but WITHOUT ANY WARRANTY; without even the implied warranty of
+##   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+##   GNU General Public License for more details.
+
+##   You should have received a copy of the GNU General Public License
+##   along with this program; if not, write to the Free Software
+##   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+
+AUTOMAKE_OPTIONS = 1.8 foreign
+
+DISTCLEANFILES = *~
+
+if MAINTAINER_MODE
+
+MAINTAINERCLEANFILES = $(srcdir)/Makefile.in
+
+endif
+
+AM_CPPFLAGS = $(CPL_INCLUDES) $(HDRL_INCLUDES) -DHDRL_USE_PRIVATE
+AM_LDFLAGS = $(CPL_LDFLAGS) $(HDRL_LDFLAGS)
+
+LDADD = ../libhdrl.la $(LIBCPLCORE) $(LIBCPLDFS) $(LIBCPLDRS) $(LIBCPLUI) $(LIBCEXT) -lm
+ 
+check_PROGRAMS = hdrl_buffer-test \
+		 hdrl_overscan-test \
+		 hdrl_sigclip-test \
+		 hdrl_utils-test \
+		 hdrl_combine-test \
+		 hdrl_bpm_2d-test \
+		 hdrl_bpm_3d-test \
+		 hdrl_bpm_fit-test \
+		 hdrl_bpm_utils-test \
+		 hdrl_collapse-test \
+		 hdrl_image-test \
+		 hdrl_imagelist_io-test \
+		 hdrl_imagelist_basic-test \
+		 hdrl_imagelist_view-test \
+		 hdrl_elemop-test \
+		 hdrl_parameter-test \
+		 hdrl_fit-test \
+		 hdrl_strehl-test \
+		 hdrl_lacosmics-test
+
+hdrl_overscan_test_SOURCES = hdrl_overscan-test.c
+hdrl_sigclip_test_SOURCES = hdrl_sigclip-test.c
+hdrl_utils_test_SOURCES = hdrl_utils-test.c
+hdrl_combine_test_SOURCES = hdrl_combine-test.c
+hdrl_bpm_2d_test_SOURCES = hdrl_bpm_2d-test.c
+hdrl_bpm_3d_test_SOURCES = hdrl_bpm_3d-test.c
+hdrl_bpm_fit_test_SOURCES = hdrl_bpm_fit-test.c
+hdrl_bpm_utils_test_SOURCES = hdrl_bpm_utils-test.c
+hdrl_collapse_test_SOURCES = hdrl_collapse-test.c
+hdrl_image_test_SOURCES = hdrl_image-test.c
+hdrl_imagelist_io_test_SOURCES = hdrl_imagelist_io-test.c
+hdrl_imagelist_basic_test_SOURCES = hdrl_imagelist_basic-test.c
+hdrl_imagelist_view_test_SOURCES = hdrl_imagelist_view-test.c
+hdrl_elemop_test_SOURCES = hdrl_elemop-test.c
+hdrl_parameter_test_SOURCES = hdrl_parameter-test.c
+hdrl_buffer_test_SOURCES = hdrl_buffer-test.c
+hdrl_fit_test_SOURCES = hdrl_fit-test.c
+hdrl_strehl_test_SOURCES = hdrl_strehl-test.c
+hdrl_lacosmics_test_SOURCES = hdrl_lacosmics-test.c
+
+# Be sure to reexport important environment variables.
+TESTS_ENVIRONMENT = MAKE="$(MAKE)" CC="$(CC)" CFLAGS="$(CFLAGS)" \
+	CPPFLAGS="$(CPPFLAGS)" LD="$(LD)" LDFLAGS="$(LDFLAGS)" \
+	LIBS="$(LIBS)" LN_S="$(LN_S)" NM="$(NM)" RANLIB="$(RANLIB)" \
+	OBJEXT="$(OBJEXT)" EXEEXT="$(EXEEXT)" \
+	MALLOC_PERTURB_=31 MALLOC_CHECK_=2
+
+TESTS = $(check_PROGRAMS) 
+
+# Expected failures
+XFAIL_TESTS =
+
+# We need to remove any files that the above tests created.
+clean-local:
+	$(RM) *.fits *.tfits *.log
+
+if PURIFY
+include $(top_builddir)/Makefile.purify
+endif
diff --git a/irplib/tests/Makefile.in b/hdrl/tests/Makefile.in
similarity index 61%
copy from irplib/tests/Makefile.in
copy to hdrl/tests/Makefile.in
index 9554647..398f6e5 100644
--- a/irplib/tests/Makefile.in
+++ b/hdrl/tests/Makefile.in
@@ -13,7 +13,6 @@
 # PARTICULAR PURPOSE.
 
 @SET_MAKE@
-
 VPATH = @srcdir@
 am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
 am__make_running_with_option = \
@@ -79,25 +78,28 @@ POST_UNINSTALL = :
 build_triplet = @build@
 host_triplet = @host@
 target_triplet = @target@
-check_PROGRAMS = irplib_wlxcorr-test$(EXEEXT) \
-	irplib_hist-test$(EXEEXT) irplib_polynomial-test$(EXEEXT) \
-	irplib_plugin-test$(EXEEXT) irplib_utils-test$(EXEEXT) \
-	irplib_framelist-test$(EXEEXT) irplib_wcs-test$(EXEEXT) \
-	irplib_strehl-test$(EXEEXT) irplib_cat-test$(EXEEXT) \
-	irplib_sdp_spectrum-test$(EXEEXT)
-subdir = irplib/tests
+check_PROGRAMS = hdrl_buffer-test$(EXEEXT) hdrl_overscan-test$(EXEEXT) \
+	hdrl_sigclip-test$(EXEEXT) hdrl_utils-test$(EXEEXT) \
+	hdrl_combine-test$(EXEEXT) hdrl_bpm_2d-test$(EXEEXT) \
+	hdrl_bpm_3d-test$(EXEEXT) hdrl_bpm_fit-test$(EXEEXT) \
+	hdrl_bpm_utils-test$(EXEEXT) hdrl_collapse-test$(EXEEXT) \
+	hdrl_image-test$(EXEEXT) hdrl_imagelist_io-test$(EXEEXT) \
+	hdrl_imagelist_basic-test$(EXEEXT) \
+	hdrl_imagelist_view-test$(EXEEXT) hdrl_elemop-test$(EXEEXT) \
+	hdrl_parameter-test$(EXEEXT) hdrl_fit-test$(EXEEXT) \
+	hdrl_strehl-test$(EXEEXT) hdrl_lacosmics-test$(EXEEXT)
+XFAIL_TESTS =
+subdir = tests
 DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
-	$(top_srcdir)/admin/depcomp $(noinst_HEADERS) \
-	$(pkginclude_HEADERS) $(top_srcdir)/admin/test-driver
+	$(top_srcdir)/admin/depcomp $(top_srcdir)/admin/test-driver
 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4macros/cpl.m4 \
-	$(top_srcdir)/m4macros/eso.m4 $(top_srcdir)/m4macros/gsl.m4 \
-	$(top_srcdir)/m4macros/libtool.m4 \
+am__aclocal_m4_deps = $(top_srcdir)/m4macros/libtool.m4 \
 	$(top_srcdir)/m4macros/ltoptions.m4 \
 	$(top_srcdir)/m4macros/ltsugar.m4 \
 	$(top_srcdir)/m4macros/ltversion.m4 \
 	$(top_srcdir)/m4macros/lt~obsolete.m4 \
-	$(top_srcdir)/m4macros/purify.m4 $(top_srcdir)/acinclude.m4 \
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/m4macros/cpl.m4 \
+	$(top_srcdir)/m4macros/eso.m4 $(top_srcdir)/m4macros/purify.m4 \
 	$(top_srcdir)/configure.ac
 am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
@@ -105,86 +107,132 @@ mkinstalldirs = $(install_sh) -d
 CONFIG_HEADER = $(top_builddir)/config.h
 CONFIG_CLEAN_FILES =
 CONFIG_CLEAN_VPATH_FILES =
-am_irplib_cat_test_OBJECTS = irplib_cat-test.$(OBJEXT)
-irplib_cat_test_OBJECTS = $(am_irplib_cat_test_OBJECTS)
+am_hdrl_bpm_2d_test_OBJECTS = hdrl_bpm_2d-test.$(OBJEXT)
+hdrl_bpm_2d_test_OBJECTS = $(am_hdrl_bpm_2d_test_OBJECTS)
+hdrl_bpm_2d_test_LDADD = $(LDADD)
 am__DEPENDENCIES_1 =
-am__DEPENDENCIES_2 = $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+hdrl_bpm_2d_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
-irplib_cat_test_DEPENDENCIES = $(am__DEPENDENCIES_2)
 AM_V_lt = $(am__v_lt_ at AM_V@)
 am__v_lt_ = $(am__v_lt_ at AM_DEFAULT_V@)
 am__v_lt_0 = --silent
 am__v_lt_1 = 
-irplib_cat_test_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(AM_CFLAGS) $(CFLAGS) $(irplib_cat_test_LDFLAGS) $(LDFLAGS) \
-	-o $@
-am_irplib_framelist_test_OBJECTS = irplib_framelist-test.$(OBJEXT)
-irplib_framelist_test_OBJECTS = $(am_irplib_framelist_test_OBJECTS)
-irplib_framelist_test_DEPENDENCIES = $(am__DEPENDENCIES_2)
-irplib_framelist_test_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(AM_CFLAGS) $(CFLAGS) $(irplib_framelist_test_LDFLAGS) \
-	$(LDFLAGS) -o $@
-am_irplib_hist_test_OBJECTS = irplib_hist-test.$(OBJEXT)
-irplib_hist_test_OBJECTS = $(am_irplib_hist_test_OBJECTS)
-irplib_hist_test_DEPENDENCIES = $(am__DEPENDENCIES_2)
-irplib_hist_test_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(AM_CFLAGS) $(CFLAGS) $(irplib_hist_test_LDFLAGS) $(LDFLAGS) \
-	-o $@
-am_irplib_plugin_test_OBJECTS = irplib_plugin-test.$(OBJEXT)
-irplib_plugin_test_OBJECTS = $(am_irplib_plugin_test_OBJECTS)
-irplib_plugin_test_DEPENDENCIES = $(am__DEPENDENCIES_2)
-irplib_plugin_test_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(AM_CFLAGS) $(CFLAGS) $(irplib_plugin_test_LDFLAGS) \
-	$(LDFLAGS) -o $@
-am_irplib_polynomial_test_OBJECTS = irplib_polynomial-test.$(OBJEXT)
-irplib_polynomial_test_OBJECTS = $(am_irplib_polynomial_test_OBJECTS)
-irplib_polynomial_test_DEPENDENCIES = $(am__DEPENDENCIES_2)
-irplib_polynomial_test_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(AM_CFLAGS) $(CFLAGS) $(irplib_polynomial_test_LDFLAGS) \
-	$(LDFLAGS) -o $@
-am_irplib_sdp_spectrum_test_OBJECTS =  \
-	irplib_sdp_spectrum-test.$(OBJEXT)
-irplib_sdp_spectrum_test_OBJECTS =  \
-	$(am_irplib_sdp_spectrum_test_OBJECTS)
-irplib_sdp_spectrum_test_DEPENDENCIES = $(am__DEPENDENCIES_2)
-irplib_sdp_spectrum_test_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(AM_CFLAGS) $(CFLAGS) $(irplib_sdp_spectrum_test_LDFLAGS) \
-	$(LDFLAGS) -o $@
-am_irplib_strehl_test_OBJECTS = irplib_strehl-test.$(OBJEXT)
-irplib_strehl_test_OBJECTS = $(am_irplib_strehl_test_OBJECTS)
-irplib_strehl_test_DEPENDENCIES = $(am__DEPENDENCIES_2)
-irplib_strehl_test_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(AM_CFLAGS) $(CFLAGS) $(irplib_strehl_test_LDFLAGS) \
-	$(LDFLAGS) -o $@
-am_irplib_utils_test_OBJECTS = irplib_utils-test.$(OBJEXT)
-irplib_utils_test_OBJECTS = $(am_irplib_utils_test_OBJECTS)
-irplib_utils_test_DEPENDENCIES = $(am__DEPENDENCIES_2)
-irplib_utils_test_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(AM_CFLAGS) $(CFLAGS) $(irplib_utils_test_LDFLAGS) $(LDFLAGS) \
-	-o $@
-am_irplib_wcs_test_OBJECTS = irplib_wcs-test.$(OBJEXT)
-irplib_wcs_test_OBJECTS = $(am_irplib_wcs_test_OBJECTS)
-irplib_wcs_test_DEPENDENCIES = $(am__DEPENDENCIES_2)
-irplib_wcs_test_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(AM_CFLAGS) $(CFLAGS) $(irplib_wcs_test_LDFLAGS) $(LDFLAGS) \
-	-o $@
-am_irplib_wlxcorr_test_OBJECTS = irplib_wlxcorr-test.$(OBJEXT)
-irplib_wlxcorr_test_OBJECTS = $(am_irplib_wlxcorr_test_OBJECTS)
-irplib_wlxcorr_test_DEPENDENCIES = $(am__DEPENDENCIES_2)
-irplib_wlxcorr_test_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(AM_CFLAGS) $(CFLAGS) $(irplib_wlxcorr_test_LDFLAGS) \
-	$(LDFLAGS) -o $@
+am_hdrl_bpm_3d_test_OBJECTS = hdrl_bpm_3d-test.$(OBJEXT)
+hdrl_bpm_3d_test_OBJECTS = $(am_hdrl_bpm_3d_test_OBJECTS)
+hdrl_bpm_3d_test_LDADD = $(LDADD)
+hdrl_bpm_3d_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_hdrl_bpm_fit_test_OBJECTS = hdrl_bpm_fit-test.$(OBJEXT)
+hdrl_bpm_fit_test_OBJECTS = $(am_hdrl_bpm_fit_test_OBJECTS)
+hdrl_bpm_fit_test_LDADD = $(LDADD)
+hdrl_bpm_fit_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_hdrl_bpm_utils_test_OBJECTS = hdrl_bpm_utils-test.$(OBJEXT)
+hdrl_bpm_utils_test_OBJECTS = $(am_hdrl_bpm_utils_test_OBJECTS)
+hdrl_bpm_utils_test_LDADD = $(LDADD)
+hdrl_bpm_utils_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_hdrl_buffer_test_OBJECTS = hdrl_buffer-test.$(OBJEXT)
+hdrl_buffer_test_OBJECTS = $(am_hdrl_buffer_test_OBJECTS)
+hdrl_buffer_test_LDADD = $(LDADD)
+hdrl_buffer_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_hdrl_collapse_test_OBJECTS = hdrl_collapse-test.$(OBJEXT)
+hdrl_collapse_test_OBJECTS = $(am_hdrl_collapse_test_OBJECTS)
+hdrl_collapse_test_LDADD = $(LDADD)
+hdrl_collapse_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_hdrl_combine_test_OBJECTS = hdrl_combine-test.$(OBJEXT)
+hdrl_combine_test_OBJECTS = $(am_hdrl_combine_test_OBJECTS)
+hdrl_combine_test_LDADD = $(LDADD)
+hdrl_combine_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_hdrl_elemop_test_OBJECTS = hdrl_elemop-test.$(OBJEXT)
+hdrl_elemop_test_OBJECTS = $(am_hdrl_elemop_test_OBJECTS)
+hdrl_elemop_test_LDADD = $(LDADD)
+hdrl_elemop_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_hdrl_fit_test_OBJECTS = hdrl_fit-test.$(OBJEXT)
+hdrl_fit_test_OBJECTS = $(am_hdrl_fit_test_OBJECTS)
+hdrl_fit_test_LDADD = $(LDADD)
+hdrl_fit_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_hdrl_image_test_OBJECTS = hdrl_image-test.$(OBJEXT)
+hdrl_image_test_OBJECTS = $(am_hdrl_image_test_OBJECTS)
+hdrl_image_test_LDADD = $(LDADD)
+hdrl_image_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_hdrl_imagelist_basic_test_OBJECTS =  \
+	hdrl_imagelist_basic-test.$(OBJEXT)
+hdrl_imagelist_basic_test_OBJECTS =  \
+	$(am_hdrl_imagelist_basic_test_OBJECTS)
+hdrl_imagelist_basic_test_LDADD = $(LDADD)
+hdrl_imagelist_basic_test_DEPENDENCIES = ../libhdrl.la \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1)
+am_hdrl_imagelist_io_test_OBJECTS = hdrl_imagelist_io-test.$(OBJEXT)
+hdrl_imagelist_io_test_OBJECTS = $(am_hdrl_imagelist_io_test_OBJECTS)
+hdrl_imagelist_io_test_LDADD = $(LDADD)
+hdrl_imagelist_io_test_DEPENDENCIES = ../libhdrl.la \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1)
+am_hdrl_imagelist_view_test_OBJECTS =  \
+	hdrl_imagelist_view-test.$(OBJEXT)
+hdrl_imagelist_view_test_OBJECTS =  \
+	$(am_hdrl_imagelist_view_test_OBJECTS)
+hdrl_imagelist_view_test_LDADD = $(LDADD)
+hdrl_imagelist_view_test_DEPENDENCIES = ../libhdrl.la \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1)
+am_hdrl_lacosmics_test_OBJECTS = hdrl_lacosmics-test.$(OBJEXT)
+hdrl_lacosmics_test_OBJECTS = $(am_hdrl_lacosmics_test_OBJECTS)
+hdrl_lacosmics_test_LDADD = $(LDADD)
+hdrl_lacosmics_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_hdrl_overscan_test_OBJECTS = hdrl_overscan-test.$(OBJEXT)
+hdrl_overscan_test_OBJECTS = $(am_hdrl_overscan_test_OBJECTS)
+hdrl_overscan_test_LDADD = $(LDADD)
+hdrl_overscan_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_hdrl_parameter_test_OBJECTS = hdrl_parameter-test.$(OBJEXT)
+hdrl_parameter_test_OBJECTS = $(am_hdrl_parameter_test_OBJECTS)
+hdrl_parameter_test_LDADD = $(LDADD)
+hdrl_parameter_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_hdrl_sigclip_test_OBJECTS = hdrl_sigclip-test.$(OBJEXT)
+hdrl_sigclip_test_OBJECTS = $(am_hdrl_sigclip_test_OBJECTS)
+hdrl_sigclip_test_LDADD = $(LDADD)
+hdrl_sigclip_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_hdrl_strehl_test_OBJECTS = hdrl_strehl-test.$(OBJEXT)
+hdrl_strehl_test_OBJECTS = $(am_hdrl_strehl_test_OBJECTS)
+hdrl_strehl_test_LDADD = $(LDADD)
+hdrl_strehl_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_hdrl_utils_test_OBJECTS = hdrl_utils-test.$(OBJEXT)
+hdrl_utils_test_OBJECTS = $(am_hdrl_utils_test_OBJECTS)
+hdrl_utils_test_LDADD = $(LDADD)
+hdrl_utils_test_DEPENDENCIES = ../libhdrl.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
 AM_V_P = $(am__v_P_ at AM_V@)
 am__v_P_ = $(am__v_P_ at AM_DEFAULT_V@)
 am__v_P_0 = false
@@ -219,53 +267,33 @@ AM_V_CCLD = $(am__v_CCLD_ at AM_V@)
 am__v_CCLD_ = $(am__v_CCLD_ at AM_DEFAULT_V@)
 am__v_CCLD_0 = @echo "  CCLD    " $@;
 am__v_CCLD_1 = 
-SOURCES = $(irplib_cat_test_SOURCES) $(irplib_framelist_test_SOURCES) \
-	$(irplib_hist_test_SOURCES) $(irplib_plugin_test_SOURCES) \
-	$(irplib_polynomial_test_SOURCES) \
-	$(irplib_sdp_spectrum_test_SOURCES) \
-	$(irplib_strehl_test_SOURCES) $(irplib_utils_test_SOURCES) \
-	$(irplib_wcs_test_SOURCES) $(irplib_wlxcorr_test_SOURCES)
-DIST_SOURCES = $(irplib_cat_test_SOURCES) \
-	$(irplib_framelist_test_SOURCES) $(irplib_hist_test_SOURCES) \
-	$(irplib_plugin_test_SOURCES) \
-	$(irplib_polynomial_test_SOURCES) \
-	$(irplib_sdp_spectrum_test_SOURCES) \
-	$(irplib_strehl_test_SOURCES) $(irplib_utils_test_SOURCES) \
-	$(irplib_wcs_test_SOURCES) $(irplib_wlxcorr_test_SOURCES)
+SOURCES = $(hdrl_bpm_2d_test_SOURCES) $(hdrl_bpm_3d_test_SOURCES) \
+	$(hdrl_bpm_fit_test_SOURCES) $(hdrl_bpm_utils_test_SOURCES) \
+	$(hdrl_buffer_test_SOURCES) $(hdrl_collapse_test_SOURCES) \
+	$(hdrl_combine_test_SOURCES) $(hdrl_elemop_test_SOURCES) \
+	$(hdrl_fit_test_SOURCES) $(hdrl_image_test_SOURCES) \
+	$(hdrl_imagelist_basic_test_SOURCES) \
+	$(hdrl_imagelist_io_test_SOURCES) \
+	$(hdrl_imagelist_view_test_SOURCES) \
+	$(hdrl_lacosmics_test_SOURCES) $(hdrl_overscan_test_SOURCES) \
+	$(hdrl_parameter_test_SOURCES) $(hdrl_sigclip_test_SOURCES) \
+	$(hdrl_strehl_test_SOURCES) $(hdrl_utils_test_SOURCES)
+DIST_SOURCES = $(hdrl_bpm_2d_test_SOURCES) $(hdrl_bpm_3d_test_SOURCES) \
+	$(hdrl_bpm_fit_test_SOURCES) $(hdrl_bpm_utils_test_SOURCES) \
+	$(hdrl_buffer_test_SOURCES) $(hdrl_collapse_test_SOURCES) \
+	$(hdrl_combine_test_SOURCES) $(hdrl_elemop_test_SOURCES) \
+	$(hdrl_fit_test_SOURCES) $(hdrl_image_test_SOURCES) \
+	$(hdrl_imagelist_basic_test_SOURCES) \
+	$(hdrl_imagelist_io_test_SOURCES) \
+	$(hdrl_imagelist_view_test_SOURCES) \
+	$(hdrl_lacosmics_test_SOURCES) $(hdrl_overscan_test_SOURCES) \
+	$(hdrl_parameter_test_SOURCES) $(hdrl_sigclip_test_SOURCES) \
+	$(hdrl_strehl_test_SOURCES) $(hdrl_utils_test_SOURCES)
 am__can_run_installinfo = \
   case $$AM_UPDATE_INFO_DIR in \
     n|no|NO) false;; \
     *) (install-info --version) >/dev/null 2>&1;; \
   esac
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(pkgincludedir)"
-HEADERS = $(noinst_HEADERS) $(pkginclude_HEADERS)
 am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
 # Read a list of newline-separated strings from the standard input,
 # and print each of them once, without duplicates.  Input order is
@@ -307,6 +335,33 @@ am__tty_colors = { \
     std=''; \
   fi; \
 }
+am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj = case $$p in \
+    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=$$p;; \
+  esac;
+am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
+am__install_max = 40
+am__nobase_strip_setup = \
+  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip = \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list = $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
+  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
+    if (++n[$$2] == $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list = \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
+am__uninstall_files_from_dir = { \
+  test -z "$$files" \
+    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
+    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
+         $(am__cd) "$$dir" && rm -f $$files; }; \
+  }
 am__recheck_rx = ^[ 	]*:recheck:[ 	]*
 am__global_test_result_rx = ^[ 	]*:global-test-result:[ 	]*
 am__copy_in_global_log_rx = ^[ 	]*:copy-in-global-log:[ 	]*
@@ -473,8 +528,6 @@ AUTOMAKE = @AUTOMAKE@
 AWK = @AWK@
 CC = @CC@
 CCDEPMODE = @CCDEPMODE@
-CFITSIO_INCLUDES = @CFITSIO_INCLUDES@
-CFITSIO_LDFLAGS = @CFITSIO_LDFLAGS@
 CFLAGS = @CFLAGS@
 CPL_INCLUDES = @CPL_INCLUDES@
 CPL_LDFLAGS = @CPL_LDFLAGS@
@@ -497,34 +550,33 @@ ESO_DEBUG_FLAGS = @ESO_DEBUG_FLAGS@
 EXEEXT = @EXEEXT@
 FGREP = @FGREP@
 GREP = @GREP@
-GSL_INCLUDES = @GSL_INCLUDES@
-GSL_LDFLAGS = @GSL_LDFLAGS@
-GSL_LIBS = @GSL_LIBS@
+HDRL_BINARY_AGE = @HDRL_BINARY_AGE@
+HDRL_BINARY_VERSION = @HDRL_BINARY_VERSION@
+HDRL_INCLUDES = @HDRL_INCLUDES@
+HDRL_INTERFACE_AGE = @HDRL_INTERFACE_AGE@
+HDRL_LDFLAGS = @HDRL_LDFLAGS@
+HDRL_MAJOR_VERSION = @HDRL_MAJOR_VERSION@
+HDRL_MICRO_VERSION = @HDRL_MICRO_VERSION@
+HDRL_MINOR_VERSION = @HDRL_MINOR_VERSION@
+HDRL_VERSION = @HDRL_VERSION@
 INSTALL = @INSTALL@
 INSTALL_DATA = @INSTALL_DATA@
 INSTALL_PROGRAM = @INSTALL_PROGRAM@
 INSTALL_SCRIPT = @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-IRPLIB_CPPFLAGS = @IRPLIB_CPPFLAGS@
-LAPACK_INCLUDES = @LAPACK_INCLUDES@
-LAPACK_LDFLAGS = @LAPACK_LDFLAGS@
 LATEX = @LATEX@
 LD = @LD@
 LDFLAGS = @LDFLAGS@
 LIBCEXT = @LIBCEXT@
-LIBCFITSIO = @LIBCFITSIO@
 LIBCPLCORE = @LIBCPLCORE@
 LIBCPLDFS = @LIBCPLDFS@
 LIBCPLDRS = @LIBCPLDRS@
 LIBCPLUI = @LIBCPLUI@
-LIBIRPLIB = @LIBIRPLIB@
-LIBLAPACK = @LIBLAPACK@
+LIBHDRL = @LIBHDRL@
 LIBOBJS = @LIBOBJS@
-LIBPTHREAD = @LIBPTHREAD@
 LIBS = @LIBS@
 LIBTOOL = @LIBTOOL@
 LIBTOOL_DEPS = @LIBTOOL_DEPS@
-LIBXSH = @LIBXSH@
 LIPO = @LIPO@
 LN_S = @LN_S@
 LTLIBOBJS = @LTLIBOBJS@
@@ -549,7 +601,6 @@ PACKAGE_TARNAME = @PACKAGE_TARNAME@
 PACKAGE_URL = @PACKAGE_URL@
 PACKAGE_VERSION = @PACKAGE_VERSION@
 PATH_SEPARATOR = @PATH_SEPARATOR@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
 PURIFY_CMD = @PURIFY_CMD@
 RANLIB = @RANLIB@
 SED = @SED@
@@ -557,15 +608,6 @@ SET_MAKE = @SET_MAKE@
 SHELL = @SHELL@
 STRIP = @STRIP@
 VERSION = @VERSION@
-XSH_BINARY_AGE = @XSH_BINARY_AGE@
-XSH_BINARY_VERSION = @XSH_BINARY_VERSION@
-XSH_INCLUDES = @XSH_INCLUDES@
-XSH_INTERFACE_AGE = @XSH_INTERFACE_AGE@
-XSH_LDFLAGS = @XSH_LDFLAGS@
-XSH_MAJOR_VERSION = @XSH_MAJOR_VERSION@
-XSH_MICRO_VERSION = @XSH_MICRO_VERSION@
-XSH_MINOR_VERSION = @XSH_MINOR_VERSION@
-XSH_VERSION = @XSH_VERSION@
 abs_builddir = @abs_builddir@
 abs_srcdir = @abs_srcdir@
 abs_top_builddir = @abs_top_builddir@
@@ -587,7 +629,6 @@ build_cpu = @build_cpu@
 build_os = @build_os@
 build_vendor = @build_vendor@
 builddir = @builddir@
-configdir = @configdir@
 datadir = @datadir@
 datarootdir = @datarootdir@
 docdir = @docdir@
@@ -610,10 +651,7 @@ mandir = @mandir@
 mkdir_p = @mkdir_p@
 oldincludedir = @oldincludedir@
 pdfdir = @pdfdir@
-pipedocsdir = @pipedocsdir@
-plugindir = @plugindir@
 prefix = @prefix@
-privatelibdir = @privatelibdir@
 program_transform_name = @program_transform_name@
 psdir = @psdir@
 sbindir = @sbindir@
@@ -625,58 +663,43 @@ target_alias = @target_alias@
 target_cpu = @target_cpu@
 target_os = @target_os@
 target_vendor = @target_vendor@
-testsdir = @testsdir@
 top_build_prefix = @top_build_prefix@
 top_builddir = @top_builddir@
 top_srcdir = @top_srcdir@
-wkfcopydir = @wkfcopydir@
-wkfextradir = @wkfextradir@
 AUTOMAKE_OPTIONS = 1.8 foreign
 DISTCLEANFILES = *~
- at MAINTAINER_MODE_TRUE@MAINTAINERCLEANFILES = Makefile.in
-AM_CPPFLAGS = $(all_includes) -I../../irplib/
-LDADD = $(LIBIRPLIB) $(LIBCFITSIO) $(LIBCPLCORE) $(LIBCPLUI) $(LIBCPLDFS) $(LIBCPLDRS)
-pkginclude_HEADERS = 
-noinst_HEADERS = 
-irplib_wlxcorr_test_SOURCES = irplib_wlxcorr-test.c
-irplib_wlxcorr_test_LDFLAGS = $(CPL_LDFLAGS)
-irplib_wlxcorr_test_LDADD = $(LDADD)
-irplib_hist_test_SOURCES = irplib_hist-test.c
-irplib_hist_test_LDFLAGS = $(CPL_LDFLAGS)
-irplib_hist_test_LDADD = $(LDADD)
-irplib_polynomial_test_SOURCES = irplib_polynomial-test.c
-irplib_polynomial_test_LDFLAGS = $(CPL_LDFLAGS)
-irplib_polynomial_test_LDADD = $(LDADD)
-irplib_plugin_test_SOURCES = irplib_plugin-test.c
-irplib_plugin_test_LDFLAGS = $(CPL_LDFLAGS)
-irplib_plugin_test_LDADD = $(LDADD)
-irplib_utils_test_SOURCES = irplib_utils-test.c
-irplib_utils_test_LDFLAGS = $(CPL_LDFLAGS)
-irplib_utils_test_LDADD = $(LDADD)
-irplib_framelist_test_SOURCES = irplib_framelist-test.c
-irplib_framelist_test_LDFLAGS = $(CPL_LDFLAGS) 
-irplib_framelist_test_LDADD = $(LDADD)
-irplib_wcs_test_SOURCES = irplib_wcs-test.c
-irplib_wcs_test_LDFLAGS = $(CPL_LDFLAGS) $(WCSLIB_LDFLAGS)
-irplib_wcs_test_LDADD = $(LDADD) $(LIBWCSLIB)
-irplib_cat_test_SOURCES = irplib_cat-test.c
-irplib_cat_test_LDFLAGS = $(CPL_LDFLAGS) $(WCSLIB_LDFLAGS)
-irplib_cat_test_LDADD = $(LDADD) $(LIBWCSLIB)
-irplib_strehl_test_SOURCES = irplib_strehl-test.c
-irplib_strehl_test_LDFLAGS = $(CPL_LDFLAGS) $(WCSLIB_LDFLAGS)
-irplib_strehl_test_LDADD = $(LDADD) $(LIBWCSLIB)
-irplib_sdp_spectrum_test_SOURCES = irplib_sdp_spectrum-test.c
-irplib_sdp_spectrum_test_LDFLAGS = $(CPL_LDFLAGS)
-irplib_sdp_spectrum_test_LDADD = $(LDADD)
-TESTS = $(check_PROGRAMS)
+ at MAINTAINER_MODE_TRUE@MAINTAINERCLEANFILES = $(srcdir)/Makefile.in
+AM_CPPFLAGS = $(CPL_INCLUDES) $(HDRL_INCLUDES) -DHDRL_USE_PRIVATE
+AM_LDFLAGS = $(CPL_LDFLAGS) $(HDRL_LDFLAGS)
+LDADD = ../libhdrl.la $(LIBCPLCORE) $(LIBCPLDFS) $(LIBCPLDRS) $(LIBCPLUI) $(LIBCEXT) -lm
+hdrl_overscan_test_SOURCES = hdrl_overscan-test.c
+hdrl_sigclip_test_SOURCES = hdrl_sigclip-test.c
+hdrl_utils_test_SOURCES = hdrl_utils-test.c
+hdrl_combine_test_SOURCES = hdrl_combine-test.c
+hdrl_bpm_2d_test_SOURCES = hdrl_bpm_2d-test.c
+hdrl_bpm_3d_test_SOURCES = hdrl_bpm_3d-test.c
+hdrl_bpm_fit_test_SOURCES = hdrl_bpm_fit-test.c
+hdrl_bpm_utils_test_SOURCES = hdrl_bpm_utils-test.c
+hdrl_collapse_test_SOURCES = hdrl_collapse-test.c
+hdrl_image_test_SOURCES = hdrl_image-test.c
+hdrl_imagelist_io_test_SOURCES = hdrl_imagelist_io-test.c
+hdrl_imagelist_basic_test_SOURCES = hdrl_imagelist_basic-test.c
+hdrl_imagelist_view_test_SOURCES = hdrl_imagelist_view-test.c
+hdrl_elemop_test_SOURCES = hdrl_elemop-test.c
+hdrl_parameter_test_SOURCES = hdrl_parameter-test.c
+hdrl_buffer_test_SOURCES = hdrl_buffer-test.c
+hdrl_fit_test_SOURCES = hdrl_fit-test.c
+hdrl_strehl_test_SOURCES = hdrl_strehl-test.c
+hdrl_lacosmics_test_SOURCES = hdrl_lacosmics-test.c
 
 # Be sure to reexport important environment variables.
 TESTS_ENVIRONMENT = MAKE="$(MAKE)" CC="$(CC)" CFLAGS="$(CFLAGS)" \
-        CPPFLAGS="$(CPPFLAGS)" LD="$(LD)" LDFLAGS="$(LDFLAGS)" \
-        LIBS="$(LIBS)" LN_S="$(LN_S)" NM="$(NM)" RANLIB="$(RANLIB)" \
-        OBJEXT="$(OBJEXT)" EXEEXT="$(EXEEXT)" \
-        MALLOC_PERTURB_=137 MALLOC_CHECK_=2
+	CPPFLAGS="$(CPPFLAGS)" LD="$(LD)" LDFLAGS="$(LDFLAGS)" \
+	LIBS="$(LIBS)" LN_S="$(LN_S)" NM="$(NM)" RANLIB="$(RANLIB)" \
+	OBJEXT="$(OBJEXT)" EXEEXT="$(EXEEXT)" \
+	MALLOC_PERTURB_=31 MALLOC_CHECK_=2
 
+TESTS = $(check_PROGRAMS) 
 all: all-am
 
 .SUFFIXES:
@@ -690,9 +713,9 @@ $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am  $(am__confi
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign irplib/tests/Makefile'; \
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign tests/Makefile'; \
 	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign irplib/tests/Makefile
+	  $(AUTOMAKE) --foreign tests/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -721,45 +744,81 @@ clean-checkPROGRAMS:
 	echo " rm -f" $$list; \
 	rm -f $$list
 
-irplib_cat-test$(EXEEXT): $(irplib_cat_test_OBJECTS) $(irplib_cat_test_DEPENDENCIES) $(EXTRA_irplib_cat_test_DEPENDENCIES) 
-	@rm -f irplib_cat-test$(EXEEXT)
-	$(AM_V_CCLD)$(irplib_cat_test_LINK) $(irplib_cat_test_OBJECTS) $(irplib_cat_test_LDADD) $(LIBS)
+hdrl_bpm_2d-test$(EXEEXT): $(hdrl_bpm_2d_test_OBJECTS) $(hdrl_bpm_2d_test_DEPENDENCIES) $(EXTRA_hdrl_bpm_2d_test_DEPENDENCIES) 
+	@rm -f hdrl_bpm_2d-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_bpm_2d_test_OBJECTS) $(hdrl_bpm_2d_test_LDADD) $(LIBS)
+
+hdrl_bpm_3d-test$(EXEEXT): $(hdrl_bpm_3d_test_OBJECTS) $(hdrl_bpm_3d_test_DEPENDENCIES) $(EXTRA_hdrl_bpm_3d_test_DEPENDENCIES) 
+	@rm -f hdrl_bpm_3d-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_bpm_3d_test_OBJECTS) $(hdrl_bpm_3d_test_LDADD) $(LIBS)
+
+hdrl_bpm_fit-test$(EXEEXT): $(hdrl_bpm_fit_test_OBJECTS) $(hdrl_bpm_fit_test_DEPENDENCIES) $(EXTRA_hdrl_bpm_fit_test_DEPENDENCIES) 
+	@rm -f hdrl_bpm_fit-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_bpm_fit_test_OBJECTS) $(hdrl_bpm_fit_test_LDADD) $(LIBS)
+
+hdrl_bpm_utils-test$(EXEEXT): $(hdrl_bpm_utils_test_OBJECTS) $(hdrl_bpm_utils_test_DEPENDENCIES) $(EXTRA_hdrl_bpm_utils_test_DEPENDENCIES) 
+	@rm -f hdrl_bpm_utils-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_bpm_utils_test_OBJECTS) $(hdrl_bpm_utils_test_LDADD) $(LIBS)
+
+hdrl_buffer-test$(EXEEXT): $(hdrl_buffer_test_OBJECTS) $(hdrl_buffer_test_DEPENDENCIES) $(EXTRA_hdrl_buffer_test_DEPENDENCIES) 
+	@rm -f hdrl_buffer-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_buffer_test_OBJECTS) $(hdrl_buffer_test_LDADD) $(LIBS)
+
+hdrl_collapse-test$(EXEEXT): $(hdrl_collapse_test_OBJECTS) $(hdrl_collapse_test_DEPENDENCIES) $(EXTRA_hdrl_collapse_test_DEPENDENCIES) 
+	@rm -f hdrl_collapse-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_collapse_test_OBJECTS) $(hdrl_collapse_test_LDADD) $(LIBS)
+
+hdrl_combine-test$(EXEEXT): $(hdrl_combine_test_OBJECTS) $(hdrl_combine_test_DEPENDENCIES) $(EXTRA_hdrl_combine_test_DEPENDENCIES) 
+	@rm -f hdrl_combine-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_combine_test_OBJECTS) $(hdrl_combine_test_LDADD) $(LIBS)
 
-irplib_framelist-test$(EXEEXT): $(irplib_framelist_test_OBJECTS) $(irplib_framelist_test_DEPENDENCIES) $(EXTRA_irplib_framelist_test_DEPENDENCIES) 
-	@rm -f irplib_framelist-test$(EXEEXT)
-	$(AM_V_CCLD)$(irplib_framelist_test_LINK) $(irplib_framelist_test_OBJECTS) $(irplib_framelist_test_LDADD) $(LIBS)
+hdrl_elemop-test$(EXEEXT): $(hdrl_elemop_test_OBJECTS) $(hdrl_elemop_test_DEPENDENCIES) $(EXTRA_hdrl_elemop_test_DEPENDENCIES) 
+	@rm -f hdrl_elemop-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_elemop_test_OBJECTS) $(hdrl_elemop_test_LDADD) $(LIBS)
 
-irplib_hist-test$(EXEEXT): $(irplib_hist_test_OBJECTS) $(irplib_hist_test_DEPENDENCIES) $(EXTRA_irplib_hist_test_DEPENDENCIES) 
-	@rm -f irplib_hist-test$(EXEEXT)
-	$(AM_V_CCLD)$(irplib_hist_test_LINK) $(irplib_hist_test_OBJECTS) $(irplib_hist_test_LDADD) $(LIBS)
+hdrl_fit-test$(EXEEXT): $(hdrl_fit_test_OBJECTS) $(hdrl_fit_test_DEPENDENCIES) $(EXTRA_hdrl_fit_test_DEPENDENCIES) 
+	@rm -f hdrl_fit-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_fit_test_OBJECTS) $(hdrl_fit_test_LDADD) $(LIBS)
 
-irplib_plugin-test$(EXEEXT): $(irplib_plugin_test_OBJECTS) $(irplib_plugin_test_DEPENDENCIES) $(EXTRA_irplib_plugin_test_DEPENDENCIES) 
-	@rm -f irplib_plugin-test$(EXEEXT)
-	$(AM_V_CCLD)$(irplib_plugin_test_LINK) $(irplib_plugin_test_OBJECTS) $(irplib_plugin_test_LDADD) $(LIBS)
+hdrl_image-test$(EXEEXT): $(hdrl_image_test_OBJECTS) $(hdrl_image_test_DEPENDENCIES) $(EXTRA_hdrl_image_test_DEPENDENCIES) 
+	@rm -f hdrl_image-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_image_test_OBJECTS) $(hdrl_image_test_LDADD) $(LIBS)
 
-irplib_polynomial-test$(EXEEXT): $(irplib_polynomial_test_OBJECTS) $(irplib_polynomial_test_DEPENDENCIES) $(EXTRA_irplib_polynomial_test_DEPENDENCIES) 
-	@rm -f irplib_polynomial-test$(EXEEXT)
-	$(AM_V_CCLD)$(irplib_polynomial_test_LINK) $(irplib_polynomial_test_OBJECTS) $(irplib_polynomial_test_LDADD) $(LIBS)
+hdrl_imagelist_basic-test$(EXEEXT): $(hdrl_imagelist_basic_test_OBJECTS) $(hdrl_imagelist_basic_test_DEPENDENCIES) $(EXTRA_hdrl_imagelist_basic_test_DEPENDENCIES) 
+	@rm -f hdrl_imagelist_basic-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_imagelist_basic_test_OBJECTS) $(hdrl_imagelist_basic_test_LDADD) $(LIBS)
 
-irplib_sdp_spectrum-test$(EXEEXT): $(irplib_sdp_spectrum_test_OBJECTS) $(irplib_sdp_spectrum_test_DEPENDENCIES) $(EXTRA_irplib_sdp_spectrum_test_DEPENDENCIES) 
-	@rm -f irplib_sdp_spectrum-test$(EXEEXT)
-	$(AM_V_CCLD)$(irplib_sdp_spectrum_test_LINK) $(irplib_sdp_spectrum_test_OBJECTS) $(irplib_sdp_spectrum_test_LDADD) $(LIBS)
+hdrl_imagelist_io-test$(EXEEXT): $(hdrl_imagelist_io_test_OBJECTS) $(hdrl_imagelist_io_test_DEPENDENCIES) $(EXTRA_hdrl_imagelist_io_test_DEPENDENCIES) 
+	@rm -f hdrl_imagelist_io-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_imagelist_io_test_OBJECTS) $(hdrl_imagelist_io_test_LDADD) $(LIBS)
 
-irplib_strehl-test$(EXEEXT): $(irplib_strehl_test_OBJECTS) $(irplib_strehl_test_DEPENDENCIES) $(EXTRA_irplib_strehl_test_DEPENDENCIES) 
-	@rm -f irplib_strehl-test$(EXEEXT)
-	$(AM_V_CCLD)$(irplib_strehl_test_LINK) $(irplib_strehl_test_OBJECTS) $(irplib_strehl_test_LDADD) $(LIBS)
+hdrl_imagelist_view-test$(EXEEXT): $(hdrl_imagelist_view_test_OBJECTS) $(hdrl_imagelist_view_test_DEPENDENCIES) $(EXTRA_hdrl_imagelist_view_test_DEPENDENCIES) 
+	@rm -f hdrl_imagelist_view-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_imagelist_view_test_OBJECTS) $(hdrl_imagelist_view_test_LDADD) $(LIBS)
 
-irplib_utils-test$(EXEEXT): $(irplib_utils_test_OBJECTS) $(irplib_utils_test_DEPENDENCIES) $(EXTRA_irplib_utils_test_DEPENDENCIES) 
-	@rm -f irplib_utils-test$(EXEEXT)
-	$(AM_V_CCLD)$(irplib_utils_test_LINK) $(irplib_utils_test_OBJECTS) $(irplib_utils_test_LDADD) $(LIBS)
+hdrl_lacosmics-test$(EXEEXT): $(hdrl_lacosmics_test_OBJECTS) $(hdrl_lacosmics_test_DEPENDENCIES) $(EXTRA_hdrl_lacosmics_test_DEPENDENCIES) 
+	@rm -f hdrl_lacosmics-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_lacosmics_test_OBJECTS) $(hdrl_lacosmics_test_LDADD) $(LIBS)
 
-irplib_wcs-test$(EXEEXT): $(irplib_wcs_test_OBJECTS) $(irplib_wcs_test_DEPENDENCIES) $(EXTRA_irplib_wcs_test_DEPENDENCIES) 
-	@rm -f irplib_wcs-test$(EXEEXT)
-	$(AM_V_CCLD)$(irplib_wcs_test_LINK) $(irplib_wcs_test_OBJECTS) $(irplib_wcs_test_LDADD) $(LIBS)
+hdrl_overscan-test$(EXEEXT): $(hdrl_overscan_test_OBJECTS) $(hdrl_overscan_test_DEPENDENCIES) $(EXTRA_hdrl_overscan_test_DEPENDENCIES) 
+	@rm -f hdrl_overscan-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_overscan_test_OBJECTS) $(hdrl_overscan_test_LDADD) $(LIBS)
 
-irplib_wlxcorr-test$(EXEEXT): $(irplib_wlxcorr_test_OBJECTS) $(irplib_wlxcorr_test_DEPENDENCIES) $(EXTRA_irplib_wlxcorr_test_DEPENDENCIES) 
-	@rm -f irplib_wlxcorr-test$(EXEEXT)
-	$(AM_V_CCLD)$(irplib_wlxcorr_test_LINK) $(irplib_wlxcorr_test_OBJECTS) $(irplib_wlxcorr_test_LDADD) $(LIBS)
+hdrl_parameter-test$(EXEEXT): $(hdrl_parameter_test_OBJECTS) $(hdrl_parameter_test_DEPENDENCIES) $(EXTRA_hdrl_parameter_test_DEPENDENCIES) 
+	@rm -f hdrl_parameter-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_parameter_test_OBJECTS) $(hdrl_parameter_test_LDADD) $(LIBS)
+
+hdrl_sigclip-test$(EXEEXT): $(hdrl_sigclip_test_OBJECTS) $(hdrl_sigclip_test_DEPENDENCIES) $(EXTRA_hdrl_sigclip_test_DEPENDENCIES) 
+	@rm -f hdrl_sigclip-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_sigclip_test_OBJECTS) $(hdrl_sigclip_test_LDADD) $(LIBS)
+
+hdrl_strehl-test$(EXEEXT): $(hdrl_strehl_test_OBJECTS) $(hdrl_strehl_test_DEPENDENCIES) $(EXTRA_hdrl_strehl_test_DEPENDENCIES) 
+	@rm -f hdrl_strehl-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_strehl_test_OBJECTS) $(hdrl_strehl_test_LDADD) $(LIBS)
+
+hdrl_utils-test$(EXEEXT): $(hdrl_utils_test_OBJECTS) $(hdrl_utils_test_DEPENDENCIES) $(EXTRA_hdrl_utils_test_DEPENDENCIES) 
+	@rm -f hdrl_utils-test$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(hdrl_utils_test_OBJECTS) $(hdrl_utils_test_LDADD) $(LIBS)
 
 mostlyclean-compile:
 	-rm -f *.$(OBJEXT)
@@ -767,16 +826,25 @@ mostlyclean-compile:
 distclean-compile:
 	-rm -f *.tab.c
 
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/irplib_cat-test.Po at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/irplib_framelist-test.Po at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/irplib_hist-test.Po at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/irplib_plugin-test.Po at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/irplib_polynomial-test.Po at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/irplib_sdp_spectrum-test.Po at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/irplib_strehl-test.Po at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/irplib_utils-test.Po at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/irplib_wcs-test.Po at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/irplib_wlxcorr-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_bpm_2d-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_bpm_3d-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_bpm_fit-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_bpm_utils-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_buffer-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_collapse-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_combine-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_elemop-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_fit-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_image-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_imagelist_basic-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_imagelist_io-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_imagelist_view-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_lacosmics-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_overscan-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_parameter-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_sigclip-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_strehl-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdrl_utils-test.Po at am__quote@
 
 .c.o:
 @am__fastdepCC_TRUE@	$(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
@@ -804,27 +872,6 @@ mostlyclean-libtool:
 
 clean-libtool:
 	-rm -rf .libs _libs
-install-pkgincludeHEADERS: $(pkginclude_HEADERS)
-	@$(NORMAL_INSTALL)
-	@list='$(pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \
-	if test -n "$$list"; then \
-	  echo " $(MKDIR_P) '$(DESTDIR)$(pkgincludedir)'"; \
-	  $(MKDIR_P) "$(DESTDIR)$(pkgincludedir)" || exit 1; \
-	fi; \
-	for p in $$list; do \
-	  if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-	  echo "$$d$$p"; \
-	done | $(am__base_list) | \
-	while read files; do \
-	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(pkgincludedir)'"; \
-	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(pkgincludedir)" || exit $$?; \
-	done
-
-uninstall-pkgincludeHEADERS:
-	@$(NORMAL_UNINSTALL)
-	@list='$(pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \
-	files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
-	dir='$(DESTDIR)$(pkgincludedir)'; $(am__uninstall_files_from_dir)
 
 ID: $(am__tagged_files)
 	$(am__define_uniq_tagged_files); mkid -fID $$unique
@@ -1019,72 +1066,135 @@ recheck: all $(check_PROGRAMS)
 	        am__force_recheck=am--force-recheck \
 	        TEST_LOGS="$$log_list"; \
 	exit $$?
-irplib_wlxcorr-test.log: irplib_wlxcorr-test$(EXEEXT)
-	@p='irplib_wlxcorr-test$(EXEEXT)'; \
-	b='irplib_wlxcorr-test'; \
+hdrl_buffer-test.log: hdrl_buffer-test$(EXEEXT)
+	@p='hdrl_buffer-test$(EXEEXT)'; \
+	b='hdrl_buffer-test'; \
+	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
+	--log-file $$b.log --trs-file $$b.trs \
+	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
+	"$$tst" $(AM_TESTS_FD_REDIRECT)
+hdrl_overscan-test.log: hdrl_overscan-test$(EXEEXT)
+	@p='hdrl_overscan-test$(EXEEXT)'; \
+	b='hdrl_overscan-test'; \
+	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
+	--log-file $$b.log --trs-file $$b.trs \
+	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
+	"$$tst" $(AM_TESTS_FD_REDIRECT)
+hdrl_sigclip-test.log: hdrl_sigclip-test$(EXEEXT)
+	@p='hdrl_sigclip-test$(EXEEXT)'; \
+	b='hdrl_sigclip-test'; \
+	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
+	--log-file $$b.log --trs-file $$b.trs \
+	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
+	"$$tst" $(AM_TESTS_FD_REDIRECT)
+hdrl_utils-test.log: hdrl_utils-test$(EXEEXT)
+	@p='hdrl_utils-test$(EXEEXT)'; \
+	b='hdrl_utils-test'; \
+	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
+	--log-file $$b.log --trs-file $$b.trs \
+	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
+	"$$tst" $(AM_TESTS_FD_REDIRECT)
+hdrl_combine-test.log: hdrl_combine-test$(EXEEXT)
+	@p='hdrl_combine-test$(EXEEXT)'; \
+	b='hdrl_combine-test'; \
+	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
+	--log-file $$b.log --trs-file $$b.trs \
+	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
+	"$$tst" $(AM_TESTS_FD_REDIRECT)
+hdrl_bpm_2d-test.log: hdrl_bpm_2d-test$(EXEEXT)
+	@p='hdrl_bpm_2d-test$(EXEEXT)'; \
+	b='hdrl_bpm_2d-test'; \
 	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
 	--log-file $$b.log --trs-file $$b.trs \
 	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
 	"$$tst" $(AM_TESTS_FD_REDIRECT)
-irplib_hist-test.log: irplib_hist-test$(EXEEXT)
-	@p='irplib_hist-test$(EXEEXT)'; \
-	b='irplib_hist-test'; \
+hdrl_bpm_3d-test.log: hdrl_bpm_3d-test$(EXEEXT)
+	@p='hdrl_bpm_3d-test$(EXEEXT)'; \
+	b='hdrl_bpm_3d-test'; \
 	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
 	--log-file $$b.log --trs-file $$b.trs \
 	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
 	"$$tst" $(AM_TESTS_FD_REDIRECT)
-irplib_polynomial-test.log: irplib_polynomial-test$(EXEEXT)
-	@p='irplib_polynomial-test$(EXEEXT)'; \
-	b='irplib_polynomial-test'; \
+hdrl_bpm_fit-test.log: hdrl_bpm_fit-test$(EXEEXT)
+	@p='hdrl_bpm_fit-test$(EXEEXT)'; \
+	b='hdrl_bpm_fit-test'; \
 	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
 	--log-file $$b.log --trs-file $$b.trs \
 	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
 	"$$tst" $(AM_TESTS_FD_REDIRECT)
-irplib_plugin-test.log: irplib_plugin-test$(EXEEXT)
-	@p='irplib_plugin-test$(EXEEXT)'; \
-	b='irplib_plugin-test'; \
+hdrl_bpm_utils-test.log: hdrl_bpm_utils-test$(EXEEXT)
+	@p='hdrl_bpm_utils-test$(EXEEXT)'; \
+	b='hdrl_bpm_utils-test'; \
 	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
 	--log-file $$b.log --trs-file $$b.trs \
 	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
 	"$$tst" $(AM_TESTS_FD_REDIRECT)
-irplib_utils-test.log: irplib_utils-test$(EXEEXT)
-	@p='irplib_utils-test$(EXEEXT)'; \
-	b='irplib_utils-test'; \
+hdrl_collapse-test.log: hdrl_collapse-test$(EXEEXT)
+	@p='hdrl_collapse-test$(EXEEXT)'; \
+	b='hdrl_collapse-test'; \
 	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
 	--log-file $$b.log --trs-file $$b.trs \
 	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
 	"$$tst" $(AM_TESTS_FD_REDIRECT)
-irplib_framelist-test.log: irplib_framelist-test$(EXEEXT)
-	@p='irplib_framelist-test$(EXEEXT)'; \
-	b='irplib_framelist-test'; \
+hdrl_image-test.log: hdrl_image-test$(EXEEXT)
+	@p='hdrl_image-test$(EXEEXT)'; \
+	b='hdrl_image-test'; \
 	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
 	--log-file $$b.log --trs-file $$b.trs \
 	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
 	"$$tst" $(AM_TESTS_FD_REDIRECT)
-irplib_wcs-test.log: irplib_wcs-test$(EXEEXT)
-	@p='irplib_wcs-test$(EXEEXT)'; \
-	b='irplib_wcs-test'; \
+hdrl_imagelist_io-test.log: hdrl_imagelist_io-test$(EXEEXT)
+	@p='hdrl_imagelist_io-test$(EXEEXT)'; \
+	b='hdrl_imagelist_io-test'; \
 	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
 	--log-file $$b.log --trs-file $$b.trs \
 	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
 	"$$tst" $(AM_TESTS_FD_REDIRECT)
-irplib_strehl-test.log: irplib_strehl-test$(EXEEXT)
-	@p='irplib_strehl-test$(EXEEXT)'; \
-	b='irplib_strehl-test'; \
+hdrl_imagelist_basic-test.log: hdrl_imagelist_basic-test$(EXEEXT)
+	@p='hdrl_imagelist_basic-test$(EXEEXT)'; \
+	b='hdrl_imagelist_basic-test'; \
 	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
 	--log-file $$b.log --trs-file $$b.trs \
 	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
 	"$$tst" $(AM_TESTS_FD_REDIRECT)
-irplib_cat-test.log: irplib_cat-test$(EXEEXT)
-	@p='irplib_cat-test$(EXEEXT)'; \
-	b='irplib_cat-test'; \
+hdrl_imagelist_view-test.log: hdrl_imagelist_view-test$(EXEEXT)
+	@p='hdrl_imagelist_view-test$(EXEEXT)'; \
+	b='hdrl_imagelist_view-test'; \
 	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
 	--log-file $$b.log --trs-file $$b.trs \
 	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
 	"$$tst" $(AM_TESTS_FD_REDIRECT)
-irplib_sdp_spectrum-test.log: irplib_sdp_spectrum-test$(EXEEXT)
-	@p='irplib_sdp_spectrum-test$(EXEEXT)'; \
-	b='irplib_sdp_spectrum-test'; \
+hdrl_elemop-test.log: hdrl_elemop-test$(EXEEXT)
+	@p='hdrl_elemop-test$(EXEEXT)'; \
+	b='hdrl_elemop-test'; \
+	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
+	--log-file $$b.log --trs-file $$b.trs \
+	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
+	"$$tst" $(AM_TESTS_FD_REDIRECT)
+hdrl_parameter-test.log: hdrl_parameter-test$(EXEEXT)
+	@p='hdrl_parameter-test$(EXEEXT)'; \
+	b='hdrl_parameter-test'; \
+	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
+	--log-file $$b.log --trs-file $$b.trs \
+	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
+	"$$tst" $(AM_TESTS_FD_REDIRECT)
+hdrl_fit-test.log: hdrl_fit-test$(EXEEXT)
+	@p='hdrl_fit-test$(EXEEXT)'; \
+	b='hdrl_fit-test'; \
+	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
+	--log-file $$b.log --trs-file $$b.trs \
+	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
+	"$$tst" $(AM_TESTS_FD_REDIRECT)
+hdrl_strehl-test.log: hdrl_strehl-test$(EXEEXT)
+	@p='hdrl_strehl-test$(EXEEXT)'; \
+	b='hdrl_strehl-test'; \
+	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
+	--log-file $$b.log --trs-file $$b.trs \
+	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
+	"$$tst" $(AM_TESTS_FD_REDIRECT)
+hdrl_lacosmics-test.log: hdrl_lacosmics-test$(EXEEXT)
+	@p='hdrl_lacosmics-test$(EXEEXT)'; \
+	b='hdrl_lacosmics-test'; \
 	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
 	--log-file $$b.log --trs-file $$b.trs \
 	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
@@ -1138,11 +1248,8 @@ check-am: all-am
 	$(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS)
 	$(MAKE) $(AM_MAKEFLAGS) check-TESTS
 check: check-am
-all-am: Makefile $(HEADERS)
+all-am: Makefile
 installdirs:
-	for dir in "$(DESTDIR)$(pkgincludedir)"; do \
-	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-	done
 install: install-am
 install-exec: install-exec-am
 install-data: install-data-am
@@ -1201,7 +1308,7 @@ info: info-am
 
 info-am:
 
-install-data-am: install-pkgincludeHEADERS
+install-data-am:
 
 install-dvi: install-dvi-am
 
@@ -1247,7 +1354,7 @@ ps: ps-am
 
 ps-am:
 
-uninstall-am: uninstall-pkgincludeHEADERS
+uninstall-am:
 
 .MAKE: check-am install-am install-strip
 
@@ -1259,21 +1366,18 @@ uninstall-am: uninstall-pkgincludeHEADERS
 	install-data install-data-am install-dvi install-dvi-am \
 	install-exec install-exec-am install-html install-html-am \
 	install-info install-info-am install-man install-pdf \
-	install-pdf-am install-pkgincludeHEADERS install-ps \
-	install-ps-am install-strip installcheck installcheck-am \
-	installdirs maintainer-clean maintainer-clean-generic \
-	mostlyclean mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool pdf pdf-am ps ps-am recheck tags tags-am \
-	uninstall uninstall-am uninstall-pkgincludeHEADERS
+	install-pdf-am install-ps install-ps-am install-strip \
+	installcheck installcheck-am installdirs maintainer-clean \
+	maintainer-clean-generic mostlyclean mostlyclean-compile \
+	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
+	recheck tags tags-am uninstall uninstall-am
 
 
 # We need to remove any files that the above tests created.
-clean-local: 
-	 $(RM) *.log *.paf *.fits .logfile
+clean-local:
+	$(RM) *.fits *.tfits *.log
 
-#if PURIFY
-#include $(top_builddir)/Makefile.purify
-#endif
+ at PURIFY_TRUE@include $(top_builddir)/Makefile.purify
 
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
diff --git a/hdrl/tests/hdrl_bpm_2d-test.c b/hdrl/tests/hdrl_bpm_2d-test.c
new file mode 100644
index 0000000..084de13
--- /dev/null
+++ b/hdrl/tests/hdrl_bpm_2d-test.c
@@ -0,0 +1,233 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_bpm_2d.h"
+#include "hdrl_image.h"
+
+#include <cpl.h>
+#include <math.h>
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_bpm_2d_test    Testing of the HDRL bpm_2d
+ */
+/*----------------------------------------------------------------------------*/
+
+void test_parlist(void)
+{
+    /* parameter parsing smoketest */
+    hdrl_parameter * hpar;
+    hdrl_parameter * fil_def =
+        hdrl_bpm_2d_parameter_create_filtersmooth(4, 5, 6,
+                                                  CPL_FILTER_MEDIAN,
+                                                  CPL_BORDER_NOP,
+                                                  7, 9);
+    hdrl_parameter * leg_def =
+        hdrl_bpm_2d_parameter_create_legendresmooth(4, 5, 6,
+                                                    20, 21,
+                                                    11, 12, 2, 10);
+    cpl_parameterlist * pos = hdrl_bpm_2d_parameter_create_parlist(
+                "RECIPE", "bpm", "FILTER", fil_def, leg_def);
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_eq(cpl_parameterlist_get_size(pos), 17);
+
+    hpar = hdrl_bpm_2d_parameter_parse_parlist(pos, "RECIPE.invalid");
+    cpl_test_null(hpar);
+    cpl_test_error(CPL_ERROR_DATA_NOT_FOUND);
+
+    hpar = hdrl_bpm_2d_parameter_parse_parlist(pos, "RECIPE.bpm");
+    cpl_parameterlist_delete(pos);
+    cpl_test_error(CPL_ERROR_NONE);
+
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_filter(hpar), CPL_FILTER_MEDIAN);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_border(hpar), CPL_BORDER_NOP);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_kappa_low(hpar), 4);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_kappa_high(hpar), 5);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_maxiter(hpar), 6);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_smooth_x(hpar), 7);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_smooth_y(hpar), 9);
+    /* TODO wrong par error? */
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_steps_x(hpar), 0);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_steps_y(hpar), 0);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_filter_size_x(hpar), 0);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_filter_size_y(hpar), 0);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_order_x(hpar), 0);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_order_y(hpar), 0);
+    hdrl_parameter_delete(hpar);
+
+    pos = hdrl_bpm_2d_parameter_create_parlist(
+                "RECIPE", "bpm", "LEGENDRE", fil_def, leg_def);
+    cpl_test_error(CPL_ERROR_NONE);
+
+    hpar = hdrl_bpm_2d_parameter_parse_parlist(pos, "RECIPE.bpm");
+    cpl_parameterlist_delete(pos);
+    cpl_test_error(CPL_ERROR_NONE);
+
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_kappa_low(hpar), 4);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_kappa_high(hpar), 5);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_maxiter(hpar), 6);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_steps_x(hpar), 20);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_steps_y(hpar), 21);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_filter_size_x(hpar), 11);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_filter_size_y(hpar), 12);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_order_x(hpar), 2);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_order_y(hpar), 10);
+    /* TODO wrong par error? */
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_filter(hpar), CPL_FILTER_MEDIAN);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_border(hpar), CPL_BORDER_FILTER);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_smooth_x(hpar), 0);
+    cpl_test_eq(hdrl_bpm_2d_parameter_get_smooth_y(hpar), 0);
+    hdrl_parameter_delete(hpar);
+
+    hdrl_parameter_delete(leg_def);
+    hdrl_parameter_delete(fil_def);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check hdrl_bpm_2d_compute() in various conditions
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_bpm_2d_test_compute(void)
+{
+    cpl_image       *   data = NULL;
+    cpl_mask        *   data_bpm = NULL;
+    cpl_image       *   errors = NULL;
+    cpl_mask        *   mask_out = NULL;
+    hdrl_parameter  *   bpm_param = NULL;
+
+    /* Create BPM parameters */
+    bpm_param = hdrl_bpm_2d_parameter_create_filtersmooth(3., 3., 2, 
+            CPL_FILTER_MEDIAN, CPL_BORDER_FILTER, 3, 3) ;
+
+    { /* Test sigmaclipped mean */
+        /* gauss mean 100 sigma 3.5 and 2 outliers */
+        double values[] = {92, 93, 94, 94, 95, 95, 96, 96, 96, 97,
+                        97, 97, 97, 98, 98, 98, 98, 99, 99, 99,
+                        99, 100, 100, 100, 100, 100, 101, 101, 101, 101,
+                        102, 102, 102, 102, 103, 103, 103, 103, 104, 104,
+                        104, 105, 105, 106, 106, 107, 108, 500, 600 };
+
+        data = cpl_image_wrap(7, 7, CPL_TYPE_DOUBLE, values);
+        errors = cpl_image_new(7, 7, CPL_TYPE_DOUBLE);
+        cpl_image_add_scalar(errors, 1);
+
+        cpl_image_set(errors, 7, 7, 100000.);
+        cpl_image_set(errors, 6, 7, 10000.);
+
+        hdrl_image * sigimage = hdrl_image_create(data, errors);
+
+        mask_out = hdrl_bpm_2d_compute(sigimage, bpm_param) ;
+        cpl_mask_delete(mask_out);
+        
+        hdrl_parameter_delete(bpm_param) ;
+        bpm_param = hdrl_bpm_2d_parameter_create_legendresmooth(3., 3.,
+                2,  20, 20, 11, 11, 3, 3) ;
+
+        mask_out = hdrl_bpm_2d_compute(sigimage, bpm_param) ;
+
+        //cpl_mask_save(mask_out, "bpm1.fits", NULL, CPL_IO_CREATE);
+
+        cpl_mask_delete(mask_out);
+        cpl_image_unwrap(data);
+        cpl_image_delete(errors);
+        hdrl_image_delete(sigimage);
+    }
+
+    {
+        data = cpl_image_new(200, 300, CPL_TYPE_FLOAT);
+        data_bpm = cpl_mask_new(200, 300);
+
+        cpl_image_fill_noise_uniform(data, 90, 110);
+        cpl_image_set(data, 50, 50, 300.);
+        cpl_image_set(data, 100, 100, 300.);
+        cpl_image_set(data, 150, 150, 300.);
+        cpl_image_set(data, 110, 260, 300.);
+
+        cpl_mask_set(data_bpm, 120,120, CPL_BINARY_1);
+        cpl_mask_set(data_bpm, 120,121, CPL_BINARY_1);
+        cpl_mask_set(data_bpm, 120,122, CPL_BINARY_1);
+        cpl_mask_set(data_bpm, 121,120, CPL_BINARY_1);
+        cpl_mask_set(data_bpm, 121,121, CPL_BINARY_1);
+        cpl_mask_set(data_bpm, 121,122, CPL_BINARY_1);
+        cpl_mask_set(data_bpm, 122,120, CPL_BINARY_1);
+        cpl_mask_set(data_bpm, 122,121, CPL_BINARY_1);
+        cpl_mask_set(data_bpm, 122,122, CPL_BINARY_1);
+        /*set one outlier on a bad pixel*/
+        cpl_image_set(data, 122, 122, 300.);
+
+        cpl_image_reject_from_mask(data, data_bpm);
+
+        errors=cpl_image_power_create(data, 0.5);
+        hdrl_image * image = hdrl_image_create(data, errors);
+
+        /* Note that for CPL_FILTER_STDEV one gets more false positives!! */
+        hdrl_parameter_delete(bpm_param) ;
+        bpm_param = hdrl_bpm_2d_parameter_create_filtersmooth(3., 3., 5, 
+                CPL_FILTER_MEDIAN, CPL_BORDER_FILTER, 3, 3) ;
+        mask_out = hdrl_bpm_2d_compute(image, bpm_param) ;
+        cpl_test_eq(cpl_mask_get(mask_out, 50, 50),   CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(mask_out, 100, 100), CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(mask_out, 150, 150), CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(mask_out, 110, 260), CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(mask_out, 122, 122), CPL_BINARY_0);
+        cpl_mask_delete(mask_out);
+
+        hdrl_parameter_delete(bpm_param) ;
+        bpm_param = hdrl_bpm_2d_parameter_create_legendresmooth(3., 3.,
+                5, 20, 20, 11, 11, 3, 3) ;
+        mask_out = hdrl_bpm_2d_compute(image, bpm_param) ;
+        cpl_test_eq(cpl_mask_get(mask_out, 50, 50),   CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(mask_out, 100, 100), CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(mask_out, 150, 150), CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(mask_out, 110, 260), CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(mask_out, 122, 122), CPL_BINARY_0);
+
+        cpl_mask_delete(data_bpm);
+        cpl_mask_delete(mask_out);
+        cpl_image_delete(data);
+        cpl_image_delete(errors);
+        hdrl_image_delete(image);
+    }
+    hdrl_parameter_delete(bpm_param) ;
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief   Unit tests of BPM module
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+    hdrl_bpm_2d_test_compute();
+    test_parlist();
+    cpl_test_error(CPL_ERROR_NONE);
+    return cpl_test_end(0);
+}
diff --git a/hdrl/tests/hdrl_bpm_3d-test.c b/hdrl/tests/hdrl_bpm_3d-test.c
new file mode 100644
index 0000000..12dc7e7
--- /dev/null
+++ b/hdrl/tests/hdrl_bpm_3d-test.c
@@ -0,0 +1,266 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013,2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_bpm_3d.h"
+#include "hdrl_image.h"
+
+#include <cpl.h>
+#include <math.h>
+#include <string.h>
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_bpm_3d_test    Testing of the HDRL bpm_3d
+ */
+/*----------------------------------------------------------------------------*/
+
+void test_parlist(void)
+{
+    /* parameter parsing smoketest */
+    hdrl_parameter * hpar;
+    hdrl_parameter * deflts = hdrl_bpm_3d_parameter_create(4, 5,
+            HDRL_BPM_3D_THRESHOLD_RELATIVE);
+    cpl_parameterlist * pos = hdrl_bpm_3d_parameter_create_parlist(
+                "RECIPE", "bpm", deflts);
+    hdrl_parameter_delete(deflts) ;
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_eq(cpl_parameterlist_get_size(pos), 3);
+
+    hpar = hdrl_bpm_3d_parameter_parse_parlist(pos, "RECIPE.invalid");
+    cpl_test_null(hpar);
+    cpl_test_error(CPL_ERROR_DATA_NOT_FOUND);
+
+    hpar = hdrl_bpm_3d_parameter_parse_parlist(pos, "RECIPE.bpm");
+    cpl_parameterlist_delete(pos);
+    cpl_test_error(CPL_ERROR_NONE);
+
+    cpl_test_eq(hdrl_bpm_3d_parameter_get_method(hpar),
+                HDRL_BPM_3D_THRESHOLD_RELATIVE);
+    cpl_test_eq(hdrl_bpm_3d_parameter_get_kappa_low(hpar), 4);
+    cpl_test_eq(hdrl_bpm_3d_parameter_get_kappa_high(hpar), 5);
+    hdrl_parameter_delete(hpar);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check hdrl_bpm_3d_compute() in various conditions
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_bpm_3d_test_compute(void)
+{
+    cpl_image       *   data = NULL;
+    cpl_mask        *   data_bpm = NULL;
+    cpl_image       *   errors = NULL;
+    cpl_imagelist   *   result_data = NULL;
+    hdrl_imagelist  *   imglist = NULL;
+    cpl_image       *   img_tmp = NULL;
+    int                 bad = 0;
+    hdrl_parameter  *   bpm_param ;
+
+    {
+        imglist = hdrl_imagelist_new();
+        for (int var = 0; var <5 ; ++var) {
+            data = cpl_image_new(200, 300, CPL_TYPE_DOUBLE);
+            data_bpm = cpl_mask_new(200, 300);
+            /* STDEV is about 10 for these images */
+            cpl_image_fill_noise_uniform(data, 82, 118);
+            if(var == 0) {
+                /* Negative outlier set and marked as bad */
+                cpl_image_set(data,    10, 10, 20.);
+                cpl_mask_set(data_bpm, 10, 10, CPL_BINARY_1);
+
+                /* Positive outlier set and marked as bad */
+                cpl_image_set(data,    50, 50, 300.);
+                cpl_mask_set(data_bpm, 50, 50, CPL_BINARY_1);
+
+                /* Positive outliers set */
+                cpl_image_set(data,   60, 60, 300.);
+                cpl_image_set(data,   61, 61, 300.);
+                cpl_image_set(data,   62, 62, 300.);
+
+                /* Negative outliers set */
+                cpl_image_set(data,   70, 70, 20.);
+                cpl_image_set(data,   71, 71, 20.);
+                cpl_image_set(data,   72, 72, 20.);
+
+                /*Some pixels marked as bad*/
+                cpl_mask_set(data_bpm, 80,  80, CPL_BINARY_1);
+                cpl_mask_set(data_bpm, 81,  80, CPL_BINARY_1);
+                cpl_mask_set(data_bpm, 82,  80, CPL_BINARY_1);
+
+            } else if (var == 3) {
+                cpl_image_set(data, 150, 150, 300.);
+                cpl_image_set(data, 110, 260, 300.);
+                cpl_mask_set(data_bpm, 70, 70, CPL_BINARY_1);
+                cpl_mask_set(data_bpm, 80, 80, CPL_BINARY_1);
+            }
+
+            cpl_image_reject_from_mask(data, data_bpm);
+            errors=cpl_image_power_create(data, 0.5);
+            hdrl_image * image = hdrl_image_create(data, errors);
+
+            hdrl_imagelist_set(imglist, image, var);
+            /* free the memory */
+            cpl_mask_delete(data_bpm);
+            cpl_image_delete(data);
+            cpl_image_delete(errors);
+
+        }
+        //----------------------------------------------------------------------
+        bpm_param = hdrl_bpm_3d_parameter_create(-50.0, 50.0,
+                HDRL_BPM_3D_THRESHOLD_ABSOLUTE) ;
+        result_data = hdrl_bpm_3d_compute(imglist, bpm_param);
+        hdrl_parameter_delete(bpm_param) ;
+        img_tmp = cpl_imagelist_get(result_data, 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 10, 10, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 50, 50, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 60, 60, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 61, 61, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 62, 62, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 70, 70, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 71, 71, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 72, 72, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 80, 80, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 81, 80, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 82, 80, &bad), 0);
+        cpl_imagelist_delete(result_data);
+        //----------------------------------------------------------------------
+
+        //----------------------------------------------------------------------
+        bpm_param = hdrl_bpm_3d_parameter_create(5., 5.,
+                HDRL_BPM_3D_THRESHOLD_RELATIVE) ;
+        result_data = hdrl_bpm_3d_compute(imglist, bpm_param);
+        hdrl_parameter_delete(bpm_param) ;
+        img_tmp = cpl_imagelist_get(result_data, 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 10, 10, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 50, 50, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 60, 60, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 61, 61, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 62, 62, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 70, 70, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 71, 71, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 72, 72, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 80, 80, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 81, 80, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 82, 80, &bad), 0);
+        cpl_imagelist_delete(result_data);
+        //----------------------------------------------------------------------
+
+        //----------------------------------------------------------------------
+        bpm_param = hdrl_bpm_3d_parameter_create(5., 5.,
+                HDRL_BPM_3D_THRESHOLD_ERROR) ;
+        result_data = hdrl_bpm_3d_compute(imglist, bpm_param);
+        hdrl_parameter_delete(bpm_param) ;
+        cpl_test_error(CPL_ERROR_NONE);
+
+        img_tmp = cpl_imagelist_get(result_data, 0);
+
+        cpl_test_eq(cpl_image_get(img_tmp, 10, 10, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 50, 50, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 60, 60, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 61, 61, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 62, 62, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 70, 70, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 71, 71, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 72, 72, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 80, 80, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 81, 80, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 82, 80, &bad), 0);
+        /*cpl_imagelist_save(result_data, "result.fits", CPL_TYPE_INT, NULL,
+          CPL_IO_CREATE);*/
+        cpl_imagelist_delete(result_data);
+        //----------------------------------------------------------------------
+
+        //----------------------------------------------------------------------
+        bpm_param = hdrl_bpm_3d_parameter_create(500., 5.,
+                HDRL_BPM_3D_THRESHOLD_ERROR) ;
+        result_data = hdrl_bpm_3d_compute(imglist, bpm_param);
+        hdrl_parameter_delete(bpm_param) ;
+        cpl_test_error(CPL_ERROR_NONE);
+
+        img_tmp = cpl_imagelist_get(result_data, 0);
+
+        cpl_test_eq(cpl_image_get(img_tmp, 10, 10, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 50, 50, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 60, 60, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 61, 61, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 62, 62, &bad), 1);
+        cpl_test_eq(cpl_image_get(img_tmp, 70, 70, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 71, 71, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 72, 72, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 80, 80, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 81, 80, &bad), 0);
+        cpl_test_eq(cpl_image_get(img_tmp, 82, 80, &bad), 0);
+        cpl_imagelist_delete(result_data);
+        //----------------------------------------------------------------------
+
+        bpm_param = hdrl_bpm_3d_parameter_create(5., 5.,
+                HDRL_BPM_3D_THRESHOLD_ERROR) ;
+        result_data = hdrl_bpm_3d_compute(NULL, bpm_param);
+        hdrl_parameter_delete(bpm_param) ;
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+        bpm_param = hdrl_bpm_3d_parameter_create(5.1, 5.,
+                HDRL_BPM_3D_THRESHOLD_ABSOLUTE) ;
+        result_data = hdrl_bpm_3d_compute(imglist, bpm_param);
+        hdrl_parameter_delete(bpm_param) ;
+        cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+        bpm_param = hdrl_bpm_3d_parameter_create(-5., 5.,
+                HDRL_BPM_3D_THRESHOLD_RELATIVE) ;
+        result_data = hdrl_bpm_3d_compute(imglist, bpm_param);
+        hdrl_parameter_delete(bpm_param) ;
+        cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+        bpm_param = hdrl_bpm_3d_parameter_create(-5., 5.,
+                HDRL_BPM_3D_THRESHOLD_ERROR) ;
+        result_data = hdrl_bpm_3d_compute(imglist, bpm_param);
+        hdrl_parameter_delete(bpm_param) ;
+        cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+        bpm_param = hdrl_bpm_3d_parameter_create(5., -5.,
+                HDRL_BPM_3D_THRESHOLD_ERROR) ;
+        result_data = hdrl_bpm_3d_compute(imglist, bpm_param);
+        hdrl_parameter_delete(bpm_param) ;
+        cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+        hdrl_imagelist_delete(imglist);
+    }
+    return cpl_error_get_code();
+}
+
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief   Unit tests of BPM module
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+    hdrl_bpm_3d_test_compute();
+    test_parlist();
+    cpl_test_error(CPL_ERROR_NONE);
+    return cpl_test_end(0);
+}
diff --git a/hdrl/tests/hdrl_bpm_fit-test.c b/hdrl/tests/hdrl_bpm_fit-test.c
new file mode 100644
index 0000000..996066c
--- /dev/null
+++ b/hdrl/tests/hdrl_bpm_fit-test.c
@@ -0,0 +1,227 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_bpm_fit.h"
+
+#include <cpl.h>
+#include <math.h>
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_bpm_fit_test    Testing of the HDRL bpm_fit
+ */
+/*----------------------------------------------------------------------------*/
+
+void test_invalid_parameter(void)
+{
+    hdrl_parameter * p;
+    /* invalid degree */
+    p = hdrl_bpm_fit_parameter_create_pval(-1, 0.1);
+    cpl_test_null(p);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    p = hdrl_bpm_fit_parameter_create_rel_chi(-1, 0.1, 0.1);
+    cpl_test_null(p);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    p = hdrl_bpm_fit_parameter_create_rel_coef(-1, 0.1, 0.1);
+    cpl_test_null(p);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    /* invalid threshold */
+    p = hdrl_bpm_fit_parameter_create_pval(1, -0.1);
+    cpl_test_null(p);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    p = hdrl_bpm_fit_parameter_create_pval(1, 100.1);
+    cpl_test_null(p);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    p = hdrl_bpm_fit_parameter_create_rel_chi(1, -0.1, 0.1);
+    cpl_test_null(p);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    p = hdrl_bpm_fit_parameter_create_rel_coef(1, -0.1, -0.1);
+    cpl_test_null(p);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    /* NULL input */
+    hdrl_bpm_fit_parameter_get_pval(NULL);
+    cpl_test_error(CPL_ERROR_NULL_INPUT);
+    hdrl_bpm_fit_parameter_get_rel_chi_low(NULL);
+    cpl_test_error(CPL_ERROR_NULL_INPUT);
+    hdrl_bpm_fit_parameter_get_rel_coef_high(NULL);
+    cpl_test_error(CPL_ERROR_NULL_INPUT);
+}
+
+void test_parameter(void)
+{
+    hdrl_parameter * p;
+
+    p = hdrl_bpm_fit_parameter_create_pval(1, 10.);
+    cpl_test_abs(hdrl_bpm_fit_parameter_get_pval(p), 10., 0);
+    cpl_test_lt((hdrl_bpm_fit_parameter_get_rel_chi_low(p)), 0);
+    cpl_test_lt((hdrl_bpm_fit_parameter_get_rel_coef_high(p)), 0);
+    hdrl_parameter_delete(p);
+
+    p = hdrl_bpm_fit_parameter_create_rel_chi(1, 10., 5.);
+    cpl_test_eq(hdrl_bpm_fit_parameter_get_rel_chi_low(p), 10.);
+    cpl_test_eq(hdrl_bpm_fit_parameter_get_rel_chi_high(p), 5.);
+    cpl_test_lt(hdrl_bpm_fit_parameter_get_pval(p), 0);
+    cpl_test_lt(hdrl_bpm_fit_parameter_get_rel_coef_low(p), 0);
+    cpl_test_lt(hdrl_bpm_fit_parameter_get_rel_coef_high(p), 0);
+    hdrl_parameter_delete(p);
+
+    p = hdrl_bpm_fit_parameter_create_rel_coef(1, 10., 3.);
+    cpl_test_eq(hdrl_bpm_fit_parameter_get_rel_coef_low(p), 10.);
+    cpl_test_eq(hdrl_bpm_fit_parameter_get_rel_coef_high(p), 3.);
+    cpl_test_lt(hdrl_bpm_fit_parameter_get_pval(p), 0);
+    cpl_test_lt(hdrl_bpm_fit_parameter_get_rel_chi_low(p), 0);
+    cpl_test_lt(hdrl_bpm_fit_parameter_get_rel_chi_high(p), 0);
+    hdrl_parameter_delete(p);
+}
+
+void test_parameterlist(void)
+{
+    hdrl_parameter * p;
+    hdrl_parameter * def;
+    cpl_parameterlist * parlist;
+
+    def = hdrl_bpm_fit_parameter_create_pval(-2, 0.1) ;
+    parlist = hdrl_bpm_fit_parameter_create_parlist("RECIPE", "bpm_fit", def);
+    hdrl_parameter_delete(def); 
+    p = hdrl_bpm_fit_parameter_parse_parlist(parlist, "RECIPE.bpm_fit");
+    cpl_test_null(p);
+    cpl_test_error(CPL_ERROR_NULL_INPUT);
+    cpl_parameterlist_delete(parlist);
+
+    def = hdrl_bpm_fit_parameter_create_pval(2, -1) ;
+    parlist = hdrl_bpm_fit_parameter_create_parlist("RECIPE", "bpm_fit", def);
+    hdrl_parameter_delete(def); 
+    p = hdrl_bpm_fit_parameter_parse_parlist(parlist, "RECIPE.bpm_fit");
+    cpl_test_null(p);
+    cpl_test_error(CPL_ERROR_NULL_INPUT);
+    cpl_parameterlist_delete(parlist);
+
+    def = hdrl_bpm_fit_parameter_create_pval(2, 0.1) ;
+    parlist = hdrl_bpm_fit_parameter_create_parlist("RECIPE", "bpm_fit", def);
+    hdrl_parameter_delete(def); 
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_eq(cpl_parameterlist_get_size(parlist), 6);
+
+    p = hdrl_bpm_fit_parameter_parse_parlist(parlist, "RECIPE.invalid");
+    cpl_test_null(p);
+    cpl_test_error(CPL_ERROR_DATA_NOT_FOUND);
+
+    p = hdrl_bpm_fit_parameter_parse_parlist(parlist, "RECIPE.bpm_fit");
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_eq(cpl_parameterlist_get_size(parlist), 6);
+    cpl_test_eq(hdrl_bpm_fit_parameter_get_degree(p), 2);
+    cpl_test_abs(hdrl_bpm_fit_parameter_get_pval(p), 0.1, 0);
+    hdrl_parameter_delete(p);
+    cpl_parameterlist_delete(parlist);
+
+    def = hdrl_bpm_fit_parameter_create_rel_chi(2, 3., 2.) ;
+    parlist = hdrl_bpm_fit_parameter_create_parlist( "RECIPE", "bpm_fit", def);
+    hdrl_parameter_delete(def); 
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_eq(cpl_parameterlist_get_size(parlist), 6);
+    p = hdrl_bpm_fit_parameter_parse_parlist(parlist, "RECIPE.bpm_fit");
+    cpl_test_eq(hdrl_bpm_fit_parameter_get_degree(p), 2);
+    cpl_test_eq(hdrl_bpm_fit_parameter_get_rel_chi_low(p), 3.);
+    cpl_test_eq(hdrl_bpm_fit_parameter_get_rel_chi_high(p), 2.);
+    hdrl_parameter_delete(p);
+    cpl_parameterlist_delete(parlist);
+
+    def = hdrl_bpm_fit_parameter_create_rel_coef(2, 2., 3.) ;
+    parlist = hdrl_bpm_fit_parameter_create_parlist("RECIPE", "bpm_fit", def);
+    hdrl_parameter_delete(def); 
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_eq(cpl_parameterlist_get_size(parlist), 6);
+    p = hdrl_bpm_fit_parameter_parse_parlist(parlist, "RECIPE.bpm_fit");
+    cpl_test_eq(hdrl_bpm_fit_parameter_get_degree(p), 2);
+    cpl_test_eq(hdrl_bpm_fit_parameter_get_rel_coef_low(p), 2.);
+    cpl_test_eq(hdrl_bpm_fit_parameter_get_rel_coef_high(p), 3.);
+    hdrl_parameter_delete(p);
+    cpl_parameterlist_delete(parlist);
+}
+
+void test_bpm_fit(void)
+{
+    int rej;
+    hdrl_imagelist * hl = hdrl_imagelist_new();
+    cpl_vector * sample = cpl_vector_new(10);
+    for (size_t i = 0; i < 10; i++) {
+        hdrl_image * himg =  hdrl_image_new(13, 4);
+        hdrl_image_add_scalar(himg, (hdrl_value){i + 1, sqrt(i + 1)});
+        hdrl_image_set_pixel(himg, 1, 1, (hdrl_value){1.01, 1.});
+        hdrl_imagelist_set(hl, himg, i);
+        cpl_vector_set(sample, i, i);
+    }
+
+    hdrl_parameter * p;
+    cpl_image * out_mask;
+
+    p = hdrl_bpm_fit_parameter_create_pval(1, 0.1);
+    hdrl_bpm_fit_compute(p, hl, sample, &out_mask);
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_eq(cpl_image_get_flux(out_mask), 0.);
+    cpl_image_delete(out_mask);
+    hdrl_parameter_delete(p);
+
+    p = hdrl_bpm_fit_parameter_create_rel_coef(1, 1., 1.);
+    hdrl_bpm_fit_compute(p, hl, sample, &out_mask);
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_eq(cpl_image_get(out_mask, 1, 1, &rej), 3);
+    cpl_image_delete(out_mask);
+    hdrl_parameter_delete(p);
+
+    p = hdrl_bpm_fit_parameter_create_rel_chi(1, 1., 1.);
+    hdrl_image_add_scalar(hdrl_imagelist_get(hl, 4),
+                          (hdrl_value){5.1 , sqrt(5.1)});
+    hdrl_bpm_fit_compute(p, hl, sample, &out_mask);
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_eq(cpl_image_get_flux(out_mask), 1.);
+    cpl_test_eq(cpl_image_get(out_mask, 1, 1, &rej), 1.);
+    cpl_image_delete(out_mask);
+    hdrl_parameter_delete(p);
+
+    hdrl_imagelist_delete(hl);
+    cpl_vector_delete(sample);
+}
+
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief   Unit tests of BPM module
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+    test_invalid_parameter();
+    test_parameter();
+    test_parameterlist();
+    test_bpm_fit();
+    cpl_test_error(CPL_ERROR_NONE);
+    return cpl_test_end(0);
+}
diff --git a/hdrl/tests/hdrl_bpm_utils-test.c b/hdrl/tests/hdrl_bpm_utils-test.c
new file mode 100644
index 0000000..208c25b
--- /dev/null
+++ b/hdrl/tests/hdrl_bpm_utils-test.c
@@ -0,0 +1,414 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_bpm_utils.h"
+#include "hdrl_image.h"
+
+#include <cpl.h>
+#include <math.h>
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_bpm_utils_test    Testing of the HDRL bpm_utils
+ */
+/*----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check hdrl_bpm_to_mask() in various conditions
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_bpm_test_bpm_to_mask(void)
+{
+    cpl_size nx = 20;
+    cpl_size ny = 20;
+    {
+        cpl_mask * mask = hdrl_bpm_to_mask(NULL, 0);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+        cpl_test_null(mask);
+    }
+    /* non int input */
+    {
+        cpl_image * bpm = cpl_image_new(nx, ny, CPL_TYPE_DOUBLE);
+        cpl_mask * mask = hdrl_bpm_to_mask(bpm, 0);
+        cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+        cpl_test_null(mask);
+        cpl_image_delete(bpm);
+
+        /* too big mask */
+        bpm = cpl_image_new(nx, ny, CPL_TYPE_INT);
+        mask = hdrl_bpm_to_mask(bpm, ~0LLU);
+        cpl_test_null(mask);
+        cpl_test_error(CPL_ERROR_UNSUPPORTED_MODE);
+
+        cpl_image_delete(bpm);
+    }
+    /* empty bpm */
+    {
+        cpl_image * bpm = cpl_image_new(nx, ny, CPL_TYPE_INT);
+        cpl_mask * mask = NULL;
+        mask = hdrl_bpm_to_mask(bpm, 0);
+        cpl_test_nonnull(mask);
+        cpl_test_eq(cpl_mask_count(mask), 0);
+        cpl_image_delete(bpm);
+        cpl_mask_delete(mask);
+    }
+    /* range of codes */
+    {
+        cpl_image * bpm = cpl_image_new(nx, ny, CPL_TYPE_INT);
+        cpl_mask * mask = NULL;
+        cpl_image_set(bpm, 1, 1, 1);
+        cpl_image_set(bpm, 1, 2, 2);
+        cpl_image_set(bpm, 1, 3, 3);
+        cpl_image_set(bpm, 1, 4, 4);
+
+        mask = hdrl_bpm_to_mask(bpm, 1);
+        cpl_test_nonnull(mask);
+        cpl_test_eq(cpl_mask_count(mask), 2);
+        cpl_mask_delete(mask);
+
+        mask = hdrl_bpm_to_mask(bpm, ~0u);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_test_nonnull(mask);
+        cpl_test_eq(cpl_mask_count(mask), 4);
+        cpl_mask_delete(mask);
+
+        cpl_image_delete(bpm);
+    }
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check hdrl_mask_to_bpm() in various conditions
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_bpm_test_mask_to_bpm(void)
+{
+    cpl_size nx = 20;
+    cpl_size ny = 20;
+    {
+        cpl_image * bpm = hdrl_mask_to_bpm(NULL, 0);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+        cpl_test_null(bpm);
+    }
+    /* empty mask */
+    {
+        cpl_image * bpm;
+        cpl_mask * mask = cpl_mask_new(nx, ny);
+        bpm = hdrl_mask_to_bpm(mask, 0);
+        cpl_test_nonnull(bpm);
+        cpl_test_eq(cpl_image_get_flux(bpm), 0);
+        cpl_image_delete(bpm);
+        cpl_mask_delete(mask);
+    }
+    /* non-empty mask */
+    {
+        cpl_image * bpm = NULL;
+        cpl_mask * mask = cpl_mask_new(nx, ny);
+        cpl_mask_set(mask, 1, 1, CPL_BINARY_1);
+        cpl_mask_set(mask, 1, 2, CPL_BINARY_1);
+        cpl_mask_set(mask, 1, 3, CPL_BINARY_1);
+        cpl_mask_set(mask, 1, 4, CPL_BINARY_1);
+
+        bpm = hdrl_mask_to_bpm(mask, 1);
+        cpl_test_nonnull(bpm);
+        cpl_test_eq(cpl_image_get_flux(bpm), 4);
+        cpl_image_delete(bpm);
+
+        bpm = hdrl_mask_to_bpm(mask, 5);
+        cpl_test_nonnull(bpm);
+        cpl_test_eq(cpl_image_get_flux(bpm), 5 * 4);
+        cpl_image_delete(bpm);
+
+        cpl_mask_delete(mask);
+    }
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check hdrl_bpm_filter() in various conditions
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_bpm_test_hdrl_bpm_filter(void)
+{
+    cpl_mask  * img_mask = NULL;
+
+    img_mask = cpl_mask_new(200, 300);
+
+    cpl_mask_set(img_mask,  50,  50, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 100, 100, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 150, 150, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 100, 250, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 100, 252, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 100, 254, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 100, 256, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 102, 252, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 102, 254, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 102, 256, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 198, 252, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 198, 254, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 198, 256, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 200, 252, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 200, 254, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 200, 256, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 199, 300, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 199, 299, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 199, 298, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 200, 300, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 200, 299, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 200, 298, CPL_BINARY_1);
+    /*Test the border behaviour*/
+    cpl_mask_set(img_mask, 199, 200, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 199, 198, CPL_BINARY_1);
+
+
+    /*cpl_mask_save(img_mask, "img_mask.fits", NULL, CPL_IO_CREATE);*/
+
+    {
+        cpl_mask * filtered_mask = NULL;
+        filtered_mask = hdrl_bpm_filter(img_mask, 3, 3, CPL_FILTER_CLOSING);
+
+        cpl_test_eq(cpl_mask_get(filtered_mask, 100, 255),  CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(filtered_mask, 101, 255),  CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(filtered_mask, 102, 255),  CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(filtered_mask, 103, 255),  CPL_BINARY_0);
+
+        cpl_test_eq(cpl_mask_get(filtered_mask, 100, 251),  CPL_BINARY_1);
+
+        cpl_test_eq(cpl_mask_get(filtered_mask, 198, 255),  CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(filtered_mask, 199, 255),  CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(filtered_mask, 200, 255),  CPL_BINARY_1);
+
+        cpl_test_eq(cpl_mask_get(filtered_mask, 198, 254),  CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(filtered_mask, 199, 254),  CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(filtered_mask, 200, 254),  CPL_BINARY_1);
+
+        /*Test the border behaviour*/
+        cpl_test_eq(cpl_mask_get(filtered_mask, 200, 199),  CPL_BINARY_0);
+
+         /*cpl_mask_save(filtered_mask, "filtered_closing_mask.fits", NULL,
+                      CPL_IO_CREATE);*/
+        cpl_mask_delete(filtered_mask);
+    }
+
+    /* free the memory */
+    cpl_mask_delete(img_mask);
+
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Can be used to test additional bad pixel growing algoritms 
+  @return cpl_error_code
+  NOT TRIGGERED
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_bpm_test_bpmgrow(void)
+{
+    return cpl_error_get_code();
+
+    cpl_mask  * img_mask = NULL;
+    img_mask = cpl_mask_new(200, 300);
+    cpl_mask_set(img_mask,  50,  50, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 100, 100, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 150, 150, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 100, 250, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 100, 252, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 100, 254, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 100, 256, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 102, 252, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 102, 254, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 102, 256, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 198, 252, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 198, 254, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 198, 256, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 200, 252, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 200, 254, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 200, 256, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 199, 300, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 199, 299, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 199, 298, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 200, 300, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 200, 299, CPL_BINARY_1);
+    cpl_mask_set(img_mask, 200, 298, CPL_BINARY_1);
+
+    cpl_mask_save(img_mask, "img_mask.fits", NULL, CPL_IO_CREATE);
+
+    if(1){
+          /* Set all pixels to bad, if there are a predefined number of bad
+           * pixels in the neighborhood - it uses the morpho filter which
+           * is much slower than e.g. the CPL_FILTER_AVERAGE_FAST filter */
+
+        cpl_matrix * kernel = cpl_matrix_new(3, 3);
+        cpl_matrix_fill(kernel, 1.0);
+        cpl_image * result_data = cpl_image_new_from_mask(img_mask);
+
+        cpl_image * filtered_data = cpl_image_new(
+                        cpl_image_get_size_x(result_data),
+                        cpl_image_get_size_y(result_data),
+                        CPL_TYPE_FLOAT);
+
+        cpl_image_filter(filtered_data, result_data, kernel,
+                         CPL_FILTER_MORPHO_SCALE, CPL_BORDER_FILTER);
+
+
+        cpl_mask * filtered_mask = cpl_mask_threshold_image_create(
+                        filtered_data, 3.-0.5, DBL_MAX);
+
+        cpl_mask_save(filtered_mask, "filtered_morpho_mask.fits", NULL,
+                      CPL_IO_CREATE);
+
+        cpl_mask_delete(filtered_mask);
+        cpl_image_delete(result_data);
+        cpl_image_delete(filtered_data);
+        cpl_matrix_delete(kernel);
+
+    }
+
+    if(1){
+        /* Set all pixels to bad, if there are a predefined number of bad
+         * pixels in the neighborhood - it uses the CPL_FILTER_AVERAGE_FAST
+         * filter. This filter is fast but shrinks the window at the border.
+         * Therefore a simple scaling to the number of bad pixels in the
+         * neighborhood (nx * ny * average) can not be done at the image-border.
+         * Nevertheless one can never detect less, but only more neighboring
+         * bad pixels near the border (the bad pixel density increases at the
+         * border as the windows shrinks) -
+         * so it would be a conservative approach.
+         *
+         *  */
+
+        cpl_mask * kernel = cpl_mask_new(3, 3);
+        cpl_mask_not(kernel); /* All values set to unity*/
+
+
+        cpl_image * result_data = cpl_image_new_from_mask(img_mask);
+
+        cpl_image * filtered_data = cpl_image_new(
+                        cpl_image_get_size_x(result_data),
+                        cpl_image_get_size_y(result_data),
+                        CPL_TYPE_FLOAT);
+
+
+
+        cpl_image_filter_mask(filtered_data, result_data, kernel,
+                              CPL_FILTER_AVERAGE_FAST, CPL_BORDER_FILTER);
+
+
+
+        cpl_mask * filtered_mask = cpl_mask_threshold_image_create(
+                        filtered_data, (3.-0.5)/(3.*3.), DBL_MAX);
+
+
+        cpl_mask_save(filtered_mask, "filtered_average_mask.fits", NULL, CPL_IO_CREATE);
+
+        cpl_mask_delete(filtered_mask);
+        cpl_image_delete(result_data);
+        cpl_image_delete(filtered_data);
+        cpl_mask_delete(kernel);
+
+    }
+
+    if(1){
+        /* This algo first smoothed the bad pixels by a gaussian kernel and
+         * then one can use a threshold to detect new bad pixels on the
+         * smoothed image. Here it is difficult to find good parameters for the
+         * gaussian and the subsequent thresholding.
+         *  */
+
+        double sig_x = 3.;   /*Sigma in x for the gaussian distribution.*/
+        double sig_y = 3.;   /*Sigma in y for the gaussian distribution.*/
+
+
+        /* creating the Gaussian kernel */
+        cpl_size n = 5;
+        cpl_image * gauss = cpl_image_new(2 * n + 1, 2 * n + 1, CPL_TYPE_DOUBLE);
+
+        cpl_image_fill_gaussian(gauss, n + 1, n + 1, (double)121.0, sig_x, sig_y);
+
+        /* filtering the image */
+        cpl_matrix * kernel = cpl_matrix_wrap(2 * n + 1, 2 * n + 1,
+                                     cpl_image_get_data_double(gauss));
+        /*cpl_image_filter(im1, im2, gauss_data, CPL_FILTER_LINEAR,
+                         CPL_BORDER_FILTER);*/
+
+        /*cpl_matrix * kernel = cpl_matrix_new(3, 3);
+        cpl_matrix_fill(kernel, 1.0);*/
+
+        cpl_image * result_data = cpl_image_new_from_mask(img_mask);
+
+        cpl_image * filtered_data = cpl_image_new(
+                        cpl_image_get_size_x(result_data),
+                        cpl_image_get_size_y(result_data),
+                        CPL_TYPE_DOUBLE);
+
+        cpl_image_filter(filtered_data, result_data, kernel,
+                         CPL_FILTER_LINEAR, CPL_BORDER_FILTER);
+
+
+        cpl_mask * filtered_mask = cpl_mask_threshold_image_create(
+                        filtered_data, 3.-0.5, DBL_MAX);
+
+        cpl_image_save(filtered_data, "filtered_gauss_data.fits",
+                       CPL_TYPE_DOUBLE, NULL, CPL_IO_CREATE);
+        cpl_image_save(gauss, "gauss.fits",
+                       CPL_TYPE_DOUBLE, NULL, CPL_IO_CREATE);
+
+        cpl_mask_save(filtered_mask, "filtered_gauss_mask.fits", NULL, CPL_IO_CREATE);
+
+        cpl_matrix_unwrap(kernel);
+        cpl_image_delete(gauss);
+        cpl_mask_delete(filtered_mask);
+        cpl_image_delete(result_data);
+        cpl_image_delete(filtered_data);
+    }
+    /* free the memory */
+    cpl_mask_delete(img_mask);
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief   Unit tests of BPM module
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+    hdrl_bpm_test_bpm_to_mask();
+    hdrl_bpm_test_mask_to_bpm();
+    hdrl_bpm_test_hdrl_bpm_filter();
+    hdrl_bpm_test_bpmgrow() ;
+    cpl_test_error(CPL_ERROR_NONE);
+    return cpl_test_end(0);
+}
diff --git a/hdrl/tests/hdrl_buffer-test.c b/hdrl/tests/hdrl_buffer-test.c
new file mode 100644
index 0000000..74f57bb
--- /dev/null
+++ b/hdrl/tests/hdrl_buffer-test.c
@@ -0,0 +1,98 @@
+/* $Id: hdrl_buffer-test.c,v 1.1 2013-10-23 09:13:56 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-23 09:13:56 $
+ * $Revision: 1.1 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#ifndef _POSIX_C_SOURCE
+#define _POSIX_C_SOURCE 200112L
+#endif
+#include "hdrl_buffer.h"
+
+#include <cpl.h>
+
+#include <stdlib.h>
+#include <string.h>
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_buffer_test   
+            Testing of hdrl_buffer module
+ */
+/*----------------------------------------------------------------------------*/
+
+cpl_error_code test_basic(void)
+{
+    hdrl_buffer * buf = hdrl_buffer_new();
+    char * p2 = hdrl_buffer_allocate(buf, 10023);
+    memset(p2, 1, 10023);
+    hdrl_buffer_free(buf, p2);
+    hdrl_buffer_delete(buf);
+
+    cpl_msg_info(cpl_func, "test pool <= object");
+    buf = hdrl_buffer_new();
+    for (size_t i = 0; i < 100; i++) {
+        char * p = hdrl_buffer_allocate(buf, 1<<20);
+        memset(p, 1, 1<<20);
+        hdrl_buffer_free(buf, p);
+    }
+    hdrl_buffer_delete(buf);
+
+    cpl_msg_info(cpl_func, "test pool > object");
+    buf = hdrl_buffer_new();
+    for (size_t i = 0; i < 1000; i++) {
+        char * p = hdrl_buffer_allocate(buf, 1<<18);
+        p[(1<<18) - 1] = 1;
+        hdrl_buffer_free(buf, p);
+    }
+    hdrl_buffer_delete(buf);
+
+    return cpl_error_get_code();
+}
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ @brief   Unit tests of hdrl_image
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+
+    test_basic();
+    setenv("HDRL_BUFFER_MALLOC", "1", 1);
+    test_basic();
+
+    return cpl_test_end(0);
+}
diff --git a/hdrl/tests/hdrl_collapse-test.c b/hdrl/tests/hdrl_collapse-test.c
new file mode 100644
index 0000000..dcbe03e
--- /dev/null
+++ b/hdrl/tests/hdrl_collapse-test.c
@@ -0,0 +1,635 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013,2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_combine.h"
+#include "hdrl_iter.h"
+#include "hdrl_types.h"
+#include <cpl.h>
+
+#include <math.h>
+#include <stdlib.h>
+
+#ifndef ARRAY_LEN
+#define ARRAY_LEN(a) sizeof((a))/sizeof((a)[0])
+#endif
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_collapse_test   Testing of the HDRL reduce module
+ */
+/*----------------------------------------------------------------------------*/
+typedef struct {
+    double v1;
+    double v2;
+} pair;
+
+/* cpl_test_abs that handles nan, rej is the rej variable of cpl_image_get to
+ * test if NAN is marked as a bad pixel or -1 if not applicable */
+#define hdrl_test_abs(a, b, tol, rej) \
+    if (isnan(a)) { \
+        cpl_test(isnan(a) == isnan(b)); \
+        cpl_test(rej == -1 || rej != 0); \
+    } \
+    else { \
+        cpl_test_abs(a, b, tol); \
+    }
+
+
+/* cpl_image_get that really returns the value regardless of bad or not */
+static double
+_hdrl_image_get(cpl_image * img, cpl_size x, cpl_size y, int * rej)
+{
+    double v = cpl_image_get(img, x, y, rej);
+    if (*rej) {
+        size_t nx = cpl_image_get_size_x(img);
+        if (cpl_image_get_type(img) == CPL_TYPE_DOUBLE) {
+            v = cpl_image_get_data_double(img)[(y - 1) * nx + (x - 1)];
+        }
+        else {
+            v = cpl_image_get_data_float(img)[(y - 1) * nx + (x - 1)];
+        }
+    }
+    return v;
+}
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief convert list to image format to list to vector format
+ *
+ * @param data  image
+ * @param errs  errors
+ * @param x     x coordinate to extract (FITS)
+ * @param y     y coordinate to extract (FITS)
+ * @param vl    imagelist to put new data list into
+ * @param el    imagelist to put new error list into
+ */
+/* ---------------------------------------------------------------------------*/
+static void
+prep_l2v_input(cpl_imagelist * data,
+               cpl_imagelist * errs,
+               cpl_size x,
+               cpl_size y,
+               cpl_imagelist * vl,
+               cpl_imagelist * el)
+{
+    int d;
+    size_t n = cpl_imagelist_get_size(data);
+    cpl_image * vimg = cpl_image_new(1, n, HDRL_TYPE_DATA);
+    cpl_image * verr = cpl_image_new(1, n, HDRL_TYPE_ERROR);
+    for (size_t i = 0; i < n; i++) {
+        cpl_image * img = cpl_imagelist_get(data, i);
+        cpl_image_set(vimg, 1, i + 1, cpl_image_get(img, x, y, &d));
+        if (d) {
+            cpl_image_reject(vimg, 1, i + 1);
+        }
+        img = cpl_imagelist_get(errs, i);
+        cpl_image_set(verr, 1, i + 1, cpl_image_get(img, x, y, &d));
+        if (d) {
+            cpl_image_reject(verr, 1, i + 1);
+        }
+    }
+    cpl_imagelist_set(vl, vimg, 0);
+    cpl_imagelist_set(el, verr, 0);
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief test list to image and list to vector collapses
+ *
+ * @param data  data for list to image
+ * @param errs  errors for list to image
+ * @param l2im  list to image reduction method
+ * @param l2vm  list to vector reduction method
+ * @param x     x coordinate to extract for l2v (FITS)
+ * @param y     y coordinate to extract for l2v (FITS)
+ * @param v     value tolerance pair for expected data result at x, y
+ * @param e     value tolerance pair for expected error result at x, y
+ * @param expcontrib  expected contribution map
+ */
+/* ---------------------------------------------------------------------------*/
+void test_l2i_and_l2v(cpl_imagelist * data,
+                      cpl_imagelist * errs,
+                      hdrl_collapse_imagelist_to_image_t * l2im,
+                      hdrl_collapse_imagelist_to_vector_t * l2vm,
+                      cpl_size x,
+                      cpl_size y,
+                      pair v,
+                      pair e,
+                      cpl_image * expcontrib)
+{
+    int d;
+    /* test list to image */
+    cpl_image * outimg, *outerr, *contrib;
+    hdrl_imagelist_combine(data, errs, l2im, &outimg, &outerr, &contrib);
+
+    hdrl_test_abs(_hdrl_image_get(outimg, x, y, &d), v.v1, v.v2, d);
+    hdrl_test_abs(_hdrl_image_get(outerr, x, y, &d), e.v1, e.v2, d);
+    cpl_test_image_abs(contrib, expcontrib, 0);
+    cpl_image_delete(outimg);
+    cpl_image_delete(outerr);
+    cpl_image_delete(contrib);
+
+    /* map the list to image input into a list to vector input that should give
+     * the same result */
+    cpl_imagelist * vl = cpl_imagelist_new();
+    cpl_imagelist * el = cpl_imagelist_new();
+    prep_l2v_input(data, errs, x, y, vl, el);
+
+    /* test list to vector */
+    cpl_vector * voutimg, *vouterr;
+    cpl_array * acontrib;
+    hdrl_collapse_imagelist_to_vector_call(l2vm, vl, el,
+                                           &voutimg, &vouterr, &acontrib,
+                                           NULL);
+    cpl_imagelist_delete(vl);
+    cpl_imagelist_delete(el);
+    if (voutimg) {
+        hdrl_test_abs(cpl_vector_get(voutimg, 0), v.v1, v.v2, -1);
+        hdrl_test_abs(cpl_vector_get(vouterr, 0), e.v1, e.v2, -1);
+        cpl_test_abs(cpl_array_get_int(acontrib, 0, NULL),
+                     cpl_image_get(expcontrib, x, y, &d), 0);
+    }
+    else {
+        cpl_test_abs(cpl_image_get(expcontrib, x, y, &d), 0, 0);
+    }
+
+    cpl_vector_delete(voutimg);
+    cpl_vector_delete(vouterr);
+    cpl_array_delete(acontrib);
+    hdrl_collapse_imagelist_to_image_delete(l2im);
+    hdrl_collapse_imagelist_to_vector_delete(l2vm);
+}
+
+void test_parameters(void)
+{
+    hdrl_parameter * hpar = hdrl_collapse_mean_parameter_create();
+    cpl_test(hdrl_collapse_parameter_is_mean(hpar));
+    hdrl_parameter_delete(hpar);
+    hpar = hdrl_collapse_median_parameter_create();
+    cpl_test(hdrl_collapse_parameter_is_median(hpar));
+    hdrl_parameter_delete(hpar);
+    hpar = hdrl_collapse_weighted_mean_parameter_create();
+    cpl_test(hdrl_collapse_parameter_is_weighted_mean(hpar));
+    hdrl_parameter_delete(hpar);
+
+    cpl_test(hdrl_collapse_parameter_is_mean(HDRL_COLLAPSE_MEAN));
+    cpl_test(!hdrl_collapse_parameter_is_mean(HDRL_COLLAPSE_MEDIAN));
+    hdrl_parameter_delete((hdrl_parameter*)HDRL_COLLAPSE_MEAN);
+
+    cpl_test(hdrl_collapse_parameter_is_median(HDRL_COLLAPSE_MEDIAN));
+    hdrl_parameter_delete((hdrl_parameter*)HDRL_COLLAPSE_MEDIAN);
+
+    cpl_test(hdrl_collapse_parameter_is_weighted_mean(
+                                              HDRL_COLLAPSE_WEIGHTED_MEAN));
+    hdrl_parameter_delete((hdrl_parameter*)HDRL_COLLAPSE_WEIGHTED_MEAN);
+}
+
+
+void test_parlist(void)
+{
+    /* parameter parsing smoketest */
+    hdrl_parameter * hpar;
+    hdrl_parameter * sigclip_def =
+        hdrl_collapse_sigclip_parameter_create(1., 2., 5);
+    hdrl_parameter * minmax_def =
+        hdrl_collapse_minmax_parameter_create(1., 1.);
+    cpl_parameterlist * parlist = hdrl_collapse_parameter_create_parlist(
+                "RECIPE", "collapse", "SIGCLIP", sigclip_def, minmax_def) ;
+    hdrl_parameter_delete(sigclip_def);
+    hdrl_parameter_delete(minmax_def);
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_eq(cpl_parameterlist_get_size(parlist), 6);
+
+    hpar = hdrl_collapse_parameter_parse_parlist(parlist, "RECIPE.invalid");
+    cpl_test_null(hpar);
+    cpl_test_error(CPL_ERROR_DATA_NOT_FOUND);
+
+    hpar = hdrl_collapse_parameter_parse_parlist(parlist, "RECIPE.collapse");
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test(hdrl_collapse_parameter_is_sigclip(hpar));
+    cpl_test(!hdrl_collapse_parameter_is_median(hpar));
+    cpl_test_eq(hdrl_collapse_sigclip_parameter_get_kappa_high(hpar), 2.);
+    cpl_test_eq(hdrl_collapse_sigclip_parameter_get_kappa_low(hpar), 1.);
+    cpl_test_eq(hdrl_collapse_sigclip_parameter_get_niter(hpar), 5);
+    hdrl_parameter_delete(hpar);
+    cpl_parameterlist_delete(parlist);
+
+    hpar = hdrl_collapse_mean_parameter_create();
+    cpl_test(hdrl_collapse_parameter_is_mean(hpar));
+    hdrl_parameter_delete(hpar);
+    hpar = hdrl_collapse_median_parameter_create();
+    cpl_test(hdrl_collapse_parameter_is_median(hpar));
+    hdrl_parameter_delete(hpar);
+    hpar = hdrl_collapse_weighted_mean_parameter_create();
+    cpl_test(hdrl_collapse_parameter_is_weighted_mean(hpar));
+    hdrl_parameter_delete(hpar);
+}
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ @brief   Unit tests of reduce module
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+
+    test_parameters();
+    test_parlist();
+
+#define TST_FREE \
+        cpl_image_delete(outimg); outimg = NULL; \
+        cpl_image_delete(outerr); outerr = NULL; \
+        cpl_image_delete(contrib); contrib = NULL; \
+        cpl_vector_delete(voutimg); voutimg = NULL; \
+        cpl_vector_delete(vouterr); vouterr = NULL; \
+        cpl_array_delete(acontrib); acontrib = NULL; \
+        hdrl_collapse_imagelist_to_image_delete(method); method = NULL;
+        //hdrl_collapse_imagelist_to_vector_delete(vmethod); method = NULL;
+
+    /* create data, value 5., error +-1 */
+    cpl_imagelist * data = cpl_imagelist_new();
+    cpl_imagelist * errs = cpl_imagelist_new();
+    cpl_size nz = 5;
+    cpl_size nx = 40;
+    cpl_size ny = 37;
+    cpl_image * img = cpl_image_new(nx, ny, CPL_TYPE_DOUBLE);
+    cpl_image * err = cpl_image_new(nx, ny, CPL_TYPE_DOUBLE);
+    cpl_image_add_scalar(img, 5.);
+    cpl_image_add_scalar(err, 2.);
+
+    /* create expected results (err / sqrt(nz) for mean) */
+    cpl_image * expect_err = cpl_image_duplicate(err);
+    cpl_image_divide_scalar(expect_err, sqrt(nz));
+    cpl_image * expect_contrib = cpl_image_new(nx, ny, CPL_TYPE_INT);
+    cpl_image_add_scalar(expect_contrib, nz);
+    for (cpl_size i = 0; i < nz; i++) {
+        cpl_imagelist_set(data, cpl_image_duplicate(img),
+                          cpl_imagelist_get_size(data));
+        cpl_imagelist_set(errs, cpl_image_duplicate(err),
+                          cpl_imagelist_get_size(errs));
+    }
+    cpl_image * outimg, * outerr, * contrib;
+    
+    cpl_vector * expect_vimg = cpl_vector_new(nz);
+    cpl_vector * expect_verr = cpl_vector_new(nz);
+    cpl_array * expect_acontrib = cpl_array_new(nz, CPL_TYPE_INT);
+    cpl_vector * voutimg, * vouterr;
+    cpl_array * acontrib;
+    cpl_vector_fill(expect_vimg, 5.);
+    cpl_vector_fill(expect_verr, 2. / sqrt(nx * ny));
+    cpl_array_fill_window_int(expect_acontrib, 0, nz, nx * ny);
+
+    /* test reductions on uniform error cases */
+    {
+        /* mean */
+        hdrl_collapse_imagelist_to_image_t * method =
+            hdrl_collapse_imagelist_to_image_mean();
+        hdrl_collapse_imagelist_to_image_call(method, data, errs,
+                                              &outimg, &outerr, &contrib,
+                                              NULL);
+
+        cpl_test_image_abs(outimg, img, HDRL_EPS_DATA);
+        cpl_test_image_abs(outerr, expect_err, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+
+        hdrl_collapse_imagelist_to_vector_t * vmethod =
+            hdrl_collapse_imagelist_to_vector_mean();
+        hdrl_collapse_imagelist_to_vector_call(vmethod, data, errs,
+                                               &voutimg, &vouterr, &acontrib,
+                                               NULL);
+        cpl_test_vector_abs(voutimg, expect_vimg, HDRL_EPS_DATA);
+        cpl_test_vector_abs(vouterr, expect_verr, HDRL_EPS_ERROR);
+        cpl_test_array_abs(acontrib, expect_acontrib, 0);
+        hdrl_collapse_imagelist_to_vector_delete(vmethod);
+        TST_FREE;
+
+        /* sigclip */
+        method = hdrl_collapse_imagelist_to_image_sigclip(3., 3., 3);
+        hdrl_collapse_imagelist_to_image_call(method, data, errs,
+                                              &outimg, &outerr, &contrib,
+                                              NULL);
+
+        cpl_test_image_abs(outimg, img, HDRL_EPS_DATA);
+        cpl_test_image_abs(outerr, expect_err, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+
+
+        vmethod = hdrl_collapse_imagelist_to_vector_sigclip(3., 3., 3);
+        hdrl_collapse_imagelist_to_vector_call(vmethod, data, errs,
+                                               &voutimg, &vouterr, &acontrib,
+                                               NULL);
+        cpl_test_vector_abs(voutimg, expect_vimg, HDRL_EPS_DATA);
+        cpl_test_vector_abs(vouterr, expect_verr, HDRL_EPS_ERROR);
+        cpl_test_array_abs(acontrib, expect_acontrib, 0);
+        hdrl_collapse_imagelist_to_vector_delete(vmethod);
+        TST_FREE;
+
+        /* minmax */
+        method = hdrl_collapse_imagelist_to_image_minmax(0., 0.);
+        hdrl_collapse_imagelist_to_image_call(method, data, errs,
+                                              &outimg, &outerr, &contrib,
+                                              NULL);
+
+        cpl_test_image_abs(outimg, img, HDRL_EPS_DATA);
+        cpl_test_image_abs(outerr, expect_err, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+
+
+        vmethod = hdrl_collapse_imagelist_to_vector_minmax(0., 0.);
+        hdrl_collapse_imagelist_to_vector_call(vmethod, data, errs,
+                                               &voutimg, &vouterr, &acontrib,
+                                               NULL);
+        cpl_test_vector_abs(voutimg, expect_vimg, HDRL_EPS_DATA);
+        cpl_test_vector_abs(vouterr, expect_verr, HDRL_EPS_ERROR);
+        cpl_test_array_abs(acontrib, expect_acontrib, 0);
+        hdrl_collapse_imagelist_to_vector_delete(vmethod);
+        TST_FREE;
+
+        /* weighted mean */
+        method = hdrl_collapse_imagelist_to_image_weighted_mean();
+        hdrl_collapse_imagelist_to_image_call(method, data, errs,
+                                              &outimg, &outerr, &contrib,
+                                              NULL);
+
+        cpl_test_image_abs(outimg, img, HDRL_EPS_DATA);
+        cpl_test_image_abs(outerr, expect_err, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+        TST_FREE;
+
+        /* median */
+        cpl_image_multiply_scalar(expect_err, sqrt(CPL_MATH_PI_2));
+        method = hdrl_collapse_imagelist_to_image_median();
+        hdrl_collapse_imagelist_to_image_call(method, data, errs,
+                                              &outimg, &outerr, &contrib,
+                                              NULL);
+
+        cpl_test_image_abs(outimg, img, HDRL_EPS_DATA);
+        cpl_test_image_abs(outerr, expect_err, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+
+        cpl_vector_multiply_scalar(expect_verr, sqrt(CPL_MATH_PI_2));
+        vmethod = hdrl_collapse_imagelist_to_vector_median();
+        hdrl_collapse_imagelist_to_vector_call(vmethod, data, errs,
+                                               &voutimg, &vouterr, &acontrib,
+                                               NULL);
+        cpl_test_vector_abs(voutimg, expect_vimg, HDRL_EPS_DATA);
+        cpl_test_vector_abs(vouterr, expect_verr, HDRL_EPS_ERROR);
+        cpl_test_array_abs(acontrib, expect_acontrib, 0);
+        hdrl_collapse_imagelist_to_vector_delete(vmethod);
+        TST_FREE;
+    }
+    /* test non uniform error cases */
+    {
+        double v[] = {1, 2, 1, 3, 2};
+        double e[] = {0.5, 0.7, 0.1, 1.0, 0.01};
+        for (cpl_size i = 0; i < nz; i++) {
+            cpl_image * tmp = cpl_imagelist_get(data, i);
+            cpl_image_set(tmp, 1, 1, v[i]);
+            tmp = cpl_imagelist_get(errs, i);
+            cpl_image_set(tmp, 1, 1, e[i]);
+        }
+        hdrl_collapse_imagelist_to_image_t * method =
+            hdrl_collapse_imagelist_to_image_mean();
+        hdrl_collapse_imagelist_to_vector_t * vmethod =
+            hdrl_collapse_imagelist_to_vector_mean();
+        test_l2i_and_l2v(data, errs, method, vmethod, 1, 1,
+                         (pair){1.8, HDRL_EPS_DATA},
+                         (pair){0.26458269028793246, HDRL_EPS_ERROR},
+                         expect_contrib);
+
+        method = hdrl_collapse_imagelist_to_image_sigclip(3., 3., 3);
+        vmethod = hdrl_collapse_imagelist_to_vector_sigclip(3., 3., 3);
+        test_l2i_and_l2v(data, errs, method, vmethod, 1, 1,
+                         (pair){1.8, HDRL_EPS_DATA},
+                         (pair){0.26458269028793246, HDRL_EPS_ERROR},
+                         expect_contrib);
+
+        method = hdrl_collapse_imagelist_to_image_minmax(1, 1);
+        vmethod = hdrl_collapse_imagelist_to_vector_minmax(1, 1);
+        cpl_image * expect_contrib_minmax =
+                        cpl_image_subtract_scalar_create(expect_contrib, 2);
+        test_l2i_and_l2v(data, errs, method, vmethod, 1, 1,
+                         (pair){5. / 3., HDRL_EPS_DATA},
+                         (pair){sqrt(0.1 * 0.1 + 0.7 * 0.7 + 0.01 * 0.01) / 3.,
+                                HDRL_EPS_ERROR},
+                         expect_contrib_minmax);
+        cpl_image_delete(expect_contrib_minmax);
+
+        method = hdrl_collapse_imagelist_to_image_weighted_mean();
+        vmethod = hdrl_collapse_imagelist_to_vector_weighted_mean();
+        test_l2i_and_l2v(data, errs, method, vmethod, 1, 1,
+                         (pair){1.9898090843925733, HDRL_EPS_ERROR},
+                         (pair){0.0099469054598625289, HDRL_EPS_ERROR},
+                         expect_contrib);
+    }
+    /* test non uniform error cases with rejected values */
+    {
+        double v[] = {1,   2,   1,   3,   2};
+        double e[] = {0.5, 0.7, 0.1, 1.0, 0.01};
+        for (cpl_size i = 0; i < nz; i++) {
+            cpl_image * tmp = cpl_imagelist_get(data, i);
+            cpl_image_set(tmp, 1, 1, v[i]);
+            if (i == 3) {
+                cpl_image_reject(tmp, 1, 1);
+            }
+            tmp = cpl_imagelist_get(errs, i);
+            cpl_image_set(tmp, 1, 1, e[i]);
+            if (i == 3) {
+                cpl_image_reject(tmp, 1, 1);
+            }
+        }
+        cpl_image_delete(expect_contrib);
+        expect_contrib = cpl_image_new_from_accepted(data);
+
+        hdrl_collapse_imagelist_to_image_t * method =
+            hdrl_collapse_imagelist_to_image_mean();
+        hdrl_collapse_imagelist_to_vector_t * vmethod =
+            hdrl_collapse_imagelist_to_vector_mean();
+        test_l2i_and_l2v(data, errs, method, vmethod, 1, 1,
+                         (pair){1.5, HDRL_EPS_DATA},
+                         (pair){0.21652078422174625, HDRL_EPS_ERROR},
+                         expect_contrib);
+
+        method = hdrl_collapse_imagelist_to_image_sigclip(3., 3., 3);
+        vmethod = hdrl_collapse_imagelist_to_vector_sigclip(3., 3., 3);
+        test_l2i_and_l2v(data, errs, method, vmethod, 1, 1,
+                         (pair){1.5, HDRL_EPS_DATA},
+                         (pair){0.21652078422174625, HDRL_EPS_ERROR},
+                         expect_contrib);
+
+        method = hdrl_collapse_imagelist_to_image_minmax(1, 1);
+        vmethod = hdrl_collapse_imagelist_to_vector_minmax(1, 1);
+        cpl_image * expect_contrib_minmax =
+                        cpl_image_subtract_scalar_create(expect_contrib, 2);
+        test_l2i_and_l2v(data, errs, method, vmethod, 1, 1,
+                         (pair){3. / 2., HDRL_EPS_DATA},
+                         (pair){sqrt(0.1 * 0.1 + 0.01 * 0.01) / 2.,
+                                HDRL_EPS_ERROR},
+                         expect_contrib_minmax);
+        cpl_image_delete(expect_contrib_minmax);
+
+        method = hdrl_collapse_imagelist_to_image_weighted_mean();
+        vmethod = hdrl_collapse_imagelist_to_vector_weighted_mean();
+        test_l2i_and_l2v(data, errs, method, vmethod, 1, 1,
+                         (pair){1.9897091252756485, HDRL_EPS_ERROR},
+                         (pair){0.0099473975744101273, HDRL_EPS_ERROR},
+                         expect_contrib);
+    }
+    /* test all values rejected list to image */
+    {
+        double v[] = {1, 2, 1, 3, 2};
+        double e[] = {0.5, 0.7, 0.1, 1.0, 0.01};
+        for (cpl_size i = 0; i < nz; i++) {
+            cpl_image * tmp = cpl_imagelist_get(data, i);
+            cpl_image_set(tmp, 1, 1, v[i]);
+            cpl_image_reject(tmp, 1, 1);
+            tmp = cpl_imagelist_get(errs, i);
+            cpl_image_set(tmp, 1, 1, e[i]);
+            cpl_image_reject(tmp, 1, 1);
+        }
+        cpl_image_delete(expect_contrib);
+        expect_contrib = cpl_image_new_from_accepted(data);
+
+        hdrl_collapse_imagelist_to_image_t * img_meth[] = {
+            hdrl_collapse_imagelist_to_image_mean(),
+            hdrl_collapse_imagelist_to_image_sigclip(3., 3., 3),
+            hdrl_collapse_imagelist_to_image_weighted_mean(),
+            hdrl_collapse_imagelist_to_image_median(),
+        };
+        hdrl_collapse_imagelist_to_vector_t * vec_meth[] = {
+            hdrl_collapse_imagelist_to_vector_mean(),
+            hdrl_collapse_imagelist_to_vector_sigclip(3., 3., 3),
+            hdrl_collapse_imagelist_to_vector_weighted_mean(),
+            hdrl_collapse_imagelist_to_vector_median(),
+        };
+
+        for (size_t i = 0; i < ARRAY_LEN(img_meth); i++) {
+            test_l2i_and_l2v(data, errs, img_meth[i], vec_meth[i], 1, 1,
+                             (pair){NAN, HDRL_EPS_DATA},
+                             (pair){NAN, HDRL_EPS_ERROR},
+                             expect_contrib);
+        }
+
+        hdrl_collapse_imagelist_to_image_t * method =
+            hdrl_collapse_imagelist_to_image_minmax(1., 1.);
+        hdrl_collapse_imagelist_to_vector_t * vmethod =
+            hdrl_collapse_imagelist_to_vector_minmax(1., 1.);
+        cpl_image * expect_contrib_minmax =
+            cpl_image_subtract_scalar_create(expect_contrib, 2);
+        cpl_image_set(expect_contrib_minmax, 1, 1, 0);
+        test_l2i_and_l2v(data, errs, method, vmethod, 1, 1,
+                         (pair){NAN, HDRL_EPS_DATA},
+                         (pair){NAN, HDRL_EPS_ERROR},
+                         expect_contrib_minmax);
+        cpl_image_delete(expect_contrib_minmax);
+    }
+    /* test median error propagation with rejects, only makes sense on uniform
+     * errors as the scaling relies on gaussian errors */
+    {
+        double v[] = {1, 2, 1, 3, 2};
+        double e[] = {1., 1., 1., 1., 1.};
+        int d;
+        for (cpl_size i = 0; i < nz; i++) {
+            cpl_image * tmp = cpl_imagelist_get(data, i);
+            cpl_image_set(tmp, 1, 1, v[i]);
+            cpl_image_set(tmp, 2, 2, v[i]);
+            if (i > 1) {
+                cpl_image_reject(tmp, 1, 1);
+            }
+            tmp = cpl_imagelist_get(errs, i);
+            cpl_image_set(tmp, 1, 1, e[i]);
+            cpl_image_set(tmp, 2, 2, e[i]);
+            if (i > 1) {
+                cpl_image_reject(tmp, 1, 1);
+            }
+        }
+        cpl_image_delete(expect_contrib);
+        expect_contrib = cpl_image_new_from_accepted(data);
+
+        hdrl_collapse_imagelist_to_image_t * method =
+            hdrl_collapse_imagelist_to_image_median();
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, &contrib);
+
+        /* contrib > 2 -> sqrt(nz * pi / 2) error scaling */
+        cpl_test_abs(cpl_image_get(outimg, 2, 2, &d), 2., HDRL_EPS_DATA);
+        cpl_test_abs(cpl_image_get(outerr, 2, 2, &d),
+                     1. / sqrt(nz) * sqrt(CPL_MATH_PI_2), HDRL_EPS_ERROR);
+        /* contrib <= 2 -> median is a mean, no scaling */
+        cpl_test_abs(cpl_image_get(outimg, 1, 1, &d), 1.5, HDRL_EPS_DATA);
+        cpl_test_abs(cpl_image_get(outerr, 1, 1, &d), 1. / sqrt(2.), HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+
+        cpl_imagelist * vl = cpl_imagelist_new();
+        cpl_imagelist * el = cpl_imagelist_new();
+        prep_l2v_input(data, errs, 1, 1, vl, el);
+        hdrl_collapse_imagelist_to_vector_t * vmethod =
+            hdrl_collapse_imagelist_to_vector_median();
+        hdrl_collapse_imagelist_to_vector_call(vmethod, vl, el,
+                                               &voutimg, &vouterr, &acontrib,
+                                               NULL);
+        hdrl_test_abs(cpl_vector_get(voutimg, 0), 1.5, HDRL_EPS_DATA, -1);
+        hdrl_test_abs(cpl_vector_get(vouterr, 0), 1. / sqrt(2.),
+                      HDRL_EPS_ERROR, -1);
+        cpl_test_abs(cpl_array_get_int(acontrib, 0, NULL), 2, 0);
+        cpl_vector_delete(voutimg);
+        cpl_vector_delete(vouterr);
+        cpl_array_delete(acontrib);
+        cpl_imagelist_empty(vl);
+        cpl_imagelist_empty(el);
+
+        prep_l2v_input(data, errs, 2, 2, vl, el);
+        hdrl_collapse_imagelist_to_vector_call(vmethod, vl, el,
+                                               &voutimg, &vouterr, &acontrib,
+                                               NULL);
+        hdrl_test_abs(cpl_vector_get(voutimg, 0), 2., HDRL_EPS_DATA, -1);
+        hdrl_test_abs(cpl_vector_get(vouterr, 0),
+                      1. / sqrt(nz) * sqrt(CPL_MATH_PI_2), HDRL_EPS_ERROR, -1);
+        cpl_test_abs(cpl_array_get_int(acontrib, 0, NULL), 5, 0);
+        cpl_imagelist_delete(vl);
+        cpl_imagelist_delete(el);
+        hdrl_collapse_imagelist_to_vector_delete(vmethod);
+
+        TST_FREE;
+    }
+
+    cpl_imagelist_delete(data);
+    cpl_imagelist_delete(errs);
+    cpl_image_delete(expect_err);
+    cpl_image_delete(expect_contrib);
+    cpl_image_delete(img);
+    cpl_image_delete(err);
+    cpl_vector_delete(expect_vimg);
+    cpl_vector_delete(expect_verr);
+    cpl_array_delete(expect_acontrib);
+
+    return cpl_test_end(0);
+#undef TST_FREE
+}
diff --git a/hdrl/tests/hdrl_combine-test.c b/hdrl/tests/hdrl_combine-test.c
new file mode 100644
index 0000000..ac69520
--- /dev/null
+++ b/hdrl/tests/hdrl_combine-test.c
@@ -0,0 +1,333 @@
+/* $Id: hdrl_combine-test.c,v 1.7 2013-09-24 14:58:54 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-09-24 14:58:54 $
+ * $Revision: 1.7 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_combine.h"
+#include <cpl.h>
+
+#include <math.h>
+#include <stdlib.h>
+
+#ifndef ARRAY_LEN
+#define ARRAY_LEN(a) sizeof((a))/sizeof((a)[0])
+#endif
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_combine_test   Testing of the HDRL combine module
+ */
+/*----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ @brief   Unit tests of combine module
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+
+#define TST_FREE \
+        cpl_image_delete(outimg); \
+        cpl_image_delete(outerr); \
+        cpl_image_delete(contrib); \
+        hdrl_collapse_imagelist_to_image_delete(method);
+
+    /* create data, value 5., error +-1 */
+    cpl_imagelist * data = cpl_imagelist_new();
+    cpl_imagelist * errs = cpl_imagelist_new();
+    cpl_image * img = cpl_image_new(40, 40, CPL_TYPE_DOUBLE);
+    cpl_image * err = cpl_image_new(40, 40, CPL_TYPE_DOUBLE);
+    cpl_image_add_scalar(img, 5.);
+    cpl_image_add_scalar(err, 2.);
+    size_t nz = 5;
+
+    /* create expected results (err / sqrt(nz) for mean) */
+    cpl_image * expect_err = cpl_image_duplicate(err);
+    cpl_image_divide_scalar(expect_err, sqrt(nz));
+    cpl_image * expect_contrib = cpl_image_new(40, 40, CPL_TYPE_INT);
+    cpl_image_add_scalar(expect_contrib, 5);
+    for (size_t i = 0; i < nz; i++) {
+        cpl_imagelist_set(data, cpl_image_duplicate(img), cpl_imagelist_get_size(data));
+        cpl_imagelist_set(errs, cpl_image_duplicate(err), cpl_imagelist_get_size(errs));
+    }
+    cpl_image * outimg, * outerr, * contrib;
+
+    /* test inputs */
+    {
+        hdrl_collapse_imagelist_to_image_t * method =
+            hdrl_collapse_imagelist_to_image_mean();
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, NULL);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+        hdrl_imagelist_combine(data, errs, method, &outimg, NULL, &contrib);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+        hdrl_imagelist_combine(data, errs, method, NULL, &outerr, &contrib);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+        hdrl_imagelist_combine(data, errs, NULL, &outimg, &outerr, &contrib);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+        hdrl_imagelist_combine(data, NULL, method, &outimg, &outerr, &contrib);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+        hdrl_imagelist_combine(NULL, errs, method, &outimg, &outerr, &contrib);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+        hdrl_collapse_imagelist_to_image_delete(method);
+    }
+    /* wrong imagelist sizes */
+    {
+        hdrl_collapse_imagelist_to_image_t * method =
+            hdrl_collapse_imagelist_to_image_mean();
+        cpl_imagelist * data2 = cpl_imagelist_duplicate(data);
+        cpl_imagelist * errs2;
+        cpl_image_delete(cpl_imagelist_unset(data2, 0));
+        hdrl_imagelist_combine(data2, errs, method, &outimg, &outerr, &contrib);
+        cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+        cpl_imagelist_delete(data2);
+
+        data2 = cpl_imagelist_new();
+        errs2 = cpl_imagelist_new();
+        hdrl_imagelist_combine(data2, errs2, method, &outimg, &outerr, &contrib);
+        cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+        cpl_imagelist_delete(data2);
+        cpl_imagelist_delete(errs2);
+        hdrl_collapse_imagelist_to_image_delete(method);
+    }
+    /* test reductions on uniform error cases */
+    {
+        /* mean */
+        hdrl_collapse_imagelist_to_image_t * method =
+            hdrl_collapse_imagelist_to_image_mean();
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, &contrib);
+
+        cpl_test_image_abs(outimg, img, HDRL_EPS_DATA);
+        cpl_test_image_abs(outerr, expect_err, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+        TST_FREE;
+
+        /* sigclip */
+        method = hdrl_collapse_imagelist_to_image_sigclip(3., 3., 3);
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, &contrib);
+
+        cpl_test_image_abs(outimg, img, HDRL_EPS_DATA);
+        cpl_test_image_abs(outerr, expect_err, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+        TST_FREE;
+
+        /* minmax */
+        method = hdrl_collapse_imagelist_to_image_minmax(0, 0);
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, &contrib);
+
+        cpl_test_image_abs(outimg, img, HDRL_EPS_DATA);
+        cpl_test_image_abs(outerr, expect_err, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+        TST_FREE;
+
+        /* weighted mean */
+        method = hdrl_collapse_imagelist_to_image_weighted_mean();
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, &contrib);
+
+        cpl_test_image_abs(outimg, img, HDRL_EPS_DATA);
+        cpl_test_image_abs(outerr, expect_err, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+        TST_FREE;
+
+        /* median */
+        cpl_image_multiply_scalar(expect_err, sqrt(CPL_MATH_PI_2));
+        method = hdrl_collapse_imagelist_to_image_median();
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, &contrib);
+
+        cpl_test_image_abs(outimg, img, HDRL_EPS_DATA);
+        cpl_test_image_abs(outerr, expect_err, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+        TST_FREE;
+    }
+    /* test non uniform error cases */
+    {
+        double v[] = {1, 2, 1, 3, 2};
+        double e[] = {0.5, 0.7, 0.1, 1.0, 0.01};
+        int d;
+        for (size_t i = 0; i < nz; i++) {
+            cpl_image * tmp = cpl_imagelist_get(data, i);
+            cpl_image_set(tmp, 1, 1, v[i]);
+            tmp = cpl_imagelist_get(errs, i);
+            cpl_image_set(tmp, 1, 1, e[i]);
+        }
+        hdrl_collapse_imagelist_to_image_t * method =
+            hdrl_collapse_imagelist_to_image_mean();
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, &contrib);
+        cpl_test_abs(cpl_image_get(outimg, 1, 1, &d), 1.8, HDRL_EPS_DATA);
+        cpl_test_abs(cpl_image_get(outerr, 1, 1, &d), 0.26458269028793246, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+        TST_FREE;
+
+        method = hdrl_collapse_imagelist_to_image_sigclip(3., 3., 3);
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, &contrib);
+
+        cpl_test_abs(cpl_image_get(outimg, 1, 1, &d), 1.8, HDRL_EPS_DATA);
+        cpl_test_abs(cpl_image_get(outerr, 1, 1, &d), 0.26458269028793246, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+        TST_FREE;
+
+        method = hdrl_collapse_imagelist_to_image_minmax(1, 1);
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, &contrib);
+
+        cpl_test_abs(cpl_image_get(outimg, 1, 1, &d), 5./3., HDRL_EPS_DATA);
+
+        /* The minmax rejection algorithm has a
+         * intrinsic problem with same values but different errors. If for
+         * example the two lowest values are 1+-0.5 and 1+-500 what "1" should
+         * be kept? It doesn't matter for the mean, but for the propagated
+         * error  - the implemented algorithm propagates the smaller error */
+
+        cpl_test_abs(cpl_image_get(outerr, 1, 1, &d),
+                     sqrt(0.1 * 0.1 + 0.7 * 0.7 + 0.01 * 0.01) / 3.,
+                     HDRL_EPS_ERROR);
+        cpl_image * expect_contrib_minmax =
+                        cpl_image_subtract_scalar_create(expect_contrib, 2);
+        cpl_test_image_abs(contrib, expect_contrib_minmax, 0);
+        cpl_image_delete(expect_contrib_minmax);
+        TST_FREE;
+
+        method = hdrl_collapse_imagelist_to_image_weighted_mean();
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, &contrib);
+        cpl_test_abs(cpl_image_get(outimg, 1, 1, &d), 1.9898090843925733, HDRL_EPS_DATA);
+        cpl_test_abs(cpl_image_get(outerr, 1, 1, &d), 0.0099469054598625289, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+        TST_FREE;
+    }
+    /* test non uniform error cases with rejected values */
+    {
+        double v[] = {1, 2, 1, 3, 2};
+        double e[] = {0.5, 0.7, 0.1, 1.0, 0.01};
+        int d;
+        for (size_t i = 0; i < nz; i++) {
+            cpl_image * tmp = cpl_imagelist_get(data, i);
+            cpl_image_set(tmp, 1, 1, v[i]);
+            if (i == 3) {
+                cpl_image_reject(tmp, 1, 1);
+            }
+            tmp = cpl_imagelist_get(errs, i);
+            cpl_image_set(tmp, 1, 1, e[i]);
+            if (i == 3) {
+                cpl_image_reject(tmp, 1, 1);
+            }
+        }
+        cpl_image_delete(expect_contrib);
+        expect_contrib = cpl_image_new_from_accepted(data);
+
+        hdrl_collapse_imagelist_to_image_t * method =
+            hdrl_collapse_imagelist_to_image_mean();
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, &contrib);
+
+        cpl_test_abs(cpl_image_get(outimg, 1, 1, &d), 1.5, HDRL_EPS_DATA);
+        cpl_test_abs(cpl_image_get(outerr, 1, 1, &d), 0.21652078422174625, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+        TST_FREE;
+
+        method = hdrl_collapse_imagelist_to_image_sigclip(3., 3., 3);
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, &contrib);
+
+        cpl_test_abs(cpl_image_get(outimg, 1, 1, &d), 1.5, HDRL_EPS_DATA);
+        cpl_test_abs(cpl_image_get(outerr, 1, 1, &d), 0.21652078422174625, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+        TST_FREE;
+
+        method = hdrl_collapse_imagelist_to_image_minmax(1, 1);
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, &contrib);
+
+        cpl_test_abs(cpl_image_get(outimg, 1, 1, &d), 3./2., HDRL_EPS_DATA);
+        cpl_test_abs(cpl_image_get(outerr, 1, 1, &d),
+                      sqrt(0.01 * 0.01 + 0.1 * 0.1) / 2., HDRL_EPS_ERROR);
+        cpl_image * expect_contrib_minmax =
+                         cpl_image_subtract_scalar_create(expect_contrib, 2);
+        cpl_test_image_abs(contrib, expect_contrib_minmax, 0);
+        cpl_image_delete(expect_contrib_minmax);
+        TST_FREE;
+
+        method = hdrl_collapse_imagelist_to_image_weighted_mean();
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, &contrib);
+
+        cpl_test_abs(cpl_image_get(outimg, 1, 1, &d), 1.9897091252756485, HDRL_EPS_DATA);
+        cpl_test_abs(cpl_image_get(outerr, 1, 1, &d), 0.0099473975744101273, HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+        TST_FREE;
+    }
+    /* test median error propagation with rejects, only makes sense on uniform
+     * errors as the scaling relies on gaussian errors */
+    {
+        double v[] = {1, 2, 1, 3, 2};
+        double e[] = {1., 1., 1., 1., 1.};
+        int d;
+        for (size_t i = 0; i < nz; i++) {
+            cpl_image * tmp = cpl_imagelist_get(data, i);
+            cpl_image_set(tmp, 1, 1, v[i]);
+            cpl_image_set(tmp, 2, 2, v[i]);
+            if (i > 1) {
+                cpl_image_reject(tmp, 1, 1);
+            }
+            tmp = cpl_imagelist_get(errs, i);
+            cpl_image_set(tmp, 1, 1, e[i]);
+            cpl_image_set(tmp, 2, 2, e[i]);
+            if (i > 1) {
+                cpl_image_reject(tmp, 1, 1);
+            }
+        }
+        cpl_image_delete(expect_contrib);
+        expect_contrib = cpl_image_new_from_accepted(data);
+
+        hdrl_collapse_imagelist_to_image_t * method =
+            hdrl_collapse_imagelist_to_image_median();
+        hdrl_imagelist_combine(data, errs, method, &outimg, &outerr, &contrib);
+
+        /* contrib > 2 -> sqrt(nz * pi / 2) error scaling */
+        cpl_test_abs(cpl_image_get(outimg, 2, 2, &d), 2., HDRL_EPS_DATA);
+        cpl_test_abs(cpl_image_get(outerr, 2, 2, &d),
+                     1. / sqrt(nz) * sqrt(CPL_MATH_PI_2), HDRL_EPS_ERROR);
+        /* contrib <= 2 -> median is a mean, no scaling */
+        cpl_test_abs(cpl_image_get(outimg, 1, 1, &d), 1.5, HDRL_EPS_DATA);
+        cpl_test_abs(cpl_image_get(outerr, 1, 1, &d), 1. / sqrt(2.), HDRL_EPS_ERROR);
+        cpl_test_image_abs(contrib, expect_contrib, 0);
+        TST_FREE;
+    }
+
+    cpl_imagelist_delete(data);
+    cpl_imagelist_delete(errs);
+    cpl_image_delete(expect_err);
+    cpl_image_delete(expect_contrib);
+    cpl_image_delete(img);
+    cpl_image_delete(err);
+
+    return cpl_test_end(0);
+#undef TST_FREE
+}
diff --git a/hdrl/tests/hdrl_elemop-test.c b/hdrl/tests/hdrl_elemop-test.c
new file mode 100644
index 0000000..f918917
--- /dev/null
+++ b/hdrl/tests/hdrl_elemop-test.c
@@ -0,0 +1,950 @@
+/* $Id: hdrl_elemop-test.c,v 1.4 2013-09-25 12:06:52 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-09-25 12:06:52 $
+ * $Revision: 1.4 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_elemop.h"
+#include "hdrl_types.h"
+#include <cpl.h>
+
+#include <math.h>
+#include <stdlib.h>
+
+#ifndef ARRAY_LEN
+#define ARRAY_LEN(a) sizeof((a))/sizeof((a)[0])
+#endif
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_elemop_test   Testing of the HDRL variance module
+ */
+/*----------------------------------------------------------------------------*/
+
+static cpl_error_code
+hdrl_test_add(void)
+{
+    {
+        hdrl_data_t a, b;
+        hdrl_error_t ea, eb;
+        hdrl_elemop_add(&a, &ea, 1, &b, &eb, 2, NULL);
+        cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    }
+
+    {
+        hdrl_data_t a = 2;
+        hdrl_error_t ea = 0.5;
+        const hdrl_data_t b = 2;
+        const hdrl_error_t eb = 0.5;
+
+        hdrl_elemop_add(&a, &ea, 1, &b, &eb, 1, NULL);
+
+        cpl_test_rel(a, 4., HDRL_EPS_DATA);
+        cpl_test_rel(ea, sqrt(0.5), HDRL_EPS_ERROR);
+    }
+
+    {
+        hdrl_data_t a = 2;
+        hdrl_error_t ea = 0.5;
+
+        hdrl_elemop_add(&a, &ea, 1, &a, &ea, 1, NULL);
+
+        cpl_test_rel(a, 4., HDRL_EPS_DATA);
+        cpl_test_rel(ea, sqrt(1.0), HDRL_EPS_ERROR);
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        const hdrl_data_t b[] = {-2, 6};
+        const hdrl_error_t eb[] = {0.5, 3};
+
+        hdrl_elemop_add(a, ea, ARRAY_LEN(a), b, eb, ARRAY_LEN(b), NULL);
+
+        cpl_test_rel(a[0], 0., HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], sqrt(0.5), HDRL_EPS_ERROR);
+        cpl_test_rel(a[1], 9., HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], sqrt(1 * 1 + 3 * 3), HDRL_EPS_ERROR);
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+
+        hdrl_elemop_add(a, ea, ARRAY_LEN(a), a, ea, ARRAY_LEN(a), NULL);
+
+        cpl_test_rel(a[0], 4., HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], 1, HDRL_EPS_ERROR);
+        cpl_test_rel(a[1], 6., HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], 2., HDRL_EPS_ERROR);
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        const hdrl_data_t b = -2;
+        const hdrl_error_t eb = 0.5;
+
+        hdrl_elemop_add(a, ea, ARRAY_LEN(a), &b, &eb, 1, NULL);
+
+        cpl_test_rel(a[0], 0., HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], sqrt(0.5), HDRL_EPS_ERROR);
+        cpl_test_rel(a[1], 1., HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], sqrt(1 * 1 + 0.5 * 0.5), HDRL_EPS_ERROR);
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        const hdrl_data_t b = -2;
+        const hdrl_error_t eb = 0.5;
+        cpl_binary mask[] = {0, 1};
+
+        hdrl_elemop_add(a, ea, ARRAY_LEN(a), &b, &eb, 1, mask);
+
+        cpl_test_rel(a[0], 0., HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], sqrt(0.5), HDRL_EPS_ERROR);
+        cpl_test_rel(a[1], 3., HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], 1., HDRL_EPS_ERROR);
+    }
+
+    /*{
+        hdrl_data_t a = 2;
+        hdrl_error_t ea = 0.7;
+        hdrl_data_t a2 = a;
+        hdrl_error_t ea2 = ea;
+        const hdrl_data_t b = 2;
+        const hdrl_error_t eb = 0.7;
+        const double covab = 1;
+
+        hdrl_elemop_add(&a, &ea, &a, &ea, 1);
+        hdrl_elemop_add_cov(&a2, &ea2, &b, &eb, &covab, 1);
+
+        cpl_test_rel(a, a2, HDRL_EPS_DATA);
+        cpl_test_rel(ea, ea2, HDRL_EPS_ERROR);
+        cpl_test_rel(ea, 1.4, HDRL_EPS_ERROR);
+    }*/
+
+    return cpl_error_get_code();
+}
+
+static cpl_error_code
+hdrl_test_sub(void)
+{
+    {
+        hdrl_data_t a, b;
+        hdrl_error_t ea, eb;
+        hdrl_elemop_sub(&a, &ea, 1, &b, &eb, 2, NULL);
+        cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    }
+
+    {
+        hdrl_data_t a = 2;
+        hdrl_error_t ea = 0.5;
+        const hdrl_data_t b = 2;
+        const hdrl_error_t eb = 0.5;
+
+        hdrl_elemop_sub(&a, &ea, 1, &b, &eb, 1, NULL);
+
+        cpl_test_rel(a, 0., HDRL_EPS_DATA);
+        cpl_test_rel(ea, sqrt(0.5), HDRL_EPS_ERROR);
+    }
+
+    {
+        hdrl_data_t a = 2;
+        hdrl_error_t ea = 0.5;
+
+        hdrl_elemop_sub(&a, &ea, 1, &a, &ea, 1, NULL);
+
+        cpl_test_rel(a, 0., HDRL_EPS_DATA);
+        cpl_test_rel(ea, 0., HDRL_EPS_ERROR);
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        const hdrl_data_t b[] = {-2, 6};
+        const hdrl_error_t eb[] = {0.5, 3};
+
+        hdrl_elemop_sub(a, ea, ARRAY_LEN(a), b, eb, ARRAY_LEN(b), NULL);
+
+        cpl_test_rel(a[0], 4., HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], sqrt(0.5), HDRL_EPS_ERROR);
+        cpl_test_rel(a[1], -3., HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], sqrt(1 * 1 + 3 * 3), HDRL_EPS_ERROR);
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+
+        hdrl_elemop_sub(a, ea, ARRAY_LEN(a), a, ea, ARRAY_LEN(a), NULL);
+
+        cpl_test_rel(a[0], 0., HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], 0., HDRL_EPS_ERROR);
+        cpl_test_rel(a[1], 0., HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], 0., HDRL_EPS_ERROR);
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        const hdrl_data_t b = -2;
+        const hdrl_error_t eb = 0.5;
+
+        hdrl_elemop_sub(a, ea, ARRAY_LEN(a), &b, &eb, 1, NULL);
+
+        cpl_test_rel(a[0], 4., HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], sqrt(0.5), HDRL_EPS_ERROR);
+        cpl_test_rel(a[1], 5., HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], sqrt(1 * 1 + 0.5 * 0.5), HDRL_EPS_ERROR);
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        const hdrl_data_t b = -2;
+        const hdrl_error_t eb = 0.5;
+        cpl_binary mask[] = {0, 1};
+
+        hdrl_elemop_sub(a, ea, ARRAY_LEN(a), &b, &eb, 1, mask);
+
+        cpl_test_rel(a[0], 4., HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], sqrt(0.5), HDRL_EPS_ERROR);
+        cpl_test_rel(a[1], 3., HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], 1., HDRL_EPS_ERROR);
+    }
+
+    return cpl_error_get_code();
+}
+
+
+static cpl_error_code
+hdrl_test_mul(void)
+{
+    {
+        hdrl_data_t a, b;
+        hdrl_error_t ea, eb;
+        hdrl_elemop_mul(&a, &ea, 1, &b, &eb, 2, NULL);
+        cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    }
+
+    {
+        hdrl_data_t a = 2;
+        hdrl_error_t ea = 0.5;
+        const hdrl_data_t b = 3;
+        const hdrl_error_t eb = 0.5;
+
+        hdrl_elemop_mul(&a, &ea, 1, &b, &eb, 1, NULL);
+
+        cpl_test_rel(a, 6., HDRL_EPS_DATA);
+        cpl_test_rel(ea, sqrt(3.25), HDRL_EPS_ERROR * 10);
+    }
+
+    {
+        hdrl_data_t a = 2;
+        hdrl_error_t ea = 0.5;
+
+        hdrl_elemop_mul(&a, &ea, 1, &a, &ea, 1, NULL);
+
+        cpl_test_rel(a, 4., HDRL_EPS_DATA);
+        cpl_test_rel(ea, 2., HDRL_EPS_ERROR * 10);
+
+        a = 1.7;
+        ea = 2.8;
+
+        hdrl_elemop_mul(&a, &ea, 1, &a, &ea, 1, NULL);
+
+        cpl_test_rel(a, 1.7 * 1.7, HDRL_EPS_DATA);
+        cpl_test_rel(ea, 9.52, HDRL_EPS_ERROR * 10);
+
+        a = -1.7;
+        ea = 2.8;
+
+        hdrl_elemop_mul(&a, &ea, 1, &a, &ea, 1, NULL);
+
+        cpl_test_rel(a, 1.7 * 1.7, HDRL_EPS_DATA);
+        cpl_test_rel(ea, 9.52, HDRL_EPS_ERROR * 10);
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        const hdrl_data_t b[] = {-2, 6};
+        const hdrl_error_t eb[] = {0.5, 3};
+
+        hdrl_elemop_mul(a, ea, ARRAY_LEN(a), b, eb, ARRAY_LEN(b), NULL);
+
+        cpl_test_rel(a[0], -4., HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], sqrt(2), HDRL_EPS_ERROR * 10);
+        cpl_test_rel(a[1], 18., HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], 10.816653826391969, HDRL_EPS_ERROR * 10);
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        const hdrl_data_t b = -2;
+        const hdrl_error_t eb = 0.5;
+
+        hdrl_elemop_mul(a, ea, ARRAY_LEN(a), &b, &eb, 1, NULL);
+
+        cpl_test_rel(a[0], -4., HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], sqrt(2.), HDRL_EPS_ERROR * 10);
+        cpl_test_rel(a[1], -6., HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], 2.5, HDRL_EPS_ERROR * 10);
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        const hdrl_data_t b = -2;
+        const hdrl_error_t eb = 0.5;
+        cpl_binary mask[] = {0, 1};
+
+        hdrl_elemop_mul(a, ea, ARRAY_LEN(a), &b, &eb, 1, mask);
+
+        cpl_test_rel(a[0], -4., HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], sqrt(2.), HDRL_EPS_ERROR * 10);
+        cpl_test_rel(a[1], 3., HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], 1., HDRL_EPS_ERROR);
+    }
+
+    /* {
+        hdrl_data_t a = 2;
+        hdrl_error_t ea = 0.7;
+        hdrl_data_t a2 = a;
+        hdrl_error_t ea2 = ea;
+        const hdrl_data_t b = 2;
+        const hdrl_error_t eb = 0.7;
+        const double covab = 1;
+
+        hdrl_elemop_mul(&a, &ea, &a, &ea, 1);
+        hdrl_elemop_mul_cov(&a2, &ea2, &b, &eb, &covab, 1);
+
+        cpl_test_rel(a, a2, HDRL_EPS_DATA);
+        cpl_test_rel(ea, ea2, HDRL_EPS_ERROR);
+        cpl_test_rel(ea, 2.8, HDRL_EPS_ERROR);
+    } */
+
+    return cpl_error_get_code();
+}
+
+
+static cpl_error_code
+hdrl_test_div(void)
+{
+    {
+        hdrl_data_t a, b;
+        hdrl_error_t ea, eb;
+        hdrl_elemop_div(&a, &ea, 1, &b, &eb, 2, NULL);
+        cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    }
+
+    {
+        hdrl_data_t a = 2;
+        hdrl_error_t ea = 0.5;
+        const hdrl_data_t b = 3;
+        const hdrl_error_t eb = 0.5;
+
+        hdrl_elemop_div(&a, &ea, 1, &b, &eb, 1, NULL);
+
+        cpl_test_rel(a, 2. / 3., HDRL_EPS_DATA);
+        cpl_test_rel(ea, 0.20030840419244383, HDRL_EPS_ERROR * 10);
+    }
+
+    {
+        hdrl_data_t a = 2;
+        hdrl_error_t ea = 0.5;
+
+        hdrl_elemop_div(&a, &ea, 1, &a, &ea, 1, NULL);
+
+        cpl_test_rel(a, 1., HDRL_EPS_DATA);
+        cpl_test_rel(ea, 0., HDRL_EPS_ERROR * 10);
+
+        a = 1.7;
+        ea = 2.8;
+
+        hdrl_elemop_div(&a, &ea, 1, &a, &ea, 1, NULL);
+
+        cpl_test_rel(a, 1., HDRL_EPS_DATA);
+        cpl_test_rel(ea, 0., HDRL_EPS_ERROR * 10);
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        const hdrl_data_t b[] = {-2, 6};
+        const hdrl_error_t eb[] = {0.5, 3};
+
+        hdrl_elemop_div(a, ea, ARRAY_LEN(a), b, eb, ARRAY_LEN(b), NULL);
+
+        cpl_test_rel(a[0], -1., HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], 0.35355339059327379, HDRL_EPS_ERROR * 10);
+        cpl_test_rel(a[1], 3./6., HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], 0.3004626062886658, HDRL_EPS_ERROR * 10);
+    }
+
+    /* division by 0. */
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        hdrl_data_t b[] = {-2, 0.};
+        const hdrl_error_t eb[] = {0.5, 3};
+
+        hdrl_elemop_div(a, ea, ARRAY_LEN(a), b, eb, ARRAY_LEN(b), NULL);
+
+        cpl_test_rel(a[0], -1., HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], 0.35355339059327379, HDRL_EPS_ERROR * 10);
+        cpl_test(isnan(a[1]));
+        cpl_test(isnan(ea[1]));
+
+        b[0] = 0.;
+        hdrl_elemop_div(a, ea, ARRAY_LEN(a), b, eb, 1, NULL);
+
+        cpl_test(isnan(a[0]));
+        cpl_test(isnan(ea[0]));
+        cpl_test(isnan(a[1]));
+        cpl_test(isnan(ea[1]));
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        const hdrl_data_t b = -2;
+        const hdrl_error_t eb = 0.5;
+
+        hdrl_elemop_div(a, ea, ARRAY_LEN(a), &b, &eb, 1, NULL);
+
+        cpl_test_rel(a[0], -1., HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], 0.35355339059327379, HDRL_EPS_ERROR * 10);
+        cpl_test_rel(a[1], -3. / 2., HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], 0.625, HDRL_EPS_ERROR * 10);
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        const hdrl_data_t b = -2;
+        const hdrl_error_t eb = 0.5;
+        cpl_binary mask[] = {0, 1};
+
+        hdrl_elemop_div(a, ea, ARRAY_LEN(a), &b, &eb, 1, mask);
+
+        cpl_test_rel(a[0], -1., HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], 0.35355339059327379, HDRL_EPS_ERROR * 10);
+        cpl_test_rel(a[1], 3., HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], 1., HDRL_EPS_ERROR);
+    }
+
+    return cpl_error_get_code();
+}
+
+static cpl_error_code
+hdrl_test_pow(void)
+{
+    {
+        hdrl_data_t a, b;
+        hdrl_error_t ea, eb;
+        hdrl_elemop_pow(&a, &ea, 1, &b, &eb, 2, NULL);
+        cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    }
+
+    {
+        hdrl_data_t a = 1.2;
+        hdrl_error_t ea = 0.5;
+
+        hdrl_elemop_pow(&a, &ea, 1, &a, &ea, 1, NULL);
+
+        cpl_test_rel(a, pow(1.2, 1.2), HDRL_EPS_DATA);
+        cpl_test_rel(ea, 0.7357378647225408, HDRL_EPS_ERROR * 10);
+    }
+
+    /* square root test */
+    {
+        hdrl_data_t a = 1.2;
+        hdrl_error_t ea = 0.6;
+        hdrl_data_t b = 0.5;
+        hdrl_error_t eb = 0.;
+
+        hdrl_elemop_pow(&a, &ea, 1, &b, &eb, 1, NULL);
+
+        cpl_test_rel(a, sqrt(1.2), HDRL_EPS_DATA);
+        cpl_test_rel(ea, 0.27386127875258304, HDRL_EPS_ERROR * 10);
+
+        a = -1.2;
+        hdrl_elemop_pow(&a, &ea, 1, &b, &eb, 1, NULL);
+
+        cpl_test(isnan(a));
+        cpl_test(isnan(ea));
+
+        /* negative value test */
+        a = -1.2;
+        ea = 0.6;
+        b = 3.;
+        hdrl_elemop_pow(&a, &ea, 1, &b, &eb, 1, NULL);
+
+        cpl_test_rel(a, pow(-1.2, 3.), HDRL_EPS_DATA);
+        cpl_test_rel(ea, 2.592, HDRL_EPS_ERROR * 10);
+    }
+
+    /* pow with error free power 2 exponent == repeated multiplication */
+    {
+        hdrl_data_t a = -1.2;
+        hdrl_error_t ea = 0.5;
+        hdrl_data_t b = 2.0;
+        hdrl_error_t eb = 0.0;
+
+        hdrl_elemop_pow(&a, &ea, 1, &b, &eb, 1, NULL);
+
+        hdrl_data_t a2 = -1.2;
+        hdrl_error_t ea2 = 0.5;
+        hdrl_elemop_mul(&a2, &ea2, 1, &a2, &ea2, 1, NULL);
+
+        cpl_test_rel(a, a2, HDRL_EPS_DATA);
+        cpl_test_rel(ea, ea2, HDRL_EPS_ERROR * 10);
+
+        a = -1.2;
+        ea = 0.5;
+        b = 4.0;
+        eb = 0.0;
+        hdrl_elemop_pow(&a, &ea, 1, &b, &eb, 1, NULL);
+        hdrl_elemop_mul(&a2, &ea2, 1, &a2, &ea2, 1, NULL);
+        cpl_test_rel(a, a2, HDRL_EPS_DATA);
+        cpl_test_rel(ea, ea2, HDRL_EPS_ERROR * 10);
+    }
+    /* array pow with error free power 2 exponent == repeated multiplication */
+    {
+        hdrl_data_t a[] = {0.3, 10.};
+        hdrl_error_t ea[] = {0.5, 2.};
+        hdrl_data_t b[] = {2.0, 2.0};
+        hdrl_error_t eb[] = {0., 0.};
+
+        hdrl_elemop_pow(a, ea, 2, b, eb, 2, NULL);
+
+        hdrl_data_t a2[] = {0.3, 10.};
+        hdrl_error_t ea2[] = {0.5, 2.};
+        hdrl_elemop_mul(a2, ea2, 2, a2, ea2, 2, NULL);
+
+        cpl_test_rel(a[0], a2[0], HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], ea2[0], HDRL_EPS_ERROR * 10);
+        cpl_test_rel(a[1], a2[1], HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], ea2[1], HDRL_EPS_ERROR * 10);
+    }
+
+    /* pow with error free -1 exponent == reciprocal */
+    {
+        hdrl_data_t a = 1.2;
+        hdrl_error_t ea = 0.5;
+        hdrl_data_t b = -1.0;
+        hdrl_error_t eb = 0.0;
+
+        hdrl_elemop_pow(&a, &ea, 1, &b, &eb, 1, NULL);
+
+        hdrl_data_t a2 = 1.0;
+        hdrl_error_t ea2 = 0.;
+        hdrl_data_t b2 = 1.2;
+        hdrl_error_t eb2 = 0.5;
+        hdrl_elemop_div(&a2, &ea2, 1, &b2, &eb2, 1, NULL);
+
+        cpl_test_rel(a, a2, HDRL_EPS_DATA);
+        cpl_test_rel(ea, ea2, HDRL_EPS_ERROR * 10);
+    }
+
+    /* array pow with error free -1 exponent == reciprocal*/
+    {
+        hdrl_data_t a[] = {0.3, 10.};
+        hdrl_error_t ea[] = {0.5, 2.};
+        hdrl_data_t b[] = {-1.0, -1.0};
+        hdrl_error_t eb[] = {0., 0.};
+
+        hdrl_elemop_pow(a, ea, 2, b, eb, 2, NULL);
+
+        hdrl_data_t a2[] = {1.0, 1.0};
+        hdrl_error_t ea2[] = {0., 0.};
+        hdrl_data_t b2[] = {0.3, 10.};
+        hdrl_error_t eb2[] = {0.5, 2.};
+        hdrl_elemop_div(a2, ea2, 2, b2, eb2, 2, NULL);
+
+        cpl_test_rel(a[0], a2[0], HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], ea2[0], HDRL_EPS_ERROR * 10);
+        cpl_test_rel(a[1], a2[1], HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], ea2[1], HDRL_EPS_ERROR * 10);
+    }
+
+    {
+        hdrl_data_t a = 1.2;
+        hdrl_error_t ea = 0.5;
+        hdrl_data_t b = 2.0;
+        hdrl_error_t eb = 2.0;
+
+        hdrl_elemop_pow(&a, &ea, 1, &b, &eb, 1, NULL);
+
+        cpl_test_rel(a, pow(1.2, b), HDRL_EPS_DATA);
+        cpl_test_rel(ea, 1.3098531960320208, HDRL_EPS_ERROR * 10);
+    }
+
+    {
+        hdrl_data_t a = 0.;
+        hdrl_error_t ea = 0.5;
+        hdrl_data_t b = -1.;
+        hdrl_error_t eb = 0.;
+
+        hdrl_elemop_pow(&a, &ea, 1, &b, &eb, 1, NULL);
+
+        cpl_test(isnan(a));
+        cpl_test(isnan(ea));
+    }
+
+    {
+        hdrl_data_t a[] = {0., 0.};
+        hdrl_error_t ea[] = {0.5, 0.5};
+        hdrl_data_t b = -1.;
+        hdrl_error_t eb = 0.;
+
+        hdrl_elemop_pow(a, ea, 2, &b, &eb, 1, NULL);
+
+        cpl_test(isnan(a[0]));
+        cpl_test(isnan(ea[0]));
+        cpl_test(isnan(a[1]));
+        cpl_test(isnan(ea[1]));
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        const hdrl_data_t b[] = {-2, 6};
+        const hdrl_error_t eb[] = {0.5, 3};
+
+        hdrl_elemop_pow(a, ea, ARRAY_LEN(a), b, eb, ARRAY_LEN(b), NULL);
+
+        cpl_test_rel(a[0], 0.25, HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], 0.15209233492346647, HDRL_EPS_ERROR * 10);
+        cpl_test_rel(a[1], 729, HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], 2810.438304633068, HDRL_EPS_ERROR * 10);
+    }
+
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        const hdrl_data_t b = -2;
+        const hdrl_error_t eb = 0.5;
+
+        hdrl_elemop_pow(a, ea, ARRAY_LEN(a), &b, &eb, 1, NULL);
+
+        cpl_test_rel(a[0], 0.25, HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], 0.15209233492346647, HDRL_EPS_ERROR * 10);
+        cpl_test_rel(a[1], 0.1111111111111111, HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], 0.09597978726560344, HDRL_EPS_ERROR * 10);
+    }
+
+    /* masked test */
+    {
+        hdrl_data_t a[] = {2, 3};
+        hdrl_error_t ea[] = {0.5, 1};
+        const hdrl_data_t b[] = {-2, 6};
+        const hdrl_error_t eb[] = {0.5, 3};
+        cpl_binary mask[] = {0, 1};
+
+        hdrl_elemop_pow(a, ea, ARRAY_LEN(a), b, eb, ARRAY_LEN(b), mask);
+
+        cpl_test_rel(a[0], 0.25, HDRL_EPS_DATA);
+        cpl_test_rel(ea[0], 0.15209233492346647, HDRL_EPS_ERROR * 10);
+        cpl_test_rel(a[1], 3., HDRL_EPS_DATA);
+        cpl_test_rel(ea[1], 1., HDRL_EPS_ERROR * 10);
+    }
+
+    return cpl_error_get_code();
+}
+
+static cpl_error_code
+hdrl_test_image(void)
+{
+    int is_rej;
+    hdrl_data_t ad[] = {2, 2};
+    hdrl_error_t ae[] = {0.5, 0.5};
+    hdrl_data_t bd[] = {3, 3};
+    hdrl_error_t be[] = {0.5, 0.5};
+    cpl_image * iad = cpl_image_wrap(1, 2, HDRL_TYPE_DATA, ad);
+    cpl_image * iae = cpl_image_wrap(1, 2, HDRL_TYPE_ERROR, ae);
+    cpl_image * ibd = cpl_image_wrap(1, 2, HDRL_TYPE_DATA, bd);
+    cpl_image * ibe = cpl_image_wrap(1, 2, HDRL_TYPE_ERROR, be);
+
+    hdrl_elemop_image_add_image(iad, iae, ibd, ibe);
+
+    cpl_test_rel(ad[0], 5., HDRL_EPS_DATA);
+    cpl_test_rel(ae[0], sqrt(0.5), HDRL_EPS_ERROR);
+
+    hdrl_elemop_image_sub_image(iad, iae, ibd, ibe);
+    cpl_test_rel(ad[0], 5. - 3., HDRL_EPS_DATA);
+
+    hdrl_elemop_image_mul_image(iad, iae, ibd, ibe);
+    cpl_test_rel(ad[0], (5. - 3.) * 3., HDRL_EPS_DATA);
+
+    hdrl_elemop_image_div_image(iad, iae, ibd, ibe);
+    cpl_test_rel(ad[0], ((5. - 3.) * 3.) / 3., HDRL_EPS_DATA);
+
+    hdrl_elemop_image_pow_image(iad, iae, ibd, ibe);
+    cpl_test_rel(ad[0], pow(((5. - 3.) * 3.) / 3., 3.), HDRL_EPS_DATA);
+
+    bd[0] = -1.;
+    ad[0] = 0.;
+    hdrl_elemop_image_pow_image(iad, iae, ibd, ibe);
+    cpl_test(cpl_image_is_rejected(iad, 1, 1));
+    cpl_image_accept_all(iad);
+    cpl_image_accept_all(iae);
+    ad[0] = 2.;
+
+    bd[0] = 0.;
+    hdrl_elemop_image_div_image(iad, iae, ibd, ibe);
+    cpl_test(cpl_image_is_rejected(iad, 1, 1));
+    bd[0] = 3.;
+
+    /* test a has bpm */
+    ad[0] = 2.;
+    ae[0] = 0.5;
+    cpl_image_set(iad, 1, 1, 2.);
+    cpl_image_reject(iad, 1, 1);
+    hdrl_elemop_image_div_image(iad, iae, ibd, ibe);
+    cpl_test(cpl_image_is_rejected(iad, 1, 1));
+    cpl_test_rel(ad[0], 2., 0);
+    cpl_image_accept_all(iad);
+    cpl_test_rel(cpl_image_get(iad, 1, 1, &is_rej), 2., 0);
+
+    /* test a and b have bpm */
+    ad[0] = 2.;
+    ae[0] = 0.5;
+    cpl_image_reject(iad, 1, 1);
+    cpl_image_reject(ibd, 1, 2);
+    hdrl_elemop_image_div_image(iad, iae, ibd, ibe);
+    cpl_test(cpl_image_is_rejected(iad, 1, 1));
+    cpl_test(cpl_image_is_rejected(iad, 1, 2));
+    cpl_test_rel(ad[0], 2., 0);
+    cpl_test_rel(ae[0], 0.5, 0);
+
+    /* test b has bpm */
+    ad[1] = 2.;
+    ae[1] = 0.5;
+    bd[1] = 2.;
+    be[1] = 0.5;
+    cpl_image_accept_all(iad);
+    cpl_image_reject(ibd, 1, 2);
+    hdrl_elemop_image_div_image(iad, iae, ibd, ibe);
+    cpl_test(cpl_image_is_rejected(iad, 1, 2));
+    cpl_test_rel(ad[1], 2., 0);
+    cpl_test_rel(ae[1], 0.5, 0);
+
+    cpl_image_unwrap(iad);
+    cpl_image_unwrap(iae);
+    cpl_image_unwrap(ibd);
+    cpl_image_unwrap(ibe);
+
+    return cpl_error_get_code();
+}
+
+
+static cpl_error_code
+hdrl_test_image_scalar(void)
+{
+    int is_rej;
+    hdrl_data_t ad = 2;
+    hdrl_error_t ae = 0.5;
+    const hdrl_data_t bd = 3;
+    const hdrl_error_t be = 0.5;
+    cpl_image * iad = cpl_image_wrap(1, 1, HDRL_TYPE_DATA, &ad);
+    cpl_image * iae = cpl_image_wrap(1, 1, HDRL_TYPE_ERROR, &ae);
+
+    hdrl_elemop_image_add_scalar(iad, iae, bd, be);
+
+    cpl_test_rel(ad, 5., HDRL_EPS_DATA);
+    cpl_test_rel(ae, sqrt(0.5), HDRL_EPS_ERROR);
+
+    hdrl_elemop_image_sub_scalar(iad, iae, bd, be);
+    cpl_test_rel(ad, 5. - 3., HDRL_EPS_DATA);
+
+    hdrl_elemop_image_mul_scalar(iad, iae, bd, be);
+    cpl_test_rel(ad, (5. - 3.) * 3., HDRL_EPS_DATA);
+
+    hdrl_elemop_image_div_scalar(iad, iae, bd, be);
+    cpl_test_rel(ad, ((5. - 3.) * 3.) / 3., HDRL_EPS_DATA);
+
+    hdrl_elemop_image_pow_scalar(iad, iae, bd, be);
+    cpl_test_rel(ad, pow(((5. - 3.) * 3.) / 3., 3.), HDRL_EPS_DATA);
+
+    hdrl_elemop_image_div_scalar(iad, iae, 0., be);
+    cpl_test(cpl_image_is_rejected(iad, 1, 1));
+
+    cpl_image_accept_all(iad);
+    cpl_image_set(iad, 1, 1, 0.);
+    hdrl_elemop_image_pow_scalar(iad, iae, -1., be);
+    cpl_test(cpl_image_is_rejected(iad, 1, 1));
+
+    cpl_image_set(iad, 1, 1, 2.);
+    cpl_image_reject(iad, 1, 1);
+    hdrl_elemop_image_div_scalar(iad, iae, bd, be);
+    cpl_test(cpl_image_is_rejected(iad, 1, 1));
+    cpl_image_accept_all(iad);
+    cpl_test_rel(cpl_image_get(iad, 1, 1, &is_rej), 2., 0);
+
+    cpl_image_unwrap(iad);
+    cpl_image_unwrap(iae);
+
+    return cpl_error_get_code();
+}
+
+
+static cpl_error_code
+hdrl_test_imagelist(void)
+{
+    int is_rej;
+    hdrl_data_t ad = 2;
+    hdrl_error_t ae = 0.5;
+    hdrl_data_t bd = 3;
+    hdrl_error_t be = 0.5;
+    cpl_image * _iad = cpl_image_wrap(1, 1, HDRL_TYPE_DATA, &ad);
+    cpl_image * _iae = cpl_image_wrap(1, 1, HDRL_TYPE_ERROR, &ae);
+    cpl_image * _ibd = cpl_image_wrap(1, 1, HDRL_TYPE_DATA, &bd);
+    cpl_image * _ibe = cpl_image_wrap(1, 1, HDRL_TYPE_ERROR, &be);
+    cpl_imagelist * iad = cpl_imagelist_new();
+    cpl_imagelist * iae = cpl_imagelist_new();
+    cpl_imagelist * ibd = cpl_imagelist_new();
+    cpl_imagelist * ibe = cpl_imagelist_new();
+    cpl_imagelist_set(iad, _iad, 0);
+    cpl_imagelist_set(ibd, _ibd, 0);
+    cpl_imagelist_set(iae, _iae, 0);
+    cpl_imagelist_set(ibe, _ibe, 0);
+
+    hdrl_elemop_imagelist_add_imagelist(iad, iae, ibd, ibe);
+    cpl_test_rel(ad, 5., HDRL_EPS_DATA);
+    cpl_test_rel(ae, sqrt(0.5), HDRL_EPS_ERROR);
+
+    hdrl_elemop_imagelist_sub_imagelist(iad, iae, ibd, ibe);
+    cpl_test_rel(ad, 5. - 3., HDRL_EPS_DATA);
+
+    hdrl_elemop_imagelist_mul_imagelist(iad, iae, ibd, ibe);
+    cpl_test_rel(ad, (5. - 3.) * 3., HDRL_EPS_DATA);
+
+    hdrl_elemop_imagelist_div_imagelist(iad, iae, ibd, ibe);
+    cpl_test_rel(ad, ((5. - 3.) * 3.) / 3., HDRL_EPS_DATA);
+
+    hdrl_elemop_imagelist_pow_imagelist(iad, iae, ibd, ibe);
+    cpl_test_rel(ad, pow(((5. - 3.) * 3.) / 3., 3.), HDRL_EPS_DATA);
+
+    cpl_image_set(_iad, 1, 1, 2.);
+    cpl_image_reject(_iad, 1, 1);
+    hdrl_elemop_imagelist_div_imagelist(iad, iae, ibd, ibe);
+    cpl_test(cpl_image_is_rejected(_iad, 1, 1));
+    cpl_image_accept_all(_iad);
+    cpl_test_rel(cpl_image_get(_iad, 1, 1, &is_rej), 2., 0);
+    cpl_imagelist_unwrap(iad);
+    cpl_imagelist_unwrap(iae);
+    cpl_imagelist_unwrap(ibd);
+    cpl_imagelist_unwrap(ibe);
+    cpl_image_unwrap(_iad);
+    cpl_image_unwrap(_iae);
+    cpl_image_unwrap(_ibd);
+    cpl_image_unwrap(_ibe);
+
+    return cpl_error_get_code();
+}
+
+static cpl_error_code
+hdrl_test_imagelist_image(void)
+{
+    int is_rej;
+    hdrl_data_t ad = 2;
+    hdrl_error_t ae = 0.5;
+    hdrl_data_t bd = 3;
+    hdrl_error_t be = 0.5;
+    cpl_image * _iad = cpl_image_wrap(1, 1, HDRL_TYPE_DATA, &ad);
+    cpl_image * _iae = cpl_image_wrap(1, 1, HDRL_TYPE_ERROR, &ae);
+    cpl_image * ibd = cpl_image_wrap(1, 1, HDRL_TYPE_DATA, &bd);
+    cpl_image * ibe = cpl_image_wrap(1, 1, HDRL_TYPE_ERROR, &be);
+    cpl_imagelist * iad = cpl_imagelist_new();
+    cpl_imagelist * iae = cpl_imagelist_new();
+    cpl_imagelist_set(iad, _iad, 0);
+    cpl_imagelist_set(iae, _iae, 0);
+
+    hdrl_elemop_imagelist_add_image(iad, iae, ibd, ibe);
+    cpl_test_rel(ad, 5., HDRL_EPS_DATA);
+    cpl_test_rel(ae, sqrt(0.5), HDRL_EPS_ERROR);
+
+    hdrl_elemop_imagelist_sub_image(iad, iae, ibd, ibe);
+    cpl_test_rel(ad, 5. - 3., HDRL_EPS_DATA);
+
+    hdrl_elemop_imagelist_mul_image(iad, iae, ibd, ibe);
+    cpl_test_rel(ad, (5. - 3.) * 3., HDRL_EPS_DATA);
+
+    hdrl_elemop_imagelist_div_image(iad, iae, ibd, ibe);
+    cpl_test_rel(ad, ((5. - 3.) * 3.) / 3., HDRL_EPS_DATA);
+
+    hdrl_elemop_imagelist_pow_image(iad, iae, ibd, ibe);
+    cpl_test_rel(ad, pow(((5. - 3.) * 3.) / 3., 3.), HDRL_EPS_DATA);
+
+    cpl_image_set(_iad, 1, 1, 2.);
+    cpl_image_reject(_iad, 1, 1);
+    hdrl_elemop_imagelist_div_image(iad, iae, ibd, ibe);
+    cpl_test(cpl_image_is_rejected(_iad, 1, 1));
+    cpl_image_accept_all(_iad);
+    cpl_test_rel(cpl_image_get(_iad, 1, 1, &is_rej), 2., 0);
+    cpl_imagelist_unwrap(iad);
+    cpl_imagelist_unwrap(iae);
+    cpl_image_unwrap(_iad);
+    cpl_image_unwrap(_iae);
+    cpl_image_unwrap(ibd);
+    cpl_image_unwrap(ibe);
+
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ @brief   Unit tests of variance module
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+
+    hdrl_test_add();
+    hdrl_test_sub();
+    hdrl_test_mul();
+    hdrl_test_div();
+    hdrl_test_pow();
+    hdrl_test_image();
+    hdrl_test_image_scalar();
+    hdrl_test_imagelist();
+    hdrl_test_imagelist_image();
+
+    return cpl_test_end(0);
+}
diff --git a/hdrl/tests/hdrl_fit-test.c b/hdrl/tests/hdrl_fit-test.c
new file mode 100644
index 0000000..86ae569
--- /dev/null
+++ b/hdrl/tests/hdrl_fit-test.c
@@ -0,0 +1,320 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_fit.c"
+#include "hdrl_imagelist.h"
+#include "hdrl_test.h"
+
+#include <cpl.h>
+
+#include <math.h>
+
+#ifndef ARRAY_LEN
+#define ARRAY_LEN(a) sizeof((a))/sizeof((a)[0])
+#endif
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_fit_test
+            Testing of hdrl_fit module
+ */
+/*----------------------------------------------------------------------------*/
+
+#define matrix_eq(m, exp, eps) \
+    do { \
+        for (size_t i = 0; i < (size_t)cpl_matrix_get_nrow(m); i++) { \
+            for (size_t j = 0; j < (size_t)cpl_matrix_get_ncol(m); j++) { \
+                cpl_test_abs(cpl_matrix_get(m, i, j), exp[i * \
+                             cpl_matrix_get_ncol(m) + j], eps); \
+            } \
+        } \
+    } while (0)
+
+static void test_vander1d(void)
+{
+    {
+        double p[] = {1, 2, 3, 4};
+        double exp[] = {1., 1., 1.,
+                        1., 2., 4.,
+                        1., 3., 9.,
+                        1., 4., 16.};
+        cpl_vector * pv = cpl_vector_wrap(ARRAY_LEN(p), p);
+        cpl_matrix * v = polyvander1d(pv, 2);
+        cpl_test_error(CPL_ERROR_NONE);
+        matrix_eq(v, exp, DBL_EPSILON * 5);
+        cpl_matrix_delete(v);
+
+        v = polyvander1d(pv, 2);
+        cpl_test_error(CPL_ERROR_NONE);
+        matrix_eq(v, exp, DBL_EPSILON * 5);
+        cpl_matrix_delete(v);
+
+        cpl_vector_unwrap(pv);
+    }
+    /* could be used for weight_design function */
+    if (0) {
+        double p[] = {1, 2, 3, 4};
+        double e[] = {1, 1, 4, 1};
+        double exp[] = {1.,   1.,   1.,
+                        1.,   2.,   4.,
+                        0.25, 0.75, 2.25,
+                        1.,   4.,   16.};
+        cpl_vector * pv = cpl_vector_wrap(ARRAY_LEN(p), p);
+        cpl_vector * ev = cpl_vector_wrap(ARRAY_LEN(e), e);
+        cpl_matrix * v = polyvander1d(pv, 2);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        matrix_eq(v, exp, DBL_EPSILON * 5);
+        cpl_vector_unwrap(pv);
+        cpl_vector_unwrap(ev);
+        cpl_matrix_delete(v);
+    }
+}
+
+static void test_fit(void)
+{
+    {
+        double s[] = {1, 2, 3, 4};
+        double p[] = {2, 2.5, 3, 3.5};
+        double exp[] = {1.5, 0.5, 0.};
+        double eres[] = {0., 0., 0., 0.};
+        cpl_vector * sv = cpl_vector_wrap(ARRAY_LEN(s), s);
+        cpl_vector * pv = cpl_vector_wrap(ARRAY_LEN(p), p);
+        cpl_vector * vre = cpl_vector_wrap(ARRAY_LEN(eres), eres);
+        cpl_matrix * v = polyvander1d(sv, 2);
+        hdrl_ls_fit_result * r = fit(v, pv, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+        matrix_eq(r->coef, exp, DBL_EPSILON * 10);
+        cpl_vector * res = hdrl_ls_fit_result_get_residuals(r, pv);
+        cpl_test_vector_abs(res, vre, DBL_EPSILON * 5);
+        cpl_vector_unwrap(vre);
+        cpl_vector_delete(res);
+        cpl_matrix_delete(v);
+        cpl_vector_unwrap(pv);
+        cpl_vector_unwrap(sv);
+        hdrl_ls_fit_result_delete(r);
+    }
+    {
+        double s[] = {1, 2, 3, 4, 5};
+        double p[] = {1.1, 2.5, 3.4, 3.8, 7};
+        double e[] = {0.3, 0.2, 0.2, 0.1, 0.5};
+        double exp[] = {0.54529, 0.858981};
+        double cexp[] = {0.0756216, -0.0206541, -0.0206541, 0.00613226};
+        cpl_vector * vfit = cpl_vector_new(ARRAY_LEN(s));
+        cpl_vector * vres = cpl_vector_new(ARRAY_LEN(s));
+        for (size_t i = 0; i < ARRAY_LEN(s); i++) {
+            cpl_vector_set(vfit, i, exp[0] + exp[1] * s[i]);
+            cpl_vector_set(vres, i,  p[i] - (exp[0] + exp[1] * s[i]));
+        }
+
+        cpl_vector * sv = cpl_vector_wrap(ARRAY_LEN(s), s);
+        cpl_vector * pv = cpl_vector_wrap(ARRAY_LEN(p), p);
+        cpl_vector * ev = cpl_vector_wrap(ARRAY_LEN(e), e);
+        cpl_matrix * v = polyvander1d(sv, 1);
+
+        hdrl_ls_fit_result * r = fit(v, pv, ev);
+        cpl_test_error(CPL_ERROR_NONE);
+        matrix_eq(r->coef, exp, DBL_EPSILON * 1e10);
+        matrix_eq(r->cov, cexp, DBL_EPSILON * 1e10);
+
+        cpl_vector * values = hdrl_ls_fit_result_get_fitted_values(r);
+        cpl_test_vector_abs(values, vfit, DBL_EPSILON * 1e10);
+        cpl_vector_delete(vfit);
+        cpl_vector_delete(values);
+        cpl_vector * resi = hdrl_ls_fit_result_get_residuals(r, pv);
+        cpl_test_vector_abs(resi, vres, DBL_EPSILON * 1e10);
+        cpl_vector_delete(vres);
+        cpl_vector_delete(resi);
+        cpl_matrix_delete(v);
+
+        hdrl_ls_fit_result_delete(r);
+
+        r = polyfit1d(sv, pv, ev, 1);
+        cpl_test_error(CPL_ERROR_NONE);
+        matrix_eq(r->coef, exp, DBL_EPSILON * 1e10);
+        hdrl_ls_fit_result_delete(r);
+
+        cpl_vector_unwrap(pv);
+        cpl_vector_unwrap(ev);
+        cpl_vector_unwrap(sv);
+    }
+}
+
+
+void test_poisson(void)
+{
+    double x[] = { 10.  , 62.1 , 114.2, 166.3, 218.4, 270.5, 322.6,
+                   374.7, 426.8, 478.9, 531.1, 583.2, 635.3, 687.4, 739.5,
+                   791.6, 843.7, 895.8, 947.9, 1000. };
+    /* poisson data with lambda: x / 10 (== variance) and 100 offset */
+    double y[] = { 103, 107, 111, 112, 117, 127, 126, 125, 139, 150, 157, 162,
+                   153, 158, 162, 184, 191, 195, 182, 196 };
+    cpl_vector * vx = cpl_vector_wrap(ARRAY_LEN(x), x);
+    cpl_vector * vy = cpl_vector_wrap(ARRAY_LEN(y), y);
+    /* relative model errors  (poisson model ~ sqrt(x)) */
+    cpl_vector * ve_model = cpl_vector_duplicate(vx);
+    cpl_vector_power(ve_model, 0.5);
+    /* real absolute error of the population != relative model errors */
+    cpl_vector * ve_real = cpl_vector_duplicate(vx);
+    cpl_vector_divide_scalar(ve_real, 10);
+    cpl_vector_power(ve_real, 0.5);
+
+
+    double exp_c[] = {101.4164, 0.0919476};
+    cpl_matrix * design = polyvander1d(vx, 1);
+    hdrl_ls_fit_result * res = polyfit1d(vx, vy, ve_model, 1);
+    matrix_eq(res->coef, exp_c, DBL_EPSILON * 2e12);
+    /* get sample error */
+    cpl_vector * pred_e =
+        hdrl_ls_fit_result_get_fit_interval(res, vy, ve_model);
+    /* should be less than < 20% deviation to population error */
+    cpl_test_vector_abs(pred_e, ve_real, 0.7);
+    cpl_vector_delete(pred_e);
+
+    cpl_vector_unwrap(vx);
+    cpl_vector_unwrap(vy);
+    cpl_vector_delete(ve_model);
+    cpl_vector_delete(ve_real);
+    cpl_matrix_delete(design);
+    hdrl_ls_fit_result_delete(res);
+}
+
+void test_imglistfit(void)
+{
+    {
+        size_t n = 5;
+        hdrl_imagelist * input = hdrl_imagelist_new();
+        cpl_vector * samp = cpl_vector_new(n);
+        hdrl_imagelist * out_coef = NULL;
+        cpl_image * out_chi2 = NULL;
+        cpl_image * out_dof = NULL;
+        hdrl_fit_polynomial_imagelist(NULL, NULL, 0, NULL, NULL, NULL);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+
+        hdrl_fit_polynomial_imagelist(input, NULL, 0, NULL, NULL, NULL);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+
+        hdrl_fit_polynomial_imagelist(NULL, samp, 0, NULL, NULL, NULL);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+
+        hdrl_fit_polynomial_imagelist(input, samp, 0, NULL, NULL, NULL);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+
+        hdrl_fit_polynomial_imagelist(input, samp, -1, &out_coef, &out_chi2, &out_dof);
+        cpl_test_error(CPL_ERROR_INCOMPATIBLE_INPUT);
+
+        for (size_t i = 0; i < n; i++) {
+            double t = (i + 1) * 100;
+            hdrl_image * img = hdrl_image_new(10, 10);
+            /* slight deviation from linear to get nonzero scale */
+            hdrl_image_add_scalar(img,
+                              (hdrl_value){0.5 * t + 100 - i, sqrt(0.5 * t)});
+            hdrl_imagelist_set(input, img, i);
+            cpl_vector_set(samp, i, t);
+        }
+
+        hdrl_fit_polynomial_imagelist(input, samp, 1, &out_coef, &out_chi2, &out_dof);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_test_eq(cpl_image_get_type(out_dof), HDRL_TYPE_DATA);
+        cpl_test_eq(cpl_image_get_type(out_chi2), HDRL_TYPE_DATA);
+        cpl_test_eq(hdrl_imagelist_get_size(out_coef), 2);
+
+        hdrl_image * coef0 = hdrl_imagelist_get(out_coef, 0);
+        hdrl_image * expect = hdrl_image_new(10, 10);
+        hdrl_image_add_scalar(expect, (hdrl_value){101, 9.0045});
+        hdrl_test_image_abs(coef0, expect, HDRL_EPS_DATA * 1e11);
+        hdrl_image_delete(expect);
+
+        hdrl_image * coef1 = hdrl_imagelist_get(out_coef, 1);
+        expect = hdrl_image_new(10, 10);
+        hdrl_image_add_scalar(expect, (hdrl_value){0.49, 0.0351317});
+        hdrl_test_image_abs(coef1, expect, HDRL_EPS_DATA * 1e11);
+        hdrl_image_delete(expect);
+
+        cpl_image * cexpect = cpl_image_new(10, 10, HDRL_TYPE_DATA);
+        /* dof*scaling between weights and measured error */
+        cpl_image_add_scalar(cexpect, 1.831e-29);
+        cpl_test_image_abs(out_chi2, cexpect, DBL_EPSILON * 1e9);
+        cpl_image_delete(cexpect);
+
+        cexpect = cpl_image_new(10, 10, HDRL_TYPE_DATA);
+        cpl_image_add_scalar(cexpect, 3);
+        cpl_test_image_abs(out_dof, cexpect, 0);
+        cpl_image_delete(cexpect);
+
+        hdrl_imagelist_delete(input);
+        cpl_vector_delete(samp);
+        hdrl_imagelist_delete(out_coef);
+        cpl_image_delete(out_chi2);
+        cpl_image_delete(out_dof);
+    }
+}
+
+void test_real_data(void)
+{
+    /* pixel from vcam ramp data with poisson model error (gain 2.4, ron 10) */
+    double x[] = {  3.,   3.,   5.,   5.,   7.,   7.,  10.,  10.,  12.,  12.,
+                    15., 15.,  20.,  20. };
+    double y[] = { 3441,  3420,  5606,  5586,  7814,  7815, 11003, 10970,
+                   13292, 13198, 16347, 16175, 21267, 21318 };
+    double e[] = { 39.16312027,  39.05124664,  49.35416031,  49.26966476,
+                   57.92955399,  57.93315125,  68.4440155 ,  68.34349823,
+                   75.08883667, 74.82757568,  83.13392639,  82.7017746 ,
+                   94.66387939,  94.77605438 };
+    cpl_vector * vx = cpl_vector_wrap(ARRAY_LEN(x), x);
+    cpl_vector * vy = cpl_vector_wrap(ARRAY_LEN(y), y);
+    cpl_vector * ve = cpl_vector_wrap(ARRAY_LEN(e), e);
+
+    double exp_c[] = {296.10245659,  1063.12005477};
+    cpl_matrix * design = polyvander1d(vx, 1);
+    hdrl_ls_fit_result * res = polyfit1d(vx, vy, ve, 1);
+    matrix_eq(res->coef, exp_c, DBL_EPSILON * 2e10);
+
+    cpl_vector_unwrap(vx);
+    cpl_vector_unwrap(vy);
+    cpl_vector_unwrap(ve);
+    cpl_matrix_delete(design);
+    hdrl_ls_fit_result_delete(res);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ @brief   Unit tests of hdrl_image
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+
+    test_vander1d();
+    test_fit();
+    test_poisson();
+    test_imglistfit();
+    test_real_data();
+
+    return cpl_test_end(0);
+}
diff --git a/hdrl/tests/hdrl_image-test.c b/hdrl/tests/hdrl_image-test.c
new file mode 100644
index 0000000..1d18781
--- /dev/null
+++ b/hdrl/tests/hdrl_image-test.c
@@ -0,0 +1,481 @@
+/* $Id: hdrl_image-test.c,v 1.5 2013-10-23 09:13:56 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-23 09:13:56 $
+ * $Revision: 1.5 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_image.h"
+#include "hdrl_test.h"
+#include "hdrl_imagelist.h"
+#include "hdrl_buffer.h"
+#include "hdrl_types.h"
+
+#include <cpl.h>
+
+#include <math.h>
+#include <float.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+#ifndef ARRAY_LEN
+#define ARRAY_LEN(a) sizeof((a))/sizeof((a)[0])
+#endif
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_image_test   
+            Testing of hdrl_image module
+ */
+/*----------------------------------------------------------------------------*/
+
+static void test_basic(void)
+{
+    hdrl_image * img;
+    cpl_image * cimg, * cerr;
+    cpl_error_code error;
+
+    hdrl_image_delete(NULL);
+
+    /* empty creation */
+
+    img = hdrl_image_new(5, 5);
+    cpl_test_nonnull(img);
+    cpl_test_error(CPL_ERROR_NONE);
+    hdrl_image_delete(img);
+
+    img = hdrl_image_new(0, 5);
+    cpl_test_null(img);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    img = hdrl_image_new(5, 0);
+    cpl_test_null(img);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    img = hdrl_image_new(0, 0);
+    cpl_test_null(img);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    img = hdrl_image_create(NULL, NULL);
+    cpl_test_null(img);
+    cpl_test_error(CPL_ERROR_NULL_INPUT);
+
+    /* creation with cpl image */
+
+    cimg = cpl_image_new(5, 6, CPL_TYPE_DOUBLE);
+    cerr = cpl_image_new(5, 6, CPL_TYPE_DOUBLE);
+
+    img = hdrl_image_create(NULL, cerr);
+    cpl_test_null(img);
+    cpl_test_error(CPL_ERROR_NULL_INPUT);
+
+    img = hdrl_image_create(cimg, NULL);
+    cpl_test_nonnull(img);
+    hdrl_image_delete(img);
+
+    img = hdrl_image_create(cimg, cerr);
+    cpl_test_nonnull(img);
+
+    /* dump the structure */
+    error = hdrl_image_dump_structure(img, stderr);
+    cpl_test_eq_error(error, CPL_ERROR_NONE);
+
+    error = hdrl_image_dump_window(img, 1, 1, 3, 3, stderr);
+    cpl_test_eq_error(error, CPL_ERROR_NONE);
+
+    hdrl_image_delete(img);
+
+    /* with bpm */
+
+    cpl_image_reject(cimg, 2, 3);
+    img = hdrl_image_create(cimg, cerr);
+    cpl_test_nonnull(img);
+    cpl_test_eq(hdrl_image_count_rejected(img), 1);
+    hdrl_image_delete(img);
+
+    cpl_image_reject(cerr, 2, 3);
+    img = hdrl_image_create(cimg, cerr);
+    cpl_test_eq(hdrl_image_count_rejected(img), 1);
+    cpl_test_nonnull(img);
+    hdrl_image_delete(img);
+
+    /* incompatible bpm (emits warning) */
+    cpl_image_reject(cerr, 2, 4);
+    img = hdrl_image_create(cimg, cerr);
+    cpl_test_eq(hdrl_image_count_rejected(img), 1);
+    cpl_test_nonnull(img);
+    hdrl_image_delete(img);
+
+    cpl_image_accept_all(cimg);
+    img = hdrl_image_create(cimg, cerr);
+    cpl_test_eq(hdrl_image_count_rejected(img), 0);
+    cpl_test_nonnull(img);
+    hdrl_image_delete(img);
+
+    cpl_image_delete(cerr);
+    cerr = cpl_image_new(2, 6, CPL_TYPE_DOUBLE);
+    img = hdrl_image_create(cimg, cerr);
+    cpl_test_null(img);
+    cpl_test_error(CPL_ERROR_INCOMPATIBLE_INPUT);
+
+    cpl_image_delete(cerr);
+    cerr = cpl_image_new(5, 2, CPL_TYPE_DOUBLE);
+    img = hdrl_image_create(cimg, cerr);
+    cpl_test_null(img);
+    cpl_test_error(CPL_ERROR_INCOMPATIBLE_INPUT);
+
+    /* reject/accept */
+    img = hdrl_image_new(5, 5);
+    hdrl_image_reject(img, 4, 5);
+    cpl_test(hdrl_image_is_rejected(img, 4, 5));
+    hdrl_image_accept(img, 4, 5);
+    cpl_test(!hdrl_image_is_rejected(img, 4, 5));
+
+    hdrl_image_reject(img, 5, 6);
+    cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+    hdrl_image_reject(img, 0, 6);
+    cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+    hdrl_image_accept(img, 6, 5);
+    cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+    hdrl_image_accept(img, 0, 5);
+    cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+
+    hdrl_image_reject(img, 4, 5);
+    hdrl_image_accept_all(img);
+    cpl_test(!hdrl_image_is_rejected(img, 4, 5));
+    hdrl_image_delete(img);
+
+    cpl_image_delete(cimg);
+    cpl_image_delete(cerr);
+}
+
+static void test_extract(void)
+{
+    cpl_size nx = 5;
+    cpl_size ny = 13;
+    hdrl_image * himg = hdrl_image_new(nx, ny);
+    hdrl_image * ex;
+    hdrl_image_add_scalar(himg, (hdrl_value){1., 1.});
+
+    ex = hdrl_image_extract(himg, 1, 1, nx, ny);
+    cpl_test_nonnull(ex);
+    hdrl_test_image_abs(himg, ex, 0);
+    hdrl_image_delete(ex);
+
+    ex = hdrl_image_extract(himg, 1, 1, 0, 0);
+    cpl_test_nonnull(ex);
+    hdrl_test_image_abs(himg, ex, 0);
+    hdrl_image_delete(ex);
+
+    ex = hdrl_image_extract(himg, 0, 0, 0, 0);
+    cpl_test_nonnull(ex);
+    cpl_test_eq(hdrl_image_get_size_x(ex), 1);
+    cpl_test_eq(hdrl_image_get_size_y(ex), 1);
+    hdrl_image_delete(ex);
+
+    ex = hdrl_image_extract(himg, 2, 2, -1, -1);
+    cpl_test_nonnull(ex);
+    cpl_test_eq(hdrl_image_get_size_x(ex), nx - 2);
+    cpl_test_eq(hdrl_image_get_size_y(ex), ny - 2);
+    hdrl_image_delete(ex);
+
+    ex = hdrl_image_extract(himg, 2, 2, -1, 2 * ny);
+    cpl_test_null(ex);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    ex = hdrl_image_extract(himg, 2, 2, -1, -2 * ny);
+    cpl_test_null(ex);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    ex = hdrl_image_extract(himg, 2, 2, -2 * nx, -2);
+    cpl_test_null(ex);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    ex = hdrl_image_extract(himg, 2, -2 * ny, -2, -2);
+    cpl_test_null(ex);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    ex = hdrl_image_extract(himg, -2 * nx, -2, -2, -2);
+    cpl_test_null(ex);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    hdrl_image_delete(himg);
+}
+
+static void test_power(void)
+{
+    hdrl_value v;
+    hdrl_image * himg = hdrl_image_new(1, 1);
+    hdrl_image_set_pixel(himg, 1, 1, (hdrl_value){2., 0.5});
+    hdrl_image_pow_scalar(himg, (hdrl_value){2., 0.});
+    v = hdrl_image_get_pixel(himg, 1, 1, NULL);
+    cpl_test_rel(v.data, 4., DBL_EPSILON);
+    cpl_test_rel(v.error, 2.0, DBL_EPSILON);
+
+    hdrl_image_set_pixel(himg, 1, 1, (hdrl_value){2., 0.5});
+    hdrl_image_pow_scalar(himg, (hdrl_value){4., 0.});
+    v = hdrl_image_get_pixel(himg, 1, 1, NULL);
+    cpl_test_rel(v.data, 16, DBL_EPSILON);
+    cpl_test_rel(v.error, 16, DBL_EPSILON);
+
+    hdrl_image_set_pixel(himg, 1, 1, (hdrl_value){2., 0.5});
+    hdrl_image_pow_scalar(himg, (hdrl_value){-1., 0.});
+    v = hdrl_image_get_pixel(himg, 1, 1, NULL);
+    cpl_test_rel(v.data, 0.5, DBL_EPSILON);
+    cpl_test_rel(v.error, 0.125, DBL_EPSILON);
+
+    hdrl_image_set_pixel(himg, 1, 1, (hdrl_value){2., 0.5});
+    hdrl_image_pow_scalar(himg, (hdrl_value){-2., 0.});
+    v = hdrl_image_get_pixel(himg, 1, 1, NULL);
+    cpl_test_rel(v.data, 0.25, DBL_EPSILON);
+    cpl_test_rel(v.error, 0.125, DBL_EPSILON); /* yes the same as ^-1 */
+
+    hdrl_image_set_pixel(himg, 1, 1, (hdrl_value){2., 0.5});
+    hdrl_image_pow_scalar(himg, (hdrl_value){-4., 0.});
+    v = hdrl_image_get_pixel(himg, 1, 1, NULL);
+    cpl_test_rel(v.data, 0.0625, DBL_EPSILON);
+    cpl_test_rel(v.error, 0.0625, DBL_EPSILON);
+
+    hdrl_image_delete(himg);
+}
+
+static void test_copy(void)
+{
+    hdrl_image * dst = hdrl_image_new(50, 50);
+    hdrl_image * src = hdrl_image_new(30, 30);
+    hdrl_image * expected = hdrl_image_new(50, 50);
+
+    hdrl_image_copy(dst, src, 10, 10);
+    hdrl_test_image_abs(dst, expected, 0);
+
+    hdrl_image_reject(expected, 1, 1);
+    /* bypass hdrl_image functions */
+    cpl_image_reject(hdrl_image_get_image(src), 1, 1);
+
+    hdrl_image_copy(dst, src, 10, 10);
+    hdrl_test_image_abs(dst, expected, 0);
+
+    hdrl_image_delete(dst);
+    hdrl_image_delete(src);
+    hdrl_image_delete(expected);
+}
+
+static void test_insert(void)
+{
+    hdrl_image * dst = hdrl_image_new(50, 50);
+    hdrl_image * dst2 = hdrl_image_new(50, 50);
+    cpl_image * im1 = cpl_image_new(50, 50, HDRL_TYPE_DATA);
+    cpl_image * im2 = cpl_image_new(50, 50, HDRL_TYPE_ERROR);
+    hdrl_image * him = hdrl_image_create(im1, im2);
+    cpl_image_reject(im1, 1, 1);
+    hdrl_image_reject(him, 1, 1);
+
+    hdrl_image_copy(dst2, him, 1, 1);
+    hdrl_image_insert(dst, im1, im2, 1, 1);
+    hdrl_test_image_abs(dst, dst2, 0);
+
+    hdrl_image_insert(dst, im1, NULL, 1, 1);
+    hdrl_test_image_abs(dst, dst2, 0);
+
+    hdrl_image_delete(dst);
+    hdrl_image_delete(dst2);
+    hdrl_image_delete(him);
+    cpl_image_delete(im1);
+    cpl_image_delete(im2);
+}
+
+static void test_reduce(void)
+{
+    {
+        size_t nx = 53, ny = 2310;
+        hdrl_value m;
+        hdrl_image * a = hdrl_image_new(nx, ny);
+        hdrl_image * b = hdrl_image_new(nx, ny);
+        hdrl_image * c = hdrl_image_new(nx, ny);
+        hdrl_imagelist * hl = hdrl_imagelist_new();
+        hdrl_image_add_scalar(a, (hdrl_value){5., 3.2});
+        hdrl_image_add_scalar(b, (hdrl_value){7., 1.2});
+        hdrl_image_add_scalar(b, (hdrl_value){-3., .2});
+
+        m = hdrl_image_get_mean(a);
+        cpl_test_abs(m.data, 5., HDRL_EPS_DATA);
+        cpl_test_abs(m.error, 3.2 / sqrt(nx * ny), HDRL_EPS_ERROR * nx * ny);
+
+        m = hdrl_image_get_weighted_mean(a);
+        cpl_test_abs(m.data, 5., HDRL_EPS_DATA);
+        cpl_test_abs(m.error, 3.2 / sqrt(nx * ny), HDRL_EPS_ERROR * nx * ny);
+
+        m = hdrl_image_get_sigclip_mean(a, 3., 3., 100);
+        cpl_test_abs(m.data, 5., HDRL_EPS_DATA);
+        cpl_test_abs(m.error, 3.2 / sqrt(nx * ny), HDRL_EPS_ERROR * nx * ny);
+
+        hdrl_imagelist_set(hl, a, 0);
+        hdrl_imagelist_set(hl, b, 1);
+        hdrl_imagelist_set(hl, c, 2);
+        hdrl_image * r;
+        cpl_image * con;
+
+        /* must be equivalent */
+        hdrl_imagelist_collapse_mean(hl, &r, &con);
+        hdrl_image_add_image(a, b);
+        hdrl_image_add_image(a, c);
+        hdrl_image_div_scalar(a, (hdrl_value){3., 0.});
+        hdrl_test_image_abs(a, r, HDRL_EPS_DATA);
+
+        hdrl_image_delete(r);
+        cpl_image_delete(con);
+        hdrl_imagelist_delete(hl);
+    }
+    { /* Test sigmaclipped mean */
+        hdrl_value m;
+        /* gauss mean 100 sigma 3.5 and 2 outliers */
+        double values[] = {92, 93, 94, 94, 95, 95, 96, 96, 96, 97,
+            97, 97, 97, 98, 98, 98, 98, 99, 99, 99,
+            99, 100, 100, 100, 100, 100, 101, 101, 101, 101,
+            102, 102, 102, 102, 103, 103, 103, 103, 104, 104,
+            104, 105, 105, 106, 106, 107, 108, 500, 600 };
+
+        cpl_image * data = cpl_image_wrap(7, 7, CPL_TYPE_DOUBLE, values);
+        cpl_image * errors = cpl_image_new(7, 7, CPL_TYPE_DOUBLE);
+        cpl_image_add_scalar(errors, 1);
+
+        cpl_image_set(errors, 7, 7, 100000.);
+        cpl_image_set(errors, 6, 7, 10000.);
+
+        hdrl_image * sigimage = hdrl_image_create(data, errors);
+
+        m = hdrl_image_get_sigclip_mean(sigimage, 3., 3., 100);
+        cpl_test_rel(m.data, 100., HDRL_EPS_DATA * 49);
+        cpl_test_rel(m.error, 1 / sqrt(7 * 7 - 2), HDRL_EPS_ERROR * 49);
+        cpl_image_unwrap(data);
+        cpl_image_delete(errors);
+        hdrl_image_delete(sigimage);
+    }
+    { /* Test minmax rejected mean */
+        hdrl_value m;
+        /* gauss mean 100 sigma 3.5 and 2 outliers */
+        double values[] = {-100000, 93, 94, 94, 95, 95, 96, 96, 96, 97,
+            97, 97, 97, 98, 98, 98, 98, 99, 99, 99,
+            99, 100, 100, 100, 100, 100, 101, 101, 101, 101,
+            102, 102, 102, 102, 103, 103, 103, 103, 104, 104,
+            104, 105, 105, 106, 106, 107, 108, 100000, 500000 };
+
+        cpl_image * data = cpl_image_wrap(7, 7, CPL_TYPE_DOUBLE, values);
+        cpl_image * errors = cpl_image_new(7, 7, CPL_TYPE_DOUBLE);
+        cpl_image_add_scalar(errors, 1);
+
+        cpl_image_set(errors, 7, 7,100000.);
+        cpl_image_set(errors, 6, 7,10000.);
+        cpl_image_set(errors, 1, 1,1000.);
+
+        /*cpl_image_save(data,"data.fits", CPL_TYPE_FLOAT, NULL,
+                       CPL_IO_CREATE);
+        cpl_image_save(errors,"errors.fits", CPL_TYPE_FLOAT, NULL,
+                       CPL_IO_CREATE);*/
+
+        hdrl_image * minmaximage = hdrl_image_create(data, errors);
+
+        m = hdrl_image_get_minmax_mean(minmaximage, 0, 0);
+        cpl_test_rel(m.data, 10298.122448979591, HDRL_EPS_DATA * 49);
+        m = hdrl_image_get_minmax_mean(minmaximage, 0, 1);
+        cpl_test_rel(m.data, 96.0, 0.005);
+        m = hdrl_image_get_minmax_mean(minmaximage, 0, 2);
+        cpl_test_rel(m.data, -2029.6170212765958, HDRL_EPS_DATA * 49);
+        m = hdrl_image_get_minmax_mean(minmaximage, 1, 2);
+        cpl_test_rel(m.data, 100.17391304347827, HDRL_EPS_DATA * 49);
+
+        hdrl_image_delete(minmaximage);
+        cpl_image_delete(errors);
+        cpl_image_unwrap(data);
+    }
+    /* test sum, sqsum */
+    {
+        size_t nx = 3, ny = 1;
+        hdrl_value m;
+        hdrl_image * a = hdrl_image_new(nx, ny);
+        hdrl_image_set_pixel(a, 1, 1, (hdrl_value){1 , 0.5});
+        hdrl_image_set_pixel(a, 2, 1, (hdrl_value){2., 1.5});
+        hdrl_image_set_pixel(a, 3, 1, (hdrl_value){3., 2.5});
+        hdrl_image_reject(a, 1, 1);
+
+        m = hdrl_image_get_sum(a);
+        cpl_test_abs(m.data, 5., HDRL_EPS_DATA);
+        cpl_test_abs(m.error, sqrt(1.5 * 1.5 + 2.5 * 2.5), HDRL_EPS_ERROR * 3);
+
+        m = hdrl_image_get_sqsum(a);
+        cpl_test_abs(m.data, 4. + 9., HDRL_EPS_DATA);
+        cpl_test_abs(m.error, 16.15549442140351, HDRL_EPS_ERROR * 6);
+        hdrl_image_delete(a);
+    }
+}
+
+
+static inline void test_buffer(void)
+{
+    hdrl_buffer * buf = hdrl_buffer_new();
+    hdrl_imagelist * hl = hdrl_imagelist_new();
+    for (size_t i = 0; i < 900; i++) {
+        hdrl_image * img =hdrl_image_new_from_buffer(500, 500, buf);
+        hdrl_imagelist_set(hl, img, i);
+        hdrl_image_add_scalar(img, (hdrl_value){1, 1});
+    }
+    cpl_msg_warning(cpl_func, "alloc done");
+
+    hdrl_image * m;
+    cpl_image * c;
+    hdrl_imagelist_collapse_mean(hl, &m, &c);
+    hdrl_image_delete(m);
+    cpl_image_delete(c);
+    cpl_msg_warning(cpl_func, "collapse done");
+
+    hdrl_imagelist_delete(hl);
+    hdrl_buffer_delete(buf);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ @brief   Unit tests of hdrl_image
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+
+    test_basic();
+    test_power();
+    test_copy();
+    test_insert();
+    test_extract();
+    test_reduce();
+    //test_buffer();
+
+    return cpl_test_end(0);
+}
diff --git a/hdrl/tests/hdrl_imagelist_basic-test.c b/hdrl/tests/hdrl_imagelist_basic-test.c
new file mode 100644
index 0000000..e41392c
--- /dev/null
+++ b/hdrl/tests/hdrl_imagelist_basic-test.c
@@ -0,0 +1,161 @@
+/* $Id: hdrl_imagelist_basic-test.c,v 1.6 2013-10-02 12:49:29 yjung Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: yjung $
+ * $Date: 2013-10-02 12:49:29 $
+ * $Revision: 1.6 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_imagelist.h"
+#include "hdrl_test.h"
+
+#include <cpl.h>
+
+#include <math.h>
+#include <float.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+#ifndef ARRAY_LEN
+#define ARRAY_LEN(a) sizeof((a))/sizeof((a)[0])
+#endif
+#define    IMAGESZ     265
+#define    IMAGENB     10
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_imagelist_basic_test   
+            Testing of hdrl_imagelist_basic module
+ */
+/*----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------*/
+/**
+ @brief   Unit tests of hdrl_image_basic
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+
+    hdrl_imagelist  *   himlist ;
+    hdrl_image      *   himg ;
+    hdrl_image      *   himg2 ;
+    cpl_image       *   contrib ;
+    cpl_image       *   contrib2 ;
+    cpl_size            nimages = IMAGENB ;
+
+    /* Create an image list */
+    himlist = hdrl_imagelist_new() ;
+    for (cpl_size i = 0 ; i < nimages ; i++) {
+        /*
+        What about having an
+
+        hdrl_image_load_image(hdrl_image * hdrlimage
+                           const char * filename,
+                           cpl_type     im_type,
+                           cpl_size     pnum,
+                           cpl_size     xtnum);
+
+        hdrl_image_load_error(hdrl_image * hdrlimage
+                           const char * filename,
+                           cpl_type     im_type,
+                           cpl_size     pnum,
+                           cpl_size     xtnum);
+
+        with the same API like cpl?
+        two functions are better in the case the error is in another fitsfile
+        */
+
+        himg = hdrl_image_new(IMAGESZ, IMAGESZ);
+        if (i == nimages / 2)
+            hdrl_image_add_scalar(himg, (hdrl_value){1000, 100});
+        else
+            hdrl_image_add_scalar(himg, (hdrl_value){i, 1});
+        hdrl_imagelist_set(himlist, himg, i);
+    }
+   
+    // Mean collapse
+    hdrl_imagelist_collapse_mean(himlist, &himg, &contrib);
+    hdrl_imagelist_collapse(himlist, HDRL_COLLAPSE_MEAN, &himg2, &contrib2);
+    hdrl_test_image_abs(himg, himg2, 0);
+    cpl_test_image_abs(contrib, contrib2, 0);
+    cpl_image_delete(contrib) ;
+    hdrl_image_delete(himg) ;
+    cpl_image_delete(contrib2) ;
+    hdrl_image_delete(himg2) ;
+
+    // Weighted Mean collapse
+    hdrl_imagelist_collapse_weighted_mean(himlist, &himg, &contrib);
+    hdrl_imagelist_collapse(himlist, HDRL_COLLAPSE_WEIGHTED_MEAN, &himg2, &contrib2);
+    hdrl_test_image_abs(himg, himg2, 0);
+    cpl_test_image_abs(contrib, contrib2, 0);
+    cpl_image_delete(contrib) ;
+    hdrl_image_delete(himg) ;
+    cpl_image_delete(contrib2) ;
+    hdrl_image_delete(himg2) ;
+
+    // Median collapse
+    hdrl_imagelist_collapse_median(himlist, &himg, &contrib);
+    hdrl_imagelist_collapse(himlist, HDRL_COLLAPSE_MEDIAN, &himg2, &contrib2);
+    hdrl_test_image_abs(himg, himg2, 0);
+    cpl_test_image_abs(contrib, contrib2, 0);
+    cpl_image_delete(contrib) ;
+    hdrl_image_delete(himg) ;
+    cpl_image_delete(contrib2) ;
+    hdrl_image_delete(himg2) ;
+
+    // Sigclip collapse
+    cpl_image * rej_low, * rej_high;
+    hdrl_imagelist_collapse_sigclip(himlist, 1.0, 3.0, 10, &himg, &contrib,
+                                    NULL, NULL);
+    cpl_image_delete(contrib) ;
+    hdrl_image_delete(himg) ;
+    hdrl_imagelist_collapse_sigclip(himlist, 1.0, 3.0, 10, &himg, &contrib,
+                                    &rej_low, NULL);
+    cpl_image_delete(contrib) ;
+    cpl_image_delete(rej_low) ;
+    hdrl_image_delete(himg) ;
+    hdrl_imagelist_collapse_sigclip(himlist, 1.0, 3.0, 10, &himg, &contrib,
+                                    NULL, &rej_high);
+    cpl_image_delete(contrib) ;
+    cpl_image_delete(rej_high) ;
+    hdrl_image_delete(himg) ;
+    hdrl_imagelist_collapse_sigclip(himlist, 1.0, 3.0, 10, &himg, &contrib,
+                                    &rej_low, &rej_high);
+    cpl_image_delete(contrib) ;
+    cpl_image_delete(rej_low) ;
+    cpl_image_delete(rej_high) ;
+    hdrl_image_delete(himg) ;
+
+    hdrl_imagelist_delete(himlist) ;
+    return cpl_test_end(0);
+}
+
diff --git a/hdrl/tests/hdrl_imagelist_io-test.c b/hdrl/tests/hdrl_imagelist_io-test.c
new file mode 100644
index 0000000..c4bb810
--- /dev/null
+++ b/hdrl/tests/hdrl_imagelist_io-test.c
@@ -0,0 +1,204 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013,2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_imagelist.h"
+#include "hdrl_utils.h"
+#include "hdrl_image.h"
+#include "hdrl_test.h"
+
+
+#include <cpl.h>
+
+#include <stdlib.h>
+#include <stdio.h>
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_imagelist_io-test 
+        Testing of functions working on hdrl_imagelist
+ */
+/*----------------------------------------------------------------------------*/
+
+void test_get(void)
+{
+    hdrl_imagelist * hl = NULL;
+    cpl_test_eq(hdrl_imagelist_get_size_x(hl), -1);
+    cpl_test_error(CPL_ERROR_NULL_INPUT);
+    cpl_test_eq(hdrl_imagelist_get_size_y(hl), -1);
+    cpl_test_error(CPL_ERROR_NULL_INPUT);
+    cpl_test_eq(hdrl_imagelist_get_size(hl), -1);
+    cpl_test_error(CPL_ERROR_NULL_INPUT);
+
+    hl = hdrl_imagelist_new();
+    cpl_test_eq(hdrl_imagelist_get_size(hl), 0);
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_eq(hdrl_imagelist_get_size_x(hl), -1);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    cpl_test_eq(hdrl_imagelist_get_size_y(hl), -1);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    hdrl_imagelist_set(hl, hdrl_image_new(5, 6), 0);
+    cpl_test_eq(hdrl_imagelist_get_size(hl), 1);
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_eq(hdrl_imagelist_get_size_x(hl), 5);
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_eq(hdrl_imagelist_get_size_y(hl), 6);
+    cpl_test_error(CPL_ERROR_NONE);
+
+    hdrl_imagelist_delete(hl);
+}
+
+cpl_error_code test_interface(void)
+{
+    hdrl_imagelist * hl = hdrl_imagelist_new();
+    hdrl_imagelist * h;
+    int c = 0;
+    hdrl_iter * it = hdrl_imagelist_get_iter_row_slices(hl, 1,
+                                                      HDRL_ITER_OWN_OUTPUT);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    cpl_test_null(it);
+
+    it = hdrl_imagelist_get_iter_row_slices(NULL, 1, HDRL_ITER_OWN_OUTPUT);
+    cpl_test_error(CPL_ERROR_NULL_INPUT);
+    cpl_test_null(it);
+
+    hdrl_imagelist_set(hl, hdrl_image_new(5, 5), 0);
+    it = hdrl_imagelist_get_iter_row_slices(hl, 0, HDRL_ITER_OWN_OUTPUT);
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_nonnull(it);
+    for (h = hdrl_iter_next(it); h != NULL; h = hdrl_iter_next(it)) {
+        c++;
+    }
+    cpl_test_eq(c, 5);
+    hdrl_iter_delete(it);
+
+    hdrl_imagelist_set(hl, hdrl_image_new(5, 5), 0);
+    it = hdrl_imagelist_get_iter_row_slices(hl, 3, 0);
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_nonnull(it);
+    c = 0;
+    for (h = hdrl_iter_next(it); h != NULL; h = hdrl_iter_next(it)) {
+        c++;
+        hdrl_imagelist_delete(h);
+    }
+    cpl_test_eq(c, 2);
+    hdrl_iter_delete(it);
+
+    hdrl_imagelist_set(hl, hdrl_image_new(5, 5), 0);
+    it = hdrl_imagelist_get_iter_row_slices(hl, 3000, HDRL_ITER_OWN_OUTPUT);
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_nonnull(it);
+    c = 0;
+    for (h = hdrl_iter_next(it); h != NULL; h = hdrl_iter_next(it)) {
+        c++;
+    }
+    cpl_test_eq(c, 1);
+    hdrl_iter_delete(it);
+
+    hdrl_imagelist_delete(hl);
+
+    return cpl_error_get_code();
+}
+
+
+cpl_error_code test_iter(void)
+{
+    const cpl_size nx = 500;
+    const cpl_size ny = 571;
+    const cpl_size nz = 121;
+    const cpl_size yslice = 23;
+    hdrl_imagelist * hl = hdrl_imagelist_new();
+    for (cpl_size i = 0; i < nz; i++) {
+        hdrl_image * img = hdrl_image_new(nx, ny);
+        hdrl_image_add_scalar(img, (hdrl_value){i, i});
+        hdrl_image_reject(img, 1, 5);
+        if ((i % 5) == 0) {
+            hdrl_image_reject(img, 2, 5);
+        }
+        hdrl_imagelist_set(hl, img, i);
+    }
+
+    for (cpl_size y = 1; y < ny + 1; y++) {
+        hdrl_imagelist * lview = hdrl_imagelist_row_view(hl, y, y);
+        hdrl_imagelist_add_scalar(lview, (hdrl_value){y, y});
+        hdrl_imagelist_delete(lview);
+    }
+
+    cpl_size ysum = 1;
+    hdrl_image * mean;
+    cpl_image * contrib;
+    hdrl_imagelist_collapse_mean(hl, &mean, &contrib);
+    hdrl_image * slicemean = hdrl_image_new(nx, ny);
+    cpl_image * slicecontrib = cpl_image_new(nx, ny, CPL_TYPE_INT);
+
+    hdrl_iter * it = hdrl_imagelist_get_iter_row_slices(hl, yslice,
+                                                          HDRL_ITER_OWN_OUTPUT);
+    for (hdrl_imagelist * h = hdrl_iter_next(it); h != NULL;
+         h = hdrl_iter_next(it)) {
+        cpl_test_eq(hdrl_imagelist_get_size(h), nz);
+        hdrl_image * img = hdrl_imagelist_get(h, 0);
+        cpl_test_eq(hdrl_image_get_size_x(img), nx);
+        cpl_test_leq(hdrl_image_get_size_y(img), yslice);
+        hdrl_image * m;
+        cpl_image * c;
+        hdrl_imagelist_collapse_mean(h, &m, &c);
+        hdrl_image_copy(slicemean, m, 1, ysum);
+        cpl_image_copy(slicecontrib, c, 1, ysum);
+        hdrl_image_delete(m);
+        cpl_image_delete(c);
+        ysum += hdrl_image_get_size_y(img);
+    }
+
+    cpl_test_eq(ysum - 1, ny);
+    hdrl_test_image_abs(slicemean, mean, nx * ny * DBL_EPSILON);
+    cpl_test_image_abs(slicecontrib, contrib, 0);
+
+    hdrl_iter_delete(it);
+    hdrl_imagelist_delete(hl);
+    hdrl_image_delete(slicemean);
+    cpl_image_delete(slicecontrib);
+    hdrl_image_delete(mean);
+    cpl_image_delete(contrib);
+
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ @brief   Unit tests of hdrl_image module
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+
+    test_get();
+    test_interface();
+    test_iter();
+
+    return cpl_test_end(0);
+}
diff --git a/hdrl/tests/hdrl_imagelist_view-test.c b/hdrl/tests/hdrl_imagelist_view-test.c
new file mode 100644
index 0000000..864cd02
--- /dev/null
+++ b/hdrl/tests/hdrl_imagelist_view-test.c
@@ -0,0 +1,507 @@
+/* $Id: hdrl_imagelist_view-test.c,v 1.3 2013-10-22 08:26:11 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-22 08:26:11 $
+ * $Revision: 1.3 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_imagelist.h"
+#include "hdrl_test.h"
+#include "hdrl_imagelist_view.h" /* TODO put in public api? */
+
+#include <cpl.h>
+
+#define IMG_PTR(a) \
+    cpl_image_get_data(hdrl_image_get_image(a))
+#define ERR_PTR(a) \
+    cpl_image_get_data(hdrl_image_get_image(a))
+#define MSK_PTR(a) \
+    cpl_mask_get_data(hdrl_image_get_mask(a))
+#define CIMG_PTR(a) \
+    cpl_image_get_data_const(hdrl_image_get_image_const(a))
+#define CERR_PTR(a) \
+    cpl_image_get_data_const(hdrl_image_get_image_const(a))
+#define CMSK_PTR(a) \
+    cpl_mask_get_data_const(hdrl_image_get_mask_const(a))
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_imagelist_view_test   
+            Testing of hdrl_imagelist_view module
+ */
+/*----------------------------------------------------------------------------*/
+
+#define YSIZE 73
+#define XSIZE 50
+
+cpl_error_code test_row_view(void)
+{
+    hdrl_imagelist  *   hlist;
+    hdrl_image      *   himg;
+    hdrl_image      *   himg2;
+    cpl_image       *   contrib;
+    cpl_image       *   contrib2;
+    cpl_image       *   ima;
+    cpl_image       *   ima_err;
+    cpl_size            nimages = 20;
+    hdrl_imagelist * view;
+    const hdrl_imagelist * cview;
+    cpl_imagelist * clist;
+
+    /* Create an image list */
+    hlist = hdrl_imagelist_new() ;
+    clist = cpl_imagelist_new() ;
+    for (cpl_size i = 0 ; i < nimages ; i++) {
+
+        ima = cpl_image_new(XSIZE, YSIZE, HDRL_TYPE_DATA);
+        ima_err = cpl_image_new(XSIZE, YSIZE, HDRL_TYPE_ERROR);
+        cpl_image_add_scalar(ima_err, 1.);
+        cpl_image_reject(ima, 1, 5);
+        if ((i % 5) == 0) {
+            cpl_image_reject(ima, 2, 5);
+        }
+        himg = hdrl_image_create(ima, ima_err);
+        cpl_image_delete(ima_err);
+        hdrl_imagelist_set(hlist, himg, i);
+        cpl_imagelist_set(clist, ima, i);
+    }
+
+    view = hdrl_imagelist_row_view(NULL, 10, 20);
+    cpl_test_null(view);
+    cpl_test_error(CPL_ERROR_NULL_INPUT);
+    view = hdrl_imagelist_row_view(hlist, 20, 10);
+    cpl_test_null(view);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    view = hdrl_imagelist_row_view(hlist, 0, 10);
+    cpl_test_null(view);
+    cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+    view = hdrl_imagelist_row_view(hlist, 1, YSIZE + 11);
+    cpl_test_null(view);
+    cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+
+    /* const variant */
+    cview = hdrl_imagelist_const_row_view(NULL, 10, 20);
+    cpl_test_null(cview);
+    cpl_test_error(CPL_ERROR_NULL_INPUT);
+    cview = hdrl_imagelist_const_row_view(hlist, 20, 10);
+    cpl_test_null(cview);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    cview = hdrl_imagelist_const_row_view(hlist, 0, 10);
+    cpl_test_null(cview);
+    cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+    cview = hdrl_imagelist_const_row_view(hlist, 1, YSIZE + 11);
+    cpl_test_null(cview);
+    cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+   
+    // Mean collapse
+    hdrl_imagelist_collapse_mean(hlist, &himg, &contrib);
+
+    view = hdrl_imagelist_row_view(hlist, 1, YSIZE);
+    hdrl_imagelist_collapse_mean(view, &himg2, &contrib2);
+
+    hdrl_test_image_abs(himg, himg2, 0);
+    cpl_test_image_abs(contrib, contrib2, 0);
+    cpl_image * ccontrib = cpl_image_new_from_accepted(clist);
+    cpl_test_image_abs(ccontrib, contrib2, 0);
+    cpl_image * cerror = cpl_image_cast(ccontrib, HDRL_TYPE_ERROR);
+    cpl_image_power(cerror, -0.5);
+    cpl_test_image_abs(hdrl_image_get_error(himg), cerror, HDRL_EPS_ERROR);
+    cpl_image_delete(contrib2);
+    hdrl_image_delete(himg2);
+    cpl_image_delete(cerror);
+
+    /* const variant */
+    cview = hdrl_imagelist_const_row_view(hlist, 1, YSIZE);
+    hdrl_imagelist_collapse_mean(view, &himg2, &contrib2);
+
+    hdrl_test_image_abs(himg, himg2, 0);
+    cpl_test_image_abs(contrib, contrib2, 0);
+    cpl_test_image_abs(ccontrib, contrib2, 0);
+    cerror = cpl_image_cast(ccontrib, HDRL_TYPE_ERROR);
+    cpl_image_power(cerror, -0.5);
+    cpl_test_image_abs(hdrl_image_get_error(himg), cerror, HDRL_EPS_ERROR);
+    hdrl_image_delete(himg);
+    cpl_image_delete(contrib2);
+    hdrl_image_delete(himg2);
+    cpl_image_delete(ccontrib);
+    cpl_image_delete(cerror);
+    cpl_image_delete(contrib);
+
+    /* one has no bpm */
+    hdrl_image * iorig = hdrl_imagelist_get(hlist, 1);
+    hdrl_image * iview = hdrl_imagelist_get(view, 1);
+    cpl_test_eq_ptr(IMG_PTR(iorig), IMG_PTR(iview));
+    cpl_test_eq_ptr(ERR_PTR(iorig), ERR_PTR(iview));
+    cpl_test_eq_ptr(MSK_PTR(iorig), MSK_PTR(iview));
+
+    const hdrl_image * ciview = hdrl_imagelist_get(cview, 1);
+    cpl_test_eq_ptr(IMG_PTR(iorig), CIMG_PTR(ciview));
+    cpl_test_eq_ptr(ERR_PTR(iorig), CERR_PTR(ciview));
+    cpl_test_eq_ptr(MSK_PTR(iorig), CMSK_PTR(ciview));
+
+    /* zero has bpm */
+    iorig = hdrl_imagelist_get(hlist, 0);
+    iview = hdrl_imagelist_get(view, 0);
+    cpl_test_eq_ptr(IMG_PTR(iorig), IMG_PTR(iview));
+    cpl_test_eq_ptr(ERR_PTR(iorig), ERR_PTR(iview));
+    cpl_test_eq_ptr(MSK_PTR(iorig), MSK_PTR(iview));
+
+    ciview = hdrl_imagelist_get(cview, 0);
+    cpl_test_eq_ptr(IMG_PTR(iorig), CIMG_PTR(ciview));
+    cpl_test_eq_ptr(ERR_PTR(iorig), CERR_PTR(ciview));
+    cpl_test_eq_ptr(MSK_PTR(iorig), CMSK_PTR(ciview));
+
+    hdrl_image * icopy = hdrl_image_duplicate(iview);
+    cpl_test_eq(hdrl_image_get_size_y(icopy), YSIZE);
+    cpl_test_noneq_ptr(IMG_PTR(icopy), IMG_PTR(iview));
+    cpl_test_noneq_ptr(ERR_PTR(icopy), ERR_PTR(iview));
+    cpl_test_noneq_ptr(MSK_PTR(icopy), MSK_PTR(iview));
+    hdrl_image_delete(icopy);
+
+    hdrl_imagelist * lcopy = hdrl_imagelist_duplicate(view);
+    hdrl_imagelist_delete(view);
+    cpl_test_eq(hdrl_imagelist_get_size(lcopy), nimages);
+    cpl_test_eq(hdrl_image_get_size_y(hdrl_imagelist_get(lcopy, 0)), YSIZE);
+    hdrl_imagelist_delete(lcopy);
+
+    cpl_size nsizey = YSIZE - 17 - 5 + 1;
+    view = hdrl_imagelist_row_view(hlist, 5, YSIZE - 17);
+    hdrl_image * vimg = hdrl_imagelist_get(view, 0);
+    hdrl_image_add_scalar(vimg, (hdrl_value){5, 1});
+
+    cpl_test_eq(hdrl_image_get_size_x(vimg), XSIZE);
+    cpl_test_eq(hdrl_image_get_size_y(vimg), nsizey);
+
+    hdrl_image * orig = hdrl_imagelist_get(hlist, 0);
+    /* mean of original image (mix of 5s and zeros) */
+    cpl_test_noneq(hdrl_image_get_mean(orig).data, 5);
+
+    vimg = hdrl_imagelist_get(view, 0);
+    cpl_test_rel(hdrl_image_get_mean(vimg).data, 5,
+                 HDRL_EPS_DATA * XSIZE * YSIZE);
+
+    hdrl_imagelist_delete(view);
+    hdrl_imagelist_delete((hdrl_imagelist*)cview);
+
+    hdrl_imagelist_delete(hlist);
+    cpl_imagelist_delete(clist);
+
+    return cpl_error_get_code();
+}
+
+cpl_error_code test_cpl_row_view_invalid(void)
+{
+    cpl_imagelist * imglist = cpl_imagelist_new();
+    cpl_imagelist * errlist = cpl_imagelist_new();
+    const hdrl_imagelist * view;
+
+    view = hdrl_imagelist_const_cpl_row_view(NULL, errlist, 1, 2);
+    cpl_test_null(view);
+    cpl_test_error(CPL_ERROR_NULL_INPUT);
+
+    view = hdrl_imagelist_const_cpl_row_view(imglist, errlist, 1, 0);
+    cpl_test_null(view);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    view = hdrl_imagelist_const_cpl_row_view(imglist, errlist, 1, 2);
+    cpl_test_null(view);
+    cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+
+    cpl_image * img = cpl_image_new(5, 5, HDRL_TYPE_DATA);
+    cpl_imagelist_set(imglist, img, 0);
+    cpl_image * err = cpl_image_new(6, 5, HDRL_TYPE_ERROR);
+    cpl_imagelist_set(errlist, err, 0);
+
+    view = hdrl_imagelist_const_cpl_row_view(imglist, errlist, 1, 2);
+    cpl_test_null(view);
+    cpl_test_error(CPL_ERROR_INCOMPATIBLE_INPUT);
+
+    cpl_image_delete(cpl_imagelist_unset(imglist, 0));
+    cpl_image_delete(cpl_imagelist_unset(errlist, 0));
+
+    img = cpl_image_new(5, 5, CPL_TYPE_INT);
+    cpl_imagelist_set(imglist, img, 0);
+    err = cpl_image_new(5, 5, CPL_TYPE_INT);
+    cpl_imagelist_set(errlist, err, 0);
+
+    view = hdrl_imagelist_const_cpl_row_view(imglist, errlist, 1, 2);
+    cpl_test_null(view);
+    cpl_test_error(CPL_ERROR_INCOMPATIBLE_INPUT);
+
+    cpl_image_delete(cpl_imagelist_unset(imglist, 0));
+    cpl_image_delete(cpl_imagelist_unset(errlist, 0));
+
+    img = cpl_image_new(5, 5, HDRL_TYPE_DATA);
+    cpl_imagelist_set(imglist, img, 0);
+    err = cpl_image_new(5, 5, HDRL_TYPE_ERROR);
+    cpl_imagelist_set(errlist, err, 0);
+    cpl_image_reject(img, 1, 1);
+
+    view = hdrl_imagelist_const_cpl_row_view(imglist, errlist, 1, 2);
+    cpl_test_null(view);
+    cpl_test_error(CPL_ERROR_INCOMPATIBLE_INPUT);
+
+    cpl_image_reject(img, 1, 1);
+    cpl_image_reject(err, 1, 2);
+
+    view = hdrl_imagelist_const_cpl_row_view(imglist, errlist, 1, 2);
+    cpl_test_null(view);
+    cpl_test_error(CPL_ERROR_INCOMPATIBLE_INPUT);
+
+    cpl_image_accept_all(img);
+
+    view = hdrl_imagelist_const_cpl_row_view(imglist, errlist, 1, 2);
+    cpl_test_null(view);
+    cpl_test_error(CPL_ERROR_INCOMPATIBLE_INPUT);
+
+    cpl_imagelist_delete(imglist);
+    cpl_imagelist_delete(errlist);
+
+    return cpl_error_get_code();
+}
+
+cpl_error_code test_cpl_row_view(void)
+{
+    hdrl_imagelist  *   hlist;
+    hdrl_imagelist  *   hlist_noerr;
+    hdrl_image      *   himg;
+    hdrl_image      *   vhimg;
+    cpl_image       *   contrib;
+    cpl_image       *   vcontrib;
+    cpl_image       *   ima;
+    cpl_image       *   ima_err;
+    cpl_size            nimages = 20;
+    const hdrl_imagelist * cview;
+    cpl_imagelist * cimglist, * cerrlist;
+
+    /* Create an image list */
+    hlist = hdrl_imagelist_new() ;
+    hlist_noerr = hdrl_imagelist_new() ;
+    cimglist = cpl_imagelist_new() ;
+    cerrlist = cpl_imagelist_new() ;
+    for (cpl_size i = 0 ; i < nimages ; i++) {
+
+        ima = cpl_image_new(XSIZE, YSIZE, HDRL_TYPE_DATA);
+        ima_err = cpl_image_new(XSIZE, YSIZE, HDRL_TYPE_ERROR);
+        cpl_image_add_scalar(ima_err, 1.);
+        cpl_image_reject(ima, 1, 5);
+        cpl_image_reject(ima_err, 1, 5);
+        if ((i % 5) == 0) {
+            cpl_image_reject(ima, 2, 5);
+            cpl_image_reject(ima_err, 2, 5);
+        }
+        himg = hdrl_image_create(ima, ima_err);
+        hdrl_imagelist_set(hlist, himg, i);
+        hdrl_imagelist_set(hlist_noerr, hdrl_image_create(ima, NULL), i);
+        cpl_imagelist_set(cimglist, ima, i);
+        cpl_imagelist_set(cerrlist, ima_err, i);
+    }
+
+    cview = hdrl_imagelist_const_cpl_row_view(cimglist, cerrlist, 1, YSIZE);
+    cpl_test_nonnull(cview);
+    cpl_test_error(CPL_ERROR_NONE);
+    hdrl_imagelist_collapse_weighted_mean(hlist, &himg, &contrib);
+    hdrl_imagelist_collapse_weighted_mean(cview, &vhimg, &vcontrib);
+    hdrl_test_image_abs(himg, vhimg, 0);
+    cpl_test_image_abs(contrib, vcontrib, 0);
+    hdrl_image_delete(himg);
+    hdrl_image_delete(vhimg);
+    cpl_image_delete(contrib);
+    cpl_image_delete(vcontrib);
+
+    hdrl_imagelist_collapse_mean(hlist, &himg, &contrib);
+    hdrl_imagelist_collapse_mean(cview, &vhimg, &vcontrib);
+    hdrl_test_image_abs(himg, vhimg, 0);
+    cpl_test_image_abs(contrib, vcontrib, 0);
+    hdrl_image_delete(himg);
+    hdrl_image_delete(vhimg);
+    cpl_image_delete(contrib);
+    cpl_image_delete(vcontrib);
+
+    hdrl_imagelist_delete((hdrl_imagelist*)cview);
+
+    /* no error test */
+    cview = hdrl_imagelist_const_cpl_row_view(cimglist, NULL, 1, YSIZE);
+    hdrl_imagelist_collapse_mean(hlist_noerr, &himg, &contrib);
+    hdrl_imagelist_collapse_mean(cview, &vhimg, &vcontrib);
+    hdrl_test_image_abs(himg, vhimg, 0);
+    cpl_test_image_abs(contrib, vcontrib, 0);
+    hdrl_image_delete(himg);
+    hdrl_image_delete(vhimg);
+    cpl_image_delete(contrib);
+    cpl_image_delete(vcontrib);
+
+    hdrl_imagelist_collapse_median(hlist_noerr, &himg, &contrib);
+    hdrl_imagelist_collapse_median(cview, &vhimg, &vcontrib);
+    hdrl_test_image_abs(himg, vhimg, 0);
+    cpl_test_image_abs(contrib, vcontrib, 0);
+    hdrl_image_delete(himg);
+    hdrl_image_delete(vhimg);
+    cpl_image_delete(contrib);
+    cpl_image_delete(vcontrib);
+
+    hdrl_imagelist_collapse_sigclip(hlist_noerr, 3., 3., 3, &himg, &contrib,
+                                    NULL, NULL);
+    hdrl_imagelist_collapse_sigclip(cview, 3., 3., 3, &vhimg, &vcontrib,
+                                    NULL, NULL);
+    hdrl_test_image_abs(himg, vhimg, 0);
+    cpl_test_image_abs(contrib, vcontrib, 0);
+    hdrl_image_delete(himg);
+    hdrl_image_delete(vhimg);
+    cpl_image_delete(contrib);
+    cpl_image_delete(vcontrib);
+
+    hdrl_imagelist_collapse_minmax(hlist_noerr, 3., 3., &himg, &contrib,
+                                    NULL, NULL);
+    hdrl_imagelist_collapse_minmax(cview, 3., 3., &vhimg, &vcontrib,
+                                    NULL, NULL);
+    hdrl_test_image_abs(himg, vhimg, 0);
+    cpl_test_image_abs(contrib, vcontrib, 0);
+    hdrl_image_delete(himg);
+    hdrl_image_delete(vhimg);
+    cpl_image_delete(contrib);
+    cpl_image_delete(vcontrib);
+
+    hdrl_imagelist_delete((hdrl_imagelist*)cview);
+    hdrl_imagelist_delete(hlist);
+    hdrl_imagelist_delete(hlist_noerr);
+    cpl_imagelist_delete(cimglist);
+    cpl_imagelist_delete(cerrlist);
+
+    return cpl_error_get_code();
+}
+
+
+cpl_error_code test_image_view(void)
+{
+    hdrl_imagelist * hl = hdrl_imagelist_new();
+    hdrl_imagelist * view;
+
+    view = hdrl_imagelist_image_view(hl, 5, 1);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    cpl_test_null(view);
+
+    view = hdrl_imagelist_image_view(hl, 1, 1);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    cpl_test_null(view);
+
+    view = hdrl_imagelist_image_view(hl, 0, 1);
+    cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+    cpl_test_null(view);
+
+    hdrl_imagelist_set(hl, hdrl_image_new(5, 7), 0);
+
+    view = hdrl_imagelist_image_view(hl, 1, 2);
+    cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+    cpl_test_null(view);
+
+    view = hdrl_imagelist_image_view(hl, -1, 1);
+    cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+    cpl_test_null(view);
+
+    view = hdrl_imagelist_image_view(hl, 0, 1);
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_nonnull(view);
+
+    cpl_test_eq(hdrl_imagelist_get_size(view), hdrl_imagelist_get_size(hl));
+
+    hdrl_imagelist_add_scalar(hl, (hdrl_value){1, 1});
+
+    hdrl_test_image_abs(hdrl_imagelist_get(view, 0),
+                        hdrl_imagelist_get(hl, 0), 0);
+
+    hdrl_image * n = hdrl_image_new(5, 7);
+    hdrl_imagelist_set(hl, hdrl_image_new(5, 7), 1);
+
+    hdrl_test_image_abs(hdrl_imagelist_get(view, 0),
+                        hdrl_imagelist_get(hl, 0), 0);
+    hdrl_test_image_abs(hdrl_imagelist_get(hl, 1), n, 0);
+    hdrl_imagelist_delete(view);
+    hdrl_image_delete(n);
+
+    hdrl_imagelist_set(hl, hdrl_image_new(5, 7), 2);
+    hdrl_imagelist_set(hl, hdrl_image_new(5, 7), 3);
+    view = hdrl_imagelist_image_view(hl, 1, 2);
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_eq(hdrl_imagelist_get_size(view), 1);
+    cpl_test_eq_ptr(IMG_PTR(hdrl_imagelist_get(view, 0)),
+                    IMG_PTR(hdrl_imagelist_get(hl, 1)));
+    cpl_test_eq_ptr(ERR_PTR(hdrl_imagelist_get(view, 0)),
+                    ERR_PTR(hdrl_imagelist_get(hl, 1)));
+    cpl_test_eq_ptr(MSK_PTR(hdrl_imagelist_get(view, 0)),
+                    MSK_PTR(hdrl_imagelist_get(hl, 1)));
+    hdrl_imagelist_delete(view);
+
+    view = hdrl_imagelist_image_view(hl, 1, 3);
+    cpl_test_eq(hdrl_imagelist_get_size(view), 2);
+    cpl_test_eq_ptr(IMG_PTR(hdrl_imagelist_get(view, 0)),
+                    IMG_PTR(hdrl_imagelist_get(hl, 1)));
+    cpl_test_eq_ptr(ERR_PTR(hdrl_imagelist_get(view, 0)),
+                    ERR_PTR(hdrl_imagelist_get(hl, 1)));
+    cpl_test_eq_ptr(MSK_PTR(hdrl_imagelist_get(view, 0)),
+                    MSK_PTR(hdrl_imagelist_get(hl, 1)));
+    cpl_test_eq_ptr(IMG_PTR(hdrl_imagelist_get(view, 1)),
+                    IMG_PTR(hdrl_imagelist_get(hl, 2)));
+    cpl_test_eq_ptr(ERR_PTR(hdrl_imagelist_get(view, 1)),
+                    ERR_PTR(hdrl_imagelist_get(hl, 2)));
+    cpl_test_eq_ptr(MSK_PTR(hdrl_imagelist_get(view, 1)),
+                    MSK_PTR(hdrl_imagelist_get(hl, 2)));
+
+    /* test view of view */
+    hdrl_imagelist * rview = hdrl_imagelist_row_view(view, 2, 7);
+    cpl_test_eq(hdrl_imagelist_get_size(rview), hdrl_imagelist_get_size(view));
+    hdrl_image * tmp = hdrl_imagelist_get(rview, 0);
+    cpl_test_eq(hdrl_image_get_size_x(tmp), 5);
+    cpl_test_eq(hdrl_image_get_size_y(tmp), 6);
+    hdrl_imagelist_delete(rview);
+
+    hdrl_imagelist_delete(hl);
+    hdrl_imagelist_delete(view);
+
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ @brief   Unit tests of hdrl_image_view
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+
+    test_row_view();
+    test_image_view();
+    test_cpl_row_view_invalid();
+    test_cpl_row_view();
+
+    return cpl_test_end(0);
+}
diff --git a/hdrl/tests/hdrl_lacosmics-test.c b/hdrl/tests/hdrl_lacosmics-test.c
new file mode 100644
index 0000000..1402feb
--- /dev/null
+++ b/hdrl/tests/hdrl_lacosmics-test.c
@@ -0,0 +1,244 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_lacosmics.h"
+#include "hdrl_bpm_2d.h"
+#include <cpl.h>
+
+#include <math.h>
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_lacosmics_test   Testing of the HDRL cosmic ray rejection
+ */
+/*----------------------------------------------------------------------------*/
+
+cpl_error_code test_lacosmic_bad_input(void)
+{
+    cpl_mask * res;
+    hdrl_parameter * params = hdrl_lacosmic_parameter_create(5, 2.0, 5);
+    /* image smaller than 7x7 kernel */
+    hdrl_image * img = hdrl_image_new(6, 1000);
+    res = hdrl_lacosmic_edgedetect(img, params);
+    cpl_test_error(CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_test_null(res);
+    hdrl_image_delete(img);
+
+    img = hdrl_image_new(1200, 4);
+    res = hdrl_lacosmic_edgedetect(img, params);
+    cpl_test_error(CPL_ERROR_INCOMPATIBLE_INPUT);
+    cpl_test_null(res);
+    hdrl_image_delete(img);
+
+    hdrl_parameter_delete(params);
+
+    return cpl_error_get_code();
+}
+
+cpl_error_code test_lacosmic_edgedetect(void)
+{
+    cpl_image * img_data  = NULL;
+    cpl_mask  * img_mask = NULL;
+    cpl_image * img_error  = NULL;
+    cpl_mask *  result_mask = NULL;
+    /* detect single pixel cosmics  */
+    {
+        img_data = cpl_image_new(200, 300, CPL_TYPE_DOUBLE);
+        img_mask = cpl_mask_new(200, 300);
+        cpl_image_fill_noise_uniform(img_data, 90, 110);
+        double error = (110 - 90) / sqrt(12);
+        cpl_image_set(img_data,  50,  50, 300.);
+        cpl_image_set(img_data, 100, 100, 300.);
+        cpl_image_set(img_data, 150, 150, 300.);
+        cpl_image_set(img_data, 100, 250, 300.);
+
+        img_error = cpl_image_new(cpl_image_get_size_x(img_data),
+                                  cpl_image_get_size_y(img_data),
+                                  CPL_TYPE_DOUBLE);
+        cpl_image_add_scalar(img_error, error);
+
+        cpl_mask_set(img_mask, 120,120, CPL_BINARY_1);
+        cpl_mask_set(img_mask, 120,121, CPL_BINARY_1);
+        cpl_mask_set(img_mask, 120,122, CPL_BINARY_1);
+        cpl_mask_set(img_mask, 121,120, CPL_BINARY_1);
+        cpl_mask_set(img_mask, 121,121, CPL_BINARY_1);
+        cpl_mask_set(img_mask, 121,122, CPL_BINARY_1);
+        cpl_mask_set(img_mask, 122,120, CPL_BINARY_1);
+        cpl_mask_set(img_mask, 122,121, CPL_BINARY_1);
+        cpl_mask_set(img_mask, 122,122, CPL_BINARY_1);
+        /*set one outlier on a bad pixel*/
+        cpl_image_set(img_data, 122, 122, 300.);
+
+        cpl_image_reject_from_mask(img_data, img_mask);
+        hdrl_image * image = hdrl_image_create(img_data, img_error);
+        hdrl_parameter * params =
+            hdrl_lacosmic_parameter_create(error * 2, 2.0, 5);
+        result_mask = hdrl_lacosmic_edgedetect(image, params);
+        hdrl_parameter_delete(params) ;
+
+        /*
+        cpl_image_save(data, "test_image.fits", CPL_TYPE_DOUBLE, NULL,
+                       CPL_IO_CREATE);
+        cpl_image_save(data_error, "test_error.fits", CPL_TYPE_DOUBLE, NULL,
+                       CPL_IO_CREATE);
+        cpl_mask_save(data_result, "test_cr.fits", NULL, CPL_IO_CREATE);
+        */
+
+        cpl_test_eq(cpl_mask_get(result_mask,  50,  50), CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(result_mask, 100, 100), CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(result_mask, 150, 150), CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(result_mask, 100, 250), CPL_BINARY_1);
+        cpl_test_eq(cpl_mask_get(result_mask, 122, 122), CPL_BINARY_0);
+
+        cpl_test_eq(cpl_mask_get(result_mask, 110, 260), CPL_BINARY_0);
+
+        /* free the memory */
+        cpl_image_delete(img_data);
+        cpl_mask_delete(img_mask);
+        cpl_image_delete(img_error);
+        cpl_mask_delete(result_mask);
+        hdrl_image_delete(image);
+    }
+
+    /* detect a very big rectangular cosmic  */
+    {
+        img_data = cpl_image_new(150, 200, CPL_TYPE_DOUBLE);
+        img_mask = cpl_mask_new(150, 200);
+        cpl_image_fill_noise_uniform(img_data, 90, 110);
+        double error = (110 - 90) / sqrt(12);
+
+        for (int varx = 50; varx < 75; ++varx) {
+            for (int vary = 60; vary < 130; ++vary) {
+                cpl_image_set(img_data, varx, vary, 5000);
+            }
+        }
+        for (int varx = 20; varx < 120; ++varx) {
+            for (int vary = 20; vary < 40; ++vary) {
+                cpl_image_set(img_data, varx, vary, 5000);
+            }
+        }
+        img_error = cpl_image_new(cpl_image_get_size_x(img_data),
+                                  cpl_image_get_size_y(img_data),
+                                  CPL_TYPE_DOUBLE);
+        cpl_image_add_scalar(img_error, error);
+
+        hdrl_image * image = hdrl_image_create(img_data, img_error);
+        /* In order to detect the full rectangle, f_lim has to be set to a low
+         * value - if not, the central part is not detected */
+        hdrl_parameter * params =
+            hdrl_lacosmic_parameter_create(error * 2, 0.5, 65);
+        result_mask = hdrl_lacosmic_edgedetect(image, params);
+        hdrl_parameter_delete(params) ;
+
+        /*
+        cpl_image_save(data, "input_data.fits", CPL_TYPE_DOUBLE, NULL,
+                       CPL_IO_CREATE);
+        cpl_image_save(data_error, "input_error.fits", CPL_TYPE_DOUBLE, NULL,
+                       CPL_IO_CREATE);
+        cpl_mask_save(data_result, "output_mask.fits", NULL, CPL_IO_CREATE);
+        */
+
+        cpl_test_eq(cpl_mask_count(result_mask), 100*20+25*70);
+        /* free the memory */
+        cpl_image_delete(img_data);
+        cpl_mask_delete(img_mask);
+        cpl_image_delete(img_error);
+        cpl_mask_delete(result_mask);
+        hdrl_image_delete(image);
+    }
+    /* detect a very big rectangular cosmic with bad pixels */
+    {
+        img_data = cpl_image_new(150, 200, CPL_TYPE_DOUBLE);
+        img_mask = cpl_mask_new(150, 200);
+        cpl_image_fill_noise_uniform(img_data, 90, 110);
+        double error = (110 - 90) / sqrt(12);
+
+        for (int varx = 50; varx < 75; ++varx) {
+            for (int vary = 60; vary < 130; ++vary) {
+                cpl_image_set(img_data, varx, vary, 5000);
+            }
+        }
+        for (int varx = 20; varx < 120; ++varx) {
+            for (int vary = 20; vary < 40; ++vary) {
+                cpl_image_set(img_data, varx, vary, 5000);
+            }
+        }
+
+        /*mark bad pixels*/
+        for (int varx = 65; varx < 68; ++varx) {
+            for (int vary = 1; vary < 150; ++vary) {
+                cpl_mask_set(img_mask, varx, vary, CPL_BINARY_1);
+            }
+        }
+        img_error = cpl_image_new(cpl_image_get_size_x(img_data),
+                                  cpl_image_get_size_y(img_data),
+                                  CPL_TYPE_DOUBLE);
+        cpl_image_add_scalar(img_error, error);
+        cpl_image_reject_from_mask(img_data, img_mask);
+
+        hdrl_image * image = hdrl_image_create(img_data, img_error);
+
+        /* In order to detect the full rectangle, f_lim has to be set to a low
+         * value - if not, the central part is not detected */
+        hdrl_parameter * params =
+            hdrl_lacosmic_parameter_create(error * 2, 0.5, 80);
+        result_mask = hdrl_lacosmic_edgedetect(image, params);
+        hdrl_parameter_delete(params) ;
+        /*
+        cpl_image_save(data, "input_data.fits", CPL_TYPE_DOUBLE, NULL,
+                       CPL_IO_CREATE);
+        cpl_image_save(data_error, "input_error.fits", CPL_TYPE_DOUBLE, NULL,
+                       CPL_IO_CREATE);
+        cpl_mask_save(data_bpm, "input_mask.fits", NULL, CPL_IO_CREATE);
+
+        cpl_mask_save(data_result, "output_mask.fits", NULL, CPL_IO_CREATE);
+         */
+
+        cpl_test_eq(cpl_mask_count(result_mask), 100*20 + 25*70 - 3*70 - 3*20);
+        /* free the memory */
+        cpl_image_delete(img_data);
+        cpl_mask_delete(img_mask);
+        cpl_image_delete(img_error);
+        cpl_mask_delete(result_mask);
+        hdrl_image_delete(image);
+    }
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ @brief   Unit tests of Cosmic module
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+    test_lacosmic_bad_input();
+    test_lacosmic_edgedetect();
+    cpl_test_error(CPL_ERROR_NONE);
+    return cpl_test_end(0);
+}
diff --git a/hdrl/tests/hdrl_overscan-test.c b/hdrl/tests/hdrl_overscan-test.c
new file mode 100644
index 0000000..a81f8ea
--- /dev/null
+++ b/hdrl/tests/hdrl_overscan-test.c
@@ -0,0 +1,856 @@
+/* 
+ * This file is part of the HDRL
+ * Copyright (C) 2012,2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl.h"
+#include "hdrl_utils.h"
+#include "hdrl_test.h"
+#include "hdrl_overscan_defs.h"
+
+#include "hdrl_collapse.h" //TMP
+#include <cpl.h>
+
+#include <math.h>
+#include <stdlib.h>
+
+/*-----------------------------------------------------------------------------
+                                Define
+ -----------------------------------------------------------------------------*/
+
+typedef enum {
+    HDRL_OSCAN_COLLAPSE_TEST_MEAN,
+    HDRL_OSCAN_COLLAPSE_TEST_MEDIAN,
+    HDRL_OSCAN_COLLAPSE_TEST_SIGCLIP,
+    HDRL_OSCAN_COLLAPSE_TEST_MINMAX
+} hdrl_oscan_collapse_test ;
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_overscan_test  Testing of the HDRL Overscan module
+ */
+/*----------------------------------------------------------------------------*/
+
+void test_parlist(void)
+{
+    /* parameter parsing smoketest */
+    hdrl_parameter * hpar;
+    hdrl_parameter * rect_region_def =
+        hdrl_rect_region_parameter_create(1, 1, 20, 20);
+    hdrl_parameter * sigclip_def =
+        hdrl_collapse_sigclip_parameter_create(3., 3., 5);
+    hdrl_parameter * minmax_def =
+        hdrl_collapse_minmax_parameter_create(2., 3.);
+    cpl_parameterlist * pos = hdrl_overscan_parameter_create_parlist(
+                "RECIPE", "oscan", "alongX", 10, 10., rect_region_def,
+                "MINMAX", sigclip_def, minmax_def);
+    hdrl_parameter_delete(sigclip_def);
+    hdrl_parameter_delete(minmax_def);
+    hdrl_parameter_delete(rect_region_def);
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_eq(cpl_parameterlist_get_size(pos), 13);
+
+    hpar = hdrl_overscan_parameter_parse_parlist(pos, "RECIPE.invalid");
+    cpl_test_null(hpar);
+    cpl_test_error(CPL_ERROR_DATA_NOT_FOUND);
+
+    hpar = hdrl_overscan_parameter_parse_parlist(pos, "RECIPE.oscan");
+    cpl_parameterlist_delete(pos);
+    cpl_test_error(CPL_ERROR_NONE);
+    {
+        hdrl_parameter * rect = hdrl_overscan_parameter_get_rect_region(hpar);
+        cpl_test_eq(hdrl_rect_region_get_llx(rect), 1);
+        cpl_test_eq(hdrl_rect_region_get_lly(rect), 1);
+        cpl_test_eq(hdrl_rect_region_get_urx(rect), 20);
+        cpl_test_eq(hdrl_rect_region_get_ury(rect), 20);
+    }
+    cpl_test_eq(hdrl_overscan_parameter_get_box_hsize(hpar), 10);
+    cpl_test_eq(hdrl_overscan_parameter_get_ccd_ron(hpar), 10.);
+    cpl_test_eq(hdrl_overscan_parameter_get_correction_direction(hpar),
+                HDRL_X_AXIS);
+    {
+        hdrl_parameter * col = hdrl_overscan_parameter_get_collapse(hpar);
+        cpl_test(hdrl_collapse_parameter_is_minmax(col));
+        cpl_test(!hdrl_collapse_parameter_is_mean(col));
+        cpl_test_eq(hdrl_collapse_minmax_parameter_get_nlow(col), 2);
+        cpl_test_eq(hdrl_collapse_minmax_parameter_get_nhigh(col), 3);
+    }
+
+    hdrl_parameter_destroy(hpar);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check hdrl_overscan_compute proper error on null input images
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_overscan_test_null_input(void)
+{
+    hdrl_parameter                  *   os_region = NULL;
+    hdrl_parameter                  *   os_collapse = NULL;
+    hdrl_parameter                  *   os_param = NULL;
+    hdrl_overscan_compute_result    *   overscan_computation = NULL;
+
+    /* Overscan Parameters */
+    os_region = hdrl_rect_region_parameter_create(1, 1, 1, 1) ;
+    os_collapse = hdrl_collapse_mean_parameter_create() ;
+    os_param = hdrl_overscan_parameter_create(HDRL_Y_AXIS, 1., 1, 
+            os_collapse, os_region) ;
+
+    /* test functionality */
+    overscan_computation = hdrl_overscan_compute(NULL, os_param) ;
+    hdrl_parameter_delete(os_region) ;
+    hdrl_parameter_delete(os_collapse) ;
+    hdrl_parameter_delete(os_param) ;
+
+    cpl_test_null(overscan_computation);
+
+    hdrl_overscan_compute_result_delete(overscan_computation);
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check hdrl_overscan_compute proper error on null input region
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_overscan_test_null_region(void)
+{
+    cpl_image                       *   image_data = NULL;
+    hdrl_parameter                  *   os_region = NULL;
+    hdrl_parameter                  *   os_collapse = NULL;
+    hdrl_parameter                  *   os_param = NULL;
+    hdrl_overscan_compute_result    *   overscan_computation = NULL;
+
+    /* create input structures (on purpose not the input region) */
+    image_data = cpl_image_new(1, 1, CPL_TYPE_DOUBLE);
+
+    /* Overscan Parameters */
+    os_collapse = hdrl_collapse_mean_parameter_create() ;
+    os_param = hdrl_overscan_parameter_create(HDRL_Y_AXIS, 1., 1, 
+            os_collapse, os_region) ;
+
+    /* test functionality */
+    overscan_computation = hdrl_overscan_compute(image_data, os_param);
+    cpl_image_delete(image_data);
+    hdrl_parameter_delete(os_collapse) ;
+    hdrl_parameter_delete(os_param) ;
+    cpl_test_null(overscan_computation);
+
+    hdrl_overscan_compute_result_delete(overscan_computation);
+
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check hdrl_overscan_compute proper error on null input sigclip
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_overscan_test_null_sigclip(void)
+{
+    cpl_image                       *   image_data = NULL;
+    hdrl_parameter                  *   os_region = NULL;
+    hdrl_parameter                  *   os_collapse = NULL;
+    hdrl_parameter                  *   os_param = NULL;
+    hdrl_overscan_compute_result    *   overscan_computation = NULL;
+
+    /* create input structures (on purpose not the input region) */
+    image_data = cpl_image_new(1, 1, CPL_TYPE_DOUBLE);
+
+    /* Overscan Parameters */
+    os_region = hdrl_rect_region_parameter_create(1, 1, 1, 1) ;
+    os_param = hdrl_overscan_parameter_create(HDRL_Y_AXIS, 1., 1, 
+            os_collapse, os_region) ;
+
+    /* test functionality */
+    overscan_computation = hdrl_overscan_compute(image_data, os_param);
+    cpl_image_delete(image_data);
+    hdrl_parameter_delete(os_region) ;
+    hdrl_parameter_delete(os_param) ;
+    cpl_test_null(overscan_computation);
+
+    hdrl_overscan_compute_result_delete(overscan_computation);
+
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check hdrl_overscan_compute proper error on null input compute control
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_overscan_test_null_params(void)
+{
+    cpl_image* image_data = cpl_image_new(1, 1, CPL_TYPE_DOUBLE);
+    hdrl_overscan_compute_result * overscan_computation = NULL;
+
+    /* test functionality */
+    overscan_computation = hdrl_overscan_compute(image_data, NULL);
+    cpl_test_null(overscan_computation);
+
+    hdrl_overscan_compute_result_delete(overscan_computation);
+    cpl_image_delete(image_data);
+
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check hdrl_overscan_compute proper error on wrong input region
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_overscan_test_wrong_region(void)
+{
+    hdrl_parameter                  *   os_region = NULL;
+    hdrl_parameter                  *   os_collapse = NULL;
+    hdrl_parameter                  *   os_param = NULL;
+    cpl_image                       *   image_data = NULL;
+    hdrl_overscan_compute_result    *   computation = NULL;
+
+    /* create input image  */
+    image_data = cpl_image_new(5, 10, CPL_TYPE_DOUBLE);
+
+    /* Overscan Parameters */
+    /* Initialize a region outside the bounds of the image */
+    os_region = hdrl_rect_region_parameter_create(1, 1, 5, 10) ;
+    os_collapse = hdrl_collapse_mean_parameter_create() ;
+    os_param = hdrl_overscan_parameter_create(HDRL_Y_AXIS, 1., 1, 
+            os_collapse, os_region) ;
+
+    /* Run it and check */
+    hdrl_rect_region_parameter_update(os_region, 0, 2, 4, 2) ;
+
+    computation = hdrl_overscan_compute(image_data, os_param) ;
+    cpl_test_null(computation);
+    cpl_test_eq_error(cpl_error_get_code(), CPL_ERROR_ILLEGAL_INPUT);
+        
+    /* Initialize a region with size exceeding the X size of the image */
+    hdrl_rect_region_parameter_update(os_region, 1, 5, 6, 10) ;
+
+    // TODO yves fix and reenable
+    //computation = hdrl_overscan_compute(image_data, os_param) ;
+    //cpl_test_null(computation);
+    //cpl_test_eq_error(cpl_error_get_code(), CPL_ERROR_ILLEGAL_INPUT);
+    
+    /* Destroy and return */
+    hdrl_parameter_delete(os_region) ;
+    hdrl_parameter_delete(os_collapse) ;
+    hdrl_parameter_delete(os_param) ;
+    cpl_image_delete(image_data);
+
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check hdrl_overscan_compute proper error on wrong input region
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static double hdrl_overscan_test_uniform_image(const double inp_value)
+{
+    double                              out_value = 0;
+    cpl_image                       *   image_data = NULL;
+    cpl_image                       *   image_errs = NULL;
+    hdrl_image                      *   image;
+    hdrl_overscan_compute_result    *   comp_res = NULL;
+    hdrl_overscan_correct_result    *   overscan_correction = NULL;
+    hdrl_parameter                  *   os_region = NULL;
+    hdrl_parameter                  *   os_collapse = NULL;
+    hdrl_parameter                  *   os_param = NULL;
+
+    /* Create input structures (on purpose not the input region) */
+    image_data = cpl_image_new(100, 100, HDRL_TYPE_DATA);
+    cpl_image_add_scalar(image_data, inp_value);
+    image_errs = cpl_image_new(100, 100, HDRL_TYPE_ERROR);
+    cpl_image_add_scalar(image_errs, inp_value);
+    cpl_image_power(image_errs, 0.5);
+    image = hdrl_image_wrap(image_data, image_errs, NULL, CPL_FALSE);
+
+    /* Overscan Parameters */
+    os_region = hdrl_rect_region_parameter_create(1, 1, 100, 100) ;
+    os_collapse = hdrl_collapse_median_parameter_create() ;
+    os_param = hdrl_overscan_parameter_create(HDRL_Y_AXIS, 1., 5, 
+            os_collapse, os_region) ;
+
+    /* Compute the Overscan correction */
+    comp_res = hdrl_overscan_compute(image_data, os_param);
+    cpl_test_nonnull(comp_res);
+
+    hdrl_parameter_delete(os_region) ;
+    hdrl_parameter_delete(os_collapse) ;
+    hdrl_parameter_delete(os_param) ;
+    
+    out_value = cpl_image_get_mean(
+                           hdrl_image_get_image(comp_res->correction));
+    cpl_test_abs(out_value, inp_value, HDRL_EPS_DATA);
+
+    overscan_correction = hdrl_overscan_correct(image, NULL, comp_res);
+    cpl_test_nonnull(overscan_correction);
+
+    hdrl_overscan_compute_result_delete(comp_res);
+    hdrl_overscan_correct_result_delete(overscan_correction);
+    hdrl_image_delete(image);
+    return out_value;
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check overscan directions and shrinking window
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_overscan_test_dir(cpl_size Nx, cpl_size Ny, int hbox)
+{
+    const double                        error = 10;
+    hdrl_image * image = hdrl_image_new(Nx, Ny);
+    cpl_image * image_data = hdrl_image_get_image(image);
+    cpl_image * image_errs = hdrl_image_get_error(image);
+    hdrl_parameter                  *   os_region = NULL;
+    hdrl_parameter                  *   os_collapse = NULL;
+    hdrl_parameter                  *   os_param = NULL;
+    hdrl_overscan_compute_result    *   res_os_comp = NULL;
+    hdrl_overscan_compute_result    *   res_os_comp_turn = NULL;
+    hdrl_overscan_correct_result    *   res_os_cor = NULL;
+    hdrl_overscan_correct_result    *   res_os_cor_turn = NULL;
+    int                                 rej;
+
+    cpl_msg_info(cpl_func, "check mean hbox %d, Nx %ld, Ny %ld",
+                 hbox, (long)Nx, (long)Ny);
+
+    /* create image incrementing in x axis, constant in y axis */
+    for (cpl_size x = 0; x < Nx; x++) {
+        for (cpl_size y = 0; y < Ny; y++) {
+            cpl_image_set(image_data, x + 1, y + 1, x);
+            cpl_image_set(image_errs, x + 1, y + 1, x);
+        }
+    }
+    cpl_image_power(image_errs, 0.5);
+
+    /* Overscan Parameters */
+    os_region = hdrl_rect_region_parameter_create(1, 1, Nx, Ny) ;
+    os_collapse = hdrl_collapse_mean_parameter_create() ;
+    os_param = hdrl_overscan_parameter_create(HDRL_Y_AXIS,
+            error * sqrt(Ny * (1 + 2 * hbox)), hbox, os_collapse, os_region) ;
+
+    /* test compute y direction */
+    res_os_comp = hdrl_overscan_compute(image_data, os_param);
+    cpl_test_error(CPL_ERROR_NONE);
+
+    {
+        /* in y direction overscan has same incremental pattern as input */
+        cpl_image * ex = cpl_image_extract(image_data, 1, 1, Nx, 1);
+        /* cpl mean implementation has a rather large error */
+        cpl_test_image_abs(ex, hdrl_image_get_image(res_os_comp->correction),
+                           2 * (1 + 2 * hbox) * Ny * HDRL_EPS_DATA);
+
+        /* perfect match => zero chi2 = 0*/
+        if (hbox == 0) {
+            cpl_image_subtract(ex, ex);
+            cpl_test_image_abs(ex, res_os_comp->red_chi2,
+                               2 * (1 + 2 * hbox) * Ny * HDRL_EPS_DATA);
+        }
+
+        /* error constant in middle */
+        cpl_image_subtract(ex, ex);
+        cpl_image_add_scalar(ex, error);
+        /* error larger on boundary */
+        for (int i = 0; i < hbox; i++) {
+            double cor = sqrt((1 + 2. * (hbox)) / (1 + 2 * i));
+            cpl_image_set(ex, 1 + i, 1, error * cor);
+            cpl_image_set(ex, Nx - i, 1, error * cor);
+        }
+        cpl_test_image_abs(ex, hdrl_image_get_error(res_os_comp->correction),
+                           Ny * HDRL_EPS_ERROR);
+
+        cpl_image_delete(ex);
+    }
+
+    /* test compute x direction */
+
+    hdrl_parameter_delete(os_param) ;
+    os_param = hdrl_overscan_parameter_create(HDRL_X_AXIS,
+            error * sqrt(Nx * (1 + 2 * hbox)), hbox, os_collapse, os_region) ;
+    res_os_comp_turn = hdrl_overscan_compute(image_data, os_param);
+
+    hdrl_parameter_delete(os_region) ;
+    hdrl_parameter_delete(os_collapse) ;
+    hdrl_parameter_delete(os_param) ;
+
+    cpl_test_error(CPL_ERROR_NONE);
+
+    {
+        /* in x direction overscan is the mean of the sum */
+        cpl_image * ex = cpl_image_new(1, Ny, HDRL_TYPE_DATA);
+        cpl_image_add_scalar(ex, (Nx - 1.) / 2.);
+        cpl_test_image_abs(ex,
+                           hdrl_image_get_image(res_os_comp_turn->correction),
+                           2 * (1 + 2 * hbox) * Nx * HDRL_EPS_DATA);
+
+        /* reduced chi2 so it should be constant with this pattern */
+        cpl_image_subtract(ex, ex);
+        cpl_image_add_scalar(ex, cpl_image_get(res_os_comp_turn->red_chi2,
+                                                1, 1, &rej));
+        cpl_test_image_abs(ex, res_os_comp_turn->red_chi2,
+                           2 * (1 + 2 * hbox) * Nx * HDRL_EPS_DATA);
+
+        /* error constant in middle */
+        cpl_image_subtract(ex, ex);
+        cpl_image_add_scalar(ex, error);
+        /* error larger on boundary */
+        for (int i = 0; i < hbox; i++) {
+            double cor = sqrt((1 + 2. * (hbox)) / (1 + 2 * i));
+            cpl_image_set(ex, 1, 1 + i, error * cor);
+            cpl_image_set(ex, 1, Ny - i, error * cor);
+        }
+        cpl_test_image_abs(ex,
+                           hdrl_image_get_error(res_os_comp_turn->correction),
+                           3 * Nx * HDRL_EPS_ERROR);
+
+        cpl_image_delete(ex);
+    }
+
+
+    /* test correct y direction */
+    res_os_cor = hdrl_overscan_correct(image, NULL, res_os_comp);
+    cpl_test_error(CPL_ERROR_NONE);
+
+    {
+        /* corrected y direction is just a zero image */
+        cpl_image * ex = cpl_image_new(Nx, Ny, HDRL_TYPE_DATA);
+
+        cpl_test_image_abs(ex, hdrl_image_get_image(res_os_cor->corrected),
+                           2 * (1 + 2 * hbox) * Ny * HDRL_EPS_DATA);
+
+        /* gaussian error */
+        for (cpl_size y = 0; y < Ny; y++) {
+            for (cpl_size x = 0; x < Nx; x++) {
+                double val = cpl_image_get(image_errs, x + 1, y + 1, &rej);
+                cpl_image_set(ex, x + 1, y + 1, hypot(error, val));
+            }
+            /* larger on boundaries */
+            for (int i = 0; i < hbox; i++) {
+                double cor = sqrt((1 + 2. * (hbox)) / (1 + 2 * i));
+                double val = cpl_image_get(image_errs, 1 + i, y + 1, &rej);
+                cpl_image_set(ex, 1 + i, y + 1, hypot(error * cor, val));
+                val = cpl_image_get(image_errs, Nx - i, y + 1, &rej);
+                cpl_image_set(ex, Nx - i, y + 1, hypot(error * cor, val));
+            }
+        }
+
+        cpl_test_image_abs(ex, hdrl_image_get_error(res_os_cor->corrected),
+                           Ny * HDRL_EPS_ERROR);
+
+        cpl_image_delete(ex);
+    }
+
+    res_os_cor_turn = hdrl_overscan_correct(image, NULL, res_os_comp_turn);
+    cpl_test_error(CPL_ERROR_NONE);
+
+    {
+        /* overscan in x direction constant over whole axis */
+        cpl_image * ex = cpl_image_duplicate(image_data);
+        cpl_image_subtract_scalar(ex,
+                hdrl_image_get_pixel(res_os_comp_turn->correction, 1, 1,
+                                     &rej).data);
+        cpl_test_image_abs(ex, hdrl_image_get_image(res_os_cor_turn->corrected),
+                2 * (1 + 2 * hbox) * Nx * HDRL_EPS_DATA);
+
+        /* gaussian error */
+        for (cpl_size x = 0; x < Nx; x++) {
+            for (cpl_size y = 0; y < Ny; y++) {
+                double val = cpl_image_get(image_errs, x + 1, y + 1, &rej);
+                cpl_image_set(ex, x + 1, y + 1, hypot(error, val));
+            }
+            /* larger on boundaries */
+            for (int i = 0; i < hbox; i++) {
+                double cor = sqrt((1 + 2. * (hbox)) / (1 + 2 * i));
+                double val = cpl_image_get(image_errs, 1 + x, 1 + i, &rej);
+                cpl_image_set(ex, x + 1, 1 + i, hypot(error * cor, val));
+                val = cpl_image_get(image_errs, x + 1, Ny - i, &rej);
+                cpl_image_set(ex, x + 1, Ny - i, hypot(error * cor, val));
+            }
+        }
+
+        cpl_test_image_abs(ex,
+                           hdrl_image_get_error(res_os_cor_turn->corrected),
+                           3 * Nx * HDRL_EPS_ERROR);
+
+        cpl_image_delete(ex);
+    }
+
+    hdrl_overscan_compute_result_delete(res_os_comp);
+    hdrl_overscan_compute_result_delete(res_os_comp_turn);
+    hdrl_overscan_correct_result_delete(res_os_cor);
+    hdrl_overscan_correct_result_delete(res_os_cor_turn);
+    hdrl_image_delete(image);
+
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check single pixel overscan
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_overscan_test_full_hbox(
+        cpl_size                    Nx, 
+        cpl_size                    Ny)
+{
+    const double                        error = 10;
+    hdrl_image * image = hdrl_image_new(Nx, Ny);
+    cpl_image * image_data = hdrl_image_get_image(image);
+    cpl_image * image_errs = hdrl_image_get_error(image);
+    hdrl_parameter                  *   os_region = NULL;
+    hdrl_parameter                  *   os_collapse = NULL;
+    hdrl_parameter                  *   os_param = NULL;
+    hdrl_overscan_compute_result    *   res_os_comp = NULL;
+    hdrl_overscan_correct_result    *   res_os_cor = NULL;
+
+    /* sets overscan to use full region and emit single pixel value */
+    cpl_msg_info(cpl_func, "check mean full box, Nx %ld, Ny %ld",
+                 (long)Nx, (long)Ny);
+
+    /* create image incrementing in x axis, constant in y axis */
+    for (cpl_size x = 0; x < Nx; x++) {
+        for (cpl_size y = 0; y < Ny; y++) {
+            cpl_image_set(image_data, x + 1, y + 1, x);
+            cpl_image_set(image_errs, x + 1, y + 1, x);
+        }
+    }
+    cpl_image_power(image_errs, 0.5);
+
+    /* Overscan Parameters */
+    os_region = hdrl_rect_region_parameter_create(1, 1, Nx, Ny) ;
+    os_collapse = hdrl_collapse_mean_parameter_create() ;
+    /* invalid boxsize */
+    os_param = hdrl_overscan_parameter_create(HDRL_Y_AXIS,
+            error * sqrt(Nx * Ny), -2, os_collapse, os_region) ;
+
+    res_os_comp = hdrl_overscan_compute(image_data, os_param);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    /* test compute y direction */
+    hdrl_parameter_delete(os_param) ;
+    os_param = hdrl_overscan_parameter_create(HDRL_Y_AXIS,
+            error * sqrt(Nx * Ny), HDRL_OVERSCAN_FULL_BOX, 
+            os_collapse, os_region) ;
+    res_os_comp = hdrl_overscan_compute(image_data, os_param);
+
+    hdrl_parameter_delete(os_region) ;
+    hdrl_parameter_delete(os_collapse) ;
+    hdrl_parameter_delete(os_param) ;
+
+    cpl_test_error(CPL_ERROR_NONE);
+
+    {
+        /* we expect a row with all the same overscan value */
+        hdrl_image * ex = hdrl_image_new(Nx, 1);
+        hdrl_image_add_scalar(ex, (hdrl_value){(Nx - 1.) / 2., error});
+        /* cpl mean implementation has a rather large error */
+        hdrl_test_image_abs(ex, res_os_comp->correction,
+                            2 * Nx * Ny * HDRL_EPS_DATA);
+
+        hdrl_test_image_abs(ex, res_os_comp->correction,
+                           Nx * Ny * HDRL_EPS_DATA);
+
+        hdrl_image_delete(ex);
+    }
+
+    hdrl_overscan_compute_result_delete(res_os_comp);
+    hdrl_overscan_correct_result_delete(res_os_cor);
+    hdrl_image_delete(image);
+
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check result of turned image when changing direction
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_overscan_test_turn_eq(
+        cpl_size                    Nx, 
+        cpl_size                    Ny, 
+        int                         hbox,
+        hdrl_oscan_collapse_test    method)
+{
+    const double                        error = 10;
+    hdrl_image * image = hdrl_image_new(Nx, Ny);
+    hdrl_image * image_t;
+    cpl_image * image_data = hdrl_image_get_image(image);
+    cpl_image * image_errs = hdrl_image_get_error(image);
+    hdrl_parameter                  *   os_region = NULL;
+    hdrl_parameter                  *   os_collapse = NULL;
+    hdrl_parameter                  *   os_param = NULL;
+    hdrl_overscan_compute_result    *   res_os_comp = NULL;
+    hdrl_overscan_compute_result    *   res_os_comp_turn = NULL;
+    hdrl_overscan_correct_result    *   res_os_cor = NULL;
+    hdrl_overscan_correct_result    *   res_os_cor_turn = NULL;
+
+    for (cpl_size x = 0; x < Nx; x++) {
+        for (cpl_size y = 0; y < Ny; y++) {
+            /* small range due to missing cpl_test_img_rel */
+            double v = (50 - rand() % 100) / (double)((rand() % 50) + 1);
+            cpl_image_set(image_data, x + 1, y + 1, v);
+            cpl_image_set(image_errs, x + 1, y + 1, fabs(v));
+        }
+    }
+    cpl_image_power(image_errs, 0.5);
+    image_t = hdrl_image_duplicate(image);
+    hdrl_image_turn(image_t, +1);
+    
+    if (method == HDRL_OSCAN_COLLAPSE_TEST_MEAN) {
+        cpl_msg_info(cpl_func, "Mean method hbox %d, Nx %ld, Ny %ld",
+                     hbox, (long)Nx, (long)Ny);
+        os_collapse = hdrl_collapse_mean_parameter_create() ;
+    } else if (method == HDRL_OSCAN_COLLAPSE_TEST_MEDIAN) {
+        cpl_msg_info(cpl_func, "Median method hbox %d, Nx %ld, Ny %ld",
+                     hbox, (long)Nx, (long)Ny);
+        os_collapse = hdrl_collapse_median_parameter_create() ;
+
+    } else if (method == HDRL_OSCAN_COLLAPSE_TEST_SIGCLIP) {
+        cpl_msg_info(cpl_func, "Sigma-Clipping method hbox %d, Nx %ld, Ny %ld",
+                     hbox, (long)Nx, (long)Ny);
+        os_collapse = hdrl_collapse_sigclip_parameter_create(3.,3.,3) ;
+    } else if (method == HDRL_OSCAN_COLLAPSE_TEST_MINMAX) {
+        cpl_msg_info(cpl_func, "MinMax method hbox %d, Nx %ld, Ny %ld",
+                     hbox, (long)Nx, (long)Ny);
+        os_collapse = hdrl_collapse_minmax_parameter_create(3, 3);
+    }
+
+    /* Overscan Parameters */
+    os_region = hdrl_rect_region_parameter_create(1, 1, Nx, Ny) ;
+    os_param = hdrl_overscan_parameter_create(HDRL_Y_AXIS,
+            error * sqrt(Ny * (1 + 2 * hbox)), hbox, os_collapse, os_region) ;
+
+    /* test compute y direction */
+    res_os_comp = hdrl_overscan_compute(image_data, os_param);
+    cpl_test_error(CPL_ERROR_NONE);
+
+    /* test compute x direction */
+    hdrl_rect_region_parameter_update(os_region, 1, 1, Ny, Nx) ;
+    hdrl_parameter_delete(os_param) ;
+    os_param = hdrl_overscan_parameter_create(HDRL_X_AXIS,
+            error * sqrt(Ny * (1 + 2 * hbox)), hbox, os_collapse, os_region) ;
+    res_os_comp_turn = hdrl_overscan_compute(hdrl_image_get_image(image_t),
+                                             os_param);
+    cpl_test_error(CPL_ERROR_NONE);
+
+    hdrl_parameter_delete(os_region) ;
+    hdrl_parameter_delete(os_collapse) ;
+    hdrl_parameter_delete(os_param) ;
+
+    {
+        hdrl_image * cor_t = hdrl_image_duplicate(res_os_comp_turn->correction);
+        cpl_image * con_t = cpl_image_duplicate(res_os_comp_turn->contribution);
+        cpl_image * chi_t = cpl_image_duplicate(res_os_comp_turn->red_chi2);
+        hdrl_image_turn(cor_t, -1);
+        cpl_image_turn(con_t, -1);
+        cpl_image_turn(chi_t, -1);
+        hdrl_test_image_abs(res_os_comp->correction,
+                            cor_t, (1 + hbox) * Ny * HDRL_EPS_DATA);
+        cpl_test_image_abs(res_os_comp->red_chi2, chi_t,
+                           (1 + hbox) * Ny * HDRL_EPS_DATA);
+        cpl_test_image_abs(res_os_comp->contribution, con_t, 0);
+        hdrl_image_delete(cor_t);
+        cpl_image_delete(con_t);
+        cpl_image_delete(chi_t);
+    }
+
+    /* test correct y direction */
+    res_os_cor = hdrl_overscan_correct(image, NULL, res_os_comp);
+    cpl_test_error(CPL_ERROR_NONE);
+
+    res_os_cor_turn = hdrl_overscan_correct(image_t, NULL, res_os_comp_turn);
+    cpl_test_error(CPL_ERROR_NONE);
+
+    hdrl_image_turn(res_os_cor_turn->corrected, -1);
+    hdrl_test_image_abs(res_os_cor->corrected, res_os_cor_turn->corrected,
+                       (1 + hbox) * Ny * HDRL_EPS_DATA);
+
+    hdrl_overscan_compute_result_delete(res_os_comp);
+    hdrl_overscan_compute_result_delete(res_os_comp_turn);
+    hdrl_overscan_correct_result_delete(res_os_cor);
+    hdrl_overscan_correct_result_delete(res_os_cor_turn);
+    hdrl_image_delete(image);
+    hdrl_image_delete(image_t);
+
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check case where a overscan box only contains bad pixels
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_overscan_test_empty_box(
+        hdrl_oscan_collapse_test    method)
+{
+    cpl_size                            Nx = 10 ;
+    cpl_size                            Ny = 10;
+    cpl_image * image_data = cpl_image_new(Nx, Ny, HDRL_TYPE_DATA);
+    cpl_image * image_errs = cpl_image_new(Nx, Ny, HDRL_TYPE_ERROR);
+    hdrl_parameter                  *   os_region = NULL;
+    hdrl_parameter                  *   os_collapse = NULL;
+    hdrl_parameter                  *   os_param = NULL;
+    hdrl_overscan_compute_result    *   res_os_comp = NULL;
+
+
+    /* Overscan Parameters */
+    if (method == HDRL_OSCAN_COLLAPSE_TEST_MEAN) {
+        cpl_msg_info(cpl_func, "check empty box MEAN");
+        os_collapse = hdrl_collapse_mean_parameter_create() ;
+    } else if (method == HDRL_OSCAN_COLLAPSE_TEST_MEDIAN) {
+        cpl_msg_info(cpl_func, "check empty box MEDIAN");
+        os_collapse = hdrl_collapse_median_parameter_create() ;
+    } else if (method == HDRL_OSCAN_COLLAPSE_TEST_SIGCLIP) {
+        cpl_msg_info(cpl_func, "check empty box SIGCLIP");
+        os_collapse = hdrl_collapse_sigclip_parameter_create(3.,3.,3) ;
+    } else if (method == HDRL_OSCAN_COLLAPSE_TEST_MINMAX) {
+        cpl_msg_info(cpl_func, "check empty box MINMAX");
+        os_collapse = hdrl_collapse_minmax_parameter_create(3, 3);
+    }
+    os_region = hdrl_rect_region_parameter_create(1, 1, Nx, Ny) ;
+    os_param = hdrl_overscan_parameter_create(HDRL_Y_AXIS, 1., 0, 
+            os_collapse, os_region) ;
+
+    /* reject one row (= one box */
+    for (cpl_size i = 0; i < Ny; i++) cpl_image_reject(image_data, 2, i + 1);
+
+    /* test compute y direction */
+    res_os_comp = hdrl_overscan_compute(image_data, os_param);
+    
+    hdrl_parameter_delete(os_region) ;
+    hdrl_parameter_delete(os_collapse) ;
+    hdrl_parameter_delete(os_param) ;
+    
+    cpl_test_error(CPL_ERROR_NONE);
+
+    /* expecting bad pixels in the bad box */
+    {
+        int rej;
+        cpl_test_eq(cpl_image_get(res_os_comp->contribution, 2, 1, &rej), 0);
+        cpl_test(hdrl_image_is_rejected(res_os_comp->correction, 2, 1));
+        cpl_test(cpl_image_is_rejected(res_os_comp->red_chi2, 2, 1));
+        if (res_os_comp->sigclip_reject_low) {
+            cpl_test(cpl_image_is_rejected(res_os_comp->sigclip_reject_low,
+                                           2, 1));
+            cpl_test(cpl_image_is_rejected(res_os_comp->sigclip_reject_high,
+                                           2, 1));
+        }
+    }
+
+    hdrl_overscan_compute_result_delete(res_os_comp);
+    cpl_image_delete(image_data);
+    cpl_image_delete(image_errs);
+
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief   Unit tests of overscan functions module
+ */
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+    cpl_error_code code;
+    double inp_value = 0;
+
+    /* parameter parsing tests */
+    test_parlist();
+
+    /* Overscan with NULL input images */
+    code = hdrl_overscan_test_null_input();
+    cpl_test_eq_error(code, CPL_ERROR_NULL_INPUT);
+
+    /* Overscan with NULL region */
+    code = hdrl_overscan_test_null_region();
+    cpl_test_eq_error(code, CPL_ERROR_ILLEGAL_INPUT);
+
+    /* Overscan with NULL sigclip */
+    code = hdrl_overscan_test_null_sigclip();
+    cpl_test_eq_error(code, CPL_ERROR_ILLEGAL_INPUT);
+
+    /* Overscan with NULL control */
+    code = hdrl_overscan_test_null_params();
+    cpl_test_eq_error(code, CPL_ERROR_NULL_INPUT);
+
+    /* Overscan with wrong region */
+    code = hdrl_overscan_test_wrong_region();
+    cpl_test_eq_error(code, CPL_ERROR_NONE);
+
+    /* Check expected results with uniform frame */
+    hdrl_overscan_test_uniform_image(inp_value);
+    
+    cpl_size anx[] = {97,  45, 200};
+    cpl_size any[] = {575, 34, 200};
+
+    for (size_t i = 0; i < sizeof(anx) / sizeof(anx[0]); i++) {
+        cpl_size nx = anx[i];
+        cpl_size ny = any[i];
+
+        for (int hbox = 0; hbox < 12; hbox++) {
+            hdrl_overscan_test_dir(nx, ny, hbox);
+        }
+
+        for (int hbox = 0; hbox < 6; hbox+=2) {
+            hdrl_overscan_test_turn_eq(nx, ny, hbox,
+                    HDRL_OSCAN_COLLAPSE_TEST_MEAN);
+            hdrl_overscan_test_turn_eq(nx, ny, hbox,
+                    HDRL_OSCAN_COLLAPSE_TEST_MEDIAN);
+            hdrl_overscan_test_turn_eq(nx, ny, hbox,
+                    HDRL_OSCAN_COLLAPSE_TEST_SIGCLIP);
+            hdrl_overscan_test_turn_eq(nx, ny, hbox,
+                    HDRL_OSCAN_COLLAPSE_TEST_MINMAX);
+        }
+
+        hdrl_overscan_test_full_hbox(nx, ny);
+    }
+
+    hdrl_overscan_test_empty_box(HDRL_OSCAN_COLLAPSE_TEST_MEAN);
+    hdrl_overscan_test_empty_box(HDRL_OSCAN_COLLAPSE_TEST_MEDIAN);
+    hdrl_overscan_test_empty_box(HDRL_OSCAN_COLLAPSE_TEST_SIGCLIP);
+    hdrl_overscan_test_empty_box(HDRL_OSCAN_COLLAPSE_TEST_MINMAX);
+
+    /** \todo Test expected results with uniform frame + spikes */
+    //cpl_test(hdrl_overscan_test_uniform_image_and_outliers(),value);
+
+    /** \todo Test expected results with uniform frame + noise */
+    //cpl_test(hdrl_overscan_test_uniform_image_and_noise(),value);
+
+    return cpl_test_end(0);
+}
diff --git a/hdrl/tests/hdrl_parameter-test.c b/hdrl/tests/hdrl_parameter-test.c
new file mode 100644
index 0000000..8e81e11
--- /dev/null
+++ b/hdrl/tests/hdrl_parameter-test.c
@@ -0,0 +1,192 @@
+/* $Id: hdrl_parameter-test.c,v 1.1 2013-10-01 13:26:32 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-01 13:26:32 $
+ * $Revision: 1.1 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_parameter.h"
+#include <cpl.h>
+
+#include <assert.h>
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_parameter-test   Testing of the HDRL parameter
+ */
+/*----------------------------------------------------------------------------*/
+
+
+/* define sigma clipping parameter object */
+typedef struct {
+    HDRL_PARAMETER_HEAD;
+    double kappa_low;
+    double kappa_high;
+    int niter;
+} hdrl_parameter_sigclip;
+
+/* define type metadata */
+static hdrl_parameter_typeobj hdrl_parameter_sigclip_type = {
+    HDRL_PARAMETER_COLLAPSE_SIGCLIP,/* type */
+    (hdrl_alloc *)&cpl_malloc,      /* fp_alloc */
+    (hdrl_free *)&cpl_free,         /* fp_free */
+    NULL,                           /* fp_destroy */
+    sizeof(hdrl_parameter_sigclip), /* obj_size */
+};
+
+/* define initializing constructor */
+hdrl_parameter * hdrl_parameter_sigclip_create(double kappa, int niter)
+{
+    hdrl_parameter_sigclip * p = (hdrl_parameter_sigclip *)
+       hdrl_parameter_new(&hdrl_parameter_sigclip_type);
+    p->kappa_low = kappa;
+    p->kappa_high = kappa;
+    p->niter = niter;
+    return (hdrl_parameter *)p;
+}
+
+int hdrl_parameter_is_sigclip(hdrl_parameter * self)
+{
+    return hdrl_parameter_check_type(self, &hdrl_parameter_sigclip_type);
+}
+
+/* public */
+double hdrl_parameter_sigclip_get_kappa(hdrl_parameter * p)
+{
+    assert(hdrl_parameter_is_sigclip(p));
+
+    hdrl_parameter_sigclip * sp = (hdrl_parameter_sigclip *)p;
+    return sp->kappa_low;
+}
+
+
+
+typedef struct {
+    HDRL_PARAMETER_HEAD;
+    int hbox_size;
+    hdrl_parameter * collapse;
+} hdrl_parameter_overscan;
+
+void hdrl_parameter_overscan_destroy(hdrl_parameter *);
+
+static hdrl_parameter_typeobj hdrl_parameter_overscan_type = {
+    HDRL_PARAMETER_OVERSCAN,                       /* type */
+    (hdrl_alloc *)&cpl_malloc,                     /* fp_alloc */
+    (hdrl_free *)&cpl_free,                        /* fp_free */
+    (hdrl_free *)&hdrl_parameter_overscan_destroy, /* fp_destroy */
+    sizeof(hdrl_parameter_overscan),               /* obj_size */
+};
+
+hdrl_parameter *
+hdrl_parameter_overscan_create(int hbox_size, hdrl_parameter * collapse)
+{
+    hdrl_parameter_overscan * p =
+        (hdrl_parameter_overscan *)hdrl_parameter_new(&hdrl_parameter_overscan_type);
+    p->hbox_size = hbox_size;
+    p->collapse = collapse;
+    return (hdrl_parameter *)p;
+}
+
+int hdrl_parameter_is_overscan(hdrl_parameter * p)
+{
+    return hdrl_parameter_check_type(p, &hdrl_parameter_overscan_type);
+}
+
+void hdrl_parameter_overscan_destroy(hdrl_parameter * p)
+{
+    assert(hdrl_parameter_is_overscan(p));
+    hdrl_parameter_destroy(((hdrl_parameter_overscan*)p)->collapse);
+    hdrl_parameter_get_type(p)->fp_free(p);
+}
+
+double hdrl_parameter_overscan_get_hbox_size(hdrl_parameter * p)
+{
+    assert(hdrl_parameter_is_overscan(p));
+
+    hdrl_parameter_overscan * sp = (hdrl_parameter_overscan *)p;
+    return sp->hbox_size;
+}
+
+hdrl_parameter * hdrl_parameter_overscan_get_collapse(hdrl_parameter * p)
+{
+    assert(hdrl_parameter_is_overscan(p));
+
+    hdrl_parameter_overscan * sp = (hdrl_parameter_overscan *)p;
+    return sp->collapse;
+}
+
+void test_parameters(hdrl_parameter * p)
+{
+    hdrl_parameter * collapse = hdrl_parameter_overscan_get_collapse(p);
+    cpl_test_error(CPL_ERROR_NONE);
+    cpl_test_nonnull(collapse);
+
+    cpl_test(hdrl_parameter_is_sigclip(collapse));
+    cpl_test(!hdrl_parameter_is_overscan(collapse));
+
+    cpl_test(!hdrl_parameter_is_sigclip(p));
+    cpl_test(hdrl_parameter_is_overscan(p));
+
+    cpl_test_eq(0, hdrl_parameter_overscan_get_hbox_size(p));
+
+    cpl_test_eq(2, hdrl_parameter_sigclip_get_kappa(collapse));
+    cpl_test_eq(2, ((hdrl_parameter_sigclip*)collapse)->kappa_low);
+}
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ @brief   Unit tests of parameter module
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+
+    hdrl_parameter * collapse = hdrl_parameter_sigclip_create(2, 3);
+    hdrl_parameter * osp = hdrl_parameter_overscan_create(0, collapse);
+    test_parameters(osp);
+    hdrl_parameter_destroy(osp);
+
+    collapse = hdrl_parameter_sigclip_create(2, 3);
+    osp = hdrl_parameter_overscan_create(0, collapse);
+    hdrl_parameter_delete(osp);
+    hdrl_parameter_delete(collapse);
+
+    hdrl_parameter_delete(NULL);
+    hdrl_parameter_destroy(NULL);
+
+    cpl_test_error(CPL_ERROR_NONE);
+
+    return cpl_test_end(0);
+}
+
diff --git a/hdrl/tests/hdrl_sigclip-test.c b/hdrl/tests/hdrl_sigclip-test.c
new file mode 100644
index 0000000..b20d9fd
--- /dev/null
+++ b/hdrl/tests/hdrl_sigclip-test.c
@@ -0,0 +1,705 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2012,2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_sigclip.h"
+#include "hdrl_utils.h"
+#include <cpl.h>
+
+#include <math.h>
+#include <stdlib.h>
+
+#ifndef ARRAY_LEN
+#define ARRAY_LEN(a) sizeof((a))/sizeof((a)[0])
+#endif
+
+#ifndef SQR
+#define SQR(a) ((a) * (a))
+#endif
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_sigclip_test   Testing of the HDRL Sigma Clipping module
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_clip_kappa_sigma_test(void)
+{
+    double omean, omean_err, rej_low, rej_high;
+    cpl_size naccepted;
+
+    {
+        double * dpixels = cpl_calloc(9, sizeof(double));
+
+        cpl_vector * data = cpl_vector_wrap(9, dpixels);
+        cpl_vector * errors = cpl_vector_new(9);
+        cpl_vector_fill(errors, 1);
+
+        /* null optional out params */
+        hdrl_kappa_sigma_clip(data, errors, 3, 3, 3, CPL_FALSE,
+                              &omean, NULL, NULL, NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_eq(omean, 0.);
+
+        /* all out params NULL makes no sense */
+        hdrl_kappa_sigma_clip(data, errors, 3, 3, 3, CPL_FALSE,
+                              NULL, NULL, NULL, NULL, NULL);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+
+        /* NULL data */
+        hdrl_kappa_sigma_clip(NULL, errors, 3, 3, 3, CPL_FALSE,
+                              &omean, NULL, NULL, NULL, NULL);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+
+        /* wrong iter */
+        hdrl_kappa_sigma_clip(data, errors, 3, 3, 0, CPL_TRUE,
+                             &omean, NULL, NULL, NULL, NULL);
+        cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+        cpl_vector_delete(data);
+        cpl_vector_delete(errors);
+    }
+
+    {
+        double * dpixels = cpl_calloc(9, sizeof(double));
+
+        cpl_vector * data = cpl_vector_wrap(9, dpixels);
+        cpl_vector * errors = cpl_vector_new(9);
+        cpl_vector_fill(errors, 1);
+
+        hdrl_kappa_sigma_clip(data, errors, 3, 3, 3, CPL_FALSE,
+                              &omean, &omean_err, &naccepted,
+                              NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_eq(omean, 0.);
+        cpl_test_rel(omean_err, 1 / sqrt(9), 0.001);
+        cpl_test_eq(naccepted, 9);
+
+        cpl_vector_delete(data);
+        cpl_vector_delete(errors);
+    }
+
+    {
+        /* MAD sigma ~3 median 6, check that 1.5 and 10.5 which are closer to
+         * 6 -+ 3 * 1.5 than 4 and 6 but beyond the k*sig limit are not included */
+        double values[] = {1.5, 6., 4., 6., 4., 6., 4., 6., 10.5};
+        const int n = ARRAY_LEN(values);
+
+        cpl_vector * data = cpl_vector_wrap(n, values);
+        cpl_vector * errors = cpl_vector_new(n);
+        cpl_vector_fill(errors, 1);
+
+        hdrl_kappa_sigma_clip(data, errors, 1.5, 1.5, 1, CPL_FALSE,
+                              &omean, &omean_err, &naccepted,
+                              &rej_low, &rej_high);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_rel(omean, (4. * 3 + 6 * 4.) / 7., 0.001);
+        cpl_test_rel(omean_err, 1 / sqrt(n - 2), 0.001);
+        cpl_test_rel(rej_low, 1.55, 0.02);
+        cpl_test_rel(rej_high, 10.44, 0.02);
+        cpl_test_eq(naccepted, n - 2);
+
+        cpl_vector_unwrap(data);
+        cpl_vector_delete(errors);
+    }
+
+    {
+        /* special case of one remaining pixels */
+        double values[] = {10.};
+        const int n = ARRAY_LEN(values);
+
+        cpl_vector * data = cpl_vector_wrap(n, values);
+        cpl_vector * errors = cpl_vector_new(n);
+        cpl_vector_fill(errors, 1);
+
+        hdrl_kappa_sigma_clip(data, errors, 2., 2., 1, CPL_FALSE,
+                              &omean, &omean_err, &naccepted,
+                              &rej_low, &rej_high);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_rel(omean, values[0], 0.001);
+        cpl_test_rel(omean_err, 1, 0.001);
+        cpl_test_rel(rej_low, values[0], 0.02);
+        cpl_test_rel(rej_high, values[0], 0.02);
+        cpl_test_eq(naccepted, n);
+
+        cpl_vector_unwrap(data);
+        cpl_vector_delete(errors);
+    }
+
+    {
+        /* gaus mean 100 sigma 3.5 */
+        double values[] = {92, 93, 94, 94, 95, 95, 96, 96, 96, 97,
+            97, 97, 97, 98, 98, 98, 98, 99, 99, 99,
+            99, 100, 100, 100, 100, 100, 101, 101, 101, 101,
+            102, 102, 102, 102, 103, 103, 103, 103, 104, 104,
+            104, 105, 105, 106, 106, 107, 108 };
+        const int n = ARRAY_LEN(values);
+
+        cpl_vector * data = cpl_vector_wrap(n, values);
+        cpl_vector * errors = cpl_vector_new(n);
+        cpl_vector_fill(errors, 1);
+
+        /* kappa 2 included by iqr 92 and 108 */
+        hdrl_kappa_sigma_clip(data, errors, 2., 2., 3, CPL_FALSE,
+                              &omean, &omean_err, &naccepted,
+                              &rej_low, &rej_high);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_rel(omean, 100., 0.001);
+        cpl_test_rel(omean_err, 1 / sqrt(n), 0.001);
+        /* sigma overestimated by iqr */
+        cpl_test_rel(rej_low, 91., 0.005);
+        cpl_test_rel(rej_high, 109, 0.005);
+        cpl_test_eq(naccepted, n);
+
+        cpl_vector_unwrap(data);
+        cpl_vector_delete(errors);
+    }
+
+    {
+        /* gaus mean 100 sigma 3.5, 2 sigma range, 2 outliers */
+        double values[] = {1, 150, 94, 94, 95, 95, 96, 96, 96, 97,
+            97, 97, 97, 98, 98, 98, 98, 99, 99, 99,
+            99, 100, 100, 100, 100, 100, 101, 101, 101, 101,
+            102, 102, 102, 102, 103, 103, 103, 103, 104, 104,
+            104, 105, 105, 106, 106, 107, 108 };
+        const int n = ARRAY_LEN(values);
+
+        cpl_vector * data = cpl_vector_wrap(n, values);
+        cpl_vector * errors = cpl_vector_new(n);
+        cpl_vector_fill(errors, 1);
+
+        hdrl_kappa_sigma_clip(data, errors, 3, 3, 3, CPL_FALSE,
+                              &omean, &omean_err, &naccepted,
+                              NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_rel(omean, 100., 0.005);
+        cpl_test_rel(omean_err, 1 / sqrt(n - 2), 0.001);
+        cpl_test_eq(naccepted, n - 2);
+
+        cpl_vector_unwrap(data);
+        cpl_vector_delete(errors);
+    }
+
+    /* test inputs are not modified */
+    {
+        double values[] = {54, 234. ,5,2, 343, 23 , 2, 0.21, 0.1232 , 1.2e3};
+        const int n = ARRAY_LEN(values);
+
+        cpl_vector * data = cpl_vector_wrap(n, values);
+        cpl_vector * errors = cpl_vector_duplicate(data);
+        cpl_vector * odata = cpl_vector_duplicate(data);
+        cpl_vector * oerrors = cpl_vector_duplicate(errors);
+
+        hdrl_kappa_sigma_clip(data, errors, 3, 3, 3, CPL_FALSE,
+                              &omean, &omean_err, &naccepted,
+                              NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_vector_abs(data, odata, FLT_EPSILON);
+        cpl_test_vector_abs(errors, oerrors, FLT_EPSILON);
+
+        cpl_vector_unwrap(data);
+        cpl_vector_delete(errors);
+        cpl_vector_delete(odata);
+        cpl_vector_delete(oerrors);
+    }
+
+
+    /* image test */
+    {
+        /* gaus mean 100 sigma 3.5, 2 sigma range, 2 outliers */
+        double values[] = {1, 150, 94, 94, 95, 95, 96, 96, 96, 97,
+            97, 97, 97, 98, 98, 98, 98, 99, 99, 99,
+            99, 100, 100, 100, 100, 100, 101, 101, 101, 101,
+            102, 102, 102, 102, 103, 103, 103, 103, 104, 104,
+            104, 105, 105, 106, 106, 107, 108, 100, 100};
+        const int n = ARRAY_LEN(values);
+
+        cpl_image * data = cpl_image_wrap(sqrt(n), sqrt(n), CPL_TYPE_DOUBLE, 
+                values);
+        cpl_image * errors = cpl_image_new(sqrt(n), sqrt(n), CPL_TYPE_DOUBLE);
+        cpl_image_add_scalar(errors, 1);
+
+        hdrl_kappa_sigma_clip_image(data, errors, 3, 3, 3,
+                                   &omean, &omean_err, &naccepted,
+                                   NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_rel(omean, 100., 0.005);
+        cpl_test_rel(omean_err, 1 / sqrt(n - 2), 0.001);
+        cpl_test_eq(naccepted, n - 2);
+
+        cpl_image_unwrap(data);
+        cpl_image_delete(errors);
+    }
+
+    /* image test with bad pixels */
+    {
+        /* gaus mean 100 sigma 3.5, 2 sigma range, 2 outliers */
+        float values[] = {1, 150, 94, 94, 95, 95, 96, 96, 96, 97,
+            97, 97, 97, 98, 98, 98, 98, 99, 99, 99,
+            99, 100, 100, 100, 100, 100, 101, 101, 101, 101,
+            102, 102, 102, 102, 103, 103, 103, 103, 104, 104,
+            104, 105, 105, 106, 106, 107, 108, 100, 100};
+        const int n = sqrt(ARRAY_LEN(values));
+
+        cpl_image * data = cpl_image_wrap(n, n, CPL_TYPE_FLOAT, values);
+        cpl_image * errors = cpl_image_new(n, n, CPL_TYPE_FLOAT);
+        cpl_image_add_scalar(errors, 1);
+        /* set two bad pixels with really high error */
+        cpl_image_reject(data, n, n);
+        cpl_image_reject(data, n, n - 1);
+        cpl_image_set(errors, n, n, 2343.e30);
+        cpl_image_set(errors, n, n - 1, 2343.e30);
+        cpl_image_reject_from_mask(errors, cpl_image_get_bpm(data));
+
+        hdrl_kappa_sigma_clip_image(data, errors, 3, 3, 3,
+                                   &omean, &omean_err, &naccepted,
+                                   NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_rel(omean, 100., 0.005);
+        cpl_test_rel(omean_err, 1 / sqrt(n * n - 4), 0.001);
+        cpl_test_eq(naccepted, (n * n) - 4);
+
+        cpl_image_unwrap(data);
+        cpl_image_delete(errors);
+    }
+
+    /* test unequal bpms */
+    {
+        const int n = 5;
+        cpl_image * data = cpl_image_new(n, n, CPL_TYPE_FLOAT);
+        cpl_image * errors = cpl_image_new(n, n, CPL_TYPE_FLOAT);
+        cpl_image_reject(data, n, n);
+        cpl_image_reject(data, n, n - 1);
+
+        hdrl_kappa_sigma_clip_image(data, errors, 3, 3, 3,
+                                   &omean, &omean_err, &naccepted,
+                                   NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_image_delete(data);
+        cpl_image_delete(errors);
+    }
+
+    return cpl_error_get_code();
+}
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_minmax_test   Testing of the HDRL MINMAX Clipping module
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_clip_minmax_test(void)
+{
+    double omean, omean_err, nlow, nhigh, rej_low, rej_high;
+
+    cpl_size naccepted;
+
+    {
+        double * dpixels = cpl_calloc(9, sizeof(double));
+
+        cpl_vector * data = cpl_vector_wrap(9, dpixels);
+        cpl_vector * errors = cpl_vector_new(9);
+        cpl_vector_fill(errors, 1);
+
+        /* null optional out params */
+        hdrl_minmax_clip(data, errors, 3, 3, CPL_FALSE,
+                         &omean, NULL, NULL, NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_eq(omean, 0.);
+
+        /* all out params NULL makes no sense */
+        hdrl_minmax_clip(data, errors, 3, 3, CPL_FALSE,
+                         NULL, NULL, NULL, NULL, NULL);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+
+        /* NULL data */
+        hdrl_minmax_clip(NULL, errors, 3, 3, CPL_TRUE,
+                         &omean, NULL, NULL, NULL, &rej_high);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+
+
+        cpl_vector_delete(data);
+        cpl_vector_delete(errors);
+    }
+
+    {
+        double * dpixels = cpl_calloc(9, sizeof(double));
+        cpl_vector * data = cpl_vector_wrap(9, dpixels);
+        cpl_vector * errors = cpl_vector_new(9);
+        cpl_vector_fill(errors, 1);
+        nlow = 3;
+        nhigh = 3;
+        hdrl_minmax_clip(data, errors, nlow, nhigh, CPL_FALSE,
+                         &omean, &omean_err, &naccepted,
+                         &rej_low, &rej_high);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_eq(omean, 0.);
+        cpl_test_rel(omean_err, 1 / sqrt(9 - (nlow + nhigh)), 0.001);
+        cpl_test_eq(naccepted, 9 - (nlow + nhigh));
+        cpl_test_eq(rej_low, 0.);
+        cpl_test_eq(rej_high, 0.);
+
+        cpl_vector_delete(data);
+        cpl_vector_delete(errors);
+    }
+
+
+    {
+        /* special case of one remaining pixels */
+        double values[] = {10.};
+        const int n = ARRAY_LEN(values);
+
+        cpl_vector * data = cpl_vector_wrap(n, values);
+        cpl_vector * errors = cpl_vector_new(n);
+        cpl_vector_fill(errors, 1);
+        nlow = 1;
+        nhigh = 1;
+        hdrl_minmax_clip(data, errors, nlow, nhigh, CPL_FALSE,
+                         &omean, &omean_err, &naccepted,
+                         &rej_low, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test(isnan(omean));
+        cpl_test(isnan(omean_err));
+        cpl_test_eq(naccepted, 0);
+        cpl_test_eq(rej_low, 0); /* invalid */
+
+        cpl_vector_unwrap(data);
+        cpl_vector_delete(errors);
+    }
+
+    {
+        /* gaus mean 100 sigma 3.5  - special case - don't reject anything */
+        double values[] = {92, 93, 94, 94, 95, 95, 96, 96, 96, 97,
+                        97, 97, 97, 98, 98, 98, 98, 99, 99, 99,
+                        99, 100, 100, 100, 100, 100, 101, 101, 101, 101,
+                        102, 102, 102, 102, 103, 103, 103, 103, 104, 104,
+                        104, 105, 105, 106, 106, 107, 108 };
+        const int n = ARRAY_LEN(values);
+
+        cpl_vector * data = cpl_vector_wrap(n, values);
+        cpl_vector * errors = cpl_vector_new(n);
+        cpl_vector_fill(errors, 1);
+        nlow = 0;
+        nhigh = 0;
+
+        hdrl_minmax_clip(data, errors, nlow, nhigh, CPL_FALSE,
+                         &omean, &omean_err, &naccepted,
+                         &rej_low, &rej_high);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_rel(omean, 100., n * HDRL_EPS_DATA);
+        cpl_test_rel(omean_err, 1 / sqrt(n -(nlow + nhigh)), 0.001);
+        cpl_test_eq(rej_low, 92.);
+        cpl_test_eq(rej_high, 108);
+        cpl_test_eq(naccepted, n - (nlow + nhigh));
+
+        cpl_vector_unwrap(data);
+        cpl_vector_delete(errors);
+    }
+
+    {
+        /* gaus mean 100 sigma 3.5 */
+        double values[] = {92, 93, 94, 94, 95, 95, 96, 96, 96, 97,
+                        97, 97, 97, 98, 98, 98, 98, 99, 99, 99,
+                        99, 100, 100, 100, 100, 100, 101, 101, 101, 101,
+                        102, 102, 102, 102, 103, 103, 103, 103, 104, 104,
+                        104, 105, 105, 106, 106, 107, 108 };
+        const int n = ARRAY_LEN(values);
+
+        cpl_vector * data = cpl_vector_wrap(n, values);
+        cpl_vector * errors = cpl_vector_new(n);
+        cpl_vector_fill(errors, 1);
+        nlow = 2;
+        nhigh = 2;
+
+        hdrl_minmax_clip(data, errors, nlow, nhigh, CPL_FALSE,
+                         &omean, &omean_err, &naccepted,
+                         &rej_low, &rej_high);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_rel(omean, 100., 0.001);
+        cpl_test_rel(omean_err, 1 / sqrt(n -(nlow + nhigh)), 0.001);
+        /* sigma overestimated by iqr */
+        cpl_test_eq(rej_low, 94.);
+        cpl_test_eq(rej_high, 106);
+        cpl_test_eq(naccepted, n - (nlow + nhigh));
+
+        cpl_vector_unwrap(data);
+        cpl_vector_delete(errors);
+    }
+
+    {
+        /* gaus mean 100 sigma 3.5, 2 sigma range, 2 outliers */
+        double values[] = {1, 150, 94, 94, 95, 95, 96, 96, 96, 97,
+                        97, 97, 97, 98, 98, 98, 98, 99, 99, 99,
+                        99, 100, 100, 100, 100, 100, 101, 101, 101, 101,
+                        102, 102, 102, 102, 103, 103, 103, 103, 104, 104,
+                        104, 105, 105, 106, 106, 107, 108 };
+        const int n = ARRAY_LEN(values);
+
+        cpl_vector * data = cpl_vector_wrap(n, values);
+        cpl_vector * errors = cpl_vector_new(n);
+        cpl_vector_fill(errors, 1);
+        nlow = 3;
+        nhigh = 3;
+        hdrl_minmax_clip(data, errors, nlow, nhigh, CPL_FALSE,
+                         &omean, &omean_err, &naccepted,
+                         NULL, &rej_high);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_rel(omean, 100., 0.005);
+        cpl_test_rel(omean_err, 1 / sqrt(n - (nlow + nhigh)), 0.001);
+        cpl_test_eq(naccepted, n - (nlow + nhigh));
+
+        cpl_vector_unwrap(data);
+        cpl_vector_delete(errors);
+    }
+
+    /* test inputs are not modified */
+    {
+        double values[] = {54, 234. ,5,2, 343, 23 , 2, 0.21, 0.1232 , 1.2e3};
+        const int n = ARRAY_LEN(values);
+
+        cpl_vector * data = cpl_vector_wrap(n, values);
+        cpl_vector * errors = cpl_vector_duplicate(data);
+        cpl_vector * odata = cpl_vector_duplicate(data);
+        cpl_vector * oerrors = cpl_vector_duplicate(errors);
+        nlow = 3;
+        nhigh = 3;
+
+        hdrl_minmax_clip(data, errors, nlow, nhigh, CPL_FALSE,
+                         &omean, &omean_err, &naccepted,
+                         &rej_low, &rej_high);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_test_eq(rej_low, 2.);
+        cpl_test_eq(rej_high, 54.);
+
+        cpl_test_vector_abs(data, odata, 0.);
+        cpl_test_vector_abs(errors, oerrors, 0.);
+
+        cpl_vector_unwrap(data);
+        cpl_vector_delete(errors);
+        cpl_vector_delete(odata);
+        cpl_vector_delete(oerrors);
+    }
+
+
+    /* image test */
+    {
+        /* gaus mean 100 sigma 3.5, 2 sigma range, 3 outliers */
+        double values[] = {1, 150, 94, 94, 95, 95, 96, 96, 96, 97,
+                        97, 97, 97, 98, 98, 98, 98, 99, 99, 99,
+                        99, 100, 100, 100, 100, 100, 101, 101, 101, 101,
+                        102, 102, 102, 102, 103, 103, 103, 103, 104, 104,
+                        104, 105, 105, 106, 106, 107, 108, 100, -1000};
+        const int n = ARRAY_LEN(values);
+
+        cpl_image * data = cpl_image_wrap(sqrt(n), sqrt(n), CPL_TYPE_DOUBLE,
+                        values);
+        cpl_image * errors = cpl_image_new(sqrt(n), sqrt(n), CPL_TYPE_DOUBLE);
+        cpl_image_add_scalar(errors, 1);
+        nlow = 2;
+        nhigh = 1;
+
+        hdrl_minmax_clip_image(data, errors, nlow, nhigh,
+                               &omean, &omean_err, &naccepted,
+                               NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_rel(omean, 100., 0.005);
+        cpl_test_rel(omean_err, 1 / sqrt(n - (nlow + nhigh)), 0.001);
+        cpl_test_eq(naccepted, n - (nlow + nhigh));
+
+        cpl_image_unwrap(data);
+        cpl_image_delete(errors);
+    }
+
+    /* image test with bad pixels */
+    {
+        /* gaus mean 100 sigma 3.5, 2 sigma range, 2 outliers */
+        float values[] = {1, 150, 94, 94, 95, 95, 96, 96, 96, 97,
+                        97, 97, 97, 98, 98, 98, 98, 99, 99, 99,
+                        99, 100, 100, 100, 100, 100, 101, 101, 101, 101,
+                        102, 102, 102, 102, 103, 103, 103, 103, 104, 104,
+                        104, 105, 105, 106, 106, 107, 108, 100, 100};
+        const int n = sqrt(ARRAY_LEN(values));
+
+        cpl_image * data = cpl_image_wrap(n, n, CPL_TYPE_FLOAT, values);
+        cpl_image * errors = cpl_image_new(n, n, CPL_TYPE_FLOAT);
+        cpl_image_add_scalar(errors, 1);
+        nlow = 1;
+        nhigh = 1;
+
+        /* set two bad pixels with really high error */
+        cpl_image_reject(data, n, n);
+        cpl_image_reject(data, n, n - 1);
+        cpl_image_set(errors, n, n, 2343.e30);
+        cpl_image_set(errors, n, n - 1, 2343.e30);
+        cpl_image_reject_from_mask(errors, cpl_image_get_bpm(data));
+
+        hdrl_minmax_clip_image(data, errors, nlow, nhigh,
+                               &omean, &omean_err, &naccepted,
+                               NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+
+
+        cpl_test_rel(omean, 100., 0.005);
+        cpl_test_rel(omean_err, 1 / sqrt(n * n - (nlow + nhigh + 2)), 0.001);
+        cpl_test_eq(naccepted, (n * n) - (nlow + nhigh + 2));
+
+        cpl_image_unwrap(data);
+        cpl_image_delete(errors);
+    }
+
+    /* test unequal bpms */
+    {
+        const int n = 5;
+        cpl_image * data = cpl_image_new(n, n, CPL_TYPE_FLOAT);
+        cpl_image * errors = cpl_image_new(n, n, CPL_TYPE_FLOAT);
+        cpl_image_reject(data, n, n);
+        cpl_image_reject(data, n, n - 1);
+        nlow = 3;
+        nhigh = 3;
+
+        hdrl_minmax_clip_image(data, errors, nlow, nhigh,
+                               &omean, &omean_err, &naccepted,
+                               NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_image_delete(data);
+        cpl_image_delete(errors);
+    }
+    /* image test equal range of rejected values */
+    {
+        float values[] = {-5., -5., -5., 1., 5., 1., 5., 1., 5., 5.};
+        float errors[] = {50., 500., 100., 1., 5., 1., 500., 1., 200.};
+        const int n = sqrt(ARRAY_LEN(values));
+
+        cpl_image * data = cpl_image_wrap(n, n, CPL_TYPE_FLOAT, values);
+        cpl_image * errs = cpl_image_wrap(n, n, CPL_TYPE_FLOAT, errors);
+        cpl_image * odata = cpl_image_duplicate(data);
+        cpl_image * oerrs = cpl_image_duplicate(errs);
+
+        hdrl_minmax_clip_image(data, errs, 2, 2,
+                               &omean, &omean_err, &naccepted,
+                               NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+
+
+        cpl_test_rel(omean, 0.6, 10 * HDRL_EPS_DATA);
+        cpl_test_rel(omean_err, sqrt((SQR(50.) + 1. * 3. + SQR(5.)) /
+                                     SQR(n * n - 4)),
+                     20 * HDRL_EPS_ERROR);
+        cpl_test_eq(naccepted, (n * n) - (4));
+
+        /* select multiple smallest errors, low*/
+        hdrl_minmax_clip_image(data, errs, 1, 2,
+                               &omean, &omean_err, &naccepted,
+                               NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        /* select multiple smallest errors, high */
+        hdrl_minmax_clip_image(data, errs, 2, 1,
+                               &omean, &omean_err, &naccepted,
+                               NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_rel(omean, 8. / 6., 10 * HDRL_EPS_DATA);
+        cpl_test_rel(omean_err,
+                     sqrt((SQR(50.) + SQR(200.) + 1. * 3. + SQR(5.)) /
+                           SQR(n * n - (3))),
+                     20 * HDRL_EPS_ERROR);
+        cpl_test_eq(naccepted, (n * n) - (3));
+
+        /* select multiple smallest errors, low + high */
+        hdrl_minmax_clip_image(data, errs, 1, 1,
+                               &omean, &omean_err, &naccepted,
+                               NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_rel(omean, 3. / 7., 10 * HDRL_EPS_DATA);
+        cpl_test_rel(omean_err,
+                     sqrt((SQR(50.) + SQR(100.) + SQR(200.) + 3. + SQR(5.)) /
+                          SQR(n * n - 2)),
+                     20 * HDRL_EPS_ERROR);
+        cpl_test_eq(naccepted, (n * n) - (2));
+
+        /* 50 error not in equal range so we should get the 100. error */
+        values[0] = -5.0001;
+        cpl_image_set(odata, 1, 1, values[0]);
+        hdrl_minmax_clip_image(data, errs, 2, 2,
+                               &omean, &omean_err, &naccepted,
+                               NULL, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_rel(omean, 0.6, 10 * HDRL_EPS_DATA);
+        cpl_test_rel(omean_err, sqrt((SQR(100.) + 1. * 3. + SQR(5.)) /
+                                    SQR(n * n - 4)),
+                     20 * HDRL_EPS_ERROR);
+        cpl_test_eq(naccepted, (n * n) - (4));
+
+        /* check original have not been overwritten */
+        cpl_test_image_abs(data, odata, 0);
+        cpl_test_image_abs(errs, oerrs, 0);
+
+        cpl_image_delete(odata);
+        cpl_image_delete(oerrs);
+        cpl_image_unwrap(data);
+        cpl_image_unwrap(errs);
+    }
+
+    return cpl_error_get_code();
+}
+
+
+
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ @brief   Unit tests of clipping
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+
+    hdrl_clip_kappa_sigma_test();
+    hdrl_clip_minmax_test();
+
+    return cpl_test_end(0);
+}
diff --git a/hdrl/tests/hdrl_strehl-test.c b/hdrl/tests/hdrl_strehl-test.c
new file mode 100644
index 0000000..6a1d483
--- /dev/null
+++ b/hdrl/tests/hdrl_strehl-test.c
@@ -0,0 +1,585 @@
+/*
+ * This file is part of the HDRL
+ * Copyright (C) 2014 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_strehl.c"
+#include "hdrl_strehl.h"
+#include "hdrl_test.h"
+
+#include <cpl.h>
+
+#include <math.h>
+#include <string.h>
+
+#ifndef ARRAY_LEN
+#define ARRAY_LEN(a) sizeof((a))/sizeof((a)[0])
+#endif
+
+
+/*----------------------------------------------------------------------------*/
+/**
+  @defgroup hdrl_strehl_test  Testing of the HDRL Strehl module
+ */
+/*----------------------------------------------------------------------------*/
+
+void hdrl_strehl_test_parlist(void)
+{
+    /* parameter parsing smoketest */
+    double wavelength = 1.635e-6;
+    double m1 = 5.08/2;
+    double m2 = 5.08/2*0.36;
+    double psx = 0.0331932/2.;
+    double psy = 0.0331932/2.;
+    double r1 = 1.5;
+    double r2 = 1.5;
+    double r3 = 2.0;
+
+    hdrl_parameter * hpar;
+    hdrl_parameter * strehl_def =
+        hdrl_strehl_parameter_create(wavelength, m1, m2, psx, psy, r1, r2, r3);
+
+    cpl_parameterlist * strehl = hdrl_strehl_parameter_create_parlist(
+                "RECIPE", "strehl", strehl_def);
+
+    hdrl_parameter_delete(strehl_def);
+    cpl_test_error(CPL_ERROR_NONE);
+
+    cpl_test_eq(cpl_parameterlist_get_size(strehl), 8);
+
+    hpar = hdrl_strehl_parameter_parse_parlist(strehl, "RECIPE.invalid");
+    cpl_test_null(hpar);
+    cpl_test_error(CPL_ERROR_DATA_NOT_FOUND);
+
+    hpar = hdrl_strehl_parameter_parse_parlist(strehl, "RECIPE.strehl");
+    cpl_parameterlist_delete(strehl);
+    cpl_test_error(CPL_ERROR_NONE);
+    {
+        cpl_test_eq(hdrl_strehl_parameter_get_wavelength(hpar), wavelength);
+        cpl_test_eq(hdrl_strehl_parameter_get_m1(hpar), m1);
+        cpl_test_eq(hdrl_strehl_parameter_get_m2(hpar), m2);
+        cpl_test_eq(hdrl_strehl_parameter_get_pixel_scale_x(hpar), psx);
+        cpl_test_eq(hdrl_strehl_parameter_get_pixel_scale_y(hpar), psy);
+        cpl_test_eq(hdrl_strehl_parameter_get_flux_radius(hpar), r1);
+        cpl_test_eq(hdrl_strehl_parameter_get_bkg_radius_low(hpar), r2);
+        cpl_test_eq(hdrl_strehl_parameter_get_bkg_radius_high(hpar), r3);
+    }
+
+    hdrl_parameter_destroy(hpar);
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check hdrl_strehl_compute proper error on null input images
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static hdrl_image* hdrl_strehl_test_gauss_create(void)
+{
+
+    double sig_x = 3.;
+    double sig_y = 3.;
+    cpl_size n = 5;
+    double dmad;
+    hdrl_image* hgauss;
+    cpl_image * gauss_data;
+    cpl_image * gauss_error;
+
+    gauss_data = cpl_image_new(2 * n + 1, 2 * n + 1, CPL_TYPE_DOUBLE);
+    cpl_image_fill_gaussian(gauss_data, n + 1, n + 1, (double)121.0, sig_x, sig_y);
+    gauss_error = cpl_image_duplicate(gauss_data);
+    cpl_image_multiply_scalar(gauss_error, 0);
+    cpl_image_get_mad(gauss_data, &dmad);
+    cpl_image_add_scalar(gauss_error, (dmad * CPL_MATH_STD_MAD));
+
+    hgauss = hdrl_image_create(gauss_data, gauss_error);
+    cpl_image_delete(gauss_data);
+    cpl_image_delete(gauss_error);
+
+    return hgauss;
+}
+
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check hdrl_strehl_compute proper error on null input images
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_strehl_test_null_input(void)
+{
+    double w = 1.635e-6;
+    double m1 = 5.08/2;
+    double m2 = 5.08/2*0.36;
+    double psx = 0.0331932/2.;
+    double psy = 0.0331932/2.;
+    double r1 = 1.5;
+    double r2 = 1.5;
+    double r3 = 2.0;
+
+    hdrl_image                      * hima =NULL;
+
+    hdrl_parameter                  *   strehl_param = NULL;
+    hdrl_strehl_result                  strehl_result;
+
+    /* Strehl Parameters */
+    strehl_param = hdrl_strehl_parameter_create(w, m1, m2, psx, psy, r1, r2, r3);
+
+    /* test functionality */
+    strehl_result = hdrl_strehl_compute(hima, strehl_param) ;
+    hdrl_parameter_delete(strehl_param) ;
+
+    cpl_test(isnan(strehl_result.strehl_value.data));
+    cpl_test_error(CPL_ERROR_NULL_INPUT);
+
+    return cpl_error_get_code();
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief Check hdrl_strehl_compute proper error on illegal inputs
+  @return cpl_error_code
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_strehl_test_illegal_input(void)
+{
+    double w = 1.635e-6;
+    double m1 = 5.08/2;
+    double m2 = 5.08/2*0.36;
+    double psx = 0.0331932/2.;
+    double psy = 0.0331932/2.;
+    double r1 = 1.5;
+    double r2 = 1.5;
+    double r3 = 2.0;
+
+    hdrl_image * hima = hdrl_strehl_test_gauss_create();
+    hdrl_parameter * strehl_param;
+
+    strehl_param = hdrl_strehl_parameter_create(-1, m1, m2, psx, psy, r1, r2, r3);
+    cpl_test_null(strehl_param);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    strehl_param = hdrl_strehl_parameter_create(w, -1, m2, psx, psy, r1, r2, r3);
+    cpl_test_null(strehl_param);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    strehl_param = hdrl_strehl_parameter_create(w, m1, -1, psx, psy, r1, r2, r3);
+    cpl_test_null(strehl_param);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    strehl_param = hdrl_strehl_parameter_create(w, m1, m2, -1, psy, r1, r2, r3);
+    cpl_test_null(strehl_param);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    strehl_param = hdrl_strehl_parameter_create(w, m1, m2, psx, -1, r1, r2, r3);
+    cpl_test_null(strehl_param);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    strehl_param = hdrl_strehl_parameter_create(w, m1, m2, psx, psy, -1, r2, r3);
+    cpl_test_null(strehl_param);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    strehl_param = hdrl_strehl_parameter_create(w, m1, m2, psx, psy, r1, -1, r3);
+    cpl_test_null(strehl_param);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    strehl_param = hdrl_strehl_parameter_create(w, m1, m2, psx, psy, r1, r2, -1);
+    cpl_test_null(strehl_param);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+    strehl_param = hdrl_strehl_parameter_create(w, m1, m1 + 1, psx, psy, r1, r2, r3);
+    cpl_test_null(strehl_param);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    hdrl_image_delete(hima);
+
+    return cpl_error_get_code();
+}
+
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_strehl_test
+            Testing of hdrl_strehl module
+ */
+/*----------------------------------------------------------------------------*/
+
+void test_psf(void)
+{
+    double m1 = 8.3 / 2; /* telescope mirror radii [m] */
+    double m2 = 1.1 / 2; /* telescope obstruction radii [m] */
+    size_t nx = 256; /* PSF image X size */
+    size_t ny = 256; /* PSF image Y size */
+    size_t hx = nx / 2; /* pixel position of peak (FITS) */
+    size_t hy = ny / 2; /* pixel position of peak (FITS) */
+    double peak; /* expected PSF peak value */
+    int rej;
+
+
+    double wavelength = 7.7e-6; /* observing wavelength in [m] */
+    double pscale_x = 0.075; /* pixel scale in x [as] */
+    double pscale_y = 0.075; /* pixel scale in y [as] */
+
+    /* exactly centered psf (symmetric) */
+    cpl_image * psf = compute_psf(wavelength, m1, m2, pscale_x, pscale_y,
+                                  hx, hy,
+                                  nx, ny);
+    peak = 0.670695;
+    cpl_test_abs(cpl_image_get(psf, hx, hy, &rej), 1., 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx, hy - 1, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx + 1, hy, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx, hy + 1, &rej), peak, 1e-4);
+    cpl_image_delete(psf);
+
+    /* exactly centered psf (symmetric) one pixel lower in x */
+    psf = compute_psf(wavelength, m1, m2, pscale_x, pscale_y,
+                      hx - 1, hy,
+                      nx, ny);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy, &rej), 1., 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 2, hy, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy - 1, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx, hy, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy + 1, &rej), peak, 1e-4);
+    cpl_image_delete(psf);
+
+    /* centered at origin of pixel -> square block */
+    psf = compute_psf(wavelength, m1, m2, pscale_x, pscale_y,
+                      hx - 0.5, hy - 0.5,
+                      nx, ny);
+    peak = 0.821877;
+    cpl_test_abs(cpl_image_get(psf, hx, hy, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy - 1, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx, hy - 1, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy, &rej), peak, 1e-4);
+    cpl_image_delete(psf);
+
+    /* + .75 / 0.25  */
+    psf = compute_psf(wavelength, m1, m2, pscale_x, pscale_y,
+                      hx + .75, hy + .25,
+                      nx, ny);
+    cpl_test_abs(cpl_image_get(psf, hx, hy, &rej), 0.781698, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy, &rej), 0.255305, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx, hy - 1, &rej), 0.411749, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx + 1, hy, &rej), 0.952739, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx, hy + 1, &rej), 0.636695, 1e-4);
+    cpl_image_delete(psf);
+
+    /* centered at origin of pixel -> square block
+     * asymmetric pixel scale */
+    psf = compute_psf(wavelength, m1, m2, pscale_x, 0.025,
+                      hx - 0.5, hy - 0.5,
+                      nx, ny);
+    peak = 0.897496;
+    cpl_test_abs(cpl_image_get(psf, hx, hy, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy - 1, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx, hy - 1, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy, &rej), peak, 1e-4);
+    /* x direction tails */
+    peak = 0.383906;
+    cpl_test_abs(cpl_image_get(psf, hx + 1, hy, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx + 1, hy - 1, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 2, hy, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 2, hy - 1, &rej), peak, 1e-4);
+    /* y direction tails */
+    peak = 0.821877;
+    cpl_test_abs(cpl_image_get(psf, hx, hy + 1, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy + 1, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx, hy - 2, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy - 2, &rej), peak, 1e-4);
+    cpl_image_delete(psf);
+
+    /* exactly centered psf (symmetric) double sampled*/
+    hx = nx; /* fits */
+    hy = ny; /* fits */
+    psf = compute_psf(wavelength, m1, m2, pscale_x / 2., pscale_y / 2.,
+                      hx, hx,
+                      nx * 2, ny * 2);
+    peak = 0.907339;
+    cpl_test_abs(cpl_image_get(psf, hx, hy, &rej), 1., 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx, hy - 1, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx + 1, hy, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx, hy + 1, &rej), peak, 1e-4);
+    cpl_image_delete(psf);
+
+    /* centered at origin of pixel -> square block
+     * asymmetric pixel scale and image size*/
+    ny = 2 * nx;
+    hx = nx / 2; /* fits */
+    hy = ny / 2; /* fits */
+    psf = compute_psf(wavelength, m1, m2, pscale_x, 0.025,
+                      hx - 0.5, hy - 0.5,
+                      nx, ny);
+    peak = 0.897496;
+    cpl_test_abs(cpl_image_get(psf, hx, hy, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy - 1, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx, hy - 1, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy, &rej), peak, 1e-4);
+    /* x direction tails */
+    peak = 0.383906;
+    cpl_test_abs(cpl_image_get(psf, hx + 1, hy, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx + 1, hy - 1, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 2, hy, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 2, hy - 1, &rej), peak, 1e-4);
+    /* y direction tails */
+    peak = 0.821877;
+    cpl_test_abs(cpl_image_get(psf, hx, hy + 1, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy + 1, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx, hy - 2, &rej), peak, 1e-4);
+    cpl_test_abs(cpl_image_get(psf, hx - 1, hy - 2, &rej), peak, 1e-4);
+    cpl_image_delete(psf);
+}
+
+
+void test_strehl_with_bkg(void)
+{
+    hdrl_image * himg;
+    cpl_image * img;
+    hdrl_strehl_result r;
+    /* TODO add more unit tests */
+    double m1 = 8.3 / 2;
+    double m2 = 1.1 / 2;
+    size_t nx = 256;
+    size_t ny = 256;
+    double lam = 7.7e-6;
+    /* oversampled image, 0.075 would be about 2*nyquist */
+    double pscale = 0.03;
+
+    /* realistic bkg slope */
+    double slope_x = 1. / nx * 100;
+
+    cpl_image* bkg  = NULL;
+    double*    pbkg = NULL;
+
+    img = compute_psf(lam, m1, m2, pscale, pscale, nx / 2., ny / 2., nx, ny);
+
+    /* we multiply for a large factor to make sure that the psf has high S/N */
+    cpl_image_multiply_scalar(img, 2000.);
+
+    /* create a background image with a simple slope along X direction */
+    bkg = cpl_image_duplicate(img);
+    cpl_image_multiply_scalar(bkg, 0);
+    pbkg=cpl_image_get_data_double(bkg);
+
+
+    for(size_t j = 0; j < ny; j++) {
+        for(size_t i = 0; i < nx; i++) {
+            pbkg[i+nx*j] = i * slope_x;
+        }
+    }
+    cpl_image_add(img, bkg);
+    /*
+      cpl_image_save(img, "data.fits", CPL_TYPE_FLOAT, NULL, CPL_IO_DEFAULT);
+      cpl_image_save(bkg, "bkg.fits", CPL_TYPE_FLOAT, NULL, CPL_IO_DEFAULT);
+     */
+
+    himg = hdrl_image_create(img, NULL);
+
+    /* upsampling/downsampling introduces an error */
+    double rel = 0.015;
+
+    /* real test starts here: we need to subtract bkg from proper region */
+    r = compute_strehl(himg, lam, m1, m2, pscale, pscale, .5, 2.5, 3.0);
+    cpl_test_abs(r.strehl_value.data, 1.0, rel);
+
+    hdrl_image_delete(himg);
+    cpl_image_delete(img);
+    cpl_image_delete(bkg);
+
+}
+
+void test_strehl(void)
+{
+    hdrl_image * himg;
+    cpl_image * img;
+    hdrl_strehl_result r;
+    /* TODO add more unit tests */
+    double m1 = 8.3 / 2;
+    double m2 = 1.1 / 2;
+    size_t nx = 256;
+    size_t ny = 256;
+    double lam = 7.7e-6;
+    /* oversampled image, 0.075 would be about 2*nyquist */
+    double pscale = 0.03;
+    img = compute_psf(lam, m1, m2, pscale, pscale,
+                      nx / 2, ny / 2, nx, ny);
+    himg = hdrl_image_create(img, NULL);
+
+    /* add unmasked larger maximum */
+    hdrl_image_set_pixel(himg, 28, 231, (hdrl_value){1.5, 1.5});
+
+    /* bad background */
+    r = compute_strehl(himg, lam, m1, m2, pscale, pscale, 1.5, -1, 4.);
+    cpl_test_error(CPL_ERROR_INCOMPATIBLE_INPUT);
+    r = compute_strehl(himg, lam, m1, m2, pscale, pscale, 1.5, 4., -1);
+    cpl_test_error(CPL_ERROR_INCOMPATIBLE_INPUT);
+    r = compute_strehl(himg, lam, m1, m2, pscale, pscale, 1.5, 5, 5);
+    cpl_test_error(CPL_ERROR_INCOMPATIBLE_INPUT);
+
+    cpl_mask_not(hdrl_image_get_mask(himg));
+    r = compute_strehl(himg, lam, m1, m2, pscale, pscale, 1.5, 5, 6);
+    cpl_test_error(CPL_ERROR_DATA_NOT_FOUND);
+    cpl_mask_not(hdrl_image_get_mask(himg));
+
+    /* upsampling/downsampling introduces an error */
+    double rel = 0.015;
+
+    r = compute_strehl(himg, lam, m1, m2, pscale, pscale, .5, -1, -1);
+    cpl_test_abs(r.strehl_value.data, 1.0, rel);
+    cpl_test_abs(r.star_x, nx / 2., rel);
+    cpl_test_abs(r.star_y, nx / 2., rel);
+
+    /* test with background */
+    hdrl_image_add_scalar(himg, (hdrl_value){5., 0.});
+    r = compute_strehl(himg, lam, m1, m2, pscale, pscale, .5, 2, 3);
+    cpl_test_abs(r.strehl_value.data, 1.0, rel);
+    cpl_test_abs(r.star_background.data, 5.0, rel);
+    cpl_test_abs(r.star_background.error, 0., rel);
+
+    /* test with bad pixel in background */
+    hdrl_image_set_pixel(himg, 128, 161, (hdrl_value){1e20, 1e20});
+    hdrl_image_reject(himg, 128, 161);
+    r = compute_strehl(himg, lam, m1, m2, pscale, pscale, .5, 2, 3);
+    cpl_test_abs(r.strehl_value.data, 1.0, rel);
+    cpl_test_abs(r.star_background.data, 5.0, rel);
+    cpl_test_abs(r.star_background.error, 0., rel);
+
+    /* test zero background */
+    r = compute_strehl(himg, lam, m1, m2, pscale, pscale, .5, 50, 55);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    hdrl_image_delete(himg);
+    cpl_image_delete(img);
+
+
+    /* test other psf offsets */
+    for (size_t i = 0; i < 10; i++) {
+        img = compute_psf(lam, m1, m2, pscale, pscale,
+                          nx / 2 + i / 10., ny / 2 + i / 10., nx, ny);
+        himg = hdrl_image_create(img, NULL);
+        r = compute_strehl(himg, lam, m1, m2, pscale, pscale, .5, -1, -1);
+        cpl_test_abs(r.strehl_value.data, 1.0, rel);
+        hdrl_image_delete(himg);
+        cpl_image_delete(img);
+    }
+
+    /* failing fit */
+    himg = hdrl_image_new(nx, ny);
+    r = compute_strehl(himg, lam, m1, m2, pscale, pscale, .5, -1, -1);
+    cpl_test_error(CPL_ERROR_DATA_NOT_FOUND);
+    hdrl_image_delete(himg);
+}
+
+
+void test_strehl_data(int argc, char * argv[])
+{
+    /* pass images via commandline to test */
+    for (size_t i = 2; i < (size_t)argc; i++) {
+        hdrl_image * himg;
+        cpl_image * img;
+        hdrl_strehl_result r;
+        cpl_frame * frm = cpl_frame_new();
+        cpl_frame_set_filename(frm, argv[i]);
+        cpl_size next = cpl_frame_get_nextensions(frm);
+        cpl_frame_delete(frm);
+        img = cpl_image_load(argv[i], CPL_TYPE_DOUBLE, 0, 0);
+        double radius = atof(argv[1]); /* arcsec */
+        if (next == 0) {
+            double dmad;
+            cpl_image_get_mad(img, &dmad);
+            /* peak/signal to noise ratio */
+            cpl_image * err = cpl_image_duplicate(img);
+            cpl_image_multiply_scalar(err, 0);
+            cpl_image_add_scalar(err, (dmad * CPL_MATH_STD_MAD));
+            himg = hdrl_image_create(img, err);
+            cpl_msg_info(cpl_func, "image error %g", (dmad * CPL_MATH_STD_MAD));
+        }
+        else {
+            cpl_image * err = cpl_image_load(argv[i], CPL_TYPE_DOUBLE, 0, 1);
+            himg = hdrl_image_create(img, err);
+            cpl_msg_info(cpl_func, "using ext 1 as error");
+        }
+        if (strstr(argv[i], "_2.fits")) {
+            r = compute_strehl(himg, 1.635e-6, 5.08/2, 5.08/2*0.36, 0.0331932,
+                               0.0331932, radius, -1, -1);
+        }
+        else if (strstr(argv[i], "_4.fits")) {
+            r = compute_strehl(himg, 1.635e-6, 5.08/2, 5.08/2*0.36,
+                               0.0331932/2., 0.0331932/2., radius, -1, -1);
+        }
+        else if (strstr(argv[i], ".fits")) {
+            cpl_msg_warning(cpl_func,"case .fits");
+            cpl_image_save(hdrl_image_get_image(himg), "data.fits", CPL_TYPE_FLOAT, NULL, CPL_IO_DEFAULT);
+            cpl_image_save(hdrl_image_get_error(himg), "errs.fits", CPL_TYPE_FLOAT, NULL, CPL_IO_DEFAULT);
+            cpl_msg_info(cpl_func,"r1=%g r2=%g r3=%g",radius,-1.,-1.);
+            cpl_msg_info(cpl_func,"m1=%g m2=%g pscale_x=%g pscale_y=%g",
+                         8.0,1.12,0.01225,0.01225);
+            r = compute_strehl(himg, 1.6e-6, 8.0/2, 1.12/2,
+                               0.01225, 0.01225, radius, 1.5, 2.0);
+        }
+        else {
+            cpl_msg_error(cpl_func, "Unknown pixelscale for %s", argv[i]);
+            continue;
+        }
+        cpl_msg_info(cpl_func, "Strehl for %s: %g", argv[i], r.strehl_value.data);
+        cpl_test_abs(r.strehl_value.data, 1.0, 0);
+        cpl_image_delete(img);
+    }
+//    img = cpl_image_load("/tmp/jtaylor/Torino_2.fits", CPL_TYPE_DOUBLE, 0, 0);
+//    r = compute_strehl(img, 1.635e-6, 5.08/2, 5.08/2*0.36, 0.0331932, 0.0331932);
+//    cpl_test_abs(r, 1.0, 0);
+//
+//   img = cpl_image_load("/tmp/jtaylor/Teramo_4.fits", CPL_TYPE_DOUBLE, 0, 0);
+//    r = compute_strehl(img, 1.635e-6, 5.08/2, 5.08/2*0.36, 0.0165966, 0.0165966);
+//    cpl_test_abs(r, 1.0, 0);
+//
+//    img = cpl_image_load("/tmp/jtaylor/Cagliari_4.fits", CPL_TYPE_DOUBLE, 0, 0);
+//    r = compute_strehl(img, 1.635e-6, 5.08/2, 5.08/2*0.36, 0.0165966, 0.0165966);
+//    cpl_test_abs(r, 1.0, 0);
+//
+//    double d = 5.08 / 2.;
+//    img = cpl_image_load("/tmp/jtaylor/Firenze_4.fits", CPL_TYPE_DOUBLE, 0, 0);
+//    r = compute_strehl(img, 1.635e-6, d, d*0.36, 0.0165966, 0.0165966);
+//    cpl_test_abs(r, 1.0, 0);
+    
+
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ @brief   Unit tests of hdrl_image
+ **/
+/*----------------------------------------------------------------------------*/
+int main(int argc, char * argv[])
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+
+    hdrl_strehl_test_parlist();
+    hdrl_strehl_test_null_input();
+    hdrl_strehl_test_illegal_input();
+
+    test_psf();
+    test_strehl();
+    test_strehl_with_bkg();
+    test_strehl_data(argc, argv);
+
+    return cpl_test_end(0);
+}
diff --git a/hdrl/tests/hdrl_utils-test.c b/hdrl/tests/hdrl_utils-test.c
new file mode 100644
index 0000000..46a8111
--- /dev/null
+++ b/hdrl/tests/hdrl_utils-test.c
@@ -0,0 +1,629 @@
+/* $Id: hdrl_utils-test.c,v 1.11 2013-10-23 10:49:28 jtaylor Exp $
+ *
+ * This file is part of the HDRL
+ * Copyright (C) 2013 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-10-23 10:49:28 $
+ * $Revision: 1.11 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+                                    Includes
+ -----------------------------------------------------------------------------*/
+
+#include "hdrl_utils.h"
+#include "hdrl_collapse.h"
+#include <cpl.h>
+
+#include <math.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+#ifndef ARRAY_LEN
+#define ARRAY_LEN(a) sizeof((a))/sizeof((a)[0])
+#endif
+
+
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup hdrl_utils_test   Testing of the HDRL utility module
+ */
+/*----------------------------------------------------------------------------*/
+static cpl_error_code hdrl_image_to_vector_test(void)
+{
+
+    {
+        cpl_vector * v = hdrl_image_to_vector(NULL, NULL);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+        cpl_test_null(v);
+        v = hdrl_image_to_vector(NULL, (void*)1);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+        cpl_test_null(v);
+    }
+    {
+        cpl_image * img = cpl_image_new(5, 6, CPL_TYPE_INT);
+        cpl_vector * v = hdrl_image_to_vector(img, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_test_eq(cpl_vector_get_size(v), 5 * 6);
+        cpl_image_delete(img);
+        cpl_vector_delete(v);
+    }
+    /* empty result */
+    {
+        cpl_image * img = cpl_image_new(1, 1, CPL_TYPE_INT);
+        cpl_image_reject(img, 1, 1);
+        cpl_vector * v = hdrl_image_to_vector(img, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_test_null(v);
+        cpl_image_delete(img);
+    }
+    /* bad pixel in image bpm */
+    {
+        cpl_image * img = cpl_image_new(5, 6, CPL_TYPE_INT);
+        cpl_image_set(img, 3, 5, 100);
+        cpl_image_reject(img, 3, 5);
+        cpl_vector * v = hdrl_image_to_vector(img, NULL);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_test_eq(cpl_vector_get_size(v), 5 * 6 - 1);
+        cpl_test_eq(cpl_vector_get_sum(v), 0);
+        cpl_image_delete(img);
+        cpl_vector_delete(v);
+    }
+    /* bad pixel in external bpm */
+    {
+        cpl_image * img = cpl_image_new(5, 6, CPL_TYPE_INT);
+        cpl_mask * m = cpl_mask_new(5, 6);
+        cpl_image_set(img, 2, 5, 100);
+        cpl_image_set(img, 3, 5, 100);
+        cpl_mask_set(m, 3, 5, CPL_BINARY_1);
+        cpl_vector * v = hdrl_image_to_vector(img, m);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_test_eq(cpl_vector_get_size(v), 5 * 6 - 1);
+        cpl_test_eq(cpl_vector_get_sum(v), 100);
+        cpl_image_delete(img);
+        cpl_mask_delete(m);
+        cpl_vector_delete(v);
+    }
+    /* no cast bad pixel in external bpm */
+    {
+        cpl_image * img = cpl_image_new(5, 6, CPL_TYPE_DOUBLE);
+        cpl_mask * m = cpl_mask_new(5, 6);
+        cpl_image_set(img, 2, 5, 100.);
+        cpl_image_set(img, 3, 5, 100.);
+        cpl_mask_set(m, 3, 5, CPL_BINARY_1);
+        cpl_vector * v = hdrl_image_to_vector(img, m);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_test_eq(cpl_vector_get_size(v), 5 * 6 - 1);
+        cpl_test_eq(cpl_vector_get_sum(v), 100);
+        cpl_image_delete(img);
+        cpl_mask_delete(m);
+        cpl_vector_delete(v);
+    }
+    return cpl_error_get_code();
+}
+
+
+static cpl_error_code hdrl_imagelist_to_vector_test(void)
+{
+    {
+        cpl_imagelist * list = cpl_imagelist_new();
+        cpl_vector * v = hdrl_imagelist_to_vector(NULL, 1, 1);
+        cpl_test_error(CPL_ERROR_NULL_INPUT);
+        cpl_test_null(v);
+        v = hdrl_imagelist_to_vector(list, 1, 1);
+        cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+        cpl_test_null(v);
+        cpl_imagelist_set(list, cpl_image_new(5, 5, CPL_TYPE_INT), 0);
+        v = hdrl_imagelist_to_vector(list, 0, 0);
+        cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+        cpl_test_null(v);
+        v = hdrl_imagelist_to_vector(list, 0, 1);
+        cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+        cpl_test_null(v);
+        v = hdrl_imagelist_to_vector(list, 1, 0);
+        cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+        cpl_test_null(v);
+        v = hdrl_imagelist_to_vector(list, 10, 3);
+        cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+        cpl_test_null(v);
+        v = hdrl_imagelist_to_vector(list, 3, 10);
+        cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+        cpl_test_null(v);
+        v = hdrl_imagelist_to_vector(list, 10, 10);
+        cpl_test_error(CPL_ERROR_ACCESS_OUT_OF_RANGE);
+        cpl_test_null(v);
+        cpl_imagelist_delete(list);
+    }
+    {
+        cpl_imagelist * list = cpl_imagelist_new();
+        cpl_imagelist_set(list, cpl_image_new(5, 6, CPL_TYPE_INT), 0);
+        cpl_vector * v = hdrl_imagelist_to_vector(list, 1, 1);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_test_eq(cpl_vector_get_size(v), 1);
+        cpl_vector_delete(v);
+        cpl_imagelist_set(list, cpl_image_new(5, 6, CPL_TYPE_INT), 1);
+        v = hdrl_imagelist_to_vector(list, 1, 1);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_test_eq(cpl_vector_get_size(v), 2);
+        cpl_imagelist_delete(list);
+        cpl_vector_delete(v);
+    }
+    /* empty result */
+    {
+        cpl_imagelist * list = cpl_imagelist_new();
+        cpl_image * img = cpl_image_new(5, 6, CPL_TYPE_INT);
+        cpl_image_reject(img, 2, 1);
+        cpl_imagelist_set(list, img, 0);
+        cpl_imagelist_set(list, cpl_image_duplicate(img), 1);
+        cpl_vector * v = hdrl_imagelist_to_vector(list, 2, 1);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_test_null(v);
+        cpl_imagelist_delete(list);
+        cpl_vector_delete(v);
+    }
+    /* bad pixel in image bpm */
+    {
+        cpl_imagelist * list = cpl_imagelist_new();
+        cpl_image * img = cpl_image_new(5, 6, CPL_TYPE_INT);
+        cpl_image_set(img, 2, 1, 100);
+        cpl_imagelist_set(list, cpl_image_duplicate(img), 0);
+        cpl_imagelist_set(list, cpl_image_duplicate(img), 1);
+        cpl_image_reject(img, 2, 1);
+        cpl_imagelist_set(list, img, 2);
+        /* add a good image so potential uninitialized memory is included */
+        cpl_imagelist_set(list, cpl_image_new(5, 6, CPL_TYPE_INT), 3);
+        cpl_vector * v = hdrl_imagelist_to_vector(list, 2, 1);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_test_eq(cpl_vector_get_size(v), 3);
+        cpl_test_eq(cpl_vector_get_sum(v), 200);
+        cpl_imagelist_delete(list);
+        cpl_vector_delete(v);
+    }
+    /* no cast bad pixel in image bpm */
+    {
+        cpl_imagelist * list = cpl_imagelist_new();
+        cpl_image * img = cpl_image_new(5, 6, CPL_TYPE_DOUBLE);
+        cpl_image_add_scalar(img, 37);
+        cpl_image_set(img, 5, 6, 100);
+        cpl_imagelist_set(list, cpl_image_duplicate(img), 0);
+        cpl_imagelist_set(list, cpl_image_duplicate(img), 1);
+        cpl_image_reject(img, 5, 6);
+        cpl_imagelist_set(list, img, 2);
+        /* add a good image so potential uninitialized memory is included */
+        cpl_imagelist_set(list, cpl_image_new(5, 6, CPL_TYPE_DOUBLE), 3);
+        cpl_vector * v = hdrl_imagelist_to_vector(list, 5, 6);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_test_eq(cpl_vector_get_size(v), 3);
+        cpl_test_eq(cpl_vector_get_sum(v), 200);
+        cpl_imagelist_delete(list);
+        cpl_vector_delete(v);
+    }
+    /* no cast bad pixel in image bpm, full row test */
+    {
+        cpl_imagelist * list = cpl_imagelist_new();
+        cpl_image * img = cpl_image_new(5, 6, CPL_TYPE_DOUBLE);
+        cpl_image_add_scalar(img, 37);
+        cpl_image_set(img, 5, 6, 100);
+        cpl_imagelist_set(list, cpl_image_duplicate(img), 0);
+        cpl_imagelist_set(list, cpl_image_duplicate(img), 1);
+        cpl_image_reject(img, 5, 6);
+        cpl_imagelist_set(list, img, 2);
+        /* add a good image so potential uninitialized memory is included */
+        cpl_imagelist_set(list, cpl_image_new(5, 6, CPL_TYPE_DOUBLE), 3);
+        cpl_vector * o[5];
+        hdrl_imagelist_to_vector_row(list, 6, o);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_test_eq(cpl_vector_get_size(o[4]), 3);
+        cpl_test_eq(cpl_vector_get_sum(o[4]), 200);
+        cpl_imagelist_delete(list);
+        for (size_t i = 0; i < 5; i++) {
+            cpl_vector_delete(o[i]);
+        }
+    }
+    /* no cast bad pixel in image bpm, full row test non-double */
+    {
+        cpl_imagelist * list = cpl_imagelist_new();
+        cpl_image * img = cpl_image_new(5, 6, CPL_TYPE_INT);
+        cpl_image_add_scalar(img, 37);
+        cpl_image_set(img, 5, 6, 100);
+        cpl_imagelist_set(list, cpl_image_duplicate(img), 0);
+        cpl_imagelist_set(list, cpl_image_duplicate(img), 1);
+        cpl_image_reject(img, 5, 6);
+        cpl_imagelist_set(list, img, 2);
+        /* add a good image so potential uninitialized memory is included */
+        cpl_imagelist_set(list, cpl_image_new(5, 6, CPL_TYPE_INT), 3);
+        cpl_vector * o[5];
+        hdrl_imagelist_to_vector_row(list, 6, o);
+        cpl_test_error(CPL_ERROR_NONE);
+        cpl_test_eq(cpl_vector_get_size(o[4]), 3);
+        cpl_test_eq(cpl_vector_get_sum(o[4]), 200);
+        cpl_imagelist_delete(list);
+        for (size_t i = 0; i < 5; i++) {
+            cpl_vector_delete(o[i]);
+        }
+    }
+    return cpl_error_get_code();
+}
+
+
+static cpl_error_code hdrl_normalize_test(void)
+{
+    cpl_imagelist * data = cpl_imagelist_new();
+    cpl_imagelist * errs = cpl_imagelist_new();
+    cpl_vector * vnorm_d, * vnorm_e;
+    cpl_array * acontrib;
+
+    const size_t nz = 23;
+    const size_t nx = 41;
+    const size_t ny = 17;
+    for (size_t i = 0; i < nz; i++) {
+        cpl_image * img = cpl_image_new(nx, ny, HDRL_TYPE_DATA);
+        cpl_image_add_scalar(img, i + 1);
+        cpl_image * err = cpl_image_new(nx, ny, HDRL_TYPE_ERROR);
+        cpl_image_add_scalar(err, i + 1);
+        cpl_image_divide_scalar(err, 3.);
+        cpl_imagelist_set(data, img, i);
+        cpl_imagelist_set(errs, err, i);
+    }
+
+
+    hdrl_collapse_imagelist_to_vector_t * vmethod =
+        hdrl_collapse_imagelist_to_vector_mean();
+    hdrl_collapse_imagelist_to_vector_call(vmethod, data, errs,
+                                           &vnorm_d, &vnorm_e, &acontrib,
+                                           NULL);
+    cpl_array_delete(acontrib);
+
+    /* additive */
+    {
+        cpl_imagelist * ndata = cpl_imagelist_duplicate(data);
+        cpl_imagelist * nerrs = cpl_imagelist_duplicate(errs);
+        hdrl_normalize_imagelist_by_vector(vnorm_d, vnorm_e,
+                                           HDRL_SCALE_ADDITIVE,
+                                           ndata, nerrs);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_image_abs(cpl_imagelist_get_const(data, 0),
+                           cpl_imagelist_get_const(ndata, 0), HDRL_EPS_DATA);
+        cpl_test_image_abs(cpl_imagelist_get_const(errs, 0),
+                           cpl_imagelist_get_const(nerrs, 0), HDRL_EPS_ERROR);
+        for (size_t i = 1; i < nz; i++) {
+            cpl_image * expect_d = cpl_image_new(nx, ny, HDRL_TYPE_DATA);
+            cpl_image * expect_e = cpl_image_new(nx, ny, HDRL_TYPE_ERROR);
+            double escale = hypot(((i + 1) / 3.) / sqrt(nx * ny),
+                                  (1. / 3.) / sqrt(nx * ny));
+            cpl_image_add_scalar(expect_e, hypot(escale, (i + 1) / 3.));
+            cpl_image_add_scalar(expect_d, 1);
+            cpl_test_image_abs(expect_d, cpl_imagelist_get_const(ndata, i),
+                               HDRL_EPS_DATA);
+            cpl_test_image_abs(expect_e, cpl_imagelist_get_const(nerrs, i),
+                               HDRL_EPS_ERROR * 4);
+            cpl_image_delete(expect_d);
+            cpl_image_delete(expect_e);
+        }
+        cpl_imagelist_delete(ndata);
+        cpl_imagelist_delete(nerrs);
+    }
+
+    /* multiplicative */
+    {
+        cpl_imagelist * ndata = cpl_imagelist_duplicate(data);
+        cpl_imagelist * nerrs = cpl_imagelist_duplicate(errs);
+        hdrl_normalize_imagelist_by_vector(vnorm_d, vnorm_e,
+                                           HDRL_SCALE_MULTIPLICATIVE,
+                                           ndata, nerrs);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_image_abs(cpl_imagelist_get_const(data, 0),
+                           cpl_imagelist_get_const(ndata, 0), HDRL_EPS_DATA);
+        cpl_test_image_abs(cpl_imagelist_get_const(errs, 0),
+                           cpl_imagelist_get_const(nerrs, 0), HDRL_EPS_ERROR);
+        for (size_t i = 1; i < nz; i++) {
+            cpl_image * expect_d = cpl_image_new(nx, ny, HDRL_TYPE_DATA);
+            cpl_image * expect_e = cpl_image_new(nx, ny, HDRL_TYPE_ERROR);
+            /* off by about 10e-4 due to missing correlation */
+            cpl_image_add_scalar(expect_e, 0.3338112308308246);
+            cpl_image_add_scalar(expect_d, 1.);
+            cpl_test_image_abs(expect_d, cpl_imagelist_get_const(ndata, i),
+                               HDRL_EPS_DATA);
+            cpl_test_image_abs(expect_e, cpl_imagelist_get_const(nerrs, i),
+                               HDRL_EPS_ERROR * 4);
+            cpl_image_delete(expect_d);
+            cpl_image_delete(expect_e);
+        }
+        cpl_imagelist_delete(ndata);
+        cpl_imagelist_delete(nerrs);
+    }
+
+    cpl_imagelist_delete(data);
+    cpl_imagelist_delete(errs);
+    cpl_vector_delete(vnorm_d);
+    cpl_vector_delete(vnorm_e);
+    hdrl_collapse_imagelist_to_vector_delete(vmethod);
+
+    return cpl_error_get_code();
+}
+
+
+static cpl_error_code hdrl_normalize_image_test(void)
+{
+    cpl_imagelist * data = cpl_imagelist_new();
+    cpl_imagelist * errs = cpl_imagelist_new();
+    cpl_imagelist * vnorm_d = cpl_imagelist_new();
+    cpl_imagelist * vnorm_e = cpl_imagelist_new();
+    cpl_vector * vnorm_d_, * vnorm_e_;
+    cpl_array * acontrib;
+
+    const size_t nz = 23;
+    const size_t nx = 41;
+    const size_t ny = 17;
+    for (size_t i = 0; i < nz; i++) {
+        cpl_image * img = cpl_image_new(nx, ny, HDRL_TYPE_DATA);
+        cpl_image_add_scalar(img, i + 1);
+        cpl_image * err = cpl_image_new(nx, ny, HDRL_TYPE_ERROR);
+        cpl_image_add_scalar(err, i + 1);
+        cpl_image_divide_scalar(err, 3.);
+        cpl_imagelist_set(data, img, i);
+        cpl_imagelist_set(errs, err, i);
+    }
+
+
+    hdrl_collapse_imagelist_to_vector_t * vmethod =
+        hdrl_collapse_imagelist_to_vector_mean();
+    hdrl_collapse_imagelist_to_vector_call(vmethod, data, errs,
+                                           &vnorm_d_, &vnorm_e_, &acontrib,
+                                           NULL);
+    cpl_array_delete(acontrib);
+    for (cpl_size i = 0; i < cpl_vector_get_size(vnorm_d_); i++) {
+        cpl_image * dimg = cpl_image_new(nx, ny, HDRL_TYPE_DATA);
+        cpl_image * eimg = cpl_image_new(nx, ny, HDRL_TYPE_ERROR);
+        cpl_image_add_scalar(dimg, cpl_vector_get(vnorm_d_, i));
+        cpl_image_add_scalar(eimg, cpl_vector_get(vnorm_e_, i));
+        cpl_imagelist_set(vnorm_d, dimg, i);
+        cpl_imagelist_set(vnorm_e, eimg, i);
+    }
+    cpl_vector_delete(vnorm_d_);
+    cpl_vector_delete(vnorm_e_);
+
+    /* additive */
+    {
+        cpl_imagelist * ndata = cpl_imagelist_duplicate(data);
+        cpl_imagelist * nerrs = cpl_imagelist_duplicate(errs);
+        hdrl_normalize_imagelist_by_imagelist(vnorm_d, vnorm_e,
+                                              HDRL_SCALE_ADDITIVE,
+                                              ndata, nerrs);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_image_abs(cpl_imagelist_get_const(data, 0),
+                           cpl_imagelist_get_const(ndata, 0), HDRL_EPS_DATA);
+        cpl_test_image_abs(cpl_imagelist_get_const(errs, 0),
+                           cpl_imagelist_get_const(nerrs, 0), HDRL_EPS_ERROR);
+        for (size_t i = 1; i < nz; i++) {
+            cpl_image * expect_d = cpl_image_new(nx, ny, HDRL_TYPE_DATA);
+            cpl_image * expect_e = cpl_image_new(nx, ny, HDRL_TYPE_ERROR);
+            double escale = hypot(((i + 1) / 3.) / sqrt(nx * ny),
+                                  (1. / 3.) / sqrt(nx * ny));
+            cpl_image_add_scalar(expect_e, hypot(escale, (i + 1) / 3.));
+            cpl_image_add_scalar(expect_d, 1);
+            cpl_test_image_abs(expect_d, cpl_imagelist_get_const(ndata, i),
+                               HDRL_EPS_DATA);
+            cpl_test_image_abs(expect_e, cpl_imagelist_get_const(nerrs, i),
+                               HDRL_EPS_ERROR * 4);
+            cpl_image_delete(expect_d);
+            cpl_image_delete(expect_e);
+        }
+        cpl_imagelist_delete(ndata);
+        cpl_imagelist_delete(nerrs);
+    }
+
+    /* multiplicative */
+    {
+        cpl_imagelist * ndata = cpl_imagelist_duplicate(data);
+        cpl_imagelist * nerrs = cpl_imagelist_duplicate(errs);
+        hdrl_normalize_imagelist_by_imagelist(vnorm_d, vnorm_e,
+                                              HDRL_SCALE_MULTIPLICATIVE,
+                                              ndata, nerrs);
+        cpl_test_error(CPL_ERROR_NONE);
+
+        cpl_test_image_abs(cpl_imagelist_get_const(data, 0),
+                           cpl_imagelist_get_const(ndata, 0), HDRL_EPS_DATA);
+        cpl_test_image_abs(cpl_imagelist_get_const(errs, 0),
+                           cpl_imagelist_get_const(nerrs, 0), HDRL_EPS_ERROR);
+        for (size_t i = 1; i < nz; i++) {
+            cpl_image * expect_d = cpl_image_new(nx, ny, HDRL_TYPE_DATA);
+            cpl_image * expect_e = cpl_image_new(nx, ny, HDRL_TYPE_ERROR);
+            /* off by about 10e-4 due to missing correlation */
+            cpl_image_add_scalar(expect_e, 0.3338112308308246);
+            cpl_image_add_scalar(expect_d, 1.);
+            cpl_test_image_abs(expect_d, cpl_imagelist_get_const(ndata, i),
+                               HDRL_EPS_DATA);
+            cpl_test_image_abs(expect_e, cpl_imagelist_get_const(nerrs, i),
+                               HDRL_EPS_ERROR * 4);
+            cpl_image_delete(expect_d);
+            cpl_image_delete(expect_e);
+        }
+        cpl_imagelist_delete(ndata);
+        cpl_imagelist_delete(nerrs);
+    }
+
+    cpl_imagelist_delete(data);
+    cpl_imagelist_delete(errs);
+    cpl_imagelist_delete(vnorm_d);
+    cpl_imagelist_delete(vnorm_e);
+    hdrl_collapse_imagelist_to_vector_delete(vmethod);
+
+    return cpl_error_get_code();
+}
+
+
+/* path related smoke tests */
+void hdrl_path_test(void)
+{
+    char * cwd;
+    int fd;
+
+    cwd = hdrl_get_cwd();
+    cpl_test_nonnull(cwd);
+
+    fd = hdrl_get_tempfile(NULL, CPL_TRUE);
+    cpl_test(fd >= 0);
+    close(fd);
+
+    //fd = hdrl_get_tempfile(NULL, CPL_FALSE);
+    //cpl_test(fd >= 0);
+
+    fd = hdrl_get_tempfile(cwd, CPL_TRUE);
+    cpl_test(fd >= 0);
+
+    //fd = hdrl_get_tempfile(cwd, CPL_FALSE);
+    //cpl_test(fd >= 0);
+
+    cpl_free(cwd);
+}
+
+void hdrl_string_test(void)
+{
+    char * s;
+    s = hdrl_join_string(NULL, 0, "test");
+    cpl_test_null(s);
+    cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
+
+    s = hdrl_join_string(NULL, 1, "test");
+    cpl_test(strcmp(s, "test") == 0);
+    cpl_free(s);
+
+    s = hdrl_join_string(NULL, 2, "test", "bla");
+    cpl_test(strcmp(s, "testbla") == 0);
+    cpl_free(s);
+
+    s = hdrl_join_string(".", 1, "test");
+    cpl_test(strcmp(s, "test") == 0);
+    cpl_free(s);
+
+    s = hdrl_join_string(".", 2, "test", "bla");
+    cpl_test(strcmp(s, "test.bla") == 0);
+    cpl_free(s);
+
+    s = hdrl_join_string("--", 3, "test", "bla", "val");
+    cpl_test(strcmp(s, "test--bla--val") == 0);
+    cpl_free(s);
+
+    s = hdrl_join_string("--", 3, "", "bla", "val");
+    cpl_test(strcmp(s, "bla--val") == 0);
+    cpl_free(s);
+
+    s = hdrl_join_string("--", 3, "test", "", "val");
+    cpl_test(strcmp(s, "test--val") == 0);
+    cpl_free(s);
+
+    s = hdrl_join_string(",", 3, "test", NULL, "val");
+    cpl_test(strcmp(s, "test,val") == 0);
+    cpl_free(s);
+
+    s = hdrl_join_string("--", 4, "", NULL, "val", "test");
+    cpl_test(strcmp(s, "val--test") == 0);
+    cpl_free(s);
+
+    s = hdrl_join_string("--", 3, NULL, "bla", "val");
+    cpl_test(strcmp(s, "bla--val") == 0);
+    cpl_free(s);
+
+    s = hdrl_join_string("--", 3, "test", "bla", "");
+    cpl_test(strcmp(s, "test--bla") == 0);
+    cpl_free(s);
+
+    s = hdrl_join_string("--", 3, "test", "bla", NULL);
+    cpl_test(strcmp(s, "test--bla") == 0);
+    cpl_free(s);
+}
+
+
+void hdrl_pfilter_test(void)
+{
+    size_t nx = 100;
+    size_t any[] = {13, 22, 47, 100, 103, 104, 202, 203, 204,
+                    542, 1034, 1239};
+    size_t am[] = {3, 5, 7, 13};
+    for (size_t j = 0; j < ARRAY_LEN(am); j++) {
+        cpl_mask * m = cpl_mask_new(am[j], am[j]);
+        cpl_matrix * k = cpl_matrix_new(am[j], am[j]);
+        cpl_mask_not(m);
+        cpl_matrix_add_scalar(k, 1);
+        for (size_t i = 0; i < ARRAY_LEN(any); i++) {
+            size_t ny = any[i];
+            cpl_msg_info(cpl_func, "Testing ny %zu mask %zu", ny, am[j]);
+            cpl_image * img = cpl_image_new(nx, ny, CPL_TYPE_DOUBLE);
+            double * d = cpl_image_get_data_double(img);
+            for (size_t kindex = 0; kindex < nx * ny; kindex++) {
+                d[kindex] = kindex + rand() % 100;
+                if (i % 2 == 0 && ((int)d[kindex] % 20) == 0) {
+                    cpl_image_reject(img, (rand() % nx) + 1, (rand() % ny) + 1);
+                }
+            }
+            cpl_image * orig_inp = cpl_image_duplicate(img);
+            cpl_image * ro = cpl_image_duplicate(img);
+            cpl_image * rp;
+            cpl_image_filter_mask(ro, img, m, CPL_FILTER_MEDIAN, CPL_BORDER_FILTER);
+            rp = hdrl_parallel_filter_image(img, NULL, m, CPL_FILTER_MEDIAN);
+            cpl_test_image_abs(rp, ro, 0);
+            /* input unchanged */
+            cpl_test_image_abs(img, orig_inp, 0);
+            cpl_image_delete(rp);
+
+            cpl_image_filter(ro, img, k, CPL_FILTER_LINEAR, CPL_BORDER_FILTER);
+            rp = hdrl_parallel_filter_image(img, k, NULL, CPL_FILTER_LINEAR);
+            cpl_test_image_abs(rp, ro, 0);
+            /* input unchanged */
+            cpl_test_image_abs(img, orig_inp, 0);
+            cpl_image_delete(rp);
+            cpl_image_delete(ro);
+            cpl_image_delete(img);
+            cpl_image_delete(orig_inp);
+        }
+        cpl_mask_delete(m);
+        cpl_matrix_delete(k);
+    }
+}
+
+/*----------------------------------------------------------------------------*/
+/**
+ @brief   Unit tests of utility module
+ **/
+/*----------------------------------------------------------------------------*/
+int main(void)
+{
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+
+    hdrl_image_to_vector_test();
+    hdrl_imagelist_to_vector_test();
+    hdrl_normalize_test();
+    hdrl_normalize_image_test();
+    hdrl_path_test();
+    hdrl_string_test();
+    hdrl_pfilter_test();
+
+    return cpl_test_end(0);
+}
diff --git a/irplib/Makefile.in b/irplib/Makefile.in
index 7a84366..f29d3ca 100644
--- a/irplib/Makefile.in
+++ b/irplib/Makefile.in
@@ -87,6 +87,7 @@ DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps = $(top_srcdir)/m4macros/cpl.m4 \
 	$(top_srcdir)/m4macros/eso.m4 $(top_srcdir)/m4macros/gsl.m4 \
+	$(top_srcdir)/m4macros/hdrl.m4 \
 	$(top_srcdir)/m4macros/libtool.m4 \
 	$(top_srcdir)/m4macros/ltoptions.m4 \
 	$(top_srcdir)/m4macros/ltsugar.m4 \
@@ -287,6 +288,10 @@ GREP = @GREP@
 GSL_INCLUDES = @GSL_INCLUDES@
 GSL_LDFLAGS = @GSL_LDFLAGS@
 GSL_LIBS = @GSL_LIBS@
+HDRL_INCLUDES = @HDRL_INCLUDES@
+HDRL_INTERNAL_CFLAGS = @HDRL_INTERNAL_CFLAGS@
+HDRL_LDFLAGS = @HDRL_LDFLAGS@
+HDRL_LIBS = @HDRL_LIBS@
 INSTALL = @INSTALL@
 INSTALL_DATA = @INSTALL_DATA@
 INSTALL_PROGRAM = @INSTALL_PROGRAM@
@@ -304,6 +309,7 @@ LIBCPLCORE = @LIBCPLCORE@
 LIBCPLDFS = @LIBCPLDFS@
 LIBCPLDRS = @LIBCPLDRS@
 LIBCPLUI = @LIBCPLUI@
+LIBHDRL = @LIBHDRL@
 LIBIRPLIB = @LIBIRPLIB@
 LIBLAPACK = @LIBLAPACK@
 LIBOBJS = @LIBOBJS@
@@ -406,6 +412,7 @@ psdir = @psdir@
 sbindir = @sbindir@
 sharedstatedir = @sharedstatedir@
 srcdir = @srcdir@
+subdirs = @subdirs@
 sysconfdir = @sysconfdir@
 target = @target@
 target_alias = @target_alias@
diff --git a/irplib/irplib_framelist.c b/irplib/irplib_framelist.c
index d01dbb9..dd600f0 100644
--- a/irplib/irplib_framelist.c
+++ b/irplib/irplib_framelist.c
@@ -620,7 +620,7 @@ cpl_error_code irplib_framelist_load_propertylist(irplib_framelist * self,
   @param    invert Boolean to invert the sense of the pattern matching.
   @return   CPL_ERROR_NONE or the relevant CPL error code
   @see      irplib_framelist_load_propertylist()
-  @note     Use a regexp of "" to load all properties. If a frame already has
+  @note     Use a regexp of ".?" to load all properties. If a frame already has
             a propertylist, it is not modified (and no propertylist is loaded
             for that frame).
 
diff --git a/irplib/irplib_mkmaster.c b/irplib/irplib_mkmaster.c
index 3e5fa72..c0054ba 100644
--- a/irplib/irplib_mkmaster.c
+++ b/irplib/irplib_mkmaster.c
@@ -387,7 +387,7 @@ irplib_mkmaster_dark_qc(const cpl_imagelist* raw_images,
    cpl_ensure_code(parameters !=NULL, CPL_ERROR_NULL_INPUT);
 
   if (pr_num_x != 0 && pr_num_y != 0 && pr_box_sx != 0 && pr_box_sy != 0) {
-    int i = 0;
+    int i;
     for (i = 0; i < cpl_imagelist_get_size(raw_images); i++) {
       cpl_image* current_dark = cpl_image_duplicate(
           cpl_imagelist_get_const(preproc_images, i));
diff --git a/irplib/irplib_plugin.c b/irplib/irplib_plugin.c
index d0f072f..6bbdb40 100644
--- a/irplib/irplib_plugin.c
+++ b/irplib/irplib_plugin.c
@@ -126,19 +126,21 @@ const char * irplib_parameterlist_get_string(const cpl_parameterlist * self,
                                              const char * recipe,
                                              const char * parameter)
 {
-
     const cpl_parameter * par = irplib_parameterlist_get(self, instrume,
                                                          recipe, parameter);
-    const char * value;
 
-    cpl_ensure(par != NULL, cpl_error_get_code(), NULL);
+    if (par == NULL) {
 
-    value = cpl_parameter_get_string(par);
+        (void)cpl_error_set_where(cpl_func);
 
-    if (value == NULL) (void)cpl_error_set_where(cpl_func);
+        return NULL;
+    } else {
+        const char * value = cpl_parameter_get_string(par);
 
-    return value;
+        if (value == NULL) (void)cpl_error_set_where(cpl_func);
 
+        return value;
+    }
 }
 
 /*----------------------------------------------------------------------------*/
@@ -157,21 +159,23 @@ cpl_boolean irplib_parameterlist_get_bool(const cpl_parameterlist * self,
                                           const char * recipe,
                                           const char * parameter)
 {
-
     const cpl_parameter * par = irplib_parameterlist_get(self, instrume,
                                                          recipe, parameter);
-    cpl_errorstate        prestate = cpl_errorstate_get();
-    cpl_boolean           value;
 
+    if (par == NULL) {
 
-    cpl_ensure(par != NULL, cpl_error_get_code(), CPL_FALSE);
+        (void)cpl_error_set_where(cpl_func);
 
-    value = cpl_parameter_get_bool(par);
-
-    if (!cpl_errorstate_is_equal(prestate)) (void)cpl_error_set_where(cpl_func);
+        return CPL_FALSE;
+    } else {
+        cpl_errorstate    prestate = cpl_errorstate_get();
+        const cpl_boolean value    = cpl_parameter_get_bool(par);
 
-    return value;
+        if (!cpl_errorstate_is_equal(prestate))
+            (void)cpl_error_set_where(cpl_func);
 
+        return value;
+    }
 }
 
 
@@ -191,20 +195,23 @@ int irplib_parameterlist_get_int(const cpl_parameterlist * self,
                                  const char * recipe,
                                  const char * parameter)
 {
-
     const cpl_parameter * par = irplib_parameterlist_get(self, instrume,
                                                          recipe, parameter);
-    cpl_errorstate        prestate = cpl_errorstate_get();
-    int                   value;
 
+    if (par == NULL) {
 
-    cpl_ensure(par != NULL, cpl_error_get_code(), 0);
+        (void)cpl_error_set_where(cpl_func);
 
-    value = cpl_parameter_get_int(par);
+        return 0;
+    } else {
+        cpl_errorstate prestate = cpl_errorstate_get();
+        const int      value    = cpl_parameter_get_int(par);
 
-    if (!cpl_errorstate_is_equal(prestate)) (void)cpl_error_set_where(cpl_func);
+        if (!cpl_errorstate_is_equal(prestate))
+            (void)cpl_error_set_where(cpl_func);
 
-    return value;
+        return value;
+    }
 }
 
 /*----------------------------------------------------------------------------*/
@@ -223,20 +230,23 @@ double irplib_parameterlist_get_double(const cpl_parameterlist * self,
                                        const char * recipe,
                                        const char * parameter)
 {
-
     const cpl_parameter * par = irplib_parameterlist_get(self, instrume,
                                                          recipe, parameter);
-    cpl_errorstate        prestate = cpl_errorstate_get();
-    double                value;
 
+    if (par == NULL) {
 
-    cpl_ensure(par != NULL, cpl_error_get_code(), 0.0);
+        (void)cpl_error_set_where(cpl_func);
 
-    value = cpl_parameter_get_double(par);
+        return 0.0;
+    } else {
+        cpl_errorstate prestate = cpl_errorstate_get();
+        const double   value    = cpl_parameter_get_double(par);
 
-    if (!cpl_errorstate_is_equal(prestate)) (void)cpl_error_set_where(cpl_func);
+        if (!cpl_errorstate_is_equal(prestate))
+            (void)cpl_error_set_where(cpl_func);
 
-    return value;
+        return value;
+    }
 }
 
 /*----------------------------------------------------------------------------*/
diff --git a/irplib/irplib_ppm.c b/irplib/irplib_ppm.c
index 9c4a090..615f663 100644
--- a/irplib/irplib_ppm.c
+++ b/irplib/irplib_ppm.c
@@ -1,7 +1,6 @@
-/* $Id: irplib_ppm.c,v 1.31 2012-06-11 07:24:09 llundin Exp $
- *
+/*
  * This file is part of the irplib package
- * Copyright (C) 2002,2003 European Southern Observatory
+ * Copyright (C) 2002,2003,2014 European Southern Observatory
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -18,13 +17,6 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
  */
 
-/*
- * $Author: llundin $
- * $Date: 2012-06-11 07:24:09 $
- * $Revision: 1.31 $
- * $Name: not supported by cvs2svn $
- */
-
 #ifdef HAVE_CONFIG_H
 #include <config.h>
 #endif
@@ -33,19 +25,12 @@
                                    Includes
  -----------------------------------------------------------------------------*/
 
-#include <math.h>
-#include <cpl.h>
-
 #include "irplib_ppm.h"
 #include "irplib_wlxcorr.h"
 #include "irplib_spectrum.h"
 
-/* TEMPORARY SUPPORT OF CPL 5.x */
-#ifndef CPL_SIZE_FORMAT
-#define CPL_SIZE_FORMAT "d"
-#define cpl_size int
-#endif
-/* END TEMPORARY SUPPORT OF CPL 5.x */
+#include <math.h>
+#include <cpl.h>
 
 /*-----------------------------------------------------------------------------
                                    Private functions
diff --git a/irplib/irplib_sdp_spectrum.c b/irplib/irplib_sdp_spectrum.c
index 7f7b603..78d873b 100644
--- a/irplib/irplib_sdp_spectrum.c
+++ b/irplib/irplib_sdp_spectrum.c
@@ -128,11 +128,11 @@ cpl_error_set_regex_macro(const char *, cpl_error_code, int,
 #define KEY_LAMRMS              "LAMRMS"
 #define KEY_LAMRMS_COMMENT      "[nm] RMS of the residuals of the wavel. solution"
 #define KEY_GAIN                "GAIN"
-#define KEY_GAIN_COMMENT        "[e-/ADU] Conversion factor in electrons per data unit"
+#define KEY_GAIN_COMMENT        "Conversion factor (e-/ADU) electrons per data unit"
 #define KEY_DETRON              "DETRON"
-#define KEY_DETRON_COMMENT      "[e-] Readout noise per output"
+#define KEY_DETRON_COMMENT      "Readout noise per output (e-)"
 #define KEY_EFFRON              "EFFRON"
-#define KEY_EFFRON_COMMENT      "[e-] Median effective readout noise"
+#define KEY_EFFRON_COMMENT      "Median effective readout noise (e-)"
 #define KEY_SNR                 "SNR"
 #define KEY_SNR_COMMENT         "Median signal to noise ratio per order"
 #define KEY_NCOMBINE            "NCOMBINE"
@@ -1807,10 +1807,10 @@ irplib_sdp_spectrum_add_column(irplib_sdp_spectrum *self, const char *name,
   /* Setup a new array cell column and fill its properties (possibly with
    * defaults). */
   error = cpl_table_new_column_array(self->table, name, type, self->nelem);
-  if (unit != NULL) {
+  if (unit != NULL && *unit != '\0') {
     error |= cpl_table_set_column_unit(self->table, name, unit);
   } else {
-    error |= cpl_table_set_column_unit(self->table, name, "");
+    error |= cpl_table_set_column_unit(self->table, name, " ");
   }
   if (format != NULL) {
     error |= cpl_table_set_column_format(self->table, name, format);
@@ -2019,9 +2019,14 @@ irplib_sdp_spectrum_update_column(irplib_sdp_spectrum *self, const char *name,
   /* Update the unit and format values if requested. Note, we copy the original
    * value to be able to restore it if an error occurs. */
   if (flags & IRPLIB_COLUMN_UNIT) {
+    const char* unit = cpl_table_get_column_unit(table, colname);
+    /* Prevent completely empty strings else cfitsio silently deletes the
+     * keyword. */
+    if (unit != NULL && *unit == '\0') {
+      unit = " ";
+    }
     orig_unit = cpl_strdup(cpl_table_get_column_unit(self->table, name));
-    cpl_table_set_column_unit(self->table, name,
-                              cpl_table_get_column_unit(table, colname));
+    cpl_table_set_column_unit(self->table, name, unit);
     if (! cpl_errorstate_is_equal(prestate)) goto cleanup;
   }
   if (flags & IRPLIB_COLUMN_FORMAT) {
@@ -2093,13 +2098,33 @@ irplib_sdp_spectrum_get_column_unit(const irplib_sdp_spectrum *self,
   return cpl_table_get_column_unit(self->table, name);
 }
 
-
+/*----------------------------------------------------------------------------*/
+/**
+ * @brief Set the physical units for a column.
+ * @param self The spectrum object to update.
+ * @param name The name of the column to update.
+ * @param unit The string indicating the physical units for the column.
+ * @return @c CPL_ERROR_NONE on success or an appropriate error code otherwise.
+ *
+ * This function will set the string indicating the physical units for the
+ * column named  by @c name. Valid values for @c unit is @a NULL or a string
+ * with at least one character. Empty strings will be implicitly converted to a
+ * string with a single space character since CFITSIO does not allow empty
+ * strings for the @a TUNIT keywords. If any error occurs then a error code is
+ * set and returned, otherwise @c CPL_ERROR_NONE is returned on success.
+ */
+/*----------------------------------------------------------------------------*/
 cpl_error_code
 irplib_sdp_spectrum_set_column_unit(irplib_sdp_spectrum *self,
                                     const char *name, const char *unit)
 {
   cpl_ensure_code(self != NULL, CPL_ERROR_NULL_INPUT);
   assert(self->table != NULL);
+  /* Prevent completely empty strings else cfitsio silently deletes the
+   * keyword. */
+  if (unit != NULL && *unit == '\0') {
+    unit = " ";
+  }
   return cpl_table_set_column_unit(self->table, name, unit);
 }
 
@@ -2118,6 +2143,11 @@ irplib_sdp_spectrum_copy_column_unit(irplib_sdp_spectrum *self,
     cpl_errorstate prestate = cpl_errorstate_get();
     const char *value = cpl_propertylist_get_string(plist, key);
     if (cpl_errorstate_is_equal(prestate)) {
+      /* Prevent completely empty strings else cfitsio silently deletes the
+       * keyword. */
+      if (value != NULL && *value == '\0') {
+        value = " ";
+      }
       return cpl_table_set_column_unit(self->table, name, value);
     } else {
       return cpl_error_set_message(cpl_func, cpl_error_get_code(),
diff --git a/irplib/irplib_slitpos.c b/irplib/irplib_slitpos.c
index 346a02a..19db1ff 100644
--- a/irplib/irplib_slitpos.c
+++ b/irplib/irplib_slitpos.c
@@ -1,7 +1,6 @@
-/* $Id: irplib_slitpos.c,v 1.31 2013-07-04 12:10:12 jtaylor Exp $
- *
+/*
  * This file is part of the irplib package
- * Copyright (C) 2002,2003 European Southern Observatory
+ * Copyright (C) 2002,2003,2014 European Southern Observatory
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -18,13 +17,6 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
  */
 
-/*
- * $Author: jtaylor $
- * $Date: 2013-07-04 12:10:12 $
- * $Revision: 1.31 $
- * $Name: not supported by cvs2svn $
- */
-
 #ifdef HAVE_CONFIG_H
 #include <config.h>
 #endif
@@ -41,25 +33,19 @@
                                 Includes
  -----------------------------------------------------------------------------*/
 
+#include "irplib_slitpos.h"
+#include "irplib_flat.h"
+
+#include <cpl.h>
+
 #include <string.h>
 #include <math.h>
 #include <assert.h>
-#include <cpl.h>
-
-#include "irplib_slitpos.h"
-#include "irplib_flat.h"
 
 /*-----------------------------------------------------------------------------
                                 Defines
  -----------------------------------------------------------------------------*/
 
-/* TEMPORARY SUPPORT OF CPL 5.x */
-#ifndef CPL_SIZE_FORMAT
-#define CPL_SIZE_FORMAT "d"
-#define cpl_size int
-#endif
-/* END TEMPORARY SUPPORT OF CPL 5.x */
-
 #ifndef IRPLIB_SLITPOS_KERNEL_SIZE_Y
 #define IRPLIB_SLITPOS_KERNEL_SIZE_Y      5
 #endif
diff --git a/irplib/irplib_spectrum.c b/irplib/irplib_spectrum.c
index f5afa51..a330083 100644
--- a/irplib/irplib_spectrum.c
+++ b/irplib/irplib_spectrum.c
@@ -1,7 +1,6 @@
-/* $Id: irplib_spectrum.c,v 1.29 2012-01-12 11:50:41 llundin Exp $
- *
+/*
  * This file is part of the irplib package
- * Copyright (C) 2002,2003 European Southern Observatory
+ * Copyright (C) 2002,2003,2014 European Southern Observatory
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -18,13 +17,6 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
  */
 
-/*
- * $Author: llundin $
- * $Date: 2012-01-12 11:50:41 $
- * $Revision: 1.29 $
- * $Name: not supported by cvs2svn $
- */
-
 #ifdef HAVE_CONFIG_H
 #include <config.h>
 #endif
@@ -33,24 +25,17 @@
                                 Includes
  -----------------------------------------------------------------------------*/
 
+#include "irplib_wlxcorr.h"
+#include "irplib_spectrum.h"
+
 #include <math.h>
 #include <float.h>
 #include <cpl.h>
 
-#include "irplib_wlxcorr.h"
-#include "irplib_spectrum.h"
-
 /*-----------------------------------------------------------------------------
                                    Define
  -----------------------------------------------------------------------------*/
 
-/* TEMPORARY SUPPORT OF CPL 5.x */
-#ifndef CPL_SIZE_FORMAT
-#define CPL_SIZE_FORMAT "d"
-#define cpl_size int
-#endif
-/* END TEMPORARY SUPPORT OF CPL 5.x */
-
 #define SPECTRUM_HW                     16
 #define MIN_THRESH_FACT                 0.9
 #define MAX_THRESH_FACT                 1.1
diff --git a/irplib/irplib_strehl.c b/irplib/irplib_strehl.c
index 5a88c34..b436245 100644
--- a/irplib/irplib_strehl.c
+++ b/irplib/irplib_strehl.c
@@ -349,9 +349,9 @@ double irplib_strehl_disk_flux(const cpl_image * im,
     cpl_ensure(im != NULL, CPL_ERROR_NULL_INPUT, 0.0);
     cpl_ensure(rad > 0.0, CPL_ERROR_ILLEGAL_INPUT, 0.0);
 
-    for (j = IRPLIB_MAX(ly, 0); j < IRPLIB_MIN(uy, ny-1); j++) {
+    for (j = IRPLIB_MAX(ly, 0); j < IRPLIB_MIN(uy, ny); j++) {
         const double yj = (double)j - ypos;
-        for (i = IRPLIB_MAX(lx, 0); i < IRPLIB_MIN(ux, nx-1); i++) {
+        for (i = IRPLIB_MAX(lx, 0); i < IRPLIB_MIN(ux, nx); i++) {
             const double xi   = (double)i - xpos;
             const double dist = yj * yj + xi * xi;
             if (dist <= sqr) {
@@ -422,9 +422,9 @@ double irplib_strehl_ring_background(const cpl_image *       im,
     /* Count number of pixels in the ring */
     /* Retrieve all pixels which belong to the ring */
     npix = 0;
-    for (j = IRPLIB_MAX(ly, 0); j < IRPLIB_MIN(uy, ny-1); j++) {
+    for (j = IRPLIB_MAX(ly, 0); j < IRPLIB_MIN(uy, ny); j++) {
         const double yj = (double)j - ypos;
-        for (i = IRPLIB_MAX(lx, 0); i < IRPLIB_MIN(ux, nx-1); i++) {
+        for (i = IRPLIB_MAX(lx, 0); i < IRPLIB_MIN(ux, nx); i++) {
             const double xi   = (double)i - xpos;
             const double dist = yj * yj + xi * xi;
             if (sqr_int <= dist && dist <= sqr_ext) {
@@ -758,9 +758,9 @@ cpl_error_code irplib_strehl_disk_max(const cpl_image * self,
     cpl_ensure_code(radius > 0.0,  CPL_ERROR_ILLEGAL_INPUT);
 
 
-    for (j = IRPLIB_MAX(ly, 0); j < IRPLIB_MIN(uy, ny-1); j++) {
+    for (j = IRPLIB_MAX(ly, 0); j < IRPLIB_MIN(uy, ny); j++) {
         const double yj = (double)j - ypos;
-        for (i = IRPLIB_MAX(lx, 0); i < IRPLIB_MIN(ux, nx-1); i++) {
+        for (i = IRPLIB_MAX(lx, 0); i < IRPLIB_MIN(ux, nx); i++) {
             const double xi   = (double)i - xpos;
             const double dist = yj * yj + xi * xi;
             if (dist <= sqr) {
diff --git a/irplib/irplib_utils.c b/irplib/irplib_utils.c
index 51ca123..4b7525d 100644
--- a/irplib/irplib_utils.c
+++ b/irplib/irplib_utils.c
@@ -1,7 +1,6 @@
-/* $Id: irplib_utils.c,v 1.85 2013-07-04 12:10:55 jtaylor Exp $
- *
+/*
  * This file is part of the irplib package
- * Copyright (C) 2002,2003 European Southern Observatory
+ * Copyright (C) 2002,2003,2014 European Southern Observatory
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -18,13 +17,6 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
  */
 
-/*
- * $Author: jtaylor $
- * $Date: 2013-07-04 12:10:55 $
- * $Revision: 1.85 $
- * $Name: not supported by cvs2svn $
- */
-
 #ifdef HAVE_CONFIG_H
 #include <config.h>
 #endif
@@ -34,27 +26,18 @@
  -----------------------------------------------------------------------------*/
 #include "irplib_utils.h"
 
-#include <cpl.h>
-#include <math.h>
-
 #include <string.h>
 #include <assert.h>
 #include <stdlib.h>
 #include <errno.h>
 
-
+#include <cpl.h>
+#include <math.h>
 
 /*-----------------------------------------------------------------------------
                            Defines
  -----------------------------------------------------------------------------*/
 
-/* TEMPORARY SUPPORT OF CPL 5.x */
-#ifndef CPL_SIZE_FORMAT
-#define CPL_SIZE_FORMAT "d"
-#define cpl_size int
-#endif
-/* END TEMPORARY SUPPORT OF CPL 5.x */
-
 #ifndef inline
 #define inline /* inline */
 #endif
@@ -1535,11 +1518,10 @@ static void quicksort(int* iindex, double* exptime, int left, int right)
 }
 cpl_error_code irplib_frameset_sort(const cpl_frameset *  self, int* iindex, double* exptime)
 {
-	int sz = 0;
 	int i = 0;
 	const cpl_frame* tmp_frame = 0;
 	cpl_error_code error = CPL_ERROR_NONE;
-	sz = cpl_frameset_get_size(self);
+	int sz = cpl_frameset_get_size(self);
 	cpl_frameset_iterator* iterator = NULL;
 
 	/* 1. get an array of frames */
@@ -1594,51 +1576,61 @@ static double frame_get_exptime(const cpl_frame * pframe)
 /*----------------------------------------------------------------------------*/
 void * irplib_aligned_malloc(size_t alignment, size_t size)
 {
-#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 201112L
-    return aligned_alloc(alignment, size);
-#elif defined HAVE_POSIX_MEMALIGN && defined HAVE_DECL_POSIX_MEMALIGN
-    void *ptr;
-    if (alignment == 1)
-        return malloc (size);
-    if (alignment == 2 || (sizeof (void *) == 8 && alignment == 4))
-        alignment = sizeof (void *);
-    if (posix_memalign (&ptr, alignment, size) == 0)
-        return ptr;
-    else
-        return NULL;
-#else
-    /* copied from gmm_malloc.h in gcc-4.8 */
-    void * malloc_ptr;
-    void * aligned_ptr;
-
+    if (alignment == 0)
+        alignment = 1;
     /* Error if align is not a power of two.  */
     if (alignment & (alignment - 1)) {
         errno = EINVAL;
         return NULL;
     }
+    /* make size a multiple of alignment (required by C11) */
+    if ((size % alignment) != 0) {
+        size += alignment - (size % alignment);
+    }
 
-    if (size == 0)
-        return NULL;
+#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 201112L
+    return aligned_alloc(alignment, size);
+#elif defined HAVE_POSIX_MEMALIGN && defined HAVE_DECL_POSIX_MEMALIGN
+    {
+        void *ptr;
+        if (alignment == 1)
+            return malloc (size);
+        if (alignment == 2 || (sizeof (void *) == 8 && alignment == 4))
+            alignment = sizeof (void *);
+        if (posix_memalign (&ptr, alignment, size) == 0)
+            return ptr;
+        else
+            return NULL;
+    }
+#else
+    /* copied from gmm_malloc.h in gcc-4.8 */
+    {
+        void * malloc_ptr;
+        void * aligned_ptr;
 
-    /* Assume malloc'd pointer is aligned at least to sizeof (void*).
-       If necessary, add another sizeof (void*) to store the value
-       returned by malloc. Effectively this enforces a minimum alignment
-       of sizeof double. */
-    if (alignment < 2 * sizeof (void *))
-        alignment = 2 * sizeof (void *);
+        if (size == 0)
+            return NULL;
 
-    malloc_ptr = malloc (size + alignment);
-    if (!malloc_ptr)
-        return NULL;
+        /* Assume malloc'd pointer is aligned at least to sizeof (void*).
+           If necessary, add another sizeof (void*) to store the value
+           returned by malloc. Effectively this enforces a minimum alignment
+           of sizeof double. */
+        if (alignment < 2 * sizeof (void *))
+            alignment = 2 * sizeof (void *);
 
-    /* Align  We have at least sizeof (void *) space below malloc'd ptr. */
-    aligned_ptr = (void *) (((size_t) malloc_ptr + alignment)
-                            & ~((size_t) (alignment) - 1));
+        malloc_ptr = malloc (size + alignment);
+        if (!malloc_ptr)
+            return NULL;
 
-    /* Store the original pointer just before p.  */
-    *(((void **) aligned_ptr) - 1) = malloc_ptr;
+        /* Align  We have at least sizeof (void *) space below malloc'd ptr. */
+        aligned_ptr = (void *) (((size_t) malloc_ptr + alignment)
+                                & ~((size_t) (alignment) - 1));
 
-    return aligned_ptr;
+        /* Store the original pointer just before p.  */
+        *(((void **) aligned_ptr) - 1) = malloc_ptr;
+
+        return aligned_ptr;
+    }
 #endif
 }
 
diff --git a/irplib/irplib_wavecal.c b/irplib/irplib_wavecal.c
index a9f2314..8c23224 100644
--- a/irplib/irplib_wavecal.c
+++ b/irplib/irplib_wavecal.c
@@ -1,7 +1,6 @@
-/* $Id: irplib_wavecal.c,v 1.52 2012-08-03 21:05:32 llundin Exp $
- *
+/*
  * This file is part of the IRPLIB Pipeline
- * Copyright (C) 2002,2003 European Southern Observatory
+ * Copyright (C) 2002,2003,2014 European Southern Observatory
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -18,13 +17,6 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
  */
 
-/*
- * $Author: llundin $
- * $Date: 2012-08-03 21:05:32 $
- * $Revision: 1.52 $
- * $Name: not supported by cvs2svn $
- */
-
 #ifdef HAVE_CONFIG_H
 #include <config.h>
 #endif
@@ -33,20 +25,13 @@
                                    Includes
  -----------------------------------------------------------------------------*/
 
-/* TEMPORARY SUPPORT OF CPL 5.x */
-#include <cpl.h>
-
-#ifndef CPL_SIZE_FORMAT
-#define CPL_SIZE_FORMAT "d"
-#define cpl_size int
-#endif
-/* END TEMPORARY SUPPORT OF CPL 5.x */
-
 #include "irplib_wavecal_impl.h"
 
 /* Needed for irplib_errorstate_dump_debug() */
 #include "irplib_utils.h"
 
+#include <cpl.h>
+
 #include <string.h>
 #include <math.h>
 
diff --git a/irplib/irplib_wlxcorr.c b/irplib/irplib_wlxcorr.c
index 6c86650..d15bc41 100644
--- a/irplib/irplib_wlxcorr.c
+++ b/irplib/irplib_wlxcorr.c
@@ -1,7 +1,6 @@
-/* $Id: irplib_wlxcorr.c,v 1.58 2013-01-29 08:43:33 jtaylor Exp $
- *
+/*
  * This file is part of the IRPLIB package
- * Copyright (C) 2002,2003 European Southern Observatory
+ * Copyright (C) 2002,2003,2014 European Southern Observatory
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -18,13 +17,6 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
  */
 
-/*
- * $Author: jtaylor $
- * $Date: 2013-01-29 08:43:33 $
- * $Revision: 1.58 $
- * $Name: not supported by cvs2svn $
- */
-
 #ifdef HAVE_CONFIG_H
 #include <config.h>
 #endif
@@ -33,15 +25,15 @@
    								Includes
  -----------------------------------------------------------------------------*/
 
-#include <math.h>
-#include <string.h>
-
-#include <cpl.h>
-
 #include "irplib_wavecal_impl.h"
 
 #include "irplib_wlxcorr.h"
 
+#include <cpl.h>
+
+#include <math.h>
+#include <string.h>
+
 /*----------------------------------------------------------------------------*/
 /**
  * @defgroup irplib_wlxcorr     Wavelength Cross correlation w. plotting
@@ -58,13 +50,6 @@
                            Defines
  -----------------------------------------------------------------------------*/
 
-/* TEMPORARY SUPPORT OF CPL 5.x */
-#ifndef CPL_SIZE_FORMAT
-#define CPL_SIZE_FORMAT "d"
-#define cpl_size int
-#endif
-/* END TEMPORARY SUPPORT OF CPL 5.x */
-
 #ifndef inline
 #define inline /* inline */
 #endif
@@ -892,7 +877,7 @@ int irplib_wlxcorr_catalog_plot(
         cpl_msg_error(cpl_func, "Cannot plot the catalog") ;
         return -1 ;
     }
-    nvals = start - stop + 1 ;
+    nvals = stop - start + 1 ;
 
     /* Create the bivector to plot */
     subcat_x = cpl_vector_extract(cpl_bivector_get_x_const(cat),start,stop, 1) ;
diff --git a/irplib/tests/Makefile.am b/irplib/tests/Makefile.am
index 79227bd..e0f4f0c 100644
--- a/irplib/tests/Makefile.am
+++ b/irplib/tests/Makefile.am
@@ -28,7 +28,7 @@ MAINTAINERCLEANFILES = Makefile.in
 
 endif
 
-AM_CPPFLAGS = $(all_includes) -I../../irplib/
+AM_CPPFLAGS = $(all_includes)
 
 LDADD = $(LIBIRPLIB) $(LIBCFITSIO) $(LIBCPLCORE) $(LIBCPLUI) $(LIBCPLDFS) $(LIBCPLDRS)
 
diff --git a/irplib/tests/Makefile.in b/irplib/tests/Makefile.in
index 9554647..b45379b 100644
--- a/irplib/tests/Makefile.in
+++ b/irplib/tests/Makefile.in
@@ -92,6 +92,7 @@ DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps = $(top_srcdir)/m4macros/cpl.m4 \
 	$(top_srcdir)/m4macros/eso.m4 $(top_srcdir)/m4macros/gsl.m4 \
+	$(top_srcdir)/m4macros/hdrl.m4 \
 	$(top_srcdir)/m4macros/libtool.m4 \
 	$(top_srcdir)/m4macros/ltoptions.m4 \
 	$(top_srcdir)/m4macros/ltsugar.m4 \
@@ -500,6 +501,10 @@ GREP = @GREP@
 GSL_INCLUDES = @GSL_INCLUDES@
 GSL_LDFLAGS = @GSL_LDFLAGS@
 GSL_LIBS = @GSL_LIBS@
+HDRL_INCLUDES = @HDRL_INCLUDES@
+HDRL_INTERNAL_CFLAGS = @HDRL_INTERNAL_CFLAGS@
+HDRL_LDFLAGS = @HDRL_LDFLAGS@
+HDRL_LIBS = @HDRL_LIBS@
 INSTALL = @INSTALL@
 INSTALL_DATA = @INSTALL_DATA@
 INSTALL_PROGRAM = @INSTALL_PROGRAM@
@@ -517,6 +522,7 @@ LIBCPLCORE = @LIBCPLCORE@
 LIBCPLDFS = @LIBCPLDFS@
 LIBCPLDRS = @LIBCPLDRS@
 LIBCPLUI = @LIBCPLUI@
+LIBHDRL = @LIBHDRL@
 LIBIRPLIB = @LIBIRPLIB@
 LIBLAPACK = @LIBLAPACK@
 LIBOBJS = @LIBOBJS@
@@ -619,6 +625,7 @@ psdir = @psdir@
 sbindir = @sbindir@
 sharedstatedir = @sharedstatedir@
 srcdir = @srcdir@
+subdirs = @subdirs@
 sysconfdir = @sysconfdir@
 target = @target@
 target_alias = @target_alias@
@@ -634,7 +641,7 @@ wkfextradir = @wkfextradir@
 AUTOMAKE_OPTIONS = 1.8 foreign
 DISTCLEANFILES = *~
 @MAINTAINER_MODE_TRUE at MAINTAINERCLEANFILES = Makefile.in
-AM_CPPFLAGS = $(all_includes) -I../../irplib/
+AM_CPPFLAGS = $(all_includes)
 LDADD = $(LIBIRPLIB) $(LIBCFITSIO) $(LIBCPLCORE) $(LIBCPLUI) $(LIBCPLDFS) $(LIBCPLDRS)
 pkginclude_HEADERS = 
 noinst_HEADERS = 
diff --git a/irplib/tests/irplib_plugin-test.c b/irplib/tests/irplib_plugin-test.c
index dfeffa1..dd07c01 100644
--- a/irplib/tests/irplib_plugin-test.c
+++ b/irplib/tests/irplib_plugin-test.c
@@ -38,9 +38,6 @@
 cpl_recipe_define(test_recipe, 123, "Some Author", "someone at local.org", "2014",
                   "For testing.", "Simple recipe for testing.");
 
-static cpl_error_code test_recipe_fill_parameterlist(cpl_parameterlist *self);
-static int test_recipe(cpl_frameset *frames, const cpl_parameterlist *params);
-
 static void test_irplib_recipe_test(void);
 
 /*----------------------------------------------------------------------------*/
diff --git a/irplib/tests/irplib_sdp_spectrum-test.c b/irplib/tests/irplib_sdp_spectrum-test.c
index 88b5684..3c4b29d 100644
--- a/irplib/tests/irplib_sdp_spectrum-test.c
+++ b/irplib/tests/irplib_sdp_spectrum-test.c
@@ -133,12 +133,13 @@ static int test_get_set_functions(void)
 {
   /* Create a new spectrum structure and set all keywords with dummy values. */
   irplib_sdp_spectrum *a = irplib_sdp_spectrum_new();
+  irplib_sdp_spectrum *b;
   cpl_test_assert(a != NULL);
   fill_keywords(a);
 
   /* Duplicate the spectrum and check if the new spectrum's keywords are the
    * same as for the first spectrum. */
-  irplib_sdp_spectrum *b = irplib_sdp_spectrum_duplicate(a);
+  b = irplib_sdp_spectrum_duplicate(a);
   cpl_test_assert(b != NULL);
   cpl_test_abs(irplib_sdp_spectrum_get_ra(b), 1.23, DBL_EPSILON);
   cpl_test_abs(irplib_sdp_spectrum_get_dec(b), 2.34, DBL_EPSILON);
@@ -553,7 +554,7 @@ static int test_column_functions(void)
   cpl_test_eq(irplib_sdp_spectrum_get_nelem(a), 0);
   cpl_test_eq(irplib_sdp_spectrum_get_column_type(a, "A"),
               CPL_TYPE_FLOAT | CPL_TYPE_POINTER);
-  cpl_test_eq_string(irplib_sdp_spectrum_get_column_unit(a, "A"), "");
+  cpl_test_eq_string(irplib_sdp_spectrum_get_column_unit(a, "A"), " ");
   cpl_test_nonnull(irplib_sdp_spectrum_get_column_format(a, "A"));
   cpl_test_eq_string(irplib_sdp_spectrum_get_column_tutyp(a, "A"), "");
   cpl_test_eq_string(irplib_sdp_spectrum_get_column_tucd(a, "A"), "");
diff --git a/irplib/tests/irplib_wlxcorr-test.c b/irplib/tests/irplib_wlxcorr-test.c
index 34c0b3e..f3ee213 100644
--- a/irplib/tests/irplib_wlxcorr-test.c
+++ b/irplib/tests/irplib_wlxcorr-test.c
@@ -1,7 +1,6 @@
-/* $Id: irplib_wlxcorr-test.c,v 1.16 2013-01-29 08:43:33 jtaylor Exp $
- *
+/*
  * This file is part of the ESO Common Pipeline Library
- * Copyright (C) 2001-2004 European Southern Observatory
+ * Copyright (C) 2001-2004,2014 European Southern Observatory
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -18,13 +17,6 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
  */
 
-/*
- * $Author: jtaylor $
- * $Date: 2013-01-29 08:43:33 $
- * $Revision: 1.16 $
- * $Name: not supported by cvs2svn $
- */
-
 /*-----------------------------------------------------------------------------
                                    Includes
  -----------------------------------------------------------------------------*/
@@ -42,14 +34,6 @@
 #include <math.h>
 #include <float.h>
 
-/* TEMPORARY SUPPORT OF CPL 5.x */
-#ifndef CPL_SIZE_FORMAT
-#define CPL_SIZE_FORMAT "d"
-#define cpl_size int
-#endif
-/* END TEMPORARY SUPPORT OF CPL 5.x */
-
-
 
 /*----------------------------------------------------------------------------*/
 /**
diff --git a/m4macros/hdrl.m4 b/m4macros/hdrl.m4
new file mode 100644
index 0000000..85f8991
--- /dev/null
+++ b/m4macros/hdrl.m4
@@ -0,0 +1,28 @@
+# HDRL_CHECK([location])
+# ----------------------
+# Sets build variables required to build and link hdrl
+# the argument defines the relative location of the hdrl external in the source
+# tree
+AC_DEFUN([HDRL_CHECK],
+[
+    HDRL_LOCATION="$1"
+    AC_MSG_CHECKING([HDRL in $HDRL_LOCATION])
+
+    # visibility hidden to not expose any hdrl symbols in the pipeline shared
+    # libraries
+    HDRL_INTERNAL_CFLAGS="-std=c99 -fvisibility=hidden"
+    # requires cpl and libm as it is a static library
+    HDRL_LIBS="-lhdrl -lcplcore -lcpldrs -lcplui -lcpldfs -lcext -lm"
+    # la file to be added to DEPENDENCIES libtool doesn't track static libs
+    LIBHDRL="\$(top_builddir)/$HDRL_LOCATION/libhdrl.la"
+    HDRL_LDFLAGS="-L\$(top_builddir)/$HDRL_LOCATION"
+    HDRL_INCLUDES="-I\$(top_srcdir)/$HDRL_LOCATION"
+
+    AC_SUBST(HDRL_LIBS)
+    AC_SUBST(LIBHDRL)
+    AC_SUBST(HDRL_LDFLAGS)
+    AC_SUBST(HDRL_INTERNAL_CFLAGS)
+    AC_SUBST(HDRL_INCLUDES)
+
+    AC_MSG_RESULT([ok])
+])
diff --git a/recipes/Makefile.am b/recipes/Makefile.am
index 835f1f5..53f1325 100644
--- a/recipes/Makefile.am
+++ b/recipes/Makefile.am
@@ -70,136 +70,71 @@ plugin_LTLIBRARIES = xsh_cfg_recover.la \
 			xsh_scired_ifu_offset_drl.la \
 			xsh_util_physmod.la 
 
-#                        xsh_absorp.la \
-#			xsh_util_bpmap_coadd.la \
-#			xsh_util_compute_response.la \
-#			xsh_util_bpmap_nl_raw2pre.la \
-#			xsh_util_bpmap2rp.la \
-#			xsh_util_integrate.la \
-#			xsh_util_apply_response.la 
-#			xsh_util_efficiency1d.la \
-#			xsh_scired_ifu_stare_drl.la \
-#			xsh_scired_ifu_offset_drl.la \
-#			xsh_geom_ifu.la 
-#			xsh_util_ipml.la \
-#			xsh_util_ifu_stare.la \
-#			xsh_util_ifu_offset.la \
-#			xsh_util_ifu_build_cube.la \
-#			xsh_util_efficiency2d.la \
-#			xsh_util_guess_xy.la
-#			xsh_respon_uvbvis.la \
-#			xsh_respon_visnir.la \
-#			xsh_util_ima_arith.la \
-#			xsh_util_ima_shift.la \
-#			xsh_util_genconfig.la \
-#			xsh_linear.la \
-#			xsh_util_ima_getextno.la \
-#			xsh_util_afc.la \
-#			xsh_model_first_anneal.la \
-#			xsh_model_compute.la \
-#			xsh_model_anneal.la \
-#			xsh_util_ima_rebin.la \
-#			xsh_util_ima_oversample.la \
-#			xsh_util_ima_subsample.la \
-#
-
-
 
 xsh_cfg_recover_la_SOURCES = xsh_cfg_recover.c
-xsh_cfg_recover_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_cfg_recover_la_LIBADD = $(AM_LIBADD)
 
 
 xsh_lingain_la_SOURCES = xsh_lingain.c
-xsh_lingain_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_lingain_la_LIBADD = $(AM_LIBADD)
 
 xsh_mbias_la_SOURCES = xsh_mbias.c
-xsh_mbias_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_mbias_la_LIBADD = $(AM_LIBADD)
 
 xsh_mdark_la_SOURCES = xsh_mdark.c
-xsh_mdark_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_mdark_la_LIBADD = $(AM_LIBADD)
 
 xsh_mflat_la_SOURCES = xsh_mflat.c
-xsh_mflat_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_mflat_la_LIBADD = $(AM_LIBADD)
 
 xsh_orderpos_la_SOURCES = xsh_orderpos.c
-xsh_orderpos_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_orderpos_la_LIBADD = $(AM_LIBADD)
 
 xsh_predict_la_SOURCES = xsh_predict.c
-xsh_predict_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_predict_la_LIBADD = $(AM_LIBADD)
 
 xsh_2dmap_la_SOURCES = xsh_2dmap.c
-xsh_2dmap_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_2dmap_la_LIBADD = $(AM_LIBADD)
 
 xsh_wavecal_la_SOURCES = xsh_wavecal.c
-xsh_wavecal_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_wavecal_la_LIBADD = $(AM_LIBADD)
 
 xsh_flexcomp_la_SOURCES = xsh_flexcomp.c
-xsh_flexcomp_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_flexcomp_la_LIBADD = $(AM_LIBADD)
 
 xsh_respon_slit_stare_la_SOURCES = xsh_respon_slit_stare.c
-xsh_respon_slit_stare_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_respon_slit_stare_la_LIBADD = $(AM_LIBADD)
 
 xsh_respon_slit_offset_la_SOURCES = xsh_respon_slit_offset.c
-xsh_respon_slit_offset_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_respon_slit_offset_la_LIBADD = $(AM_LIBADD)
 
 xsh_respon_slit_nod_la_SOURCES = xsh_respon_slit_nod.c
-xsh_respon_slit_nod_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_respon_slit_nod_la_LIBADD = $(AM_LIBADD)
 
 xsh_scired_slit_stare_la_SOURCES = xsh_scired_slit_stare.c
-xsh_scired_slit_stare_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_scired_slit_stare_la_LIBADD = $(AM_LIBADD)
 
 xsh_scired_slit_nod_la_SOURCES = xsh_scired_slit_nod.c
-xsh_scired_slit_nod_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_scired_slit_nod_la_LIBADD = $(AM_LIBADD)
 
 xsh_scired_slit_offset_la_SOURCES = xsh_scired_slit_offset.c
-xsh_scired_slit_offset_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_scired_slit_offset_la_LIBADD = $(AM_LIBADD)
 
 xsh_scired_ifu_stare_la_SOURCES = xsh_util_ifu_stare.c
-xsh_scired_ifu_stare_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_scired_ifu_stare_la_LIBADD = $(AM_LIBADD)
 
 xsh_scired_ifu_offset_la_SOURCES = xsh_util_ifu_offset.c
-xsh_scired_ifu_offset_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_scired_ifu_offset_la_LIBADD = $(AM_LIBADD)
 
 xsh_scired_ifu_stare_drl_la_SOURCES = xsh_scired_ifu_stare.c
-xsh_scired_ifu_stare_drl_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_scired_ifu_stare_drl_la_LIBADD = $(AM_LIBADD)
 
 xsh_scired_ifu_offset_drl_la_SOURCES = xsh_scired_ifu_offset.c
-xsh_scired_ifu_offset_drl_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_scired_ifu_offset_drl_la_LIBADD = $(AM_LIBADD)
 
 xsh_util_physmod_la_SOURCES = xsh_util_physmod.c
-xsh_util_physmod_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_util_physmod_la_LIBADD = $(AM_LIBADD)
 
 xsh_geom_ifu_la_SOURCES = xsh_geom_ifu.c
-xsh_geom_ifu_la_LIBADD = $(LIBXSH) $(LIBADD)
-
-#xsh_absorp_la_SOURCES = xsh_absorp.c
-#xsh_util_ipml_la_SOURCES = xsh_util_ipml.c
-#xsh_util_ipml_la_LIBADD = $(LIBIPML) $(LIBADD)
-#xsh_util_ipml_la_CPPFLAGS=-Wall -fPIC  $(CPL_INCLUDES) -rdynamic
-#xsh_util_bpmap2rp_la_SOURCES = xsh_util_bpmap2rp.c
-#xsh_util_bpmap_nl_raw2pre_la_SOURCES = xsh_util_bpmap_nl_raw2pre.c
-#xsh_util_bpmap_coadd_la_SOURCES = xsh_util_bpmap_coadd.c
-#xsh_util_afc_la_SOURCES = xsh_util_afc.c
-#xsh_util_crh_single_la_SOURCES = xsh_util_crh_single.c
-#xsh_util_efficiency2d_la_SOURCES = xsh_util_efficiency2d.c
-#xsh_util_efficiency1d_la_SOURCES = xsh_util_efficiency1d.c
-#xsh_util_integrate_la_SOURCES = xsh_util_integrate.c
-#xsh_util_ima_oversample_la_SOURCES = xsh_util_ima_oversample.c
-#xsh_util_ima_subsample_la_SOURCES = xsh_util_ima_subsample.c
-#xsh_util_apply_response_la_SOURCES = xsh_util_apply_response.c
-#xsh_util_compute_response_la_SOURCES = xsh_util_compute_response.c
-#xsh_util_ima_getextno_la_SOURCES = xsh_util_ima_getextno.c
-#xsh_util_ima_arith_la_SOURCES = xsh_util_ima_arith.c
-#xsh_util_ima_shift_la_SOURCES = xsh_util_ima_shift.c
-#xsh_util_ima_rebin_la_SOURCES = xsh_util_ima_rebin.c
-#xsh_linear_la_SOURCES = xsh_linear.c
-#xsh_model_compute_la_SOURCES = xsh_model_compute.c
-#xsh_model_anneal_la_SOURCES = xsh_model_anneal.c
-#xsh_model_first_anneal_la_SOURCES = xsh_model_first_anneal.c
-#xsh_util_genconfig_la_SOURCES = xsh_util_genconfig.c
-#xsh_respon_uvbvis_la_SOURCES = xsh_respon_uvbvis.c
-#xsh_respon_visnir_la_SOURCES = xsh_respon_visnir.c
-#xsh_util_ifu_stare_la_SOURCES = xsh_util_ifu_stare.c
-#xsh_util_ifu_offset_la_SOURCES = xsh_util_ifu_offset.c
-#xsh_util_ifu_build_cube_la_SOURCES = xsh_util_ifu_build_cube.c
-#xsh_util_guess_xy_la_SOURCES = xsh_util_guess_xy.c
+xsh_geom_ifu_la_LIBADD = $(AM_LIBADD)
+
diff --git a/recipes/Makefile.in b/recipes/Makefile.in
index 916aaa9..152a7d3 100644
--- a/recipes/Makefile.in
+++ b/recipes/Makefile.in
@@ -86,6 +86,7 @@ DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps = $(top_srcdir)/m4macros/cpl.m4 \
 	$(top_srcdir)/m4macros/eso.m4 $(top_srcdir)/m4macros/gsl.m4 \
+	$(top_srcdir)/m4macros/hdrl.m4 \
 	$(top_srcdir)/m4macros/libtool.m4 \
 	$(top_srcdir)/m4macros/ltoptions.m4 \
 	$(top_srcdir)/m4macros/ltsugar.m4 \
@@ -131,104 +132,83 @@ LTLIBRARIES = $(plugin_LTLIBRARIES)
 am__DEPENDENCIES_1 =
 am__DEPENDENCIES_2 = $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1)
-xsh_2dmap_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+am__DEPENDENCIES_3 = $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_2)
+xsh_2dmap_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_2dmap_la_OBJECTS = xsh_2dmap.lo
 xsh_2dmap_la_OBJECTS = $(am_xsh_2dmap_la_OBJECTS)
 AM_V_lt = $(am__v_lt_ at AM_V@)
 am__v_lt_ = $(am__v_lt_ at AM_DEFAULT_V@)
 am__v_lt_0 = --silent
 am__v_lt_1 = 
-xsh_cfg_recover_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_cfg_recover_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_cfg_recover_la_OBJECTS = xsh_cfg_recover.lo
 xsh_cfg_recover_la_OBJECTS = $(am_xsh_cfg_recover_la_OBJECTS)
-xsh_flexcomp_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_flexcomp_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_flexcomp_la_OBJECTS = xsh_flexcomp.lo
 xsh_flexcomp_la_OBJECTS = $(am_xsh_flexcomp_la_OBJECTS)
-xsh_geom_ifu_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_geom_ifu_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_geom_ifu_la_OBJECTS = xsh_geom_ifu.lo
 xsh_geom_ifu_la_OBJECTS = $(am_xsh_geom_ifu_la_OBJECTS)
-xsh_lingain_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_lingain_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_lingain_la_OBJECTS = xsh_lingain.lo
 xsh_lingain_la_OBJECTS = $(am_xsh_lingain_la_OBJECTS)
-xsh_mbias_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_mbias_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_mbias_la_OBJECTS = xsh_mbias.lo
 xsh_mbias_la_OBJECTS = $(am_xsh_mbias_la_OBJECTS)
-xsh_mdark_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_mdark_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_mdark_la_OBJECTS = xsh_mdark.lo
 xsh_mdark_la_OBJECTS = $(am_xsh_mdark_la_OBJECTS)
-xsh_mflat_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_mflat_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_mflat_la_OBJECTS = xsh_mflat.lo
 xsh_mflat_la_OBJECTS = $(am_xsh_mflat_la_OBJECTS)
-xsh_orderpos_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_orderpos_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_orderpos_la_OBJECTS = xsh_orderpos.lo
 xsh_orderpos_la_OBJECTS = $(am_xsh_orderpos_la_OBJECTS)
-xsh_predict_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_predict_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_predict_la_OBJECTS = xsh_predict.lo
 xsh_predict_la_OBJECTS = $(am_xsh_predict_la_OBJECTS)
-xsh_respon_slit_nod_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_respon_slit_nod_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_respon_slit_nod_la_OBJECTS = xsh_respon_slit_nod.lo
 xsh_respon_slit_nod_la_OBJECTS = $(am_xsh_respon_slit_nod_la_OBJECTS)
-xsh_respon_slit_offset_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_respon_slit_offset_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_respon_slit_offset_la_OBJECTS = xsh_respon_slit_offset.lo
 xsh_respon_slit_offset_la_OBJECTS =  \
 	$(am_xsh_respon_slit_offset_la_OBJECTS)
-xsh_respon_slit_stare_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_respon_slit_stare_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_respon_slit_stare_la_OBJECTS = xsh_respon_slit_stare.lo
 xsh_respon_slit_stare_la_OBJECTS =  \
 	$(am_xsh_respon_slit_stare_la_OBJECTS)
-xsh_scired_ifu_offset_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_scired_ifu_offset_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_scired_ifu_offset_la_OBJECTS = xsh_util_ifu_offset.lo
 xsh_scired_ifu_offset_la_OBJECTS =  \
 	$(am_xsh_scired_ifu_offset_la_OBJECTS)
-xsh_scired_ifu_offset_drl_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_scired_ifu_offset_drl_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_scired_ifu_offset_drl_la_OBJECTS = xsh_scired_ifu_offset.lo
 xsh_scired_ifu_offset_drl_la_OBJECTS =  \
 	$(am_xsh_scired_ifu_offset_drl_la_OBJECTS)
-xsh_scired_ifu_stare_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_scired_ifu_stare_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_scired_ifu_stare_la_OBJECTS = xsh_util_ifu_stare.lo
 xsh_scired_ifu_stare_la_OBJECTS =  \
 	$(am_xsh_scired_ifu_stare_la_OBJECTS)
-xsh_scired_ifu_stare_drl_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_scired_ifu_stare_drl_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_scired_ifu_stare_drl_la_OBJECTS = xsh_scired_ifu_stare.lo
 xsh_scired_ifu_stare_drl_la_OBJECTS =  \
 	$(am_xsh_scired_ifu_stare_drl_la_OBJECTS)
-xsh_scired_slit_nod_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_scired_slit_nod_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_scired_slit_nod_la_OBJECTS = xsh_scired_slit_nod.lo
 xsh_scired_slit_nod_la_OBJECTS = $(am_xsh_scired_slit_nod_la_OBJECTS)
-xsh_scired_slit_offset_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_scired_slit_offset_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_scired_slit_offset_la_OBJECTS = xsh_scired_slit_offset.lo
 xsh_scired_slit_offset_la_OBJECTS =  \
 	$(am_xsh_scired_slit_offset_la_OBJECTS)
-xsh_scired_slit_stare_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_scired_slit_stare_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_scired_slit_stare_la_OBJECTS = xsh_scired_slit_stare.lo
 xsh_scired_slit_stare_la_OBJECTS =  \
 	$(am_xsh_scired_slit_stare_la_OBJECTS)
-xsh_util_physmod_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_util_physmod_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_util_physmod_la_OBJECTS = xsh_util_physmod.lo
 xsh_util_physmod_la_OBJECTS = $(am_xsh_util_physmod_la_OBJECTS)
-xsh_wavecal_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2)
+xsh_wavecal_la_DEPENDENCIES = $(am__DEPENDENCIES_3)
 am_xsh_wavecal_la_OBJECTS = xsh_wavecal.lo
 xsh_wavecal_la_OBJECTS = $(am_xsh_wavecal_la_OBJECTS)
 AM_V_P = $(am__v_P_ at AM_V@)
@@ -360,6 +340,10 @@ GREP = @GREP@
 GSL_INCLUDES = @GSL_INCLUDES@
 GSL_LDFLAGS = @GSL_LDFLAGS@
 GSL_LIBS = @GSL_LIBS@
+HDRL_INCLUDES = @HDRL_INCLUDES@
+HDRL_INTERNAL_CFLAGS = @HDRL_INTERNAL_CFLAGS@
+HDRL_LDFLAGS = @HDRL_LDFLAGS@
+HDRL_LIBS = @HDRL_LIBS@
 INSTALL = @INSTALL@
 INSTALL_DATA = @INSTALL_DATA@
 INSTALL_PROGRAM = @INSTALL_PROGRAM@
@@ -377,6 +361,7 @@ LIBCPLCORE = @LIBCPLCORE@
 LIBCPLDFS = @LIBCPLDFS@
 LIBCPLDRS = @LIBCPLDRS@
 LIBCPLUI = @LIBCPLUI@
+LIBHDRL = @LIBHDRL@
 LIBIRPLIB = @LIBIRPLIB@
 LIBLAPACK = @LIBLAPACK@
 LIBOBJS = @LIBOBJS@
@@ -479,6 +464,7 @@ psdir = @psdir@
 sbindir = @sbindir@
 sharedstatedir = @sharedstatedir@
 srcdir = @srcdir@
+subdirs = @subdirs@
 sysconfdir = @sysconfdir@
 target = @target@
 target_alias = @target_alias@
@@ -531,83 +517,50 @@ plugin_LTLIBRARIES = xsh_cfg_recover.la \
 			xsh_scired_ifu_offset_drl.la \
 			xsh_util_physmod.la 
 
-
-#                        xsh_absorp.la \
-#			xsh_util_bpmap_coadd.la \
-#			xsh_util_compute_response.la \
-#			xsh_util_bpmap_nl_raw2pre.la \
-#			xsh_util_bpmap2rp.la \
-#			xsh_util_integrate.la \
-#			xsh_util_apply_response.la 
-#			xsh_util_efficiency1d.la \
-#			xsh_scired_ifu_stare_drl.la \
-#			xsh_scired_ifu_offset_drl.la \
-#			xsh_geom_ifu.la 
-#			xsh_util_ipml.la \
-#			xsh_util_ifu_stare.la \
-#			xsh_util_ifu_offset.la \
-#			xsh_util_ifu_build_cube.la \
-#			xsh_util_efficiency2d.la \
-#			xsh_util_guess_xy.la
-#			xsh_respon_uvbvis.la \
-#			xsh_respon_visnir.la \
-#			xsh_util_ima_arith.la \
-#			xsh_util_ima_shift.la \
-#			xsh_util_genconfig.la \
-#			xsh_linear.la \
-#			xsh_util_ima_getextno.la \
-#			xsh_util_afc.la \
-#			xsh_model_first_anneal.la \
-#			xsh_model_compute.la \
-#			xsh_model_anneal.la \
-#			xsh_util_ima_rebin.la \
-#			xsh_util_ima_oversample.la \
-#			xsh_util_ima_subsample.la \
-#
 xsh_cfg_recover_la_SOURCES = xsh_cfg_recover.c
-xsh_cfg_recover_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_cfg_recover_la_LIBADD = $(AM_LIBADD)
 xsh_lingain_la_SOURCES = xsh_lingain.c
-xsh_lingain_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_lingain_la_LIBADD = $(AM_LIBADD)
 xsh_mbias_la_SOURCES = xsh_mbias.c
-xsh_mbias_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_mbias_la_LIBADD = $(AM_LIBADD)
 xsh_mdark_la_SOURCES = xsh_mdark.c
-xsh_mdark_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_mdark_la_LIBADD = $(AM_LIBADD)
 xsh_mflat_la_SOURCES = xsh_mflat.c
-xsh_mflat_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_mflat_la_LIBADD = $(AM_LIBADD)
 xsh_orderpos_la_SOURCES = xsh_orderpos.c
-xsh_orderpos_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_orderpos_la_LIBADD = $(AM_LIBADD)
 xsh_predict_la_SOURCES = xsh_predict.c
-xsh_predict_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_predict_la_LIBADD = $(AM_LIBADD)
 xsh_2dmap_la_SOURCES = xsh_2dmap.c
-xsh_2dmap_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_2dmap_la_LIBADD = $(AM_LIBADD)
 xsh_wavecal_la_SOURCES = xsh_wavecal.c
-xsh_wavecal_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_wavecal_la_LIBADD = $(AM_LIBADD)
 xsh_flexcomp_la_SOURCES = xsh_flexcomp.c
-xsh_flexcomp_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_flexcomp_la_LIBADD = $(AM_LIBADD)
 xsh_respon_slit_stare_la_SOURCES = xsh_respon_slit_stare.c
-xsh_respon_slit_stare_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_respon_slit_stare_la_LIBADD = $(AM_LIBADD)
 xsh_respon_slit_offset_la_SOURCES = xsh_respon_slit_offset.c
-xsh_respon_slit_offset_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_respon_slit_offset_la_LIBADD = $(AM_LIBADD)
 xsh_respon_slit_nod_la_SOURCES = xsh_respon_slit_nod.c
-xsh_respon_slit_nod_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_respon_slit_nod_la_LIBADD = $(AM_LIBADD)
 xsh_scired_slit_stare_la_SOURCES = xsh_scired_slit_stare.c
-xsh_scired_slit_stare_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_scired_slit_stare_la_LIBADD = $(AM_LIBADD)
 xsh_scired_slit_nod_la_SOURCES = xsh_scired_slit_nod.c
-xsh_scired_slit_nod_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_scired_slit_nod_la_LIBADD = $(AM_LIBADD)
 xsh_scired_slit_offset_la_SOURCES = xsh_scired_slit_offset.c
-xsh_scired_slit_offset_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_scired_slit_offset_la_LIBADD = $(AM_LIBADD)
 xsh_scired_ifu_stare_la_SOURCES = xsh_util_ifu_stare.c
-xsh_scired_ifu_stare_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_scired_ifu_stare_la_LIBADD = $(AM_LIBADD)
 xsh_scired_ifu_offset_la_SOURCES = xsh_util_ifu_offset.c
-xsh_scired_ifu_offset_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_scired_ifu_offset_la_LIBADD = $(AM_LIBADD)
 xsh_scired_ifu_stare_drl_la_SOURCES = xsh_scired_ifu_stare.c
-xsh_scired_ifu_stare_drl_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_scired_ifu_stare_drl_la_LIBADD = $(AM_LIBADD)
 xsh_scired_ifu_offset_drl_la_SOURCES = xsh_scired_ifu_offset.c
-xsh_scired_ifu_offset_drl_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_scired_ifu_offset_drl_la_LIBADD = $(AM_LIBADD)
 xsh_util_physmod_la_SOURCES = xsh_util_physmod.c
-xsh_util_physmod_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_util_physmod_la_LIBADD = $(AM_LIBADD)
 xsh_geom_ifu_la_SOURCES = xsh_geom_ifu.c
-xsh_geom_ifu_la_LIBADD = $(LIBXSH) $(LIBADD)
+xsh_geom_ifu_la_LIBADD = $(AM_LIBADD)
 all: all-am
 
 .SUFFIXES:
@@ -1010,38 +963,6 @@ uninstall-am: uninstall-pluginLTLIBRARIES
 	uninstall-pluginLTLIBRARIES
 
 
-#xsh_absorp_la_SOURCES = xsh_absorp.c
-#xsh_util_ipml_la_SOURCES = xsh_util_ipml.c
-#xsh_util_ipml_la_LIBADD = $(LIBIPML) $(LIBADD)
-#xsh_util_ipml_la_CPPFLAGS=-Wall -fPIC  $(CPL_INCLUDES) -rdynamic
-#xsh_util_bpmap2rp_la_SOURCES = xsh_util_bpmap2rp.c
-#xsh_util_bpmap_nl_raw2pre_la_SOURCES = xsh_util_bpmap_nl_raw2pre.c
-#xsh_util_bpmap_coadd_la_SOURCES = xsh_util_bpmap_coadd.c
-#xsh_util_afc_la_SOURCES = xsh_util_afc.c
-#xsh_util_crh_single_la_SOURCES = xsh_util_crh_single.c
-#xsh_util_efficiency2d_la_SOURCES = xsh_util_efficiency2d.c
-#xsh_util_efficiency1d_la_SOURCES = xsh_util_efficiency1d.c
-#xsh_util_integrate_la_SOURCES = xsh_util_integrate.c
-#xsh_util_ima_oversample_la_SOURCES = xsh_util_ima_oversample.c
-#xsh_util_ima_subsample_la_SOURCES = xsh_util_ima_subsample.c
-#xsh_util_apply_response_la_SOURCES = xsh_util_apply_response.c
-#xsh_util_compute_response_la_SOURCES = xsh_util_compute_response.c
-#xsh_util_ima_getextno_la_SOURCES = xsh_util_ima_getextno.c
-#xsh_util_ima_arith_la_SOURCES = xsh_util_ima_arith.c
-#xsh_util_ima_shift_la_SOURCES = xsh_util_ima_shift.c
-#xsh_util_ima_rebin_la_SOURCES = xsh_util_ima_rebin.c
-#xsh_linear_la_SOURCES = xsh_linear.c
-#xsh_model_compute_la_SOURCES = xsh_model_compute.c
-#xsh_model_anneal_la_SOURCES = xsh_model_anneal.c
-#xsh_model_first_anneal_la_SOURCES = xsh_model_first_anneal.c
-#xsh_util_genconfig_la_SOURCES = xsh_util_genconfig.c
-#xsh_respon_uvbvis_la_SOURCES = xsh_respon_uvbvis.c
-#xsh_respon_visnir_la_SOURCES = xsh_respon_visnir.c
-#xsh_util_ifu_stare_la_SOURCES = xsh_util_ifu_stare.c
-#xsh_util_ifu_offset_la_SOURCES = xsh_util_ifu_offset.c
-#xsh_util_ifu_build_cube_la_SOURCES = xsh_util_ifu_build_cube.c
-#xsh_util_guess_xy_la_SOURCES = xsh_util_guess_xy.c
-
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff --git a/recipes/xsh_lingain.c b/recipes/xsh_lingain.c
index 511662a..3b3cf97 100644
--- a/recipes/xsh_lingain.c
+++ b/recipes/xsh_lingain.c
@@ -321,14 +321,16 @@ xsh_params_set_defaults(cpl_parameterlist* pars,
    cpl_parameter* p=NULL;
 
   if (xsh_instrument_get_arm(inst) == XSH_ARM_UVB){
-     check(p=xsh_parameters_find(pars,RECIPE_ID,"kappa"));
+
+      p=cpl_parameterlist_find(pars, "xshoo.xsh_lingain.kappa");
+
      if(xsh_parameter_get_default_flag(p) == 0) {
+     //if( fabs(val-def) > DBL_MIN ) {
         /* if the user has not set the parameter use default */
         cpl_parameter_set_double(p,5.);
      }    
   }
 
-
  cleanup:
  
   return cpl_error_get_code();
@@ -436,7 +438,7 @@ xsh_lingain(cpl_frameset            * frameset,
 
     //xsh_lingain_pre_format(raws,instrument,bpmap,0,&frameset);
 
-    xsh_lingain_fill_parlist_default_opt(plist);
+    check(xsh_lingain_fill_parlist_default_opt(plist));
     check(xsh_params_set_defaults(parlist,instrument));
     xsh_lingain_set_saturation_limit(plist,instrument);
 
diff --git a/recipes/xsh_mflat.c b/recipes/xsh_mflat.c
index 73a7c60..4f1a34b 100644
--- a/recipes/xsh_mflat.c
+++ b/recipes/xsh_mflat.c
@@ -525,6 +525,108 @@ xsh_params_set_defaults(cpl_parameterlist* pars,
 
 }
 
+static cpl_error_code
+xsh_qc_ifu_flat(cpl_frame* mflat,xsh_instrument* instrument)
+{
+    int do_it = 0;
+    if ( (xsh_instrument_get_arm(instrument) == XSH_ARM_UVB) ||
+                    (xsh_instrument_get_arm(instrument) == XSH_ARM_VIS) ) {
+        int binx=instrument->binx;
+        int biny=instrument->biny;
+        if( binx == 1 && biny == 1 ) {
+            do_it = 1;
+        }
+    } else {
+        if ( xsh_instrument_get_arm(instrument) == XSH_ARM_NIR ) {
+            do_it = 1;
+        }
+    }
+
+    if(do_it) {
+        xsh_pre* pre = xsh_pre_load(mflat,instrument);
+        double s1r;
+        double s2r;
+        double s3r;
+
+        double s1b;
+        double s2b;
+        double s3b;
+
+        if (xsh_instrument_get_arm(instrument) == XSH_ARM_UVB){
+
+
+            s1r=cpl_image_get_median_window(pre->data,1454,1500,1469,1600);
+            s2r=cpl_image_get_median_window(pre->data,1479,1500,1491,1600);
+            s3r=cpl_image_get_median_window(pre->data,1503,1500,1516,1600);
+
+            s1b=cpl_image_get_median_window(pre->data,515,2380,530,2380);
+            s2b=cpl_image_get_median_window(pre->data,541,2330,555,2380);
+            s3b=cpl_image_get_median_window(pre->data,566,2330,579,2380);
+
+        } else if (xsh_instrument_get_arm(instrument) == XSH_ARM_VIS){
+
+            s1r=cpl_image_get_median_window(pre->data,1652,2050,1666,2100);
+            s2r=cpl_image_get_median_window(pre->data,1674,2050,1684,2100);
+            s3r=cpl_image_get_median_window(pre->data,1697,2050,1711,2100);
+
+            s1b=cpl_image_get_median_window(pre->data,426,2650,444,2757);
+            s2b=cpl_image_get_median_window(pre->data,452,2650,470,2757);
+            s3b=cpl_image_get_median_window(pre->data,477,2650,496,2757);
+
+        } else if (xsh_instrument_get_arm(instrument) == XSH_ARM_NIR){
+
+            s1r=cpl_image_get_median_window(pre->data,620,1133,630,1175);
+            s2r=cpl_image_get_median_window(pre->data,636,1133,646,1175);
+            s3r=cpl_image_get_median_window(pre->data,653,1133,663,1175);
+
+            s1b=cpl_image_get_median_window(pre->data,128,1080,133,1111);
+            s2b=cpl_image_get_median_window(pre->data,141,1080,150,1111);
+            s3b=cpl_image_get_median_window(pre->data,158,1080,167,1111);
+
+        }
+        xsh_msg("s1b %g",s1b);
+        xsh_msg("s2b %g",s2b);
+        xsh_msg("s3b %g",s3b);
+
+        xsh_msg("s1r %g",s1r);
+        xsh_msg("s2r %g",s2r);
+        xsh_msg("s3r %g",s3r);
+
+        double A=(s2r-s2b)/s2r;
+        double m=(s1r+s2r+s3r)/3.0;
+        double a=(m-s1r)*(m-s1r);
+        double b=(m-s2r)*(m-s2r);
+        double c=(m-s3r)*(m-s3r);
+        double R=sqrt((a+b+c)/2.0);
+
+        double RD=(s1r-s3r)/(s1r+s2r)*2.0;
+
+        m=(s1b+s2b+s3b)/3.0;
+        a=(m-s1b)*(m-s1b);
+        b=(m-s2b)*(m-s2b);
+        c=(m-s3b)*(m-s3b);
+        double B=sqrt((a+b+c)/2.0);
+        double BD=(s1b-s3b)/(s1b+s2b)*2.0;
+
+        xsh_msg("FLUX_ORDER_RATIO %g",A);
+        xsh_msg("SLICE_RMS        %g",R);
+        xsh_msg("SLICE2_RMS       %g",B);
+        xsh_msg("SLICE_S_DIFF     %g",RD);
+        xsh_msg("SLICE2_S_DIFF    %g",BD);
+
+        cpl_propertylist_append_double(pre->data_header,"QC.FRATIO",A);
+        cpl_propertylist_append_double(pre->data_header,"QC.SLICER.RMS",R);
+        cpl_propertylist_append_double(pre->data_header,"QC.SLICEB.RMS",B);
+        cpl_propertylist_append_double(pre->data_header,"QC.SLICER.SDIFF",RD);
+        cpl_propertylist_append_double(pre->data_header,"QC.SLICEB.SDIFF",BD);
+        xsh_pre_save(pre,cpl_frame_get_filename(mflat),cpl_frame_get_tag(mflat),0);
+        xsh_pre_free(&pre);
+    }
+
+    return cpl_error_get_code();
+}
+
+
 
 /*--------------------------------------------------------------------------*/
 /**
@@ -706,7 +808,10 @@ static void xsh_mflat(cpl_parameterlist* parameters, cpl_frameset* frameset)
 
      xsh_msg("Detect dead-saturated pixels");
      check(xsh_image_mflat_detect_blemishes(master_flat_frame, instrument));
-
+     /* Temporarily disactivated */
+     if(xsh_instrument_get_mode(instrument) == XSH_MODE_IFU) {
+         xsh_qc_ifu_flat(master_flat_frame,instrument);
+     }
 
      /***********************************************************************/
      /* Products */
@@ -897,6 +1002,11 @@ static void xsh_mflat(cpl_parameterlist* parameters, cpl_frameset* frameset)
  
      xsh_msg("Detect dead-saturated pixels");
      check(xsh_image_mflat_detect_blemishes(master_flat_frame,instrument));
+     /* Temporarily disactivated */
+     if(xsh_instrument_get_mode(instrument) == XSH_MODE_IFU) {
+         xsh_qc_ifu_flat(master_flat_frame,instrument);
+     }
+
 
      check( xsh_add_product_pre( master_flat_frame, frameset,
                                  parameters, RECIPE_ID, instrument));
diff --git a/recipes/xsh_respon_slit_stare.c b/recipes/xsh_respon_slit_stare.c
index ce99e95..f92f6da 100644
--- a/recipes/xsh_respon_slit_stare.c
+++ b/recipes/xsh_respon_slit_stare.c
@@ -454,7 +454,7 @@ xsh_respon_slit_stare(cpl_parameterlist* parameters,
   int recipe_use_model = 0 ;
   int do_optextract = 0;
   int do_flatfield = 1;
-  int do_compute_map = 0 ;
+  int do_compute_map = FALSE ;
   int generate_sdp_format = 0;
   // int do_compute_eff = 0 ;
   xsh_extract_param extract_par = {  LOCALIZATION_METHOD};
@@ -608,8 +608,8 @@ xsh_respon_slit_stare(cpl_parameterlist* parameters,
 
   check( do_sub_sky = xsh_parameters_subtract_sky_single_get_true( RECIPE_ID,
     parameters));
-  if ( (do_sub_sky && !do_compute_map) &&
-       (wavemap_frame == NULL || slitmap_frame == NULL) ) {
+
+  if ( do_sub_sky == 1   && (wavemap_frame == NULL || slitmap_frame == NULL) ) {
        xsh_msg_warning( "sky-subtract is true but wave,slits maps missing create them");
     do_compute_map = TRUE;
 
@@ -799,10 +799,17 @@ xsh_respon_slit_stare(cpl_parameterlist* parameters,
       single_frame_sky_sub_tab_frame, instrument, sub_sky_nbkpts2, sky_par,
       &sky_frame, &sky_frame_eso, &sky_frame_ima, rec_prefix,1));
 
-  xsh_add_temporary_file(cpl_frame_get_filename(slitmap_frame));
-  xsh_add_temporary_file(cpl_frame_get_filename(wavemap_frame));
+  if(slitmap_frame) {
+      xsh_add_temporary_file(cpl_frame_get_filename(slitmap_frame));
+  }
+
+  if(wavemap_frame) {
+      xsh_add_temporary_file(cpl_frame_get_filename(wavemap_frame));
+  }
+
   xsh_add_temporary_file(cpl_frame_get_filename(sub_sky2_frame));
 
+
   if(do_sub_sky) {
      xsh_add_temporary_file(cpl_frame_get_filename(sky_frame_ima));
   }
diff --git a/reflex/Makefile.in b/reflex/Makefile.in
index 70eef73..34c63f4 100644
--- a/reflex/Makefile.in
+++ b/reflex/Makefile.in
@@ -85,6 +85,7 @@ DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps = $(top_srcdir)/m4macros/cpl.m4 \
 	$(top_srcdir)/m4macros/eso.m4 $(top_srcdir)/m4macros/gsl.m4 \
+	$(top_srcdir)/m4macros/hdrl.m4 \
 	$(top_srcdir)/m4macros/libtool.m4 \
 	$(top_srcdir)/m4macros/ltoptions.m4 \
 	$(top_srcdir)/m4macros/ltsugar.m4 \
@@ -185,6 +186,10 @@ GREP = @GREP@
 GSL_INCLUDES = @GSL_INCLUDES@
 GSL_LDFLAGS = @GSL_LDFLAGS@
 GSL_LIBS = @GSL_LIBS@
+HDRL_INCLUDES = @HDRL_INCLUDES@
+HDRL_INTERNAL_CFLAGS = @HDRL_INTERNAL_CFLAGS@
+HDRL_LDFLAGS = @HDRL_LDFLAGS@
+HDRL_LIBS = @HDRL_LIBS@
 INSTALL = @INSTALL@
 INSTALL_DATA = @INSTALL_DATA@
 INSTALL_PROGRAM = @INSTALL_PROGRAM@
@@ -202,6 +207,7 @@ LIBCPLCORE = @LIBCPLCORE@
 LIBCPLDFS = @LIBCPLDFS@
 LIBCPLDRS = @LIBCPLDRS@
 LIBCPLUI = @LIBCPLUI@
+LIBHDRL = @LIBHDRL@
 LIBIRPLIB = @LIBIRPLIB@
 LIBLAPACK = @LIBLAPACK@
 LIBOBJS = @LIBOBJS@
@@ -304,6 +310,7 @@ psdir = @psdir@
 sbindir = @sbindir@
 sharedstatedir = @sharedstatedir@
 srcdir = @srcdir@
+subdirs = @subdirs@
 sysconfdir = @sysconfdir@
 target = @target@
 target_alias = @target_alias@
diff --git a/reflex/xsh_calib_interactive_common.py b/reflex/xsh_calib_interactive_common.py
index 125a1e3..429a2b3 100644
--- a/reflex/xsh_calib_interactive_common.py
+++ b/reflex/xsh_calib_interactive_common.py
@@ -652,8 +652,19 @@ try:
 
     def setGeneralParameters(self,paramList,rec_id):
       group="general"
-
-      help1="""Integer representation of the bits to be considered bad when decoding the bad pixel mask pixel values."""
+      help1="""Integer representation of the bits to be considered bad when decoding the bad pixel mask pixel values.
+                    Most frequent codes relevant for the user:
+                    0: good pixel, 
+                    8: pick-up noise, 
+                    16: cosmic-ray removed, 
+                    32: cosmic-ray unremoved, 
+                    128: calibration file defect, 
+                    256: hot pixel, 
+                    512: dark pixel, 
+                    4096: A/D converted saturation, 
+                    32768: non linear pixel, 
+                    1048576: extrapolated flux in NIR, 
+                    4194304: Interpolated flux during extraction."""
       #if rec_id[4:11] != "predict" and rec_id[4:12] != "orderpos" :
 
       #   paramList.append(RecipeParameter(rec_id,displayName="decode-bp",group=group,description=help1))
diff --git a/reflex/xsh_object_interactive_common.py b/reflex/xsh_object_interactive_common.py
index 34e53c2..fc400c4 100644
--- a/reflex/xsh_object_interactive_common.py
+++ b/reflex/xsh_object_interactive_common.py
@@ -639,7 +639,21 @@ try:
 
     def setGeneralParameters(self,paramList,rec_id):
       group="general"
-      help1="""Integer representation of the bits to be considered bad when decoding the bad pixel mask pixel values."""
+      help1="""Integer representation of the bits to be considered bad when decoding the bad pixel mask pixel values.
+                    Most frequent codes relevant for the user:
+                    0: good pixel, 
+                    8: pick-up noise, 
+                    16: cosmic-ray removed, 
+                    32: cosmic-ray unremoved, 
+                    128: calibration file defect, 
+                    256: hot pixel, 
+                    512: dark pixel, 
+                    4096: A/D converted saturation, 
+                    32768: non linear pixel, 
+                    1048576: extrapolated flux in NIR, 
+                    4194304: Interpolated flux during extraction."""
+      
+      
       paramList.append(RecipeParameter(rec_id,displayName="decode-bp",group=group,description=help1))
       help2="""pre-overscan correction.0: no correction1: mean overscan correction2: mean prescan correction3: (mean pre+mean overscan)/2 correction."""
       paramList.append(RecipeParameter(rec_id,displayName="pre-overscan-corr",group=group,description=help2))
diff --git a/reflex/xsh_object_interactive_common_ifu.py b/reflex/xsh_object_interactive_common_ifu.py
index c0b75f9..00ad206 100644
--- a/reflex/xsh_object_interactive_common_ifu.py
+++ b/reflex/xsh_object_interactive_common_ifu.py
@@ -820,7 +820,19 @@ try:
 
     def setGeneralParameters(self,paramList,rec_id):
       group="general"
-      help1="""Integer representation of the bits to be considered bad when decoding the bad pixel mask pixel values."""
+      help1="""Integer representation of the bits to be considered bad when decoding the bad pixel mask pixel values.
+                    Most frequent codes relevant for the user:
+                    0: good pixel, 
+                    8: pick-up noise, 
+                    16: cosmic-ray removed, 
+                    32: cosmic-ray unremoved, 
+                    128: calibration file defect, 
+                    256: hot pixel, 
+                    512: dark pixel, 
+                    4096: A/D converted saturation, 
+                    32768: non linear pixel, 
+                    1048576: extrapolated flux in NIR, 
+                    4194304: Interpolated flux during extraction."""
       paramList.append(RecipeParameter(rec_id,displayName="decode-bp",group=group,description=help1))
       help2="""pre-overscan correction.0: no correction1: mean overscan correction2: mean prescan correction3: (mean pre+mean overscan)/2 correction."""
       paramList.append(RecipeParameter(rec_id,displayName="pre-overscan-corr",group=group,description=help2))
diff --git a/reflex/xsh_wkf.oca b/reflex/xsh_wkf.oca
index 987520d..d1442cc 100644
--- a/reflex/xsh_wkf.oca
+++ b/reflex/xsh_wkf.oca
@@ -180,8 +180,9 @@ then
   CATG = "CALIB";
 }
 
+
 if
-  DPR.CATG=="CALIB" and DPR.TYPE=="LAMP,QFLAT" and DPR.TECH=="ECHELLE,SLIT" and SEQ.ARM=="UVB" and INS.LAMP4.NAME=="UVB_High" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+  DPR.CATG=="CALIB" and DPR.TYPE=="LAMP,QFLAT" and DPR.TECH=="ECHELLE,SLIT" and SEQ.ARM=="UVB" and INS.LAMP4.NAME=="UVB_High" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") 
 then
 {
   RAW.TYPE = "FLAT_SLIT_UVB";
@@ -189,6 +190,7 @@ then
   CATG = "CALIB";
 }
 
+
 if
   DPR.CATG=="CALIB" and DPR.TYPE=="LAMP,DFLAT" and DPR.TECH=="ECHELLE,SLIT" and SEQ.ARM=="UVB" and INS.LAMP3.NAME=="UVB_Low_D2" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
 then
@@ -1106,6 +1108,13 @@ then
   REFLEX.TARGET = "T";
 }
 
+
+
+
+
+
+
+
 if
   DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,SLIT,OFFSET" and SEQ.ARM=="UVB" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
 then
@@ -1164,6 +1173,7 @@ then
   REFLEX.TARGET = "T";
 }
 
+
 if
   DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,SLIT,OFFSET" and SEQ.ARM=="NIR" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and INS.OPTI5.NAME like "%JH" 
 then
@@ -1184,6 +1194,99 @@ then
   REFLEX.TARGET = "T";
 }
 
+
+
+
+
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="UVB" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_UVB";
+  REFLEX.CATG = "OBJECT_SLIT_STARE_UVB";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="SKY" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="UVB" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_UVB";
+  REFLEX.CATG = "SKY_SLIT_UVB";
+  CATG = "SCIENCE";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="VIS" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_VIS";
+  REFLEX.CATG = "OBJECT_SLIT_STARE_VIS";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="SKY" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="VIS" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_VIS";
+  REFLEX.CATG = "SKY_SLIT_VIS";
+  CATG = "SCIENCE";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="NIR" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and INS.OPTI5.NAME like "%x11" 
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_NIR";
+  REFLEX.CATG = "OBJECT_SLIT_STARE_NIR";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="SKY" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="NIR" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and INS.OPTI5.NAME like "%x11" 
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_NIR";
+  REFLEX.CATG = "SKY_SLIT_NIR";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="NIR" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and INS.OPTI5.NAME like "%JH" 
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_JH_NIR";
+  REFLEX.CATG = "OBJECT_SLIT_STARE_NIR";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="SKY" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="NIR" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and INS.OPTI5.NAME like "%JH" 
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_JH_NIR";
+  REFLEX.CATG = "SKY_SLIT_NIR";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+
+
+
+
+
+
+
+
+
 if
   DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and SEQ.ARM=="UVB" and DPR.TECH=="ECHELLE,IFU,STARE" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
 then
@@ -1214,6 +1317,9 @@ then
   REFLEX.TARGET = "T";
 }
 
+
+
+
 if
   DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,IFU,OFFSET" and SEQ.ARM=="UVB" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
 then
@@ -1272,6 +1378,75 @@ then
 }
 
 
+
+
+
+
+
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,IFU,MAPPING" and SEQ.ARM=="UVB" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_IFU_STARE_UVB";
+  REFLEX.CATG = "OBJECT_IFU_STARE_UVB";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="SKY" and DPR.TECH=="ECHELLE,IFU,MAPPING" and SEQ.ARM=="UVB" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_IFU_STARE_UVB";
+  REFLEX.CATG = "SKY_IFU_UVB";
+  CATG = "SCIENCE";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,IFU,MAPPING" and SEQ.ARM=="VIS" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_IFU_STARE_VIS";
+  REFLEX.CATG = "OBJECT_IFU_STARE_VIS";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="SKY" and DPR.TECH=="ECHELLE,IFU,MAPPING" and SEQ.ARM=="VIS" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_IFU_STARE_VIS";
+  REFLEX.CATG = "SKY_IFU_VIS";
+  CATG = "SCIENCE";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,IFU,MAPPING" and SEQ.ARM=="NIR" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_IFU_STARE_NIR";
+  REFLEX.CATG = "OBJECT_IFU_STARE_NIR";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="SKY" and DPR.TECH=="ECHELLE,IFU,MAPPING" and SEQ.ARM=="NIR" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_IFU_STARE_NIR";
+  REFLEX.CATG = "SKY_IFU_NIR";
+  CATG = "SCIENCE";
+}
+
+
+
+
+
+
+
 //========================================================================
 //Reference frames
 //========================================================================
@@ -1529,6 +1704,7 @@ select execute(ACTION_ORDERPOS_VIS) from inputFiles where RAW.TYPE=="ORDERDEF_VI
 select execute(ACTION_ORDERPOS_NIR) from inputFiles where RAW.TYPE=="ORD_NIR"
   group by DET.DIT,DET.NDIT,SEQ.ARM,TPL.START as (TPL_A,tpl);
 
+
 select execute(ACTION_MFLAT_SLIT_UVB) from inputFiles where RAW.TYPE=="FLAT_SLIT_UVB"
   group by DET.READ.CLOCK,INS.OPTI3.NAME,TPL.START as (TPL_A,tpl);
 select execute(ACTION_MFLAT_SLIT_VIS) from inputFiles where RAW.TYPE=="FLAT_SLIT_VIS"
@@ -1937,6 +2113,13 @@ recipe xsh_orderpos;
 
 action ACTION_MFLAT_IFU_UVB
 {
+
+minRet = 1;
+select file as FLAT_D2_IFU_UVB from rawFiles where DPR.TYPE=="LAMP,DFLAT" and DPR.TECH=="ECHELLE,IFU" and SEQ.ARM=="UVB" and INS.LAMP3.NAME=="UVB_Low_D2" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and inputFile.TPL.START==TPL.START and inputFile.INS.OPTI3.NAME==INS.OPTI3.NAME and inputFile.DET.READ.CLOCK==DET.READ.CLOCK;
+
+minRet = 1; 
+select file as FLAT_QTH_IFU_UVB from rawFiles where DPR.TYPE=="LAMP,QFLAT" and DPR.TECH=="ECHELLE,IFU" and SEQ.ARM=="UVB" and INS.LAMP4.NAME=="UVB_High" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and inputFile.TPL.START==TPL.START and inputFile.INS.OPTI3.NAME==INS.OPTI3.NAME and inputFile.DET.READ.CLOCK==DET.READ.CLOCK;
+
 minRet = 0; maxRet = 1;
 select file as BP_MAP_RP_UVB from calibFiles where PRO.CATG=="BP_MAP_RP_UVB" and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
 
@@ -2006,6 +2189,14 @@ select file as SPECTRAL_FORMAT_TAB_NIR from calibFiles where PRO.CATG=="SPECTRAL
 
 action ACTION_MFLAT_SLIT_UVB
 {
+
+minRet = 1;
+select file as FLAT_D2_SLIT_UVB from rawFiles where DPR.TYPE=="LAMP,DFLAT" and DPR.TECH=="ECHELLE,SLIT" and SEQ.ARM=="UVB" and INS.LAMP3.NAME=="UVB_Low_D2" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and inputFile.TPL.START==TPL.START and inputFile.INS.OPTI3.NAME==INS.OPTI3.NAME and inputFile.DET.READ.CLOCK==DET.READ.CLOCK;
+
+minRet = 1;
+select file as FLAT_QTH_SLIT_UVB from rawFiles where DPR.TYPE=="LAMP,QFLAT" and DPR.TECH=="ECHELLE,SLIT" and SEQ.ARM=="UVB" and INS.LAMP4.NAME=="UVB_High" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and inputFile.TPL.START==TPL.START and inputFile.INS.OPTI3.NAME==INS.OPTI3.NAME and inputFile.DET.READ.CLOCK==DET.READ.CLOCK;
+
+
 minRet = 0; maxRet = 1;
 select file as BP_MAP_RP_UVB from calibFiles where PRO.CATG=="BP_MAP_RP_UVB" and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
 
diff --git a/reflex/xsh_wkf_stare.oca b/reflex/xsh_wkf_stare.oca
index 79d3d5e..046b7b7 100644
--- a/reflex/xsh_wkf_stare.oca
+++ b/reflex/xsh_wkf_stare.oca
@@ -732,6 +732,153 @@ then
   REFLEX.TARGET = "T";
 }
 
+
+
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="UVB" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_UVB";
+  REFLEX.CATG = "OBJECT_SLIT_STARE_UVB";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="SKY" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="UVB" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_UVB";
+  REFLEX.CATG = "SKY_SLIT_UVB";
+  CATG = "SCIENCE";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="VIS" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_VIS";
+  REFLEX.CATG = "OBJECT_SLIT_STARE_VIS";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="SKY" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="VIS" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_VIS";
+  REFLEX.CATG = "SKY_SLIT_VIS";
+  CATG = "SCIENCE";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="NIR" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and INS.OPTI5.NAME like "%x11" 
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_NIR";
+  REFLEX.CATG = "OBJECT_SLIT_STARE_NIR";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="SKY" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="NIR" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and INS.OPTI5.NAME like "%x11" 
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_NIR";
+  REFLEX.CATG = "SKY_SLIT_NIR";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="NIR" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and INS.OPTI5.NAME like "%JH" 
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_JH_NIR";
+  REFLEX.CATG = "OBJECT_SLIT_STARE_NIR";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="SKY" and DPR.TECH=="ECHELLE,SLIT,MAPPING" and SEQ.ARM=="NIR" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and INS.OPTI5.NAME like "%JH" 
+then
+{
+  RAW.TYPE = "SCI_SLIT_STARE_JH_NIR";
+  REFLEX.CATG = "SKY_SLIT_NIR";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+
+
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,IFU,MAPPING" and SEQ.ARM=="UVB" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_IFU_STARE_UVB";
+  REFLEX.CATG = "OBJECT_IFU_STARE_UVB";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="SKY" and DPR.TECH=="ECHELLE,IFU,MAPPING" and SEQ.ARM=="UVB" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_IFU_STARE_UVB";
+  REFLEX.CATG = "SKY_IFU_UVB";
+  CATG = "SCIENCE";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,IFU,MAPPING" and SEQ.ARM=="VIS" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_IFU_STARE_VIS";
+  REFLEX.CATG = "OBJECT_IFU_STARE_VIS";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="SKY" and DPR.TECH=="ECHELLE,IFU,MAPPING" and SEQ.ARM=="VIS" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_IFU_STARE_VIS";
+  REFLEX.CATG = "SKY_IFU_VIS";
+  CATG = "SCIENCE";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="OBJECT" and DPR.TECH=="ECHELLE,IFU,MAPPING" and SEQ.ARM=="NIR" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_IFU_STARE_NIR";
+  REFLEX.CATG = "OBJECT_IFU_STARE_NIR";
+  CATG = "SCIENCE";
+  REFLEX.TARGET = "T";
+}
+
+if
+  DPR.CATG=="SCIENCE" and DPR.TYPE=="SKY" and DPR.TECH=="ECHELLE,IFU,MAPPING" and SEQ.ARM=="NIR" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER")
+then
+{
+  RAW.TYPE = "SCI_IFU_STARE_NIR";
+  REFLEX.CATG = "SKY_IFU_NIR";
+  CATG = "SCIENCE";
+}
+
+
+
+
+
+
 //========================================================================
 //Reference frames
 //========================================================================
@@ -1330,6 +1477,14 @@ recipe xsh_orderpos;
 
 action ACTION_MFLAT_IFU_UVB
 {
+
+minRet = 1; 
+select file as FLAT_D2_IFU_UVB from rawFiles where DPR.TYPE=="LAMP,DFLAT" and DPR.TECH=="ECHELLE,IFU" and SEQ.ARM=="UVB" and INS.LAMP3.NAME=="UVB_Low_D2" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and inputFile.TPL.START==TPL.START and inputFile.INS.OPTI3.NAME==INS.OPTI3.NAME and inputFile.DET.READ.CLOCK==DET.READ.CLOCK;
+
+minRet = 1; 
+select file as FLAT_QTH_IFU_UVB from rawFiles where DPR.TYPE=="LAMP,QFLAT" and DPR.TECH=="ECHELLE,IFU" and SEQ.ARM=="UVB" and INS.LAMP4.NAME=="UVB_High" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and inputFile.TPL.START==TPL.START and inputFile.INS.OPTI3.NAME==INS.OPTI3.NAME and inputFile.DET.READ.CLOCK==DET.READ.CLOCK;
+
+
 minRet = 0; maxRet = 1;
 select file as BP_MAP_RP_UVB from calibFiles where PRO.CATG=="BP_MAP_RP_UVB" and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
 
@@ -1399,6 +1554,14 @@ select file as SPECTRAL_FORMAT_TAB_NIR from calibFiles where PRO.CATG=="SPECTRAL
 
 action ACTION_MFLAT_SLIT_UVB
 {
+
+minRet = 1; 
+select file as FLAT_D2_SLIT_UVB from rawFiles where DPR.TYPE=="LAMP,DFLAT" and DPR.TECH=="ECHELLE,SLIT" and SEQ.ARM=="UVB" and INS.LAMP3.NAME=="UVB_Low_D2" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and inputFile.TPL.START==TPL.START and inputFile.INS.OPTI3.NAME==INS.OPTI3.NAME and inputFile.DET.READ.CLOCK==DET.READ.CLOCK;
+
+minRet = 1; 
+select file as FLAT_QTH_SLIT_UVB from rawFiles where DPR.TYPE=="LAMP,QFLAT" and DPR.TECH=="ECHELLE,SLIT" and SEQ.ARM=="UVB" and INS.LAMP4.NAME=="UVB_High" and (INSTRUME=="SHOOT" or INSTRUME=="XSHOOTER") and inputFile.TPL.START==TPL.START and inputFile.INS.OPTI3.NAME==INS.OPTI3.NAME and inputFile.DET.READ.CLOCK==DET.READ.CLOCK;
+
+
 minRet = 0; maxRet = 1;
 select file as BP_MAP_RP_UVB from calibFiles where PRO.CATG=="BP_MAP_RP_UVB" and inputFile.DET.WIN1.BINX==DET.WIN1.BINX and inputFile.DET.WIN1.BINY==DET.WIN1.BINY and inputFile.DET.CHIP1.ID==DET.CHIP1.ID and (inputFile.INSTRUME=="SHOOT" or inputFile.INSTRUME=="XSHOOTER");
 
diff --git a/reflex/xshooter.xml.in b/reflex/xshooter.xml.in
index 3baa3b7..9fe8e46 100644
--- a/reflex/xshooter.xml.in
+++ b/reflex/xshooter.xml.in
@@ -119,7 +119,7 @@
             </property>
         </property>
     </property>
-    <property name="entityId" class="org.kepler.moml.NamedObjId" value="urn:lsid:kepler-project.org/ns/:52827:3:35">
+    <property name="entityId" class="org.kepler.moml.NamedObjId" value="urn:lsid:kepler-project.org/ns/:66731:7:7">
     </property>
     <property name="class" class="ptolemy.kernel.util.StringAttribute" value="ptolemy.actor.TypedCompositeActor">
         <property name="id" class="ptolemy.kernel.util.StringAttribute" value="null">
@@ -462,7 +462,7 @@
         <property name="allowDirectories" class="ptolemy.data.expr.Parameter" value="true">
         </property>
     </property>
-    <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={164, 39, 1550, 1015}, maximized=false}">
+    <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={182, 0, 1550, 1015}, maximized=false}">
     </property>
     <property name="_vergilSize" class="ptolemy.actor.gui.SizeAttribute" value="[1238, 863]">
     </property>
@@ -1789,7 +1789,7 @@
         <property name="_location" class="ptolemy.kernel.util.Location" value="[705.0, 105.0]">
         </property>
     </property>
-    <property name="END_PRODUCTS_SUBDIR" class="ptolemy.data.expr.StringParameter" value="2014-07-19T07:36:25/XSHOO.2014-04-23T05:59:05.340_tpl">
+    <property name="END_PRODUCTS_SUBDIR" class="ptolemy.data.expr.StringParameter" value="2015-01-09T10:08:36/XSHOO.2011-09-20T23:59:56.307_tpl">
 <property name="KeplerDocumentation" class="ptolemy.vergil.basic.KeplerDocumentationAttribute">
 <property name="description" class="ptolemy.kernel.util.ConfigurableAttribute"><configure>null</configure></property>
 <property name="author" class="ptolemy.kernel.util.ConfigurableAttribute"><configure>Edward A. Lee</configure></property>
@@ -1825,7 +1825,7 @@
         <property name="derivedFrom" class="org.kepler.moml.NamedObjIdReferralList" value="urn:lsid:kepler-project.org:actor:421:1">
         </property>
     </property>
-    <property name="GLOBAL_TIMESTAMP" class="ptolemy.data.expr.StringParameter" value="2014-07-19T07:36:25">
+    <property name="GLOBAL_TIMESTAMP" class="ptolemy.data.expr.StringParameter" value="2015-01-09T10:08:36">
 <property name="KeplerDocumentation" class="ptolemy.vergil.basic.KeplerDocumentationAttribute">
 <property name="description" class="ptolemy.kernel.util.ConfigurableAttribute"><configure>null</configure></property>
 <property name="author" class="ptolemy.kernel.util.ConfigurableAttribute"><configure>Edward A. Lee</configure></property>
@@ -3339,7 +3339,7 @@
         <property name="derivedFrom" class="org.kepler.moml.NamedObjIdReferralList" value="urn:lsid:kepler-project.org:actor:436:1">
         </property>
     </property>
-    <property name="derivedFrom" class="org.kepler.moml.NamedObjIdReferralList" value="urn:lsid:kepler-project.org:actor:436:1:urn:lsid:kepler-project.org/ns/:12776:4:415:urn:lsid:kepler-project.org/ns/:12776:55:75:urn:lsid:kepler-project.org/ns/:12776:59:142:urn:lsid:kepler-project.org/ns/:12776:68:228:urn:lsid:kepler-project.org/ns/:12776:84:51:urn:lsid:kepler-project.org/ns/:2745:31:9:urn:lsid:kepler-project.org/ns/:2745:32:214:urn:lsid:kepler-project.org/ns/:2745:45:122:urn:lsid:kepl [...]
+    <property name="derivedFrom" class="org.kepler.moml.NamedObjIdReferralList" value="urn:lsid:kepler-project.org:actor:436:1:urn:lsid:kepler-project.org/ns/:12776:4:415:urn:lsid:kepler-project.org/ns/:12776:55:75:urn:lsid:kepler-project.org/ns/:12776:59:142:urn:lsid:kepler-project.org/ns/:12776:68:228:urn:lsid:kepler-project.org/ns/:12776:84:51:urn:lsid:kepler-project.org/ns/:2745:31:9:urn:lsid:kepler-project.org/ns/:2745:32:214:urn:lsid:kepler-project.org/ns/:2745:45:122:urn:lsid:kepl [...]
     </property>
     <property name="Annotation43" class="ptolemy.vergil.kernel.attributes.TextAttribute">
         <property name="_hideName" class="ptolemy.data.expr.SingletonParameter" value="true">
@@ -4464,7 +4464,7 @@
         <property name="derivedFrom" class="org.kepler.moml.NamedObjIdReferralList" value="urn:lsid:kepler-project.org:actor:433:1">
         </property>
     </property>
-    <property name="N_SELECTED_DATASETS" class="ptolemy.data.expr.StringParameter" value="3">
+    <property name="N_SELECTED_DATASETS" class="ptolemy.data.expr.StringParameter" value="8">
 <property name="KeplerDocumentation" class="ptolemy.vergil.basic.KeplerDocumentationAttribute">
 <property name="description" class="ptolemy.kernel.util.ConfigurableAttribute"><configure>null</configure></property>
 <property name="author" class="ptolemy.kernel.util.ConfigurableAttribute"><configure>Edward A. Lee</configure></property>
@@ -4572,7 +4572,7 @@
         <property name="derivedFrom" class="org.kepler.moml.NamedObjIdReferralList" value="urn:lsid:kepler-project.org:actor:421:1:urn:lsid:kepler-project.org/ns/:38254:6:1">
         </property>
     </property>
-    <property name="SelectionDatasetMethod" class="ptolemy.data.expr.StringParameter" value="Interactive">
+    <property name="SelectDatasetMethod" class="ptolemy.data.expr.StringParameter" value="Interactive">
 <property name="KeplerDocumentation" class="ptolemy.vergil.basic.KeplerDocumentationAttribute">
 <property name="description" class="ptolemy.kernel.util.ConfigurableAttribute"><configure>null</configure></property>
 <property name="author" class="ptolemy.kernel.util.ConfigurableAttribute"><configure>Edward A. Lee</configure></property>
@@ -6834,7 +6834,7 @@
 <property name="userLevelDocumentation" class="ptolemy.kernel.util.ConfigurableAttribute"><configure><p>A Composite actor is an aggregation of actors. It may have a local director that is responsible for executing the contained actors. A Composite actor with a local director is called an opaque actor. Composite actors do not require a local director. Composite actors with no local director "inherit" the director from the containing workflow and are called non-opaque.</ [...]
 </property>        <property name="_location" class="ptolemy.kernel.util.Location" value="[450.0, 970.0]">
         </property>
-        <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={175, 121, 1268, 726}, maximized=false}">
+        <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={175, 121, 1264, 721}, maximized=false}">
         </property>
         <property name="_vergilSize" class="ptolemy.actor.gui.SizeAttribute" value="[952, 569]">
         </property>
@@ -8240,6 +8240,8 @@
             </property>
             <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="XSH_MOD_CFG_OPT_2D_UVB,XSH_MOD_CFG_OPT_2D_VIS,XSH_MOD_CFG_OPT_2D_NIR,DISP_TAB_UVB,DISP_TAB_VIS,DISP_TAB_NIR,WAVE_ON_UVB,WAVE_RESID_TAB_LINES_UVB,WAVE_ON_VIS,WAVE_RESID_TAB_LINES_VIS,WAVE_ON_NIR,WAVE_RESID_TAB_LINES_NIR">
             </property>
+            <property name="Allow empty inputs" class="ptolemy.data.expr.Parameter" value="true">
+            </property>
             <property name="recipe_param_5" class="ptolemy.data.expr.Parameter" value="pre-overscan-corr=PORT">
             </property>
             <property name="recipe_param_6" class="ptolemy.data.expr.Parameter" value="detectarclines-fit-win-hsize=PORT">
@@ -8437,7 +8439,7 @@
 <property name="userLevelDocumentation" class="ptolemy.kernel.util.ConfigurableAttribute"><configure><p>A Composite actor is an aggregation of actors. It may have a local director that is responsible for executing the contained actors. A Composite actor with a local director is called an opaque actor. Composite actors do not require a local director. Composite actors with no local director "inherit" the director from the containing workflow and are called non-opaque.</ [...]
 </property>        <property name="_location" class="ptolemy.kernel.util.Location" value="[1125.0, 685.0]">
         </property>
-        <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={0, 189, 1601, 861}, maximized=false}">
+        <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={0, 154, 1601, 861}, maximized=false}">
         </property>
         <property name="_vergilSize" class="ptolemy.actor.gui.SizeAttribute" value="[1289, 709]">
         </property>
@@ -11801,6 +11803,8 @@
                     <property name="style" class="ptolemy.actor.gui.style.LineStyle">
                     </property>
                 </property>
+                <property name="Allow empty inputs" class="ptolemy.data.expr.Parameter" value="true">
+                </property>
                 <property name="Pause before execution" class="ptolemy.data.expr.Parameter" value="false">
                 </property>
                 <property name="recipe_param_4" class="ptolemy.data.expr.Parameter" value="decode-bp=PORT">
@@ -14028,6 +14032,8 @@
                 </property>
                 <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="FLUX_SLIT_MERGE1D_UVB,FLUX_SLIT_MERGE2D_UVB,SKY_SLIT_MERGE2D_UVB,RESPONSE_MERGE1D_SLIT_UVB,FLUX_SLIT_FLUX_MERGE1D_UVB,FLUX_SLIT_MERGE1D_VIS,FLUX_SLIT_MERGE2D_VIS,SKY_SLIT_MERGE2D_VIS,RESPONSE_MERGE1D_SLIT_VIS,FLUX_SLIT_FLUX_MERGE1D_VIS,FLUX_SLIT_MERGE1D_NIR,FLUX_SLIT_MERGE2D_NIR,SKY_SLIT_MERGE2D_NIR,RESPONSE_MERGE1D_SLIT_NIR,FLUX_SLIT_FLUX_MERGE1D_NIR">
                 </property>
+                <property name="Allow empty inputs" class="ptolemy.data.expr.Parameter" value="true">
+                </property>
                 <property name="recipe_param_4" class="ptolemy.data.expr.Parameter" value="decode-bp=PORT">
                 </property>
                 <property name="recipe_param_5" class="ptolemy.data.expr.Parameter" value="pre-overscan-corr=PORT">
@@ -16309,6 +16315,8 @@
                 </property>
                 <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="FLUX_SLIT_MERGE1D_UVB,FLUX_SLIT_MERGE2D_UVB,FLUX_SLIT_FLUX_MERGE1D_UVB,RESPONSE_MERGE1D_SLIT_UVB,FLUX_SLIT_MERGE1D_VIS,FLUX_SLIT_MERGE2D_VIS,FLUX_SLIT_FLUX_MERGE1D_VIS,RESPONSE_MERGE1D_SLIT_VIS,FLUX_SLIT_MERGE1D_NIR,FLUX_SLIT_MERGE2D_NIR,FLUX_SLIT_FLUX_MERGE1D_NIR,RESPONSE_MERGE1D_SLIT_NIR">
                 </property>
+                <property name="Allow empty inputs" class="ptolemy.data.expr.Parameter" value="true">
+                </property>
                 <property name="recipe_param_4" class="ptolemy.data.expr.Parameter" value="decode-bp=PORT">
                 </property>
                 <property name="recipe_param_5" class="ptolemy.data.expr.Parameter" value="pre-overscan-corr=PORT">
@@ -16843,7 +16851,7 @@
 <property name="userLevelDocumentation" class="ptolemy.kernel.util.ConfigurableAttribute"><configure><p>A Composite actor is an aggregation of actors. It may have a local director that is responsible for executing the contained actors. A Composite actor with a local director is called an opaque actor. Composite actors do not require a local director. Composite actors with no local director "inherit" the director from the containing workflow and are called non-opaque.</ [...]
 </property>        <property name="_location" class="ptolemy.kernel.util.Location" value="[1220.0, 1245.0]">
         </property>
-        <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={-23, 35, 1680, 972}, maximized=false}">
+        <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={0, 43, 1680, 972}, maximized=false}">
         </property>
         <property name="_vergilSize" class="ptolemy.actor.gui.SizeAttribute" value="[1417, 820]">
         </property>
@@ -20994,10 +21002,12 @@
                 </property>
                 <property name="Input Files Category" class="ptolemy.data.expr.StringParameter" value="OBJECT_SLIT_STARE_UVB,SPECTRAL_FORMAT_TAB_UVB,MASTER_BIAS_UVB,MASTER_DARK_UVB,ORDER_TAB_EDGES_SLIT_UVB,ORDER_TAB_AFC_SLIT_UVB,MASTER_FLAT_SLIT_UVB,DISP_TAB_UVB,DISP_TAB_AFC_UVB,XSH_MOD_CFG_OPT_2D_UVB,XSH_MOD_CFG_OPT_AFC_UVB,BP_MAP_NL_UVB,OBJECT_SLIT_STARE_VIS,SPECTRAL_FORMAT_TAB_VIS,MASTER_BIAS_VIS,MASTER_DARK_VIS,ORDER_TAB_EDGES_SLIT_VIS,ORDER_TAB_AFC_SLIT_VIS,MASTER_FLAT_SLIT_VIS,DISP [...]
                 </property>
-                <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="SCI_SLIT_MERGE1D_UVB,SCI_SLIT_MERGE2D_UVB,SKY_SLIT_MERGE2D_UVB,SCI_SLIT_SKY_UVB,SCI_SLIT_SUB_SKY_UVB,SCI_SLIT_FLUX_MERGE1D_UVB,SCI_SLIT_MERGE_OXT1D_UVB,SCI_SLIT_FLUX_MOXT1D_UVB,SCI_SLIT_MERGE1D_VIS,SCI_SLIT_MERGE2D_VIS,SKY_SLIT_MERGE2D_VIS,SCI_SLIT_SKY_VIS,SCI_SLIT_SUB_SKY_VIS,SCI_SLIT_FLUX_MERGE1D_VIS,SCI_SLIT_MERGE_OXT1D_VIS,SCI_SLIT_FLUX_MOXT1D_VIS,SCI_SLIT_MERGE1D_NIR,SCI_SLIT_MERG [...]
+                <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="SCI_SLIT_MERGE1D_UVB,SCI_SLIT_MERGE2D_UVB,SKY_SLIT_MERGE2D_UVB,SCI_SLIT_SKY_UVB,SCI_SLIT_SUB_SKY_UVB,SCI_SLIT_FLUX_MERGE1D_UVB,SCI_SLIT_FLUX_MERGE2D_UVB,SCI_SLIT_MERGE_OXT1D_UVB,SCI_SLIT_FLUX_MOXT1D_UVB,SCI_SLIT_MERGE1D_VIS,SCI_SLIT_MERGE2D_VIS,SKY_SLIT_MERGE2D_VIS,SCI_SLIT_SKY_VIS,SCI_SLIT_SUB_SKY_VIS,SCI_SLIT_FLUX_MERGE1D_VIS,SCI_SLIT_FLUX_MERGE2D_VIS,SCI_SLIT_MERGE_OXT1D_VIS,SCI_SLI [...]
                     <property name="style" class="ptolemy.actor.gui.style.LineStyle">
                     </property>
                 </property>
+                <property name="Allow empty inputs" class="ptolemy.data.expr.Parameter" value="true">
+                </property>
                 <property name="Pause before execution" class="ptolemy.data.expr.Parameter" value="false">
                 </property>
                 <property name="recipe_param_4" class="ptolemy.data.expr.Parameter" value="decode-bp=PORT">
@@ -21309,7 +21319,7 @@
 <property name="userLevelDocumentation" class="ptolemy.kernel.util.ConfigurableAttribute"><configure><p>A Composite actor is an aggregation of actors. It may have a local director that is responsible for executing the contained actors. A Composite actor with a local director is called an opaque actor. Composite actors do not require a local director. Composite actors with no local director "inherit" the director from the containing workflow and are called non-opaque.</ [...]
 </property>            <property name="_location" class="ptolemy.kernel.util.Location" value="[550.0, 640.0]">
             </property>
-            <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={118, 127, 1532, 923}, maximized=false}">
+            <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={21, 19, 1532, 923}, maximized=false}">
             </property>
             <property name="_vergilSize" class="ptolemy.actor.gui.SizeAttribute" value="[1220, 771]">
             </property>
@@ -23076,7 +23086,9 @@
                 </property>
                 <property name="Input Files Category" class="ptolemy.data.expr.StringParameter" value="OBJECT_SLIT_OFFSET_UVB,SKY_SLIT_UVB,SPECTRAL_FORMAT_TAB_UVB,MASTER_BIAS_UVB,ORDER_TAB_EDGES_SLIT_UVB,ORDER_TAB_AFC_SLIT_UVB,MASTER_FLAT_SLIT_UVB,DISP_TAB_UVB,DISP_TAB_AFC_UVB,XSH_MOD_CFG_OPT_2D_UVB,XSH_MOD_CFG_OPT_AFC_UVB,BP_MAP_NL_UVB,OBJECT_SLIT_OFFSET_VIS,SKY_SLIT_VIS,SPECTRAL_FORMAT_TAB_VIS,MASTER_BIAS_VIS,ORDER_TAB_EDGES_SLIT_VIS,ORDER_TAB_AFC_SLIT_VIS,MASTER_FLAT_SLIT_VIS,DISP_TAB [...]
                 </property>
-                <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="SCI_SLIT_MERGE1D_UVB,SCI_SLIT_MERGE2D_UVB,SKY_SLIT_MERGE2D_UVB,SCI_SLIT_MERGE1D_VIS,SCI_SLIT_MERGE2D_VIS,SKY_SLIT_MERGE2D_VIS,SCI_SLIT_MERGE1D_NIR,SCI_SLIT_MERGE2D_NIR,SKY_SLIT_MERGE2D_NIR,SCI_SLIT_FLUX_MERGE1D_UVB,SCI_SLIT_FLUX_MERGE1D_VIS,SCI_SLIT_FLUX_MERGE1D_NIR,TELL_SLIT_MERGE1D_UVB,TELL_SLIT_MERGE2D_UVB,TELL_SLIT_MERGE1D_VIS,TELL_SLIT_MERGE2D_VIS,TELL_SLIT_MERGE1D_NIR,TELL_SLIT_M [...]
+                <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="SCI_SLIT_MERGE1D_UVB,SCI_SLIT_MERGE2D_UVB,SKY_SLIT_MERGE2D_UVB,SCI_SLIT_MERGE1D_VIS,SCI_SLIT_MERGE2D_VIS,SKY_SLIT_MERGE2D_VIS,SCI_SLIT_MERGE1D_NIR,SCI_SLIT_MERGE2D_NIR,SKY_SLIT_MERGE2D_NIR,SCI_SLIT_FLUX_MERGE1D_UVB,SCI_SLIT_FLUX_MERGE1D_VIS,SCI_SLIT_FLUX_MERGE1D_NIR,SCI_SLIT_FLUX_MERGE2D_UVB,SCI_SLIT_FLUX_MERGE2D_VIS,SCI_SLIT_FLUX_MERGE2D_NIR,TELL_SLIT_MERGE1D_UVB,TELL_SLIT_MERGE2D_UVB [...]
+                </property>
+                <property name="Allow empty inputs" class="ptolemy.data.expr.Parameter" value="true">
                 </property>
                 <property name="recipe_param_4" class="ptolemy.data.expr.Parameter" value="decode-bp=PORT">
                 </property>
@@ -23359,7 +23371,7 @@
 <property name="userLevelDocumentation" class="ptolemy.kernel.util.ConfigurableAttribute"><configure><p>A Composite actor is an aggregation of actors. It may have a local director that is responsible for executing the contained actors. A Composite actor with a local director is called an opaque actor. Composite actors do not require a local director. Composite actors with no local director "inherit" the director from the containing workflow and are called non-opaque.</ [...]
 </property>            <property name="_location" class="ptolemy.kernel.util.Location" value="[620.0, 695.0]">
             </property>
-            <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={0, 80, 1532, 923}, maximized=false}">
+            <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={70, 17, 1532, 923}, maximized=false}">
             </property>
             <property name="_vergilSize" class="ptolemy.actor.gui.SizeAttribute" value="[1220, 771]">
             </property>
@@ -25177,7 +25189,9 @@
                 </property>
                 <property name="Input Files Category" class="ptolemy.data.expr.StringParameter" value="OBJECT_SLIT_NOD_UVB,SPECTRAL_FORMAT_TAB_UVB,MASTER_BIAS_UVB,ORDER_TAB_EDGES_SLIT_UVB,ORDER_TAB_AFC_SLIT_UVB,MASTER_FLAT_SLIT_UVB,DISP_TAB_EDGES_UVB,DISP_TAB_AFC_UVB,XSH_MOD_CFG_OPT_2D_UVB,XSH_MOD_CFG_OPT_AFC_UVB,BP_MAP_NL_UVB,OBJECT_SLIT_NOD_VIS,SPECTRAL_FORMAT_TAB_VIS,MASTER_BIAS_VIS,ORDER_TAB_EDGES_SLIT_VIS,ORDER_TAB_AFC_SLIT_VIS,MASTER_FLAT_SLIT_VIS,DISP_TAB_VIS,DISP_TAB_AFC_VIS,XSH_ [...]
                 </property>
-                <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="SCI_SLIT_MERGE1D_UVB,SCI_SLIT_MERGE2D_UVB,SCI_SLIT_MERGE1D_VIS,SCI_SLIT_MERGE2D_VIS,SCI_SLIT_MERGE1D_NIR,SCI_SLIT_MERGE2D_NIR,SCI_SLIT_FLUX_MERGE1D_UVB,SCI_SLIT_FLUX_MERGE1D_VIS,SCI_SLIT_FLUX_MERGE1D_NIR,TELL_SLIT_MERGE1D_UVB,TELL_SLIT_MERGE2D_UVB,TELL_SLIT_MERGE1D_VIS,TELL_SLIT_MERGE2D_VIS,TELL_SLIT_MERGE1D_NIR,TELL_SLIT_MERGE2D_NIR,TELL_SLIT_FLUX_MERGE1D_UVB,TELL_SLIT_FLUX_MERGE1D_VI [...]
+                <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="SCI_SLIT_MERGE1D_UVB,SCI_SLIT_MERGE2D_UVB,SCI_SLIT_MERGE1D_VIS,SCI_SLIT_MERGE2D_VIS,SCI_SLIT_MERGE1D_NIR,SCI_SLIT_MERGE2D_NIR,SCI_SLIT_FLUX_MERGE1D_UVB,SCI_SLIT_FLUX_MERGE1D_VIS,SCI_SLIT_FLUX_MERGE1D_NIR,SCI_SLIT_FLUX_MERGE2D_UVB,SCI_SLIT_FLUX_MERGE2D_VIS,SCI_SLIT_FLUX_MERGE2D_NIR,TELL_SLIT_MERGE1D_UVB,TELL_SLIT_MERGE2D_UVB,TELL_SLIT_MERGE1D_VIS,TELL_SLIT_MERGE2D_VIS,TELL_SLIT_MERGE1D_ [...]
+                </property>
+                <property name="Allow empty inputs" class="ptolemy.data.expr.Parameter" value="true">
                 </property>
                 <property name="recipe_param_4" class="ptolemy.data.expr.Parameter" value="decode-bp=PORT">
                 </property>
@@ -27238,6 +27252,8 @@
                 </property>
                 <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="CAL_IFU_MERGE3D_DATA_OBJ_UVB,CAL_IFU_MERGE3D_TRACE_OBJ_UVB,CAL_IFU_ORDER3D_DATA_OBJ_UVB,FLUX_IFU_MERGE3D_DATA_OBJ_UVB,FLUX_IFU_MERGE3D_TRACE_OBJ_UVB,FLUX_IFU_ORDER3D_DATA_OBJ_UVB,TELL_IFU_MERGE3D_DATA_OBJ_UVB,TELL_IFU_MERGE3D_TRACE_OBJ_UVB,TELL_IFU_ORDER3D_DATA_OBJ_UVB,SCI_IFU_MERGE3D_DATA_OBJ_UVB,SCI_IFU_MERGE3D_TRACE_OBJ_UVB,SCI_IFU_ORDER3D_DATA_OBJ_UVB,IFU_CFG_COR_UVB,CAL_IFU_MERGE3 [...]
                 </property>
+                <property name="Allow empty inputs" class="ptolemy.data.expr.Parameter" value="true">
+                </property>
                 <property name="recipe_param_4" class="ptolemy.data.expr.Parameter" value="decode-bp=PORT">
                 </property>
                 <property name="recipe_param_6" class="ptolemy.data.expr.Parameter" value="stack-method=PORT">
@@ -29695,6 +29711,8 @@
                 </property>
                 <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="FLUX_IFU_MERGE3D_DATA_OBJ_UVB,FLUX_IFU_MERGE3D_TRACE_OBJ_UVB,FLUX_IFU_ORDER3D_DATA_OBJ_UVB,TELL_IFU_MERGE3D_DATA_OBJ_UVB,TELL_IFU_MERGE3D_TRACE_OBJ_UVB,TELL_IFU_ORDER3D_DATA_OBJ_UVB,SCI_IFU_MERGE3D_DATA_OBJ_UVB,SCI_IFU_MERGE3D_TRACE_OBJ_UVB,SCI_IFU_ORDER3D_DATA_OBJ_UVB,IFU_CFG_COR_UVB,FLUX_IFU_MERGE3D_DATA_OBJ_VIS,FLUX_IFU_MERGE3D_TRACE_OBJ_VIS,FLUX_IFU_ORDER3D_DATA_OBJ_VIS,TELL_IFU_ME [...]
                 </property>
+                <property name="Allow empty inputs" class="ptolemy.data.expr.Parameter" value="true">
+                </property>
                 <property name="Pause after execution" class="ptolemy.data.expr.Parameter" value="false">
                 </property>
                 <property name="recipe_param_4" class="ptolemy.data.expr.Parameter" value="decode-bp=PORT">
@@ -30160,7 +30178,7 @@
 <property name="userLevelDocumentation" class="ptolemy.kernel.util.ConfigurableAttribute"><configure><p>A Composite actor is an aggregation of actors. It may have a local director that is responsible for executing the contained actors. A Composite actor with a local director is called an opaque actor. Composite actors do not require a local director. Composite actors with no local director "inherit" the director from the containing workflow and are called non-opaque.</ [...]
 </property>        <property name="_location" class="ptolemy.kernel.util.Location" value="[680.0, 1125.0]">
         </property>
-        <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={154, 304, 1537, 944}, maximized=false}">
+        <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={-256, 69, 1532, 923}, maximized=false}">
         </property>
         <property name="_vergilSize" class="ptolemy.actor.gui.SizeAttribute" value="[1220, 771]">
         </property>
@@ -31247,6 +31265,8 @@
             </property>
             <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="XSH_MOD_CFG_OPT_AFC_UVB,XSH_MOD_CFG_OPT_AFC_VIS,XSH_MOD_CFG_OPT_AFC_NIR,ORDER_TAB_AFC_SLIT_UVB,ORDER_TAB_AFC_SLIT_VIS,ORDER_TAB_AFC_SLIT_NIR,ORDER_TAB_AFC_IFU_UVB,ORDER_TAB_AFC_IFU_VIS,ORDER_TAB_AFC_IFU_NIR,DISP_TAB_AFC_UVB,DISP_TAB_AFC_VIS,DISP_TAB_AFC_NIR">
             </property>
+            <property name="Allow empty inputs" class="ptolemy.data.expr.Parameter" value="true">
+            </property>
             <property name="recipe_param_6" class="ptolemy.data.expr.Parameter" value="detectarclines-fit-win-hsize=6">
             </property>
             <property name="recipe_param_7" class="ptolemy.data.expr.Parameter" value="detectarclines-search-win-hsize=3">
@@ -32196,6 +32216,8 @@
             </property>
             <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="BP_MAP_NL_UVB,BP_MAP_NL_VIS,BP_MAP_NL_NIR">
             </property>
+            <property name="Allow empty inputs" class="ptolemy.data.expr.Parameter" value="true">
+            </property>
             <property name="Pause before execution" class="ptolemy.data.expr.Parameter" value="false">
             </property>
             <property name="Pause after execution" class="ptolemy.data.expr.Parameter" value="false">
@@ -32428,7 +32450,7 @@
 <property name="userLevelDocumentation" class="ptolemy.kernel.util.ConfigurableAttribute"><configure><p>A Composite actor is an aggregation of actors. It may have a local director that is responsible for executing the contained actors. A Composite actor with a local director is called an opaque actor. Composite actors do not require a local director. Composite actors with no local director "inherit" the director from the containing workflow and are called non-opaque.</ [...]
 </property>        <property name="_location" class="ptolemy.kernel.util.Location" value="[-140.0, 775.0]">
         </property>
-        <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={0, 98, 1680, 952}, maximized=false}">
+        <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={0, 63, 1680, 952}, maximized=false}">
         </property>
         <property name="_vergilSize" class="ptolemy.actor.gui.SizeAttribute" value="[1504, 800]">
         </property>
@@ -33181,7 +33203,7 @@
 <property name="userLevelDocumentation" class="ptolemy.kernel.util.ConfigurableAttribute"><configure><p>A Composite actor is an aggregation of actors. It may have a local director that is responsible for executing the contained actors. A Composite actor with a local director is called an opaque actor. Composite actors do not require a local director. Composite actors with no local director "inherit" the director from the containing workflow and are called non-opaque.</ [...]
 </property>            <property name="_location" class="ptolemy.kernel.util.Location" value="{305.0, 550.0}">
             </property>
-            <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={86, 122, 1532, 923}, maximized=false}">
+            <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={86, 92, 1532, 923}, maximized=false}">
             </property>
             <property name="_vergilSize" class="ptolemy.actor.gui.SizeAttribute" value="[1220, 771]">
             </property>
@@ -34043,6 +34065,8 @@
                 </property>
                 <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="MASTER_BIAS_UVB,MASTER_BIAS_VIS">
                 </property>
+                <property name="Allow empty inputs" class="ptolemy.data.expr.Parameter" value="true">
+                </property>
                 <property name="_location" class="ptolemy.kernel.util.Location" value="[255.0, 410.0]">
                 </property>
                 <port name="sof in" class="ptolemy.actor.TypedIOPort">
@@ -34246,7 +34270,7 @@
 <property name="userLevelDocumentation" class="ptolemy.kernel.util.ConfigurableAttribute"><configure><p>A Composite actor is an aggregation of actors. It may have a local director that is responsible for executing the contained actors. A Composite actor with a local director is called an opaque actor. Composite actors do not require a local director. Composite actors with no local director "inherit" the director from the containing workflow and are called non-opaque.</ [...]
 </property>            <property name="_location" class="ptolemy.kernel.util.Location" value="[560.0, 490.0]">
             </property>
-            <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={88, 122, 1536, 928}, maximized=false}">
+            <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={88, 92, 1532, 923}, maximized=false}">
             </property>
             <property name="_vergilSize" class="ptolemy.actor.gui.SizeAttribute" value="[1220, 771]">
             </property>
@@ -34825,6 +34849,8 @@
                 </property>
                 <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="MASTER_DARK_UVB,MASTER_DARK_VIS,MASTER_DARK_NIR">
                 </property>
+                <property name="Allow empty inputs" class="ptolemy.data.expr.Parameter" value="true">
+                </property>
                 <property name="_location" class="ptolemy.kernel.util.Location" value="[15.0, 375.0]">
                 </property>
                 <port name="sof in" class="ptolemy.actor.TypedIOPort">
@@ -35100,7 +35126,7 @@
 <property name="userLevelDocumentation" class="ptolemy.kernel.util.ConfigurableAttribute"><configure><p>A Composite actor is an aggregation of actors. It may have a local director that is responsible for executing the contained actors. A Composite actor with a local director is called an opaque actor. Composite actors do not require a local director. Composite actors with no local director "inherit" the director from the containing workflow and are called non-opaque.</ [...]
 </property>        <property name="_location" class="ptolemy.kernel.util.Location" value="[-10.0, 970.0]">
         </property>
-        <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={160, 208, 1327, 816}, maximized=false}">
+        <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={160, 204, 1323, 811}, maximized=false}">
         </property>
         <property name="_vergilSize" class="ptolemy.actor.gui.SizeAttribute" value="[1011, 659]">
         </property>
@@ -35870,7 +35896,7 @@
 <property name="userLevelDocumentation" class="ptolemy.kernel.util.ConfigurableAttribute"><configure><p>A Composite actor is an aggregation of actors. It may have a local director that is responsible for executing the contained actors. A Composite actor with a local director is called an opaque actor. Composite actors do not require a local director. Composite actors with no local director "inherit" the director from the containing workflow and are called non-opaque.</ [...]
 </property>            <property name="_location" class="ptolemy.kernel.util.Location" value="[640.0, 665.0]">
             </property>
-            <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={352, 272, 1327, 762}, maximized=false}">
+            <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={352, 258, 1323, 757}, maximized=false}">
             </property>
             <property name="_vergilSize" class="ptolemy.actor.gui.SizeAttribute" value="[1011, 605]">
             </property>
@@ -36262,6 +36288,8 @@
                 </property>
                 <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="ORDER_TAB_CENTR_UVB,ORDER_TAB_CENTR_VIS,ORDER_TAB_CENTR_NIR,ORDERDEF_ON_UVB,ORDERPOS_RESID_TAB_UVB,ORDERDEF_ON_VIS,ORDERPOS_RESID_TAB_VIS,ORDERDEF_ON_NIR,ORDERPOS_RESID_TAB_NIR">
                 </property>
+                <property name="Allow empty inputs" class="ptolemy.data.expr.Parameter" value="true">
+                </property>
                 <property name="recipe_param_4" class="ptolemy.data.expr.Parameter" value="decode-bp=2144337919">
                 </property>
                 <property name="recipe_param_5" class="ptolemy.data.expr.Parameter" value="pre-overscan-corr=PORT">
@@ -37008,7 +37036,7 @@
 <property name="userLevelDocumentation" class="ptolemy.kernel.util.ConfigurableAttribute"><configure><p>A Composite actor is an aggregation of actors. It may have a local director that is responsible for executing the contained actors. A Composite actor with a local director is called an opaque actor. Composite actors do not require a local director. Composite actors with no local director "inherit" the director from the containing workflow and are called non-opaque.</ [...]
 </property>            <property name="_location" class="ptolemy.kernel.util.Location" value="[450.0, 455.0]">
             </property>
-            <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={-416, 50, 1327, 816}, maximized=false}">
+            <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={0, 50, 1323, 811}, maximized=false}">
             </property>
             <property name="_vergilSize" class="ptolemy.actor.gui.SizeAttribute" value="[1011, 659]">
             </property>
@@ -37776,6 +37804,8 @@
                 </property>
                 <property name="Output Files Category" class="ptolemy.data.expr.StringParameter" value="XSH_MOD_CFG_OPT_FMT_UVB,ORDER_TAB_GUESS_UVB,XSH_MOD_CFG_OPT_FMT_VIS,ORDER_TAB_GUESS_VIS,XSH_MOD_CFG_OPT_FMT_NIR,ORDER_TAB_GUESS_NIR,FMTCHK_ON_UVB,FMTCHK_ON_VIS,FMTCHK_ON_NIR,FMTCHK_RESID_TAB_LINES_UVB,FMTCHK_RESID_TAB_LINES_VIS,FMTCHK_RESID_TAB_LINES_NIR">
                 </property>
+                <property name="Allow empty inputs" class="ptolemy.data.expr.Parameter" value="true">
+                </property>
                 <property name="recipe_param_5" class="ptolemy.data.expr.Parameter" value="pre-overscan-corr=PORT">
                 </property>
                 <property name="recipe_param_6" class="ptolemy.data.expr.Parameter" value="detectarclines-fit-win-hsize=PORT">
@@ -39503,7 +39533,7 @@
         </port>
         <entity name="DataSetChooser" class="org.eso.DataSetChooser">
             <display name="Data Set Chooser"/>
-            <property name="Selection mode" class="ptolemy.data.expr.StringParameter" value="$SelectionDatasetMethod">
+            <property name="Selection mode" class="ptolemy.data.expr.StringParameter" value="$SelectDatasetMethod">
             </property>
             <property name="FITS Viewer" class="ptolemy.data.expr.StringParameter" value="$FITS_VIEWER">
             </property>
@@ -39955,7 +39985,7 @@
             </property>
         </entity>
         <entity name="Display" class="ptolemy.actor.lib.gui.Display">
-            <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={308, 398, 512, 394}, maximized=false}">
+            <property name="_windowProperties" class="ptolemy.actor.gui.WindowPropertiesAttribute" value="{bounds={108, 56, 512, 394}, maximized=false}">
             </property>
             <property name="_paneSize" class="ptolemy.actor.gui.SizeAttribute" value="[508, 346]">
             </property>
@@ -40115,7 +40145,7 @@
             </port>
         </entity>
         <entity name="Directory Maker" class="org.resurgence.actor.DirectoryMaker">
-            <property name="Directory name" class="ptolemy.actor.parameters.PortParameter" value="ROOT_DATA_PATH_TO_REPLACE/reflex_end_products/2014-07-19T07:36:25/XSHOO.2014-04-23T05:59:05.340_tpl">
+            <property name="Directory name" class="ptolemy.actor.parameters.PortParameter" value="ROOT_DATA_PATH_TO_REPLACE/reflex_end_products/2015-01-09T10:08:36/XSHOO.2011-09-20T23:59:56.307_tpl">
             </property>
 <property name="KeplerDocumentation" class="ptolemy.vergil.basic.KeplerDocumentationAttribute">
 <property name="description" class="ptolemy.kernel.util.ConfigurableAttribute"><configure>null</configure></property>
@@ -41233,7 +41263,7 @@
             </property>
         </entity>
         <entity name="Write README" class="org.geon.FileWrite">
-            <property name="fileName" class="ptolemy.actor.parameters.FilePortParameter" value="ROOT_DATA_PATH_TO_REPLACE/reflex_end_products/2014-07-19T07:36:25/README">
+            <property name="fileName" class="ptolemy.actor.parameters.FilePortParameter" value="ROOT_DATA_PATH_TO_REPLACE/reflex_end_products/2015-01-09T10:08:36/README">
             </property>
             <property name="append" class="ptolemy.data.expr.Parameter" value="true">
             </property>
diff --git a/regtests/Makefile.in b/regtests/Makefile.in
index da100b7..907518b 100644
--- a/regtests/Makefile.in
+++ b/regtests/Makefile.in
@@ -83,6 +83,7 @@ DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am
 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps = $(top_srcdir)/m4macros/cpl.m4 \
 	$(top_srcdir)/m4macros/eso.m4 $(top_srcdir)/m4macros/gsl.m4 \
+	$(top_srcdir)/m4macros/hdrl.m4 \
 	$(top_srcdir)/m4macros/libtool.m4 \
 	$(top_srcdir)/m4macros/ltoptions.m4 \
 	$(top_srcdir)/m4macros/ltsugar.m4 \
@@ -214,6 +215,10 @@ GREP = @GREP@
 GSL_INCLUDES = @GSL_INCLUDES@
 GSL_LDFLAGS = @GSL_LDFLAGS@
 GSL_LIBS = @GSL_LIBS@
+HDRL_INCLUDES = @HDRL_INCLUDES@
+HDRL_INTERNAL_CFLAGS = @HDRL_INTERNAL_CFLAGS@
+HDRL_LDFLAGS = @HDRL_LDFLAGS@
+HDRL_LIBS = @HDRL_LIBS@
 INSTALL = @INSTALL@
 INSTALL_DATA = @INSTALL_DATA@
 INSTALL_PROGRAM = @INSTALL_PROGRAM@
@@ -231,6 +236,7 @@ LIBCPLCORE = @LIBCPLCORE@
 LIBCPLDFS = @LIBCPLDFS@
 LIBCPLDRS = @LIBCPLDRS@
 LIBCPLUI = @LIBCPLUI@
+LIBHDRL = @LIBHDRL@
 LIBIRPLIB = @LIBIRPLIB@
 LIBLAPACK = @LIBLAPACK@
 LIBOBJS = @LIBOBJS@
@@ -333,6 +339,7 @@ psdir = @psdir@
 sbindir = @sbindir@
 sharedstatedir = @sharedstatedir@
 srcdir = @srcdir@
+subdirs = @subdirs@
 sysconfdir = @sysconfdir@
 target = @target@
 target_alias = @target_alias@
diff --git a/regtests/tests/Makefile.in b/regtests/tests/Makefile.in
index 11501cd..2f9413e 100644
--- a/regtests/tests/Makefile.in
+++ b/regtests/tests/Makefile.in
@@ -83,6 +83,7 @@ DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am
 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps = $(top_srcdir)/m4macros/cpl.m4 \
 	$(top_srcdir)/m4macros/eso.m4 $(top_srcdir)/m4macros/gsl.m4 \
+	$(top_srcdir)/m4macros/hdrl.m4 \
 	$(top_srcdir)/m4macros/libtool.m4 \
 	$(top_srcdir)/m4macros/ltoptions.m4 \
 	$(top_srcdir)/m4macros/ltsugar.m4 \
@@ -154,6 +155,10 @@ GREP = @GREP@
 GSL_INCLUDES = @GSL_INCLUDES@
 GSL_LDFLAGS = @GSL_LDFLAGS@
 GSL_LIBS = @GSL_LIBS@
+HDRL_INCLUDES = @HDRL_INCLUDES@
+HDRL_INTERNAL_CFLAGS = @HDRL_INTERNAL_CFLAGS@
+HDRL_LDFLAGS = @HDRL_LDFLAGS@
+HDRL_LIBS = @HDRL_LIBS@
 INSTALL = @INSTALL@
 INSTALL_DATA = @INSTALL_DATA@
 INSTALL_PROGRAM = @INSTALL_PROGRAM@
@@ -171,6 +176,7 @@ LIBCPLCORE = @LIBCPLCORE@
 LIBCPLDFS = @LIBCPLDFS@
 LIBCPLDRS = @LIBCPLDRS@
 LIBCPLUI = @LIBCPLUI@
+LIBHDRL = @LIBHDRL@
 LIBIRPLIB = @LIBIRPLIB@
 LIBLAPACK = @LIBLAPACK@
 LIBOBJS = @LIBOBJS@
@@ -273,6 +279,7 @@ psdir = @psdir@
 sbindir = @sbindir@
 sharedstatedir = @sharedstatedir@
 srcdir = @srcdir@
+subdirs = @subdirs@
 sysconfdir = @sysconfdir@
 target = @target@
 target_alias = @target_alias@
diff --git a/xsh/Makefile.am b/xsh/Makefile.am
index 2437276..a63eb20 100644
--- a/xsh/Makefile.am
+++ b/xsh/Makefile.am
@@ -100,7 +100,10 @@ noinst_HEADERS =    xsh_utils.h               \
 			xsh_data_pre_3d.h \
 			xsh_data_star_flux.h \
 			xsh_time.h \
+			xsh_ksigma_clip.h \
 			xsh_detmon.h \
+			xsh_detmon_dfs.h \
+			xsh_detmon_utils.h \
 			xsh_detmon_body.h \
 			xsh_detmon_lg_impl.h \
 			xsh_detmon_lg.h \
@@ -110,7 +113,8 @@ noinst_HEADERS =    xsh_utils.h               \
                         xsh_baryvel.h \
                        xsh_irplib_mkmaster.h \
                        xsh_cpl_size.h \
-                        xsh_blaze.h
+                        xsh_blaze.h \
+                        xsh_hdrl_functions.h
 
 
 pkginclude_HEADERS =
@@ -201,7 +205,9 @@ libxsh_la_SOURCES =    xsh_utils.c               \
 			xsh_compute_response.c \
 			xsh_data_star_flux.c \
 			xsh_time.c \
+			xsh_ksigma_clip.c \
 		       xsh_detmon.c \
+		       xsh_detmon_utils.c \
                        xsh_detmon_lg.c \
                        xsh_data_check.c \
 			xsh_utils_polynomial.c \
@@ -214,10 +220,11 @@ libxsh_la_SOURCES =    xsh_utils.c               \
                         xsh_baryvel.c \
                        xsh_irplib_mkmaster.c \
 			xsh_compute_absorp.c \
-                        xsh_blaze.c
+                        xsh_blaze.c \
+                        xsh_hdrl_functions.c
 
 
 
-libxsh_la_LDFLAGS =   $(LAPACK_LDFLAGS) $(GSL_LDFLAGS) $(CPL_LDFLAGS) -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE)
-libxsh_la_LIBADD = $(LIBCFITSIO) $(LIBIRPLIB) $(LIBCPLDFS) $(LIBCPLUI) $(LIBCPLDRS) $(LIBCPLCORE) $(GSL_LIBS) $(LIBLAPACK)
+libxsh_la_LDFLAGS =   $(LAPACK_LDFLAGS) $(GSL_LDFLAGS) $(CPL_LDFLAGS) $(HDRL_LDFLAGS) -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE)
+libxsh_la_LIBADD = $(LIBCFITSIO) $(LIBIRPLIB) $(LIBCPLDFS) $(LIBCPLUI) $(LIBCPLDRS) $(LIBCPLCORE) $(HDRL_LIBS) $(GSL_LIBS) $(LIBLAPACK) 
 libxsh_la_DEPENDENCIES = $(LIBIRPLIB)
diff --git a/xsh/Makefile.in b/xsh/Makefile.in
index 39a8396..dd206c2 100644
--- a/xsh/Makefile.in
+++ b/xsh/Makefile.in
@@ -87,6 +87,7 @@ DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps = $(top_srcdir)/m4macros/cpl.m4 \
 	$(top_srcdir)/m4macros/eso.m4 $(top_srcdir)/m4macros/gsl.m4 \
+	$(top_srcdir)/m4macros/hdrl.m4 \
 	$(top_srcdir)/m4macros/libtool.m4 \
 	$(top_srcdir)/m4macros/ltoptions.m4 \
 	$(top_srcdir)/m4macros/ltsugar.m4 \
@@ -163,11 +164,12 @@ am_libxsh_la_OBJECTS = xsh_utils.lo xsh_utils_image.lo \
 	xsh_data_image_3d.lo xsh_data_pre_3d.lo \
 	xsh_subtract_sky_single.lo xsh_format.lo \
 	xsh_compute_response.lo xsh_data_star_flux.lo xsh_time.lo \
-	xsh_detmon.lo xsh_detmon_lg.lo xsh_data_check.lo \
-	xsh_utils_polynomial.lo xsh_utils_efficiency.lo \
-	xsh_efficiency_response.lo xsh_data_atmos_ext.lo \
-	xsh_flexcor.lo xsh_ifu.lo xsh_calibrate_flux.lo xsh_baryvel.lo \
-	xsh_irplib_mkmaster.lo xsh_compute_absorp.lo xsh_blaze.lo
+	xsh_ksigma_clip.lo xsh_detmon.lo xsh_detmon_utils.lo \
+	xsh_detmon_lg.lo xsh_data_check.lo xsh_utils_polynomial.lo \
+	xsh_utils_efficiency.lo xsh_efficiency_response.lo \
+	xsh_data_atmos_ext.lo xsh_flexcor.lo xsh_ifu.lo \
+	xsh_calibrate_flux.lo xsh_baryvel.lo xsh_irplib_mkmaster.lo \
+	xsh_compute_absorp.lo xsh_blaze.lo xsh_hdrl_functions.lo
 libxsh_la_OBJECTS = $(am_libxsh_la_OBJECTS)
 AM_V_lt = $(am__v_lt_ at AM_V@)
 am__v_lt_ = $(am__v_lt_ at AM_DEFAULT_V@)
@@ -317,6 +319,10 @@ GREP = @GREP@
 GSL_INCLUDES = @GSL_INCLUDES@
 GSL_LDFLAGS = @GSL_LDFLAGS@
 GSL_LIBS = @GSL_LIBS@
+HDRL_INCLUDES = @HDRL_INCLUDES@
+HDRL_INTERNAL_CFLAGS = @HDRL_INTERNAL_CFLAGS@
+HDRL_LDFLAGS = @HDRL_LDFLAGS@
+HDRL_LIBS = @HDRL_LIBS@
 INSTALL = @INSTALL@
 INSTALL_DATA = @INSTALL_DATA@
 INSTALL_PROGRAM = @INSTALL_PROGRAM@
@@ -334,6 +340,7 @@ LIBCPLCORE = @LIBCPLCORE@
 LIBCPLDFS = @LIBCPLDFS@
 LIBCPLDRS = @LIBCPLDRS@
 LIBCPLUI = @LIBCPLUI@
+LIBHDRL = @LIBHDRL@
 LIBIRPLIB = @LIBIRPLIB@
 LIBLAPACK = @LIBLAPACK@
 LIBOBJS = @LIBOBJS@
@@ -436,6 +443,7 @@ psdir = @psdir@
 sbindir = @sbindir@
 sharedstatedir = @sharedstatedir@
 srcdir = @srcdir@
+subdirs = @subdirs@
 sysconfdir = @sysconfdir@
 target = @target@
 target_alias = @target_alias@
@@ -520,7 +528,10 @@ noinst_HEADERS = xsh_utils.h               \
 			xsh_data_pre_3d.h \
 			xsh_data_star_flux.h \
 			xsh_time.h \
+			xsh_ksigma_clip.h \
 			xsh_detmon.h \
+			xsh_detmon_dfs.h \
+			xsh_detmon_utils.h \
 			xsh_detmon_body.h \
 			xsh_detmon_lg_impl.h \
 			xsh_detmon_lg.h \
@@ -530,7 +541,8 @@ noinst_HEADERS = xsh_utils.h               \
                         xsh_baryvel.h \
                        xsh_irplib_mkmaster.h \
                        xsh_cpl_size.h \
-                        xsh_blaze.h
+                        xsh_blaze.h \
+                        xsh_hdrl_functions.h
 
 pkginclude_HEADERS = 
 privatelib_LTLIBRARIES = libxsh.la
@@ -618,7 +630,9 @@ libxsh_la_SOURCES = xsh_utils.c               \
 			xsh_compute_response.c \
 			xsh_data_star_flux.c \
 			xsh_time.c \
+			xsh_ksigma_clip.c \
 		       xsh_detmon.c \
+		       xsh_detmon_utils.c \
                        xsh_detmon_lg.c \
                        xsh_data_check.c \
 			xsh_utils_polynomial.c \
@@ -631,10 +645,11 @@ libxsh_la_SOURCES = xsh_utils.c               \
                         xsh_baryvel.c \
                        xsh_irplib_mkmaster.c \
 			xsh_compute_absorp.c \
-                        xsh_blaze.c
+                        xsh_blaze.c \
+                        xsh_hdrl_functions.c
 
-libxsh_la_LDFLAGS = $(LAPACK_LDFLAGS) $(GSL_LDFLAGS) $(CPL_LDFLAGS) -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE)
-libxsh_la_LIBADD = $(LIBCFITSIO) $(LIBIRPLIB) $(LIBCPLDFS) $(LIBCPLUI) $(LIBCPLDRS) $(LIBCPLCORE) $(GSL_LIBS) $(LIBLAPACK)
+libxsh_la_LDFLAGS = $(LAPACK_LDFLAGS) $(GSL_LDFLAGS) $(CPL_LDFLAGS) $(HDRL_LDFLAGS) -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE)
+libxsh_la_LIBADD = $(LIBCFITSIO) $(LIBIRPLIB) $(LIBCPLDFS) $(LIBCPLUI) $(LIBCPLDRS) $(LIBCPLCORE) $(HDRL_LIBS) $(GSL_LIBS) $(LIBLAPACK) 
 libxsh_la_DEPENDENCIES = $(LIBIRPLIB)
 all: all-recursive
 
@@ -758,6 +773,7 @@ distclean-compile:
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_detect_order.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_detmon.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_detmon_lg.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_detmon_utils.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_dfs.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_divide.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_drl_check.Plo at am__quote@
@@ -769,9 +785,11 @@ distclean-compile:
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_flexcor.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_follow_arclines.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_format.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_hdrl_functions.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_hist.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_ifu.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_irplib_mkmaster.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_ksigma_clip.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_localize_obj.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_merge_ord.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/xsh_model_anneal.Plo at am__quote@
diff --git a/xsh/tests/Makefile.am b/xsh/tests/Makefile.am
index 1adc2cd..629cf73 100644
--- a/xsh/tests/Makefile.am
+++ b/xsh/tests/Makefile.am
@@ -118,7 +118,10 @@ check_PROGRAMS = test_xsh_prepare \
   test_xsh_telluric_cor \
   test_xsh_bspline \
   test_xsh_bspline_interpol \
-  test_xsh_dfs_sdp
+  test_xsh_dfs_sdp \
+  test_tell_catalog \
+  test_telluric_sampling \
+  test_spectrum_stat
 #The following two requires an input FITS file:
 #  test_xsh_spectrum1d_cut_dichroic_uvb \
 #  test_xsh_image1d_cut_dichroic_uvb
@@ -128,6 +131,15 @@ check_PROGRAMS = test_xsh_prepare \
 #  test_xsh_cpl_vector_correl_hdelta 
 #  test_xsh_data_image_3d 
 
+test_telluric_sampling_SOURCES = test-telluric_sampling.c tests.c
+test_telluric_sampling_LDADD   = $(LIBXSH)
+
+test_spectrum_stat_SOURCES = test-spectrum_stat.c tests.c
+test_spectrum_stat_LDADD   = $(LIBXSH)
+
+test_tell_catalog_SOURCES = test-tell_catalog.c tests.c
+test_tell_catalog_LDADD   = $(LIBXSH)
+
 test_xsh_telluric_cor_SOURCES = test-xsh_telluric_cor.c tests.c
 test_xsh_telluric_cor_LDADD   = $(LIBXSH)
 
@@ -472,7 +484,8 @@ TESTS = test_xsh_prepare\
   test_xsh_correct_vacuum_to_air \
   test_xsh_telluric_cor \
   test_xsh_bspline \
-  test_xsh_dfs_sdp
+  test_xsh_dfs_sdp \
+  test_spectrum_stat
 
 #The following two require an input FITS file
 #  test_xsh_spectrum1d_cut_dichroic_uvb \
diff --git a/xsh/tests/Makefile.in b/xsh/tests/Makefile.in
index 1d09796..1fefbea 100644
--- a/xsh/tests/Makefile.in
+++ b/xsh/tests/Makefile.in
@@ -136,7 +136,9 @@ check_PROGRAMS = test_xsh_prepare$(EXEEXT) test_xsh_data_pre$(EXEEXT) \
 	test_xsh_xcorrel_gaussians$(EXEEXT) \
 	test_xsh_correct_vacuum_to_air$(EXEEXT) \
 	test_xsh_telluric_cor$(EXEEXT) test_xsh_bspline$(EXEEXT) \
-	test_xsh_bspline_interpol$(EXEEXT) test_xsh_dfs_sdp$(EXEEXT)
+	test_xsh_bspline_interpol$(EXEEXT) test_xsh_dfs_sdp$(EXEEXT) \
+	test_tell_catalog$(EXEEXT) test_telluric_sampling$(EXEEXT) \
+	test_spectrum_stat$(EXEEXT)
 TESTS = test_xsh_prepare$(EXEEXT) test_xsh_data_pre$(EXEEXT) \
 	test_xsh_data_spectralformat$(EXEEXT) \
 	test_xsh_remove_crh_multiple$(EXEEXT) \
@@ -193,7 +195,7 @@ TESTS = test_xsh_prepare$(EXEEXT) test_xsh_data_pre$(EXEEXT) \
 	test_xsh_xcorrel_gaussians$(EXEEXT) \
 	test_xsh_correct_vacuum_to_air$(EXEEXT) \
 	test_xsh_telluric_cor$(EXEEXT) test_xsh_bspline$(EXEEXT) \
-	test_xsh_dfs_sdp$(EXEEXT)
+	test_xsh_dfs_sdp$(EXEEXT) test_spectrum_stat$(EXEEXT)
 subdir = xsh/tests
 DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
 	$(top_srcdir)/admin/depcomp $(noinst_HEADERS) \
@@ -201,6 +203,7 @@ DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps = $(top_srcdir)/m4macros/cpl.m4 \
 	$(top_srcdir)/m4macros/eso.m4 $(top_srcdir)/m4macros/gsl.m4 \
+	$(top_srcdir)/m4macros/hdrl.m4 \
 	$(top_srcdir)/m4macros/libtool.m4 \
 	$(top_srcdir)/m4macros/ltoptions.m4 \
 	$(top_srcdir)/m4macros/ltsugar.m4 \
@@ -233,6 +236,18 @@ am_test_product_xsh_master_bias_OBJECTS =  \
 test_product_xsh_master_bias_OBJECTS =  \
 	$(am_test_product_xsh_master_bias_OBJECTS)
 test_product_xsh_master_bias_DEPENDENCIES = $(am__DEPENDENCIES_2)
+am_test_spectrum_stat_OBJECTS = test-spectrum_stat.$(OBJEXT) \
+	tests.$(OBJEXT)
+test_spectrum_stat_OBJECTS = $(am_test_spectrum_stat_OBJECTS)
+test_spectrum_stat_DEPENDENCIES = $(am__DEPENDENCIES_2)
+am_test_tell_catalog_OBJECTS = test-tell_catalog.$(OBJEXT) \
+	tests.$(OBJEXT)
+test_tell_catalog_OBJECTS = $(am_test_tell_catalog_OBJECTS)
+test_tell_catalog_DEPENDENCIES = $(am__DEPENDENCIES_2)
+am_test_telluric_sampling_OBJECTS = test-telluric_sampling.$(OBJEXT) \
+	tests.$(OBJEXT)
+test_telluric_sampling_OBJECTS = $(am_test_telluric_sampling_OBJECTS)
+test_telluric_sampling_DEPENDENCIES = $(am__DEPENDENCIES_2)
 am_test_xsh_atrous_OBJECTS = test-xsh_atrous.$(OBJEXT) tests.$(OBJEXT)
 test_xsh_atrous_OBJECTS = $(am_test_xsh_atrous_OBJECTS)
 test_xsh_atrous_DEPENDENCIES = $(am__DEPENDENCIES_2)
@@ -599,7 +614,9 @@ am__v_CCLD_0 = @echo "  CCLD    " $@;
 am__v_CCLD_1 = 
 SOURCES = $(test_cpl_image_fit_gaussian_SOURCES) \
 	$(test_product_xsh_master_bias_SOURCES) \
-	$(test_xsh_atrous_SOURCES) $(test_xsh_bspline_SOURCES) \
+	$(test_spectrum_stat_SOURCES) $(test_tell_catalog_SOURCES) \
+	$(test_telluric_sampling_SOURCES) $(test_xsh_atrous_SOURCES) \
+	$(test_xsh_bspline_SOURCES) \
 	$(test_xsh_bspline_interpol_SOURCES) \
 	$(test_xsh_build_cube_SOURCES) $(test_xsh_combine_nod_SOURCES) \
 	$(test_xsh_compute_absorp_SOURCES) \
@@ -664,7 +681,9 @@ SOURCES = $(test_cpl_image_fit_gaussian_SOURCES) \
 	$(test_xsh_xcorrel_gaussians_SOURCES)
 DIST_SOURCES = $(test_cpl_image_fit_gaussian_SOURCES) \
 	$(test_product_xsh_master_bias_SOURCES) \
-	$(test_xsh_atrous_SOURCES) $(test_xsh_bspline_SOURCES) \
+	$(test_spectrum_stat_SOURCES) $(test_tell_catalog_SOURCES) \
+	$(test_telluric_sampling_SOURCES) $(test_xsh_atrous_SOURCES) \
+	$(test_xsh_bspline_SOURCES) \
 	$(test_xsh_bspline_interpol_SOURCES) \
 	$(test_xsh_build_cube_SOURCES) $(test_xsh_combine_nod_SOURCES) \
 	$(test_xsh_compute_absorp_SOURCES) \
@@ -995,6 +1014,10 @@ GREP = @GREP@
 GSL_INCLUDES = @GSL_INCLUDES@
 GSL_LDFLAGS = @GSL_LDFLAGS@
 GSL_LIBS = @GSL_LIBS@
+HDRL_INCLUDES = @HDRL_INCLUDES@
+HDRL_INTERNAL_CFLAGS = @HDRL_INTERNAL_CFLAGS@
+HDRL_LDFLAGS = @HDRL_LDFLAGS@
+HDRL_LIBS = @HDRL_LIBS@
 INSTALL = @INSTALL@
 INSTALL_DATA = @INSTALL_DATA@
 INSTALL_PROGRAM = @INSTALL_PROGRAM@
@@ -1012,6 +1035,7 @@ LIBCPLCORE = @LIBCPLCORE@
 LIBCPLDFS = @LIBCPLDFS@
 LIBCPLDRS = @LIBCPLDRS@
 LIBCPLUI = @LIBCPLUI@
+LIBHDRL = @LIBHDRL@
 LIBIRPLIB = @LIBIRPLIB@
 LIBLAPACK = @LIBLAPACK@
 LIBOBJS = @LIBOBJS@
@@ -1114,6 +1138,7 @@ psdir = @psdir@
 sbindir = @sbindir@
 sharedstatedir = @sharedstatedir@
 srcdir = @srcdir@
+subdirs = @subdirs@
 sysconfdir = @sysconfdir@
 target = @target@
 target_alias = @target_alias@
@@ -1143,6 +1168,12 @@ noinst_HEADERS = tests.h
 #  test_xsh_response_fit_bspline \
 #  test_xsh_cpl_vector_correl_hdelta 
 #  test_xsh_data_image_3d 
+test_telluric_sampling_SOURCES = test-telluric_sampling.c tests.c
+test_telluric_sampling_LDADD = $(LIBXSH)
+test_spectrum_stat_SOURCES = test-spectrum_stat.c tests.c
+test_spectrum_stat_LDADD = $(LIBXSH)
+test_tell_catalog_SOURCES = test-tell_catalog.c tests.c
+test_tell_catalog_LDADD = $(LIBXSH)
 test_xsh_telluric_cor_SOURCES = test-xsh_telluric_cor.c tests.c
 test_xsh_telluric_cor_LDADD = $(LIBXSH)
 test_xsh_mark_tell_SOURCES = test-xsh_mark_tell.c tests.c
@@ -1380,6 +1411,18 @@ test_product_xsh_master_bias$(EXEEXT): $(test_product_xsh_master_bias_OBJECTS) $
 	@rm -f test_product_xsh_master_bias$(EXEEXT)
 	$(AM_V_CCLD)$(LINK) $(test_product_xsh_master_bias_OBJECTS) $(test_product_xsh_master_bias_LDADD) $(LIBS)
 
+test_spectrum_stat$(EXEEXT): $(test_spectrum_stat_OBJECTS) $(test_spectrum_stat_DEPENDENCIES) $(EXTRA_test_spectrum_stat_DEPENDENCIES) 
+	@rm -f test_spectrum_stat$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(test_spectrum_stat_OBJECTS) $(test_spectrum_stat_LDADD) $(LIBS)
+
+test_tell_catalog$(EXEEXT): $(test_tell_catalog_OBJECTS) $(test_tell_catalog_DEPENDENCIES) $(EXTRA_test_tell_catalog_DEPENDENCIES) 
+	@rm -f test_tell_catalog$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(test_tell_catalog_OBJECTS) $(test_tell_catalog_LDADD) $(LIBS)
+
+test_telluric_sampling$(EXEEXT): $(test_telluric_sampling_OBJECTS) $(test_telluric_sampling_DEPENDENCIES) $(EXTRA_test_telluric_sampling_DEPENDENCIES) 
+	@rm -f test_telluric_sampling$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(test_telluric_sampling_OBJECTS) $(test_telluric_sampling_LDADD) $(LIBS)
+
 test_xsh_atrous$(EXEEXT): $(test_xsh_atrous_OBJECTS) $(test_xsh_atrous_DEPENDENCIES) $(EXTRA_test_xsh_atrous_DEPENDENCIES) 
 	@rm -f test_xsh_atrous$(EXEEXT)
 	$(AM_V_CCLD)$(LINK) $(test_xsh_atrous_OBJECTS) $(test_xsh_atrous_LDADD) $(LIBS)
@@ -1700,6 +1743,9 @@ distclean-compile:
 
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test-cpl_image_fit_gaussian.Po at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test-product_xsh_master_bias.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test-spectrum_stat.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test-tell_catalog.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test-telluric_sampling.Po at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test-xsh_atrous.Po at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test-xsh_bspline.Po at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test-xsh_bspline_interpol.Po at am__quote@
@@ -2560,6 +2606,13 @@ test_xsh_dfs_sdp.log: test_xsh_dfs_sdp$(EXEEXT)
 	--log-file $$b.log --trs-file $$b.trs \
 	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
 	"$$tst" $(AM_TESTS_FD_REDIRECT)
+test_spectrum_stat.log: test_spectrum_stat$(EXEEXT)
+	@p='test_spectrum_stat$(EXEEXT)'; \
+	b='test_spectrum_stat'; \
+	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
+	--log-file $$b.log --trs-file $$b.trs \
+	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
+	"$$tst" $(AM_TESTS_FD_REDIRECT)
 .test.log:
 	@p='$<'; \
 	$(am__set_b); \
diff --git a/xsh/tests/test-xsh_slitmap.c b/xsh/tests/test-spectrum_stat.c
similarity index 51%
copy from xsh/tests/test-xsh_slitmap.c
copy to xsh/tests/test-spectrum_stat.c
index d7f4e6d..ba251cf 100644
--- a/xsh/tests/test-xsh_slitmap.c
+++ b/xsh/tests/test-spectrum_stat.c
@@ -18,10 +18,10 @@
  *                                                                            */
 
 /*
- * $Author: rhaigron $
- * $Date: 2010-09-25 13:45:38 $
- * $Revision: 1.6 $
- *
+ * $Author: amodigli $
+ * $Date: 2011-12-02 14:13:14 $
+ * $Revision: 1.3 $
+ * $Name: not supported by cvs2svn $
  */
 #ifdef HAVE_CONFIG_H
 #  include <config.h>
@@ -29,143 +29,80 @@
 
 /*--------------------------------------------------------------------------*/
 /**
- * @defgroup test_xsh_slitmap     Test Data type ORDER functions
- * @ingroup unit_tests
- *
- */
+  @defgroup xsh_test_tools     
+    Test some tools functions for performances check
+  @ingroup unit_tests
+*/
 /*--------------------------------------------------------------------------*/
 /**@{*/
 
 /*---------------------------------------------------------------------------
                                 Includes
  ---------------------------------------------------------------------------*/
-
-
-#include <xsh_data_order.h>
+#include <xsh_utils.h>
 #include <xsh_error.h>
 #include <xsh_msg.h>
-#include <xsh_data_instrument.h>
-#include <xsh_dfs.h>
-#include <xsh_pfits.h>
 #include <tests.h>
-#include <xsh_utils_table.h>
 #include <cpl.h>
 #include <math.h>
-#include <getopt.h>
-#include <xsh_drl.h>
-
+#include <time.h>
+#include <sys/time.h>
 /*---------------------------------------------------------------------------
                             Defines
  ---------------------------------------------------------------------------*/
-#define XSH_FLOAT_PRECISION 0.000001
-#define MODULE_ID "XSH_SLITMAP"
-
-enum {
-  BINX_OPT, BINY_OPT,DEBUG_OPT, HELP_OPT
-} ;
-
-static struct option LongOptions[] = {
-  {"debug", required_argument, 0, DEBUG_OPT},
-  {"help", 0, 0, HELP_OPT},
-  {NULL, 0, 0, 0}
-} ;
-
-
-static void Help( void )
-{
-  puts ("Computes the slilet sizes with Order Table and SLIT MAP");
-  puts( "Usage : ./test_xsh_slitmap <sof>");
-
-  puts( "Options" ) ;
-  puts( " --debug=<n>        : Level of debug LOW | MEDIUM | HIGH [MEDIUM]" );
-  puts( " --help             : What you see" ) ;
-
-  puts( "The input files argument MUST be in this order:" ) ;
-  puts( " 1. SOF [IFU_MAP|SLIT_MAP]");
-
-  TEST_END();
-  exit(0);
-}
-
-static void HandleOptions( int argc, char ** argv)
-{
-  int opt ;
-  int option_index = 0;
-
-  while( (opt = getopt_long( argc, argv, "debug:help",
-                             LongOptions, &option_index )) != EOF )
-    switch( opt ) {
-    case DEBUG_OPT:
-      if ( strcmp( optarg, "LOW")==0){
-        xsh_debug_level_set( XSH_DEBUG_LEVEL_LOW);
-      }
-      else if ( strcmp( optarg, "HIGH")==0){
-        xsh_debug_level_set( XSH_DEBUG_LEVEL_HIGH);
-      }
-      break;
-    case HELP_OPT:
-      Help();
-      break;
-    default:
-      break;
-    }
-}
+#define MODULE_ID "CPL_IMAGE_FIT_GAUSSIAN"
 
 /*--------------------------------------------------------------------------*/
 /**
   @brief
-    Unit test of xsh_slitmap
+    Some test about performances
   @return
-    0 if success
-
-*/
+ */
 /*--------------------------------------------------------------------------*/
-int main(int argc, char** argv)
+int main( int argc, char** argv)
 {
   int ret = 0;
-  xsh_instrument *instrument = NULL ;
-
-  const char *sof_name = NULL;
-  cpl_frameset *set = NULL;
-  cpl_frame * slitmap_frame = NULL ;
-  double sd, su, sld, slu;
 
-  /* Initialize libraries */
   TESTS_INIT( MODULE_ID);
   cpl_msg_set_level( CPL_MSG_DEBUG);
   xsh_debug_level_set( XSH_DEBUG_LEVEL_MEDIUM) ;
 
-  HandleOptions( argc, argv);
-
-  if ( (argc-optind) >= 1 ) {
-    sof_name = argv[optind];
-  }
-  else {
-    Help();
-    exit( 0);
+  char name1[256];
+  cpl_table* tab1=NULL;
+
+  double mean=0;
+  double rms=0;
+  double median=0;
+  double min=0;
+  double max=0;
+  int i=0;
+
+  xsh_msg("argc=%d",argc);
+  if((size_t)argc != 2){
+      xsh_msg_warning("Provide one inputs: spectra tables");
+      return 0;
+  } else {
+      sprintf(name1,argv[1]);
   }
 
-  /* Create frameset from sof */
-  check( set = sof_to_frameset( sof_name));
-
-  /* Validate frame set */
-  check( instrument = xsh_dfs_set_groups( set));
+  tab1=cpl_table_load(name1, 1, 1);
 
-  check( slitmap_frame = xsh_find_slitmap( set, instrument));
-  xsh_msg("SLITMAP        : %s",
-    cpl_frame_get_filename( slitmap_frame));
+  mean=cpl_table_get_column_mean(tab1,"counts_bkg");
+  median=cpl_table_get_column_median(tab1,"counts_bkg");
+  min=cpl_table_get_column_min(tab1,"counts_bkg");
+  max=cpl_table_get_column_max(tab1,"counts_bkg");
+  rms=cpl_table_get_column_stdev(tab1,"counts_bkg");
 
-  check( xsh_get_slit_edges( slitmap_frame, &sd, &su, &sld, &slu, instrument));
+  xsh_msg_warning("Spectrum %s mean: %g median: %g min: %g max: %g rms: %g",
+          name1,mean,median,min,max,rms);
+  cpl_table_delete(tab1);
 
   cleanup:
     if (cpl_error_get_code() != CPL_ERROR_NONE) {
       xsh_error_dump(CPL_MSG_ERROR);
-      ret = 1;
+      ret  = 1;
     }
-    xsh_free_frameset( &set);
-    xsh_instrument_free( &instrument);
-    TEST_END();
-    return ret ;
+    return ret;
 }
 
 /**@}*/
diff --git a/xsh/tests/test-tell_catalog.c b/xsh/tests/test-tell_catalog.c
new file mode 100644
index 0000000..77b17b6
--- /dev/null
+++ b/xsh/tests/test-tell_catalog.c
@@ -0,0 +1,145 @@
+/*                                                                            *
+ *   This file is part of the ESO X-shooter Pipeline                          *
+ *   Copyright (C) 2006 European Southern Observatory                         *
+ *                                                                            *
+ *   This library is free software; you can redistribute it and/or modify     *
+ *   it under the terms of the GNU General Public License as published by     *
+ *   the Free Software Foundation; either version 2 of the License, or        *
+ *   (at your option) any later version.                                      *
+ *                                                                            *
+ *   This program is distributed in the hope that it will be useful,          *
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of           *
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
+ *   GNU General Public License for more details.                             *
+ *                                                                            *
+ *   You should have received a copy of the GNU General Public License        *
+ *   along with this program; if not, write to the Free Software              *
+ *   Foundation, 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA     *
+ *                                                                            */
+
+/*
+ * $Author: amodigli $
+ * $Date: 2011-12-02 14:13:14 $
+ * $Revision: 1.3 $
+ * $Name: not supported by cvs2svn $
+ */
+#ifdef HAVE_CONFIG_H
+#  include <config.h>
+#endif
+
+/*--------------------------------------------------------------------------*/
+/**
+  @defgroup xsh_test_tools     
+    Test some tools functions for performances check
+  @ingroup unit_tests
+*/
+/*--------------------------------------------------------------------------*/
+/**@{*/
+
+/*---------------------------------------------------------------------------
+                                Includes
+ ---------------------------------------------------------------------------*/
+#include <xsh_utils.h>
+#include <xsh_error.h>
+#include <xsh_msg.h>
+#include <tests.h>
+#include <cpl.h>
+#include <math.h>
+#include <time.h>
+#include <sys/time.h>
+/*---------------------------------------------------------------------------
+                            Defines
+ ---------------------------------------------------------------------------*/
+#define MODULE_ID "CPL_IMAGE_FIT_GAUSSIAN"
+
+/*--------------------------------------------------------------------------*/
+/**
+  @brief
+    Some test about performances
+  @return
+ */
+/*--------------------------------------------------------------------------*/
+int test_catalog()
+{
+  int ret = 0;
+
+  char namei[180];
+  char nameo[80];
+  cpl_table* tbl=NULL;
+  cpl_propertylist* plist=NULL;
+  int next=2; //72
+  int nrow;
+  double* wave=NULL;
+  double lambda=0;
+  double lambda2=0;
+  double lambda4=0;
+
+  double lam_c=0;
+  int i=0;
+  int j=0;
+  double um2angstrom=1.e4;
+
+  cpl_frame* frame=NULL;
+  
+  sprintf(namei,"/home/amodigli/pipelines/workspace/xshoop/xsh/tests/telluric_model_catalog_vis.fits");
+  sprintf(nameo,"telluric_model_catalog_vis_new.fits");
+  frame=cpl_frame_new();
+  cpl_frame_set_filename(frame,namei);
+  cpl_frame_set_type(frame,CPL_FRAME_TYPE_TABLE);
+  cpl_frame_set_tag(frame,"TEST");
+  cpl_frame_set_group(frame,CPL_FRAME_GROUP_CALIB);
+  next=cpl_frame_get_nextensions(frame);
+
+  for(i=0;i<next;i++) {
+     xsh_msg_warning("process ext %d",i);
+     tbl=cpl_table_load(namei, i+1, 1);
+     plist=cpl_propertylist_load(namei,i);
+     nrow=cpl_table_get_nrow(tbl);
+     xsh_msg("nrow %d",nrow);
+     wave=cpl_table_get_data_double(tbl,"lam");
+     for(j=0;j<nrow;j++) {
+         /* the coefficient below refers to Angstrom units while the telluric
+          * model catalog has wavelengths expressed in um
+          */
+        lambda=1.e4*wave[j];
+        lambda2=lambda*lambda;
+        lambda4=lambda2*lambda2;
+        /* to come back to um we multiply by 10-4 */
+        lam_c=1.e-4*lambda/(1.0002735182+131.4182/lambda2+2.76249e8/lambda4);
+        wave[j]=lam_c;
+     }
+     xsh_msg("saving ext %d",i);
+     if(i==0) {
+        cpl_table_save(tbl,plist,NULL,nameo,CPL_IO_DEFAULT);
+     } else {
+        cpl_table_save(tbl,plist,NULL,nameo,CPL_IO_EXTEND);
+     }
+
+
+     xsh_msg("saved ext %d",i);
+     xsh_free_table(&tbl);
+     xsh_free_propertylist(&plist);
+  }
+  cpl_frame_delete(frame);
+ 
+  cleanup:
+    if (cpl_error_get_code() != CPL_ERROR_NONE) {
+      xsh_error_dump(CPL_MSG_ERROR);
+      ret  = 1;
+    }
+    return ret;
+}
+
+
+int main(int argc, char* argv[])
+{
+
+    cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
+    //test_catalog();
+
+
+    return cpl_test_end(0);
+}
+
+
+/**@}*/
diff --git a/xsh/tests/test-xsh_correct_vacuum_to_air.c b/xsh/tests/test-telluric_sampling.c
similarity index 51%
copy from xsh/tests/test-xsh_correct_vacuum_to_air.c
copy to xsh/tests/test-telluric_sampling.c
index 4a72559..119689f 100644
--- a/xsh/tests/test-xsh_correct_vacuum_to_air.c
+++ b/xsh/tests/test-telluric_sampling.c
@@ -19,8 +19,8 @@
 
 /*
  * $Author: amodigli $
- * $Date: 2012-08-02 13:29:37 $
- * $Revision: 1.2 $
+ * $Date: 2011-12-02 14:13:14 $
+ * $Revision: 1.3 $
  * $Name: not supported by cvs2svn $
  */
 #ifdef HAVE_CONFIG_H
@@ -30,8 +30,7 @@
 /*--------------------------------------------------------------------------*/
 /**
   @defgroup xsh_test_tools     
-    Apply formula:
-    lam_air = lam_vac/(1.0002735182+131.4182/lam_vac2+2.76249E8/lam_vac4)
+    Test some tools functions for performances check
   @ingroup unit_tests
 */
 /*--------------------------------------------------------------------------*/
@@ -40,20 +39,18 @@
 /*---------------------------------------------------------------------------
                                 Includes
  ---------------------------------------------------------------------------*/
+#include <xsh_utils.h>
 #include <xsh_error.h>
 #include <xsh_msg.h>
-#include <xsh_data_instrument.h>
-#include <xsh_pfits.h>
 #include <tests.h>
 #include <cpl.h>
 #include <math.h>
 #include <time.h>
 #include <sys/time.h>
-#include <xsh_cpl_size.h>
 /*---------------------------------------------------------------------------
                             Defines
  ---------------------------------------------------------------------------*/
-#define MODULE_ID "XSH_CORRECT_VACUUM_TO_AIR"
+#define MODULE_ID "CPL_IMAGE_FIT_GAUSSIAN"
 
 /*--------------------------------------------------------------------------*/
 /**
@@ -66,92 +63,86 @@ int main( int argc, char** argv)
 {
   int ret = 0;
 
-  cpl_table* table_names = NULL;
-  cpl_table* table_spect = NULL;
-  cpl_frame* std_catalog = NULL;
-  cpl_propertylist* phead = NULL;
-  cpl_propertylist* xhead = NULL;
-
-  //xsh_instrument* instrument = NULL;
-  const char* fname_out = "catalog_new.fits";
-  const char* fname_inp;
-
-  int nb_frames = 0;
-  int next = 0;
-  int i = 0;
-  int nrow = 0;
-  int j = 0;
-
-  double* plambda = NULL;
-  //double* pflux = NULL;
-  //double* pbin = NULL;
-  double c1 = 1.0002735182;
-  double c2 = 131.4182;
-  double c4 = 2.76249E8;
-  double w = 0;
-  double w2 = 0;
-  double w4 = 0;
-  double wair=0;
-
-  double nm2AA=10.;
-
   TESTS_INIT( MODULE_ID);
-  cpl_msg_set_level(CPL_MSG_DEBUG);
-  xsh_debug_level_set(XSH_DEBUG_LEVEL_MEDIUM);
-
-  nb_frames = argc - optind;
-  if (nb_frames == 1) {
-    fname_inp = argv[optind];
+  cpl_msg_set_level( CPL_MSG_DEBUG);
+  xsh_debug_level_set( XSH_DEBUG_LEVEL_MEDIUM) ;
+
+  char name1[256];
+  char name2[256];
+
+  cpl_table* tab1=NULL;
+  cpl_table* tab2=NULL;
+  cpl_table* tabo=NULL;
+  cpl_propertylist* plist=NULL;
+
+  int nrows;
+  double* pratio=NULL;
+  double* praw1=NULL;
+  double* praw2=NULL;
+  float* pwav1=NULL;
+  double* pwavo=NULL;
+  double mean=0;
+  double rms=0;
+  double median=0;
+  double min=0;
+  double max=0;
+  int i=0;
+  xsh_msg("argc=%d",argc);
+  if((size_t)argc != 3){
+      xsh_msg_error("Provide two inputs: resp1, resp2 tables");
   } else {
-    xsh_msg( "********** NOT ENOUGH INPUT FRAMES **********" );
-    exit(0);
+      sprintf(name1,argv[1]);
+      sprintf(name2,argv[2]);
   }
 
-  std_catalog = cpl_frame_new();
-  cpl_frame_set_filename(std_catalog, fname_inp);
-  next = cpl_frame_get_nextensions(std_catalog);
-  phead = cpl_propertylist_load(fname_inp, 0);
-  table_names = cpl_table_load(fname_inp, 1, 0);
-  xhead = cpl_propertylist_load(fname_inp, 1);
-  cpl_table_save(table_names, phead, xhead, fname_out, CPL_IO_DEFAULT);
-
-  for (i = 2; i <= next; i++) {
-
-    table_spect = cpl_table_load(fname_inp, i, 0);
-    xhead = cpl_propertylist_load(fname_inp, i);
-    plambda = cpl_table_get_data_double(table_spect, "LAMBDA");
-    nrow = cpl_table_get_nrow(table_spect);
-
-    if (i == 2 || i == 4) {
-      /* only for GD71,GD153, that are at extention 2,4 of catalogue apply correction */
-      for (j = 0; j < nrow; j++) {
-        w = nm2AA * plambda[j];
-        w2 = w * w;
-        w4 = w2*w2;
-        wair = w / (c1 + c2 / w2 + c4 / w4 );
-        plambda[j] = wair / nm2AA;
-        //xsh_msg("w_cor star[%d]= %g [AA]",i, w-wair);
-      }
-    }
-    xsh_msg("save out tab on file %s",fname_out);
-    check(cpl_table_save(table_spect, xhead, NULL, fname_out, CPL_IO_EXTEND));
-    xsh_free_propertylist(&xhead);
-    xsh_free_table(&table_spect);
-
+  tab1=cpl_table_load(name1, 1, 1);
+  tab2=cpl_table_load(name1, 1, 1);
+  nrows=cpl_table_get_nrow(tab1);
+
+  tabo=cpl_table_new(nrows);
+  cpl_table_new_column(tabo,"wave",CPL_TYPE_DOUBLE);
+  cpl_table_new_column(tabo,"ratio",CPL_TYPE_DOUBLE);
+
+  cpl_table_fill_column_window_double(tabo, "ratio", 0, nrows, 0);
+  cpl_table_fill_column_window_double(tabo, "wave", 0, nrows, 0);
+  pratio=cpl_table_get_data_double(tabo,"ratio");
+  praw1=cpl_table_get_data_double(tab1,"REF_DIV_OBS");
+
+  praw2=cpl_table_get_data_double(tab2,"REF_DIV_OBS");
+  pwav1=cpl_table_get_data_float(tab1,"LAMBDA");
+  pwavo=cpl_table_get_data_double(tabo,"wave");
+  for(i=0;i<nrows;i++) {
+     pwavo[i]=(double)pwav1[i];
+     pratio[i]=praw1[i]/praw2[i];
   }
 
-
-  cleanup: xsh_free_table(&table_names);
-  xsh_free_table(&table_spect);
-  xsh_free_propertylist(&xhead);
-  xsh_free_propertylist(&phead);
-  xsh_free_frame(&std_catalog);
-
-  if (cpl_error_get_code() != CPL_ERROR_NONE) {
-    xsh_error_dump(CPL_MSG_ERROR);
-    ret = 1;
-  }
-  return ret;
+  mean=cpl_table_get_column_mean(tabo,"ratio");
+  median=cpl_table_get_column_median(tabo,"ratio");
+  min=cpl_table_get_column_min(tabo,"ratio");
+  max=cpl_table_get_column_max(tabo,"ratio");
+  rms=cpl_table_get_column_stdev(tabo,"ratio");
+
+  plist=cpl_propertylist_new();
+  cpl_propertylist_append_double(plist,"MEAN",mean);
+  cpl_propertylist_append_double(plist,"MEDIAN",median);
+  cpl_propertylist_append_double(plist,"RMS",rms);
+  cpl_propertylist_append_double(plist,"MIN",min);
+  cpl_propertylist_append_double(plist,"MAX",max);
+
+  cpl_table_save(tabo,plist,NULL,"ratio.fits",CPL_IO_DEFAULT);
+
+  cpl_table_delete(tab1);
+  cpl_table_delete(tab2);
+  cpl_table_delete(tabo);
+  cpl_propertylist_delete(plist);
+  xsh_msg_warning("statistic: mean: %g median: %g rms: %g min: %g max: %g",
+                  mean,median,rms,min,max);
+  cleanup:
+    if (cpl_error_get_code() != CPL_ERROR_NONE) {
+      xsh_error_dump(CPL_MSG_ERROR);
+      ret  = 1;
+    }
+    return ret;
 }
 
 /**@}*/
diff --git a/xsh/tests/test-xsh_bspline_interpol.c b/xsh/tests/test-xsh_bspline_interpol.c
index 632d198..20503d4 100644
--- a/xsh/tests/test-xsh_bspline_interpol.c
+++ b/xsh/tests/test-xsh_bspline_interpol.c
@@ -51,7 +51,7 @@
 #include <math.h>
 #include <gsl/gsl_errno.h>
 #include <gsl/gsl_spline.h>
-
+#include <getopt.h>
 /*--------------------------------------------------------------------------
   Defines
   --------------------------------------------------------------------------*/
diff --git a/xsh/tests/test-xsh_compute_noise_map.c b/xsh/tests/test-xsh_compute_noise_map.c
index be20e42..0fd1169 100644
--- a/xsh/tests/test-xsh_compute_noise_map.c
+++ b/xsh/tests/test-xsh_compute_noise_map.c
@@ -54,7 +54,7 @@
 #include <tests.h>
 #include <cpl.h>
 #include <math.h>
-
+#include <getopt.h>
 /*---------------------------------------------------------------------------
                             Defines
  ---------------------------------------------------------------------------*/
diff --git a/xsh/tests/test-xsh_correct_vacuum_to_air.c b/xsh/tests/test-xsh_correct_vacuum_to_air.c
index 4a72559..15e5e21 100644
--- a/xsh/tests/test-xsh_correct_vacuum_to_air.c
+++ b/xsh/tests/test-xsh_correct_vacuum_to_air.c
@@ -48,8 +48,11 @@
 #include <cpl.h>
 #include <math.h>
 #include <time.h>
+#include <getopt.h>
 #include <sys/time.h>
 #include <xsh_cpl_size.h>
+#include <getopt.h>
+
 /*---------------------------------------------------------------------------
                             Defines
  ---------------------------------------------------------------------------*/
diff --git a/xsh/tests/test-xsh_create_master_bias.c b/xsh/tests/test-xsh_create_master_bias.c
index 12d2050..d6913b4 100644
--- a/xsh/tests/test-xsh_create_master_bias.c
+++ b/xsh/tests/test-xsh_create_master_bias.c
@@ -93,7 +93,8 @@ int main(void)
   const char* RECIPE_ID="xsh_mbias";
   const char* ftag=NULL;
   const int decode_bp=2147483647;
-
+ 
+  int nframes=5;
   /* Initialize libraries */
   TESTS_INIT_WORKSPACE(MODULE_ID);
   TESTS_INIT(MODULE_ID);
@@ -108,11 +109,15 @@ int main(void)
   ftag=XSH_GET_TAG_FROM_ARM(XSH_MASTER_BIAS,instrument);
 
   /* Create a frame and add it to frameset*/
-  frame = xsh_test_create_frame("frame.fits",10,10,
-    XSH_BIAS_UVB,CPL_FRAME_GROUP_RAW, instrument);
   set = cpl_frameset_new();
-  cpl_frameset_insert(set,frame);
-
+  for(int i=0;i<nframes;i++) {
+     name=cpl_sprintf("frame%d.fits",i);
+     frame = xsh_test_create_frame(name,20,20,
+       XSH_BIAS_UVB,CPL_FRAME_GROUP_RAW, instrument);
+     cpl_frameset_insert(set,cpl_frame_duplicate(frame));
+     xsh_free_frame(&frame);
+     cpl_free(name);
+  }
 
   /* Set generic parameters (common to all recipes) */
   parameters = cpl_parameterlist_new();
diff --git a/xsh/tests/test-xsh_create_master_dark.c b/xsh/tests/test-xsh_create_master_dark.c
index 27a1b5c..871c396 100644
--- a/xsh/tests/test-xsh_create_master_dark.c
+++ b/xsh/tests/test-xsh_create_master_dark.c
@@ -92,6 +92,7 @@ int main(void)
   char* name=NULL;
   cpl_propertylist* header=NULL;
   cpl_image* ima=NULL;
+  int nframes=5;
   const int decode_bp=2147483647;
   /* Initialize libraries */
   TESTS_INIT_WORKSPACE(MODULE_ID);
@@ -122,10 +123,17 @@ int main(void)
 
 
   /* Create a frame and add it to frameset*/
-  frame = xsh_test_create_frame("frame.fits",10,10,
-    XSH_BIAS_UVB,CPL_FRAME_GROUP_RAW, instrument);
+  /* Create a frame and add it to frameset*/
   set = cpl_frameset_new();
-  cpl_frameset_insert(set,frame);
+  for(int i=0;i<nframes;i++) {
+     name=cpl_sprintf("frame%d.fits",i);
+     frame = xsh_test_create_frame(name,20,20,
+       XSH_DARK_UVB,CPL_FRAME_GROUP_RAW, instrument);
+     cpl_frameset_insert(set,cpl_frame_duplicate(frame));
+     xsh_free_frame(&frame);
+     cpl_free(name);
+  }
+
   xsh_instrument_set_decode_bp( instrument, decode_bp ) ;
   /* Create a PRE frame */
   check(xsh_prepare(set,NULL, NULL, "PRE",instrument,0,CPL_FALSE));
diff --git a/xsh/tests/test-xsh_data_order.c b/xsh/tests/test-xsh_data_order.c
index f6e02a5..47be5d2 100644
--- a/xsh/tests/test-xsh_data_order.c
+++ b/xsh/tests/test-xsh_data_order.c
@@ -56,7 +56,6 @@
 /*---------------------------------------------------------------------------
                             Defines
  ---------------------------------------------------------------------------*/
-#define XSH_FLOAT_PRECISION 0.000001
 #define MODULE_ID "XSH_DATA_ORDER"
 
 #define SYNTAX "Test the order table\n"\
diff --git a/xsh/tests/test-xsh_data_wave_tab_2d.c b/xsh/tests/test-xsh_data_wave_tab_2d.c
index 7568113..e7b485c 100644
--- a/xsh/tests/test-xsh_data_wave_tab_2d.c
+++ b/xsh/tests/test-xsh_data_wave_tab_2d.c
@@ -59,7 +59,6 @@
 /*---------------------------------------------------------------------------
                             Defines
  ---------------------------------------------------------------------------*/
-#define XSH_FLOAT_PRECISION 0.000001
 #define MODULE_ID "XSH_DATA_WAVE_TAB_2D"
 
 enum {
diff --git a/xsh/tests/test-xsh_data_wave_tab_2d_sample.c b/xsh/tests/test-xsh_data_wave_tab_2d_sample.c
index 1a81056..5ae4515 100644
--- a/xsh/tests/test-xsh_data_wave_tab_2d_sample.c
+++ b/xsh/tests/test-xsh_data_wave_tab_2d_sample.c
@@ -59,7 +59,6 @@
 /*---------------------------------------------------------------------------
                             Defines
  ---------------------------------------------------------------------------*/
-#define XSH_FLOAT_PRECISION 0.000001
 #define MODULE_ID "XSH_DATA_WAVE_TAB_2D_SAMPLE"
 
 #define SYNTAX "Test the wave tab 2d\n"\
diff --git a/xsh/tests/test-xsh_detect_line_file.c b/xsh/tests/test-xsh_detect_line_file.c
index 08060a0..ca491c9 100644
--- a/xsh/tests/test-xsh_detect_line_file.c
+++ b/xsh/tests/test-xsh_detect_line_file.c
@@ -51,6 +51,7 @@
 #include <math.h>
 #include <time.h>
 #include <sys/time.h>
+#include <getopt.h>
 #include <xsh_cpl_size.h>
 /*---------------------------------------------------------------------------
                             Defines
diff --git a/xsh/tests/test-xsh_slitmap.c b/xsh/tests/test-xsh_slitmap.c
index d7f4e6d..4c1f7f9 100644
--- a/xsh/tests/test-xsh_slitmap.c
+++ b/xsh/tests/test-xsh_slitmap.c
@@ -57,7 +57,6 @@
 /*---------------------------------------------------------------------------
                             Defines
  ---------------------------------------------------------------------------*/
-#define XSH_FLOAT_PRECISION 0.000001
 #define MODULE_ID "XSH_SLITMAP"
 
 enum {
diff --git a/xsh/tests/test-xsh_subtract_sky_nod.c b/xsh/tests/test-xsh_subtract_sky_nod.c
index 83dfd69..09fc734 100644
--- a/xsh/tests/test-xsh_subtract_sky_nod.c
+++ b/xsh/tests/test-xsh_subtract_sky_nod.c
@@ -55,7 +55,6 @@
 /*---------------------------------------------------------------------------
                             Defines
  ---------------------------------------------------------------------------*/
-#define XSH_FLOAT_PRECISION 0.000001
 #define MODULE_ID "XSH_SUBTRACT_SKY_NOD"
 
 #define SYNTAX "Test xsh_subtract_sky_nod\n"\
diff --git a/xsh/tests/tests.c b/xsh/tests/tests.c
index 6c87414..e7aa1cc 100644
--- a/xsh/tests/tests.c
+++ b/xsh/tests/tests.c
@@ -61,6 +61,27 @@
 /*---------------------------------------------------------------------------
   Defines
   ---------------------------------------------------------------------------*/
+/*----------------------------------------------------------------------------*/
+/**
+ * AMO added (useful in unit tests)
+  @brief    generates random data with Poisson distribution
+  @param    expectedValue random generator goal value
+  @return   random value
+ */
+/*----------------------------------------------------------------------------*/
+static int xsh_poisson_random(double expectedValue) {
+    int n = 0; //counter of iteration
+    double limit;
+    double x;  //pseudo random number
+    limit = exp(-expectedValue);
+    x = (double)rand() / (double)INT_MAX;
+    while (x > limit) {
+      n++;
+      x *= (double)rand() / (double)INT_MAX;
+    }
+    return n;
+  }
+
 
 /*---------------------------------------------------------------------------
   Functions implementation
@@ -103,7 +124,9 @@ cpl_frame* xsh_test_create_frame(const char* name,int nx, int ny,
   cpl_propertylist *header = NULL;
   cpl_image *data = NULL;
   cpl_frame *frame = NULL;
-
+  float* pdata=NULL;
+  int size=nx*ny;
+  int i,j;
   XSH_ASSURE_NOT_NULL( instrument);
   XSH_ASSURE_NOT_NULL( name);
 
@@ -118,9 +141,14 @@ cpl_frame* xsh_test_create_frame(const char* name,int nx, int ny,
 			  50,     /* norm */
 			  nx, ny / 8.0); /* sigma */
 
+  /* add random noise, centered at 100 */
+  pdata=cpl_image_get_data_float(data);
+  for(j=0;j<size;j++) {
+      pdata[j]+=xsh_poisson_random(100.);
+  }
   check( cpl_image_save(data, name, XSH_PRE_DATA_BPP,header,
     CPL_IO_DEFAULT));
-
+ 
   /* Create test frame */
   frame = cpl_frame_new();
   cpl_frame_set_filename(frame,name);
diff --git a/xsh/tests/tests.h b/xsh/tests/tests.h
index d8a7d75..c655e81 100644
--- a/xsh/tests/tests.h
+++ b/xsh/tests/tests.h
@@ -148,7 +148,7 @@
 
 /* Define accuracies here */
 #define XSH_DRL_FUNC_RMS 0.01
-#define XSH_FLOAT_PRECISION 0.000001
+#define XSH_FLOAT_PRECISION 0.000003
 
 void
 tests_set_defaults(cpl_parameterlist *parlist);
diff --git a/xsh/xsh_badpixelmap.c b/xsh/xsh_badpixelmap.c
index 0fbc481..d070a4a 100644
--- a/xsh/xsh_badpixelmap.c
+++ b/xsh/xsh_badpixelmap.c
@@ -55,7 +55,7 @@
 #include <xsh_qc_definition.h>
 #include <xsh_error.h>
 #include <xsh_msg.h>
-
+#include <xsh_ksigma_clip.h>
 #include <cpl.h>
 #include <string.h>
 
@@ -1187,6 +1187,79 @@ xsh_image_flag_bptype_with_crox(cpl_image* ima)
 }
 
 cpl_error_code
+xsh_count_crh(xsh_pre* pre, xsh_instrument* instr,const int datancom)
+{
+    int* pqual=NULL;
+    int size;
+    int bp_code_sat=0;
+    int ncrh=0;
+    int i=0;
+
+    float ncrh_avg=0;
+    XSH_ASSURE_NOT_NULL_MSG(pre, "Null input pre frame");
+    XSH_ASSURE_NOT_NULL_MSG(instr, "Null input pre frame");
+    size=pre->nx*pre->ny;
+
+
+    check(pqual=cpl_image_get_data_int(pre->qual));
+    for(i=0;i<size;i++) {
+        if(
+            (QFLAG_COSMIC_RAY_REMOVED   & pqual[i]) > 0 ||
+            (QFLAG_COSMIC_RAY_UNREMOVED & pqual[i]) > 0
+            )
+        {
+          (ncrh)++;
+        }
+    }
+    xsh_msg("ncrh=%d",ncrh);
+    xsh_pfits_set_qc_ncrh(pre->data_header,ncrh);
+    xsh_msg("datancom=%d",datancom);
+    ncrh_avg=ncrh/datancom;
+    xsh_msg("ncrh=%f",ncrh_avg);
+    xsh_pfits_set_qc_ncrh_mean(pre->data_header,ncrh_avg);
+
+    cleanup:
+     return cpl_error_get_code();
+}
+
+
+cpl_error_code
+xsh_count_satpix(xsh_pre* pre, xsh_instrument* instr,const int datancom)
+{
+    int* pqual=NULL;
+    int size;
+    int bp_code_sat=0;
+    int nsat=0;
+    int i=0;
+
+    float nsat_avg=0;
+    XSH_ASSURE_NOT_NULL_MSG(pre, "Null input pre frame");
+    XSH_ASSURE_NOT_NULL_MSG(instr, "Null input pre frame");
+    size=pre->nx*pre->ny;
+    bp_code_sat=QFLAG_ADC_SATURATION;
+
+    if(xsh_instrument_get_arm(instr) == XSH_ARM_NIR) {
+        bp_code_sat=QFLAG_SATURATED_DATA;
+    }
+
+    check(pqual=cpl_image_get_data_int(pre->qual));
+    for(i=0;i<size;i++) {
+        if( (bp_code_sat & pqual[i]) > 0 ) {
+          (nsat)++;
+        }
+    }
+    xsh_msg("nsat=%d",nsat);
+    xsh_pfits_set_nsat(pre->data_header,nsat);
+    xsh_msg("datancom=%d",datancom);
+    nsat_avg=nsat/datancom;
+    xsh_msg("nsat=%f",nsat_avg);
+    xsh_pfits_set_frac_sat(pre->data_header,nsat_avg);
+
+    cleanup:
+     return cpl_error_get_code();
+}
+
+cpl_error_code
 xsh_badpixelmap_flag_saturated_pixels(xsh_pre* pre,xsh_instrument* instr,const double cor_val, int flag, int* nsat)
 {
   int size=0;
diff --git a/xsh/xsh_badpixelmap.h b/xsh/xsh_badpixelmap.h
index eeef1c4..f1bd628 100644
--- a/xsh/xsh_badpixelmap.h
+++ b/xsh/xsh_badpixelmap.h
@@ -109,6 +109,10 @@ void xsh_badpixelmap_or( xsh_pre *self, const xsh_pre *right ) ;
 void xsh_bpmap_bitwise_to_flag(cpl_image * bpmap,int flag );
 cpl_error_code xsh_badpixelmap_coadd(cpl_frame *self, const cpl_frame *right,const int mode ) ;
 
+cpl_error_code
+xsh_count_satpix(xsh_pre* pre, xsh_instrument* instr, const int datancom);
+cpl_error_code
+xsh_count_crh(xsh_pre* pre, xsh_instrument* instr,const int datancom);
 
 cpl_error_code
 xsh_image_clean_badpixel(cpl_frame* in);
diff --git a/xsh/xsh_compute_linearity.c b/xsh/xsh_compute_linearity.c
index cbb9be5..dc18be2 100644
--- a/xsh/xsh_compute_linearity.c
+++ b/xsh/xsh_compute_linearity.c
@@ -138,10 +138,7 @@ cpl_frameset * xsh_subtract_on_off( cpl_frameset *set,
 
   for( i = 0 ; i<nframes ; i+=2 ) {
     const char *filename = NULL;
-
-    if ( i == 0 )
-      currOn = cpl_frameset_get_first (set);
-    else currOn = cpl_frameset_get_next (set);
+    currOn = cpl_frameset_get_frame(set,i);
     assure( currOn != NULL, cpl_error_get_code(),
 	    "Cant get frame of frameset" ) ;
     filename = cpl_frame_get_filename (currOn);
@@ -149,7 +146,7 @@ cpl_frameset * xsh_subtract_on_off( cpl_frameset *set,
     check_msg( preOn = xsh_pre_load( currOn, instrument ),
 	       "Cant load PRE ON" ) ;
 
-    currOff = cpl_frameset_get_next (set);
+    currOff = cpl_frameset_get_frame (set,i+1);
     assure( currOff != NULL, cpl_error_get_code(),
 	    "Cant get frame of frameset" ) ;
     filename = cpl_frame_get_filename (currOff);
@@ -241,8 +238,8 @@ xsh_linear_group_by_exptime (cpl_frameset * raws, xsh_instrument* instrument,
     cpl_propertylist *header;
     current = NULL ;
 
-    if ( i == 0 ) current = cpl_frameset_get_frame (raws,0);
-    else current = cpl_frameset_get_next (raws) ;
+    current = cpl_frameset_get_frame (raws,i);
+
     assure( current != NULL, CPL_ERROR_ILLEGAL_INPUT,
 	    "Cant get Frame #%d from frameset", i ) ;
     /* Load propertylist of current frame */
@@ -641,7 +638,7 @@ xsh_compute_linearity (cpl_frameset * medSet, xsh_instrument *instrument,
       assure( bpmap_header != NULL, cpl_error_get_code(),
 	      "Cant get bpmap header of frame %d", i ) ;
     }
-    current = cpl_frameset_get_next( medSet ) ;
+    current = cpl_frameset_get_frame( medSet,i+1 ) ;
     xsh_msg_dbg_low( "-- Next Frame" ) ;
   }
 
@@ -661,38 +658,6 @@ xsh_compute_linearity (cpl_frameset * medSet, xsh_instrument *instrument,
 			      resBpmap, decode_bp ) ;
   }
 
-#if defined(JUST_FOR_TEST)
-  // Just a test
-  {
-    int ll = 0;
-    cpl_vector * pixvect = NULL;
-    cpl_vector * temps = NULL;
-    cpl_polynomial *poly = NULL;
-
-
-    pixvect = cpl_vector_new( nframes ) ;
-    temps = cpl_vector_new( nframes ) ;
-
-    xsh_msg( "===== Fit polynome (1) sur valeurs moyennes des med frames" ) ;
-    for( ll = 0 ; ll < nframes ; ll++ ) {
-      cpl_image *cur = NULL ;
-      cur = cpl_imagelist_get( medList, ll ) ;
-      xsh_msg( "       #%d: mean=%lf, DIT=%lf", ll, cpl_image_get_mean( cur ),
-	       *(Dit+ll) ) ;
-      cpl_vector_set( pixvect, ll, cpl_image_get_mean( cur ) ) ;
-      cpl_vector_set( temps, ll, *(Dit+ll) ) ;
-    }
-    poly = xsh_polynomial_fit_1d_create( temps, pixvect,
-					 LINEAR_POLYNOMIAL_DEGREE,
-					 NULL ) ;
-    cpl_polynomial_dump( poly, stderr ) ;
-    xsh_msg( "===== Ca ne ressemble en rien a ce qu'on obtient dans le" ) ;
-    xsh_msg( "      fit general. Bizarre n'est-il pas ?" ) ;
-    for ( ll = 0 ; ll<=LINEAR_POLYNOMIAL_DEGREE ; ll++ )
-      xsh_msg( ">>>>> %d : %lf\n", ll,
-	       cpl_polynomial_get_coeff( poly, &ll ) ) ;
-  }
-#endif
 #if defined(USE_CPL_POLYNOMIAL)
   /* CPL imagelist Polynomial fit */
   xsh_msg( "Now fit polynomial - CPL version" ) ;
diff --git a/xsh/xsh_create_master.c b/xsh/xsh_create_master.c
index 967dbf3..2e39a33 100644
--- a/xsh/xsh_create_master.c
+++ b/xsh/xsh_create_master.c
@@ -1751,8 +1751,8 @@ xsh_compute_fpn_mbias(cpl_frameset* raws,
  if ( xsh_instrument_get_arm(instrument) != XSH_ARM_NIR){
     nraws=cpl_frameset_get_size(raws);
     if(nraws > 1) {
-       frm1=cpl_frameset_get_first(raws);
-       frm2=cpl_frameset_get_next(raws);
+       frm1=cpl_frameset_get_frame(raws,0);
+       frm2=cpl_frameset_get_frame(raws,1);
        ima1=cpl_image_load(cpl_frame_get_filename(frm1),CPL_TYPE_FLOAT,0,0);
        ima2=cpl_image_load(cpl_frame_get_filename(frm2),CPL_TYPE_FLOAT,0,0);
 
@@ -2066,6 +2066,10 @@ xsh_flat_create_normalized_master2(cpl_imagelist * flats,
   int starty=0;
   int endy=0;
   double tolerance=1.e-5;
+
+  cpl_mask* mask;
+  int nflagged=0;
+
   ni = cpl_imagelist_get_size(flats);
 
   /* evaluate median on many windows distributed all over orders of flats */
@@ -2094,7 +2098,7 @@ xsh_flat_create_normalized_master2(cpl_imagelist * flats,
     /* normalize flats by master flat previously computed */
     flat_mflat = cpl_image_duplicate(flat);
     cpl_image_divide(flat_mflat, mflat);
-
+    mask = cpl_image_get_bpm(flat_mflat);
     k = 0;
     for (ord = 0; ord < nord; ord++) {
       //absord = ord + ord_min;
@@ -2130,10 +2134,10 @@ xsh_flat_create_normalized_master2(cpl_imagelist * flats,
         check(lly=xsh_min_int(lly,ury));
 
         check(pvec_flux[k]=0);
-
-        check(
-            pvec_flux[k]=cpl_image_get_median_window(flat_mflat,llx,lly,urx,ury));
-
+        nflagged=cpl_mask_count_window(mask,llx,lly,urx,ury);
+        if(nflagged < (urx-llx+1)*(ury-lly+1) ) {
+           check(pvec_flux[k]=cpl_image_get_median_window(flat_mflat,llx,lly,urx,ury));
+        }
         k++;
       }
 
diff --git a/xsh/xsh_detmon.c b/xsh/xsh_detmon.c
index 7708446..f388337 100644
--- a/xsh/xsh_detmon.c
+++ b/xsh/xsh_detmon.c
@@ -1,4 +1,4 @@
-/* $Id: xsh_detmon.c,v 1.30 2012-01-15 14:14:29 amodigli Exp $
+/* $Id: xsh_detmon.c,v 1.11 2013-07-19 12:00:24 jtaylor Exp $
  *
  * This file is part of the irplib package
  * Copyright (C) 2002, 2003 European Southern Observatory
@@ -19,9 +19,9 @@
  */
 
 /*
- * $Author: amodigli $
- * $Date: 2012-01-15 14:14:29 $
- * $Revision: 1.30 $
+ * $Author: jtaylor $
+ * $Date: 2013-07-19 12:00:24 $
+ * $Revision: 1.11 $
  * $Name: not supported by cvs2svn $
  */
 
@@ -43,9 +43,9 @@
 #include <cpl.h>
 
 #include "xsh_detmon.h"
-#include "xsh_error.h"
 
-#include "xsh_hist.h"
+#include "xsh_ksigma_clip.h"
+//#include "irplib_hist.h"
 #include "irplib_utils.h"
 
 
@@ -53,7 +53,7 @@
 #define pdist(x1,y1,x2,y2) (((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2)))
 
 #define cpl_drand() ((double)rand()/(double)RAND_MAX)
-
+/**@{*/
 /*--------------------------------------------------------------------------*/
 
 /*
@@ -93,186 +93,27 @@ enum readouts
 
 static struct
 {
-    /* Inputs */
-    const char             *method;
-    const char             *pmethod;
-    irplib_ronbias_method   method_bitmask;
-    int                     prescan_llx;
-    int                     prescan_lly;
-    int                     prescan_urx;
-    int                     prescan_ury;
-    int                     overscan_llx;
-    int                     overscan_lly;
-    int                     overscan_urx;
-    int                     overscan_ury;
-    int                     preoverscan_degree;
-    int                     random_nsamples;
-    int                     random_sizex;
-    int                     random_sizey;
-    int                     criteria;
-    int                     ref_llx;
-    int                     ref_lly;
-    int                     ref_urx;
-    int                     ref_ury;
-    const char             *stacking_method;
-    int                     stacking_ks_low;
-    int                     stacking_ks_high;
-    int                     stacking_ks_iter;
-    int                     master_shift_x;
-    int                     master_shift_y;
-    int                     ron_llx;
-    int                     ron_lly;
-    int                     ron_urx;
-    int                     ron_ury;
-    int                     exts;
-    int                     nb_extensions;
-} detmon_ronbias_config;
-
-static struct
-{
-    int         mode;
-    cpl_boolean direction;
-    double      speed;
-    int         llx;
-    int         lly;
-    int         urx;
-    int         ury;
-    int         kappa;
-    int         exts;
-    int         nb_extensions;
-} detmon_pernoise_config;
-
-static struct
-{
     const char * ron_method;
     const char * dsnu_method;
     int         exts;
     int         nb_extensions;
     cpl_boolean opt_nir;
-} detmon_dark_config;
+} xsh_detmon_dark_config;
 
 #define NIR TRUE
 #define OPT FALSE
 
 /*---------------------------------------------------------------------------
-                                  Private function prototypes
- ---------------------------------------------------------------------------*/
-
-static cpl_error_code
-xsh_ksigma_clip_double(const double  * pi,
-		       cpl_binary * pm,
-		       int               llx,
-			  int               lly,
-			  int               urx,
-			  int               ury,
-			  int               nx,
-			  double            var_sum,
-			  int               npixs,
-			  double            kappa,
-			  int               nclip,
-			  double            tolerance,
-			  double          * mean,
-			  double          * stdev);
-
-static cpl_error_code
-xsh_ksigma_clip_float(const float     * pi,
-		      cpl_binary * pm,
-			 int               llx,
-			 int               lly,
-			 int               urx,
-			 int               ury,
-			 int               nx,
-			 double            var_sum,
-			 int               npixs,
-			 double            kappa,
-			 int               nclip,
-			 double            tolerance,
-			 double          * mean,
-			 double          * stdev);
-
-static cpl_error_code
-xsh_ksigma_clip_int(const int       * pi,
-		    cpl_binary * pm,
-		       int               llx,
-		       int               lly,
-		       int               urx,
-		       int               ury,
-		       int               nx,
-		       double            var_sum,
-		       int               npixs,
-		       double            kappa,
-		       int               nclip,
-		       double            tolerance,
-		       double          * mean,
-		       double          * stdev);
-
+  Private function prototypes
+  ---------------------------------------------------------------------------*/
 
 /* Functions for RON/Bias recipe, xsh_detmon_ronbias() */
 
-static cpl_error_code
-xsh_detmon_ronbias_retrieve_parlist(const char *,
-                                       const char *,
-                                       const cpl_parameterlist *,
-                                       cpl_boolean);
-
-static cpl_error_code
-xsh_detmon_ronbias_random(const cpl_imagelist *,
-			     const cpl_image *, cpl_propertylist *);
-
-static cpl_error_code
-xsh_detmon_ronbias_histo(const cpl_imagelist *,
-			    const cpl_image *, cpl_propertylist *);
-
-static cpl_error_code
-xsh_detmon_ronbias_preoverscan(const cpl_imagelist *, /*const cpl_image *,*/
-                                   cpl_propertylist *, cpl_image **);
-
-static cpl_error_code
-xsh_detmon_ronbias_region(const cpl_imagelist *,
-			     const cpl_image *, cpl_propertylist *);
-
-static cpl_image *
-xsh_detmon_ronbias_master(const cpl_imagelist *,
-			     cpl_mask **, cpl_mask **, cpl_mask **,
-                             cpl_propertylist *);
-
-static cpl_error_code
-xsh_detmon_ronbias_save(const cpl_parameterlist *,
-                           cpl_frameset *,
-                           const char *,
-                           const char *,
-                           const char *,
-                           const cpl_propertylist *,
-                           const cpl_propertylist *,
-                           const cpl_propertylist *,
-                           const cpl_propertylist *,
-                           const cpl_propertylist *,
-                           const cpl_propertylist *,
-                           const cpl_propertylist *,
-                           const char *,
-                           const cpl_image *,
-                           const cpl_image *,
-			   const cpl_mask *,
-			   const cpl_mask *,
-			   const cpl_mask *,
-                           cpl_propertylist *,
-                           const int,
-                           const int,
-                           cpl_frameset *,
-                           int);
-
-int
-xsh_detmon_ronbias_dfs_set_groups(cpl_frameset *, const char *);
-
-
-static cpl_error_code
-xsh_detmon_ronbias_dutycycl(const cpl_frameset *, cpl_propertylist *);
-
 cpl_error_code
 xsh_detmon_rm_bpixs(cpl_image **,
-                       const double,
-                       int         ,
-                       int         );
+                const double,
+                int         ,
+                int         );
 
 /* The following 2 functions are duplicated from cpl_det */
 
@@ -283,390 +124,29 @@ irplib_bivector_gen_rect_poisson(const int *r,
                                  const int np,
                                  const int homog);
 
-/* End of duplicated code */
-
-
-cpl_error_code
-xsh_detmon_ronbias_check_defaults(const cpl_frameset *, const int whichext);
-
-
-/* Functions for Periodic Noise Characterisation, xsh_detmon_pernoise() */
-
-int
-xsh_detmon_pernoise_dfs_set_groups(cpl_frameset *,
-                                      const char *);
-
-static cpl_error_code
-xsh_detmon_pernoise_retrieve_parlist(const char *,
-                                       const char *,
-                                       const cpl_parameterlist *);
-
-static cpl_error_code
-xsh_detmon_pernoise_qc(cpl_propertylist *,
-                          cpl_table        *,
-                          int);
-
-static cpl_error_code
-xsh_detmon_pernoise_save(const cpl_parameterlist *,
-                            cpl_frameset *,
-                            const char *,
-                            const char *,
-                            const char *,
-                            const char *,
-                            cpl_table **,
-                            cpl_propertylist **,
-                            const int,
-                            const int,
-                            const cpl_frameset *);
-
-cpl_error_code
-xsh_detmon_pernoise_rm_bg(cpl_image *,
-                             int,
-                             int);
-
-int
-xsh_detmon_dark_dfs_set_groups(cpl_frameset *,
-                                  const char *);
-
-cpl_error_code
-xsh_detmon_dark_dsnu(cpl_frameset *,
-                        cpl_imagelist *,
-                        cpl_table *,
-                        cpl_image *,
-                        int pos);
-
-
 static cpl_error_code
 xsh_detmon_dark_save(const cpl_parameterlist *,
-                        cpl_frameset *,
-                        const char *,
-                        const char *,
-                        const char *,
-                        const char *,
-                        const char *,
-                        const char *,
-                        cpl_imagelist **,
-                        cpl_table **,
-                        cpl_imagelist **,
-                        cpl_propertylist **,
-                        const int,
-                        const int,
-                        const cpl_frameset *);
+                 cpl_frameset *,
+                 const char *,
+                 const char *,
+                 const char *,
+                 const char *,
+                 const char *,
+                 const char *,
+                 cpl_imagelist **,
+                 cpl_table **,
+                 cpl_imagelist **,
+                 cpl_propertylist **,
+                 const int,
+                 const int,
+                 const cpl_frameset *);
 
 
 
 static cpl_error_code
 xsh_detmon_retrieve_dark_params(const char *,
-                                   const char *,
-                                   const cpl_parameterlist *);
-
-cpl_error_code
-xsh_detmon_dark_qc(cpl_propertylist *,
-                      cpl_image *);
-
-
-
-/*         RONBIAS FILLING PARLIST        */
-
-
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Fill input parameters with default values
- * @param  parlist      parameters list
- * @param  recipe_name  recipe name
- * @param  pipeline_name pipeline name
-
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-
-cpl_error_code
-xsh_detmon_ronbias_fill_parlist_default(cpl_parameterlist * parlist,
-				   const char *recipe_name,
-				   const char *pipeline_name)
-{
-    const cpl_error_code error =
-	xsh_detmon_ronbias_fill_parlist(parlist, recipe_name, pipeline_name,
-					   "ALL", /* --method */
-					   "NORM",/* --pmethod */
-					   1,     /* --preoverscan_degree */
-					   -1,    /* --random_nsamples */
-					   -1,    /* --random_sizex */
-					   -1,    /* --random_sizey */
-					   0,     /* --criteria     */
-					   -1,    /* --ref_llx     */
-					   -1,    /* --ref_lly */
-					   -1,    /* --ref_urx */
-					   -1,    /* --ref_ury */
-					   "MEAN",/* --stacking_method */
-					   3,     /* --stacking_ks_low */
-					   3,     /* --stacking_ks_high */
-					   5,     /* --stacking_ks_iter */
-					   0,     /* --master_shift_x */
-					   0,     /* --master_shift_y */
-					   -1,    /* --ron_llx */
-					   -1,    /* --ron_lly */
-					   -1,    /* --ron_urx */
-					   -1,    /* --ron_ury */
-					   0,    /* --exts */
-					   OPT);
-    cpl_ensure_code(!error, error);
-
-    return cpl_error_get_code();
-}
-
-
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Fill input parameters with default values
- * @param  parlist      parameters list
- * @param  recipe_name  recipe name
- * @param  pipeline_name pipeline name
-
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-
-cpl_error_code
-xsh_detmon_darkron_fill_parlist_default(cpl_parameterlist * parlist,
-					   const char *recipe_name,
-					   const char *pipeline_name)
-{
-    const cpl_error_code error =
-	xsh_detmon_ronbias_fill_parlist(parlist, recipe_name, pipeline_name,
-					   "ALL", /* --method */
-					   "NORM",/* --pmethod */
-					   1,     /* --preoverscan_degree */
-					   -1,    /* --random_nsamples */
-					   -1,    /* --random_sizex */
-					   -1,    /* --random_sizey */
-					   0,     /* --criteria     */
-					   -1,    /* --ref_llx     */
-					   -1,    /* --ref_lly */
-					   -1,    /* --ref_urx */
-					   -1,    /* --ref_ury */
-					   "MEAN",/* --stacking_method */
-					   3,     /* --stacking_ks_low */
-					   3,     /* --stacking_ks_high */
-					   5,     /* --stacking_ks_iter */
-					   0,     /* --master_shift_x */
-					   0,     /* --master_shift_y */
-					   -1,    /* --ron_llx */
-					   -1,    /* --ron_lly */
-					   -1,    /* --ron_urx */
-					   -1,    /* --ron_ury */
-					   0,    /* --exts */
-					   NIR);
-    cpl_ensure_code(!error, error);
-
-    return cpl_error_get_code();
-}
-
-
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Fill input parameters with default values
- * @param  parlist      parameters list
- * @param  recipe_name  recipe name
- * @param  pipeline_name pipeline name
- * @param  method adopted method
- * @param  pmethod adopted pre-method
- * @param  preoverscan_degree degree used ti fit pre-overscan regions
- * @param  random_nsamples number of samples used for random computation
- * @param  random_sizex x size of rectangle area for random computation
- * @param  random_sizey x size of rectangle area for random computation
- * @param  criteria
- * @param  ref_llx  reference region lower left x
- * @param  ref_lly  reference region lower left y
- * @param  ref_urx  reference region upper right x
- * @param  ref_ury  reference region upper right y
- * @param  stacking_method  frame stacking method
- * @param  stacking_ks_low  kappa value to kappa sigma low intensity pixels
- * @param  stacking_ks_high  kappa value to kappa sigma high intensity pixels
- * @param  stacking_ks_iter  kappa value to kappa sigma number of iterations
- * @param  master_shift_x  x shift value applied to master
- * @param  master_shift_y  y shift value applied to master
- * @param  ron_llx  reference region lower left x to compute RON
- * @param  ron_lly  reference region lower left y to compute RON
- * @param  ron_urx  reference region upper right x to compute RON
- * @param  ron_ury  reference region upper right y to compute RON
- * @param  exts  image extension to be reduced
- * @param  opt_nir  switch to specify if in input are OPT or NIR data
-
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-
-cpl_error_code
-xsh_detmon_ronbias_fill_parlist(cpl_parameterlist * parlist,
-				   const char *recipe_name,
-				   const char *pipeline_name,
-				   const char * method,
-				   const char * pmethod,
-				   const int preoverscan_degree,
-				   const int random_nsamples,
-				   const int random_sizex,
-				   const int random_sizey,
-				   const int criteria,
-				   const int ref_llx,
-				   const int ref_lly,
-				   const int ref_urx,
-				   const int ref_ury,
-				   const char * stacking_method,
-				   const int stacking_ks_low,
-				   const int stacking_ks_high,
-				   const int stacking_ks_iter,
-				   const int master_shift_x,
-				   const int master_shift_y,
-				   const int ron_llx,
-				   const int ron_lly,
-				   const int ron_urx,
-				   const int ron_ury,
-				   const int exts,
-                                   cpl_boolean opt_nir)
-{
-
-    const char * meth_desc_opt =
-	"Method to be used when computing bias. Methods appliable: "
-	"<RANDOM | HISTO | PREOVERSCAN | REGION | ALL>. By default ALL "
-	"methods are applied. More than a method can be chosen; in that "
-	"case selected methods must be separated by a single space and put "
-	"together between inverted commas (ex. --method=\"HISTO REGION\")."
-	"\n RANDOM: Bias is computed as the mean value on a given number "
-	"(--random.nsamples) of boxes (dimensions --random.sizex and "
-	"--random.sizey) randomly taken  accross the detector.\n HISTO: "
-	"An histogram of the pixels of the image is built.\n PREOVERSCAN: "
-	"Mean, median and RMS values computed and designated areas. \n "
-	"REGION: Mean, median and RMS values on reference region.";
-
-    const char * meth_desc_nir =
-	"Method to be used when computing bias. Methods appliable: "
-	"<RANDOM | HISTO | REGION | ALL>. By default ALL "
-	"methods are applied. More than a method can be chosen; in that "
-	"case selected methods must be separated by a single space and put "
-	"together between inverted commas (ex. --method=\"HISTO REGION\")."
-	"\n RANDOM: Bias is computed as the mean value on a given number "
-	"(--random.nsamples) of boxes (dimensions --random.sizex and "
-	"--random.sizey) randomly taken  accross the detector.\n HISTO: "
-	"An histogram of the pixels of the image is built.\n "
-	"REGION: Mean, median and RMS values on reference region.";
-
-    const char * method_desc = opt_nir == OPT ? meth_desc_opt : meth_desc_nir;
-
-    const cpl_error_code error =
-	xsh_detmon_fill_parlist(parlist, recipe_name, pipeline_name, 22,
-				   "method",
-				   method_desc,
-				   "CPL_TYPE_STRING", method,
-
-				   "pmethod",
-				   "Pre-method for RANDOM, HISTO and REGION."
-				   "Difference raw frames or not",
-				   "CPL_TYPE_STRING", pmethod,
-
-				   "preoverscan.degree",
-				   "Degree used for pre-overscan method",
-				   "CPL_TYPE_INT", preoverscan_degree,
-
-				   "random.nsamples",
-				   "Number of samples",
-				   "CPL_TYPE_INT", random_nsamples,
-
-				   "random.sizex",
-				   "X size of the boxes",
-				   "CPL_TYPE_INT", random_sizex,
-
-				   "random.sizey",
-				   "Y size of the boxes",
-				   "CPL_TYPE_INT", random_sizey,
-
-				   "criteria",
-				   "Criteria",
-				   "CPL_TYPE_INT", criteria,
-
-				   "ref.llx",
-				   "x coordinate of the lower-left point "
-				   "of the reference region of the frame",
-				   "CPL_TYPE_INT", ref_llx,
-
-				   "ref.lly",
-				   "y coordinate of the lower-left point "
-				   "of the reference region of the frame",
-				   "CPL_TYPE_INT", ref_lly,
-
-				   "ref.urx",
-				   "x coordinate of the upper-right point "
-				   "of the reference region of the frame",
-				   "CPL_TYPE_INT", ref_urx,
-
-				   "ref.ury",
-				   "y coordinate of the upper-right point "
-				   "of the reference region of the frame",
-				   "CPL_TYPE_INT", ref_ury,
-
-				   "stacking.method",
-				   "Method to be used when stacking the master. Possible values < MINMAX | MEAN | MEDIAN | KSIGMA >",
-				   "CPL_TYPE_STRING", stacking_method,
-
-				   "stacking.ks.low",
-				   "Low threshold for kappa-sigma clipping",
-				   "CPL_TYPE_INT", stacking_ks_low,
-
-				   "stacking.ks.high",
-				   "High threshold for kappa-sigma clipping",
-				   "CPL_TYPE_INT", stacking_ks_high,
-
-				   "stacking.ks.iter",
-				   "Nb of iterations for kappa-sigma clipping",
-				   "CPL_TYPE_INT", stacking_ks_iter,
-
-				   "master.shift.x",
-				   "Master shift X",
-				   "CPL_TYPE_INT", master_shift_x,
-
-				   "master.shift.y",
-				   "Master shift Y",
-				   "CPL_TYPE_INT", master_shift_y,
-
-				   "ron.llx",
-				   "x coordinate of the lower-left point "
-				   "of the RON frame",
-				   "CPL_TYPE_INT", ron_llx,
-
-				   "ron.lly",
-				   "y coordinate of the lower-left point "
-				   "of the RON frame",
-				   "CPL_TYPE_INT", ron_lly,
-
-				   "ron.urx",
-				   "x coordinate of the upper-right point "
-				   "of the RON frame",
-				   "CPL_TYPE_INT", ron_urx,
-
-				   "ron.ury",
-				   "y coordinate of the upper-right point "
-				   "of the RON frame", "CPL_TYPE_INT", ron_ury,
-
-                                   "exts",
-                                   "Activate the multi-exts option",
-                                   "CPL_TYPE_INT", exts);
-
-
-    cpl_ensure_code(!error, error);
-
-    return cpl_error_get_code();
-}
-
-
+                            const char *,
+                            const cpl_parameterlist *);
 
 
 /*---------------------------------------------------------------------------*/
@@ -684,9 +164,9 @@ xsh_detmon_ronbias_fill_parlist(cpl_parameterlist * parlist,
 /*---------------------------------------------------------------------------*/
 cpl_error_code
 xsh_detmon_fill_parlist(cpl_parameterlist * parlist,
-                           const char *recipe_name,
-                           const char *pipeline_name,
-                           int npars, ...)
+                    const char *recipe_name,
+                    const char *pipeline_name,
+                    int npars, ...)
 {
 
     va_list                 ap;
@@ -700,15 +180,15 @@ xsh_detmon_fill_parlist(cpl_parameterlist * parlist,
 
 #define insert_par(PARNAME, PARDESC, PARVALUE, PARTYPE)                      \
     do {                                                                     \
-    char * par_name = cpl_sprintf("%s.%s", group_name, PARNAME);          \
-    cpl_parameter * p;                                                       \
-    assert(par_name != NULL);                                                \
-    p = cpl_parameter_new_value(par_name, PARTYPE,                           \
-                                PARDESC, group_name, PARVALUE);              \
-    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, PARNAME);             \
-    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);                        \
-    cpl_parameterlist_append(parlist, p);                                    \
-    cpl_free(par_name);                                                      \
+        char * par_name = cpl_sprintf("%s.%s", group_name, PARNAME);          \
+        cpl_parameter * p;                                                       \
+        assert(par_name != NULL);                                                \
+        p = cpl_parameter_new_value(par_name, PARTYPE,                           \
+                                    PARDESC, group_name, PARVALUE);              \
+        cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, PARNAME);             \
+        cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);                        \
+        cpl_parameterlist_append(parlist, p);                                    \
+        cpl_free(par_name);                                                      \
     } while(0);
 
 
@@ -753,7 +233,7 @@ xsh_detmon_fill_parlist(cpl_parameterlist * parlist,
 /*---------------------------------------------------------------------------*/
 
 /*
- * @brief  Retrieve input parameters
+ * @brief  Retrieve input int parameter
  * @param  pipeline_name        Input image
  * @param  recipe_name          Input image
  * @param  parlist              Shift to apply on the x-axis
@@ -763,9 +243,9 @@ xsh_detmon_fill_parlist(cpl_parameterlist * parlist,
 /*---------------------------------------------------------------------------*/
 int
 xsh_detmon_retrieve_par_int(const char *parn,
-                           const char *pipeline_name,
-                           const char *recipe_name,
-                           const cpl_parameterlist * parlist)
+                        const char *pipeline_name,
+                        const char *recipe_name,
+                        const cpl_parameterlist * parlist)
 {
     char                   *par_name;
     cpl_parameter          *par;
@@ -783,7 +263,7 @@ xsh_detmon_retrieve_par_int(const char *parn,
 /*---------------------------------------------------------------------------*/
 
 /*
- * @brief  Retrieve input parameters
+ * @brief  Retrieve input double parameter
  * @param  pipeline_name        Input image
  * @param  recipe_name          Input image
  * @param  parlist              Shift to apply on the x-axis
@@ -810,67 +290,6 @@ xsh_detmon_retrieve_par_double(const char *parn,
     return value;
 }
 
-/*--------------------------------------------------------------------------*/
-
-/*
- * @brief    Comparison function to identify different settings
- * @param    frame1  First frame
- * @param    frame2  Second frame
- * @return   0 if different, 1 if equal, -1 in error case
- */
-
-/*--------------------------------------------------------------------------*/
-
-int
-xsh_detmon_compare_dits(const cpl_frame * frame1, const cpl_frame * frame2)
-{
-    int                     comparison;
-    cpl_propertylist       *plist1;
-    cpl_propertylist       *plist2;
-    double                  dval1, dval2;
-
-    /* Test entries */
-    if(frame1 == NULL || frame2 == NULL)
-        return -1;
-
-    /* Get property lists */
-    if((plist1 = cpl_propertylist_load(cpl_frame_get_filename(frame1),
-                                       0)) == NULL) {
-        cpl_msg_error(cpl_func, "getting header from reference frame");
-        return -1;
-    }
-    if((plist2 = cpl_propertylist_load(cpl_frame_get_filename(frame2),
-                                       0)) == NULL) {
-        cpl_msg_error(cpl_func, "getting header from reference frame");
-        cpl_propertylist_delete(plist1);
-        return -1;
-    }
-
-    /* Test status */
-    if(cpl_error_get_code()) {
-        cpl_propertylist_delete(plist1);
-        cpl_propertylist_delete(plist2);
-        return -1;
-    }
-
-    /* Compare exposure time */
-    comparison = 1;
-    dval1 = irplib_pfits_get_exptime(plist1);
-    dval2 = irplib_pfits_get_exptime(plist2);
-    if(cpl_error_get_code()) {
-        cpl_msg_error(cpl_func, "cannot get exposure time");
-        cpl_propertylist_delete(plist1);
-        cpl_propertylist_delete(plist2);
-        return -1;
-    }
-    if(fabs(dval1 - dval2) > 1e-3)
-        comparison = 0;
-
-    /* Free and return */
-    cpl_propertylist_delete(plist1);
-    cpl_propertylist_delete(plist2);
-    return comparison;
-}
 
 /*---------------------------------------------------------------------------*/
 
@@ -893,3611 +312,252 @@ irplib_pfits_get_exptime(const cpl_propertylist * plist)
 }
 
 /*---------------------------------------------------------------------------*/
-
 /*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @param  opt_nir  switch to specify if in input are OPT or NIR data
- * @return CPL_ERROR_NONE on success.
+ * @brief  Generate propertylist with product category, type, technique
+ * @param  procatg product category
+ * @param  protype product type
+ * @param  protech product technique
+ * @param  proscience switch to identify a science product
+ * @return filled cpl_propertylist (to be deallocated)
  */
-
 /*---------------------------------------------------------------------------*/
-static                  cpl_error_code
-xsh_detmon_ronbias_retrieve_parlist(const char *pipeline_name,
-                                      const char *recipe_name,
-				       const cpl_parameterlist * parlist,
-                                       cpl_boolean opt_nir)
+cpl_propertylist *
+xsh_detmon_fill_prolist(const char * procatg,
+                    const char * protype,
+                    const char * protech,
+                    cpl_boolean  proscience)
 {
-    char                   *par_name;
-    cpl_parameter          *par;
-
-    char                    m1[20] = "";
-    char                    m2[20] = "";
-    char                    m3[20] = "";
-
-    /* --method */
-    par_name = cpl_sprintf("%s.%s.method", pipeline_name, recipe_name);
-    assert(par_name != NULL);
-    par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_ronbias_config.method = cpl_parameter_get_string(par);
-    cpl_free(par_name);
+    cpl_propertylist * prolist = cpl_propertylist_new();
 
-    detmon_ronbias_config.method_bitmask = 0;
-
-    /* Note: update the string format (the %__s) if m1(2,3) changes size.
-     * Remember: field width must equal 1 less than sizeof(m1(2,3)). */
-    sscanf(detmon_ronbias_config.method, "%19s %19s %19s", m1, m2, m3);
-
-    if(!strcmp(m1, "RANDOM") || !strcmp(m2, "RANDOM")
-       || !strcmp(m3, "RANDOM"))
-        detmon_ronbias_config.method_bitmask += RANDOM;
-
-    if(!strcmp(m1, "HISTO") || !strcmp(m2, "HISTO") || !strcmp(m3, "HISTO"))
-        detmon_ronbias_config.method_bitmask += HISTO;
-
-    if(!strcmp(m1, "PREOVERSCAN") || !strcmp(m2, "PREOVERSCAN")
-       || !strcmp(m3, "PREOVERSCAN")) {
-	if (opt_nir == NIR) {
-	    /* Just in case some advance user reads himself in the code and
-	       tries to trick the interface providing an option no contained
-	       in the man-page */
-	    cpl_msg_warning(cpl_func, "PREOVERSCAN is not appliable for NIR");
-	} else {
-	    detmon_ronbias_config.method_bitmask += PREOVERSCAN;
-	}
-    }
-    if(!strcmp(m1, "REGION") || !strcmp(m2, "REGION")
-       || !strcmp(m3, "REGION"))
-        detmon_ronbias_config.method_bitmask += REGION;
-
-    if(!strcmp(m1, "ALL")) {
-	if (opt_nir == OPT) {
-	    detmon_ronbias_config.method_bitmask =
-		RANDOM | HISTO | PREOVERSCAN | REGION;
-	} else {
-	    detmon_ronbias_config.method_bitmask =
-		RANDOM | HISTO | REGION;
-	}
+    cpl_propertylist_append_string(prolist, CPL_DFS_PRO_CATG,    procatg);
+    cpl_propertylist_append_bool(prolist,   CPL_DFS_PRO_SCIENCE, proscience);
+    if (protype) {
+        cpl_propertylist_append_string(prolist, CPL_DFS_PRO_TYPE,    protype);
     }
-
-    /* --pmethod */
-    par_name = cpl_sprintf("%s.%s.pmethod", pipeline_name, recipe_name);
-    assert(par_name != NULL);
-    par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_ronbias_config.pmethod = cpl_parameter_get_string(par);
-    cpl_free(par_name);
-
-    /* --preoverscan.degree */
-    detmon_ronbias_config.preoverscan_degree =
-        xsh_detmon_retrieve_par_int("preoverscan.degree", pipeline_name,
-                                   recipe_name, parlist);
-
-    /* --nsamples */
-    detmon_ronbias_config.random_nsamples =
-        xsh_detmon_retrieve_par_int("random.nsamples", pipeline_name,
-                                   recipe_name, parlist);
-
-    /* --sizex */
-    detmon_ronbias_config.random_sizex =
-        xsh_detmon_retrieve_par_int("random.sizex", pipeline_name,
-                                   recipe_name, parlist);
-
-    /* --sizey */
-    detmon_ronbias_config.random_sizey =
-        xsh_detmon_retrieve_par_int("random.sizey", pipeline_name,
-                                   recipe_name, parlist);
-
-    /* --criteria */
-    detmon_ronbias_config.criteria =
-        xsh_detmon_retrieve_par_int("criteria", pipeline_name, recipe_name,
-                                   parlist);
-
-    /* --ref.llx */
-    detmon_ronbias_config.ref_llx =
-        xsh_detmon_retrieve_par_int("ref.llx", pipeline_name, recipe_name,
-                                   parlist);
-    /* --ref.lly */
-    detmon_ronbias_config.ref_lly =
-        xsh_detmon_retrieve_par_int("ref.lly", pipeline_name, recipe_name,
-                                   parlist);
-    /* --ref.urx */
-    detmon_ronbias_config.ref_urx =
-        xsh_detmon_retrieve_par_int("ref.urx", pipeline_name, recipe_name,
-                                   parlist);
-    /* --ref.ury */
-    detmon_ronbias_config.ref_ury =
-        xsh_detmon_retrieve_par_int("ref.ury", pipeline_name, recipe_name,
-                                   parlist);
-
-    /* --stacking.method */
-    par_name =
-        cpl_sprintf("%s.%s.stacking.method", pipeline_name, recipe_name);
-    assert(par_name != NULL);
-    par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_ronbias_config.stacking_method = cpl_parameter_get_string(par);
-    cpl_free(par_name);
-
-    /* --stacking.ks.low */
-    detmon_ronbias_config.stacking_ks_low =
-        xsh_detmon_retrieve_par_int("stacking.ks.low", pipeline_name,
-                                   recipe_name, parlist);
-    /* --stacking.ks.high */
-    detmon_ronbias_config.stacking_ks_high =
-        xsh_detmon_retrieve_par_int("stacking.ks.high", pipeline_name,
-                                   recipe_name, parlist);
-    /* --stacking.ks.iter */
-    detmon_ronbias_config.stacking_ks_iter =
-        xsh_detmon_retrieve_par_int("stacking.ks.iter", pipeline_name,
-                                   recipe_name, parlist);
-    /* --master.shift.x */
-    detmon_ronbias_config.master_shift_x =
-        xsh_detmon_retrieve_par_int("master.shift.x", pipeline_name,
-                                   recipe_name, parlist);
-    /* --master.shift.y */
-    detmon_ronbias_config.master_shift_y =
-        xsh_detmon_retrieve_par_int("master.shift.y", pipeline_name,
-                                   recipe_name, parlist);
-    /* --ron.llx */
-    detmon_ronbias_config.ron_llx =
-        xsh_detmon_retrieve_par_int("ron.llx", pipeline_name, recipe_name,
-                                   parlist);
-    /* --ron.lly */
-    detmon_ronbias_config.ron_lly =
-        xsh_detmon_retrieve_par_int("ron.lly", pipeline_name, recipe_name,
-                                   parlist);
-    /* --ron.urx */
-    detmon_ronbias_config.ron_urx =
-        xsh_detmon_retrieve_par_int("ron.urx", pipeline_name, recipe_name,
-                                   parlist);
-    /* --ron.ury */
-    detmon_ronbias_config.ron_ury =
-        xsh_detmon_retrieve_par_int("ron.ury", pipeline_name, recipe_name,
-                                   parlist);
-    /* --exts */
-    detmon_ronbias_config.exts =
-        xsh_detmon_retrieve_par_int("exts", pipeline_name, recipe_name,
-                                   parlist);
-
-    if(cpl_error_get_code()) {
-        cpl_msg_error(cpl_func, "Failed to retrieve the input parameters");
-        cpl_ensure_code(0, CPL_ERROR_DATA_NOT_FOUND);
+    if (protech) {
+        cpl_propertylist_append_string(prolist, CPL_DFS_PRO_TECH,    protech);
     }
 
-
-    return CPL_ERROR_NONE;
+    return prolist;
 }
 
 /*---------------------------------------------------------------------------*/
 
 /*
- * @brief  Check parameter defauls
- * @param  set        Input set of frames
- * @param  whichext   extension to be reduced
+ * @brief  Remove bad pixels
+ * @param  image  input/output image
+ * @param  kappa  kappa for kappa-sigma clip
+ * @param  nffts  number of fft
+ * @param  nsamples number of sampling areas
  * @return CPL_ERROR_NONE on success.
  */
 
 /*---------------------------------------------------------------------------*/
-cpl_error_code
-xsh_detmon_ronbias_check_defaults(const cpl_frameset * set,
-                                     const int whichext)
-{
-    const cpl_frame  * fr        = cpl_frameset_get_frame_const(set,0);
-
-    cpl_propertylist * plist     =
-	cpl_propertylist_load(cpl_frame_get_filename(fr), whichext);
-
-    const int naxis1 = cpl_propertylist_get_int(plist, "NAXIS1");
-    const int naxis2 = cpl_propertylist_get_int(plist, "NAXIS2");
-
-    if(detmon_ronbias_config.method_bitmask & PREOVERSCAN)
-    {
-		const int nx = cpl_propertylist_get_int(plist, "ESO DET OUT1 NX");
-		const int ny = cpl_propertylist_get_int(plist, "ESO DET OUT1 NY");
-
-		int prscsize;
-		int ovscsize;
-
-		if (naxis1 != nx)
-		{
-			prscsize =
-			cpl_propertylist_get_int(plist, "ESO DET OUT1 PRSCX");
-			ovscsize =
-			cpl_propertylist_get_int(plist, "ESO DET OUT1 OVSCX");
-
-			cpl_error_ensure(cpl_error_get_code() == CPL_ERROR_NONE, cpl_error_get_code(), goto cleanup,"error");
-
-			detmon_ronbias_config.prescan_llx  = 1;
-			detmon_ronbias_config.prescan_lly  = 1;
-			detmon_ronbias_config.prescan_urx  = prscsize;
-			detmon_ronbias_config.prescan_ury  = naxis2;
-			detmon_ronbias_config.overscan_llx = naxis1 - ovscsize;
-			detmon_ronbias_config.overscan_lly = 1;
-			detmon_ronbias_config.overscan_urx = naxis1;
-			detmon_ronbias_config.overscan_ury = naxis2;
-		} else if (naxis2 != ny)
-		{
-			prscsize =
-			cpl_propertylist_get_int(plist, "ESO DET OUT1 PRSCY");
-			ovscsize =
-			cpl_propertylist_get_int(plist, "ESO DET OUT1 OVSCY");
-			cpl_error_ensure(cpl_error_get_code() == CPL_ERROR_NONE, cpl_error_get_code(), goto cleanup,"error");
-
-			detmon_ronbias_config.prescan_llx  = 1;
-			detmon_ronbias_config.prescan_lly  = 1;
-			detmon_ronbias_config.prescan_urx  = naxis1;
-			detmon_ronbias_config.prescan_ury  = prscsize;
-			detmon_ronbias_config.overscan_llx = 1;
-			detmon_ronbias_config.overscan_lly = naxis2 - ovscsize;
-			detmon_ronbias_config.overscan_urx = naxis1;
-			detmon_ronbias_config.overscan_ury = naxis2;
-		} else
-		{
-			cpl_msg_error(cpl_func,
-				  "No PREOVERSCAN areas found");
-			cpl_error_set(cpl_func, CPL_ERROR_NULL_INPUT);
-			goto cleanup;
-		}
-    }
-
-    if(detmon_ronbias_config.ref_llx == -1)
-        detmon_ronbias_config.ref_llx = naxis1 / 8;
-    if(detmon_ronbias_config.ref_lly == -1)
-        detmon_ronbias_config.ref_lly = naxis2 / 8;
-    if(detmon_ronbias_config.ref_urx == -1)
-        detmon_ronbias_config.ref_urx = naxis1 * 7 / 8;
-    if(detmon_ronbias_config.ref_ury == -1)
-        detmon_ronbias_config.ref_ury = naxis2 * 7 / 8;
-
-    if(detmon_ronbias_config.ron_llx == -1)
-        detmon_ronbias_config.ron_llx = 1;
-    if(detmon_ronbias_config.ron_lly == -1)
-        detmon_ronbias_config.ron_lly = 1;
-    if(detmon_ronbias_config.ron_urx == -1)
-        detmon_ronbias_config.ron_urx = naxis1;
-    if(detmon_ronbias_config.ron_ury == -1)
-        detmon_ronbias_config.ron_ury = naxis2;
-
-cleanup:
-    cpl_propertylist_delete(plist);
-	return cpl_error_get_code();
-}
 
 
-/*---------------------------------------------------------------------------*/
-/**
-  @brief    Apply kappa-sigma clipping on input image
-  @param    img      Input image
-  @param    llx      Lower left x position (FITS convention)
-  @param    lly      Lower left y position (FITS convention)
-  @param    urx      Upper right x position (FITS convention)
-  @param    ury      Upper right y position (FITS convention)
-  @param    kappa    Kappa value for the clipping
-  @param    nclip    Number of clipping iterations
-  @param    kmean    Mean after clipping (output)
-  @param    kstdev   Stdev after clipping (output)
-  @return   CPL_ERROR_NONE or the relevant #_cpl_error_code_ on error
-
-  This function applies an iterative kappa-sigma clipping on the image and
-  returns mean and stdev after the clipping.
-
-  The function takes as a starting point the "standard" values of mean and
-  stdev from cpl_stats.
-
-  On each iteration, the contribution of pixels outside the range
-  [mean - kappa * stdev, mean + kappa * stdev] is removed, the values of
-  mean and stdev are updated, and so are the limits of the range to be used
-  in the next iteration as well.
-
-  The algorithm stops after nclip iterations or when the variation of the
-  range between two consecutive iterations is smaller (absolute value) than
-  the tolerance.
-
-  The effectiveness of this function resides on the way the update of the
-  values of mean and stdev is done.
-
-  The contribution of a single pixel in variance can be removed as follows:
-
-  \sum_{i=1}^{N-1} (x_i - \overline{x}_{n-1})^2 =
-  \sum_{i=1}^ N    (x_i - \overline{x}_n    )^2 -
-  \frac{N}{N-1} \,( \, \overline{x}_n - x_{n} )^2
-
-  For further details on the mathematical aspects, please refer to DFS05126.
-
-  Possible #_cpl_error_code_ set in this function:
-   - CPL_ERROR_NULL_INPUT if img or kmean is NULL
-   - CPL_ERROR_ILLEGAL_INPUT if
-       a) the window specification is illegal (llx > urx or lly > ury)
-       b) the window specification is outside the image
-       c) the tolerance is negative
-       d) kappa is <= 1.0
-       e) nclip is <= 0.
-
-  The values of kmean and kstdev is undefined on error.
-*/
-/*---------------------------------------------------------------------------*/
 cpl_error_code
-xsh_ksigma_clip(const cpl_image * img,
-		   int               llx,
-		   int               lly,
-		   int               urx,
-		   int               ury,
-		   double            kappa,
-		   int               nclip,
-		   double            tolerance,
-		   double          * kmean,
-		   double          * kstdev)
+xsh_detmon_rm_bpixs(cpl_image ** image,
+                const double kappa, int nffts, int nsamples)
 {
+    int                     i, j;
 
-    int nx, ny;
-
-    double      mean, stdev;
-    //int         npixs;
-    cpl_image* sub_ima=NULL;
-    double kappa2=0;
-    double thresh=0;
-    double thresh_p=0;
-    cpl_binary * pm=0;
-    const float* pi=0;
-
-    int pix=0;
-    int i=0;
-    int j=0;
-    int k=0;
-
-    cpl_ensure_code(img != NULL, CPL_ERROR_NULL_INPUT);
-
-    nx = cpl_image_get_size_x(img);
-    ny = cpl_image_get_size_y(img);
-
-
-    cpl_ensure_code(llx > 0 && urx > llx && urx <= nx &&
-		    lly > 0 && ury > lly && ury <= ny,
-		    CPL_ERROR_ILLEGAL_INPUT);
-
-    cpl_ensure_code(tolerance >= 0.0, CPL_ERROR_ILLEGAL_INPUT);
-    cpl_ensure_code(kappa     >  1.0, CPL_ERROR_ILLEGAL_INPUT);
-    cpl_ensure_code(nclip     >    0, CPL_ERROR_ILLEGAL_INPUT);
- 
-    sub_ima=cpl_image_extract(img,llx, lly, urx, ury);
-   //npixs= nx*ny-cpl_image_count_rejected(sub_ima);
-   cpl_image_delete(sub_ima);
-   mean    = cpl_image_get_mean_window(img,llx, lly, urx, ury);
-   stdev    = cpl_image_get_stdev_window(img,llx, lly, urx, ury);
-   pi=cpl_image_get_data_float_const(img);
-   pm=cpl_mask_get_data(cpl_image_get_bpm((cpl_image*)img));
- 
-
-   kappa2=kappa*kappa;
-   thresh_p=-1;
-   for(k=0;k<nclip;k++) {
-     mean    = cpl_image_get_mean_window(img,llx, lly, urx, ury);
-     stdev    = cpl_image_get_stdev_window(img,llx, lly, urx, ury);
-     thresh=stdev*stdev*kappa2;
-     for(j=lly;j<ury;j++) {
-       for(i=llx;i<urx;i++) {
-	 pix=i+j*nx;
-	 if( 
-             (pm[pix] != CPL_BINARY_1) && 
-	     ((pi[pix]-mean)*(pi[pix]-mean) > thresh ) ) {
-	   pm[pix]=CPL_BINARY_1;
-	 } /* end check if pix is outlier */
-       } /* loop over i */
-     } /* loop over j */
-     if((fabs(thresh_p-thresh)) < tolerance) {
-       break;
-     } else {
-       thresh_p=thresh;
-     }
-   } /* loop over niter */
-
-    *kmean = mean;
-    if (kstdev != NULL) *kstdev = stdev; /* Optional */
-
+    float                  *data = cpl_image_get_data_float(*image);
+    int k = 0;
+    for(i = 0; i < nffts; i++) {
+        for(j = 0; j < nsamples; j++) {
+            float                   neighbours = 0;
+            int                     nneighs = 0;
+            float                   average = 0;
 
-    return cpl_error_get_code();
-}
+            /*
+             * Look for the way to optimize this:
+             * Some of the points added to neighbours coincide
+             * in one iteration and the following
+             */
+            if(i > 0) {
+                neighbours += *(data + (i - 1) * nsamples + j);
+                nneighs++;
+            }
+            if(i < nffts - 1) {
+                neighbours += *(data + (i + 1) * nsamples + j);
+                nneighs++;
+            }
+            if(j > 0) {
+                neighbours += *(data + i * nsamples + (j - 1));
+                nneighs++;
+            }
+            if(j < nsamples - 1) {
+                neighbours += *(data + i * nsamples + (j + 1));
+                nneighs++;
+            }
+            average = neighbours / nneighs;
+            if(average > 0) {
+                if(*(data + i * nsamples + j) < average * (-1 * kappa) ||
+                   *(data + i * nsamples + j) > average * (kappa)) {
+                    k++;
+                    *(data + i * nsamples + j) = average;
+                }
+            }
+            if(average < 0) {
+                if(*(data + i * nsamples + j) > average * (-1 * kappa) ||
+                   *(data + i * nsamples + j) < average * (kappa)) {
+                    k++;
+                    *(data + i * nsamples + j) = average;
+                }
+            }
 
-
-cpl_error_code
-xsh_ksigma_clip_old(const cpl_image * img,
-		   int               llx,
-		   int               lly,
-		   int               urx,
-		   int               ury,
-		   double            kappa,
-		   int               nclip,
-		   double            tolerance,
-		   double          * kmean,
-		   double          * kstdev)
-{
-    cpl_errorstate inistate = cpl_errorstate_get();
-
-    int nx, ny;
-
-    cpl_stats * stats;
-    double      mean, stdev, var_sum;
-    int         npixs;
-
-    cpl_ensure_code(img != NULL, CPL_ERROR_NULL_INPUT);
-
-    nx = cpl_image_get_size_x(img);
-    ny = cpl_image_get_size_y(img);
-
-    cpl_ensure_code(llx > 0 && urx > llx && urx <= nx &&
-		    lly > 0 && ury > lly && ury <= ny,
-		    CPL_ERROR_ILLEGAL_INPUT);
-
-    cpl_ensure_code(tolerance >= 0.0, CPL_ERROR_ILLEGAL_INPUT);
-    cpl_ensure_code(kappa     >  1.0, CPL_ERROR_ILLEGAL_INPUT);
-    cpl_ensure_code(nclip     >    0, CPL_ERROR_ILLEGAL_INPUT);
-
-
-    skip_if(stats = cpl_stats_new_from_image_window(img,
-					    CPL_STATS_MEAN | CPL_STATS_STDEV,
-						  llx, lly, urx, ury));
-
-    npixs   = cpl_stats_get_npix(stats); /* Non-bad pixels in window */
-    mean    = cpl_stats_get_mean(stats);
-    skip_if(stdev   = cpl_stats_get_stdev(stats));
-    var_sum = stdev * stdev * (npixs - 1);
-
-    cpl_stats_delete(stats);
-
-    /* img, llx etc. may cause errors: Check and propagate */
-    cpl_ensure_code(cpl_errorstate_is_equal(inistate), cpl_error_get_code());
-
-    switch (cpl_image_get_type(img)) {
-    case CPL_TYPE_DOUBLE:
-      xsh_ksigma_clip_double(cpl_image_get_data_double_const(img),
-			     cpl_mask_get_data(cpl_image_get_bpm((cpl_image*)img)),
-					  llx, lly, urx, ury, nx, var_sum,
-					  npixs, kappa, nclip, tolerance,
-					   &mean, &stdev);
-	break;
-    case CPL_TYPE_FLOAT:
-      xsh_ksigma_clip_float(cpl_image_get_data_float_const(img),
-			    cpl_mask_get_data(cpl_image_get_bpm((cpl_image*)img)),
-					 llx, lly, urx, ury, nx, var_sum,
-					 npixs, kappa, nclip, tolerance,
-					  &mean, &stdev);
-	break;
-    case CPL_TYPE_INT:
-      xsh_ksigma_clip_int(cpl_image_get_data_int_const(img),
-			  cpl_mask_get_data(cpl_image_get_bpm((cpl_image*)img)),
-				       llx, lly, urx, ury, nx, var_sum,
-				       npixs, kappa, nclip, tolerance,
-					&mean, &stdev);
-	break;
-    default:
-	/* It is an error in CPL to reach this point */
-	assert( 0 );
-    }
-
-    *kmean = mean;
-    if (kstdev != NULL) *kstdev = stdev; /* Optional */
-
-    end_skip;
- 
-    return cpl_error_get_code();
-}
-
-#define CONCAT(a,b) a ## _ ## b
-#define CONCAT2X(a,b) CONCAT(a,b)
-
-#define CPL_TYPE double
-#include "xsh_detmon_body.h"
-#undef CPL_TYPE
-
-#define CPL_TYPE float
-#include "xsh_detmon_body.h"
-#undef CPL_TYPE
-
-#define CPL_TYPE int
-#include "xsh_detmon_body.h"
-#undef CPL_TYPE
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-cpl_error_code
-xsh_detmon_ronbias(cpl_frameset * frameset,
-                      const cpl_parameterlist * parlist,
-                      const char *tag,
-                      const char *recipe_name,
-                      const char *pipeline_name,
-                      const char *pafregexp,
-                      const cpl_propertylist * pro_master,
-                      const cpl_propertylist * pro_xstr, /* Unsupported*/
-                      const cpl_propertylist * pro_ystr, /* Unsupported*/
-                      const cpl_propertylist * pro_synth,
-                      const cpl_propertylist * pro_bpmhot,
-                      const cpl_propertylist * pro_bpmcold,
-                      const cpl_propertylist * pro_bpmdev,
-                      const char *package,
-                      int (*compare) (const cpl_frame *, const cpl_frame *),
-                      cpl_boolean opt_nir)
-{
-
-    cpl_size                     nsets;
-    int                     i;
-
-    cpl_size                    * selection  = NULL;
-    cpl_frameset           * cur_fset   = NULL;
-    cpl_propertylist       * qclist     = NULL;
-    cpl_image              * synthetic  = NULL;
-    cpl_image              * masterbias = NULL;
-    cpl_imagelist          * rawbiases  = NULL;
-    cpl_mask               * bpmhot     = NULL;
-    cpl_mask               * bpmcold    = NULL;
-    cpl_mask               * bpmdev     = NULL;
-
-    /* Test entries */
-    cpl_ensure_code(frameset        != NULL, CPL_ERROR_NULL_INPUT);
-    cpl_ensure_code(parlist         != NULL, CPL_ERROR_NULL_INPUT);
-    cpl_ensure_code(tag             != NULL, CPL_ERROR_NULL_INPUT);
-    cpl_ensure_code(recipe_name     != NULL, CPL_ERROR_NULL_INPUT);
-    cpl_ensure_code(pipeline_name   != NULL, CPL_ERROR_NULL_INPUT);
-    cpl_ensure_code(pro_master      != NULL, CPL_ERROR_NULL_INPUT);
-    cpl_ensure_code(pro_bpmhot      != NULL, CPL_ERROR_NULL_INPUT);
-    cpl_ensure_code(pro_bpmcold     != NULL, CPL_ERROR_NULL_INPUT);
-    cpl_ensure_code(pro_bpmdev      != NULL, CPL_ERROR_NULL_INPUT);
-    cpl_ensure_code(package         != NULL, CPL_ERROR_NULL_INPUT);
-
-    if(xsh_detmon_ronbias_dfs_set_groups(frameset, tag)) {
-        cpl_msg_error(cpl_func, "Cannot identify RAW and CALIB frames");
-    }
-
-    /*
-     * First of all test the entries.
-     * See if the selected method(s) is/are appliable.
-     * See if necessary parameters for those selected have been provided.
-     */
-
-/*    clreturn_if(xsh_detmon_ronbias_test_entries());
-*/
-    /*
-     * This function reads all inputs parameters from parlist
-     * and stores them in a global variable detmon_ronbias_config.
-     * Similar to xsh_detmon_lg_retrieve_parlist(). See xsh_detmon.c
-     */
-    xsh_detmon_ronbias_retrieve_parlist(pipeline_name,
-					   recipe_name, parlist, opt_nir);
-
-    /* Extra input check for PREOVERSCAN */
-    if(detmon_ronbias_config.method_bitmask & PREOVERSCAN)
-	cpl_ensure_code(pro_synth       != NULL, CPL_ERROR_NULL_INPUT);
-
-
-    /* Labelise all input frames */
-    if(compare == NULL)
-        nsets = 1;
-    else {
-        cpl_msg_info(cpl_func, "Identify the different settings");
-        selection = cpl_frameset_labelise(frameset, compare, &nsets);
-        if(selection == NULL)
-            cpl_msg_error(cpl_func, "Cannot labelise input frames");
-    }
-
-    /* Extract settings and reduce each of them */
-    for(i = 0; i < nsets; i++) {
-	int  j;
-	int first_ext = 0;
-	int last_ext  = 1;
-
-       detmon_ronbias_config.nb_extensions = 1;
-
-	/* Reduce data set nb i */
-	cpl_msg_info(cpl_func, "Reduce data set nb %d out of %" 
-                     CPL_SIZE_FORMAT "",i + 1, nsets);
-
-	cur_fset = nsets == 1 ?
-	    cpl_frameset_duplicate(frameset) :
-	    cpl_frameset_extract(frameset, selection, i);
-	skip_if(cur_fset == NULL);
-
-       if(detmon_ronbias_config.exts > 0) {
-	   first_ext = detmon_ronbias_config.exts;
-	   last_ext  = first_ext + 1;
-       } else if(detmon_ronbias_config.exts < 0) {
-          const cpl_frame        *cur_frame =
-             cpl_frameset_get_frame_const(cur_fset,0);
-          /* Get the nb of extensions */
-          detmon_ronbias_config.nb_extensions =
-             cpl_frame_get_nextensions(cur_frame);
-	  first_ext = 1;
-	  last_ext = detmon_ronbias_config.nb_extensions + 1;
-       }
-
-       if (last_ext - first_ext > 1) {
-	   skip_if(xsh_detmon_ronbias_save(parlist, frameset,
-					      recipe_name,
-					      pipeline_name, pafregexp,
-					      pro_master, pro_xstr,
-					      pro_ystr, pro_synth,
-					      pro_bpmhot,
-					      pro_bpmcold, pro_bpmdev,
-					      package, NULL, NULL, NULL,
-					      NULL, NULL, NULL,
-					      0, 0, cur_fset, 0));
-       }
-
-       for(j = first_ext; j < last_ext; j++) {
-	   int whichext;
-
-	   qclist = cpl_propertylist_new();
-
-	   rawbiases
-	       = cpl_imagelist_load_frameset(cur_fset,
-					     CPL_TYPE_FLOAT, 1, j);
-	   skip_if(rawbiases == NULL);
-
-	   skip_if(xsh_detmon_ronbias_check_defaults(cur_fset, j));
-
-	   skip_if(xsh_detmon_ronbias_dutycycl(cur_fset, qclist));
-
-	   masterbias = xsh_detmon_ronbias_master(rawbiases,
-						     &bpmhot, &bpmcold,
-						     &bpmdev, qclist);
-	   skip_if(masterbias == NULL);
-
-	   /*
-	    * Following, a function corresponding each of the
-	    * possible methods is to be found.
-	    */
-
-          if(detmon_ronbias_config.method_bitmask & RANDOM) {
-	      skip_if(xsh_detmon_ronbias_random(rawbiases, masterbias,
-						   qclist));
-          }
-
-          if(detmon_ronbias_config.method_bitmask & HISTO) {
-	      skip_if(xsh_detmon_ronbias_histo(rawbiases, masterbias,
-						  qclist));
-          }
-
-          if(detmon_ronbias_config.method_bitmask & PREOVERSCAN) {
-	      skip_if(xsh_detmon_ronbias_preoverscan(rawbiases,
-							/*masterbias,*/
-							qclist, &synthetic));
-          }
-
-          if(detmon_ronbias_config.method_bitmask & REGION) {
-	      skip_if(xsh_detmon_ronbias_region(rawbiases, masterbias,
-						   qclist));
-          }
-
-          /*
-           * This function takes the QC list where all the results of the
-           * methods applied are stored, and compares them.
-           * No action defined yet if comparison reveals important differences.
-           */
-#if 0
-	  xsh_detmon_ronbias_check(qclist);
-#endif
-
-	  /* Definition of the extension of the output where to save
-	     the products. If input are multiextension but only
-	     computation on a single extension is required, it is 0 */
-	  whichext = first_ext > 1 ? 0 : j;
-
-          skip_if(xsh_detmon_ronbias_save(parlist, frameset,
-					     recipe_name,
-					     pipeline_name, pafregexp,
-					     pro_master, pro_xstr,
-					     pro_ystr, pro_synth,
-					     pro_bpmhot,
-					     pro_bpmcold, pro_bpmdev,
-					     package, masterbias, synthetic,
-					     bpmhot, bpmcold, bpmdev,
-					     qclist, 0, 0, cur_fset,
-					     whichext));
-
-          cpl_image_delete(synthetic);
-          cpl_image_delete(masterbias);
-          cpl_mask_delete(bpmhot);
-          cpl_mask_delete(bpmcold);
-          cpl_mask_delete(bpmdev);
-          cpl_imagelist_delete(rawbiases);
-	  cpl_propertylist_delete(qclist);
-
-	  qclist     = NULL;
-	  rawbiases  = NULL;
-	  masterbias = NULL;
-	  bpmhot     = NULL;
-	  bpmcold    = NULL;
-	  bpmdev     = NULL;
-	  synthetic  = NULL;
-       } /* for each extension */
-
-       cpl_frameset_delete(cur_fset);
-       cur_fset = NULL;
-
-    } /* for each setting */
-
-    end_skip;
-
-    cpl_free(selection);
-
-    cpl_frameset_delete(cur_fset);
-
-    cpl_image_delete(synthetic);
-    cpl_image_delete(masterbias);
-    cpl_mask_delete(bpmhot);
-    cpl_mask_delete(bpmcold);
-    cpl_mask_delete(bpmdev);
-    cpl_imagelist_delete(rawbiases);
-    cpl_propertylist_delete(qclist);
-
-    return cpl_error_get_code();
-}
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-static cpl_error_code
-xsh_detmon_ronbias_random(const cpl_imagelist * rawbiases,
-			     const cpl_image     * masterbias,
-                             cpl_propertylist    * qclist)
-{
-    int                     nraws = cpl_imagelist_get_size(rawbiases);
-    int                     i;
-    double                  bias = DBL_MAX;  /* Avoid (false) uninit warning */
-    double                  bias_error;
-
-    double                  ron_error;
-    double                 *ron =
-        (double *) cpl_malloc(sizeof(double) * nraws);
-
-    cpl_vector             *v;
-    double stdev = 0;
-    cpl_error_code error = CPL_ERROR_NONE;
-
-    /* As we are applying to diff frames instead of raw frames,
-       there is one less to compute on */
-    if(!strcmp(detmon_ronbias_config.pmethod, "DIF"))
-    {
-		nraws--;
-		/* As we are applying to diff frames instead of raw frames,
-		   there is one less to compute on */
-		for(i = 0; i < nraws; i++)
-		{
-			const cpl_image        *c1_raw =
-			cpl_imagelist_get_const(rawbiases, i);
-			const cpl_image        *c2_raw =
-			cpl_imagelist_get_const(rawbiases, i + 1);
-			/*FIXME: See if const modifier is necessary */
-			const cpl_image        *c_raw = cpl_image_subtract_create(c1_raw,
-										  c2_raw);
-		   error = cpl_flux_get_noise_window(c_raw, NULL,
-						  detmon_ronbias_config.random_sizex / 2,
-						  detmon_ronbias_config.random_nsamples,
-						  ron + i, &ron_error);
-		   cpl_image_delete((cpl_image*)c_raw);
-		   if (error != CPL_ERROR_NONE)
-		   {
-			   break;
-		   }
-		}
-    } else
-    {
-		for(i = 0; i < nraws; i++)
-		{
-			const cpl_image *c_raw = cpl_imagelist_get_const(rawbiases, i);
-			skip_if(cpl_flux_get_noise_window(c_raw, NULL,
-						  detmon_ronbias_config.random_sizex / 2,
-						  detmon_ronbias_config.random_nsamples,
-						  ron + i, &ron_error));
-		}
-    }
-
-    /*FIXME: Calls to noise_window could be out from if() and
-      coded only once */
-    if (error == CPL_ERROR_NONE)
-    {
-		xsh_flux_get_bias_window(masterbias, NULL,
-					detmon_ronbias_config.random_sizex / 2,
-					detmon_ronbias_config.random_nsamples,
-					&bias, &bias_error);
-
-		v = cpl_vector_wrap(nraws, ron);
-		stdev = cpl_vector_get_median_const(v);
-		cpl_vector_unwrap(v);
-
-
-		skip_if(cpl_propertylist_append_double(qclist,DETMON_QC_BIAS_RANDOM_VAL, bias));
-		skip_if(cpl_propertylist_set_comment(qclist,DETMON_QC_BIAS_RANDOM_VAL,
-						 DETMON_QC_BIAS_RANDOM_VAL_C));
-
-		skip_if(cpl_propertylist_append_double(qclist,DETMON_QC_BIAS_RANDOM_RON, stdev));
-		skip_if(cpl_propertylist_set_comment(qclist,DETMON_QC_BIAS_RANDOM_RON,
-						 DETMON_QC_BIAS_RANDOM_RON_C));
-    }
-
-    xsh_flux_get_bias_window(masterbias, NULL,
-				detmon_ronbias_config.random_sizex / 2,
-				detmon_ronbias_config.random_nsamples,
-				&bias, &bias_error);
-
-    v = cpl_vector_wrap(nraws, ron);
-    if (v)
-    {
-    	stdev = cpl_vector_get_median_const(v);
-		cpl_vector_unwrap(v);
-    }
-
-    error = cpl_propertylist_append_double(qclist,DETMON_QC_BIAS_RANDOM_VAL, bias);
-    error = cpl_propertylist_set_comment(qclist,DETMON_QC_BIAS_RANDOM_VAL,
-					 DETMON_QC_BIAS_RANDOM_VAL_C);
-
-
-    error = cpl_propertylist_append_double(qclist,DETMON_QC_BIAS_RANDOM_RON, stdev);
-    error = cpl_propertylist_set_comment(qclist,DETMON_QC_BIAS_RANDOM_RON,
-					 DETMON_QC_BIAS_RANDOM_RON_C);
-
-    end_skip;
-    if (ron)
-		cpl_free(ron);
-    return cpl_error_get_code();
-}
-
-static cpl_error_code
-xsh_detmon_ronbias_histo(const cpl_imagelist * rawbiases,
-			    const cpl_image * masterbias,
-                            cpl_propertylist * qclist)
-{
-    int                     nraws = cpl_imagelist_get_size(rawbiases);
-    int                     i;
-
-    double mbias = DBL_MAX;
-    double mfwhm = DBL_MAX;
-    double mmax = DBL_MAX;
-
-    cpl_vector * fwhms;
-    cpl_vector * maxs;
-
-    double mean_fwhm = DBL_MAX;
-
-    if(!strcmp(detmon_ronbias_config.pmethod, "DIF")) nraws--;
-
-    fwhms = cpl_vector_new(nraws);
-    maxs = cpl_vector_new(nraws);
-
-    for(i = 0; i < nraws; i++) {
-	/*FIXME: See if it is necessary to have const */
-	const cpl_image * c_raw;
-	double bias = DBL_MAX;
-	double fwhm = DBL_MAX;
-	double max = DBL_MAX;
-
-	if(strcmp(detmon_ronbias_config.pmethod, "DIF")) {
-           c_raw = cpl_imagelist_get_const(rawbiases, i);
-	} else {
-	    const cpl_image        *c1_raw = cpl_imagelist_get_const(rawbiases, i);
-	    const cpl_image        * c2_raw = cpl_imagelist_get_const(rawbiases, i+1);
-	    c_raw = cpl_image_subtract_create(c1_raw, c2_raw);
-	}
-
-	skip_if(xsh_detmon_ronbias_histo_reduce(c_raw, &bias, &fwhm, &max));
-
-	skip_if(bias == DBL_MAX || fwhm == DBL_MAX || max == DBL_MAX);
-
-	if(!strcmp(detmon_ronbias_config.pmethod, "DIF"))
-	    cpl_image_delete((cpl_image *)c_raw);
-
-        skip_if(cpl_vector_set(maxs, i, max));
-        skip_if(cpl_vector_set(fwhms, i, fwhm));
-
-	/* FIXME: Add properly a hist-saving in debug-mode */
-    }
-
-    skip_if(cpl_vector_divide_scalar(fwhms, HIST_FACT));
-
-    xsh_detmon_ronbias_histo_reduce(masterbias, &mbias, &mfwhm, &mmax);
-
-    skip_if(mbias == DBL_MAX || mfwhm == DBL_MAX || mmax == DBL_MAX);
-
-    skip_if(cpl_propertylist_append_double(qclist,DETMON_QC_BIAS_HISTO_VAL,
-					   mbias));
-    skip_if(cpl_propertylist_set_comment(qclist,DETMON_QC_BIAS_HISTO_VAL,
-					 DETMON_QC_BIAS_HISTO_VAL_C));
-    mean_fwhm = cpl_vector_get_mean(fwhms);
-
-    skip_if(mean_fwhm == DBL_MAX);
-    skip_if(cpl_error_get_code());
-
-    skip_if(cpl_propertylist_append_double(qclist,DETMON_QC_BIAS_HISTO_RON,
-					   mean_fwhm));
-    skip_if(cpl_propertylist_set_comment(qclist,DETMON_QC_BIAS_HISTO_RON,
-					 DETMON_QC_BIAS_HISTO_RON_C));
-
-    end_skip;
-
-    cpl_vector_delete(fwhms);
-    cpl_vector_delete(maxs);
-
-    return cpl_error_get_code();
-}
-
-cpl_error_code
-xsh_detmon_ronbias_histo_reduce(const cpl_image * c_raw,
-				   double * bias,
-				   double * fwhm,
-				   double * max)
-{
-    unsigned long           uj;
-    xsh_hist            *hist;
-    unsigned long           maxwhere = 0;
-    //unsigned long           maxf;
-
-    //double mean, stdev;
-    cpl_image * dupi;
-    unsigned long           x1a = 1;
-    unsigned long           x2a = 1;
-
-    double                  x1 = 0;
-    double                  x2 = 0;
-
-    double                  maxwhere_interp;
-    double                  max_interp;
-    double a, b, c;
-    cpl_matrix * coeffs =cpl_matrix_new(3, 3);
-    cpl_matrix * rhs    =cpl_matrix_new(3, 1);
-    int p, q;
-    cpl_matrix * result = NULL;
-    cpl_error_code error;
-
-    //mean = cpl_image_get_mean(c_raw);
-    //stdev = cpl_image_get_stdev(c_raw);
-    dupi = cpl_image_duplicate(c_raw);
-
-    /* FIXME: Still to decide if it is necessary to remove bad pixels
-       in advance or not*/
-
-    hist = xsh_hist_new();
-    error = xsh_hist_fill(hist, dupi);
-    cpl_ensure_code(!error, error);
-
-    cpl_image_delete(dupi);
-
-    //maxf = xsh_hist_get_max(hist, &maxwhere);
-
-    for( p = 0; p< 3; p++){
-	unsigned long bi = xsh_hist_get_value(hist, maxwhere-1+p);
-	cpl_matrix_set(rhs, p, 0, bi);
-	for( q= 0; q< 3; q++) {
-	    cpl_matrix_set(coeffs, p,q,pow((maxwhere-1+p),q));
-	}
-    }
-
-    result = cpl_matrix_solve(coeffs, rhs);
-
-    a = cpl_matrix_get(result, 2, 0);
-    b = cpl_matrix_get(result, 1, 0);
-    c = cpl_matrix_get(result, 0, 0);
-
-    maxwhere_interp = -0.5 * b / (2 * a);
-    max_interp = -1 * b * b / (4 * a) + c;
-
-    cpl_matrix_delete(coeffs);
-    cpl_matrix_delete(rhs);
-    cpl_matrix_delete(result);
-
-    /* Look for the points of half-maximum */
-    for(uj = 0; uj < maxwhere; uj++) {
-	if(xsh_hist_get_value(hist, uj)     <= max_interp / 2 &&
-	   xsh_hist_get_value(hist, uj + 1) >  max_interp / 2) {
-	    x1a = uj;
-	}
-    }
-    for(uj = maxwhere; uj < xsh_hist_get_nbins(hist)-1; uj++) {
-	if(xsh_hist_get_value(hist, uj)     >= max_interp / 2 &&
-	   xsh_hist_get_value(hist, uj + 1) <  max_interp / 2) {
-	    x2a = uj;
-	}
-    }
-
-    x1 = (max_interp / 2 - xsh_hist_get_value(hist, x1a)) /
-	(xsh_hist_get_value(hist, x1a + 1) -
-	 xsh_hist_get_value(hist, x1a)) + x1a;
-    x2 = (max_interp / 2 - xsh_hist_get_value(hist, x2a)) /
-	(xsh_hist_get_value(hist, x2a + 1) -
-	 xsh_hist_get_value(hist, x2a)) + x2a;
-
-    *fwhm = (x2 - x1) * xsh_hist_get_bin_size(hist);
-
-    *max = max_interp;
-
-    *bias =  maxwhere_interp * xsh_hist_get_bin_size(hist) +
-                           xsh_hist_get_start(hist);
-
-    xsh_hist_delete(hist);
-
-    return cpl_error_get_code();
-}
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-static cpl_error_code
-xsh_detmon_ronbias_preoverscan(const cpl_imagelist * rawbiases,
-                                  cpl_propertylist * qclist,
-                                  cpl_image ** synthetic)
-{
-    int                     i;
-    int                     nx, ny;
-    int                     nraws;
-
-    cpl_vector             *meanspre;
-    cpl_vector             *medspre;
-    cpl_vector             *rmsspre;
-    cpl_vector             *meansover;
-    cpl_vector             *medsover;
-    cpl_vector             *rmssover;
-
-    cpl_error_code          error;
-
-    nraws = cpl_imagelist_get_size(rawbiases);
-    cpl_ensure_code(nraws != -1, CPL_ERROR_ILLEGAL_INPUT);
-
-    meanspre = cpl_vector_new(nraws);
-    medspre = cpl_vector_new(nraws);
-    rmsspre = cpl_vector_new(nraws);
-    meansover = cpl_vector_new(nraws);
-    medsover = cpl_vector_new(nraws);
-    rmssover = cpl_vector_new(nraws);
-
-    nx = cpl_image_get_size_x(cpl_imagelist_get_const(rawbiases, 0));
-    ny = cpl_image_get_size_y(cpl_imagelist_get_const(rawbiases, 0));
-    cpl_ensure_code(nx != -1 && ny != -1, CPL_ERROR_ILLEGAL_INPUT);
-
-    if(nx < detmon_ronbias_config.prescan_urx ||
-       nx < detmon_ronbias_config.overscan_urx ||
-       ny < detmon_ronbias_config.prescan_ury ||
-       ny < detmon_ronbias_config.overscan_ury) {
-        cpl_msg_warning(cpl_func, "PREOVERSCAN method not applied. Given "
-                        "limits of prescan and overscan area "
-                        "exceed image size. Please check and rerun.");
-        return CPL_ERROR_NONE;
-    }
-
-    for(i = 0; i < nraws; i++) {
-        double                  mean = 0;
-        double                  stdev = 0;
-
-        cpl_image              *prescan = NULL;
-        cpl_image              *overscan = NULL;
-
-        const cpl_image        *c_raw = cpl_imagelist_get_const(rawbiases, i);
-
-        cpl_ensure_code(c_raw != NULL, CPL_ERROR_ILLEGAL_INPUT);
-
-        prescan =
-            cpl_image_extract(c_raw,
-                              detmon_ronbias_config.prescan_llx,
-                              detmon_ronbias_config.prescan_lly,
-                              detmon_ronbias_config.prescan_urx,
-                              detmon_ronbias_config.prescan_ury);
-        cpl_ensure_code(prescan != NULL, CPL_ERROR_ILLEGAL_INPUT);
-        overscan =
-            cpl_image_extract(c_raw,
-                              detmon_ronbias_config.overscan_llx,
-                              detmon_ronbias_config.overscan_lly,
-                              detmon_ronbias_config.overscan_urx,
-                              detmon_ronbias_config.overscan_ury);
-        cpl_ensure_code(overscan != NULL, CPL_ERROR_ILLEGAL_INPUT);
-
-        if(i == 0) {
-            *synthetic = xsh_detmon_build_synthetic(prescan, overscan);
-            cpl_msg_info(cpl_func, "Creating SYNTHETIC frame");
-            if(*synthetic == NULL) {
-                cpl_msg_error(cpl_func, "Error creating SYNTHETIC frame");
-                return CPL_ERROR_UNSPECIFIED;
-            }
-        }
-
-        error = xsh_ksigma_clip(c_raw,
-                                             detmon_ronbias_config.
-                                             prescan_llx,
-                                             detmon_ronbias_config.
-                                             prescan_lly,
-                                             detmon_ronbias_config.
-                                             prescan_urx,
-                                             detmon_ronbias_config.
-                                             prescan_ury,
-                                             (double) detmon_ronbias_config.
-                                             stacking_ks_low,
-                                             detmon_ronbias_config.
-                                             stacking_ks_iter, 1e-5,
-					     &mean, &stdev);
-        cpl_ensure_code(!error, error);
-
-        cpl_ensure_code(mean != 0 && stdev != 0, CPL_ERROR_UNSPECIFIED);
-
-        error = cpl_vector_set(medspre, i, cpl_image_get_median(prescan));
-        cpl_ensure_code(!error, error);
-
-        error = cpl_vector_set(meanspre, i, mean);
-        cpl_ensure_code(!error, error);
-        error = cpl_vector_set(rmsspre, i, stdev);
-        cpl_ensure_code(!error, error);
-        error = xsh_ksigma_clip(c_raw,
-                                             detmon_ronbias_config.
-                                             overscan_llx,
-                                             detmon_ronbias_config.
-                                             overscan_lly,
-                                             detmon_ronbias_config.
-                                             overscan_urx,
-                                             detmon_ronbias_config.
-                                             overscan_ury,
-                                             (double) detmon_ronbias_config.
-                                             stacking_ks_low,
-                                             detmon_ronbias_config.
-                                             stacking_ks_iter, 1e-5,
-					     &mean, &stdev);
-        cpl_ensure_code(!error, error);
-
-        cpl_ensure_code(mean != 0 && stdev != 0, CPL_ERROR_UNSPECIFIED);
-
-        error = cpl_vector_set(medsover, i, cpl_image_get_median(overscan));
-        cpl_ensure_code(!error, error);
-
-        error = cpl_vector_set(meansover, i, mean);
-        cpl_ensure_code(!error, error);
-        error = cpl_vector_set(rmssover, i, stdev);
-        cpl_ensure_code(!error, error);
-
-        cpl_image_delete(prescan);
-        cpl_image_delete(overscan);
-    }
-
-    error = cpl_propertylist_append_double(qclist,DETMON_QC_BIAS_PRESCAN_MEAN,
-                                           cpl_vector_get_mean(meanspre));
-
-    error = cpl_propertylist_set_comment(qclist,DETMON_QC_BIAS_PRESCAN_MEAN,
-					 DETMON_QC_BIAS_PRESCAN_MEAN_C);
-
-    cpl_ensure_code(!error, error);
-    error = cpl_propertylist_append_double(qclist,DETMON_QC_BIAS_PRESCAN_MED,
-                                           cpl_vector_get_mean(medspre));
-    error = cpl_propertylist_set_comment(qclist,DETMON_QC_BIAS_PRESCAN_MED,
-					 DETMON_QC_BIAS_PRESCAN_MED_C);
-
-    cpl_ensure_code(!error, error);
-    error = cpl_propertylist_append_double(qclist,DETMON_QC_BIAS_PRESCAN_RON,
-                                           cpl_vector_get_mean(rmsspre));
-
-    error = cpl_propertylist_set_comment(qclist,DETMON_QC_BIAS_PRESCAN_RON,
-					 DETMON_QC_BIAS_PRESCAN_RON_C);
-    cpl_ensure_code(!error, error);
-
-    error =
-        cpl_propertylist_append_double(qclist,DETMON_QC_BIAS_OVERSCAN_MEAN,
-                                       cpl_vector_get_mean(meansover));
-    error = cpl_propertylist_set_comment(qclist,DETMON_QC_BIAS_OVERSCAN_MEAN,
-					 DETMON_QC_BIAS_OVERSCAN_MEAN_C);
-    cpl_ensure_code(!error, error);
-    error = cpl_propertylist_append_double(qclist,DETMON_QC_BIAS_OVERSCAN_MED,
-                                           cpl_vector_get_mean(medsover));
-    error = cpl_propertylist_set_comment(qclist,DETMON_QC_BIAS_OVERSCAN_MED,
-					 DETMON_QC_BIAS_OVERSCAN_MED_C);
-    cpl_ensure_code(!error, error);
-    error = cpl_propertylist_append_double(qclist,DETMON_QC_BIAS_OVERSCAN_RON,
-                                           cpl_vector_get_mean(rmssover));
-    error = cpl_propertylist_set_comment(qclist,DETMON_QC_BIAS_OVERSCAN_RON,
-					 DETMON_QC_BIAS_OVERSCAN_RON_C);
-    cpl_ensure_code(!error, error);
-
-    /* The following seems not to be necessary.
-       Pending of revision to be removed */
-    /*
-    error =
-        cpl_propertylist_append_double(qclist,
-                                       "ESO QC BIAS PRESCAN MEAN STDEV",
-                                       cpl_vector_get_stdev(meanspre));
-    cpl_ensure_code(!error, error);
-    error =
-        cpl_propertylist_append_double(qclist,
-                                       "ESO QC BIAS PRESCAN MED STDEV",
-                                       cpl_vector_get_stdev(medspre));
-    cpl_ensure_code(!error, error);
-    error =
-        cpl_propertylist_append_double(qclist,
-                                       "ESO QC BIAS PRESCAN RMS STDEV",
-                                       cpl_vector_get_stdev(rmsspre));
-    cpl_ensure_code(!error, error);
-
-    error =
-        cpl_propertylist_append_double(qclist,
-                                       "ESO QC BIAS OVERSCAN MEAN STDEV",
-                                       cpl_vector_get_stdev(meansover));
-    cpl_ensure_code(!error, error);
-    error =
-        cpl_propertylist_append_double(qclist,
-                                       "ESO QC BIAS OVERSCAN MED STDEV",
-                                       cpl_vector_get_stdev(medsover));
-    cpl_ensure_code(!error, error);
-    error =
-        cpl_propertylist_append_double(qclist,
-                                       "ESO QC BIAS OVERSCAN RMS STDEV",
-                                       cpl_vector_get_stdev(rmssover));
-    cpl_ensure_code(!error, error);
-    */
-
-    cpl_vector_delete(meanspre);
-    cpl_vector_delete(medspre);
-    cpl_vector_delete(rmsspre);
-    cpl_vector_delete(meansover);
-    cpl_vector_delete(medsover);
-    cpl_vector_delete(rmssover);
-
-    return CPL_ERROR_NONE;
-}
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-static cpl_error_code
-xsh_detmon_ronbias_region(const cpl_imagelist * rawbiases,
-			     const cpl_image * masterbias,
-                             cpl_propertylist * qclist)
-{
-
-    int                     nraws = cpl_imagelist_get_size(rawbiases);
-    int                     i;
-
-    int                     nx =
-        cpl_image_get_size_x(cpl_imagelist_get_const(rawbiases, 0));
-    int                     ny =
-        cpl_image_get_size_y(cpl_imagelist_get_const(rawbiases, 0));
-
-    cpl_vector *rmssreg;
-    cpl_error_code          error;
-
-    const cpl_image * c_raw;
-    double median, mbias, mstdev;
-
-    if(!strcmp(detmon_ronbias_config.pmethod, "DIF")) nraws--;
-
-    rmssreg = cpl_vector_new(nraws);
-
-    if(nx < detmon_ronbias_config.ref_urx ||
-       ny < detmon_ronbias_config.ref_ury) {
-        cpl_msg_warning(cpl_func, "REGION method not applied. Given "
-                        "limits of prescan and overscan area "
-                        "exceed image size. Please check and rerun.");
-        return CPL_ERROR_NONE;
-    }
-
-    for(i = 0; i < nraws; i++) {
-        double                  mean = 0;
-        double                  stdev = 0;
-	if(strcmp(detmon_ronbias_config.pmethod, "DIF")) {
-	    c_raw = cpl_imagelist_get_const(rawbiases, i);
-	} else {
-	    const cpl_image        *c1_raw = cpl_imagelist_get_const(rawbiases, i);
-	    const cpl_image        * c2_raw = cpl_imagelist_get_const(rawbiases, i+1);
-	    c_raw = cpl_image_subtract_create(c1_raw, c2_raw);
-	}
-        error = xsh_ksigma_clip(c_raw,
-                                             detmon_ronbias_config.ref_llx,
-                                             detmon_ronbias_config.ref_lly,
-                                             detmon_ronbias_config.ref_urx,
-                                             detmon_ronbias_config.ref_ury,
-                                             (double) detmon_ronbias_config.
-                                             stacking_ks_low,
-                                             detmon_ronbias_config.
-                                             stacking_ks_iter, 1e-5,
-					     &mean, &stdev);
-        cpl_ensure_code(!error, error);
-        /*        cpl_vector_set(rmssreg, i, cpl_image_get_stdev_window(c_raw,
-           detmon_ronbias_config.ref_llx,
-           detmon_ronbias_config.ref_lly,
-           detmon_ronbias_config.ref_urx,
-           detmon_ronbias_config.ref_ury));
-         */
-        error = cpl_vector_set(rmssreg, i, stdev);
-        cpl_ensure_code(!error, error);
-	if(!strcmp(detmon_ronbias_config.pmethod, "DIF")) cpl_image_delete((cpl_image *)c_raw);
-    }
-
-    median =  cpl_image_get_median_window(masterbias,
-					  detmon_ronbias_config.ref_llx,
-					  detmon_ronbias_config.ref_lly,
-					  detmon_ronbias_config.ref_urx,
-					  detmon_ronbias_config.ref_ury);
-    error = xsh_ksigma_clip(masterbias,
-					 detmon_ronbias_config.ref_llx,
-					 detmon_ronbias_config.ref_lly,
-					 detmon_ronbias_config.ref_urx,
-					 detmon_ronbias_config.ref_ury,
-					 (double) detmon_ronbias_config.
-					 stacking_ks_low,
-					 detmon_ronbias_config.
-					 stacking_ks_iter, 1e-5,
-					 &mbias, &mstdev);
-
-    error = cpl_propertylist_append_double(qclist,DETMON_QC_BIAS_REGION_MED,
-					   median);
-    error = cpl_propertylist_set_comment(qclist,DETMON_QC_BIAS_REGION_MED,
-					 DETMON_QC_BIAS_REGION_MED_C);
-    cpl_ensure_code(!error, error);
-
-    error = cpl_propertylist_append_double(qclist,DETMON_QC_BIAS_REGION_VAL,
-					   mbias);
-    error = cpl_propertylist_set_comment(qclist,DETMON_QC_BIAS_REGION_VAL,
-					 DETMON_QC_BIAS_REGION_VAL_C);
-    cpl_ensure_code(!error, error);
-    error = cpl_propertylist_append_double(qclist,DETMON_QC_BIAS_REGION_RON,
-					   cpl_vector_get_mean(rmssreg));
-    error = cpl_propertylist_set_comment(qclist,DETMON_QC_BIAS_REGION_RON,
-					 DETMON_QC_BIAS_REGION_RON_C);
-    cpl_ensure_code(!error, error);
-    /*
-    error =
-        cpl_propertylist_append_double(qclist, "ESO QC BIAS REGION RMS STDEV",
-                                       cpl_vector_get_stdev(rmssreg));
-    cpl_ensure_code(!error, error);
-    */
-    cpl_vector_delete(rmssreg);
-
-    return cpl_error_get_code();
-}
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-static cpl_image *
-xsh_detmon_ronbias_master(const cpl_imagelist * rawbiases,
-			     cpl_mask ** bpmhot, cpl_mask ** bpmcold,
-			     cpl_mask ** bpmdev, cpl_propertylist * qclist)
-{
-    double                  mean = 0;
-    double                  stdev = 0;
-    cpl_image              *masterbias = NULL;
-    double dark_med, stdev_med,lower, upper;
-    int hotpix_nb, coldpix_nb, devpix_nb;
-    cpl_image * stdev_im = NULL;
-
-    if(!strcmp(detmon_ronbias_config.stacking_method, "MEAN"))
-        masterbias = cpl_imagelist_collapse_create(rawbiases);
-    if(!strcmp(detmon_ronbias_config.stacking_method, "MINMAX"))
-        masterbias =
-            cpl_imagelist_collapse_minmax_create(rawbiases, 0, 10000);
-    if(!strcmp(detmon_ronbias_config.stacking_method, "KSIGMA"))
-        masterbias =
-	cpl_imagelist_collapse_sigclip_create(rawbiases, 3.0, 3.0, 0.9,
-					      CPL_COLLAPSE_MEAN, NULL);
-
-    if(!strcmp(detmon_ronbias_config.stacking_method, "MEDIAN"))
-        masterbias = cpl_imagelist_collapse_median_create(rawbiases);
-
-    skip_if(masterbias == NULL);
-
-    skip_if(xsh_ksigma_clip(masterbias, 1, 1,
-                                         cpl_image_get_size_x(masterbias),
-                                         cpl_image_get_size_y(masterbias),
-                                         (double) detmon_ronbias_config.
-                                         stacking_ks_low,
-                                         detmon_ronbias_config.
-                                         stacking_ks_iter, 1e-5,
-					 &mean, &stdev));
-
-    if(irplib_isnan(mean))
-	cpl_msg_error(cpl_func, "We have an error in mean");
-    if(irplib_isnan(stdev))
-	cpl_msg_error(cpl_func, "We have an error in stdev");
-
-    skip_if(cpl_propertylist_append_double(qclist,DETMON_QC_MASTER_MEAN,
-					   mean));
-    skip_if(cpl_propertylist_set_comment(qclist,DETMON_QC_MASTER_MEAN,
-					 DETMON_QC_MASTER_MEAN_C));
-
-    skip_if(cpl_propertylist_append_double(qclist,DETMON_QC_MASTER_RMS,
-					   stdev));
-    skip_if(cpl_propertylist_set_comment(qclist,DETMON_QC_MASTER_RMS,
-					 DETMON_QC_MASTER_RMS_C));
-
-    /* Compute median-rms of the central part of the dark  */
-    dark_med = cpl_image_get_median(masterbias);
-
-    lower = dark_med - stdev * detmon_ronbias_config.stacking_ks_low;
-    upper = dark_med + stdev * detmon_ronbias_config.stacking_ks_high;
-
-    /* Create the hot pixel map */
-    cpl_mask_delete(*bpmhot);
-    irplib_check(*bpmhot = cpl_mask_threshold_image_create(masterbias,
-							   upper, DBL_MAX),
-                 "Cannot compute the hot pixel map");
-    hotpix_nb = cpl_mask_count(*bpmhot);
-    skip_if (0);
-
-    /* Create the cold pixel map */
-    cpl_mask_delete(*bpmcold);
-    irplib_check(*bpmcold = cpl_mask_threshold_image_create(masterbias,
-							    -FLT_MAX, lower),
-                 "Cannot compute the cold pixel map");
-    coldpix_nb = cpl_mask_count(*bpmcold);
-    skip_if (0);
-
-    /* Create the deviant pixel map */
-    stdev_im  = irplib_imagelist_collapse_stdev_create(rawbiases);
-    stdev_med = cpl_image_get_median(stdev_im);
-
-    skip_if(xsh_ksigma_clip(stdev_im, 1, 1,
-                                         cpl_image_get_size_x(stdev_im),
-                                         cpl_image_get_size_y(stdev_im),
-                                         (double) detmon_ronbias_config.
-                                         stacking_ks_low,
-                                         detmon_ronbias_config.
-                                         stacking_ks_iter, 1e-5,
-					 &mean, &stdev));
-
-    lower = stdev_med - stdev * detmon_ronbias_config.stacking_ks_low;
-    upper = stdev_med + stdev * detmon_ronbias_config.stacking_ks_high;
-
-    cpl_mask_delete(*bpmdev);
-    irplib_check(*bpmdev = cpl_mask_threshold_image_create(stdev_im,
-							   lower, upper),
-                 "Cannot compute the cold pixel map");
-    cpl_mask_not(*bpmdev);
-    devpix_nb = cpl_mask_count(*bpmdev);
-    skip_if (0);
-
-
-    skip_if(cpl_propertylist_append_int(qclist,DETMON_QC_NBCOLDPIX,coldpix_nb));
-    skip_if(cpl_propertylist_set_comment(qclist,DETMON_QC_NBCOLDPIX,
-					 DETMON_QC_NBCOLDPIX_C));
-
-    skip_if(cpl_propertylist_append_int(qclist,DETMON_QC_NBHOTPIX, hotpix_nb));
-    skip_if(cpl_propertylist_set_comment(qclist,DETMON_QC_NBHOTPIX,
-					 DETMON_QC_NBHOTPIX_C));
-
-    skip_if(cpl_propertylist_append_int(qclist,DETMON_QC_NBDEVPIX, devpix_nb));
-    skip_if(cpl_propertylist_set_comment(qclist,DETMON_QC_NBDEVPIX,
-					 DETMON_QC_NBDEVPIX_C));
-
-    end_skip;
-
-    cpl_image_delete(stdev_im);
-
-    if (cpl_error_get_code()) {
-	cpl_image_delete(masterbias);
-	masterbias = NULL;
-    }
-
-    return masterbias;
-}
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-static                  cpl_error_code
-xsh_detmon_ronbias_save(const cpl_parameterlist * parlist,
-                           cpl_frameset * frameset,
-                           const char *recipe_name,
-                           const char *pipeline_name,
-			   const char *pafregexp,
-			   const cpl_propertylist * pro_master,
-			   const cpl_propertylist * pro_xstr, /* Unsupported*/
-			   const cpl_propertylist * pro_ystr, /* Unsupported*/
-			   const cpl_propertylist * pro_synth,
-			   const cpl_propertylist * pro_bpmhot,
-			   const cpl_propertylist * pro_bpmcold,
-			   const cpl_propertylist * pro_bpmdev,
-                           const char *package,
-                           const cpl_image * masterbias,
-                           const cpl_image * synthetic,
-                           const cpl_mask * bpmhot,
-                           const cpl_mask * bpmcold,
-                           const cpl_mask * bpmdev,
-                           cpl_propertylist * qclist,
-                           const int flag_sets,
-                           const int which_set,
-                           cpl_frameset * usedframes,
-                           int whichext)
-{
-
-    cpl_frame              *ref_frame;
-    cpl_propertylist       *plist = NULL;
-    char                   *name_o = NULL; /* Avoid (false) uninit warning */
-
-    cpl_propertylist       * paflist   = NULL;
-    cpl_propertylist       * mainplist = NULL;
-    cpl_propertylist       * xplist    = NULL;
-    cpl_image              * image     = NULL;
-
-    cpl_propertylist  * mypro_master     =
-	cpl_propertylist_duplicate(pro_master);
-
-    cpl_propertylist  * mypro_synth = NULL;
-    cpl_propertylist  * mypro_bpmhot    =
-	cpl_propertylist_duplicate(pro_bpmhot);
-    cpl_propertylist  * mypro_bpmcold =
-	cpl_propertylist_duplicate(pro_bpmcold);
-    cpl_propertylist  * mypro_bpmdev =
-	cpl_propertylist_duplicate(pro_bpmdev);
-
-    cpl_ensure_code(parlist != NULL, CPL_ERROR_NULL_INPUT);
-    cpl_ensure_code(frameset != NULL, CPL_ERROR_NULL_INPUT);
-    cpl_ensure_code(pafregexp != NULL, CPL_ERROR_NULL_INPUT);
-    cpl_ensure_code(package != NULL, CPL_ERROR_NULL_INPUT);
-    cpl_ensure_code(recipe_name != NULL, CPL_ERROR_NULL_INPUT);
-    cpl_ensure_code(pipeline_name != NULL, CPL_ERROR_NULL_INPUT);
-    cpl_ensure_code(usedframes != NULL, CPL_ERROR_NULL_INPUT);
-
-    if (pro_synth)
-	mypro_synth = cpl_propertylist_duplicate(pro_synth);
-
-    /* Extra check while XSTR and YSTR are not supported */
-    cpl_ensure_code(pro_xstr == NULL && pro_ystr == NULL,
-		    CPL_ERROR_UNSUPPORTED_MODE);
-
-    /* Extract extension headers if multi-extension */
-    if (detmon_ronbias_config.exts < 0) {
-        const char * filename =
-            cpl_frame_get_filename(cpl_frameset_get_frame(frameset,0));
-
-
-            xplist = cpl_propertylist_load_regexp(filename, whichext,
-                                                     "ESO DET", 0);
-	    skip_if(cpl_propertylist_append(xplist, qclist));
-    }
-
-    cpl_msg_info(cpl_func,"dealing with extention %d",whichext);
-
-    /* This is only used later for PAF */
-    /* Get FITS header from reference file */
-    ref_frame = cpl_frameset_get_frame(frameset,0);
-    skip_if(ref_frame == NULL);
-
-    skip_if((mainplist =
-	cpl_propertylist_load(cpl_frame_get_filename(ref_frame),
-			      0)) == NULL);
-
-    /**************************/
-    /*  Write the MASTERBIAS  */
-    /**************************/
-
-    /* Set the file name for the table */
-    if(!flag_sets) {
-       name_o = cpl_sprintf("%s_masterbias.fits", recipe_name);
-       assert(name_o != NULL);
-    } else {
-       name_o =
-          cpl_sprintf("%s_masterbias_set%02d.fits", recipe_name,
-                      which_set);
-       assert(name_o != NULL);
-    }
-    /* Save the MASTERBIAS image */
-    if (whichext == 0) {
-	cpl_propertylist_append(mypro_master, qclist);
-
-	skip_if(cpl_dfs_save_image(frameset, NULL, parlist, usedframes, NULL,
-	                           masterbias, CPL_BPP_IEEE_FLOAT, recipe_name,
-	                           mypro_master, NULL, package, name_o));
-    } else
-	skip_if(cpl_image_save(masterbias,
-			       name_o, CPL_BPP_IEEE_FLOAT, xplist,
-			       CPL_IO_EXTEND));
-
-    /* Free */
-    cpl_free(name_o);
-    name_o = NULL;
-
-    /*****************************/
-    /*  Write the HOT PIXEL MAP  */
-    /*****************************/
-
-    /* Set the file name for the table */
-    if(!flag_sets) {
-       name_o = cpl_sprintf("%s_hotpixmap.fits", recipe_name);
-       assert(name_o != NULL);
-    } else {
-       name_o =
-          cpl_sprintf("%s_hotpixmap_set%02d.fits", recipe_name,
-                      which_set);
-       assert(name_o != NULL);
-    }
-    /* Save the HOTBPM image */
-    skip_if(0);
-    image = cpl_image_new_from_mask(bpmhot);
-    cpl_error_reset();
-
-    if (whichext == 0) {
-	cpl_propertylist_append(mypro_bpmhot, qclist);
-
-	skip_if(cpl_dfs_save_image(frameset, NULL, parlist, usedframes, NULL,
-	                           image, CPL_BPP_IEEE_FLOAT, recipe_name,
-			           mypro_bpmhot, NULL, package, name_o));
-    } else
-	skip_if(cpl_image_save(image,
-			       name_o, CPL_BPP_IEEE_FLOAT, xplist,
-			       CPL_IO_EXTEND));
-
-    /* Free */
-    cpl_free(name_o);
-    cpl_image_delete(image);
-    image = NULL;
-    name_o = NULL;
-
-    /*****************************/
-    /*  Write the COLD PIXEL MAP  */
-    /*****************************/
-
-    /* Set the file name for the table */
-    if(!flag_sets) {
-       name_o = cpl_sprintf("%s_coldpixmap.fits", recipe_name);
-       assert(name_o != NULL);
-    } else {
-       name_o =
-          cpl_sprintf("%s_coldpixmap_set%02d.fits", recipe_name,
-                      which_set);
-       assert(name_o != NULL);
-    }
-    /* Save the COLDBPM image */
-    skip_if(0);
-    image = cpl_image_new_from_mask(bpmcold);
-    cpl_error_reset();
-
-    if (whichext == 0) {
-	cpl_propertylist_append(mypro_bpmcold, qclist);
-
-	skip_if(cpl_dfs_save_image(frameset, NULL, parlist, usedframes, NULL,
-	                           image, CPL_BPP_IEEE_FLOAT, recipe_name,
-	                           mypro_bpmcold, NULL, package, name_o));
-
-    } else
-	skip_if(cpl_image_save(image,
-			       name_o, CPL_BPP_IEEE_FLOAT, xplist,
-			       CPL_IO_EXTEND));
-
-    /* Free */
-    cpl_free(name_o);
-    cpl_image_delete(image);
-    image = NULL;
-    name_o = NULL;
-
-    /*****************************/
-    /*  Write the DEV PIXEL MAP  */
-    /*****************************/
-
-    /* Set the file name for the table */
-    if(!flag_sets) {
-       name_o = cpl_sprintf("%s_devpixmap.fits", recipe_name);
-       assert(name_o != NULL);
-    } else {
-       name_o =
-          cpl_sprintf("%s_devpixmap_set%02d.fits", recipe_name,
-                      which_set);
-       assert(name_o != NULL);
-    }
-    /* Save the DEVBPM image */
-    skip_if(0);
-    image = cpl_image_new_from_mask(bpmdev);
-    cpl_error_reset();
-
-    if (whichext == 0) {
-	cpl_propertylist_append(mypro_bpmdev, qclist);
-
-	skip_if(cpl_dfs_save_image(frameset, NULL,parlist, usedframes, NULL,
-	                           image, CPL_BPP_IEEE_FLOAT, recipe_name,
-                                   mypro_bpmdev, NULL, package, name_o));
-    } else
-	skip_if(cpl_image_save(image,
-			       name_o, CPL_BPP_IEEE_FLOAT, xplist,
-			       CPL_IO_EXTEND));
-
-    /* Free */
-    cpl_free(name_o);
-    cpl_image_delete(image);
-    image = NULL;
-    name_o = NULL;
-
-    /*******************************/
-    /*  Write the SYNTHETIC        */
-    /*******************************/
-    if(detmon_ronbias_config.method_bitmask & PREOVERSCAN) {
-	/* Set the file name for the table */
-	if(!flag_sets) {
-	    name_o = cpl_sprintf("%s_synthetic.fits", recipe_name);
-	    assert(name_o != NULL);
-	} else {
-	    name_o =
-                cpl_sprintf("%s_synthetic_set%02d.fits", recipe_name,
-                            which_set);
-	    assert(name_o != NULL);
-	}
-
-	if (whichext == 0) {
-          /* Save the SYNTHETIC image */
-	    cpl_propertylist_append(mypro_synth, qclist);
-
-	    skip_if(cpl_dfs_save_image(frameset, NULL, parlist, usedframes,
-                                       NULL,synthetic, CPL_BPP_IEEE_DOUBLE,
-                                       recipe_name, mypro_synth, NULL,
-                                       package, name_o));
-	} else
-	   skip_if(cpl_image_save(synthetic, name_o, CPL_BPP_IEEE_FLOAT,
-				  xplist, CPL_IO_EXTEND));
-
-       /* Free */
-       cpl_free(name_o);
-       name_o = NULL;
-    }
-
-    /*******************************/
-    /*  Write the PAF file         */
-    /*******************************/
-    if (qclist) {
-	paflist = cpl_propertylist_new();
-
-	/* Set the file name for the PAF */
-	if(detmon_ronbias_config.exts >= 0) {
-	    skip_if((plist =
-		     cpl_propertylist_load(cpl_frame_get_filename(ref_frame),
-					   detmon_ronbias_config.exts)) == NULL);
-
-	    if(!flag_sets) {
-		name_o = cpl_sprintf("%s.paf", recipe_name);
-		assert(name_o != NULL);
-	    } else {
-		name_o = cpl_sprintf("%s_set%02d.paf",
-				     recipe_name, which_set);
-		assert(name_o != NULL);
-	    }
-	} else {
-	    skip_if((plist =
-		     cpl_propertylist_load(cpl_frame_get_filename(ref_frame),
-					   whichext)) == NULL);
-
-
-	    if(!flag_sets) {
-		name_o = cpl_sprintf("%s_ext%02d.paf",
-				     recipe_name, whichext);
-		assert(name_o != NULL);
-	    } else {
-		name_o = cpl_sprintf("%s_set%02d_ext%02d.paf",
-				     recipe_name,
-				     which_set, whichext);
-		assert(name_o != NULL);
-	    }
-	}
-
-	/* Get the keywords for the paf file */
-	skip_if(cpl_propertylist_copy_property_regexp(paflist, plist,
-						      pafregexp, 0));
-	skip_if(cpl_propertylist_copy_property_regexp(paflist, mainplist,
-						      pafregexp, 0));
-
-	skip_if(cpl_propertylist_append(paflist, qclist));
-
-	/* Save the PAF */
-	skip_if(cpl_dfs_save_paf(pipeline_name, recipe_name, paflist, name_o));
-
-    }
-
-    end_skip;
-
-    cpl_propertylist_delete(plist);
-    cpl_propertylist_delete(paflist);
-    cpl_propertylist_delete(mainplist);
-    cpl_propertylist_delete(xplist);
-    cpl_free(name_o);
-    cpl_image_delete(image);
-
-    cpl_propertylist_delete(mypro_master);
-    cpl_propertylist_delete(mypro_synth);
-    cpl_propertylist_delete(mypro_bpmhot);
-    cpl_propertylist_delete(mypro_bpmcold);
-    cpl_propertylist_delete(mypro_bpmdev);
-
-    return cpl_error_get_code();
-}
-
-cpl_propertylist *
-xsh_detmon_fill_prolist(const char * procatg,
-			   const char * protype,
-			   const char * protech,
-			   cpl_boolean  proscience)
-{
-    cpl_propertylist * prolist = cpl_propertylist_new();
-
-    cpl_propertylist_append_string(prolist, CPL_DFS_PRO_CATG,    procatg);
-    cpl_propertylist_append_bool(prolist,   CPL_DFS_PRO_SCIENCE, proscience);
-    if (protype)
-	cpl_propertylist_append_string(prolist, CPL_DFS_PRO_TYPE,    protype);
-    if (protech)
-	cpl_propertylist_append_string(prolist, CPL_DFS_PRO_TECH,    protech);
-
-    return prolist;
-}
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-int
-xsh_detmon_ronbias_dfs_set_groups(cpl_frameset * set, const char *tag)
-{
-    cpl_frame              *cur_frame;
-    const char             *cur_tag;
-    int                     nframes;
-    int                     i;
-
-    /* Check entries */
-    if(set == NULL)
-        return -1;
-
-    /* Initialize */
-    nframes = cpl_frameset_get_size(set);
-
-    /* Loop on frames */
-    for(i = 0; i < nframes; i++) {
-        cur_frame = cpl_frameset_get_frame(set, i);
-        cur_tag = cpl_frame_get_tag(cur_frame);
-
-        /* RAW frames */
-        if(!strcmp(cur_tag, tag))
-            cpl_frame_set_group(cur_frame, CPL_FRAME_GROUP_RAW);
-        /* CALIB frames */
-
-/*        else if (!strcmp(tag, IIINSTRUMENT_CALIB_FLAT))
-            cpl_frame_set_group(cur_frame, CPL_FRAME_GROUP_CALIB) ;
-*/
-    }
-    return 0;
-}
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-cpl_image *
-xsh_detmon_build_synthetic(cpl_image * prescan, cpl_image * overscan)
-{
-    cpl_size                     j;
-
-    int                     distance = detmon_ronbias_config.overscan_urx -
-        detmon_ronbias_config.prescan_llx + 1;
-
-    double                 *mean_x =
-        (double *) cpl_malloc(sizeof(double) * distance);
-
-    double                 *xvalues =
-        (double *) cpl_malloc(sizeof(double) * distance);
-
-    cpl_vector             *x = NULL;
-    cpl_vector             *y = NULL;
-
-    cpl_polynomial         *poly = NULL;
-    cpl_polynomial         *poly2 = NULL;
-
-    cpl_matrix     * samppos;
-    cpl_vector     * fitresidual;
-
-    //double                  mse;
-    cpl_size                     pows[2] = { 0, 0 };
-
-    cpl_image              *synthetic = NULL;
-
-    double                  initial = 0;
-
-    /* Initialize */
-    for(j = 0; j < distance; j++) {
-        *(mean_x + j) = 0;
-        *(xvalues + j) = j;
-    }
-
-    for(j = 0; j < cpl_image_get_size_x(prescan); j++) {
-        *(mean_x + j) =
-            cpl_image_get_mean_window(prescan, j + 1, 1, j + 1,
-                                      cpl_image_get_size_y(prescan));
-    }
-
-    for(j = 0; j < cpl_image_get_size_x(overscan); j++) {
-        *(mean_x + distance - cpl_image_get_size_x(overscan) + j) =
-            cpl_image_get_mean_window(overscan, j + 1, 1, j + 1,
-                                      cpl_image_get_size_y(overscan));
-    }
-
-    x = cpl_vector_wrap(distance, xvalues);
-    y = cpl_vector_wrap(distance, mean_x);
-
-    poly = cpl_polynomial_new(1);
-    samppos =
-	cpl_matrix_wrap(1, cpl_vector_get_size(x), cpl_vector_get_data(x));
-    fitresidual = cpl_vector_new(cpl_vector_get_size(x));
-
-    cpl_polynomial_fit(poly, samppos, NULL, y, NULL,
-		       CPL_FALSE, NULL,
-		       (cpl_size*)&(detmon_ronbias_config.preoverscan_degree));
-
-    cpl_vector_fill_polynomial_fit_residual(fitresidual, y, NULL, poly,
-                                            samppos, NULL);
-    cpl_matrix_unwrap(samppos);
-    /*
-    mse = cpl_vector_product(fitresidual, fitresidual)
-         / cpl_vector_get_size(fitresidual);
-    */
-    cpl_vector_delete(fitresidual);
-
-    cpl_vector_unwrap(x);
-    cpl_vector_unwrap(y);
-
-    initial = *mean_x;
-
-    cpl_free(xvalues);
-    cpl_free(mean_x);
-
-    poly2 = cpl_polynomial_new(2);
-
-    j = 0;
-    cpl_polynomial_set_coeff(poly2, pows, cpl_polynomial_get_coeff(poly, &j));
-
-    pows[0] = 1;
-    j = 1;
-    cpl_polynomial_set_coeff(poly2, pows, cpl_polynomial_get_coeff(poly, &j));
-
-    cpl_polynomial_delete(poly);
-
-    synthetic =
-        cpl_image_new(distance, cpl_image_get_size_y(prescan),
-                      CPL_TYPE_DOUBLE);
-
-    if(cpl_image_fill_polynomial(synthetic, poly2, initial, 1, 1, 1)) {
-        cpl_msg_error(cpl_func, "Error creating the synthetic frame");
-        cpl_polynomial_delete(poly2);
-        return NULL;
-    }
-
-    cpl_polynomial_delete(poly2);
-
-    return synthetic;
-}
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-static cpl_error_code
-xsh_detmon_ronbias_dutycycl(const cpl_frameset * frameset,
-                               cpl_propertylist * qclist)
-{
-    const cpl_frame        *first = 0;
-    cpl_propertylist       *plistfirst = 0;
-    double                  tfirst;
-    int                     nraws;
-    const cpl_frame        *last = 0;
-    cpl_propertylist       *plistlast = 0;
-    double                  tlast;
-    double                  dutycycl;
-    cpl_error_code          error;
-
-    first = cpl_frameset_get_frame_const(frameset,0);
-    plistfirst = cpl_propertylist_load(cpl_frame_get_filename(first), 0);
-    tfirst = cpl_propertylist_get_double(plistfirst, "MJD-OBS");
-    nraws = cpl_frameset_get_size(frameset);
-    last = cpl_frameset_get_frame_const(frameset, nraws - 1);
-    plistlast = cpl_propertylist_load(cpl_frame_get_filename(last), 0);
-    tlast = cpl_propertylist_get_double(plistlast, "MJD-OBS");
-    dutycycl = (tlast - tfirst) / (nraws - 1);
-
-    error = cpl_error_get_code();
-    if (error != CPL_ERROR_NONE)
-    {
-    	goto cleanup;
-    }
-	cpl_propertylist_append_double(qclist,DETMON_QC_DUTYCYCL, dutycycl);
-    error = cpl_propertylist_set_comment(qclist,DETMON_QC_DUTYCYCL,
-					 DETMON_QC_DUTYCYCL_C);
-
-cleanup:
-
-    cpl_propertylist_delete(plistfirst);
-    cpl_propertylist_delete(plistlast);
-
-    return error;
-}
-
-
-/*--------------------------------------------------------------------------*/
-
-/*
- * @brief  Reduce periodic noise
- * @param  image         Input image
- * @param  freq          Readout frequency, given in Kpixel/s.
- *
- * @return 1-d image, representing the distribution of noise. NULL if failed.
- */
-
-/*--------------------------------------------------------------------------*/
-
-
-#define HORIZONTAL TRUE
-
-cpl_table              *
-xsh_detmon_pernoise_reduce(cpl_image * image)
-{
-    int                     nsamples, nffts;
-    int                     i, j;
-
-    int status;
-    float * hanning = 0;
-    //float * data = 0;
-    float * power = 0;
-    cpl_image * power_im = 0;
-    cpl_image * output = 0;
-    cpl_image * pos_spec = 0;
-    cpl_table * table = 0;
-    cpl_image* fourier_im = 0;
-    double freq;
-    cpl_error_code error = CPL_ERROR_NONE;
-    cpl_image * sub_image = 0;
-    int nffts_old;
-
-
-    if(detmon_pernoise_config.direction == HORIZONTAL) {
-        error = cpl_image_flip(image, 1);
-        cpl_ensure(!error, error, NULL);
-    }
-
-    nsamples = cpl_image_get_size_x(image);
-    nffts = cpl_image_get_size_y(image);
-
-
-    /* Rewrite the previous lines with a better style (: ...) */
-
-    /*
-     * 1. preprocessing task:
-     * Estimate the background fitting the image to a
-     * 2-D polynomial and substract it from the image.
-     */
-
-    error = xsh_detmon_pernoise_rm_bg(image, nsamples, nffts);
-    cpl_ensure(!error, error, NULL);
-
-    sub_image = cpl_image_extract(image, nsamples/8 + 1, nffts/8+1,
-                                              nsamples*7/8, nffts*7/8);
-    nffts_old = nffts;
-    nsamples = cpl_image_get_size_x(sub_image);
-    nffts = cpl_image_get_size_y(sub_image);
-
-    /*
-     * 2. preprocessing task:
-     * Remove the effect of hot and dark pixels, replacing their values by
-     * the average value of the neighbouring pixels.
-     */
-
-    /*
-     * 3. preprocessing task:
-     * Apply a Hanning vector
-     */
-
-    hanning = cpl_malloc(sizeof(float) * nsamples);
-
-    for(i = 0; i < nsamples; i++) {
-        *(hanning + i) = 0.5 - 0.5 * cos(2 * CPL_MATH_PI * (float) i / nsamples);
-        for(j = 0; j < nffts; j++) {
-            double                  value =
-                cpl_image_get(sub_image, i + 1, j + 1, &status);
-            error = cpl_image_set(sub_image, i + 1, j + 1, (*(hanning + i)) * value);
-        }
-    }
-
-    cpl_free(hanning);
-    if (error != CPL_ERROR_NONE)
-    {
-    	goto cleanup;
-    }
-    //data = cpl_image_get_data_float(sub_image);
-
-    power = (float *) cpl_calloc(sizeof(float), nsamples * nffts);
-
-
-    fourier_im = cpl_image_new(nsamples,nffts,  CPL_TYPE_FLOAT_COMPLEX);
-    error = cpl_fft_image(fourier_im, sub_image, CPL_FFT_FORWARD);
-/*
-      fourier =
-	(fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nsamples*nffts);
-
-      input =
-	(fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nsamples*nffts);
-
-      for(i = 0; i< nffts*nsamples; i++){
- 	*((float complex *)input + i) = data[i] + I * 0.0;
-      }
-
-      p = fftw_create_plan(nsamples, FFTW_FORWARD, FFTW_ESTIMATE);
-
-      fftw(p, nffts, input, 1, nsamples,
-	 fourier, 1, nsamples);
-
-      fftw_destroy_plan(p);
-*/
-    for(i = 1; i <= nffts; i++) {
-        for(j = 1; j <= nsamples; j++) {
-        	int rej = 0;
-        	double complex cvalue = cpl_image_get_complex(fourier_im,j, i, &rej );
-        	double value = cabs(cvalue);
-                /*
-             *(power + j + i * nsamples) = *((float complex *)fourier + j + i * nsamples) *
-		conjf(*((float complex *)fourier +j + i * nsamples));
-                */
-        	cpl_image_set(power_im, j, i, value);
-        }
-        /*  Is it necessary to divide here by 2 * pi? */
-    }
-    cpl_image_delete(fourier_im);
-
-/*
-    fftw_free(fourier);
-    fftw_free(input);
-    power_im = cpl_image_wrap_float(nsamples, nffts, power);
-*/
-    output   = cpl_image_collapse_create(power_im, 0);
-    pos_spec = cpl_image_extract(output, 1, 1, nsamples/2, 1);
-
-    /* cpl_image_unwrap(power_im); */
-    cpl_image_delete(power_im);
-    cpl_free(power);
-
-    cpl_image_delete(output);
-
-    table = cpl_table_new(nsamples/2);
-    cpl_table_new_column(table, "FREQ", CPL_TYPE_DOUBLE);
-    cpl_table_new_column(table, "POW", CPL_TYPE_DOUBLE);
-
-    freq = detmon_pernoise_config.speed*1000/nffts_old;
-
-    for(i = 0; i < nsamples/2; i++) {
-        error = cpl_table_set(table, "FREQ", i, freq/(nsamples/2)*i);
-        error = cpl_table_set(table, "POW", i, cpl_image_get(pos_spec, i+1, 1, &status));
-    }
-
-    for(i= 0; i < 5; i++) {
-        error = cpl_table_set(table, "POW", i, 0.0);
-    }
-
-
-cleanup:
-    cpl_image_delete(pos_spec);
-
-    cpl_image_delete(sub_image);
-    if (error != CPL_ERROR_NONE)
-    {
-    	cpl_table_delete(table);
-    	table = 0;
-    }
-    return table;
-}
-#undef HORIZONTAL
-
-
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-
-
-cpl_error_code
-xsh_detmon_rm_bpixs(cpl_image ** image,
-                       const double kappa, int nffts, int nsamples)
-{
-    int                     i, j;
-
-    float                  *data = cpl_image_get_data_float(*image);
-    int k = 0;
-    for(i = 0; i < nffts; i++) {
-        for(j = 0; j < nsamples; j++) {
-            float                   neighbours = 0;
-            int                     nneighs = 0;
-            float                   average = 0;
-
-            /*
-             * Look for the way to optimize this:
-             * Some of the points added to neighbours coincide
-             * in one iteration and the following
-             */
-            if(i > 0) {
-                neighbours += *(data + (i - 1) * nsamples + j);
-                nneighs++;
-            }
-            if(i < nffts - 1) {
-                neighbours += *(data + (i + 1) * nsamples + j);
-                nneighs++;
-            }
-            if(j > 0) {
-                neighbours += *(data + i * nsamples + (j - 1));
-                nneighs++;
-            }
-            if(j < nsamples - 1) {
-                neighbours += *(data + i * nsamples + (j + 1));
-                nneighs++;
-            }
-            average = neighbours / nneighs;
-            if(average > 0) {
-                if(*(data + i * nsamples + j) < average * (-1 * kappa) ||
-                   *(data + i * nsamples + j) > average * (kappa)) {
-                    k++;
-                    *(data + i * nsamples + j) = average;
-                }
-            }
-            if(average < 0) {
-                if(*(data + i * nsamples + j) > average * (-1 * kappa) ||
-                   *(data + i * nsamples + j) < average * (kappa)) {
-                    k++;
-                    *(data + i * nsamples + j) = average;
-                }
-            }
-
-        }
-    }
-
-
-    return cpl_error_get_code();
-
-}
-
-/* Start duplicated code */
-
-#define RECT_RON_HS         4
-#define RECT_RON_SAMPLES    100
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-cpl_error_code
-xsh_flux_get_bias_window(const cpl_image * diff,
-                            const int *zone_def,
-                            int ron_hsize,
-                            int ron_nsamp, double *bias, double *error)
-{
-    const int               hsize = ron_hsize < 0 ? RECT_RON_HS : ron_hsize;
-    const int               nsamples =
-        ron_nsamp < 0 ? RECT_RON_SAMPLES : ron_nsamp;
-    cpl_bivector           *sample_reg;
-    cpl_vector             *rms_list;
-    int                     rect[4];
-    int                     zone[4];
-    double                 *px;
-    double                 *py;
-    double                 *pr;
-    int                     i;
-
-    /* Test entries */
-    cpl_ensure_code(diff && bias, CPL_ERROR_NULL_INPUT);
-
-    /* Generate nsamples window centers in the image */
-    if(zone_def != NULL) {
-        rect[0] = zone_def[0] + hsize + 1;      /* xmin */
-        rect[1] = zone_def[1] - hsize - 1;      /* xmax */
-        rect[2] = zone_def[2] + hsize + 1;      /* ymin */
-        rect[3] = zone_def[3] - hsize - 1;      /* ymax */
-    } else {
-        rect[0] = hsize + 1;    /* xmin */
-        rect[1] = cpl_image_get_size_x(diff) - hsize - 1;       /* xmax */
-        rect[2] = hsize + 1;    /* ymin */
-        rect[3] = cpl_image_get_size_y(diff) - hsize - 1;       /* ymax */
-    }
-
-    cpl_ensure_code(rect[0] < rect[1] && rect[2] < rect[3],
-                    CPL_ERROR_ILLEGAL_INPUT);
-
-    /* Generate n+1 regions, because the first region is always at (0,0) */
-    /* and it would bias the measurement. */
-    sample_reg =
-        irplib_bivector_gen_rect_poisson(rect, nsamples + 1, nsamples + 1);
-    cpl_ensure(sample_reg != NULL, CPL_ERROR_ILLEGAL_INPUT,
-               CPL_ERROR_ILLEGAL_INPUT);
-
-    px = cpl_bivector_get_x_data(sample_reg);
-    py = cpl_bivector_get_y_data(sample_reg);
-
-    /* Now, for each window center, extract a vignette and compute the */
-    /* signal RMS in it. Store this rms into a table. */
-    rms_list = cpl_vector_new(nsamples);
-    cpl_ensure(rms_list != NULL, CPL_ERROR_NULL_INPUT, CPL_ERROR_NULL_INPUT);
-    pr = cpl_vector_get_data(rms_list);
-
-    for(i = 0; i < nsamples; i++) {
-        zone[0] = (int) px[i + 1] - hsize;
-        zone[1] = (int) px[i + 1] + hsize;
-        zone[2] = (int) py[i + 1] - hsize;
-        zone[3] = (int) py[i + 1] + hsize;
-        pr[i] = cpl_image_get_mean_window(diff,
-                                          zone[0], zone[2], zone[1], zone[3]);
-    }
-    cpl_bivector_delete(sample_reg);
-
-    /* The error is the rms of the rms */
-    if(error != NULL)
-        *error = cpl_vector_get_stdev(rms_list);
-
-    /* The final computed RMS is the median of all values.  */
-    /* This call will modify the rms_list */
-    *bias = cpl_vector_get_median(rms_list);
-
-    cpl_vector_delete(rms_list);
-
-    return CPL_ERROR_NONE;
-}
-
-#undef RECT_RON_HS
-#undef RECT_RON_SAMPLES
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-static cpl_bivector    *
-irplib_bivector_gen_rect_poisson(const int *r, const int np, const int homog)
-{
-    double                  min_dist;
-    int                     i;
-    int                     gnp;
-    cpl_bivector           *list;
-    double                  cand_x, cand_y;
-    int                     ok;
-    int                     start_ndx;
-    int                     xmin, xmax, ymin, ymax;
-
-    /* Corrected Homogeneity factor */
-    const int               homogc = 0 < homog && homog < np ? homog : np;
-    double                 *px;
-    double                 *py;
-
-    /* error handling: test arguments are correct */
-    cpl_ensure(r, CPL_ERROR_NULL_INPUT, NULL);
-    cpl_ensure(np > 0, CPL_ERROR_ILLEGAL_INPUT, NULL);
-
-    list = cpl_bivector_new(np);
-    cpl_ensure(list, CPL_ERROR_NULL_INPUT, NULL);
-    px = cpl_bivector_get_x_data(list);
-    py = cpl_bivector_get_y_data(list);
-
-    xmin = r[0];
-    xmax = r[1];
-    ymin = r[2];
-    ymax = r[3];
-
-    min_dist =
-        CPL_MATH_SQRT1_2 * ((xmax - xmin) * (ymax - ymin) / (double) (homogc + 1));
-    gnp = 1;
-    px[0] = 0;
-    py[0] = 0;
-
-    /* First: generate <homog> points */
-    while(gnp < homogc) {
-        /* Pick a random point within requested range */
-        cand_x = cpl_drand() * (xmax - xmin) + xmin;
-        cand_y = cpl_drand() * (ymax - ymin) + ymin;
-
-        /* Check the candidate obeys the minimal Poisson distance */
-        ok = 1;
-        for(i = 0; i < gnp; i++) {
-            if(pdist(cand_x, cand_y, px[i], py[i]) < min_dist) {
-                /* does not check Poisson law: reject point */
-                ok = 0;
-                break;
-            }
-        }
-        if(ok) {
-            /* obeys Poisson law: register the point as valid */
-            px[gnp] = cand_x;
-            py[gnp] = cand_y;
-            gnp++;
-        }
-    }
-
-    /* Iterative process: */
-    /* Pick points out of Poisson distance of the last <homogc-1> points. */
-    start_ndx = 0;
-    while(gnp < np) {
-        /* Pick a random point within requested range */
-        cand_x = cpl_drand() * (xmax - xmin) + xmin;
-        cand_y = cpl_drand() * (ymax - ymin) + ymin;
-
-        /* Check the candidate obeys the minimal Poisson distance */
-        ok = 1;
-        for(i = 0; i < homogc; i++) {
-            if(pdist(cand_x,
-                     cand_y,
-                     px[start_ndx + i], py[start_ndx + i]) < min_dist) {
-                /* does not check Poisson law: reject point */
-                ok = 0;
-                break;
-            }
-        }
-        if(ok) {
-            /* obeys Poisson law: register the point as valid */
-            px[gnp] = cand_x;
-            py[gnp] = cand_y;
-            gnp++;
-        }
-    }
-
-    /* Iterative process: */
-    /* Pick points out of Poisson distance of the last <homogc-1> points. */
-    start_ndx = 0;
-    while(gnp < np) {
-        /* Pick a random point within requested range */
-        cand_x = cpl_drand() * (xmax - xmin) + xmin;
-        cand_y = cpl_drand() * (ymax - ymin) + ymin;
-
-        /* Check the candidate obeys the minimal Poisson distance */
-        ok = 1;
-        for(i = 0; i < homogc; i++) {
-            if(pdist(cand_x,
-                     cand_y,
-                     px[start_ndx + i], py[start_ndx + i]) < min_dist) {
-                /* does not check Poisson law: reject point */
-                ok = 0;
-                break;
-            }
-        }
-        if(ok) {
-            /* obeys Poisson law: register the point as valid */
-            px[gnp] = cand_x;
-            py[gnp] = cand_y;
-            gnp++;
-            start_ndx++;
-        }
-    }
-    return list;
-}
-
-/* End of duplicated code */
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-cpl_error_code
-xsh_detmon_pernoise(cpl_frameset      * frameset,
-                       const cpl_parameterlist * parlist,
-                       const char        * tag,
-                       const char        * recipe_name,
-                       const char        * pipeline_name,
-                       const char        * procatg_tbl,
-                       const char        * package,
-                       int              (*compare)(const cpl_frame *,
-                                                   const cpl_frame *))
-{
-    cpl_size                     nsets;
-    cpl_size                    *selection = NULL;
-    int                     i;
-    cpl_error_code          error;
-
-    if(xsh_detmon_pernoise_dfs_set_groups(frameset, tag)) {
-        cpl_msg_error(cpl_func, "Cannot identify RAW and CALIB frames");
-    }
-
-    /*
-     * This function reads all inputs parameters from parlist
-     * and stores them in a global variable detmon_ronbias_config.
-     * Similar to xsh_detmon_lg_retrieve_parlist(). See xsh_detmon.c
-     */
-    error = xsh_detmon_pernoise_retrieve_parlist(pipeline_name,
-                                                   recipe_name, parlist);
-    cpl_ensure_code(!error, error);
-
-    /* Labelise all input frames */
-    if(compare == NULL)
-        nsets = 1;
-    else {
-        cpl_msg_info(cpl_func, "Identify the different settings");
-        selection = cpl_frameset_labelise(frameset, compare, &nsets);
-        if(selection == NULL)
-            cpl_msg_error(cpl_func, "Cannot labelise input frames");
-    }
-
-    detmon_pernoise_config.nb_extensions = 1;
-    if(detmon_pernoise_config.exts < 0) {
-        const cpl_frame        *cur_frame =
-            cpl_frameset_get_frame_const(frameset,0);
-        /* Get the nb of extensions */
-        detmon_pernoise_config.nb_extensions =
-            cpl_frame_get_nextensions(cur_frame);
-    }
-
-    /* Extract settings and reduce each of them */
-    for(i = 0; i < nsets; i++)
-    {
-        int j;
-        cpl_table ** freq_table;
-        cpl_propertylist ** qclist =
-            (cpl_propertylist **)
-            cpl_malloc(detmon_pernoise_config.nb_extensions *
-                       sizeof(cpl_propertylist *));
-
-        cpl_imagelist ** raws = (cpl_imagelist **) cpl_malloc(detmon_pernoise_config.nb_extensions * sizeof(cpl_imagelist *));
-        cpl_image ** input = (cpl_image **) cpl_malloc(detmon_pernoise_config.nb_extensions * sizeof(cpl_image *));
-
-        /* Initialise memory for products */
-        if(detmon_pernoise_config.mode == 1)
-        {
-            freq_table =
-                (cpl_table **) cpl_malloc(detmon_pernoise_config.nb_extensions *
-                                          4 * sizeof(cpl_table *));
-        } else
-        {
-            freq_table =
-                (cpl_table **) cpl_malloc(detmon_pernoise_config.nb_extensions *
-                                          sizeof(cpl_table *));
-        }
-
-        if(detmon_pernoise_config.exts >= 0)
-        {
-            *raws =
-                cpl_imagelist_load_frameset(frameset, CPL_TYPE_FLOAT, 1,
-                                            detmon_pernoise_config.exts);
-            *input = cpl_image_subtract_create(cpl_imagelist_get(*raws,0),
-                                               cpl_imagelist_get(*raws,1));
-        } else
-        {
-            cpl_imagelist          *raws_all_exts =
-                cpl_imagelist_load_frameset(frameset, CPL_TYPE_FLOAT, 1,
-                                            -1);
-            for(j = 0; j < detmon_pernoise_config.nb_extensions; j++)
-            {
-                int nframes = cpl_frameset_get_size(frameset);
-                int                     k;
-                for(k = 0; k < nframes; k++)
-                {
-                    cpl_image              *image =
-                        cpl_imagelist_unset(raws_all_exts,
-                                            (detmon_pernoise_config.
-                                             nb_extensions - 1 - j) * k);
-                    cpl_imagelist_set(raws[j], image, k);
-                }
-                input[j] =
-                    cpl_image_subtract_create(cpl_imagelist_get(raws[j],0),
-                                              cpl_imagelist_get(raws[j],1));
-            }
-        }
-
-        for(j = 0; j < detmon_pernoise_config.nb_extensions; j++) {
-            cpl_msg_info(cpl_func, "Starting reduction");
-            qclist[j] = cpl_propertylist_new();
-            if(detmon_pernoise_config.mode == 1)
-            {
-                int nx = cpl_image_get_size_x(input[j]);
-                int ny = cpl_image_get_size_y(input[j]);
-                int k = 0;
-                cpl_image* quad[4];
-
-                quad[0] = cpl_image_extract(input[j], 1, 1, nx/2, ny/2);
-                quad[1] = cpl_image_extract(input[j], 1, ny/2+1, nx/2, ny);
-                quad[2] = cpl_image_extract(input[j], nx/2+1, 1, nx, ny/2);
-                quad[3] = cpl_image_extract(input[j], nx/2+1, ny/2+1, nx, ny);
-
-                for (k = 0; k < 4; k++)
-                {
-                	freq_table[j * 4 + k] = xsh_detmon_pernoise_reduce(quad[k]);
-                }
-                for(k = 0; k < 4; k++)
-                {
-                	error = xsh_detmon_pernoise_qc(qclist[j], freq_table[j + k], k+1);
-                	if (error != CPL_ERROR_NONE)
-                		break;
-                }
-                for (k = 0; k < 4; k++)
-                {
-                	cpl_image_delete(quad[k]);
-                }
-            } else
-            {
-                freq_table[j] = xsh_detmon_pernoise_reduce(input[j]);
-                if(freq_table[j] != NULL)
-                {
-                	error = xsh_detmon_pernoise_qc(qclist[j], freq_table[j], 0);
-                }
-            }
-            if (error != CPL_ERROR_NONE)
-            {
-            	break;
-            }
-        }
-        if (error == CPL_ERROR_NONE)
-        {
-        	error = xsh_detmon_pernoise_save(parlist, frameset, recipe_name,
-                                            pipeline_name, procatg_tbl,
-                                            package, freq_table, qclist, 0,
-                                            0, frameset);
-        }
-
-        for(j = 0; j < detmon_pernoise_config.nb_extensions; j++)
-        {
-            cpl_propertylist_delete(qclist[j]);
-            cpl_imagelist_delete(raws[j]);
-            cpl_image_delete(input[j]);
-        }
-        cpl_free(qclist);
-        cpl_free(raws);
-        cpl_free(input);
-        if(detmon_pernoise_config.mode == 1)
-        {
-            for(j= 0; j < detmon_pernoise_config.nb_extensions * 4; j++) {
-                cpl_table_delete(freq_table[j]);
-            }
-        } else {
-            for(j= 0; j < detmon_pernoise_config.nb_extensions; j++) {
-                cpl_table_delete(freq_table[j]);
-            }
-        }
-        cpl_free(freq_table);
-        if (error != CPL_ERROR_NONE)
-        {
-        	break;
-        }
-    }
-
-    return cpl_error_get_code();
-}
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-int
-xsh_detmon_pernoise_dfs_set_groups(cpl_frameset * set, const char *tag)
-{
-    cpl_frame              *cur_frame;
-    const char             *cur_tag;
-    int                     nframes;
-    int                     i;
-
-    /* Check entries */
-    if(set == NULL)
-        return -1;
-
-    /* Initialize */
-    nframes = cpl_frameset_get_size(set);
-
-    /* Loop on frames */
-    for(i = 0; i < nframes; i++) {
-        cur_frame = cpl_frameset_get_frame(set, i);
-        cur_tag = cpl_frame_get_tag(cur_frame);
-
-        /* RAW frames */
-        if(!strcmp(cur_tag, tag))
-            cpl_frame_set_group(cur_frame, CPL_FRAME_GROUP_RAW);
-        /* CALIB frames */
-
-/*        else if (!strcmp(tag, IIINSTRUMENT_CALIB_FLAT))
-          cpl_frame_set_group(cur_frame, CPL_FRAME_GROUP_CALIB) ;
-*/
-    }
-    return 0;
-}
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-cpl_error_code
-xsh_detmon_fill_pernoise_params(cpl_parameterlist * parlist,
-                                   const char *recipe_name,
-                                   const char *pipeline_name,
-                                   int mode,
-                                   const char * direction,
-                                   double speed,
-                                   int llx,
-                                   int lly,
-                                   int urx,
-                                   int ury,
-                                   double kappa,
-                                   int exts)
-{
-    xsh_detmon_fill_parlist(parlist, recipe_name, pipeline_name, 9,
-
-                               "mode",
-                               "Mode",
-                               "CPL_TYPE_INT", mode,
-
-                               "direction",
-                               "Readout direction",
-                               "CPL_TYPE_BOOL", direction,
-
-                               "speed",
-                               "Readout speed",
-                               "CPL_TYPE_DOUBLE", speed,
-
-                               "llx",
-                               "(yet unsupported) x coordinate of the lower-left "
-                               "point of the region of interest. If not modified, default value will be 1.",
-                               "CPL_TYPE_INT", llx,
-                               "lly",
-                               "(yet unsupported) y coordinate of the lower-left "
-                               "point of the region of interest. If not modified, default value will be 1.",
-                               "CPL_TYPE_INT", lly,
-                               "urx",
-                               "(yet unsupported) x coordinate of the upper-right "
-                               "point of the region of interest. If not modified, default value will be X dimension of the input image.",
-                               "CPL_TYPE_INT", urx,
-                               "ury",
-                               "(yet unsupported) y coordinate of the upper-right "
-                               "point of the region of interest. If not modified, default value will be Y dimension of the input image.",
-                               "CPL_TYPE_INT", ury,
-
-                               "kappa",
-                               "Kappa used for determining threshold of bad (hot, cold) pixels",
-                               "CPL_TYPE_DOUBLE", kappa,
-
-                               "exts",
-                               "Activate the multi-exts option",
-                               "CPL_TYPE_INT", exts);
-
-    return 0;
-}
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-int
-xsh_detmon_fill_pernoise_params_default(cpl_parameterlist * parlist,
-                                           const char *recipe_name,
-                                           const char *pipeline_name)
-{
-    xsh_detmon_fill_pernoise_params(parlist, recipe_name, pipeline_name,
-                                       1,           /* --mode      */
-                                       "CPL_TRUE",  /* --direction */
-                                       84.5,        /* --speed     */
-                                       -1,          /* --llx       */
-                                       -1,          /* --lly       */
-                                       -1,          /* --urx       */
-                                       -1,          /* --ury       */
-                                       100,          /* --kappa     */
-                                       0);          /* --exts      */
-
-    return 0;
-
-}
-
-
-static cpl_error_code
-xsh_detmon_pernoise_retrieve_parlist(const char *pipeline_name,
-                                       const char *recipe_name,
-                                       const cpl_parameterlist * parlist)
-{
-    char                   *par_name;
-    cpl_parameter          *par;
-
-    /* --mode */
-    detmon_pernoise_config.mode =
-        xsh_detmon_retrieve_par_int("mode", pipeline_name, recipe_name,
-                                   parlist);
-
-    /* --direction */
-    par_name = cpl_sprintf("%s.%s.direction", pipeline_name, recipe_name);
-    assert(par_name != NULL);
-    par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_pernoise_config.direction = cpl_parameter_get_bool(par);
-    cpl_free(par_name);
-
-    /* --speed */
-    par_name = cpl_sprintf("%s.%s.speed", pipeline_name, recipe_name);
-    assert(par_name != NULL);
-    par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_pernoise_config.speed = cpl_parameter_get_double(par);
-    cpl_free(par_name);
-
-    /* --llx */
-    detmon_pernoise_config.llx =
-        xsh_detmon_retrieve_par_int("llx", pipeline_name, recipe_name,
-                                   parlist);
-
-    /* --lly */
-    detmon_pernoise_config.lly =
-        xsh_detmon_retrieve_par_int("lly", pipeline_name, recipe_name,
-                                   parlist);
-    /* --urx */
-    detmon_pernoise_config.urx =
-        xsh_detmon_retrieve_par_int("urx", pipeline_name, recipe_name,
-                                   parlist);
-    /* --ury */
-    detmon_pernoise_config.ury =
-        xsh_detmon_retrieve_par_int("ury", pipeline_name, recipe_name,
-                                   parlist);
-    /* --kappa */
-    detmon_pernoise_config.kappa =
-        xsh_detmon_retrieve_par_double("kappa", pipeline_name, recipe_name,
-                                   parlist);
-
-    /* --exts */
-    detmon_pernoise_config.exts =
-        xsh_detmon_retrieve_par_int("exts", pipeline_name, recipe_name,
-                                   parlist);
-
-    if(cpl_error_get_code()) {
-        cpl_msg_error(cpl_func, "Failed to retrieve the input parameters");
-        cpl_ensure_code(0, CPL_ERROR_DATA_NOT_FOUND);
-    }
-
-    return cpl_error_get_code();
-}
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-static                  cpl_error_code
-xsh_detmon_pernoise_save(const cpl_parameterlist * parlist,
-                            cpl_frameset * frameset,
-                            const char *recipe_name,
-                            const char *pipeline_name,
-                            const char *procatg_tbl,
-                            const char *package,
-                            cpl_table ** freq_table,
-                            cpl_propertylist ** qclist,
-                            const int flag_sets,
-                            const int which_set,
-                            const cpl_frameset * usedframes)
-{
-
-    cpl_frame              *ref_frame;
-    cpl_propertylist       *plist;
-    char                   *name_o = NULL; /* Avoid (false) uninit warning */
-    int                     i, j;
-    cpl_propertylist       *paflist;
-    cpl_error_code          error;
-
-    cpl_propertylist * pro_tbl = cpl_propertylist_new();
-
-    cpl_propertylist_append_string(pro_tbl,
-                                   CPL_DFS_PRO_CATG, procatg_tbl);
-
-    cpl_propertylist_append(pro_tbl, qclist[0]);
-
-    /*******************************/
-    /*  Write the FREQ TABLE  */
-
-    /*******************************/
-
-    if(detmon_pernoise_config.mode != 1) {
-        /* Set the file name for the table */
-        if(!flag_sets) {
-            name_o = cpl_sprintf("%s_freq_table.fits", recipe_name);
-            assert(name_o != NULL);
-        } else {
-            name_o =
-                cpl_sprintf("%s_freq_table_set%02d.fits", recipe_name,
-                               which_set);
-            assert(name_o != NULL);
-        }
-
-        /* Save the table */
-        if(cpl_dfs_save_table(frameset, NULL, parlist, usedframes, NULL, freq_table[0],
-                              NULL, recipe_name, pro_tbl, NULL,
-                              package, name_o)) {
-            cpl_msg_error(cpl_func, "Cannot save the product: %s", name_o);
-            cpl_free(name_o);
-            cpl_ensure_code(0, CPL_ERROR_FILE_NOT_CREATED);
-        }
-
-        if(detmon_pernoise_config.exts < 0) {
-
-            for(i = 1; i < detmon_pernoise_config.nb_extensions; i++) {
-                error =
-                    cpl_table_save(freq_table[i], NULL, qclist[i], name_o,
-                                   CPL_IO_EXTEND);
-                cpl_ensure_code(!error, error);
-            }
-        }
-
-        /* Free */
-        cpl_free(name_o);
-
-    } else {
-        for (j = 1; j <= 4; j++) {
-            /* Set the file name for the table */
-            if(!flag_sets) {
-                name_o = cpl_sprintf("%s_freq_table_quad%02d.fits",
-                                        recipe_name, j);
-                assert(name_o != NULL);
-            } else {
-                name_o =
-                    cpl_sprintf("%s_freq_table_quad%02d_set%02d.fits",
-                                   recipe_name, j, which_set);
-                assert(name_o != NULL);
-            }
-
-            /* Save the table */
-            if(cpl_dfs_save_table(frameset, NULL, parlist, usedframes, NULL,
-                                  freq_table[j - 1],
-                                  NULL, recipe_name, pro_tbl, NULL,
-                                  package, name_o)) {
-                cpl_msg_error(cpl_func, "Cannot save the product: %s", name_o);
-                cpl_free(name_o);
-                cpl_ensure_code(0, CPL_ERROR_FILE_NOT_CREATED);
-            }
-
-            if(detmon_pernoise_config.exts < 0) {
-                for(i = 1; i < detmon_pernoise_config.nb_extensions; i++) {
-                    error = cpl_table_save(freq_table[(j-1) + 4 * i],
-                                           NULL, qclist[i], name_o,
-                                           CPL_IO_EXTEND);
-                    cpl_ensure_code(!error, error);
-                }
-            }
-
-            /* Free */
-            cpl_free(name_o);
-        }
-
-    }
-    /*******************************/
-    /*  Write the PAF file(s)      */
-    /*******************************/
-
-    /* Get FITS header from reference file */
-    ref_frame = cpl_frameset_get_frame(frameset,0);
-    if((plist = cpl_propertylist_load(cpl_frame_get_filename(ref_frame),
-                                      0)) == NULL) {
-        cpl_msg_error(cpl_func, "getting header from reference frame");
-        cpl_ensure_code(0, cpl_error_get_code());
-    }
-
-    /* Get the keywords for the paf file */
-    paflist = cpl_propertylist_new();
-    cpl_propertylist_copy_property_regexp(paflist, plist,
-                                          "^(ARCFILE|MJD-OBS|ESO TPL ID|"
-                                          "DATE-OBS|ESO DET DIT|ESO DET NDIT|"
-                                          "ESO DET NCORRS|"
-                                          "ESO DET MODE NAME)$", 0);
-
-    for(i = 0; i < detmon_pernoise_config.nb_extensions; i++) {
-        cpl_propertylist * c_paflist = cpl_propertylist_duplicate(paflist);
-        error = cpl_propertylist_append(c_paflist, qclist[i]);
-        cpl_ensure_code(!error, error);
-
-        /* Set the file name for the bpm */
-        if(detmon_pernoise_config.exts >= 0) {
-            if(!flag_sets) {
-                name_o = cpl_sprintf("%s.paf", recipe_name);
-                assert(name_o != NULL);
-            } else {
-                name_o = cpl_sprintf("%s_set%02d.paf", recipe_name, which_set);
-                assert(name_o != NULL);
-            }
-        } else {
-            if(!flag_sets) {
-                name_o = cpl_sprintf("%s_ext%02d.paf", recipe_name, i+1);
-                assert(name_o != NULL);
-            } else {
-                name_o = cpl_sprintf("%s_set%02d_ext%02d.paf", recipe_name, which_set, i+1);
-                assert(name_o != NULL);
-            }
-        }
-        /* Save the PAF */
-        if(cpl_dfs_save_paf(pipeline_name, recipe_name, c_paflist, name_o)) {
-            cpl_msg_error(cpl_func, "Cannot save the product: %s", name_o);
-            cpl_free(name_o);
-            cpl_propertylist_delete(paflist);
-            cpl_propertylist_delete(plist);
-            cpl_free(name_o);
-            cpl_ensure_code(0, CPL_ERROR_FILE_NOT_CREATED);
-        }
-        cpl_propertylist_delete(c_paflist);
-        cpl_free(name_o);
-    }
-
-    cpl_propertylist_delete(plist);
-    cpl_propertylist_delete(paflist);
-    cpl_propertylist_delete(pro_tbl);
-
-    return cpl_error_get_code();
-}
-
-static cpl_error_code
-xsh_detmon_pernoise_qc(cpl_propertylist * qclist,
-                          cpl_table * table,
-                          int iquad)
-{
-    cpl_error_code error;
-    char * propname;
-
-    double freqs[3] = {0, 0, 0};
-    double pows[3] = {0, 0, 0};
-
-/*    error = cpl_propertylist_append_bool(reflist, "POW", TRUE);
-    cpl_ensure_code(!error, error);
-
-    error = cpl_table_sort(table, reflist);
-    cpl_ensure_code(!error, error);
-*/
-
-    int nrows = cpl_table_get_nrow(table);
-    int i;
-
-    double * all_freqs = cpl_table_get_data_double(table, "FREQ");
-    double * all_pows  = cpl_table_get_data_double(table, "POW");
-
-    for ( i= 1; i< nrows-1; i++){
-        if (all_pows[i] > pows[0]) {
-            if(all_pows[i-1] < all_pows[i] && all_pows[i] > all_pows[i+1]){
-                pows[2]=pows[1];
-                pows[1]=pows[0];
-                pows[0]=all_pows[i];
-
-                freqs[2]=freqs[1];
-                freqs[1]=freqs[0];
-                freqs[0]=all_freqs[i];
-            }
-        } else if (all_pows[i] > pows[1]) {
-            if(all_pows[i-1] < all_pows[i] && all_pows[i] > all_pows[i+1]){
-                pows[2]=pows[1];
-                pows[1]=all_pows[i];
-
-                freqs[2]=freqs[1];
-                freqs[1]=all_freqs[i];
-            }
-
-        } else if(all_pows[i] > pows[2]) {
-            if(all_pows[i-1] < all_pows[i] && all_pows[i] > all_pows[i+1]){
-                pows[2]=all_pows[i];
-
-                freqs[2]=all_freqs[i];
-            }
-
-        }
-    }
-
-    if (detmon_pernoise_config.mode == 1) {
-        propname = cpl_sprintf("ESO QC FREQ1 %d", iquad);
-        assert(propname != NULL);
-    } else {
-        propname = cpl_sprintf("ESO QC FREQ1");
-    }
-
-    error = cpl_propertylist_append_double(qclist, propname, freqs[0]);
-    error = cpl_propertylist_set_comment(qclist,propname,DETMON_QC_FREQ_C);
-    cpl_ensure_code(!error, error);
-
-    cpl_free(propname);
-
-    if (detmon_pernoise_config.mode == 1) {
-        propname = cpl_sprintf("ESO QC FREQ2 %d", iquad);
-        assert(propname != NULL);
-    } else {
-        propname = cpl_sprintf("ESO QC FREQ2");
-    }
-
-    error = cpl_propertylist_append_double(qclist, propname, freqs[1]);
-    error = cpl_propertylist_set_comment(qclist,propname,DETMON_QC_FREQ_C);
-    cpl_ensure_code(!error, error);
-
-    cpl_free(propname);
-
-    if (detmon_pernoise_config.mode == 1) {
-        propname = cpl_sprintf("ESO QC FREQ3 %d", iquad);
-        assert(propname != NULL);
-    } else {
-        propname = cpl_sprintf("ESO QC FREQ3");
-    }
-
-    error = cpl_propertylist_append_double(qclist, propname, freqs[2]);
-    error = cpl_propertylist_set_comment(qclist,propname,DETMON_QC_FREQ_C);
-    cpl_ensure_code(!error, error);
-
-    cpl_free(propname);
-
-    if (detmon_pernoise_config.mode == 1) {
-        propname = cpl_sprintf("ESO QC POW1 %d", iquad);
-        assert(propname != NULL);
-    } else {
-        propname = cpl_sprintf("ESO QC POW1");
-    }
-
-    error = cpl_propertylist_append_double(qclist, propname, pows[0]);
-    error = cpl_propertylist_set_comment(qclist,propname,DETMON_QC_POW_C);
-    cpl_ensure_code(!error, error);
-
-    cpl_free(propname);
-
-    if (detmon_pernoise_config.mode == 1) {
-        propname = cpl_sprintf("ESO QC POW2 %d", iquad);
-        assert(propname != NULL);
-    } else {
-        propname = cpl_sprintf("ESO QC POW2");
-    }
-
-    error = cpl_propertylist_append_double(qclist, propname, pows[1]);
-    error = cpl_propertylist_set_comment(qclist,propname,DETMON_QC_POW_C);
-    cpl_ensure_code(!error, error);
-
-    cpl_free(propname);
-
-    if (detmon_pernoise_config.mode == 1) {
-        propname = cpl_sprintf("ESO QC POW3 %d", iquad);
-        assert(propname != NULL);
-    } else {
-        propname = cpl_sprintf("ESO QC POW3");
-    }
-
-    error = cpl_propertylist_append_double(qclist, propname, pows[2]);
-    error = cpl_propertylist_set_comment(qclist,propname,DETMON_QC_POW_C);
-    cpl_ensure_code(!error, error);
-
-
-    cpl_free(propname);
-
-    return cpl_error_get_code();
-}
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-cpl_error_code
-xsh_detmon_pernoise_rm_bg(cpl_image * image, int nsamples, int nffts)
-{
-    cpl_vector             *values = cpl_vector_new(nsamples * nffts);
-
-    int                     rejected;
-    int i, j;
-    cpl_vector *xy_pos = cpl_vector_new(nsamples * nffts * 2);
-    //double mse = 0;
-    cpl_polynomial * poly_2d = 0;
-    cpl_image * poly_ima = 0;
-    cpl_size degree = 3;
-    cpl_error_code error = CPL_ERROR_NONE;
-    cpl_matrix * samppos = 0;
-    cpl_vector * fitresidual = 0;
-
-    for(i = 1; i <= nffts; i++) {
-        for(j = 1; j <= nsamples; j++) {
-            cpl_vector_set(xy_pos, (i - 1) * nsamples + (j - 1), j);
-            cpl_vector_set(xy_pos, (i - 1) * nsamples + (j - 1) + nsamples * nffts, i);
-            cpl_vector_set(values, (i - 1) * nsamples + (j - 1),
-                           cpl_image_get(image, j, i, &rejected));
-            error = cpl_error_get_code();
-            if (error != CPL_ERROR_NONE)
-            {
-            	break;
-            }
-        }
-        if (error != CPL_ERROR_NONE)
-        {
-        	break;
         }
-    }
-    if (error != CPL_ERROR_NONE)
-    {
-    	goto cleanup;
-    }
-    poly_2d = cpl_polynomial_new(2);
-    samppos =
-	cpl_matrix_wrap(2, nsamples * nffts, cpl_vector_get_data(xy_pos));
-    fitresidual = cpl_vector_new(nsamples * nffts);
-    cpl_polynomial_fit(poly_2d, samppos, NULL, values, NULL,
-		       CPL_FALSE, NULL, &degree);
-
-    cpl_vector_fill_polynomial_fit_residual(fitresidual, values, NULL, poly_2d,
-					    samppos, NULL);
-    cpl_matrix_unwrap(samppos);
-    /*
-    mse = cpl_vector_product(fitresidual, fitresidual)
-	/ cpl_vector_get_size(fitresidual);
-	*/
-
-    cpl_vector_delete(fitresidual);
-
-
-    poly_ima = cpl_image_new(nsamples, nffts, CPL_TYPE_FLOAT);
-
-    cpl_image_fill_polynomial(poly_ima, poly_2d, 1, 1, 1, 1);
-
-    cpl_image_subtract(image, poly_ima);
+    }
 
-cleanup:
-    cpl_polynomial_delete(poly_2d);
-    cpl_image_delete(poly_ima);
-    cpl_vector_delete(xy_pos);
-    cpl_vector_delete(values);
 
     return cpl_error_get_code();
+
 }
 
 /*---------------------------------------------------------------------------*/
 
 /*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
+ * @brief  Generates Poisson distributed values
+ * @param  r        Input values
+ * @param  np       number of points
+ * @param  homog    homogeneity factor
  * @return CPL_ERROR_NONE on success.
  */
 
 /*---------------------------------------------------------------------------*/
-cpl_error_code
-xsh_detmon_dark(cpl_frameset      * frameset,
-                   const cpl_parameterlist * parlist,
-                   const char        * tag,
-                   const char        * recipe_name,
-                   const char        * pipeline_name,
-                   const char        * procatg_master,
-                   const char        * procatg_dsnu,
-                   const char        * procatg_tbl,
-                   const char        * package,
-                   int              (*compare)(const cpl_frame *,
-                                               const cpl_frame *))
+static cpl_bivector    *
+irplib_bivector_gen_rect_poisson(const int *r, const int np, const int homog)
 {
-    cpl_size                     nsets;
-    cpl_size                    *selection = NULL;
+    double                  min_dist;
     int                     i;
-    cpl_error_code          error;
+    int                     gnp;
+    cpl_bivector           *list;
+    double                  cand_x, cand_y;
+    int                     ok;
+    int                     start_ndx;
+    int                     xmin, xmax, ymin, ymax;
 
-    if(xsh_detmon_dark_dfs_set_groups(frameset, tag)) {
-        cpl_msg_error(cpl_func, "Cannot identify RAW and CALIB frames");
-    }
+    /* Corrected Homogeneity factor */
+    const int               homogc = 0 < homog && homog < np ? homog : np;
+    double                 *px;
+    double                 *py;
 
-    /*
-     * This function reads all inputs parameters from parlist
-     * and stores them in a global variable detmon_ronbias_config.
-     * Similar to xsh_detmon_lg_retrieve_parlist(). See xsh_detmon.c
-     */
-    error = xsh_detmon_retrieve_dark_params(pipeline_name,
-                                               recipe_name, parlist);
-    cpl_ensure_code(!error, error);
-
-    /* Labelise all input frames */
-    if(compare == NULL)
-        nsets = 1;
-    else {
-        cpl_msg_info(cpl_func, "Identify the different settings");
-        selection = cpl_frameset_labelise(frameset, compare, &nsets);
-        if(selection == NULL)
-            cpl_msg_error(cpl_func, "Cannot labelise input frames");
-    }
+    /* error handling: test arguments are correct */
+    cpl_ensure(r, CPL_ERROR_NULL_INPUT, NULL);
+    cpl_ensure(np > 0, CPL_ERROR_ILLEGAL_INPUT, NULL);
 
-    detmon_dark_config.nb_extensions = 1;
-    if(detmon_dark_config.exts < 0) {
-        const cpl_frame        *cur_frame =
-            cpl_frameset_get_frame_const(frameset,0);
-        /* Get the nb of extensions */
-        detmon_dark_config.nb_extensions =
-            cpl_frame_get_nextensions(cur_frame);
-    }
+    list = cpl_bivector_new(np);
+    cpl_ensure(list, CPL_ERROR_NULL_INPUT, NULL);
+    px = cpl_bivector_get_x_data(list);
+    py = cpl_bivector_get_y_data(list);
 
-    /* Extract settings and reduce each of them */
-    for(i = 0; i < nsets; i++) {
-        cpl_size                    *select_dits = NULL;
-        cpl_frameset           *cur_fset =
-            nsets == 1 ? cpl_frameset_duplicate(frameset) :
-            cpl_frameset_extract(frameset, selection, i);
-
-        cpl_size                     ndits = 0;
-        int                     j, k;
-        cpl_table ** dsnu_table = NULL;
-        cpl_imagelist ** dsnu = NULL;
-
-        cpl_propertylist ** qclist =
-            (cpl_propertylist **)
-            cpl_malloc(detmon_dark_config.nb_extensions *
-                       sizeof(cpl_propertylist *));
-
-
-        cpl_imagelist ** masters =
-            (cpl_imagelist **)
-            cpl_malloc(detmon_dark_config.nb_extensions *
-                       sizeof(cpl_imagelist *));
-
-        /* Initialise memory for products */
-        if(detmon_dark_config.opt_nir == OPT) {
-            dsnu_table =
-                (cpl_table **) cpl_malloc(detmon_dark_config.nb_extensions *
-                                          sizeof(cpl_table *));
-            dsnu =
-                (cpl_imagelist **)
-                cpl_malloc(detmon_dark_config.nb_extensions *
-                                          sizeof(cpl_imagelist *));
-        }
+    xmin = r[0];
+    xmax = r[1];
+    ymin = r[2];
+    ymax = r[3];
 
-        select_dits = cpl_frameset_labelise(cur_fset,
-                                            xsh_detmon_compare_dits,
-                                            &ndits);
+    min_dist =
+        CPL_MATH_SQRT1_2 * ((xmax - xmin) * (ymax - ymin) / (double) (homogc + 1));
+    gnp = 1;
+    px[0] = 0;
+    py[0] = 0;
 
-        if(detmon_dark_config.exts >= 0) {
-            *masters = cpl_imagelist_new();
-            if(detmon_dark_config.opt_nir == OPT) {
-                *dsnu = cpl_imagelist_new();
-                *dsnu_table = cpl_table_new(ndits);
-            }
-            *qclist = cpl_propertylist_new();
-            cpl_table_new_column(*dsnu_table, "DIT", CPL_TYPE_DOUBLE);
-            cpl_table_new_column(*dsnu_table, "STDEV", CPL_TYPE_DOUBLE);
-        } else {
-            for ( j = 0; j < detmon_dark_config.nb_extensions; j ++) {
-                masters[j] = cpl_imagelist_new();
-                if(detmon_dark_config.opt_nir == OPT) {
-                    dsnu[j] = cpl_imagelist_new();
-                    dsnu_table[j] = cpl_table_new(ndits);
-                }
-                qclist[j] = cpl_propertylist_new();
-                cpl_table_new_column(dsnu_table[j], "DIT", CPL_TYPE_DOUBLE);
-                cpl_table_new_column(dsnu_table[j], "STDEV", CPL_TYPE_DOUBLE);
+    /* First: generate <homog> points */
+    while(gnp < homogc) {
+        /* Pick a random point within requested range */
+        cand_x = cpl_drand() * (xmax - xmin) + xmin;
+        cand_y = cpl_drand() * (ymax - ymin) + ymin;
+
+        /* Check the candidate obeys the minimal Poisson distance */
+        ok = 1;
+        for(i = 0; i < gnp; i++) {
+            if(pdist(cand_x, cand_y, px[i], py[i]) < min_dist) {
+                /* does not check Poisson law: reject point */
+                ok = 0;
+                break;
             }
         }
+        if(ok) {
+            /* obeys Poisson law: register the point as valid */
+            px[gnp] = cand_x;
+            py[gnp] = cand_y;
+            gnp++;
+        }
+    }
 
-        for(j = 0; j < ndits; j++) {
-            cpl_frameset  * cur_fdit = cpl_frameset_extract(cur_fset,
-                                                            select_dits, j);
-            cpl_imagelist ** raws =
-                (cpl_imagelist **)
-                cpl_malloc(detmon_dark_config.nb_extensions *
-                           sizeof(cpl_imagelist *));
-
-            if(detmon_dark_config.exts >= 0) {
-                cpl_image * collapsed;
-                *raws =
-                    cpl_imagelist_load_frameset(cur_fdit, CPL_TYPE_FLOAT, 1,
-                                                detmon_dark_config.exts);
-                collapsed = cpl_imagelist_collapse_create(*raws);
-                cpl_imagelist_set(*masters, collapsed, j);
-                if(detmon_dark_config.opt_nir == OPT) {
-                    xsh_detmon_dark_dsnu(cur_fdit, *dsnu, *dsnu_table,
-                                            collapsed, j);
-                }
-                xsh_detmon_dark_qc(*qclist, collapsed);
-            } else {
-                cpl_imagelist          *raws_all_exts =
-                    cpl_imagelist_load_frameset(cur_fdit, CPL_TYPE_FLOAT, 1,
-                                                -1);
-                for(k = 0; k < detmon_dark_config.nb_extensions; k++) {
-                    int nframes = cpl_frameset_get_size(cur_fdit);
-                    int h;
-                    cpl_image * collapsed;
-                    for(h = 0; h < nframes; h++) {
-                        cpl_image              *image =
-                            cpl_imagelist_unset(raws_all_exts,
-                                                (detmon_dark_config.
-                                                 nb_extensions - 1 - k) * h);
-                        cpl_imagelist_set(raws[k], image, h);
-                    }
-                    collapsed = cpl_imagelist_collapse_create(raws[k]);
-                    cpl_imagelist_set(masters[k],collapsed, j);
-                    if(detmon_dark_config.opt_nir == OPT) {
-                        xsh_detmon_dark_dsnu(cur_fdit, dsnu[k],
-                                                dsnu_table[j], collapsed, j);
-                    }
-                    xsh_detmon_dark_qc(qclist[k], collapsed);
-                }
-            }
+    /* Iterative process: */
+    /* Pick points out of Poisson distance of the last <homogc-1> points. */
+    start_ndx = 0;
+    while(gnp < np) {
+        /* Pick a random point within requested range */
+        cand_x = cpl_drand() * (xmax - xmin) + xmin;
+        cand_y = cpl_drand() * (ymax - ymin) + ymin;
 
-            cpl_frameset_delete(cur_fdit);
-            for(k = 0; k < detmon_dark_config.nb_extensions; k++) {
-                cpl_imagelist_delete(raws[k]);
+        /* Check the candidate obeys the minimal Poisson distance */
+        ok = 1;
+        for(i = 0; i < homogc; i++) {
+            if(pdist(cand_x,
+                     cand_y,
+                     px[start_ndx + i], py[start_ndx + i]) < min_dist) {
+                /* does not check Poisson law: reject point */
+                ok = 0;
+                break;
             }
-            cpl_free(raws);
-        } /* end of loop (for) around different DIT values */
-
-        cpl_frameset_delete(cur_fset);
+        }
+        if(ok) {
+            /* obeys Poisson law: register the point as valid */
+            px[gnp] = cand_x;
+            py[gnp] = cand_y;
+            gnp++;
+        }
+    }
 
-        xsh_detmon_dark_save(parlist, frameset, recipe_name, pipeline_name,
-                                procatg_master, procatg_tbl, procatg_dsnu,
-                                package, masters, dsnu_table, dsnu, qclist,
-                                0, 0, frameset);
+    /* Iterative process: */
+    /* Pick points out of Poisson distance of the last <homogc-1> points. */
+    start_ndx = 0;
+    while(gnp < np) {
+        /* Pick a random point within requested range */
+        cand_x = cpl_drand() * (xmax - xmin) + xmin;
+        cand_y = cpl_drand() * (ymax - ymin) + ymin;
 
-        if(detmon_dark_config.opt_nir == OPT) {
-            for(j = 0; j < detmon_dark_config.nb_extensions; j++) {
-                cpl_table_delete(dsnu_table[j]);
-                cpl_imagelist_delete(dsnu[j]);
+        /* Check the candidate obeys the minimal Poisson distance */
+        ok = 1;
+        for(i = 0; i < homogc; i++) {
+            if(pdist(cand_x,
+                     cand_y,
+                     px[start_ndx + i], py[start_ndx + i]) < min_dist) {
+                /* does not check Poisson law: reject point */
+                ok = 0;
+                break;
             }
-            cpl_free(dsnu_table);
-            cpl_free(dsnu);
         }
-
-        for(j = 0; j < detmon_dark_config.nb_extensions; j++) {
-            cpl_propertylist_delete(qclist[j]);
-            cpl_imagelist_delete(masters[j]);
+        if(ok) {
+            /* obeys Poisson law: register the point as valid */
+            px[gnp] = cand_x;
+            py[gnp] = cand_y;
+            gnp++;
+            start_ndx++;
         }
-        cpl_free(qclist);
-        cpl_free(masters);
-        cpl_free(select_dits);
-
-    } /* end of loop (for) around different setting */
-
-    cpl_free(selection);
-
-    return cpl_error_get_code();
-}
-
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-int
-xsh_detmon_dark_dfs_set_groups(cpl_frameset * set, const char *tag)
-{
-    cpl_frame              *cur_frame;
-    const char             *cur_tag;
-    int                     nframes;
-    int                     i;
-
-    /* Check entries */
-    if(set == NULL)
-        return -1;
-
-    /* Initialize */
-    nframes = cpl_frameset_get_size(set);
-
-    /* Loop on frames */
-    for(i = 0; i < nframes; i++) {
-        cur_frame = cpl_frameset_get_frame(set, i);
-        cur_tag = cpl_frame_get_tag(cur_frame);
-
-        /* RAW frames */
-        if(!strcmp(cur_tag, tag))
-            cpl_frame_set_group(cur_frame, CPL_FRAME_GROUP_RAW);
-        /* CALIB frames */
-
-/*        else if (!strcmp(tag, IIINSTRUMENT_CALIB_FLAT))
-          cpl_frame_set_group(cur_frame, CPL_FRAME_GROUP_CALIB) ;
-*/
     }
-    return 0;
+    return list;
 }
 
+
 /*---------------------------------------------------------------------------*/
 
 /*
  * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
+ * @param  pipeline_name        Input pipeline name
+ * @param  recipe_name          Input recipe name
+ * @param  parlist              Input parameter list
  * @return CPL_ERROR_NONE on success.
  */
 
 /*---------------------------------------------------------------------------*/
 static                  cpl_error_code
 xsh_detmon_retrieve_dark_params(const char *pipeline_name,
-                                      const char *recipe_name,
-                                      const cpl_parameterlist * parlist)
+                            const char *recipe_name,
+                            const cpl_parameterlist * parlist)
 {
     char                   *par_name;
     cpl_parameter          *par;
@@ -4506,27 +566,27 @@ xsh_detmon_retrieve_dark_params(const char *pipeline_name,
     par_name = cpl_sprintf("%s.%s.ron.method", pipeline_name, recipe_name);
     assert(par_name != NULL);
     par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_dark_config.ron_method = cpl_parameter_get_string(par);
+    xsh_detmon_dark_config.ron_method = cpl_parameter_get_string(par);
     cpl_free(par_name);
 
     /* --dsnu.method */
     par_name = cpl_sprintf("%s.%s.dsnu.method", pipeline_name, recipe_name);
     assert(par_name != NULL);
     par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_dark_config.dsnu_method = cpl_parameter_get_string(par);
+    xsh_detmon_dark_config.dsnu_method = cpl_parameter_get_string(par);
     cpl_free(par_name);
 
     /* --opt_nir */
     par_name = cpl_sprintf("%s.%s.opt_nir", pipeline_name, recipe_name);
     assert(par_name != NULL);
     par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_dark_config.opt_nir = cpl_parameter_get_bool(par);
+    xsh_detmon_dark_config.opt_nir = cpl_parameter_get_bool(par);
     cpl_free(par_name);
 
     /* --exts */
-    detmon_dark_config.exts =
+    xsh_detmon_dark_config.exts =
         xsh_detmon_retrieve_par_int("exts", pipeline_name, recipe_name,
-                                   parlist);
+                                parlist);
 
     if(cpl_error_get_code()) {
         cpl_msg_error(cpl_func, "Failed to retrieve the input parameters");
@@ -4541,139 +601,42 @@ xsh_detmon_retrieve_dark_params(const char *pipeline_name,
 /*---------------------------------------------------------------------------*/
 
 /*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-cpl_error_code
-xsh_detmon_fill_dark_params(cpl_parameterlist * parlist,
-                               const char *recipe_name,
-                               const char *pipeline_name,
-                               const char * ron_method,
-                               const char * dsnu_method,
-                               const char * opt_nir,
-                               int exts)
-{
-    xsh_detmon_fill_parlist(parlist, recipe_name, pipeline_name, 4,
-
-                               "ron.method",
-                               "Method used to compute RON. Currently no "
-			       "change is possible, RMS computed",
-                               "CPL_TYPE_STRING", ron_method,
-
-                               "dsnu.method",
-                               "Method used to compute DSNU map. Currently no "
-			       "change is possible. Method used STDEV",
-                               "CPL_TYPE_STRING", dsnu_method,
-
-                               "opt_nir",
-                               "Boolean, OPT (FALSE) or NIR(TRUE)",
-                               "CPL_TYPE_BOOL", opt_nir,
-
-                               "exts",
-                               "Activate the multi-exts option. Default 0"
-			       "(primary unit), -1 (all exts)",
-                               "CPL_TYPE_INT", exts);
-
-    return cpl_error_get_code();
-}
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-int
-xsh_detmon_fill_dark_params_default(cpl_parameterlist * parlist,
-                                       const char *recipe_name,
-                                       const char *pipeline_name)
-{
-    xsh_detmon_fill_dark_params(parlist, recipe_name, pipeline_name,
-                                   "SIMPLE", /* --ron.method  */
-                                   "STDEV",  /* --dsnu.method */
-                                   "CPL_FALSE",  /* OPT*/
-                                   0);       /* --exts        */
-    return cpl_error_get_code();
-}
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
- * @return CPL_ERROR_NONE on success.
- */
-
-/*---------------------------------------------------------------------------*/
-cpl_error_code
-xsh_detmon_dark_dsnu(cpl_frameset * cur_fdit,
-                        cpl_imagelist * dsnu,
-                        cpl_table * dsnu_table,
-                        cpl_image * collapsed,
-                        int pos)
-{
-    cpl_frame * first = cpl_frameset_get_frame(cur_fdit,0);
-    cpl_propertylist * plist =
-        cpl_propertylist_load(cpl_frame_get_filename(first), 0);
-    double dit = irplib_pfits_get_exptime(plist);
-    double mean = cpl_image_get_mean(collapsed);
-
-    cpl_image * dsnu_map =
-        cpl_image_subtract_scalar_create(collapsed, mean);
-    double stdev;
-    cpl_image_divide_scalar(dsnu_map, mean);
-    stdev = cpl_image_get_stdev(dsnu_map);
-
-    cpl_imagelist_set(dsnu, dsnu_map, pos);
-
-    cpl_table_set(dsnu_table, "DIT", pos, dit);
-    cpl_table_set(dsnu_table, "STDEV", pos, stdev);
-
-    cpl_propertylist_delete(plist);
-
-    return cpl_error_get_code();
-
-}
-
-/*---------------------------------------------------------------------------*/
-
-/*
- * @brief  Retrieve input parameters
- * @param  pipeline_name        Input image
- * @param  recipe_name          Input image
- * @param  parlist              Shift to apply on the x-axis
+ * @brief  Save dark recipe products
+ * @param  parlist        input parameter list
+ * @param  frameset       input frameset
+ * @param  recipe_name    input recipe name
+ * @param  pipeline_name  input pipeline name
+ * @param  procatg_master input procatg of master product
+ * @param  procatg_tbl    input procatg table
+ * @param  procatg_dsnu   input procatg dsnu product
+ * @param  package        input package name
+ * @param  masters        list of masters products
+ * @param  dsnu_table     dsnu table product
+ * @param  dsnu           list of dsnu images products
+ * @param  qclist         qc parameters
+ * @param  flag_sets      switch
+ * @param  which_set      specifier
+ * @param  usedframes     used frames
  * @return CPL_ERROR_NONE on success.
  */
 
 /*---------------------------------------------------------------------------*/
 static                  cpl_error_code
 xsh_detmon_dark_save(const cpl_parameterlist * parlist,
-                        cpl_frameset * frameset,
-                        const char *recipe_name,
-                        const char *pipeline_name,
-                        const char *procatg_master,
-                        const char *procatg_tbl,
-                        const char *procatg_dsnu,
-                        const char *package,
-                        cpl_imagelist ** masters,
-                        cpl_table ** dsnu_table,
-                        cpl_imagelist ** dsnu,
-                        cpl_propertylist ** qclist,
-                        const int flag_sets,
-                        const int which_set,
-                        const cpl_frameset * usedframes)
+                 cpl_frameset * frameset,
+                 const char *recipe_name,
+                 const char *pipeline_name,
+                 const char *procatg_master,
+                 const char *procatg_tbl,
+                 const char *procatg_dsnu,
+                 const char *package,
+                 cpl_imagelist ** masters,
+                 cpl_table ** dsnu_table,
+                 cpl_imagelist ** dsnu,
+                 cpl_propertylist ** qclist,
+                 const int flag_sets,
+                 const int which_set,
+                 const cpl_frameset * usedframes)
 {
 
     cpl_frame              *ref_frame;
@@ -4701,14 +664,13 @@ xsh_detmon_dark_save(const cpl_parameterlist * parlist,
         } else {
             name_o =
                 cpl_sprintf("%s_master_dit_%d_set%02d.fits",
-                               recipe_name, i, which_set);
+                            recipe_name, i, which_set);
             assert(name_o != NULL);
         }
 
 
         /* Save the image */
-        if(detmon_dark_config.exts >= 0) {
-
+        if(xsh_detmon_dark_config.exts >= 0) {
             cpl_propertylist * pro_master = cpl_propertylist_new();
 
             cpl_propertylist_append_string(pro_master,
@@ -4728,8 +690,7 @@ xsh_detmon_dark_save(const cpl_parameterlist * parlist,
 
             }
 
-	    cpl_propertylist_delete(pro_master);
-
+            cpl_propertylist_delete(pro_master);
         } else {
             cpl_propertylist * pro_master = cpl_propertylist_new();
 
@@ -4739,7 +700,7 @@ xsh_detmon_dark_save(const cpl_parameterlist * parlist,
             cpl_propertylist_append(pro_master, qclist[0]);
 
             if(cpl_dfs_save_image(frameset, NULL, parlist, usedframes, NULL,
-	                          NULL, CPL_BPP_IEEE_FLOAT, recipe_name,
+                                  NULL, CPL_BPP_IEEE_FLOAT, recipe_name,
                                   pro_master, NULL,
                                   package, name_o)) {
                 cpl_msg_error(cpl_func, "Cannot save the product: %s",
@@ -4748,8 +709,8 @@ xsh_detmon_dark_save(const cpl_parameterlist * parlist,
                 cpl_ensure_code(0, CPL_ERROR_FILE_NOT_CREATED);
             }
 
-	    cpl_propertylist_delete(pro_master);
-            for(j = 0; j < detmon_dark_config.nb_extensions; j++) {
+            cpl_propertylist_delete(pro_master);
+            for(j = 0; j < xsh_detmon_dark_config.nb_extensions; j++) {
                 error =
                     cpl_image_save(cpl_imagelist_get(masters[j], i),
                                    name_o, CPL_BPP_IEEE_FLOAT, qclist[j],
@@ -4757,14 +718,14 @@ xsh_detmon_dark_save(const cpl_parameterlist * parlist,
                 cpl_ensure_code(!error, error);
             }
         }
-	cpl_free(name_o);
+        cpl_free(name_o);
     }
 
-    if (detmon_dark_config.opt_nir == OPT) {
+    if (xsh_detmon_dark_config.opt_nir == OPT) {
         cpl_propertylist * pro_tbl = cpl_propertylist_new();
 
         cpl_propertylist_append_string(pro_tbl,
-                                     CPL_DFS_PRO_CATG, procatg_tbl);
+                                       CPL_DFS_PRO_CATG, procatg_tbl);
 
         cpl_propertylist_append(pro_tbl, qclist[0]);
         /*******************************/
@@ -4778,10 +739,9 @@ xsh_detmon_dark_save(const cpl_parameterlist * parlist,
         } else {
             name_o =
                 cpl_sprintf("%s_dsnu_table_set%02d.fits", recipe_name,
-                               which_set);
+                            which_set);
             assert(name_o != NULL);
         }
-
         /* Save the table */
         if(cpl_dfs_save_table(frameset, NULL, parlist, usedframes, NULL,
                               dsnu_table[0], NULL, recipe_name, pro_tbl, NULL,
@@ -4791,12 +751,11 @@ xsh_detmon_dark_save(const cpl_parameterlist * parlist,
             cpl_ensure_code(0, CPL_ERROR_FILE_NOT_CREATED);
         }
 
-
         cpl_propertylist_delete(pro_tbl);
 
-        if(detmon_dark_config.exts < 0) {
+        if(xsh_detmon_dark_config.exts < 0) {
 
-            for(i = 1; i < detmon_dark_config.nb_extensions; i++) {
+            for(i = 1; i < xsh_detmon_dark_config.nb_extensions; i++) {
                 error =
                     cpl_table_save(dsnu_table[i], NULL, qclist[i], name_o,
                                    CPL_IO_EXTEND);
@@ -4820,20 +779,19 @@ xsh_detmon_dark_save(const cpl_parameterlist * parlist,
             } else {
                 name_o =
                     cpl_sprintf("%s_dsnu_map_dit_%d_set%02d.fits",
-                                   recipe_name, i, which_set);
+                                recipe_name, i, which_set);
                 assert(name_o != NULL);
             }
 
 
             /* Save the image */
-            if(detmon_dark_config.exts >= 0) {
-
-	    	cpl_propertylist * pro_dsnu = cpl_propertylist_new();
+            if(xsh_detmon_dark_config.exts >= 0) {
+                cpl_propertylist * pro_dsnu = cpl_propertylist_new();
 
-		cpl_propertylist_append_string(pro_dsnu,
-	                                       CPL_DFS_PRO_CATG, procatg_dsnu);
+                cpl_propertylist_append_string(pro_dsnu,
+                                               CPL_DFS_PRO_CATG, procatg_dsnu);
 
-	        cpl_propertylist_append(pro_dsnu, qclist[0]);
+                cpl_propertylist_append(pro_dsnu, qclist[0]);
 
                 if(cpl_dfs_save_image
                    (frameset, NULL, parlist, usedframes, NULL,
@@ -4847,19 +805,17 @@ xsh_detmon_dark_save(const cpl_parameterlist * parlist,
 
                 }
 
-	        cpl_propertylist_delete(pro_dsnu);
-
+                cpl_propertylist_delete(pro_dsnu);
             } else {
+                cpl_propertylist * pro_dsnu = cpl_propertylist_new();
 
-	    	cpl_propertylist * pro_dsnu = cpl_propertylist_new();
-
-		cpl_propertylist_append_string(pro_dsnu,
-	                                       CPL_DFS_PRO_CATG, procatg_dsnu);
+                cpl_propertylist_append_string(pro_dsnu,
+                                               CPL_DFS_PRO_CATG, procatg_dsnu);
 
-	        cpl_propertylist_append(pro_dsnu, qclist[0]);
+                cpl_propertylist_append(pro_dsnu, qclist[0]);
 
-	        if(cpl_dfs_save_image(frameset, NULL, parlist, usedframes,
-	                              NULL, NULL,
+                if(cpl_dfs_save_image(frameset, NULL, parlist, usedframes,
+                                      NULL, NULL,
                                       CPL_BPP_IEEE_FLOAT, recipe_name,
                                       pro_dsnu, NULL,
                                       package, name_o)) {
@@ -4869,9 +825,8 @@ xsh_detmon_dark_save(const cpl_parameterlist * parlist,
                     cpl_ensure_code(0, CPL_ERROR_FILE_NOT_CREATED);
                 }
 
-	        cpl_propertylist_delete(pro_dsnu);
-
-                for(j = 0; j < detmon_dark_config.nb_extensions; j++) {
+                cpl_propertylist_delete(pro_dsnu);
+                for(j = 0; j < xsh_detmon_dark_config.nb_extensions; j++) {
                     error =
                         cpl_image_save(cpl_imagelist_get(dsnu[j], i),
                                        name_o, CPL_BPP_IEEE_FLOAT, qclist[j],
@@ -4879,7 +834,7 @@ xsh_detmon_dark_save(const cpl_parameterlist * parlist,
                     cpl_ensure_code(!error, error);
                 }
             }
-	    cpl_free(name_o);
+            cpl_free(name_o);
         }
 
 
@@ -4891,7 +846,7 @@ xsh_detmon_dark_save(const cpl_parameterlist * parlist,
     /*******************************/
 
     /* Get FITS header from reference file */
-    ref_frame = cpl_frameset_get_frame(frameset,0);
+    ref_frame = cpl_frameset_get_first(frameset);
     if((plist = cpl_propertylist_load(cpl_frame_get_filename(ref_frame),
                                       0)) == NULL) {
         cpl_msg_error(cpl_func, "getting header from reference frame");
@@ -4906,13 +861,13 @@ xsh_detmon_dark_save(const cpl_parameterlist * parlist,
                                           "ESO DET NCORRS|"
                                           "ESO DET MODE NAME)$", 0);
 
-    for(i = 0; i < detmon_dark_config.nb_extensions; i++) {
+    for(i = 0; i < xsh_detmon_dark_config.nb_extensions; i++) {
         cpl_propertylist * c_paflist = cpl_propertylist_duplicate(paflist);
         error = cpl_propertylist_append(c_paflist, qclist[i]);
         cpl_ensure_code(!error, error);
 
         /* Set the file name for the bpm */
-        if(detmon_dark_config.exts >= 0) {
+        if(xsh_detmon_dark_config.exts >= 0) {
             if(!flag_sets) {
                 name_o = cpl_sprintf("%s.paf", recipe_name);
                 assert(name_o != NULL);
@@ -4948,93 +903,6 @@ xsh_detmon_dark_save(const cpl_parameterlist * parlist,
     return cpl_error_get_code();
 }
 
-cpl_error_code
-xsh_detmon_dark_qc(cpl_propertylist * qclist,
-                      cpl_image * collapsed)
-{
-    double mean = cpl_image_get_mean(collapsed);
-    double stdev = cpl_image_get_stdev(collapsed);
-
-    cpl_error_code error;
-
-    error = cpl_propertylist_append_double(qclist,DETMON_QC_DARK, mean);
-    error = cpl_propertylist_set_comment(qclist,DETMON_QC_DARK,
-					 DETMON_QC_DARK_C);
-    cpl_ensure_code(!error, error);
-
-    error = cpl_propertylist_append_double(qclist,DETMON_QC_DARK_STDEV, stdev);
-    error = cpl_propertylist_set_comment(qclist,DETMON_QC_DARK_STDEV,
-					 DETMON_QC_DARK_STDEV_C);
-    cpl_ensure_code(!error, error);
-
-    return cpl_error_get_code();
-}
-
-
-/*---------------------------------------------------------------------------*/
-/**
-  @brief    Collapse an imagelist to the stdev of each pixel position
-  @param    imlist    the input images list
-  @return   the average image or NULL on error case.
-  @see cpl_imagelist_is_uniform()
-
-  The returned image has to be deallocated with cpl_image_delete().
-
-  The bad pixel maps of the images in the input list are taken into
-  account, the result image pixels are flagged as rejected for those
-  where there were no good pixel at the same position in the input image list.
-
-  Possible #_cpl_error_code_ set in this function:
-  - CPL_ERROR_NULL_INPUT if (one of) the input pointer(s) is NULL
-  - CPL_ERROR_ILLEGAL_INPUT if the input image list is not valid
- */
-/*---------------------------------------------------------------------------*/
-cpl_image *
-irplib_imagelist_collapse_stdev_create(const cpl_imagelist * imlist)
-{
-    cpl_image          *    mean;
-    cpl_image          *    delta;
-    cpl_image          *    sq_delta;
-    cpl_image          *    stdev;
-
-    int                     i;
-
-    /* Check inputs */
-    cpl_ensure(imlist != NULL, CPL_ERROR_NULL_INPUT, NULL);
-    cpl_ensure(cpl_imagelist_is_uniform(imlist) == 0, CPL_ERROR_ILLEGAL_INPUT,
-               NULL);
-
-    /* Create mean image with its first iterative value = first image */
-    mean = cpl_image_duplicate(cpl_imagelist_get_const(imlist, 0));
-    cpl_image_fill_rejected(mean, 0.0);
-    cpl_image_accept_all(mean);
-
-    stdev = cpl_image_new(cpl_image_get_size_x(mean),
-			  cpl_image_get_size_y(mean),
-			  CPL_TYPE_FLOAT);
 
-    for (i = 1; i < cpl_imagelist_get_size(imlist); i++) {
-        delta = cpl_image_subtract_create(cpl_imagelist_get_const(imlist, i),
-	                                  mean);
-        cpl_image_fill_rejected(delta, 0.0);
-        cpl_image_accept_all(delta);
 
-	sq_delta = cpl_image_multiply_create(delta, delta);
-
-	cpl_image_multiply_scalar(sq_delta, ((double) i / (double)(i+1)));
-	cpl_image_add(stdev, sq_delta);
-
-	cpl_image_divide_scalar(delta, i + 1);
-	cpl_image_add(mean, delta);
-
-        cpl_image_delete(delta);
-        cpl_image_delete(sq_delta);
-    }
-
-    cpl_image_divide_scalar(stdev, cpl_imagelist_get_size(imlist) - 1);
-    cpl_image_power(stdev, 0.5);
-
-    cpl_image_delete(mean);
-
-    return stdev;
-}
+/**@}*/
diff --git a/xsh/xsh_detmon.h b/xsh/xsh_detmon.h
index 5d645f5..060cc2b 100644
--- a/xsh/xsh_detmon.h
+++ b/xsh/xsh_detmon.h
@@ -1,4 +1,4 @@
-/* $Id: xsh_detmon.h,v 1.22 2011-12-09 10:05:22 amodigli Exp $
+/* $Id: xsh_detmon.h,v 1.3 2013-01-25 16:08:41 jtaylor Exp $
  *
  * This file is part of the irplib package
  * Copyright (C) 2002, 2003 European Southern Observatory
@@ -19,9 +19,9 @@
  */
 
 /*
- * $Author: amodigli $
- * $Date: 2011-12-09 10:05:22 $
- * $Revision: 1.22 $
+ * $Author: jtaylor $
+ * $Date: 2013-01-25 16:08:41 $
+ * $Revision: 1.3 $
  * $Name: not supported by cvs2svn $
  */
 
@@ -34,6 +34,7 @@
 
 #include <cpl.h>
 #include <xsh_cpl_size.h>
+
 /*----------------------------------------------------------------------------
                                    Prototypes
  ----------------------------------------------------------------------------*/
@@ -42,261 +43,18 @@
 #define NIR TRUE
 #define OPT FALSE
 
-#define DETMON_QC_FREQ       "ESO QC FREQ"
-#define DETMON_QC_FREQ_C     "Spectrum frequency"
-
-#define DETMON_QC_POW       "ESO QC POW"
-#define DETMON_QC_POW_C     "Spectrum power"
-
-#define DETMON_QC_DUTYCYCL       "ESO QC DUTYCYCL"
-#define DETMON_QC_DUTYCYCL_C     "DUTYCYCL value (time to store a frame)"
-
-#define DETMON_QC_MASTER_MEAN    "ESO QC MASTER MEAN"
-#define DETMON_QC_MASTER_MEAN_C  "Master Mean value"
-
-#define DETMON_QC_MASTER_RMS    "ESO QC MASTER RMS"
-#define DETMON_QC_MASTER_RMS_C  "Master RMS value"
-
-#define DETMON_QC_NBCOLDPIX    "ESO QC NBCOLPIX"
-#define DETMON_QC_NBCOLDPIX_C  "Number of cold pixels"
-
-#define DETMON_QC_NBHOTPIX    "ESO QC NBHOTPIX"
-#define DETMON_QC_NBHOTPIX_C  "Number of hot pixels"
-
-#define DETMON_QC_NBDEVPIX    "ESO QC NBDEVPIX"
-#define DETMON_QC_NBDEVPIX_C  "Number of deviating pixels"
-
-#define DETMON_QC_BIAS_RANDOM_VAL    "ESO QC BIAS RANDOM VAL"
-#define DETMON_QC_BIAS_RANDOM_VAL_C  "Bias level (random sampling method) [ADU]"
-
-#define DETMON_QC_BIAS_RANDOM_RON    "ESO QC BIAS RANDOM RON"
-#define DETMON_QC_BIAS_RANDOM_RON_C  "Bias Read Out Noise (random sampling method) [ADU]"
-
-#define DETMON_QC_BIAS_HISTO_VAL    "ESO QC BIAS HISTO VAL"
-#define DETMON_QC_BIAS_HISTO_VAL_C  "Bias level (histogram method) [ADU]"
-
-#define DETMON_QC_BIAS_HISTO_RON    "ESO QC BIAS HISTO RON"
-#define DETMON_QC_BIAS_HISTO_RON_C  "Bias Read Out Noise (histogram method) [e- rms]"
-
-#define DETMON_QC_BIAS_PRESCAN_MEAN    "ESO QC BIAS PRESCAN MEAN"
-#define DETMON_QC_BIAS_PRESCAN_MEAN_C  "Bias mean level (on prescan region) [ADU]"
-
-#define DETMON_QC_BIAS_PRESCAN_MED    "ESO QC BIAS PRESCAN MED"
-#define DETMON_QC_BIAS_PRESCAN_MED_C  "Bias median level (on prescan region) [ADU]"
-
-#define DETMON_QC_BIAS_PRESCAN_RON    "ESO QC BIAS PRESCAN RON"
-#define DETMON_QC_BIAS_PRESCAN_RON_C  "Bias Read Out Noise (on prescan region) [e- rms]"
-
-
-#define DETMON_QC_BIAS_OVERSCAN_MEAN    "ESO QC BIAS OVERSCAN MEAN"
-#define DETMON_QC_BIAS_OVERSCAN_MEAN_C  "Bias mean level (on overscan region) [ADU]"
-
-#define DETMON_QC_BIAS_OVERSCAN_MED    "ESO QC BIAS OVERSCAN MED"
-#define DETMON_QC_BIAS_OVERSCAN_MED_C  "Bias median level (on overscan region) [ADU]"
-
-#define DETMON_QC_BIAS_OVERSCAN_RON    "ESO QC BIAS OVERSCAN RON"
-#define DETMON_QC_BIAS_OVERSCAN_RON_C  "Bias Read Out Noise (on overscan region) [e- rms]"
-
-#define DETMON_QC_BIAS_REGION_VAL    "ESO QC BIAS REGION VAL"
-#define DETMON_QC_BIAS_REGION_VAL_C  "Bias level (on user defined region) [ADU]"
-
-#define DETMON_QC_BIAS_REGION_MED    "ESO QC BIAS REGION MED"
-#define DETMON_QC_BIAS_REGION_MED_C  "Bias median level (on user defined region) [ADU]"
-
-#define DETMON_QC_BIAS_REGION_RON    "ESO QC BIAS REGION RON"
-#define DETMON_QC_BIAS_REGION_RON_C  "Bias Read Out Noise (on user defined region) [e- rms]"
-
-
-#define DETMON_QC_DARK    "ESO QC DARK"
-#define DETMON_QC_DARK_C  "Dark level [ADU]"
-
-#define DETMON_QC_DARK_STDEV    "ESO QC DARK STDEV"
-#define DETMON_QC_DARK_STDEV_C  "Dark stdev level [ADU]"
-
-
-
-/* Macros to generate the recipe(s) description(s) */
-#define xsh_detmon_ronbias_get_description(RECIPE_NAME, PIPE_NAME,          \
-                                              DETMON_RONBIAS_RAW)              \
-    RECIPE_NAME " -- " PIPE_NAME " ronbias recipe for OPT/IR.\n"            \
-    "The files listed in the Set Of Frames must be tagged:\n"                  \
-    "raw-file.fits  "DETMON_RONBIAS_RAW"\n"
-
-#define xsh_detmon_pernoise_get_description(RECIPE_NAME, PIPE_NAME,         \
-                                              DETMON_PERNOISE_RAW)             \
-    RECIPE_NAME " -- " PIPE_NAME " Recipe for Periodic Noise Characterisation.\n"            \
-    "The files listed in the Set Of Frames must be tagged:\n"                  \
-    "raw-file.fits  "DETMON_PERNOISE_RAW"\n"
-
-#define xsh_detmon_dark_get_description(RECIPE_NAME, PIPE_NAME,         \
-                                              DETMON_DARK_RAW)             \
-    RECIPE_NAME " -- " PIPE_NAME " Dark Recipe.\n"            \
-    "The files listed in the Set Of Frames must be tagged:\n"                  \
-    "raw-file.fits  "DETMON_DARK_RAW"\n"
-
-#define RANDOM       ((irplib_ronbias_method) 1 << 1)
-#define HISTO        ((irplib_ronbias_method) 1 << 2)
-#define PREOVERSCAN  ((irplib_ronbias_method) 1 << 3)
-#define REGION       ((irplib_ronbias_method) 1 << 4)
-
-typedef unsigned long irplib_ronbias_method;
 
 #undef REGEXP
 #define REGEXP "ARCFILE|MJD-OBS|ESO TPL ID|DATE-OBS|ESO DET DIT|ESO DET NDIT"
 
-#if defined CPL_VERSION_CODE && CPL_VERSION_CODE < CPL_VERSION(4, 2, 0) 
-
-#define CPL_DFS_PRO_CATG     "ESO PRO CATG"
-#define CPL_DFS_PRO_TYPE     "ESO PRO TYPE"
-#define CPL_DFS_PRO_SCIENCE  "ESO PRO SCIENCE"
-#define CPL_DFS_PRO_TECH     "ESO PRO TECH"
-
-#endif
-
-cpl_image * 
-irplib_imagelist_collapse_stdev_create(const cpl_imagelist * imlist);
-
-cpl_error_code
-xsh_detmon_ronbias(cpl_frameset      *,
-                      const cpl_parameterlist *,
-                      const char        *,
-                      const char        *,
-                      const char        *,
-                      const char        *,
-		      const cpl_propertylist *,
-		      const cpl_propertylist *,
-		      const cpl_propertylist *,
-		      const cpl_propertylist *,
-		      const cpl_propertylist *,
-		      const cpl_propertylist *,
-		      const cpl_propertylist *,
-                      const char        *,
-                      int              (*)(const cpl_frame *,
-                                           const cpl_frame *),
-                      cpl_boolean);
-
 cpl_propertylist *
 xsh_detmon_fill_prolist(const char *,
 			   const char *,
 			   const char *,
 			   cpl_boolean);
 
-cpl_error_code
-xsh_detmon_ronbias_fill_parlist_default(cpl_parameterlist *,
-					   const char        *,
-					   const char        *);
-
-cpl_error_code
-xsh_detmon_darkron_fill_parlist_default(cpl_parameterlist *,
-					   const char        *,
-					   const char        *);
-
-cpl_error_code
-xsh_detmon_ronbias_fill_parlist(cpl_parameterlist *,
-				   const char *,
-				   const char *,
-				   const char *,
-				   const char *,
-				   const int,
-				   const int,
-				   const int,
-				   const int,
-				   const int,
-				   const int,
-				   const int,
-				   const int,
-				   const int,
-				   const char *,
-				   const int,
-				   const int,
-				   const int,
-				   const int,
-				   const int,
-				   const int,
-				   const int,
-				   const int,
-				   const int,
-				   const int,
-                                   cpl_boolean);
-
-cpl_error_code
-xsh_detmon_ronbias_histo_reduce(const cpl_image * c_raw,
-				   double * bias,
-				   double * fwhm,
-				   double * max);
-cpl_image *
-xsh_detmon_build_synthetic(cpl_image *,
-                              cpl_image *);
-
-cpl_error_code
-xsh_flux_get_bias_window(const cpl_image *,
-                            const int       *,
-                            int              ,
-                            int              ,
-                            double          *,
-                            double          *);
-
-cpl_error_code
-xsh_detmon_fill_pernoise_params(cpl_parameterlist *,
-                                   const char *,
-                                   const char *,
-                                   int mode,
-                                   const char *direction,
-                                   double speed,
-                                   int llx,
-                                   int lly,
-                                   int urx,
-                                   int ury,
-                                   double kappa,
-                                   int exts);
-
-int xsh_detmon_fill_pernoise_params_default(cpl_parameterlist        *,
-                              const char        *,
-                              const char        *);
-
-cpl_error_code
-xsh_detmon_pernoise(cpl_frameset      *,
-                      const cpl_parameterlist *,
-                      const char        *,
-                      const char        *,
-                      const char        *,
-                      const char        *,
-                      const char        *,
-                      int              (*)(const cpl_frame *,
-                                           const cpl_frame *));
 
-cpl_table *
-xsh_detmon_pernoise_reduce(cpl_image       *);
 
-cpl_error_code
-xsh_detmon_dark(cpl_frameset      *,
-                   const cpl_parameterlist *,
-                   const char        *,
-                   const char        *,
-                   const char        *,
-                   const char        *,
-                   const char        *,
-                   const char        *,
-                   const char        *,
-                   int              (*)(const cpl_frame *,
-                                        const cpl_frame *));
-
-cpl_error_code
-xsh_detmon_fill_dark_params(cpl_parameterlist * parlist,
-                               const char *recipe_name,
-                               const char *pipeline_name,
-                               const char * ron_method,
-                               const char * dsnu_method,
-                               const char * optnir,
-                               int exts);
-
-int
-xsh_detmon_fill_dark_params_default(cpl_parameterlist * parlist,
-                                       const char *recipe_name,
-                                       const char *pipeline_name);
-
-int
-xsh_detmon_compare_dits(const cpl_frame *, const cpl_frame *);
 
 double                  irplib_pfits_get_exptime(const cpl_propertylist *);
 
@@ -304,17 +62,6 @@ cpl_error_code
 xsh_detmon_fill_parlist(cpl_parameterlist *,
                            const char *, const char *, int, ...);
 
-cpl_error_code
-xsh_ksigma_clip(const cpl_image *,
-		   const int,
-		   const int,
-		   const int,
-		   const int,
-		   const double,
-		   const int,
-		   const double,
-		   double *,
-		   double *);
 int
 xsh_detmon_retrieve_par_int(const char *,
                             const char *,
@@ -325,5 +72,9 @@ xsh_detmon_retrieve_par_double(const char *,
                             const char *,
                             const char *, const cpl_parameterlist *);
 
+int xsh_detmon_lg_mr(cpl_frameset            * frameset,
+                 const cpl_parameterlist * parlist_,
+                 const char * recipe,
+                 cpl_boolean opt);
 
 #endif
diff --git a/xsh/xsh_detmon_dfs.h b/xsh/xsh_detmon_dfs.h
new file mode 100644
index 0000000..3eacebc
--- /dev/null
+++ b/xsh/xsh_detmon_dfs.h
@@ -0,0 +1,52 @@
+/* $Id: detmon_dfs.h,v 1.5 2013-01-29 08:56:40 jtaylor Exp $
+ *
+ * This file is part of the IIINSTRUMENT Pipeline
+ * Copyright (C) 2002,2003 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-01-29 08:56:40 $
+ * $Revision: 1.5 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifndef DETMON_DFS_H
+#define DETMON_DFS_H
+
+/*-----------------------------------------------------------------------------
+   								Define
+ -----------------------------------------------------------------------------*/
+
+/* Define here the PRO.CATG keywords */
+#define DETMON_IR_LG            "DETMON_IR_LG"
+
+/* Define here the DO.CATG keywords */
+#define DETMON_IR_LG_ON_RAW                    "ON_RAW"
+#define DETMON_IR_LG_OFF_RAW			"OFF_RAW"
+
+#define DETMON_OPT_LG_ON_RAW                    "ON_RAW"
+#define DETMON_OPT_LG_OFF_RAW			"OFF_RAW"
+
+#define NIR TRUE
+#define OPT FALSE
+
+/*-----------------------------------------------------------------------------
+                                Functions prototypes
+ -----------------------------------------------------------------------------*/
+
+#endif
diff --git a/xsh/xsh_detmon_lg.c b/xsh/xsh_detmon_lg.c
index c5c201e..334895b 100644
--- a/xsh/xsh_detmon_lg.c
+++ b/xsh/xsh_detmon_lg.c
@@ -1,4 +1,4 @@
-/* $Id: xsh_detmon_lg.c,v 1.34 2013-07-15 08:11:18 amodigli Exp $
+/* $Id: xsh_detmon_lg.c,v 1.31 2013-08-07 09:32:37 jtaylor Exp $
  *
  * This file is part of the irplib package
  * Copyright (C) 2002, 2003 European Southern Observatory
@@ -20,9 +20,9 @@
 
 
 /*
- * $Author: amodigli $
- * $Date: 2013-07-15 08:11:18 $
- * $Revision: 1.34 $
+ * $Author: jtaylor $
+ * $Date: 2013-08-07 09:32:37 $
+ * $Revision: 1.31 $
  * $Name: not supported by cvs2svn $
  *
  */
@@ -35,25 +35,28 @@
                                   Includes
  ---------------------------------------------------------------------------*/
 
-#include <complex.h>
-
-
-#include <math.h>
-#include <string.h>
-#include <assert.h>
-
 #include <cpl.h>
 #include <cpl_fft.h>
+#include "hdrl.h"
+
 #include "xsh_detmon.h"
+#include "xsh_detmon_utils.h"
 #include "xsh_detmon_lg.h"
 #include "xsh_detmon_lg_impl.h"
+#include "xsh_detmon_dfs.h"
 
+#include "xsh_ksigma_clip.h"
 #include "irplib_utils.h"
-#include "xsh_hist.h"
-#include "xsh_globals.h"
+#include "irplib_hist.h"
+#include <complex.h>
+
 
+#include <math.h>
+#include <string.h>
+#include <assert.h>
+/**@{*/
 /*
- * @defgroup xsh_detmon        Detector monitoring functions
+ * @defgroup irplib_xsh_detmon        Detector monitoring functions
  */
 
 /*--------------------------------------------------------------------------*/
@@ -64,9 +67,9 @@
 /*method for calculating Fixed Pattern Noise (FPN)*/
 enum _FPN_METHOD
 {
-	FPN_UNKNOWN,
-	FPN_HISTOGRAM, /*default*/
-	FPN_SMOOTH,
+    FPN_UNKNOWN,
+    FPN_HISTOGRAM, /*default*/
+    FPN_SMOOTH,
 };
 typedef enum _FPN_METHOD FPN_METHOD;
 static struct
@@ -126,17 +129,14 @@ static struct
     double                  lamp_stability;
     cpl_boolean             lamp_ok;
     /* by kmirny */
-    int                    (* load_fset) (
-    		const cpl_frameset *, cpl_type, cpl_imagelist *
-    		);
-    cpl_imagelist *                    (* load_fset_wrp) (
-    		const cpl_frameset *, cpl_type, int
-    		);
+    int (* load_fset) (const cpl_frameset *, cpl_type, cpl_imagelist *);
+    cpl_imagelist * (* load_fset_wrp) (const cpl_frameset *, cpl_type, int);
     FPN_METHOD fpn_method;
     int fpn_smooth;
     double saturation_limit;
+    double gain_threshold;
     cpl_boolean            split_coeffs;
-} detmon_lg_config;
+} xsh_detmon_lg_config;
 
 /* static const char* COL_NAME_DET1_WIN1_UIT1 = "DET1_WIN1_UIT1"; */
 /*---------------------------------------------------------------------------
@@ -147,94 +147,109 @@ static struct
 /*  Parameters */
 static cpl_error_code
 xsh_detmon_lg_retrieve_parlist(const char *,
-				  const char *, const cpl_parameterlist *,
-                                  cpl_boolean);
+                           const char *, const cpl_parameterlist *,
+                           cpl_boolean);
 
 
 static cpl_error_code
 xsh_detmon_lg_split_onoff(const cpl_frameset *,
-                             cpl_frameset *,
-                             cpl_frameset *,
-                             const char *, const char * /*, cpl_boolean*/);
+                      cpl_frameset *,
+                      cpl_frameset *,
+                      const char *, const char * /*, cpl_boolean*/);
 
 static cpl_error_code
 xsh_detmon_lg_reduce(const cpl_frameset *,
-                        const cpl_frameset *,
-/*                        int *,
-                          int *, */
-    				    int* index_on, int* index_off, double* exptime_on, double* exptime_off,
-    				    int *next_index_on, int* next_index_off,
-                        cpl_imagelist **,
-                        cpl_table *,
-                        cpl_table *,
-                        cpl_image **,
-                        cpl_imagelist *,
-                        cpl_imagelist *,
-                        cpl_propertylist *,
-                        cpl_propertylist *,
-                        cpl_propertylist *,
-                        cpl_propertylist *,
-		 int                    (* load_fset) (const cpl_frameset *,
-						       cpl_type,
-		                                       cpl_imagelist *),
-                        const cpl_boolean, int);
+                 const cpl_frameset *,
+                 int* index_on, int* index_off,
+                 double* exptime_on, double* exptime_off,
+                 int *next_index_on, int* next_index_off,
+                 cpl_imagelist **,
+                 cpl_table *,
+                 cpl_table *,
+                 cpl_image **,
+                 cpl_imagelist *,
+                 cpl_imagelist *,
+                 cpl_propertylist *,
+                 cpl_propertylist *,
+                 cpl_propertylist *,
+                 cpl_propertylist *,
+                 int (* load_fset) (const cpl_frameset *,
+                                    cpl_type,
+                                    cpl_imagelist *),
+                 const cpl_boolean, int);
+
+
+
 
 static cpl_error_code
 xsh_detmon_lin_table_fill_row(cpl_table *, double,
-				 cpl_imagelist *,
-				 const cpl_imagelist *,
-				 const cpl_imagelist *,
-				 int, int, int, int,
-				 const int,
-                                 const int,
-				 unsigned);
+                          cpl_imagelist *,
+                          const cpl_imagelist *,
+                          const cpl_imagelist *,
+                          int, int, int, int,
+                          const int,
+                          const int,
+                          unsigned);
 
 static cpl_error_code
 xsh_detmon_gain_table_fill_row(cpl_table * gain_table,
-				  double c_dit,int c_ndit,
-		  cpl_imagelist * autocorr_images,
-		  cpl_imagelist * diff_flats,
-		  const cpl_imagelist * ons,
-                        const cpl_imagelist * offs,
-                        double kappa, int nclip,
-                        int llx, int lly, int urx, int ury,
-                        int m, int n,
-                        double saturation_limit,
-		  const int pos, unsigned mode, int* rows_affected);
+                           double c_dit,int c_ndit,
+                           cpl_imagelist * autocorr_images,
+                           cpl_imagelist * diff_flats,
+                           const cpl_imagelist * ons,
+                           const cpl_imagelist * offs,
+                           double kappa, int nclip,
+                           int llx, int lly, int urx, int ury,
+                           int m, int n,
+                           double saturation_limit,
+                           double gain_threshold,
+                           const int pos, unsigned mode, int* rows_affected);
+
+
+static cpl_error_code
+xsh_detmon_check_saturation_on_pair(cpl_imagelist * autocorr_images,
+                           cpl_imagelist * diff_flats,
+                           const cpl_imagelist * ons,
+                           const cpl_imagelist * offs,
+                           double kappa, int nclip,
+                           int llx, int lly, int urx, int ury,
+                           double saturation_limit,
+                           const int pos, unsigned mode,
+                           int* rows_linear_affected);
 
 static                  cpl_error_code
 xsh_detmon_lg_save(const cpl_parameterlist *,
-                      cpl_frameset *,
-                      const char *,
-                      const char *,
-                      const char *,
-		      const cpl_propertylist  *,
-		      const cpl_propertylist  *,
-		      const cpl_propertylist  *,
-		      const cpl_propertylist  *,
-		      const cpl_propertylist  *,
-		      const cpl_propertylist  *,
-                      const char *,
-                      cpl_imagelist *,
-                      cpl_table *,
-                      cpl_table *,
-                      cpl_image *,
-                      cpl_imagelist *,
-                      cpl_imagelist *,
-                      cpl_propertylist *,
-                      cpl_propertylist *,
-                      cpl_propertylist *,
-                      cpl_propertylist *,
-                      const int, const int, const cpl_frameset *,
-                      int);
+               cpl_frameset *,
+               const char *,
+               const char *,
+               const char *,
+               const cpl_propertylist  *,
+               const cpl_propertylist  *,
+               const cpl_propertylist  *,
+               const cpl_propertylist  *,
+               const cpl_propertylist  *,
+               const cpl_propertylist  *,
+               const char *,
+               cpl_imagelist *,
+               cpl_table *,
+               cpl_table *,
+               cpl_image *,
+               cpl_imagelist *,
+               cpl_imagelist *,
+               cpl_propertylist *,
+               cpl_propertylist *,
+               cpl_propertylist *,
+               cpl_propertylist *,
+               const int, const int, const cpl_frameset *,
+               int);
 
 static cpl_error_code
 xsh_detmon_lg_qc_ptc(const cpl_table  *,
-			cpl_propertylist *, unsigned, int);
+                 cpl_propertylist *, unsigned, int);
 
 static cpl_error_code
 xsh_detmon_lg_qc_med(const cpl_table  *,
-			cpl_propertylist *, int);
+                 cpl_propertylist *, int);
 
 
 static double
@@ -243,20 +258,22 @@ irplib_pfits_get_dit(const cpl_propertylist *);
 static double
 irplib_pfits_get_dit_opt(const cpl_propertylist *);
 static double
-irplib_pfits_get_prop_double(const cpl_propertylist * plist, const char* prop_name);
+irplib_pfits_get_prop_double(const cpl_propertylist * plist,
+                             const char* prop_name);
 
-static cpl_image       *xsh_detmon_bpixs(const cpl_imagelist *, cpl_boolean, const double, int *);
+static cpl_image * xsh_detmon_bpixs(const cpl_imagelist *,
+                                cpl_boolean, const double, int *);
 
 static double
 xsh_detmon_autocorr_factor(const cpl_image *,
-                              cpl_image **, int, int);
+                       cpl_image **, int, int);
 
 
 
-static                  cpl_error_code
+static cpl_error_code
 xsh_detmon_opt_contamination(const cpl_imagelist *,
-				const cpl_imagelist *,
-				unsigned mode, cpl_propertylist *);
+                         const cpl_imagelist *,
+                         unsigned mode, cpl_propertylist *);
 
 #if 0
 xsh_detmon_opt_lampcr(cpl_frameset *, int);
@@ -267,14 +284,14 @@ xsh_detmon_lg_dfs_set_groups(cpl_frameset *, const char *, const char *);
 
 static cpl_error_code
 xsh_detmon_lg_reduce_all(const cpl_table *,
-			    cpl_propertylist *,
-			    cpl_propertylist *
-,			    cpl_propertylist *,
-			    cpl_propertylist *,
-			    cpl_imagelist **,
-			    cpl_image **,
-                            const cpl_imagelist *,
-			    const cpl_table *, int, cpl_boolean);
+                     cpl_propertylist *,
+                     cpl_propertylist *,
+                     cpl_propertylist *,
+                     cpl_propertylist *,
+                     cpl_imagelist **,
+                     cpl_image **,
+                     const cpl_imagelist *,
+                     const cpl_table *, int, cpl_boolean);
 
 static cpl_error_code
 xsh_detmon_lg_check_defaults(const cpl_image *);
@@ -284,10 +301,9 @@ xsh_detmon_lg_rescale(cpl_imagelist *);
 
 static cpl_error_code
 xsh_detmon_lg_reduce_init(cpl_table *,
-                             cpl_table *,
-                             cpl_imagelist **,
-                             const cpl_boolean);
-
+                      cpl_table *,
+                      cpl_imagelist **,
+                      const cpl_boolean);
 
 
 static cpl_error_code
@@ -295,115 +311,121 @@ xsh_detmon_add_adl_column(cpl_table *, cpl_boolean);
 
 static cpl_error_code
 xsh_detmon_lg_lamp_stab(const cpl_frameset *,
-			   const cpl_frameset *,
-                           cpl_boolean, int);
+                    const cpl_frameset *,
+                    cpl_boolean, int);
 
 
 static cpl_error_code
 xsh_detmon_lg_reduce_dit(const cpl_frameset * set_on,
-			    int* index_on, double* exptime_on,
-			    const int dit_nb,
-                int * dit_nskip,
-			    const cpl_frameset * set_off,
-			    int * index_off, double* exptime_off,
-			    int* next_on, int* next_off,
-			    cpl_table * linear_table,
-			    cpl_table * gain_table,
-			    cpl_imagelist * linearity_inputs,
-			    cpl_propertylist * qclist,
-			    cpl_boolean opt_nir,
-			    cpl_imagelist * autocorr_images,
-			    cpl_imagelist * diff_flats,
-                cpl_imagelist * opt_offs,
-                int whichext,
-                int * rows_affected);
+                     int* index_on, double* exptime_on,
+                     const int dit_nb,
+                     int * dit_nskip,
+                     const cpl_frameset * set_off,
+                     int * index_off, double* exptime_off,
+                     int* next_on, int* next_off,
+                     cpl_table * linear_table,
+                     cpl_table * gain_table,
+                     cpl_imagelist * linearity_inputs,
+                     cpl_propertylist * qclist,
+                     cpl_boolean opt_nir,
+                     cpl_imagelist * autocorr_images,
+                     cpl_imagelist * diff_flats,
+                     cpl_imagelist * opt_offs,
+                     int whichext,
+                     int * rows_linear_affected,
+                     int * rows_gain_affected);
 
 static cpl_error_code
 xsh_detmon_lg_core(cpl_frameset * cur_fset_on,
-		      cpl_frameset * cur_fset_off,
-		      int * index_on,
-			  int * index_off,
-			  double * exptime_on,
-			  double * exptime_off,
-		      int whichext,
-                      int whichset,
-		      const char              * recipe_name,
-		      const char              * pipeline_name,
-		      const char              * pafregexp,
-		      const cpl_propertylist  * pro_lintbl,
-		      const cpl_propertylist  * pro_gaintbl,
-		      const cpl_propertylist  * pro_coeffscube,
-		      const cpl_propertylist  * pro_bpm,
-		      const cpl_propertylist  * pro_corr,
-		      const cpl_propertylist  * pro_diff,
-		      const char              * package,
-		      int                    (* load_fset) (const cpl_frameset *,
-							    cpl_type,
-							    cpl_imagelist *),
-		      int nsets, cpl_boolean opt_nir,
-                      cpl_frameset * frameset, const cpl_parameterlist * parlist,
-                      cpl_frameset * cur_fset);
+               cpl_frameset * cur_fset_off,
+               int * index_on,
+               int * index_off,
+               double * exptime_on,
+               double * exptime_off,
+               int whichext,
+               int whichset,
+               const char              * recipe_name,
+               const char              * pipeline_name,
+               const char              * pafregexp,
+               const cpl_propertylist  * pro_lintbl,
+               const cpl_propertylist  * pro_gaintbl,
+               const cpl_propertylist  * pro_coeffscube,
+               const cpl_propertylist  * pro_bpm,
+               const cpl_propertylist  * pro_corr,
+               const cpl_propertylist  * pro_diff,
+               const char              * package,
+               int                    (* load_fset) (const cpl_frameset *,
+                                                     cpl_type,
+                                                     cpl_imagelist *),
+               int nsets, cpl_boolean opt_nir,
+               cpl_frameset * frameset, const cpl_parameterlist * parlist,
+               cpl_frameset * cur_fset);
 
 static cpl_error_code
 xsh_detmon_lg_lineff(double *, cpl_propertylist *, int, int);
 
 /*
-static int
-xsh_detmon_lg_compare_pairs(const cpl_frame *,
-			       const cpl_frame *);
-*/
+   static int
+   xsh_detmon_lg_compare_pairs(const cpl_frame *,
+   const cpl_frame *);
+   */
 static cpl_error_code
 xsh_detmon_gain_table_create(cpl_table *,
-                                const cpl_boolean);
+                         const cpl_boolean);
 
 
 static cpl_error_code
 xsh_detmon_lin_table_create(cpl_table *,
-                               const cpl_boolean);
+                        const cpl_boolean);
 
 static cpl_vector *
 xsh_detmon_lg_find_dits(const cpl_vector *,
-                           double            );
+                    double            );
 
 static cpl_error_code
 xsh_detmon_lg_find_dits_ndits(const cpl_vector * exptimes,
-			   const cpl_vector * vec_ndits,
-                           double             tolerance,
-                           cpl_vector** diff_dits,
-				 cpl_vector** diff_ndits);
+                          const cpl_vector * vec_ndits,
+                          double             tolerance,
+                          cpl_vector** diff_dits,
+                          cpl_vector** diff_ndits);
 
 static cpl_error_code
 xsh_detmon_fpn_compute(const cpl_frameset *set_on,
-		int * index_on,
-		int last_best,
-		cpl_propertylist *lint_qclist,
-		int llx,
-		int lly,
-		int urx,
-		int ury,
-		double gain,
-		int whichext,
-		FPN_METHOD fpn_method,
-		int smooth_size);
+                   int * index_on,
+                   int last_linear_best,
+                   cpl_propertylist *lint_qclist,
+                   int llx,
+                   int lly,
+                   int urx,
+                   int ury,
+                   double gain,
+                   int whichext,
+                   FPN_METHOD fpn_method,
+                   int smooth_size);
 static double irplib_fpn_lg(const cpl_image* f1, int* range, double gain,
-		FPN_METHOD fpn_method, int, double* mse);
+                            FPN_METHOD fpn_method, int, double* mse);
 static double irplib_calculate_total_noise(const cpl_image* pimage);
 
-static cpl_imagelist* irplib_load_fset_wrp(const cpl_frameset *, cpl_type, int whichext);
-static cpl_imagelist * irplib_load_fset_wrp_ext(const cpl_frameset *, cpl_type, int);
+static cpl_imagelist* irplib_load_fset_wrp(const cpl_frameset *,
+                                           cpl_type, int whichext);
+static cpl_imagelist * irplib_load_fset_wrp_ext(const cpl_frameset *,
+                                                cpl_type, int);
 
-static cpl_error_code irplib_table_create_column(cpl_table* ptable, cpl_propertylist* plist);
-static cpl_error_code irplib_fill_table_DETWINUIT(cpl_table* ptable, cpl_propertylist* plist, int row);
+static cpl_error_code irplib_table_create_column(cpl_table* ptable,
+                                                 cpl_propertylist* plist);
+static cpl_error_code irplib_fill_table_DETWINUIT(cpl_table* ptable,
+                                                  cpl_propertylist* plist,
+                                                  int row);
 
 static cpl_error_code
 xsh_detmon_pair_extract_next(const cpl_frameset * set,
-                           int* index,
-                           int* next_element,
-                          double* dit_array,
-/*                           int * with_equal_dit,
-                             int onoff, */
-                           cpl_frameset ** pair,
-                           double tolerance);
+                         int* index,
+                         int* next_element,
+                         double* dit_array,
+                         /* int * with_equal_dit,
+                            int onoff, */
+                         cpl_frameset ** pair,
+                         double tolerance);
 static cpl_error_code
 xsh_detmon_single_extract_next(const cpl_frameset * set,
                            int* index,
@@ -412,10 +434,10 @@ xsh_detmon_single_extract_next(const cpl_frameset * set,
                            cpl_frameset ** pair);
 
 /*
-static int frame_get_ndit(const cpl_frame * pframe);
-static cpl_error_code
-irplib_frameset_get_ndit(const cpl_frameset *  self, int* ndit);
-*/
+   static int frame_get_ndit(const cpl_frame * pframe);
+   static cpl_error_code
+   irplib_frameset_get_ndit(const cpl_frameset *  self, int* ndit);
+   */
 static cpl_error_code xsh_detmon_table_fill_invalid(cpl_table* ptable, double code);
 static void xsh_detmon_lg_add_empty_image(cpl_imagelist* imlist, int pos);
 static int xsh_detmon_lg_check_before_gain(const cpl_vector* x, const cpl_vector* y);
@@ -472,178 +494,236 @@ irplib_frameset_get_ndit(const cpl_frameset *  self, int* ndit)
 }
 */
 
-static cpl_error_code xsh_detmon_lg_reduce_set(int i, cpl_frameset * frameset, int nsets,
-        const char              * tag_on,
-        const char              * tag_off,
-        const char              * recipe_name,
-        const char              * pipeline_name,
-        const char              * pafregexp,
-        const cpl_propertylist  * pro_lintbl,
-        const cpl_propertylist  * pro_gaintbl,
-        const cpl_propertylist  * pro_coeffscube,
-        const cpl_propertylist  * pro_bpm,
-        const cpl_propertylist  * pro_corr,
-        const cpl_propertylist  * pro_diff,
-        const char              * package,
-        int                    (* load_fset)
-			(const cpl_frameset *, cpl_type, cpl_imagelist *),
-        const cpl_boolean         opt_nir,
-        const cpl_parameterlist * parlist,
-        cpl_size* selection
-        );
+/*----------------------------------------------------------------------------*/
+/**
+  @brief   compute photon count error in [ADU]
+  @param   ima_data in [ADU]
+  @param   gain detector's gain in [e- / ADU]
+  @param   ron  detector's read out noise in [ADU]
+  @param   ima_errs output error image in [ADU]
+  @return  cpl_error_code
+  @note ima_errs need to be deallocated
+        ima_data must contain the photon counts with no offsets
+        this usually means the image must be overscan and bias corrected
+        Then the shot noise can be calculated from the poissonian distribution
+        as sqrt(electron-counts). To this (transformed back into ADUs) the
+        readout noise is added in quadrature.
+  @doc
+  error is computed with standard formula
+
+  \f$ err_{ADU} = \sqrt{ \frac{ counts }{ gain } + ron^{ 2 } } \f$
+
+  If an image value is negative the associated error is set to RON
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code
+hdrldemo_detector_shotnoise_model(const cpl_image* ima_data, const double gain,
+                              const double ron, cpl_image ** ima_errs)
+{
+    cpl_ensure_code(ima_data, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(ima_errs, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(gain > 0., CPL_ERROR_ILLEGAL_INPUT);
+    cpl_ensure_code(ron > 0., CPL_ERROR_ILLEGAL_INPUT);
+
+    *ima_errs = cpl_image_duplicate(ima_data);
+    /* set negative values (= zero measurable electrons) to read out noise */
+    cpl_image_threshold(*ima_errs, 0., INFINITY, ron, ron);
+
+    /* err_ADU = sqrt(counts/gain + ron * ron)*/
+
+    cpl_image_divide_scalar(*ima_errs, gain);
+    cpl_image_add_scalar(*ima_errs, ron * ron);
+    cpl_image_power(*ima_errs, 0.5);
+
+    return cpl_error_get_code();
+}
+
+
+
+static cpl_error_code
+xsh_detmon_lg_reduce_set(int i, cpl_frameset * frameset,
+                     int nsets,
+                     const char              * tag_on,
+                     const char              * tag_off,
+                     const char              * recipe_name,
+                     const char              * pipeline_name,
+                     const char              * pafregexp,
+                     const cpl_propertylist  * pro_lintbl,
+                     const cpl_propertylist  * pro_gaintbl,
+                     const cpl_propertylist  * pro_coeffscube,
+                     const cpl_propertylist  * pro_bpm,
+                     const cpl_propertylist  * pro_corr,
+                     const cpl_propertylist  * pro_diff,
+                     const char              * package,
+                     int                    (* load_fset)
+                     (const cpl_frameset *, cpl_type, cpl_imagelist *),
+                     const cpl_boolean         opt_nir,
+                     const cpl_parameterlist * parlist,
+                     cpl_size* selection
+                    );
 static double irplib_compute_err(double gain, double ron, double photon_noise);
 /* wrapper function for different cpl versions*/
-static cpl_error_code xsh_detmon_lg_dfs_save_imagelist(
-		cpl_frameset * frameset,
-        const cpl_parameterlist * parlist,
-        const cpl_frameset *usedframes,
-        const cpl_imagelist *coeffs,
-        const char *recipe_name,
-        const cpl_propertylist *mypro_coeffscube,
-        const char * package,
-        const char * name_o);
+static cpl_error_code
+xsh_detmon_lg_dfs_save_imagelist(cpl_frameset * frameset,
+                             const cpl_parameterlist * parlist,
+                             const cpl_frameset *usedframes,
+                             const cpl_imagelist *coeffs,
+                             const char *recipe_name,
+                             const cpl_propertylist *mypro_coeffscube,
+                             const char * package,
+                             const char * name_o);
 
 /*--------------------------------------------------------------------------*/
-static cpl_error_code xsh_detmon_lg_reduce_set(int i, cpl_frameset * frameset, int nsets,
-        const char              * tag_on,
-        const char              * tag_off,
-        const char              * recipe_name,
-        const char              * pipeline_name,
-        const char              * pafregexp,
-        const cpl_propertylist  * pro_lintbl,
-        const cpl_propertylist  * pro_gaintbl,
-        const cpl_propertylist  * pro_coeffscube,
-        const cpl_propertylist  * pro_bpm,
-        const cpl_propertylist  * pro_corr,
-        const cpl_propertylist  * pro_diff,
-        const char              * package,
-        int                    (* load_fset)
-			(const cpl_frameset *, cpl_type, cpl_imagelist *),
-        const cpl_boolean         opt_nir,
-        const cpl_parameterlist * parlist,
-        cpl_size* selection
-        )
-{
-	int  j;
-	int nexts = detmon_lg_config.nb_extensions;
-
-	double* exptime_on = 0;
-	double* exptime_off = 0;
-	int* index_on = 0;
-	int* index_off = 0;
-	cpl_frameset  * cur_fset = NULL;
-	cpl_frameset* cur_fset_on = 0;
-	cpl_frameset* cur_fset_off = 0;
-
-	/* Reduce data set nb i */
-	cur_fset =
-           (nsets == 1) ? /* would be better (selection == 0) ? */
-		cpl_frameset_duplicate(frameset) : cpl_frameset_extract(frameset, selection, i);
-
-
-	skip_if(cur_fset == NULL);
-
-	/* Split input frameset into 2 sub-framesets for ON and OFF frames */
-	cur_fset_on  = cpl_frameset_new();
-	cur_fset_off = cpl_frameset_new();
-	cpl_msg_info(cpl_func, "Splitting into ON and OFF sub-framesets");
-	skip_if (xsh_detmon_lg_split_onoff(cur_fset,
-						  cur_fset_on, cur_fset_off,
-						  tag_on, tag_off /*, opt_nir*/));
-	if (cpl_frameset_get_size(cur_fset_on)  == 0)
-	{
-		cpl_msg_error(cpl_func, "No lamp frames in input");
-		skip_if(1);
-	}
+static void irplib_free(char** pointer){
 
-	if (cpl_frameset_get_size(cur_fset_off)  == 0)
-	{
-		cpl_msg_error(cpl_func, "No dark / bias frames in input");
-		skip_if(1);
-	}
-	cpl_msg_info(cpl_func, "found on-frames[%" CPL_SIZE_FORMAT "] off-frames[%" CPL_SIZE_FORMAT "]",cpl_frameset_get_size(cur_fset_on), cpl_frameset_get_size(cur_fset_off));
-	/* Labelise each sub-frameset according to DIT values */
-/*		selection_on = cpl_frameset_labelise(cur_fset_on,
-						 xsh_detmon_lg_compare_pairs,
-						 &nsets_on);
+    if(pointer && *pointer) {
+        cpl_free(*pointer);
+        *pointer=NULL;
+    }
+}
 
-	skip_if (selection_on == NULL);
-*/
-	exptime_on = cpl_malloc(sizeof(double)*cpl_frameset_get_size(cur_fset_on));
-	exptime_off = cpl_malloc(sizeof(double)*cpl_frameset_get_size(cur_fset_off));
-
-	index_on = cpl_malloc(sizeof(int)*cpl_frameset_get_size(cur_fset_on));
-	index_off = cpl_malloc(sizeof(int)*cpl_frameset_get_size(cur_fset_off));
-	irplib_frameset_sort(cur_fset_on, index_on, exptime_on);
-	irplib_frameset_sort(cur_fset_off, index_off, exptime_off);
-/*	for (j = 0; j < cpl_frameset_get_size(cur_fset_on); j++)
-	{
-		cpl_msg_info(cpl_func, "%d: \t %d \t %f", j , index_on[j], exptime_on[j]);
-	}
-	*/
-	/* TODO Check that each ON frame pair has a corresponding OFF frame*/
+static cpl_error_code
+xsh_detmon_lg_reduce_set(int i, cpl_frameset * frameset, int nsets,
+                     const char              * tag_on,
+                     const char              * tag_off,
+                     const char              * recipe_name,
+                     const char              * pipeline_name,
+                     const char              * pafregexp,
+                     const cpl_propertylist  * pro_lintbl,
+                     const cpl_propertylist  * pro_gaintbl,
+                     const cpl_propertylist  * pro_coeffscube,
+                     const cpl_propertylist  * pro_bpm,
+                     const cpl_propertylist  * pro_corr,
+                     const cpl_propertylist  * pro_diff,
+                     const char              * package,
+                     int                    (* load_fset)
+                     (const cpl_frameset *, cpl_type, cpl_imagelist *),
+                     const cpl_boolean         opt_nir,
+                     const cpl_parameterlist * parlist,
+                     cpl_size* selection
+                    )
+{
+    int  j;
+    int nexts = xsh_detmon_lg_config.nb_extensions;
+
+    double* exptime_on = 0;
+    double* exptime_off = 0;
+    int* index_on = 0;
+    int* index_off = 0;
+    cpl_frameset  * cur_fset = NULL;
+    cpl_frameset* cur_fset_on = 0;
+    cpl_frameset* cur_fset_off = 0;
+
+    /* Reduce data set nb i */
+    cur_fset =
+        (nsets == 1) ? /* would be better (selection == 0) ? */
+        cpl_frameset_duplicate(frameset) : cpl_frameset_extract(frameset, selection, i);
+
+
+    skip_if(cur_fset == NULL);
+
+    /* Split input frameset into 2 sub-framesets for ON and OFF frames */
+    cur_fset_on  = cpl_frameset_new();
+    cur_fset_off = cpl_frameset_new();
+    cpl_msg_info(cpl_func, "Splitting into ON and OFF sub-framesets");
+    skip_if (xsh_detmon_lg_split_onoff(cur_fset,
+                                   cur_fset_on, cur_fset_off,
+                                   tag_on, tag_off /*, opt_nir*/));
+    if (cpl_frameset_get_size(cur_fset_on)  == 0)
+    {
+        cpl_msg_error(cpl_func, "No lamp frames in input");
+        skip_if(1);
+    }
 
-	/* Test if they have equal nb of labels */
-/*		if (!detmon_lg_config.collapse) {
-		skip_if(nsets_on != nsets_off);
-	}
-*/
-	skip_if(xsh_detmon_check_order(exptime_on, cpl_frameset_get_size(cur_fset_on), detmon_lg_config.tolerance, detmon_lg_config.order));
+    if (cpl_frameset_get_size(cur_fset_off)  == 0)
+    {
+        cpl_msg_error(cpl_func, "No dark / bias frames in input");
+        skip_if(1);
+    }
+    cpl_msg_info(cpl_func, "found on-frames[%" CPL_SIZE_FORMAT "] off-frames[%" CPL_SIZE_FORMAT "]",cpl_frameset_get_size(cur_fset_on), cpl_frameset_get_size(cur_fset_off));
+    /* Labelise each sub-frameset according to DIT values */
+    /*		selection_on = cpl_frameset_labelise(cur_fset_on,
+                xsh_detmon_lg_compare_pairs,
+                &nsets_on);
+
+                skip_if (selection_on == NULL);
+                */
+    exptime_on = cpl_malloc(sizeof(double)*cpl_frameset_get_size(cur_fset_on));
+    exptime_off = cpl_malloc(sizeof(double)*cpl_frameset_get_size(cur_fset_off));
+
+    index_on = cpl_malloc(sizeof(int)*cpl_frameset_get_size(cur_fset_on));
+    index_off = cpl_malloc(sizeof(int)*cpl_frameset_get_size(cur_fset_off));
+    irplib_frameset_sort(cur_fset_on, index_on, exptime_on);
+    irplib_frameset_sort(cur_fset_off, index_off, exptime_off);
+    /*	for (j = 0; j < cpl_frameset_get_size(cur_fset_on); j++)
+        {
+        cpl_msg_info(cpl_func, "%d: \t %d \t %f", j , index_on[j], exptime_on[j]);
+        }
+        */
+    /* TODO Check that each ON frame pair has a corresponding OFF frame*/
 
-	if(detmon_lg_config.exts >= 0)
-	{
-		/*
-		 * In the optical domain, the first 2 frames
-		 * are used apart from the pairs.
-		 */
+    /* Test if they have equal nb of labels */
+    /*		if (!xsh_detmon_lg_config.collapse) {
+                skip_if(nsets_on != nsets_off);
+                }
+                */
+    skip_if(xsh_detmon_check_order(exptime_on, cpl_frameset_get_size(cur_fset_on), xsh_detmon_lg_config.tolerance, xsh_detmon_lg_config.order));
+
+    if(xsh_detmon_lg_config.exts >= 0)
+    {
+        /*
+         * In the optical domain, the first 2 frames
+         * are used apart from the pairs.
+         */
 
 #if 0
-		if (detmon_lg_config.lamp_ok) {
-		skip_if(xsh_detmon_opt_lampcr(cur_fset, 0));
-		}
+        if (xsh_detmon_lg_config.lamp_ok) {
+            skip_if(xsh_detmon_opt_lampcr(cur_fset, 0));
+        }
 #endif
-		skip_if(xsh_detmon_lg_core(cur_fset_on, cur_fset_off,
-					      index_on,
-					      index_off,
-					      exptime_on,
-					      exptime_off,
-					      detmon_lg_config.exts,
-					      i,
-			    recipe_name, pipeline_name, pafregexp,
-			    pro_lintbl, pro_gaintbl, pro_coeffscube, pro_bpm, pro_corr, pro_diff,
-			    package, load_fset, nsets, opt_nir, frameset, parlist, cur_fset));
-	} else {
-		for(j = 1; j <= nexts; j++) {
-		/*
-		 * In the optical domain, the first 2 frames
-		 * are used apart from the pairs.
-		 */
+        skip_if(xsh_detmon_lg_core(cur_fset_on, cur_fset_off,
+                               index_on,
+                               index_off,
+                               exptime_on,
+                               exptime_off,
+                               xsh_detmon_lg_config.exts,
+                               i,
+                               recipe_name, pipeline_name, pafregexp,
+                               pro_lintbl, pro_gaintbl, pro_coeffscube, pro_bpm, pro_corr, pro_diff,
+                               package, load_fset, nsets, opt_nir, frameset, parlist, cur_fset));
+    } else {
+        for(j = 1; j <= nexts; j++) {
+            /*
+             * In the optical domain, the first 2 frames
+             * are used apart from the pairs.
+             */
 
 #if 0
-		if (detmon_lg_config.lamp_ok) {
-			skip_if(xsh_detmon_opt_lampcr(cur_fset, j));
-		}
+            if (xsh_detmon_lg_config.lamp_ok) {
+                skip_if(xsh_detmon_opt_lampcr(cur_fset, j));
+            }
 #endif
 
-		skip_if(xsh_detmon_lg_core(cur_fset_on, cur_fset_off,
-					      index_on,
-					      index_off,
-					      exptime_on,
-					      exptime_off,
-						  j, i,  recipe_name, pipeline_name,pafregexp,  pro_lintbl, pro_gaintbl, pro_coeffscube, pro_bpm, pro_corr, pro_diff, package, load_fset, nsets, opt_nir, frameset, parlist, cur_fset));
-		}
-	}
-	end_skip;
-
-	cpl_frameset_delete(cur_fset);
-	cpl_frameset_delete(cur_fset_on);
-	cpl_frameset_delete(cur_fset_off);
-	cpl_free(index_on);
-	cpl_free(index_off);
-	cpl_free(exptime_on);
-	cpl_free(exptime_off);
+            skip_if(xsh_detmon_lg_core(cur_fset_on, cur_fset_off,
+                                   index_on,
+                                   index_off,
+                                   exptime_on,
+                                   exptime_off,
+                                   j, i,  recipe_name, pipeline_name,pafregexp,  pro_lintbl, pro_gaintbl, pro_coeffscube, pro_bpm, pro_corr, pro_diff, package, load_fset, nsets, opt_nir, frameset, parlist, cur_fset));
+        }
+    }
+    end_skip;
+
+    cpl_frameset_delete(cur_fset);
+    cpl_frameset_delete(cur_fset_on);
+    cpl_frameset_delete(cur_fset_off);
+    cpl_free(index_on);
+    cpl_free(index_off);
+    cpl_free(exptime_on);
+    cpl_free(exptime_off);
     return cpl_error_get_code();
 }
+
 /*
  * @brief  Reduce linearity and gain in the IR domain
  * @param  parlist              List of required parameters
@@ -720,29 +800,29 @@ static cpl_error_code xsh_detmon_lg_reduce_set(int i, cpl_frameset * frameset, i
 
 cpl_error_code
 xsh_detmon_lg(cpl_frameset            * frameset,
-                 const cpl_parameterlist * parlist,
-                 const char              * tag_on,
-                 const char              * tag_off,
-                 const char              * recipe_name,
-                 const char              * pipeline_name,
-                 const char              * pafregexp,
-                 const cpl_propertylist  * pro_lintbl,
-                 const cpl_propertylist  * pro_gaintbl,
-                 const cpl_propertylist  * pro_coeffscube,
-                 const cpl_propertylist  * pro_bpm,
-                 const cpl_propertylist  * pro_corr,
-                 const cpl_propertylist  * pro_diff,
-                 const char              * package,
-                 int                    (* compare) (const cpl_frame *,
-						     const cpl_frame *),
-		 int                    (* load_fset) (const cpl_frameset *,
-						       cpl_type,
-		                                       cpl_imagelist *),
-                 const cpl_boolean         opt_nir)
+          const cpl_parameterlist * parlist,
+          const char              * tag_on,
+          const char              * tag_off,
+          const char              * recipe_name,
+          const char              * pipeline_name,
+          const char              * pafregexp,
+          const cpl_propertylist  * pro_lintbl,
+          const cpl_propertylist  * pro_gaintbl,
+          const cpl_propertylist  * pro_coeffscube,
+          const cpl_propertylist  * pro_bpm,
+          const cpl_propertylist  * pro_corr,
+          const cpl_propertylist  * pro_diff,
+          const char              * package,
+          int                    (* compare) (const cpl_frame *,
+                                              const cpl_frame *),
+          int                    (* load_fset) (const cpl_frameset *,
+                                                cpl_type,
+                                                cpl_imagelist *),
+          const cpl_boolean         opt_nir)
 {
+    cpl_errorstate cleanstate = cpl_errorstate_get();
     cpl_size              nsets;
     cpl_size            * selection = NULL;
-    int              i;
     cpl_frame      * first     = NULL;
     cpl_image      * reference = NULL;
 
@@ -781,7 +861,7 @@ xsh_detmon_lg(cpl_frameset            * frameset,
      */
 
     skip_if (xsh_detmon_lg_retrieve_parlist(pipeline_name, recipe_name,
-					       parlist, opt_nir));
+                                        parlist, opt_nir));
 
     /*
      * Retrieve first image to check some parameters' values and
@@ -789,29 +869,47 @@ xsh_detmon_lg(cpl_frameset            * frameset,
      */
 
     first = cpl_frameset_get_first(frameset);
-    irplib_ensure (first != NULL, CPL_ERROR_ILLEGAL_INPUT, "Empty data set!");
-
-    detmon_lg_config.load_fset = load_fset;
-    detmon_lg_config.load_fset_wrp = load_fset ? irplib_load_fset_wrp_ext : irplib_load_fset_wrp;
-
-
-    if (detmon_lg_config.exts < 0) {
-        reference = cpl_image_load(cpl_frame_get_filename(first),
-                                   CPL_TYPE_FLOAT, 0, 1);
+    irplib_ensure (first != NULL, CPL_ERROR_ILLEGAL_INPUT, "Empty data set! Provide %s and %s input frames",tag_on,tag_off);
+
+    xsh_detmon_lg_config.load_fset = load_fset;
+    xsh_detmon_lg_config.load_fset_wrp = load_fset ? irplib_load_fset_wrp_ext : irplib_load_fset_wrp;
+
+
+    xsh_detmon_lg_config.nb_extensions = 1;
+    if (xsh_detmon_lg_config.exts < 0) {
+        int i = 1;
+        xsh_detmon_lg_config.nb_extensions = cpl_frame_get_nextensions(first);
+        while (reference == NULL && i <= xsh_detmon_lg_config.nb_extensions) {
+            reference = cpl_image_load(cpl_frame_get_filename(first),
+                                       CPL_TYPE_FLOAT, 0, i);
+            if (reference == NULL) {
+                cpl_msg_warning(cpl_func, "Extension %d empty, skipping", i);
+                cpl_errorstate_set(cleanstate);
+            }
+            i++;
+        }
+        cpl_errorstate_set(cleanstate);
+        irplib_ensure (reference != NULL, CPL_ERROR_ILLEGAL_INPUT,
+                       "No data found in any extension");
+        cpl_msg_info(cpl_func, "Using extension %d as reference", i - 1);
     } else {
-	if (load_fset != NULL) {
-	    cpl_frameset * new = cpl_frameset_new();
-	    cpl_imagelist * p = cpl_imagelist_new();
-	    cpl_frameset_insert(new, cpl_frame_duplicate(first));
-	    (*load_fset)(new, CPL_TYPE_FLOAT, p);
-	    reference = cpl_image_duplicate(cpl_imagelist_get(p, 0));
-	    cpl_imagelist_delete(p);
-	    cpl_frameset_delete(new);
-	} else {
-           cpl_msg_info(cpl_func,"name=%s",cpl_frame_get_filename(first));
-	    reference = cpl_image_load(cpl_frame_get_filename(first),
-				       CPL_TYPE_FLOAT, 0, detmon_lg_config.exts);
-	}
+        if (load_fset != NULL) {
+            cpl_frameset * new = cpl_frameset_new();
+            cpl_imagelist * p = cpl_imagelist_new();
+            cpl_frameset_insert(new, cpl_frame_duplicate(first));
+            (*load_fset)(new, CPL_TYPE_FLOAT, p);
+            reference = cpl_image_duplicate(cpl_imagelist_get(p, 0));
+            cpl_imagelist_delete(p);
+            cpl_frameset_delete(new);
+        } else {
+            cpl_msg_info(cpl_func,"name=%s",cpl_frame_get_filename(first));
+            reference = cpl_image_load(cpl_frame_get_filename(first),
+                                       CPL_TYPE_FLOAT, 0, xsh_detmon_lg_config.exts);
+        }
+        cpl_errorstate_set(cleanstate);
+        irplib_ensure (reference != NULL, CPL_ERROR_ILLEGAL_INPUT,
+                       "No data found in requested extension %d",
+                       xsh_detmon_lg_config.exts);
     }
     skip_if (reference == NULL);
 
@@ -832,45 +930,39 @@ xsh_detmon_lg(cpl_frameset            * frameset,
         skip_if (selection == NULL);
     }
 
-    /* Get the nb of extensions */
-    detmon_lg_config.nb_extensions = 1;
-    if (detmon_lg_config.exts < 0)
-    {
-    	detmon_lg_config.nb_extensions = cpl_frame_get_nextensions(first);
-    }
     /* Extract settings and reduce each of them */
-    for(i = 0; i < nsets; i++)
+    for(int i = 0; i < nsets; i++)
     {
-    	int fr_size = cpl_frameset_get_size(frameset);
-    	int fr_size_new = 0;
-    	cpl_msg_info(cpl_func, "Reduce data set nb %d out of %" 
-                     CPL_SIZE_FORMAT "",i + 1, nsets);
-    	skip_if(xsh_detmon_lg_reduce_set(i, frameset, nsets, tag_on, tag_off,
-    	        recipe_name,
-    	        pipeline_name,
-    	        pafregexp,
-                pro_lintbl,
-                pro_gaintbl,
-                pro_coeffscube,
-                pro_bpm,
-                pro_corr,
-                pro_diff,
-                package,
-                load_fset,
-                opt_nir,
-                parlist,
-                selection));
-    	fr_size_new = cpl_frameset_get_size(frameset);
-    	/* the size of the frameset could be changed during the xsh_detmon_lg_reduce_set call
-    	 * so the size of the selection array should be adjusted with some fake values,
-    	 * to avoid reading of the not allocated memory
-    	 * see DFS08110 for the error description
-    	 * */
-    	if (fr_size_new > fr_size)
-    	{
-    		selection = cpl_realloc(selection, fr_size_new  * sizeof(selection[0]));
-    		memset(selection + fr_size,  -1, (fr_size_new - fr_size) * sizeof(selection[0]));
-    	}
+        int fr_size = cpl_frameset_get_size(frameset);
+        int fr_size_new = 0;
+        cpl_msg_info(cpl_func, "Reduce data set nb %d out of %" CPL_SIZE_FORMAT "",
+                     i + 1, nsets);
+        skip_if(xsh_detmon_lg_reduce_set(i, frameset, nsets, tag_on, tag_off,
+                                     recipe_name,
+                                     pipeline_name,
+                                     pafregexp,
+                                     pro_lintbl,
+                                     pro_gaintbl,
+                                     pro_coeffscube,
+                                     pro_bpm,
+                                     pro_corr,
+                                     pro_diff,
+                                     package,
+                                     load_fset,
+                                     opt_nir,
+                                     parlist,
+                                     selection));
+        fr_size_new = cpl_frameset_get_size(frameset);
+        /* the size of the frameset could be changed during the xsh_detmon_lg_reduce_set call
+         * so the size of the selection array should be adjusted with some fake values,
+         * to avoid reading of the not allocated memory
+         * see DFS08110 for the error description
+         * */
+        if (fr_size_new > fr_size)
+        {
+            selection = cpl_realloc(selection, fr_size_new  * sizeof(selection[0]));
+            memset(selection + fr_size,  -1, (fr_size_new - fr_size) * sizeof(selection[0]));
+        }
     }
 
     end_skip;
@@ -919,113 +1011,120 @@ xsh_detmon_lg(cpl_frameset            * frameset,
 
 static cpl_error_code
 xsh_detmon_lg_core(cpl_frameset * cur_fset_on,
-		      cpl_frameset * cur_fset_off,
-		      int * index_on,
-			  int * index_off,
-			  double * exptime_on,
-			  double * exptime_off,
-		      int whichext,
-                      int whichset,
-		      const char              * recipe_name,
-		      const char              * pipeline_name,
-		      const char              * pafregexp,
-		      const cpl_propertylist  * pro_lintbl,
-		      const cpl_propertylist  * pro_gaintbl,
-		      const cpl_propertylist  * pro_coeffscube,
-		      const cpl_propertylist  * pro_bpm,
-		      const cpl_propertylist  * pro_corr,
-		      const cpl_propertylist  * pro_diff,
-		      const char              * package,
-		      int                    (* load_fset) (const cpl_frameset *,
-							    cpl_type,
-							    cpl_imagelist *),
-		      int nsets, cpl_boolean opt_nir,
-                      cpl_frameset * frameset, const cpl_parameterlist * parlist,
-                      cpl_frameset * cur_fset)
+               cpl_frameset * cur_fset_off,
+               int * index_on,
+               int * index_off,
+               double * exptime_on,
+               double * exptime_off,
+               int whichext,
+               int whichset,
+               const char              * recipe_name,
+               const char              * pipeline_name,
+               const char              * pafregexp,
+               const cpl_propertylist  * pro_lintbl,
+               const cpl_propertylist  * pro_gaintbl,
+               const cpl_propertylist  * pro_coeffscube,
+               const cpl_propertylist  * pro_bpm,
+               const cpl_propertylist  * pro_corr,
+               const cpl_propertylist  * pro_diff,
+               const char              * package,
+               int                    (* load_fset) (const cpl_frameset *,
+                                                     cpl_type,
+                                                     cpl_imagelist *),
+               int nsets, cpl_boolean opt_nir,
+               cpl_frameset * frameset, const cpl_parameterlist * parlist,
+               cpl_frameset * cur_fset)
 {
-    cpl_table        * gain_table      = cpl_table_new(cpl_frameset_get_size(cur_fset_on)/2);
-    cpl_table        * linear_table    = cpl_table_new(cpl_frameset_get_size(cur_fset_on)/2);
-    cpl_imagelist    * coeffs          = NULL;
-    cpl_image        * bpm             = NULL;
-    cpl_imagelist    * autocorr_images = NULL;
-    cpl_imagelist    * diff_flats      = NULL;
-    cpl_propertylist * gaint_qclist    = NULL;
-    cpl_propertylist * lint_qclist     = NULL;
-    cpl_propertylist * linc_qclist     = NULL;
-    cpl_propertylist * bpm_qclist      = NULL;
+    cpl_table * gain_table = cpl_table_new(
+                                           cpl_frameset_get_size(cur_fset_on) / 2);
+    cpl_table * linear_table = cpl_table_new(
+                                             cpl_frameset_get_size(cur_fset_on) / 2);
+    cpl_imagelist * coeffs = NULL;
+    cpl_image * bpm = NULL;
+    cpl_imagelist * autocorr_images = NULL;
+    cpl_imagelist * diff_flats = NULL;
+    cpl_propertylist * gaint_qclist = NULL;
+    cpl_propertylist * lint_qclist = NULL;
+    cpl_propertylist * linc_qclist = NULL;
+    cpl_propertylist * bpm_qclist = NULL;
 
     int next_index_on = 0;
     int next_index_off = 0;
 
-
     /* Reduce extension nb i */
-    cpl_msg_info(cpl_func, "Reduce extension nb %d ",
-		 whichext);
+    cpl_msg_info(cpl_func, "Reduce extension nb %d ", whichext);
 
     /* FIXME: All other memory objects in use should be
        initialised here (except coeffs which can not be) */
-    if (detmon_lg_config.intermediate) {
-	autocorr_images = cpl_imagelist_new();
-	diff_flats      = cpl_imagelist_new();
+    if (xsh_detmon_lg_config.intermediate) {
+        autocorr_images = cpl_imagelist_new();
+        diff_flats = cpl_imagelist_new();
     }
 
     gaint_qclist = cpl_propertylist_new();
-    lint_qclist  = cpl_propertylist_new();
-    linc_qclist  = cpl_propertylist_new();
-    bpm_qclist   = cpl_propertylist_new();
+    lint_qclist = cpl_propertylist_new();
+    linc_qclist = cpl_propertylist_new();
+    bpm_qclist = cpl_propertylist_new();
 
     /* Reduction done here */
     cpl_msg_info(cpl_func, "Starting data reduction");
-    skip_if(xsh_detmon_lg_reduce(cur_fset_on, cur_fset_off,
-				    index_on, index_off, exptime_on, exptime_off,
-				    &next_index_on, &next_index_off,
-				    &coeffs, gain_table,
-				    linear_table, &bpm, autocorr_images,
-				    diff_flats, gaint_qclist, lint_qclist,
-				    linc_qclist, bpm_qclist, load_fset,
-				    opt_nir, whichext));
+    if (xsh_detmon_lg_reduce(cur_fset_on, cur_fset_off,
+                             index_on, index_off, exptime_on, exptime_off,
+                             &next_index_on, &next_index_off,
+                             &coeffs, gain_table,
+                             linear_table, &bpm, autocorr_images,
+                             diff_flats, gaint_qclist, lint_qclist,
+                             linc_qclist, bpm_qclist, load_fset,
+                             opt_nir, whichext) == CPL_ERROR_CONTINUE) {
+        cpl_msg_info(cpl_func, "Empty extension %d", whichext);
+    }
 
     /* Save the products for each setting */
     cpl_msg_info(cpl_func, "Saving the products");
-    if(nsets == 1) {
-	skip_if(xsh_detmon_lg_save(parlist, frameset, recipe_name,
-				      pipeline_name, pafregexp,
-				      pro_lintbl, pro_gaintbl,
-				      pro_coeffscube, pro_bpm,
-				      pro_corr, pro_diff, package,
-				      coeffs, gain_table, linear_table,
-				      bpm, autocorr_images, diff_flats,
-				      gaint_qclist, lint_qclist, linc_qclist,
-				      bpm_qclist, 0, 0, cur_fset, whichext));
+    if (nsets == 1) {
+        skip_if(
+                xsh_detmon_lg_save(parlist, frameset, recipe_name,
+                               pipeline_name, pafregexp,
+                               pro_lintbl, pro_gaintbl,
+                               pro_coeffscube, pro_bpm,
+                               pro_corr, pro_diff, package,
+                               coeffs, gain_table, linear_table,
+                               bpm, autocorr_images, diff_flats,
+                               gaint_qclist, lint_qclist, linc_qclist,
+                               bpm_qclist, 0, 0, cur_fset, whichext));
     } else {
-	skip_if(xsh_detmon_lg_save(parlist, frameset, recipe_name,
-				      pipeline_name, pafregexp,
-				      pro_lintbl, pro_gaintbl,
-				      pro_coeffscube, pro_bpm,
-				      pro_corr, pro_diff, package,
-				      coeffs, gain_table, linear_table,
-				      bpm, autocorr_images, diff_flats,
-				      gaint_qclist, lint_qclist, linc_qclist,
-				      bpm_qclist, 1, whichset+ 1, cur_fset,
-				      whichext));
+        skip_if(
+                xsh_detmon_lg_save(parlist, frameset, recipe_name,
+                               pipeline_name, pafregexp,
+                               pro_lintbl, pro_gaintbl,
+                               pro_coeffscube, pro_bpm,
+                               pro_corr, pro_diff, package,
+                               coeffs, gain_table, linear_table,
+                               bpm, autocorr_images, diff_flats,
+                               gaint_qclist, lint_qclist, linc_qclist,
+                               bpm_qclist, 1, whichset+ 1, cur_fset,
+                               whichext));
     }
 
     end_skip;
 
     /* Free for each extension */
+
     cpl_table_delete(gain_table);
     cpl_table_delete(linear_table);
     cpl_imagelist_delete(coeffs);
     cpl_propertylist_delete(gaint_qclist);
     cpl_propertylist_delete(lint_qclist);
     cpl_propertylist_delete(linc_qclist);
-    cpl_propertylist_delete(bpm_qclist);
+    if(bpm_qclist != NULL) cpl_propertylist_delete(bpm_qclist);
     cpl_image_delete(bpm);
     cpl_imagelist_delete(autocorr_images);
     cpl_imagelist_delete(diff_flats);
 
     return cpl_error_get_code();
 }
+
+
 /*--------------------------------------------------------------------------*/
 
 /*
@@ -1048,22 +1147,16 @@ xsh_detmon_lg_core(cpl_frameset * cur_fset_on,
 
 cpl_image              *
 xsh_detmon_image_correlate(const cpl_image * image1,
-                              const cpl_image * image2,
-                              const int m, const int n)
+                       const cpl_image * image2,
+                       const int m, const int n)
 {
     cpl_image              *image1_padded = NULL;
     cpl_image              *image2_padded = NULL;
     int                     nx, ny;
     int                     nx2, ny2;
-    int                     i,j;
 
-    cpl_image              *corr_image = NULL;
     cpl_image              *corr_image_window = NULL;
-    cpl_image              *reorganised= NULL;
-    cpl_image              *image= NULL;
 
-    cpl_image* image_ri_inv = NULL;
-    cpl_image* image_in_inv = NULL;
     cpl_image* image_ri1 = NULL;
     cpl_image* image_ri2 = NULL;
     cpl_error_code err = CPL_ERROR_NONE;
@@ -1101,94 +1194,99 @@ xsh_detmon_image_correlate(const cpl_image * image1,
     cpl_fft_image(image_ri1, image1_padded, CPL_FFT_FORWARD);
     cpl_fft_image(image_ri2, image2_padded, CPL_FFT_FORWARD);
     err = cpl_error_get_code();
-	cpl_image_delete(image1_padded);
-	image1_padded = NULL;
-	cpl_image_delete(image2_padded);
-	image2_padded = NULL;
+    cpl_image_delete(image1_padded);
+    image1_padded = NULL;
+    cpl_image_delete(image2_padded);
+    image2_padded = NULL;
     if (err == CPL_ERROR_NONE)
     {
-    /* Cleanup resources */
-		image_ri_inv = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);
-		image_in_inv = cpl_image_new(nx, ny, CPL_TYPE_FLOAT_COMPLEX);
-
-		for (i = 1; i <= nx; i++)
-		{
-			for (j = 1; j <= ny; j++)
-			{
-				int rej = 0;
-				double complex value1, value2, value;
-				value1 = cpl_image_get_complex(image_ri1, i, j, &rej);
-				value2 = cpl_image_get_complex(image_ri2, i, j, &rej);;
-				value = conj(value1) * value2;
-				cpl_image_set_complex(image_in_inv, i, j, value);
-			}
-		}
-		cpl_image_delete(image_ri1);
-		image_ri1 = NULL;
-		cpl_image_delete(image_ri2);
-		image_ri2 = NULL;
-
-		err = cpl_error_get_code();
-		if (err == CPL_ERROR_NONE)
-		{
-
-		/* Actually perform the FFT */
-		cpl_fft_image(image_ri_inv, image_in_inv,CPL_FFT_BACKWARD);
-		cpl_image_delete(image_in_inv);
-
-		/* Get the module of the inversed signal */
-		corr_image = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);
-		for (i = 1; i <= nx; i++)
-		{
-			for (j = 1; j <= ny; j++)
-			{
-				int rej = 0;
-				double value =0;
-				value = cpl_image_get(image_ri_inv, i, j, &rej);
-				cpl_image_set(corr_image, i, j, value);
-			}
-		}
-		cpl_image_delete(image_ri_inv);
-		err = cpl_error_get_code();
-		if (err == CPL_ERROR_NONE)
-		{
-		/* Reorganise the pixels to the output */
-			reorganised = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);
-
-			image = cpl_image_extract(corr_image, nx / 2 + 1, 1, nx, ny);
-			cpl_image_copy(reorganised, image, 1, 1);
-			cpl_image_delete(image);
-			image = cpl_image_extract(corr_image, 1, 1, nx / 2, ny);
-			cpl_image_copy(reorganised, image, nx / 2 + 1, 1);
-			cpl_image_delete(image);
-
-			cpl_image_delete(corr_image);
-
-			corr_image = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);
-			image = cpl_image_extract(reorganised, 1, ny / 2 + 1, nx, ny);
-			cpl_image_copy(corr_image, image, 1, 1);
-			cpl_image_delete(image);
-
-			image = cpl_image_extract(reorganised, 1, 1, nx, ny / 2);
-			cpl_image_copy(corr_image, image, 1, ny / 2 + 1);
-			cpl_image_delete(image);
-			/* Extract a window with the desired shifts */
-			corr_image_window = cpl_image_extract(corr_image,
-												  nx / 2 + 1 - m,
-												  ny / 2 + 1 - n,
-												  nx / 2 + 1 + m, ny / 2 + 1 + n);
-			}
-		/* Free and return */
-
-		}
-		cpl_image_delete(reorganised);
-		cpl_image_delete(corr_image);
-
-		if(cpl_image_divide_scalar(corr_image_window,
-								   cpl_image_get_max(corr_image_window))) {
-			cpl_image_delete(corr_image_window);
-			return NULL;
-		}
+        /* Cleanup resources */
+        cpl_image * corr_image = NULL;
+        cpl_image * reorganised= NULL;
+        cpl_image * image_ri_inv = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);
+        cpl_image * image_in_inv = cpl_image_new(nx, ny,
+                                                 CPL_TYPE_FLOAT_COMPLEX);
+        int i,j;
+
+        for (i = 1; i <= nx; i++)
+        {
+            for (j = 1; j <= ny; j++)
+            {
+                int rej = 0;
+                double complex value1, value2, value;
+                value1 = cpl_image_get_complex(image_ri1, i, j, &rej);
+                value2 = cpl_image_get_complex(image_ri2, i, j, &rej);;
+                value = conj(value1) * value2;
+                cpl_image_set_complex(image_in_inv, i, j, value);
+            }
+        }
+        cpl_image_delete(image_ri1);
+        image_ri1 = NULL;
+        cpl_image_delete(image_ri2);
+        image_ri2 = NULL;
+
+        err = cpl_error_get_code();
+        if (err == CPL_ERROR_NONE)
+        {
+
+            /* Actually perform the FFT */
+            cpl_fft_image(image_ri_inv, image_in_inv,CPL_FFT_BACKWARD);
+            cpl_image_delete(image_in_inv);
+
+            /* Get the module of the inversed signal */
+            corr_image = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);
+            for (i = 1; i <= nx; i++)
+            {
+                for (j = 1; j <= ny; j++)
+                {
+                    int rej = 0;
+                    double value =0;
+                    value = cpl_image_get(image_ri_inv, i, j, &rej);
+                    cpl_image_set(corr_image, i, j, value);
+                }
+            }
+            cpl_image_delete(image_ri_inv);
+            err = cpl_error_get_code();
+            if (err == CPL_ERROR_NONE)
+            {
+                /* Reorganise the pixels to the output */
+                cpl_image * image =
+                    cpl_image_extract(corr_image, nx / 2 + 1, 1, nx, ny);
+                reorganised = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);
+
+                cpl_image_copy(reorganised, image, 1, 1);
+                cpl_image_delete(image);
+                image = cpl_image_extract(corr_image, 1, 1, nx / 2, ny);
+                cpl_image_copy(reorganised, image, nx / 2 + 1, 1);
+                cpl_image_delete(image);
+
+                cpl_image_delete(corr_image);
+
+                corr_image = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);
+                image = cpl_image_extract(reorganised, 1, ny / 2 + 1, nx, ny);
+                cpl_image_copy(corr_image, image, 1, 1);
+                cpl_image_delete(image);
+
+                image = cpl_image_extract(reorganised, 1, 1, nx, ny / 2);
+                cpl_image_copy(corr_image, image, 1, ny / 2 + 1);
+                cpl_image_delete(image);
+                /* Extract a window with the desired shifts */
+                corr_image_window = cpl_image_extract(corr_image,
+                                                      nx / 2 + 1 - m,
+                                                      ny / 2 + 1 - n,
+                                                      nx / 2 + 1 + m, ny / 2 + 1 + n);
+            }
+            /* Free and return */
+
+        }
+        cpl_image_delete(reorganised);
+        cpl_image_delete(corr_image);
+
+        if(cpl_image_divide_scalar(corr_image_window,
+                                   cpl_image_get_max(corr_image_window))) {
+            cpl_image_delete(corr_image_window);
+            return NULL;
+        }
     }
     cpl_image_delete (image_ri1);
     cpl_image_delete (image_ri2);
@@ -1218,7 +1316,7 @@ xsh_detmon_image_correlate(const cpl_image * image1,
 
 cpl_image              *
 xsh_detmon_autocorrelate(const cpl_image * input2, const int m,
-                            const int n)
+                     const int n)
 {
     cpl_image              *im_re = NULL;
     cpl_image              *im_im = NULL;
@@ -1358,54 +1456,54 @@ xsh_detmon_autocorrelate(const cpl_image * input2, const int m,
 /*---------------------------------------------------------------------------*/
 cpl_error_code
 xsh_detmon_lg_fill_parlist_nir_default(cpl_parameterlist * parlist,
-                                  const char *recipe_name,
-                                  const char *pipeline_name)
+                                   const char *recipe_name,
+                                   const char *pipeline_name)
 {
     const cpl_error_code error =
-	xsh_detmon_lg_fill_parlist(parlist, recipe_name, pipeline_name,
-			      "PTC", /* --method */
-			      3,   /* --order         */
-                              3.,        /* --kappa         */
-                              5,       /* --niter         */
-                              -1,       /* --llx           */
-                              -1,       /* --lly           */
-                              -1,       /* --urx           */
-                              -1,       /* --ury           */
-                              10000,    /* --ref_level     */
-                              "CPL_FALSE",      /* --intermediate  */
-                              "CPL_FALSE",      /* --autocorr      */
-                              "CPL_FALSE",      /* --collapse      */
-                              "CPL_TRUE",       /* --rescale       */
-				      "CPL_TRUE",/* --pix2pix */
-				      "CPL_FALSE", /* --bpmbin */
-                              -1,       /* --filter        */
-                              26,       /* --m             */
-                              26,       /* --n             */
-				      1e-3, /* --tolerance */
-			      "CPL_TRUE", /* --pafgen */
-				      recipe_name, /* --pafname */
-                              -1,       /* --llx1          */
-                              -1,       /* --lly1          */
-                              -1,       /* --urx1          */
-                              -1,       /* --ury1          */
-                              -1,       /* --llx2          */
-                              -1,       /* --lly2          */
-                              -1,       /* --urx2          */
-                              -1,       /* --ury2          */
-                              -1,       /* --llx3          */
-                              -1,       /* --lly3          */
-                              -1,       /* --urx3          */
-                              -1,       /* --ury3          */
-                              -1,       /* --llx4          */
-                              -1,       /* --lly4          */
-                              -1,       /* --urx4          */
-                              -1,       /* --ury4          */
-                              -1,       /* --llx5          */
-                              -1,       /* --lly5          */
-                              -1,       /* --urx5          */
-                              -1,       /* --ury5          */
-				      0,      /* --exts */
-	                      NIR);       /* This is to specify OPT params */
+        xsh_detmon_lg_fill_parlist(parlist, recipe_name, pipeline_name,
+                               "PTC", /* --method */
+                               3,   /* --order         */
+                               3.,        /* --kappa         */
+                               5,       /* --niter         */
+                               -1,       /* --llx           */
+                               -1,       /* --lly           */
+                               -1,       /* --urx           */
+                               -1,       /* --ury           */
+                               10000,    /* --ref_level     */
+                               "CPL_FALSE",      /* --intermediate  */
+                               "CPL_FALSE",      /* --autocorr      */
+                               "CPL_FALSE",      /* --collapse      */
+                               "CPL_TRUE",       /* --rescale       */
+                               "CPL_TRUE",/* --pix2pix */
+                               "CPL_FALSE", /* --bpmbin */
+                               -1,       /* --filter        */
+                               26,       /* --m             */
+                               26,       /* --n             */
+                               1e-3, /* --tolerance */
+                               "CPL_FALSE", /* --pafgen */
+                               recipe_name, /* --pafname */
+                               -1,       /* --llx1          */
+                               -1,       /* --lly1          */
+                               -1,       /* --urx1          */
+                               -1,       /* --ury1          */
+                               -1,       /* --llx2          */
+                               -1,       /* --lly2          */
+                               -1,       /* --urx2          */
+                               -1,       /* --ury2          */
+                               -1,       /* --llx3          */
+                               -1,       /* --lly3          */
+                               -1,       /* --urx3          */
+                               -1,       /* --ury3          */
+                               -1,       /* --llx4          */
+                               -1,       /* --lly4          */
+                               -1,       /* --urx4          */
+                               -1,       /* --ury4          */
+                               -1,       /* --llx5          */
+                               -1,       /* --lly5          */
+                               -1,       /* --urx5          */
+                               -1,       /* --ury5          */
+                               0,      /* --exts */
+                               NIR);       /* This is to specify OPT params */
 
 
     cpl_ensure_code(!error, error);
@@ -1427,60 +1525,116 @@ xsh_detmon_lg_fill_parlist_nir_default(cpl_parameterlist * parlist,
 /*---------------------------------------------------------------------------*/
 cpl_error_code
 xsh_detmon_lg_fill_parlist_opt_default(cpl_parameterlist * parlist,
-                                  const char *recipe_name,
-                                  const char *pipeline_name)
+                                   const char *recipe_name,
+                                   const char *pipeline_name)
 {
     const cpl_error_code error =
-	xsh_detmon_lg_fill_parlist(parlist, recipe_name, pipeline_name,
-			      "PTC", /* --method */
-			      3,   /* --order         */
-                              3.,        /* --kappa         */
-                              5,       /* --niter         */
-                              -1,       /* --llx           */
-                              -1,       /* --lly           */
-                              -1,       /* --urx           */
-                              -1,       /* --ury           */
-                              10000,    /* --ref_level     */
-                              "CPL_FALSE",      /* --intermediate  */
-                              "CPL_FALSE",      /* --autocorr      */
-                              "CPL_TRUE",      /* --collapse      */
-                              "CPL_TRUE",       /* --rescale       */
-				      "CPL_FALSE", /* --pix2pix */
-				      "CPL_FALSE", /* --bpmbin */
-                              -1,       /* --filter        */
-                              26,       /* --m             */
-                              26,       /* --n             */
-				      1e-3, /* --tolerance */
-			      "CPL_FALSE", /* --pafgen */
-				      recipe_name, /* --pafname */
-                              -1,       /* --llx1          */
-                              -1,       /* --lly1          */
-                              -1,       /* --urx1          */
-                              -1,       /* --ury1          */
-                              -1,       /* --llx2          */
-                              -1,       /* --lly2          */
-                              -1,       /* --urx2          */
-                              -1,       /* --ury2          */
-                              -1,       /* --llx3          */
-                              -1,       /* --lly3          */
-                              -1,       /* --urx3          */
-                              -1,       /* --ury3          */
-                              -1,       /* --llx4          */
-                              -1,       /* --lly4          */
-                              -1,       /* --urx4          */
-                              -1,       /* --ury4          */
-                              -1,       /* --llx5          */
-                              -1,       /* --lly5          */
-                              -1,       /* --urx5          */
-                              -1,       /* --ury5          */
-				      0,      /* --exts */
-	                      OPT);       /* This is to specify OPT params */
+        xsh_detmon_lg_fill_parlist(parlist, recipe_name, pipeline_name,
+                               "PTC", /* --method */
+                               3,   /* --order         */
+                               3.,        /* --kappa         */
+                               5,       /* --niter         */
+                               -1,       /* --llx           */
+                               -1,       /* --lly           */
+                               -1,       /* --urx           */
+                               -1,       /* --ury           */
+                               10000,    /* --ref_level     */
+                               "CPL_FALSE",      /* --intermediate  */
+                               "CPL_FALSE",      /* --autocorr      */
+                               "CPL_TRUE",      /* --collapse      */
+                               "CPL_TRUE",       /* --rescale       */
+                               "CPL_FALSE", /* --pix2pix */
+                               "CPL_FALSE", /* --bpmbin */
+                               -1,       /* --filter        */
+                               26,       /* --m             */
+                               26,       /* --n             */
+                               1e-3, /* --tolerance */
+                               "CPL_FALSE", /* --pafgen */
+                               recipe_name, /* --pafname */
+                               -1,       /* --llx1          */
+                               -1,       /* --lly1          */
+                               -1,       /* --urx1          */
+                               -1,       /* --ury1          */
+                               -1,       /* --llx2          */
+                               -1,       /* --lly2          */
+                               -1,       /* --urx2          */
+                               -1,       /* --ury2          */
+                               -1,       /* --llx3          */
+                               -1,       /* --lly3          */
+                               -1,       /* --urx3          */
+                               -1,       /* --ury3          */
+                               -1,       /* --llx4          */
+                               -1,       /* --lly4          */
+                               -1,       /* --urx4          */
+                               -1,       /* --ury4          */
+                               -1,       /* --llx5          */
+                               -1,       /* --lly5          */
+                               -1,       /* --urx5          */
+                               -1,       /* --ury5          */
+                               0,      /* --exts */
+                               OPT);       /* This is to specify OPT params */
 
     cpl_ensure_code(!error, error);
 
     return cpl_error_get_code();
 }
 
+cpl_error_code
+xsh_detmon_lg_fill_parlist_default_mr(cpl_parameterlist * parlist,
+                                  const char *recipe_name,
+                                  const char *pipeline_name)
+{
+    char * group_name = cpl_sprintf("%s.%s", pipeline_name, recipe_name);
+    char * par_name = cpl_sprintf("%s.%s", group_name, "regions-file");
+    cpl_parameter * p  = cpl_parameter_new_value(par_name, CPL_TYPE_STRING,
+                                                 "File containing regions, "
+                                                 "four comma separated points "
+                                                 "per line",
+                                                 group_name, "");
+    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "regions-file");
+    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
+    cpl_parameterlist_append(parlist, p);
+    cpl_free(par_name);
+    cpl_free(group_name);
+
+    group_name = cpl_sprintf("%s.%s", pipeline_name, recipe_name);
+    par_name = cpl_sprintf("%s.%s", group_name, "regions");
+    p  = cpl_parameter_new_value(par_name, CPL_TYPE_STRING,
+                                 "Colon separated list of regions, four "
+                                 "points each, comma separated: "
+                                 "llx,lly,urx,ury:llx,...",
+                                 group_name, "");
+    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "regions");
+    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
+    cpl_parameterlist_append(parlist, p);
+    cpl_free(par_name);
+    cpl_free(group_name);
+
+    return cpl_error_get_code();
+}
+
+cpl_error_code
+xsh_detmon_lg_fill_parlist_opt_default_mr(cpl_parameterlist * parlist,
+                                      const char *recipe_name,
+                                      const char *pipeline_name)
+{
+    xsh_detmon_lg_fill_parlist_opt_default(parlist, recipe_name, pipeline_name);
+    xsh_detmon_lg_fill_parlist_default_mr(parlist, recipe_name, pipeline_name);
+    return cpl_error_get_code();
+}
+
+cpl_error_code
+xsh_detmon_lg_fill_parlist_nir_default_mr(cpl_parameterlist * parlist,
+                                      const char *recipe_name,
+                                      const char *pipeline_name)
+{
+    xsh_detmon_lg_fill_parlist_nir_default(parlist, recipe_name, pipeline_name);
+    xsh_detmon_lg_fill_parlist_default_mr(parlist, recipe_name, pipeline_name);
+
+    return cpl_error_get_code();
+}
+
+
 /*---------------------------------------------------------------------------*/
 /**
   @brief    Generic parlist filling for Lin/Gain recipe
@@ -1538,231 +1692,238 @@ xsh_detmon_lg_fill_parlist_opt_default(cpl_parameterlist * parlist,
 /*---------------------------------------------------------------------------*/
 cpl_error_code
 xsh_detmon_lg_fill_parlist(cpl_parameterlist * parlist,
-                          const char *recipe_name, const char *pipeline_name,
-			  const char *method,
-                          int order,
-                          double kappa,
-                          int niter,
-                          int llx,
-                          int lly,
-                          int urx,
-                          int ury,
-                          int ref_level,
-                          const char *intermediate,
-                          const char *autocorr,
-                          const char *collapse,
-                          const char *rescale,
-			      const char *pix2pix,
-			      const char *bpmbin,
-                          int filter,
-                          int m,
-                          int n,
-			      double tolerance,
-			      const char *pafgen,
-			      const char * pafname,
-                          int llx1,
-                          int lly1,
-                          int urx1,
-                          int ury1,
-                          int llx2,
-                          int lly2,
-                          int urx2,
-                          int ury2,
-                          int llx3,
-                          int lly3,
-                          int urx3,
-                          int ury3,
-                          int llx4,
-                          int lly4,
-                          int urx4,
-                          int ury4,
-			      int llx5, int lly5, int urx5, int ury5, int exts,
-                          cpl_boolean opt_nir)
+                       const char *recipe_name, const char *pipeline_name,
+                       const char *method,
+                       int order,
+                       double kappa,
+                       int niter,
+                       int llx,
+                       int lly,
+                       int urx,
+                       int ury,
+                       int ref_level,
+                       const char *intermediate,
+                       const char *autocorr,
+                       const char *collapse,
+                       const char *rescale,
+                       const char *pix2pix,
+                       const char *bpmbin,
+                       int filter,
+                       int m,
+                       int n,
+                       double tolerance,
+                       const char *pafgen,
+                       const char * pafname,
+                       int llx1,
+                       int lly1,
+                       int urx1,
+                       int ury1,
+                       int llx2,
+                       int lly2,
+                       int urx2,
+                       int ury2,
+                       int llx3,
+                       int lly3,
+                       int urx3,
+                       int ury3,
+                       int llx4,
+                       int lly4,
+                       int urx4,
+                       int ury4,
+                       int llx5, int lly5, int urx5, int ury5, int exts,
+                       cpl_boolean opt_nir)
 {
     const cpl_error_code error =
-	xsh_detmon_fill_parlist(parlist, recipe_name, pipeline_name, 25,
-			       "method",
-			       "Method to be used when computing GAIN. Methods appliable: <PTC | MED>. By default PTC method will be applied.",
-                                   "CPL_TYPE_STRING", method,
-
-                               "order",
-                               "Polynomial order for the fit (Linearity)",
-                               "CPL_TYPE_INT", order,
-                               "kappa",
-                               "Kappa value for the kappa-sigma clipping (Gain)",
-                               "CPL_TYPE_DOUBLE", kappa,
-                               "niter",
-                               "Number of iterations to compute rms (Gain)",
-                               "CPL_TYPE_INT", niter,
-                               "llx",
-                               "x coordinate of the lower-left "
-                               "point of the region of interest. If not modified, default value will be 1.",
-                               "CPL_TYPE_INT", llx,
-                               "lly",
-                               "y coordinate of the lower-left "
-                               "point of the region of interest. If not modified, default value will be 1.",
-                               "CPL_TYPE_INT", lly,
-                               "urx",
-                               "x coordinate of the upper-right "
-                               "point of the region of interest. If not modified, default value will be X dimension of the input image.",
-                               "CPL_TYPE_INT", urx,
-                               "ury",
-                               "y coordinate of the upper-right "
-                               "point of the region of interest. If not modified, default value will be Y dimension of the input image.",
-                               "CPL_TYPE_INT", ury,
-                               "ref_level",
-                               "User reference level",
-                               "CPL_TYPE_INT", ref_level,
-                               "intermediate",
-                               "De-/Activate intermediate products",
-                               "CPL_TYPE_BOOL", intermediate,
-                               
-                               "autocorr",
-                               "De-/Activate the autocorr option",
-                               "CPL_TYPE_BOOL", autocorr,
-                               
-                               "collapse",
-                               "De-/Activate the collapse option",
-                               "CPL_TYPE_BOOL", collapse,
-                               "rescale",
-                               "De-/Activate the image rescale option",
-                               "CPL_TYPE_BOOL", rescale,
-				   "pix2pix",
-                               "De-/Activate the computation with pixel to pixel accuracy",
-                               "CPL_TYPE_BOOL", pix2pix,
-				   "bpmbin",
-                               "De-/Activate the binary bpm option",
-                               "CPL_TYPE_BOOL", bpmbin,
-                               "m",
-                               "Maximum x-shift for the autocorr",
-                               "CPL_TYPE_INT", m,
-                               "filter",
-                               "Upper limit of Median flux to be filtered",
-                               "CPL_TYPE_INT", filter,
-                               "n",
-                               "Maximum y-shift for the autocorr",
-				   "CPL_TYPE_INT", n,
-                               "tolerance",
-                               "Tolerance for pair discrimination",
-				   "CPL_TYPE_DOUBLE", tolerance,
-
-                               "pafgen",
-                               "Generate PAF file",
-				   "CPL_TYPE_BOOL", pafgen,
-                               "pafname",
-                               "Specific name for PAF file",
-				   "CPL_TYPE_STRING", pafname,
-
-
-                               "exts",
-                               "Activate the multi-exts option. Choose -1 to process all extensions. Choose an extension number"
-                               " to process the appropriate extension.",
-                               "CPL_TYPE_INT", exts,
-
-                               "fpn_method",
-                               "Method for computing Fixed Pattern Noise (SMOOTH or HISTOGRAM)",
-                               "CPL_TYPE_STRING", "HISTOGRAM",
-
-                               "fpn_smooth",
-                               "template size in pixels for smoothing during FPN computation (only for SMOOTH method)",
-                               "CPL_TYPE_INT", 13,
-
-                               "saturation_limit",
-                               "all frames with mean saturation above the limit would not be used in calculation",
-                               "CPL_TYPE_DOUBLE", 65535.0
-	);
-   xsh_detmon_fill_parlist(parlist, recipe_name, pipeline_name, 1,
-                               "coeffs_cube_split",
-                               "if TRUE, the recipe writes as many "
-                               "COEFFS_CUBE_Pi (i=0..order) as the value of "
-                               "the order parameter in a separate file",
-                               "CPL_TYPE_BOOL", "CPL_FALSE");
+        xsh_detmon_fill_parlist(parlist, recipe_name, pipeline_name, 26,
+                            "method",
+                            "Method to be used when computing GAIN. Methods appliable: <PTC | MED>. By default PTC method will be applied.",
+                            "CPL_TYPE_STRING", method,
+
+                            "order",
+                            "Polynomial order for the fit (Linearity)",
+                            "CPL_TYPE_INT", order,
+                            "kappa",
+                            "Kappa value for the kappa-sigma clipping (Gain)",
+                            "CPL_TYPE_DOUBLE", kappa,
+                            "niter",
+                            "Number of iterations to compute rms (Gain)",
+                            "CPL_TYPE_INT", niter,
+                            "llx",
+                            "x coordinate of the lower-left "
+                            "point of the region of interest. If not modified, default value will be 1.",
+                            "CPL_TYPE_INT", llx,
+                            "lly",
+                            "y coordinate of the lower-left "
+                            "point of the region of interest. If not modified, default value will be 1.",
+                            "CPL_TYPE_INT", lly,
+                            "urx",
+                            "x coordinate of the upper-right "
+                                "point of the region of interest. If not modified, default value will be X dimension of the input image.",
+                            "CPL_TYPE_INT", urx,
+                            "ury",
+                            "y coordinate of the upper-right "
+                                "point of the region of interest. If not modified, default value will be Y dimension of the input image.",
+                            "CPL_TYPE_INT", ury,
+                            "ref_level",
+                            "User reference level",
+                            "CPL_TYPE_INT", ref_level,
+                            "intermediate",
+                            "De-/Activate intermediate products",
+                            "CPL_TYPE_BOOL", intermediate,
+
+                            "autocorr",
+                            "De-/Activate the autocorr option",
+                            "CPL_TYPE_BOOL", autocorr,
+
+                            "collapse",
+                            "De-/Activate the collapse option",
+                            "CPL_TYPE_BOOL", collapse,
+                            "rescale",
+                            "De-/Activate the image rescale option",
+                            "CPL_TYPE_BOOL", rescale,
+                            "pix2pix",
+                            "De-/Activate the computation with pixel to pixel accuracy",
+                            "CPL_TYPE_BOOL", pix2pix,
+                            "bpmbin",
+                            "De-/Activate the binary bpm option",
+                            "CPL_TYPE_BOOL", bpmbin,
+                            "m",
+                            "Maximum x-shift for the autocorr",
+                            "CPL_TYPE_INT", m,
+                            "filter",
+                            "Upper limit of Median flux to be filtered",
+                            "CPL_TYPE_INT", filter,
+                            "n",
+                            "Maximum y-shift for the autocorr",
+                            "CPL_TYPE_INT", n,
+                            "tolerance",
+                            "Tolerance for pair discrimination",
+                            "CPL_TYPE_DOUBLE", tolerance,
+
+                            "pafgen",
+                            "Generate PAF file",
+                            "CPL_TYPE_BOOL", pafgen,
+                            "pafname",
+                            "Specific name for PAF file",
+                            "CPL_TYPE_STRING", pafname,
+
+
+                            "exts",
+                            "Activate the multi-exts option. Choose -1 to process all extensions. Choose an extension number"
+                                " to process the appropriate extension.",
+                            "CPL_TYPE_INT", exts,
+
+                            "fpn_method",
+                            "Method for computing Fixed Pattern Noise (SMOOTH or HISTOGRAM)",
+                            "CPL_TYPE_STRING", "HISTOGRAM",
+
+                            "fpn_smooth",
+                            "template size in pixels for smoothing during FPN computation (only for SMOOTH method)",
+                            "CPL_TYPE_INT", 13,
+
+                            "saturation_limit",
+                            "all frames with mean saturation above the limit would not be used in linearity calculation",
+                            "CPL_TYPE_DOUBLE", 65535.0,
+
+                            "gain_threshold",
+                            "all frames with mean flux above the threshold would not be used in gain calculation",
+                            "CPL_TYPE_DOUBLE", 65535.0
+
+                                );
+    xsh_detmon_fill_parlist(parlist, recipe_name, pipeline_name, 1,
+                        "coeffs_cube_split",
+                        "if TRUE, the recipe writes as many "
+                        "COEFFS_CUBE_Pi (i=0..order) as the value of "
+                        "the order parameter in a separate file",
+                        "CPL_TYPE_BOOL", "CPL_FALSE");
     /* OPT specific parameters */
     if(opt_nir == FALSE) {
-    	const cpl_error_code erroropt =
-	    xsh_detmon_fill_parlist(parlist, recipe_name, pipeline_name, 20,
-                               "llx1",
-                               "x coord of the lower-left point of the first "
-                               "field used for contamination measurement. If not modified, default value will be 1.",
-                               "CPL_TYPE_INT", llx1,
-                               "lly1",
-                               "y coord of the lower-left point of the first "
-                               "field used for contamination measurement. If not modified, default value will be 1.",
-                               "CPL_TYPE_INT", lly1,
-                               "urx1",
-                               "x coord of the upper-right point of the first "
-                               "field used for contamination measurement. If not modified, default value will be X dimension of the input image.",
-                               "CPL_TYPE_INT", urx1,
-                               "ury1",
-                               "y coord of the upper-right point of the first "
-                               "field used for contamination measurement. If not modified, default value will be Y dimension of the input image.",
-                               "CPL_TYPE_INT", ury1,
-                               "llx2",
-                               "x coord of the lower-left point of the second "
-                               "field used for contamination measurement. If not modified, default value will be 1.",
-                               "CPL_TYPE_INT", llx2,
-                               "lly2",
-                               "y coord of the lower-left point of the second "
-                               "field used for contamination measurement. If not modified, default value will be 1.",
-                               "CPL_TYPE_INT", lly2,
-                               "urx2",
-                               "x coord of the upper-right point of the second "
-                               "field used for contamination measurement. If not modified, default value will be half of the X dimension of the input image.",
-                               "CPL_TYPE_INT", urx2,
-                               "ury2",
-                               "y coord of the upper-right point of the second "
-                               "field used for contamination measurement. If not modified, default value will be half of the Y dimension of the input image.",
-                               "CPL_TYPE_INT", ury2,
-                               "llx3",
-                               "x coord of the lower-left point of the third "
-                               "field used for contamination measurement. If not modified, default value will be 1.",
-                               "CPL_TYPE_INT", llx3,
-                               "lly3",
-                               "y coord of the lower-left point of the third "
-                               "field used for contamination measurement. If not modified, default value will be half of the Y dimension of the input image.",
-                               "CPL_TYPE_INT", lly3,
-                               "urx3",
-                               "x coord of the upper-right point of the third "
-                               "field used for contamination measurement. If not modified, default value will be half of X dimension of the image.",
-                               "CPL_TYPE_INT", urx3,
-                               "ury3",
-                               "y coord of the upper-right point of the third "
-                               "field used for contamination measurement. If not modified, default value will be Y dimension of the image.",
-                               "CPL_TYPE_INT", ury3,
-                               "llx4",
-                               "x coord of the lower-left point of the fourth "
-                               "field used for contamination measurement. If not modified, default value will be half of X dimension of the image.",
-                               "CPL_TYPE_INT", llx4,
-                               "lly4",
-                               "y coord of the lower-left point of the fourth "
-                               "field used for contamination measurement. If not modified, default value will be half of the Y dimension of the input image.",
-                               "CPL_TYPE_INT", lly4,
-                               "urx4",
-                               "x coord of the upper-right point of the fourth "
-                               "field used for contamination measurement. If not modified, default value will be X dimension of the image.",
-                               "CPL_TYPE_INT", urx4,
-                               "ury4",
-                               "y coord of the upper-right point of the fourth "
-                               "field used for contamination measurement. If not modified, default value will be Y dimension of the input image.",
-                               "CPL_TYPE_INT", ury4,
-                               "llx5",
-                               "x coord of the lower-left point of the fifth "
-                               "field used for contamination measurement. If not modified, default value will be half of the X dimension of the input image.",
-                               "CPL_TYPE_INT", llx5,
-                               "lly5",
-                               "y coord of the lower-left point of the fifth "
-                               "field used for contamination measurement. If not modified, default value will be 1.",
-                               "CPL_TYPE_INT", lly5,
-                               "urx5",
-                               "x coord of the upper-right point of the fifth "
-                               "field used for contamination measurement. If not modified, default value will be X dimension of the image.",
-                               "CPL_TYPE_INT", urx5,
-
-                               "ury5",
-                               "y coord of the upper-right point of the fifth "
-                               "field used for contamination measurement. If not modified, default value will be half of Y dimension of the input image.",
-				   "CPL_TYPE_INT", ury5);
-		cpl_ensure_code(!erroropt, erroropt);
+        const cpl_error_code erroropt =
+            xsh_detmon_fill_parlist(parlist, recipe_name, pipeline_name, 20,
+                                "llx1",
+                                "x coord of the lower-left point of the first "
+                                "field used for contamination measurement. If not modified, default value will be 1.",
+                                "CPL_TYPE_INT", llx1,
+                                "lly1",
+                                "y coord of the lower-left point of the first "
+                                "field used for contamination measurement. If not modified, default value will be 1.",
+                                "CPL_TYPE_INT", lly1,
+                                "urx1",
+                                "x coord of the upper-right point of the first "
+                                "field used for contamination measurement. If not modified, default value will be X dimension of the input image.",
+                                "CPL_TYPE_INT", urx1,
+                                "ury1",
+                                "y coord of the upper-right point of the first "
+                                "field used for contamination measurement. If not modified, default value will be Y dimension of the input image.",
+                                "CPL_TYPE_INT", ury1,
+                                "llx2",
+                                "x coord of the lower-left point of the second "
+                                "field used for contamination measurement. If not modified, default value will be 1.",
+                                "CPL_TYPE_INT", llx2,
+                                "lly2",
+                                "y coord of the lower-left point of the second "
+                                    "field used for contamination measurement. If not modified, default value will be 1.",
+                                "CPL_TYPE_INT", lly2,
+                                "urx2",
+                                "x coord of the upper-right point of the second "
+                                    "field used for contamination measurement. If not modified, default value will be half of the X dimension of the input image.",
+                                "CPL_TYPE_INT", urx2,
+                                "ury2",
+                                "y coord of the upper-right point of the second "
+                                    "field used for contamination measurement. If not modified, default value will be half of the Y dimension of the input image.",
+                                "CPL_TYPE_INT", ury2,
+                                "llx3",
+                                "x coord of the lower-left point of the third "
+                                    "field used for contamination measurement. If not modified, default value will be 1.",
+                                "CPL_TYPE_INT", llx3,
+                                "lly3",
+                                "y coord of the lower-left point of the third "
+                                    "field used for contamination measurement. If not modified, default value will be half of the Y dimension of the input image.",
+                                "CPL_TYPE_INT", lly3,
+                                "urx3",
+                                "x coord of the upper-right point of the third "
+                                    "field used for contamination measurement. If not modified, default value will be half of X dimension of the image.",
+                                "CPL_TYPE_INT", urx3,
+                                "ury3",
+                                "y coord of the upper-right point of the third "
+                                    "field used for contamination measurement. If not modified, default value will be Y dimension of the image.",
+                                "CPL_TYPE_INT", ury3,
+                                "llx4",
+                                "x coord of the lower-left point of the fourth "
+                                    "field used for contamination measurement. If not modified, default value will be half of X dimension of the image.",
+                                "CPL_TYPE_INT", llx4,
+                                "lly4",
+                                "y coord of the lower-left point of the fourth "
+                                    "field used for contamination measurement. If not modified, default value will be half of the Y dimension of the input image.",
+                                "CPL_TYPE_INT", lly4,
+                                "urx4",
+                                "x coord of the upper-right point of the fourth "
+                                    "field used for contamination measurement. If not modified, default value will be X dimension of the image.",
+                                "CPL_TYPE_INT", urx4,
+                                "ury4",
+                                "y coord of the upper-right point of the fourth "
+                                    "field used for contamination measurement. If not modified, default value will be Y dimension of the input image.",
+                                "CPL_TYPE_INT", ury4,
+                                "llx5",
+                                "x coord of the lower-left point of the fifth "
+                                    "field used for contamination measurement. If not modified, default value will be half of the X dimension of the input image.",
+                                "CPL_TYPE_INT", llx5,
+                                "lly5",
+                                "y coord of the lower-left point of the fifth "
+                                    "field used for contamination measurement. If not modified, default value will be 1.",
+                                "CPL_TYPE_INT", lly5,
+                                "urx5",
+                                "x coord of the upper-right point of the fifth "
+                                    "field used for contamination measurement. If not modified, default value will be X dimension of the image.",
+                                "CPL_TYPE_INT", urx5,
+
+                                "ury5",
+                                "y coord of the upper-right point of the fifth "
+                                    "field used for contamination measurement. If not modified, default value will be half of Y dimension of the input image.",
+                                "CPL_TYPE_INT", ury5);
+
+
+        cpl_ensure_code(!erroropt, erroropt);
     }
 
     cpl_ensure_code(!error, error);
@@ -1782,9 +1943,9 @@ xsh_detmon_lg_fill_parlist(cpl_parameterlist * parlist,
 /*---------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_lg_retrieve_parlist(const char              * pipeline_name,
-				  const char              * recipe_name,
-				  const cpl_parameterlist * parlist,
-				  cpl_boolean               opt_nir)
+                           const char              * recipe_name,
+                           const cpl_parameterlist * parlist,
+                           cpl_boolean               opt_nir)
 {
 
     char                   * par_name;
@@ -1794,117 +1955,117 @@ xsh_detmon_lg_retrieve_parlist(const char              * pipeline_name,
     par_name = cpl_sprintf("%s.%s.method", pipeline_name, recipe_name);
     assert(par_name != NULL);
     par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_lg_config.method = cpl_parameter_get_string(par);
+    xsh_detmon_lg_config.method = cpl_parameter_get_string(par);
     cpl_free(par_name);
 
     /* --order */
-    detmon_lg_config.order =
+    xsh_detmon_lg_config.order =
         xsh_detmon_retrieve_par_int("order", pipeline_name, recipe_name,
-                                   parlist);
+                                parlist);
 
     /* --kappa */
-    detmon_lg_config.kappa =
+    xsh_detmon_lg_config.kappa =
         xsh_detmon_retrieve_par_double("kappa", pipeline_name, recipe_name,
                                    parlist);
 
     /* --niter */
-    detmon_lg_config.niter =
+    xsh_detmon_lg_config.niter =
         xsh_detmon_retrieve_par_int("niter", pipeline_name, recipe_name,
-                                   parlist);
+                                parlist);
 
     /* --llx */
-    detmon_lg_config.llx =
+    xsh_detmon_lg_config.llx =
         xsh_detmon_retrieve_par_int("llx", pipeline_name, recipe_name,
-                                   parlist);
+                                parlist);
 
     /* --lly */
-    detmon_lg_config.lly =
+    xsh_detmon_lg_config.lly =
         xsh_detmon_retrieve_par_int("lly", pipeline_name, recipe_name,
-                                   parlist);
+                                parlist);
 
     /* --urx */
-    detmon_lg_config.urx =
+    xsh_detmon_lg_config.urx =
         xsh_detmon_retrieve_par_int("urx", pipeline_name, recipe_name,
-                                   parlist);
+                                parlist);
 
     /* --ury */
-    detmon_lg_config.ury =
+    xsh_detmon_lg_config.ury =
         xsh_detmon_retrieve_par_int("ury", pipeline_name, recipe_name,
-                                   parlist);
+                                parlist);
 
     /* --ref_level */
-    detmon_lg_config.ref_level =
+    xsh_detmon_lg_config.ref_level =
         xsh_detmon_retrieve_par_int("ref_level", pipeline_name, recipe_name,
-                                   parlist);
+                                parlist);
 
     /* --intermediate */
     par_name =
         cpl_sprintf("%s.%s.intermediate", pipeline_name, recipe_name);
     assert(par_name != NULL);
     par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_lg_config.intermediate = cpl_parameter_get_bool(par);
+    xsh_detmon_lg_config.intermediate = cpl_parameter_get_bool(par);
     cpl_free(par_name);
 
     /* --autocorr */
     par_name = cpl_sprintf("%s.%s.autocorr", pipeline_name, recipe_name);
     assert(par_name != NULL);
     par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_lg_config.autocorr = cpl_parameter_get_bool(par);
+    xsh_detmon_lg_config.autocorr = cpl_parameter_get_bool(par);
     cpl_free(par_name);
-    
+
     /* --coeffs_cube_split */
     par_name = cpl_sprintf("%s.%s.coeffs_cube_split", pipeline_name, recipe_name);
     assert(par_name != NULL);
     par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_lg_config.split_coeffs = cpl_parameter_get_bool(par);
+    xsh_detmon_lg_config.split_coeffs = cpl_parameter_get_bool(par);
     cpl_free(par_name);
-    
+
     /* --collapse */
     par_name = cpl_sprintf("%s.%s.collapse", pipeline_name, recipe_name);
     assert(par_name != NULL);
     par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_lg_config.collapse = cpl_parameter_get_bool(par);
+    xsh_detmon_lg_config.collapse = cpl_parameter_get_bool(par);
     cpl_free(par_name);
 
     /* --rescale */
     par_name = cpl_sprintf("%s.%s.rescale", pipeline_name, recipe_name);
     assert(par_name != NULL);
     par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_lg_config.rescale = cpl_parameter_get_bool(par);
+    xsh_detmon_lg_config.rescale = cpl_parameter_get_bool(par);
     cpl_free(par_name);
 
     /* --pix2pix */
     par_name = cpl_sprintf("%s.%s.pix2pix", pipeline_name, recipe_name);
     assert(par_name != NULL);
     par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_lg_config.pix2pix = cpl_parameter_get_bool(par);
+    xsh_detmon_lg_config.pix2pix = cpl_parameter_get_bool(par);
     cpl_free(par_name);
 
     /* --bpmbin */
     par_name = cpl_sprintf("%s.%s.bpmbin", pipeline_name, recipe_name);
     assert(par_name != NULL);
     par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_lg_config.bpmbin = cpl_parameter_get_bool(par);
+    xsh_detmon_lg_config.bpmbin = cpl_parameter_get_bool(par);
     cpl_free(par_name);
 
     /* --filter */
-    detmon_lg_config.filter =
+    xsh_detmon_lg_config.filter =
         xsh_detmon_retrieve_par_int("filter", pipeline_name,
-                                   recipe_name, parlist);
+                                recipe_name, parlist);
 
     /* --m */
-    detmon_lg_config.m =
+    xsh_detmon_lg_config.m =
         xsh_detmon_retrieve_par_int("m", pipeline_name, recipe_name, parlist);
 
     /* --n */
-    detmon_lg_config.n =
+    xsh_detmon_lg_config.n =
         xsh_detmon_retrieve_par_int("n", pipeline_name, recipe_name, parlist);
 
     /* --tolerance */
     par_name = cpl_sprintf("%s.%s.tolerance", pipeline_name, recipe_name);
     assert(par_name != NULL);
     par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_lg_config.tolerance = cpl_parameter_get_double(par);
+    xsh_detmon_lg_config.tolerance = cpl_parameter_get_double(par);
     cpl_free(par_name);
 
 
@@ -1912,161 +2073,175 @@ xsh_detmon_lg_retrieve_parlist(const char              * pipeline_name,
     par_name = cpl_sprintf("%s.%s.pafgen", pipeline_name, recipe_name);
     assert(par_name != NULL);
     par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_lg_config.pafgen = cpl_parameter_get_bool(par);
+    xsh_detmon_lg_config.pafgen = cpl_parameter_get_bool(par);
     cpl_free(par_name);
 
     /* --pafname */
     par_name = cpl_sprintf("%s.%s.pafname", pipeline_name, recipe_name);
     assert(par_name != NULL);
     par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-    detmon_lg_config.pafname = cpl_parameter_get_string(par);
+    xsh_detmon_lg_config.pafname = cpl_parameter_get_string(par);
     cpl_free(par_name);
 
     if(opt_nir == OPT) {
-	/* --llx1 */
-	detmon_lg_config.llx1 =
-	    xsh_detmon_retrieve_par_int("llx1", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --lly1 */
-	detmon_lg_config.lly1 =
-	    xsh_detmon_retrieve_par_int("lly1", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --urx1 */
-	detmon_lg_config.urx1 =
-	    xsh_detmon_retrieve_par_int("urx1", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --ury1 */
-	detmon_lg_config.ury1 =
-	    xsh_detmon_retrieve_par_int("ury1", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --llx2 */
-	detmon_lg_config.llx2 =
-	    xsh_detmon_retrieve_par_int("llx2", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --lly2 */
-	detmon_lg_config.lly2 =
-	    xsh_detmon_retrieve_par_int("lly2", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --urx2 */
-	detmon_lg_config.urx2 =
-	    xsh_detmon_retrieve_par_int("urx2", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --ury2 */
-	detmon_lg_config.ury2 =
-	    xsh_detmon_retrieve_par_int("ury2", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --llx3 */
-	detmon_lg_config.llx3 =
-	    xsh_detmon_retrieve_par_int("llx3", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --lly3 */
-	detmon_lg_config.lly3 =
-	    xsh_detmon_retrieve_par_int("lly3", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --urx3 */
-	detmon_lg_config.urx3 =
-	    xsh_detmon_retrieve_par_int("urx3", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --ury3 */
-	detmon_lg_config.ury3 =
-	    xsh_detmon_retrieve_par_int("ury3", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --llx4 */
-	detmon_lg_config.llx4 =
-	    xsh_detmon_retrieve_par_int("llx4", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --lly4 */
-	detmon_lg_config.lly4 =
-	    xsh_detmon_retrieve_par_int("lly4", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --urx4 */
-	detmon_lg_config.urx4 =
-	    xsh_detmon_retrieve_par_int("urx4", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --ury4 */
-	detmon_lg_config.ury4 =
-	    xsh_detmon_retrieve_par_int("ury4", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --llx5 */
-	detmon_lg_config.llx5 =
-	    xsh_detmon_retrieve_par_int("llx5", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --lly5 */
-	detmon_lg_config.lly5 =
-	    xsh_detmon_retrieve_par_int("lly5", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --urx5 */
-	detmon_lg_config.urx5 =
-	    xsh_detmon_retrieve_par_int("urx5", pipeline_name, recipe_name,
-				       parlist);
-
-	/* --ury5 */
-	detmon_lg_config.ury5 =
-	    xsh_detmon_retrieve_par_int("ury5", pipeline_name, recipe_name,
-				       parlist);
+        /* --llx1 */
+        xsh_detmon_lg_config.llx1 =
+            xsh_detmon_retrieve_par_int("llx1", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --lly1 */
+        xsh_detmon_lg_config.lly1 =
+            xsh_detmon_retrieve_par_int("lly1", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --urx1 */
+        xsh_detmon_lg_config.urx1 =
+            xsh_detmon_retrieve_par_int("urx1", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --ury1 */
+        xsh_detmon_lg_config.ury1 =
+            xsh_detmon_retrieve_par_int("ury1", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --llx2 */
+        xsh_detmon_lg_config.llx2 =
+            xsh_detmon_retrieve_par_int("llx2", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --lly2 */
+        xsh_detmon_lg_config.lly2 =
+            xsh_detmon_retrieve_par_int("lly2", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --urx2 */
+        xsh_detmon_lg_config.urx2 =
+            xsh_detmon_retrieve_par_int("urx2", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --ury2 */
+        xsh_detmon_lg_config.ury2 =
+            xsh_detmon_retrieve_par_int("ury2", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --llx3 */
+        xsh_detmon_lg_config.llx3 =
+            xsh_detmon_retrieve_par_int("llx3", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --lly3 */
+        xsh_detmon_lg_config.lly3 =
+            xsh_detmon_retrieve_par_int("lly3", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --urx3 */
+        xsh_detmon_lg_config.urx3 =
+            xsh_detmon_retrieve_par_int("urx3", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --ury3 */
+        xsh_detmon_lg_config.ury3 =
+            xsh_detmon_retrieve_par_int("ury3", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --llx4 */
+        xsh_detmon_lg_config.llx4 =
+            xsh_detmon_retrieve_par_int("llx4", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --lly4 */
+        xsh_detmon_lg_config.lly4 =
+            xsh_detmon_retrieve_par_int("lly4", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --urx4 */
+        xsh_detmon_lg_config.urx4 =
+            xsh_detmon_retrieve_par_int("urx4", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --ury4 */
+        xsh_detmon_lg_config.ury4 =
+            xsh_detmon_retrieve_par_int("ury4", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --llx5 */
+        xsh_detmon_lg_config.llx5 =
+            xsh_detmon_retrieve_par_int("llx5", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --lly5 */
+        xsh_detmon_lg_config.lly5 =
+            xsh_detmon_retrieve_par_int("lly5", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --urx5 */
+        xsh_detmon_lg_config.urx5 =
+            xsh_detmon_retrieve_par_int("urx5", pipeline_name, recipe_name,
+                                    parlist);
+
+        /* --ury5 */
+        xsh_detmon_lg_config.ury5 =
+            xsh_detmon_retrieve_par_int("ury5", pipeline_name, recipe_name,
+                                    parlist);
     }
 
     /* --exts */
-    detmon_lg_config.exts =
+    xsh_detmon_lg_config.exts =
         xsh_detmon_retrieve_par_int("exts", pipeline_name, recipe_name,
-                                   parlist);
+                                parlist);
     /* --fpn_method */
     {
-    	const char* str_method = 0;
-    	detmon_lg_config.fpn_method = FPN_HISTOGRAM;
-		par_name =
-			cpl_sprintf("%s.%s.fpn_method", pipeline_name, recipe_name);
-		assert(par_name != NULL);
-		par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-		if (par)
-		{
-			str_method = cpl_parameter_get_string(par);
-			if (strcmp(str_method, "SMOOTH") == 0)
-			{
-				detmon_lg_config.fpn_method = FPN_SMOOTH;
-			}
-			else if (strcmp(str_method, "HISTOGRAM") == 0)
-			{
-				detmon_lg_config.fpn_method = FPN_HISTOGRAM;
-			}
-		}
-		cpl_free(par_name);
+        xsh_detmon_lg_config.fpn_method = FPN_HISTOGRAM;
+        par_name =
+            cpl_sprintf("%s.%s.fpn_method", pipeline_name, recipe_name);
+        assert(par_name != NULL);
+        par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
+        if (par)
+        {
+            const char * str_method = cpl_parameter_get_string(par);
+            if (strcmp(str_method, "SMOOTH") == 0)
+            {
+                xsh_detmon_lg_config.fpn_method = FPN_SMOOTH;
+            }
+            else if (strcmp(str_method, "HISTOGRAM") == 0)
+            {
+                xsh_detmon_lg_config.fpn_method = FPN_HISTOGRAM;
+            }
+        }
+        cpl_free(par_name);
     }
     /* --fpn_smooth */
-    detmon_lg_config.fpn_smooth =
+    xsh_detmon_lg_config.fpn_smooth =
         xsh_detmon_retrieve_par_int("fpn_smooth", pipeline_name, recipe_name,
-                                   parlist);
+                                parlist);
     /* --saturation_limit*/
     {
-    	detmon_lg_config.saturation_limit = 65535;
-		par_name =
-			cpl_sprintf("%s.%s.saturation_limit", pipeline_name, recipe_name);
-		assert(par_name != NULL);
-		par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
-		if (par)
-		{
-			detmon_lg_config.saturation_limit  = cpl_parameter_get_double(par);
-		}
-		cpl_free(par_name);
+        xsh_detmon_lg_config.saturation_limit = 65535;
+        par_name =
+            cpl_sprintf("%s.%s.saturation_limit", pipeline_name, recipe_name);
+        assert(par_name != NULL);
+        par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
+        if (par)
+        {
+            xsh_detmon_lg_config.saturation_limit  = cpl_parameter_get_double(par);
+        }
+        cpl_free(par_name);
+    }
+
+    /* --gain_threshold*/
+    {
+        xsh_detmon_lg_config.gain_threshold = 0;
+        par_name =
+            cpl_sprintf("%s.%s.gain_threshold", pipeline_name, recipe_name);
+        assert(par_name != NULL);
+        par = cpl_parameterlist_find((cpl_parameterlist *) parlist, par_name);
+        if (par)
+        {
+            xsh_detmon_lg_config.gain_threshold  = cpl_parameter_get_double(par);
+        }
+        cpl_free(par_name);
     }
+
     if(cpl_error_get_code())
     {
         cpl_msg_error(cpl_func, "Failed to retrieve the input parameters");
@@ -2090,82 +2265,82 @@ xsh_detmon_lg_check_defaults(const cpl_image * reference)
     const int               nx = cpl_image_get_size_x(reference);
     const int               ny = cpl_image_get_size_y(reference);
 
-    detmon_lg_config.nx = nx;
-    detmon_lg_config.ny = ny;
-
-    detmon_lg_config.wholechip = CPL_FALSE;
-
-    if(detmon_lg_config.llx == -1)
-        detmon_lg_config.llx = 1;
-    if(detmon_lg_config.lly == -1)
-        detmon_lg_config.lly = 1;
-    if(detmon_lg_config.urx == -1)
-        detmon_lg_config.urx = nx;
-    if(detmon_lg_config.ury == -1)
-        detmon_lg_config.ury = ny;
-
-    if (detmon_lg_config.llx == 1  &&
-	detmon_lg_config.lly == 1  &&
-	detmon_lg_config.urx == nx &&
-	detmon_lg_config.ury == ny)
-	detmon_lg_config.wholechip = CPL_TRUE;
-
-    if(detmon_lg_config.llx1 == -1)
-        detmon_lg_config.llx1 = 1;
-    if(detmon_lg_config.lly1 == -1)
-        detmon_lg_config.lly1 = 1;
-    if(detmon_lg_config.urx1 == -1)
-        detmon_lg_config.urx1 = nx;
-    if(detmon_lg_config.ury1 == -1)
-        detmon_lg_config.ury1 = ny;
-
-    if(detmon_lg_config.llx2 == -1)
-        detmon_lg_config.llx2 = 1;
-    if(detmon_lg_config.lly2 == -1)
-        detmon_lg_config.lly2 = 1;
-    if(detmon_lg_config.urx2 == -1)
-        detmon_lg_config.urx2 = nx / 2;
-    if(detmon_lg_config.ury2 == -1)
-        detmon_lg_config.ury2 = ny / 2;
-
-    if(detmon_lg_config.llx3 == -1)
-        detmon_lg_config.llx3 = 1;
-    if(detmon_lg_config.lly3 == -1)
-        detmon_lg_config.lly3 = ny / 2;
-    if(detmon_lg_config.urx3 == -1)
-        detmon_lg_config.urx3 = nx / 2;
-    if(detmon_lg_config.ury3 == -1)
-        detmon_lg_config.ury3 = ny;
-
-    if(detmon_lg_config.llx4 == -1)
-        detmon_lg_config.llx4 = nx / 2;
-    if(detmon_lg_config.lly4 == -1)
-        detmon_lg_config.lly4 = ny / 2;
-    if(detmon_lg_config.urx4 == -1)
-        detmon_lg_config.urx4 = nx;
-    if(detmon_lg_config.ury4 == -1)
-        detmon_lg_config.ury4 = ny;
-
-    if(detmon_lg_config.llx5 == -1)
-        detmon_lg_config.llx5 = nx / 2;
-    if(detmon_lg_config.lly5 == -1)
-        detmon_lg_config.lly5 = 1;
-    if(detmon_lg_config.urx5 == -1)
-        detmon_lg_config.urx5 = nx;
-    if(detmon_lg_config.ury5 == -1)
-        detmon_lg_config.ury5 = ny / 2;
-
-    if(detmon_lg_config.intermediate == TRUE) {
+    xsh_detmon_lg_config.nx = nx;
+    xsh_detmon_lg_config.ny = ny;
+
+    xsh_detmon_lg_config.wholechip = CPL_FALSE;
+
+    if(xsh_detmon_lg_config.llx == -1)
+        xsh_detmon_lg_config.llx = 1;
+    if(xsh_detmon_lg_config.lly == -1)
+        xsh_detmon_lg_config.lly = 1;
+    if(xsh_detmon_lg_config.urx == -1)
+        xsh_detmon_lg_config.urx = nx;
+    if(xsh_detmon_lg_config.ury == -1)
+        xsh_detmon_lg_config.ury = ny;
+
+    if (xsh_detmon_lg_config.llx == 1  &&
+        xsh_detmon_lg_config.lly == 1  &&
+        xsh_detmon_lg_config.urx == nx &&
+        xsh_detmon_lg_config.ury == ny)
+        xsh_detmon_lg_config.wholechip = CPL_TRUE;
+
+    if(xsh_detmon_lg_config.llx1 == -1)
+        xsh_detmon_lg_config.llx1 = 1;
+    if(xsh_detmon_lg_config.lly1 == -1)
+        xsh_detmon_lg_config.lly1 = 1;
+    if(xsh_detmon_lg_config.urx1 == -1)
+        xsh_detmon_lg_config.urx1 = nx;
+    if(xsh_detmon_lg_config.ury1 == -1)
+        xsh_detmon_lg_config.ury1 = ny;
+
+    if(xsh_detmon_lg_config.llx2 == -1)
+        xsh_detmon_lg_config.llx2 = 1;
+    if(xsh_detmon_lg_config.lly2 == -1)
+        xsh_detmon_lg_config.lly2 = 1;
+    if(xsh_detmon_lg_config.urx2 == -1)
+        xsh_detmon_lg_config.urx2 = nx / 2;
+    if(xsh_detmon_lg_config.ury2 == -1)
+        xsh_detmon_lg_config.ury2 = ny / 2;
+
+    if(xsh_detmon_lg_config.llx3 == -1)
+        xsh_detmon_lg_config.llx3 = 1;
+    if(xsh_detmon_lg_config.lly3 == -1)
+        xsh_detmon_lg_config.lly3 = ny / 2;
+    if(xsh_detmon_lg_config.urx3 == -1)
+        xsh_detmon_lg_config.urx3 = nx / 2;
+    if(xsh_detmon_lg_config.ury3 == -1)
+        xsh_detmon_lg_config.ury3 = ny;
+
+    if(xsh_detmon_lg_config.llx4 == -1)
+        xsh_detmon_lg_config.llx4 = nx / 2;
+    if(xsh_detmon_lg_config.lly4 == -1)
+        xsh_detmon_lg_config.lly4 = ny / 2;
+    if(xsh_detmon_lg_config.urx4 == -1)
+        xsh_detmon_lg_config.urx4 = nx;
+    if(xsh_detmon_lg_config.ury4 == -1)
+        xsh_detmon_lg_config.ury4 = ny;
+
+    if(xsh_detmon_lg_config.llx5 == -1)
+        xsh_detmon_lg_config.llx5 = nx / 2;
+    if(xsh_detmon_lg_config.lly5 == -1)
+        xsh_detmon_lg_config.lly5 = 1;
+    if(xsh_detmon_lg_config.urx5 == -1)
+        xsh_detmon_lg_config.urx5 = nx;
+    if(xsh_detmon_lg_config.ury5 == -1)
+        xsh_detmon_lg_config.ury5 = ny / 2;
+
+    if(xsh_detmon_lg_config.intermediate == TRUE) {
         cpl_msg_warning(cpl_func, "PLEASE NOTE: The --intermediate option saves the difference and correlation images produced during autocorrelation computation. Therefore, --autocorr option has been automatically activated. If you didn't want to run this, please abort and rerun.");
-        detmon_lg_config.autocorr = TRUE;
+        xsh_detmon_lg_config.autocorr = TRUE;
     }
 
 
-    detmon_lg_config.lamp_stability = 0.0;
+    xsh_detmon_lg_config.lamp_stability = 0.0;
 
-    detmon_lg_config.lamp_ok = FALSE;
+    xsh_detmon_lg_config.lamp_ok = FALSE;
 
-    detmon_lg_config.cr = 0.0;
+    xsh_detmon_lg_config.cr = 0.0;
 
     return cpl_error_get_code();
 }
@@ -2184,41 +2359,38 @@ xsh_detmon_lg_check_defaults(const cpl_image * reference)
 /*---------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_lg_split_onoff(const cpl_frameset * cur_fset,
-                             cpl_frameset * cur_fset_on,
-                             cpl_frameset * cur_fset_off,
-                             const char *tag_on,
-                             const char *tag_off)
+                      cpl_frameset * cur_fset_on,
+                      cpl_frameset * cur_fset_off,
+                      const char *tag_on,
+                      const char *tag_off)
 {
     int                     nframes;
     int                     i;
 
+    cpl_frame * cur_frame_dup = NULL;
+
+#if 0
     const cpl_frame * first;
     const cpl_frame * second;
-
     const char * first_tag;
     const char * second_tag;
-
-    cpl_frame * cur_frame_dup = NULL;
-
     skip_if((first   = cpl_frameset_get_first_const(cur_fset)) == NULL);
     skip_if((second  = cpl_frameset_get_next_const (cur_fset)) == NULL);
 
     skip_if((first_tag  = cpl_frame_get_tag(first))  == NULL);
     skip_if((second_tag = cpl_frame_get_tag(second)) == NULL);
-
-#if 0
     if (opt_nir == OPT &&
-	((!strcmp(first_tag, tag_on ) && !strcmp(second_tag, tag_off)) ||
-	 (!strcmp(first_tag, tag_off) && !strcmp(second_tag, tag_on )))) {
-	detmon_lg_config.lamp_ok = TRUE;
+        ((!strcmp(first_tag, tag_on ) && !strcmp(second_tag, tag_off)) ||
+         (!strcmp(first_tag, tag_off) && !strcmp(second_tag, tag_on )))) {
+        xsh_detmon_lg_config.lamp_ok = TRUE;
     }
 #endif
 
     nframes = cpl_frameset_get_size(cur_fset);
-    for(i = detmon_lg_config.lamp_ok ? 2 : 0; i < nframes; i++) {
+    for(i = xsh_detmon_lg_config.lamp_ok ? 2 : 0; i < nframes; i++) {
         const cpl_frame * cur_frame =
-	    cpl_frameset_get_frame_const(cur_fset, i);
-	char            * tag;
+            cpl_frameset_get_position_const(cur_fset, i);
+        char            * tag;
 
         /* Duplication is required for insertion to a different frameset */
         cur_frame_dup = cpl_frame_duplicate(cur_frame);
@@ -2231,7 +2403,7 @@ xsh_detmon_lg_split_onoff(const cpl_frameset * cur_fset,
             skip_if(cpl_frameset_insert(cur_fset_off, cur_frame_dup));
         } else {
             cpl_frame_delete(cur_frame_dup);
-	    cur_frame_dup = NULL;
+            cur_frame_dup = NULL;
         }
     }
     cur_frame_dup = NULL;
@@ -2269,79 +2441,93 @@ xsh_detmon_lg_split_onoff(const cpl_frameset * cur_fset,
 
 static cpl_error_code
 xsh_detmon_lg_reduce(const cpl_frameset * set_on,
-                        const cpl_frameset * set_off,
-    				    int* index_on, int* index_off, double* exptime_on, double* exptime_off,
-    				    int *next_index_on, int* next_index_off,
-                        cpl_imagelist ** coeffs_ptr,
-                        cpl_table * gain_table,
-                        cpl_table * linear_table,
-                        cpl_image ** bpm_ptr,
-                        cpl_imagelist * autocorr_images,
-                        cpl_imagelist * diff_flats,
-                        cpl_propertylist * gaint_qclist,
-                        cpl_propertylist * lint_qclist,
-                        cpl_propertylist * linc_qclist,
-                        cpl_propertylist * bpm_qclist,
-		 int                    (* load_fset) (const cpl_frameset *,
-						       cpl_type,
-		                                       cpl_imagelist *),
-			const cpl_boolean opt_nir,
-                        int whichext)
+                 const cpl_frameset * set_off,
+                 int* index_on, int* index_off,
+                 double* exptime_on, double* exptime_off,
+                 int *next_index_on, int* next_index_off,
+                 cpl_imagelist ** coeffs_ptr,
+                 cpl_table * gain_table,
+                 cpl_table * linear_table,
+                 cpl_image ** bpm_ptr,
+                 cpl_imagelist * autocorr_images,
+                 cpl_imagelist * diff_flats,
+                 cpl_propertylist * gaint_qclist,
+                 cpl_propertylist * lint_qclist,
+                 cpl_propertylist * linc_qclist,
+                 cpl_propertylist * bpm_qclist,
+                 int (* load_fset) (const cpl_frameset *,
+                                    cpl_type,
+                                    cpl_imagelist *),
+                 const cpl_boolean opt_nir,
+                 int whichext)
 {
-	const double D_INVALID_VALUE = -999;
+    cpl_errorstate prestate = cpl_errorstate_get();
+    const double D_INVALID_VALUE = -999;
     int                     i;
     cpl_imagelist         * linearity_inputs = NULL;
     cpl_imagelist         * opt_offs = NULL;
     int                     nsets;
     cpl_propertylist      * reflist = NULL;
-    int dit_nskip=0;
-	int rows_affected = 1;
-	int last_best = 0;
+    int dit_nskip = 0;
+    int rows_linear_affected = 1;
+    int rows_gain_affected = 1;
+    int last_linear_best = 0;
+    int last_gain_best = 0;
     /* Test entries */
     cpl_ensure(set_on != NULL, CPL_ERROR_NULL_INPUT, CPL_ERROR_NULL_INPUT);
     cpl_ensure(set_off != NULL, CPL_ERROR_NULL_INPUT, CPL_ERROR_NULL_INPUT);
 
     nsets = cpl_frameset_get_size(set_on) / 2;
 
-    detmon_lg_config.load_fset = load_fset;
-    if(detmon_lg_config.collapse) {
+    xsh_detmon_lg_config.load_fset = load_fset;
+    if(xsh_detmon_lg_config.collapse) {
         /*
          * When the 'collapse' option is used, there are no OFF pairs. We
          * construct a pair with the 2 first raw OFF frames, which will be
          * passed for each DIT value, to maintain the same API in the function
          * xsh_detmon_gain_table_fill_row().
          */
-        const cpl_frame        *first = cpl_frameset_get_first_const(set_off);
-        cpl_frame              *dup_first = cpl_frame_duplicate(first);
+        const cpl_frame *first = cpl_frameset_get_first_const(set_off);
+        cpl_frame       *dup_first = cpl_frame_duplicate(first);
 
-        const cpl_frame        *second = cpl_frameset_get_next_const(set_off);
-        cpl_frame              *dup_second = cpl_frame_duplicate(second);
+        const cpl_frame *second = cpl_frameset_get_next_const(set_off);
+        cpl_frame       *dup_second = cpl_frame_duplicate(second);
 
-        cpl_frameset           *raw_offs = cpl_frameset_new();
+        cpl_frameset    *raw_offs = cpl_frameset_new();
 
         skip_if(cpl_frameset_insert(raw_offs, dup_first));
         skip_if(cpl_frameset_insert(raw_offs, dup_second));
 
         opt_offs = cpl_imagelist_load_frameset(raw_offs, CPL_TYPE_FLOAT,
-					       0, whichext);
+                                               0, whichext);
 
         cpl_frameset_delete(raw_offs);
-
+        if (opt_offs == NULL) {
+            cpl_errorstate_set(prestate);
+            return CPL_ERROR_CONTINUE;
+        }
     }
 
     skip_if(xsh_detmon_lg_reduce_init(gain_table,
-					 linear_table,
-					 &linearity_inputs,
-		                         opt_nir));
-    if (!strcmp(detmon_lg_config.method, "PTC"))
+                                  linear_table,
+                                  &linearity_inputs,
+                                  opt_nir));
+/*
+    if (!strcmp(xsh_detmon_lg_config.method, "PTC"))
     {
-    	cpl_msg_warning(cpl_func, "PTC method incompatible with lamp stability computation");
+        cpl_msg_warning(cpl_func, "PTC method incompatible with lamp stability"
+                        "computation");
     }
-    else if(!detmon_lg_config.collapse)
+*/
+    /* do always lamp stability check */
+    if(xsh_detmon_lg_lamp_stab(set_on, set_off,
+                        opt_nir, whichext)) {
+       cpl_errorstate_set(prestate);
+   }
+ 
+   if(!xsh_detmon_lg_config.collapse)
     {
-    	skip_if(xsh_detmon_lg_lamp_stab(set_on, set_off,
-					   opt_nir, whichext));
-    }
+     }
     /* Unselect all rows, to select only invalid ones */
     skip_if(cpl_table_unselect_all(linear_table));
     skip_if(cpl_table_unselect_all(gain_table));
@@ -2350,30 +2536,48 @@ xsh_detmon_lg_reduce(const cpl_frameset * set_on,
 
     for(i = 0; i < nsets ; i++)
     {
-			skip_if(xsh_detmon_lg_reduce_dit(set_on,
-					index_on, exptime_on,
-					i,
-					&dit_nskip,
-					set_off,
-					index_off, exptime_off,
-					next_index_on, next_index_off,
-					linear_table,
-					gain_table, linearity_inputs,
-					lint_qclist, opt_nir,
-					autocorr_images, diff_flats,
-					opt_offs,  whichext,
-					&rows_affected));
-       	if (rows_affected == 0)
-       	{
-       		cpl_msg_warning(cpl_func, "The rest frames would not be taken into calculation, check the messages above");
-       		cpl_table_select_row(linear_table, i);
-            cpl_table_select_row(gain_table, i);
-       	}
-       	else
-       	{
-       		last_best = i;
-       	}
+        skip_if(xsh_detmon_lg_reduce_dit(set_on,
+                                     index_on, exptime_on,
+                                     i,
+                                     &dit_nskip,
+                                     set_off,
+                                     index_off, exptime_off,
+                                     next_index_on, next_index_off,
+                                     linear_table,
+                                     gain_table, linearity_inputs,
+                                     lint_qclist, opt_nir,
+                                     autocorr_images, diff_flats,
+                                     opt_offs,  whichext,
+                                     &rows_linear_affected,&rows_gain_affected));
+        /* TODO: the following if could be done directly inside the
+         * function xsh_detmon_lg_reduce_dit
+         */
+        if (rows_linear_affected == 0)
+        {
+            cpl_msg_warning(cpl_func, "The rest frames would not be taken "
+                            "into linear calculation, check the messages above");
+            cpl_table_select_row(linear_table, i);
+        }
+        else
+        {
+            last_linear_best = i;
+        }
+
+        if (rows_gain_affected == 0)
+         {
+             cpl_msg_warning(cpl_func, "The rest frames would not be taken "
+                             "into gain calculation, check the messages above");
+             cpl_table_select_row(gain_table, i);
+         }
+         else
+         {
+             last_gain_best = i;
+         }
+
+
+
     }
+
     skip_if(xsh_detmon_add_adl_column(linear_table, opt_nir));
 
     /*
@@ -2383,6 +2587,7 @@ xsh_detmon_lg_reduce(const cpl_frameset * set_on,
     skip_if(cpl_table_erase_selected(gain_table));
     skip_if(cpl_table_erase_selected(linear_table));
 
+
     reflist = cpl_propertylist_new();
     skip_if(cpl_propertylist_append_bool(reflist, "ADU", FALSE));
     skip_if(cpl_table_sort(gain_table, reflist));
@@ -2392,38 +2597,39 @@ xsh_detmon_lg_reduce(const cpl_frameset * set_on,
      * computations which are over all posible DIT values.
      */
     skip_if(xsh_detmon_lg_reduce_all(linear_table,
-					gaint_qclist, lint_qclist, linc_qclist,
-					bpm_qclist, coeffs_ptr, bpm_ptr,
-					linearity_inputs,
-					gain_table, whichext, opt_nir));
-	{
-	    /*FPN Computation*/
-		double gain = cpl_propertylist_get_double(gaint_qclist, DETMON_QC_GAIN);
-//		cpl_propertylist_append_int(gaint_qclist, "NNNEXT", whichext);		
-//		cpl_msg_warning(cpl_func, "---------- ext %i" , whichext);
-		cpl_error_code cplerr = cpl_error_get_code();
-		if (cplerr != CPL_ERROR_NONE || (gain == 0.0))
-		{
-			cpl_msg_warning(cpl_func, "Cannot read gain from QC parameters - FPN will not be computed");
-			cpl_error_reset();
-		}
-		else
-		{
-		xsh_detmon_fpn_compute(set_on, index_on, last_best, lint_qclist,
-				detmon_lg_config.llx,
-				detmon_lg_config.lly,
-				detmon_lg_config.urx,
-				detmon_lg_config.ury,
-				gain,
-				whichext,
-				detmon_lg_config.fpn_method,
-				detmon_lg_config.fpn_smooth);
-		}
-	}
-	/* change NaN in the gain table to the invalid value D_INVALID_VALUE*/
-	xsh_detmon_table_fill_invalid(gain_table, D_INVALID_VALUE);
-    end_skip;
+                                 gaint_qclist, lint_qclist, linc_qclist,
+                                 bpm_qclist, coeffs_ptr, bpm_ptr,
+                                 linearity_inputs,
+                                 gain_table, whichext, opt_nir));
+    {
+        /*FPN Computation*/
+        double gain = cpl_propertylist_get_double(gaint_qclist, DETMON_QC_GAIN);
+        //		cpl_propertylist_append_int(gaint_qclist, "NNNEXT", whichext);
+        //		cpl_msg_warning(cpl_func, "---------- ext %i" , whichext);
+        cpl_error_code cplerr = cpl_error_get_code();
+        if (cplerr != CPL_ERROR_NONE || (gain == 0.0))
+        {
+            cpl_msg_warning(cpl_func, "Cannot read gain from QC parameters - "
+                            "FPN will not be computed");
+            cpl_error_reset();
+        }
+        else
+        {
+            xsh_detmon_fpn_compute(set_on, index_on, last_linear_best, lint_qclist,
+                               xsh_detmon_lg_config.llx,
+                               xsh_detmon_lg_config.lly,
+                               xsh_detmon_lg_config.urx,
+                               xsh_detmon_lg_config.ury,
+                               gain,
+                               whichext,
+                               xsh_detmon_lg_config.fpn_method,
+                               xsh_detmon_lg_config.fpn_smooth);
+        }
+    }
+    /* change NaN in the gain table to the invalid value D_INVALID_VALUE*/
 
+    xsh_detmon_table_fill_invalid(gain_table, D_INVALID_VALUE);
+    end_skip;
     cpl_imagelist_delete(linearity_inputs);
     cpl_imagelist_delete(opt_offs);
     cpl_propertylist_delete(reflist);
@@ -2433,87 +2639,87 @@ xsh_detmon_lg_reduce(const cpl_frameset * set_on,
 
 static cpl_error_code xsh_detmon_table_fill_invalid(cpl_table* ptable, double code)
 {
-	int ncols = cpl_table_get_ncol(ptable);
-	cpl_array* pnames = cpl_table_get_column_names(ptable);
-	int nrows = cpl_table_get_nrow(ptable);
-	int i = 0;
-	for (i=0; i < ncols; i++)
-	{
-		int j = 0;
-		for (j = 0; j< nrows; j++)
-		{
-			const char* colname = cpl_array_get_data_string_const(pnames)[i];
-			int isnull;
-			cpl_type type = cpl_table_get_column_type(ptable, colname);
-			cpl_table_get(ptable, colname, j, &isnull);
-			if(isnull == 1)
-			{
-				if (type == CPL_TYPE_DOUBLE)
-				{
-					cpl_table_set(ptable,colname,j, code);
-				}
-				else if (type == CPL_TYPE_FLOAT)
-				{
-					cpl_table_set_float(ptable,colname,j, (float)code);
-				}
-			}
-		}
-	}
-	cpl_array_delete(pnames);
-	return cpl_error_get_code();
+    int ncols = cpl_table_get_ncol(ptable);
+    cpl_array* pnames = cpl_table_get_column_names(ptable);
+    int nrows = cpl_table_get_nrow(ptable);
+    int i = 0;
+    for (i=0; i < ncols; i++)
+    {
+        int j = 0;
+        for (j = 0; j< nrows; j++)
+        {
+            const char* colname = cpl_array_get_data_string_const(pnames)[i];
+            int isnull;
+            cpl_type type = cpl_table_get_column_type(ptable, colname);
+            cpl_table_get(ptable, colname, j, &isnull);
+            if(isnull == 1)
+            {
+                if (type == CPL_TYPE_DOUBLE)
+                {
+                    cpl_table_set(ptable,colname,j, code);
+                }
+                else if (type == CPL_TYPE_FLOAT)
+                {
+                    cpl_table_set_float(ptable,colname,j, (float)code);
+                }
+            }
+        }
+    }
+    cpl_array_delete(pnames);
+    return cpl_error_get_code();
 }
 
 static cpl_error_code
 xsh_detmon_fpn_compute(const cpl_frameset *set_on,
-		int * index_on,
-		int last_best,
-		cpl_propertylist *lint_qclist,
-		int llx,
-		int lly,
-		int urx,
-		int ury,
-		double gain,
-		int whichext,
-		FPN_METHOD fpn_method,
-		int smooth_size)
+                   int * index_on,
+                   int last_linear_best,
+                   cpl_propertylist *lint_qclist,
+                   int llx,
+                   int lly,
+                   int urx,
+                   int ury,
+                   double gain,
+                   int whichext,
+                   FPN_METHOD fpn_method,
+                   int smooth_size)
 {
-	double fpn = 0;
-	const cpl_image* im1 = 0;
-	int range[4];
-	cpl_imagelist* ons = 0;
-	cpl_frameset          * pair_on = 0;
-	int nsets_extracted = cpl_frameset_get_size(set_on);
-	cpl_size * selection = NULL;
-	double mse = 0;
-	range[0] = llx;
-	range[1] = lly;
-	range[2] = urx;
-	range[3] = ury;
-
-	/* Retrieve 2 ON frames with the highest DIT -
-	 * the last best 2 values in the index*/
-	selection = cpl_malloc(sizeof(cpl_size) * nsets_extracted);
-	memset(&selection[0], 0, sizeof(cpl_size) * nsets_extracted);
+    double fpn = 0;
+    const cpl_image* im1 = 0;
+    int range[4];
+    cpl_imagelist* ons = 0;
+    cpl_frameset          * pair_on = 0;
+    int nsets_extracted = cpl_frameset_get_size(set_on);
+    cpl_size * selection = NULL;
+    double mse = 0;
+    range[0] = llx;
+    range[1] = lly;
+    range[2] = urx;
+    range[3] = ury;
+
+    /* Retrieve 2 ON frames with the highest DIT -
+     * the last best 2 values in the index*/
+    selection = cpl_malloc(sizeof(cpl_size) * nsets_extracted);
+    memset(&selection[0], 0, sizeof(cpl_size) * nsets_extracted);
+
+    selection[index_on[last_linear_best*2 + 0] ] = 1;
+    selection[index_on[last_linear_best*2 + 1] ] = 1;
+    pair_on = cpl_frameset_extract(set_on, selection, 1);
+    ons = xsh_detmon_lg_config.load_fset_wrp(pair_on, CPL_TYPE_FLOAT, whichext);
+
+    skip_if(ons == NULL);
+    skip_if((im1 = cpl_imagelist_get_const(ons, 0)) == NULL);
+
+    fpn = irplib_fpn_lg(im1, range, gain, fpn_method, smooth_size, &mse);
+    skip_if(cpl_propertylist_append_double(lint_qclist, DETMON_QC_FPN,
+                                           fpn));
+    skip_if(cpl_propertylist_append_double(lint_qclist, "ESO QC GAIN ERR",
+                                           mse));
 
-	selection[index_on[last_best*2 + 0] ] = 1;
-	selection[index_on[last_best*2 + 1] ] = 1;
-	 pair_on = cpl_frameset_extract(set_on, selection, 1);
- 	 ons = detmon_lg_config.load_fset_wrp(pair_on, CPL_TYPE_FLOAT, whichext);
-
-	skip_if(ons == NULL);
-	skip_if((im1 = cpl_imagelist_get_const(ons, 0)) == NULL);
-
-	fpn = irplib_fpn_lg(im1, range, gain, fpn_method, smooth_size, &mse);
-	skip_if(cpl_propertylist_append_double(lint_qclist, DETMON_QC_FPN,
-						       fpn));
-	skip_if(cpl_propertylist_append_double(lint_qclist, "ESO QC GAIN ERR",
-						       mse));
-
-	cleanup:
-	cpl_frameset_delete(pair_on);
-	cpl_imagelist_delete(ons);
-	cpl_free(selection);
-	return cpl_error_get_code();
+    end_skip;
+    cpl_frameset_delete(pair_on);
+    cpl_imagelist_delete(ons);
+    cpl_free(selection);
+    return cpl_error_get_code();
 }
 
 /*--------------------------------------------------------------------------*/
@@ -2527,17 +2733,19 @@ xsh_detmon_fpn_compute(const cpl_frameset *set_on,
 /*--------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_lg_lamp_stab(const cpl_frameset * lamps,
-			   const cpl_frameset * darks,
-                           cpl_boolean          opt_nir,
-                           int                  whichext)
+                    const cpl_frameset * darks,
+                    cpl_boolean          opt_nir,
+                    int                  whichext)
 {
+   
     /*
      * NOTE:
      * Most of this code is copied (and modified) from
      * isaac_img_detlin_load(), in isaac_img_detlin.c v.1.25
      */
-
+   
     int                     nb_lamps;
+    int                     nb_darks;
 
     cpl_vector          *   selection = NULL;
     cpl_propertylist    *   plist;
@@ -2552,62 +2760,64 @@ xsh_detmon_lg_lamp_stab(const cpl_frameset * lamps,
 
     /* Check that there are as many lamp as darks */
     cpl_ensure_code((nb_lamps = cpl_frameset_get_size(lamps)) >= 3,
-		    CPL_ERROR_ILLEGAL_INPUT);
+                    CPL_ERROR_ILLEGAL_INPUT);
+/*
     cpl_ensure_code(cpl_frameset_get_size(darks) == nb_lamps,
-	            CPL_ERROR_ILLEGAL_INPUT);
-
+                    CPL_ERROR_ILLEGAL_INPUT);
+*/
     /* Check out that they have consistent integration times */
     cpl_msg_info(__func__, "Checking DIT consistency");
     selection = cpl_vector_new(nb_lamps);
     ditvals = cpl_malloc(nb_lamps * sizeof(double));
     dit_stab = 0;
     for (i = 0; i < nb_lamps; i++) {
-	const cpl_frame           * c_lamp;
-	const cpl_frame           * c_dark;
+        const cpl_frame           * c_lamp;
+        const cpl_frame           * c_dark;
         /* Check if ok */
         skip_if (cpl_error_get_code());
 
         /* DIT from LAMP */
-        c_lamp = cpl_frameset_get_frame_const(lamps, i);
+        c_lamp = cpl_frameset_get_position_const(lamps, i);
         plist = cpl_propertylist_load(cpl_frame_get_filename(c_lamp), 0);
-	if(opt_nir)
-	    dit_lamp = (double)irplib_pfits_get_dit(plist);
-	else
-	    dit_lamp = (double)irplib_pfits_get_dit_opt(plist);
+        if(opt_nir)
+            dit_lamp = (double)irplib_pfits_get_dit(plist);
+        else
+            dit_lamp = (double)irplib_pfits_get_dit_opt(plist);
         cpl_propertylist_delete(plist);
         skip_if (cpl_error_get_code());
 
         /* DIT from DARK */
-        c_dark = cpl_frameset_get_frame_const(darks, i);
+        c_dark = cpl_frameset_get_position_const(darks, i);
         plist  = cpl_propertylist_load(cpl_frame_get_filename(c_dark), 0);
-	if(opt_nir)
-	    dit_dark = (double)irplib_pfits_get_dit(plist);
-	else
-	    dit_dark = (double)irplib_pfits_get_dit_opt(plist);
+        if(opt_nir)
+            dit_dark = (double)irplib_pfits_get_dit(plist);
+        else
+            dit_dark = (double)irplib_pfits_get_dit_opt(plist);
         cpl_propertylist_delete(plist);
         skip_if (cpl_error_get_code());
 
         /* Check consistency */
         if (fabs(dit_dark-dit_lamp) > 1e-3) {
-            cpl_msg_error(__func__, "DIT not consistent between LAMP and DARK");
-	    /* FIXME: Should an error code be set here? */
-	    skip_if(1);
+            cpl_msg_error(__func__, "DIT not consistent between LAMP and DARK, skip lamp stability computation");
+            /* FIXME: Should an error code be set here? */
+            
+            skip_if(1);
         }
         ditvals[i] = dit_lamp;
         /* Set selection */
         if (i==0) {
             cpl_vector_set(selection, i, -1.0);
             dit_stab ++;
-	    last_stab = 0;
+            last_stab = 0;
         } else {
-	    /*
-	     * The second condition is to make sure that frames taken into
-	     * account for lamp stability are not consecutive.
-	     */
+            /*
+             * The second condition is to make sure that frames taken into
+             * account for lamp stability are not consecutive.
+             */
             if (fabs(dit_lamp - ditvals[0]) < 1e-5 && i - last_stab > 3) {
                 cpl_vector_set(selection, i, -1.0);
                 dit_stab ++;
-		last_stab = i;
+                last_stab = i;
             } else {
                 cpl_vector_set(selection, i, 1.0);
             }
@@ -2619,43 +2829,64 @@ xsh_detmon_lg_lamp_stab(const cpl_frameset * lamps,
         cpl_msg_info(__func__, "Not enough frames for stability check");
     } else {
 
-	/* Load the data and compute lamp-dark */
-	cpl_msg_info(__func__, "Compute the differences lamp - dark");
-	lamps_data = cpl_imagelist_load_frameset(lamps, CPL_TYPE_FLOAT, 1,
-						 whichext);
-	darks_data = cpl_imagelist_load_frameset(darks, CPL_TYPE_FLOAT, 1,
-						 whichext);
-	skip_if(cpl_imagelist_subtract(lamps_data,darks_data));
-
-	/* Check the lamp stability */
-	cpl_msg_info(__func__, "Check the lamp stability");
-	stab_levels = cpl_malloc(dit_stab * sizeof(double));
-	j = 0;
-	for (i=0; i<nb_lamps; i++) {
-	    if (cpl_vector_get(selection, i) < 0) {
-		stab_levels[j] =
-		    cpl_image_get_mean(cpl_imagelist_get(lamps_data, i));
-		j++;
-	    }
-	}
-
-	/* Compute the lamp stability */
-	for (i=1; i<dit_stab; i++) {
-	    if ((fabs(stab_levels[i]-stab_levels[0]) / stab_levels[0]) >
-                detmon_lg_config.lamp_stability)
-		detmon_lg_config.lamp_stability =
-		    fabs(stab_levels[i]-stab_levels[0]) / stab_levels[0];
-	}
-
-
-	/* Check the lamp stability */
-	if (detmon_lg_config.lamp_stability > 0.01) {
+        /* Load the data and compute lamp-dark */
+        cpl_msg_info(__func__, "Compute the differences lamp - dark");
+
+ 
+        lamps_data = xsh_detmon_load_frameset_window(lamps, CPL_TYPE_FLOAT, 0, 
+                                                 whichext,
+                                                 xsh_detmon_lg_config.llx,
+                                                 xsh_detmon_lg_config.lly,
+                                                 xsh_detmon_lg_config.urx,
+                                                 xsh_detmon_lg_config.ury,
+                                                 -1, -1);
+
+        darks_data = xsh_detmon_load_frameset_window(lamps, CPL_TYPE_FLOAT, 0, 
+                                                 whichext,
+                                                 xsh_detmon_lg_config.llx,
+                                                 xsh_detmon_lg_config.lly,
+                                                 xsh_detmon_lg_config.urx,
+                                                 xsh_detmon_lg_config.ury,
+                                                 -1, -1);
+
+        nb_darks=cpl_imagelist_get_size(darks_data);
+        if(nb_darks==nb_lamps) {
+            skip_if(cpl_imagelist_subtract(lamps_data,darks_data));
+        } else {
+            cpl_image* master_dark=cpl_imagelist_collapse_median_create(darks_data);
+            cpl_imagelist_subtract_image(lamps_data,master_dark);
+            cpl_image_delete(master_dark);
+        }
+        /* Check the lamp stability */
+        cpl_msg_info(__func__, "Check the lamp stability");
+        stab_levels = cpl_malloc(dit_stab * sizeof(double));
+        j = 0;
+        for (i=0; i<nb_lamps; i++) {
+            if (cpl_vector_get(selection, i) < 0) {
+                stab_levels[j] =
+                    cpl_image_get_mean(cpl_imagelist_get(lamps_data, i));
+                j++;
+            }
+        }
+     
+        /* Compute the lamp stability */
+        for (i=1; i<dit_stab; i++) {
+            if ((fabs(stab_levels[i]-stab_levels[0]) / stab_levels[0]) >
+                xsh_detmon_lg_config.lamp_stability)
+                xsh_detmon_lg_config.lamp_stability =
+                    fabs(stab_levels[i]-stab_levels[0]) / stab_levels[0];
+        }
+      
+
+        /* Check the lamp stability */
+        if (xsh_detmon_lg_config.lamp_stability > 0.01) {
             cpl_msg_warning(__func__,
-			    "level difference too high - proceed anyway");
-	}
+                            "Lamp stability level %g difference too high - proceed anyway",xsh_detmon_lg_config.lamp_stability);
+        }
     }
     end_skip;
 
+           
     cpl_free(ditvals);
     cpl_vector_delete(selection);
     cpl_imagelist_delete(lamps_data);
@@ -2691,30 +2922,30 @@ xsh_detmon_lg_lamp_stab(const cpl_frameset * lamps,
 /*--------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_lg_reduce_dit(const cpl_frameset * set_on,
-			    int* index_on, double* exptime_on,
-			    const int dit_nb,
-                int * dit_nskip,
-			    const cpl_frameset * set_off,
-			    int * index_off, double* exptime_off,
-			    int* next_on, int* next_off,
-			    cpl_table * linear_table,
-			    cpl_table * gain_table,
-			    cpl_imagelist * linearity_inputs,
-			    cpl_propertylist * qclist,
-			    cpl_boolean opt_nir,
-			    cpl_imagelist * autocorr_images,
-			    cpl_imagelist * diff_flats,
-                cpl_imagelist * opt_offs,
-                int whichext,
-                int* rows_affected)
+                     int* index_on, double* exptime_on,
+                     const int dit_nb,
+                     int * dit_nskip,
+                     const cpl_frameset * set_off,
+                     int * index_off, double* exptime_off,
+                     int* next_on, int* next_off,
+                     cpl_table * linear_table,
+                     cpl_table * gain_table,
+                     cpl_imagelist * linearity_inputs,
+                     cpl_propertylist * qclist,
+                     cpl_boolean opt_nir,
+                     cpl_imagelist * autocorr_images,
+                     cpl_imagelist * diff_flats,
+                     cpl_imagelist * opt_offs,
+                     int whichext,
+                     int* rows_linear_affected,
+                     int* rows_gain_affected)
 {
     cpl_frameset          * pair_on = NULL;
     cpl_frameset          * pair_off = NULL;
     cpl_imagelist         * ons = NULL;
     cpl_imagelist         * offs = NULL;
     cpl_boolean             follow = CPL_TRUE;
-    cpl_imagelist *         masterl = NULL;
-    unsigned mode = detmon_lg_config.autocorr ? IRPLIB_GAIN_WITH_AUTOCORR : 0;
+    unsigned mode = xsh_detmon_lg_config.autocorr ? IRPLIB_GAIN_WITH_AUTOCORR : 0;
     double c_dit;
     int c_ndit;
 
@@ -2725,205 +2956,220 @@ xsh_detmon_lg_reduce_dit(const cpl_frameset * set_on,
     cpl_propertylist * plist = NULL;
     cpl_propertylist* pDETlist = NULL;
 
-    mode = detmon_lg_config.collapse ?
-	mode | IRPLIB_GAIN_COLLAPSE    | IRPLIB_LIN_COLLAPSE:
-	mode | IRPLIB_GAIN_NO_COLLAPSE | IRPLIB_LIN_NO_COLLAPSE;
-    mode = detmon_lg_config.pix2pix  ?
-	mode | IRPLIB_LIN_PIX2PIX : mode;
+    mode = xsh_detmon_lg_config.collapse ?
+        mode | IRPLIB_GAIN_COLLAPSE    | IRPLIB_LIN_COLLAPSE:
+        mode | IRPLIB_GAIN_NO_COLLAPSE | IRPLIB_LIN_NO_COLLAPSE;
+    mode = xsh_detmon_lg_config.pix2pix  ?
+        mode | IRPLIB_LIN_PIX2PIX : mode;
     mode = opt_nir  ?
-	mode | IRPLIB_GAIN_NIR | IRPLIB_LIN_NIR :
-	mode | IRPLIB_GAIN_OPT | IRPLIB_LIN_OPT ;
+        mode | IRPLIB_GAIN_NIR | IRPLIB_LIN_NIR :
+        mode | IRPLIB_GAIN_OPT | IRPLIB_LIN_OPT ;
 
 
     /* ON pair extraction */
-    skip_if(xsh_detmon_pair_extract_next(set_on, index_on, next_on, exptime_on, &pair_on,  detmon_lg_config.tolerance));
+    skip_if(xsh_detmon_pair_extract_next(set_on, index_on, next_on, exptime_on, &pair_on,  xsh_detmon_lg_config.tolerance));
     current_dit = exptime_on[*next_on - 1];
 
     /* Load the ON images */
-    ons = detmon_lg_config.load_fset_wrp(pair_on, CPL_TYPE_FLOAT, whichext);
+    ons = xsh_detmon_lg_config.load_fset_wrp(pair_on, CPL_TYPE_FLOAT, whichext);
     skip_if(ons == NULL);
-    cpl_msg_debug(cpl_func, " Loaded ON images: %" CPL_SIZE_FORMAT ", exptime[%f]",cpl_imagelist_get_size(ons), current_dit );
+    cpl_msg_debug(cpl_func, " Loaded ON images: %"  CPL_SIZE_FORMAT 
+                  ", exptime[%f]",cpl_imagelist_get_size(ons), current_dit );
     if(cpl_imagelist_get_size(ons) != 2)
     {
-    	cpl_msg_error(cpl_func, "cannot take ON pair, number of images[%" CPL_SIZE_FORMAT "]", cpl_imagelist_get_size(ons));
-    	skip_if(TRUE);
+        cpl_msg_error(cpl_func, "cannot take ON pair, number of images[%" 
+                      CPL_SIZE_FORMAT "]", cpl_imagelist_get_size(ons));
+        skip_if(TRUE);
     }
-    if(detmon_lg_config.filter > 0)
+    if(xsh_detmon_lg_config.filter > 0)
     {
-		double med1 =
-			cpl_image_get_median_window(cpl_imagelist_get(ons, 0),
-						detmon_lg_config.llx,
-						detmon_lg_config.lly,
-						detmon_lg_config.urx,
-						detmon_lg_config.ury);
-		double med2 =
-			cpl_image_get_median_window(cpl_imagelist_get(ons, 1),
-						detmon_lg_config.llx,
-						detmon_lg_config.lly,
-						detmon_lg_config.urx,
-						detmon_lg_config.ury);
-		if ( med1 > (double)detmon_lg_config.filter ||
-			 med2 > (double)detmon_lg_config.filter)
-			{
-				follow = CPL_FALSE;
-				cpl_table_select_row(gain_table,   dit_nb);
-				cpl_table_select_row(linear_table, dit_nb);
-				(*dit_nskip)++;
-				cpl_msg_warning(cpl_func, "Frames of EXPTIME nb %d "
-						"will not be taken into account for computation "
-						"as they are above --filter threshold", dit_nb);
-			}
-    }
-
-    if (follow || detmon_lg_config.filter < 0)
+        double med1 =
+            cpl_image_get_median_window(cpl_imagelist_get(ons, 0),
+                                        xsh_detmon_lg_config.llx,
+                                        xsh_detmon_lg_config.lly,
+                                        xsh_detmon_lg_config.urx,
+                                        xsh_detmon_lg_config.ury);
+        double med2 =
+            cpl_image_get_median_window(cpl_imagelist_get(ons, 1),
+                                        xsh_detmon_lg_config.llx,
+                                        xsh_detmon_lg_config.lly,
+                                        xsh_detmon_lg_config.urx,
+                                        xsh_detmon_lg_config.ury);
+        if ( med1 > (double)xsh_detmon_lg_config.filter ||
+             med2 > (double)xsh_detmon_lg_config.filter)
+        {
+            follow = CPL_FALSE;
+            cpl_table_select_row(gain_table,   dit_nb);
+            cpl_table_select_row(linear_table, dit_nb);
+            (*dit_nskip)++;
+            cpl_msg_warning(cpl_func, "Frames of EXPTIME nb %d "
+                            "will not be taken into account for computation "
+                            "as they are above --filter threshold", dit_nb);
+        }
+    }
+
+    if (follow || xsh_detmon_lg_config.filter < 0)
     {
 
-		/*
-		 * If the --collapse option is not activated by the user, the OFF
-		 * sub-frameset is also supposed to be organized into pairs and,
-		 * therefore, processed as the ON sub-frameset.
-		 */
-		if(!detmon_lg_config.collapse)
-		{
-			if (!strcmp(detmon_lg_config.method, "MED") ||
-			cpl_frameset_get_size(set_on) == cpl_frameset_get_size(set_off))
-			{
-				skip_if(xsh_detmon_pair_extract_next(set_off, index_off, next_off, exptime_off, &pair_off,  detmon_lg_config.tolerance));
-			}
-			else
-			{
-				skip_if(xsh_detmon_single_extract_next(set_off, index_off, next_off, exptime_off, &pair_off));
-			}
-			/* Load the OFF images */
-			cpl_msg_debug(cpl_func, "  Load the OFF images, ext[%d], exptime[%f]", whichext, exptime_off[*next_off - 1]);
-			offs = detmon_lg_config.load_fset_wrp(pair_off, CPL_TYPE_FLOAT, whichext);
-
-			skip_if(offs == NULL);
-			skip_if(cpl_error_get_code());
-		} else
-		{
-			/*
-			 * The master bias is required only for
-			 * linearity computation in the OPT domain
-			 */
-			cpl_image * collapse;
-			masterl = cpl_imagelist_load_frameset(set_off, CPL_TYPE_FLOAT,
-											  1, whichext);
-			skip_if(masterl == NULL);
-			skip_if(cpl_error_get_code());
-
-			collapse = cpl_imagelist_collapse_create(masterl);
-			skip_if(collapse == NULL);
-			skip_if(cpl_imagelist_set(masterl, collapse, 0));
-
-			/* Any extra error checking needed here? */
-			offs = (cpl_imagelist *)masterl;
-		}
-
-		/* Rescaling */
-		if(detmon_lg_config.rescale)
-		{
-			skip_if(xsh_detmon_lg_rescale(ons));
-			if (!detmon_lg_config.collapse &&
-			!strcmp(detmon_lg_config.method, "MED"))
-			skip_if(xsh_detmon_lg_rescale(offs));
-		}
-		/* DIT or EXPTIME value extraction */
-
-		filename =
-			cpl_frame_get_filename(cpl_frameset_get_first_const(pair_on));
-		skip_if ((plist = cpl_propertylist_load(filename, 0)) == NULL);
-		/* Add columns to the tables DETi WINi UITi*/
-		if (plist)
-		{
-			pDETlist = cpl_propertylist_new();
-			cpl_propertylist_copy_property_regexp(pDETlist, plist, "DET[0-9]* WIN[0-9]* UIT[0-9]*",0);
-			if (dit_nb == 0)
-			{
-				irplib_table_create_column(gain_table, pDETlist);
-				irplib_table_create_column(linear_table, pDETlist);
-			}
-		}
-		if(opt_nir == NIR) {
-			c_dit = irplib_pfits_get_dit(plist);
-			c_ndit = irplib_pfits_get_ndit(plist);
-		} else {
-			c_dit = irplib_pfits_get_exptime(plist);
-			c_ndit=1;
-		}
-
-		/*
-		 * --GAIN part for each DIT value--
-		 * The following call to xsh_detmon_gain_table_fill_row() fills
-		 * in the row nb i
-		 * of the GAIN table (output) and of the FIT table (by-product to be
-		 * used later for the polynomial computation of the GAIN)
-		 */
-		if(detmon_lg_config.collapse) {
-			offs = (cpl_imagelist *) opt_offs;
-		}
-
-		cpl_msg_info(cpl_func, "Computing GAIN for EXPTIME value nb %d",
-				 dit_nb + 1);
-
-		/* In case PTC is applied, this is allowed */
-		if(cpl_imagelist_get_size(offs) == 1 && mode & IRPLIB_GAIN_NO_COLLAPSE && dit_nb == 0)
-		{
-			cpl_table_erase_column(gain_table, "MEAN_OFF1");
-			cpl_table_erase_column(gain_table, "MEAN_OFF2");
-			cpl_table_erase_column(gain_table, "SIG_OFF_DIF");
-			cpl_table_erase_column(gain_table, "GAIN");
-			cpl_table_erase_column(gain_table, "GAIN_CORR");
-			cpl_table_new_column(gain_table, "MEAN_OFF", CPL_TYPE_DOUBLE);
-		}
-
-		skip_if(xsh_detmon_gain_table_fill_row(gain_table,
-							  c_dit,c_ndit,
-						  autocorr_images,
-						  diff_flats, ons, offs,
-                          detmon_lg_config.kappa,
-                          detmon_lg_config.niter,
-                          detmon_lg_config.llx,
-                          detmon_lg_config.lly,
-                          detmon_lg_config.urx,
-                          detmon_lg_config.ury,
-						  detmon_lg_config.m,
-                          detmon_lg_config.n,
-                          detmon_lg_config.saturation_limit,
-                          dit_nb, mode, rows_affected));
-
-
-		if (*rows_affected)
-		{
-			/* fill DETi WINi OPTi columns - see DFS06921*/
-			skip_if(irplib_fill_table_DETWINUIT(gain_table, pDETlist, dit_nb));
-			/* Linearity reduction */
-			cpl_msg_info(cpl_func, "Linearity reduction for nb %d",
-							 dit_nb + 1);
-			skip_if(xsh_detmon_lin_table_fill_row(linear_table, c_dit,
-								 linearity_inputs, ons, offs,
-								 detmon_lg_config.llx,
-								 detmon_lg_config.lly,
-								 detmon_lg_config.urx,
-								 detmon_lg_config.ury,
-								 dit_nb, *dit_nskip, mode));
-			/* fill DETi WINi OPTi columns - see DFS06921*/
-			skip_if(irplib_fill_table_DETWINUIT(linear_table, pDETlist, dit_nb));
-		}
-
-
-                /* as we know only at this point if a frame is
-                   saturated or not, and we would like to compute the
-                   contamination only on the last non saturated frame,
-                   we need de facto to compute saturation on any non saturated
-                   frame, by overwriting the QC parameter. In the end it will
-                   remain only the last value corresponding to a non saturated
-                   frame */
-
-		if(opt_nir == OPT &&
-                   *rows_affected != 0 ) {
-                   xsh_detmon_opt_contamination(ons, offs, mode, qclist);
-		}
+        /*
+         * If the --collapse option is not activated by the user, the OFF
+         * sub-frameset is also supposed to be organized into pairs and,
+         * therefore, processed as the ON sub-frameset.
+         */
+        if(!xsh_detmon_lg_config.collapse)
+        {
+            /* TODO: We removed this check as with NACO data, that has an odd
+             * number of input OFF frames it would stop with error
+             * despite the recipe would reduce the data properly.
+             * On the other side, on some data without such a check one may get
+             * failures on another place.
+             * we need to document such cases and understand how to better deal
+             * in a robust way the case of odd input off frames
+             *
+            if (cpl_frameset_get_size(set_off) % 2 != 0) {
+                cpl_error_set_message(cpl_func, CPL_ERROR_INCOMPATIBLE_INPUT,
+                                      "If collapse is FALSE the OFF frameset"
+                                      " must be organized in pairs.");
+                skip_if(1);
+            }
+            */
+            if (!strcmp(xsh_detmon_lg_config.method, "MED") ||
+                cpl_frameset_get_size(set_on) == cpl_frameset_get_size(set_off))
+            {
+                skip_if(xsh_detmon_pair_extract_next(set_off, index_off, next_off, exptime_off, &pair_off,  xsh_detmon_lg_config.tolerance));
+            }
+            else
+            {
+                skip_if(xsh_detmon_single_extract_next(set_off, index_off, next_off, exptime_off, &pair_off));
+            }
+            /* Load the OFF images */
+            cpl_msg_debug(cpl_func, "  Load the OFF images, ext[%d], exptime[%f]", whichext, exptime_off[*next_off - 1]);
+            offs = xsh_detmon_lg_config.load_fset_wrp(pair_off, CPL_TYPE_FLOAT, whichext);
+
+            skip_if(offs == NULL);
+            skip_if(cpl_error_get_code());
+        }
+        else {
+            offs = (cpl_imagelist *) opt_offs;
+        }
+
+        /* Rescaling */
+        if(xsh_detmon_lg_config.rescale)
+        {
+            skip_if(xsh_detmon_lg_rescale(ons));
+            if (!xsh_detmon_lg_config.collapse &&
+                !strcmp(xsh_detmon_lg_config.method, "MED"))
+                skip_if(xsh_detmon_lg_rescale(offs));
+        }
+        /* DIT or EXPTIME value extraction */
+
+        filename =
+            cpl_frame_get_filename(cpl_frameset_get_first_const(pair_on));
+        skip_if ((plist = cpl_propertylist_load(filename, 0)) == NULL);
+        /* Add columns to the tables DETi WINi UITi*/
+        if (plist)
+        {
+            pDETlist = cpl_propertylist_new();
+            cpl_propertylist_copy_property_regexp(pDETlist, plist, "DET[0-9]* WIN[0-9]* UIT[0-9]*",0);
+            if (dit_nb == 0)
+            {
+                irplib_table_create_column(gain_table, pDETlist);
+                irplib_table_create_column(linear_table, pDETlist);
+            }
+        }
+        if(opt_nir == NIR) {
+            c_dit = irplib_pfits_get_dit(plist);
+            c_ndit = irplib_pfits_get_ndit(plist);
+        } else {
+            c_dit = irplib_pfits_get_exptime(plist);
+            c_ndit=1;
+        }
+
+        /*
+         * --GAIN part for each DIT value--
+         * The following call to xsh_detmon_gain_table_fill_row() fills
+         * in the row nb i
+         * of the GAIN table (output) and of the FIT table (by-product to be
+         * used later for the polynomial computation of the GAIN)
+         */
+
+        cpl_msg_info(cpl_func, "Computing GAIN for EXPTIME value nb %d",
+                     dit_nb + 1);
+
+        /* In case PTC is applied, this is allowed */
+        if(cpl_imagelist_get_size(offs) == 1 && mode & IRPLIB_GAIN_NO_COLLAPSE && dit_nb == 0)
+        {
+            cpl_table_erase_column(gain_table, "MEAN_OFF1");
+            cpl_table_erase_column(gain_table, "MEAN_OFF2");
+            cpl_table_erase_column(gain_table, "SIG_OFF_DIF");
+            cpl_table_erase_column(gain_table, "GAIN");
+            cpl_table_erase_column(gain_table, "GAIN_CORR");
+            cpl_table_new_column(gain_table, "MEAN_OFF", CPL_TYPE_DOUBLE);
+        }
+
+
+        skip_if(xsh_detmon_gain_table_fill_row(gain_table,
+                                           c_dit,c_ndit,
+                                           autocorr_images,
+                                           diff_flats, ons, offs,
+                                           xsh_detmon_lg_config.kappa,
+                                           xsh_detmon_lg_config.niter,
+                                           xsh_detmon_lg_config.llx,
+                                           xsh_detmon_lg_config.lly,
+                                           xsh_detmon_lg_config.urx,
+                                           xsh_detmon_lg_config.ury,
+                                           xsh_detmon_lg_config.m,
+                                           xsh_detmon_lg_config.n,
+                                           xsh_detmon_lg_config.saturation_limit,
+                                           xsh_detmon_lg_config.gain_threshold,
+                                           dit_nb, mode, rows_gain_affected));
+
+
+        skip_if(xsh_detmon_check_saturation_on_pair(autocorr_images,
+                        diff_flats,ons,offs,
+                        xsh_detmon_lg_config.kappa,
+                        xsh_detmon_lg_config.niter,
+                        xsh_detmon_lg_config.llx,
+                        xsh_detmon_lg_config.lly,
+                        xsh_detmon_lg_config.urx,
+                        xsh_detmon_lg_config.ury,
+                        xsh_detmon_lg_config.saturation_limit,
+                        dit_nb, mode, rows_linear_affected));
+
+
+        if (*rows_gain_affected)
+        {
+            /* fill DETi WINi OPTi columns - see DFS06921*/
+            skip_if(irplib_fill_table_DETWINUIT(gain_table, pDETlist, dit_nb));
+            /* Linearity reduction */
+            cpl_msg_info(cpl_func, "Linearity reduction for nb %d",
+                         dit_nb + 1);
+        }
+        if (*rows_linear_affected) {
+            skip_if(xsh_detmon_lin_table_fill_row(linear_table, c_dit,
+                                              linearity_inputs, ons, offs,
+                                              xsh_detmon_lg_config.llx,
+                                              xsh_detmon_lg_config.lly,
+                                              xsh_detmon_lg_config.urx,
+                                              xsh_detmon_lg_config.ury,
+                                              dit_nb, *dit_nskip, mode));
+            /* fill DETi WINi OPTi columns - see DFS06921*/
+            skip_if(irplib_fill_table_DETWINUIT(linear_table, pDETlist, dit_nb));
+        }
+
+
+        /* as we know only at this point if a frame is
+           saturated or not, and we would like to compute the
+           contamination only on the last non saturated frame,
+           we need de facto to compute saturation on any non saturated
+           frame, by overwriting the QC parameter. In the end it will
+           remain only the last value corresponding to a non saturated
+           frame */
+
+        if(opt_nir == OPT &&
+           *rows_linear_affected != 0 ) {
+            xsh_detmon_opt_contamination(ons, offs, mode, qclist);
+        }
 
     }
 
@@ -2932,16 +3178,12 @@ xsh_detmon_lg_reduce_dit(const cpl_frameset * set_on,
     cpl_frameset_delete(pair_on);
     cpl_imagelist_delete(ons);
 
-    if(!detmon_lg_config.collapse ) {
-	cpl_imagelist_delete(offs);
-    }
-
-    if(!detmon_lg_config.collapse) {
-	cpl_frameset_delete(pair_off);
+    if(!xsh_detmon_lg_config.collapse ) {
+        cpl_imagelist_delete(offs);
     }
 
-    if(detmon_lg_config.collapse) {
-	cpl_imagelist_delete(masterl);
+    if(!xsh_detmon_lg_config.collapse) {
+        cpl_frameset_delete(pair_off);
     }
 
     cpl_propertylist_delete(plist);
@@ -2958,7 +3200,7 @@ xsh_detmon_lg_reduce_dit(const cpl_frameset * set_on,
 /*---------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_add_adl_column(cpl_table * table,
-                             cpl_boolean opt_nir)
+                      cpl_boolean opt_nir)
 {
     cpl_error_code          error;
     double                  mean_med_dit;
@@ -2968,9 +3210,9 @@ xsh_detmon_add_adl_column(cpl_table * table,
 
     mean_med_dit = cpl_table_get_column_mean(table, "MED_DIT");
     if (opt_nir == OPT)
-	dits = cpl_table_get_data_double(table, "EXPTIME");
+        dits = cpl_table_get_data_double(table, "EXPTIME");
     else
-	dits = cpl_table_get_data_double(table, "DIT");
+        dits = cpl_table_get_data_double(table, "DIT");
 
     error = cpl_table_copy_data_double(table, "ADL", dits);
     cpl_ensure_code(!error, error);
@@ -2991,16 +3233,16 @@ xsh_detmon_add_adl_column(cpl_table * table,
 /*---------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_lg_reduce_init(cpl_table * gain_table,
-                             cpl_table * linear_table,
-                             cpl_imagelist ** linearity_inputs,
-                             const cpl_boolean opt_nir)
+                      cpl_table * linear_table,
+                      cpl_imagelist ** linearity_inputs,
+                      const cpl_boolean opt_nir)
 {
     skip_if(xsh_detmon_gain_table_create(gain_table, opt_nir));
     skip_if(xsh_detmon_lin_table_create(linear_table, opt_nir));
 
-    if(detmon_lg_config.pix2pix) {
-	*linearity_inputs = cpl_imagelist_new();
-	skip_if(*linearity_inputs == NULL);
+    if(xsh_detmon_lg_config.pix2pix) {
+        *linearity_inputs = cpl_imagelist_new();
+        skip_if(*linearity_inputs == NULL);
     }
 
     end_skip;
@@ -3018,7 +3260,7 @@ xsh_detmon_lg_reduce_init(cpl_table * gain_table,
 static double
 irplib_pfits_get_dit(const cpl_propertylist * plist)
 {
-	return irplib_pfits_get_prop_double(plist, "ESO DET DIT");
+    return irplib_pfits_get_prop_double(plist, "ESO DET DIT");
 }
 
 /*--------------------------------------------------------------------------*/
@@ -3031,7 +3273,7 @@ irplib_pfits_get_dit(const cpl_propertylist * plist)
 static double
 irplib_pfits_get_dit_opt(const cpl_propertylist * plist)
 {
-	return irplib_pfits_get_prop_double(plist, "ESO DET WIN1 UIT1");
+    return irplib_pfits_get_prop_double(plist, "ESO DET WIN1 UIT1");
 }
 
 
@@ -3043,35 +3285,197 @@ irplib_pfits_get_dit_opt(const cpl_propertylist * plist)
 static cpl_propertylist*
 xsh_detmon_load_pro_keys(const char* NAME_O)
 {
-   cpl_propertylist* pro_keys=NULL;
-   pro_keys=cpl_propertylist_load_regexp(NAME_O,0,"^(ESO PRO)",0);
-   return pro_keys;
+    cpl_propertylist* pro_keys=NULL;
+    pro_keys=cpl_propertylist_load_regexp(NAME_O,0,"^(ESO PRO)",0);
+    return pro_keys;
 }
 
 
-static double irplib_pfits_get_prop_double(const cpl_propertylist * plist, const char* prop_name)
+static double irplib_pfits_get_prop_double(const cpl_propertylist * plist,
+                                           const char* prop_name)
 {
-   double dit;
-   dit = cpl_propertylist_get_double(plist, prop_name);
-   if(cpl_error_get_code() != CPL_ERROR_NONE)
-   {
-	   cpl_msg_error(cpl_func, "Cannot read property '%s', err[%s]",prop_name, cpl_error_get_where());
-   }
-   return dit;
+    double dit;
+    dit = cpl_propertylist_get_double(plist, prop_name);
+    if(cpl_error_get_code() != CPL_ERROR_NONE)
+    {
+        cpl_msg_error(cpl_func, "Cannot read property '%s', err[%s]",
+                      prop_name, cpl_error_get_where());
+    }
+    return dit;
+}
+
+static cpl_error_code
+xsh_detmon_gain_compute_qc(double kappa, int nclip, const int pos,
+                       const cpl_imagelist* offs, unsigned mode,
+                       double double_adu, double avg_on1, double avg_on2,
+                       double avg_off1, double avg_off2, double sigma,
+                       double sig_off_dif, double gain, int c_ndit,
+                       double gain_corr, double autocorr, cpl_image* on_dif,
+                       cpl_table* gain_table)
+{
+
+    /* here xsh_detmon actually computes gain QC parameter */
+    double avg_on_dif, sig_on_dif;
+    xsh_ksigma_clip(on_dif, 1, 1, cpl_image_get_size_x(on_dif),
+                       cpl_image_get_size_y(on_dif), kappa, nclip, 1e-5,
+                       &avg_on_dif, &sig_on_dif);
+    skip_if(
+                    cpl_table_set_double(gain_table, "SIG_ON_DIF", pos,
+                                    sig_on_dif));
+    if (cpl_imagelist_get_size(offs) == 1 && mode & IRPLIB_GAIN_NO_COLLAPSE) {
+        double_adu = (avg_on1 + avg_on2) - 2 * avg_off1;
+    }
+    else {
+        double_adu = (avg_on1 + avg_on2) - (avg_off1 + avg_off2);
+
+        sigma = (sig_on_dif * sig_on_dif) - (sig_off_dif * sig_off_dif);
+
+        /* sigma_corr = autocorr * sigma; */
+
+        gain = double_adu / (c_ndit * sigma);
+
+        gain_corr = gain / (autocorr);
+
+        skip_if(cpl_table_set_double(gain_table, "GAIN", pos, gain));
+        skip_if(
+                        cpl_table_set_double(gain_table, "GAIN_CORR", pos,
+                                        gain_corr));
+    }
+    /* cpl_msg_info(cpl_func,"gain=%g gain_corr=%g autocorr=%g",gain,gain_corr,autocorr); */
+    skip_if(cpl_table_set_double(gain_table, "AUTOCORR", pos, autocorr));
+    skip_if(cpl_table_set_double(gain_table, "ADU", pos, double_adu / 2));
+    /* FIXME: Remove the following 3 columns after testing period */
+    skip_if(
+                    cpl_table_set_double(gain_table, "Y_FIT", pos,
+                                    c_ndit * sig_on_dif * sig_on_dif));
+    skip_if(
+                    cpl_table_set_double(gain_table, "Y_FIT_CORR", pos,
+                                    c_ndit * sig_on_dif * sig_on_dif));
+    skip_if(cpl_table_set_double(gain_table, "X_FIT", pos, double_adu));
+    skip_if(
+                    cpl_table_set_double(gain_table, "X_FIT_CORR", pos,
+                                    double_adu / autocorr));
+
+    end_skip;
+
+      return cpl_error_get_code();
+}
+
+double
+xsh_detmon_gain_prepare_autocorr(unsigned mode, const int pos, double autocorr,
+                             int m, int n, cpl_imagelist* diff_flats,
+                             cpl_image* on_dif, cpl_imagelist* autocorr_images)
+{
+    if (mode & IRPLIB_GAIN_WITH_AUTOCORR) {
+        if (diff_flats) {
+            cpl_image * diff = cpl_image_duplicate(on_dif);
+            skip_if(cpl_imagelist_set(diff_flats, diff, pos));
+        }
+        if (autocorr_images) {
+            cpl_image * corr = NULL;
+            autocorr = xsh_detmon_autocorr_factor(on_dif, &corr, m, n);
+            if (corr) {
+                skip_if(cpl_imagelist_set(autocorr_images, corr, pos));
+            }
+            else {
+                xsh_detmon_lg_add_empty_image(autocorr_images, pos);
+            }
+        }
+        else {
+            autocorr = xsh_detmon_autocorr_factor(on_dif, NULL, m, n);
+        }
+        autocorr = isnan(autocorr) ? 1.0 : autocorr;
+    }
+    else {
+        autocorr = 1.0;
+    }
+    end_skip;
+
+    return autocorr;
+}
+
+double
+xsh_detmon_gain_prepare_table(const cpl_imagelist* offs, unsigned mode, int llx,
+                          int lly, int urx, int ury, double kappa, int nclip,
+                          double avg_off1, double std, const int pos,
+                          cpl_table* gain_table, double* avg_off2,
+                          double* sig_off_dif)
+{
+    /* prepare gain table to compute gain QC param */
+    /* TODO: AMO sees that the condition  (mode & IRPLIB_GAIN_NO_COLLAPSE)
+     * is repeated in 2 if entries==> probably one should rewrite the if
+     * construct
+     */
+    if (cpl_imagelist_get_size(offs) == 1 && mode & IRPLIB_GAIN_NO_COLLAPSE) {
+
+        skip_if(
+                        xsh_ksigma_clip(cpl_imagelist_get_const(offs, 0),
+                                        llx, lly, urx, ury, kappa, nclip, 1e-5,
+                                        &avg_off1, &std));
+        skip_if(cpl_table_set_double(gain_table, "MEAN_OFF", pos, avg_off1));
+
+    }
+    else if ((mode & IRPLIB_GAIN_NO_COLLAPSE)
+                    || (pos == 0 && mode & IRPLIB_GAIN_COLLAPSE)) {
+        cpl_image * off_dif = NULL;
+        double avg_off_dif;
+        skip_if(
+                        xsh_ksigma_clip(cpl_imagelist_get_const(offs, 0),
+                                        llx, lly, urx, ury, kappa, nclip, 1e-5,
+                                        &avg_off1, &std));
+        skip_if(cpl_table_set_double(gain_table, "MEAN_OFF1", pos, avg_off1));
+        skip_if(
+                        xsh_ksigma_clip(cpl_imagelist_get_const(offs, 1),
+                                        llx, lly, urx, ury, kappa, nclip, 1e-5,
+                                        avg_off2, &std));
+        skip_if(cpl_table_set_double(gain_table, "MEAN_OFF2", pos, *avg_off2));
+        off_dif = xsh_detmon_subtract_create_window(
+                        cpl_imagelist_get_const(offs, 0),
+                        cpl_imagelist_get_const(offs, 1), llx, lly, urx, ury);
+        skip_if(off_dif == NULL);
+        xsh_ksigma_clip(off_dif, 1, 1, cpl_image_get_size_x(off_dif),
+                        cpl_image_get_size_y(off_dif), kappa, nclip, 1e-5,
+                        &avg_off_dif, sig_off_dif);
+        cpl_image_delete(off_dif);
+        skip_if(
+                        cpl_table_set_double(gain_table, "SIG_OFF_DIF", pos,
+                                        *sig_off_dif));
+    }
+    else if (pos > 0 && (mode & IRPLIB_GAIN_COLLAPSE)) {
+
+        int status;
+        avg_off1 = cpl_table_get_double(gain_table, "MEAN_OFF1", 0, &status);
+        skip_if(cpl_table_set_double(gain_table, "MEAN_OFF1", pos, avg_off1));
+        *avg_off2 = cpl_table_get_double(gain_table, "MEAN_OFF2", 0, &status);
+        skip_if(cpl_table_set_double(gain_table, "MEAN_OFF2", pos, *avg_off2));
+        *sig_off_dif = cpl_table_get_double(gain_table, "SIG_OFF_DIF", 0,
+                        &status);
+        skip_if(
+                        cpl_table_set_double(gain_table, "SIG_OFF_DIF", pos,
+                                        *sig_off_dif));
+    }
+
+    end_skip;
+
+    return avg_off1;
 }
+
 /*---------------------------------------------------------------------------*/
 /**
   @brief    Operate on input ON and OFF images related to gain
             Computes all quantities needed to determine the gain:
 
 
-  @param    gain_table             Gain table
-  @param    autocorr_images        Corr images (intermediate product)
-  @param    diff_flats             Diff flats (intermediate product)
-  @param    ons                    Images of the ON pair
-  @param    offs                   Images of the OFF pair
-  @param    pos                    DIT being processed (entry pos. in table)
-
+  @param    gain_table       Gain table
+  @param    autocorr_images  Corr images (intermediate product)
+  @param    diff_flats       Diff flats (intermediate product)
+  @param    ons              Images of the ON pair
+  @param    offs             Images of the OFF pair
+  @param    pos              DIT being processed (entry pos. in table)
+  @param    mode             Possible options (combined with bitwise or)
+                             autocorr true/false, opt/nir, collapse true/false
+                             pix2pix true/false
+  @param    rows_affected    this parameter is set to skip gain computation
 
   @doc      To compute the gain are needed the following quantities:
             -a clean mean on each ON and OFF frame of the pair,
@@ -3094,212 +3498,227 @@ static double irplib_pfits_get_prop_double(const cpl_propertylist * plist, const
 /*---------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_gain_table_fill_row(cpl_table * gain_table,
-				  double c_dit,int c_ndit,
-				  cpl_imagelist * autocorr_images,
-				  cpl_imagelist * diff_flats,
-				  const cpl_imagelist * ons,
-                                  const cpl_imagelist * offs,
-                                  double kappa, int nclip,
-                                  int llx, int lly, int urx, int ury,
-                                  int m, int n,
-                                  double saturation_limit,
-				  const int pos, unsigned mode, int* rows_affected)
+                           double c_dit,int c_ndit,
+                           cpl_imagelist * autocorr_images,
+                           cpl_imagelist * diff_flats,
+                           const cpl_imagelist * ons,
+                           const cpl_imagelist * offs,
+                           double kappa, int nclip,
+                           int llx, int lly, int urx, int ury,
+                           int m, int n,
+                           double saturation_limit,
+                           double gain_threshold,
+                           const int pos, unsigned mode, int* rows_gain_affected)
 {
-    const cpl_image        *image=NULL;
-    double                  std = 0;
+    const cpl_image        *image;
     cpl_image              *on_dif = NULL;
-    cpl_image              *off_dif = NULL;
-    double                  avg_on1=0, avg_on2=0;
-    double                  avg_off1=0, avg_off2=0;
-    double                  avg_on_dif=0, sig_on_dif=0;
-    double                  avg_off_dif=0, sig_off_dif=0;
-    double                  double_adu=0, autocorr=0, gain=0, gain_corr=0;
-    double                  sigma=0;
-    //double sigma_corr=0;
+    double                  std = 0;
+    double                  avg_on1, avg_on2;
+    double                  avg_off1, avg_off2;
+    double                  double_adu, autocorr, gain, gain_corr;
+    double                  sigma;
 
     cpl_table_set(gain_table, "FLAG", pos, 1);
     if (mode & IRPLIB_GAIN_NIR)
     {
-    	cpl_table_set(gain_table, "DIT", pos, c_dit);
-    	cpl_table_set(gain_table, "NDIT", pos, c_ndit);
+        cpl_table_set(gain_table, "DIT", pos, c_dit);
+        cpl_table_set(gain_table, "NDIT", pos, c_ndit);
     } else if (mode & IRPLIB_GAIN_OPT)
     {
-    	cpl_table_set(gain_table, "EXPTIME", pos, c_dit);
+        cpl_table_set(gain_table, "EXPTIME", pos, c_dit);
     } else
     {
-		cpl_msg_error(cpl_func, "Mandatory mode (OPT or NIR) not provided");
-		skip_if(1);
+        cpl_msg_error(cpl_func, "Mandatory mode (OPT or NIR) not provided");
+        skip_if(1);
     }
-    if(*rows_affected == 0)
+    if(*rows_gain_affected == 0)
     {
-    	cpl_msg_info(cpl_func, "skip the frame #%d", pos + 1);
-    	cpl_table_set(gain_table, "FLAG", pos, 0);
-    	if(mode & IRPLIB_GAIN_WITH_AUTOCORR)
-		{
-		  autocorr = -1;
-		  if (diff_flats)
-		  {
-			  xsh_detmon_lg_add_empty_image(diff_flats, pos);
-		  }
-		  if (autocorr_images)
-		  {
-			  xsh_detmon_lg_add_empty_image(autocorr_images, pos);
-		  }
-		}
-    	return cpl_error_get_code();
+        cpl_msg_info(cpl_func, "skip the frame #%d", pos + 1);
+        cpl_table_set(gain_table, "FLAG", pos, 0);
+        if(mode & IRPLIB_GAIN_WITH_AUTOCORR)
+        {
+            autocorr = -1;
+            if (diff_flats)
+            {
+                xsh_detmon_lg_add_empty_image(diff_flats, pos);
+            }
+            if (autocorr_images)
+            {
+                xsh_detmon_lg_add_empty_image(autocorr_images, pos);
+            }
+        }
+        return cpl_error_get_code();
     }
     skip_if((image = cpl_imagelist_get_const(ons, 0)) == NULL);
     skip_if(xsh_ksigma_clip(image, llx, lly, urx, ury, kappa,
-                                         nclip, 1e-5, &avg_on1, &std));
-	skip_if((image = cpl_imagelist_get_const(ons, 1)) == NULL);
-	skip_if(xsh_ksigma_clip(image, llx, lly, urx, ury, kappa,
-					 nclip, 1e-5, &avg_on2, &std));
+                               nclip, 1e-5, &avg_on1, &std));
+    skip_if((image = cpl_imagelist_get_const(ons, 1)) == NULL);
+    skip_if(xsh_ksigma_clip(image, llx, lly, urx, ury, kappa,
+                               nclip, 1e-5, &avg_on2, &std));
 
-    if ((avg_on1 > saturation_limit) || (avg_on2 > saturation_limit))
+    if (
+         (avg_on1 > gain_threshold) ||
+         (avg_on2 > gain_threshold)
+       )
     {
-    	cpl_msg_warning(cpl_func, "Average saturation is above the limit, the frames would not be taken into calculation");
-    	cpl_msg_warning(cpl_func, "saturation levels [%f ; %f], limit [%f]", avg_on1, avg_on2, saturation_limit);
-    	cpl_msg_info(cpl_func, "skip the frame #%d", pos + 1);
-    	cpl_table_set(gain_table, "FLAG", pos, 0);
-		if(mode & IRPLIB_GAIN_WITH_AUTOCORR)
-		{
-		  autocorr = -1;
-		  if (diff_flats)
-		  {
-			  xsh_detmon_lg_add_empty_image(diff_flats, pos);
-		  }
-		  if (autocorr_images)
-		  {
-			  xsh_detmon_lg_add_empty_image(autocorr_images, pos);
-		  }
-		}
-    	*rows_affected = 0;
+        /* If frames has intensity above threshold write out warning and adjust
+         * imagelists
+         */
+        if ( (avg_on1 > gain_threshold) || (avg_on2 > gain_threshold) )
+        {
+            cpl_msg_warning(cpl_func, "Average level is above the limit set by the gain_theshold parameter, "
+                            "the frames would not be taken into calculation");
+
+            cpl_msg_warning(cpl_func, "Average levels [%f ; %f], limit [%f]",
+                            avg_on1, avg_on2, gain_threshold);
+        }
+
+        cpl_msg_info(cpl_func, "skip the frame #%d", pos + 1);
+        cpl_table_set(gain_table, "FLAG", pos, 0);
+        if(mode & IRPLIB_GAIN_WITH_AUTOCORR)
+        {
+            autocorr = -1;
+            if (diff_flats)
+            {
+                xsh_detmon_lg_add_empty_image(diff_flats, pos);
+            }
+            if (autocorr_images)
+            {
+                xsh_detmon_lg_add_empty_image(autocorr_images, pos);
+            }
+        }
+        *rows_gain_affected = 0;
     }
     else
     {
-    	*rows_affected = 1;
-		skip_if(cpl_table_set_double(gain_table, "MEAN_ON1", pos, avg_on1));
-		skip_if(cpl_table_set_double(gain_table, "MEAN_ON2", pos, avg_on2));
-		on_dif =
-		cpl_image_subtract_create(cpl_imagelist_get_const(ons, 0),
-					  cpl_imagelist_get_const(ons, 1));
-		skip_if(on_dif == NULL);
-		skip_if(xsh_ksigma_clip(on_dif, llx, lly, urx, ury, kappa,
-						 nclip, 1e-5,
-											 &avg_on_dif, &sig_on_dif));
-		skip_if(cpl_table_set_double(gain_table, "SIG_ON_DIF", pos, sig_on_dif));
-
-		if(mode & IRPLIB_GAIN_WITH_AUTOCORR)
-		{
-		  if (diff_flats)
-		  {
-			  cpl_image * diff = cpl_image_duplicate(on_dif);
-			  skip_if(cpl_imagelist_set(diff_flats, diff, pos));
-		  }
-		  if (autocorr_images)
-		  {
-			cpl_image * corr = NULL;
-			autocorr = xsh_detmon_autocorr_factor(on_dif, &corr, m, n);
-			if(corr)
-			{
-				skip_if(cpl_imagelist_set(autocorr_images, corr, pos));
-			}
-			else
-			{
-				xsh_detmon_lg_add_empty_image(autocorr_images, pos);
-			}
-		  } else
-		  {
-			autocorr = xsh_detmon_autocorr_factor(on_dif, NULL, m, n);
-		  }
-		  autocorr = isnan(autocorr) ? 1.0 : autocorr;
-		} else
-		{
-			autocorr = 1.0;
-		}
-
-		if (cpl_imagelist_get_size(offs) == 1 && mode & IRPLIB_GAIN_NO_COLLAPSE)
-		{
-
-			skip_if(xsh_ksigma_clip(cpl_imagelist_get_const(offs, 0),
-					   llx, lly, urx, ury, kappa, nclip,
-					   1e-5, &avg_off1, &std));
-			skip_if(cpl_table_set_double(gain_table, "MEAN_OFF", pos, avg_off1));
-
-		} else if (mode & IRPLIB_GAIN_NO_COLLAPSE ||
-			 ( pos == 0 && mode & IRPLIB_GAIN_COLLAPSE )) {
-			skip_if(xsh_ksigma_clip(cpl_imagelist_get_const(offs, 0),
-												 llx, lly, urx, ury, kappa, nclip,
-												 1e-5, &avg_off1, &std));
-			skip_if(cpl_table_set_double(gain_table, "MEAN_OFF1", pos, avg_off1));
-			skip_if(xsh_ksigma_clip(cpl_imagelist_get_const(offs, 1),
-												 llx, lly, urx, ury, kappa, nclip,
-							 1e-5, &avg_off2, &std));
-			skip_if(cpl_table_set_double(gain_table, "MEAN_OFF2", pos, avg_off2));
-			off_dif =
-				cpl_image_subtract_create(cpl_imagelist_get_const(offs, 0),
-										  cpl_imagelist_get_const(offs, 1));
-			skip_if(off_dif == NULL);
-			skip_if(xsh_ksigma_clip(off_dif, llx, lly, urx, ury,
-												 kappa, nclip, 1e-5,
-							 &avg_off_dif, &sig_off_dif));
-			skip_if(cpl_table_set_double(gain_table, "SIG_OFF_DIF",
-						 pos, sig_off_dif));
-		} else if (pos > 0 && mode & IRPLIB_GAIN_COLLAPSE)
-		{
-			int status;
-			avg_off1 = cpl_table_get_double(gain_table, "MEAN_OFF1", 0, &status);
-			skip_if(cpl_table_set_double(gain_table, "MEAN_OFF1", pos, avg_off1));
-			avg_off2 = cpl_table_get_double(gain_table, "MEAN_OFF2", 0, &status);
-			skip_if(cpl_table_set_double(gain_table, "MEAN_OFF2", pos, avg_off2));
-			sig_off_dif = cpl_table_get_double(gain_table, "SIG_OFF_DIF",
-											   0, &status);
-			skip_if(cpl_table_set_double(gain_table, "SIG_OFF_DIF",
-										 pos, sig_off_dif));
-		}
-
-		if (cpl_imagelist_get_size(offs) == 1 && mode & IRPLIB_GAIN_NO_COLLAPSE)
-		{
-			double_adu = (avg_on1 + avg_on2) - 2 * avg_off1;
-		}
-		else
-		{
-			double_adu = (avg_on1 + avg_on2) - (avg_off1 + avg_off2);
-
-			sigma = (sig_on_dif * sig_on_dif) - (sig_off_dif * sig_off_dif);
-
-			//sigma_corr = autocorr * sigma;
-
-			gain = double_adu / (c_ndit * sigma);
-
-			gain_corr = gain / (autocorr);
-
-			skip_if(cpl_table_set_double(gain_table, "GAIN", pos, gain));
-			skip_if(cpl_table_set_double(gain_table, "GAIN_CORR", pos, gain_corr));
-		}
-
-		skip_if(cpl_table_set_double(gain_table, "AUTOCORR", pos, autocorr));
-		skip_if(cpl_table_set_double(gain_table, "ADU", pos, double_adu / 2));
-
-		/* FIXME: Remove the following 3 columns after testing period */
-		skip_if(cpl_table_set_double(gain_table, "Y_FIT",
-					     pos,
-					     c_ndit* sig_on_dif * sig_on_dif));
-		skip_if(cpl_table_set_double(gain_table, "Y_FIT_CORR",
-					     pos,
-					     c_ndit * sig_on_dif * sig_on_dif));
-		skip_if(cpl_table_set_double(gain_table, "X_FIT", pos, double_adu));
-		skip_if(cpl_table_set_double(gain_table, "X_FIT_CORR",
-					 pos, double_adu / autocorr));
+        /* we can compute gain: first computes relevant quantities to cover all
+         * cases, then compute QC parameter.
+         */
+        double sig_off_dif;
+        *rows_gain_affected = 1;
+        skip_if(cpl_table_set_double(gain_table, "MEAN_ON1", pos, avg_on1));
+        skip_if(cpl_table_set_double(gain_table, "MEAN_ON2", pos, avg_on2));
+
+        on_dif =
+            xsh_detmon_subtract_create_window(cpl_imagelist_get_const(ons, 0),
+                                          cpl_imagelist_get_const(ons, 1),
+                                          llx, lly, urx, ury);
+        skip_if(on_dif == NULL);
+
+        autocorr = xsh_detmon_gain_prepare_autocorr(mode, pos, autocorr, m, n,
+                        diff_flats, on_dif, autocorr_images);
+
+        avg_off1 = xsh_detmon_gain_prepare_table(offs, mode, llx, lly, urx, ury,
+                        kappa, nclip, avg_off1, std, pos, gain_table, &avg_off2,
+                        &sig_off_dif);
+
+        xsh_detmon_gain_compute_qc(kappa, nclip, pos, offs, mode, double_adu,
+                        avg_on1, avg_on2, avg_off1, avg_off2, sigma,
+                        sig_off_dif, gain, c_ndit, gain_corr, autocorr, on_dif,
+                        gain_table);
     }
     end_skip;
 
     cpl_image_delete(on_dif);
-    cpl_image_delete(off_dif);
 
     return cpl_error_get_code();
 }
 
+
+
+/*---------------------------------------------------------------------------*/
+/**
+  @brief    Operate on input ON and OFF images related to gain
+            Computes all quantities needed to determine the gain:
+
+
+  @param    autocorr_images  Corr images (intermediate product)
+  @param    diff_flats       Diff flats (intermediate product)
+  @param    ons              Images of the ON pair
+  @param    offs             Images of the OFF pair
+  @param    pos              DIT being processed (entry pos. in table)
+  @param    mode             Possible options (combined with bitwise or)
+                             autocorr true/false, opt/nir, collapse true/false
+                             pix2pix true/false
+  @param    rows_linear_affected    this parameter is set to skip gain computation
+
+  @doc      To compute the gain are needed the following quantities:
+            -a clean mean on each ON and OFF frame of the pair,
+            -a clean standard deviation on each difference ON-OFF of the pair,
+
+  @return   cpl_error_code.
+ */
+/*---------------------------------------------------------------------------*/
+static cpl_error_code
+xsh_detmon_check_saturation_on_pair(cpl_imagelist * autocorr_images,
+                           cpl_imagelist * diff_flats,
+                           const cpl_imagelist * ons,
+                           const cpl_imagelist * offs,
+                           double kappa, int nclip,
+                           int llx, int lly, int urx, int ury,
+                           double saturation_limit,
+                           const int pos, unsigned mode, int* rows_linear_affected)
+{
+    const cpl_image        *image;
+    double                  std = 0;
+    double                  avg_on1, avg_on2;
+    double                  sigma;
+
+
+    if(*rows_linear_affected == 0)
+    {
+        cpl_msg_info(cpl_func, "For linearity skip the frame #%d", pos + 1);
+        if(mode & IRPLIB_GAIN_WITH_AUTOCORR)
+        {
+            if (diff_flats)
+            {
+                xsh_detmon_lg_add_empty_image(diff_flats, pos);
+            }
+            if (autocorr_images)
+            {
+                xsh_detmon_lg_add_empty_image(autocorr_images, pos);
+            }
+        }
+        return cpl_error_get_code();
+    }
+    skip_if((image = cpl_imagelist_get_const(ons, 0)) == NULL);
+    skip_if(xsh_ksigma_clip(image, llx, lly, urx, ury, kappa,
+                               nclip, 1e-5, &avg_on1, &std));
+    skip_if((image = cpl_imagelist_get_const(ons, 1)) == NULL);
+    skip_if(xsh_ksigma_clip(image, llx, lly, urx, ury, kappa,
+                               nclip, 1e-5, &avg_on2, &std));
+
+    if (
+         (avg_on1 > saturation_limit) ||
+         (avg_on2 > saturation_limit)
+       )
+    {
+        /* If frames has intensity above threshold write out warning and adjust
+         * imagelists
+         */
+        if ( (avg_on1 > saturation_limit) || (avg_on2 > saturation_limit) )
+        {
+            cpl_msg_warning(cpl_func, "Average level is above the limit set by the saturation_limit parameter, "
+                            "the frames would not be taken into calculation");
+
+            cpl_msg_warning(cpl_func, "Average levels [%f ; %f], limit [%f]",
+                            avg_on1, avg_on2, saturation_limit);
+        }
+
+        cpl_msg_info(cpl_func, "skip the frame #%d", pos + 1);
+        *rows_linear_affected = 0;
+    } else{
+
+    }
+
+    end_skip;
+
+    return cpl_error_get_code();
+}
+
+
+
+
 /*--------------------------------------------------------------------------*/
 /**
   @brief  Produce bad pixel map according to coefficients' cube
@@ -3311,64 +3730,64 @@ xsh_detmon_gain_table_fill_row(cpl_table * gain_table,
 
 static cpl_image       *
 xsh_detmon_bpixs(const cpl_imagelist * coeffs,
-                    cpl_boolean bpmbin,
-                    const double kappa,
-                    int *nbpixs)
+             cpl_boolean bpmbin,
+             const double kappa,
+             int *nbpixs)
 {
-    int                     size;
-    int                     i;
+
+
     const cpl_image        *first= cpl_imagelist_get_const(coeffs, 0);
-    cpl_stats              *stats;
-    double                  cur_mean;
-    double                  cur_stdev;
-    double                  lo_cut;
-    double                  hi_cut;
-    cpl_mask               *cur_mask;
+
+
+
+
+
+
     cpl_mask               *mask = cpl_mask_new(cpl_image_get_size_x(first),
-	                                        cpl_image_get_size_y(first));
-    cpl_image              *cur_image = NULL;
+                                                cpl_image_get_size_y(first));
+
     cpl_image              *bpm = NULL; /* Avoid false uninit warning */
-    double                  p;
 
-    size = cpl_imagelist_get_size(coeffs);
+
+    int size = cpl_imagelist_get_size(coeffs);
 
     if(!bpmbin) {
-	bpm = cpl_image_new(cpl_image_get_size_x(first),
-		 	    cpl_image_get_size_y(first),
-			    CPL_TYPE_INT);
+        bpm = cpl_image_new(cpl_image_get_size_x(first),
+                            cpl_image_get_size_y(first),
+                            CPL_TYPE_INT);
     }
 
 
-    for(i = 0; i < size; i++) {
+    for(int i = 0; i < size; i++) {
         const cpl_image * cur_coeff = cpl_imagelist_get_const(coeffs, i);
 
-        stats = cpl_stats_new_from_image(cur_coeff,
+        cpl_stats* stats = cpl_stats_new_from_image(cur_coeff,
                                          CPL_STATS_MEAN | CPL_STATS_STDEV);
-        cur_mean = cpl_stats_get_mean(stats);
-        cur_stdev = cpl_stats_get_stdev(stats);
+        double cur_mean = cpl_stats_get_mean(stats);
+        double cur_stdev = cpl_stats_get_stdev(stats);
 
-        lo_cut = cur_mean - kappa * cur_stdev;
-        hi_cut = cur_mean + kappa * cur_stdev;
+        double lo_cut = cur_mean - kappa * cur_stdev;
+        double hi_cut = cur_mean + kappa * cur_stdev;
 
-        cur_mask = cpl_mask_threshold_image_create(cur_coeff, lo_cut, hi_cut);
+        cpl_mask* cur_mask = cpl_mask_threshold_image_create(cur_coeff, lo_cut, hi_cut);
         cpl_mask_not(cur_mask);
 
-	if(!bpmbin) {
-	    cur_image = cpl_image_new_from_mask(cur_mask);
-	    p = pow(2, i);
-	    cpl_image_power(cur_image, p);
-	    cpl_image_add(bpm, cur_image);
-	    cpl_image_delete(cur_image);
-	}
+        if(!bpmbin) {
+            cpl_image* cur_image = cpl_image_new_from_mask(cur_mask);
+            double p = pow(2, i);
+            cpl_image_power(cur_image, p);
+            cpl_image_add(bpm, cur_image);
+            cpl_image_delete(cur_image);
+        }
 
-	cpl_mask_or(mask, cur_mask);
+        cpl_mask_or(mask, cur_mask);
 
         cpl_mask_delete(cur_mask);
         cpl_stats_delete(stats);
     }
 
     if(bpmbin) {
-	bpm = cpl_image_new_from_mask(mask);
+        bpm = cpl_image_new_from_mask(mask);
     }
 
     *nbpixs += cpl_mask_count(mask);
@@ -3378,6 +3797,113 @@ xsh_detmon_bpixs(const cpl_imagelist * coeffs,
     return bpm;
 }
 
+
+/*--------------------------------------------------------------------------*/
+/**
+  @brief  Produce bad pixel map by comparing to coefficients' cube fits to actual intensity values.
+  @param  coeffs    Coeffs' cube; each plane correspond to a coefficient
+  @param  nbpixs    Pointer to output total nb of bad pixels
+  @return Bad pixel map
+ */
+/*--------------------------------------------------------------------------*/
+/* Not used so we temporary comment it out
+static cpl_image       *
+xsh_detmon_bpixs2(cpl_vector* x,const cpl_imagelist* y,
+     const cpl_imagelist * coeffs,cpl_table* gain_table,
+    const int order, const double kappa,cpl_boolean bpmbin,
+    int *nbpixs)
+{
+
+
+  int    size_x=0;
+  int    size_y=0;
+  int    size_c=0;
+
+
+  int    i=0;
+  int    j=0;
+  cpl_size    k=0;
+  int z=0;
+  int pix=0;
+  int sx=0;
+  int sy=0;
+
+  double* px=NULL;
+  const float* pdata=NULL;
+  const float* pcoeffs=NULL;
+  double pfit=0.;
+  double* pgain=NULL;
+  cpl_binary* pmask=NULL;
+  double gain=0;
+  const cpl_image* img_data=NULL;
+
+  const cpl_image* img_coeffs=NULL;
+  cpl_image* bpm=NULL;
+  cpl_mask* mask=NULL;
+
+  cpl_polynomial* pol=NULL;
+
+  size_x = cpl_vector_get_size(x);
+  size_y = cpl_imagelist_get_size(y);
+  size_c = cpl_imagelist_get_size(coeffs);
+  img_data = cpl_imagelist_get_const(coeffs, 0);
+  sx = cpl_image_get_size_x(img_data);
+  sy = cpl_image_get_size_y(img_data);
+  mask = cpl_mask_new(sx,sy);
+
+  cpl_ensure(size_x == size_y, CPL_ERROR_NULL_INPUT, NULL);
+
+  cpl_ensure(size_c == (order+1), CPL_ERROR_NULL_INPUT, NULL);
+
+  px = cpl_vector_get_data(x);
+  pmask=cpl_mask_get_data(mask);
+  pgain=cpl_table_get_data_double(gain_table,"GAIN");
+  pol=cpl_polynomial_new(1);
+  for (z = 0; z < size_x; z++) {
+
+    img_data = cpl_imagelist_get_const(y, z);
+    pdata = cpl_image_get_data_float_const(img_data);
+    gain=pgain[z];
+
+    for (j = 0; j < sy; j++) {
+
+      for (i = 0; i < sx; i++) {
+
+        pix = j * sx + i;
+
+        for (k = size_c-1; k >= 0; k--) {
+
+          img_coeffs = cpl_imagelist_get_const(coeffs, k);
+          pcoeffs = cpl_image_get_data_float_const(img_coeffs);
+          cpl_polynomial_set_coeff(pol, &k, pcoeffs[pix]);
+
+        }
+
+        pfit = cpl_polynomial_eval_1d(pol,px[z],NULL);
+        if (pdata[pix] > 0) {
+          if (fabs(pdata[pix] - pfit) > kappa * sqrt(gain*pdata[pix])) {
+            pmask[pix] = CPL_BINARY_1;
+          } // check if point to be flagged 
+        } // check if pos intensity 
+      } // i loop 
+    } // j loop 
+
+    //cpl_image_delete(img_data);
+
+  } // z loop 
+  cpl_polynomial_delete(pol);
+  if (bpmbin) {
+    bpm = cpl_image_new_from_mask(mask);
+  }
+
+  *nbpixs += cpl_mask_count(mask);
+
+  cpl_mask_delete(mask);
+
+  return bpm;
+}
+
+*/
 /*---------------------------------------------------------------------------*/
 /**
   @brief  Compute autocorr factor
@@ -3394,7 +3920,7 @@ xsh_detmon_bpixs(const cpl_imagelist * coeffs,
 
 static double
 xsh_detmon_autocorr_factor(const cpl_image * image,
-                              cpl_image ** autocorr_image, int m, int n)
+                       cpl_image ** autocorr_image, int m, int n)
 {
     cpl_image * mycorr_image = NULL;
     double      autocorr = 0;
@@ -3404,12 +3930,12 @@ xsh_detmon_autocorr_factor(const cpl_image * image,
     err=cpl_error_get_code();
     if (err == CPL_ERROR_UNSUPPORTED_MODE)
     {
-    	cpl_msg_warning(cpl_func, "FFTW is not supported by CPL, autocorrelation "
-    			"would be computed using internal implementation");
-    	cpl_error_reset();
-    	if (mycorr_image)
-    		cpl_image_delete(mycorr_image);
-    	mycorr_image = xsh_detmon_autocorrelate(image, m, n);
+        cpl_msg_warning(cpl_func, "FFTW is not supported by CPL, autocorrelation "
+                        "would be computed using internal implementation");
+        cpl_error_reset();
+        if (mycorr_image)
+            cpl_image_delete(mycorr_image);
+        mycorr_image = xsh_detmon_autocorrelate(image, m, n);
     }
     if(mycorr_image == NULL) {
         return -1;
@@ -3426,17 +3952,18 @@ xsh_detmon_autocorr_factor(const cpl_image * image,
 }
 
 static cpl_propertylist*
-detmon_lg_extract_qclist_4plane(cpl_propertylist* linc_qclist,const int ip)
+xsh_detmon_lg_extract_qclist_4plane(cpl_propertylist* linc_qclist,const int ip)
 {
 
-   cpl_propertylist* sub_set=NULL;
-   char qc_key[40];
+    cpl_propertylist* sub_set=NULL;
+    char* qc_key=NULL;
 
-   sub_set=cpl_propertylist_new();
-   sprintf(qc_key,"QC LIN COEF%d",ip);
-   cpl_propertylist_copy_property_regexp(sub_set,linc_qclist,qc_key,0);
+    sub_set=cpl_propertylist_new();
+    qc_key=cpl_sprintf("QC LIN COEF%d",ip);
+    cpl_propertylist_copy_property_regexp(sub_set,linc_qclist,qc_key,0);
 
-   return sub_set;
+    cpl_free(qc_key);
+    return sub_set;
 
 }
 
@@ -3452,49 +3979,49 @@ detmon_lg_extract_qclist_4plane(cpl_propertylist* linc_qclist,const int ip)
 */
 static cpl_error_code
 xsh_detmon_lg_extract_extention_header(cpl_frameset* frameset,
-                                          cpl_propertylist* gaint_qclist,
-                                          cpl_propertylist* lint_qclist,
-                                          cpl_propertylist* linc_qclist, 
-                                          cpl_propertylist* bpm_qclist,
-                                          int whichext)
+                                   cpl_propertylist* gaint_qclist,
+                                   cpl_propertylist* lint_qclist,
+                                   cpl_propertylist* linc_qclist, 
+                                   cpl_propertylist* bpm_qclist,
+                                   int whichext)
 {
 
-   cpl_propertylist *      xplist = NULL;
-
-   const char * filename =
-      cpl_frame_get_filename(cpl_frameset_get_first(frameset));
-
-   xplist = cpl_propertylist_load_regexp(filename, whichext,
-                                         "ESO DET|EXTNAME", 0);
-   if (detmon_lg_config.exts >= 0) 
-   {
-      /* for one extension, copy only extname keyword (if any) - DFS09856 */
-      cpl_property* propExtname = NULL;            
-      propExtname = cpl_propertylist_get_property(xplist, "EXTNAME");
-      cpl_error_reset();
-      if (NULL != propExtname)
-      {            
-         propExtname = cpl_property_duplicate(propExtname);
-      }
-      cpl_propertylist_delete(xplist);
-      xplist = NULL;                        
-      if (NULL != propExtname)
-      {
-         xplist = cpl_propertylist_new();
-         cpl_propertylist_append_property(xplist, propExtname);
-         cpl_property_delete(propExtname);
-      }
-   }
-   if (NULL != xplist)
-   {
-      cpl_propertylist_append(gaint_qclist, xplist);
-      cpl_propertylist_append(lint_qclist,  xplist);
-      cpl_propertylist_append(linc_qclist,  xplist);
-      cpl_propertylist_append(bpm_qclist,   xplist);
-      cpl_propertylist_delete(xplist);
-   }
+    cpl_propertylist *      xplist = NULL;
 
-   return cpl_error_get_code();
+    const char * filename =
+        cpl_frame_get_filename(cpl_frameset_get_first(frameset));
+
+    xplist = cpl_propertylist_load_regexp(filename, whichext,
+                                          "ESO DET|EXTNAME", 0);
+    if (xsh_detmon_lg_config.exts >= 0) 
+    {
+        /* for one extension, copy only extname keyword (if any) - DFS09856 */
+        cpl_property* propExtname = NULL;            
+        propExtname = cpl_propertylist_get_property(xplist, "EXTNAME");
+        cpl_error_reset();
+        if (NULL != propExtname)
+        {            
+            propExtname = cpl_property_duplicate(propExtname);
+        }
+        cpl_propertylist_delete(xplist);
+        xplist = NULL;                        
+        if (NULL != propExtname)
+        {
+            xplist = cpl_propertylist_new();
+            cpl_propertylist_append_property(xplist, propExtname);
+            cpl_property_delete(propExtname);
+        }
+    }
+    if (NULL != xplist)
+    {
+        cpl_propertylist_append(gaint_qclist, xplist);
+        cpl_propertylist_append(lint_qclist,  xplist);
+        cpl_propertylist_append(linc_qclist,  xplist);
+        cpl_propertylist_append(bpm_qclist,   xplist);
+        cpl_propertylist_delete(xplist);
+    }
+
+    return cpl_error_get_code();
 }
 
 
@@ -3513,30 +4040,29 @@ xsh_detmon_lg_extract_extention_header(cpl_frameset* frameset,
 /*---------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_lg_save_table_with_pro_keys(cpl_table* table,
-					  const char* name_o,
-					  cpl_propertylist* xheader,
-                                          unsigned CPL_IO_MODE)
+                                   const char* name_o,
+                                   cpl_propertylist* xheader,
+                                   unsigned CPL_IO_MODE)
 {
 
-   cpl_propertylist* pro_keys=NULL;
-   cpl_propertylist* pri_head=NULL;
+    cpl_propertylist* pro_keys=NULL;
 
-   pro_keys=xsh_detmon_load_pro_keys(name_o);
-   cpl_propertylist_append(xheader,pro_keys);
+    pro_keys=xsh_detmon_load_pro_keys(name_o);
+    cpl_propertylist_append(xheader,pro_keys);
 
-   if(CPL_IO_MODE==CPL_IO_DEFAULT) {
-      pri_head=cpl_propertylist_load(name_o,0);
-      cpl_table_save(table, pri_head,xheader,name_o,
-                     CPL_IO_DEFAULT);
-      cpl_propertylist_delete(pri_head);
+    if(CPL_IO_MODE==CPL_IO_DEFAULT) {
+        cpl_propertylist * pri_head=cpl_propertylist_load(name_o,0);
+        cpl_table_save(table, pri_head,xheader,name_o,
+                       CPL_IO_DEFAULT);
+        cpl_propertylist_delete(pri_head);
 
-   } else {
-      cpl_table_save(table,NULL,xheader,name_o,
-                     CPL_IO_EXTEND);
-   }
-   cpl_propertylist_delete(pro_keys);
+    } else {
+        cpl_table_save(table,NULL,xheader,name_o,
+                       CPL_IO_EXTEND);
+    }
+    cpl_propertylist_delete(pro_keys);
 
-   return cpl_error_get_code();
+    return cpl_error_get_code();
 }
 
 /*---------------------------------------------------------------------------*/
@@ -3550,20 +4076,20 @@ xsh_detmon_lg_save_table_with_pro_keys(cpl_table* table,
 /*---------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_lg_save_image_with_pro_keys(cpl_image* image,
-					  const char* name_o,
-					  cpl_propertylist* xheader)
+                                   const char* name_o,
+                                   cpl_propertylist* xheader)
 {
 
-  cpl_propertylist* pro_keys=NULL;
-  pro_keys=xsh_detmon_load_pro_keys(name_o);
-  cpl_propertylist_append(xheader,pro_keys);
+    cpl_propertylist* pro_keys=NULL;
+    pro_keys=xsh_detmon_load_pro_keys(name_o);
+    cpl_propertylist_append(xheader,pro_keys);
 
-  cpl_image_save(image,name_o, CPL_BPP_IEEE_FLOAT, 
-		 xheader,CPL_IO_EXTEND);      
-  cpl_propertylist_delete(pro_keys);
-      
+    cpl_image_save(image,name_o, CPL_BPP_IEEE_FLOAT, 
+                   xheader,CPL_IO_EXTEND);      
+    cpl_propertylist_delete(pro_keys);
 
-  return cpl_error_get_code();
+
+    return cpl_error_get_code();
 }
 
 /*---------------------------------------------------------------------------*/
@@ -3577,21 +4103,21 @@ xsh_detmon_lg_save_image_with_pro_keys(cpl_image* image,
 /*---------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_lg_save_imagelist_with_pro_keys(cpl_imagelist* imagelist,
-					  const char* name_o,
-					  cpl_propertylist* xheader)
+                                       const char* name_o,
+                                       cpl_propertylist* xheader)
 {
 
-  cpl_propertylist* pro_keys=NULL;
-  pro_keys=xsh_detmon_load_pro_keys(name_o);
-  cpl_propertylist_append(xheader,pro_keys);
+    cpl_propertylist* pro_keys=NULL;
+    pro_keys=xsh_detmon_load_pro_keys(name_o);
+    cpl_propertylist_append(xheader,pro_keys);
 
-  cpl_imagelist_save(imagelist,name_o, CPL_BPP_IEEE_FLOAT, 
-                     xheader,CPL_IO_EXTEND);      
+    cpl_imagelist_save(imagelist,name_o, CPL_BPP_IEEE_FLOAT, 
+                       xheader,CPL_IO_EXTEND);      
 
-  cpl_propertylist_delete(pro_keys);
-      
+    cpl_propertylist_delete(pro_keys);
 
-  return cpl_error_get_code();
+
+    return cpl_error_get_code();
 }
 
 /*---------------------------------------------------------------------------*/
@@ -3613,63 +4139,62 @@ xsh_detmon_lg_save_imagelist_with_pro_keys(cpl_imagelist* imagelist,
 
 static cpl_error_code
 xsh_detmon_lg_save_plane(const cpl_parameterlist * parlist,
-                            cpl_frameset* frameset, 
-                            const cpl_frameset * usedframes,      
-                            int whichext,
-                            const char* recipe_name,
-                            cpl_propertylist* mypro_coeffscube,
-                            cpl_propertylist* linc_plane_qclist,
-                            const char* package,
-                            const char* NAME_O,
-                            cpl_image* plane)
+                     cpl_frameset* frameset, 
+                     const cpl_frameset * usedframes,      
+                     int whichext,
+                     const char* recipe_name,
+                     cpl_propertylist* mypro_coeffscube,
+                     cpl_propertylist* linc_plane_qclist,
+                     const char* package,
+                     const char* NAME_O,
+                     cpl_image* plane)
 {
-   cpl_propertylist* plist=NULL;
-
-   if(detmon_lg_config.exts == 0) {
-      cpl_dfs_save_image(frameset, NULL, parlist, usedframes,
-                         NULL, NULL,
-                         CPL_BPP_IEEE_FLOAT, recipe_name,
-                         mypro_coeffscube, NULL,
-                         package, NAME_O);
-      plist=cpl_propertylist_load(NAME_O,0);
-     cpl_image_save(plane,NAME_O, CPL_BPP_IEEE_FLOAT, 
-                    plist,CPL_IO_DEFAULT);      
-     cpl_propertylist_delete(plist);
-
-   } else if(detmon_lg_config.exts > 0) {
-     cpl_dfs_save_image(frameset, NULL, parlist, usedframes,
-                         NULL, NULL,
-                         CPL_BPP_IEEE_FLOAT, recipe_name,
-                         mypro_coeffscube, NULL,
-                         package, NAME_O);
-
-     xsh_detmon_lg_save_image_with_pro_keys(plane,NAME_O,linc_plane_qclist);
-   } else {
-      if(whichext == 1) 
-      {
-         cpl_dfs_save_image(frameset, NULL, parlist, 
-                            usedframes,NULL, NULL,
-                            CPL_BPP_IEEE_FLOAT, recipe_name,
-                            mypro_coeffscube, NULL,
-                            package, NAME_O);
-	xsh_detmon_lg_save_image_with_pro_keys(plane,NAME_O,linc_plane_qclist);
-      } else {
-
-	xsh_detmon_lg_save_image_with_pro_keys(plane,NAME_O,linc_plane_qclist);
-
-      }
+    if(xsh_detmon_lg_config.exts == 0) {
+        cpl_propertylist* plist=NULL;
+        cpl_dfs_save_image(frameset, NULL, parlist, usedframes,
+                           NULL, NULL,
+                           CPL_BPP_IEEE_FLOAT, recipe_name,
+                           mypro_coeffscube, NULL,
+                           package, NAME_O);
+        plist=cpl_propertylist_load(NAME_O,0);
+        cpl_image_save(plane,NAME_O, CPL_BPP_IEEE_FLOAT, 
+                       plist,CPL_IO_DEFAULT);      
+        cpl_propertylist_delete(plist);
 
-   }
-  
-   return cpl_error_get_code();
-}
+    } else if(xsh_detmon_lg_config.exts > 0) {
+        cpl_dfs_save_image(frameset, NULL, parlist, usedframes,
+                           NULL, NULL,
+                           CPL_BPP_IEEE_FLOAT, recipe_name,
+                           mypro_coeffscube, NULL,
+                           package, NAME_O);
 
+        xsh_detmon_lg_save_image_with_pro_keys(plane,NAME_O,linc_plane_qclist);
+    } else {
+        if(whichext == 1) 
+        {
+            cpl_dfs_save_image(frameset, NULL, parlist, 
+                               usedframes,NULL, NULL,
+                               CPL_BPP_IEEE_FLOAT, recipe_name,
+                               mypro_coeffscube, NULL,
+                               package, NAME_O);
+            xsh_detmon_lg_save_image_with_pro_keys(plane,NAME_O,linc_plane_qclist);
+        } else {
 
+            xsh_detmon_lg_save_image_with_pro_keys(plane,NAME_O,linc_plane_qclist);
 
-/*---------------------------------------------------------------------------*/
-/**
-  @brief    Save cube product
-  @param    parlist            Input parlist
+        }
+
+    }
+
+    return cpl_error_get_code();
+}
+
+
+
+/*---------------------------------------------------------------------------*/
+/**
+  @brief    Save cube product
+  @param    parlist            Input parlist
   @param    frameset           Input frameset
   @param    usedframes         usedframes
   @param    whichext           Extension being processed
@@ -3686,186 +4211,190 @@ xsh_detmon_lg_save_plane(const cpl_parameterlist * parlist,
 
 static cpl_error_code
 xsh_detmon_lg_save_cube(const cpl_parameterlist * parlist,
-                           cpl_frameset* frameset, 
-                           const cpl_frameset * usedframes,      
-                           int whichext,
-                           const char* recipe_name,
-                           cpl_propertylist* mypro_coeffscube,
-                           cpl_propertylist* linc_qclist,
-                           const char* package,
-                           const char* NAME_O,
-                           cpl_imagelist* coeffs)
+                    cpl_frameset* frameset, 
+                    const cpl_frameset * usedframes,      
+                    int whichext,
+                    const char* recipe_name,
+                    cpl_propertylist* mypro_coeffscube,
+                    cpl_propertylist* linc_qclist,
+                    const char* package,
+                    const char* NAME_O,
+                    cpl_imagelist* coeffs)
 {
 
-   if(detmon_lg_config.exts == 0) {  
-      cpl_propertylist_append(mypro_coeffscube, linc_qclist);
-      xsh_detmon_lg_dfs_save_imagelist
-         (frameset,  parlist, usedframes, coeffs,
-          recipe_name, mypro_coeffscube, package,
-          NAME_O);   
-   } else if(detmon_lg_config.exts > 0)  {
-      cpl_dfs_save_image(frameset, NULL, parlist, usedframes,
-                         NULL, NULL,
-                         CPL_BPP_IEEE_FLOAT, recipe_name,
-                         mypro_coeffscube, NULL,
-                         package, NAME_O);
-
-      xsh_detmon_lg_save_imagelist_with_pro_keys(coeffs,NAME_O,linc_qclist);
-
-   } else {
-      if(whichext == 1) {
-         cpl_dfs_save_image(frameset, NULL, parlist, usedframes,
-                            NULL, NULL,
-                            CPL_BPP_IEEE_FLOAT, recipe_name,
-                            mypro_coeffscube, NULL,
-                            package, NAME_O);
-	xsh_detmon_lg_save_imagelist_with_pro_keys(coeffs,NAME_O,linc_qclist);
-      } else {
-	xsh_detmon_lg_save_imagelist_with_pro_keys(coeffs,NAME_O,linc_qclist);
-      }
-   }
-   
-   return cpl_error_get_code();
+    if(xsh_detmon_lg_config.exts == 0) {  
+        cpl_propertylist_append(mypro_coeffscube, linc_qclist);
+        xsh_detmon_lg_dfs_save_imagelist
+            (frameset,  parlist, usedframes, coeffs,
+             recipe_name, mypro_coeffscube, package,
+             NAME_O);   
+    } else if(xsh_detmon_lg_config.exts > 0)  {
+        cpl_dfs_save_image(frameset, NULL, parlist, usedframes,
+                           NULL, NULL,
+                           CPL_BPP_IEEE_FLOAT, recipe_name,
+                           mypro_coeffscube, NULL,
+                           package, NAME_O);
+
+        xsh_detmon_lg_save_imagelist_with_pro_keys(coeffs,NAME_O,linc_qclist);
+
+    } else {
+        if(whichext == 1) {
+            cpl_dfs_save_image(frameset, NULL, parlist, usedframes,
+                               NULL, NULL,
+                               CPL_BPP_IEEE_FLOAT, recipe_name,
+                               mypro_coeffscube, NULL,
+                               package, NAME_O);
+            if (coeffs)
+                xsh_detmon_lg_save_imagelist_with_pro_keys(coeffs,NAME_O,linc_qclist);
+            else
+                cpl_propertylist_save(linc_qclist, NAME_O, CPL_IO_EXTEND);
+        } else {
+            if (coeffs)
+                xsh_detmon_lg_save_imagelist_with_pro_keys(coeffs,NAME_O,linc_qclist);
+            else
+                cpl_propertylist_save(linc_qclist, NAME_O, CPL_IO_EXTEND);
+        }
+    }
+
+    return cpl_error_get_code();
 }
 
 static char*
 xsh_detmon_lg_set_paf_name_and_header(cpl_frame* ref_frame,
-                                         int flag_sets,int which_set,
-                                         int whichext,
-                                         const char* paf_suf,
-                                         cpl_propertylist** plist)
+                                  int flag_sets,int which_set,
+                                  int whichext,
+                                  const char* paf_suf,
+                                  cpl_propertylist** plist)
 {
-   char * paf_name=NULL;
-
-   if(detmon_lg_config.exts >= 0) 
-   {
-      *plist =cpl_propertylist_load(cpl_frame_get_filename(ref_frame),
-                                    detmon_lg_config.exts);
-
-      if(!flag_sets) 
-      {
-         paf_name=cpl_sprintf("%s_%s.paf", detmon_lg_config.pafname,paf_suf);
-      } 
-      else 
-      {
-         paf_name=cpl_sprintf("%s_%s_set%02d.paf",
-                              detmon_lg_config.pafname, paf_suf,which_set);
-      }
-   } 
-   else 
-   {
-      *plist = cpl_propertylist_load(cpl_frame_get_filename(ref_frame),
-                                     whichext);
-
-
-      if(!flag_sets) 
-      {
-         paf_name=cpl_sprintf("%s_%s_ext%02d.paf",
-                              detmon_lg_config.pafname, paf_suf,whichext);
-      } 
-      else 
-      {
-         paf_name=cpl_sprintf("%s_%s_set%02d_ext%02d.paf",
-                              detmon_lg_config.pafname,paf_suf,
-                              which_set, whichext);
-      }
-   }
+    char * paf_name=NULL;
+
+    if(xsh_detmon_lg_config.exts >= 0) 
+    {
+        *plist =cpl_propertylist_load(cpl_frame_get_filename(ref_frame),
+                                      xsh_detmon_lg_config.exts);
 
-   return paf_name;
+        if(!flag_sets) 
+        {
+            paf_name=cpl_sprintf("%s_%s.paf", xsh_detmon_lg_config.pafname,paf_suf);
+        } 
+        else 
+        {
+            paf_name=cpl_sprintf("%s_%s_set%02d.paf",
+                                 xsh_detmon_lg_config.pafname, paf_suf,which_set);
+        }
+    } 
+    else 
+    {
+        *plist = cpl_propertylist_load(cpl_frame_get_filename(ref_frame),
+                                       whichext);
+
+
+        if(!flag_sets) 
+        {
+            paf_name=cpl_sprintf("%s_%s_ext%02d.paf",
+                                 xsh_detmon_lg_config.pafname, paf_suf,whichext);
+        } 
+        else 
+        {
+            paf_name=cpl_sprintf("%s_%s_set%02d_ext%02d.paf",
+                                 xsh_detmon_lg_config.pafname,paf_suf,
+                                 which_set, whichext);
+        }
+    }
+
+    return paf_name;
 }
 
 
 static char*
 xsh_detmon_lg_set_paf_name_and_header_ext(cpl_frame* ref_frame,
-                                         int flag_sets,int which_set,
-                                         int whichext,
-                                         const char* paf_suf,
-                                         cpl_propertylist** plist)
+                                      int flag_sets,int which_set,
+                                      int whichext,
+                                      const char* paf_suf,
+                                      cpl_propertylist** plist)
 {
-   char* paf_name=NULL;
-
-   if(detmon_lg_config.exts >= 0) 
-   {
-      *plist = cpl_propertylist_load(cpl_frame_get_filename(ref_frame),
-                                     detmon_lg_config.exts);
-
-      if(!flag_sets) 
-      {
-         paf_name=cpl_sprintf("%s_%s.paf", detmon_lg_config.pafname,paf_suf);
-      } else 
-      {
-         paf_name=cpl_sprintf("%s_%s_set%02d.paf",
-                              detmon_lg_config.pafname, paf_suf,which_set);
-      }
-   } else 
-   {
-      *plist = cpl_propertylist_load(cpl_frame_get_filename(ref_frame),
-                                     whichext);
-      if(!flag_sets) 
-      {
-         paf_name=cpl_sprintf("%s_%s_ext%02d.paf",
-                              detmon_lg_config.pafname, paf_suf,whichext);
-      } else 
-      {
-         paf_name=cpl_sprintf("%s_%s_set%02d_ext%02d.paf",
-                              detmon_lg_config.pafname,paf_suf,
-                              which_set, whichext);
-      }
-   }
-  return paf_name;
+    char* paf_name=NULL;
+
+    if(xsh_detmon_lg_config.exts >= 0) 
+    {
+        *plist = cpl_propertylist_load(cpl_frame_get_filename(ref_frame),
+                                       xsh_detmon_lg_config.exts);
+
+        if(!flag_sets) 
+        {
+            paf_name=cpl_sprintf("%s_%s.paf", xsh_detmon_lg_config.pafname,paf_suf);
+        } else 
+        {
+            paf_name=cpl_sprintf("%s_%s_set%02d.paf",
+                                 xsh_detmon_lg_config.pafname, paf_suf,which_set);
+        }
+    } else 
+    {
+        *plist = cpl_propertylist_load(cpl_frame_get_filename(ref_frame),
+                                       whichext);
+        if(!flag_sets) 
+        {
+            paf_name=cpl_sprintf("%s_%s_ext%02d.paf",
+                                 xsh_detmon_lg_config.pafname, paf_suf,whichext);
+        } else 
+        {
+            paf_name=cpl_sprintf("%s_%s_set%02d_ext%02d.paf",
+                                 xsh_detmon_lg_config.pafname,paf_suf,
+                                 which_set, whichext);
+        }
+    }
+    return paf_name;
 
 }
 
 static cpl_error_code    
 xsh_detmon_lg_save_paf_product(cpl_frame* ref_frame,int flag_sets,
-                                 int which_set,int whichext,
-                                 const char* pafregexp,
-                                 const char* procatg,
-                                 const char* pipeline_name,
-                                 const char* recipe_name,
-                                  const char* paf_suf,
-                                  cpl_propertylist* qclist,
-                                  const int ext)
+                           int which_set,int whichext,
+                           const char* pafregexp,
+                           const char* procatg,
+                           const char* pipeline_name,
+                           const char* recipe_name,
+                           const char* paf_suf,
+                           cpl_propertylist* qclist,
+                           const int ext)
 
 {
+    /* Set the file name for the linearity table PAF */
+    char* paf_name=NULL;
+    cpl_propertylist* plist=NULL;
+    cpl_propertylist* paflist = NULL;
+    cpl_propertylist* mainplist=NULL;
+
+    mainplist =cpl_propertylist_load(cpl_frame_get_filename(ref_frame),0);
+    if(ext==0) {
+        paf_name=xsh_detmon_lg_set_paf_name_and_header(ref_frame,flag_sets,
+                                                   which_set,whichext,
+                                                   paf_suf,&plist);
+    } else {
+        paf_name=xsh_detmon_lg_set_paf_name_and_header_ext(ref_frame,flag_sets,
+                                                       which_set,whichext,
+                                                       paf_suf,&plist);
+    }
 
-   /* Set the file name for the linearity table PAF */
-   char* paf_name=NULL;
-   char NAME_O[128];
-   cpl_propertylist* plist=NULL;
-   cpl_propertylist* paflist = NULL;
-   cpl_propertylist* mainplist=NULL;
-
-   mainplist =cpl_propertylist_load(cpl_frame_get_filename(ref_frame),0);
-   if(ext==0) {
-      paf_name=xsh_detmon_lg_set_paf_name_and_header(ref_frame,flag_sets,
-                                                        which_set,whichext,
-                                                        paf_suf,&plist);
-   } else {
-      paf_name=xsh_detmon_lg_set_paf_name_and_header_ext(ref_frame,flag_sets,
-                                                            which_set,whichext,
-                                                            paf_suf,&plist);
-   }
-   sprintf(NAME_O,paf_name);
 
-   paflist = cpl_propertylist_new();
-   cpl_propertylist_append_string(paflist, CPL_DFS_PRO_CATG,procatg);
+    paflist = cpl_propertylist_new();
+    cpl_propertylist_append_string(paflist, CPL_DFS_PRO_CATG,procatg);
 
-   /* Get the keywords for the paf file */
-   cpl_propertylist_copy_property_regexp(paflist, plist,pafregexp, 0);
-   cpl_propertylist_copy_property_regexp(paflist, mainplist,pafregexp, 0);
-   cpl_propertylist_append(paflist,qclist);
+    /* Get the keywords for the paf file */
+    cpl_propertylist_copy_property_regexp(paflist, plist,pafregexp, 0);
+    cpl_propertylist_copy_property_regexp(paflist, mainplist,pafregexp, 0);
+    cpl_propertylist_append(paflist,qclist);
 
-   /* Save the PAF */
-   cpl_dfs_save_paf(pipeline_name, recipe_name,paflist, NAME_O);
+    /* Save the PAF */
+    cpl_dfs_save_paf(pipeline_name, recipe_name,paflist,paf_name);
 
-   /* free memory */
-   cpl_propertylist_delete(mainplist);
-   cpl_propertylist_delete(paflist);
-   cpl_propertylist_delete(plist);
-   cpl_free(paf_name);
+    /* free memory */
+    cpl_propertylist_delete(mainplist);
+    cpl_propertylist_delete(paflist);
+    cpl_propertylist_delete(plist);
+    cpl_free(paf_name);
 
-   return cpl_error_get_code();
+    return cpl_error_get_code();
 
 }
 
@@ -3904,39 +4433,38 @@ xsh_detmon_lg_save_paf_product(cpl_frame* ref_frame,int flag_sets,
   ---------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_lg_save(const cpl_parameterlist * parlist,
-                      cpl_frameset * frameset,
-                      const char *recipe_name,
-                      const char *pipeline_name,
-                      const char *pafregexp,
-		      const cpl_propertylist  * pro_lintbl,
-		      const cpl_propertylist  * pro_gaintbl,
-		      const cpl_propertylist  * pro_coeffscube,
-		      const cpl_propertylist  * pro_bpm,
-		      const cpl_propertylist  * pro_corr,
-		      const cpl_propertylist  * pro_diff,
-                      const char *package,
-                      cpl_imagelist * coeffs,
-                      cpl_table * gain_table,
-                      cpl_table * linear_table,
-                      cpl_image * bpms,
-                      cpl_imagelist * autocorr_images,
-                      cpl_imagelist * diff_flats,
-                      cpl_propertylist * gaint_qclist,
-                      cpl_propertylist * lint_qclist,
-                      cpl_propertylist * linc_qclist,
-                      cpl_propertylist * bpm_qclist,
-                      const int flag_sets,
-                      const int which_set,
-                      const cpl_frameset * usedframes,
-                      int whichext)
+               cpl_frameset * frameset,
+               const char *recipe_name,
+               const char *pipeline_name,
+               const char *pafregexp,
+               const cpl_propertylist  * pro_lintbl,
+               const cpl_propertylist  * pro_gaintbl,
+               const cpl_propertylist  * pro_coeffscube,
+               const cpl_propertylist  * pro_bpm,
+               const cpl_propertylist  * pro_corr,
+               const cpl_propertylist  * pro_diff,
+               const char *package,
+               cpl_imagelist * coeffs,
+               cpl_table * gain_table,
+               cpl_table * linear_table,
+               cpl_image * bpms,
+               cpl_imagelist * autocorr_images,
+               cpl_imagelist * diff_flats,
+               cpl_propertylist * gaint_qclist,
+               cpl_propertylist * lint_qclist,
+               cpl_propertylist * linc_qclist,
+               cpl_propertylist * bpm_qclist,
+               const int flag_sets,
+               const int which_set,
+               const cpl_frameset * usedframes,
+               int whichext)
 {
 
     cpl_frame              *ref_frame;
     cpl_propertylist       *plist = NULL;
     cpl_propertylist       *mainplist = NULL;
-    const int NAME_O_BUF_SIZE = 4096;
-    char                   NAME_O[NAME_O_BUF_SIZE];
-    char                   PREF_O[NAME_O_BUF_SIZE];
+    char*                   NAME_O=NULL;
+    char*                   PREF_O=NULL;
     int                     nb_images;
     int                     i;
 
@@ -3945,36 +4473,36 @@ xsh_detmon_lg_save(const cpl_parameterlist * parlist,
     cpl_propertylist* linc_plane_qclist=NULL;
     cpl_image* plane=NULL;
     int ip=0;
-    char pcatg_plane[40];
+    char* pcatg_plane=NULL;
 
     cpl_propertylist  * mypro_lintbl     =
-	cpl_propertylist_duplicate(pro_lintbl);
+        cpl_propertylist_duplicate(pro_lintbl);
     cpl_propertylist  * mypro_gaintbl    =
-	cpl_propertylist_duplicate(pro_gaintbl);
+        cpl_propertylist_duplicate(pro_gaintbl);
     cpl_propertylist  * mypro_coeffscube =
-	cpl_propertylist_duplicate(pro_coeffscube);
+        cpl_propertylist_duplicate(pro_coeffscube);
     cpl_propertylist  * mypro_bpm        =
-	cpl_propertylist_duplicate(pro_bpm);
+        cpl_propertylist_duplicate(pro_bpm);
     cpl_propertylist  * mypro_corr       =
-	cpl_propertylist_duplicate(pro_corr);
+        cpl_propertylist_duplicate(pro_corr);
     cpl_propertylist  * mypro_diff       =
-	cpl_propertylist_duplicate(pro_diff);
+        cpl_propertylist_duplicate(pro_diff);
 
     const char * procatg_lintbl =
-	cpl_propertylist_get_string(mypro_lintbl, CPL_DFS_PRO_CATG);
+        cpl_propertylist_get_string(mypro_lintbl, CPL_DFS_PRO_CATG);
 
     const char * procatg_gaintbl =
-	cpl_propertylist_get_string(mypro_gaintbl, CPL_DFS_PRO_CATG);
+        cpl_propertylist_get_string(mypro_gaintbl, CPL_DFS_PRO_CATG);
 
     const char * procatg_coeffscube =
-	cpl_propertylist_get_string(mypro_coeffscube, CPL_DFS_PRO_CATG);
+        cpl_propertylist_get_string(mypro_coeffscube, CPL_DFS_PRO_CATG);
     const char * procatg_bpm =
-	cpl_propertylist_get_string(mypro_bpm, CPL_DFS_PRO_CATG);
+        cpl_propertylist_get_string(mypro_bpm, CPL_DFS_PRO_CATG);
 
 
     /* Extract extension headers if multi-extension */
     xsh_detmon_lg_extract_extention_header(frameset,gaint_qclist,lint_qclist,
-                                              linc_qclist,bpm_qclist,whichext);
+                                       linc_qclist,bpm_qclist,whichext);
 
     /* This is only used later for PAF and temporarily for COEFFS_CUBE
        (see if defined)*/
@@ -3982,392 +4510,411 @@ xsh_detmon_lg_save(const cpl_parameterlist * parlist,
     ref_frame = cpl_frameset_get_first(frameset);
 
     skip_if((mainplist =
-	cpl_propertylist_load(cpl_frame_get_filename(ref_frame),
-			      0)) == NULL);
+             cpl_propertylist_load(cpl_frame_get_filename(ref_frame),
+                                   0)) == NULL);
 
     /*******************************/
     /*  Write the LINEARITY TABLE  */
     /*******************************/
-   
+    cpl_msg_info(cpl_func,"Write the LINEARITY TABLE");
     /* Set the file name for the table */
     if(!flag_sets) {
-        sprintf(NAME_O,"%s_linearity_table.fits", recipe_name);
+        NAME_O=cpl_sprintf("%s_linearity_table.fits", recipe_name);
     } else {
-       sprintf(NAME_O,"%s_linearity_table_set%02d.fits", recipe_name,
+        NAME_O=cpl_sprintf("%s_linearity_table_set%02d.fits", recipe_name,
                            which_set);
     }
 
-    if (detmon_lg_config.exts >= 0) {
-       /* Save the table */
-       cpl_propertylist_append(mypro_lintbl, lint_qclist);
-       skip_if(cpl_dfs_save_table(frameset, NULL,parlist, usedframes, NULL,
-                                  linear_table,NULL, recipe_name,
-                                  mypro_lintbl, NULL, package, NAME_O));
-    
-       xsh_detmon_lg_save_table_with_pro_keys(linear_table,NAME_O,
-                                                 lint_qclist,CPL_IO_DEFAULT);
+    if (xsh_detmon_lg_config.exts >= 0) {
+        /* Save the table */
+        cpl_propertylist_append(mypro_lintbl, lint_qclist);
+        skip_if(cpl_dfs_save_table(frameset, NULL,parlist, usedframes, NULL,
+                                   linear_table,NULL, recipe_name,
+                                   mypro_lintbl, NULL, package, NAME_O));
+
+        xsh_detmon_lg_save_table_with_pro_keys(linear_table,NAME_O,
+                                           lint_qclist,CPL_IO_DEFAULT);
 
     } else {
-       if(whichext == 1) {
-          /* Save the 1. extension table */
-          skip_if(cpl_dfs_save_table(frameset,NULL, parlist, usedframes, NULL, 
-                                     linear_table,lint_qclist, recipe_name, 
-                                     mypro_lintbl,NULL, package, NAME_O));
-          xsh_detmon_lg_save_table_with_pro_keys(linear_table,NAME_O,
-                                                    lint_qclist,CPL_IO_DEFAULT);
+        if(whichext == 1) {
+            /* Save the 1. extension table */
+            skip_if(cpl_dfs_save_table(frameset,NULL, parlist, usedframes, NULL, 
+                                       linear_table,lint_qclist, recipe_name, 
+                                       mypro_lintbl,NULL, package, NAME_O));
+            xsh_detmon_lg_save_table_with_pro_keys(linear_table,NAME_O,
+                                               lint_qclist,CPL_IO_DEFAULT);
 
 
 
 
-       } else {
+        } else {
 
-          xsh_detmon_lg_save_table_with_pro_keys(linear_table,NAME_O,
-                                                    lint_qclist,CPL_IO_EXTEND);
-       }
+            xsh_detmon_lg_save_table_with_pro_keys(linear_table,NAME_O,
+                                               lint_qclist,CPL_IO_EXTEND);
+        }
     }
+    irplib_free(&NAME_O);
     /**************************/
     /*  Write the GAIN TABLE  */
     /**************************/
-
+    cpl_msg_info(cpl_func,"Write the GAIN TABLE");
     /* Set the file name for the table */
     if(!flag_sets) {
-        sprintf(NAME_O,"%s_gain_table.fits", recipe_name);
+        NAME_O=cpl_sprintf("%s_gain_table.fits", recipe_name);
     } else {
-        sprintf(NAME_O,"%s_gain_table_set%02d.fits", recipe_name,
+        NAME_O=cpl_sprintf("%s_gain_table_set%02d.fits", recipe_name,
                            which_set);
     }
 
-    if (detmon_lg_config.exts >= 0) 
+    if (xsh_detmon_lg_config.exts >= 0) 
     {
-       /* Save the table */
+        /* Save the table */
 
-       cpl_propertylist_append(mypro_gaintbl, gaint_qclist);
-       skip_if(cpl_dfs_save_table(frameset, NULL, parlist, usedframes, NULL,
-                                  gain_table,NULL, recipe_name, mypro_gaintbl,
-                                  NULL, package, NAME_O));
-       xsh_detmon_lg_save_table_with_pro_keys(gain_table,NAME_O,
-                                                 gaint_qclist,CPL_IO_DEFAULT);
+        cpl_propertylist_append(mypro_gaintbl, gaint_qclist);
+        skip_if(cpl_dfs_save_table(frameset, NULL, parlist, usedframes, NULL,
+                                   gain_table,NULL, recipe_name, mypro_gaintbl,
+                                   NULL, package, NAME_O));
+        xsh_detmon_lg_save_table_with_pro_keys(gain_table,NAME_O,
+                                           gaint_qclist,CPL_IO_DEFAULT);
 
     } 
     else 
     {
-       if(whichext == 1) 
-       {
-          /* Save the 1. extension table */
-          skip_if(cpl_dfs_save_table(frameset, NULL, parlist, usedframes, NULL, gain_table,
-                                     gaint_qclist, recipe_name, mypro_gaintbl,
-                                     NULL, package, NAME_O));
-          xsh_detmon_lg_save_table_with_pro_keys(gain_table,NAME_O,
-                                                    gaint_qclist,CPL_IO_DEFAULT);
-
-       } 
-       else 
-       {
-
-          xsh_detmon_lg_save_table_with_pro_keys(gain_table,NAME_O,
-                                                    gaint_qclist,CPL_IO_EXTEND);
-       }
+        if(whichext == 1) 
+        {
+            /* Save the 1. extension table */
+            skip_if(cpl_dfs_save_table(frameset, NULL, parlist, usedframes, NULL, gain_table,
+                                       gaint_qclist, recipe_name, mypro_gaintbl,
+                                       NULL, package, NAME_O));
+            xsh_detmon_lg_save_table_with_pro_keys(gain_table,NAME_O,
+                                               gaint_qclist,CPL_IO_DEFAULT);
+
+        } 
+        else 
+        {
+
+            xsh_detmon_lg_save_table_with_pro_keys(gain_table,NAME_O,
+                                               gaint_qclist,CPL_IO_EXTEND);
+        }
     }
 
-    if(detmon_lg_config.pix2pix) 
+    if(xsh_detmon_lg_config.pix2pix) 
     {
 
-      /***************************/
-      /*  Write the COEFFS FITS  */
-      /***************************/
-   
-      if(!flag_sets) 
-      {
-        sprintf(PREF_O,"%s_coeffs_cube", recipe_name);
-      } else 
-      {
-         sprintf(PREF_O,"%s_coeffs_cube_set%02d",
-               recipe_name, which_set);
-      }
-      if (detmon_lg_config.split_coeffs == 0) {
-         sprintf(NAME_O,"%s.fits", PREF_O);
-      }
-
-
-      /* Save the imagelist */
-      if(detmon_lg_config.split_coeffs != 0){ 
-
-
-         nb_images = cpl_imagelist_get_size(coeffs);
-         for(ip=0;ip<nb_images;ip++) {
-
-            sprintf(NAME_O,"%s_P%d.fits", PREF_O,ip);
-            sprintf(pcatg_plane,"COEFFS_CUBE_P%d",ip);
-            cpl_propertylist_delete(mypro_coeffscube);
-            mypro_coeffscube=cpl_propertylist_duplicate(pro_coeffscube);
-            cpl_propertylist_set_string(mypro_coeffscube,CPL_DFS_PRO_CATG,
-                                        pcatg_plane);
-            linc_plane_qclist=detmon_lg_extract_qclist_4plane(linc_qclist,ip);
-            cpl_propertylist_append(mypro_coeffscube, linc_plane_qclist);
-            plane=cpl_imagelist_get(coeffs,ip);
-            xsh_detmon_lg_save_plane(parlist,frameset,usedframes,whichext,
-                                        recipe_name,mypro_coeffscube,
-                                        linc_plane_qclist,package,NAME_O,plane);
-          
-            if(NULL!=linc_plane_qclist) {
-               cpl_propertylist_delete(linc_plane_qclist);
-            }
+        /***************************/
+        /*  Write the COEFFS FITS  */
+        /***************************/
+        cpl_msg_info(cpl_func,"Write the COEFFS FITS");
+        irplib_free(&NAME_O);
+        if(!flag_sets) 
+        {
+            PREF_O=cpl_sprintf("%s_coeffs_cube", recipe_name);
+        } else 
+        {
+            PREF_O=cpl_sprintf("%s_coeffs_cube_set%02d",
+                               recipe_name, which_set);
+        }
+        if (xsh_detmon_lg_config.split_coeffs == 0) {
+            NAME_O=cpl_sprintf("%s.fits", PREF_O);
+        }
 
-         } /* end for loop over cube planes */
-      } else {
 
-         xsh_detmon_lg_save_cube(parlist,frameset,usedframes,whichext,
-                                    recipe_name,mypro_coeffscube,
-                                    linc_qclist,package,NAME_O,coeffs);
-      }
+        /* Save the imagelist */
+        if(xsh_detmon_lg_config.split_coeffs != 0){ 
 
-      /*******************************/
-      /*  Write the BAD PIXEL MAP    */
-      /*******************************/
-   
-      /* Set the file name for the bpm */
-      if(!flag_sets) 
-      {
-         sprintf(NAME_O,"%s_bpm.fits", recipe_name);
-      } else 
-      {
-         sprintf(NAME_O,"%s_bpm_set%02d.fits", recipe_name, which_set);
-      }
-   
 
-      /* Save the image */
-      if(detmon_lg_config.exts == 0)       {
-         cpl_propertylist_append(mypro_bpm, bpm_qclist);
-         cpl_dfs_save_image(frameset, NULL, parlist, usedframes, NULL, bpms,
-                                 CPL_BPP_IEEE_FLOAT, recipe_name,
-                                 mypro_bpm, NULL, package,
-                                 NAME_O);
-      }
-      else if(detmon_lg_config.exts > 0) 
-      { 
-         skip_if(cpl_dfs_save_image(frameset, NULL, parlist, usedframes,NULL,  NULL,
-                                    CPL_BPP_IEEE_FLOAT, recipe_name,
-                                    mypro_bpm, NULL, package,
-                                    NAME_O));
-         xsh_detmon_lg_save_image_with_pro_keys(bpms,NAME_O,bpm_qclist);
-
-      } else 
-      {
-         if (whichext == 1) 
-         {
+            nb_images = cpl_imagelist_get_size(coeffs);
+            for(ip=0;ip<nb_images;ip++) {
+                NAME_O=cpl_sprintf("%s_P%d.fits", PREF_O,ip);
+                pcatg_plane=cpl_sprintf("COEFFS_CUBE_P%d",ip);
+                cpl_propertylist_delete(mypro_coeffscube);
+                mypro_coeffscube=cpl_propertylist_duplicate(pro_coeffscube);
+                cpl_propertylist_set_string(mypro_coeffscube,CPL_DFS_PRO_CATG,
+                                            pcatg_plane);
+                linc_plane_qclist=xsh_detmon_lg_extract_qclist_4plane(linc_qclist,ip);
+                cpl_propertylist_append(mypro_coeffscube, linc_plane_qclist);
+                plane=cpl_imagelist_get(coeffs,ip);
+                xsh_detmon_lg_save_plane(parlist,frameset,usedframes,whichext,
+                                     recipe_name,mypro_coeffscube,
+                                     linc_plane_qclist,package,NAME_O,plane);
+
+                if(NULL!=linc_plane_qclist) {
+                    cpl_propertylist_delete(linc_plane_qclist);
+                }
+                irplib_free(&NAME_O);
+
+            } /* end for loop over cube planes */
+        } else {
+
+            xsh_detmon_lg_save_cube(parlist,frameset,usedframes,whichext,
+                                recipe_name,mypro_coeffscube,
+                                linc_qclist,package,NAME_O,coeffs);
+        }
+
+        /*******************************/
+        /*  Write the BAD PIXEL MAP    */
+        /*******************************/
+        cpl_msg_info(cpl_func,"Write the BAD PIXEL MAP");
+        irplib_free(&NAME_O);
+        /* Set the file name for the bpm */
+        if(!flag_sets) 
+        {
+            NAME_O=cpl_sprintf("%s_bpm.fits", recipe_name);
+        } else 
+        {
+            NAME_O=cpl_sprintf("%s_bpm_set%02d.fits", recipe_name, which_set);
+        }
+
+
+        /* Save the image */
+        if(xsh_detmon_lg_config.exts == 0)       {
+            cpl_propertylist_append(mypro_bpm, bpm_qclist);
+            cpl_dfs_save_image(frameset, NULL, parlist, usedframes, NULL, bpms,
+                               CPL_BPP_IEEE_FLOAT, recipe_name,
+                               mypro_bpm, NULL, package,
+                               NAME_O);
+        }
+        else if(xsh_detmon_lg_config.exts > 0) 
+        { 
             skip_if(cpl_dfs_save_image(frameset, NULL, parlist, usedframes,NULL,  NULL,
-                     CPL_BPP_IEEE_FLOAT, recipe_name,
-                     mypro_bpm, NULL, package,
-                     NAME_O));
-            xsh_detmon_lg_save_image_with_pro_keys(bpms,NAME_O,bpm_qclist);
-         } else 
-         {
+                                       CPL_BPP_IEEE_FLOAT, recipe_name,
+                                       mypro_bpm, NULL, package,
+                                       NAME_O));
             xsh_detmon_lg_save_image_with_pro_keys(bpms,NAME_O,bpm_qclist);
-         }
-      }
+
+        } else 
+        {
+            if (whichext == 1) 
+            {
+                skip_if(cpl_dfs_save_image(frameset, NULL, parlist, usedframes,NULL,  NULL,
+                                           CPL_BPP_IEEE_FLOAT, recipe_name,
+                                           mypro_bpm, NULL, package,
+                                           NAME_O));
+                xsh_detmon_lg_save_image_with_pro_keys(bpms,NAME_O,bpm_qclist);
+            } else 
+            {
+                xsh_detmon_lg_save_image_with_pro_keys(bpms,NAME_O,bpm_qclist);
+            }
+        }
     } /* End of if(pix2pix) */
 
-    if(detmon_lg_config.intermediate) 
+    if(xsh_detmon_lg_config.intermediate) 
     {
         /******************************/
         /*  Write the AUTOCORRS FITS  */
         /******************************/
-      nb_images = cpl_imagelist_get_size(autocorr_images);
-      cpl_ensure_code(nb_images > 0, CPL_ERROR_DATA_NOT_FOUND);
-      for(i = 0; i < nb_images; i++)
-      {
-         cpl_propertylist* pplist = cpl_propertylist_duplicate(mypro_corr);
-         int inull = 0;
-         cpl_array* pnames = cpl_table_get_column_names(linear_table);
-         double ddit = 0;
-         if(i < cpl_table_get_nrow(linear_table))
-         {
-            ddit = cpl_table_get_double(linear_table,
-            cpl_array_get_data_string_const(pnames)[0], i, &inull);
-         }
-         cpl_array_delete(pnames);
-         /*cpl_propertylist_append_double(pplist, "ESO DET DIT", ddit);*/
+        cpl_msg_info(cpl_func,"Write the AUTOCORRS FITS");
+        nb_images = cpl_imagelist_get_size(autocorr_images);
+        cpl_ensure_code(nb_images > 0, CPL_ERROR_DATA_NOT_FOUND);
+        for(i = 0; i < nb_images; i++)
+        {
+            cpl_propertylist* pplist = cpl_propertylist_duplicate(mypro_corr);
+            int inull = 0;
+            cpl_array* pnames = cpl_table_get_column_names(linear_table);
+            double ddit = 0;
+            if(i < cpl_table_get_nrow(linear_table))
+            {
+                ddit = cpl_table_get_double(linear_table,
+                                            cpl_array_get_data_string_const(pnames)[0], i, &inull);
+            }
+            cpl_array_delete(pnames);
+            /*cpl_propertylist_append_double(pplist, "ESO DET DIT", ddit);*/
             /* Set the file name for each image */
+            irplib_free(&NAME_O);
             if(!flag_sets)
             {
-                sprintf(NAME_O,"%s_autocorr_%d.fits", recipe_name, i);
+                NAME_O=cpl_sprintf("%s_autocorr_%d.fits", recipe_name, i);
                 assert(NAME_O != NULL);
             } else
             {
-                sprintf(NAME_O,"%s_autocorr_%02d_set%02d.fits",
+                NAME_O=cpl_sprintf("%s_autocorr_%02d_set%02d.fits",
                                    recipe_name, i, which_set);
                 assert(NAME_O != NULL);
             }
             /* Save the image */
-            if(detmon_lg_config.exts > 0)
+            if(xsh_detmon_lg_config.exts > 0)
             {
-               cpl_propertylist* pextlist = cpl_propertylist_new();
-               cpl_propertylist_append_double(pextlist, "ESO DET DIT", ddit);
-               skip_if(cpl_dfs_save_image(frameset, NULL, parlist, usedframes, 
-                                          NULL,NULL,CPL_BPP_IEEE_FLOAT, 
-                                          recipe_name, pplist, NULL,
-                                          package, NAME_O));
+                cpl_propertylist* pextlist = cpl_propertylist_new();
+                cpl_propertylist_append_double(pextlist, "ESO DET DIT", ddit);
+                skip_if(cpl_dfs_save_image(frameset, NULL, parlist, usedframes, 
+                                           NULL,NULL,CPL_BPP_IEEE_FLOAT, 
+                                           recipe_name, pplist, NULL,
+                                           package, NAME_O));
 
                 xsh_detmon_lg_save_image_with_pro_keys(
-                   cpl_imagelist_get(autocorr_images, i),NAME_O,pextlist);
+                                                   cpl_imagelist_get(autocorr_images, i),NAME_O,pextlist);
 
                 cpl_propertylist_delete(pextlist);
             } else
-            if(detmon_lg_config.exts == 0)
-            {
-                cpl_propertylist_append_double(pplist, "ESO DET DIT", ddit);            
-                cpl_dfs_save_image(frameset, NULL, parlist, usedframes, NULL,
-                    cpl_imagelist_get(autocorr_images, i), CPL_BPP_IEEE_FLOAT,
-                    recipe_name, pplist, NULL, package,
-                    NAME_O);
+                if(xsh_detmon_lg_config.exts == 0)
+                {
+                    cpl_propertylist_append_double(pplist, "ESO DET DIT", ddit);            
+                    cpl_dfs_save_image(frameset, NULL, parlist, usedframes, NULL,
+                                       cpl_imagelist_get(autocorr_images, i),
+                                       CPL_BPP_IEEE_FLOAT,
+                                       recipe_name, pplist, NULL, package,
+                                       NAME_O);
 
-            }
-            else
-            {
-               cpl_propertylist* pextlist = cpl_propertylist_new();
-               cpl_propertylist_append_double(pextlist, "ESO DET DIT", ddit);
-               if(whichext == 1)
-               {
-                  skip_if(cpl_dfs_save_image(frameset, NULL, parlist, usedframes, NULL,NULL,
-                        CPL_BPP_IEEE_FLOAT, recipe_name,
-                        pplist, NULL,
-                        package, NAME_O));
-
-                  xsh_detmon_lg_save_image_with_pro_keys(
-                     cpl_imagelist_get(autocorr_images, i),NAME_O,pextlist);
-
-               } else
-               {
-
-                  xsh_detmon_lg_save_image_with_pro_keys(
-                     cpl_imagelist_get(autocorr_images, i),NAME_O,pextlist);
-               }
-               cpl_propertylist_delete(pextlist);
-            }
+                }
+                else
+                {
+                    cpl_propertylist* pextlist = cpl_propertylist_new();
+                    cpl_propertylist_append_double(pextlist, "ESO DET DIT", ddit);
+                    if(whichext == 1)
+                    {
+                        skip_if(cpl_dfs_save_image(frameset, NULL, parlist,
+                                                   usedframes, NULL,NULL,
+                                                   CPL_BPP_IEEE_FLOAT, recipe_name,
+                                                   pplist, NULL,
+                                                   package, NAME_O));
+
+                        xsh_detmon_lg_save_image_with_pro_keys(
+                                                           cpl_imagelist_get(autocorr_images, i),NAME_O,pextlist);
+
+                    } else
+                    {
+
+                        xsh_detmon_lg_save_image_with_pro_keys(
+                                                           cpl_imagelist_get(autocorr_images, i),NAME_O,pextlist);
+                    }
+                    cpl_propertylist_delete(pextlist);
+                }
             cpl_propertylist_delete (pplist);
         }
-    
+        irplib_free(&NAME_O);
+
 
         /*
-        cpl_msg_info(cpl_func, "-----before Write the DIFFS FITS %d", __LINE__);
-        */
+           cpl_msg_info(cpl_func, "-----before Write the DIFFS FITS %d", __LINE__);
+           */
         /***************************/
         /*   Write the DIFFS FITS  */
         /***************************/
-      for(i = 0; i < nb_images; i++)
-      {
-         cpl_propertylist* pplist = cpl_propertylist_duplicate(mypro_diff);
-         int inull = 0;
-         cpl_array* pnames = cpl_table_get_column_names(linear_table);
-         double ddit = 0;
-         if(i < cpl_table_get_nrow(linear_table))
-         {
-            ddit = cpl_table_get_double(linear_table,
-                                        cpl_array_get_data_string_const(pnames)[0], i, &inull);
-         }
-         cpl_array_delete(pnames);
-         /*cpl_propertylist_append_double(pplist, "ESO DET DIT", ddit);*/
-         /* Set the file name for each image */
-         if(!flag_sets)
-         {
-            sprintf(NAME_O,"%s_diff_flat_%d.fits", recipe_name, i);
-         } else
-         {
-            sprintf(NAME_O,"%s_diff_flat_%d_set%02d.fits",
-                    recipe_name, i, which_set);
-         }
-         /* Save the image */
-         if(detmon_lg_config.exts > 0)
-         {
-            cpl_propertylist* pextlist = cpl_propertylist_new();
-            cpl_propertylist_append_double(pextlist, "ESO DET DIT", ddit);     
-            cpl_propertylist_append_double(mypro_diff, "ESO DET DIT", ddit);   
-            skip_if(cpl_dfs_save_image(frameset, NULL, parlist, usedframes, 
-                                       NULL,NULL,CPL_BPP_IEEE_FLOAT,recipe_name,
-                                       mypro_diff, NULL,package, NAME_O));
-
-            xsh_detmon_lg_save_image_with_pro_keys(
-               cpl_imagelist_get(diff_flats, i),NAME_O,pextlist);
+        cpl_msg_info(cpl_func,"Write the DIFFS FITS");
 
-            cpl_propertylist_delete(pextlist);
-         }
-         else if(detmon_lg_config.exts == 0)
-         {
-            cpl_propertylist_append_double(pplist, "ESO DET DIT", ddit);       
-            cpl_dfs_save_image
-               (frameset, NULL, parlist, usedframes, NULL,
-                cpl_imagelist_get(diff_flats, i), CPL_BPP_IEEE_FLOAT,
-                recipe_name, pplist, NULL, package,
-                NAME_O);
-
-         } else
-         {
-            cpl_propertylist* pextlist = cpl_propertylist_new();
-            cpl_propertylist_append_double(pextlist, "ESO DET DIT", ddit);   
-            if(whichext == 1)
+        for(i = 0; i < nb_images; i++)
+        {
+            cpl_propertylist* pplist = cpl_propertylist_duplicate(mypro_diff);
+            int inull = 0;
+            cpl_array* pnames = cpl_table_get_column_names(linear_table);
+            double ddit = 0;
+            if(i < cpl_table_get_nrow(linear_table))
+            {
+                ddit = cpl_table_get_double(linear_table,
+                                            cpl_array_get_data_string_const(pnames)[0], i, &inull);
+            }
+            cpl_array_delete(pnames);
+            /*cpl_propertylist_append_double(pplist, "ESO DET DIT", ddit);*/
+            /* Set the file name for each image */
+            if(!flag_sets)
+            {
+                NAME_O=cpl_sprintf("%s_diff_flat_%d.fits", recipe_name, i);
+            } else
             {
-               cpl_propertylist_append_double(mypro_diff,"ESO DET DIT",ddit);   
-//                  cpl_propertylist_erase(mypro_diff, "ESO DET DIT");
-               skip_if(cpl_dfs_save_image(frameset, NULL, parlist, 
-                                          usedframes, NULL,NULL,
-                                          CPL_BPP_IEEE_FLOAT, recipe_name,
-                                          mypro_diff, NULL,package, NAME_O));
+                NAME_O=cpl_sprintf("%s_diff_flat_%d_set%02d.fits",
+                                   recipe_name, i, which_set);
+            }
+            /* Save the image */
+            if(xsh_detmon_lg_config.exts > 0)
+            {
+                cpl_propertylist* pextlist = cpl_propertylist_new();
+                cpl_propertylist_append_double(pextlist, "ESO DET DIT", ddit);     
+                cpl_propertylist_append_double(mypro_diff, "ESO DET DIT", ddit);   
+                skip_if(cpl_dfs_save_image(frameset, NULL, parlist, usedframes, 
+                                           NULL,NULL,CPL_BPP_IEEE_FLOAT,
+                                           recipe_name,
+                                           mypro_diff, NULL,package, NAME_O));
 
-               xsh_detmon_lg_save_image_with_pro_keys(
-                  cpl_imagelist_get(diff_flats, i),NAME_O,pextlist);
+                xsh_detmon_lg_save_image_with_pro_keys(
+                                                   cpl_imagelist_get(diff_flats, i),NAME_O,pextlist);
 
-            } else
+                cpl_propertylist_delete(pextlist);
+            }
+            else if(xsh_detmon_lg_config.exts == 0)
             {
+                cpl_propertylist_append_double(pplist, "ESO DET DIT", ddit);       
+                cpl_dfs_save_image
+                    (frameset, NULL, parlist, usedframes, NULL,
+                     cpl_imagelist_get(diff_flats, i), CPL_BPP_IEEE_FLOAT,
+                     recipe_name, pplist, NULL, package,
+                     NAME_O);
 
-               xsh_detmon_lg_save_image_with_pro_keys(
-                  cpl_imagelist_get(diff_flats, i),NAME_O,pextlist);
+            } else
+            {
+                cpl_propertylist* pextlist = cpl_propertylist_new();
+                cpl_propertylist_append_double(pextlist, "ESO DET DIT", ddit);   
+                if(whichext == 1)
+                {
+                    cpl_propertylist_append_double(mypro_diff,"ESO DET DIT",ddit);   
+                    //                  cpl_propertylist_erase(mypro_diff, "ESO DET DIT");
+                    skip_if(cpl_dfs_save_image(frameset, NULL, parlist, 
+                                               usedframes, NULL,NULL,
+                                               CPL_BPP_IEEE_FLOAT, recipe_name,
+                                               mypro_diff, NULL,package, NAME_O));
+
+                    xsh_detmon_lg_save_image_with_pro_keys(
+                                                       cpl_imagelist_get(diff_flats, i),NAME_O,pextlist);
+
+                } else
+                {
+
+                    xsh_detmon_lg_save_image_with_pro_keys(
+                                                       cpl_imagelist_get(diff_flats, i),NAME_O,pextlist);
 
+                }
+                cpl_propertylist_delete(pextlist);
             }
-            cpl_propertylist_delete(pextlist);
-         }
-         cpl_propertylist_delete(pplist);
-      }
+            cpl_propertylist_delete(pplist);
+            irplib_free(&NAME_O);
+        }
     } /* End of if(intermediate) */
 
 
     /*******************************/
     /*  Write the PAF file(s)      */
     /*******************************/
-    if(detmon_lg_config.pafgen) {
-
-       xsh_detmon_lg_save_paf_product(ref_frame,flag_sets,which_set,whichext,
-                                         pafregexp,procatg_gaintbl,
-                                         pipeline_name,recipe_name,
-                                         "qc01",gaint_qclist,0);
-
-       xsh_detmon_lg_save_paf_product(ref_frame,flag_sets,which_set,whichext,
-                                         pafregexp,procatg_lintbl,
-                                         pipeline_name,recipe_name,
-                                         "qc02",lint_qclist,0);
-
-       if(detmon_lg_config.pix2pix) 
-       {
-
-          xsh_detmon_lg_save_paf_product(ref_frame,flag_sets,which_set,
-                                            whichext,pafregexp,
-                                            procatg_coeffscube,
-                                            pipeline_name,recipe_name,
-                                            "qc03",linc_qclist,1);
-
-          xsh_detmon_lg_save_paf_product(ref_frame,flag_sets,which_set,
-                                            whichext,pafregexp,procatg_bpm,
-                                            pipeline_name,recipe_name,
-                                            "qc04",bpm_qclist,1);
-       }
+    cpl_msg_info(cpl_func,"Write the PAF file(s)");
+
+    if(xsh_detmon_lg_config.pafgen) {
+
+        xsh_detmon_lg_save_paf_product(ref_frame,flag_sets,which_set,whichext,
+                                   pafregexp,procatg_gaintbl,
+                                   pipeline_name,recipe_name,
+                                   "qc01",gaint_qclist,0);
+
+        xsh_detmon_lg_save_paf_product(ref_frame,flag_sets,which_set,whichext,
+                                   pafregexp,procatg_lintbl,
+                                   pipeline_name,recipe_name,
+                                   "qc02",lint_qclist,0);
+
+        if(xsh_detmon_lg_config.pix2pix) 
+        {
+
+            xsh_detmon_lg_save_paf_product(ref_frame,flag_sets,which_set,
+                                       whichext,pafregexp,
+                                       procatg_coeffscube,
+                                       pipeline_name,recipe_name,
+                                       "qc03",linc_qclist,1);
+
+            xsh_detmon_lg_save_paf_product(ref_frame,flag_sets,which_set,
+                                       whichext,pafregexp,procatg_bpm,
+                                       pipeline_name,recipe_name,
+                                       "qc04",bpm_qclist,1);
+        }
     }
 
     end_skip;
+    cpl_msg_info(cpl_func,"exit");
 
     cpl_propertylist_delete(xplist);
     if(plist!=NULL) {
-       cpl_propertylist_delete(plist);
-       plist=NULL;
+        cpl_propertylist_delete(plist);
+        plist=NULL;
     }
+
+    irplib_free(&NAME_O);
+    cpl_free(PREF_O);
+    cpl_free(pcatg_plane);
     cpl_propertylist_delete(mainplist);
     cpl_propertylist_delete(mypro_lintbl);
     cpl_propertylist_delete(mypro_gaintbl);
@@ -4375,6 +4922,7 @@ xsh_detmon_lg_save(const cpl_parameterlist * parlist,
     cpl_propertylist_delete(mypro_bpm);
     cpl_propertylist_delete(mypro_corr);
     cpl_propertylist_delete(mypro_diff);
+
     return cpl_error_get_code();
 }
 
@@ -4390,113 +4938,74 @@ xsh_detmon_lg_save(const cpl_parameterlist * parlist,
 /*---------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_opt_contamination(const cpl_imagelist * ons,
-				const cpl_imagelist * offs,
-				unsigned mode,
-                                cpl_propertylist * qclist)
+                         const cpl_imagelist * offs,
+                         unsigned mode,
+                         cpl_propertylist * qclist)
 {
+    struct rect {
+        size_t llx;
+        size_t lly;
+        size_t urx;
+        size_t ury;
+    };
+    struct rect rects[5] = {
+        (struct rect){ xsh_detmon_lg_config.llx1,
+                       xsh_detmon_lg_config.lly1,
+                       xsh_detmon_lg_config.urx1,
+                       xsh_detmon_lg_config.ury1},
+        (struct rect){ xsh_detmon_lg_config.llx2,
+                       xsh_detmon_lg_config.lly2,
+                       xsh_detmon_lg_config.urx2,
+                       xsh_detmon_lg_config.ury2},
+        (struct rect){ xsh_detmon_lg_config.llx3,
+                       xsh_detmon_lg_config.lly3,
+                       xsh_detmon_lg_config.urx3,
+                       xsh_detmon_lg_config.ury3},
+        (struct rect){ xsh_detmon_lg_config.llx4,
+                       xsh_detmon_lg_config.lly4,
+                       xsh_detmon_lg_config.urx4,
+                       xsh_detmon_lg_config.ury4},
+        (struct rect){ xsh_detmon_lg_config.llx5,
+                       xsh_detmon_lg_config.lly5,
+                       xsh_detmon_lg_config.urx5,
+                       xsh_detmon_lg_config.ury5},
+    };
+
+    for (size_t i = 0; i < 5; i++) {
+        cpl_image * dif_avg;
+        const cpl_image * off2;
+        double median;
+        char kname[300];
+        if (cpl_imagelist_get_size(offs) == 1 || mode & IRPLIB_LIN_COLLAPSE)
+            off2 = cpl_imagelist_get_const(offs, 0);
+        else
+            off2 = cpl_imagelist_get_const(offs, 1);
 
-    double                  median[5] = {0, 0, 0, 0, 0};
-
-    cpl_image * dif1=NULL;
-    cpl_image * dif2=NULL;
-    cpl_image * dif_avg=NULL;
-    char kname[2048];
-    int offsize = cpl_imagelist_get_size(offs);
-
-    /* Algorithm defined: substract ON - OFF and average 2 differences */
-    dif1 = cpl_image_subtract_create(cpl_imagelist_get_const(ons, 0),
-                                     cpl_imagelist_get_const(offs, 0));
-
-    if (offsize == 1 || mode & IRPLIB_LIN_COLLAPSE)
-        dif2 = cpl_image_subtract_create(cpl_imagelist_get_const(ons, 1),
-                                         cpl_imagelist_get_const(offs, 0));
-    else if (mode & IRPLIB_LIN_NO_COLLAPSE)
-        dif2 = cpl_image_subtract_create(cpl_imagelist_get_const(ons, 1),
-                                         cpl_imagelist_get_const(offs, 1));
-
-    dif_avg = cpl_image_average_create(dif1, dif2);
-
-    cpl_image_abs(dif_avg);
-
-    median[0] = cpl_image_get_median_window(dif_avg,
-					    detmon_lg_config.llx1,
-					    detmon_lg_config.lly1,
-					    detmon_lg_config.urx1,
-					    detmon_lg_config.ury1);
-
-    skip_if(0);
-    sprintf(kname, "%s%d", DETMON_QC_CONTAM,1);
-
-    if(cpl_propertylist_has(qclist,kname)){
-       skip_if(cpl_propertylist_update_double(qclist,kname,median[0]));
-    } else {
-       skip_if(cpl_propertylist_append_double(qclist,kname,median[0]));
-       skip_if(cpl_propertylist_set_comment(qclist,kname,DETMON_QC_CONTAM_C));
-    }
-    median[1] = cpl_image_get_median_window(dif_avg,
-					    detmon_lg_config.llx2,
-					    detmon_lg_config.lly2,
-					    detmon_lg_config.urx2,
-					    detmon_lg_config.ury2);
-
-    skip_if(0);
-    sprintf(kname, "%s%d", DETMON_QC_CONTAM,2);
-    if(cpl_propertylist_has(qclist,kname)){
-       skip_if(cpl_propertylist_update_double(qclist,kname,median[1]));
-    } else {
-       skip_if(cpl_propertylist_append_double(qclist,kname,median[1]));
-       skip_if(cpl_propertylist_set_comment(qclist,kname,DETMON_QC_CONTAM_C));
-    }
-    median[2] = cpl_image_get_median_window(dif_avg,
-					    detmon_lg_config.llx3,
-					    detmon_lg_config.lly3,
-					    detmon_lg_config.urx3,
-					    detmon_lg_config.ury3);
-    skip_if(0);
+        dif_avg = xsh_detmon_subtracted_avg(cpl_imagelist_get_const(ons, 0),
+                                        cpl_imagelist_get_const(offs, 0),
+                                        cpl_imagelist_get_const(ons, 1),
+                                        off2,
+                                        rects[i].llx,
+                                        rects[i].lly,
+                                        rects[i].urx,
+                                        rects[i].ury);
 
-    sprintf(kname, "%s%d", DETMON_QC_CONTAM,3);
-    if(cpl_propertylist_has(qclist,kname)){
-       skip_if(cpl_propertylist_update_double(qclist,kname,median[2]));
-    } else {
-       skip_if(cpl_propertylist_append_double(qclist,kname,median[2]));
-       skip_if(cpl_propertylist_set_comment(qclist,kname,DETMON_QC_CONTAM_C));
-    }
+        median = cpl_image_get_median(dif_avg);
+        cpl_image_delete(dif_avg);
 
-    median[3] = cpl_image_get_median_window(dif_avg,
-					    detmon_lg_config.llx4,
-					    detmon_lg_config.lly4,
-					    detmon_lg_config.urx4,
-					    detmon_lg_config.ury4);
-    skip_if(0);
+        skip_if(0);
+        sprintf(kname, "%s%d", DETMON_QC_CONTAM, i + 1);
 
-    sprintf(kname,"%s%d", DETMON_QC_CONTAM,4);
-    if(cpl_propertylist_has(qclist,kname)){
-       skip_if(cpl_propertylist_update_double(qclist,kname,median[3]));
-    } else {
-       skip_if(cpl_propertylist_append_double(qclist,kname,median[3]));
-       skip_if(cpl_propertylist_set_comment(qclist,kname,DETMON_QC_CONTAM_C));
+        if(cpl_propertylist_has(qclist,kname)){
+            skip_if(cpl_propertylist_update_double(qclist,kname,median));
+        } else {
+            skip_if(cpl_propertylist_append_double(qclist,kname,median));
+            skip_if(cpl_propertylist_set_comment(qclist,kname,DETMON_QC_CONTAM_C));
+        }
     }
 
-    median[4] = cpl_image_get_median_window(dif_avg,
-					    detmon_lg_config.llx5,
-					    detmon_lg_config.lly5,
-					    detmon_lg_config.urx5,
-					    detmon_lg_config.ury5);
-    skip_if(0);
-
-    sprintf(kname,"%s%d", DETMON_QC_CONTAM,5);
-    if(cpl_propertylist_has(qclist,kname)){
-       skip_if(cpl_propertylist_update_double(qclist,kname,median[4]));
-    } else {
-       skip_if(cpl_propertylist_append_double(qclist,kname,median[4]));
-       skip_if(cpl_propertylist_set_comment(qclist,kname,DETMON_QC_CONTAM_C));
-    }
     end_skip;
 
-    cpl_image_delete(dif1);
-    cpl_image_delete(dif2);
-    cpl_image_delete(dif_avg);
-
     return cpl_error_get_code();
 }
 
@@ -4535,7 +5044,7 @@ xsh_detmon_opt_lampcr(cpl_frameset * cur_fset, int ext)
 
     dit = irplib_pfits_get_dit_opt(plist);
 
-    detmon_lg_config.cr = cpl_image_get_mean(on) / dit;
+    xsh_detmon_lg_config.cr = cpl_image_get_mean(on) / dit;
 
     end_skip;
 
@@ -4557,33 +5066,33 @@ xsh_detmon_opt_lampcr(cpl_frameset * cur_fset, int ext)
 /*---------------------------------------------------------------------------*/
 int
 xsh_detmon_lg_dfs_set_groups(cpl_frameset * set,
-                                const char *tag_on, const char *tag_off)
+                         const char *tag_on, const char *tag_off)
 {
-    cpl_frame              *cur_frame;
-    const char             *tag;
-    int                     nframes;
-    int                     i;
+
+
+
+
 
     /* Check entries */
     if(set == NULL)
         return -1;
 
     /* Initialize */
-    nframes = cpl_frameset_get_size(set);
+    int nframes = cpl_frameset_get_size(set);
 
     /* Loop on frames */
-    for(i = 0; i < nframes; i++) {
-        cur_frame = cpl_frameset_get_frame(set, i);
-        tag = cpl_frame_get_tag(cur_frame);
+    for(int i = 0; i < nframes; i++) {
+        cpl_frame* cur_frame = cpl_frameset_get_position(set, i);
+        const char* tag = cpl_frame_get_tag(cur_frame);
 
         /* RAW frames */
         if(!strcmp(tag, tag_on) || !strcmp(tag, tag_off))
             cpl_frame_set_group(cur_frame, CPL_FRAME_GROUP_RAW);
         /* CALIB frames */
 
-/*        else if (!strcmp(tag, IIINSTRUMENT_CALIB_FLAT))
-            cpl_frame_set_group(cur_frame, CPL_FRAME_GROUP_CALIB);
-*/
+        /*        else if (!strcmp(tag, IIINSTRUMENT_CALIB_FLAT))
+                  cpl_frame_set_group(cur_frame, CPL_FRAME_GROUP_CALIB);
+                  */
     }
     return 0;
 }
@@ -4600,67 +5109,340 @@ xsh_detmon_lg_dfs_set_groups(cpl_frameset * set,
 /*---------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_lg_fits_coeffs_and_bpm2chip(cpl_imagelist ** coeffs_ptr,
-                                          cpl_image **bpms_ptr)
+                                   cpl_image **bpms_ptr)
 {
-   cpl_image* dummy_bpm=NULL;
-   cpl_image * dummy_coeff=NULL;
-   cpl_imagelist * dummy_coeffs=NULL;
-   int * db_p=NULL;
-   int * rb_p =NULL;
-   float ** dcs_p;
-   float ** rcs_p;
-   int dlength=0;
-   int rlength=0;
-   int shift_idx=0;
-   int i=0;
-   int k=0;
-   int j=0;
-
-   dummy_bpm = cpl_image_new(detmon_lg_config.nx,
-                             detmon_lg_config.ny,
-                             CPL_TYPE_INT);
-   dummy_coeffs = cpl_imagelist_new();
-
-   db_p = cpl_image_get_data_int(dummy_bpm);
-   rb_p = cpl_image_get_data_int(*bpms_ptr);;  
-   dcs_p = cpl_malloc(sizeof(float *) * (detmon_lg_config.order + 1));
-   rcs_p = cpl_malloc(sizeof(float *) * (detmon_lg_config.order + 1));
-   dlength = detmon_lg_config.nx;
-   rlength = detmon_lg_config.urx - detmon_lg_config.llx + 1;
-   for (i = 0; i <= detmon_lg_config.order; i++) 
-   {
-      dummy_coeff = cpl_image_new(detmon_lg_config.nx,
-                                  detmon_lg_config.ny,
-                                  CPL_TYPE_FLOAT);
-
-      cpl_imagelist_set(dummy_coeffs, dummy_coeff, i);
-      dcs_p[i] = cpl_image_get_data_float(dummy_coeff);
-      rcs_p[i] = cpl_image_get_data_float(cpl_imagelist_get(*coeffs_ptr, i));
-   }
-   /*copy the coefficients from temporary image to the dummy_bpm*/  
-   for (i = detmon_lg_config.lly - 1; i < detmon_lg_config.ury; i++) 
-   {
-      for (j = detmon_lg_config.llx - 1; j < detmon_lg_config.urx; j++) 
-      {
-         shift_idx=(i - detmon_lg_config.lly + 1) * rlength +
-            j - detmon_lg_config.llx + 1;
-         *(db_p + i * dlength + j) = *(rb_p + shift_idx);
-         for (k = 0; k <= detmon_lg_config.order; k++) 
-         {
-            *(dcs_p[k] + i * dlength + j) =
-               *(rcs_p[k] + (i - detmon_lg_config.lly + 1) * rlength +
-                 j - detmon_lg_config.llx + 1);
-         }
-      }
-   }
-   cpl_imagelist_delete(*coeffs_ptr);
-   cpl_image_delete(*bpms_ptr);
-   *coeffs_ptr = dummy_coeffs;
-   *bpms_ptr = dummy_bpm;
-   cpl_free(dcs_p);
-   cpl_free(rcs_p);
-
-   return cpl_error_get_code();
+
+
+
+
+
+
+
+
+
+    int shift_idx=0;
+
+
+
+
+    cpl_image* dummy_bpm = cpl_image_new(xsh_detmon_lg_config.nx,
+                              xsh_detmon_lg_config.ny,
+                              CPL_TYPE_INT);
+    cpl_imagelist* dummy_coeffs = cpl_imagelist_new();
+
+    int* db_p = cpl_image_get_data_int(dummy_bpm);
+    int* rb_p = cpl_image_get_data_int(*bpms_ptr);;
+    float** dcs_p = cpl_malloc(sizeof(float *) * (xsh_detmon_lg_config.order + 1));
+    float** rcs_p = cpl_malloc(sizeof(float *) * (xsh_detmon_lg_config.order + 1));
+    int dlength = xsh_detmon_lg_config.nx;
+
+    int rlength = xsh_detmon_lg_config.urx - xsh_detmon_lg_config.llx + 1;
+    for (int i = 0; i <= xsh_detmon_lg_config.order; i++)
+    {
+        cpl_image* dummy_coeff = cpl_image_new(xsh_detmon_lg_config.nx,
+                                    xsh_detmon_lg_config.ny,
+                                    CPL_TYPE_FLOAT);
+
+        cpl_imagelist_set(dummy_coeffs, dummy_coeff, i);
+        dcs_p[i] = cpl_image_get_data_float(dummy_coeff);
+        rcs_p[i] = cpl_image_get_data_float(cpl_imagelist_get(*coeffs_ptr, i));
+    }
+    /*copy the coefficients from temporary image to the dummy_bpm*/  
+    for (int i = xsh_detmon_lg_config.lly - 1; i < xsh_detmon_lg_config.ury; i++)
+    {
+        for (int j = xsh_detmon_lg_config.llx - 1; j < xsh_detmon_lg_config.urx; j++)
+        {
+            shift_idx=(i - xsh_detmon_lg_config.lly + 1) * rlength +
+                j - xsh_detmon_lg_config.llx + 1;
+            *(db_p + i * dlength + j) = *(rb_p + shift_idx);
+            for (int k = 0; k <= xsh_detmon_lg_config.order; k++)
+            {
+                *(dcs_p[k] + i * dlength + j) =
+                    *(rcs_p[k] + (i - xsh_detmon_lg_config.lly + 1) * rlength +
+                      j - xsh_detmon_lg_config.llx + 1);
+            }
+        }
+    }
+    cpl_imagelist_delete(*coeffs_ptr);
+    cpl_image_delete(*bpms_ptr);
+    *coeffs_ptr = dummy_coeffs;
+    *bpms_ptr = dummy_bpm;
+    cpl_free(dcs_p);
+    cpl_free(rcs_p);
+
+    return cpl_error_get_code();
+}
+
+/* Not used so we temporaryly comment it out
+static cpl_error_code
+xsh_detmon_lg_qclog_lin_coeff(cpl_imagelist* coeffs_ptr, const int order, cpl_propertylist* linc_qclist)
+{
+  cpl_image* image=NULL;
+  int i=0;
+  double coeff=0;
+  double * pcoeffs = cpl_malloc(sizeof(double)*(order + 1));
+  char* name_o1=NULL;
+  char* name_o2=NULL;
+
+  for(i = 0; i <= order; i++)
+  {
+    image = cpl_imagelist_get(coeffs_ptr, i);
+    coeff = cpl_image_get_median(image);
+    pcoeffs[i] = coeff;
+    name_o1 = cpl_sprintf("ESO QC LIN COEF%d", i);
+    name_o2 = cpl_sprintf("ESO QC LIN COEF%d ERR", i);
+    assert(name_o1 != NULL);
+    assert(name_o2 != NULL);
+    cpl_propertylist_append_double(linc_qclist, name_o1, coeff);
+    cpl_propertylist_set_comment(linc_qclist,name_o1,DETMON_QC_LIN_COEF_C);
+    cpl_free(name_o1);
+    name_o1= NULL;
+    cpl_propertylist_append_double(linc_qclist, name_o2,cpl_image_get_stdev(image));
+    cpl_propertylist_set_comment(linc_qclist,name_o2,DETMON_QC_LIN_COEF_ERR_C);
+    cpl_free(name_o2);
+    name_o2= NULL;
+  }
+  cpl_free(pcoeffs);
+
+  return cpl_error_get_code();
+}
+*/
+/*----------------------------------------------------------------------------*/
+/**
+  @brief   compute photon count error in [ADU]
+  @param   ima_data in [ADU]
+  @param   gain detector's gain in [e- / ADU]
+  @param   ron  detector's read out noise in [ADU]
+  @param   ima_errs output error image in [ADU]
+  @return  cpl_error_code
+  @note ima_errs need to be deallocated
+        ima_data must contain the photon counts with no offsets
+        this usually means the image must be overscan and bias corrected
+        Then the shot noise can be calculated from the poissonian distribution
+        as sqrt(electron-counts). To this (transformed back into ADUs) the
+        readout noise is added in quadrature.
+  @doc
+  error is computed with standard formula
+
+  \f$ err_{ADU} = \sqrt{ \frac{ counts }{ gain } + ron^{ 2 } } \f$
+
+  If an image value is negative the associated error is set to RON
+ */
+/*----------------------------------------------------------------------------*/
+cpl_error_code
+xsh_detmon_detector_shotnoise_model(const cpl_image* ima_data, const double gain,
+                              const double ron, cpl_image ** ima_errs)
+{
+    cpl_ensure_code(ima_data, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(ima_errs, CPL_ERROR_NULL_INPUT);
+    cpl_ensure_code(gain > 0., CPL_ERROR_ILLEGAL_INPUT);
+    cpl_ensure_code(ron > 0., CPL_ERROR_ILLEGAL_INPUT);
+
+    *ima_errs = cpl_image_duplicate(ima_data);
+    /* set negative values (= zero measurable electrons) to read out noise */
+    cpl_image_threshold(*ima_errs, 0., INFINITY, ron, ron);
+
+    /* err_ADU = sqrt(counts/gain + ron * ron)*/
+
+    cpl_image_divide_scalar(*ima_errs, gain);
+    cpl_image_add_scalar(*ima_errs, ron * ron);
+    cpl_image_power(*ima_errs, 0.5);
+
+    return cpl_error_get_code();
+}
+
+int
+xsh_detmon_compute_badpixmap(cpl_boolean opt_nir, const int nsets,
+                const cpl_table* linear_table,
+                const cpl_imagelist* linearity_inputs, int nbpixs,
+                cpl_vector* x, cpl_propertylist* gaint_qclist,
+                cpl_image** bpms_ptr)
+{
+    /* Here determines the bad pixel map
+     * HDRL based version
+     * AMO: this if is repeated: the following code should be up up
+     */
+    if (opt_nir == NIR) {
+        x = cpl_vector_wrap(nsets,
+                        (double *) cpl_table_get_data_double_const(linear_table,
+                                        "DIT"));
+    }
+    else {
+        x = cpl_vector_wrap(nsets,
+                        (double *) cpl_table_get_data_double_const(linear_table,
+                                        "EXPTIME"));
+
+    }
+    int sz = cpl_imagelist_get_size(linearity_inputs);
+    int sx = cpl_image_get_size_x(cpl_imagelist_get_const(linearity_inputs, 0));
+    int sy = cpl_image_get_size_y(cpl_imagelist_get_const(linearity_inputs, 0));
+    double kappa = xsh_detmon_lg_config.kappa;
+    int niter = xsh_detmon_lg_config.niter;
+    int llx = xsh_detmon_lg_config.llx;
+    int urx = xsh_detmon_lg_config.urx;
+    int lly = xsh_detmon_lg_config.lly;
+    int ury = xsh_detmon_lg_config.ury;
+    hdrl_parameter* p;
+    double median;
+    cpl_image *ima, *err;
+    // fit-chi-rel method
+    // errors to be used with fit_chi_rel method
+    cpl_imagelist* errors = cpl_imagelist_new();
+    /*
+     // case1: error proportional to sqrt(EXPTIME)
+     for(int i=0;i<sz;i++) {
+     err=cpl_image_new(sx,sy,CPL_TYPE_DOUBLE);
+     cpl_image_add_scalar(err,1.);
+     cpl_imagelist_set(errors,err,i);
+     }
+     */
+    /*
+     // case2:shot noise model to be used with fit_chi_rel method
+     double gain=1.;
+     double ron=1.;
+     for(int i=0;i<sz;i++) {
+     ima=cpl_imagelist_get(linearity_inputs,i);
+     hdrldemo_detector_shotnoise_model(ima, gain, ron, &err);
+     cpl_imagelist_set(errors,err,i);
+     }
+     */
+    // case3: error obtained using mad error approximation
+    double dmad;
+    //cpl_msg_info(cpl_func,"sz=%d",sz);
+    cpl_imagelist* linearity_scaled = cpl_imagelist_new();
+    double gain = 0;
+    gain = cpl_propertylist_get_double(gaint_qclist, DETMON_QC_GAIN);
+    //cpl_msg_info(cpl_func,"ok1 gain=%g",gain);
+    /* on simulations gain ,may be < 0: make sure it is > 0 */
+    //cpl_msg_info(cpl_func,"ok1 gain=%g",gain);
+    gain = (gain < 0) ? 1 : gain;
+    double gain_eff = 2 * gain;
+    //gain_eff=1;
+    double ron = 1;
+    double avg = 0;
+    double rms = 0;
+    int k = 0;
+    char dname[80];
+    char ename[80];
+    char fname[80];
+    skip_if(rms);
+    //cpl_msg_info(cpl_func,"sz=%d",sz);
+    //cpl_msg_info(cpl_func,"llx=%d lly=%d urx=%d ury=%d",llx,lly,urx,ury);
+    for (int i = 0; i < sz; i++) {
+        ima = cpl_imagelist_get(linearity_inputs, i);
+        /*
+         cpl_msg_info(cpl_func,"sx=%d sy=%d",
+         cpl_image_get_size_x(ima),cpl_image_get_size_y(ima));
+         */
+        //cpl_msg_info(cpl_func,"max_x=%d max_y=%d",urx-llx+1,ury-lly+1);
+        //median=cpl_image_get_median_window(ima,1,1,urx-llx+1,ury-lly+1);
+        skip_if(
+                        xsh_ksigma_clip(ima, 1, 1, urx - llx + 1,
+                                        ury - lly + 1, kappa, niter, 1e-5, &avg,
+                                        &rms));
+
+        //cpl_msg_info(cpl_func,"avg=%g median=%g",avg,median);
+        //cpl_msg_info(cpl_func,"thresh=%g", xsh_detmon_lg_config.saturation_limit);
+        if (avg < xsh_detmon_lg_config.saturation_limit) {
+
+            //cpl_msg_info(cpl_func,">>>>i=%d", i);
+            /*
+             err=cpl_image_duplicate(ima);
+             cpl_image_multiply_scalar(err, gain);
+             cpl_image_power(err,0.5);
+             */
+            cpl_image_get_mad(ima, &dmad);
+            err = cpl_image_duplicate(ima);
+            cpl_image_multiply_scalar(err, 0);
+            cpl_image_add_scalar(err, dmad * CPL_MATH_STD_MAD);
+
+            //xsh_detmon_detector_shotnoise_model(ima, gain_eff,ron, &err);
+            /*
+             cpl_msg_info(cpl_func,"err sx=%d",cpl_image_get_size_x(err));
+             cpl_msg_info(cpl_func,"err sy=%d",cpl_image_get_size_y(err));
+             cpl_msg_info(cpl_func,"ima sx=%d",cpl_image_get_size_x(ima));
+             cpl_msg_info(cpl_func,"ima sy=%d",cpl_image_get_size_y(ima));
+             cpl_msg_info(cpl_func,"sy=%d",cpl_image_get_size_y(err));
+             */
+            cpl_imagelist_set(errors, err, i);
+            /*
+             sprintf(dname,"data_%d.fits",i);
+             sprintf(ename,"errs_%d.fits",i);
+             cpl_image_save(err, ename, CPL_BPP_IEEE_FLOAT,NULL,CPL_IO_DEFAULT);
+             cpl_image_save(ima, dname, CPL_BPP_IEEE_FLOAT,NULL,CPL_IO_DEFAULT);
+             */
+            skip_if(
+                            cpl_imagelist_set(linearity_scaled,
+                                            cpl_image_duplicate(ima), i));
+        }
+    }
+    hdrl_imagelist* hil = hdrl_imagelist_create(linearity_scaled, errors);
+    /*
+     cpl_imagelist_save(linearity_scaled,"lin_data.fits", CPL_BPP_IEEE_FLOAT,NULL,CPL_IO_DEFAULT);
+     cpl_imagelist_save(errors,"lin_errs.fits", CPL_BPP_IEEE_FLOAT,NULL,CPL_IO_DEFAULT);
+     */
+    cpl_imagelist_delete(errors);
+    /* P-val method */
+    double pval = 0.001;
+    p = hdrl_bpm_fit_parameter_create_pval(1, pval);
+    /*
+     p = hdrl_bpm_fit_parameter_create_rel_coef(1, 1., 1.);
+     hdrl_parameter_delete(p);
+     */
+    /* chi-rel method
+     int ord=xsh_detmon_lg_config.order;
+     p = hdrl_bpm_fit_parameter_create_rel_chi(1, kappa, kappa);
+     */
+    hdrl_bpm_fit_compute(p, hil, x, bpms_ptr);
+    //cpl_vector_dump(x,stdout);
+    /*
+     // bpm-3D method
+     cpl_imagelist* linearity_scaled=cpl_imagelist_new();
+
+     for(int i=0;i<sz;i++) {
+     ima=cpl_imagelist_get(linearity_inputs,i);
+     median=cpl_image_get_median(ima);
+     if(median < xsh_detmon_lg_config.saturation_limit) {
+     cpl_image_divide_scalar(ima,median);
+     cpl_imagelist_set(linearity_scaled,cpl_image_duplicate(ima),i);
+     }
+     }
+     hdrl_imagelist* hil= hdrl_imagelist_create(linearity_scaled,NULL);
+
+
+     // bpm-3D method
+     hdrl_bpm_3d_method      method = HDRL_BPM_3D_THRESHOLD_RELATIVE ;
+     p=hdrl_bpm_3d_parameter_create(kappa, kappa, method) ;
+     cpl_imagelist * out_imlist = hdrl_bpm_3d_compute(hil, p);
+     *bpms_ptr = cpl_imagelist_collapse_create(out_imlist);
+     cpl_msg_info(cpl_func,"BP map value: min=%g max=%g",
+     cpl_image_get_min(*bpms_ptr),cpl_image_get_max(*bpms_ptr));
+     */
+    nbpixs = cpl_image_get_flux(*bpms_ptr);
+    /* clean-up memory */
+    hdrl_imagelist_delete(hil);
+    cpl_imagelist_delete(linearity_scaled);
+    cpl_vector_unwrap((cpl_vector*) x);
+    hdrl_parameter_delete(p);
+    // 3D method only
+    //cpl_imagelist_delete(out_imlist);
+    /* ORIGINAL BP MAP COMPUTATION
+     *bpms_ptr = xsh_detmon_bpixs(*coeffs_ptr, xsh_detmon_lg_config.bpmbin,
+     xsh_detmon_lg_config.kappa, &nbpixs);
+     */
+    /*
+     *bpms_ptr = xsh_detmon_bpixs2(x,linearity_inputs,*coeffs_ptr,gain_table,
+     xsh_detmon_lg_config.order,xsh_detmon_lg_config.bpmbin,xsh_detmon_lg_config.kappa,&nbpixs);
+     */
+    /*
+     cpl_vector_unwrap((cpl_vector*)x);
+     cpl_vector_unwrap((cpl_vector*)y);
+     */
+    //cpl_msg_info(cpl_func,"nbpixs=%d",nbpixs);
+    skip_if(*bpms_ptr == NULL);
+
+    end_skip;
+    return nbpixs;
 }
 
 /*---------------------------------------------------------------------------*/
@@ -4680,27 +5462,27 @@ xsh_detmon_lg_fits_coeffs_and_bpm2chip(cpl_imagelist ** coeffs_ptr,
 /*---------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_lg_reduce_all(const cpl_table * linear_table,
-                            cpl_propertylist * gaint_qclist,
-                            cpl_propertylist * lint_qclist,
-                            cpl_propertylist * linc_qclist,
-                            cpl_propertylist * bpm_qclist,
-                            cpl_imagelist ** coeffs_ptr,
-                            cpl_image ** bpms_ptr,
-                            const cpl_imagelist * linearity_inputs,
-                            const cpl_table * gain_table,
-			    int which_ext, cpl_boolean opt_nir)
+                      cpl_propertylist * gaint_qclist,
+                      cpl_propertylist * lint_qclist,
+                      cpl_propertylist * linc_qclist,
+                      cpl_propertylist * bpm_qclist,
+                      cpl_imagelist ** coeffs_ptr,
+                      cpl_image ** bpms_ptr,
+                      const cpl_imagelist * linearity_inputs,
+                      const cpl_table * gain_table,
+                      int which_ext, cpl_boolean opt_nir)
 {
 
     int                     nbpixs = 0;
-    const int               nsets = cpl_table_get_nrow(linear_table);
-    int                     i;
+    const int               linear_nsets = cpl_table_get_nrow(linear_table);
+    const int               gain_nsets = cpl_table_get_nrow(gain_table);
     double autocorr;
     cpl_polynomial         *poly_linfit = NULL;
     cpl_image              *fiterror = NULL;
     char * name_o1 = NULL;
     char * name_o2 = NULL;
-    double * pcoeffs = cpl_malloc(sizeof(double)*(detmon_lg_config.order + 1));
-    unsigned mode = detmon_lg_config.autocorr ? IRPLIB_GAIN_WITH_AUTOCORR : 0;
+    double * pcoeffs = NULL;
+    unsigned mode = xsh_detmon_lg_config.autocorr ? IRPLIB_GAIN_WITH_AUTOCORR : 0;
     double min_val=0;
     double max_val=0;
     cpl_vector *x =NULL;
@@ -4712,7 +5494,7 @@ xsh_detmon_lg_reduce_all(const cpl_table * linear_table,
     int sizey = 0;
 
     int vsize = 0;
-
+    cpl_size deg=0;
     /* FIXME: This should go before the x and y vectors.
        Checking for all the inputs */
     cpl_ensure_code(gaint_qclist != NULL, CPL_ERROR_NULL_INPUT);
@@ -4720,189 +5502,203 @@ xsh_detmon_lg_reduce_all(const cpl_table * linear_table,
     cpl_ensure_code(linc_qclist != NULL, CPL_ERROR_NULL_INPUT);
     cpl_ensure_code(bpm_qclist != NULL, CPL_ERROR_NULL_INPUT);
 
+    pcoeffs = cpl_malloc(sizeof(double)*(xsh_detmon_lg_config.order + 1));
+
     skip_if(cpl_propertylist_append_string(gaint_qclist, DETMON_QC_METHOD,
-					   detmon_lg_config.method));
+                                           xsh_detmon_lg_config.method));
     skip_if(cpl_propertylist_set_comment(gaint_qclist, DETMON_QC_METHOD,
-					 DETMON_QC_METHOD_C));
-
-    if (!strcmp(detmon_lg_config.method, "PTC")) {
-	/* Computation of GAIN via polynomial fit */
-	if (detmon_lg_config.exts >= 0) {
-	    cpl_msg_info(cpl_func,
-			 "Polynomial fitting for the GAIN (constant term method)");
-	} else {
-	    cpl_msg_info(cpl_func,
-			 "Polynomial fitting for the GAIN (constant term method)"
-			 " for extension nb %d", which_ext);
-	}
-	skip_if(xsh_detmon_lg_qc_ptc(gain_table, gaint_qclist, mode, nsets));
+                                         DETMON_QC_METHOD_C));
+
+
+    if (!strcmp(xsh_detmon_lg_config.method, "PTC")) {
+        /* Computation of GAIN via polynomial fit */
+        if (xsh_detmon_lg_config.exts >= 0) {
+            cpl_msg_info(cpl_func,
+                         "Polynomial fitting for the GAIN (constant term method)");
+        } else {
+            cpl_msg_info(cpl_func,
+                         "Polynomial fitting for the GAIN (constant term method)"
+                         " for extension nb %d", which_ext);
+        }
+        skip_if(xsh_detmon_lg_qc_ptc(gain_table, gaint_qclist, mode, gain_nsets));
     } else {
-	skip_if(xsh_detmon_lg_qc_med(gain_table, gaint_qclist, nsets));
+        skip_if(xsh_detmon_lg_qc_med(gain_table, gaint_qclist, gain_nsets));
     }
 
     /*^FIXME: This shouldn't be written when no applied */
     /* Lamp flux */
-    if(detmon_lg_config.lamp_ok) {
-	skip_if(cpl_propertylist_append_double(lint_qclist, DETMON_QC_LAMP_FLUX,
-					       detmon_lg_config.cr));
-	skip_if(cpl_propertylist_set_comment(lint_qclist, DETMON_QC_LAMP_FLUX,
-					     DETMON_QC_LAMP_FLUX_C));
+    if(xsh_detmon_lg_config.lamp_ok) {
+        skip_if(cpl_propertylist_append_double(lint_qclist, DETMON_QC_LAMP_FLUX,
+                                               xsh_detmon_lg_config.cr));
+        skip_if(cpl_propertylist_set_comment(lint_qclist, DETMON_QC_LAMP_FLUX,
+                                             DETMON_QC_LAMP_FLUX_C));
     }
 
     /*^FIXME: This shouldn't be written when no applied */
-    if(detmon_lg_config.autocorr == TRUE) {
-	autocorr = cpl_table_get_column_median(gain_table, "AUTOCORR");
-	skip_if(cpl_propertylist_append_double(gaint_qclist, DETMON_QC_AUTOCORR,
-					       autocorr));
-	skip_if(cpl_propertylist_set_comment(gaint_qclist, DETMON_QC_AUTOCORR,
-					     DETMON_QC_AUTOCORR_C));
-    }
-    if (detmon_lg_config.exts >= 0) {
+    if(xsh_detmon_lg_config.autocorr == TRUE) {
+        autocorr = cpl_table_get_column_median(gain_table, "AUTOCORR");
+        skip_if(cpl_propertylist_append_double(gaint_qclist, DETMON_QC_AUTOCORR,
+                                               autocorr));
+        skip_if(cpl_propertylist_set_comment(gaint_qclist, DETMON_QC_AUTOCORR,
+                                             DETMON_QC_AUTOCORR_C));
+    }
+    if (xsh_detmon_lg_config.exts >= 0) {
         cpl_msg_info(cpl_func, "Polynomial fitting pix-to-pix");
     } else {
         cpl_msg_info(cpl_func, "Polynomial fitting pix-to-pix"
-                               " for extension nb %d", which_ext);
+                     " for extension nb %d", which_ext);
     }
 
-    if(!detmon_lg_config.pix2pix) {
-	double mse = 0;
-        /* Computation of LINEARITY via polynomial fit */
-	y = cpl_vector_wrap(nsets,
-			    (double *)cpl_table_get_data_double_const(linear_table,
-							      "MED"));
+    if(!xsh_detmon_lg_config.pix2pix) {
+        const int order=xsh_detmon_lg_config.order;
+
 
-	if (opt_nir == NIR)
-	    x = cpl_vector_wrap(nsets,
-				(double *)cpl_table_get_data_double_const(linear_table,
-							      "DIT"));
-	else
-	    x = cpl_vector_wrap(nsets,
-				(double *)cpl_table_get_data_double_const(linear_table,
-							      "EXPTIME"));
 
 
+
+        double mse = 0;
+        /* Computation of LINEARITY via polynomial fit */
+        y = cpl_vector_wrap(linear_nsets,
+                            (double *)cpl_table_get_data_double_const(linear_table,
+                                                                      "MED"));
+
+        if (opt_nir == NIR) {
+            x = cpl_vector_wrap(linear_nsets,
+                                (double *)cpl_table_get_data_double_const(linear_table,
+                                                                          "DIT"));
+        } else {
+            x = cpl_vector_wrap(linear_nsets,
+                                (double *)cpl_table_get_data_double_const(linear_table,
+                                                                          "EXPTIME"));
+        }
+
         if(x == NULL || y == NULL) {
-	    cpl_vector_unwrap((cpl_vector *)x);
-	    cpl_vector_unwrap((cpl_vector *)y);
-	    /*
-	     * As x and y are const vectors, if they would be defined at the
-	     * beginning of the function (required for skip_if - end_skip
-	     * scheme), they couldn't be initialised to NULL (required too).
-	     * Therefore, they are considered apart from the scheme.
-	     */
-	    skip_if(1);
-	}
+            cpl_vector_unwrap((cpl_vector *)x);
+            cpl_vector_unwrap((cpl_vector *)y);
+            /*
+             * As x and y are const vectors, if they would be defined at the
+             * beginning of the function (required for skip_if - end_skip
+             * scheme), they couldn't be initialised to NULL (required too).
+             * Therefore, they are considered apart from the scheme.
+             */
+            skip_if(1);
+        }
 
         cpl_msg_info(cpl_func, "Polynomial fitting for the LINEARITY");
-        poly_linfit = irplib_polynomial_fit_1d_create(x, y,
-						   detmon_lg_config.order,
-						   &mse);
+        poly_linfit = irplib_polynomial_fit_1d_create(x, y,order,&mse);
 
-	if(detmon_lg_config.order == cpl_vector_get_size(x) - 1) {
-	    cpl_msg_warning(cpl_func, "The fitting is not over-determined.");
-	    mse = 0;
-	}
+        if(order == cpl_vector_get_size(x) - 1) {
+            cpl_msg_warning(cpl_func, "The fitting is not over-determined.");
+            mse = 0;
+        }
 
-	if(poly_linfit == NULL) {
-	    cpl_vector_unwrap((cpl_vector *)x);
-	    cpl_vector_unwrap((cpl_vector *)y);
-	    /* See comment in previous error checking if() statement */
-	    skip_if(1);
-	}
+        if(poly_linfit == NULL) {
+            cpl_vector_unwrap((cpl_vector *)x);
+            cpl_vector_unwrap((cpl_vector *)y);
+            /* See comment in previous error checking if() statement */
+            skip_if(1);
+        }
 
 
         min_val=cpl_vector_get_min(y);
         max_val=cpl_vector_get_max(y);
 
-	cpl_vector_unwrap((cpl_vector *)x);
-	cpl_vector_unwrap((cpl_vector *)y);
-        cpl_size deg=0;
-        for(deg = 0; deg <= detmon_lg_config.order; deg++) {
+        cpl_vector_unwrap((cpl_vector *)x);
+        cpl_vector_unwrap((cpl_vector *)y);
+
+        for(deg = 0; deg <= order; deg++) {
             const double            coeff =
                 cpl_polynomial_get_coeff(poly_linfit, &deg);
             char                   *name_o =
                 cpl_sprintf("ESO QC LIN COEF%" CPL_SIZE_FORMAT "", deg);
             assert(name_o != NULL);
             skip_if(cpl_propertylist_append_double(lint_qclist, name_o, coeff));
-    	    skip_if(cpl_propertylist_set_comment(lint_qclist,name_o,
-						 DETMON_QC_LIN_COEF_C));
+            skip_if(cpl_propertylist_set_comment(lint_qclist,name_o,
+                                                 DETMON_QC_LIN_COEF_C));
 
             cpl_free(name_o);
-	    pcoeffs[deg] = coeff;
+            pcoeffs[deg] = coeff;
         }
-	skip_if(cpl_propertylist_append_double(lint_qclist,DETMON_QC_ERRFIT, mse));
-    	skip_if(cpl_propertylist_set_comment(lint_qclist,DETMON_QC_ERRFIT,
-					     DETMON_QC_ERRFIT_MSE_C));
+        skip_if(cpl_propertylist_append_double(lint_qclist,DETMON_QC_ERRFIT, mse));
+        skip_if(cpl_propertylist_set_comment(lint_qclist,DETMON_QC_ERRFIT,
+                                             DETMON_QC_ERRFIT_MSE_C));
 
 
-    } else 
-    {
-	     y = cpl_vector_wrap(nsets,
-			    (double *)cpl_table_get_data_double_const(linear_table,
-							      "MED"));
-        if (opt_nir == NIR) 
-        {
-            x = cpl_vector_wrap(nsets,
-			    (double *)cpl_table_get_data_double_const(linear_table,
-							      "DIT"));
-        } else 
+    } else {
+        const int order=xsh_detmon_lg_config.order;
+        /* pix2pix == TRUE */
+        y = cpl_vector_wrap(linear_nsets,
+                            (double *)cpl_table_get_data_double_const(linear_table,
+                                                                      "MED"));
+
+        if (opt_nir == NIR)
         {
-	        x = cpl_vector_wrap(nsets,
-			    (double *)cpl_table_get_data_double_const(linear_table,
-							      "EXPTIME"));
+            x = cpl_vector_wrap(linear_nsets,
+                                (double *)cpl_table_get_data_double_const(linear_table,
+                                                                          "DIT"));
+        } else {
+            x = cpl_vector_wrap(linear_nsets,
+                                (double *)cpl_table_get_data_double_const(linear_table,
+                                                                          "EXPTIME"));
 
         }
+
         first = cpl_imagelist_get_const(linearity_inputs, 0);
         sizex = cpl_image_get_size_x(first);
         sizey = cpl_image_get_size_y(first);
         vsize = cpl_vector_get_size(x);
         fiterror = cpl_image_new(sizex, sizey, CPL_TYPE_FLOAT);
-	     *coeffs_ptr =
-	        cpl_fit_imagelist_polynomial(x, linearity_inputs, 0,
-					 detmon_lg_config.order, FALSE,
-					 CPL_TYPE_FLOAT, fiterror);
+        *coeffs_ptr =
+            cpl_fit_imagelist_polynomial(x, linearity_inputs, 0,order, FALSE,
+                                         CPL_TYPE_FLOAT, fiterror);
         min_val=cpl_vector_get_min(y);
         max_val=cpl_vector_get_max(y);
         cpl_vector_unwrap((cpl_vector*)x);
         cpl_vector_unwrap((cpl_vector*)y);
+
         irplib_ensure(*coeffs_ptr != NULL, CPL_ERROR_UNSPECIFIED,
-		      "Failed polynomial fit");
-        for(i = 0; i <= detmon_lg_config.order; i++) 
+                      "Failed polynomial fit");
+        //xsh_detmon_lg_qclog_lin_coeff(*coeffs_ptr, order,linc_qclist);
+
+        for(deg = 0; deg <= order; deg++)
         {
-            cpl_image *image = cpl_imagelist_get(*coeffs_ptr, i);
-	         const double coeff = cpl_image_get_median(image);
-	         pcoeffs[i] = coeff;
-            name_o1 = cpl_sprintf("ESO QC LIN COEF%d", i);
-            name_o2 = cpl_sprintf("ESO QC LIN COEF%d ERR", i);
+            cpl_image *image = cpl_imagelist_get(*coeffs_ptr, deg);
+            const double coeff = cpl_image_get_median(image);
+            pcoeffs[deg] = coeff;
+            name_o1 = cpl_sprintf("ESO QC LIN COEF%d", (int)deg);
+            name_o2 = cpl_sprintf("ESO QC LIN COEF%d ERR", (int)deg);
             assert(name_o1 != NULL);
             assert(name_o2 != NULL);
             skip_if(cpl_propertylist_append_double(linc_qclist, name_o1, coeff));
-    	      skip_if(cpl_propertylist_set_comment(linc_qclist,name_o1,
-						 DETMON_QC_LIN_COEF_C));
+            skip_if(cpl_propertylist_set_comment(linc_qclist,name_o1,
+                                                 DETMON_QC_LIN_COEF_C));
             cpl_free(name_o1);
-	         name_o1= NULL;
+            name_o1= NULL;
             skip_if(cpl_propertylist_append_double(linc_qclist, name_o2,
-					   cpl_image_get_stdev(image)));
-    	      skip_if(cpl_propertylist_set_comment(linc_qclist,name_o2,
-						 DETMON_QC_LIN_COEF_ERR_C));
+                                                   cpl_image_get_stdev(image)));
+            skip_if(cpl_propertylist_set_comment(linc_qclist,name_o2,
+                                                 DETMON_QC_LIN_COEF_ERR_C));
             cpl_free(name_o2);
-	         name_o2= NULL;
+            name_o2= NULL;
         }
-	     if(detmon_lg_config.order == vsize - 1) 
+
+
+        if(order == vsize - 1)
         {
-	        cpl_msg_warning(cpl_func, "The fitting is not over-determined.");
-	        skip_if(cpl_propertylist_append_double(linc_qclist,DETMON_QC_ERRFIT,
-						   0.0));
-    	    skip_if(cpl_propertylist_set_comment(linc_qclist,DETMON_QC_ERRFIT,
-						 DETMON_QC_ERRFIT_C));
-	     } else 
+            cpl_msg_warning(cpl_func, "The fitting is not over-determined.");
+            skip_if(cpl_propertylist_append_double(linc_qclist,DETMON_QC_ERRFIT,
+                                                   0.0));
+            skip_if(cpl_propertylist_set_comment(linc_qclist,DETMON_QC_ERRFIT,
+                                                 DETMON_QC_ERRFIT_C));
+        } else
         {
-	        skip_if(cpl_propertylist_append_double(linc_qclist,DETMON_QC_ERRFIT,
-						   cpl_image_get_median(fiterror)));
-    	     skip_if(cpl_propertylist_set_comment(linc_qclist,DETMON_QC_ERRFIT,
-						 DETMON_QC_ERRFIT_C));
-	     }
-   }
+            skip_if(cpl_propertylist_append_double(linc_qclist,DETMON_QC_ERRFIT,
+                                                   cpl_image_get_median(fiterror)));
+            skip_if(cpl_propertylist_set_comment(linc_qclist,DETMON_QC_ERRFIT,
+                                                 DETMON_QC_ERRFIT_C));
+        }
+    } /* end case pix2pix == TRUE */
+
     skip_if(cpl_propertylist_append_double(lint_qclist,DETMON_QC_COUNTS_MIN,
                                            min_val));
     skip_if(cpl_propertylist_set_comment(lint_qclist,DETMON_QC_COUNTS_MIN,
@@ -4911,37 +5707,42 @@ xsh_detmon_lg_reduce_all(const cpl_table * linear_table,
                                            max_val));
     skip_if(cpl_propertylist_set_comment(lint_qclist,DETMON_QC_COUNTS_MAX,
                                          DETMON_QC_COUNTS_MAX_C));
-    skip_if(xsh_detmon_lg_lineff(pcoeffs,lint_qclist,detmon_lg_config.ref_level,
-                                    detmon_lg_config.order));
+    skip_if(xsh_detmon_lg_lineff(pcoeffs,lint_qclist,xsh_detmon_lg_config.ref_level,
+                             xsh_detmon_lg_config.order));
     /* Detection of bad pixels */
-    if (detmon_lg_config.exts >= 0) 
+    if (xsh_detmon_lg_config.exts >= 0)
     {
         cpl_msg_info(cpl_func, "Bad pixel detection");
-    } else 
+    } else
     {
         cpl_msg_info(cpl_func, "Bad pixel detection"
-		     " for extension nb %d", which_ext);
+                     " for extension nb %d", which_ext);
     }
-    if(detmon_lg_config.pix2pix) 
+    if(xsh_detmon_lg_config.pix2pix)
     {
-       *bpms_ptr = xsh_detmon_bpixs(*coeffs_ptr, detmon_lg_config.bpmbin,
-                                       detmon_lg_config.kappa, &nbpixs);
-	     skip_if(*bpms_ptr == NULL);
+
+        /* Determines bad pixel map */
+        nbpixs = xsh_detmon_compute_badpixmap(opt_nir, linear_nsets, linear_table,
+                        linearity_inputs, nbpixs, x,gaint_qclist, bpms_ptr);
+        /* we still have to unwrapp x & y that we kept for bpixs2 function */ 
     }
+
+
     skip_if(cpl_propertylist_append_int(bpm_qclist, DETMON_QC_NUM_BPM, nbpixs));
     skip_if(cpl_propertylist_set_comment(bpm_qclist, DETMON_QC_NUM_BPM,
                                          DETMON_QC_NUM_BPM_C));
-    if(detmon_lg_config.lamp_stability != 0.0) 
+    cpl_msg_info(cpl_func,"stability=%g",xsh_detmon_lg_config.lamp_stability);
+    if(xsh_detmon_lg_config.lamp_stability != 0.0)
     {
-	     skip_if(cpl_propertylist_append_double(lint_qclist, DETMON_QC_LAMP_STAB,
-					       detmon_lg_config.lamp_stability));
-	     skip_if(cpl_propertylist_set_comment(lint_qclist, DETMON_QC_LAMP_STAB,
-					     DETMON_QC_LAMP_STAB_C));
+        skip_if(cpl_propertylist_append_double(lint_qclist, DETMON_QC_LAMP_STAB,
+                                               xsh_detmon_lg_config.lamp_stability));
+        skip_if(cpl_propertylist_set_comment(lint_qclist, DETMON_QC_LAMP_STAB,
+                                             DETMON_QC_LAMP_STAB_C));
     }
     /* Fit COEFFS_CUBE and BPM outputs to whole-chip size images (DFS05711) */
-    if (!detmon_lg_config.wholechip && detmon_lg_config.pix2pix) 
+    if (!xsh_detmon_lg_config.wholechip && xsh_detmon_lg_config.pix2pix)
     {
-       xsh_detmon_lg_fits_coeffs_and_bpm2chip(coeffs_ptr,bpms_ptr);
+        xsh_detmon_lg_fits_coeffs_and_bpm2chip(coeffs_ptr,bpms_ptr);
     }
     end_skip;
 
@@ -4951,6 +5752,8 @@ xsh_detmon_lg_reduce_all(const cpl_table * linear_table,
     cpl_image_delete(fiterror);
     cpl_polynomial_delete(poly_linfit);
 
+
+
     return cpl_error_get_code();
 }
 
@@ -4965,36 +5768,45 @@ xsh_detmon_lg_reduce_all(const cpl_table * linear_table,
 /*---------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_lg_lineff(double * pcoeffs,
-                        cpl_propertylist * qclist,
-                        int ref_level,
-                        int order)
+                 cpl_propertylist * qclist,
+                 int ref_level,
+                 int order)
 {
     double           lineff = 0;
     double           root = 0;
-    cpl_polynomial * poly = cpl_polynomial_new(1);
+    double residual, slope;
     int i;
+    cpl_size deg=0;
+    cpl_polynomial * poly = cpl_polynomial_new(1);
 
-    double residual, slope;
 
     /*
      * Construction of the polynomial F_m(F_r) from F_m(t),
      * using F_r = a_1 * t.
      */
+    /*
+       for (deg = 0; deg <= order; deg++) {
+       cpl_msg_info(cpl_func,"coef[%d]=%g",deg,pcoeffs[deg]);
+       }
+       */
+
+
     pcoeffs[0] -= ref_level;
 
     for (i = 2; i <= order; i++)
     {
-    	int j;
-    	for(j = 0; j < i; j++)
-    	{
-    		pcoeffs[i] /= pcoeffs[1];
-    	}
+        int j;
+        for(j = 0; j < i; j++)
+        {
+            pcoeffs[i] /= pcoeffs[1];
+        }
     }
 
     pcoeffs[1] = 1;
-    cpl_size deg=0;
+
     for (deg = 0; deg <= order; deg++) {
-	skip_if(cpl_polynomial_set_coeff(poly, &deg, pcoeffs[deg]));
+        /*cpl_msg_info(cpl_func,"coef[%d]=%g",deg,pcoeffs[deg]);*/
+        skip_if(cpl_polynomial_set_coeff(poly, &deg, pcoeffs[deg]));
     }
 
     /*
@@ -5006,38 +5818,43 @@ xsh_detmon_lg_lineff(double * pcoeffs,
     residual = cpl_polynomial_eval_1d(poly, 0.0, &slope);
 
     if (slope <= 0.0 && residual >= 0.0) {
-	cpl_msg_warning(cpl_func, "Reference level (--ref_level) outside"
-			" linearity range of the detector. Cannot compute"
-			" linearity efficiency (QC.LINEFF).");
-	lineff = -1;
+        cpl_msg_warning(cpl_func, "Reference level (--ref_level) outside"
+                        " linearity range of the detector. Cannot compute"
+                        " linearity efficiency (QC.LINEFF).");
+        lineff = -1;
     }
     else
     {
-    	cpl_error_code err = cpl_polynomial_solve_1d(poly, 0.0, &root, 1);
-    	if (err == CPL_ERROR_NONE)
-    	{
-    		lineff = (root - ref_level) / ref_level;
-    	}
-    	else
-    	{
-    		cpl_error_reset();
-    		cpl_msg_warning(cpl_func,
-    				"Cannot compute linearity efficiency (QC.LINEFF)"
-    				"for the current combination "
-    				" of (--ref-level equal %d) and (--order equal %d) parameters. Try "
-    				"to decrease (--ref-level) value.", ref_level, order);
-    	}
+        cpl_error_code err = cpl_polynomial_solve_1d(poly, 0.0, &root, 1);
+        /*
+           cpl_msg_info(cpl_func,"root=%g ref_level=%d lin_eff=%d",
+           root,ref_level,ref_level);
+           */
+        if (err == CPL_ERROR_NONE)
+        {
+
+            lineff = (root - ref_level) / ref_level;
+        }
+        else
+        {
+            cpl_error_reset();
+            cpl_msg_warning(cpl_func,
+                            "Cannot compute linearity efficiency (QC.LINEFF)"
+                            "for the current combination "
+                            " of (--ref-level equal %d) and (--order equal %d) parameters. Try "
+                            "to decrease (--ref-level) value.", ref_level, order);
+        }
     }
     cpl_msg_warning(cpl_func, "DETMON_QC_LIN_EFF=%f",lineff );
     skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_LIN_EFF,
-					   lineff));
+                                           lineff));
     skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_LIN_EFF,
-					 DETMON_QC_LIN_EFF_C));
+                                         DETMON_QC_LIN_EFF_C));
 
     skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_LIN_EFF_FLUX,
-					   ref_level));
+                                           ref_level));
     skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_LIN_EFF_FLUX,
-					 DETMON_QC_LIN_EFF_FLUX_C));
+                                         DETMON_QC_LIN_EFF_FLUX_C));
 
     end_skip;
 
@@ -5056,7 +5873,7 @@ xsh_detmon_lg_lineff(double * pcoeffs,
 /*---------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_lg_qc_ptc(const cpl_table  * gain_table,
-			cpl_propertylist * qclist, unsigned mode, int rows_in_gain)
+                 cpl_propertylist * qclist, unsigned mode, int rows_in_gain)
 {
     double                  mse = 0;
     cpl_polynomial         *poly_fit = NULL;
@@ -5077,18 +5894,18 @@ xsh_detmon_lg_qc_ptc(const cpl_table  * gain_table,
     y = cpl_vector_wrap(nsets, (double *)cpl_table_get_data_double_const(gain_table, "Y_FIT"));
 
     skip_if(x == NULL || y == NULL);
-   if (0 == xsh_detmon_lg_check_before_gain(x, y))
-   {
-      if (x)
-      {
-         cpl_vector_unwrap(x);
-      }
-      if (y)
-      {
-         cpl_vector_unwrap(y);
-      }   
-      return CPL_ERROR_NONE;
-   }
+    if (0 == xsh_detmon_lg_check_before_gain(x, y))
+    {
+        if (x)
+        {
+            cpl_vector_unwrap(x);
+        }
+        if (y)
+        {
+            cpl_vector_unwrap(y);
+        }   
+        return CPL_ERROR_NONE;
+    }
     /*it is not really a MSE, but chi square of the fit, see cpl_vector_fill_polynomial_fit_residual for details*/
     poly_fit = irplib_polynomial_fit_1d_create_chiq(x, y, 1, &mse);
     skip_if(poly_fit == NULL);
@@ -5100,80 +5917,80 @@ xsh_detmon_lg_qc_ptc(const cpl_table  * gain_table,
     skip_if (!cpl_errorstate_is_equal(prestate) || coef==0);
     skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_CONAD, coef));
     skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_CONAD,
-					 DETMON_QC_CONAD_C));
-   if (coef != 0)
-   {
-      skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_GAIN,
-    				   1 / coef));
-      skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_GAIN,
-					 DETMON_QC_GAIN_C));
+                                         DETMON_QC_CONAD_C));
+    if (coef != 0)
+    {
+        skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_GAIN,
+                                               1 / coef));
+        skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_GAIN,
+                                             DETMON_QC_GAIN_C));
     }          
-/*  MSE is removed - see DFS07358 for details
-    skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_GAIN_MSE, mse));
-    skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_GAIN_MSE,
-					 DETMON_QC_GAIN_MSE_C));
-					 */
+    /*  MSE is removed - see DFS07358 for details
+        skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_GAIN_MSE, mse));
+        skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_GAIN_MSE,
+        DETMON_QC_GAIN_MSE_C));
+        */
     i = 0;
-/* QC.RON computation is disabled, see DFS05852 for details*/
-
-/* *     skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_RON,
-					   cpl_polynomial_get_coeff(poly_fit, &i)));
-    skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_RON,
-					 DETMON_QC_RON_C));
-*/
-   if(mode & IRPLIB_GAIN_WITH_AUTOCORR){
-   const cpl_vector             *x2 =
-      cpl_vector_wrap(nsets, (double *)cpl_table_get_data_double_const(gain_table, "X_FIT_CORR"));
-   const cpl_vector             *y2 =
-      cpl_vector_wrap(nsets, (double *)cpl_table_get_data_double_const(gain_table, "Y_FIT"));
-
-	if(x2 == NULL || y2 == NULL) {
-	    cpl_vector_unwrap((cpl_vector *)x2);
-	    cpl_vector_unwrap((cpl_vector *)y2);
-	    /*
-	     * As x and y are const vectors, if they would be defined at the
-	     * beginning of the function (required for skip_if - end_skip
-	     * scheme), they couldn't be initialised to NULL (required too).
-	     * Therefore, they are considered apart from the scheme.
-	     */
-	    skip_if(1);
-	}
+    /* QC.RON computation is disabled, see DFS05852 for details*/
+
+    /* *     skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_RON,
+       cpl_polynomial_get_coeff(poly_fit, &i)));
+       skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_RON,
+       DETMON_QC_RON_C));
+       */
+    if(mode & IRPLIB_GAIN_WITH_AUTOCORR){
+        const cpl_vector             *x2 =
+            cpl_vector_wrap(nsets, (double *)cpl_table_get_data_double_const(gain_table, "X_FIT_CORR"));
+        const cpl_vector             *y2 =
+            cpl_vector_wrap(nsets, (double *)cpl_table_get_data_double_const(gain_table, "Y_FIT"));
+
+        if(x2 == NULL || y2 == NULL) {
+            cpl_vector_unwrap((cpl_vector *)x2);
+            cpl_vector_unwrap((cpl_vector *)y2);
+            /*
+             * As x and y are const vectors, if they would be defined at the
+             * beginning of the function (required for skip_if - end_skip
+             * scheme), they couldn't be initialised to NULL (required too).
+             * Therefore, they are considered apart from the scheme.
+             */
+            skip_if(1);
+        }
 
-	/* Revise mse, maybe used afterwards */
-	poly_fit2 = irplib_polynomial_fit_1d_create(x2, y2, 1, &mse);
-	if(poly_fit2 == NULL) {
-	    cpl_vector_unwrap((cpl_vector *)x2);
-	    cpl_vector_unwrap((cpl_vector *)y2);
+        /* Revise mse, maybe used afterwards */
+        poly_fit2 = irplib_polynomial_fit_1d_create(x2, y2, 1, &mse);
+        if(poly_fit2 == NULL) {
+            cpl_vector_unwrap((cpl_vector *)x2);
+            cpl_vector_unwrap((cpl_vector *)y2);
 
-	    cpl_msg_error(cpl_func, "Error during polynomial fit, err[%s]", cpl_error_get_where());
-	    /* See comment in previous error checking if() statement */
-	    skip_if(1);
-	}
-	skip_if(cpl_error_get_code() != CPL_ERROR_NONE);
-	cpl_vector_unwrap((cpl_vector *)x2);
-	cpl_vector_unwrap((cpl_vector *)y2);
-	skip_if(cpl_error_get_code() != CPL_ERROR_NONE);
-	/* Write the QC params corresponding to the fitting of the GAIN */
-	i = 1;
-	prestate = cpl_errorstate_get();
-	coef = cpl_polynomial_get_coeff(poly_fit2, &i);
-	skip_if(cpl_error_get_code() != CPL_ERROR_NONE);
-	skip_if (!cpl_errorstate_is_equal(prestate) || coef == 0);
-
-	skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_CONAD_CORR,
-					       coef));
-	skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_CONAD_CORR,
-					     DETMON_QC_CONAD_CORR_C));
-
-	skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_GAIN_CORR,
-					       1 / coef));
-	skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_GAIN_CORR,
-					     DETMON_QC_GAIN_CORR_C));
+            cpl_msg_error(cpl_func, "Error during polynomial fit, err[%s]", cpl_error_get_where());
+            /* See comment in previous error checking if() statement */
+            skip_if(1);
+        }
+        skip_if(cpl_error_get_code() != CPL_ERROR_NONE);
+        cpl_vector_unwrap((cpl_vector *)x2);
+        cpl_vector_unwrap((cpl_vector *)y2);
+        skip_if(cpl_error_get_code() != CPL_ERROR_NONE);
+        /* Write the QC params corresponding to the fitting of the GAIN */
+        i = 1;
+        prestate = cpl_errorstate_get();
+        coef = cpl_polynomial_get_coeff(poly_fit2, &i);
+        skip_if(cpl_error_get_code() != CPL_ERROR_NONE);
+        skip_if (!cpl_errorstate_is_equal(prestate) || coef == 0);
+
+        skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_CONAD_CORR,
+                                               coef));
+        skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_CONAD_CORR,
+                                             DETMON_QC_CONAD_CORR_C));
+
+        skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_GAIN_CORR,
+                                               1 / coef));
+        skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_GAIN_CORR,
+                                             DETMON_QC_GAIN_CORR_C));
     }
 
     end_skip;
 
-   /*cleanup*/
+    /*cleanup*/
     cpl_vector_unwrap(x);
     cpl_vector_unwrap(y);
     cpl_polynomial_delete(poly_fit);
@@ -5190,23 +6007,23 @@ xsh_detmon_lg_qc_ptc(const cpl_table  * gain_table,
  */
 static int xsh_detmon_lg_check_before_gain(const cpl_vector* x, const cpl_vector* y)
 {
-   const double TOLERANCE = 1e-37;/*MINDOUBLE is not everywhere defined (Mac);*/
-   double xmin = cpl_vector_get_min(x);
-   double xmax = cpl_vector_get_max(x);
-   double ymin = cpl_vector_get_min(y);
-   double ymax = cpl_vector_get_max(y);
-   double ystdev = cpl_vector_get_stdev(y);
-   double xstdev = cpl_vector_get_stdev(x);   
-   int retval = 1;
-   if (fabs(xmax-xmin) < TOLERANCE && 
-       fabs(ymax - ymin) < TOLERANCE &&
-       xstdev < TOLERANCE &&
-       ystdev < TOLERANCE)
-   {
-      cpl_msg_warning(cpl_func, "An empty frame has been detected, linearity, coeffs, gain, FPN values will not be computed.");
-      retval = 0;
-   }
-   return retval;
+    const double TOLERANCE = 1e-37;/*MINDOUBLE is not everywhere defined (Mac);*/
+    double xmin = cpl_vector_get_min(x);
+    double xmax = cpl_vector_get_max(x);
+    double ymin = cpl_vector_get_min(y);
+    double ymax = cpl_vector_get_max(y);
+    double ystdev = cpl_vector_get_stdev(y);
+    double xstdev = cpl_vector_get_stdev(x);   
+    int retval = 1;
+    if (fabs(xmax-xmin) < TOLERANCE && 
+        fabs(ymax - ymin) < TOLERANCE &&
+        xstdev < TOLERANCE &&
+        ystdev < TOLERANCE)
+    {
+        cpl_msg_warning(cpl_func, "An empty frame has been detected, linearity, coeffs, gain, FPN values will not be computed.");
+        retval = 0;
+    }
+    return retval;
 }
 /*---------------------------------------------------------------------------*/
 /**
@@ -5220,62 +6037,61 @@ static int xsh_detmon_lg_check_before_gain(const cpl_vector* x, const cpl_vector
 /*---------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_lg_qc_med(const cpl_table * gain_table,
-			    cpl_propertylist * qclist, int rows_in_gain)
+                 cpl_propertylist * qclist, int rows_in_gain)
 {
 
-   double gain=0;
-   //int q_STUB; /* dummy variable to remove warning "unused var" */
-   cpl_vector             *x = NULL;
-   cpl_vector             *y = NULL;   
-   int check_result = 0;
-   
-   //q_STUB = rows_in_gain;
-   
+    double gain=0;
+    cpl_vector             *x = NULL;
+    cpl_vector             *y = NULL;   
+    int check_result = 0;
+
+    if (rows_in_gain) {/* silence unused var */};
+
     x = cpl_vector_wrap(rows_in_gain, (double *)cpl_table_get_data_double_const(gain_table, "X_FIT"));
     y = cpl_vector_wrap(rows_in_gain, (double *)cpl_table_get_data_double_const(gain_table, "Y_FIT"));
     check_result = xsh_detmon_lg_check_before_gain(x, y);
-   if (x)
-   {
-      cpl_vector_unwrap(x);
-   }
-   if (y)
-   {
-      cpl_vector_unwrap(y);
-   }   
-   if (0 == check_result)
-   {
-      return CPL_ERROR_NONE;
-   }
+    if (x)
+    {
+        cpl_vector_unwrap(x);
+    }
+    if (y)
+    {
+        cpl_vector_unwrap(y);
+    }   
+    if (0 == check_result)
+    {
+        return CPL_ERROR_NONE;
+    }
 
-   gain=cpl_table_get_column_median(gain_table, "GAIN");
+    gain=cpl_table_get_column_median(gain_table, "GAIN");
 
-   skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_GAIN,gain));
+    skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_GAIN,gain));
 
-   skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_GAIN,
-                                        DETMON_QC_GAIN_C));
+    skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_GAIN,
+                                         DETMON_QC_GAIN_C));
 
-   skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_GAIN_MSE,
-                                          cpl_table_get_column_stdev
-                                          (gain_table, "GAIN")));
-   skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_GAIN_MSE,
-                                        DETMON_QC_GAIN_MSE_C));
+    skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_GAIN_MSE,
+                                           cpl_table_get_column_stdev
+                                           (gain_table, "GAIN")));
+    skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_GAIN_MSE,
+                                         DETMON_QC_GAIN_MSE_C));
 
-   skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_CONAD,1./gain));
-   skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_CONAD,
-                                        DETMON_QC_CONAD_C));
+    skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_CONAD,1./gain));
+    skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_CONAD,
+                                         DETMON_QC_CONAD_C));
 
 
-   gain=cpl_table_get_column_median(gain_table, "GAIN_CORR");
+    gain=cpl_table_get_column_median(gain_table, "GAIN_CORR");
 
-   skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_GAIN_CORR,
-                                          gain));
-   skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_GAIN_CORR,
-                                        DETMON_QC_GAIN_CORR_C));
+    skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_GAIN_CORR,
+                                           gain));
+    skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_GAIN_CORR,
+                                         DETMON_QC_GAIN_CORR_C));
 
 
-   skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_CONAD_CORR,1./gain));
-   skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_CONAD_CORR,
-                                        DETMON_QC_CONAD_CORR_C));
+    skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_CONAD_CORR,1./gain));
+    skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_CONAD_CORR,
+                                         DETMON_QC_CONAD_CORR_C));
 
 
     end_skip;
@@ -5297,10 +6113,18 @@ xsh_detmon_lg_qc_med(const cpl_table * gain_table,
 static cpl_error_code
 xsh_detmon_lg_rescale(cpl_imagelist * to_rescale)
 {
-    double                  med1 =
-        cpl_image_get_median(cpl_imagelist_get(to_rescale, 0));
-    double                  med2 =
-        cpl_image_get_median(cpl_imagelist_get(to_rescale, 1));
+    double med1 =
+        cpl_image_get_median_window(cpl_imagelist_get(to_rescale, 0),
+                                    xsh_detmon_lg_config.llx,
+                                    xsh_detmon_lg_config.lly,
+                                    xsh_detmon_lg_config.urx,
+                                    xsh_detmon_lg_config.ury);
+    double med2 =
+        cpl_image_get_median_window(cpl_imagelist_get(to_rescale, 1),
+                                    xsh_detmon_lg_config.llx,
+                                    xsh_detmon_lg_config.lly,
+                                    xsh_detmon_lg_config.urx,
+                                    xsh_detmon_lg_config.ury);
 
     skip_if(0);
 
@@ -5320,54 +6144,55 @@ xsh_detmon_lg_rescale(cpl_imagelist * to_rescale)
 
 static cpl_error_code
 xsh_detmon_pair_extract_next(const cpl_frameset * set,
-                           int* iindex,
-                           int* next_element,
-                           double* dit_array,
-                           cpl_frameset ** pair,
-                                double tolerance) /* detmon_lg_config.tolerance */
+                         int* iindex,
+                         int* next_element,
+                         double* dit_array,
+                         cpl_frameset ** pair,
+                         double tolerance) /* xsh_detmon_lg_config.tolerance */
 {
-	double dit = -100;
-	double dit_next = -100;
-	cpl_size* selection;
-	int nsets_extracted = 0;
+    double dit = -100;
+    double dit_next = -100;
+    cpl_size* selection;
+    int nsets_extracted = 0;
     cpl_ensure_code(set             != NULL, CPL_ERROR_NULL_INPUT);
     cpl_ensure_code(dit_array       != NULL, CPL_ERROR_NULL_INPUT);
     cpl_ensure_code(iindex 			!= NULL, CPL_ERROR_NULL_INPUT);
     cpl_ensure_code(pair            != NULL, CPL_ERROR_NULL_INPUT);
 
-	nsets_extracted = cpl_frameset_get_size(set);
-	selection = cpl_malloc(sizeof(cpl_size) * nsets_extracted);
-	memset(&selection[0], 0, sizeof(cpl_size) * nsets_extracted);
+    nsets_extracted = cpl_frameset_get_size(set);
+    selection = cpl_malloc(sizeof(cpl_size) * nsets_extracted);
+    memset(&selection[0], 0, sizeof(cpl_size) * nsets_extracted);
 
 
-	dit = dit_array[*next_element ];
-/*	cpl_msg_info(cpl_func, "%d: dit %f",*next_element, dit ); */
-	if (*next_element < nsets_extracted - 1)
-	{
-		dit_next = dit_array[*next_element + 1 ];
-                /* cpl_msg_info(cpl_func, "%d: dit %f",*next_element + 1, dit_next ); */
-	}
-	/* one element would be returned always */
-	selection[iindex[*next_element] ] = 1;
-	if (fabs(dit - dit_next) < tolerance)
-	{
-           /* return a second element of the pair */
-		selection[iindex[*next_element + 1] ] = 1;
-		(*next_element)++;
-	}
-	else
-	{
-		cpl_msg_warning(cpl_func, "DIT for the second frame in the pair is above tolerance level - could not be taken, dit1[%f] dit2[%f] next_element: %d ", dit, dit_next, *next_element);
-	}
-	(*next_element)++;
-	/* prepare frameset */
-	cpl_frameset_delete(*pair);
-	*pair = cpl_frameset_extract(set, selection, 1);
+    dit = dit_array[*next_element ];
+    /*	cpl_msg_info(cpl_func, "%d: dit %f",*next_element, dit ); */
+    if (*next_element < nsets_extracted - 1)
+    {
+        dit_next = dit_array[*next_element + 1 ];
+        /* cpl_msg_info(cpl_func, "%d: dit %f",*next_element + 1, dit_next ); */
+    }
+    /* one element would be returned always */
+    selection[iindex[*next_element] ] = 1;
+    if (fabs(dit - dit_next) < tolerance)
+    {
+        /* return a second element of the pair */
+        selection[iindex[*next_element + 1] ] = 1;
+        (*next_element)++;
+    }
+    else
+    {
+        cpl_msg_warning(cpl_func, "DIT for the second frame in the pair is above tolerance level - could not be taken, dit1[%f] dit2[%f] next_element: %d . Check input data set and tolerance value", dit, dit_next, *next_element);
+    }
+    (*next_element)++;
+    /* prepare frameset */
+    cpl_frameset_delete(*pair);
+    *pair = cpl_frameset_extract(set, selection, 1);
 
 
     cpl_free(selection);
     return cpl_error_get_code();
 }
+
 static cpl_error_code
 xsh_detmon_single_extract_next(const cpl_frameset * set,
                            int* iindex,
@@ -5375,7 +6200,6 @@ xsh_detmon_single_extract_next(const cpl_frameset * set,
                            double* dit_array,
                            cpl_frameset ** pair)
 {
-	double dit = -100;
 	cpl_size* selection;
 	int nsets_extracted = 0;
     cpl_ensure_code(set             != NULL, CPL_ERROR_NULL_INPUT);
@@ -5387,8 +6211,6 @@ xsh_detmon_single_extract_next(const cpl_frameset * set,
 	selection = cpl_malloc(sizeof(cpl_size) * nsets_extracted);
 	memset(&selection[0], 0, sizeof(cpl_size) * nsets_extracted);
 
-	nsets_extracted = cpl_frameset_get_size(set);
-	dit = dit_array[iindex[*next_element] ];
 	/* only one element would be returned */
 	selection[iindex[*next_element] ] = 1;
 	(*next_element)++;
@@ -5420,6 +6242,8 @@ xsh_detmon_single_extract_next(const cpl_frameset * set,
   @param    yshift             Shift applied on Y axis (Autocorrelation)
   @param    qclist             QC list
   @param    mode               Possible options (combined with bitwise or)
+                               autocorr true/false, opt/nir, collapse true/false
+                               pix2pix true/false
   @param    diff_imlist        Output Difference imlist or NULL
   @param    autocorr_imlist    Output Autocorr   imlist or NULL
   @return   Pointer to the Gain Table or NULL on error
@@ -5494,22 +6318,22 @@ xsh_detmon_single_extract_next(const cpl_frameset * set,
 
 cpl_table *
 xsh_detmon_gain(const cpl_imagelist  * imlist_on,
-		   const cpl_imagelist  * imlist_off,
-		   const cpl_vector     * exptimes,
-		   const cpl_vector     * ndit,
-		   double                 tolerance,
-		   int                    llx,
-		   int                    lly,
-		   int                    urx,
-		   int                    ury,
-                   double                 kappa,
-                   int                    nclip,
-                   int                    xshift,
-                   int                    yshift,
-		   cpl_propertylist     * qclist,
-		   unsigned               mode,
-		   cpl_imagelist       ** diff_imlist,
-		   cpl_imagelist       ** autocorr_imlist)
+            const cpl_imagelist  * imlist_off,
+            const cpl_vector     * exptimes,
+            const cpl_vector     * ndit,
+            double                 tolerance,
+            int                    llx,
+            int                    lly,
+            int                    urx,
+            int                    ury,
+            double                 kappa,
+            int                    nclip,
+            int                    xshift,
+            int                    yshift,
+            cpl_propertylist     * qclist,
+            unsigned               mode,
+            cpl_imagelist       ** diff_imlist,
+            cpl_imagelist       ** autocorr_imlist)
 {
     cpl_table     * gain_table   = NULL;
     cpl_imagelist * difflist     = NULL;
@@ -5535,21 +6359,22 @@ xsh_detmon_gain(const cpl_imagelist  * imlist_on,
 
 
     /* Search for different EXPTIME values */
-    skip_if(xsh_detmon_lg_find_dits_ndits(exptimes, ndit,tolerance,&diffdits,&diffndits));
+    skip_if(xsh_detmon_lg_find_dits_ndits(exptimes, ndit,tolerance,&diffdits,
+                                      &diffndits));
     ndiffdits = cpl_vector_get_size(diffdits);
 
     ndits     = cpl_vector_get_size(exptimes);
 
     /* AUTOCORR processing requires both. They will become outputs later. */
     if (mode & IRPLIB_GAIN_WITH_AUTOCORR && (diff_imlist || autocorr_imlist)) {
-	difflist     = cpl_imagelist_new();
-	autocorrlist = cpl_imagelist_new();
+        difflist     = cpl_imagelist_new();
+        autocorrlist = cpl_imagelist_new();
     }
 
     if (mode & IRPLIB_GAIN_COLLAPSE) {
         if (mode & IRPLIB_GAIN_WITH_RESCALE) {
-  	    c_offlist = cpl_imagelist_duplicate(imlist_off);
-	    skip_if(xsh_detmon_lg_rescale(c_offlist));
+            c_offlist = cpl_imagelist_duplicate(imlist_off);
+            skip_if(xsh_detmon_lg_rescale(c_offlist));
         } else {
             c_offlist = (cpl_imagelist *) imlist_off;
         }
@@ -5560,26 +6385,26 @@ xsh_detmon_gain(const cpl_imagelist  * imlist_on,
         int c_nons;
         int c_noffs = 0; /* False (uninit) warning */
 
-	double c_dit = 0;
-	int c_ndit = 1;
+        double c_dit = 0;
+        int c_ndit = 1;
 
         c_dit=cpl_vector_get(diffdits, i);
 
-	if(opt_nir) {
-	  c_ndit=(int)cpl_vector_get(diffndits, i);
-	}
+        if(opt_nir) {
+            c_ndit=(int)cpl_vector_get(diffndits, i);
+        }
 
-	c_onlist  = cpl_imagelist_new();
-	c_nons = 0;
+        c_onlist  = cpl_imagelist_new();
+        c_nons = 0;
 
-	if (mode & IRPLIB_GAIN_NO_COLLAPSE) {
-	    c_offlist = cpl_imagelist_new();
-	    c_noffs = 0;
-	}
+        if (mode & IRPLIB_GAIN_NO_COLLAPSE) {
+            c_offlist = cpl_imagelist_new();
+            c_noffs = 0;
+        }
 
-	/* Extraction of images of EXPTIME i */
-	for(j = 0; j < ndits; j++) {
-	    if (fabs(c_dit - cpl_vector_get(exptimes, j)) <= tolerance) {
+        /* Extraction of images of EXPTIME i */
+        for(j = 0; j < ndits; j++) {
+            if (fabs(c_dit - cpl_vector_get(exptimes, j)) <= tolerance) {
                 /*
                  * First we get the corresponding image from the ON imlist.
                  * The option IRPLIB_GAIN_WITH_RESCALE requires to modify
@@ -5603,98 +6428,98 @@ xsh_detmon_gain(const cpl_imagelist  * imlist_on,
                  * Same explanation as above but for OFF imlist.
                  * Only necessary when IRPLIB_GAIN_NO_COLLAPSE required.
                  */
-		if (mode & IRPLIB_GAIN_NO_COLLAPSE) {
+                if (mode & IRPLIB_GAIN_NO_COLLAPSE) {
                     cpl_image * im_off;
                     if (mode & IRPLIB_GAIN_WITH_RESCALE) {
                         const cpl_image * im =
-                          cpl_imagelist_get_const(imlist_off, j);
+                            cpl_imagelist_get_const(imlist_off, j);
                         im_off = cpl_image_duplicate(im);
                     } else {
                         im_off =
-                          (cpl_image *) cpl_imagelist_get_const(imlist_off, j);
+                            (cpl_image *) cpl_imagelist_get_const(imlist_off, j);
                     }
-		    skip_if(cpl_imagelist_set(c_offlist, im_off, c_noffs));
-		    c_noffs++;
-		}
-	    }
-	}
+                    skip_if(cpl_imagelist_set(c_offlist, im_off, c_noffs));
+                    c_noffs++;
+                }
+            }
+        }
 
-	/* If NO_COLLAPSE, must be the same number of images! */
-	if (mode & IRPLIB_GAIN_NO_COLLAPSE)
-	    skip_if (c_nons != c_noffs);
+        /* If NO_COLLAPSE, must be the same number of images! */
+        if (mode & IRPLIB_GAIN_NO_COLLAPSE)
+            skip_if (c_nons != c_noffs);
 
-	/* There must be pairs! */
-	skip_if (c_nons == 0 || c_nons % 2 != 0);
+        /* There must be pairs! */
+        skip_if (c_nons == 0 || c_nons % 2 != 0);
 
-	/* Rescaling */
-	if(mode & IRPLIB_GAIN_WITH_RESCALE) {
-	    skip_if(xsh_detmon_lg_rescale(c_onlist));
-	    if (mode & IRPLIB_GAIN_NO_COLLAPSE)
-		skip_if(xsh_detmon_lg_rescale(c_offlist));
-	}
+        /* Rescaling */
+        if(mode & IRPLIB_GAIN_WITH_RESCALE) {
+            skip_if(xsh_detmon_lg_rescale(c_onlist));
+            if (mode & IRPLIB_GAIN_NO_COLLAPSE)
+                skip_if(xsh_detmon_lg_rescale(c_offlist));
+        }
 
-	/* The following loop is necessary for the case of multiple pairs
-	   of same EXPTIME values */
-	while(c_nons > 0) {
-		int rows_affected = 1;
-		skip_if(xsh_detmon_gain_table_fill_row(gain_table,
-							  c_dit,c_ndit,
-						      autocorrlist,
-						      difflist, c_onlist,
-						      c_offlist, kappa, nclip,
-                                                      llx, lly, urx, ury,
-                                                      xshift, yshift,1E10,  i,
-mode, &rows_affected));
-		if (rows_affected)
-		{
-			rows_in_gain++;
-		}
+        /* The following loop is necessary for the case of multiple pairs
+           of same EXPTIME values */
+        while(c_nons > 0) {
+            int rows_affected = 1;
+            skip_if(xsh_detmon_gain_table_fill_row(gain_table,
+                                               c_dit,c_ndit,
+                                               autocorrlist,
+                                               difflist, c_onlist,
+                                               c_offlist, kappa, nclip,
+                                               llx, lly, urx, ury,
+                                               xshift, yshift,1E10,  1E10, i,
+                                               mode, &rows_affected));
+            if (rows_affected)
+            {
+                rows_in_gain++;
+            }
             if (mode & IRPLIB_GAIN_WITH_RESCALE) {
                 cpl_image_delete(cpl_imagelist_unset(c_onlist, 0));
                 cpl_image_delete(cpl_imagelist_unset(c_onlist, 0));
                 if (mode & IRPLIB_GAIN_NO_COLLAPSE) {
-                  cpl_image_delete(cpl_imagelist_unset(c_offlist, 0));
-                  cpl_image_delete(cpl_imagelist_unset(c_offlist, 0));
+                    cpl_image_delete(cpl_imagelist_unset(c_offlist, 0));
+                    cpl_image_delete(cpl_imagelist_unset(c_offlist, 0));
                 }
             } else {
-	        cpl_imagelist_unset(c_onlist, 0);
+                cpl_imagelist_unset(c_onlist, 0);
                 skip_if(0);
                 cpl_imagelist_unset(c_onlist, 0);
                 skip_if(0);
                 if (mode & IRPLIB_GAIN_NO_COLLAPSE) {
-                  cpl_imagelist_unset(c_offlist, 0);
-                  skip_if(0);
-                  cpl_imagelist_unset(c_offlist, 0);
-                  skip_if(0);
+                    cpl_imagelist_unset(c_offlist, 0);
+                    skip_if(0);
+                    cpl_imagelist_unset(c_offlist, 0);
+                    skip_if(0);
                 }
             }
             skip_if(0);
-	    c_nons -= 2;
-	}
+            c_nons -= 2;
+        }
 
-	cpl_imagelist_delete(c_onlist);
-	if (mode & IRPLIB_GAIN_NO_COLLAPSE) {
-          cpl_imagelist_delete(c_offlist);
-	}
+        cpl_imagelist_delete(c_onlist);
+        if (mode & IRPLIB_GAIN_NO_COLLAPSE) {
+            cpl_imagelist_delete(c_offlist);
+        }
     }
 
     skip_if(cpl_propertylist_append_string(qclist, DETMON_QC_METHOD, method));
     skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_METHOD,
-					 DETMON_QC_METHOD_C));
+                                         DETMON_QC_METHOD_C));
 
     /* Computation of GAIN via polynomial fit */
     if (mode & IRPLIB_GAIN_PTC) {
-      skip_if(xsh_detmon_lg_qc_ptc(gain_table, qclist, mode, rows_in_gain));
+        skip_if(xsh_detmon_lg_qc_ptc(gain_table, qclist, mode, rows_in_gain));
     } else {
-	skip_if(xsh_detmon_lg_qc_med(gain_table, qclist, rows_in_gain));
+        skip_if(xsh_detmon_lg_qc_med(gain_table, qclist, rows_in_gain));
     }
 
     if(mode & IRPLIB_GAIN_WITH_AUTOCORR) {
         double autocorr = cpl_table_get_column_median(gain_table, "AUTOCORR");
-	skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_AUTOCORR,
-					       autocorr));
-	skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_AUTOCORR,
-					     DETMON_QC_AUTOCORR_C));
+        skip_if(cpl_propertylist_append_double(qclist, DETMON_QC_AUTOCORR,
+                                               autocorr));
+        skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_AUTOCORR,
+                                             DETMON_QC_AUTOCORR_C));
     }
 
     if (diff_imlist != NULL) *diff_imlist = difflist;
@@ -5710,13 +6535,13 @@ mode, &rows_affected));
 
 static cpl_error_code
 xsh_detmon_gain_table_create(cpl_table * gain_table,
-                                const cpl_boolean opt_nir)
+                         const cpl_boolean opt_nir)
 {
     if (opt_nir == NIR) {
-	skip_if(cpl_table_new_column(gain_table, "DIT",     CPL_TYPE_DOUBLE));
-	skip_if(cpl_table_new_column(gain_table, "NDIT",     CPL_TYPE_INT));
+        skip_if(cpl_table_new_column(gain_table, "DIT",     CPL_TYPE_DOUBLE));
+        skip_if(cpl_table_new_column(gain_table, "NDIT",     CPL_TYPE_INT));
     } else { /* OPT */
-	skip_if(cpl_table_new_column(gain_table, "EXPTIME", CPL_TYPE_DOUBLE));
+        skip_if(cpl_table_new_column(gain_table, "EXPTIME", CPL_TYPE_DOUBLE));
     }
     skip_if(cpl_table_new_column(gain_table, "MEAN_ON1",    CPL_TYPE_DOUBLE));
     skip_if(cpl_table_new_column(gain_table, "MEAN_ON2",    CPL_TYPE_DOUBLE));
@@ -5741,12 +6566,12 @@ xsh_detmon_gain_table_create(cpl_table * gain_table,
 
 static cpl_error_code
 xsh_detmon_lin_table_create(cpl_table * lin_table,
-                               const cpl_boolean opt_nir)
+                        const cpl_boolean opt_nir)
 {
     if (opt_nir == NIR) {
-	skip_if(cpl_table_new_column(lin_table, "DIT",     CPL_TYPE_DOUBLE));
+        skip_if(cpl_table_new_column(lin_table, "DIT",     CPL_TYPE_DOUBLE));
     } else { /* OPT */
-	skip_if(cpl_table_new_column(lin_table, "EXPTIME", CPL_TYPE_DOUBLE));
+        skip_if(cpl_table_new_column(lin_table, "EXPTIME", CPL_TYPE_DOUBLE));
     }
     skip_if(cpl_table_new_column(lin_table, "MED",      CPL_TYPE_DOUBLE));
     skip_if(cpl_table_new_column(lin_table, "MEAN",     CPL_TYPE_DOUBLE));
@@ -5760,7 +6585,7 @@ xsh_detmon_lin_table_create(cpl_table * lin_table,
 
 static cpl_vector *
 xsh_detmon_lg_find_dits(const cpl_vector * exptimes,
-                           double             tolerance)
+                    double             tolerance)
 {
     cpl_vector * dits  = cpl_vector_new(cpl_vector_get_size(exptimes) / 2);
     int          ndits = 0;
@@ -5773,15 +6598,15 @@ xsh_detmon_lg_find_dits(const cpl_vector * exptimes,
 
     /* Search for all different EXPTIMEs */
     for(i = 1; i < cpl_vector_get_size(exptimes); i++) {
-      int ndiffs = 0;
-	for (j = 0; j < ndits; j++) {
-	    if (fabs(cpl_vector_get(exptimes, i) -
-		     cpl_vector_get(dits,     j)) > tolerance)
-              ndiffs++;
-	}
+        int ndiffs = 0;
+        for (j = 0; j < ndits; j++) {
+            if (fabs(cpl_vector_get(exptimes, i) -
+                     cpl_vector_get(dits,     j)) > tolerance)
+                ndiffs++;
+        }
         if(ndiffs == ndits) {
-          cpl_vector_set(dits, ndits, cpl_vector_get(exptimes, i));
-          ndits++;
+            cpl_vector_set(dits, ndits, cpl_vector_get(exptimes, i));
+            ndits++;
         }
     }
 
@@ -5795,10 +6620,10 @@ xsh_detmon_lg_find_dits(const cpl_vector * exptimes,
 
 static cpl_error_code
 xsh_detmon_lg_find_dits_ndits(const cpl_vector * exptimes,
-			   const cpl_vector * vec_ndits,
-                           double             tolerance,
-                           cpl_vector** diff_dits,
-			   cpl_vector** diff_ndits)
+                          const cpl_vector * vec_ndits,
+                          double             tolerance,
+                          cpl_vector** diff_dits,
+                          cpl_vector** diff_ndits)
 {
     int          ndits = 0;
 
@@ -5817,16 +6642,16 @@ xsh_detmon_lg_find_dits_ndits(const cpl_vector * exptimes,
     size=cpl_vector_get_size(exptimes);
     /* Search for all different EXPTIMEs */
     for(i = 1; i < size; i++) {
-      int ndiffs = 0;
-	for (j = 0; j < ndits; j++) {
-	    if (fabs(cpl_vector_get(exptimes, i) -
-		     cpl_vector_get(*diff_dits,j)) > tolerance)
-              ndiffs++;
-	}
+        int ndiffs = 0;
+        for (j = 0; j < ndits; j++) {
+            if (fabs(cpl_vector_get(exptimes, i) -
+                     cpl_vector_get(*diff_dits,j)) > tolerance)
+                ndiffs++;
+        }
         if(ndiffs == ndits) {
-          cpl_vector_set(*diff_dits, ndits, cpl_vector_get(exptimes, i));
-          cpl_vector_set(*diff_ndits, ndits, cpl_vector_get(vec_ndits, i));
-          ndits++;
+            cpl_vector_set(*diff_dits, ndits, cpl_vector_get(exptimes, i));
+            cpl_vector_set(*diff_ndits, ndits, cpl_vector_get(vec_ndits, i));
+            ndits++;
         }
     }
 
@@ -5858,6 +6683,8 @@ xsh_detmon_lg_find_dits_ndits(const cpl_vector * exptimes,
 
   @param    qclist             QC list
   @param    mode               Possible options (combined with bitwise or)
+                               autocorr true/false, opt/nir, collapse true/false
+                               pix2pix true/false
   @param    coeffs_cube        Output Coefficients Cube
                                (only if IRPLIB_LIN_PIX2PIX)
   @param    bpm                Bad pixel map (only if IRPLIB_LIN_PIX2PIX)
@@ -5923,21 +6750,21 @@ xsh_detmon_lg_find_dits_ndits(const cpl_vector * exptimes,
 
 cpl_table *
 xsh_detmon_lin(const cpl_imagelist  * imlist_on,
-		  const cpl_imagelist  * imlist_off,
-		  const cpl_vector     * exptimes,
-		  double                 tolerance,
-		  int                    llx,
-		  int                    lly,
-		  int                    urx,
-		  int                    ury,
-		  int                    order,
-                  int                    ref_level,
-                  double kappa,
-                  cpl_boolean bpmbin,
-		  cpl_propertylist     * qclist,
-		  unsigned               mode,
-		  cpl_imagelist       ** coeffs_cube,
-		  cpl_image           ** bpm)
+           const cpl_imagelist  * imlist_off,
+           const cpl_vector     * exptimes,
+           double                 tolerance,
+           int                    llx,
+           int                    lly,
+           int                    urx,
+           int                    ury,
+           int                    order,
+           int                    ref_level,
+           double kappa,
+           cpl_boolean bpmbin,
+           cpl_propertylist     * qclist,
+           unsigned               mode,
+           cpl_imagelist       ** coeffs_cube,
+           cpl_image           ** bpm)
 {
     cpl_table     * lin_table    = NULL;
     cpl_imagelist * c_onlist     = NULL;
@@ -5958,6 +6785,7 @@ xsh_detmon_lin(const cpl_imagelist  * imlist_on,
     int sizex = 0;
     int sizey = 0;
 
+    cpl_size deg;
     double vsize = 0;
 
 
@@ -5972,9 +6800,9 @@ xsh_detmon_lin(const cpl_imagelist  * imlist_on,
 
     /* This mode requires optional outputs */
     if (mode & IRPLIB_LIN_PIX2PIX) {
-	lin_inputs = cpl_imagelist_new();
-	cpl_ensure(coeffs_cube != NULL, CPL_ERROR_NULL_INPUT, NULL);
-	cpl_ensure(bpm         != NULL, CPL_ERROR_NULL_INPUT, NULL);
+        cpl_ensure(coeffs_cube != NULL, CPL_ERROR_NULL_INPUT, NULL);
+        cpl_ensure(bpm         != NULL, CPL_ERROR_NULL_INPUT, NULL);
+        lin_inputs = cpl_imagelist_new();
     }
 
     /* Create table with columns */
@@ -5993,39 +6821,39 @@ xsh_detmon_lin(const cpl_imagelist  * imlist_on,
 
 
 
-/* TO BE IMPLEMENTED SIMILARLY TO UPPER LEVEL FUNCTION (search for nskip)
-   if(filter > 0) {
-	double med1 =
-	    cpl_image_get_median_window(cpl_imagelist_get(imlist_on, 0),
-					llx,lly,urx,ury);
-	double med2 =
-           cpl_image_get_median_window(cpl_imagelist_get(imlist_on, 1),
-					llx,lly,urx,ury);
-	if ( med1 > (double)filter ||
-	     med2 > (double)filter) {
-	    follow = CPL_FALSE;
-	    cpl_table_select_row(lin_table, dit_nb);
-            dit_nskip++;
-	    cpl_msg_warning(cpl_func, "Frames of EXPTIME nb %d "
-			    "will not be taken into account for computation "
-			    "as they are above --filter threshold", dit_nb);
-	}
-    }
-*/
+    /* TO BE IMPLEMENTED SIMILARLY TO UPPER LEVEL FUNCTION (search for nskip)
+       if(filter > 0) {
+       double med1 =
+       cpl_image_get_median_window(cpl_imagelist_get(imlist_on, 0),
+       llx,lly,urx,ury);
+       double med2 =
+       cpl_image_get_median_window(cpl_imagelist_get(imlist_on, 1),
+       llx,lly,urx,ury);
+       if ( med1 > (double)filter ||
+       med2 > (double)filter) {
+       follow = CPL_FALSE;
+       cpl_table_select_row(lin_table, dit_nb);
+       dit_nskip++;
+       cpl_msg_warning(cpl_func, "Frames of EXPTIME nb %d "
+       "will not be taken into account for computation "
+       "as they are above --filter threshold", dit_nb);
+       }
+       }
+       */
 
 
 
 
     if (mode & IRPLIB_LIN_COLLAPSE) {
-	/*
-	 * The master bias is required only for
-	 * linearity computation in the OPT domain
-	 */
-	cpl_image * collapse = cpl_imagelist_collapse_create(imlist_off);
-	skip_if(collapse == NULL);
+        /*
+         * The master bias is required only for
+         * linearity computation in the OPT domain
+         */
+        cpl_image * collapse = cpl_imagelist_collapse_create(imlist_off);
+        skip_if(collapse == NULL);
 
-	c_offlist = cpl_imagelist_new();
-	skip_if(cpl_imagelist_set(c_offlist, collapse, 0));
+        c_offlist = cpl_imagelist_new();
+        skip_if(cpl_imagelist_set(c_offlist, collapse, 0));
     }
 
     /* Loop over the different DITs found in EXPTIMEs */
@@ -6033,18 +6861,18 @@ xsh_detmon_lin(const cpl_imagelist  * imlist_on,
         int c_nons;
         int c_noffs = 0; /* False (uninit) warning */
 
-	double c_dit = cpl_vector_get(diffdits, i);
+        double c_dit = cpl_vector_get(diffdits, i);
 
-	c_onlist  = cpl_imagelist_new();
-	c_nons = 0;
+        c_onlist  = cpl_imagelist_new();
+        c_nons = 0;
 
-	if (mode & IRPLIB_LIN_NO_COLLAPSE) {
-	    c_offlist = cpl_imagelist_new();
-	    c_noffs = 0;
-	}
+        if (mode & IRPLIB_LIN_NO_COLLAPSE) {
+            c_offlist = cpl_imagelist_new();
+            c_noffs = 0;
+        }
 
-	for(j = 0; j < ndits; j++) {
-	    if (fabs(c_dit - cpl_vector_get(exptimes, j)) <= tolerance) {
+        for(j = 0; j < ndits; j++) {
+            if (fabs(c_dit - cpl_vector_get(exptimes, j)) <= tolerance) {
                 /*
                  * First we get the corresponding image from the ON imlist.
                  * The option IRPLIB_GAIN_WITH_RESCALE requires to modify
@@ -6068,212 +6896,214 @@ xsh_detmon_lin(const cpl_imagelist  * imlist_on,
                  * Same explanation as above but for OFF imlist.
                  * Only necessary when IRPLIB_GAIN_NO_COLLAPSE required.
                  */
-		if (mode & IRPLIB_LIN_NO_COLLAPSE) {
+                if (mode & IRPLIB_LIN_NO_COLLAPSE) {
                     cpl_image * im_off;
                     if (mode & IRPLIB_LIN_WITH_RESCALE) {
                         const cpl_image * im =
-                          cpl_imagelist_get_const(imlist_off, j);
+                            cpl_imagelist_get_const(imlist_off, j);
                         im_off = cpl_image_duplicate(im);
                     } else {
                         im_off =
-                          (cpl_image *) cpl_imagelist_get_const(imlist_off, j);
+                            (cpl_image *) cpl_imagelist_get_const(imlist_off, j);
                     }
-		    skip_if(cpl_imagelist_set(c_offlist, im_off, c_noffs));
-		    c_noffs++;
-		}
-	    }
-	}
+                    skip_if(cpl_imagelist_set(c_offlist, im_off, c_noffs));
+                    c_noffs++;
+                }
+            }
+        }
 
-	/* If NO_COLLAPSE, must be the same number of images! */
-	if (mode & IRPLIB_LIN_NO_COLLAPSE)
-	    skip_if (c_nons != c_noffs);
+        /* If NO_COLLAPSE, must be the same number of images! */
+        if (mode & IRPLIB_LIN_NO_COLLAPSE)
+            skip_if (c_nons != c_noffs);
 
-	/* There must be pairs! */
-	skip_if (c_nons == 0 || c_nons % 2 != 0);
+        /* There must be pairs! */
+        skip_if (c_nons == 0 || c_nons % 2 != 0);
 
-	/* Rescaling */
-	if(mode & IRPLIB_LIN_WITH_RESCALE) {
-	    skip_if(xsh_detmon_lg_rescale(c_onlist));
-	    if (mode & IRPLIB_LIN_NO_COLLAPSE)
-		skip_if(xsh_detmon_lg_rescale(c_offlist));
-	}
+        /* Rescaling */
+        if(mode & IRPLIB_LIN_WITH_RESCALE) {
+            skip_if(xsh_detmon_lg_rescale(c_onlist));
+            if (mode & IRPLIB_LIN_NO_COLLAPSE)
+                skip_if(xsh_detmon_lg_rescale(c_offlist));
+        }
 
-	/* The following loop is necessary for the case of multiple pairs
-	   of same EXPTIME values */
-	while(c_nons > 0) {
+        /* The following loop is necessary for the case of multiple pairs
+           of same EXPTIME values */
+        while(c_nons > 0) {
 
-	    skip_if(xsh_detmon_lin_table_fill_row(lin_table, c_dit,
-						     lin_inputs,
-						     c_onlist, c_offlist,
-						     llx, lly, urx, ury,
-						     i, 0, mode));
+            skip_if(xsh_detmon_lin_table_fill_row(lin_table, c_dit,
+                                              lin_inputs,
+                                              c_onlist, c_offlist,
+                                              llx, lly, urx, ury,
+                                              i, 0, mode));
 
             if (mode & IRPLIB_LIN_WITH_RESCALE) {
                 cpl_image_delete(cpl_imagelist_unset(c_onlist, 0));
                 cpl_image_delete(cpl_imagelist_unset(c_onlist, 0));
                 if (mode & IRPLIB_LIN_NO_COLLAPSE) {
-                  cpl_image_delete(cpl_imagelist_unset(c_offlist, 0));
-                  cpl_image_delete(cpl_imagelist_unset(c_offlist, 0));
+                    cpl_image_delete(cpl_imagelist_unset(c_offlist, 0));
+                    cpl_image_delete(cpl_imagelist_unset(c_offlist, 0));
                 }
             } else {
-	        cpl_imagelist_unset(c_onlist, 0);
+                cpl_imagelist_unset(c_onlist, 0);
                 skip_if(0);
                 cpl_imagelist_unset(c_onlist, 0);
                 skip_if(0);
                 if (mode & IRPLIB_LIN_NO_COLLAPSE) {
-                  cpl_imagelist_unset(c_offlist, 0);
-                  skip_if(0);
-                  cpl_imagelist_unset(c_offlist, 0);
-                  skip_if(0);
+                    cpl_imagelist_unset(c_offlist, 0);
+                    skip_if(0);
+                    cpl_imagelist_unset(c_offlist, 0);
+                    skip_if(0);
                 }
             }
             skip_if(0);
-	    c_nons -= 2;
-	}
+            c_nons -= 2;
+        }
 
-	cpl_imagelist_delete(c_onlist);
-	if (mode & IRPLIB_LIN_NO_COLLAPSE) {
-          cpl_imagelist_delete(c_offlist);
-	}
+        cpl_imagelist_delete(c_onlist);
+        if (mode & IRPLIB_LIN_NO_COLLAPSE) {
+            cpl_imagelist_delete(c_offlist);
+        }
     }
 
     skip_if(xsh_detmon_add_adl_column(lin_table, opt_nir));
 
     if(!(mode & IRPLIB_LIN_PIX2PIX)) {
-	double mse = 0;
+        double mse = 0;
         /* Computation of LINEARITY via polynomial fit */
-	y = cpl_vector_wrap(cpl_table_get_nrow(lin_table),
-			    (double *)cpl_table_get_data_double_const(lin_table,
-							      "MED"));
+        y = cpl_vector_wrap(cpl_table_get_nrow(lin_table),
+                            (double *)cpl_table_get_data_double_const(lin_table,
+                                                                      "MED"));
         if (opt_nir == NIR) {
-           x=cpl_vector_wrap(cpl_table_get_nrow(lin_table),
-                             (double *)cpl_table_get_data_double_const(lin_table,                                                                 							      "DIT"));
+            x=cpl_vector_wrap(cpl_table_get_nrow(lin_table),
+                              (double *)cpl_table_get_data_double_const(lin_table,                                                                 							      "DIT"));
         } else {
-           x=cpl_vector_wrap(cpl_table_get_nrow(lin_table),
-                             (double *)cpl_table_get_data_double_const(lin_table,                                                                 							      "EXPTIME"));
+            x=cpl_vector_wrap(cpl_table_get_nrow(lin_table),
+                              (double *)cpl_table_get_data_double_const(lin_table,                                                                 							      "EXPTIME"));
         }
         if(x == NULL || y == NULL) {
-	    cpl_vector_unwrap((cpl_vector *)x);
-	    cpl_vector_unwrap((cpl_vector *)y);
-	    /*
-	     * As x and y are const vectors, if they would be defined at the
-	     * beginning of the function (required for skip_if - end_skip
-	     * scheme), they couldn't be initialised to NULL (required too).
-	     * Therefore, they are considered apart from the scheme.
-	     */
-	    skip_if(1);
-	}
+            cpl_vector_unwrap((cpl_vector *)x);
+            cpl_vector_unwrap((cpl_vector *)y);
+            /*
+             * As x and y are const vectors, if they would be defined at the
+             * beginning of the function (required for skip_if - end_skip
+             * scheme), they couldn't be initialised to NULL (required too).
+             * Therefore, they are considered apart from the scheme.
+             */
+            skip_if(1);
+        }
 
         cpl_msg_info(cpl_func, "Polynomial fitting for the LINEARITY");
         poly_linfit = irplib_polynomial_fit_1d_create_chiq(x, y, order, &mse);
 
-	if(order == cpl_vector_get_size(x) - 1) {
-	    cpl_msg_warning(cpl_func, "The fitting is not over-determined.");
-	    mse = 0;
-	}
+        if(order == cpl_vector_get_size(x) - 1) {
+            cpl_msg_warning(cpl_func, "The fitting is not over-determined.");
+            mse = 0;
+        }
 
-	if(poly_linfit == NULL) {
-	    cpl_vector_unwrap((cpl_vector *)x);
-	    cpl_vector_unwrap((cpl_vector *)y);
-	    /* See comment in previous error checking if() statement */
-	    skip_if(1);
-	}
+        if(poly_linfit == NULL) {
+            cpl_vector_unwrap((cpl_vector *)x);
+            cpl_vector_unwrap((cpl_vector *)y);
+            /* See comment in previous error checking if() statement */
+            skip_if(1);
+        }
 
-	cpl_vector_unwrap((cpl_vector *) x);
-    cpl_vector_unwrap((cpl_vector *) y);
-    cpl_size deg = 0;
-    for (deg = 0; deg <= order; deg++) {
-      const double coeff = cpl_polynomial_get_coeff(poly_linfit, &deg);
-      char *name_o = cpl_sprintf("ESO QC LIN COEF%" CPL_SIZE_FORMAT "", deg);
-      assert(name_o != NULL);
-      skip_if(cpl_propertylist_append_double(qclist, name_o, coeff));
-      skip_if(
-          cpl_propertylist_set_comment(qclist,name_o, DETMON_QC_LIN_COEF_C));
-      cpl_free(name_o);
-      pcoeffs[deg] = coeff;
-    }
-	skip_if(cpl_propertylist_append_double(qclist,DETMON_QC_ERRFIT, mse));
-    	    skip_if(cpl_propertylist_set_comment(qclist,DETMON_QC_ERRFIT,
-						 DETMON_QC_ERRFIT_MSE_C));
+        cpl_vector_unwrap((cpl_vector *)x);
+        cpl_vector_unwrap((cpl_vector *)y);
+
+        for(deg = 0; deg <= order; deg++) {
+            const double            coeff =
+                cpl_polynomial_get_coeff(poly_linfit, &deg);
+            char                   *name_o =
+                cpl_sprintf("ESO QC LIN COEF%" CPL_SIZE_FORMAT "", deg);
+            assert(name_o != NULL);
+            skip_if(cpl_propertylist_append_double(qclist, name_o, coeff));
+            skip_if(cpl_propertylist_set_comment(qclist,name_o,
+                                                 DETMON_QC_LIN_COEF_C));
+            cpl_free(name_o);
+            pcoeffs[deg] = coeff;
+        }
+        skip_if(cpl_propertylist_append_double(qclist,DETMON_QC_ERRFIT, mse));
+        skip_if(cpl_propertylist_set_comment(qclist,DETMON_QC_ERRFIT,
+                                             DETMON_QC_ERRFIT_MSE_C));
 
 
     } else {
-       if (opt_nir == NIR) {
-          x=cpl_vector_wrap(cpl_table_get_nrow(lin_table),
-			    (double *)cpl_table_get_data_double_const(lin_table,
-                                                                      "DIT"));
-       } else {
-          x=cpl_vector_wrap(cpl_table_get_nrow(lin_table),
-			    (double *)cpl_table_get_data_double_const(lin_table,
-                                                                      "EXPTIME"));
-       }
+        if (opt_nir == NIR) {
+            x=cpl_vector_wrap(cpl_table_get_nrow(lin_table),
+                              (double *)cpl_table_get_data_double_const(lin_table,
+                                                                        "DIT"));
+        } else {
+            x=cpl_vector_wrap(cpl_table_get_nrow(lin_table),
+                              (double *)cpl_table_get_data_double_const(lin_table,
+                                                                        "EXPTIME"));
+        }
 
 
-       first = cpl_imagelist_get_const(lin_inputs, 0);
-       sizex = cpl_image_get_size_x(first);
-       sizey = cpl_image_get_size_y(first);
+        first = cpl_imagelist_get_const(lin_inputs, 0);
+        sizex = cpl_image_get_size_x(first);
+        sizey = cpl_image_get_size_y(first);
 
-       vsize = cpl_vector_get_size(x);
+        vsize = cpl_vector_get_size(x);
 
-	fiterror = cpl_image_new(sizex, sizey, CPL_TYPE_FLOAT);
+        fiterror = cpl_image_new(sizex, sizey, CPL_TYPE_FLOAT);
 
         *coeffs_cube =
             cpl_fit_imagelist_polynomial(x, lin_inputs, 0,
                                          order, FALSE, CPL_TYPE_FLOAT,
-					 fiterror);
+                                         fiterror);
 
-	cpl_vector_unwrap((cpl_vector*)x);
-	irplib_ensure(*coeffs_cube != NULL, CPL_ERROR_UNSPECIFIED,
-		      "Failed polynomial fit");
+        cpl_vector_unwrap((cpl_vector*)x);
+        irplib_ensure(*coeffs_cube != NULL, CPL_ERROR_UNSPECIFIED,
+                      "Failed polynomial fit");
 
         for(i = 0; i <= order; i++) {
             cpl_image              *image = cpl_imagelist_get(*coeffs_cube, i);
-	    const double coeff = cpl_image_get_median(image);
+            const double coeff = cpl_image_get_median(image);
             char * name_o1 = cpl_sprintf("ESO QC LIN COEF%d", i);
             char * name_o2 = cpl_sprintf("ESO QC LIN COEF%d ERR", i);
-	    pcoeffs[i] = coeff;
+            pcoeffs[i] = coeff;
             assert(name_o1 != NULL);
             assert(name_o2 != NULL);
             skip_if(cpl_propertylist_append_double(qclist, name_o1, coeff));
-    	    skip_if(cpl_propertylist_set_comment(qclist,name_o1,
-						 DETMON_QC_LIN_COEF_C));
+            skip_if(cpl_propertylist_set_comment(qclist,name_o1,
+                                                 DETMON_QC_LIN_COEF_C));
             cpl_free(name_o1);
-	    name_o1= NULL;
+            name_o1= NULL;
             skip_if(cpl_propertylist_append_double(qclist, name_o2,
-					   cpl_image_get_stdev(image)));
-    	    skip_if(cpl_propertylist_set_comment(qclist,name_o2,
-						 DETMON_QC_LIN_COEF_ERR_C));
+                                                   cpl_image_get_stdev(image)));
+            skip_if(cpl_propertylist_set_comment(qclist,name_o2,
+                                                 DETMON_QC_LIN_COEF_ERR_C));
             cpl_free(name_o2);
-	    name_o2= NULL;
+            name_o2= NULL;
         }
 
-	if(order == vsize - 1) {
-	    cpl_msg_warning(cpl_func, "The fitting is not over-determined.");
-	    skip_if(cpl_propertylist_append_double(qclist,DETMON_QC_ERRFIT,
-						   0.0));
-    	    skip_if(cpl_propertylist_set_comment(qclist,DETMON_QC_ERRFIT,
-						 DETMON_QC_ERRFIT_C));
+        if(order == vsize - 1) {
+            cpl_msg_warning(cpl_func, "The fitting is not over-determined.");
+            skip_if(cpl_propertylist_append_double(qclist,DETMON_QC_ERRFIT,
+                                                   0.0));
+            skip_if(cpl_propertylist_set_comment(qclist,DETMON_QC_ERRFIT,
+                                                 DETMON_QC_ERRFIT_C));
 
 
-	} else {
-	    skip_if(cpl_propertylist_append_double(qclist,DETMON_QC_ERRFIT,
-						   cpl_image_get_median(fiterror)));
-    	    skip_if(cpl_propertylist_set_comment(qclist,DETMON_QC_ERRFIT,
-						 DETMON_QC_ERRFIT_C));
+        } else {
+            skip_if(cpl_propertylist_append_double(qclist,DETMON_QC_ERRFIT,
+                                                   cpl_image_get_median(fiterror)));
+            skip_if(cpl_propertylist_set_comment(qclist,DETMON_QC_ERRFIT,
+                                                 DETMON_QC_ERRFIT_C));
 
-	}
+        }
     }
 
     skip_if(xsh_detmon_lg_lineff(pcoeffs, qclist, ref_level, order));
 
     if(mode & IRPLIB_LIN_PIX2PIX) {
-	int nbpixs;
+        int nbpixs;
         *bpm = xsh_detmon_bpixs(*coeffs_cube, bpmbin, kappa, &nbpixs);
-	skip_if(*bpm == NULL);
-	skip_if(cpl_propertylist_append_int(qclist, DETMON_QC_NUM_BPM,
-					    nbpixs));
-	skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_NUM_BPM,
-					     DETMON_QC_NUM_BPM_C));
+        skip_if(*bpm == NULL);
+        skip_if(cpl_propertylist_append_int(qclist, DETMON_QC_NUM_BPM,
+                                            nbpixs));
+        skip_if(cpl_propertylist_set_comment(qclist, DETMON_QC_NUM_BPM,
+                                             DETMON_QC_NUM_BPM_C));
     }
 
     end_skip;
@@ -6315,419 +7145,419 @@ xsh_detmon_lin(const cpl_imagelist  * imlist_on,
 /*--------------------------------------------------------------------------*/
 static cpl_error_code
 xsh_detmon_lin_table_fill_row(cpl_table * lin_table, double c_dit,
-				 cpl_imagelist * linearity_inputs,
-				 const cpl_imagelist * ons,
-				 const cpl_imagelist * offs,
-				 int llx,
-				 int lly,
-				 int urx,
-				 int ury,
-				 const int pos,
-                                 const int nskip,
-				 unsigned mode)
+                          cpl_imagelist * linearity_inputs,
+                          const cpl_imagelist * ons,
+                          const cpl_imagelist * offs,
+                          int llx,
+                          int lly,
+                          int urx,
+                          int ury,
+                          const int pos,
+                          const int nskip,
+                          unsigned mode)
 {
-    cpl_image              * dif1=NULL;
-    cpl_image              * dif2=NULL;
-    cpl_image              * dif_avg=NULL;
-
-    double                   med_dit=0;
-    double                   mean_dit=0;
-    cpl_error_code           error;
     cpl_image * extracted=NULL;
-    int offsize=0;
 
     cpl_ensure_code(lin_table != NULL, CPL_ERROR_NULL_INPUT);
     cpl_ensure_code(ons != NULL, CPL_ERROR_NULL_INPUT);
     cpl_ensure_code(offs != NULL, CPL_ERROR_NULL_INPUT);
 
     if (mode & IRPLIB_LIN_PIX2PIX) {
-       cpl_msg_debug(cpl_func,"checking linearity inputs");
-	cpl_ensure_code(linearity_inputs != NULL, CPL_ERROR_NULL_INPUT);
+        cpl_msg_debug(cpl_func,"checking linearity inputs");
+        cpl_ensure_code(linearity_inputs != NULL, CPL_ERROR_NULL_INPUT);
     }
 
 
     if (mode & IRPLIB_LIN_NIR) {
-	cpl_table_set(lin_table, "DIT", pos, c_dit);
+        cpl_table_set(lin_table, "DIT", pos, c_dit);
     } else if (mode & IRPLIB_LIN_OPT) { /*OPT */
-	    cpl_table_set(lin_table, "EXPTIME", pos, c_dit);
+        cpl_table_set(lin_table, "EXPTIME", pos, c_dit);
     } else {
-	cpl_msg_error(cpl_func, "Mandatory mode not given");
+        cpl_msg_error(cpl_func, "Mandatory mode not given");
     }
 
-    offsize = cpl_imagelist_get_size(offs);
-
-    /* Algorithm defined: substract ON - OFF and average 2 differences */
-    dif1 = cpl_image_subtract_create(cpl_imagelist_get_const(ons, 0),
-                                     cpl_imagelist_get_const(offs, 0));
-
-    if (mode & IRPLIB_LIN_NO_COLLAPSE && offsize > 1)
-        dif2 = cpl_image_subtract_create(cpl_imagelist_get_const(ons, 1),
-                                         cpl_imagelist_get_const(offs, 1));
-    else
-        dif2 = cpl_image_subtract_create(cpl_imagelist_get_const(ons, 1),
-                                         cpl_imagelist_get_const(offs, 0));
-
-    dif_avg = cpl_image_average_create(dif1, dif2);
-
-    cpl_image_abs(dif_avg);
-    extracted = cpl_image_extract(dif_avg, llx, lly, urx, ury);
-
-    cpl_ensure_code(extracted != NULL, cpl_error_get_code());
-
-    cpl_table_set(lin_table, "MED", pos, cpl_image_get_median(extracted));
-    cpl_table_set(lin_table, "MEAN", pos, cpl_image_get_mean(extracted));
-    med_dit = cpl_image_get_median(extracted) / c_dit;
-    mean_dit = cpl_image_get_mean(extracted)  / c_dit;
+    {
+        const cpl_image * off2;
+        if (cpl_imagelist_get_size(offs) == 1 || mode & IRPLIB_LIN_COLLAPSE)
+            off2 = cpl_imagelist_get_const(offs, 0);
+        else
+            off2 = cpl_imagelist_get_const(offs, 1);
+
+        extracted = xsh_detmon_subtracted_avg(cpl_imagelist_get_const(ons, 0),
+                                          cpl_imagelist_get_const(offs, 0),
+                                          cpl_imagelist_get_const(ons, 1),
+                                          off2,
+                                          llx, lly, urx, ury);
+        cpl_ensure_code(extracted != NULL, cpl_error_get_code());
+    }
 
-    cpl_table_set(lin_table, "MED_DIT", pos, med_dit);
-    cpl_table_set(lin_table, "MEAN_DIT", pos, mean_dit);
+    {
+        double median = cpl_image_get_median(extracted);
+        double mean= cpl_image_get_mean(extracted);
+        cpl_table_set(lin_table, "MED", pos, median);
+        cpl_table_set(lin_table, "MEAN", pos, mean);
 
-    cpl_image_delete(dif1);
-    cpl_image_delete(dif2);
+        cpl_table_set(lin_table, "MED_DIT", pos, median / c_dit);
+        cpl_table_set(lin_table, "MEAN_DIT", pos, mean / c_dit);
+    }
 
     /* Insert to the imagelist used to fit the polynomial */
     if(mode & IRPLIB_LIN_PIX2PIX) {
-        error = cpl_imagelist_set(linearity_inputs, extracted, pos-nskip);
+        cpl_error_code error = cpl_imagelist_set(linearity_inputs, extracted,
+                                                 pos-nskip);
         cpl_ensure_code(!error, error);
     } else {
         cpl_image_delete(extracted);
     }
 
-
-    cpl_image_delete(dif_avg);
-
     return cpl_error_get_code();
 }
 
-static double irplib_calculate_total_noise_smooth(const cpl_image* pimage, int pattern_x, int pattern_y)
+static double irplib_calculate_total_noise_smooth(const cpl_image* pimage,
+                                                  int pattern_x, int pattern_y)
 {
-	cpl_image * p_tmp_image = 0;
-	cpl_image * psmooth_image = 0;
-	double ret_noise = -1;
-	cpl_mask * mask = cpl_mask_new(pattern_x, pattern_y);
-	cpl_mask_not(mask);
-	p_tmp_image = cpl_image_duplicate(pimage);
-	cpl_image_filter_mask(p_tmp_image,pimage, mask,CPL_FILTER_MEDIAN ,CPL_BORDER_FILTER);
-	cpl_image_divide_scalar(p_tmp_image, cpl_image_get_median(pimage));
-	psmooth_image  = cpl_image_divide_create(pimage,p_tmp_image);
-	ret_noise = irplib_calculate_total_noise(psmooth_image);
-	cpl_mask_delete(mask);
-	cpl_image_delete(psmooth_image);
-	cpl_image_delete(p_tmp_image);
-	return ret_noise;
+    cpl_image * p_tmp_image = 0;
+    cpl_image * psmooth_image = 0;
+    double ret_noise;
+    cpl_mask * mask = cpl_mask_new(pattern_x, pattern_y);
+    cpl_mask_not(mask);
+    p_tmp_image = cpl_image_duplicate(pimage);
+    cpl_image_filter_mask(p_tmp_image,pimage, mask,CPL_FILTER_MEDIAN ,CPL_BORDER_FILTER);
+    cpl_image_divide_scalar(p_tmp_image, cpl_image_get_median(pimage));
+    psmooth_image  = cpl_image_divide_create(pimage,p_tmp_image);
+    ret_noise = irplib_calculate_total_noise(psmooth_image);
+    cpl_mask_delete(mask);
+    cpl_image_delete(psmooth_image);
+    cpl_image_delete(p_tmp_image);
+    return ret_noise;
 }
+
 static double irplib_calculate_total_noise(const cpl_image* pimage)
 {
-	double total_noise = -1;
+    double total_noise = -1;
     unsigned long max_bin_size = 1E5;
-	const double  hstart = cpl_image_get_min(pimage);
-	const double  hrange = cpl_image_get_max(pimage) - hstart;
-	const unsigned long nbins  = max_bin_size;
-	cpl_error_code err = CPL_ERROR_NONE;
-	/* apply histogram method */
-	xsh_hist * phist = 0;
-	phist = xsh_hist_new();
-	/* 2 extra-bins for possible out-of-range values */
-
-	xsh_hist_init(phist, nbins, hstart, hrange);
-	err = xsh_hist_fill(phist, pimage);
-	if (err == CPL_ERROR_NONE)
-	{
-		unsigned int i = 0;
-		double x0 = 0;
-		double area = 0;
-		double offset = 0;
-
-		/* prepare vector */
-		unsigned long n_bins = xsh_hist_get_nbins(phist);
-		double start = xsh_hist_get_start(phist);
-		double bin_size = xsh_hist_get_bin_size(phist);
-		cpl_vector* pdata_vector = cpl_vector_new(n_bins);
-		cpl_vector* ppos_vector = cpl_vector_new(n_bins);
-		cpl_table* ptable = cpl_table_new(n_bins);
-		cpl_table_new_column(ptable, "bin", CPL_TYPE_DOUBLE);
-		cpl_table_new_column(ptable, "value", CPL_TYPE_DOUBLE);
-		for(i = 0; i < n_bins; i++)
-		{
-			unsigned int value = xsh_hist_get_value(phist, i);
-			double dvalue = (double)(value);
-			cpl_vector_set(pdata_vector, i, dvalue);
-			cpl_vector_set(ppos_vector, i, start + i * bin_size);
-
-			cpl_table_set(ptable, "bin", i, start + i * bin_size);
-			cpl_table_set(ptable, "value", i, dvalue);
-		}
-		err = cpl_vector_fit_gaussian(ppos_vector, NULL, pdata_vector, NULL, CPL_FIT_ALL, &x0, &total_noise, &area, &offset, NULL, NULL, NULL );
-		if (err == CPL_ERROR_NONE)
-		{
-			cpl_msg_info(cpl_func, "FPN Calculation: histogram x0[%f] total_noise[%f] area[%f] offset[%f]", x0, total_noise, area, offset);
-		}
-		else
-		{
-			cpl_msg_warning(cpl_func, "FPN could not be computed due failed Gaussian Fit,  err msg [%s]", cpl_error_get_message());
-			cpl_error_reset();
-		}
-		cpl_table_delete(ptable);
-		cpl_vector_delete(ppos_vector);
-		cpl_vector_delete(pdata_vector);
-	}
-	else
-	{
-		cpl_msg_warning(cpl_func, "FPN could not be computed due failed histogram computation, err msg [%s]", cpl_error_get_message());
-		cpl_error_reset();
-	}
-	xsh_hist_delete(phist);
+    const double  hstart = cpl_image_get_min(pimage);
+    const double  hrange = cpl_image_get_max(pimage) - hstart;
+    const unsigned long nbins  = max_bin_size;
+    cpl_error_code err = CPL_ERROR_NONE;
+    /* apply histogram method */
+    irplib_hist * phist = 0;
+    phist = irplib_hist_new();
+    /* 2 extra-bins for possible out-of-range values */
+
+    irplib_hist_init(phist, nbins, hstart, hrange);
+    err = irplib_hist_fill(phist, pimage);
+    if (err == CPL_ERROR_NONE)
+    {
+        unsigned int i = 0;
+        double x0 = 0;
+        double area = 0;
+        double offset = 0;
+
+        /* prepare vector */
+        unsigned long n_bins = irplib_hist_get_nbins(phist);
+        double start = irplib_hist_get_start(phist);
+        double bin_size = irplib_hist_get_bin_size(phist);
+        cpl_vector* pdata_vector = cpl_vector_new(n_bins);
+        cpl_vector* ppos_vector = cpl_vector_new(n_bins);
+        cpl_table* ptable = cpl_table_new(n_bins);
+        cpl_table_new_column(ptable, "bin", CPL_TYPE_DOUBLE);
+        cpl_table_new_column(ptable, "value", CPL_TYPE_DOUBLE);
+        for(i = 0; i < n_bins; i++)
+        {
+            unsigned int value = irplib_hist_get_value(phist, i);
+            double dvalue = (double)(value);
+            cpl_vector_set(pdata_vector, i, dvalue);
+            cpl_vector_set(ppos_vector, i, start + i * bin_size);
+
+            cpl_table_set(ptable, "bin", i, start + i * bin_size);
+            cpl_table_set(ptable, "value", i, dvalue);
+        }
+        err = cpl_vector_fit_gaussian(ppos_vector, NULL, pdata_vector, NULL, CPL_FIT_ALL, &x0, &total_noise, &area, &offset, NULL, NULL, NULL );
+        if (err == CPL_ERROR_NONE)
+        {
+            cpl_msg_info(cpl_func, "FPN Calculation: histogram x0[%f] total_noise[%f] area[%f] offset[%f]", x0, total_noise, area, offset);
+        }
+        else
+        {
+            cpl_msg_warning(cpl_func, "FPN could not be computed due failed Gaussian Fit,  err msg [%s]", cpl_error_get_message());
+            cpl_error_reset();
+        }
+        cpl_table_delete(ptable);
+        cpl_vector_delete(ppos_vector);
+        cpl_vector_delete(pdata_vector);
+    }
+    else
+    {
+        cpl_msg_warning(cpl_func, "FPN could not be computed due failed histogram computation, err msg [%s]", cpl_error_get_message());
+        cpl_error_reset();
+    }
+    irplib_hist_delete(phist);
 
-	return total_noise;
+    return total_noise;
 }
 
 static double irplib_compute_err(double gain, double ron, double FA)
 {
-	double int_gain = (gain * gain - 1) / 12;
-	if (int_gain < 0)
-	{
-		int_gain = 0;
-	}
-	return sqrt(ron * ron + FA / gain + int_gain);
+    double int_gain = (gain * gain - 1) / 12;
+    if (int_gain < 0)
+    {
+        int_gain = 0;
+    }
+    return sqrt(ron * ron + FA / gain + int_gain);
 }
+
 static double irplib_fpn_lg(const cpl_image* f1, int* range, double gain ,
-		FPN_METHOD fpn_method, int smooth_size, double* mse)
+                            FPN_METHOD fpn_method, int smooth_size, double* mse)
 {
-	cpl_image* im_diff = 0;
-	const cpl_image* im_f1 = f1;
-	cpl_image* im_inrange1 = 0;
-	double FA = 0;
-	double s_tot = 0; /* absolute total noise */
-	double s_fpn = 0; /* fixed pattern noise */
-	double sr_fpn = 0; /* relative structural noise */
-	/*che cinput*/
+    cpl_image* im_diff = 0;
+    const cpl_image* im_f1 = f1;
+    cpl_image* im_inrange1 = 0;
+    double FA = 0;
+    double s_tot = 0; /* absolute total noise */
+    double s_fpn = 0; /* fixed pattern noise */
+    double sr_fpn = 0; /* relative structural noise */
+    /*che cinput*/
     if (gain<=0) {
-     /* put dummy values Negative to indicate a problem occurred
-       (FPN should be always positive) */
-       cpl_msg_warning(cpl_func,"gain[%f]<0", gain);
-       cpl_msg_warning(cpl_func,"We set dummy values for FPN");
-       s_fpn=-999.;
-       sr_fpn=-999;
-       return sr_fpn;
-    }
-	if (range)
-	{
-		im_inrange1 = cpl_image_extract(f1, range[0], range[1], range[2], range[3]);
-		im_f1 = im_inrange1;
-	}
-	FA = cpl_image_get_median(im_f1);
+        /* put dummy values Negative to indicate a problem occurred
+           (FPN should be always positive) */
+        cpl_msg_warning(cpl_func,"gain[%f]<0", gain);
+        cpl_msg_warning(cpl_func,"We set dummy values for FPN");
+        s_fpn=-999.;
+        sr_fpn=-999;
+        return sr_fpn;
+    }
+    if (range)
+    {
+        im_inrange1 = cpl_image_extract(f1, range[0], range[1], range[2], range[3]);
+        im_f1 = im_inrange1;
+    }
+    FA = cpl_image_get_median(im_f1);
 
-	/* apply histogram method */
-        /* Is this irplib function giving the right result?? */
-	switch (fpn_method)
-	{
-	case FPN_SMOOTH:
-		cpl_msg_info(cpl_func,"SMOOTH method is used for FPN, pattern size[%d x %d] pixels",smooth_size,smooth_size );
-		s_tot = irplib_calculate_total_noise_smooth(im_f1,smooth_size,smooth_size);
-		break;
-	case FPN_HISTOGRAM:
-		cpl_msg_info(cpl_func,"HISTOGRAM method is used for FPN");
-		s_tot = irplib_calculate_total_noise(im_f1);
-		break;
-	default:
-		s_tot = -1;
-		sr_fpn = -1;
-		cpl_msg_warning(cpl_func,"fpn_method is not defined");
-		break;
-	}
-	if (s_tot > 0)
-	{
-		if (FA<0)
-		{
-		  /* put dummy values Negative to indicate a problem occurred
-		   (FPN should be always positive) */
-		   cpl_msg_warning(cpl_func,"Median flux on sum of flats<0");
-		   cpl_msg_warning(cpl_func,"We set dummy values for FPN");
-		   s_fpn=-999.;
-		   sr_fpn=-999;
-		}
-
-		if ((s_tot * s_tot - FA / gain) > 0)
-		{
-		   s_fpn = sqrt(s_tot * s_tot - FA / gain);
-		   sr_fpn = s_fpn / FA;
-		   *mse = (irplib_compute_err(gain, 0, FA)) * gain / FA;
-		} else {
-		  /* put dummy values Negative to indicate a problem occurred
-		   (FPN should be always positive) */
-		   cpl_msg_warning(cpl_func,"s_tot * s_tot < FA / gain");
-		   cpl_msg_warning(cpl_func,"We set dummy values for FPN");
-		   s_fpn=-999.;
-		   sr_fpn=-999;
-		   *mse = -1;
-		}
-/*
-		cpl_msg_debug(cpl_func, "FPN Calculation: FA[%f] s_tot[%f] photon_noise[%f] s_fpn[%f] sr_fpn[%f] mse[%f]", FA, s_tot, photon_noise, s_fpn, sr_fpn, *mse);
-*/
-	}
-	cpl_image_delete(im_diff);
-	if (range)
-	{
-		cpl_image_delete(im_inrange1);
-	}
-	return sr_fpn;
+    /* apply histogram method */
+    /* Is this irplib function giving the right result?? */
+    switch (fpn_method)
+    {
+        case FPN_SMOOTH:
+            cpl_msg_info(cpl_func,"SMOOTH method is used for FPN, pattern size[%d x %d] pixels",smooth_size,smooth_size );
+            s_tot = irplib_calculate_total_noise_smooth(im_f1,smooth_size,smooth_size);
+            break;
+        case FPN_HISTOGRAM:
+            cpl_msg_info(cpl_func,"HISTOGRAM method is used for FPN");
+            s_tot = irplib_calculate_total_noise(im_f1);
+            break;
+        default:
+            s_tot = -1;
+            sr_fpn = -1;
+            cpl_msg_warning(cpl_func,"fpn_method is not defined");
+            break;
+    }
+    if (s_tot > 0)
+    {
+        if (FA<0)
+        {
+            /* put dummy values Negative to indicate a problem occurred
+               (FPN should be always positive) */
+            cpl_msg_warning(cpl_func,"Median flux on sum of flats<0");
+            cpl_msg_warning(cpl_func,"We set dummy values for FPN");
+            s_fpn=-999.;
+            sr_fpn=-999;
+        }
+
+        if ((s_tot * s_tot - FA / gain) > 0)
+        {
+            s_fpn = sqrt(s_tot * s_tot - FA / gain);
+            sr_fpn = s_fpn / FA;
+            *mse = (irplib_compute_err(gain, 0, FA)) * gain / FA;
+        } else {
+            /* put dummy values Negative to indicate a problem occurred
+               (FPN should be always positive) */
+            cpl_msg_warning(cpl_func,"s_tot * s_tot < FA / gain");
+            cpl_msg_warning(cpl_func,"We set dummy values for FPN");
+            s_fpn=-999.;
+            sr_fpn=-999;
+            *mse = -1;
+        }
+        /*
+           cpl_msg_debug(cpl_func, "FPN Calculation: FA[%f] s_tot[%f] photon_noise[%f] s_fpn[%f] sr_fpn[%f] mse[%f]", FA, s_tot, photon_noise, s_fpn, sr_fpn, *mse);
+           */
+    }
+    cpl_image_delete(im_diff);
+    if (range)
+    {
+        cpl_image_delete(im_inrange1);
+    }
+    return sr_fpn;
 }
 
-static cpl_imagelist * irplib_load_fset_wrp(const cpl_frameset * pframeset, cpl_type type , int whichext)
+
+static cpl_imagelist * irplib_load_fset_wrp(const cpl_frameset * pframeset,
+                                            cpl_type type , int whichext)
 {
-	cpl_imagelist * ret = 0;
-	ret =  cpl_imagelist_load_frameset(pframeset, type,
-            1, whichext);
-	if (ret)
-	{
-		/* check the images for size*/
-		int sz = cpl_imagelist_get_size(ret);
-		int i = 0;
-		for(i = 0; i < sz; i ++)
-		{
-			cpl_image* pimage = 0;
-			pimage = cpl_imagelist_get(ret, i);
-			if (pimage)
-			{
-				int size_x = 0;
-				int size_y = 0;
-				size_x = cpl_image_get_size_x(pimage);
-				size_y = cpl_image_get_size_y(pimage);
-				if (detmon_lg_config.nx != size_x || detmon_lg_config.ny != size_y)
-				{
-					cpl_msg_error(cpl_func, "All images in the input should have the same size,\n" \
-							" image #%d has size x[%d] y[%d], expected size  x[%d] y[%d]", i, size_x, size_y,
-							detmon_lg_config.nx, detmon_lg_config.ny);
-					cpl_error_set(cpl_func, CPL_ERROR_ILLEGAL_INPUT);
-					cpl_imagelist_delete(ret);
-					ret = 0;
-				}
-			}
-		}
-	}
-	return ret;
+    /* FIXME: load image into window size from beginning to
+     * save all the extracts */
+    return xsh_detmon_load_frameset_window(pframeset, type, 0, whichext,
+                                       xsh_detmon_lg_config.llx,
+                                       xsh_detmon_lg_config.lly,
+                                       xsh_detmon_lg_config.urx,
+                                       xsh_detmon_lg_config.ury,
+                                       xsh_detmon_lg_config.nx,
+                                       xsh_detmon_lg_config.ny);
 }
 
-static cpl_imagelist * irplib_load_fset_wrp_ext(const cpl_frameset * pframeset, cpl_type type , int whichext)
+static cpl_imagelist * irplib_load_fset_wrp_ext(const cpl_frameset * pframeset,
+                                                cpl_type type , int whichext)
 {
-   int i = whichext; /* fake code to avoid compiler warning */
-	cpl_imagelist* offs = cpl_imagelist_new();
-	detmon_lg_config.load_fset(pframeset, type, offs);
-	i++;
-	return offs;
+    int i = whichext; /* fake code to avoid compiler warning */
+    cpl_imagelist* offs = cpl_imagelist_new();
+    xsh_detmon_lg_config.load_fset(pframeset, type, offs);
+    i++;
+    return offs;
 }
 
-static cpl_error_code irplib_table_create_column(cpl_table* ptable, cpl_propertylist* plist)
+static cpl_error_code irplib_table_create_column(cpl_table* ptable,
+                                                 cpl_propertylist* plist)
 {
-	if (ptable && plist)
-	{
-		int size = cpl_propertylist_get_size(plist);
-		int i = 0;
-		for (i = 0; i < size; i++)
-		{
-			cpl_property* pprop = cpl_propertylist_get(plist,i);
-			if (pprop)
-			{
-				const char* pname = cpl_property_get_name(pprop);
-				if (pname)
-				{
-					cpl_table_new_column(ptable, pname, cpl_property_get_type(pprop));
-					if (cpl_error_get_code() != CPL_ERROR_NONE)
-					{
-						cpl_msg_warning(cpl_func, "cannot create new column[%s], err[%s]", pname, cpl_error_get_message());
-						break; /* leave the cycle */
-					}
-				}
-			}
-		}
-	}
-	return cpl_error_get_code();
+    if (ptable && plist)
+    {
+        int size = cpl_propertylist_get_size(plist);
+        int i = 0;
+        for (i = 0; i < size; i++)
+        {
+            cpl_property* pprop = cpl_propertylist_get(plist,i);
+            if (pprop)
+            {
+                const char* pname = cpl_property_get_name(pprop);
+                if (pname)
+                {
+                    cpl_table_new_column(ptable, pname, cpl_property_get_type(pprop));
+                    if (cpl_error_get_code() != CPL_ERROR_NONE)
+                    {
+                        cpl_msg_warning(cpl_func, "cannot create new column[%s], err[%s]", pname, cpl_error_get_message());
+                        break; /* leave the cycle */
+                    }
+                }
+            }
+        }
+    }
+    return cpl_error_get_code();
 }
 
-static cpl_error_code irplib_fill_table_DETWINUIT(cpl_table* ptable, cpl_propertylist* plist, int row)
+static cpl_error_code irplib_fill_table_DETWINUIT(cpl_table* ptable,
+                                                  cpl_propertylist* plist, int row)
 {
-	cpl_error_code err = CPL_ERROR_NONE;
-	if (ptable && plist)
-	{
-		int size = cpl_propertylist_get_size(plist);
-		int i = 0;
-		for (i = 0; i < size; i++)
-		{
-			cpl_property* pprop = cpl_propertylist_get(plist,i);
-			if (pprop)
-			{
-				const char* pname = cpl_property_get_name(pprop);
-				double  value = cpl_property_get_double(pprop);
-				if (pname)
-				{
-					cpl_table_set_double(ptable, pname, row, value);
-					if (cpl_error_get_code() != CPL_ERROR_NONE)
-					{
-						cpl_msg_warning(cpl_func, "cannot write value to the table, column[%s] value[%f], err[%s]", pname, value, cpl_error_get_message());
-						cpl_error_reset();
-						break; /* leave the cycle */
-					}
-				}
-			}
-		}
-	}
-	return err;
+    cpl_error_code err = CPL_ERROR_NONE;
+    if (ptable && plist)
+    {
+        int size = cpl_propertylist_get_size(plist);
+        int i = 0;
+        for (i = 0; i < size; i++)
+        {
+            cpl_property* pprop = cpl_propertylist_get(plist,i);
+            if (pprop)
+            {
+                const char* pname = cpl_property_get_name(pprop);
+                double  value = cpl_property_get_double(pprop);
+                if (pname)
+                {
+                    cpl_table_set_double(ptable, pname, row, value);
+                    if (cpl_error_get_code() != CPL_ERROR_NONE)
+                    {
+                        cpl_msg_warning(cpl_func, "cannot write value to the table, column[%s] value[%f], err[%s]", pname, value, cpl_error_get_message());
+                        cpl_error_reset();
+                        break; /* leave the cycle */
+                    }
+                }
+            }
+        }
+    }
+    return err;
 }
-cpl_error_code xsh_detmon_check_order(const double *exptime, int sz, double tolerance, int order)
+
+cpl_error_code xsh_detmon_check_order(const double *exptime, int sz,
+                                  double tolerance, int order)
 {
-	int nsets = 0;
-	int i = 0;
-	/* 1. Determine number of groups */
-/*   cpl_msg_warning(cpl_func, "xsh_detmon_check_order sz[%i]", sz);*/
-	do
-	{
-/*      cpl_msg_warning(cpl_func, "xsh_detmon_check_order i[%i] exptime[%g]", i, exptime[i]);   */
-		nsets++;
-		do
-		{
-			i++;
-			if(i == sz - 1)
-			{
-				break;
-			}
-		} while(fabs(exptime[i-1] - exptime[i]) < tolerance);
-	} while(i < sz - 1);
-	/* the very last adjustment for the last group */
-	if (!(fabs(exptime[i-1] - exptime[i]) < tolerance)) nsets++;
-	if(nsets <= order)
-	{
-             cpl_error_set_message(cpl_func,CPL_ERROR_INCOMPATIBLE_INPUT,
-                                   "Not enough frames for the polynomial"
-                                   " fitting. nsets = %d <= %d order",
-                                   nsets,order);
-	}
-	return cpl_error_get_code();
+    int nsets = 0;
+    int i = 0;
+    /* 1. Determine number of groups */
+    /*   cpl_msg_warning(cpl_func, "xsh_detmon_check_order sz[%i]", sz);*/
+    do
+    {
+        /*      cpl_msg_warning(cpl_func, "xsh_detmon_check_order i[%i] exptime[%g]", i, exptime[i]);   */
+        nsets++;
+        do
+        {
+            i++;
+            if(i == sz - 1)
+            {
+                break;
+            }
+        } while(fabs(exptime[i-1] - exptime[i]) < tolerance);
+    } while(i < sz - 1);
+    /* the very last adjustment for the last group */
+    if (!fabs(exptime[i-1] - exptime[i]) < tolerance) nsets++;
+    if(nsets <= order)
+    {
+        cpl_error_set_message(cpl_func,CPL_ERROR_INCOMPATIBLE_INPUT,
+                              "Not enough frames for the polynomial"
+                              " fitting. nsets = %d <= %d order",
+                              nsets,order);
+    }
+    return cpl_error_get_code();
 }
 
-static cpl_error_code xsh_detmon_lg_dfs_save_imagelist(
-		cpl_frameset * frameset,
-        const cpl_parameterlist * parlist,
-        const cpl_frameset *usedframes,
-        const cpl_imagelist *coeffs,
-        const char *recipe_name,
-        const cpl_propertylist *mypro_coeffscube,
-        const char * package,
-        const char * name_o)
+static cpl_error_code
+xsh_detmon_lg_dfs_save_imagelist(
+                             cpl_frameset * frameset,
+                             const cpl_parameterlist * parlist,
+                             const cpl_frameset *usedframes,
+                             const cpl_imagelist *coeffs,
+                             const char *recipe_name,
+                             const cpl_propertylist *mypro_coeffscube,
+                             const char * package,
+                             const char * name_o)
 {
-	   return(cpl_dfs_save_imagelist
-	       (frameset, NULL, parlist, usedframes, NULL,coeffs, CPL_BPP_IEEE_FLOAT,
-		recipe_name, mypro_coeffscube, NULL, package,
-		name_o));
+    return(cpl_dfs_save_imagelist
+           (frameset, NULL, parlist, usedframes, NULL,coeffs, CPL_BPP_IEEE_FLOAT,
+            recipe_name, mypro_coeffscube, NULL, package,
+            name_o));
 }
+
 static void xsh_detmon_lg_add_empty_image(cpl_imagelist* imlist, int pos)
 {
-	const cpl_image* first = cpl_imagelist_get(imlist, 0);
-	if (first)
-	{
-		  int x = cpl_image_get_size_x(first);
-		  int y = cpl_image_get_size_y(first);
-		  cpl_type type = cpl_image_get_type(first);
-		  cpl_image * blank = cpl_image_new(x, y, type);
-		  cpl_imagelist_set(imlist, blank, pos);
-	}
+    const cpl_image* first = cpl_imagelist_get(imlist, 0);
+    if (first)
+    {
+        int x = cpl_image_get_size_x(first);
+        int y = cpl_image_get_size_y(first);
+        cpl_type type = cpl_image_get_type(first);
+        cpl_image * blank = cpl_image_new(x, y, type);
+        cpl_imagelist_set(imlist, blank, pos);
+    }
+}
+
+
+cpl_error_code
+xsh_detmon_lg_set_tag(cpl_frameset* set, const char** tag_on, const char** tag_off)
+{
+    int ntag_old=0;
+    int ntag_new=0;
+
+    ntag_old=cpl_frameset_count_tags(set,DETMON_LG_ON_RAW_OLD);
+    ntag_new=cpl_frameset_count_tags(set,DETMON_LG_ON_RAW_NEW);
+    if(ntag_old) {
+        *tag_on=DETMON_LG_ON_RAW_OLD;
+        *tag_off=DETMON_LG_OFF_RAW_OLD;
+    } else if (ntag_new) {
+        *tag_on=DETMON_LG_ON_RAW_NEW;
+        *tag_off=DETMON_LG_OFF_RAW_NEW;
+    } else {
+        cpl_msg_error(cpl_func,"Provide %s and %s (or %s and %s) input frames",
+                      DETMON_LG_ON_RAW_NEW,DETMON_LG_OFF_RAW_NEW,
+                      DETMON_LG_ON_RAW_OLD,DETMON_LG_OFF_RAW_OLD);
+    }
+
+
+    return cpl_error_get_code();
 }
+/**@}*/
diff --git a/xsh/xsh_detmon_lg.h b/xsh/xsh_detmon_lg.h
index 3cc428c..c5ec655 100644
--- a/xsh/xsh_detmon_lg.h
+++ b/xsh/xsh_detmon_lg.h
@@ -1,4 +1,4 @@
-/* $Id: xsh_detmon_lg.h,v 1.16 2011-12-02 14:15:28 amodigli Exp $
+/* $Id: xsh_detmon_lg.h,v 1.4 2013-06-18 13:34:19 jtaylor Exp $
  *
  * This file is part of the irplib package
  * Copyright (C) 2002, 2003 European Southern Observatory
@@ -19,24 +19,31 @@
  */
 
 /*
- * $Author: amodigli $
- * $Date: 2011-12-02 14:15:28 $
- * $Revision: 1.16 $
+ * $Author: jtaylor $
+ * $Date: 2013-06-18 13:34:19 $
+ * $Revision: 1.4 $
  * $Name: not supported by cvs2svn $
  */
 
-#ifndef XSH_DETMON_LG_H
-#define XSH_DETMON_LG_H
+#ifndef XSH_IRPLIB_DETMON_LG_H
+#define XSH_IRPLIB_DETMON_LG_H
 
 /*----------------------------------------------------------------------------
                                    Includes
  ----------------------------------------------------------------------------*/
 
 #include <cpl.h>
+#include <xsh_cpl_size.h>
 
 /*----------------------------------------------------------------------------
                                    Prototypes
  ----------------------------------------------------------------------------*/
+/* Define here the DO.CATG keywords */
+#define DETMON_LG_ON_RAW_OLD                    "ON_RAW"
+#define DETMON_LG_OFF_RAW_OLD			"OFF_RAW"
+#define DETMON_LG_ON_RAW_NEW                    "DETMON_LAMP_ON"
+#define DETMON_LG_OFF_RAW_NEW			"DETMON_LAMP_OFF"
+
 
 #define NIR TRUE
 #define OPT FALSE
@@ -48,13 +55,13 @@
 #define DETMON_QC_COUNTS_MAX_C     "Maximum median value used in linearity test (in a user defined region) [ADU]"
 
 #define DETMON_QC_CONAD       "ESO QC CONAD"
-#define DETMON_QC_CONAD_C     "CONAD value [el/ADU]"
+#define DETMON_QC_CONAD_C     "Conversion from e- to ADUs [ADU/e-]"
 
 #define DETMON_QC_CONAD_CORR       "ESO QC CONAD CORR"
-#define DETMON_QC_CONAD_CORR_C     "CONAD value taken QC.AUTOCORR into account [el/ADU]"
+#define DETMON_QC_CONAD_CORR_C     "CONAD value taken QC.AUTOCORR into account [ADU/e-]"
 
 #define DETMON_QC_GAIN        "ESO QC GAIN"
-#define DETMON_QC_GAIN_C      "GAIN (see QC.METHOD) [ADU/el]"
+#define DETMON_QC_GAIN_C      "GAIN (see QC.METHOD) [e-/ADU]"
 
 #define DETMON_QC_GAIN_MSE    "ESO QC GAIN MSE"
 #define DETMON_QC_GAIN_MSE_C  "Measured Squared error in GAIN computation"
@@ -66,7 +73,7 @@
 #define DETMON_QC_AUTOCORR_C  "Autocorrelation factor computed as sum of " \
                               "all pixels in autocorrelation image"
 #define DETMON_QC_GAIN_CORR   "ESO QC GAIN CORR"
-#define DETMON_QC_GAIN_CORR_C "GAIN taken QC.AUTOCORR into account [el/ADU]"
+#define DETMON_QC_GAIN_CORR_C "GAIN taken QC.AUTOCORR into account [e-/ADU]"
 
 #define DETMON_QC_LAMP_FLUX   "ESO QC LAMP FLUX"
 #define DETMON_QC_LAMP_FLUX_C "Lamp flux"
@@ -109,23 +116,34 @@
 
 /* Macros to generate the recipe(s) description(s) */
 #define xsh_detmon_lg_get_description(RECIPE_NAME, PIPE_NAME,              \
-                                         DETMON_IR_LG_ON_RAW,                 \
-                                         DETMON_IR_LG_OFF_RAW)                \
+				  DETMON_LG_ON_RAW_NEW,                 \
+				  DETMON_LG_OFF_RAW_NEW,                \
+				  DETMON_LG_ON_RAW_OLD,                \
+                                  DETMON_LG_OFF_RAW_OLD)                \
     RECIPE_NAME " -- " PIPE_NAME " linearity/gain recipe for OPT/IR.\n"           \
     "The files listed in the Set Of Frames must be tagged:\n"                 \
-    "the raw-on-file.fits  "DETMON_IR_LG_ON_RAW"  and\n"                      \
-    "the raw-off-file.fits "DETMON_IR_LG_OFF_RAW"\n"                          \
+    "the raw-on-file.fits  "DETMON_LG_ON_RAW_NEW"  and\n"                      \
+    "the raw-off-file.fits "DETMON_LG_OFF_RAW_NEW"\n"                          \
+    "For backward compatibility are alternatively still supported the following tags:\n" \
+    "the raw-on-file.fits  "DETMON_LG_ON_RAW_OLD"  and\n"                      \
+    "the raw-off-file.fits "DETMON_LG_OFF_RAW_OLD"\n"                          \
     "The recipe requires at least order+1 valid pairs of ON frames\n"         \
     "and order+1 valid pairs of OFF frames, \n"                               \
     "where order is the value of the 'order' parameter.\n"                    \
-    "There is no requirement for pairs of OFF frames if collapse parameter"   \
+    "There is no requirement for pairs of OFF frames if collapse parameter "  \
     "is set to true.\n"                                                       \
-    "Frames with median flux over --filter will be excluded from the"         \
+    "Frames with median flux over --filter will be excluded from the "        \
     "computation.\n"                                                          \
-    "To perform a stability check you need frames with at least 2 DIT"        \
+    "To perform a stability check you need frames with at least 2 DIT "       \
     "values\n"                                                                \
-    "NOTE for multiextension cases: it is mandatory to modify the --exts"     \
-    "parameter, either to -1 (all extensions) or to any valid extension nb.\n"
+    "NOTE for multiextension cases: it is mandatory to modify the --exts "    \
+    "parameter, either to -1 (all extensions) or to any valid extension nb.\n" \
+    "\n" \
+    "The output PRO.CATG are:\n" \
+    "GAIN_INFO    - the gain table\n" \
+    "DET_LIN_INFO - the linearity table\n" \
+    "BP_MAP_NL    - the bad pixel map (only produced with --pix2pix=TRUE)\n" \
+    "COEFFS_CUBE  - the fit coefficient cube (only produced with --pix2pix=TRUE)\n"
 
 #define REGEXP "ARCFILE|MJD-OBS|ESO TPL ID|DATE-OBS|ESO DET DIT|ESO DET NDIT"
 
@@ -183,11 +201,21 @@ xsh_detmon_lg_fill_parlist_nir_default(cpl_parameterlist *,
                               const char        *);
 
 cpl_error_code
+xsh_detmon_lg_fill_parlist_nir_default_mr(cpl_parameterlist * parlist,
+                                      const char *recipe_name,
+                                      const char *pipeline_name);
+
+cpl_error_code
 xsh_detmon_lg_fill_parlist_opt_default(cpl_parameterlist *,
                               const char        *,
                               const char        *);
 
 cpl_error_code
+xsh_detmon_lg_fill_parlist_opt_default_mr(cpl_parameterlist * parlist,
+                                      const char *recipe_name,
+                                      const char *pipeline_name);
+
+cpl_error_code
 xsh_detmon_lg_fill_parlist(cpl_parameterlist * parlist,
                           const char *recipe_name, const char *pipeline_name,
 			  const char *method,
@@ -231,7 +259,7 @@ xsh_detmon_lg_fill_parlist(cpl_parameterlist * parlist,
                           int lly5,
                           int urx5,
                           int ury5,
-			      int exts,
+			               int exts,
                           cpl_boolean opt_nir);
 
 cpl_image *
@@ -275,4 +303,6 @@ xsh_detmon_lin(const cpl_imagelist  *,
 		  cpl_imagelist       **,
 		  cpl_image           **);
 
+cpl_error_code
+xsh_detmon_lg_set_tag(cpl_frameset* set, const char** tag_on, const char** tag_off);
 #endif
diff --git a/xsh/xsh_detmon_lg_impl.h b/xsh/xsh_detmon_lg_impl.h
index 25846d0..1eeeb1d 100644
--- a/xsh/xsh_detmon_lg_impl.h
+++ b/xsh/xsh_detmon_lg_impl.h
@@ -1,4 +1,4 @@
-/* $Id: xsh_detmon_lg_impl.h,v 1.4 2011-12-02 14:15:28 amodigli Exp $
+/* $Id: detmon_lg_impl.h,v 1.1 2011-11-02 13:14:23 amodigli Exp $
  *
  * This file is part of the irplib package
  * Copyright (C) 2002, 2003 European Southern Observatory
@@ -21,13 +21,10 @@
 
 /*
  * $Author: amodigli $
- * $Date: 2011-12-02 14:15:28 $
- * $Revision: 1.4 $
+ * $Date: 2011-11-02 13:14:23 $
+ * $Revision: 1.1 $
  * $Name: not supported by cvs2svn $
  * $Log: not supported by cvs2svn $
- * Revision 1.3  2009/12/11 08:47:21  amodigli
- * updated to latest delivery
- *
  * Revision 1.2  2009/08/17 15:10:16  kmirny
  *
  * DFS07454 DFS07437
@@ -36,8 +33,8 @@
  * DFS07454
  *
 */
-#ifndef IRPLIB_DETMON_LG_IMPL_H_
-#define IRPLIB_DETMON_LG_IMPL_H_
+#ifndef XSH_IRPLIB_DETMON_LG_IMPL_H_
+#define XSH_IRPLIB_DETMON_LG_IMPL_H_
 
 cpl_error_code
 xsh_detmon_pair_extract(const cpl_frameset *,
@@ -50,4 +47,4 @@ cpl_error_code
 xsh_detmon_check_order(const double *exptime, int sz, double tolerance, int order);
 
 
-#endif /* IRPLIB_DETMON_LG_IMPL_H_ */
+#endif /* XSH_IRPLIB_DETMON_LG_IMPL_H_ */
diff --git a/xsh/xsh_detmon_utils.c b/xsh/xsh_detmon_utils.c
new file mode 100644
index 0000000..04288f8
--- /dev/null
+++ b/xsh/xsh_detmon_utils.c
@@ -0,0 +1,277 @@
+/* $Id: xsh_detmon_utils.c,v 1.8 2013-07-15 12:03:32 amodigli Exp $
+ *
+ * This file is part of the IIINSTRUMENT Pipeline
+ * Copyright (C) 2002,2003 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
+ */
+
+/*
+ * $Author: amodigli $
+ * $Date: 2013-07-15 12:03:32 $
+ * $Revision: 1.8 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*-----------------------------------------------------------------------------
+   								Includes
+ -----------------------------------------------------------------------------*/
+
+#include "xsh_detmon_utils.h"
+#include "irplib_utils.h"
+
+#include <cpl.h>
+#include <assert.h>
+
+/**@{*/
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup iiinstrument_utils     Miscellaneous Utilities
+ */
+/*----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------*/
+/**
+  @brief	Get the pipeline copyright and license
+  @return   The copyright and license string
+
+  The function returns a pointer to the statically allocated license string.
+  This string should not be modified using the returned pointer.
+ */
+/*----------------------------------------------------------------------------*/
+const char * xsh_detmon_get_license(void)
+{
+    const char  *   xsh_detmon_license = 
+        "This file is part of the DETMON Instrument Pipeline\n"
+        "Copyright (C) 2002,2003 European Southern Observatory\n"
+        "\n"
+        "This program is free software; you can redistribute it and/or modify\n"
+        "it under the terms of the GNU General Public License as published by\n"
+        "the Free Software Foundation; either version 2 of the License, or\n"
+        "(at your option) any later version.\n"
+        "\n"
+        "This program is distributed in the hope that it will be useful,\n"
+        "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
+        "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
+        "GNU General Public License for more details.\n"
+        "\n"
+        "You should have received a copy of the GNU General Public License\n"
+        "along with this program; if not, write to the Free Software\n"
+        "Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, \n"
+        "MA  02111-1307  USA" ;
+    return xsh_detmon_license ;
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief utility to convert negative region to full image
+ *
+ * @param ref reference image, region set to image size
+ * @param llx  lower left X coordinate
+ * @param lly  lower left Y coordinate
+ * @param urx  upper right X coordinate
+ * @param ury  upper right Y coordinate
+ *
+ */
+/* ---------------------------------------------------------------------------*/
+static void expand_region(const cpl_image * ref,
+                          cpl_size * llx,
+                          cpl_size * lly,
+                          cpl_size * urx,
+                          cpl_size * ury)
+{
+    if (*llx < 1)
+        *llx = 1;
+    if (*lly < 1)
+        *lly = 1;
+    if (*urx < 1)
+        *urx = cpl_image_get_size_x(ref);
+    if (*ury < 1)
+        *ury = cpl_image_get_size_y(ref);
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief load data in frameset into an imagelist
+ *
+ * @param fset   frameset to load from
+ * @param type   type to convert data to
+ * @param pnum   plane number in cube to load (0 for first)
+ * @param xtnum  extension in file to load (0 for first, -1 for all)
+ * @param llx    lower left x
+ * @param lly    lower left y
+ * @param urx    upper right x
+ * @param ury    upper right y
+ * @param nx     output image size x
+ * @param ny     output image size y
+ *
+ * @return imagelist of loaded images padded to nx/ny
+ * @note pads images with zeros to output image size
+ *       unlike cpl_imagelist_frameset_load no support for
+ *       loading multiple planes
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_imagelist *
+xsh_detmon_load_frameset_window(const cpl_frameset * fset, cpl_type type,
+                            cpl_size pnum, cpl_size xtnum,
+                            cpl_size llx, cpl_size lly,
+                            cpl_size urx, cpl_size ury,
+                            cpl_size nx, cpl_size ny)
+{
+    cpl_imagelist * list = cpl_imagelist_new();
+    const size_t n = cpl_frameset_get_size(fset);
+    skip_if(pnum < 0);
+    if (nx >= 0 && ny >= 0) {
+        error_if(urx - llx + 1 > nx || ury - lly + 1 > ny ,
+                 CPL_ERROR_ILLEGAL_INPUT,
+                 "window size [%d:%d,%d:%d] larger than output size [%d, %d]",
+                 (int)llx, (int)urx, (int)lly, (int)ury, (int)nx, (int)ny);
+    }
+
+    for (size_t i = 0; i < n; i++) {
+        const cpl_frame * frm = cpl_frameset_get_position_const(fset, i);
+        const char * fn = cpl_frame_get_filename(frm);
+        if (xtnum  < 0) {
+            cpl_size next = cpl_frame_get_nextensions(frm);
+            for (size_t e = 0; e < next; e++) {
+                cpl_image * image = cpl_image_load_window(fn, type, pnum, e,
+                                                          llx, lly, urx, ury);
+                skip_if(image == NULL);
+                if(nx < 0 || ny < 0 ) {
+                   cpl_imagelist_set(list, image, cpl_imagelist_get_size(list));
+                } else {
+                   cpl_image * full = cpl_image_new(nx, ny, type);
+                   cpl_image_copy(full, image, llx, lly);
+                   cpl_image_delete(image);
+                   cpl_imagelist_set(list, full, cpl_imagelist_get_size(list));
+                }
+
+            }
+        }
+        else {
+            cpl_image * image = cpl_image_load_window(fn, type, pnum, xtnum,
+                                                      llx, lly, urx, ury);
+            skip_if(image == NULL);
+            if(nx < 0 || ny < 0 ) {
+                cpl_imagelist_set(list, image, cpl_imagelist_get_size(list));
+            } else {
+                cpl_image * full = cpl_image_new(nx, ny, type);
+                cpl_image_copy(full, image, llx, lly);
+                cpl_image_delete(image);
+                cpl_imagelist_set(list, full, cpl_imagelist_get_size(list));
+            }
+        }
+    }
+
+    end_skip;
+
+    if (cpl_error_get_code()) {
+        cpl_imagelist_delete(list);
+        return NULL;
+    }
+
+    return list;
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief subtract window two images creating new image of window size
+ *
+ * @param a image
+ * @param b image
+ * @param llx  lower left X coordinate
+ * @param lly  lower left Y coordinate
+ * @param urx  upper right X coordinate
+ * @param ury  upper right Y coordinate
+ *
+ * @return image of window size
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_image * xsh_detmon_subtract_create_window(const cpl_image * a,
+                                          const cpl_image * b,
+                                          cpl_size llx,
+                                          cpl_size lly,
+                                          cpl_size urx,
+                                          cpl_size ury)
+{
+    cpl_image * na = cpl_image_extract(a, llx, lly, urx, ury);
+    cpl_image * nb = cpl_image_extract(b, llx, lly, urx, ury);
+    cpl_image_subtract(na, nb);
+    cpl_image_delete(nb);
+
+    return na;
+}
+
+
+/* ---------------------------------------------------------------------------*/
+/**
+ * @brief return absolute average of subtracted images
+ *
+ * @param on1  first on image
+ * @param off1 first off image
+ * @param on2  second on image
+ * @param off2 second off image
+ * @param off2 second off image
+ * @param llx  lower left X coordinate
+ * @param lly  lower left Y coordinate
+ * @param urx  upper right X coordinate
+ * @param ury  upper right Y coordinate
+ *
+ * @return abs(avg((on1 - off1), (on2 - off2)))
+ */
+/* ---------------------------------------------------------------------------*/
+cpl_image * xsh_detmon_subtracted_avg(const cpl_image * on1,
+                                  const cpl_image * off1,
+                                  const cpl_image * on2,
+                                  const cpl_image * off2,
+                                  cpl_size llx, cpl_size lly,
+                                  cpl_size urx, cpl_size ury)
+{
+    expand_region(on1, &llx, &lly, &urx, &ury);
+    cpl_image * dif1 = cpl_image_extract(on1, llx, lly, urx, ury);
+    cpl_image * dif2 = cpl_image_extract(on2, llx, lly, urx, ury);
+    cpl_image * b = cpl_image_extract(off1, llx, lly, urx, ury);
+    cpl_image * dif_avg;
+
+    cpl_image_subtract(dif1, b);
+    if (off1 != off2) {
+        cpl_image_delete(b);
+        b = cpl_image_extract(off2, llx, lly, urx, ury);
+        cpl_image_subtract(dif1, b);
+    }
+    else {
+        cpl_image_subtract(dif2, b);
+    }
+    cpl_image_delete(b);
+
+    dif_avg = cpl_image_average_create(dif1, dif2);
+    cpl_image_abs(dif_avg);
+
+    cpl_image_delete(dif1);
+    cpl_image_delete(dif2);
+
+    return dif_avg;
+}
+
+/**@}*/
+
diff --git a/xsh/xsh_detmon_utils.h b/xsh/xsh_detmon_utils.h
new file mode 100644
index 0000000..00ee3df
--- /dev/null
+++ b/xsh/xsh_detmon_utils.h
@@ -0,0 +1,64 @@
+/* $Id: detmon_utils.h,v 1.5 2013-07-05 12:51:21 jtaylor Exp $
+ *
+ * This file is part of the IIINSTRUMENT Pipeline
+ * Copyright (C) 2002,2003 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-07-05 12:51:21 $
+ * $Revision: 1.5 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifndef XSH_DETMON_UTILS_H
+#define XSH_DETMON_UTILS_H
+
+/*-----------------------------------------------------------------------------
+   								Includes
+ -----------------------------------------------------------------------------*/
+
+#include <cpl.h>
+
+/*-----------------------------------------------------------------------------
+   							        Prototypes
+ -----------------------------------------------------------------------------*/
+
+const char * xsh_detmon_get_license(void) ;
+
+cpl_imagelist *
+xsh_detmon_load_frameset_window(const cpl_frameset * fset, cpl_type type,
+                            cpl_size pnum, cpl_size xtnum,
+                            cpl_size llx, cpl_size lly,
+                            cpl_size urx, cpl_size ury,
+                            cpl_size nx, cpl_size ny);
+
+cpl_image * xsh_detmon_subtract_create_window(const cpl_image * a,
+                                          const cpl_image * b,
+                                          cpl_size llx,
+                                          cpl_size lly,
+                                          cpl_size urx,
+                                          cpl_size ury);
+
+cpl_image * xsh_detmon_subtracted_avg(const cpl_image * on1,
+                                  const cpl_image * off1,
+                                  const cpl_image * on2,
+                                  const cpl_image * off2,
+                                  cpl_size llx, cpl_size lly,
+                                  cpl_size urx, cpl_size ury);
+
+#endif
diff --git a/xsh/xsh_dfs.c b/xsh/xsh_dfs.c
index ab84f46..3ce8c83 100644
--- a/xsh/xsh_dfs.c
+++ b/xsh/xsh_dfs.c
@@ -51,6 +51,7 @@
 #include <cpl.h>
 #include <stdio.h>
 #include <string.h>
+#include <strings.h>
 #include <time.h>
 #include <math.h>
 #include <assert.h>
@@ -235,8 +236,8 @@ int xsh_dfs_files_dont_exist(cpl_frameset *frameset)
         return 0;
     }
 
-    frame = cpl_frameset_get_first(frameset);
-
+    cpl_frameset_iterator* it = cpl_frameset_iterator_new(frameset);
+    frame = cpl_frameset_iterator_get(it);
     while (frame) {
         if (access(cpl_frame_get_filename(frame), F_OK)) {
             cpl_msg_error(func, "File %s (%s) was not found", 
@@ -244,9 +245,10 @@ int xsh_dfs_files_dont_exist(cpl_frameset *frameset)
                           cpl_frame_get_tag(frame));
             cpl_error_set(func, CPL_ERROR_FILE_NOT_FOUND);
         }
-
-        frame = cpl_frameset_get_next(frameset);
+        cpl_frameset_iterator_advance(it, 1);
+        frame = cpl_frameset_iterator_get(it);
     }
+    cpl_frameset_iterator_delete(it);
 
     if (cpl_error_get_code())
         return 1;
@@ -984,14 +986,18 @@ xsh_frameset_merge(cpl_frameset * set1, cpl_frameset* set2)
 
    passure(set1 != NULL, "Wrong input set");
   
-   check(frm_tmp = cpl_frameset_get_first(set2));
+   cpl_frameset_iterator* it = cpl_frameset_iterator_new(set2);
+   frm_tmp = cpl_frameset_iterator_get(it);
+
    while (frm_tmp != NULL)
    {
       frm_dup=cpl_frame_duplicate(frm_tmp);
       cpl_frameset_insert(set1,frm_dup);
-      frm_tmp = cpl_frameset_get_next(set2);
-   }
+      cpl_frameset_iterator_advance(it, 1);
+      frm_tmp = cpl_frameset_iterator_get(it);
 
+   }
+   cpl_frameset_iterator_delete(it);
   cleanup:
    return cpl_error_get_code();
 }
@@ -1008,7 +1014,8 @@ xsh_instrument* xsh_dfs_set_groups (cpl_frameset * set)
 {
   cpl_frame * cur_frame = NULL;
   xsh_instrument* instrument = NULL;
-
+  int i;
+  int nfrm;
   /* Check entries */
   assure (set != NULL, CPL_ERROR_NULL_INPUT, "Null frame set");
   assure (!cpl_frameset_is_empty(set),CPL_ERROR_ILLEGAL_INPUT,
@@ -1016,13 +1023,11 @@ xsh_instrument* xsh_dfs_set_groups (cpl_frameset * set)
 		  
   /* allocate instrument structure */
   instrument = xsh_instrument_new();
-  
+  nfrm=cpl_frameset_get_size(set);
   /* Loop on frames */
-  for (cur_frame = cpl_frameset_get_first (set);
-       cur_frame != NULL; 
-       cur_frame = cpl_frameset_get_next (set)) {
+  for (i = 0; i<nfrm; i++) {
     const char *tag = NULL;
-
+    cur_frame=cpl_frameset_get_frame(set,i);
     check(tag = cpl_frame_get_tag (cur_frame));
 
     /* SET GROUP */
@@ -1079,10 +1084,12 @@ cpl_error_code
 xsh_dfs_extract_raw_frames (cpl_frameset * input, cpl_frameset * raws)
 {
   cpl_frame *cur_frame = NULL;
-
+  int i=0;
+  int nfrm=0;
   /* Loop on frames */
-  for (cur_frame = cpl_frameset_get_first (input);
-       cur_frame != NULL; cur_frame = cpl_frameset_get_next (input)) {
+  nfrm=cpl_frameset_get_size(input);
+  for (i=0; i < nfrm; i++) {
+      cur_frame=cpl_frameset_get_frame(input,i);
     /* RAW frames */
     if (cpl_frame_get_group (cur_frame) == CPL_FRAME_GROUP_RAW) {
       cpl_frameset_insert (raws, cpl_frame_duplicate(cur_frame));
@@ -1104,10 +1111,13 @@ cpl_error_code
 xsh_dfs_extract_calib_frames (cpl_frameset * input, cpl_frameset * calib)
 {
   cpl_frame *cur_frame = NULL;
-
+  int i;
+  int nfrm;
   /* Loop on frames */
-  for (cur_frame = cpl_frameset_get_first (input);
-       cur_frame != NULL; cur_frame = cpl_frameset_get_next (input)) {
+  nfrm=cpl_frameset_get_size(input);
+
+  for (i = 0; i< nfrm; i++) {
+    cur_frame=cpl_frameset_get_frame(input,i);
     /* RAW frames */
     if (cpl_frame_get_group (cur_frame) == CPL_FRAME_GROUP_CALIB) {
       cpl_frameset_insert (calib, cpl_frame_duplicate(cur_frame));
@@ -1130,10 +1140,13 @@ cpl_error_code
 xsh_dfs_extract_pro_frames (cpl_frameset * input, cpl_frameset * pros)
 {
   cpl_frame *cur_frame = NULL;
+  int i=0;
+  int nfrm=0;
   XSH_ASSURE_NOT_NULL_MSG(pros,"Null pros frameset. Alllocated it outside!");
   /* Loop on frames */
-  for (cur_frame = cpl_frameset_get_first (input);
-       cur_frame != NULL; cur_frame = cpl_frameset_get_next (input)) {
+  nfrm=cpl_frameset_get_size(input);
+  for (i=0;i<nfrm; i++) {
+      cur_frame=cpl_frameset_get_frame(input,i);
     /* PRO frames */
     if (cpl_frame_get_group (cur_frame) == CPL_FRAME_GROUP_PRODUCT) {
       cpl_frameset_insert (pros, cpl_frame_duplicate(cur_frame));
@@ -1157,10 +1170,13 @@ xsh_dfs_split_in_group (cpl_frameset * input, cpl_frameset * raws,
 			cpl_frameset * calib)
 {
   cpl_frame *cur_frame = NULL;
-
+  int i=0;
+  int nfrm=0;
   /* Loop on frames */
-  for (cur_frame = cpl_frameset_get_first (input);
-       cur_frame != NULL; cur_frame = cpl_frameset_get_next (input)) {
+  nfrm=cpl_frameset_get_size(input);
+
+  for (i = 0; i < nfrm; i++) {
+      cur_frame=cpl_frameset_get_frame(input,i);
     /* RAW frames */
     if (cpl_frame_get_group (cur_frame) == CPL_FRAME_GROUP_RAW) {
       //xsh_dfs_check_nan(cur_frame);
@@ -1195,7 +1211,8 @@ xsh_dfs_split_qth_d2(cpl_frameset * input,
 {
   cpl_frame* cur_frame = NULL;
   cpl_frame* temp =NULL;
-
+  int i=0;
+  int nfrm=0;
   /* check parameters input */
   XSH_ASSURE_NOT_NULL( input);
   XSH_ASSURE_NOT_NULL( qth);
@@ -1205,11 +1222,11 @@ xsh_dfs_split_qth_d2(cpl_frameset * input,
   XSH_NEW_FRAMESET( *qth);
   XSH_NEW_FRAMESET( *d2);
 
+  nfrm=cpl_frameset_get_size(input);
   /* Loop on frames */
-  for (cur_frame = cpl_frameset_get_first (input);
-       cur_frame != NULL; cur_frame = cpl_frameset_get_next (input)) {
+  for (i = 0; i < nfrm; i++) {
     const char* tag = NULL;
-
+    cur_frame=cpl_frameset_get_frame(input,i);
     check(tag = cpl_frame_get_tag(cur_frame));
     /* ON frames */
     if ( strstr(tag,"D2") != NULL) {
@@ -1249,7 +1266,8 @@ void xsh_dfs_split_nir(cpl_frameset * input, cpl_frameset** on,
 {
   cpl_frame* cur_frame = NULL;
   cpl_frame* temp =NULL;
-
+  int i=0;
+  int nfrm=0;
   /* check parameters input */
   XSH_ASSURE_NOT_NULL(input);
   XSH_ASSURE_NOT_NULL(on);
@@ -1258,12 +1276,11 @@ void xsh_dfs_split_nir(cpl_frameset * input, cpl_frameset** on,
   /* create frameset */
   XSH_NEW_FRAMESET(*on);
   XSH_NEW_FRAMESET(*off);
- 
+  nfrm=cpl_frameset_get_size(input);
   /* Loop on frames */
-  for (cur_frame = cpl_frameset_get_first (input);
-       cur_frame != NULL; cur_frame = cpl_frameset_get_next (input)) {
+  for (i = 0; i< nfrm ; i++) {
     const char* tag = NULL;
-
+    cur_frame = cpl_frameset_get_frame(input,i);
     check(tag = cpl_frame_get_tag(cur_frame));
     /* ON frames */
     if ( strstr(tag,"ON") != NULL) {
@@ -1313,7 +1330,8 @@ xsh_dfs_split_offset(cpl_frameset * input,
   cpl_frame* cur_frame = NULL;
   cpl_frame* temp =NULL;
   int nobj = 0, nsky = 0 ;
-
+  int i=0;
+  int nfrm=0;
   /* check parameters input */
   XSH_ASSURE_NOT_NULL(input);
   XSH_ASSURE_NOT_NULL(object);
@@ -1322,11 +1340,11 @@ xsh_dfs_split_offset(cpl_frameset * input,
   /* create frameset */
   *object=cpl_frameset_new();
   *sky=cpl_frameset_new();
-
+  nfrm=cpl_frameset_get_size(input);
   /* Loop on frames */
-  for (cur_frame = cpl_frameset_get_first (input);
-       cur_frame != NULL; cur_frame = cpl_frameset_get_next (input)) {
+  for (i = 0; i < nfrm; i++ ) {
     const char* tag = NULL;
+    cur_frame=cpl_frameset_get_frame(input,i);
 
     check(tag = cpl_frame_get_tag(cur_frame));
     /* OBJECT frames */
@@ -1464,7 +1482,8 @@ xsh_dfs_filter( cpl_frameset * set, const char* tags[], int size){
   XSH_ASSURE_NOT_ILLEGAL( size > 0);
 
   /* Loop on frames */
-  check( cur_frame = cpl_frameset_get_first (set));
+  cpl_frameset_iterator* it = cpl_frameset_iterator_new(set);
+  cur_frame = cpl_frameset_iterator_get(it);
 
   while(cur_frame != NULL){
     const char* ftag = NULL;
@@ -1474,13 +1493,17 @@ xsh_dfs_filter( cpl_frameset * set, const char* tags[], int size){
       cpl_frame *del_frame = NULL;
       
       del_frame = cur_frame;
-      check( cur_frame = cpl_frameset_get_next( set));
+      cpl_frameset_iterator_advance(it, 1);
+      cur_frame = cpl_frameset_iterator_get(it);
+
       check( cpl_frameset_erase_frame( set, del_frame));
     }
     else{
-      check(cur_frame = cpl_frameset_get_next (set));
+      cpl_frameset_iterator_advance(it, 1);
+      cur_frame = cpl_frameset_iterator_get(it);
     }  
   }
+  cpl_frameset_iterator_delete(it);
 
   cleanup:
     return;
@@ -1538,10 +1561,13 @@ cpl_frame *
 xsh_find_bpmap (cpl_frameset * set)
 {
   cpl_frame *cur_frame = NULL;
+  int i=0;
+  int nfrm=0;
 
+  nfrm=cpl_frameset_get_size(set);
   /* Loop on frames */
-  for (cur_frame = cpl_frameset_get_first (set);
-       cur_frame != NULL; cur_frame = cpl_frameset_get_next (set)) {
+  for (i = 0; i < nfrm; i++) {
+    cur_frame = cpl_frameset_get_frame(set,i);
     if (strstr (cpl_frame_get_tag (cur_frame), "BADPIXEL_MAP")) {
       return cur_frame;
     }
@@ -1561,10 +1587,13 @@ cpl_frame *
 xsh_find_master_bpmap (cpl_frameset * set)
 {
   cpl_frame *cur_frame = NULL;
+  int i=0;
+  int nfrm=0;
 
+  nfrm=cpl_frameset_get_size(set);
   /* Loop on frames */
-  for (cur_frame = cpl_frameset_get_first (set);
-       cur_frame != NULL; cur_frame = cpl_frameset_get_next (set)) {
+  for (i = 0; i < nfrm; i++) {
+      cur_frame=cpl_frameset_get_frame(set,i);
     if (strstr (cpl_frame_get_tag (cur_frame), XSH_MASTER_BP_MAP)) {
       return cur_frame;
     }
@@ -1582,10 +1611,13 @@ xsh_find_master_bpmap (cpl_frameset * set)
 cpl_frame * xsh_find_off(cpl_frameset* set)
 {
   cpl_frame *cur_frame = NULL;
+  int i=0;
+  int nfrm=0;
 
+  nfrm=cpl_frameset_get_size(set);
   /* Loop on frames */
-  for (cur_frame = cpl_frameset_get_first (set);
-       cur_frame != NULL; cur_frame = cpl_frameset_get_next (set)) {
+  for (i=0;i<nfrm; i++) {
+      cur_frame=cpl_frameset_get_frame(set,i);
     if (strstr (cpl_frame_get_tag (cur_frame), "OFF")) {
       return cur_frame;
     }
@@ -1603,10 +1635,12 @@ cpl_frame * xsh_find_off(cpl_frameset* set)
 cpl_frame * xsh_find_on(cpl_frameset* set)
 {
   cpl_frame *cur_frame = NULL;
-
+  int i=0;
+  int nfrm=0;
+  nfrm=cpl_frameset_get_size(set);
   /* Loop on frames */
-  for (cur_frame = cpl_frameset_get_first (set);
-       cur_frame != NULL; cur_frame = cpl_frameset_get_next (set)) {
+  for (i = 0; i< nfrm; i++) {
+      cur_frame=cpl_frameset_get_frame(set,i);
     if (strstr (cpl_frame_get_tag (cur_frame), "ON")) {
       return cur_frame;
     }
@@ -1626,17 +1660,19 @@ xsh_dfs_find_flat(cpl_frameset* raws,cpl_frameset* flat)
 {
   cpl_frame *cur_frame = NULL;
   const char* tag = NULL;
+  int i=0;
+  int nfrm=0;
+
   /* check input */
   assure (raws != NULL, CPL_ERROR_NULL_INPUT, "Null frameset");
   assure (flat != NULL, CPL_ERROR_NULL_INPUT, "Null frameset");
   
   /* init */
-  tag = cpl_frame_get_tag(cpl_frameset_get_first(raws)); 
-  
+  nfrm=cpl_frameset_get_size(raws);
   /* Loop on frames */
-  for (cur_frame = cpl_frameset_get_first (raws);
-       cur_frame != NULL; cur_frame = cpl_frameset_get_next (raws))
+  for (i = 0; i < nfrm; i++)
     {
+      cur_frame=cpl_frameset_get_frame(raws,i);
       tag = cpl_frame_get_tag (cur_frame);
       if (strstr(tag,"FLAT")!=NULL)
 	cpl_frameset_insert (flat, cur_frame);
@@ -4793,6 +4829,32 @@ static const char * xsh_get_column_unit(cpl_propertylist * header,
   if (! cpl_errorstate_is_equal(prestate)) return NULL;
   return column_unit;
 }
+/**
+ * @internal
+ * @brief Calculates number of raw frames.
+ *
+ * @param frames  The list of used frames to check.
+*/
+static int xsh_get_nraws(const cpl_frameset* frames)
+{
+    cpl_frameset_iterator* iter = NULL;
+    int counter=0;
+    iter = cpl_frameset_iterator_new(frames);
+    const cpl_frame* frame = cpl_frameset_iterator_get_const(iter);
+    while (frame != NULL) {
+        if (cpl_frame_get_group(frame) == CPL_FRAME_GROUP_RAW) {
+            counter++;
+        }
+        cpl_errorstate status = cpl_errorstate_get();
+        cpl_frameset_iterator_advance(iter, 1);
+        if (cpl_error_get_code() == CPL_ERROR_ACCESS_OUT_OF_RANGE) {
+              cpl_errorstate_set(status);
+        }
+        frame = cpl_frameset_iterator_get_const(iter);
+    }
+    cpl_frameset_iterator_delete(iter);
+    return counter;
+}
 
 /**
  * @internal
@@ -4835,6 +4897,7 @@ static double xsh_calculate_mjd_end(const cpl_frame *product_frame,
       /* Extract the MJD-OBS and EXPTIME keywords and update the mjdend
        * candidate. */
       double obsval, expval, total, dit;
+      double factor=1./(86400.);
       int ndit, nditskip;
       check(obsval = cpl_propertylist_get_double(keywords, XSH_MJDOBS));
       switch (arm) {
@@ -4855,8 +4918,9 @@ static double xsh_calculate_mjd_end(const cpl_frame *product_frame,
           check(expval = cpl_propertylist_get_double(keywords, XSH_EXPTIME));
           break;
       }
-      total = obsval + expval / (60.0*60.0*24.0);
+      total = obsval + expval * factor;
       if (total > mjdend) mjdend = total;
+
     }
     /* Increment the iterator to the next frame. */
     cpl_errorstate status = cpl_errorstate_get();
@@ -4868,6 +4932,7 @@ static double xsh_calculate_mjd_end(const cpl_frame *product_frame,
   }
 
 cleanup:
+
   cpl_frameset_iterator_delete(iter);
   cpl_propertylist_delete(keywords);
   return mjdend;
@@ -5292,6 +5357,7 @@ static cpl_error_code xsh_sdp_spectrum_create(
   prestate = cpl_errorstate_get();
   double mjdobs = cpl_propertylist_get_double(sourcekeys, XSH_MJDOBS);
   double mjdend = cpl_propertylist_get_double(sourcekeys, XSH_MJDEND);
+
   if (cpl_errorstate_is_equal(prestate)) {
     error |= irplib_sdp_spectrum_set_mjdobs(sdp_spectrum, mjdobs);
     error |= irplib_sdp_spectrum_set_mjdend(sdp_spectrum, mjdend);
@@ -5571,8 +5637,33 @@ static cpl_error_code xsh_sdp_spectrum_create(
 
   /* Calculate the TELAPSE and TMID keywords from MJD-OBS and MJD-END. */
   if (! isnan(mjdobs) && ! isnan(mjdend)) {
-    error |= irplib_sdp_spectrum_set_telapse(sdp_spectrum,
-                                             (mjdend - mjdobs) * 86400.);
+      int nframes=xsh_get_nraws(usedframes);
+      if(nframes==1) {
+          /* this is a special case for which to prevent rounding errors due to
+           * the very small difference MJDEND - MJDSTART, and using the fact that
+           * MJDEND - MJDSTART= EXPTIME (or DIT*NDIT) we compute TELAPSE as
+           * TELAPSE=EXPTIME (UVB,VIS) or TELAPSE=DIT*NDIT
+           */
+          double telapse;
+          if( xsh_instrument_get_arm(instrument) == XSH_ARM_NIR ) {
+              double dit = cpl_propertylist_get_double(sourcekeys, XSH_DET_DIT);
+              int ndit = cpl_propertylist_get_int(sourcekeys, XSH_DET_NDIT);
+              int nditskip = cpl_propertylist_get_int(sourcekeys,XSH_DET_NDITSKIP);
+              if (nditskip == 0) {
+                  telapse = dit * ndit;
+              } else {
+                  xsh_msg_warning("Found '%s' with a non zero value. Do not know how"
+                                  " to handle this case so will over estimate '%s'.",
+                                  XSH_DET_NDITSKIP, XSH_MJDEND);
+              }
+          } else {
+              telapse = cpl_propertylist_get_double(sourcekeys, XSH_EXPTIME);
+          }
+          error |= irplib_sdp_spectrum_set_telapse(sdp_spectrum,telapse);
+      } else {
+          error |= irplib_sdp_spectrum_set_telapse(sdp_spectrum,
+                          (mjdend - mjdobs) * 86400.);
+      }
     error |= irplib_sdp_spectrum_set_tmid(sdp_spectrum,
                                           (mjdend + mjdobs) * 0.5);
   } else {
diff --git a/xsh/xsh_drl_check.c b/xsh/xsh_drl_check.c
index 164db04..bae9fea 100644
--- a/xsh/xsh_drl_check.c
+++ b/xsh/xsh_drl_check.c
@@ -276,7 +276,7 @@ cpl_frame* xsh_check_remove_crh_multiple( cpl_frameset* raws,
 
   }
   else {
-    check( result = cpl_frame_duplicate(cpl_frameset_get_first( raws)));
+    check( result = cpl_frame_duplicate(cpl_frameset_get_frame( raws,0)));
   }
   cleanup:
     return result;
diff --git a/xsh/xsh_dump.c b/xsh/xsh_dump.c
index 4b11b0e..e1b7f4b 100644
--- a/xsh/xsh_dump.c
+++ b/xsh/xsh_dump.c
@@ -206,8 +206,9 @@ xsh_print_cpl_frameset (cpl_frameset * frames)
     xsh_msg ("NULL");
   }
   else {
-    cpl_frame *f = NULL;
-    check (f = cpl_frameset_get_first (frames));
+    const cpl_frame *f = NULL;
+    cpl_frameset_iterator* it = cpl_frameset_iterator_new(frames);
+    f = cpl_frameset_iterator_get(it);
 
     if (f == NULL) {
       xsh_msg ("[Empty frame set]");
@@ -215,13 +216,17 @@ xsh_print_cpl_frameset (cpl_frameset * frames)
     else {
       do {
 	check (xsh_print_cpl_frame (f));
-	check (f = cpl_frameset_get_next (frames));
+	cpl_frameset_iterator_advance(it, 1);
+	f = cpl_frameset_iterator_get_const(it);
+
       }
       while (f != NULL);
     }
+    cpl_frameset_iterator_delete(it);
   }
 
 cleanup:
+
   return cpl_error_get_code ();
 }
 
diff --git a/xsh/xsh_flexcor.c b/xsh/xsh_flexcor.c
index f365e80..87229f6 100644
--- a/xsh/xsh_flexcor.c
+++ b/xsh/xsh_flexcor.c
@@ -257,7 +257,8 @@ cpl_frame* xsh_flexcor( cpl_frame* afc_frame,
       /* The result of pipe_anneal is a frame, so we need to extract the
 	 config_model data structure to be consistent with what was done
 	 for the other arms */
-      check( xsh_model_config_load_best(model_config_frame, &config_model));
+      check( xsh_model_config_load_best(MODEL_CONF_OPT_frame, &config_model));
+
     }
 
     xsh_msg("file name=%s",cpl_frame_get_filename(model_config_frame));
diff --git a/xsh/xsh_follow_arclines.c b/xsh/xsh_follow_arclines.c
index 3554423..8b76192 100644
--- a/xsh/xsh_follow_arclines.c
+++ b/xsh/xsh_follow_arclines.c
@@ -745,6 +745,10 @@ set_qc_parameters( cpl_propertylist *tilt_header,
   check( xsh_pfits_set_qc( tilt_header, &n, QC_WAVECAL_FOUNDLINE,
                            instrument));
   check( xsh_pfits_set_qc( tilt_header, &specres_med, QC_RESOLMED, instrument));
+  if(isnan(specres_stdev)) {
+      /* dummy value to allow saving of product */
+      specres_stdev = -999;
+  }
   check( xsh_pfits_set_qc( tilt_header, &specres_stdev, QC_RESOLRMS, instrument));
 
 
diff --git a/xsh/xsh_hdrl_functions.c b/xsh/xsh_hdrl_functions.c
new file mode 100644
index 0000000..2690870
--- /dev/null
+++ b/xsh/xsh_hdrl_functions.c
@@ -0,0 +1,139 @@
+/*                                                                            *
+ *   This file is part of the ESO X-shooter Pipeline                          *
+ *   Copyright (C) 2006 European Southern Observatory                         *
+ *                                                                            *
+ *   This library is free software; you can redistribute it and/or modify     *
+ *   it under the terms of the GNU General Public License as published by     *
+ *   the Free Software Foundation; either version 2 of the License, or        *
+ *   (at your option) any later version.                                      *
+ *                                                                            *
+ *   This program is distributed in the hope that it will be useful,          *
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of           *
+ *   MERCHANTABILITY or F1ITNESS FOR A PARTICULAR PURPOSE.  See the           *
+ *   GNU General Public License for more details.                             *
+ *                                                                            *
+ *   You should have received a copy of the GNU General Public License        *
+ *   along with this program; if not, write to the Free Software              *
+ *   Foundation, 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA     *
+ *                                                                            */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+/*----------------------------------------------------------------------------*/
+/**
+ * @defgroup xsh_rectify  Rectify Image
+ * @ingroup drl_functions
+ *
+ * Function ...
+ */
+/*----------------------------------------------------------------------------*/
+/**@{*/
+
+/*-----------------------------------------------------------------------------
+  Includes
+  ----------------------------------------------------------------------------*/
+#include <xsh_hdrl_functions.h>
+
+#include <cpl.h>
+#include <hdrl.h>
+
+#include <xsh_msg.h>
+#include <xsh_dfs.h>
+
+#include <xsh_error.h>
+#include <xsh_qc_handling.h>
+
+/* This should be defined in a more clever way, a parameter for example */
+#define REGDEBUG_FULL 0
+
+cpl_frame*
+xsh_hdrl_remove_crh_single( cpl_frame* frm,
+                       xsh_instrument* instrument,
+                       xsh_remove_crh_single_param *  crh_single_par,
+                       const char* ftag ) {
+
+    double sigma_lim, f_lim;
+    int max_iter;
+    xsh_pre* inp_pre = NULL; /**< Input PRE */
+    xsh_pre* out_pre = NULL; /**< Result PRE */
+    cpl_frame* res_frame;
+    cpl_mask* result_mask;
+    cpl_image* img_data;
+    cpl_image* img_errs;
+    cpl_image* img_mask;
+
+    /* Check parameters */
+    XSH_ASSURE_NOT_NULL_MSG( frm,"Null input science frame" );
+    XSH_ASSURE_NOT_NULL_MSG( instrument,"Null instrument setting" );
+    XSH_ASSURE_NOT_NULL_MSG( crh_single_par,"Null input parameters" );
+    XSH_ASSURE_NOT_NULL_MSG( ftag,"Null input parameters" );
+
+    sigma_lim = crh_single_par->sigma_lim;
+    f_lim = crh_single_par->f_lim;
+    max_iter = crh_single_par->nb_iter;
+    xsh_msg_dbg_high("  Params: sigma_lim %.2f f_lim %.2f, iter %d",
+                     sigma_lim, f_lim, max_iter);
+
+    check( inp_pre = xsh_pre_load( frm, instrument));
+    check( out_pre = xsh_pre_duplicate( inp_pre ) );
+    check( img_data = xsh_pre_get_data( out_pre));
+    check( img_errs = xsh_pre_get_errs( out_pre));
+    check( img_mask = xsh_pre_get_qual( out_pre));
+
+
+    // XSH has image data in FLOAT!!
+    cpl_image* d_data=cpl_image_cast(img_data,CPL_TYPE_DOUBLE);
+    cpl_image* d_errs=cpl_image_cast(img_errs,CPL_TYPE_DOUBLE);
+
+
+    cpl_image_set_bpm(img_data,img_mask);
+    hdrl_image * image = hdrl_image_create(d_data, d_errs);
+    hdrl_parameter * params = hdrl_lacosmic_parameter_create(sigma_lim, f_lim, max_iter);
+
+    result_mask = hdrl_lacosmic_edgedetect(image, params);
+    int nb_crh=cpl_mask_count(result_mask);
+
+    /* we need now to convert back to XSH format
+     * Use images instead than mask
+     * Use proper bad pixel code
+     * Combine found CRH to original bad pixels
+     */
+
+
+    img_mask=cpl_image_new_from_mask(result_mask);
+    cpl_image_multiply_scalar(img_mask,QFLAG_COSMIC_RAY_UNREMOVED);
+    xsh_badpixelmap_image_coadd(&(out_pre->qual), img_mask,1);
+
+#if REGDEBUG_FULL
+    cpl_image_save( img_mask, "CRH_SINGLE.fits", CPL_BPP_32_SIGNED, NULL,
+                    CPL_IO_DEFAULT);
+    cpl_image_save( out_pre->qual, "CRH_SINGLE2.fits", CPL_BPP_32_SIGNED, NULL,
+                       CPL_IO_DEFAULT);
+#endif
+
+
+    char* res_name = xsh_stringcat_any(ftag, ".fits", (void*)NULL);
+
+    xsh_msg_dbg_high( "Saving Result Frame '%s'", res_name);
+    check( xsh_add_qc_crh( out_pre, nb_crh, 1) );
+    check( res_frame = xsh_pre_save( out_pre, res_name, ftag,0 ) );
+    check( cpl_frame_set_tag( res_frame, ftag ) );
+
+    XSH_FREE( res_name);
+
+    cleanup:
+    xsh_print_rec_status(16);
+    cpl_image_delete(d_data);
+    cpl_image_delete(d_errs);
+    hdrl_parameter_delete(params) ;
+    hdrl_image_delete(image);
+    cpl_mask_delete(result_mask);
+
+    return res_frame;
+}
+
+
+/*----------------------------------------------------------------------------*/
+
+/**@}*/
diff --git a/xsh/xsh_hdrl_functions.h b/xsh/xsh_hdrl_functions.h
new file mode 100644
index 0000000..e29d30a
--- /dev/null
+++ b/xsh/xsh_hdrl_functions.h
@@ -0,0 +1,46 @@
+/*                                                                            *
+ *   This file is part of the ESO X-shooter Pipeline                          *
+ *   Copyright (C) 2006 European Southern Observatory                         *
+ *                                                                            *
+ *   This library is free software; you can redistribute it and/or modify     *
+ *   it under the terms of the GNU General Public License as published by     *
+ *   the Free Software Foundation; either version 2 of the License, or        *
+ *   (at your option) any later version.                                      *
+ *                                                                            *
+ *   This program is distributed in the hope that it will be useful,          *
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of           *
+ *   MERCHANTABILITY or F1ITNESS FOR A PARTICULAR PURPOSE.  See the           *
+ *   GNU General Public License for more details.                             *
+ *                                                                            *
+ *   You should have received a copy of the GNU General Public License        *
+ *   along with this program; if not, write to the Free Software              *
+ *   Foundation, 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA     *
+ *                                                                            */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+
+#ifndef XSH_HDRL_FUNCTIONS_H
+#define XSH_HDRL_FUNCTIONS_H
+
+/*-----------------------------------------------------------------------------
+  Includes
+  ----------------------------------------------------------------------------*/
+#include <xsh_error.h>
+#include <xsh_msg.h>
+#include <hdrl.h>
+#include <cpl.h>
+
+cpl_frame*
+xsh_hdrl_remove_crh_single( cpl_frame* frm,
+                       xsh_instrument* instrument,
+                       xsh_remove_crh_single_param *  crh_single_par,
+                       const char* ftag ) ;
+
+
+/*----------------------------------------------------------------------------*/
+
+
+#endif
diff --git a/xsh/xsh_irplib_mkmaster.c b/xsh/xsh_irplib_mkmaster.c
index 5f90fbc..7f3a305 100644
--- a/xsh/xsh_irplib_mkmaster.c
+++ b/xsh/xsh_irplib_mkmaster.c
@@ -38,6 +38,7 @@
 #include "xsh_irplib_mkmaster.h"
 #include "xsh_utils_imagelist.h"
 #include "xsh_pfits.h"
+#include "xsh_ksigma_clip.h"
 #include "xsh_msg.h"
 /*----------------------------------------------------------------------------*/
 /**
@@ -367,6 +368,7 @@ xsh_irplib_mkmaster_median(cpl_imagelist* images,const double kappa, const int n
    double mean=0;
    cpl_imagelist* iml=NULL;
 
+   cpl_ensure(images != NULL, CPL_ERROR_NULL_INPUT,NULL);
    //cpl_msg_info(cpl_func,"method median");
    iml=cpl_imagelist_duplicate(images);
    levels=xsh_irplib_imagelist_get_clean_mean_levels(iml,kappa,nclip,tolerance);
@@ -381,7 +383,6 @@ xsh_irplib_mkmaster_median(cpl_imagelist* images,const double kappa, const int n
 
 
    cpl_image_add_scalar(master,mean);
-
    cpl_vector_delete(levels);
    cpl_imagelist_delete(iml);
 
diff --git a/xsh/xsh_ksigma_clip.c b/xsh/xsh_ksigma_clip.c
new file mode 100644
index 0000000..5df508e
--- /dev/null
+++ b/xsh/xsh_ksigma_clip.c
@@ -0,0 +1,245 @@
+/* $Id: xsh_detmon.c,v 1.11 2013-07-19 12:00:24 jtaylor Exp $
+ *
+ * This file is part of the irplib package
+ * Copyright (C) 2002, 2003 European Southern Observatory
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * $Author: jtaylor $
+ * $Date: 2013-07-19 12:00:24 $
+ * $Revision: 1.11 $
+ * $Name: not supported by cvs2svn $
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <complex.h>
+
+/*---------------------------------------------------------------------------
+                                  Includes
+ ---------------------------------------------------------------------------*/
+
+#include <math.h>
+#include <string.h>
+#include <assert.h>
+#include <float.h>
+
+#include <cpl.h>
+
+#include "xsh_ksigma_clip.h"
+
+
+static cpl_error_code
+xsh_ksigma_clip_double(const double  * pi,
+		       cpl_binary * pm,
+		       int               llx,
+			  int               lly,
+			  int               urx,
+			  int               ury,
+			  int               nx,
+			  double            var_sum,
+			  int               npixs,
+			  double            kappa,
+			  int               nclip,
+			  double            tolerance,
+			  double          * mean,
+			  double          * stdev);
+
+static cpl_error_code
+xsh_ksigma_clip_float(const float     * pi,
+		      cpl_binary * pm,
+			 int               llx,
+			 int               lly,
+			 int               urx,
+			 int               ury,
+			 int               nx,
+			 double            var_sum,
+			 int               npixs,
+			 double            kappa,
+			 int               nclip,
+			 double            tolerance,
+			 double          * mean,
+			 double          * stdev);
+
+static cpl_error_code
+xsh_ksigma_clip_int(const int       * pi,
+		    cpl_binary * pm,
+		       int               llx,
+		       int               lly,
+		       int               urx,
+		       int               ury,
+		       int               nx,
+		       double            var_sum,
+		       int               npixs,
+		       double            kappa,
+		       int               nclip,
+		       double            tolerance,
+		       double          * mean,
+		       double          * stdev);
+
+
+/*---------------------------------------------------------------------------*/
+/**
+  @brief    Apply kappa-sigma clipping on input image
+  @param    img      Input image
+  @param    llx      Lower left x position (FITS convention)
+  @param    lly      Lower left y position (FITS convention)
+  @param    urx      Upper right x position (FITS convention)
+  @param    ury      Upper right y position (FITS convention)
+  @param    kappa    Kappa value for the clipping
+  @param    nclip    Number of clipping iterations
+  @param    kmean    Mean after clipping (output)
+  @param    kstdev   Stdev after clipping (output)
+  @return   CPL_ERROR_NONE or the relevant #_cpl_error_code_ on error
+
+  This function applies an iterative kappa-sigma clipping on the image and
+  returns mean and stdev after the clipping.
+
+  The function takes as a starting point the "standard" values of mean and
+  stdev from cpl_stats.
+
+  On each iteration, the contribution of pixels outside the range
+  [mean - kappa * stdev, mean + kappa * stdev] is removed, the values of
+  mean and stdev are updated, and so are the limits of the range to be used
+  in the next iteration as well.
+
+  The algorithm stops after nclip iterations or when the variation of the
+  range between two consecutive iterations is smaller (absolute value) than
+  the tolerance.
+
+  The effectiveness of this function resides on the way the update of the
+  values of mean and stdev is done.
+
+  The contribution of a single pixel in variance can be removed as follows:
+
+  \sum_{i=1}^{N-1} (x_i - \overline{x}_{n-1})^2 =
+  \sum_{i=1}^ N    (x_i - \overline{x}_n    )^2 -
+  \frac{N}{N-1} \,( \, \overline{x}_n - x_{n} )^2
+
+  For further details on the mathematical aspects, please refer to DFS05126.
+
+  Possible #_cpl_error_code_ set in this function:
+   - CPL_ERROR_NULL_INPUT if img or kmean is NULL
+   - CPL_ERROR_ILLEGAL_INPUT if
+       a) the window specification is illegal (llx > urx or lly > ury)
+       b) the window specification is outside the image
+       c) the tolerance is negative
+       d) kappa is <= 1.0
+       e) nclip is <= 0.
+
+  The values of kmean and kstdev is undefined on error.
+*/
+/*---------------------------------------------------------------------------*/
+cpl_error_code
+xsh_ksigma_clip(const cpl_image * img,
+		   int               llx,
+		   int               lly,
+		   int               urx,
+		   int               ury,
+		   double            kappa,
+		   int               nclip,
+		   double            tolerance,
+		   double          * kmean,
+		   double          * kstdev)
+{
+
+    int nx, ny;
+
+    double      mean, stdev;
+    //int         npixs;
+    cpl_image* sub_ima=NULL;
+    double kappa2=0;
+    double thresh=0;
+    double thresh_p=0;
+    cpl_binary * pm=0;
+    const float* pi=0;
+
+    int pix=0;
+    int i=0;
+    int j=0;
+    int k=0;
+
+    cpl_ensure_code(img != NULL, CPL_ERROR_NULL_INPUT);
+
+    nx = cpl_image_get_size_x(img);
+    ny = cpl_image_get_size_y(img);
+
+    cpl_ensure_code(llx > 0 && urx > llx && urx <= nx &&
+		    lly > 0 && ury > lly && ury <= ny,
+		    CPL_ERROR_ILLEGAL_INPUT);
+
+    cpl_ensure_code(tolerance >= 0.0, CPL_ERROR_ILLEGAL_INPUT);
+    cpl_ensure_code(kappa     >  1.0, CPL_ERROR_ILLEGAL_INPUT);
+    cpl_ensure_code(nclip     >    0, CPL_ERROR_ILLEGAL_INPUT);
+ 
+    sub_ima=cpl_image_extract(img,llx, lly, urx, ury);
+   //npixs= nx*ny-cpl_image_count_rejected(sub_ima);
+   cpl_image_delete(sub_ima);
+   mean    = cpl_image_get_mean_window(img,llx, lly, urx, ury);
+   stdev    = cpl_image_get_stdev_window(img,llx, lly, urx, ury);
+   pi=cpl_image_get_data_float_const(img);
+   pm=cpl_mask_get_data(cpl_image_get_bpm((cpl_image*)img));
+ 
+
+   kappa2=kappa*kappa;
+   thresh_p=-1;
+   for(k=0;k<nclip;k++) {
+     mean    = cpl_image_get_mean_window(img,llx, lly, urx, ury);
+     stdev    = cpl_image_get_stdev_window(img,llx, lly, urx, ury);
+     thresh=stdev*stdev*kappa2;
+     for(j=lly;j<ury;j++) {
+       for(i=llx;i<urx;i++) {
+	 pix=i+j*nx;
+	 if( 
+             (pm[pix] != CPL_BINARY_1) && 
+	     ((pi[pix]-mean)*(pi[pix]-mean) > thresh ) ) {
+	   pm[pix]=CPL_BINARY_1;
+	 } /* end check if pix is outlier */
+       } /* loop over i */
+     } /* loop over j */
+     if((fabs(thresh_p-thresh)) < tolerance) {
+       break;
+     } else {
+       thresh_p=thresh;
+     }
+   } /* loop over niter */
+
+    *kmean = mean;
+    if (kstdev != NULL) *kstdev = stdev; /* Optional */
+
+
+    return cpl_error_get_code();
+}
+
+#define CONCAT(a,b) a ## _ ## b
+#define CONCAT2X(a,b) CONCAT(a,b)
+
+#define CPL_TYPE double
+#include "xsh_detmon_body.h"
+#undef CPL_TYPE
+
+#define CPL_TYPE float
+#include "xsh_detmon_body.h"
+#undef CPL_TYPE
+
+#define CPL_TYPE int
+#include "xsh_detmon_body.h"
+#undef CPL_TYPE
+
+/**@}*/
diff --git a/xsh/xsh_detmon_lg_impl.h b/xsh/xsh_ksigma_clip.h
similarity index 51%
copy from xsh/xsh_detmon_lg_impl.h
copy to xsh/xsh_ksigma_clip.h
index 25846d0..99f28ce 100644
--- a/xsh/xsh_detmon_lg_impl.h
+++ b/xsh/xsh_ksigma_clip.h
@@ -1,4 +1,4 @@
-/* $Id: xsh_detmon_lg_impl.h,v 1.4 2011-12-02 14:15:28 amodigli Exp $
+/* $Id: xsh_detmon.h,v 1.3 2013-01-25 16:08:41 jtaylor Exp $
  *
  * This file is part of the irplib package
  * Copyright (C) 2002, 2003 European Southern Observatory
@@ -18,36 +18,36 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02111-1307 USA
  */
 
-
 /*
- * $Author: amodigli $
- * $Date: 2011-12-02 14:15:28 $
- * $Revision: 1.4 $
+ * $Author: jtaylor $
+ * $Date: 2013-01-25 16:08:41 $
+ * $Revision: 1.3 $
  * $Name: not supported by cvs2svn $
- * $Log: not supported by cvs2svn $
- * Revision 1.3  2009/12/11 08:47:21  amodigli
- * updated to latest delivery
- *
- * Revision 1.2  2009/08/17 15:10:16  kmirny
- *
- * DFS07454 DFS07437
- *
- * Revision 1.1  2009/08/12 09:26:43  kmirny
- * DFS07454
- *
-*/
-#ifndef IRPLIB_DETMON_LG_IMPL_H_
-#define IRPLIB_DETMON_LG_IMPL_H_
+ */
 
-cpl_error_code
-xsh_detmon_pair_extract(const cpl_frameset *,
-                           int *, int,
-                           int ,
-                           int *,
-                           int,
-                           cpl_frameset **);
-cpl_error_code
-xsh_detmon_check_order(const double *exptime, int sz, double tolerance, int order);
+#ifndef XSH_KSIGMA_CLIP_H
+#define XSH_KSIGMA_CLIP_H
+
+/*----------------------------------------------------------------------------
+                                   Includes
+ ----------------------------------------------------------------------------*/
 
+#include <cpl.h>
+#include <xsh_cpl_size.h>
 
-#endif /* IRPLIB_DETMON_LG_IMPL_H_ */
+/*----------------------------------------------------------------------------
+                                   Prototypes
+ ----------------------------------------------------------------------------*/
+
+cpl_error_code
+xsh_ksigma_clip(const cpl_image *,
+		   const int,
+		   const int,
+		   const int,
+		   const int,
+		   const double,
+		   const int,
+		   const double,
+		   double *,
+		   double *);
+#endif
diff --git a/xsh/xsh_model_kernel.c b/xsh/xsh_model_kernel.c
index 3e394b2..8bfa215 100644
--- a/xsh/xsh_model_kernel.c
+++ b/xsh/xsh_model_kernel.c
@@ -5815,7 +5815,7 @@ xsh_model_first_anneal_save(
    /* Get the reference frame */
    raws=cpl_frameset_new();
    check(xsh_dfs_extract_raw_frames(set,raws));
-   check(ref_frame=cpl_frameset_get_first(raws));
+   check(ref_frame=cpl_frameset_get_frame(raws,0));
    check(plist=cpl_propertylist_load(cpl_frame_get_filename(ref_frame),0));
    xsh_free_frameset(&raws);
 
diff --git a/xsh/xsh_parameters.c b/xsh/xsh_parameters.c
index 3a2f5bb..4a3cd6e 100644
--- a/xsh/xsh_parameters.c
+++ b/xsh/xsh_parameters.c
@@ -406,22 +406,33 @@ void xsh_parameters_generic( const char *recipe_id,
 
 cpl_error_code
 xsh_parameters_decode_bp( const char *recipe_id,
-           cpl_parameterlist * plist,const int ival )
-{
-  XSH_ASSURE_NOT_NULL( recipe_id ) ;
-  XSH_ASSURE_NOT_NULL( plist ) ;
-  int mval=DECODE_BP_FLAG_MAX;
-  int val=0;
-  if(ival<0) {
-    val=DECODE_BP_FLAG_DEF;
-  } else {
-    val=ival;
-  }
-  check(xsh_parameters_new_range_int( plist, recipe_id,"decode-bp",
-              val, 0,mval,
-                                      "Integer representation of the bits to be considered bad when decoding the bad pixel mask pixel values."));
- cleanup:
-  return cpl_error_get_code();
+                          cpl_parameterlist * plist,const int ival )
+{
+    XSH_ASSURE_NOT_NULL( recipe_id ) ;
+    XSH_ASSURE_NOT_NULL( plist ) ;
+    int mval=DECODE_BP_FLAG_MAX;
+    int val=0;
+    if(ival<0) {
+        val=DECODE_BP_FLAG_DEF;
+    } else {
+        val=ival;
+    }
+    check(xsh_parameters_new_range_int( plist, recipe_id,"decode-bp",
+                    val, 0,mval,"Integer representation of the bits to be considered bad when decoding the bad pixel mask pixel values. \n\
+ Most frequent codes relevant for the user: \n\
+ 0: good pixel, \n\
+ 8: pick-up noise, \n\
+ 16: cosmic-ray removed, \n\
+ 32: cosmic-ray unremoved, \n\
+ 128: calibration file defect, \n\
+ 256: hot pixel, \n\
+ 512: dark pixel, \n\
+ 4096: A/D converted saturation, \n\
+ 32768: non linear pixel, \n\
+ 1048576: extrapolated flux in NIR, \n\
+ 4194304: Interpolated flux during extraction."));
+    cleanup:
+    return cpl_error_get_code();
 }
 
 cpl_error_code
diff --git a/xsh/xsh_pfits.c b/xsh/xsh_pfits.c
index cf6e090..154a694 100644
--- a/xsh/xsh_pfits.c
+++ b/xsh/xsh_pfits.c
@@ -4206,44 +4206,59 @@ xsh_plist_set_extra_common_keys(cpl_propertylist* plist)
 */
 cpl_error_code
 xsh_plist_set_extra_keys(cpl_propertylist* plist,
-			 const char* hduclas1,
-			 const char* hduclas2,
-			 const char* hduclas3,
-			 const char* scidata,
-			 const char* errdata,
-			 const char* qualdata,
+                         const char* hduclas1,
+                         const char* hduclas2,
+                         const char* hduclas3,
+                         const char* scidata,
+                         const char* errdata,
+                         const char* qualdata,
                          const int type)
 {
 
-  //XSH_ASSURE_NOT_ILLEGAL_MSG(type<3,"type  < 3");
-  XSH_ASSURE_NOT_ILLEGAL_MSG(type>=0,"type  > 0");
+    //XSH_ASSURE_NOT_ILLEGAL_MSG(type<3,"type  < 3");
+    XSH_ASSURE_NOT_ILLEGAL_MSG(type>=0,"type  > 0");
 
-  xsh_plist_set_extra_common_keys(plist);
+    xsh_plist_set_extra_common_keys(plist);
 
-  cpl_propertylist_append_string(plist,"HDUCLAS1",hduclas1) ;
-  cpl_propertylist_set_comment(plist,"HDUCLAS1","hdu format classification") ;
+    cpl_propertylist_append_string(plist,"HDUCLAS1",hduclas1) ;
+    cpl_propertylist_set_comment(plist,"HDUCLAS1","hdu format classification") ;
 
-  cpl_propertylist_append_string(plist,"HDUCLAS2",hduclas2) ;
-  cpl_propertylist_set_comment(plist,"HDUCLAS2","hdu type classification") ;
+    cpl_propertylist_append_string(plist,"HDUCLAS2",hduclas2) ;
+    cpl_propertylist_set_comment(plist,"HDUCLAS2","hdu type classification") ;
 
-  if(type!=0) {
-    cpl_propertylist_append_string(plist,"HDUCLAS3",hduclas3) ;
-    cpl_propertylist_set_comment(plist,"HDUCLAS3","hdu info classification") ;
-    cpl_propertylist_append_string(plist,"SCIDATA",scidata) ;
-    cpl_propertylist_set_comment(plist,"SCIDATA","name of data extension") ;
-  }
+    if(type == 0) {
+        if(!cpl_propertylist_has(plist,"EXTNAME")) {
+            cpl_propertylist_append_string(plist,"EXTNAME",scidata) ;
+            cpl_propertylist_set_comment(plist,"EXTNAME","name of data extension") ;
+        }
+    }
 
-  if(type!=1) {
-    cpl_propertylist_append_string(plist,"ERRDATA",errdata) ;
-    cpl_propertylist_set_comment(plist,"ERRDATA","name of errs extension") ;
-  }
+    if(type!=0) {
+        if(!cpl_propertylist_has(plist,"HDUCLAS3")) {
+            cpl_propertylist_append_string(plist,"HDUCLAS3",hduclas3) ;
+            cpl_propertylist_set_comment(plist,"HDUCLAS3","hdu info classification") ;
+        }
+        if(!cpl_propertylist_has(plist,"SCIDATA")) {
+            cpl_propertylist_append_string(plist,"SCIDATA",scidata) ;
+            cpl_propertylist_set_comment(plist,"SCIDATA","name of data extension") ;
+        }
+    }
 
-  if(type!=2) {
-    cpl_propertylist_append_string(plist,"QUALDATA",qualdata) ;
-    cpl_propertylist_set_comment(plist,"QUALDATA","name of qual extension") ;
-  }
- cleanup:
-  return cpl_error_get_code();
+    if(type!=1) {
+        if(!cpl_propertylist_has(plist,"ERRDATA")) {
+            cpl_propertylist_append_string(plist,"ERRDATA",errdata) ;
+            cpl_propertylist_set_comment(plist,"ERRDATA","name of errs extension") ;
+        }
+    }
+
+    if(type!=2) {
+        if(!cpl_propertylist_has(plist,"QUALDATA")) {
+            cpl_propertylist_append_string(plist,"QUALDATA",qualdata) ;
+            cpl_propertylist_set_comment(plist,"QUALDATA","name of qual extension") ;
+        }
+    }
+    cleanup:
+    return cpl_error_get_code();
 }
 
 cpl_error_code 
diff --git a/xsh/xsh_pfits_qc.c b/xsh/xsh_pfits_qc.c
index 387ac6e..4e212ef 100644
--- a/xsh/xsh_pfits_qc.c
+++ b/xsh/xsh_pfits_qc.c
@@ -749,9 +749,9 @@ cleanup:
  */
 /*-------------------------------------------------------------------------- */
 void
-xsh_pfits_set_qc_ncrh_mean (cpl_propertylist * plist, int value)
+xsh_pfits_set_qc_ncrh_mean (cpl_propertylist * plist, const double value)
 {
-  check_msg (cpl_propertylist_update_int (plist, XSH_QC_CRH_NUMBER_MEAN, value),
+  check_msg (cpl_propertylist_update_float (plist, XSH_QC_CRH_NUMBER_MEAN, value),
 	     "Error writing keyword '%s'", XSH_QC_CRH_NUMBER_MEAN);
   cpl_propertylist_set_comment(plist, XSH_QC_CRH_NUMBER_MEAN,XSH_QC_CRH_NUMBER_MEAN_C);
 
@@ -768,7 +768,7 @@ cleanup:
 void
 xsh_pfits_set_qc_crrate (cpl_propertylist * plist, double value)
 {
-  check_msg (cpl_propertylist_update_double (plist, XSH_QC_CRH_RATE, value),
+  check_msg (cpl_propertylist_update_float (plist, XSH_QC_CRH_RATE, value),
 	     "Error writing keyword '%s'", XSH_QC_CRH_RATE);
   cpl_propertylist_set_comment(plist,XSH_QC_CRH_RATE,XSH_QC_CRH_RATE_C);
 
diff --git a/xsh/xsh_pfits_qc.h b/xsh/xsh_pfits_qc.h
index 26ee686..6066793 100644
--- a/xsh/xsh_pfits_qc.h
+++ b/xsh/xsh_pfits_qc.h
@@ -247,7 +247,7 @@ void  xsh_pfits_set_qc_ron2( cpl_propertylist * plist, double value);
 void  xsh_pfits_set_qc_ron1_err( cpl_propertylist * plist, double value);
 void  xsh_pfits_set_qc_ron2_err( cpl_propertylist * plist, double value);
 void xsh_pfits_set_qc_ncrh(cpl_propertylist * plist, int value) ;
-void xsh_pfits_set_qc_ncrh_mean(cpl_propertylist * plist, int value) ;
+void xsh_pfits_set_qc_ncrh_mean(cpl_propertylist * plist, const double value) ;
 void xsh_pfits_set_qc_crrate(cpl_propertylist * plist, double value) ;
 void xsh_pfits_set_qc_mdarkavg(cpl_propertylist * plist, double value);
 void xsh_pfits_set_qc_mdarkmed(cpl_propertylist * plist, double value);
diff --git a/xsh/xsh_qc_definition.h b/xsh/xsh_qc_definition.h
index 7dec043..5873475 100644
--- a/xsh/xsh_qc_definition.h
+++ b/xsh/xsh_qc_definition.h
@@ -102,8 +102,7 @@
 
 
 #define XSH_QC_CRH_RATE "ESO QC CRRATE"
-#define XSH_QC_CRH_RATE_C "Number of detected cosmic ray hits per surface unit (cm2) and per second."
-
+#define XSH_QC_CRH_RATE_C "Number of detected CRH per cm2 and s"
 #define XSH_QC_CRH_NUMBER  "ESO QC NCRH"
 #define XSH_QC_CRH_NUMBER_C  "Number of detected cosmic ray hits"
 #define XSH_QC_CRH_NUMBER_MEAN "ESO QC NCRH AVG"
diff --git a/xsh/xsh_qc_handling.c b/xsh/xsh_qc_handling.c
index 6ef2c16..8bc5781 100644
--- a/xsh/xsh_qc_handling.c
+++ b/xsh/xsh_qc_handling.c
@@ -45,6 +45,7 @@
 #include "xsh_msg.h"
 #include "xsh_qc_handling.h"
 #include "xsh_qc_definition.h"
+#include "xsh_pfits_qc.h"
 
 
 /*-----------------------------------------------------------------------------
@@ -212,4 +213,52 @@ int xsh_is_qc_for_pro_catg( const char * pro_catg, qc_description * pqc )
   return 0 ;
 }
 
+
+
+/**
+ * Calculates and set the QC parameters relevant for Cosmic Rays.
+ *
+ * @param pre Pointer to XSH_PRE Structure
+ * @param nbcrh Total umber of cosmics found
+ * @param nframes Number of frames used to remove cosmics
+ */
+void xsh_add_qc_crh (xsh_pre* pre, int nbcrh, int nframes)
+{
+  double qc_crrate = 0.0;
+  float nbcr_avg ;        /**< Average of cosmics per frame */
+
+  XSH_ASSURE_NOT_NULL(pre);
+  XSH_ASSURE_NOT_ILLEGAL(pre->pszx >0. && pre->pszy > 0);
+  XSH_ASSURE_NOT_ILLEGAL(pre->exptime > 0);
+  /*
+    QC.CRRATE = avg_nb_of_crh_per_frame/(exposure_time*size_of_detector_in_cm2)
+    Nb of Cosmics per cm2 per second.
+    The whole size of the image in cm2 is given by pszx and pszy. These
+    values are in MICRONS.
+  */
+  xsh_msg_dbg_medium( "add_qc_crh - Exptime = %f", pre->exptime ) ;
+  qc_crrate =
+    (double) nbcrh / (((double) nframes) * (pre->exptime *
+    (pre->pszx / 10000.0) * (pre->pszy /10000.0) * pre->nx * pre->ny)) ;
+  nbcr_avg = nbcrh/nframes ;
+
+  /*
+    Now set QC KW
+  */
+  check( xsh_pfits_set_qc_crrate( pre->data_header,qc_crrate) ) ;
+  check( xsh_pfits_set_qc_ncrh( pre->data_header,nbcrh) ) ;
+  check( xsh_pfits_set_qc_ncrh_mean( pre->data_header,nbcr_avg) ) ;
+  /* Same thing for the qual header */
+  check( xsh_pfits_set_qc_crrate( pre->qual_header,qc_crrate) ) ;
+  check( xsh_pfits_set_qc_ncrh( pre->qual_header,nbcrh) ) ;
+  check( xsh_pfits_set_qc_ncrh_mean( pre->qual_header,nbcr_avg) ) ;
+  cleanup:
+    return ;
+}
+
+
+
+
+
+
 /**@}*/
diff --git a/xsh/xsh_qc_handling.h b/xsh/xsh_qc_handling.h
index f39abe5..9156aa2 100644
--- a/xsh/xsh_qc_handling.h
+++ b/xsh/xsh_qc_handling.h
@@ -27,6 +27,10 @@
 #define XSH_QC_HANDLING_H
 
 #include "xsh_data_instrument.h"
+#include "xsh_data_pre.h"
+
+
+
 
 typedef struct {
   const char *kw_name;  /**< QC name */
@@ -52,4 +56,7 @@ int xsh_qc_in_recipe( qc_description * pqc, xsh_instrument * instrument ) ;
 int xsh_is_qc_for_arm( const char * arm, qc_description * pqc ) ;
 int xsh_is_qc_for_pro_catg( const char * pro_catg, qc_description * pqc ) ;
 
+void xsh_add_qc_crh (xsh_pre* pre, int nbcrh, int nframes);
+
+
 #endif
diff --git a/xsh/xsh_remove_crh_multi.c b/xsh/xsh_remove_crh_multi.c
index f87d027..e83beaa 100644
--- a/xsh/xsh_remove_crh_multi.c
+++ b/xsh/xsh_remove_crh_multi.c
@@ -184,7 +184,7 @@ static void
 add_qc_crh (xsh_pre* pre, int nbcrh, int nframes)
 {
   double qc_crrate = 0.0;
-  int nbcr_avg ;		/**< Average of cosmics per frame */
+  float nbcr_avg ;		/**< Average of cosmics per frame */
   XSH_ASSURE_NOT_NULL(pre);
   XSH_ASSURE_NOT_ILLEGAL(pre->pszx >0. && pre->pszy > 0); 
   XSH_ASSURE_NOT_ILLEGAL(pre->exptime > 0); 
diff --git a/xsh/xsh_remove_crh_single.c b/xsh/xsh_remove_crh_single.c
index 108af1a..a6edfe2 100644
--- a/xsh/xsh_remove_crh_single.c
+++ b/xsh/xsh_remove_crh_single.c
@@ -54,7 +54,7 @@
 #include <xsh_badpixelmap.h>
 #include <xsh_parameters.h>
 #include <xsh_utils_wrappers.h>
-
+#include <xsh_qc_handling.h>
 /*-----------------------------------------------------------------------------
   Functions prototypes
  -----------------------------------------------------------------------------*/
@@ -69,50 +69,6 @@
 
 
 
-/** 
- * Calculates and set the QC parameters relevant for Cosmic Rays.
- * 
- * @param pre Pointer to XSH_PRE Structure
- * @param nbcrh Total umber of cosmics found
- * @param nframes Number of frames used to remove cosmics
- */
-static void add_qc_crh (xsh_pre* pre, int nbcrh, int nframes)
-{
-  double qc_crrate = 0.0;
-  int nbcr_avg ;		/**< Average of cosmics per frame */
-
-  XSH_ASSURE_NOT_NULL(pre);
-  XSH_ASSURE_NOT_ILLEGAL(pre->pszx >0. && pre->pszy > 0); 
-  XSH_ASSURE_NOT_ILLEGAL(pre->exptime > 0); 
-  /*
-    QC.CRRATE = avg_nb_of_crh_per_frame/(exposure_time*size_of_detector_in_cm2)
-    Nb of Cosmics per cm2 per second.
-    The whole size of the image in cm2 is given by pszx and pszy. These
-    values are in MICRONS.
-  */
-  xsh_msg_dbg_medium( "add_qc_crh - Exptime = %f", pre->exptime ) ;
-  qc_crrate =
-    (double) nbcrh / (((double) nframes) * (pre->exptime * 
-    (pre->pszx / 10000.0) * (pre->pszy /10000.0) * pre->nx * pre->ny)) ;
-  nbcr_avg = nbcrh/nframes ;
-
-  /*
-    Now set QC KW
-  */
-  check( xsh_pfits_set_qc_crrate( pre->data_header,qc_crrate) ) ;
-  check( xsh_pfits_set_qc_ncrh( pre->data_header,nbcrh) ) ;
-  check( xsh_pfits_set_qc_ncrh_mean( pre->data_header,nbcr_avg) ) ;
-  /* Same thing for the qual header */
-  check( xsh_pfits_set_qc_crrate( pre->qual_header,qc_crrate) ) ;
-  check( xsh_pfits_set_qc_ncrh( pre->qual_header,nbcrh) ) ;
-  check( xsh_pfits_set_qc_ncrh_mean( pre->qual_header,nbcr_avg) ) ;
-  cleanup:
-    return ;
-}
-
-
-
-
 
 cpl_frame * xsh_abs_remove_crh_single( cpl_frame *sci_frame,
                                    xsh_instrument * instrument,
@@ -545,7 +501,7 @@ cpl_frame * xsh_remove_crh_single(cpl_frame * in_sci_frame,
 
   res_name = xsh_stringcat_any(res_tag, ".fits", (void*)NULL);
   xsh_msg_dbg_high( "Saving Result Frame '%s'", res_name);
-  check( add_qc_crh( sci_pre, nb_crh, 1) );
+  check( xsh_add_qc_crh( sci_pre, nb_crh, 1) );
   check( res_frame = xsh_pre_save( sci_pre, res_name, res_tag,0 ) );
   check( cpl_frame_set_tag( res_frame, res_tag ) );
   XSH_FREE( res_name);
diff --git a/xsh/xsh_subtract_sky_nod.c b/xsh/xsh_subtract_sky_nod.c
index 5b824f8..bac1320 100644
--- a/xsh/xsh_subtract_sky_nod.c
+++ b/xsh/xsh_subtract_sky_nod.c
@@ -116,88 +116,7 @@ static void save_pre_frame( cpl_frame * frame, xsh_instrument * instrument,
  * @return Frameset of A-B and B-A frames
  */
 
-#if 0
-cpl_frameset * xsh_subtract_sky_nod( cpl_frameset * org_raws, int nraws,
-			  xsh_instrument * instrument )
-{
-  int i, npairs ;
-  cpl_frameset * result = NULL ;
-  char arm_name[16] ;
-  cpl_frameset * raws = NULL ;
-
-  /*Before anything else, order the frameset by date=obs */
-  check( raws = xsh_order_frameset_by_date( org_raws ) ) ;
-
-  check( result = cpl_frameset_new() ) ;
-  sprintf( arm_name, "%s_", xsh_instrument_arm_tostring( instrument ) ) ;
-
-  for( npairs = 0, i = 0 ; i<nraws ; i += 4 ) {
-    char * a_b_name, * b_a_name, str[16] ;
-    cpl_frame * a = NULL, * b = NULL ;
-    cpl_frame * a_b = NULL, * b_a = NULL ;
-    double nodthrow = 0, jitterbox = 0, reloffset = 0, cumoffset = 0 ;
-
-    if ( i == 0 ) check(a = cpl_frameset_get_first( raws )) ;
-    else check(a = cpl_frameset_get_next( raws )) ;
-
-    check(b = cpl_frameset_get_next( raws ) );
-    xsh_msg( "1-st pair: A='%s'", cpl_frame_get_filename( a ) ) ;
-
-    xsh_msg( "           B='%s'", cpl_frame_get_filename( b ) ) ;
-    sprintf( str, "%d", npairs ) ;
-
-    a_b_name = xsh_stringcat_any( "A_B_SUBTRACTED_NOD_", arm_name, str,
-				  ".fits", (void*)NULL );
-    b_a_name = xsh_stringcat_any( "B_A_SUBTRACTED_NOD_", arm_name, str,
-				  ".fits", (void*)NULL );
-    check( a_b = xsh_pre_frame_subtract( a, b, a_b_name, instrument,0 )) ;
-    save_pre_frame( a_b, instrument ) ;
-    xsh_rec_get_nod_kw( a_b, &nodthrow, &jitterbox, &reloffset, &cumoffset ) ;
-    xsh_msg( "     A-B: Nodthrow: %lf, Jitterbox: %lf, Reloffset: %lf, Cumoffset: %lf",
-	     nodthrow, jitterbox, reloffset, cumoffset) ;
-    check( b_a = xsh_pre_frame_subtract( b, a, b_a_name, instrument,0 )) ;
-    save_pre_frame( b_a, instrument ) ;
-    xsh_rec_get_nod_kw( b_a, &nodthrow, &jitterbox, &reloffset, &cumoffset ) ;
-    xsh_msg( "     B-A: Nodthrow: %lf, Jitterbox: %lf, Reloffset: %lf, Cumoffset: %lf",
-	     nodthrow, jitterbox, reloffset, cumoffset) ;
-
-    check(cpl_frameset_insert( result, a_b )) ;
-    check(cpl_frameset_insert( result, b_a )) ;
-
-    if ( nraws == 2 ) break ;
-
-    /* Second pair of B,A (B now is first !) */
-    npairs++ ;
-    check(b = cpl_frameset_get_next( raws )) ;
-    check(a = cpl_frameset_get_next( raws ) );
-    xsh_msg( "2-nd pair: A='%s'", cpl_frame_get_filename( a ) ) ;
-    xsh_msg( "           B='%s'", cpl_frame_get_filename( b ) ) ;
-    sprintf( str, "%d", npairs ) ;
-    a_b_name = xsh_stringcat_any( "A_B_SUBTRACTED_NOD_", arm_name, str,
-				  ".fits", (void*)NULL );
-    b_a_name = xsh_stringcat_any( "B_A_SUBTRACTED_NOD_", arm_name, str,
-				  ".fits", (void*)NULL );
-    check( a_b = xsh_pre_frame_subtract( a, b, a_b_name, instrument,0 )) ;
-    save_pre_frame( a_b, instrument ) ;
-    xsh_rec_get_nod_kw( a_b, &nodthrow, &jitterbox, &reloffset, &cumoffset ) ;
-    xsh_msg( "     A-B: Nodthrow: %lf, Jitterbox: %lf, Reloffset: %lf, Cumoffset: %lf",
-	     nodthrow, jitterbox, reloffset, cumoffset) ;
-    check( b_a = xsh_pre_frame_subtract( b, a, b_a_name, instrument,0 )) ;
-    save_pre_frame( b_a, instrument ) ;
-    xsh_rec_get_nod_kw( b_a, &nodthrow, &jitterbox, &reloffset, &cumoffset ) ;
-    xsh_msg( "     B-A: Nodthrow: %lf, Jitterbox: %lf, Reloffset: %lf, Cumoffset: %lf",
-	     nodthrow, jitterbox, reloffset, cumoffset) ;
-
-    check(cpl_frameset_insert( result, a_b )) ;
-    check(cpl_frameset_insert( result, b_a )) ;
-  }
-  xsh_msg_dbg_high( "Done OK" ) ;
-
- cleanup:
-  return result ;
 
-}
-#else
 /*****************************************************************************/
 /*****************************************************************************/
 cpl_frameset* xsh_subtract_sky_nod( cpl_frameset *raws_ord_set, 
@@ -244,6 +163,5 @@ cpl_frameset* xsh_subtract_sky_nod( cpl_frameset *raws_ord_set,
 
 }
 /*****************************************************************************/
-#endif
 
 /**@}*/
diff --git a/xsh/xsh_subtract_sky_single.c b/xsh/xsh_subtract_sky_single.c
index 9c74a39..a560c9b 100644
--- a/xsh/xsh_subtract_sky_single.c
+++ b/xsh/xsh_subtract_sky_single.c
@@ -1466,7 +1466,7 @@ xsh_subtract_sky_single (cpl_frame *sci_frame,
 
 /*****************************************************************************/
 /*****************************************************************************/
-static inline int xsh_bspline_eval_all(const double x, gsl_vector *B,
+static int xsh_bspline_eval_all(const double x, gsl_vector *B,
     size_t *idx, gsl_bspline_workspace *w, size_t *start_i) {
   if (B->size != w->k) {
     GSL_ERROR("B vector not of length k", GSL_EBADLEN);
diff --git a/xsh/xsh_utils_image.c b/xsh/xsh_utils_image.c
index c326ca5..230cb7e 100644
--- a/xsh/xsh_utils_image.c
+++ b/xsh/xsh_utils_image.c
@@ -1326,8 +1326,8 @@ xsh_compute_ron(cpl_frameset* frames,
 
    if ( nfrm < 2 ) goto cleanup;
 
-   check(bias1=cpl_frameset_get_first(frames));
-   check(bias2=cpl_frameset_get_next(frames));
+   check(bias1=cpl_frameset_get_frame(frames,0));
+   check(bias2=cpl_frameset_get_frame(frames,1));
    check(name1=cpl_frame_get_filename(bias1));
    check(name2=cpl_frame_get_filename(bias2));
    check(ima1=cpl_image_load(name1,CPL_TYPE_FLOAT,0,0));
@@ -1555,11 +1555,11 @@ xsh_image_search_bad_pixels_via_noise(cpl_imagelist *  darks,
              pbpdata[col+lx*row] < 
              stats->cleanmean-thresh_sigma_factor*stats->cleanstdev) 
          {
-            pbpdata[col+lx*row] = 0. ;
+             pbpdata[col+lx*row] = QFLAG_HOT_PIXEL ;
          }
          else
          {
-            pbpdata[col+lx*row] = QFLAG_HOT_PIXEL ;
+             pbpdata[col+lx*row] = 0. ;
          }
       }
    }
diff --git a/xsh/xsh_utils_response.c b/xsh/xsh_utils_response.c
index 0467b6a..f460a69 100644
--- a/xsh/xsh_utils_response.c
+++ b/xsh/xsh_utils_response.c
@@ -803,7 +803,7 @@ xsh_align_model_to_spectrum(cpl_table* table_me,cpl_table* table_se,const double
   double* flux_s = NULL;
   double* flux_m = NULL;
   int size_s = 0;
-  int hsearch = 500;
+  int hsearch = 200;
   /*
   int size_m = 0;
 
diff --git a/xsh/xsh_utils_scired_slit.c b/xsh/xsh_utils_scired_slit.c
index 93cc1c7..8c89f38 100644
--- a/xsh/xsh_utils_scired_slit.c
+++ b/xsh/xsh_utils_scired_slit.c
@@ -40,7 +40,7 @@
 #include <xsh_error.h>
 #include <xsh_drl_check.h>
 #include <xsh_pfits.h>
-
+#include <xsh_hdrl_functions.h>
 /*
 static int 
 xsh_frame_has_same_nod_pos(cpl_frame* ref, cpl_frame* cmp)
@@ -129,7 +129,7 @@ xsh_stare_params_bin_scale(cpl_frameset* raws,
   int binx=0;
   int biny=0;
 
-  check(frame=cpl_frameset_get_first(raws));
+  check(frame=cpl_frameset_get_frame(raws,0));
   check(name=cpl_frame_get_filename(frame));
   check(plist=cpl_propertylist_load(name,0));
   check(binx=xsh_pfits_get_binx(plist));
@@ -230,7 +230,7 @@ cpl_frameset* xsh_nod_group_by_reloff( cpl_frameset *ord_set,xsh_instrument *ins
 
   cpl_frameset *result = NULL;
   cpl_frameset *rmcrh_set = NULL;
-  cpl_frame *frame = NULL;
+  const cpl_frame *frame = NULL;
   cpl_propertylist *header = NULL;
 
   const char* nod_name = NULL;
@@ -252,7 +252,9 @@ cpl_frameset* xsh_nod_group_by_reloff( cpl_frameset *ord_set,xsh_instrument *ins
 
   check( result=cpl_frameset_new());
 
-  check( frame = cpl_frameset_get_first( ord_set));
+  cpl_frameset_iterator* it = cpl_frameset_iterator_new(ord_set);
+  frame = cpl_frameset_iterator_get(it);
+
   check( nod_name = cpl_frame_get_filename( frame));  
   check( header = cpl_propertylist_load( nod_name, 0));
 
@@ -299,7 +301,9 @@ cpl_frameset* xsh_nod_group_by_reloff( cpl_frameset *ord_set,xsh_instrument *ins
     check( rmcrh_set = cpl_frameset_new());
     cpl_frameset_insert( rmcrh_set, cpl_frame_duplicate( frame));
 
-    check( frame = cpl_frameset_get_next( ord_set));
+    cpl_frameset_iterator_advance(it, 1);
+    frame = cpl_frameset_iterator_get_const(it);
+
     /* finds frame with same nod position to the current one and store them in the same frameset */
     while( frame != NULL){
       check( nod_name = cpl_frame_get_filename( frame));
@@ -314,7 +318,10 @@ cpl_frameset* xsh_nod_group_by_reloff( cpl_frameset *ord_set,xsh_instrument *ins
       else{
         break;
       }
-      check( frame = cpl_frameset_get_next( ord_set));
+
+      cpl_frameset_iterator_advance(it, 1);
+      frame = cpl_frameset_iterator_get_const(it);
+
     }
 
     /* Combine frames with same nod position. This to improve statistics and also remove cosmic ray hits */
@@ -335,6 +342,7 @@ cpl_frameset* xsh_nod_group_by_reloff( cpl_frameset *ord_set,xsh_instrument *ins
   }
 
   cleanup:
+    cpl_frameset_iterator_delete(it);
     if ( cpl_error_get_code() != CPL_ERROR_NONE){
       xsh_free_propertylist( &header);
       xsh_free_frameset( &rmcrh_set);
@@ -386,7 +394,8 @@ cpl_frameset* xsh_nod_group_by_reloff2( cpl_frameset *ord_set,xsh_instrument *in
 
   check( result=cpl_frameset_new());
 
-  check( frame = cpl_frameset_get_first( ord_set));
+  check( frame = cpl_frameset_get_frame( ord_set,0));
+
   check( nod_name = cpl_frame_get_filename( frame));
   check( header = cpl_propertylist_load( nod_name, 0));
 
@@ -1143,7 +1152,7 @@ xsh_scired_get_proper_maps(cpl_frameset* raws, cpl_frameset* calib,
     cpl_frame* ref_frame=NULL;
     int recipe_use_model=FALSE;
     if (xsh_mode_is_physmod(calib,instrument)){
-       ref_frame=cpl_frameset_get_first(raws);
+       ref_frame=cpl_frameset_get_frame(raws,0);
      }
      else{
        ref_frame = master_flat;
@@ -1244,7 +1253,7 @@ xsh_scired_slit_nod_get_calibs(cpl_frameset* raws,
   }
 
   if ( recipe_use_model){
-    ref_frame=cpl_frameset_get_first(raws);
+    ref_frame=cpl_frameset_get_frame(raws,0);
   }
   else{
     ref_frame = *master_flat;

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-astro/packages/cpl-plugin-xsh.git



More information about the debian-science-commits mailing list