/* $Id: sinfo_utl_cube2ima.c,v 1.8 2012-03-03 10:17:31 amodigli Exp $
 *
 * This file is part of the IIINSTRUMENT 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: 2012-03-03 10:17:31 $
 * $Revision: 1.8 $
 * $Name: not supported by cvs2svn $
 */

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

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

#include "sinfo_functions.h"
#include "sinfo_new_cube_ops.h"
#include "sinfo_utl_cube2ima.h"
#include "sinfo_key_names.h"
#include <sinfo_error.h>
#include <sinfo_utils_wrappers.h>

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



/*-----------------------------------------------------------------------------
                            Static variables
 -----------------------------------------------------------------------------*/

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

/**@{*/
/**
 * @addtogroup sinfo_utl_cube2ima Cube to image transformation
 *
 * TBD
 */

/*----------------------------------------------------------------------------*/
/**
  @brief    Get the command line options and execute the data reduction
  @param    parlist     the parameters list
  @param    framelist   the frames list
  @return   0 if everything is ok
 */
/*----------------------------------------------------------------------------*/
int sinfo_utl_cube2ima(
                cpl_parameterlist   *   parlist,
                cpl_frameset        *   framelist)
{
    cpl_parameter       *   param =NULL ;
    const char          *   name_i =NULL;
    const char          *   name_o =NULL;

    double                  ws=0 ;
    double                  we=0 ;
    double                  wc=0 ;
    double                  wd=0 ;


    int naxis3=0;
    double lams=0;
    double lame=0;

    cpl_frame           *   frm_cub=NULL ;

    cpl_propertylist    *   plist=NULL ;
    cpl_frame           *   product_frame=NULL;

    cpl_imagelist * cube=NULL;
    cpl_image * img=NULL;


    /* HOW TO RETRIEVE INPUT PARAMETERS */
    /* --stropt */
    name_o ="out_ima.fits";

    /* --doubleopt */
    check_nomsg(param = cpl_parameterlist_find(parlist,
                    "sinfoni.sinfo_utl_cube2ima.ws"));
    check_nomsg(ws = cpl_parameter_get_double(param)) ;

    /* --doubleopt */
    check_nomsg(param = cpl_parameterlist_find(parlist,
                    "sinfoni.sinfo_utl_cube2ima.we"));
    check_nomsg(we = cpl_parameter_get_double(param)) ;

    /* Identify the RAW and CALIB frames in the input frameset */
    check(sinfo_dfs_set_groups(framelist),
          "Cannot identify RAW and CALIB frames");

    /* HOW TO ACCESS INPUT DATA */
    check(frm_cub = cpl_frameset_find(framelist, SI_UTL_CUBE2IMA_CUBE),
          "SOF does not have a file tagged as %s",SI_UTL_CUBE2IMA_CUBE);

    check_nomsg(name_i = cpl_frame_get_filename(frm_cub));

    plist=cpl_propertylist_load(name_i,0);
    naxis3=sinfo_pfits_get_naxis3(plist);
    wd=sinfo_pfits_get_cdelt3(plist);
    wc=sinfo_pfits_get_crval3(plist);
    sinfo_free_propertylist(&plist);

    lams=wc-naxis3*wd/2+wd;
    lame=lams+(naxis3-2)*wd;

    check_nomsg(param = cpl_parameterlist_find(parlist,
                    "sinfoni.sinfo_utl_cube2ima.ws"));

    if(ws != cpl_parameter_get_default_double(param)) {
        if (ws < lams) {
            sinfo_msg_warning("ws =%f too low set it to %f",ws,lams);
            ws=lams;
        }
        else if (ws >= lame) {
            sinfo_msg_warning("ws =%f too high set it to %f",ws,lams);
            ws=lams;
        }
    } else {
        ws=lams;
    }

    check_nomsg(param = cpl_parameterlist_find(parlist,
                    "sinfoni.sinfo_utl_cube2ima.we"));
    if(we != cpl_parameter_get_default_double(param)) {
        if (we > lame) {
            sinfo_msg_warning("we =%f too low set it to %f",we,lame);
            we=lame;
        }
        else if (we <= lams) {
            sinfo_msg_warning("we =%f too low set it to %f",we,lame);
            we=lame;
        }
    } else {
        we=lame;
    }

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

    /* recipe's algorithm */
    check_nomsg(cube = cpl_imagelist_load((char*)name_i,CPL_TYPE_FLOAT,0));
    if(NULL==(img=sinfo_new_average_cube_to_image_between_waves(cube,wd,wc,
                    ws,we))) {
        sinfo_msg_error("Cannot average cube to image in wavelength "
                        "range [%f,%f] um",ws,we) ;

        sinfo_free_imagelist(&cube);
        sinfo_free_propertylist(&plist);

    }
    sinfo_free_imagelist(&cube);

    /* HOW TO SAVE A PRODUCT ON DISK  */
    /* 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, SI_UTL_CUBE2IMA_PROIMA)) ;
    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_nomsg(cpl_propertylist_erase_regexp(plist, "^ESO PRO CATG",0));
    check(cpl_dfs_setup_product_header(plist, 
                    product_frame,
                    framelist,
                    parlist,
                    "si_sinfo_utl_cube2ima",
                    "SINFONI",
                    KEY_VALUE_HPRO_DID,NULL),
          "Problem in the product DFS-compliance") ;

    /* Save the file */
    check_nomsg(cpl_propertylist_erase_regexp(plist, "^CTYPE3",0));
    check_nomsg(cpl_propertylist_erase_regexp(plist, "^CRPIX3",0));
    check_nomsg(cpl_propertylist_erase_regexp(plist, "^CRVAL3",0));
    check_nomsg(cpl_propertylist_erase_regexp(plist, "^CDELT3",0));
    check_nomsg(cpl_propertylist_erase_regexp(plist, "^CUNIT3",0));

    check(cpl_image_save(img, 
                    name_o,
                    CPL_BPP_IEEE_FLOAT,
                    plist,
                    CPL_IO_DEFAULT),
          "Could not save product");

    check_nomsg(sinfo_free_propertylist(&plist)) ;

    /* Log the saved file in the input frameset */
    check_nomsg(cpl_frameset_insert(framelist, product_frame)) ;
    check_nomsg(sinfo_free_image(&img)) ;

    /* Return */

    cleanup:
    sinfo_free_imagelist(&cube);
    sinfo_free_propertylist(&plist);
    sinfo_free_image(&img);

    if (cpl_error_get_code()) 
        return -1 ;
    else 
        return 0 ;
}
/**@}*/
