/*
 * This file is part of the ESO UVES Pipeline
 * Copyright (C) 2004,2005 European Southern Observatory
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
 */

/*
 * $Author: jtaylor $
 * $Date: 2012-11-19 09:16:16 $
 * $Revision: 1.37 $
 * $Name: not supported by cvs2svn $
 * $Log: not supported by cvs2svn $
 * Revision 1.36  2010/09/24 09:31:30  amodigli
 * put back QFITS dependency to fix problem spot by NRI on FIBER mode (with MIDAS calibs) data
 *
 * Revision 1.34  2009/04/14 07:12:12  amodigli
 * moved MAREMMA definition to flames_midas_def.h
 *
 * Revision 1.33  2007/07/30 09:05:11  amodigli
 * defined several new h files (removed from flames_uves.h)
 *
 * Revision 1.32  2007/07/30 06:50:54  amodigli
 * defined several new h files (removed from flames_uves.h)
 *
 * Revision 1.31  2007/07/28 13:27:46  amodigli
 * Moved several function declarations from flames_uves.h to other new .h files
 *
 * Revision 1.30  2007/07/27 08:28:30  amodigli
 * Moved several function declarations from flames_uves.h to other new .h files
 *
 * Revision 1.28  2007/07/03 08:44:15  jmlarsen
 * Moved definition of FLAMES_DEBUG
 *
 * Revision 1.27  2007/06/22 11:47:18  jmlarsen
 * Renamed DEBUG -> FLAMES_DEBUG
 *
 * Revision 1.26  2007/06/20 08:40:49  amodigli
 * added definition of FLAMESBOUNDTYPE
 *
 * Revision 1.25  2007/06/06 08:17:33  amodigli
 * replace tab with 4 spaces
 *
 * Revision 1.24  2007/06/04 16:54:44  amodigli
 * removed compilation warnings
 *
 * Revision 1.23  2007/06/04 14:09:12  jmlarsen
 * Back to earlier version
 *
 * Revision 1.21  2007/06/04 11:25:27  jmlarsen
 * Removed out of place function declarations
 *
 * Revision 1.20  2007/06/04 06:47:14  amodigli
 * moved function declaration to flames_uves.h
 *
 * Revision 1.19  2007/06/04 06:26:49  amodigli
 * added flames_mainopt
 *
 * Revision 1.18  2007/05/31 11:26:14  amodigli
 * removed flames_corvel declaration
 *
 * Revision 1.17  2007/05/30 06:30:19  amodigli
 * fixed compilation warnings
 *
 * Revision 1.16  2007/05/29 15:36:05  amodigli
 * fixed compilation warnings (cpl_frameset*) in place of (const char*)
 *
 * Revision 1.15  2007/05/29 15:26:37  amodigli
 * fixed compilation warnings (cpl_frameset*) in place of (const char*)
 *
 * Revision 1.13  2007/05/29 11:11:26  amodigli
 * fixed a few compilation warnings (const char*)
 *
 * Revision 1.12  2007/05/16 14:31:08  amodigli
 * fixed some warnings (added const to char*)
 *
 * Revision 1.11  2007/05/09 05:17:42  amodigli
 * only ANSI C interface
 *
 * Revision 1.10  2007/05/07 06:54:05  amodigli
 * added writeslitff  flames_corvel lfit
 *
 * Revision 1.9  2007/05/04 12:20:51  amodigli
 * added const qualifier on char* where appropriate
 *
 * Revision 1.8  2007/04/24 12:49:34  jmlarsen
 * Replaced cpl_propertylist -> uves_propertylist which is much faster
 *
 * Revision 1.7  2007/03/23 13:44:37  jmlarsen
 * Implemented SCKWR- functions
 *
 * Revision 1.6  2007/03/23 10:41:02  jmlarsen
 * Added workaround for CPL bug
 *
 * Revision 1.5  2007/03/23 08:04:55  jmlarsen
 * Work on conversion
 *
 * Revision 1.4  2007/03/15 15:40:43  jmlarsen
 * Changed filename extension bdf -> fits
 *
 * Revision 1.3  2007/01/29 13:09:57  jmlarsen
 * Work on conversion to CPL
 *
 * Revision 1.2  2007/01/15 14:00:23  jmlarsen
 * Imported FLAMES sources from MIDAS pipeline
 *
 * Revision 1.1  2007/01/10 08:06:10  jmlarsen
 * Added source files
 *
 * Revision 1.10  2006/11/13 12:24:22  jmlarsen
 * Fixed WAVECAL_DOM
 *
 * Revision 1.9  2006/10/24 14:43:31  jmlarsen
 * Removed flames_cal_mkmaster recipe
 *
 * Revision 1.8  2006/10/24 14:23:18  jmlarsen
 * Fixed wavecal, predict recipe names
 *
 * Revision 1.7  2006/10/19 08:24:02  jmlarsen
 * Added recipe id, msg domains
 *
 * Revision 1.6  2006/10/17 12:43:05  jmlarsen
 * Include uves_recipe
 *
 * Revision 1.5  2006/10/17 12:39:05  jmlarsen
 * Added flames_orderpos definitions
 *
 * Revision 1.4  2006/10/17 12:33:42  jmlarsen
 * Moved FLAMES source to flames directory
 *
 * Revision 1.8  2006/08/24 07:18:12  amodigli
 * fixed doxygen warnings
 *
 * Revision 1.7  2006/07/31 06:28:11  amodigli
 * porting to CPL
 *
 * Revision 1.6  2006/07/06 06:53:12  jmlarsen
 * Excluded some typedefs from doxygen doc.
 *
 * Revision 1.5  2006/06/26 08:16:40  amodigli
 * added get_info stuff
 *
 * Revision 1.4  2006/06/26 07:52:49  amodigli
 * added defines for new recipes
 *
 * Revision 1.3  2006/06/22 15:25:35  amodigli
 * changes for flames_cal_prep_sff_ofpos
 *
 * Revision 1.2  2006/06/22 06:42:38  amodigli
 * fixed some compilation warnings
 *
 * Revision 1.1  2006/06/19 06:50:36  amodigli
 * added
 *
 * Revision 1.2  2006/05/15 06:09:10  amodigli
 * fixed compilation warning
 *
 * Revision 1.14  2006/02/03 07:46:30  jmlarsen
 * Moved recipe implementations to ./uves directory
 *
 * Revision 1.3  2005/12/19 16:17:55  jmlarsen
 * Replaced bool -> int
 *
 */

