/* $Id: sinfo_utl_cube_arith.c,v 1.14 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.14 $
 * $Name: not supported by cvs2svn $
 */


#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif
/*----------------------------------------------------------------------------
                                Includes
 ----------------------------------------------------------------------------*/

#include "sinfo_utl_cube_arith.h"
#include <sinfo_spectrum_ops.h>
#include <sinfo_new_cube_ops.h>
#include "sinfo_key_names.h"
#include "sinfo_pro_types.h"
#include <sinfo_error.h>
#include <sinfo_utilities.h>
#include <sinfo_utils_wrappers.h>



/*-----------------------------------------------------------------------------
                            Functions prototypes
 ----------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------
                            Static variables
 ----------------------------------------------------------------------------*/

/**@{*/
/**
 * @addtogroup sinfo_utl_cube_arith Cube arithmetics
 *
 * TBD
 */

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

/*---------------------------------------------------------------------------*/
/**
  @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_cube_arith(
                cpl_parameterlist   *   parlist,
                cpl_frameset        *   framelist)
{
    cpl_parameter       *   param =NULL;
    const char          *   operation =NULL;
    const char          *   name_c =NULL;
    const char          *   name_s =NULL;
    const char          *   name_o =NULL;
    const char          *   name_d ="start";

    /* double                  temp=0 ; */
    double                  value=0 ;
    double                  def_value=0 ;

    cpl_parameter *         p=NULL;
    cpl_frame           *   frm_cube=NULL ;
    cpl_frame           *   frm_spct=NULL ;

    cpl_propertylist    *   plist=NULL ;
    cpl_image           *   image=NULL ;
    cpl_frame           *   product_frame=NULL;
    cpl_imagelist       *   cub_ims=NULL;
    cpl_imagelist * cube_i=NULL;
    cpl_imagelist * cube_o=NULL;
    cpl_imagelist * cube_d=NULL;
    cpl_image * std_star=NULL;
    Vector * bb=NULL;
    Vector*   spectrum=NULL;
    cpl_vector* vec=NULL;
    /* Identify the RAW and CALIB frames in the input frameset */
    check(sinfo_dfs_set_groups(framelist),
          "Cannot identify RAW and CALIB frames") ;


    /* HOW TO RETRIEVE INPUT PARAMETERS */
    /* --stropt */
    check_nomsg(param = cpl_parameterlist_find(parlist,
                    "sinfoni.sinfo_utl_cube_arith.op"));
    check_nomsg(operation = cpl_parameter_get_string(param));
    name_o = "out_cube.fits";


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

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

    check_nomsg(name_c = cpl_frame_get_filename(frm_cube));
    check_nomsg(p = cpl_parameterlist_find(parlist,
                    "sinfoni.sinfo_utl_cube_arith.value"));
    check_nomsg(def_value = cpl_parameter_get_default_double(p));
    if (value == def_value) {
        if ((frm_spct = cpl_frameset_find(framelist,
                        SI_UTL_CUBE_ARITH_SPECTRUM))==NULL) {
            sinfo_msg( "SOF does not have a file tagged as %s",
                            SI_UTL_CUBE_ARITH_SPECTRUM);
            cpl_error_reset();
        } else {
            sinfo_msg( "SOF contains a file tagged as %s",
                            SI_UTL_CUBE_ARITH_SPECTRUM);
            name_s = cpl_frame_get_filename(frm_spct);
            name_d = "spectrum";
        }
    }

    if (value == def_value) {
        if ((frm_spct = cpl_frameset_find(framelist, PRO_SPECTRUM))!=NULL) {
            sinfo_msg( "SOF contains a file tagged as %s",PRO_SPECTRUM);
            name_s = cpl_frame_get_filename(frm_spct);
            name_d = "spectrum";
        } else if ((frm_spct = cpl_frameset_find(framelist, PRO_IMA))!=NULL) {
            sinfo_msg( "SOF contains a file tagged as %s",PRO_IMA);
            name_s = cpl_frame_get_filename(frm_spct);
            name_d = "image";
        } else {
            sinfo_msg( "SOF does not contains a file tagged as %s nor as %s",
                            PRO_SPECTRUM,PRO_IMA);
            sinfo_msg( "Assume operation by a constant");
            cpl_error_reset();
        }
    }
    check(plist=cpl_propertylist_load(cpl_frame_get_filename(frm_cube),0),
          "Cannot read the FITS header") ;


    /* Now performing the data reduction */
    /* Let's generate one image for the example */
    check_nomsg(cube_i= cpl_imagelist_load((char*)name_c,CPL_TYPE_FLOAT,0));
    if (value == def_value) {
        sinfo_msg("value equal to default");
        if( strcmp(name_d,"spectrum") == 0 ) {
            sinfo_msg("Operation by spectrum");
            sinfo_msg("loading spectrum image file %s",name_s);
            check_nomsg(std_star=cpl_image_load((char*)name_s,CPL_TYPE_FLOAT,0,0));

            //check_nomsg(std_star=sinfo_vector_to_image(vec,CPL_TYPE_FLOAT));
            check_nomsg(spectrum  = sinfo_new_image_to_vector(std_star));
            if (strcmp(operation,"/") == 0) {
                cube_o = sinfo_new_div_cube_by_spectrum (cube_i, spectrum);
            } else if (strcmp(operation,"-") == 0) {
                cube_o = sinfo_new_sub_spectrum_from_cube(cube_i, spectrum);
            } else if (strcmp(operation,"+") == 0) {
                cube_o = sinfo_new_add_spectrum_to_cube(cube_i, spectrum);
            } else if (strcmp(operation,"*") == 0) {
                cube_o = sinfo_new_mul_spectrum_to_cube(cube_i, spectrum);
                /*
              } else if (strcmp(operation,"calib") == 0) {
              bb = sinfo_new_blackbody_spectrum ((char*)name_s, temp); 
              cube_d   = sinfo_new_div_cube_by_Spectrum (cube_i, spectrum);
              cube_o = sinfo_new_mul_spectrum_to_cube(cube_d, bb); 
                 */

            } else {
                sinfo_msg_error("operation %s not supported",operation);
                sinfo_msg("If an input spectrum is given and no value is set");
                sinfo_msg("operations supported are: `/`,`-`,`+`,'*'");
                goto cleanup;
            }
            if (strcmp(operation,"calib") == 0) {
                goto cleanup;
            }
        } else if ( strcmp(name_d,"image") == 0) {
            sinfo_msg("Operation by image");
            check_nomsg(std_star=cpl_image_load ((char*)name_s,
                            CPL_TYPE_FLOAT,0,0));
            if(strcmp(operation,"+") == 0) {
                cknull(cube_o = sinfo_new_add_image_to_cube(cube_i,std_star),
                                "operation %s failed",operation);
            } else if (strcmp(operation,"-") == 0) {
                cknull(cube_o = sinfo_new_sub_image_from_cube(cube_i,std_star),
                                "operation %s failed",operation);
            } else if (strcmp(operation,"*") == 0) {
                cknull(cube_o = sinfo_new_mul_image_to_cube(cube_i,std_star),
                                "operation %s failed",operation);
            } else if (strcmp(operation,"/") == 0) {
                cknull(cube_o = sinfo_new_div_cube_by_image(cube_i,std_star),
                                "operation %s failed",operation);
            } else {
                sinfo_msg_error("operation %s not supported",operation);
                sinfo_msg("If an input image is set");
                sinfo_msg("operations supported are: `-`, `+`, `*`, `/`");
                goto cleanup;
            }
        } else {
            sinfo_msg("Operation %s by constant",operation);

            check_nomsg(cube_o = cpl_imagelist_duplicate(cube_i));

            if(strcmp(operation,"+") == 0) {
                check(cpl_imagelist_add_scalar(cube_o,value),
                                "operation %s failed",operation);
            } else if (strcmp(operation,"-") == 0) {
                check(cpl_imagelist_subtract_scalar(cube_o,value),
                                "operation %s failed",operation);
            } else if (strcmp(operation,"*") == 0) {
                check(cpl_imagelist_multiply_scalar(cube_o,value),
                                "operation %s failed",operation);
            } else if (strcmp(operation,"/") == 0) {
                check(cpl_imagelist_divide_scalar(cube_o,value),
                                "operation %s failed",operation);
            } else {
                sinfo_msg_error("operation %s not supported",operation);
                sinfo_msg("If an input value is set");
                sinfo_msg("operations supported are: `-`, `+`, `*`, `/`");
                goto cleanup;
            }

        } /* env case op by constant && value == default */

    } else {

        sinfo_msg("Operation %s by constant",operation);

        check_nomsg(cube_o = cpl_imagelist_duplicate(cube_i));

        if(strcmp(operation,"+") == 0) {
            check(cpl_imagelist_add_scalar(cube_o,value),
                            "operation %s failed",operation);
        } else if (strcmp(operation,"-") == 0) {
            check(cpl_imagelist_subtract_scalar(cube_o,value),
                            "operation %s failed",operation);
        } else if (strcmp(operation,"*") == 0) {
            check(cpl_imagelist_multiply_scalar(cube_o,value),
                            "operation %s failed",operation);
        } else if (strcmp(operation,"/") == 0) {
            check(cpl_imagelist_divide_scalar(cube_o,value),
                            "operation %s failed",operation);
        } else {
            sinfo_msg_error("operation %s not supported",operation);
            sinfo_msg("If an input value is set");
            sinfo_msg("operations supported are: `-`, `+`, `*`, `/`");
            goto cleanup;
        }

    }
    /* HOW TO SAVE A PRODUCT ON DISK  */
    /* Set the file name */
    /* 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_CUBE_ARITH_PROCUBE)) ;
    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_cube_arith",
                    "SINFONI", KEY_VALUE_HPRO_DID,NULL),
          "Problem in the product DFS-compliance") ;

    /* Save the file */
    check(cpl_imagelist_save(cube_o, 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(framelist, product_frame)) ;



    cleanup:
    sinfoni_free_vector(&vec);
    sinfo_free_svector(&spectrum);
    sinfo_free_svector(&bb);

    sinfo_free_imagelist(&cube_d);
    sinfo_free_imagelist(&cube_i);
    sinfo_free_imagelist(&cube_o);
    //If I free the next image I get core dump!
    //sinfo_free_image(&std_star);
    sinfo_free_image(&image);
    sinfo_free_imagelist(&cub_ims);
    sinfo_free_propertylist(&plist);

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