/* $Id: visir_img_trans.c,v 1.70 2009/01/29 08:56:58 llundin Exp $
 *
 * This file is part of the VISIR Pipeline
 * Copyright (C) 2002,2003 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., 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
 */

/*
 * $Author: llundin $
 * $Date: 2009/01/29 08:56:58 $
 * $Revision: 1.70 $
 * $Name: visir-3_5_1 $
 */

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


/*-----------------------------------------------------------------------------
                                Includes
 -----------------------------------------------------------------------------*/

#include "visir_recipe.h"

/*-----------------------------------------------------------------------------
                                Defines 
 -----------------------------------------------------------------------------*/

/* FIXME: Use VISIR_HCYCLE_BPM_THRESHOLD */
#define VISIR_LIMIT_FOR_BAD_PIXELS  32000.0

#define RECIPE_STRING "visir_img_trans"

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

static cpl_error_code visir_img_trans_save(cpl_frameset *,
                                           const cpl_parameterlist *,
                                           const cpl_table *);

VISIR_RECIPE_DEFINE(visir_img_trans, 0, "Instrument Transmission recipe",
                    "This recipe computes the transmission at different "
                    "wavelengths by\n"
                    "comparing the flux of a bright star for different "
                    "observations.\n"
                    "The files listed in the Set Of Frames (sof-file) "
                    "must be tagged:\n"
                    "VISIR-transmission-file.fits IM_TEC_TRANS\n"
                    "The resuts are given in a table.\n");

/*----------------------------------------------------------------------------*/
/**
 * @defgroup visir_img_trans   Instrument Transmission
 */
/*----------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------
                                Functions code
 -----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------*/
/**
  @brief    The recipe data reduction part is implemented here 
  @param    parlist     the parameters list
  @param    framelist   the frames list
  @return   0 iff everything is ok
 */
/*----------------------------------------------------------------------------*/
static int visir_img_trans(cpl_frameset            * framelist,
                           const cpl_parameterlist * parlist)
{
    irplib_framelist * allframes = NULL;
    irplib_framelist * rawframes = NULL;
    cpl_imagelist   *   loaded = NULL;
    double          *   wls = NULL;
    int                 nfiles;
    cpl_table       *   tab = NULL;
    cpl_table       *   tab2 = NULL;
    int                 i;

    
    /* Identify the RAW and CALIB frames in the input frameset */
    skip_if (visir_dfs_set_groups(framelist));

    /* Objects observation */
    allframes = irplib_framelist_cast(framelist);
    skip_if(allframes == NULL);
    rawframes = irplib_framelist_extract(allframes, VISIR_IMG_TRANS_RAW);
    skip_if (rawframes == NULL);

    skip_if(irplib_framelist_load_propertylist_all(rawframes, 0,
                                                   visir_property_regexp,
                                                   CPL_FALSE));
    skip_if(visir_dfs_check_framelist_tag(rawframes));

    /* Load the frames */
    cpl_msg_info(cpl_func, "Load the input frames");
    if ((loaded = visir_imagelist_load_last(rawframes)) == NULL) {
        cpl_msg_error(cpl_func, "Could not load the input frames");
        skip_if(1);
    }

    nfiles = cpl_imagelist_get_size(loaded);

    skip_if( nfiles <= 0);

    /* Set the pixels above VISIR_LIMIT_FOR_BAD_PIXELS as bad */
    for (i=0 ; i < nfiles ; i++) {
        cpl_mask * map = cpl_mask_threshold_image_create(
                               cpl_imagelist_get(loaded, i),
                               VISIR_LIMIT_FOR_BAD_PIXELS,
                               DBL_MAX);
        if (map == NULL) continue;
        cpl_image_reject_from_mask(cpl_imagelist_get(loaded, i), map);
        cpl_mask_delete(map);
    }

    skip_if(0);
    
    /* Get the wavelengths from the headers */
    cpl_msg_info(cpl_func, "Get the wavelengths from the input headers");
    if ((wls = visir_utils_get_wls(rawframes)) == NULL) {
        cpl_msg_error(cpl_func, "Could not get wavelengths");
        skip_if(1);
    }
    
    /* Create the table and fill it with the relevant information */
    tab = visir_table_new_xypos(loaded, "FLUX");
    skip_if (tab == NULL);

    tab2 = cpl_table_new(nfiles);
    skip_if (tab2 == NULL);

    /* FIXME: A better way to do this, if at all necessary ? */
    skip_if (cpl_table_move_column(tab2, "FLUX", tab));

    skip_if (cpl_table_wrap_double(tab, wls, "WAVELENGTH"));
    wls = NULL;

    skip_if (cpl_table_move_column(tab, "FLUX", tab2));

    /* FIXME: Verify that this is requested */
    for (i=0; i < nfiles; i++) {
        if (cpl_table_get_double(tab, "FLUX", i, NULL) > 0) continue;
        skip_if (cpl_table_set_double(tab, "FLUX", i,
                           cpl_image_get_median(cpl_imagelist_get(loaded, i))));
    }

    /* Normalise the FLUX column */
    skip_if (cpl_table_divide_scalar(tab, "FLUX",
                                     cpl_table_get_column_max(tab, "FLUX")));

    /* Save the products */
    cpl_msg_info(cpl_func, "Save the products");
    skip_if (visir_img_trans_save(framelist, parlist, tab));

    end_skip;

    irplib_framelist_delete(allframes);
    irplib_framelist_delete(rawframes);
    cpl_free(wls);    
    cpl_table_delete(tab);
    cpl_table_delete(tab2);
    cpl_imagelist_delete(loaded);

    return cpl_error_get_code();
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Save the visir_img_trans recipe products on disk
  @param    set     The input frame set
  @param    parlist The input list of parameters
  @param    tab     The 4 columns table
  @return   0 iff everything is ok
 */
/*----------------------------------------------------------------------------*/
static cpl_error_code visir_img_trans_save(cpl_frameset            * set,
                                           const cpl_parameterlist * parlist,
                                           const cpl_table         * tab)
{

    skip_if(irplib_dfs_save_table(set, parlist, set, tab, NULL, RECIPE_STRING,
                              VISIR_IMG_TRANS_TAB_PROCATG, NULL, NULL,
                              visir_pipe_id, RECIPE_STRING CPL_DFS_FITS));

    end_skip;

    return cpl_error_get_code();

}