#ifndef FLAMES_UVES_H
#define FLAMES_UVES_H

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

/*-----------------------------------------------------------------------------
                    Includes
 -----------------------------------------------------------------------------*/
#include <cpl.h>
/*-----------------------------------------------------------------------------
                                   Typedefs
 -----------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------
                                   Defines
 ----------------------------------------------------------------------------*/

/* AM: MANCA UNO HEADER */
/* AM: Certi nomi thisisalongname possono essere scritti come 
                  this_is_a_very_long_name
        aiuterebbe la leggibilita'. 
       (se lo cambiamo ha molto bassa priorita' adesso)
*/
/* AM: DI SOLITO si cerca di raggruppare i typedef assieme, i define pure  
   raggruppare anche per contesto */

#define N_FIBRES_MAX 9
/* if you change frame_data you MUST change also FLAMESDATATYPE accordingly, 
and the same holds for frame_mask and FLAMESMASKTYPE */ 
typedef float frame_data; /* the data type for pixels in the frames */
#define FLAMESDATATYPE D_R4_FORMAT
typedef char frame_mask; /* the data type for badpixels mask */
#define FLAMESMASKTYPE D_I1_FORMAT
#define FLAMESBOUNDTYPE D_I4_FORMAT

typedef int flames_err; /* the data type for error codes returned by 
               functions */

/* the largest filename that can be handled in MIDAS catalogs; 
   this must match (or be larger than) the one defined in catext.h */
// in MIDAS this was 160. Add one to take into account file extension
//   .bdf -> .fits
#define CATREC_LEN 161
/* the smallest floating point denominator I can safely handle */
#define FEPSILON 1e-9
/* the smallest double denominator I can safely handle */
#define DEPSILON 1e-15
/* the smallest frame_data denominator I can safely handle */
#define FDEPSILON 1e-9


