/* $Id: sinfo_utl_skymap.c,v 1.13 2009-01-30 14:56:12 amodigli Exp $
 *
 * This file is part of the SINFONI 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * $Author: amodigli $
 * $Date: 2009-01-30 14:56:12 $
 * $Revision: 1.13 $
 * $Name: not supported by cvs2svn $
 */

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

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

/* cpl */
#include <cpl.h>
/* irplib */
#include <irplib_utils.h>

/* sinfoni */
#include <sinfo_tpl_utils.h>
#include <sinfo_pfits.h>
#include <sinfo_tpl_dfs.h>
#include <sinfo_raw_types.h>
#include <sinfo_pro_types.h>
#include <sinfo_functions.h>
#include <sinfo_key_names.h>
#include <sinfo_msg.h>
#include <sinfo_error.h>
#include <sinfo_utils_wrappers.h>
/*-----------------------------------------------------------------------------
                            Functions prototypes
 ----------------------------------------------------------------------------*/

static int sinfo_utl_skymap_create(cpl_plugin *) ;
static int sinfo_utl_skymap_exec(cpl_plugin *) ;
static int sinfo_utl_skymap_destroy(cpl_plugin *) ;
static int sinfo_utl_skymap(cpl_parameterlist *, cpl_frameset *) ;
/*-----------------------------------------------------------------------------
                            Static variables
 ----------------------------------------------------------------------------*/

static char sinfo_utl_skymap_description[] =
                "This recipe flags as bad pixels sky lines.\n"
                "Input are sky frames with tag SKY\n"
                "Output image is called out_skymap.fits\n"
                "\n";

/*-----------------------------------------------------------------------------
                                Functions code
 ----------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/**
 * @defgroup sinfo_utl_skymap  Recipe to generate a sky map for SINFONI SRTD
 */
/*---------------------------------------------------------------------------*/

/**@{*/
/*---------------------------------------------------------------------------*/
/**
  @brief    Build the list of available plugins, for this module. 
  @param    list    the plugin list
  @return   0 if everything is ok

  This function is exported.
 */
/*---------------------------------------------------------------------------*/
int cpl_plugin_get_info(cpl_pluginlist * list)
{
    cpl_recipe  *   recipe = cpl_calloc(1, sizeof *recipe ) ;
    cpl_plugin  *   plugin = &recipe->interface ;

    cpl_plugin_init(plugin,
                    CPL_PLUGIN_API,
                    SINFONI_BINARY_VERSION,
                    CPL_PLUGIN_TYPE_RECIPE,
                    "sinfo_utl_skymap",
                    "Flags sky lines as bad pixels, with map generation",
                    sinfo_utl_skymap_description,
                    "Andrea Modigliani",
                    "Andrea.Modigliani@eso.org",
                    sinfo_get_license(),
                    sinfo_utl_skymap_create,
                    sinfo_utl_skymap_exec,
                    sinfo_utl_skymap_destroy) ;

    cpl_pluginlist_append(list, plugin) ;

    return 0;
}

/*---------------------------------------------------------------------------*/
/**
  @brief    Setup the recipe options    
  @param    plugin  the plugin
  @return   0 if everything is ok

  Create the recipe instance and make it available to the application using 
  the interface. 
 */
/*---------------------------------------------------------------------------*/
static int sinfo_utl_skymap_create(cpl_plugin * plugin)
{
    cpl_recipe      * recipe ;
    cpl_parameter   * p ;

    /* Get the recipe out of the plugin */
    if (cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE) 
        recipe = (cpl_recipe *)plugin ;
    else return -1 ;

    /* Create the parameters list in the cpl_recipe object */
    recipe->parameters = cpl_parameterlist_new() ; 

    /* Fill the parameters list */


    /* --doubleopt */
    p = cpl_parameter_new_range("sinfoni.sinfo_utl_skymap.xsize", 
                    CPL_TYPE_INT, "X box size", "sinfoni.sinfo_utl_skymap", 1,1,2047) ;
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "xsize") ;
    cpl_parameterlist_append(recipe->parameters, p) ;

    /* --doubleopt */
    p = cpl_parameter_new_range("sinfoni.sinfo_utl_skymap.ysize", 
                    CPL_TYPE_INT, "Y box size", "sinfoni.sinfo_utl_skymap", 30,1,2047) ;
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "ysize") ;
    cpl_parameterlist_append(recipe->parameters, p) ;



    /* --doubleopt */
    p = cpl_parameter_new_value("sinfoni.sinfo_utl_skymap.threshold", 
                    CPL_TYPE_DOUBLE, "Threshold", "sinfoni.sinfo_utl_skymap", 30.) ;
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "thresh") ;
    cpl_parameterlist_append(recipe->parameters, p) ;

    /* Return */
    return 0;
}

