/* $Id: sinfo_utl_skycor.c,v 1.14 2013-09-09 15:23:10 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: 2013-09-09 15:23:10 $
 * $Revision: 1.14 $
 * $Name: not supported by cvs2svn $
 */

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

/*-----------------------------------------------------------------------------
                                Includes
 ----------------------------------------------------------------------------*/
#include <string.h>
#include <cpl.h>
#include <irplib_utils.h>
#include <sinfo_skycor.h>
#include <sinfo_skycor_config.h>
#include <sinfo_tpl_utils.h>
#include <sinfo_tpl_dfs.h>
#include <sinfo_pro_types.h>
#include <sinfo_utils_wrappers.h>
#include <sinfo_error.h>
#include <sinfo_msg.h>
#include <sinfo_pro_save.h>
#include <sinfo_globals.h>
/*-----------------------------------------------------------------------------
                                Defines
 ----------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------
                            Functions prototypes
-----------------------------------------------------------------------------*/
static int sinfo_utl_skycor_create(cpl_plugin *) ;
static int sinfo_utl_skycor_exec(cpl_plugin *) ;
static int sinfo_utl_skycor_destroy(cpl_plugin *) ;
static int sinfo_utl_skycor(cpl_parameterlist * config, cpl_frameset* set);
/*-----------------------------------------------------------------------------
                            Static variables
 -----------------------------------------------------------------------------*/

static char sinfo_utl_skycor_description[] =
                "This recipe perform a correction of possible sky line residuals in the \n"
                "object cube after standard data reduction.\n"
                "Input frames are cubes with target and sky observations.\n"
                "Their tags can be respectively OBS_OBJ (or OBS_PSF or OBS_STD) and OBS_SKY.\n"
                "The output is a cube with same tag as the corresponding input target frame.\n"
                "\n";


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

/*---------------------------------------------------------------------------*/
/**
 * @defgroup sinfo_utl_skycor Recipe to correct sky residuals on science cubes
 */
/*---------------------------------------------------------------------------*/
/**@{*/
/*---------------------------------------------------------------------------*/
/**
  @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_skycor",
                    "Sky lines residuals correction",
                    sinfo_utl_skycor_description,
                    "Andrea Modigliani",
                    "Andrea.Modigliani@eso.org",
                    sinfo_get_license(),
                    sinfo_utl_skycor_create,
                    sinfo_utl_skycor_exec,
                    sinfo_utl_skycor_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_skycor_create(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 ;

    /* reset error handling */
    irplib_reset();
    /* Create the parameters list in the cpl_recipe object */
    recipe->parameters = cpl_parameterlist_new() ; 
    sinfo_skycor_config_add(recipe->parameters);

    /* 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_skycor_exec(cpl_plugin * plugin)
{
    cpl_recipe  *   recipe ;
    int code=0;
    /* Get the recipe out of the plugin */
    cpl_errorstate initial_errorstate = cpl_errorstate_get();

    if (cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE) 
        recipe = (cpl_recipe *)plugin ;
    else return -1 ;


    code = sinfo_utl_skycor(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);              
    } 
    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_skycor_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 ;
}


/**
  @brief    Execute the plugin instance given by the interface
  @param    config  parameter configuration
  @param    set     input data set
  @return   0 if everything is ok
 */
