/**
 * Function: free_pixel_tput
 * The function releases the memory allocated
 * in a pixel throughput function.
 *
 * Parameters:
 * @param p_tput - the pixel throughput structure
 */


/**
 * Function: compute_tracedata
 * The function creates a tracedata structure for a specific
 * beam model. A tracedata structure consists of all relevant
 * information (position, wavelength, dispersion) for the pixels
 * along the trace of a specific beam. Since the reference point
 * remains constant during the modelling of a beam, it is
 * better to store the relevant data for the use in each pixel.
 *
 * Parameters:
 * @param  actbeam        - the beam of the model spectrum
 * @param  actdir         - the direct object of the model spectrum
 * @param  wl_calibration - the wavelength calibration of the model spectrum
 * @param  actspec        - the model spectrum
 *
 * Returns:
 * @return acttrace       - the tracedata structure
 */


/**
 * Function: compute_short_tracedata
 *
 * Parameters:
 * @param  actbeam        - the beam of the model spectrum
 * @param  actdir         - the direct object of the model spectrum
 * @param  wl_calibration - the wavelength calibration of the model spectrum
 * @param  actspec        - the model spectrum
 *
 * Returns:
 * @return acttrace       - the tracedata structure
 */


/*
 * Function: select_tracedata
 * The function applies additional constraints for prism data.
 * In prisms not all trace positions can be accepted, since
 * the odd calibration function results into strange wavelengths
 * and values close and beyond the singularity.
 * The function creates a new tracedata structure with values
 * only from the accepted trace range.
 *
 * Parameters:
 * @param acttrace       - the tracedata
 * @param wl_calibration - the calibration structure
 * @param nentries       - the number of valid entries
 */


/*
 * Function: fill_fluxfrom_SED
 * This function fills flux values at different wavelengths
 * into the tracedata structure. The flux values are computed
 * via the SED in the direct objects.
 *
 * Parameters:
 * @param actdir   - the direct object
 * @param acttrace - the tracedata structure
 */


/*
 * Function: print_tracedata
 * This function prints some tracedata values
 * onto the screen. Used mainly for debugging
 * reasons.
 *
 * Parameters:
 * @param acttrace - the tracedata structure
 */


/**
 * Function: fill_dirobject
 * Transforms one object into one dirobject.
 * Either transfers or computes the content
 * of the dirobject from the object.
 *
 * Parameters:
 * @param  actobject   - the object to be transformed
 * @param  npixels     - the dimension of the grism image
 * @param  drzcoeffs   - the drizzle coefficients
 * @param  model_scale - the scale for the size of the direct object area
 *
 * Returns:
 * @return actdir    - the dirobject created
 */


/**
 * Function: fill_dirobj_fromdirim
 * Transforms an object which has a direct emission model associated
 * to into a direct object. The direct object created is returned
 *
 * Parameters:
 * @param  actobject     - the object to be transformed
 * @param  object_models - the structure with the direct emission models
 *
 * Returns:
 * @return actdir    - the dirobject created
 */


/**
 * Function: fill_spectrum
 * Transfers the wavelength information from an object
 * to a dirobject. Store the minimum and maximum wavelength
 * as well as associated flux values in the structure.
 *
 * Parameters:
 * @param actobject - the object to be transformed
 * @param actdir    - the dirobject to store the flux values in
 * @param spec_mod  - the spectral model list
 * @param int_type  - the interpolation type to be used
 */


/**
 * Function: make_sed_from_beam
 *
 * Parameters:
 * @param onebeam  - the object to be transformed
 * @param int_type - the interpolation type to be used
 * @param objID    - the interpolation type to be used
 */


/**
 * Function: print_dirobject
 * Prints the data in a dirobject onto the screens.
 * "Natural" format is used, which means printed are first
 * the upper corners, then the refpoint, then
 * the lower corners.
 *
 * Parameters:
 * @param actdir - the dirobject to be printed
 */


/**
 * Function: check_interp_type
 * The function checks the requested interpolation type
 * against the number of flux values in the models.
 * The interpolation type is adjusted in case that there
 * are not enough flux values for the reuqested type.
 *
 * Parameters:
 * @param inter_type - the requested interpolation
 * @param n_flux     - the number of flux values
 * @param ID         - the object ID
 *
 * Returns:
 * @return type       - the feasable interpolation type
 */


/**
 *
 * Function: free_dirlist
 * Releases the memory allocated
 * for a list of dirobjects.
 * after releasing memory, all elements
 * are set to NULL/
 *
 * Parameters:
 * @param dirlist  - the list of dirobjects
 * @paran spec_mod - describes what all to free
 */


/**
 * Function: free_enerdist
 * The function releases all the memory
 * of a SED object
 *
 * Parameters:
 * @param sed - the SED object
 */


/**
 * Function: free_speclist
 * The function releases all the memory
 * of a list of beamspec's.
 *
 * Parameters:
 * @param speclist - a list of beamspecs
 *
 */


/**
 * Function: free_tracedata
 * Releases the memory in
 * a tracedata structure.
 *
 * Parameters:
 * @param acttrace - the structure to be freed
 */


/*
 * Function: fill_gaussvalues
 * The function determines the wavelength dependent emission
 * for a given object at a given point in the gaussian emission model.
 * The values are filled into the
 * according vector of the tracedata structure.
 *
 * Parameters:
 * @param dpixel      - the coordinates of the point
 * @param actbeam     - the beam to derive
 * @param actdir      - the direct object
 * @param lambda_ref  - the reference wavelength
 * @param conf        - the configuration structure
 * @param acttrace    - the tracedata structure
 *
 */


/**
  Creates a simulation of a flat field using random numbers.
  Use only for debugging.
*/


/**
    Load and return a gsl cube whose planes (z-direction) contain the
    coefficients of a polynomial of the form ff(i,j,lambda) = a0+a1*lambda+...

    @param fname the name of a flat cube to read and load

    @returns a pointer to a NULL terminated array of gsl_matrix
*/


/**
    Evaluates and return the flatfielding value of pixel coordinates x,y
    and at wavelength lambda, using the field dependent polynomial
    description contained in a poly_cube_flatfield structure. Uses abs(lambda)
    for cosmetic reasons.
    If the sampled wavelength falls outside of the wmin<w<wmax range, then a warning
    is issued and no flat-field coefficient is computed, and 1.0 is returned
	[new version now returns the FF value at the closest known wavelength]
    @param lambda the wavelength

*/


/**
    Completely frees up the space allocated to a gsl_matrix
    @param poly_cube a pointer to a poly_cube_flatfield structure

*/


/**
  computes the relative efficiency of a pixel from a base flat
  field and a polynomial describing the wavelength dependence of
  the efficiency.

  @param lambda the wave length to assume
  @param x x coordinate of the pixel in question relative to the origin of
    the entire image
  @param y ditto for y
  @param flat pointer to the flatfielding structure containing information
    for the ture
  @returns relative efficiency for (x,y)
*/


/**
  loads (a part) of a flatfield file

  @param flat a pointer to the flatfield descriptor
  @param flat_name the name of the file containing the flat field
  @return a pointer to a gsl_matrix containing the relative efficiencies
    for each pixel in the bbox defined in flat
  @todo do real fits io
*/


/**
  loads (a part) of the error extension from a flatfield file

  @param flat a pointer to the flatfield function containing the
    bounding box
  @param flat_name the name of the file containing the flat field
  @return a pointer to a gsl_matrix containing the relative efficiencies
    for each pixel in the bbox defined in flat
  @todo do real fits io
*/


/**
  creates a descriptor for a flatfield with a single flat field and
  a polynomial wave length dependence, such that the efficiency
  at wavelength lambda is flat(x,y)*poly(lambda).

  @param curbeam the beam to create the flatfield for, with the bbox filled
    out (e.g., after spc_extract has run)
  @param flat_name name of a flat field file
  @param order the order of the polynomial
  @param coeffs the coefficients of the polynomial (contains order+1 doubles)
  @return an allocated flatfield descriptor
*/


/**
  frees a polynom flatfield and its assoicated data structures

  @param flat  the flatfield to free
*/


/**
  computes the relative efficiency of a pixel from a set of flatfields
  at various lambdas.

  @param lambda the wave length to assume
  @param x x coordinate of the pixel in question relative to the origin of
    the entire image
  @param y ditto for y
  @param flat pointer to the flatfielding structure containing information
    for the aperture
  @returns relative efficiency for (x,y)
  @todo check if the interpolation is good at the borders of the lambda range
*/


/**
  frees a flatfield consisting of multiple images and its
  assoicated data structures

  @param flat  the flatfield to free
*/


/**
 * Function: load_object_models
 * The function loads all direct emission models stored in a mulit-extension
 * fits image into a corresponding object model structure.
 *
 * Parameters:
 * @param object_models_file - the file with the object model data
 *
 * Returns:
 * @return objmodels - the object model structure
 */


/**
 * Function: load_diremission
 * The function loads one extension of a multi-extension fits file
 * with emission model and creates a single direct emission object.
 * This object is eventually returned.
 *
 * Parameters:
 * @param object_models_file - the file with the object model data
 * @param ext_num            - the extension number to load
 *
 * Returns:
 * @return diremission - a direct emission model
 */


/**
 * Function: free_object_models
 * The function frees all memory allocated in a object model structure.
 *
 * Parameters:
 * @param objmodels - the object model structure to free
 *
 * Returns:
 * @return -
 */


/**
 * Function: free_dirim_emission
 * The function frees all memory allocated in a direct
 * emission object.
 *
 * Parameters:
 * @param diremission - the direct emission model to free
 *
 * Returns:
 * @return -
 */


/**
 * Function: print_object_models
 * The function prints a direct object model structure.
 *
 * Parameters:
 * @param objmodels - the object model structure to 'print'
 *
 * Returns:
 * @return -
 */


/**
 * Function: print_dirim_emission
 * The function prints a direct emission object.
 *
 * Parameters:
 * @param diremission - the direct emission model to print
 *
 * Returns:
 * @return -
 */


/**
 * Function: has_aperture_dirim
 * The function checks whether an object has an associated direct emission
 * structure or not. The corresponding boolean integer value is returned.
 *
 * Parameters:
 * @param objmodels - the object models structure
 * @param actobject - the object structure
 *
 * Returns:
 * @return has_dirim - boolean whether direct emission exists (=1) or not (=0)
 */


