/**
 * \brief Visualizes the warped landmark data for debugging purposes
 *
 * This function performs the following operations when DEBUG is enabled:
 * 1. Estimates homography between base and child landmarks
 * 2. Warps the base landmark's surface reflectance map (SRM) and elevation data
 * 3. Saves the warped SRM as a PNG image
 * 4. Saves the warped elevation data as a raw binary file
 *
 * \param base_landmark Pointer to base landmark structure
 * \param child_landmark Pointer to child landmark structure
 * \param visualization_buffer Pointer to temporary image buffer for visualization
 */


/**
 * \brief Helper function to free all allocated memory
 *
 * \param lmk_child Pointer to child landmark structure
 * \param lmk_base Pointer to base landmark structure
 * \param match_pair_base Pointer to base match pairs array
 * \param match_pair_child Pointer to child match pairs array
 * \param template Pointer to template array
 * \param feature_coord Pointer to feature coordinates array
 * \param feature_strength Pointer to feature strength array
 * \param tmpimg Pointer to temporary image buffer
 * \param pts_3d_child Pointer to 3D child points array
 * \param pts_3d_base Pointer to 3D base points array
 */


/**
 * \brief Extract template window from image with NaN handling
 *
 * \param[in] image Source image
 * \param[in] mask Image mask (0 for valid data, 1 for NaN)
 * \param[in] cols Image width
 * \param[in] rows Image height
 * \param[in] center_x Center x coordinate
 * \param[in] center_y Center y coordinate
 * \param[in] template_size Size of template window
 * \param[out] template_buffer Buffer to store template window
 * \param[out] nan_count Number of NaN pixels found
 * \return true if template extraction successful, false otherwise
 */


/**
 * \brief Check for NaN pixels in search window
 *
 * \param[in] mask Image mask
 * \param[in] cols Image width
 * \param[in] left Left boundary of search window
 * \param[in] top Top boundary of search window
 * \param[in] width Window width
 * \param[in] height Window height
 * \return Number of NaN pixels found
 */


//homo is from out to in


// self contained file version detection routine


/*----------------------------------------------------------------------
    void vect_cross(e, p1, p2)
    Perform cross products of 3D vectors: e = P1 X P2
    -------------------------------------------------------------------*/


/* Read any remaining signature bytes from the stream and compare them with
 * the correct PNG signature.  It is possible that this routine is called
 * with bytes already read from the signature, either because they have been
 * checked by the calling application, or because of multiple calls to this
 * routine.
 */


/* Write the pCAL chunk (described in the PNG extensions document) */


/* Function to format a floating point value in ASCII with a given
 * precision.
 */


/* Function to format a fixed point value in ASCII.
 */


/* Read and check the PNG file signature */


/* Read the chunk header (length + type name).
 * Put the type name into png_ptr->chunk_name, and return the length.
 */


/* Optionally skip data and then check the CRC.  Depending on whether we
 * are reading an ancillary or critical chunk, and how the program has set
 * things up, we may calculate the CRC on the data and print a message.
 * Returns '1' if there was a CRC error, '0' otherwise.
 */


/* Compare the CRC stored in the PNG file with that calculated by libpng from
 * the data it has read thus far.
 */


/* Manage the read buffer; this simply reallocates the buffer if it is not small
 * enough (or if it is not allocated).  The routine returns a pointer to the
 * buffer; if an error occurs and 'warn' is set the routine returns NULL, else
 * it will call png_error (via png_malloc) on failure.  (warn == 2 means
 * 'silent').
 */


/* png_inflate_claim: claim the zstream for some nefarious purpose that involves
 * decompression.  Returns Z_OK on success, else a zlib error code.  It checks
 * the owner but, in final release builds, just issues a warning if some other
 * chunk apparently owns the stream.  Prior to release it does a png_error.
 */


/* Remove a channel - this used to be 'png_do_strip_filler' but it used a
 * somewhat weird combination of flags to determine what to do.  All the calls
 * to png_do_strip_filler are changed in 1.5.2 to call this instead with the
 * correct arguments.
 *
 * The routine isn't general - the channel must be the channel at the start or
 * end (not in the middle) of each pixel.
 */


/* Added at libpng-1.5.10 */


/**
 * Creates a new hash set
 *
 * The hash function must return a hash value for the elements to insert.
 * If fnHashFunc is NULL, TIFFHashSetHashPointer will be used.
 *
 * The equal function must return if two elements are equal.
 * If fnEqualFunc is NULL, TIFFHashSetEqualPointer will be used.
 *
 * The free function is used to free elements inserted in the hash set,
 * when the hash set is destroyed, when elements are removed or replaced.
 * If fnFreeEltFunc is NULL, elements inserted into the hash set will not be
 * freed.
 *
 * @param fnHashFunc hash function. May be NULL.
 * @param fnEqualFunc equal function. May be NULL.
 * @param fnFreeEltFunc element free function. May be NULL.
 *
 * @return a new hash set
 */


/**
 * Returns the number of elements inserted in the hash set
 *
 * Note: this is not the internal size of the hash set
 *
 * @param set the hash set
 *
 * @return the number of elements in the hash set
 */


/**
 * Destroy a list. Caller responsible for freeing data objects contained in
 * list elements.
 *
 * @param psList pointer to list head.
 *
 */


/**
 * Destroys an allocated hash set.
 *
 * This function also frees the elements if a free function was
 * provided at the creation of the hash set.
 *
 * @param set the hash set
 */


/**
 * Clear all elements from a hash set.
 *
 * This function also frees the elements if a free function was
 * provided at the creation of the hash set.
 *
 * @param set the hash set
 */


/**
 * Walk through the hash set and runs the provided function on all the
 * elements
 *
 * This function is provided the user_data argument of TIFFHashSetForeach.
 * It must return true to go on the walk through the hash set, or FALSE to
 * make it stop.
 *
 * Note : the structure of the hash set must *NOT* be modified during the
 * walk.
 *
 * @param set the hash set.
 * @param fnIterFunc the function called on each element.
 * @param user_data the user data provided to the function.
 */


/**
 * Inserts an element into a hash set.
 *
 * If the element was already inserted in the hash set, the previous
 * element is replaced by the new element. If a free function was provided,
 * it is used to free the previously inserted element
 *
 * @param set the hash set
 * @param elt the new element to insert in the hash set
 *
 * @return true if success. If false is returned, elt has not been inserted,
 * but TIFFHashSetInsert() will have run the free function if provided.
 */


/**
 * Returns the element found in the hash set corresponding to the element to
 * look up The element must not be modified.
 *
 * @param set the hash set
 * @param elt the element to look up in the hash set
 *
 * @return the element found in the hash set or NULL
 */


/* time if the new compressed tile is bigger than the older one. (GDAL #4771) */


/*
 * Encode the supplied data and write it to the
 * specified strip.
 *
 * NB: Image length must be setup before writing.
 */


/*
 * Write the supplied data to the specified strip.
 *
 * NB: Image length must be setup before writing.
 */


/*
 * Write and compress a tile of data.  The
 * tile is selected by the (x,y,z,s) coordinates.
 */


/*
 * Encode the supplied data and write it to the
 * specified tile.  There must be space for the
 * data.  The function clamps individual writes
 * to a tile to the tile size, but does not (and
 * can not) check that multiple writes to the same
 * tile do not write more than tile size data.
 *
 * NB: Image length must be setup before writing; this
 *     interface does not support automatically growing
 *     the image on each write (as TIFFWriteScanline does).
 */


/*
 * Write the supplied data to the specified strip.
 * There must be space for the data; we don't check
 * if strips overlap!
 *
 * NB: Image length must be setup before writing; this
 *     interface does not support automatically growing
 *     the image on each write (as TIFFWriteScanline does).
 */


/*
 * Verify file is writable and that the directory
 * information is setup properly.  In doing the latter
 * we also "freeze" the state of the directory so
 * that important information is not changed.
 */


/*
 * Setup the raw data buffer used for encoding.
 */


/*
 * Grow the strip data structures by delta strips.
 */


/*
 * Append the data to the specified strip.
 */


/*
 * Internal version of TIFFFlushData that can be
 * called by ``encodestrip routines'' w/o concern
 * for infinite recursion.
 */


/*
 * Set the current write offset.  This should only be
 * used to set the offset to a known previous location
 * (very carefully), or to 0 so that the next write gets
 * appended to the end of the file.
 */


/*
 * Routine for handling various errors/conditions.
 * Note how they are "glued into the decoder" by
 * overriding the definitions used by the decoder.
 */


/*
 * Bit-fill a row according to the white/black
 * runs generated during G3/G4 decoding.
 */


/*
 * Write a variable-length bit-value to
 * the output stream.  Values are
 * assumed to be at most 16 bits.
 */


/*
 * Write the sequence of codes that describes
 * the specified span of zero's or one's.  The
 * appropriate table that holds the make-up and
 * terminating codes is supplied.
 */


/*
 * Write an EOL code to the output stream.  The zero-fill
 * logic for byte-aligning encoded scanlines is handled
 * here.  We also handle writing the tag bit for the next
 * scanline when doing 2d encoding.
 */


/*
 * Reset encoding state at the start of a strip.
 */


/*
 * Find a span of ones or zeros using the supplied
 * table.  The ``base'' of the bit string is supplied
 * along with the start+end bit indices.
 */


/*
 * 1d-encode a row of pixels.  The encoding is
 * a sequence of all-white or all-black spans
 * of pixels encoded with Huffman codes.
 */


/*
 * 2d-encode a row of pixels.  Consult the CCITT
 * documentation for the algorithm.
 */


/*
 * Encode a buffer of pixels.
 */


/*
 * Encode the requested amount of data.
 */


/* Variant of TIFFReadEncodedStrip() that does
 * * if *buf == NULL, *buf = _TIFFmallocExt(tif, bufsizetoalloc) only after
 * TIFFFillStrip() has succeeded. This avoid excessive memory allocation in case
 * of truncated file.
 * * calls regular TIFFReadEncodedStrip() if *buf != NULL
 */


/*
 * Read a strip of data from the file.
 */


/*
 * Read the specified strip and setup for decoding. The data buffer is
 * expanded, as necessary, to hold the strip's data.
 */


/*
 * Read and decompress a tile of data.  The
 * tile is selected by the (x,y,z,s) coordinates.
 */


/* Variant of TIFFReadTile() that does
 * * if *buf == NULL, *buf = _TIFFmallocExt(tif, bufsizetoalloc) only after
 * TIFFFillTile() has succeeded. This avoid excessive memory allocation in case
 * of truncated file.
 * * calls regular TIFFReadEncodedTile() if *buf != NULL
 */


/* Variant of TIFFReadEncodedTile() that does
 * * if *buf == NULL, *buf = _TIFFmallocExt(tif, bufsizetoalloc) only after
 * TIFFFillTile() has succeeded. This avoid excessive memory allocation in case
 * of truncated file.
 * * calls regular TIFFReadEncodedTile() if *buf != NULL
 */


/*
 * Read a tile of data from the file.
 */


/*
 * Read the specified tile and setup for decoding. The data buffer is
 * expanded, as necessary, to hold the tile's data.
 */


/*
 * Setup the raw data buffer in preparation for
 * reading a strip of raw data.  If the buffer
 * is specified as zero, then a buffer of appropriate
 * size is allocated by the library.  Otherwise,
 * the client must guarantee that the buffer is
 * large enough to hold any individual strip of
 * raw data.
 */


/*
 * Set state to appear as if a
 * strip has just been read in.
 */


/**
 * Check whether we have working codec for the specific coding scheme.
 *
 * @return returns 1 if the codec is configured and working. Otherwise
 * 0 will be returned.
 */