/*---------------------------------------------------------------------------*/
static int 
sinfo_utl_skycor(cpl_parameterlist * config, cpl_frameset* set)
{

    cpl_frame* obj_frm=NULL;
    cpl_frame* sky_frm=NULL;
    cpl_imagelist* obj_cor=NULL;
    const char *   name_o=NULL ;
    cpl_frame* product_frame=NULL;

    cpl_propertylist* plist=NULL;
    sinfo_skycor_qc* sqc=NULL;
    char obj_tag[MAX_NAME_SIZE];
    cpl_table* int_obj=NULL;

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


    ck0(sinfo_dfs_set_groups(set),"Cannot indentify RAW and CALIB frames") ;


    // get input data
    obj_frm=cpl_frameset_find(set,PRO_OBS_OBJ);
    if(obj_frm == NULL) {
        obj_frm=cpl_frameset_find(set,PRO_OBS_PSF);
        strcpy(obj_tag,PRO_OBS_PSF);
    } else {
        strcpy(obj_tag,PRO_OBS_OBJ);
    }


    if(obj_frm == NULL) {
        obj_frm=cpl_frameset_find(set,PRO_OBS_STD);
        strcpy(obj_tag,PRO_OBS_STD);
    }
    cknull(obj_frm,"No %s or %s or %s frame found",
           PRO_OBS_OBJ,PRO_OBS_PSF,PRO_OBS_STD);
    check(sky_frm=cpl_frameset_find(set,PRO_OBS_SKY),
          "No %s found",PRO_OBS_SKY);
    sqc=sinfo_skycor_qc_new();

    check(plist=cpl_propertylist_load(cpl_frame_get_filename(obj_frm),0),
          "Cannot read the FITS header") ;

    ck0(sinfo_skycor(config, obj_frm,sky_frm,sqc,&obj_cor,&int_obj),
        "determining sky residuals corrected object");
    sinfo_msg("Write out adjusted cube");
    /* Set the file name */

    cpl_frameset_erase(set,obj_tag);
    cpl_frameset_erase(set,PRO_OBS_SKY);
    name_o = "out_obj_cor.fits" ;


    /* Create product frame */
    check_nomsg(product_frame = cpl_frame_new());
    check_nomsg(cpl_frame_set_filename(product_frame, name_o)) ;
    check_nomsg(cpl_frame_set_tag(product_frame, obj_tag)) ;
    check_nomsg(cpl_frame_set_type(product_frame, CPL_FRAME_TYPE_IMAGE)) ;
    check_nomsg(cpl_frame_set_group(product_frame, CPL_FRAME_GROUP_PRODUCT)) ;
    check(cpl_frame_set_level(product_frame, CPL_FRAME_LEVEL_FINAL),
          "Error while initialising the product frame") ;
    // Add DataFlow keywords

    /*
    check(plist=cpl_propertylist_load(name_o,0),
          "Cannot read the FITS header") ;
    check_nomsg(cpl_propertylist_erase_regexp(plist, "^ESO PRO CATG",0));
    check(cpl_dfs_setup_product_header(plist, 
                                       product_frame, 
                                       set, 
                                       parlist,
                                       "sinfo_utl_skycor", 
                                       "SINFONI", 
                                       KEY_VALUE_HPRO_DID),
        "Problem in the product DFS-compliance") ;
     */

    //save the file

    check(cpl_imagelist_save(obj_cor,
                    name_o,
                    CPL_BPP_IEEE_FLOAT,
                    plist,
                    CPL_IO_DEFAULT),
          "Could not save product");
    // Log the saved file in the input frameset
    check_nomsg(cpl_frameset_insert(set,cpl_frame_duplicate(product_frame))) ;
    sinfo_free_frame(&product_frame);
    /*
  ck0(sinfo_pro_save_ims(obj_cor,set,set,"out_obj_cor.fits",
             PRO_OBS_OBJ,NULL,cpl_func,config),
      "cannot dump cube %s", "obj_cub.fits");
     */




    sinfo_free_imagelist(&obj_cor);



    name_o = "out_obj_int.fits" ;

    /* Create product frame */
    check_nomsg(product_frame = cpl_frame_new());
    check_nomsg(cpl_frame_set_filename(product_frame, name_o)) ;
    check_nomsg(cpl_frame_set_tag(product_frame, PRO_SPECTRA_QC)) ;
    check_nomsg(cpl_frame_set_type(product_frame, CPL_FRAME_TYPE_TABLE)) ;
    check_nomsg(cpl_frame_set_group(product_frame, CPL_FRAME_GROUP_PRODUCT)) ;
    check(cpl_frame_set_level(product_frame, CPL_FRAME_LEVEL_FINAL),
          "Error while initialising the product frame") ;
    check_nomsg(cpl_propertylist_update_string(plist, "ESO PRO CATG",
                    PRO_SPECTRA_QC));


    /* Add DataFlow keywords */
    /*    
    check(plist=cpl_propertylist_load(name_o,0),
          "Cannot read the FITS header") ;

    check_nomsg(cpl_propertylist_erase_regexp(plist, "^ESO PRO CATG",0));
    check(cpl_dfs_setup_product_header(plist, 
                                       product_frame, 
                                       set, 
                                       parlist,
                                       "sinfo_utl_skycor", 
                                       "SINFONI", 
                                       KEY_VALUE_HPRO_DID),
      "Problem in the product DFS-compliance") ;
     */

    /* Save the file */
    check(cpl_table_save(int_obj, plist, NULL, name_o,CPL_IO_DEFAULT),
          "Could not save product");
    sinfo_free_propertylist(&plist) ;

    /* Log the saved file in the input frameset */
    check_nomsg(cpl_frameset_insert(set, cpl_frame_duplicate(product_frame))) ;
    sinfo_free_frame(&product_frame);




    cleanup:
    sinfo_free_imagelist(&obj_cor);
    sinfo_free_table(&int_obj);
    sinfo_skycor_qc_delete(&sqc);
    sinfo_free_propertylist(&plist);
    sinfo_free_frame(&product_frame);
    if (cpl_error_get_code() != CPL_ERROR_NONE) {
        return -1;
    } else {
        return 0;
    }


}
/**@}*/