/**
 * Function: bilin_interp_matrix
 * The function computes and returns the bilinear interpolated value
 * of a given matrix at a given coordinate position. The algorithm
 * was taken from the numerical recipes.
 *
 * Parameters:
 * @param modimage - the direct emission model
 * @param x        - the x-position
 * @param y        - the y-position
 *
 * Returns:
 * @return value - the interpolated value
 */


/**
 * Function: load_spectral_models
 * The function file a spectral models structure with models extracted
 * from a fits file.
 *
 * Parameters:
 * @param  spectral_models_file - pathname to the spectral models file
 *
 * Returns:
 * @return smodels - the tracedata structure
 */


/**
 * Function: print_spectral_models
 * The function prints the content of a spectral models
 * structure onto the screen
 *
 * Parameters:
 * @param  smodels - the spectral models structure
 *
 * Returns:
 * @return -
 */


/**
 * Function: load_SED_from_fitsext
 * The function creates a energy distribution from the data stored
 * in a fits file extension. The data must be stored in the columns
 * "wavelength" and "flux".
 *
 * Parameters:
 * @param  spectral_models_file - pathname to the spectral models file
 * @param  s_models             - pointer to the fits file extension
 *
 * Returns:
 * @return sed - the energy distribution created
 */


/**
 * Function: free_spectral_models
 * Releases the memory allocated in a spectral
 * models structure
 *
 * Parameters:
 * @param  smodels - the spectral models structure
 *
 * Returns:
 * @return -
 */


/**
 * Function: allocate_spectrum
 * allocates and initializes a spectrum and its subordinate data structures
 * (this is usually called by binning routines, so I've declared it static)
 *
 * Parameters:
 * @param numbin - number of spectrum data points
 *
 * Returns:
 * @return sp  - the allocated spectrum structure
 */


/**
 * Function: free_spectrum
 * Frees a spectrum and its subordinate data structures
 *
 * Parameters:
 * @param spec - a pointer to the spectrum structure.
 */


/**
 * Function: fprintf_spectrum
 * Function to display the content of a spectrum
 *
 * Parameters:
 * @param output - a pointer to a stream
 * @param sp     - a pointer to a spectrum
 */


/**
 * Function: subtract_spectra
 * Subtract one spectrum form sa second one
 *
 * Parameters:
 * @param a - the original spectrum
 * @param b - the spectrum to subtract
 *
 * Returns:
 * @param res - the subtracted spectrum
 */


/**
 * Function: empty_counts_spectrum_copy
 * Allocate and create an empty spectrum on the basis of a
 * template spectrum
 *
 * Parameters:
 * @param a - the input spectrum
 *
 * Returns:
 * @param res - the subtracted spectrum
 */


/**
 * Function: create_SPC
 * A function that creates a FITS file containing an empty primary header
 *
 * Parameters:
 * @param filename  - the name of the file to open
 * @param overwrite - if set to 1, then any exisiting file is deleted. Nothing is done otherwise.
 */


/**
 * Function: create_SPC_opened
 * A function that creates a FITS file containing an empty primary header
 *
 * @param filename  - The name of the file to open
 * @param overwrite - If set to 1, then any exisiting file is deleted. Nothing is done otherwise.
 *
 * Returns:
 * @return output - pointer to the opened fits-file
 */


/**
 * Function: find_ID_in_SPC
 * A  function to return the number of the HDU which has a givenextname.
 *
 * Parameters:
 * @param filename - the name of the file to open
 * @param ID       - a string containing the ID to match
 *
 * Returns:
 * @return         - the number of the HDU with matching ID. Returns -1 if none is found. A warning is issued.
 */


/**
 * Function: add_ID_to_SPC
 * A function that add a binary table extension to an existing SPC FITS file.
 * The table is appended to the FITS file. No check is performed to ensure that the
 * named extension does not exist already. This function is meant to initialize
 * a FITS binary table which will be used to store the content of an spectrum structure.
 *
 * Parameters:
 * @param filename - The name of the file to open
 * @param N        - The size of the vectors in this table (i.e. number of pixels in the ap_pixel structure).
 * @param extname  - The name to give to this extension
 *
 * Returns:
 * @return hdunum  - the number of the HDU that was just created
 */


/**
 * Function: add_ID_index_to_SPC
 * Add an HDU index keyword for beam ID%d%c into the first HDU of the FITS file.
 *
 * Parameters:
 * @param filename - a pointer to an array containing the name of an existing FITS file.
 * @param ID       - a pointer to a char array containing the beam ID in the form "ID%d%c".
 * @param hdunum   - the index of the HDU containing this beam.
 */


/**
 * Function: add_spectra_to_SPC
 * Function to add a new entry into a SPC file.
 * This function takes three spectra, one containing the object, one containing
 * the background, and the last one containing the object subtracted background and
 * add the information to the appropriate (i.e. create a new one or update an existing one)
 * extension binary table.
 *
 * Parameters:
 * @param filename  - a pointer to a string containing the name of the PET file to write to/
 * @param obj_spec  - a pointer to a spectrum structure containing the object+background 1D binned spectrum
 * @param bck_spec  - a pointer to a spectrum structure containing the background 1D binned spectrum
 * @param sobj_spec - a pointer to a spectrum structure containing the object  1D binned spectrum
 * @param aperID    - the numeric aperture ID of this table.
 * @param beamID    - the numeric beam ID of this table.
 */


/**
 * Function: add_data_to_SPC
 * Function to add a specific spectrum structure into specifically
 * named columns of an existing SPC FITS file. If a column name
 * is set to NULL then that particular data column is not written to the file.
 *
 * Parameters:
 * @param spec          - a pointer to an existing spectrum structure
 * @param coutncolname  - the name of the column to write spec.counts into
 * @param errorcolname  - the name of the column to write spec.errors into
 * @param weightcolname - the name of the column to write spec.weights into
 * @param ID            - the aperture/beam ID of this spectrum
 * @param filename      - the name of an existing SPC FITS table
 * @param hdunum        - the number of the extension in the SPC FITS file to write the data to
 * @param N             - the number of elements of the spectrum to write to the table
 */


/**
 *
 * Function: add_spectra_to_SPC_opened
 * Function to add a new entry into a SPC file.
 * This function takes three spectra, one containing the object, one containing
 * the background, and the last one containing the object subtracted background and
 * add the information to the appropriate (i.e. create a new one or update an existing one)
 * extension binary table.
 *
 * @param filename a pointer to a string containing the name of the PET file to write to/
 * @param obj_spec a pointer to a spectrum structure containing the object+background 1D binned spectrum
 * @param bck_spec a pointer to a spectrum structure containing the background 1D binned spectrum
 * @param sobj_spec a pointer to a spectrum structure containing the object  1D binned spectrum
 * @param aperID the numeric aperture ID of this table.
 * @param beamID the numeric beam ID of this table.
 */


/**
 * Function: add_data_to_SPC_opened
 * Function to add a specific spectrum structure into specifically
 * named columns of an existing opened SPC FITS file. If a column name
 * is set to NULL then that particular data column is not written to the file.
 *
 * @param spec          - a pointer to an existing spectrum structure
 * @param coutncolname  - the name of the column to write spec.counts into
 * @param errorcolname  - the name of the column to write spec.errors into
 * @param weightcolname - the name of the column to write spec.weights into
 * @param ID            - the aperture/beam ID of this spectrum
 * @param input         - a pointer to an opened FITS file and HDU
 * @param N             - the number of elements of the spectrum to write to the table
 */


/**
 * Function: trim_spectrum
 * A function which trims the beginning and ending INDEF values
 * out of a spectrum structure (left by the bin_naive routine.
 * The spectrum is replace in place.
 *
 * Parameters:
 * @param spc - a pointer to an existing spectrum structure
 *
 * Returns:
 * new_spc - pointer to a trimmed spectrum structure
 */


/**
 * Function: det_vector_polyN
 * A function using GSL fitting functions to fit a set x,y,w of n elements
 * such that an Nth degree polynomial is fitted to the x and y vectors
 * using the weights w. This function avoids NaN values in ys AND elements
 * with an associated weight that is zero.
 *
 * Parameters:
 * @param m   - order of the fit
 * @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 c   - the vector with the fitted coefficients
 * @param cov - the covariance matrix
 *
 * Returns:
 * @return interp - vector with additional fitting information
 */


/**
 * Function: fill_polyN_interp
 * Evaluates a polynomial of any order and fills the
 * result plus the error, compute using the covariance
 * matrix, in vectors.
 *
 * Parameters:
 * @param xs     - double vector containing the x values
 * @param ys     - double vector containing the y values
 * @param yi     - double vector containing the intermediate 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 c      - the vector with the fitted coefficients
 * @param cov    - the covariance matrix
 * @param interp - additional fitting ifnormation
 * @param final  - flagg to indicate final fit and
 *                 therefore a replacement
 */


/**
 * Function: comp_vector_average
 * The function provides the computation of the average of
 * the y-values and store that average in temporary
 * or the original y-vector.
 *
 * @param xs    - absissa
 * @param ys    - value at xs[]
 * @param ws    - weight in ys[]
 * @param yi    - temprary y-values
 * @param n     - number of points in xs, ys, ws
 * @param final - flagg to store to temp (0) or final (1) vectors
 */


/**
 * Function: comp_vector_median
 * The function provides the computation of the median of
 * the y-values and store that median in temporary
 * or the original y-vector
 *
 * @param xs - absissa
 * @param ys - value at xs[]
 * @param ws - weight in ys[]
 * @param yi    - temprary y-values
 * @param n     - number of points in xs, ys, ws
 * @param final - flagg to store to temp (0) or final (1) vectors
 */


/**
 * Function: comp_vector_linear
 * The function fits a linear function to the y-values
 * and fills the linear inteprolated values in a temporary
 * vector and, if requested, in the original vector as well.
 *
 * @param xs    - absissa
 * @param ys    - value at xs[]
 * @param ws    - weight in ys[]
 * @param yi    - temprary y-values
 * @param n     - number of points in xs, ys, ws
 * @param final - flagg to store to temp (0) or final (1) vectors
 */


/**
 * Function: comp_vector_polyN
 * The function fits a polynomial function to the y-values
 * and fills the evaluated polynomial values in a temporary
 * vector and, if requested, in the original vector as well.
 *
 * @param xs    - absissa
 * @param ys    - value at xs[]
 * @param ws    - weight in ys[]
 * @param yi    - temprary y-values
 * @param n     - number of points in xs, ys, ws
 * @param final - flagg to store to temp (0) or final (1) vectors
 */