/*---------------------------------------------------------------------------*/
/**
  @brief    Execute the plugin instance given by the interface
  @param    plugin  the plugin
  @return   0 if everything is ok
 */
/*---------------------------------------------------------------------------*/
static int sinfo_utl_skymap_exec(cpl_plugin * plugin)
{
    cpl_recipe  *   recipe ;
    int code=0;
    cpl_errorstate initial_errorstate = cpl_errorstate_get();

    /* Get the recipe out of the plugin */
    if (cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE) 
        recipe = (cpl_recipe *)plugin ;
    else return -1 ;
    cpl_error_reset();
    //irplib_reset();
    check_nomsg(code = sinfo_utl_skymap(recipe->parameters, recipe->frames)) ;
    if (!cpl_errorstate_is_equal(initial_errorstate)) {                      
        /* Dump the error history since recipe execution start.                
           At this point the recipe cannot recover from the error */           
        cpl_errorstate_dump(initial_errorstate, CPL_FALSE, NULL);              
    } 
    cleanup:
    return code ;
}

/*---------------------------------------------------------------------------*/
/**
  @brief    Destroy what has been created by the 'create' function
  @param    plugin  the plugin
  @return   0 if everything is ok
 */
/*---------------------------------------------------------------------------*/
static int sinfo_utl_skymap_destroy(cpl_plugin * plugin)
{
    cpl_recipe  *   recipe ;

    /* Get the recipe out of the plugin */
    if (cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE) 
        recipe = (cpl_recipe *)plugin ;
    else return -1 ;

    cpl_parameterlist_delete(recipe->parameters) ; 
    return 0 ;
}