/*
 * Error handling routines (these replace corresponding
 * IJG routines from jerror.c).  These are used for both
 * compression and decompression.
 */


/*
 * This routine is invoked only for warning messages,
 * since error_exit does its own thing and trace_level
 * is never set > 0.
 */


/* Avoid the risk of denial-of-service on crafted JPEGs with an insane */
/* number of scans. */
/* See
 * http://www.libjpeg-turbo.org/pmwiki/uploads/About/TwoIssueswiththeJPEGStandard.pdf
 */


/*
 * JPEG library destination data manager.
 * These routines direct compressed data from libjpeg into the
 * libtiff output buffer.
 */


/*
 * Alternate destination manager for outputting to JPEGTables field.
 */


/*
 * JPEG library source data manager.
 * These routines supply compressed data to libjpeg.
 */


/*
 * Alternate source manager for reading from JPEGTables.
 * We can share all the code except for the init routine.
 */


/*
 * Allocate downsampled-data buffers needed for downsampled I/O.
 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
 * We use libjpeg's allocator so that buffers will be released automatically
 * when done with strip/tile.
 * This is also a handy place to compute samplesperclump, bytesperline.
 */


/* Returns 1 if the full strip should be read, even when doing scanline per */
/* scanline decoding. This happens when the JPEG stream uses multiple scans. */
/* Currently only called in CHUNKY_STRIP_READ_SUPPORT mode through */
/* scanline interface. */
/* Only reads tif->tif_dir.td_bitspersample, tif->tif_rawdata and */
/* tif->tif_rawcc members. */
/* Can be called independently of the usual setup/predecode/decode states */


/* This is a modified version of std_huff_tables() from jcparam.c
 * in libjpeg-9d because it no longer initializes default Huffman
 * tables in jpeg_set_defaults(). */


/*
 * Encode a chunk of pixels.
 * "Standard" case: incoming data is not downsampled.
 */


/*
 * Encode a chunk of pixels.
 * Incoming data is expected to be downsampled per sampling factors.
 */


/*
 * Finish up at the end of a strip or tile.
 */


/*
 * The JPEG library initialized used to be done in TIFFInitJPEG(), but
 * now that we allow a TIFF file to be opened in update mode it is necessary
 * to have some way of deciding whether compression or decompression is
 * desired other than looking at tif->tif_mode.  We accomplish this by
 * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
 * If so, we assume decompression is desired.
 *
 * This is tricky, because TIFFInitJPEG() is called while the directory is
 * being read, and generally speaking the BYTECOUNTS tag won't have been read
 * at that point.  So we try to defer jpeg library initialization till we
 * do have that tag ... basically any access that might require the compressor
 * or decompressor that occurs after the reading of the directory.
 *
 * In an ideal world compressors or decompressors would be setup
 * at the point where a single tile or strip was accessed (for read or write)
 * so that stuff like update of missing tiles, or replacement of tiles could
 * be done. However, we aren't trying to crack that nut just yet ...
 *
 * NFW, Feb 3rd, 2003.
 */


/* Common to tif_jpeg.c and tif_jpeg_12.c */


/*
 * Convert color value from the CIE L*a*b* 1976 space to CIE XYZ.
 */


/*
 * For CIELab encoded in 16 bits, L is an unsigned integer range [0,65535].
 * The a* and b* components are signed integers range [-32768,32767]. The 16
 * bit chrominance values are encoded as 256 times the 1976 CIE a* and b*
 * values
 */


/* Clamp function for sanitization purposes. Normally clamping should not */
/* occur for well behaved chroma and refBlackWhite coefficients */


/*
 * Initialize the YCbCr->RGB conversion tables.  The conversion
 * is done according to the 6.0 spec:
 *
 *    R = Y + Cr*(2 - 2*LumaRed)
 *    B = Y + Cb*(2 - 2*LumaBlue)
 *    G =   Y
 *        - LumaBlue*Cb*(2-2*LumaBlue)/LumaGreen
 *        - LumaRed*Cr*(2-2*LumaRed)/LumaGreen
 *
 * To avoid floating point arithmetic the fractional constants that
 * come out of the equations are represented as fixed point values
 * in the range 0...2^16.  We also eliminate multiplications by
 * pre-calculating possible values indexed by Cb and Cr (this code
 * assumes conversion is being done for 8-bit samples).
 */


/*
 * Check the image to see if TIFFReadRGBAImage can deal with it.
 * 1/0 is returned according to whether or not the image can
 * be handled.  If 0 is returned, emsg contains the reason
 * why it is being rejected.
 */


/*
 * Read the specified image into an ABGR-format raster. Use bottom left
 * origin for raster by default.
 */


/*
 * Greyscale images with less than 8 bits/sample are handled
 * with a table to avoid lots of shifts and masks.  The table
 * is setup so that put*bwtile (below) can retrieve 8/bitspersample
 * pixel values simply by indexing into the table with one
 * number.
 */


/*
 * Palette images with <= 8 bits/sample are handled
 * with a table to avoid lots of shifts and masks.  The table
 * is setup so that put*cmaptile (below) can retrieve 8/bitspersample
 * pixel values simply by indexing into the table with one
 * number.
 */


/*
 * Construct any mapping table used
 * by the associated put routine.
 */


/*
 * Select the appropriate conversion routine for packed data.
 */


/*
 * Read a whole strip off data from the file, and convert to RGBA form.
 * If this is the last strip, then it will only contain the portion of
 * the strip that is actually within the image space.  The result is
 * organized in bottom to top form.
 */


/*
 * Read a whole tile off data from the file, and convert to RGBA form.
 * The returned RGBA data is organized from bottom to top of tile,
 * and may include zeroed areas if the tile extends off the image.
 */


/** Define a limit in bytes for a single memory allocation done by libtiff.
 *  If max_single_mem_alloc is set to 0, which is the default, no other limit
 *  that the underlying _TIFFmalloc() or
 *  TIFFOpenOptionsSetMaxCumulatedMemAlloc() will be applied.
 */


/*
 * Set the file name.
 */


/*
 * Set open file's I/O descriptor, and return previous value.
 */


/*
 * Set open file's clientdata, and return previous value.
 */


/*
 * Return read/write mode.
 */


/*
 * Encode a chunk of pixels.
 */


/*
 * Encode a hunk of pixels.
 */


/*
 * Decode a hunk of pixels.
 */


/*
 * Seek forwards nrows in the current strip.
 */


/*
 * Initialize dump mode.
 */


/*
 * Reset encoding hash table.
 */


/*
 * Return 1/0 according to whether or not
 * it is permissible to set the tag's value.
 * Note that we allow ImageLength to be changed
 * so that we can append and extend to images.
 * Any other tag may not be altered once writing
 * has commenced, unless its value has no effect
 * on the format of the data that is written.
 */


/*
 * Record the value of a field in the
 * internal directory structure.  The
 * field will be written to the file
 * when/if the directory structure is
 * updated.
 */


/*
 * Clear the contents of the field in the internal structure.
 */


/*
 * Like TIFFSetField, but taking a varargs
 * parameter list.  This routine is useful
 * for building higher-level interfaces on
 * top of the library.
 */


/*
 * Return the value of a field in the
 * internal directory structure.
 */


/*
 * Like TIFFGetField, but taking a varargs
 * parameter list.  This routine is useful
 * for building higher-level interfaces on
 * top of the library.
 */


/*
 * Creates the EXIF GPS custom directory
 */


/*
 * Setup a default directory structure.
 */


/*
 * Print the contents of the current directory
 * to the specified stdio file stream.
 */


/*
 * Compute the # bytes in a raw strip.
 */


/*
 * Compute the # bytes in a (row-aligned) strip.
 *
 * Note that if RowsPerStrip is larger than the
 * recorded ImageLength, then the strip size is
 * truncated to reflect the actual space required
 * to hold the strip.
 */


/*
 * Return the number of bytes required to store a complete
 * decoded and packed raster scanline (as opposed to the
 * I/O size returned by TIFFScanlineSize which may be less
 * if data is store as separate planes).
 */


/*
  Unaligned safe copy of a uint64_t value from an octet array.
*/


/* Check that the 8-byte unsigned value can fit in a 4-byte unsigned range */


/* Check that the 8-byte signed value can fit in a 4-byte signed range */


/*
 * Return the maximum number of color channels specified for a given photometric
 * type. 0 is returned if photometric type isn't supported or no default value
 * is defined by the specification.
 */


/*
 * Check the directory number and offset against the list of already seen
 * directory numbers and offsets. This is a trick to prevent IFD looping.
 * The one can create TIFF file with looped directory pointers. We will
 * maintain a list of already seen directories and check every IFD offset
 * and its IFD number against that list. However, the offset of an IFD number
 * can change - e.g. when writing updates to file.
 * Returns 1 if all is ok; 0 if last directory or IFD loop is encountered,
 * or an error has occurred.
 */


/*
 * Retrieve the matching IFD directory number of a given IFD offset
 * from the list of directories already seen.
 * Returns 1 if the offset was in the list and the directory number
 * can be returned.
 * Otherwise returns 0 or if an error occurred.
 */


/*
 * Retrieve the matching IFD directory offset of a given IFD number
 * from the list of directories already seen.
 * Returns 1 if the offset was in the list of already seen IFDs and the
 * directory offset can be returned. The directory list is not updated.
 * Otherwise returns 0 or if an error occurred.
 */


/*
 * Remove an entry from the directory list of already seen directories
 * by directory offset.
 * If an entry is to be removed from the list, it is also okay if the entry
 * is not in the list or the list does not exist.
 */


/*
 * Check the count field of a directory entry against a known value.  The
 * caller is expected to skip/ignore the tag if there is a mismatch.
 */


/*
 * Fetch and set the SubjectDistance EXIF tag.
 */


/* Read the value of [Strip|Tile]Offset or [Strip|Tile]ByteCount around
 * strip/tile of number strile. Also fetch the neighbouring values using a
 * 4096 byte page size.
 */


/* Return the value of the TileOffsets/StripOffsets array for the specified
 * tile/strile */


/* Return the value of the TileByteCounts/StripByteCounts array for the
 * specified tile/strile */


/**
 * Close a previously opened TIFF file.
 *
 * TIFFClose closes a file that was previously opened with TIFFOpen().
 * Any buffered data are flushed to the file, including the contents of
 * the current directory (if modified); and all resources are reclaimed.
 *
 * @param tif A TIFF pointer.
 */


/*
 *  We have our own local lfind() equivalent to avoid subtle differences
 *  in types passed to lfind() on different systems.
 */


/*
 * Return size of TIFFDataType within TIFF-file in bytes
 */


/****************************************************************************
 *               O B S O L E T E D    I N T E R F A C E S
 *
 * Don't use this stuff in your applications, it may be removed in the future
 * libtiff versions.
 ****************************************************************************/


/*
 * Encode a rectangular chunk of pixels.  We break it up
 * into row-sized pieces to insure that encoded runs do
 * not span rows.  Otherwise, there can be problems with
 * the decoder if data is read, for example, by scanlines
 * when it was encoded by strips.
 */


/*
 * Compute which tile an (x,y,z,s) value is in.
 */


/*
 * Check an (x,y,z,s) coordinate
 * against the image bounds.
 */


/*
 * Compute how many tiles are in an image.
 */


/*
 * Compute the # bytes in each row of a tile.
 */


/*
 * Compute the # bytes in a variable length, row-aligned tile.
 */


/*
** This provides read/write access to the TIFFTagMethods within the TIFF
** structure to application code without giving access to the private
** TIFF structure.
*/