/**
 * Function: det_vector_linear
 * Performs a linear fit of the xs, ys, and ws arrays.
 * Ignores NaN values. Fitted values are returned in
 * ys and errors in ws.
 *
 * Parameters:
 * @param xs     - absissa
 * @param ys     - value at xs[]
 * @param ws     - error in ys[]
 * @param n      - number of points in xs, ys, ws
 * @param weight - make weighted fit (=1) or not (=0)
 *
 * Returns:
 * @return ret - the covariance values
 */


/**
 * Function: fill_linear_interp
 * The function computes and stores linear interpolated values
 * in one or several output vectors.
 *
 * 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 yi     - double vector containing the intermediate y-values
 * @param n      - number of points in xs,ys, and ws (must be greater than m!)
 * @param interp - vector with the fitted values
 * @param final  - flagg to indicate final fit and
 *                 therefore a replacement
 */


/**
 * Function: det_vector_average
 * The function computes the average and the standard
 * deviation from the values in a vector
 *
 * @param xs  - absissa
 * @param ys  - value at xs[]
 * @param ws  - weight in ys[]
 * @param n   - number of points in xs, ys, ws
 * @param avg - the average
 * @param std - the standard deviation
 */


/**
 * Function: det_vector_median
 * The function computes the median and the standard
 * deviation from the values in a vector
 *
 * @param xs  - absissa
 * @param ys  - value at xs[]
 * @param ws  - weight in ys[]
 * @param n   - number of points in xs, ys, ws
 * @param med - the median
 * @param std - the standard deviation
 */


/**
 * Function:fill_const_value
 * The function fills two constant values into
 * up to three vectors.
 *
 * @param ys    - value at xs[]
 * @param ws    - weight in ys[]
 * @param yi    - value at xs[]
 * @param n     - number of points in xs, ys, ws
 * @param cval  - number of points in xs, ys, ws
 * @param stdev - number of points in xs, ys, ws
 * @param final - flagg which indicates which vectors to fill
 */


/**
 * A helper function which populates the error part of an
 * observation structure using simple Poisson noise. Assumes
 * data is in electrons.
 *
 *  @param img a pointer to an exisiting observation structure
 *
 *  @return a pointer to a GDL matrix containing the error array
*/


/**
 * This function uses the DQ information contained in an observation
 * structure together with a bitmask (represented as an integer) to
 * determine if a pixel is to be flagged as bad or not. Flagged
 * pixel are replaces by GSL_NAN values.
 *
 * @param obs a pointer to an exisiting observation structure
 * @param dqmask an integer representation of a bit mask.
 */


/**
 * Function to load a multiple extension FITS file into an
 * observation structure
 *
 * @param fname a pointer to a string containing the name of the file to open
 * @param hdunum_data the extension number containing the data array (first=1)
 * @param hdunum_err the extension number containing the err array (first=1)
 * @param hdunum_dq the extension number containing the DQ array (first=1)
 * @param dqmask the bit mask (represented as an int) to apply using the
 *               DQ info to flag a pixel as good or bad
 * @param exptime exposure time (only used to determine count noise)
 * @param gain gain factor (only used to determine count noise)
 * @return observation a pointer to a new allocated, populated, DQ
 *         masked observation structure
 */


/**
    Function to load a multiple extension FITS file into an observation structure

    @param fname a pointer to a string containing the name of the file to open
    @param hdunum_data the extension number containing the data array (first=1)
    @param hdunum_err the extension number containing the err array (first=1)
    @param hdunum_dq the extension number containing the DQ array (first=1)
    @param dqmask the bit mask (represented as an int) to apply using the DQ info to flag a pixel as
        good or bad
        @param exptime exposure time (only used to determine count noise)
        @param gain gain factor (only used to determine count noise)
    @return observation a pointer to a new allocated, populated, DQ masked observation structure
*/


/**
    Return the number of extensions in a FITS image

  @param fname File name of the FITS image
  @return the number of extensions
*/


/**
  Read a FITS image, DO not read data but return an empty gsl array
  This function is meant to be a faster way to get information about
  an observation rather than the actual data.

  @param fname File name of the FITS image
  @return a gsl_matrix (overriden in aXe_grism.h) containing the
  image data or NULL
*/


/**
  Read a FITS image into a gsl array

  @param fname File name of the FITS image
  @param hdunum the number of the extension to read in (first primary = 1)
  @param fatal if non zero an error loading the data will trigger an exception
  @return a gsl_matrix (overriden in aXe_grism.h) containing the
  image data or NULL
*/


/**
    Function to create a new FITS image file with an empty first extension.
    If overwrite is non zero, any existing file is deleted.

    @param filename a pointer to an array of character containing the filename
    @param overwrite if set to 1 exisiting file is deleted first
    @return a fitsifle pointer to a newly created FITS file
*/


/**
    Function to create a new FITS image file with an empty first extension.
    If overwrite is non zero, any existing file is deleted.

    @param filename a pointer to an array of character containing the filename
    @param overwrite if set to 1 exisiting file is deleted first
*/


/**
    Store the content of a gsl_matrix into a FITS file

    @param data a pointer to an existing gsl_matrix structure
    @param fname a pointer to a string containing the name of the FITS file to write to
    @param overwrite if set to 1 then existing file is deleted, otherwise an extension is added
    @param ID an ID string which will be used to write an EXTNAME keyword in the extension
    @param HDUfile
    @param HDUfilenum

    @return the number of the HDU written to
*/


/**
    Store the content of a gsl_matrix into a FITS file

    @param data a pointer to an existing gsl_matrix structure
    @param fname a pointer to a string containing the name of the FITS file to write to
    @param overwrite if set to 1 then existing file is deleted, otherwise an extension is added
    @param ID an ID string which will be used to write an EXTNAME keyword in the extension. If NULL, no extension name is written.
    @param HDUfile
    @param HDUfilenum

    @return the number of the HDU written to
*/


/**
    Store the content of a gsl_matrix into a FITS file

    @param data a pointer to an existing gsl_matrix structure
    @param fname a pointer to a string containing the name of the FITS file to write to
    @param overwrite if set to 1 then existing file is deleted, otherwise an extension is added
    @param ID an ID string which will be used to write an EXTNAME keyword in the extension.
           If NULL, no extension name is written.
    @param hdunum, an integer pinting to the HDU the image should be written to
    @param HDUfile
    @param HDUfilenum

    @return the number of the HDU written to
*/


/**
  computes the bbox of a general quadrangle.

  @param corners the four corners of the quadrangle
  @param ll a px_point to hold the lower left corner
  @param ur a px_point to hold the upper right corner
*/


/**
  Saves a gsl matrix to a pgm image file, properly scaled and all.

  @param fname name of pgm file to write
  @param m the matrix
  @return 0 for success, -1 for failure
*/


/**
    routine to write a set of FITS header cards into a FITS header of a given
    extension. Input cards are automatically formatted propely if they are not.

    @param filename a pointer to a char array containing the name fo the existing FITS file
    @param hdu the number of the extension to write to (-1 for last one)
    @param cards a NULL terminated array of char arrays containing properly formatted cards

*/


/**
    routine to write a set of FITS header cards into a FITS header of a given
    extension. Input cards are automatically formatted propely if they are not.

    @param input a fitsfile pointer pointing to the extension to write the cards to.
    @param hdu the number of the extension to write to (-1 for last one)
    @param cards a NULL terminated array of char arrays containing properly formatted cards

*/


/**
    A helpder function which given the name of an environment variable and a string
    containing a filename, this function
    returns the complete path to the file

    @param envpathname a pointer to a cahr string containing the name of the
    environment variable to use for the path to the file
    @param inputfile a pointer to a string containing a filename, possibly formatted as file[hdu].
    This is replaced with the name of the file without the extension appended to it.
    @param filename a pointer to an allocated char array to receive the real file name
*/


/**
 * Function: free_char_arr
 * The function releases the memory allocated
 * in a memory array.
 *
 * Parameters:
 * @param char_arr - pointer to the character array
 * @param nrows    - the number of rows in the character array
 *
 */


/**
 * Function: build_config_files
 * The function parses a long character string and separates
 * individual tokens along the character ",". The tokens are
 * stored in a character array. A check is performed such
 * that not more tokens are copied than there exist rows
 * in the character array.
 *
 * Parameters:
 * @param list_file  - the character string to parse
 * @param list_files - the character array
 * @param maxnrows   - the number of rows in the character array
 *
 * Returns:
 * @return nlist   - the number of tokens copied
 */


/**
    Free a NULL terminated array of objects

    @param sobjs, a NULL terminated array containing pointers to objects

*/


/**
    output the content of an object structure

*/


/**
    Function to free an observation struture

    @param obs an observation pointer
*/


/**
 * Function: compute_modvar
 *
 *
 * Parameters:
 * @param ap_p      - the PET table
 * @param actbeam   - beam to compute the modvar structure for
 * @param dimension - dimenasion of the images
 * @param modvar    - the structure to fill
 */


/**
 * Function: prepare_inv_variance
 * The function prepares the inverse model variances
 * for a data set containing an object and a background PET.
 * This is done in subroutines which compute the
 * theoretical inverse pixel variance following
 * different methods for the object and the background PET.
 *
 * Parameters:
 * @param ap_p     - the object PET table
 * @param bg_p     - the background PET table
 * @param dobck    - integer indicating background subtraction
 * @param conf     - the configuration structure
 * @param exptime  - the exposure time
 * @param sky_cps  - the sky background
 */


/**
 * Function: compute_model_ivar
 * The function computes for each PET pixel the
 * associated inverse variance value. The input
 * for variance and inverse variance are the
 * model value, the contamination value, the
 * constant sky background value and the readnoise.
 * The computed inverse variance value is stored
 * in the weight entry of the PET.
 * The function also offers the possibility to
 * shift the trace distance by a fixed amount.
 *
 * Parameters:
 * @param ap_p     - the PET table
 * @param rdnoise  - the readnoise value
 * @param exptime  - the exposure time
 * @param sky_cps  - the sky background
 * @param xi_shift - shift in trace distance
 */


/**
 * Function: compute_value_ivar
 * The function computes for each PET pixel the
 * associated inverse variance value. The input
 * to derive the variance is the count value and
 * the readnoise.
 * The computed inverse variance value is stored
 * in the weight entry of the PET.
 * The function also offers the possibility to
 * shift the trace distance by a fixed amount.
 *
 * Parameters:
 * @param ap_p    - the PET table
 * @param rdnoise  - the readnoise value
 * @param exptime - the exposure time
 * @param sky_cps - the sky background
 * @param xi_shift - shift in trace distance
 */