/* these are the switches to control the behaviour of the background fitting
   code: it may use all pixels in all windows (USEALL), use the median value
   in each window (USEMEDIAN), use the minimum value in each window
   (USEMINIMUM), search the median in each window, sigma clip pixels too
   different from it and then use their weighted average (USEAVERAGE) */
typedef enum {USEALL, USEMEDIAN, USEMINIMUM, USEAVERAGE} scatterswitch;

/* these are the switches to control the behaviour of the background fitting
   code: before the actual fitting, it may check a neighborhood of each
   background fitting window */
typedef enum {NOBADSCAN, FRACBADSCAN, ABSBADSCAN} scatterswitch2;

/* AM: It is not clear the meaning of each code: 0 is serious? What kind of
   errors are indicated by such code number? */
/* Error codes table*/
#define NOERR 0
#define STICAZZI 1


/* Logical variables */
#ifdef TRUE  /* Workaround: first undefine because CPL defines these which it shouldn't */
#undef TRUE
#endif

#ifdef FALSE
#undef FALSE
#endif

#define TRUE 1
#define FALSE 0
typedef enum {ISTRUE, ISFALSE} flag;

/* flag for slice variables for goodfibre */

#define GOODSLICE 1 /* flag for a real good pixel slice */ 
#define BADSLICE 0  /* flag for a real bad pixel slice */
#define DEMISLICE 2 /* flag for a pixel slice good for the correction 
                       but not for the extraction */ 



/* AM: In the following comments it would be nice to try were possible and make
   sense to have them aligned on a left hand side common margin
   Please etween one structure and the following one add some white space
*/

/* the following structure contains the locations in the frame(s) to be used 
   for background fitting */
/* @cond */
typedef struct _flames_back
{
  double *x;  /* central x of the window used for scattered light contribution 
                 sizeof(x) is double*Window_Number */
  double *y;  /* central y of the window used for scattered light contribution
                 sizeof(y) is double*Window_Number */
  double **window; /* Window coordinates used for scattered light contribution 
                      The order for the column is: 
              order xstart xend ystart yend 
              window[list_number][column]
                      sizeof(window) is sizeof(double)*Window_Number*5 */
  int32_t Window_Number; /* Number of the windows used for the 
                      calculation.*/
  double *coeff;  /* coefficients of the fitted polynomial model of the 
             background, arranged in a vector starting from 1 */
  double **expon;  /* exponents of the fitted polynomial model of the 
              background */
  int xdegree; /* maximum degree in x of the fitted 
                polynomial model */
  int ydegree; /* maximum degree in y of the fitted 
                polynomial model */
} flames_background;
/* @endcond */

/* AM chipstep...not commented */

/* the following structure is used to contain a (sub)frame and all
   related data (possibly) necessary to handle it */