/*
 * This is an advanced writing function that must be used in a particular
 * sequence, and generally together with TIFFForceStrileArrayWriting(),
 * to make its intended effect. Its aim is to modify the location
 * where the [Strip/Tile][Offsets/ByteCounts] arrays are located in the file.
 * More precisely, when TIFFWriteCheck() will be called, the tag entries for
 * those arrays will be written with type = count = offset = 0 as a temporary
 * value.
 *
 * Its effect is only valid for the current directory, and before
 * TIFFWriteDirectory() is first called, and  will be reset when
 * changing directory.
 *
 * The typical sequence of calls is:
 * TIFFOpen()
 * [ TIFFCreateDirectory(tif) ]
 * Set fields with calls to TIFFSetField(tif, ...)
 * TIFFDeferStrileArrayWriting(tif)
 * TIFFWriteCheck(tif, ...)
 * TIFFWriteDirectory(tif)
 * ... potentially create other directories and come back to the above directory
 * TIFFForceStrileArrayWriting(tif): emit the arrays at the end of file
 *
 * Returns 1 in case of success, 0 otherwise.
 */


/*
 * Similar to TIFFWriteDirectory(), writes the directory out
 * but leaves all data structures in memory so that it can be
 * written again.  This will make a partially written TIFF file
 * readable before it is successfully completed/closed.
 */


/**---- ToRationalEuclideanGCD() -----------------------------------------
* Calculates the rational fractional of a double input value
* using the Euclidean algorithm to find the greatest common divisor (GCD)
------------------------------------------------------------------------*/


/**---- DoubleToRational() -----------------------------------------------
* Calculates the rational fractional of a double input value
* for UN-SIGNED rationals,
* using the Euclidean algorithm to find the greatest common divisor (GCD)
------------------------------------------------------------------------*/


/**---- DoubleToSrational() -----------------------------------------------
* Calculates the rational fractional of a double input value
* for SIGNED rationals,
* using the Euclidean algorithm to find the greatest common divisor (GCD)
------------------------------------------------------------------------*/


/**
 * Get list of configured codecs, both built-in and registered by user.
 * Caller is responsible to free this structure.
 *
 * @return returns array of TIFFCodec records (the last record should be NULL)
 * or NULL if function failed.
 */


/*
 * Decode a string of 16-bit gray pixels.
 */


/*
 * Decode a string of 24-bit pixels.
 */


/*
 * Decode a string of 32-bit pixels.
 */


/*
 * Decode a strip of pixels.  We break it into rows to
 * maintain synchrony with the encode algorithm, which
 * is row by row.
 */


/*
 * Decode a tile of pixels.  We break it into rows to
 * maintain synchrony with the encode algorithm, which
 * is row by row.
 */


/*
 * Encode a row of 16-bit pixels.
 */


/*
 * Encode a row of 24-bit pixels.
 */


/*
 * Encode a row of 32-bit pixels.
 */


/*
 * Encode a strip of pixels.  We break it into rows to
 * avoid encoding runs across row boundaries.
 */


/*
 * Encode a tile of pixels.  We break it into rows to
 * avoid encoding runs across row boundaries.
 */


/*
 * Like TIFFGetField, but return any default
 * value if the tag is not present in the directory.
 */


/*
 * This is an advanced writing function that must be used in a particular
 * sequence, and together with TIFFDeferStrileArrayWriting(),
 * to make its intended effect. Its aim is to force the writing of
 * the [Strip/Tile][Offsets/ByteCounts] arrays at the end of the file, when
 * they have not yet been rewritten.
 *
 * The typical sequence of calls is:
 * TIFFOpen()
 * [ TIFFCreateDirectory(tif) ]
 * Set fields with calls to TIFFSetField(tif, ...)
 * TIFFDeferStrileArrayWriting(tif)
 * TIFFWriteCheck(tif, ...)
 * TIFFWriteDirectory(tif)
 * ... potentially create other directories and come back to the above directory
 * TIFFForceStrileArrayWriting(tif)
 *
 * Returns 1 in case of success, 0 otherwise.
 */


/*
 * Flush buffered data to the file.
 *
 * Frank Warmerdam'2000: I modified this to return 1 if TIFF_BEENWRITING
 * is not set, so that TIFFFlush() will proceed to write out the directory.
 * The documentation says returning 1 is an error indicator, but not having
 * been writing isn't exactly a an error.  Hopefully this doesn't cause
 * problems for other people.
 */


/**
  Report an error message or warning and exit if error is fatal.

  @param level severety of the message, one of

aXe_M_FATAL (fatal error,
    exit),

aXe_M_ERROR (an error that will invalidate the result but doesn't
    preclude further processing within the program),

aXe_M_WARN1 (a problem that will most likely invalidate the result),

aXe_M_WARN2 (a problem that may invalidate the result),

aXe_M_WARN3 (a problem that might be looked into, but probably all is
    ok),

aXe_M_WARN4 (informational messages only).

  @param w_file the module the error occurred in.
  @param w_line the line the error occurred in.
  @param message the error message -- this works like printf
*/


/**
  fill in the path length field (xi in ap_pixel) from the abscissas (xs in
  ap_pixel) (helper function for spc_extract).

  @param func the spectrum trace to use for the transformation from xs to xi
  @param table a pointer to the table of aperture pixels, terminated with
  x=-1
*/


/**
   creates an ap_pixel.

   @param x x coordinate of pixel relative to beam's reference point
   @param y y coordinate of pixel relative to beam's reference point
   @param px absolute x coordinate of the pixel
   @param py absolute y coordinate of the pixel
   @param ob the observation to get the pixels from
   @param sf pointer to sectionfun structure for this beam
   @param cur_ap a pointer to the next free aperture pixel
   @return a pointer to the next free aperture pixel after the new pixels
    have been added.

*/


/**
   Does some sanity checks on make_spc_table's input.

   @param ob the object to check
   @return 0 if everything is ok, -1 otherwise
*/


/**
   computes a table of aperture pixels, i.e. of tuples containing the
   source coordinates, the distance to the spectrum trace, the path
   length along the trace, and the intensity.  The end of the table
   is marked with an ap_pixel->x==-1.  This routine can do subsampling,
   whereby each pixel is divided into n_sub*n_sub smaller pixels.
   If n_sub==1, a special (faster) handling is enabled.

   @param ob the object struct to examine
   @param beamorder the order of the spectrum to examine
   @param flags warning flags like in the warning field of the
     spectrum structure.  This has to be passed in initialized.
*/


/**
   Similar to make_spc_table, it just works only
   on one spot given in the parameters.
*/


/**
 * Function: copy_basic_input
 * The function fills one entry in an 'axe_items'-structure with
 * data from one line of the Input Image List. The data is just
 * transferred as an item list, column indices are already known.
 *
 * Parameters:
 * @param line_array - the item list of the line
 * @param iol_array  - the item list of the Input Object Lists
 * @param conf_array - the item list of the configuration files (from input)
 * @param arr_index  - the multiplicity index
 * @param dirim_col  - direct column index
 * @param dmag_col   - dmag column index
 * @param axe_item   - the aXe input to fill
 *
 * Returns:
 * @return -
 */


/**
 * Function: extract_axe_inputs
 * The function converts the data given in an Input Image List and in
 * the line input (for aXe configuration files) to a list of aXe inputs.
 * the columns to find optional inputs such as direct images are
 * given as parameters.
 * The filled structure with the aXe inputs is returned.
 *
 * Parameters:
 * @param inima     - the name of the input image list
 * @param confterm  - the configuration files given in the input
 * @param nrows     - the number of rows
 * @param nmult     - the multiplicity
 * @param dirim_col - the direct column index
 * @param conf_col  - the configuration column index
 * @param dmag_col  - the dmag column index
 *
 * Returns:
 * @return in_list - the resolved list of aXe inputs
 */


/**
 * Function: is_valid_inima_line
 * Checks whether a character string is a valid line in an input image
 * list, which means it has zero length and does not start with a '#'.
 * The function returns the number of items for valid lines and 0 otherwise.
 *
 * Parameters:
 * @param input_line - the character string to analyze
 *
 * Returns:
 * @return nitems - the number of items using blank as separator
 */


/**
 * Function: alloc_char_array
 * The function allocates memory for a character array
 * structure, which is given back to the calling routine.
 *
 * Parameters:
 * @param nitems - the number of items in the charcter array
 *
 * Returns:
 * @return an_array - the allocated character array
 */


/**
 * Function: free_char_array
 * The function releases the memory of a character array.
 *
 * Parameters:
 * @param an_array - the character array
 *
 * Returns:
 * @return -
 */


/**
 * Function: print_char_array
 * The function prints the content of a character
 * array onto the screen.
 *
 * Parameters:
 * @param an_array - the character array
 *
 * Returns:
 * @return -
 */


/**
 *Function: alloc_axe_inputs
 *
 * The function allocates memory for an 'axe_inputs' structure with
 * a defined number of entries of type basic_input.
 *
 * Parameters:
 * @param nitems - the number of items in the aXe input list
 *
 * Returns:
 * @return axe_inputs - the allocated aXe input structure
 */


/**
 *Function: free_axe_inputs
 *
 * The function releases memory in an 'axe_inputs' structure.
 *
 * Parameters:
 * @param in_list - the aXe input structure
 *
 * Returns:
 * @return -
 */


/**
 *Function: print_axe_inputs
 *
 * Print the content of the structure onto the screen.
 *
 * Parameters:
 * @param in_list - the aXe input structure
 *
 * Returns:
 * @return -
 */


/**
 * Function: trim
 * Trim leading and trailing blank charachters from a string.
 * blank charachters are the one recognised as such by the isspace lib function
 * (Space, horizontal and vertical tab, form feed, carriage return).
 *
 * Parameters:
 * @param inString  - the input string
 * @param outString - the output string
 *
 * Returns:
 * @return -
 */


/*
 * Function: print_state
 * The function prints a status report
 * on a multi-dimensional root finding
 * solver onto the screen
 *
 * Parameters:
 * @param iter - the iteration number
 * @param s    - the multi-d solver
 */


/*
 * Function: drizzle_distort
 * This function can be passed to a gsl multi-d function.
 * It defines the function:
 * x'=f'(x,y) = f(x,y)-x_0
 * y'=g'(x,y) = g(x,y)-y_0
 * with f(x,y) and g(x,y) the equations to undistort
 * the coordinates x and y, respectively and the
 * constants x_0 and y_0.
 * Solving for f'(x,y)=g'(x,y)=0.0
 * means to find (x,y) such that
 * f(x,y) = x_0 and g(x,y) = y_0.
 *
 * Parameters:
 * @param x      - the input x,y
 * @param params - the parameters for the function
 * @param f      - the result values in x,y
 *
 * Returns:
 * @return GSL_SUCCESS - always
 */


/*
 * Function: distort_point
 * The function finds the distorted coordinates
 * for a given undistorted coordinate and the
 * transformations to get the undistorted coordinates.
 * This function makes the inverse transformation
 * to the drizzle transformation.
 *
 * Parameters:
 * @param coeffs   - the drizzle coefficients
 * @param pixmax   - the image dimensions
 * @param xy_image - the undistorted (x,y)
 *
 * Returns:
 * @return xy_ret - the distorted (x,y)
 */


/*
 * Function: undistort_point
 *
 * Parameters:
 * @param coeffs   - the drizzle coefficients
 * @param pixmax   - the image dimensions
 * @param xy_image - the undistorted (x,y)
 *
 * Returns:
 * @return xy_new - the undistorted (x,y)
 */


/*
 * Function: evaln
 * The function evaluates the drizzle coefficients to return
 * either the x- or y-value in the undistorted system.
 * This is a translation of a fortran function with
 * the identical name inside the drizzle package.
 *
 * Parameters:
 * @param x         - the x-value in the distorted system
 * @param y         - the y-value in the distorted system
 * @param drzcoeffs - the drizzle coefficients
 * @param row       - which row of the coefficients to evaluate
 *
 * Returns:
 * @return ret - the undistorted coordinate value
 */


