/* $Id: sinfo_utl_cube_combine.c,v 1.20 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.20 $
 * $Name: not supported by cvs2svn $
 */

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

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

#include "sinfo_utl_cube_combine.h"
#include "sinfo_utilities.h"
#include "sinfo_utilities_scired.h"
#include <stdio.h>
#include "sinfo_key_names.h"
#include "sinfo_error.h"
#include "sinfo_utils_wrappers.h"
#include "sinfo_pro_save.h"
/*-----------------------------------------------------------------------------
                            Functions prototypes
 ----------------------------------------------------------------------------*/


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


/*-----------------------------------------------------------------------------
                                Functions code
 ----------------------------------------------------------------------------*/
/**@{*/
/**
 * @addtogroup sinfo_utl_cube_combine Utility to combine cubes
 *
 * 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_cube_combine(
        cpl_parameterlist   *   parlist, 
        cpl_frameset        *   framelist)
{
    cpl_parameter       *   param=NULL ;
    const char                *   name_o=NULL ;
    const char                *   name_i=NULL ;
    const char                *   name_m=NULL ;
   
    cpl_propertylist    *   plist=NULL ;
    cpl_image           *   image=NULL ;
    cpl_frame           *   product_frame=NULL;
    cpl_frame           *   prod_frm=NULL;
    cpl_frame           *   frame=NULL;
  
    int z=0;
    int z_min=0;
    int z_max=0;
    int z_siz=0;
    int z_stp=100;
    /* not used later
    int xsize=0;
    int ysize=0;
    */
    int scales_sky=0;

    int i=0;
    int j=0;
    int n=0;

    int size_x=0;
    int size_y=0;
    cpl_image* j_img=NULL;
    cpl_image* m_img=NULL;
 
    cpl_imagelist ** cube_object=NULL;
    cpl_imagelist * cube_jitter=NULL;
    cpl_imagelist * cube_mask=NULL;
 
    const char**    files=NULL;
    int nframes=0;

    double * times=NULL;
    float * offsetx=NULL;
    float * offsety=NULL;
    float  ref_offx=0;
    float  ref_offy=0;
    float tmpoffx=0;
    float tmpoffy=0;
    double kappa=2;
    int ks_clip=0;
    int min_size_x=9999;
    int min_size_y=9999;
    const char* name=NULL;

 
    FILE* file_list=NULL;
    int cnt=0;
    int onp=0;
  
    /* HOW TO RETRIEVE INPUT PARAMETERS */
    /* --stropt */
    check_nomsg(param = cpl_parameterlist_find(parlist, 
                        "sinfoni.sinfo_utl_cube_combine.ks_clip"));
    check_nomsg(ks_clip = cpl_parameter_get_bool(param));

    check_nomsg(param = cpl_parameterlist_find(parlist, 
                        "sinfoni.sinfo_utl_cube_combine.scale_sky"));
    check_nomsg(scales_sky = cpl_parameter_get_bool(param));


    check_nomsg(param = cpl_parameterlist_find(parlist, 
                        "sinfoni.sinfo_utl_cube_combine.kappa"));
    check_nomsg(kappa = cpl_parameter_get_double(param));

    check_nomsg(param = cpl_parameterlist_find(parlist, 
                        "sinfoni.sinfo_utl_cube_combine.name_i"));
    check_nomsg(name_i = cpl_parameter_get_string(param));

    check_nomsg(param = cpl_parameterlist_find(parlist, 
                        "sinfoni.sinfo_utl_cube_combine.name_o"));
    check_nomsg(name_o = cpl_parameter_get_string(param));


    /* not used later
    check_nomsg(param = cpl_parameterlist_find(parlist,
                        "sinfoni.sinfo_utl_cube_combine.xsize"));
    check_nomsg(xsize = cpl_parameter_get_int(param));

    check_nomsg(param = cpl_parameterlist_find(parlist,
                        "sinfoni.sinfo_utl_cube_combine.ysize"));
    check_nomsg(ysize = cpl_parameter_get_int(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 */
    n=cpl_frameset_get_size(framelist);
    if(n<1) {
      sinfo_msg_error("Empty input frame list!");
      goto cleanup ;
    }
    for (i=0;i<n;i++) {
       frame=cpl_frameset_get_frame(framelist,i);
       cpl_frame_set_group(frame,CPL_FRAME_GROUP_RAW);
    }

   

    /* Now performing the data reduction */
    /* Let's generate one image for the example */
    
    if ( NULL == (file_list = fopen (name_i, "r" ) ) )
    {      
      sinfo_msg_error("cannot open %s\n", name_i) ;
      goto cleanup ;
    }
 
    cnt = 0 ;
    while ( fscanf( file_list, "%10f %10f",&tmpoffx, &tmpoffy) != EOF )
    {
      cnt ++ ;
    }
    fclose(file_list);
   
    nframes= cnt ;
    cknull(times = (double*) cpl_calloc (nframes, sizeof (double)), 
           " could not allocate memory!") ;
 
    cknull(offsetx = (float*) cpl_calloc (nframes, sizeof(float)),
           " could not allocate memory!") ;

    cknull(offsety = (float*) cpl_calloc (nframes, sizeof(float)),
           " could not allocate memory!") ;
  
    files = (const char**) cpl_calloc(MAX_NAME_SIZE,sizeof(const char*));
    if ( NULL == (file_list = fopen (name_i, "r" ) ) )
    {
        if(files != NULL) {
          cpl_free(files);
          files=NULL;
        }
      sinfo_msg_error("cannot open %s\n", name_i) ;
      return -1 ;
    }


    cnt=0;   
    while ( fscanf( file_list, "%f %f",&tmpoffx,&tmpoffy ) != EOF ) {
      frame=cpl_frameset_get_frame(framelist,cnt);
      files[cnt]= cpl_frame_get_filename(frame);
      times[cnt]=sinfo_pfits_get_exptime(files[cnt]);
      offsetx[cnt]=tmpoffx;
      offsety[cnt]=tmpoffy;
      plist=cpl_propertylist_load(files[cnt],0);
      size_x=sinfo_pfits_get_naxis1(plist);
      size_y=sinfo_pfits_get_naxis2(plist);
      sinfo_free_propertylist(&plist);
      if(size_x < min_size_x) min_size_x=size_x;
      if(size_y < min_size_y) min_size_y=size_y;
      cnt ++ ;
    }
    sinfo_msg("Min input cube size x=%d y=%d",min_size_x,min_size_y);
 
    nframes=cnt;
    fclose(file_list);
 
    ck0(sinfo_auto_size_cube(offsetx,offsety,nframes,
                              &ref_offx,&ref_offy,&size_x,&size_y),
         "Error resizing cube");
    sinfo_msg("output ima size=%dx%d",size_x,size_y); 
    cknull(cube_object = cpl_calloc(nframes,sizeof(cpl_imagelist*)),
       "could not allocate memory") ;
 
    for (i=0;i<nframes;i++) {
      frame=cpl_frameset_get_frame(framelist,i);
      name=cpl_frame_get_filename(frame);
      check_nomsg(cube_object[i]=cpl_imagelist_load(name,CPL_TYPE_FLOAT,0));
      ck0(sinfo_new_assign_offset2(i,name,offsetx,offsety,
                                  ref_offx,ref_offy),
                                  "Error assigning offsets");
    }
    onp = cpl_imagelist_get_size(cube_object[0]);


    check(cube_jitter = cpl_imagelist_new(),"allocating new data cube object");
    check(cube_mask = cpl_imagelist_new(),"allocating new data cube mask");

    check(plist=cpl_propertylist_load(files[0],0),
      "Cannot read the FITS header") ;

   if(scales_sky == 1) {
      sinfo_msg("Subtract spatial sinfo_median to each cube plane");
      for(n=0;n<nframes;n++) {
    sinfo_msg("process cube %d\n",n);
    sinfo_new_sinfoni_correct_median_it(&(cube_object[n]));
      }
    }

   for(z=0;z<onp;z+=z_stp) {
     z_siz=(z_stp < (onp-z)) ? z_stp : (onp-z);
     z_min=z;
     z_max=z_min+z_siz;
     sinfo_msg("Coadding cubes: range [%4.4d,%4.4d) of 0-%d\n",
	       z_min,z_max,onp);

     for(j=z_min;j<z_max;j++) {

       check_nomsg(j_img=cpl_image_new(size_x,size_y,CPL_TYPE_FLOAT));
       check_nomsg(cpl_imagelist_set(cube_jitter,j_img,j));
       check_nomsg(m_img = cpl_image_new(size_x,size_y,CPL_TYPE_FLOAT));
       check_nomsg(cpl_imagelist_set(cube_mask,m_img,j));
     }
     if(ks_clip == 1){
       sinfo_new_combine_jittered_cubes_thomas_range(cube_object,
						     cube_jitter,
						     cube_mask,
						     nframes,
						     offsetx,offsety,
						     times,
						     (char*) "tanh",
						     z_min,
						     z_max,
						     kappa);
     } else {
       sinfo_new_combine_jittered_cubes_range(cube_object, 
					      cube_jitter,
					      cube_mask,
					      nframes,
					      offsetx,
					      offsety,
					      times,
					      (char*) "tanh",
					      z_min,
					      z_max) ;
     }
      
   }
   sinfo_new_convert_0_to_ZERO_for_cubes(cube_jitter) ; 
 
    name_m="out_cube_mask.fits";
     /* 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_CUBE_COMBINE_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_nomsg(cpl_frame_set_level(product_frame, CPL_FRAME_LEVEL_FINAL)) ;
      
    /* Add DataFlow keywords */
    check(cpl_dfs_setup_product_header(plist, product_frame, 
                                       framelist, parlist,
                                       "sinfo_utl_cube_combine", 
                                       "SINFONI", KEY_VALUE_HPRO_DID,NULL),
      "Problem in the product DFS-compliance") ;

    check(cpl_imagelist_save(cube_jitter, name_o, CPL_BPP_IEEE_FLOAT, plist,
                 CPL_IO_DEFAULT),"Could not save product");
    check_nomsg(cpl_frameset_insert(framelist, product_frame));
    
   
    check_nomsg(prod_frm = cpl_frame_new());
    check_nomsg(cpl_frame_set_filename(prod_frm, name_m)) ;
    check_nomsg(cpl_frame_set_tag(prod_frm, SI_UTL_CUBE_COMBINE_PROMASK)) ;
    check_nomsg(cpl_frame_set_type(prod_frm, CPL_FRAME_TYPE_IMAGE)) ;
    check_nomsg(cpl_frame_set_group(prod_frm, CPL_FRAME_GROUP_PRODUCT)) ;
    check_nomsg(cpl_frame_set_level(prod_frm, CPL_FRAME_LEVEL_FINAL)) ;

    check(cpl_imagelist_save(cube_mask, name_m, CPL_BPP_IEEE_FLOAT, plist,
                 CPL_IO_DEFAULT),"Could not save product");
    check_nomsg(cpl_frameset_insert(framelist, prod_frm));
    
 cleanup:
    sinfo_free_imagelist(&cube_jitter) ;
    sinfo_free_image(&image) ;
    sinfo_free_imagelist(&cube_mask) ;


    if(cube_object != NULL) {
      for (i=0;i< nframes;i++){
    sinfo_free_imagelist(&(cube_object[i]));      
      }
      sinfo_free_array_imagelist(&cube_object);
    }
    sinfo_free_propertylist(&plist);
    if(files != NULL) {
      cpl_free(files);
      files=NULL;
    }
    sinfo_free_double(&times);
    sinfo_free_float(&offsetx);
    sinfo_free_float(&offsety);
 
    /* Return */
    if (cpl_error_get_code()) {
        return -1 ;
    }
    else { 
        return 0 ;
    }
}
/**@}*/