/* @cond */
typedef struct _flames_frame
{
  frame_data **frame_array; /* (sub)frame data */
  frame_data **frame_sigma; /* the variance of each pixel */
  frame_mask **badpixel; /* badpixels mask */
  char *framename; /* the string containing the name of the data frame */
  char *sigmaname; /* the string containing the name of the sigma frame */
  char *badname; /* the string containing the name of the badpixel frame */
  int32_t subrows; /* (sub)frame dimensions */
  int32_t subcols;
  int32_t chiprows; /* original frame dimensions */
  int32_t chipcols;
  int32_t subfirstrow; /* first pixel contained */
  int32_t subfirstcol; /* in the present (sub)frame */
  int maxfibres; /* max number of fibres possibly present */
  char *fibremask; /* which fibres are lit in this (sub)frame 
                   TRUE means fibre lit, 
                   FALSE means fibre not lit */
  int min_lit_fibre; /* minimum index amongst the lit fibres */
  int max_lit_fibre; /* maximum index amongst the lit fibres */
  int32_t num_lit_fibres; /* number of lit fibres */
  int32_t *ind_lit_fibres; /* array containing the indexes to the 
                   lit fibres */ 
  double substartx; /* start, step MIDAS style*/
  double substarty; /* of the present (sub)frame */
  double substepx; 
  double substepy;
  double chipstartx; /* start, step MIDAS style*/
  double chipstarty; /* of the original frame */
  double chipstepx; 
  double chipstepy;
  char chipchoice; /* 'u' if this is taken from the upper chip, 
              'l' if this is taken from the lower chip */
  double ron;      /* Read Out Noise contribution to variance */
  double gain;     /* Read Out gain, used to compute variance */
  frame_data ***spectrum;  /* 3D matrix containing the extracted spectra
                  spectrum[column][order][fibre]*/
  frame_data ***specsigma; /* 3D matrix containing the variances of the 
                  extracted spectra
                  specsigma[column][order][fibre]*/
  frame_data ***normspec;  /* 3D matrix containing the normalised extracted 
                  spectra
                  normspec[column][order][fibre]*/
  frame_data ***normsigma; /* 3D matrix containing the variances of the 
                  normalised extracted spectra
                  normsigma[column][order][fibre]*/
  frame_data ***speccovar; /* 3D matrix containing the covariances of the 
                  extracted spectra between adjacent fibres:
                  speccovar[column][order][fibre]
                  contains the covariance between 
                  fibre and fibre+1 */
  frame_mask ***specmask;  /* 3D matrix containing the mask of extracted
                  columns of the spectrum (bad=0 good=1)
                  specmask[column][order][fibre] */
  frame_mask ***normmask;  /* 3D matrix containing the mask of extracted
                  columns of the normalised spectrum (bad=0 good=1)
                  normmask[column][order][fibre] */
    flames_background back;       /* Structure containing all the data of the 
                back.tbl */
  double *yshift; /* shifts in y in this frame, relative to 
             FF in calibrations */
  int32_t nflats; /* the number of fibre FF frames with respect 
                   to which the yshifts in this frame have been 
                   measured */
  float Extract_Window;   /* Window of spectrum extraction (fraction of 
                 full window) */
  float sigma;        /* Maximum value of sigma to be taken into account 
             in the sigma clipping */
  double *Used_Flux;        /* Used flux fraction for each fiber */
  int firstorder; /* first order contained in this frame */
  int lastorder; /* last order contained in this frame */
  int tab_io_oshift; /* the shift between the order table used to build this
            structure and the guess table which was originally 
            used to build the former order table */
} flames_frame;
/* @endcond */

/* The following structure contains all the data associated with a fibre mode
   FF frame. An array of these will go into the allflats structure*/
/* @cond */
typedef struct _singleflat
{
  frame_data **data;           /* odd fibre FF frame data */
  frame_data **sigma;          /* variances of the above frame */
  frame_mask **badpixel;       /* badpixels mask for the above */
  char *framename; /* the string containing the name of the data frame */
  char *sigmaname; /* the string containing the name of the sigma frame */
  char *badname; /* the string containing the name of the badpixel frame */
  int32_t numfibres; /* how many lit fibres in this FF frame */
  int32_t *fibres;   /* the indices of the fibres which are 
                  contained in this FF frame */
  double yshift;           /* shift of this FF frame with respect to all 
                  fibres frame in world coordinates units*/
} singleflat;
/* @endcond */

/* the following structure contains all the necessary data to obtain a 
   (normalized or unnormalized) single fibre flat field frame */