static int sinfo_utl_skymap(
                cpl_parameterlist   *   parlist,
                cpl_frameset        *   framelist)
{

    const char *            name_i=NULL;
    int                    xsize=0;
    int                    ysize=0;

    cpl_frame           *   sky_frm=NULL;

    const char          *   name_o=NULL ;
    cpl_propertylist    *   plist =NULL;
    cpl_frame           *   product_frame=NULL;
    cpl_frameset        *   sky_set=NULL;
    cpl_image           *   sky_ima=NULL;
    cpl_image           *   sky_map=NULL;
    double threshold=0;
    int i=0;
    int j=0;
    double sinfo_median=0;
    float* sky_ima_pix=NULL;
    float* sky_map_pix=NULL;
    int nx=0;
    int ny=0;
    int n=0;

    /* HOW TO RETRIEVE INPUT PARAMETERS */
    /* --stropt */

    sinfo_msg("Welcome to SINFONI Pipeline release %d.%d.%d",
              SINFONI_MAJOR_VERSION,SINFONI_MINOR_VERSION,SINFONI_MICRO_VERSION);

    cpl_parameter* param = cpl_parameterlist_find(parlist,
                    "sinfoni.sinfo_utl_skymap.out_filename");
    name_o = "out_skymap.fits";

    /* --intopt */
    param = cpl_parameterlist_find(parlist,"sinfoni.sinfo_utl_skymap.xsize");
    xsize = cpl_parameter_get_int(param) ;

    /* --intopt */
    param = cpl_parameterlist_find(parlist,"sinfoni.sinfo_utl_skymap.ysize");
    ysize = cpl_parameter_get_int(param) ;

    param = cpl_parameterlist_find(parlist,
                    "sinfoni.sinfo_utl_skymap.threshold");
    threshold = cpl_parameter_get_double(param) ;

    /* Identify the RAW and CALIB frames in the input frameset */
    if (sinfo_dfs_set_groups(framelist)) {
        sinfo_msg_error("Cannot identify RAW and CALIB frames") ;
        return -1 ;
    }

    /* HOW TO ACCESS INPUT DATA */
    n=cpl_frameset_get_size(framelist);
    if(n<1) {
        sinfo_msg_error("Empty input frame list!");
        return -1;
    }
    sky_set=cpl_frameset_new();
    sinfo_extract_frames_type(framelist,sky_set,RAW_SKY);

    n=cpl_frameset_get_size(framelist);
    if(n<1) {
        sinfo_msg_error("No sky frames in input list!");
        sinfo_free_frameset(&sky_set);
        return -1;
    }


    check_nomsg(sky_frm = cpl_frameset_get_frame(sky_set,0));

    if ((plist=cpl_propertylist_load(cpl_frame_get_filename(sky_frm),
                    0)) == NULL) {
        sinfo_msg_error("Cannot read the FITS header") ;
        return -1 ;
    }


    name_i=cpl_frame_get_filename(sky_frm);
    sky_ima = cpl_image_load(name_i,CPL_TYPE_FLOAT,0,0);
    sky_map=cpl_image_duplicate(sky_ima);
    sky_ima_pix=cpl_image_get_data(sky_ima);
    sky_map_pix=cpl_image_get_data(sky_map);
    nx = cpl_image_get_size_x(sky_ima);
    ny = cpl_image_get_size_y(sky_ima);
    if (nx != SIZEX || ny != SIZEY) {
        sinfo_msg_error("nx=%d ny=%d, expected nx=%d ny=%d",nx,ny,SIZEX,SIZEY);
        goto cleanup;

    }
    for(i=1;i<nx;i++) {

        for(j=ysize+1;j<ny-ysize;j++) {

            sinfo_median=cpl_image_get_median_window(sky_ima,i,j-ysize,i,j+xsize);
            if(cpl_error_get_code() != CPL_ERROR_NONE) {
                sinfo_msg_error("Exit");
                sinfo_free_image(&sky_ima);
                sinfo_free_image(&sky_map);
                sinfo_free_propertylist(&plist);
                sinfo_free_frameset(&sky_set);
                return -1;
            }
            if(sky_ima_pix[i+j*nx] > sinfo_median+threshold) {
                sky_map_pix[i+j*nx]=0.;
            } else {
                sky_map_pix[i+j*nx]=1.;
            }
        }

    }



    for(i=1;i<nx;i++) {

        for(j=0;j<ysize+1;j++) {

            sky_map_pix[i+j*nx]=0.;

        }

        for(j=ny-ysize+1;j<ny;j++) {

            sky_map_pix[i+j*nx]=0.;

        }

    }



    /* Now performing the data reduction */
    /* Let's generate one image for the example */



    /* HOW TO SAVE A PRODUCT ON DISK  */
    /* Set the file name */
    name_o = "sky_map.fits" ;

    /* Create product frame */
    product_frame = cpl_frame_new();
    cpl_frame_set_filename(product_frame, name_o) ;
    cpl_frame_set_tag(product_frame, PRO_SKY_DUMMY) ;
    cpl_frame_set_type(product_frame, CPL_FRAME_TYPE_IMAGE) ;
    cpl_frame_set_group(product_frame, CPL_FRAME_GROUP_PRODUCT) ;
    cpl_frame_set_level(product_frame, CPL_FRAME_LEVEL_FINAL) ;

    if (cpl_error_get_code()) {
        sinfo_msg_error("Error while initialising the product frame") ;
        sinfo_free_propertylist(&plist) ;
        sinfo_free_frame(&product_frame) ;
        return -1 ;
    }

    /* Add DataFlow keywords */
    if (cpl_dfs_setup_product_header(plist, product_frame, framelist, parlist,
                    "sinfo_utl_skymap",
                    "SINFONI", KEY_VALUE_HPRO_DID,NULL)
                    != CPL_ERROR_NONE) {
        sinfo_msg_error("Problem in the product DFS-compliance") ;
        sinfo_free_propertylist(&plist) ;
        sinfo_free_frame(&product_frame) ;
        sinfo_free_image(&sky_ima);
        sinfo_free_image(&sky_map);
        sinfo_free_frameset(&sky_set);
        return -1 ;
    }


    /* Save the file */
    if (cpl_image_save(sky_map, name_o, CPL_BPP_IEEE_FLOAT, plist,
                    CPL_IO_DEFAULT) != CPL_ERROR_NONE) {
        sinfo_msg_error("Could not save product");
        sinfo_free_propertylist(&plist) ;
        sinfo_free_frame(&product_frame) ;
        sinfo_free_image(&sky_map) ;
        return -1 ;
    }
    sinfo_free_propertylist(&plist) ;
    sinfo_free_image(&sky_map) ;
    sinfo_free_image(&sky_ima) ;

    /* Log the saved file in the input frameset */
    cpl_frameset_insert(framelist, product_frame) ;
    sinfo_free_frameset(&sky_set);



    cleanup:
    sinfo_free_image(&sky_ima);
    sinfo_free_image(&sky_map);
    sinfo_free_propertylist(&plist);
    sinfo_free_frameset(&sky_set);

    if(  cpl_error_get_code()!=CPL_ERROR_NONE) {
        return -1 ;
    } else {
        return 0 ;
    }
}
/**@}*/