/**
 * Function: alloc_drzstamp
 * Allocates memory for a drizzle stamp structure
 * according the the dimension specified in the input.
 *
 * Parameters:
 * @param dimension - the dimesions to allocate
 *
 * Returns:
 * @return ret  - the drizzle stamp image allocated
 */


/*
 * Function: comp_opt_weight
 * The function uses the model map and and the variance
 * map and computes optimale weigths according to the
 * Hoorne method.
 * Pixels outside of the extraction
 * area are set to 1000.0
 *
 * Parameters:
 * @param mod_map - the matrix with the model values
 * @param var_map - the matrix with the variance values
 * @param ob      - the object structure
 *
 * Returns:
 * @return weight - the matrix with the exposure time weights
 */


/*
 * This file contains default implementation of the evaluate and printout
 * routines. In most cases, customization of lmfit can be done by modifying
 * these two routines. Either modify them here, or copy and rename them.
 */


/**
 * Function: stamp_img
 * Produce a gsl array containing a stamp image.
 * Returns NULL is input object is NULL.
 *
 * Parameters:
 * @param ap_p    - a pointer to a -1 terminated ap_pixel array
 * @param width   - extraction width used
 * @param stp_min - xy-coords of the lower left corner on image
 *
 * Returns:
 * @return res  - a pointer to a newly allocated gsl_matrix containing the
 *                spectrum
 */


/**
 * Function: stamp_img_drzprep
 * Creates all drizzle prepare stamp images from a PET
 * vector. In case of an empty PET, dummy stamps are returned.
 *
 * Parameters:
 * @param opt_extr   - flagg to indicate optimal extraction
 * @param ap_p       - a pointer to a -1 terminated ap_pixel array
 * @param width      - extraction width used
 * @param nullval    - the default pixel value
 * @param quant_cont - flag to indicate quantitative cont.
 * @param dimension  - size information
 * @param drzcoeffs  - the drizzle coefficients
 * @param exptime    - the exposure time
 * @param sky_cps    - the sky background
 *
 * Returns:
 * @return drzprep_stamps - a pointer to the new struct with the
 *                          drzprep stamp images
 */


/**
 * Function: rectified_stamp_img
 * Produce a gsl array containing a 'rectified aperture'. That is,
 * an image of the spectum showing count on an xi,dist grid instead
 * of the traditional image grid x,y. Returns NULL is input object is NULL.
 *
 * Parameters:
 * @param ap_p  - a pointer to a -1 terminated ap_pixel array
 * @param width - extraction width used
 *
 * Returns:
 * @return res - a pointer to a newly allocated gsl_matrix containing the
 * rectified spectrum
 */


/**
 * Function: drizzled_stamp_img
 * Produce a structure containing a drizzled stamp image plux ther
 * associated weight image. The drizzled stamp image has constant
 * dispersion along the x-axis. No drizzling is applied
 * in cross-dispersion direction. The dimensions of the drizzled
 * stampimage were setr previously, and the information
 * is in an input structure. In case that there are no valid pixels,
 * a dummy structure with 10x10 empty pixels is returned.
 *
 * @param ap_p      - pointer to the list of PET pixels
 * @param width     - extraction width used
 * @param dimension - dimensional information on the drizzled stamp
 *
 * @return res      - structure with counts and weights of the drizzled stamp
*/


/**
    Produce a gsl array containing a 'drizzled aperture'. That is,
    an image of the spectum showing count on an xi,dist grid instead
    of the traditional image grid x,y. Returns NULL is input object is NULL.
	[modifies ap_p!!]
    @param ap_p a pointer to a -1 terminated ap_pixel array
    @param width extraction width used
	@param resampwidth A per pixel of output drizzled spectra
    @return a pointer to a newly allocated gsl_matrix containing the
    rectified spectrum
*/


/**
 * Function: interpolate_over_NaN
 * Function to interpolate over and replace NaN values in a rectified
 * stamp image. This is done by interpolating in the vertical direction.
 * The original gsl_matrix is free'd and is replaced by a new gsl_matrix pointer.
 * Does nothing if input data is NULL.
 *
 * Parameters:
 * @param data - the gsl_matrix where NaN values are to be interpolated over
 */


/*
 * Function: free_drzprep
 * The function releases the memory allocated
 * to the various components of a drzprep structure
 *
 * Parameters:
 * @param: drzprep_stamps - the stamp image to free
 */


/**
 * Function: free_stamp_img
 * Function to free the memeory allocated by a stamp image
 *
 * Parameters:
 * @param rstamp - the stamp image
 */


/**
 * Function: free_drzstamp
 * Function to free the memeory allocated by a
 * drizzled stamp image.
 *
 * Parameters:
 * @param rstamp  - the structure for the drizzled stamp image
 */


/**
 * Function: compute_gauss_cont
 * The subroutine computes ans stores the quantitative contamination
 * using the Gaussian emission model. The emitting object with Gaussian
 * shape and SED as derived from the AB filter magnitudes are composed
 * The individual nbeams are modelled, then the complete contamination
 * image is composed from the beam models.
 * Finally, the contaminating flux is computed by subtracting the
 * beam emission from the contamination image for all PET pixels.
 *
 * Parameters:
 * @param grism_file  - the full name of the grism file
 * @param OAF_file    - the name of the aperture file
 * @param CONF_file   - the full name of configuration file
 * @param specmod_file- fits table with the model spectra
 * @param model_scale - the scale for extension of the direct object area
 * @param inter_type  - the interpolation method for the flux values
 * @param lambda_psf  - wavelength the Gaussian parameters were determined at
 * @param obs         - the observation
 * @param PET_file    - the name of the PET which is modified
 * @param map_file    - the name of the contamination map
 * @param store       - flag whether the contamination image is stored or not
 *
 * Returns:
 * @return status     - returns success or failure
 */


/**
 * Function: compute_gaussdirim_cont
 * The subroutine computes ans stores the quantitative contamination
 * using the Gaussian emission model. The object shape can be defined
 * in a fits file with object models, and the SED may be defined in a
 * fits table with high resolution spectra. If no detailed object shape
 * or SED is given for an individual object, Gaussian shape and SED as
 * derived from the AB filter magnitudes are composed.
 * The individual nbeams are modelled, then the complete contamination
 * image is composed from the beam models.
 * Finally, the contaminating flux is computed by subtracting the
 * beam emission from the contamination image for all PET pixels.
 *
 * Parameters:
 * @param grism_file  - the full name of the grism file
 * @param OAF_file    - the name of the aperture file
 * @param CONF_file   - the full name of configuration file
 * @param specmod_file- fits table with the model spectra
 * @param objmod_file - fits image with object models
 * @param model_scale - the scale for extension of the direct object area
 * @param inter_type  - the interpolation method for the flux values
 * @param lambda_psf  - wavelength the Gaussian parameters were determined at
 * @param obs         - the observation
 * @param PET_file    - the name of the PET which is modified
 * @param map_file    - the name of the contamination map
 * @param store       - flag whether the contamination image is stored or not
 *
 * Returns:
 * @return status     - returns success or failure
 */


/*
 * Function: compute_fcube_cont
 * The subroutine computes ans stores the quantitative contamination
 * using the Fluxcube emission model. The emitting objects are defined
 * in fluxcube images, which were derived from MultiDrizzled direct images.
 * The individual nbeams are modelled, then the complete contamination
 * image is composed from the beam models.
 * Finally, the contaminating flux is computed by subtracting the
 * beam emission from the contamination image for all PET pixels.
 *
 *
 * Parameters:
 * @param grism_file  - the full name of the grism file
 * @param OAF_file    - the name of the aperture file
 * @param fcube_file  - the name of the fluxcube file
 * @param CONF_file   - the full name of configuration file
 * @param model_scale - the scale for extension of the direct object area
 * @param inter_type  - the interpolation method for the flux values
 * @param obs         - the observation
 * @param PET_file    - the name of the PET which is modified
 * @param map_file    - the name of the contamination map
 * @param store       - flag whether the contamination image is stored or not
 *
 * Returns:
 * @return status     - returns success or failure
 */


/**
 * Function: dimension_beamspec
 * The function checks the boundaries of a candidate
 * model spectrum of a beam. In case that the
 * model spectrum is completely outside the frame,
 * a NULL model spectrum is returned.
 * Otherwise space is allocated for the model spectrum and
 * the matrix therein, and the data are filled in.
 * Only the matrix is not defined and filled.
 *
 * Parameters:
 * @param  dirlist   - the list with all dirobjects
 * @param  actobject - one beam of this object is examined
 * @param  npixels   - the size of the CCD
 * @param  conf      - the configutration structure
 * @param  j         - the beam number to be examined
 *
 * Returns:
 * @return actspec   - the beamspec object created
 */


/**
 * Function: fill_pixel_in_speed
 * The function determines and coadds the contribution of a single pixel in
 * the direct image area to the model spectrum.
 *
 * Parameters:
 * @param  actdir   - the direct object of the model spectrum
 * @param  acttrace - the tracedata of the model spectrum
 * @param  dpixel   - the coordinates of the modelled pixel
 * @param  eval     - the emission value of the source at the modelled pixel
 * @param  resp     - the sensitivity data
 * @param  actspec  - the structure for the model spectrum
 *
 * Returns:
 * @return 1        -
 */


/**
 * Function no_diffuse_spectrum
 * Adds the simulated flux for one pixel exactly into
 * one pixel, using the integer value of the correct
 * position.
 *
 * Parameters:
 * @param  ix      - the integer x-position in the beam
 * @param  iy      - the integer y-position in the beam
 * @param  cps     - the cps-value for one entire pixel
 * @param  actspec - the beam to model
 *
 * Returns:
 * @return 1.0     - return a dummy value
 */


/**
 * Function diffuse_spectrum
 * Distribute the flux simulated for the area of one pixel
 * square in the emission model over a pixel square in
 * the beam model.
 * This method uses sub-steps starting from the exact
 * center of the light
 * This smoothes the modelled beam by avoiding integer
 * rounding effects.
 *
 * Parameters:
 * @param  ddx     - the exact x-position in the beam
 * @param  ddy     - the exact y-position in the beam
 * @param  cps     - the cps-value for one entire pixel
 * @param  actspec - the beam to model
 *
 * Returns:
 * @return 1.0     - return a dummy value
 */