/* @cond */
typedef struct _allflats
{
  singleflat *flatdata; /* an array of singleflat structures, one for each 
               odd/even/other FF frame */
  int32_t nflats; /* how many different FF structures are in the 
                   above vector */
  /* the sizes of the FF frames must be the same, because I will use them to 
     synthesize shifted ones from them, therefore these parameters are in 
     this structure */
  int32_t subrows; /* (sub)frame dimensions */
  int32_t subcols;
  int32_t chiprows; /* original frame dimensions */
  int32_t chipcols;
  int32_t subfirstrow; /* first pixel contained */
  int32_t subfirstcol; /* in the present (sub)frame */
  double substartx; /* start, step MIDAS style*/
  double substarty; /* of the present (sub)frame */
  double substepx; /* I don't see how the steps can possibly be different */
  double substepy; /* from chipstepx and chipstepy, but just in case */
  double chipstartx; /* start, step MIDAS style*/
  double chipstarty; /* of the original frame */
  double chipstepx; 
  double chipstepy;
  char chipchoice; /* 'u' if this is taken from the upper chip, 
              'l' if this is taken from the lower chip */
  double ron; /* Read Out Noise contribution to variance */
  double gain; /* Read Out gain, used to compute variance */
  int maxfibres; /* max number of fibres possibly present */
  double pixmax;         /* max value present in the FFs */ 
  double halfibrewidth; /* halfwidth of a fibre in world coordinates. I 
               suppose this is the same for all orders/fibres, 
               otherwise this will have to become a vector. */ 
  double minfibrefrac; /* fraction of a fibre to be contained within the 
              frames for the DRS to attempt its extraction */
  int firstorder; /* first order contained in the FF frames */
  int lastorder; /* last order contained in the FF frames */
  int tab_io_oshift; /* the shift between the order table used to build this
            structure and the guess table which was originally 
            used to build the former order table */
  int32_t numfibres; /* total number of lit fibres in these frames */
  char shiftable; /* has this order table been divided by the slit flat field,
             enabling y-shifting? */
  char normalised; /* has this fibre FF set been normalised to an all fibres
              FF frame? */
  int *fibremask; /* which fibres are lit in these FF frames */
  int *fibre2frame; /* which FF frame contains each fibre */
  frame_data ***normfactors; /* normalisation factors, this is a 3 dim array 
                whose dimensions are, in 
                this order: order, fibre, and x */
  frame_data ***normsigmas; /* variances of the normalisation factors above, 
                   this is a 3 dim array 
                   whose dimensions are, in 
                   this order: order, fibre, and x */
  frame_mask ***goodfibres; /* this array flags whether a given fibre is good 
                   and is thus to be considered, at a given x and 
                   order; this is a 3 dim array whose dimensions 
                   are, in this order: order, fibre, and x; 
                   GOODSLICE means good, BADSLICE means bad
                   DEMISLICE means good for correlation but bad for
                   spectrum calculation*/
  int32_t ***lowfibrebounds; /* low fibre boundaries (in pixel 
                      space) in the frames, this is a 3 
                      dim array whose dimensions are, in 
                      this order: order, fibre and x 
                      (pixel space) */
  int32_t ***highfibrebounds; /* high fibre boundaries (in pixel 
                       space) in the frames, this is a 3 
                       dim array whose dimensions are, in 
                       this order: order, fibre and x 
                       (pixel space) */
} allflats;
/* @endcond */

/* the following structure contains all data necessary to locate orders, 
   fibres and interorder positions */
/* @cond */
typedef struct _orderpos
{
  double **orderpol; /* coefficients of the order polynomial */
  int xdegree; /* degree of the polynomial in x */
  int mdegree; /* degree of the polynomial in m (orders) */
  double *fibrepos; /* position of each fibre with respect to the 
               centre of the order IN WORLD COORDINATES. */
  int maxfibres; /* max number of fibres possibly present */
  int *fibremask; /* which fibres are lit in these frames */
  double halfibrewidth; /* halfwidth of the fibres in these frames */
  int firstorder; /* the first order we should care about in these frames */
  int lastorder; /* the last order we should care about in these frames */
  int tab_io_oshift; /* the order shift between this order table and the 
            guess table which was originally used to build it */
  double tab_io_yshift; /* the y shift between corresponding orders in this 
            order table and the guess table which was originally 
            used to build it */
  char corrected; /* has this order table been corrected already to reflect
             fibre positions as they are in the all fibres FF frame? */
  double ycorrection; /* the correction which was applied to the zero degree
             term of the polynomial when referring all fibre 
             positions to an all fibres FF frame */
  char chipchoice; /* 'u' if this is taken from the upper chip, 
              'l' if this is taken from the lower chip */
  double pgausssigma;
  double pgausshalfwidth;
  double *gaussselfshift;
  double *start; /* keep START, STEP and NPIX here as well, as an additional 
            check */
  double *step;
  int *npix;
} orderpos;
/* @endcond */

