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

/*
 * $Author: amodigli $
 * $Date: 2012-03-02 17:01:40 $
 * $Revision: 1.36 $
 * $Name: not supported by cvs2svn $
 * $Log: not supported by cvs2svn $
 * Revision 1.35  2011/12/08 13:57:49  amodigli
 * Fox warnings with CPL6
 *
 * Revision 1.34  2010/09/29 09:39:07  amodigli
 * fixed compiler warnings
 *
 * Revision 1.33  2010/09/27 07:58:36  amodigli
 * fixed mem leak in case a new mask is allocated
 *
 * Revision 1.32  2010/09/27 06:33:33  amodigli
 * fixed mem leaks
 *
 * Revision 1.31  2010/09/24 09:32:03  amodigli
 * put back QFITS dependency to fix problem spot by NRI on FIBER mode (with MIDAS calibs) data
 *
 * Revision 1.29  2009/07/07 14:26:12  amodigli
 * Fixed a problem dealing with images missing a bpm
 *
 * Revision 1.28  2008/09/29 06:56:10  amodigli
 * add #include <string.h>
 *
 * Revision 1.27  2007/08/21 13:08:26  jmlarsen
 * Removed irplib_access module, largely deprecated by CPL-4
 *
 * Revision 1.26  2007/06/06 08:17:33  amodigli
 * replace tab with 4 spaces
 *
 * Revision 1.25  2007/05/24 13:07:46  jmlarsen
 * Fail if the provided flat-field has unreasonable (zero, nan or inf) mean value
 *
 * Revision 1.24  2007/05/22 11:36:37  jmlarsen
 * Removed MIDAS flag for good
 *
 * Revision 1.23  2006/11/15 15:02:14  jmlarsen
 * Implemented const safe workarounds for CPL functions
 *
 * Revision 1.21  2006/11/15 14:04:08  jmlarsen
 * Removed non-const version of parameterlist_get_first/last/next which is already
 * in CPL, added const-safe wrapper, unwrapper and deallocator functions
 *
 * Revision 1.20  2006/11/13 14:23:55  jmlarsen
 * Removed workarounds for CPL const bugs
 *
 * Revision 1.19  2006/11/06 15:19:41  jmlarsen
 * Removed unused include directives
 *
 * Revision 1.18  2006/08/17 13:56:53  jmlarsen
 * Reduced max line length
 *
 * Revision 1.17  2006/08/17 09:16:40  jmlarsen
 * Removed CPL2 code
 *
 * Revision 1.16  2006/08/10 10:49:57  jmlarsen
 * Removed workaround for cpl_image_get_bpm
 *
 * Revision 1.15  2006/06/16 08:23:31  jmlarsen
 * Changed 0 -> false
 *
 * Revision 1.14  2006/04/24 09:20:12  jmlarsen
 * Always use the MIDAS normalization
 *
 * Revision 1.13  2006/03/24 14:16:43  jmlarsen
 * Changed order of for loops for efficiency
 *
 * Revision 1.12  2006/03/03 13:54:11  jmlarsen
 * Changed syntax of check macro
 *
 * Revision 1.11  2006/02/21 14:26:54  jmlarsen
 * Minor changes
 *
 * Revision 1.10  2006/02/03 07:46:30  jmlarsen
 * Moved recipe implementations to ./uves directory
 *
 * Revision 1.9  2006/01/31 08:24:16  jmlarsen
 * Wrapper for cpl_image_get_bpm
 *
 * Revision 1.8  2006/01/25 16:13:20  jmlarsen
 * Changed interface of gauss.fitting routine
 *
 * Revision 1.7  2005/12/19 16:17:56  jmlarsen
 * Replaced bool -> int
 *
 * Revision 1.6  2005/12/16 14:22:23  jmlarsen
 * Removed midas test data; Added sof files
 *
 * Revision 1.5  2005/12/02 10:41:49  jmlarsen
 * Minor update
 *
 * Revision 1.4  2005/11/28 08:18:12  jmlarsen
 * Replaced cpl_mask_get_bpm -> cpl_image_get_bpm
 *
 * Revision 1.3  2005/11/25 09:27:00  jmlarsen
 * Switched off time component
 *
 * Revision 1.2  2005/11/24 11:54:46  jmlarsen
 * Added support for CPL 3 interface
 *
 * Revision 1.1  2005/11/11 13:18:54  jmlarsen
 * Reorganized code, renamed source files
 *
 */

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

/*----------------------------------------------------------------------------*/
/**
 * @defgroup uves_flatfield    Flat-field correction
 *
 * Divide by a master flat-field frame in (pixel, pixel)-space or in
 * (pixel, order)-space.
 */
/*----------------------------------------------------------------------------*/
/**@{*/

/*-----------------------------------------------------------------------------
                                Includes
 -----------------------------------------------------------------------------*/
#include <string.h>
#include <uves_flatfield.h>
#include <uves_utils.h>
#include <uves_utils_wrappers.h>
#include <uves_error.h>

#include <cpl.h>