/**
 * Function diffuse_spectrumII
 * Distribute the flux simulated for the area of one pixel
 * square in the emission model over a pixel square in
 * the beam model.
 * Starting from the exact center of the light, the exact fraction
 * falling on the four affected pixels is comuted and then added
 * to the spectral beam.
 * This smoothes the modelled beam by avoiding integer
 * rounding effects.
 *
 * Parameters:
 * @param  ddx     - the exact x-position in the beam
 * @param  ddy     - the exact y-position in the beam
 * @param  cps     - the cps-value for one entire pixel
 * @param  actspec - the beam to model
 *
 * Returns:
 * @return 1.0     - return a dummy value
 */


/**
 *
 * Function: make_model_image
 * Sums up the modeled spectral beams to create a
 * spectral model for the whole image.
 *
 * Parameters:
 * @param  npixels    - the dimensions of the input grism image
 * @param  speclist   - the list of modelled beams
 *
 * Returns:
 * @return all_models - the model for the whole image
 */


/**
 * Function: fill_contam_info
 * The function fills the contamination information into the
 * PET. To do that it transfers the information from the
 * aperture mask matrix into each PET. Self contamination is
 * taken into account by subtracting the value from the modelled
 * spectrum before storing the contamination.
 *
 * Parameters:
 * @param PET_file   - the PET file to add contamination
 * @param speclist   - the list of modelled spectra
 * @param all_models - the contamination image
 *
 * Returns:
 * @return 1         - returns always 1
 */


/**
 * Function: compute_geometr_cont
 * The subroutine computes the original, geometrical contamination
 * model where every beams contaminates the area he occupies.
 * Source brightness and source shape are not taken into account.
 * For every beam the sum of all contaminations by othe beams is
 * written into the PET.
 *
 * Parameters:
 * @param OAF_file - the name of the aperture file
 * @param obs      - the observation
 * @param PET_file - the name of the PET which is modified
 * @param map_file - the name of the contamination map
 * @param store    - flagg whether the contamination image is stored or not
 *
 * Returns:
 * @return status  - returns success or failure
 */


/**
 * Function: compute_gauss_dirim
 *
 * @param grism_file  - the full name of the grism file
 * @param OAF_file    - the name of the aperture file
 * @param obs         - the observation
 * @param PET_file    - the name of the PET which is modified
 * @param CONF_file   - the full name of configuration file
 * @param map_file    - the name of the contamination map
 * @param model_scale - the scale for extension of the direct object area
 * @param store       - flagg whether the contamination image is stored or not
 *
 * @return status     - returns success or failure
 */


/**
 * Function: make_gauss_dirim
 * The function creates a spectral model for the beams
 * that are considered in the contamination. The modelled
 * beams are returned as a list.
 *
 * Parameters:
 * @param  oblist    - the object list as input to select beams
 * @param  dirlist   - the direct object list to dimension the models
 * @param  npixels   - the dimensions of the model for the whole image
 * @param  CONF_file - the name of the configuration file
 *
 * Returns:
 * @return speclist  - the list of modelled beams
 */


/**
    Routine to free a FITScards structure.

    @param cards a pointer to an allocated FITScards structure whose
    allocated memory is to be free'd.
*/


/**
    Routine to generate FITS header cards containing the information
    contained in a beam structure

    The following information gets written about the beam:

    OBJECTID, Object ID, ob->ID
    NBEAM,Number of beam in object, ob->nbeam
    BEAMID, This beam ID, b->ID
    REFPNTX, x coord. of reference point, b->refpoint.x
    REFPNTY, y coord. of reference point, b->refpoint.y
    C0X, x coord. of 1st bounding quadrangle corner, b->corners[0].x
    C0Y, y coord. of 1st bounding quadrangle corner, b->corners[0].y
    C1X, x coord. of 2nd bounding quadrangle corner, b->corners[1].x
    C1Y, y coord. of 2nd bounding quadrangle corner, b->corners[1].y
    C2X, x coord. of 3rd bounding quadrangle corner, b->corners[2].x
    C2Y, y coord. of 3rd bounding quadrangle corner, b->corners[2].y
    C3X, x coord. of 4th bounding quadrangle corner, b->corners[3].x
    C3Y, y coord. of 4th bounding quadrangle corner, b->corners[3].y
    BB0X, x coord. of 1st bounding box corner, b->bbox[0].x
    BB0Y, y coord. of 1st bounding box corner, b->bbox[0].y
    BB1X, x coord. of 2nd bounding box corner, b->bbox[1].x
    BB1Y, y coord. of 2nd bounding box corner, b->bbox[1].y
    WIDTH, Width of object in pixel, b->width
    ORIENT, Orientation of object in deg. wrt y-axis, CCW, b->orient
    IGNORE, Ignore flag for this beam, b->ignore

    @param ob a pointer to an existing object structure containing the beam we are interested in
    @param b a pointer to an existing beam in the passed object ob

    @return a pointer to an allocated FITScards structure

*/


/**
    Routine to generate FITS header cards containing the information
    for drizzling and beam information contained in a beam structure

    The following information gets written about the beam:

    OBJECTID, Object ID, ob->ID
    NBEAM,Number of beam in object, ob->nbeam
    BEAMID, This beam ID, b->ID
    REFPNTX, x coord. of reference point, b->refpoint.x
    REFPNTY, y coord. of reference point, b->refpoint.y
    C0X, x coord. of 1st bounding quadrangle corner, b->corners[0].x
    C0Y, y coord. of 1st bounding quadrangle corner, b->corners[0].y
    C1X, x coord. of 2nd bounding quadrangle corner, b->corners[1].x
    C1Y, y coord. of 2nd bounding quadrangle corner, b->corners[1].y
    C2X, x coord. of 3rd bounding quadrangle corner, b->corners[2].x
    C2Y, y coord. of 3rd bounding quadrangle corner, b->corners[2].y
    C3X, x coord. of 4th bounding quadrangle corner, b->corners[3].x
    C3Y, y coord. of 4th bounding quadrangle corner, b->corners[3].y
    BB0X, x coord. of 1st bounding box corner, b->bbox[0].x
    BB0Y, y coord. of 1st bounding box corner, b->bbox[0].y
    BB1X, x coord. of 2nd bounding box corner, b->bbox[1].x
    BB1Y, y coord. of 2nd bounding box corner, b->bbox[1].y
    WIDTH, Width of object in pixel, b->width
    ORIENT, Orientation of object in deg. wrt y-axis, CCW, b->orient
    IGNORE, Ignore flag for this beam, b->ignore

    @param ob a pointer to an existing object structure containing the beam we are interested in
    @param b a pointer to an existing beam in the passed object ob

    @return a pointer to an allocated FITScards structure

*/


/**
	A helper function which generates FITS keywords containing
	the content of a disp structure.

	@param disp A pointer to a dispstruct structure

    @return a pointer to an allocated FITScards structure
*/


/**
 * The function updates the keyword "CONTAM" in a fits file.
 * Update means that an existing entry is replace.
 * It is used to update this keyword in a PET files
 * within the command aXe_PETCONT.
 *
 * @param fptr       - pointer to the fits file
 * @param model_name - the name of the model
 *
 */


/**
 * The function reads the keyword "CONTAM" in an open FITS file
 * and ananlyzes its content. In case that the content indicates
 * a quantitative contamination model, 1 is returned. If not
 * the value 0 is given back.
 *
 * @param fptr - pointer to the FITS-file
 */


/**
 * The function transports the keywird entry for
 * the keyword "CONTAM" from one FITS file to another.
 * As the parameter names suggest, this works particularly
 * form drizzle grism images to PET's
 *
 * @param grism_file_path - the name of the input FITS file
 * @param PET_file_path   - the name of the output FITS file
 *
 */


/**
 * Fills a triangle structure and makes sure the angle at points[0]
 * is <=90 deg.
 *
 * @param trig the struct to fill.
 * @param points the three point at the corners of the triangle.
 */


/**
 * pre-computes some constant items for deciding whether a point is in
 * a given convex quadrangle.
 *
 * @param iid the descriptor to fill
 * @param corners the corners of the quadrangle
 * @return 0 for success, -1 for error
 */


/* This works by computing normalized covariant coordinates */


/**
  Decides if a point is within a quadrangle.

  @param x The x-coordinate of the point.
  @param y The y-coordinate of the point.
  @param iid The descriptor of the quadrangle.
  @return 1 if point is in quadrangle, 0 otherwise.
  @see fill_is_in_descriptor
*/


/**
 * Function: ij_to_radec
 * Returns the world coordinates corresponding to the
 * point ij in an image which as a WCS wcs.
 *
 * Parameter:
 * @param wcs, a pointer to a WorldCoor WCS structure
 * @param ij, a point inthe image
 *
 * Return:
 * @return a pointer to a d_point structure containing the world
 *  coordinates at point ij in degrees.
 */


/**
 * Function: radec_to_ij
 * Returns the detector pixel coordinates corresponding to the
 * point radec in the sky sgiven the WCS wcs.
 *
 * Parameter:
 * @param wcs a pointer to a WorldCoor WCS structure
 * @param radec a point with celestial coordinates
 *
 * Return:
 * @return a pointer to a d_point structure containing the image
 *  pixel coordinates.
 */


/**
    Allocate and return a new ap_pixel structure with enough
    room for N elements

    @param N number of element
    @return a pointer to a newly allocated ap_pixel structure
    @see ap_pixel

*/


/** A function that creates a FITS file containing an empty primary header

	@param filename The name of the file to open
	@param overwrite If set to 1, then any exisiting file is deleted. Nothing is done otherwise.
*/


/** A function that creates a FITS file containing an empty primary header
    and returns a fitsfile pointer to it
	@param filename The name of the file to open
	@param overwrite If set to 1, then any exisiting file is deleted. Nothing is done otherwise.
*/


/**
	A helper function that returns the number of elements in an ap_p structure

	@param ap_p A pointer to an existing ap_pixel structure
	@return number of elements
*/


/**
 * Function: add_ALL_to_PET
 * This function populate a BINARY table with the ALL the content of an
 * ap_pixel structure. This function is meant  to be use when one wishes
 * to keep adding new extension to a multi-extension file. It need to be passed
 * a fitsfile pointer pointing to an opened FITS file. A new FITS binary table
 * extension is appended, populated with the content od the ap_p table and the
 * fitsfile pointer pointing to this new extenstion is returned.
 *
 * Parameters:
 * @param ap_p   - An existing ap_pixel structure
 * @param ID     - the name to assign to this row
 * @param input  - a pointer to an opened FITS file
 * @param update - if set, then an existing table is updated, a new one is appended otheerwise
 *
 */