/* AM: data e sigma not commented: may be obvious? */
/* the following structure will contain one slit mode FF frame, for slit 
   flatfielding of all other frames */
/* @cond */
typedef struct _slitFF
{
  frame_data **data;
  frame_data **sigma;
  frame_mask **badpixel; /* ==0 for good pixels */
  char *framename; /* the string containing the name of the data frame */
  char *sigmaname; /* the string containing the name of the sigma frame */
  char *badname; /* the string containing the name of the badpixel frame */
  char *boundname; /* the string containing the name of the boundaries frame */
  int32_t **lowbound; /* low order boundary (in pixel space) in this frame, a 
              vector whose dimensions are, in this order:
              order, x */
  int32_t **highbound; /* high order boundary (in pixel space) in this frame, 
               a vector whose dimensions are, in this order:
               order, x */
  double yshift; /* the shift of the order centre of this frame relative to 
            the reference (in world coordinates) */
  double halfwidth; /* the halfwidth of (the flat part of) the orders in this 
               slit FF (in world coordinates) */
} slitFF;
/* @endcond */

/* AM: some variables are not commented/defined */
/* the following structure will contain the necessary data for slit
   flat-fielding, i.e. a certain number of int32_t slit FF frames with different 
   offsets and their respective variances, all normalised to a common 
   reference (one of them) so that they are coincident within errors where 
   they overlap */
/* @cond */
typedef struct _allslitflats
{
  slitFF *slit;
  int32_t nflats;
  int32_t subrows; /* (sub)frame dimensions */
  int32_t subcols;
  int32_t chiprows; /* original frame dimensions */
  int32_t chipcols;
  int32_t subfirstrow; /* first pixel contained */
  int32_t subfirstcol; /* in the present (sub)frame */
  double substartx; /* start, step MIDAS style*/
  double substarty; /* of the present (sub)frame */
  double substepx; /* I don't see how the steps can possibly be different */
  double substepy; /* from chipstepx and chipstepy, but just in case */
  double chipstartx; /* start, step MIDAS style*/
  double chipstarty; /* of the original frame */
  double chipstepx; 
  double chipstepy;
  char chipchoice; /* 'u' if this is taken from the upper chip, 
              'l' if this is taken from the lower chip */
  double ron; /* Read Out Noise contribution to variance */
  double gain; /* gain factor, used to compute sigma */
  int firstorder; /* first order contained in the FF frames */
  int lastorder; /* last order contained in the FF frames */
  int tab_io_oshift; /* the shift between the order table used to build this
            structure and the guess table which was originally 
            used to build the former order table */
  int32_t **lowbound; /* overall low order boundary (in pixel 
                   space) in all frames, a vector whose 
                   dimensions are, in this order: order, x */
  int32_t **highbound; /* overall high order boundary (in pixel 
                    space) in all frames, a vector whose 
                    dimensions are, in this order: order, x */
  frame_data **normfactor; /* an overall illumination factor at a given order
                  and x (in pixel space), an array whose 
                  dimentions are, in this order:
                  order, x */
  frame_mask **goodx; /* overall good order/x mask, i.e. the ones for which 
             int32_t slit flatfielding is possible */
} allslitflats;
/* @endcond */


/* 
   ------------------------------------------------ 
   
       Prototypes and macros for each function 

   ------------------------------------------------
*/


/*
   ------------------------------------------------
   Here end the prototypes for public C functions from Numerical Recipes
   modified for their use within the MIDAS environment
   ------------------------------------------------
*/

/* Simply function (from the K&R book) to convert number to the equivalent 
   string */

/* void itoa(int , char *); */


//NOT USED
/* the following function calculates the y position of the 
   center of a given fibre "fibre" in a given order "m" at a given "x", 
   and returns it in the double variable to which "y" points. 
   Beware: both "m" and "n" are all double, while "fibre" is integer! */

flames_err 
get_fibrepos(orderpos *ordpos, int32_t fibre,double m, double x, double *y);