/*-----------------------------------------------------------------------------
                            Functions prototypes
 -----------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------
                            Implementation
 -----------------------------------------------------------------------------*/


/*----------------------------------------------------------------------------*/
/**
   @brief    Divide by flat field
   @param    image        The image to correct
   @param    noise        The noise of the provided @em image. This
                          noise image is updated according to the error
              propagation formula. Ignored if set to NULL.
   @param    master_flat  The master flat field image
   @param    mflat_noise  The master flat field noise image
   @return  CPL_ERROR_NONE iff okay.
   
   The input @em image divided by the normalized master flat image.
   The normalized master flat image has mean flux equal to 1.

   This flat field correction is performed in (pixel, pixel)-space,
   or (pixel, order)-space. The input image sizes must be equal.

   Bad pixels are properly propagated, i.e. if a pixel in the input image or master flat
   or noise images is bad, the resulting pixel is also set to bad. Also division by
   a zero or negative flat field causes a bad pixel.
*/
/*----------------------------------------------------------------------------*/
cpl_error_code
uves_flatfielding(cpl_image *image, cpl_image *noise, 
          const cpl_image *master_flat, const cpl_image *mflat_noise)
{
    double     *image_data   = NULL;      /* We have to get direct pointers because of the slow */
    cpl_mask   *image_mask   = NULL;      /*  bad pix handling in cpl_image_get()  CPLv2-3      */
    cpl_binary *image_bad    = NULL;  

    double     *noise_data   = NULL;   
    cpl_mask   *noise_mask   = NULL;   
    cpl_binary *noise_bad    = NULL;

    const double     *mf_data      = NULL;   
    const cpl_mask   *mf_mask      = NULL;   
    const cpl_binary *mf_bad       = NULL;  

    const double     *mfnoise_data = NULL;   
    const cpl_mask   *mfnoise_mask = NULL;   
    cpl_mask   *mfnoise_mask_own = NULL;   
    cpl_mask   *mf_mask_own = NULL;   
    const cpl_binary *mfnoise_bad  = NULL;  
  

    double ff_mean;
    int nx, ny;
    int x, y;
    
    passure( image != NULL, " ");
    passure( master_flat != NULL, " ");
    passure( noise == NULL || mflat_noise != NULL, " ");

    passure( cpl_image_get_type(image) == CPL_TYPE_DOUBLE, 
         "Image must be double");
    passure( noise == NULL || cpl_image_get_type(noise) == CPL_TYPE_DOUBLE, 
         "Image must be double");
    passure( cpl_image_get_type(master_flat) == CPL_TYPE_DOUBLE, 
         "Image must be double");
    passure( mflat_noise == NULL || cpl_image_get_type(mflat_noise) == CPL_TYPE_DOUBLE,
         "Image must be double");

    nx = cpl_image_get_size_x(image);
    ny = cpl_image_get_size_y(image);
    
    assure( nx == cpl_image_get_size_x(master_flat),
        CPL_ERROR_INCOMPATIBLE_INPUT,
        "Input image and master flat field image have different widths: "
        "%d and %" CPL_SIZE_FORMAT " (pixels)",
        nx, cpl_image_get_size_x(master_flat));
    
    assure( ny == cpl_image_get_size_y(master_flat),
        CPL_ERROR_INCOMPATIBLE_INPUT,
        "Input image and master flat field image have different heights: "
        "%d and %" CPL_SIZE_FORMAT " (pixels)",
        ny, cpl_image_get_size_y(master_flat));

    /* Get all pointers */
    check_nomsg(image_data = cpl_image_get_data(image));
    check_nomsg(image_mask = cpl_image_get_bpm(image));
    check_nomsg(image_bad  = cpl_mask_get_data(image_mask));

    check_nomsg(mf_data = cpl_image_get_data_const(master_flat));
    check_nomsg(mf_mask = cpl_image_get_bpm_const(master_flat));
    if(mf_mask==NULL) {
          mf_mask_own = cpl_mask_new(nx,ny);
          mf_mask = mf_mask_own ;
    }
    check_nomsg(mf_bad  = cpl_mask_get_data_const(mf_mask));

    if (noise != NULL)
    {
       check_nomsg(noise_data = cpl_image_get_data(noise));
       check_nomsg(noise_mask = cpl_image_get_bpm(noise));
       check_nomsg(noise_bad  = cpl_mask_get_data(noise_mask));

       check_nomsg(mfnoise_data = cpl_image_get_data_const(mflat_noise));
       check_nomsg(mfnoise_mask = cpl_image_get_bpm_const(mflat_noise));
       if(mfnoise_mask==NULL) {
          mfnoise_mask_own = cpl_mask_new(nx,ny);
          mfnoise_mask = mfnoise_mask_own ;
       }
       check_nomsg(mfnoise_bad  = cpl_mask_get_data_const(mfnoise_mask));
    }

    if (false)
    {
        /* This would actually be the proper thing to do (take bad
           pixels into account), but for backwards compatibility
           with MIDAS, pretend bad pixels have value zero.
           This is done in order to get the same normalization and
           be able to use response curves produces by the MIDAS pipeline.

           (The difference in normalization is usually ~10% or so)
        */
        check( ff_mean = cpl_image_get_mean(master_flat),
           "Could not read average flux of master flat image");
    }
    else
    {
        /* To get same normalization as MIDAS (which doesn't take bad pixels
         * into account), calculate 'ff_mean' while assuming that bad pixels
         * have value zero.
         */
        check( ff_mean = cpl_image_get_flux(master_flat) / (nx * ny),
           "Could not read average flux of master flat image");
    }
    
    assure( ff_mean != 0 && !irplib_isnan(ff_mean) &&
            !irplib_isinf(ff_mean), CPL_ERROR_ILLEGAL_INPUT,
            "Flat-field mean value is %g! Please provide a better flat-field",
            ff_mean );
    
    /* Divide by normalized master flat */
    for (y = 0; y < ny; y++)
    {
        for (x = 0; x < nx; x++)
        {
            double mf, mf_noise = 0;
            double flux, flux_noise = 0, flux_corrected = 0;
            double noise_corrected = 0;
            cpl_binary pis_rejected;
            bool is_bad = false;
            
            mf           = mf_data[x + y*nx];
            pis_rejected = mf_bad [x + y*nx];
            is_bad = is_bad || (pis_rejected == CPL_BINARY_1);
            /* Slow: mf = cpl_image_get(master_flat, x, y, &pis_rejected);
               is_bad = is_bad || pis_rejected; */

            if (noise != NULL)
            {
                flux_noise   = noise_data[x + y*nx];
                pis_rejected = noise_bad [x + y*nx];
                is_bad = is_bad || (pis_rejected == CPL_BINARY_1);
                /* Slow: flux_noise = 
                   cpl_image_get(image_noise, x, y, &pis_rejected); 
                   is_bad = is_bad || pis_rejected; */
                
                mf_noise     = mfnoise_data[x + y*nx];
                pis_rejected = mfnoise_bad [x + y*nx];
                is_bad = is_bad || (pis_rejected == CPL_BINARY_1);
                /* Slow: mf_noise = 
                   cpl_image_get(mflat_noise, x, y, &pis_rejected); 
                   is_bad = is_bad || pis_rejected; */
            }
            
            flux         = image_data[x + y*nx];
            pis_rejected = image_bad [x + y*nx];
            is_bad = is_bad || (pis_rejected == CPL_BINARY_1);
            /* Slow: flux = cpl_image_get(image, x, y, &pis_rejected); 
               is_bad = is_bad || pis_rejected; */
            



            if (mf > 0)
            {
                flux_corrected = (flux / mf) * ff_mean;
            }
            else
            {
                /* Some mf frames (produced by MIDAS) have have
                   negative flux values because of improper
                   background subtraction */
                is_bad = true;
            }

            if (noise != NULL)
            {
                noise_corrected = uves_error_fraction(
                flux, mf, flux_noise, mf_noise)
                * ff_mean;
            }
            
            if (is_bad) 
            {
                image_bad[x + nx*y] = CPL_BINARY_1;
                /* Slow: cpl_image_reject(image, x, y);*/
                if (noise != NULL)
                {
                    noise_bad[x + nx*y] = CPL_BINARY_1;
                    /* Slow: cpl_image_reject(noise, x, y);*/
                }
            }
            else
            {
                image_data[x + nx*y] = flux_corrected;
                /* Slow: cpl_image_set(image, x, y, flux_corrected); */
                if (noise != NULL)
                {
                    noise_data[x + nx*y] = noise_corrected;
                    /* Slow: cpl_image_set(noise, x, y, noise_corrected); */
                }
            }
        }
    }
    
  cleanup:
    if(mf_mask_own) uves_free_mask(&mf_mask_own);
    if(mfnoise_mask_own) uves_free_mask(&mfnoise_mask_own);
    return cpl_error_get_code();
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Read flat-field method from parameter list
  @param    parameters             The parameter list
  @param    context                Context of ff parameter (or NULL)
  @param    subcontext             Subcontext of ff parameter
                                           
  @return   The flat-fielding method as read from the parameter context.subcontext.ffmethod
  
**/
/*----------------------------------------------------------------------------*/
flatfielding_method
uves_get_flatfield_method(const cpl_parameterlist *parameters, 
              const char *context, const char *subcontext)
{
    const char *ff = "";
    flatfielding_method result = 0;

    check( uves_get_parameter(parameters, context, subcontext, "ffmethod", CPL_TYPE_STRING, &ff),
       "Could not read parameter");
    
    if      (strcmp(ff, "pixel"  ) == 0) result = FF_PIXEL;
    else if (strcmp(ff, "extract") == 0) result = FF_EXTRACT;
    else if (strcmp(ff, "no"     ) == 0) result = FF_NO;
    else
    {
        assure(false, CPL_ERROR_ILLEGAL_INPUT, "No such flat-fielding method: '%s'", ff);
    }
    
  cleanup:
    return result;
}

/**@}*/