/*
 * Function: devalndx
 * The function numerically differentiates the
 * function 'evaln' with respect to the x-axis.
 *
 * Parameters:
 * @param x         - the x-value in the distorted system
 * @param y         - the y-value in the distorted system
 * @param drzcoeffs - the drizzle coefficients
 * @param row       - which row of the coefficients to evaluate
 *
 * Returns:
 * @return ret - the differential
 */


/*
 * Function: devalndy
 * The function numerically differentiates the
 * function 'evaln' with respect to the y-axis.
 *
 * Parameters:
 * @param x         - the x-value in the distorted system
 * @param y         - the y-value in the distorted system
 * @param drzcoeffs - the drizzle coefficients
 * @param row       - which row of the coefficients to evaluate
 *
 * Returns:
 * @return ret - the differential
 */


/**
 * Function: aperture_conf_fprintf
 * Function to output the content of an aperture_conf structure.
 *
 * Parameters:
 * @param file - a pointer to an output stream or file
 * @param conf - a pointer to an existing aperture_conf structure
 */


/**
 * Function: free_aperture_conf
 * The function releases all memory allocated
 * in a configuration structure.
 *
 * Parameters:
 * @param conf - the configuration structure
 */


/**
 * Function: extend_config_beams
 * The function extends the size of the beams in a
 * configuration structure.
 *
 * Parameters:
 * @param conf - the configuration structure
 */


/**
 * Function: zero_tlength
 * Helper function for the 1D-root finding routine.
 * Evaluates a functional value at the position given
 * in the first parameter using the values given
 * as second parameter.
 *
 * Parameters:
 * @param x      - the independent value
 * @param params - ingredients to evaluate the function value
 *
 * Returns:
 * @return tzero - the function value
 */


/**
 * Function: condense_dispersion
 * The function strips off leading zeroes in the high order terms
 * of the dispersion solution derived from the configuration file.
 * These usually become a problem in the inversion to derive the
 * tracelength.
 *
 * Parameters:
 * @param disp__input - the configuration file dispersion
 *
 * Returns:
 * @return cdisp - the effective dispersion relation
 */


/**
 * Function: fitting_ipc_corr
 *
 * Parameters:
 * @param actbeam        - the beam to examine
 * @param conf_file_path - the full pathname too the configuration file
 * @param ipcorr         - the interpolator with the correction factor
 * @param SPC            - the full spectrum to correct
 * @param obs            - the grism image
 * @param data_matrix    - background subtracted grism image
 * @param ipc_file_path  - file name for the phase data
 *
 * Returns:
 * @return icorr - marker whether the correction was applied or not (1/0)
 */


/**
 * Function: intpix_corr_beam
 * The functio corrects a full spectrum for the intrapixel sensitivity
 * variations.
 * For every spectral element its fractional y-value is determined,
 * and then the correction factor for this y-value is computed
 * and applied to the appropriate elements of the spectral bin.
 *
 * Parameters:
 * @param actbeam        - the beam to examine
 * @param conf_file_path - the full pathname too the configuration file
 * @param ipcorr         - the interpolator with the correction factor
 * @param SPC            - the full spectrum to correct
 *
 * Returns:
 * @return -
 */


/**
 * Function: apply_corr_pet
 * The function applies an intra-pixel sensitivity correction to
 * a list of PET pixels. The correction values are given depending
 * on the wavelength of the pixel, and are applied to the PET pixels
 * in place.
 *
 * Parameters:
 * @param ipclambda - the ipc correction factor as function of wavelength
 * @param PET       - the list of PET pixels to correct
 *
 * Returns:
 * -
 */


/**
 * Function: intpix_corr_pet
 * The function applies the intra-pixel sensitivity correction to
 * a list of PET pixels. The values in the pixels are corrected in
 * place using the correction function, gemoetrical parameters and
 * dispersion relation in the various parameters.
 *
 * Parameters:
 * @param actbeam        - the beam to correct
 * @param conf_file_path - full path to the axe configuration file
 * @param ipcorr         - the ipc correction function
 * @param PET            - the list of PET pixels to correct
 *
 * Returns:
 * -
 */


/**
 * Function: is_pointlike
 * The function evaluates all criteria to decide whether an object
 * is pointlike or not. In the current implementation an object
 * is considered pointlike if a special OAF is given and the
 * the beam is NOT excluded OR if the spatial extension of the
 * object is smaller than the maximal extension.
 *
 * Parameters:
 * @param actbeam   - the beam to examine
 * @param spec_OAF  - indicates a special OAF file
 * @param max_ext   - the maximal allowed extension
 *
 * Returns:
 * @return point_like - pointer to the opened fits file
 */


/**
 * Function: free_full_spectr
 * The function frees the memory allocated in a full
 * spectrum structure.
 *
 * Parameters:
 * @param SPC - the full spectrum structure
 *
 * Returns:
 * @return -
 */


/**
 * Function: create_nlincor
 * The function creates an interpolator for the nonlinearity
 * correction applied to NICMOS data.
 *
 * Parameters:
 *
 * Returns:
 * @return nlincorr - the interpolator created
 */


/**
 * Function: nlin_corr_beam
 *
 * Parameters:
 * @param nlincorr       - the interpolator with the correction factor
 * @param SPC            - the full spectrum to correct
 *
 * Returns:
 * @return -
 */


/**
 * Function: fit_to_FITScards
 * Fills the results of the fitting into a set of fits cards.
 *
 * Parameters:
 * @param bck_vals   - vector with the fit results
 * @param npixels    - dimension of all images
 *
 * Returns:
 * @return cards - the list of fits header cards
 */


/**
 * Function: make_scale_back
 * Loads the various image data inputs and performs a fit using a kappa-sigma
 * clipping iteration. Then a scaled version of one of the input images
 * is produced and written to disk. Optionally, an ASCII list with the
 * pixel values before the fitting is produced.
 *
 * Parameters:
 * @param grism_image - full pathname to the grism image
 * @param grism_mask  - full pathname to the mask image
 * @param conf_file   - full pathname to the configuration file
 * @param scale_image - full pathname to the scaling (=master sky) image
 * @param bck_image   - full pathname to the scaled (=background) image
 * @param plist_name  - full pathname to the pixel list
 * @param scale_to_master - integer/boolean to specify what should be scaled as output
 * @param make_plis   - integer/boolean to request a pixel list as output
 *
 * Returns:
 * @return -
 */


/**
 * Function: print_plis
 * Prints the content of a pixel list structure
 * to an ASCII file.
 *
 * Parameters:
 * @param fbck_data  - the list of pixel values
 * @param plist_name - full pathname to the pixel list
 *
 * Returns:
 * @return -
 */


/**
 * Function: compute_scale_grism
 * Computes a scaled version of the input grism images, using the
 * scale given as input. Pixels masked in other images are given
 * a fixed value.
 *
 * Parameters:
 * @param gr_img  - the list of pixel values
 * @param gr_dqval - full pathname to the pixel list
 * @param gr_mask - full pathname to the pixel list
 * @param bck_vals - full pathname to the pixel list
 *
 * Returns:
 * @return bck_img - the scaled grism image
 */


/**
 * Function: compute_scale_master
 * Computes a scaled version of the scaling (=master sky) image,
 * using the scale given as input.
 *
 * Parameters:
 * @param sc_img  - the list of pixel valuessc_img
 * @param bck_vals - full pathname to the pixel list
 *
 * Returns:
 * @return bck_img - the scaled grism image
 */


/**
 * Function: fill_mask_data
 * Fills the pixel value structure with the data for the x/y-positions,
 * the grism image and the scaling image values and a weigth. dq-flagged
 * pixels and masked pixel are neglected. The mask is supposed to be a background
 * mask where pixel with a value < 900000 shall be neglected.
 * The weights are initially all set to 1.
 *
 * Parameters:
 * @param gr_img    - the grism image array
 * @param gr_dqval  - the dq-value array
 * @param gr_mask   - the grism mask array
 * @param sc_img    - the scaling image array
 * @param fbck_data - the pixel list structure
 * @param dqmask    - dq value from the configuration file
 *
 * Returns:
 * @return -
 */


/**
 * Function: fill_cont_data
 * Fills the pixel value structure with the data for the x/y-positions,
 * the grism image and the scaling image values and a weigth. dq-flagged
 * pixels and masked pixel are neglected. The mask is supposed to be a geometric
 * contamination where pixel with a value > 0 shall be neglected.
 * The weights are initially all set to 1.
 *
 * Parameters:
 * @param gr_img    - the grism image array
 * @param gr_dqval  - the dq-value array
 * @param gr_mask   - the grism mask array
 * @param sc_img    - the scaling image array
 * @param fbck_data - the pixel list structure
 *
 * Returns:
 * @return -
 */


/**
 * Function: make_ksig_scalefit
 * Determines the scale from the values in the pixel value structure.
 * The results are determined iteratively while rejecting pixels via
 * kappa-sigma clipping to get robust measurements. The results are
 * the scale value, the standard deviation, the final number of
 * not rejected points and the number of iterations.
 *
 * Parameters:
 * @param fbck_data - the pixel value structure
 *
 * Returns:
 * @return bck_vals - a vector with the fit results
 */


/**
 * Function: clipp_scale_data
 * Set the weight in the pixel value structure such as to clip
 * point that deviate from the mean/characteristic value by
 * more than the allowed amount.
 *
 * Parameters:
 * @param fbck_data - pixel values from one image
 * @param bck_vals  - vector for the result
 * @param kappa     - vector for the result
 *
 * Returns:
 * @return nclip - integer/boolean indicating new clipping
 */


/**
 * Function: object_list_to_file
 * Dump an object apperture list into a file
 *
 * Parameters:
 * @param oblist           - a point to an object list
 * @param filename         - name of the file to write output
 * @param leaveout_ignored - if ignore=1 beams are left out of the aper file
 *
 * Returns:
 * @return num - number of beams written to the aperture file
 */


/**
 * Function: aper_file_apernum
 * A helper function which returns the number of time the keyword
 * APERTURE appears in an Aperture File and returns that number.
 *
 * Parameters:
 * @param name of an Aperture File
 *
 * Returns:
 * @return number of time APERTURE appears in the file
 */


/**
 * Function: aper_file_aperlist
 * This function returns a gsl_vector containing the list of apertures
 * found in the given aperture file.
 *
 * Parameters:
 * @param filename - the name of the aperture file
 *
 * Returns:
 * @return apers - a gsl_vector_int * containing the list of aperture IDs
 */


/**
 * Function: nbeams_from_aper_file
 * Read an Aperture File and returns the number of beams
 * found for a given aperture number (up to MAX_BEAMS)
 *
 * Parameters:
 * @param filename - name of Aperture File
 * @param num      - number of apertures found in Aperture File
 *
 * Returns:
 * @returns nbeam - the number of beams for the aperture
 */


/**
 * Function: nbeams_from_char_array2
 * Read an Aperture File and returns the number of beams
 * found for a given aperture number (up to MAX_BEAMS)
 *
 * Parameters:
 * @param filename - name of Aperture File
 * @param num      - number of apertures found in Aperture File
 *
 * Returns:
 * @return nbeam - the number of beams for the aperture
 *
 */


/**
 * Function: nbeams_from_char_array
 * Read an Aperture File and returns an integer array
 * which lists the integer ID's of the beams found
 * in the given aperture.
 *
 * Parameters:
 * @param filename - name of Aperture File
 * @param num      - number of apertures found in Aperture File
 *
 * Returns:
 * @return beamIDs - the array with beam ID's
 */