/* the following function generates a single fibre flat field frame 
   shifted by "yshift" for fibre "fibre" and creates a frame 
   fully containing only this fibre (the rest of the frame is zeroed), 
   putting the results in a structure of type "frame" whose pointer is 
   "singleFFn" */

flames_err 
get_shifted_FFn(allflats *sflats, 
                orderpos *ordpos,
        int32_t fibre, 
                double yshift, 
            flames_frame *singleFFn);




/* the following functions perform a series of debugging comparisons between
   two allflats structures */
flames_err 
compareff1(orderpos *ordpos, 
           allflats *allflats1, 
       allflats *allflats2);

flames_err 
compareff2(orderpos *ordpos, 
       allflats *allflats1, 
           int32_t iframe1, 
       allflats *allflats2, 
           int32_t iframe2);


/* the following function generates an "all fibres" flat field frame with 
   a subset of fibres lit flagged in the array "litfibres", each of which is 
   multiplied by a suitable spectrum, which is contained in the array to 
   which "spectra" points, all shifted by "yshift", and creates a frame fully 
   containing only these fibres (the rest of the frame is zeroed), putting 
   the results in a structure of type "frame" whose pointer is "synthFFn" */

flames_err 
merge_shifted_FFn (allflats *sflats, 
                   orderpos *ordpos, 
           char litfibres, 
                   double **spectra, 
           double yshift, 
                   flames_frame *synthFFn);





/* The following funtion takes a (pointer to an) allslitflats structure and 
   normalises all the int32_t slit FF frames to have the same integrated flux over
   their overlap regions. Then, for each given order, each pixel that is 
   present in more than one of the frames is recomputed as a weighted average 
   and the resulting value stored back in all frames containing it (TODO: add 
   some filtering of bad pixels here as well maybe). */
flames_err 
prepslitff_2(allslitflats *slitflats, 
           orderpos *ordpos, 
       double decentSNR);




/* CPL interface
flames_err 
initemplate(frame *myframe, uves_propertylist * header, int chip);
*/



/* CPL interface
flames_err 
initbadpixel(flames_frame *myframe, 
                    uves_propertylist * header, 
                    int chip,
                    cpl_image* bp_map);
*/





/* The following function takes a pointer to a template frame structure 
   and allocates missing member to make it become a full frame */
flames_err 
template2frame(flames_frame *myframe);

/* The following function takes a pointer to a frame structure and
   frees unneeded members to make it become a template frame */
flames_err 
frame2template(flames_frame *myframe);


/* The following function takes a pointer to an allslitflats structure 
   and allocates memory for part of the arrays therein. The sizes are taken
   from the scalar members of the allslitflats structure, and must have 
   been set in advance; this is used when the flats are first read from
   disk */

flames_err 
allocslitflats2(allslitflats *slitflats);


/* Simple function (from the K&R book) to convert number to the equivalent string */

void 
itoa(int , char *);


/* This function copy a structure allflats in a completely new one.
   It is a slightly modified version of cloneallflats in order to release
   the memory allocated for the old one without any loss of data */

flames_err  
copy_all_flats(allflats *, allflats *);


/* 
   The following function updates the variances of the frames
*/

flames_err varupdate(flames_frame *,  allflats *, int, int, int **);


/* 
   The following function finds the background model for FF frames. It is the same of the
   latter one except for the different input structures.
*/

flames_err FFscatter(allflats *, orderpos *, int n);


/* 
   The following function subtract to the frame the background illumination for the Science
   Frames (Science and Th-Ar Frame).
*/

flames_err Bkg_Subtract(flames_frame *);

/* 
   The following function subtract to the frame the background illumination for the FF Frame. 
   It is the same of the latter one except for the different input structures.
*/

flames_err Bkg_SubtractFF(allflats *, int);



/* 
   ------------------------------------------------
   The following functions are used only in the standard extraction procedure
   ------------------------------------------------
*/


/* This function calculates the Illumination Fractions for each fibre */

flames_err Used_Flux(flames_frame *, allflats *, orderpos *);




/* 
   ------------------------------------------------
   Here end the prototypes for public C functions written by Pasquale
   ------------------------------------------------
*/
#endif