/**
    Funtion to display the content of an ap_pixel structure

    @param output a pointer to a stream
    @param ap an ap_pixel

*/


/**
   Function to display the content of an ap_pixel list

   @param output a pointer to a stream
   @param ap a pointer to a list of ap_pixels

*/


/**
 *  The function evaluates the a polynomial given in the input
 *  at a specific point, which also is given in the input.
 *  The polynomial follows the description of 2D vatriable
 *  quantities as given in the aXe manual.
 *
 *  @param coeffs - the coefficients of the polynomial
 *  @param p      - the point to evaluate the polynomial
 *  @param beamID - beamID of the beam of interest (A=0, B=1, etc...)
 *
 *  @return res   - of the polynomial at point p
 *
 */


/**
 *Displays the content of a tracestruct structure to *FILE
 */


/**
 * Function: make_nicmos_back
 * The subroutine computes and stores the background image for a specific
 * NICMOS grism image. The non-masked pixels in the grism image are
 * correlated with their corresponding values in the master background image.
 * A linear relation is fitted to the value pairs. Deviating points are
 * excluded using kappa-sigma clipping.
 * Using the slope of the final fit, the background image is computed
 * and stored as a fits image.
 *
 * Parameters:
 * @param obs         - the observation for the grism image
 * @param msk_name    - the full name of the mask file
 * @param master_bck  - the full name of the master sky background
 * @param bck_name    - the full name of the background image
 *
 * Returns:
 * @return -
 */


/**
 * Function: compute_nicmos_back
 * The subroutine applies a scaling factor to a master background
 * in order to get the background image for a specific grism image.
 *
 * Parameters:
 * @param mbck_img - the master background pixel
 * @param factor   - the scaling factor
 *
 * Returns:
 * @return grism_bck - the background image as gsl-matrix
 */


/**
 * Function: compute_nicmos_back
 * The subroutine iteratively fits a linear relation to the pairs of
 * grism image - master background pixel values. After each fit,
 * pairs with large deviations are determined and excluded.
 * The result of the final fit is returned.
 *
 * Parameters:
 * @param fbck_data - the data used for the fits
 *
 * Returns:
 * @return lfit - the results of the final fit
 */


/**
 * Function: clipp_fbck_data
 * The subroutine applies kappa-sigma clipping to a set of data points.
 * The difference between the measured values and the expected values
 * according to linear regression are determined.
 * Data which is outside of the accepted interval is excluded by
 * setting the weight to '0.0'. If at least one value was clipped,
 * '1' is returned, otherwise '0' (if all values are within the
 * accepted interval.
 *
 * Parameters:
 * @param fbck_data - the data used for the fits
 * @param lfit      - the result of the fit
 * @param kappa     - the kappa value
 *
 * Returns:
 * @return clipped - boolean to indicate clipped values
 */


/**
 * Function: comp_stdev_from_array
 * The subroutine computes the standard deviation
 * of a data vector, using the known mean value.
 *
 * Parameters:
 * @param data  - the data vector
 * @param ndata - number of data points to use
 * @param mean  - mean value of the data points
 *
 * Returns:
 * @return clipped - boolean to indicate clipped values
 */


/**
 * Function: make_nicmos_back
 * The subroutine creates and fills a structure with pairs of correpsonding
 * from a grism image and a master sky background. Dq-masked pixels values
 * and pixels which are part of an object beam are used, but marked with
 * a zero weight.
 *
 * Parameters:
 * @param obs       - the observation for the grism image
 * @param msk_image - the maks image values
 * @param mbck_img  - the master background values
 * @param fbck_data    - structure with the data pairs
 *
 * Returns:
 * @return -
 */


/*
 * Function: free_fitbck_data
 * The function releases the memory allocated in
 * a fit-data structure
 *
 * Parameters:
 * @param fbck_data - the allocated structure
 *
 * Returns:
 * @return -
 */


/**
  computes the value of the section function.

  @param x abscissa at which to evaluate (should be relative to the beam's
  refpoint).
  @param data a sectionfun struct (declared void to please gsl).
  @return the value of the section function.
*/


/**
  finds the section point between a line of given slope through a given
  point and a not too unreasonable function.

  @param sf the section function descriptor, created by fill_in_sectionfun.
  @param x abscissa of the given point.
  @param x ordinate of the given point.
  @param res abscissa of section point.
  @returns 0 if section point could be found, -1 if not.
*/


/**
  prepares a sectionfun structure

  @param sf a pointer to the structure to fill
  @param inclination the slope of the line (orientation of the object)
  @param b the current beam
  @return 0 if successful, -1 otherwise
*/


/**
  releases the memory allocated in the fields of a sectionfun structure
  (but not the structure itself)

  @param sf the struct the children of which should be freed
*/


/**
 * Function: load_CCD_layer
 * The function creates and returns a structure for an optical
 * CCD layer. The input parameters are interpreted, and
 * the data which defines the CCD layer is loaded.
 *
 * Parameters:
 * @param refr_table - the name of the refractive index table
 * @param thickness  - the value for the thicknes keyword
                       (number or image name)
 *
 * Returns:
 * @return opt_layer  - the optical layer created
 */


/**
 * Function: free_CCD_layer
 * The function releases all the memory allocated
 * in a structure for a CCD layer.
 *
 * Parameters:
 * @param opt_layer - structure for CCD layer
 *
 * Returns:
 * @return -
 */


/**
 * Function: load_CCD_layers
 * The function extracts from a fringe configuration file
 * all information on individual CCD layers. It creates
 * the appropriate structure for every CCD layer,
 * and creates and returns a structure which completely
 * describes all layers in a CCD.
 *
 * Parameters:
 * @param fring_conf_path - the name of a fringe configuration file
 *
 * Returns:
 * @return opt_layers - the structure for the optical layers created
 */


/**
 * Function: free_CCD_layers
 * The function releases all memory allocated in a
 * CCD layers structure.
 *
 * Parameters:
 * @param opt_layers - the CCD layers structure
 *
 * Returns:
 * @return -
 */


/**
 * Function: load_fringe_conf
 * The function loads the fringe configuration file given as parameter.
 * All relevant data marked with keywords is extracted. A fringe
 * configuration structure is built up and returned from the
 * data given in the keyvalues.
 *
 * Parameters:
 * @param fring_conf_path - the complete path-name to a fringe configuration file
 *
 * Returns:
 * @return fconf - the fringe configuration structure created
 */


/**
 * Function: check_fringe_conf
 *
 * Parameters:
 * @param fconf  - the fringe configuration structure
 *
 * Returns:
 * @return
 */


/**
 * Function: free_fringe_conf
 * The function deallocates all memory in a
 * fringe configuration structure.
 *
 * Parameters:
 * @param fconf  - the fringe configuration structure
 *
 * Returns:
 * @return -
 */


/**
 * Function: create_interp_ftable
 * This function cretaes an interpolator from data values stored
 * in a fits table. An interpolator is a structure to hold all
 * data to compute the interpolated data values for different
 * interpolation methods. Core of this structure is the interpolator
 * types offered in the gsl-library.
 * This function is a tool to extract the relevant data points from
 * a fits table and to set up and return the interpolator.
 *
 *
 * Parameters:
 * @param table_name  - the name of the fits table
 * @param hdunum      - the extension number with the data
 * @param xcol        - the column name with the indepenent values
 * @param ycol        - the column name with the dependent values
 * @param interp_type - the interpolation type
 *
 * Returns:
 * @return interp - the interpolation structure created
 */


/**
 * Function: create_interp
 * The function creates, and intializes and returns an interpolator
 * from the basic input, which is the data, the number of data
 * items and the interpolator type requested.
 *
 * Parameters:
 * @param nvals       - the number of data values in the arrays
 * @param interp_type - the interpolation type
 * @param xvals       - the array with the independent data values
 * @param yvals       - the array with the dependent data values
 *
 * Returns:
 * @return interp - the interpolation structure created
 */


/**
 * Function: print_interp
 *
 * Parameters:
 * @param interp - the interpolator structure
 *
 * Returns:
 * @return -
 */


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


/**
 * Function: free_interp
 * the function frees all memory allocated in
 * an interpolator structure.
 *
 * Parameters:
 * @param interp - the interpolator structure
 *
 * Returns:
 * @return -
 */


/**
 * Function: create_linint_ftable
 * This function creates a linear interpolator from data values stored
 * in a fits table. An linear interpolator is a structure to hold all
 * data to compute the linear interpolated data values at any
 * point bracketed by the data.
 * This function is a tool to extract the relevant data points from
 * a fits table and to set up and return the linear interpolator.
 *
 * Parameters:
 * @param table_name  - the name of the fits table
 * @param hdunum      - the extension number with the data
 * @param xcol        - the column name with the indepenent values
 * @param ycol        - the column name with the dependent values
 * @param interp_type - the interpolation type
 *
 * Returns:
 * @return lin_int - the linear interplator structure created
 */


/**
 * Function: free_linint
 * The function frees all memory allocated
 * in a linear interpolator structure.
 *
 * Parameters:
 * @param lin_int - the linear inteprolator
 *
 * Returns:
 * @return -
 */


/**
 * The function creates and loads a new flux_cube structure
 * The data is taken from the file specified in the input.
 *
 * @param  fcube_file - the file name of the fluxcube
 *
 * @return ret        - the new flux_cube structure
 */


/**
 * The function allocates space for a new
 * fluxcube structure.
 *
 * @param  nflux - the number of fluximages
 *
 * @return ret   - the fluxcube structure
 */


/**
 * The function fills the keywords XOFFS and YOFFS
 * from the primary header of the fitscube file
 * into the according items of the fitscube structure.
 * In case that those keywords are not present,
 * they are set to 0.
 *
 * @param  fcube_file - the file name of the fluxcube
 * @param  fcube      - the fluxcube structure
 *
 * @return 1          - always true
 */


/**
 * The function creates and loads the segmentation image
 * of a flux_cube file into a gsl_matrix_int structure.
 *
 * @param  fcube_file - the file name of the fluxcube
 *
 * @return ret        - pointer to the gsl_matrix_int structure
 */


/**
 * The function creates and loads a fluximage structure
 * from an extention of a fluxcube file.
 *
 * @param  fcube_file - the file name of the fluxcube
 * @param  hdunum     - the extension number to load in a fluximage
 *
 * @return fimage     - pointer to the fluximage structure loaded
 */