/**
 * Function: find_object_in_object_list
 * This function returns the array index of the object in a NULL terminated
 * array of objects which corresponds to the passed ID
 *
 * Parameters:
 * @param oblist - a NULL terminated array of objects
 * @param ID     - the numeric ID of the object/aperture to look for
 *
 * Returns:
 * @return i/-1  - the array index to the object/aperture with the wanted ID
 */


/**
 * Function: find_beam_in_object_list
 * This function returns the array index of the object in a NULL terminated
 * array of objects which corresponds to the passed ID
 *
 * Parameters:
 * @param oblist - a NULL terminated array of objects
 * @param objID  - the numeric ID of the object/aperture to look for
 * @param beamID - the numeric ID of the beam to look for
 *
 * Returns:
 * @return actbeam  - the beam identitified
 */


/**
 * Function: find_beamptr_in_object_list
 * This function returns the array index of the object in a NULL terminated
 * array of objects which corresponds to the passed ID
 *
 * Parameters:
 * @param oblist - a NULL terminated array of objects
 * @param objID  - the numeric ID of the object/aperture to look for
 * @param beamID - the numeric ID of the beam to look for
 *
 * Returns:
 * @return actbeam  - the beam identitified
 */


/**
 * Function: object_list_size
 * This function returns the number of element in an array
 * of objects.
 *
 * Parameters:
 * @param oblist - a NULL terminated array of objects
 *
 * Returns:
 * @return i     - number of elements
 */


/**
 * Function: add_to_spec_table
 * adds some count to an entry in the spectrum table
 *
 * Parameters:
 * @param spec the spectrum table to work on
 * @param bin index of spectrum table entry to add cur_p to
 * @param cur_p the ap_pixel to add
 * @param weight weight of the count
 */


/**
 * Function: pixweight_x
 * computes a weight for the bin between coordinates (x1,y1) and (x2,y2)
 * if the pi/4<=angle<=3 pi/4.
 *
 * Parameters:
 * @param x1 - x coordinate for the start point of the bin on the trace
 * @param y1 - y coordinate for the start point of the bin on the trace
 * @param x2 - x coordinate for the end point of the bin on the trace
 * @param y2 - y coordinate for the end point of the bin on the trace
 * @param pix the pixel to compute the weight for in the form of a
 *            w_pixel structure filled out by fill_w_pixel
 *
 * Returns:
 * @return sum - the pixel weight
 */


/**
 * Funtion: pixweight_y
 * Computes a weight for the bin between coordinates (x1,y1) and (x2,y2)
 * if the angle<=pi/4 or 3 pi/4<=angle.
 *
 * @param x1 - x coordinate for the start point of the bin on the trace
 * @param y1 - y coordinate for the start point of the bin on the trace
 * @param x2 - x coordinate for the end point of the bin on the trace
 * @param y2 - y coordinate for the end point of the bin on the trace
 * @param pix - the pixel to compute the weight for in the form of a
 *              w_pixel structure filled out by fill_w_pixel
 *
 * Returns:
 * @return sum - the pixel weight
 */


/* since we're only interested in weights here, the size of the square
 *  doesn't matter.  Where I left explicit ones, you could write size
 * and get the true area instead of the fraction of the total area.
 * Dunno why you'd want to do this, though.
 */


/**
 * Function: bin_naive
 * computes a spectrum from a table of aperture pixels generated from
 * spc_extract.  This is adds up the pixel values, distributing them
 * over the trace, taking into account the fracton of the pixel that
 * projects onto the given [xi,xi+1] interval.
 * Return NULL if ap_p is NULL
 *
 * Parameters:
 * @param ap_p the table of aperture pixels
 * @param px_width width of a pixel (=1 if not subsampled)
 * @param ob_width the width of the object that has generated the spectrum
 * @param ob_orientation the orientation of the object that has
 *             generated the spectrum
 * @param flags problems that were accumulated in generating ap_p;
 *   possible flags are defined for the warning member of the spectrum struct
 *
 * Returns:
 * @return spec - the 1D spectrum
 */


/**
 * Function: bin_optimal
 * computes a spectrum from a table of aperture pixels generated from
 * spc_extract.  This is adds up the pixel values, distributing them
 * over the trace, taking into account the fracton of the pixel that
 * projects onto the given [xi,xi+1] interval.
 * Return NULL if ap_p is NULL
 *
 * Parameters:
 * @param ap_p the table of aperture pixels
 * @param px_width width of a pixel (=1 if not subsampled)
 * @param ob_width the width of the object that has generated the spectrum
 * @param ob_orientation the orientation of the object that has
 *             generated the spectrum
 * @param flags problems that were accumulated in generating ap_p;
 *   possible flags are defined for the warning member of the spectrum struct
 *
 * Returns:
 * @return spec - the 1D spectrum
 */


/**
  does a straight forward summation/binning of an aperture pixel table
  with appropriate weights (cf. Hornes 1986)

  @param ap_p the table of aperture pixels
  @param ob_orient the orientation of the object that has
    generated the spectrum
  @param flags problems that were accumulated in generating ap_p;
    possible flags are defined for the warning member of the spectrum struct
  @param n_sub subsampling factor
  @return an allocated spectrum
  @see spectrum
*/


/**
 * Function: is_pt_in_a_beam
 * The function checks whether a particular image pixel is part
 * of a beam or not. The pixel is checked against an array
 * of beams it could be part of.
 *
 * Parameters:
 * @param apoint  - the point to check
 * @param iids    - an array of is_in_descriptors for all the beams that
 *                  should be checked
 * @param tnbeams - number of beams in iids
 *
 * Returns:
 * @return 1/0   - fixed values
 */


/**
 * Function: compute_background
 * The function extracts possible background pixels for a given
 * beam using a specified interpolation functions.
 * After possibly rejecting cosmics, the background is
 * interpolated on the areas which are masked out. The interpolated
 * values are filled into a background structure. If kappa-sigma klipping
 * is applied, the clipped pixels are flagged in the dq-array
 * of the background image.
 *
 * Parameters:
 * @param  obs         - the object list
 * @param  actbeam     - the beam to compute the background for
 * @param  bck_mask    - the background mask
 * @param  fib         - the baground structure
 * @param  npoints     - the number of interpolation points
 * @param  interporder - the interpolation order
 * @param  niter_med   - the number of iterations around the median
 * @param  niter_fit   - the number of iterations around the fit
 * @param  kappa       - the kappa value
 */


/**
 * Function: comp_kappasigma_interp
 * The function performs a kappa-sigma clipping rejection
 * on a set of data given in vectors for indipendent, dipendent
 * and weight values. The differences to base the clipping on
 * is "true value minus background value", where background
 * value is determined using the identical algorithm as the
 * final background determination.
 *
 * Parameters:
 * @param xs     - array for independent values
 * @param ys     - array for dependent values
 * @param ws     - weight array
 * @param n      - number of pixels
 * @param interp - number indicating the interpolation scheme
 * @param niter  - the number of iterations
 * @param kappa  - the kappa value for rejection
 * @param obs    - the object list
 * @param colnum - the column number
 */


/**
 * Function: kappa_sigma_clipp
 * The subroutine performs one kappa-sigma step on the data
 * given in various vectors for independent, dipendent and
 * weight data. The difference to apply the clipping on
 * is "original value <minus> median of the data set".
 *
 * Parameters:
 * @param xs     - array for independent values
 * @param ys     - array for dependent values
 * @param ws     - weight array
 * @param n      - number of pixels
 * @param kappa  - the kappa value for rejection
 * @param obs    - the object list
 * @param colnum - the column number
 */


/**
 * Function: comp_vector_interp
 * The function passes the interpolation data to the
 * desired interpolating function.
 *
 * Parameters:
 * @param xs     - double vector containing the x values
 * @param ys     - double vector containing the y values
 * @param ws     - double vector containing the weights associated with ys
 * @param n      - number of points in xs,ys, and ws (must be greater than m!)
 * @param interp - desired interpolation type
 * @param final  - indicates a final interpolation
 */


/**
 * Function: fullimg_background_function
 * Returns the background level for the point x, y if a complete
 * gsl_matrix of the background is available.  This function is
 * exposed to the outside through a pointer in the observation
 * structure.
 *
 * Parameters:
 * @param x ad nauseam
 * @param y ad nauseam
 * @param val pointer to a double to leave the background value in
 * @param err pointer to a double to leave the absolute error of val in
 * @param pars a gsl_matrix containing the background
 */


/**
 * Function: compute_fullimg_background
 * Computes a background image. All beams with ignore=1 are
 * completely ignored. Anything else is not.
 *
 * Parameters:
 * @param obs         - a pointer to the observation structure to fill out
 * @param oblist      - a list of all objects of the observation
 * @param npoints     - number of points to examine when fitting the background
 * @param interporder - order of the polynomial to fit to the background
 * @param niter_med   - order of the polynomial to fit to the background
 * @param niter_fit   - order of the polynomial to fit to the background
 * @param kappa       - order of the polynomial to fit to the background
 *
 * Returns:
 * @return background - an allocated background structure
 *
 */


/**
 * Function: compute_backsub_mask
 * Computes a mask image for the background subtraction. All pixels
 * covered by at least one beam are set to a vale -100000 to distinguish
 * them from pixels which are part of the background.
 *
 * Parameters:
 * @param obs a pointer to the observation structure to fill out
 * @param oblist a list of all objects of the observation
 * @param npoints number of points to examine when fitting the background
 * @param interporder order of the polynomial to fit to the background
 *
 * Returns:
 * @return an allocated background structure
 *
 */


/**
 * Function: compute_fullimg_global_background
 * The subroutine computes the background image based on all pixels
 * in a column which are not part of an object.
 *
 * Parameters:
 * @param obs         - a pointer to the observation structure to fill out
 * @param oblist      - a list of all objects of the observation
 * @param interporder - order of the polynomial to fit to the background
 *
 * Returns:
 * @return background - an allocated background structure
 *
 */


/**
 * Function: free_fullimg_background
 * Frees a background structure allocated using make_fullimg_background
 *
 * Parameters:
 * @param backg - a pointer to the background structure to free
 */


/**
 * Function: aperture_mask
 * This functions returns an image mask where pixels that are within
 * an aperture are set to the number of aperture they appear.
 * Skips any beams which are set to be ignored (ignore=1)
 *
 * Parameters:
 * @param  obs    - a pointer to an observation structure
 * @param  oblist - a pointer to an object list
 *
 * Returns:
 * @return bck   - a pointer to a gsl_matrix
 */


/**
 * Function: background_to_FITSimage
 * Function to write the data and error content of a backgound
 * observation pars component (if it is of type fullimg_background only)
 * into the main HDU (data) and first extension (error) of a FITS file.
 * A GQ array can be appended if an observation with a non NULL DQ is
 * passed to this function
 *
 * Parameters:
 * @param filename - name of the image
 * @param bck      - filled background structure
 * @param obs      - the observation the background is based upon
 */


/**
 * Function: gsmooth_background
 * Smooth all interpolated pixel in the background using a Gaussian
 * function. The smoothing is done exclusively towards the x-values.
 * The smoothing should help to reduce the noise from the limited number
 * of background pixels.
 *
 * Parameters:
 * @param  bck_mask     - the background mask
 * @param  smoot_length - number of pixels on either side to use for smoothing
 * @param  fwhm         - fwhm of the Gaussian
 * @param  fib          - the background structure
 */


