/* $Id: vimos_biascor.c,v 1.7 2015/08/07 13:07:15 jim Exp $
 *
 * This file is part of the VIMOS Pipeline
 * Copyright (C) 2015 European Southern Observatory
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * $Author: jim $
 * $Date: 2015/08/07 13:07:15 $
 * $Revision: 1.7 $
 * $Name:  $
 */

/* Includes */

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

#include <cpl.h>
#include "vimos_imaging_utils.h"
#include "vimos_mods.h"
#include <casu_fits.h>
#include <casu_utils.h>
#include <casu_stats.h>

/**@{*/

/*---------------------------------------------------------------------------*/
/**
    \ingroup reductionmodules
    \brief Correct input data for bias
  
    \par Name:
        vimos_biascor
    \par Purpose:
        Correct input data for bias
    \par Description:
        Two images are given -- one is the data for an observation, the 
        other is for a mean bias frame. The latter is subtracted from 
        the former. An overscan correction can also be done. If requested
        the overscan and underscan regions can be trimmed. The modified
        image replaces the input image.
    \par Language:
        C
    \param infile 
        The input data image (overwritten by result).
    \param biassrc 
        The input master bias image
    \param overscan
        If set, then the overscan correction is also done.
    \param trim
        If set, then the overscan and underscan regions are trimmed from
        the image.
    \param status 
        An input/output status that is the same as the returned values below.
    \retval CASU_OK 
        if everything is ok
    \retval CASU_FATAL 
        if image data fails to load or the image and the master bias have 
        different sizes.
    \par QC headers:
        None
    \par DRS headers:
        The following DRS keywords are written to the infile extension header
        - \b BIASCOR
            The name of the originating FITS file for the master bias image
        - \b OSCOR_MED: 
            The value of the overscan correction applied (if requested)
        - \b OSCOR_RMS: 
            The rms of the overscan correction applied (if requested)
        - \b TRIMMED:
            True if the input frame has been trimmed.
    \author
        Jim Lewis, CASU
 */
/*---------------------------------------------------------------------------*/

int vimos_biascor(casu_fits *infile, casu_fits *biassrc, int overscan,
                  int trim, int *status) {
    cpl_propertylist *ehu;
    cpl_image *im,*bm,*subset;
    float *idata,*work,med,sig,oscor;
    int npi,n,i,j,k,nx;
    const char *fctid = "vimos_biascor";

    /* Inherited status */

    if (*status != CASU_OK)
        return(*status);

    /* See if this file has already been done */

    ehu = casu_fits_get_ehu(infile);
    if (cpl_propertylist_has(ehu,"ESO DRS BIASCOR"))
        return(*status);

    /* Get the images and check the dimension to make sure they match */
    
    im = casu_fits_get_image(infile);
    bm = casu_fits_get_image(biassrc);
    if (casu_compare_dims(im,bm) != CASU_OK) {
        cpl_msg_error(fctid,"Object and bias data array dimensions don't match");
        FATAL_ERROR
    }

    /* If doing the overscan correction, then get the median of counts
       in the overscan strip in both images */

    if (overscan) {
        idata = cpl_image_get_data(im);
        nx = cpl_image_get_size_x(im);
        npi = (overlim[1] - overlim[0] + 1)*(overlim[3] - overlim[2] + 1);
        work = cpl_malloc(npi*sizeof(float));
        n = 0;
        for (j = overlim[2]; j <= overlim[3]; j++) {
            for (i = overlim[0]; i <= overlim[1]; i++) {
                k = (j-1)*nx + i - 1;
                work[n++] = idata[k];
            }
        }
        casu_medmad(work,NULL,n,&med,&sig);  
        sig *= 1.48;
        freespace(work);
        oscor = med - 
            cpl_propertylist_get_float(casu_fits_get_ehu(biassrc),
                                       "ESO QC OSCAN_MED");
    } else {
        oscor = 0.0;
    }

    /* Just use the cpl image routines to do the arithmetic */

    if (cpl_image_subtract(im,bm) != CPL_ERROR_NONE)
        FATAL_ERROR
    if (overscan) {         
        if (cpl_image_subtract_scalar(im,(double)oscor) != CPL_ERROR_NONE)
            FATAL_ERROR
    }

    /* Trim the image if that has been requested */

    if (trim) {
        subset = cpl_image_extract(im,(cpl_size)(underlim[1]+1),
                                   (cpl_size)underlim[2],
                                   (cpl_size)(overlim[0]-1),
                                   (cpl_size)underlim[3]);
        casu_fits_replace_image(infile,subset);
    }

    /* Now put some stuff in the DRS extension... */

    if (casu_fits_get_fullname(biassrc) != NULL) 
        cpl_propertylist_update_string(ehu,"ESO DRS BIASCOR",
                                       casu_fits_get_fullname(biassrc));
    else
        cpl_propertylist_update_string(ehu,"ESO DRS BIASCOR",
                                       "Memory File");
    cpl_propertylist_set_comment(ehu,"ESO DRS BIASCOR",
                                 "Image used for bias correction");
    cpl_propertylist_update_float(ehu,"ESO DRS OSCOR",oscor);
    cpl_propertylist_set_comment(ehu,"ESO DRS OSCOR",
                                 "level of overscan correction applied");
    if (overscan) {
        cpl_propertylist_update_float(ehu,"ESO DRS OSCAN_MED",med);
        cpl_propertylist_set_comment(ehu,"ESO DRS OSCAN_MED",
                                     "median in overscan");
        cpl_propertylist_update_float(ehu,"ESO DRS OSCAN_RMS",sig);
        cpl_propertylist_set_comment(ehu,"ESO DRS OSCAN_RMS",
                                     "rms in overscan");        
    } 
    cpl_propertylist_update_bool(ehu,"ESO DRS TRIMMED",trim);
    cpl_propertylist_set_comment(ehu,"ESO DRS TRIMMED",
                                     "Has image been trimmed?");

    /* Get out of here */

    GOOD_STATUS
}


/**@}*/

/*

$Log: vimos_biascor.c,v $
Revision 1.7  2015/08/07 13:07:15  jim
Fixed copyright to ESO

Revision 1.6  2015/06/25 11:54:07  jim
Fixed includes to casu

Revision 1.5  2015/01/29 12:07:30  jim
Modified comments

Revision 1.4  2013/11/21 09:39:08  jim
detabbed

Revision 1.3  2013/11/04 10:03:55  jim
Fixed overscan keyword for BIAS frame

Revision 1.2  2013/11/04 06:01:17  jim
changed name of qc parameters

Revision 1.1.1.1  2013-10-24 08:36:12  jim
Initial import


*/