/**
 * The function analyzes the fluximages in a
 * fluxcube structure and sorts their indices in
 * ascending wavelength. The vector with the
 * ordered indices is given back.
 *
 * @param  fcube - the pointer to the fluxcube structure
 *
 */


/**
 * The function releases the space allocated
 * for a fluxcube structure.
 *
 * @param  fcube - the pointer to the fluxcube structure
 *
 */


/**
 * The function releases the space allocated
 * for a fluximage structure.
 *
 * @param  fimage - the pointer to the fluximage structure
 *
 */


/**
 * The function transforms a pixel coordinate point in a
 * flt image into an pixel coordinate point in the associated
 * fluxcube image
 *
 * @param  fcube       - the fluxcube structure
 * @param  flt_point   - pixel coordinate point in the flt-image
 *
 * @return fcube_point - the pixel coordinate in the fluxcube
 */


/**
 * The function transforms an image coordinate point in a
 * fluxcube into an image coo point in the associated
 * flt image
 *
 * @param  fcube       - the fluxcube structure
 * @param  fcube_point - image-coo in the fcube
 *
 * @return flt_point   - the image coo in the flt
 */


/**
 * The function creates a a dirobject on the basis
 * of an object and the pixel coos of a point
 * which is part of that object.
 *
 * @param  flt_point - the fluxcube structure
 * @param  actobject - the object list
 *
 * @return dirobject - the dirobject created
 */


/**
 * The function updates a dirobject with a point
 * belonging to the same object. The new point
 * may extend the object size.
 *
 * @param actdir    - the direct object
 * @param flt_point - the new coordinate point
 *
 */


/**
 * The function computes and stores at the according position
 * the xy offsets of a direct image. This is only important
 * in the fluxcube emission model, since the image coordinates
 * in fluxcubes are 'filter' coordinates and do not take into
 * account the offsets introduce by the grism.
 * For each object and beam those offsets are evaluated
 * and stored in the direct object structure.
 *
 * @param dirlist   - the direct object
 * @param CONF_file - the new coordinate point
 *
 */


/**
 * The function fills the flux information from a point in
 * a fluxcube structure into the flux part of a direct object.
 *
 * @param fcube  - the fluxcube structure
 * @param point  - the position to take the flux from
 * @param actdir - the direct object to update
 *
 */


/**
 * The function prints the main properties of a
 * fluxcube structure onto the screen.
 * This is mostly for debuggin/development
 * purposes, and not for production
 *
 * @param fcube      - the fluxcube structure
 *
 */


/**
Calculate the area common to input clockwise polygon x(n), y(n) with
square (is, js) to (is+1, js+1).
This version is for a quadrilateral.
W.B. Sparks STScI 2-June-1990.
Phil Hodge        20-Nov-1990  Change calling sequence; single precision.
Richard Hook ECF  24-Apr-1996  Change coordinate origin
                               so that centre of pixel has integer position
                  03-Jan-2001  Removed accuracy check
Nor Pirzkal       27-Jan-2003  C version
**/


/**
 * Free the memory allocated to a dispstruct structure
 *
 * @param p  pointer to a dispstruct structure
 */


/**
 * The program checks if the dispersion relation of a certain beam
 * is given in "grism" form (polynomial) or in "prism" form
 * (inverse polynomial)
 *
 * @param  filename filename of the configuration file
 * @param  beamID   beamID of the beam of interest (A=0, B=1, etc...)
 *
 * @return c        integer to declare grism (=1) or prism (=0)
 */


/**
 * The program checks an order of a dispersion solution for the
 * "suspicion" to be either grismatic or prismatic.
 *
 * @param  filename  filename of the configuration file
 * @param  for_grism the suspicion (=1 for grism, =0 for prism)
 * @param  beamID    beamID of the beam of interest (A=0, B=1, etc...)
 * @param  order     the order of the dispersion solution to be invetigated
 *
 * @return found     integer to confirm (=0) or falsily (=1) the suspicion
 */


/**
    Utility function to parse a filename and populate a CfgStrings structure

    @param Filename a pointer to a string containing the name of a configuration file
    @param CfgInfo a pointer to an existing CfgStrings structure
    @return

    @see CfgStrings

*/


/**
    Utility function to parse a NULL terminated array of strings and populate a CfgStrings structure

    @param Filename a pointer to a string containing the name of a confiuration file
    @param CfgInfo a pointer to an existing CfgStrings structure
    @return

    @see CfgStrings

*/


/**
 * The function performs a wavelength calibration on an allready
 * existing ap_pixel table. It fills in the lambda and dlambda fields.
 *
 * @param ap_p  - the ap_pixel table to work on, with the pathlength field
 *                filled out
 * @param calib - the calibration function
 */


/*
 * Function: pwise_wl_calib
 * Make for every PET pixel an individual wavelength
 * calibration. The function was developed for FORS2 MXU spectra
 * and makes especially sense for long spectra and/or fast
 * variations of the 2D calibration solution.
 */


/**
 *  The function trims down an ap_pixel table to only allowed values
 *  for the trace path length or trace distance. The input ap_pixel
 *  is only changed. Valid entries are moved to the front side,
 *  and a new endmark is set after all valid entries
 *
 *  @param  ap_pixel       the input ap_pixel table
 *  @param  prange         the valid trace range
 *  @param  wl_calibration the calibration structure, needed to get the
 *                         first dispersion coefficient
 *
 *  @return ret            ap_pixel table output
 */


/**
 *  Calibration function for the grism: simple polynomial
 *
 * @param xi     the path length of the sample point
 * @param order  the order of the polynomial, i.e. the number of coefficients
 *               minus one
 * @param coeffs a pointer to order+1 doubles, starting with the zeroth
 *               coefficent
 *
 * @return res   wavelength at xi
 */


/**
 * Calibration function for the prism: reciprocal polynomial in the
 * form: lambda = a1 + a2/(xi-a0) + a3/(xi-a0)**2 + a4/(xi-a0)**3
 *
 * @param  xi     the path length of the sample point
 * @param  order  the order of the polynomial, i.e. the number of coefficients
 *                minus one
 * @param  coeffs a pointer to order+1 doubles, starting with the zeroth
 *                coefficent
 * @return res    wavelength at xi
 */


/**
 * Create a prism or grism calibration function, i.e. a function of one of
 * the forms "sum(a_i 1/x^i, i=0..order)" or "sum(a_i x^i, i=0..order)"
 * for transforming pathlength along the trace to lambda.
 *
 *@param for_grism if true, a the second form of the calibration function
 *                 is used (normal polynom), otherwise the first one.
 *@param order     order of the polynom
 *@param a         a GSL vector of length n containing the n coefficients
 *                 describing the wavelength calibration polynomial.
 *@return calib    an allocated structure containing an allocated array
 *                 for the coefficients.  Free using calib_free.
 */


/**
 * Function: free_calib
 * Free a calibration function and its assoicated data.
 *
 * @param  calib the calibration structure to be freed
 *
 */


/**
 * Function: fit_beamtrace
 * The function determines a new trace solution for a given beam. A gaussian
 * is fitted to the pixel values around the nominal trace position.
 * A kappa-sigma-klipping algorithm eliminates fitted trace centers
 * which are off due to cosmics or similar.
 * Finally the a new trace solution is fitted to the set of trace centers
 * The new slope is directly written to the beam structure, the
 * new y-value of the reference point is returned.
 *
 * Parameters:
 * @param conf     - the aXe configuration structure
 * @param obs      - the current observation
 * @param beamID   - the ID of the current beam
 * @param act_beam - the beam to fit
 *
 * Returns:
 * @return yf - the y-value of the reference point for the fitted trace
 */


/**
 * Function: gagauss
 * The function computes and returns the value
 * of a gauss function y = a * exp(-b*(x-c)^2) - d
 * at a position x.
 *
 * Parameters:
 * @param x      - the x-poition to evaluate the function
 * @param params - the function parameters
 *
 * Returns:
 * @return - the function value
 */


/**
 * Function: comp_shift
 *
 * Returns:
 * @return - the function value
 */


/**
 * Function: fit_wuttke
 * Fits a gaussian to the data given in the input structure.
 * Uses a library for nn-linear fits (made by Wuttke)
 *
 * Parameters:
 * @param f_data - the fit data
 *
 * Returns:
 * @return params - the fit results
 */


/*
 * Function: alloc_fit_data
 * The function allocates memory for a fit-data structure
 *
 * Parameters:
 * @param n_data - the number of points to allocate
 *
 * Returns:
 * @return f_data - the allocated structure
 */


/*
 * Function: print_fit_data
 * The function prints the content of a fit-data structure
 * onto the screen (error-out).
 *
 * Parameters:
 * @param f_data - the allocated structure
 *
 * Returns:
 * @return -
 */


/*
 * Function: print_fit_data
 * The function releases the memory allocated in
 * a fit-data structure
 *
 * Parameters:
 * @param f_data - the allocated structure
 *
 * Returns:
 * @return -
 */


/**
 * Function: comp_intrel_max
 *
 * Parameters:
 * @param f_data  - the input data
 *
 * Returns:
 * @return rel12 - "second brightes row pixel divided by brighest row pixel"
 */


/**
 * Function: bcksub_observation
 *
 * Parameters:
 * @param obs           - the grism image
 * @param bck           - the background image
 *
 * Returns:
 * @return ret - background subtracted data
 */


/**
 * Function: evaluate_ipc_fit
 *
 * Parameters:
 * @param f_data  - the input for the independent values
 * @param gpars   - the fited parameters
 * @param fpars   - the fixed parameters
 *
 * Returns:
 * @return y_values - the function values
 */


/**
 * Function: write_ipc_fit
 *
 * Parameters:
 * @param f_data   - the input data
 * @param y_values - the model values
 * @param ipc_file - name of the file to write to
 *
 * Returns:
 * @return -
 */


/**
 * Function: fit_ipc_data
 *
 * Parameters:
 * @param f_data  - the input data
 * @param gpars   - the guess or fit parameters
 * @param n_gpars - number of guess or fit parameters
 * @param fpars   - the fixed parameters
 * @param n_fpars - number of fixed parameters
 *
 * Returns:
 * @return control.fnorm - goodness of the fit value
 */


/**
 * Function: strip_wf_special
 *
 * Parameters:
 * @param old_fdata - the experimental data
 * @param i_max     - the maximum index to check for valid data
 *
 * Returns:
 * @return fdata - the new, completely filled data structure
 */