/**
 * Function: fill_pixvalues
 * The function provides the essential information for Gaussian smoothing
 * for a single pixel. It fills a vector with the values of all pixels
 * within the smoothing length. Not interpolated pixels are excluded.
 * A mask vector provides the information on which position is filled
 * with pixel values.
 *
 * Parameters:
 * @param  bck_mask     - the background mask
 * @param  smoot_length - number of pixels on either side to use for smoothing
 * @param  fib          - the background structure
 * @param  bck_mask     - the background mask
 * @param  ix           - x-value of central pixel
 * @param  iy           - y-value of central pixel
 * @param  pixvalues    - vector for pixel values
 * @param  pmask        - vector for pixel mask
 */


/**
 * Function: compute_gvalue
 * The function computes the values of a Gauss function
 * [exp(factor * xdiff^2)]. NO normalization factor is applied.
 *
 * Parameters:
 * @param xdiff   - the value [x-x_0]
 * @param efactor - the factor for the exponent
 *
 * Returns:
 * @return value - the Gaussian value
 */


/**
 * Function: compute_efactor
 * The function computes the appropriate factor of the Gaussian for any
 * FWHM given as input. This speeds up any later computation of the
 * Gaussian.
 *
 * Parameters:
 * @param fwhm - the input FWHM
 *
 * Returns:
 * @return expfactor - the factor for the Gaussian
 */


/**
 * Function: apply_response_function
 * This function applies a thoughput curve to a given spectrum
 * by dividing the count attribute of the spectrum. The flux
 * and ferror attributes of the spectrum are populated.
 * gsl spline interpolation is used to compute the throughput
 * curve at the needed spectral wavelengths.
 *
 * Parameters:
 * @param spec    - a pointer to an existing spectrum array
 * @param resp    - a pointer to a spectrum structure containing
 *                  a throughput curve previously loaded
 * @param exptime - the exposure time
 * @param gain    - the gain
 *
 * Returns
 * @return -
 */


/**
 * Function: apply_response_functionII
 * This function applies a thoughput curve to a given spectrum
 * by dividing the count attribute of the spectrum. The flux
 * and ferror attributes of the spectrum are populated.
 *
 * Parameters:
 * @param spec       - a pointer to an existing spectrum array
 * @param resp_func  - a pointer to a spectrum structure containing
 *                     a throughput curve previously loaded
 * @param quant_cont - the exposure time
 *
 * Returns
 * @return -
 */


/**
 * Function: check_conf_for_smoothing
 * The functions checks whether a smoothed flux conversion
 * is possible or not. In case that keywords in the configuration
 * files are missing, it is NOT possible, and 0 is returned.
 *
 * Parameters:
 * @param conf        - the configuarion file structure
 * @param smooth_conv - boolean for smooth conversion
 *
 * Returns
 * @return is_possible - the paramters used in the smoothing
 */


/**
 * Function: apply_smoothed_response
 * Convert a spectrum from e/s to flux units in f_lambda. The conversion is done
 * using smoothed sensitivity values that take the object width into account
 * by smoothing the sensitivity function. Gaussian smoothing is applied, taking
 * into account that the original calibration function was derived for a point
 * like object with a finite size.
 *
 * Parameters:
 * @param spec           - a pointer to an existing spectrum array
 * @param resp_func      - a pointer to a spectrum structure containing
 *                         a throughput curve
 * @param quant_cont     - indicator for quantitative contamination
 * @param bwidth         - the B_IMAGE value of the beam
 * @param psf_ext        - the width of a point-like object
 * @param wl_calibration - the wavelength calibration structure
 *
 * Returns
 * @return -
 */


/**
 * Function: find_wavelength
 * For a given trace-length value, the function returns the difference
 * between the actual and the targeted wavelength.
 * The function is designed t be called by a gsl root-solving procedure.
 *
 * Parameters:
 * @param x        - guess value for the tracelength
 * @param params   - structure with input parameters
 *
 * Returns
 * @return wav_zero - difference between actual and targeted wavelength
 */


/**
 * Function: fill_weight
 * The function fills an array with Gaussian values.
 * The number of points and the extend are all defined in
 * global variables in the h-file.
 *
 * Parameters:
 * @param weights   - the weight vector
 *
 * Returns
 * @return -
 */


/**
 * Function: create_response_function
 * Load the sensitivity file and creates a new response
 * function. Relies heavily on other subroutines
 *
 * Parameters:
 * @param filename - sensitivity file name
 *
 * Returns:
 * @return resp_func - the response function created
 */


/**
 * Function: free_response_function
 * Releases the memory allocated in a response function
 *
 * Parameters:
 * @param resp_func - the response function
 *
 * Returns:
 * @return -
  */


/**
   Function to create and return a gsl array of the same size as the grism
   part of n observation structure.

   @param ob a pointer to an observation structure
   @return a pointer to a newly allocated aXe_mask structure

*/


/**
 * This function sets all the pixels listed in an ap_pixel list
 * in an aXe_mask to 0.0

    @param a pointer to a ap_pixel array
    @param mask an existing aXe_mask structure

*/


/**
 * Function: compute_fringe_amplitude
 * The function computes the fringe image for a CCD setup stored
 * in a fringe configuration structure. This fringe configuration
 * structure completely describes the problem, and this function
 * executes the loops for every pixel over the wavelength
 * range spanned by the filter.
 *
 * Parameters
 * @param fconf - the fringe configuration structure
 *
 * Returns:
 * @return fringe_image - the image with the computed fringe amplitudes
 */


/**
 * Function: alloc_fringe_image
 * The function browses through the the structure for the CCD layers
 * and extracts all information on image sizes stored there in
 * one or several thickness images. This information is checked
 * for consistency.
 * Finally, a matrix for a fringe image is allocated, initialized
 * and returned.
 *
 * Parameters:
 * @param opt_layers - the optical layers in the CCD
 *
 * Returns:
 * @return fringe_image - the allocated matrix for the fringe image
 */


/**
 * Function: redefine_filter_throughput
 * The function re-defines an existing interpolator using only the
 * existing data values in an index range given as parameters.
 *
 * Parameters:
 * @param lower - index with the lowest data point
 * @param upper - index with the highest data point
 *
 * Returns:
 * @return new_interp - the new interpolator
 */


/**
 * Function: eval_linear_interp
 * The function computes and returns the interpolated value
 * at a given position for a linear interpolator.
 *
 * Parameters:
 * @param lin_int - the linear interpolator
 * @param xval    - the position to evaluate the linear interpolator
 *
 * Returns:
 * @return (value) - the interpolated data value
 */


/**
 * Function: compute_reflection
 * The function computes and returns the reflection index (in %)
 * for two complex refraction indices  at a given wavelength.
 *
 * Parameters:
 * @param refract_l1 - refraction index of one layer
 * @param refract_l2 - refraction index of the second layer
 *
 * Returns:
 * @return (value) - the reflection index
 */


/**
 * Function: compute_transmission
 * The function computes and returns the transmission index (in %)
 * for two complex refraction indices at a given wavelength.
 *
 * Parameters:
 * @param refract_l1 - refraction index of one layer
 * @param refract_l2 - refraction index of the second layer
 *
 * Returns:
 * @return (value) - the trnasmission index
 */


/**
 * Function: compute_attenuation
 * The function computes the attenuation/damping of a plane wave
 * with a given inverse wavelelength (phase number) traversing
 * TWO TIMES a layer of a given thickness and complex refraction
 * index.
 *
 * Parameters:
 * @param refract      - the complex refraction index
 * @param thickness    - the thickness of the layer
 * @param phase_number - the inverse wavelength
 *
 * Returns:
 * @return (value) - the attenuation
 */


/**
 * Function: compute_pshift
 * The function computes the phase shift of a plane wave
 * with a given inverse wavelelength (phase number) traversing
 * TWO TIMES a layer of a given thickness and complex refraction
 * index.
 *
 * Parameters:
 * @param refract      - the complex refraction index
 * @param thickness    - the thickness of the layer
 * @param phase_number - the inverse wavelength
 *
 * Returns:
 * @return (value) - the complex phase shift
 */


/**
 * Function: alloc_optprops_list
 * The function allocates space for a list of optical property
 * elements. the size of the list is derived from a fringe
 * configuration structure given in the input.
 *
 * Parameters:
 * @param fconf - the fringe configuration file
 *
 * Returns:
 * @return optprops - the list of optical properties
 */


/**
 * Function: print_optprops_list
 * The function prints the content of an optical property
 * list onto the screen.
 *
 * Parameters:
 * @param optprops - the optical property list
 *
 * Returns:
 * @return -
 */


/**
 * Function: free_optprops_list
 * The function releases the space allocated in an
 * optical property list.
 *
 * Parameters:
 * @param optprops - the optical property list
 *
 * Returns:
 * @return -
 */


/*
 * Function: init_optprops_list
 * The function initializes an optical property list. This means
 * it computes and stores values for the list elements. Here
 * only elements are fixed, which will not change during the
 * whole fringe computation and remain constant for all pixels
 * at all wavelengths.
 *
 * Parameters:
 * @params fconf       - the fringe configuration structure
 * @params lambda_mean - the mean wavelength of analyzed waveband
 * @params optprops    - the list of optical property elements
 *
 * Returns:
 * @return -
 */


/*
 * Function: fill_optprops_thickness
 * The function fills the thickness of the optival layers
 * at a given pixel into a list of optical properties.
 *
 * Parameters:
 * @params opt_layers - the structure for the optical layers
 * @params ii         - the mean wavelength of analyzed waveband
 * @params jj         - the list of optical property elements
 * @params optprops   - the list of optical property elements
 *
 * Returns:
 * @return -
 */


/*
 * Function: fill_optprops_all
 * This function computes and fills in all pixel AND wavelength
 * dependent values into a list of optical properties. The completely
 * filled list can then be used to determine the fringe contribution
 * at that wavelength according to a certain model which defines
 * the various light-paths.
 *
 * Parameters:
 * @params opt_layers - the structure for the optical layers
 * @params lambda     - the actual wavelength
 * @params optprops   - the list of optical property elements
 *
 * Returns:
 * @return -
 */


/*
 * Function: fill_contrib_single
 * The function computes the contribution to the fringe amplitude
 * on the basis of an appropriately filled list of optical properties.
 * In the properties the ingredients such as phase shifts and
 * attenuation and transmissions and reflections are defined.
 * This function just combines the ingredients using a model
 * which includes all single reflected beam combinations
 * as contributors to the fringing.
 *
 * Parameters:
 * @params optprops   - the list of optical property elements
 * @params fconf      - the fringe configuration structure
 *
 * Returns:
 * @return (value)    - the fringe contribution
 */


/**
  transforms a list of abscissas to a list of path lengths if the path length
  is known analytically.

  @param func the spectrum trace function to use in the transformation
  @param data the table of abscissas relative to the reference point
*/


/* computes sqrt(1+f'(x)^2), i.e. the function to integrate to obtain
 *   the path length.
 *
 * @param x the abscissa to compute the function for
 * @pars a pointer to the trace_func struct, declared void to please gsl
 */


/* Compute the path length of (x,func->func(x)) from x0 to x1 (helper
 *   function for absc_to_pathl_deriv)
 *
 * @param func the spectrum trace
 * @param x0 start of parameter range
 * @param x1 end of parameter range
 *
 */


/**
 *  transforms a list of abscissas to a list of path lengths if the derivative
 * but not the path length is known analytically.  The strategy is to compute
 * NUM_INTERPOINTS actual path lengths and the interpolate between them.
 * This should work with sufficient accuracy if the trace function is
 * reasonably smooth.
 *
 * @param func the spectrum trace function to use in the transformation
 * @param data the table of abscissas relative to the reference point
 */


/**
 * transforms a list of abscissas to a list of path lengths if not even
 * the derivative is known.
 *
 * @param func the spectrum trace function to use in the transformation
 * @param data the table of abscissas relative to the reference point
 * @todo pathlength for traces without derivatibes is not implemented
 */


/**
 * transforms a list of abscissas to a list of path lengths.  This function
 * decides what of the absc_to_pathl_len, absc_to_pathl_deriv, or
 * absc_to_pathl_val_only to use.
 *
 * @param func the spectrum trace function to use in the transformation
 * @param data the table of abscissas relative to the reference point
 */


/**
  A polynom of degree two.

  @param x the abscissa, usually relative to the beam's reference point.
  @param pars a pointer four doubles, the length (3) and the coefficients of the polynom.
  @returns the value of the polynom at x.
*/


/**
  A polynom of degree N.

  @param x the abscissa, usually relative to the beam's reference point.
  @param pars a pointer N+1 doubles, the length (N) and the coefficients of the polynom.
  @returns the value of the polynom at x.
*/


/**
  The derivative of a polynom of degree two.

  @param x the abscissa, usually relative to the beam's reference point.
  @param pars a pointer four doubles, the length (3) and the coefficients of the polynom.
  @returns the derivative of the polynom at x.
*/


/**
  The derivative of a polynom of degree N.

  @param x the abscissa, usually relative to the beam's reference point.
  @param pars a pointer N+1 doubles, the length (N) and the coefficients of the polynom.
  @returns the derivative of the polynom at x.
*/


/**
  sqrt(1+(dy/dx)^2) of an N^th order polynomial

  @param x the abscissa, usually relative to the beam's reference point.
  @param pars a pointer N+1 doubles, the length (N) and the coefficients of the polynom.
  @returns the derivative of the polynom at x.
*/


/**
  The path length of a polynom of degree two, relative to the point poly4(0).
  For higher polynoms, probably no such closed expression exists.

  @param x the abscissa, usually relative to the beam's reference point.
  @param pars a pointer four doubles, the length (3) and the coefficients of the polynom.
  @returns the path lenght for the polynom at x.
*/


/**
  The path length of a polynom of degree two, relative to the point poly4(0).
  For higher polynoms, probably no such closed expression exists.

  @param x the abscissa, usually relative to the beam's reference point.
  @param pars a pointer N+1 doubles, the length (N) and the coefficients of the polynom.
  @returns the path lenght for the polynom at x.
*/


/**
  creates a 2nd order polynomial trace function

  @param a0 coefficient for x^0
  @param a1 coefficient for x^1
  @param a2 coefficient for x^2
  @returns allocated trace_func structure or NULL for failure
*/


/**
  creates a Nth order polynomial trace function

  @param a pointer to a gsl_vector containing the coeeficients
  @returns allocated trace_func structure or NULL for failure
*/


/**
  creates a 2nd order polynomial trace function
  using the coefficients contained in a gsl vector
  of length 1,2, or 3.

  @param v, a gsl vector containing polynomial coefficients.
  @return a pointer to new trace_func object which contains a second order polynomial
  trace description
*/


/**
  creates a Nth order polynomial trace function
  using the coefficients contained in a gsl vector
  of length N.

  @param v, a gsl vector containing polynomial coefficients.
  @return a pointer to new trace_func object which contains an Nth order polynomial
  trace description
*/


/**
  Free the trace_func struct for a 2nd order polynomial.

  @param func the trace_func struct.
*/


/**
  Free the trace_func struct for a Nth order polynomial.

  @param func the trace_func struct.
*/


/**
    A helper function to convert a gsl_matrix into a linear
    integer array suitble to plot with pgplot's routines

    @param ar 2D gal_matrix
    @param r a pointer to an already allocated amount of memeory
*/


/**
    Outputs a stamp image using pgplot and using the information for an
    ap_pixel structure.

    @param ap_p an existing ap_pixel structure
    @param n_sub subsampling used (usualy 1.)
    @param ob a pointer to the object correspoding to ap_p
    @param beamnum the numeric ID of the beam corresponding to ap_p
    @param filename a pointer to a char array containing the name of the file to output the
    postscript stamp image to

*/


/**
 *  Function: is_valid_entry
 *  The routine checks whether a magnitude is valid
 *  or not. Returns true/false in case the value
 *  is valid/not valid.
 *
 * Parameters:
 *  @param  mag   - the magnitude to be checked
 *
 * Returns:
 *  @return valid - 1/0 for valid/non valid magnitude, respectively
 */


/**
 * Function: check_worldcoo_input
 * Checks whether the columns for the world coordinates
 * are present in a catalog header. Returns the number
 * of missing columns
 *
 * Parameters:
 * @param  actcatinfo - the catalog header ot be examined
 *
 * Returns:
 * @return checksum   - the number of missing columns
 */


/**
 * Function: check_imagecoo_input
 * Checks whether the columns for the image coordinates
 * are present in a catalog header. Returns the number
 * of missing columns
 *
 * Parameters:
 * @param  actcatinfo - the catalog header ot be examined
 *
 * Returns:
 * @return checksum   - the number of missing columns
 */


/**
 * Function: make_GOL_header
 * The function prints the header of a GOL file to
 * an output stream. Besides the standard columns
 * it composes the names for the magnitude columns
 * and also makes the header entries for those columns
 *
 * Parameters:
 * @param fout       - the output stream
 * @param actcatinfo - the structure with the header information
 *                     of the SExtractor catalog
 * @param waves      - vector with the wavelengths of magnitude columns
 * @param cnums      - vector with the column numbers of magnitude columns
 * @param backwin_cols - vector with the column numbers of background window columns
 * @param modinfo_cols - vector with the column numbers of modelling index numbers
 *
 */


/**
 * Function: line_is_valid
 *  The function checks whether a catalog line is
 *  valid. Valid lines have a data entry for each
 *  catalog column
 *
 * Parameters:
 *  @param  actcatinfo - the header of the catalog
 *  @param  line       - line to be examined
 *
 *
 * Returns:
 *  @return 0/1        - 0 for not valid lines, 1 for a valid line
 */


/**
 * Function: resolve_colname
 *  The function extracts the wavelength from column names.
 *  The column names must have the format "MAG_CNNNNNN...C..."
 *  with C as character and N as a number.
 *
 * Parameters:
 *  @param  colname - the column name
 *
 * Returns:
 *  @return iwave   - the wavelength extracted from the column name
 */


/**
 * Function: has_magnitudes
 *  The functions searches for columns with magnitudes in the
 *  set of column names within the catalog header structure
 *
 * Parameters:
 *  @param  actcatinfo      - the structure with the column names
 *
 * Returns:
 *  @return hasmags+magauto - the number of columns with magnitudes
 */


/**
 * Function: has_backwindow
 * The functions searches for columns which describe the apertures
 * around the object to compute the background. This information
 * is stored in the columns :BACKWIN_UPP and :BACKWIN_LOW
 *
 * Parameters:
 *  @param  actcatinfo      - the structure with the column names
 *
 * Returns:
 *  @return hasmags+magauto - the number of columns with magnitudes
 */


/**
 * Function: has_modelinfo
 * The function searches for the columns 'MODSPEC' and 'MODIMAGE'.
 * The column numbers are returned. if not found, the column
 * index -1 is returned.
 *
 * Parameters:
 *  @param  actcatinfo      - the structure with the column names
 *
 * Returns:
 *  @return ret - column numbers for object shape and spectral model
 */


/**
 * Function: check_libraries
 * A helper function which checks the versin numbers of a few
 * runtime libraries to ensure that the proper versions of libraries
 * are being found.
 */


/*
 * Function: init_search
 * Call this with the string to locate to initialize the table
 *
 * Parameters:
 * @param string - no idea
 */


/*
 * Function: strsearch
 * Call this with a buffer to search
 *
 * Parameters:
 * @param string - no idea
 *
 * Returns:
 * @return here - no idea
 */


/**
 * Function: isnum2
 * determine if a string is a number
 *
 * Parameters:
 * @param str a pointer to a string to test
 *
 * Retruns:
 * @return 1 if string contains a numeric entry, 0 otherwise
 */


/**
 * Function: string_to_gsl_array
 * Parse the content of a  string into a float GSL array.
 * Checks each entry to ensure that it is numeric. skip over
 * the non numerical ones. Entries containing ###,NaN, -NaN, +NaN are
 * set to GSL_NAN.
 *
 * Parameters:
 * @param str the pointer to a string containing floats to parse.
 *
 * Returns:
 * @return v - the gslvector with the table row
 */


/**
 * Function: stptok
 * A function to recursively tokenize an input string.
 *
 * Parameters:
 * @param s a pointer to the input string.
 * @param tok a pointer to the current token in s.
 * @param toklen the length of the tok.
 * @param brk the separator string to use.
 *
 * Returns:
 * @return a new position in the input string.
 */


/**
 * Function: lv1ws
 * Convert in-place  all blanks in a string into single space.
 *
 * Parameters:
 * @param str - a pointer to a string.
 */


/*
 * Function: rmlead
 *  Originally published as part of the MicroFirm Function Library
 *
 *  Copyright 1986, S.E. Margison
 *  Copyright 1989, Robert B.Stout
 *
 *  The user is granted a free limited license to use this source file
 *  to create royalty-free programs, subject to the terms of the
 *  license restrictions specified in the LICENSE.MFL file.
 *
 *  remove leading whitespace from a string
 *
 * Parameters:
 * @param str - pointer to the input string
 *
 * Returns:
 * @param str - pointer to the stripped string
 */


/**
 * Function: load_dummy_observation
 * A function that returns a dummy allocated abservation
 * pointer.
 *
 Returns:
 * @return obs - pointer to the dummy observation
 */


/**
 *
 *  Function: create_SexObject
 *  Allocates and creates a SExtractor object from
 *  a line of a SExtractor catalog.
 *
 *  Parameters:
 *  @param  actinfo  - the header structure with the column names
 *  @param  line     - the line to be transformed into a SexObject
 *  @param  waves    - vector with the walelengths of the magnitude columns
 *  @param  cnums    - vector with the column numbers of the magnitude columns
 *  @param  magcol   - column number of the magnitude column selected
 *                     for mag_auto
 *  @param  fullinfo - deecides whether a column is optional or not
 *
 *  Returns:
 *  @return o        - the new created SexObject
 */


/**
 *  Function: SexObject_fprintf
 *  Function to print the attributes of a SexObbject
 *  to an output stream.
 *
 *  Paramters:
 *  @param output - an ouput file or stream
 *  @param o      - a pointer to a SexObject
 */


/**
 *  Function: sobs_to_vout
 *  The function transforms a SexObject into
 *  a vector.
 *
 *  Parameters:
 *  @param  sobs - the SexObject to be transformed
 *
 *  Returns:
 *  @return vout - the vector with the Seobject data
 */


/**
 *  Function: catalog_to_wcs
 *  This function reads a sextractor catalog and using an input and an output
 *  CD matrix, converts the world ra and dec coordinates to the output CD
 *  matrix's image pixel coordinates. Non existing (i.e. NaN) world RA and
 *  DEC values are generated using
 *  the pixel coordinates and the input CD matrix
 *
 *  Parameters:
 *  @param - infile a pointer to a char array containing the name of the
 *         input catalog
 *  @param - outfile a pointer to a char array containing the name of the
 *         output catalog
 *  @param - from_wcs a pointer to an exisiting WoldCoor structure containing
 *         the input catalog CD matrix
 *  @param - to_wcs a pointer to an exisiting WoldCoor structure containing
 *         the output catalog CD matrix
 *  @param - overwrite_wcs if set to 1 then input wold coordinate are
 *         recomputed first using the from_wcs and the x,y image values
 *  @param - overwrite_img if set to 1 then the x,y coordinates of the input
 *         image are first computed using the from_wcs and the
 *          world ra and dec info
 */