/**
 * Function: strip_fitdata
 *
 * Parameters:
 * @param old_fdata - the experimental data
 * @param i_max     - the maximum index to check for valid data
 *
 * Returns:
 * @return fdata - the new, completely filled data structure
 */


/**
 * Function: kappa_sigma_klipp_ipc
 *
 * Parameters:
 * @param conf          - the aXe configuratuion structure
 * @param obs           - the grism image
 * @param data_matrix   - background subtracted grism image
 * @param actbeam       - the beam to examine
 * @param ipc_file_path - file name for the phase data
 *
 * Returns:
 * @return ret - the change in y-shift and the goodness of the fit
 */


/**
 * Function: reject_kappasigma
 *
 * Parameters:
 * @param f_data   - the experimental data
 * @param y_values - the model data
 * @param max_diff - the maximum allowed difference
 *                   between data and model
 *
 * Returns:
 * @return -
 */


/**
 * Function: calculate_sigma
 *
 * Parameters:
 * @param f_data   - the experimental data
 * @param y_values - the model data
 *
 * Returns:
 * @return sigma - the standard deviation
 */


/**
 * Function: make_spc_drztable
 * The function generates and fills an ap_pixel vector for one
 * drizzled 2D grism image.
 *
 * Parameters:
 * @param  obs     - pointer to observation structure with image values
 * @param  obs     - pointer to observation structure with image values
 * @param  ob      - pointer to the description of the current beam
 * @param  lambda0 - the starting wavelength in this drizzled image
 * @param  dlambda - the dispersion in this drizzled image
 *
 * Returns:
 * @return table   - pointer to an ap_pixel vector
 */


/**
 * Function: normalize_weight
 * The function computes the weights used in the extraction
 * from the exposure times given for each pixel in a column.
 *
 * Parameters:
 * @param  wobs - pointer to the structure which carries the pixel data
 * @param  ob   - pointer to the beam description
 */


/*
 * Function: comp_equ_weight
 * The function creates and fills a weight map with flat entries.
 * Pixels with non-zero exposure time which which contribute to the
 * extracted spectrum all receive the weight 1.0, all other
 * get the weight 0.0.
 *
 * Parameters:
 * @param exp_map - the matrix with the exposure times
 * @param ob      - the object structure
 *
 * Returns:
 * @return weight - the matrix with the exposure time weights
 */


/*
 * Function: comp_exp_weight
 * The function uses the exposure time map and computes
 * the weights which are proportional to the relative
 * exposure time of the pixel. Pixels outside of the extraction
 * area are set to 1000.0 Inside the default is 1.0 in unexposed
 * columns and 0.0 within exposed columns.
 *
 * Parameters:
 * @param exp_map - the matrix with the exposure times
 * @param ob      - the object structure
 *
 * Returns:
 * @return weight - the matrix with the exposure time weights
 */


// refactored/taken from acromag drvr235.c, L251-262


/*
    MODULES FUNCTIONAL DETAILS:

    This module is used to correct the input data for the board.
    A pointer to the Configuration Block will be passed to
    this routine.  The routine will use a pointer within the Configuration
    Block to reference the registers on the Board.
*/


/*
 Blocking options

 parameter =  0 = byte write & block
 parameter =  1 = word write & block
 parameter =  2 = 32 bit write & block
 parameter = 10 = no write, just block & wait for an input event to wake up

 Returns the interrupt pending status value.
*/


/*
    MODULES FUNCTIONAL DETAILS:
*/


/*
    MODULES FUNCTIONAL DETAILS:

    This module will issue a command to erase a sector of the M25P10 device.
    Requires a valid Sector address for the Sector Erase (SE) instruction
*/


/*
        MODULES FUNCTIONAL DETAILS:
*/


/*
    MODULES FUNCTIONAL DETAILS:

	This module will write a command and operand bytes using 8 bit data transfers.
	Will also receive response bytes.
*/


/*
    MODULES FUNCTIONAL DETAILS:

	This module will do I/O with the M25P10 device.
*/


/*
    MODULES FUNCTIONAL DETAILS:

    This module will issue a command to read the M25P10 device.
*/


/*    MODULES FUNCTIONAL DETAILS:
*/


/*
    MODULES FUNCTIONAL DETAILS:

*/


/*
    MODULES FUNCTIONAL DETAILS:

    This module is used to perform the read the calibration
    coefficients for the board.  A pointer to the Configuration
    Block will be passed to this routine.  The routine will use a pointer
    within the Configuration Block together with offsets to reference the
    registers on the Board and will transfer information from the
    Board to the Configuration Block.
*/


/*
    MODULES FUNCTIONAL DETAILS:

    This module is used to write the flash I.D. and calibration
    coefficients for the AP236 board.  A pointer to the Configuration
    Block will be passed to this routine.  The routine will use a pointer
    within the Configuration Block together with offsets to reference the
    registers on the Board.
*/


/*
    MODULES FUNCTIONAL DETAILS:

    This module is used to perform the write output function
    for the board.  A structure pointer to the board memory map,
    the analog output channel number value, and the analog output
    data value will be passed to this routine.  The routine writes
    the output data to the analog output channel register on the board.
*/


/*
    MODULES FUNCTIONAL DETAILS:

    This module is used to start conversions on the board.
*/


/*
    MODULES FUNCTIONAL DETAILS:

    This module is used to perform the read status function
    for the AP235 board.  A pointer to the Configuration Block will
    be passed to this routine.  The routine will use a pointer
    within the Configuration Block together with offsets
    to reference the registers on the Board and will transfer the
    status information from the Board to the Configuration Block.
*/


/*
    MODULES FUNCTIONAL DETAILS:

    This module is used to perform the "configure board" function
    for the AP236 board.  A pointer to the Configuration Block will
    be passed to this routine.  The routine will use a pointer
    within the Configuration Block to reference the registers
    on the Board.  Based on flag bits in the Attribute and
    Parameter Flag words in the Configuration Block, the board
    will be configured and various registers will be updated with
    new information which will be transfered from the Configuration
    Block to registers on the Board.
*/


/*
    MODULES FUNCTIONAL DETAILS:

    This module is used to write the flash I.D. and calibration
    coefficients for the AP235 board.  A pointer to the Configuration
    Block will be passed to this routine.  The routine will use a pointer
    within the Configuration Block together with offsets to reference the
    registers on the Board.
*/


/*
    MODULES FUNCTIONAL DETAILS:

    This module is used to perform a FIFO write output function for the
    selected channel.  A structure pointer to the board memory map, the analog
    output channel number value will be passed to this routine.  The routine
    writes the output data to the FIFO on the board.
*/


/*
    MODULES FUNCTIONAL DETAILS:

    This module is used to perform a DMA FIFO write output function for the
    selected channel.  A structure pointer to the board memory map, the analog
    output channel number value will be passed to this routine.  The routine
    writes the output data to the FIFO on the board.
*/


/*
    MODULES FUNCTIONAL DETAILS:

    This module is used to perform the read status function for the
    board.  A pointer to the Status Block will be passed to this routine.
    The routine will use a pointer within the Status Block together with
    offsets to reference the registers on the Board and will transfer the
    status information from the Board to the Status Block.
*/


/*
    MODULES FUNCTIONAL DETAILS:

    This module is used to perform the "configure board" function
    for the AP235 board.  A pointer to the Configuration Block will
    be passed to this routine.  The routine will use a pointer
    within the Configuration Block to reference the registers
    on the Board.  Based on flag bits in the Attribute and
    Parameter Flag words in the Configuration Block, the board
    will be configured and various registers will be updated with
    new information which will be transfered from the Configuration
    Block to registers on the Board.
*/


// suffix 2 is to avoid clash with aligned_malloc from ap235.go, which likely
// will be built into the same binary.  This is copy pasted from there.


/* Author: Mathias Zechmeister
 * Date: 2018-10-01
 *
 *  gcc -c  -Wall -O2 -ansi -pedantic -fPIC gls.c -o gls_c.o; gcc -o gls_c.so -shared gls_c.o
*/


/* "View.MemoryView":1209
 *
 * @cname('__pyx_memoryview_copy_data_to_temp')
 * cdef void *copy_data_to_temp(__Pyx_memviewslice *src,             # <<<<<<<<<<<<<<
 *                              __Pyx_memviewslice *tmpslice,
 *                              char order,
 */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/*  Process ATS file                                               */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/*  Get next command from ATS file                                 */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/*  Process all command parameters and copy to the CCSDS packet    */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/*  Process a command parameter and copy it to the CCSDS packet    */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/*  Send a command in a CCSDS packet                               */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/*  Attempt to put the child to sleep until the command time       */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/*  Top-level function for running an ATS in a child process       */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/*  Find the lowest-indexed unused ATS child process               */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/*  Clear info for specified ATS child process                     */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                   */
/*  Copy info of specified ATS child process into output structure   */
/*                                                                   */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/*  Sends Housekeeping Data                                        */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/* Reset Counters Command                                          */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/* No Op Command                                                   */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/*  Process a command                                              */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/* SCA Verify the length of the command                            */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/*  SCA main process loop (task entry point)                       */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/* Application startup initialization                              */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/* Create SCA child data mutexes                                   */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/* Create and take SCA child semaphores used to create             */
/* delays when waiting for the right time to send a command        */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/* Get the Current time from CFE TIME, ignoring subseconds         */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/* Get the Current time from CFE TIME, including subseconds        */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/* Start an ATS                                                    */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/*   Stop the currently executing ATS                              */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/* Get ATS Info                                                    */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                 */
/* Create child process for an ATS                                 */
/*                                                                 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* -------------------------------------------------------------
   channel_grid_cell_length
   returns the total length of channel(s) in the cell.
   ------------------------------------------------------------- */


/* -------------------------------------------------------------
   channel_grid_cell_width
   returns a length-weighted average of the channel widths in the cell
   ------------------------------------------------------------- */


/* -------------------------------------------------------------
   channel_grid_inc_inflow
   Given a flow (or actually mass), this function increases the inflow
   any channel(s) in the cell in proportion to their length within the
   cell.
   ------------------------------------------------------------- */


/* -------------------------------------------------------------
   channel_grid_outflow
   If the channel(s) within the cell are marked as ``sinks'', this
   function totals the mass from the channels(s) and returns the total
   mass.
   ------------------------------------------------------------- */


/* -------------------------------------------------------------
   channel_grid_sed_outflow
   If the channel(s) within the cell are marked as ``sinks'', this
   function totals the mass from the channels(s) and returns the total
   mass.
   ------------------------------------------------------------- */