/**
 * Function:catalog_to_wcs_nodim
 * This function reads a sextractor catalog and using an input and an output
 * CD matrix, converts the world ra and dec coordinates to the output
 * CD matrix's image pixel coordinates. Non existing (i.e. NaN) world RA
 * and DEC values are generated using the pixel coordinates and the input
 * CD matrix
 *
 * Parameters:
 * @param infile    - a pointer to a char array containing the name of the
 *                    input catalog
 * @param outfile   - a pointer to a char array containing the name of the
 *                    output catalog
 * @param from_wcs  - a pointer to an exisiting WoldCoor structure containing
 *                    the input catalog CD matrix
 * @param to_wcs    - a pointer to an exisiting WoldCoor structure
 *                    containing the output catalog CD matrix
 * @param overwrite_wcs - if set to 1 then input wold coordinate are
 *                        recomputed first using the from_wcs and the
 *                        x,y image values
 * @param overwrite_img - if set to 1 then the x,y coordinates of the
 *                        input image are first computed using the
 *                        from_wcs and the world ra and dec info
 */


/**
 * Function: SexMags_to_beamFlux
 * Fill an beam structure with the flux and shape information information
 * contained in a SexObject structure.
 *
 * Parameters:
 * @param sobj     - pointer to a  SexObject
 * @param actbeam  - the beam structure to be filled
 *
 * Returns:
 * @return -
 */


/**
 * Function: SexObject_to_slitgeom
 * Fill a beam structure with the optimized geometry information.
 * The quantities are computed from the object shape and
 * the trace angle.
 *
 * Parameters:
 * @param sobj        - pointer to a  SexObject
 * @param trace_angle - pointer to a  SexObject
 * @param actbeam     - the beam structure to be filled
 *
 * Returns:
 * @return -
 */


/**
 * Function: fill_corner_ignore
 * The method computes and fills the beam corner information
 * and the the ignore flag into a beam structure.
 *
 * Parameters:
 * @param sobj     - pointer to a  SexObject
 * @param obs      - a pointer to the data array containing the image
 * @param conf     - pointer to the configuration structure
 * @param beamID   - the beam ID
 * @param dmag     - number of magnitudes to add to the magnitudes cutoffs
 * @param actbeam  - the beam structure to be filled
 *
 * Returns:
 * @return -
 */


/**
 * Function: SexObject_to_beam
 * Fill an beam structure with the information contained in a SexObject
 * structure plus further information derived via the confiugration file.
 *
 * Parameters:
 * @param sobj     - pointer to a  SexObject
 * @param obs      - a pointer to the data array containing the image
 * @param conf     - pointer to the configuration structure
 * @param conffile - the name of the aperture configuration file
 * @param mfwhm    - the fwhm multiplicator constant to apply to
 *                   determine the width of the aperture box for the object.
 * @param dmag     - number of magnitudes to add to the magnitudes cutoffs
 * @param auto_reorient - if set then this task tries to optimize
 *                        the orientation of the
 *                        extraction slit - Should in general be left at 1 so that strange
 *                        geomety is avoided. If set to 2 the extraction is
 *                        forced to be vertical (90 deg.)
 * @param bck_mode - pointer for background mode
 * @param beamID   - the beam ID
 * @param actbeam  - the beam structure to be filled
 *
 * Returns:
 * @return -
 */


/**
 * Function: SexObject_to_objectII
 * Fill an object structure with the information contained in a SexObject
 * structure This function uses a configuration file to compute the full
 * list of beams for each object.
 *
 * Parameters:
 * @param sobj     - pointer to a  SexObject
 * @param obs      - a pointer to the data array containing the image
 * @param conf     - pointer to the configuration structure
 * @param conffile - the name of the aperture configuration file
 * @param mfwhm    - the fwhm multiplicator constant to apply to
 *                   determine the width of the aperture box for the object.
 * @param dmag     - number of magnitudes to add to the magnitudes cutoffs
 * @param auto_reorient - if set then this task tries to optimize
 *                        the orientation of the
 *                        extraction slit - Should in general be left at 1 so that strange
 *                        geomety is avoided. If set to 2 the extraction is
 *                        forced to be vertical (90 deg.)
 * @param bck_mode - pointer for background mode
 *
 * Returns:
 * @return a pointer to a newly allocated object structure
 */


/**
 * Function: check_conf_for_slitlessgeom
 * The functions checks whether a smoothed flux conversion
 * is possible or not. In case that keywords in the configuration
 * files are missing, it is NOT possible, and 0 is returned.
 *
 * Parameters:
 * @param conf          - the configuarion file structure
 * @param auto_reorient - integer indicating the extraction method
 *
 * Returns
 * @return is_possible - the paramters used in the smoothing
 */


/**
 * Function: fill_object_bbox
 * Fill up the aperture part of the beam of an object structure by looking at the trace polynomial
 * description associated with this object.
 *
 * Parameters:
 * @param obs - a pointer to the data array containing the image (used for bound checking)
 * @param b - A pointer to a beam whose aperture must be filled.
 * @param m_width - The width in pixel of the extraction box
 * @param dxmin - How far (in pixel) to follow the trace on the left side of the spectrum
 * @param dxmax - How far (in pixel) to follow the trace on the right hand side of the spectrum
 *
 * Returns:
 * @return 1 if bounding box appears to be valied (i.e. non-empty)
 */


/**
 * Function: size_of_sextractor_catalog
 * A utility function which parses a Sextractor catalog file,
 * and returns the number of valid catalog entries found in the file
 *
 * Parameters:
 * @param filename - a pointer pointing to a char array containing the
 *                   list of a sextractor object output catalog.
 *                   Ignores rows starting with a ";"
 */


/**
 * Function: el_to_ABC_world
 * Convert a wold coordinate ellipse into a set of 3 points on the
 * tangent plane point a is at pos of obj, semi major-axis end is point b,
 * semi minor axis is point c theta is measured from x-axis to semi-major
 * axis, counter clock wise.
 */


/**
 * Function: ABC_image_to_el
 * Convert a set of three image coordinates into an elipse structure
 *
 */


/**
 * Function: ABC_image_to_el2
 * Convert a set of three image coordinates into an elipse structure
 *
 */


/**
 *  Function: fill_missing_WCS_coordinates
 *  Update a SexObject structure and replace all missing WCS coordinates
 *  by re-computing them using the world one and the from_wcs wcs.
 *  Re-computes:
 *      peak_world_x
 *     peak_world.y
 *       xy_world.x
 *      xy_world.y
 *      el_world.a
 *      el_world.b
 *      el_world.theta
 *
 *  @param o - a pointer to an exsting SexObject. Should have been checked for validity already
 *  @param from_wcs - a pointer to an existing  WoldCoord wcs structure
 */


/**
 * Function: fill_missing_image_coordinates
 *  Update a SexObject structure and replace all missing image coordinates
 *  by re-computing them using the world one and the from_wcs wcs.
 *  Re-computes:
 *      peak_image_x
 *      peak_image.y
 *      xy_image.x
 *      xy_image.y
 *      el_image.a
 *      el_image.b
 *      el_image.theta
 *
 * Parameters:
 * @param o - a pointer to an exsting SexObject. Should have been
 *            checked for validity already
 * @param from_wcs - a pointer to an existing  WoldCoord wcs structure
 */


/**
 * Function: fill_all_missing_image_coordinates
 * Replaces all NaN values in a set of SexObjects with ones computed
 * from the available information and the associated WCS.
 *
 * Parameters:
 * @param sobjs    - an NULL terminated array containing pointers to SexObjects
 * @param from_wcs - a pointer to an existing  WoldCoord wcs structure
 * @param overwrite - forces the re-computation of all image coordinates
 *
 */


/**
 * Function: fill_all_missing_WCS_coordinates
 *  Replaces all NaN values in a set of SexObjects with ones computed from the
 *  available information and the associated WCS.
 *
 * Parameters:
 *  @param sobjs - an NULL terminated array containing pointers to SexObjects
 *  @param from_wcs - a pointer to an existing  WoldCoord wcs structure
 *  @param overwrite - forces the re-computation of all image coordinates
 *
 */


/**
 * Function: compute_new_image_coordinates
 *  Function that uses the exisiting world coordinates of a SexObject to
 *  compute new pixel coordinates using a (new) WCS.
 *
 * Parameters:
 *  @param o - a pointer to an exsting SexObject. Should have been checked
 *   for validity already
 *  @param to_wcs - a pointer to an existing  WoldCoord wcs structure
 *
 */


/**
 * Function: compute_new_image_sexobject
 * Function that uses the exisiting world coordinates of a SexObject to
 * compute new pixel coordinates using a (new) WCS.
 *
 * Parameters:
 * @param o - a pointer to an exsting SexObject. Should have been checked
 *  for validity already
 *  @param to_wcs - a pointer to an existing  WoldCoord wcs structure
 */


/**
 * Function: compute_all_new_image_coordinates
 * Replaces all SexObjects image coordinates with new ones computed using  the
 * the passed WCS.
 *
 * Parameters:
 * @param sobjs - a NULL terminated array containing pointers to SexObjects
 * @param to_wcs - a pointer to an existing  WoldCoord wcs structure
 */


/**
 * Function: free_SexObjects
 *    Free a NULL terminated array of SexObject
 *
 * Parameters:
 *  @param sobjs - a NULL terminated array containing pointers to SexObjects
 *
 */


/*
I am not sure what this routine is doing,
but one should make it better.
*/


/**
 * Function: fringe_correct_PET
 * Performs fringe corrections to PET pixel lists
 *
 * The main function to compute and perform the fringe
 * correction to a list of PET pixels. for every pixel in
 * the PET list the pixel throughput function is
 * computed, and the relevant information from
 * the fringing model is extracted. Then the fringe
 * amplitude is computed and the count value of the pixel
 * is corrected. Also the PET pixel list is simultaneously
 * parsed and corrected for the fringing.
 *
 * Parameters:
 * @param fconf    - the fringe configuration file
 * @param act_beam - the beam aperture
 * @param obj_pet  - the PET pixel
 * @param bck_pet  - the PET pixel
 */


/**
 * Function: create_interp_tput
 * The function creates and returns an interpolator
 * for a pixel throughput function. The interpolator
 * structure is allocated, data is filled in and
 * finally initialized.
 *
 * Parameters:
 * @param p_tput   - the pixel throughput structure
 *
 * Returns:
 * @return interp - the new interpolator
 */


/**
 * Function: compute_pixel_tput
 * The function computes all relevant data to characterize
 * the pixel throughput function for an individual PET pixel.
 * The information is written into a pixel throughput structure.
 *
 * Parameters:
 * @param act_beam - the beam aperture
 * @param obj_pix  - the PET pixel
 * @param p_tput   - the pixel throughput structure
 */


/**
 * Function: compute_tput_angles
 * The function computes the angles which characterize
 * a pixel in the lambda-cross dispersion plane.
 * In detail this is the angle between the lambda-axis
 * and the x-axis, and the angle between the lambda abd
 * the cross dispersion axis.
 * The two angles are computed from the basic pixel
 * and beam data.
 *
 *
 * Parameters:
 * @param act_beam - the beam aperture
 * @param act_pet  - the PET pixel
 *
 * Returns:
 * @return angles - the relevant pixel angles
 */


/**
 * Function: alloc_pixel_tput
 * The function allocates and returns memory
 * for a pixel throughput function
 *
 * Returns:
 * @return p_tput -the new allocated pixel throughput structure
 */


/**
 * Function: print_pixel_tput
 * The function prints the content of a pixel throughput
 * structure onto the screen.
 *
 * Parameters:
 * @param p_tput - the pixel throughput structure
 */