/*                                                                              *
 *   This file is part of the ESO UVES Pipeline                                 *
 *   Copyright (C) 2004,2005 European Southern Observatory                      *
 *                                                                              *
 *   This library 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, 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA       *
 *                                                                              */
 
/*
 * $Author: amodigli $
 * $Date: 2013-08-08 13:36:46 $
 * $Revision: 1.60 $
 * $Name: not supported by cvs2svn $
 * $Log: not supported by cvs2svn $
 * Revision 1.59  2013/07/29 12:38:25  amodigli
 * set med_dx, med_dy to proper values to have at least a model iteration on both chips (PIPE-4666)
 *
 * Revision 1.58  2013/07/01 15:37:10  amodigli
 * Rename DEBUG to debug_mode to remove compiler error on some platforms (that name is reserved to special compiler options)
 *
 * Revision 1.57  2010/09/27 08:00:41  amodigli
 * removed x_axis_scale and y_axis_scal params from interface as always kept constant
 *
 * Revision 1.56  2010/09/24 09:32:06  amodigli
 * put back QFITS dependency to fix problem spot by NRI on FIBER mode (with MIDAS calibs) data
 *
 * Revision 1.54  2010/08/30 14:17:20  amodigli
 * moved declaration product_filename variable up to eventually used to dump an extra QC product
 *
 * Revision 1.53  2010/06/15 15:46:26  amodigli
 * removed useless second call to uves_save_table_local of the same temporary product already saved
 *
 * Revision 1.52  2010/05/06 14:21:06  amodigli
 * increase mbox_x/y min to 10 to improve recipe robustness
 *
 * Revision 1.51  2010/05/01 16:01:27  amodigli
 * clearer error message
 *
 * Revision 1.50  2010/03/09 15:27:49  amodigli
 * removed generation of tmp product 'pippo4.fits'
 *
 * Revision 1.49  2010/03/01 18:17:22  amodigli
 * now model_prediction prediction table is generated only in debug mode
 *
 * Revision 1.48  2009/08/03 12:48:10  amodigli
 * some messaging to monitor physmodel shifts
 *
 * Revision 1.47  2009/07/13 07:56:21  amodigli
 * insert proper offsets for new CCD  echelle standard modes
 *
 * Revision 1.46  2009/07/13 06:38:41  amodigli
 * moved functions to get new CCD shifts in uves_physmod_create_table.c
 *
 * Revision 1.45  2009/04/27 08:32:59  amodigli
 * fixed trans_x/y setting in FIBER mode
 *
 * Revision 1.44  2009/04/14 07:02:07  amodigli
 * set explicit filename to distingush if physmod is executed on a normal formatcheck or on a reference one
 *
 * Revision 1.43  2008/09/29 06:58:03  amodigli
 * add #include <string.h>
 *
 * Revision 1.42  2008/05/01 09:57:03  amodigli
 * fixed compiler warnings
 *
 * Revision 1.41  2008/05/01 09:46:06  amodigli
 * modify x-y shift (if flames) if trans_x/y are set
 *
 * Revision 1.40  2008/02/15 12:43:49  amodigli
 * allow lower/upper chip for parameter process_chip
 *
 * Revision 1.39  2007/12/05 14:12:43  amodigli
 * if stability_cnt=0 does not do certain steps as in MIDAS
 *
 * Revision 1.38  2007/12/03 17:00:14  amodigli
 * removed dependency from flames and fixed a warning
 *
 * Revision 1.37  2007/12/03 10:43:00  amodigli
 * added flames_get_physmod_shift and set itermax to 1 to fix problems on flames-uves
 *
 * Revision 1.36  2007/10/23 07:37:43  amodigli
 * if provided subtract MASTER_BIAS from input raw and reference formatchecks
 *
 * Revision 1.35  2007/10/05 16:01:45  amodigli
 * using proces_chip parameter to process or not a given RED chip
 *
 * Revision 1.34  2007/08/21 13:08:26  jmlarsen
 * Removed irplib_access module, largely deprecated by CPL-4
 *
 * Revision 1.33  2007/08/10 15:24:11  amodigli
 * fixed seg fault with flames-uves
 *
 * Revision 1.32  2007/06/26 15:08:17  amodigli
 * changes to make work flames and uves physmod in simple way
 *
 * Revision 1.31  2007/06/22 09:30:22  jmlarsen
 * Changed interface of uves_save_image
 *
 * Revision 1.30  2007/06/13 15:13:48  amodigli
 * fixed mem leaks in case of fiber mode data
 *
 * Revision 1.29  2007/06/06 08:17:33  amodigli
 * replace tab with 4 spaces
 *
 * Revision 1.28  2007/05/22 14:34:32  jmlarsen
 * Removed unnecessary includes
 *
 * Revision 1.27  2007/05/14 09:38:38  amodigli
 * removed call to irplib_error_dump
 *
 * Revision 1.26  2007/04/25 08:38:40  amodigli
 * chnaged interface uves_physmod_plotmod
 *
 * Revision 1.25  2007/04/24 14:08:53  jmlarsen
 * Log more QC parameters (DFS03805)
 *
 * Revision 1.24  2007/04/24 12:50:29  jmlarsen
 * Replaced cpl_propertylist -> uves_propertylist which is much faster
 *
 * Revision 1.23  2007/04/14 05:55:19  amodigli
 * warning of flames,iter demoted to debug message
 *
 * Revision 1.22  2007/04/12 12:03:10  jmlarsen
 * Fixed doc. typo
 *
 * Revision 1.21  2007/03/05 10:18:55  jmlarsen
 * Do QC-log INS.SLITi.WID
 *
 * Revision 1.20  2007/02/26 10:16:22  jmlarsen
 * Do not QC log slit width
 *
 * Revision 1.19  2007/01/15 14:28:44  jmlarsen
 * Write default stability QC-parameters, only when master frame is provided
 *
 * Revision 1.18  2007/01/15 08:43:15  jmlarsen
 * Fixed missing plots
 *
 * Revision 1.17  2007/01/13 09:52:22  amodigli
 * fixed some problems on flames QC log
 *
 * Revision 1.16  2007/01/09 17:46:03  amodigli
 * fixed a problem in echelle mode
 *
 * Revision 1.15  2007/01/08 16:59:18  amodigli
 * changes to make flames-uves iterations to recover physical model
 *
 * Revision 1.14  2006/12/07 08:26:04  jmlarsen
 * Added uves_pfits_get_readspeed
 *
 * Revision 1.13  2006/12/01 12:29:21  jmlarsen
 * Factored out FLAMES plate-id code
 *
 * Revision 1.12  2006/11/22 08:42:20  jmlarsen
 * Set traceid = 1, not 0 for UVES
 *
 * Revision 1.10  2006/11/22 08:22:29  jmlarsen
 * Set message level according to preprocessor symbol
 *
 * Revision 1.9  2006/11/16 14:12:21  jmlarsen
 * Changed undefined trace number from 0 to -1, to support zero as an actual trace number
 *
 * Revision 1.8  2006/11/16 09:49:25  jmlarsen
 * Fixed doxygen bug
 *
 * Revision 1.7  2006/11/15 15:02:14  jmlarsen
 * Implemented const safe workarounds for CPL functions
 *
 * Revision 1.5  2006/11/15 14:04:08  jmlarsen
 * Removed non-const version of parameterlist_get_first/last/next which is already
 * in CPL, added const-safe wrapper, unwrapper and deallocator functions
 *
 * Revision 1.4  2006/11/06 15:19:41  jmlarsen
 * Removed unused include directives
 *
 * Revision 1.3  2006/10/26 14:03:48  jmlarsen
 * Fixed position of const modifier
 *
 * Revision 1.2  2006/10/25 11:43:32  amodigli
 * fixed problem running physmod in debug mode
 *
 * Revision 1.1  2006/10/24 14:09:56  jmlarsen
 * Factored out common UVES/FLAMES code
 *
 * Revision 1.30  2006/10/19 13:53:25  jmlarsen
 * Changed guess line table tag to LINE_GUESS_TAB
 *
 * Revision 1.29  2006/10/17 12:33:02  jmlarsen
 * Added semicolon at UVES_RECIPE_DEFINE invocation
 *
 * Revision 1.28  2006/10/11 12:22:36  amodigli
 * now the stability check consist only i the msrawxy and the table comparison, as in MIDAS
 *
 * Revision 1.27  2006/10/09 13:01:13  jmlarsen
 * Use macro to define recipe interface functions
 *
 * Revision 1.26  2006/09/19 14:31:38  jmlarsen
 * uves_insert_frame(): use bitmap to specify which image statistics keywords must be computed
 *
 * Revision 1.25  2006/09/19 06:55:39  jmlarsen
 * Changed interface of uves_frameset to optionally write image statistics kewwords
 *
 * Revision 1.24  2006/08/24 11:36:37  jmlarsen
 * Write recipe start/stop time to header
 *
 * Revision 1.23  2006/08/18 13:35:42  jmlarsen
 * Fixed/changed QC parameter formats
 *
 * Revision 1.22  2006/08/17 13:56:53  jmlarsen
 * Reduced max line length
 *
 * Revision 1.21  2006/08/11 14:56:05  amodigli
 * removed Doxygen warnings
 *
 * Revision 1.20  2006/08/07 11:35:35  jmlarsen
 * Disabled parameter environment variable mode
 *
 * Revision 1.19  2006/08/01 14:42:34  amodigli
 * fixed bugs getting raw header from master formatcheck
 *
 * Revision 1.18  2006/07/31 06:29:26  amodigli
 * added QC on stability test
 *
 * Revision 1.17  2006/07/28 14:51:26  amodigli
 * fixed some bugs on improper table selection
 *
 * Revision 1.16  2006/07/14 12:19:28  jmlarsen
 * Support multiple QC tests per product
 *
 * Revision 1.15  2006/07/03 12:46:34  amodigli
 * updated description
 *
 * Revision 1.14  2006/06/28 13:28:29  amodigli
 * improved output
 *
 * Revision 1.13  2006/06/20 09:06:39  amodigli
 * correct input tag info in man page
 *
 * Revision 1.12  2006/06/16 08:25:45  jmlarsen
 * Manually propagate ESO.DET. keywords from 1st/2nd input header
 *
 * Revision 1.11  2006/06/13 11:57:02  jmlarsen
 * Check that calibration frames are from the same chip ID
 *
 * Revision 1.10  2006/06/07 13:06:28  jmlarsen
 * Changed doxygen tag addtogroup -> defgroup
 *
 * Revision 1.9  2006/06/07 09:01:28  amodigli
 * added some doc
 *
 * Revision 1.8  2006/05/08 15:42:16  amodigli
 * allow to specify order column label
 *
 * Revision 1.7  2006/04/20 10:47:39  amodigli
 * added qclog
 *
 * Revision 1.6  2006/04/07 07:11:12  jmlarsen
 * Minor doc. fix
 *
 * Revision 1.5  2006/04/06 09:48:15  amodigli
 * changed uves_frameset_insert interface to have QC log
 *
 * Revision 1.4  2006/04/06 08:42:19  jmlarsen
 * Changed indentation
 *
 * Revision 1.3  2006/03/03 13:54:11  jmlarsen
 * Changed syntax of check macro
 *
 * Revision 1.2  2006/02/28 09:15:22  jmlarsen
 * Minor update
 *
 * Revision 1.1  2006/02/03 07:46:30  jmlarsen
 * Moved recipe implementations to ./uves directory
 *
 * Revision 1.66  2006/01/25 10:09:18  jmlarsen
 * Added doxygen end marker
 *
 * Revision 1.65  2006/01/20 10:36:25  amodigli
 *
 * Fixed warings from doxigen
 *
 * Revision 1.64  2006/01/19 10:03:06  amodigli
 * Fixed leaks
 *
 * Revision 1.62  2006/01/16 13:52:58  jmlarsen
 * Removed memory leak
 *
 * Revision 1.61  2006/01/16 08:01:57  amodigli
 *
 * Added stability check
 *
 * Revision 1.60  2006/01/13 13:43:15  jmlarsen
 * Removed memory leak
 *
 * Revision 1.59  2006/01/13 09:54:42  amodigli
 * Fixed some bugs: improved agreement with MIDAS version
 *
 * Revision 1.58  2006/01/09 15:23:06  jmlarsen
 * Removed some warnings
 *
 * Revision 1.57  2006/01/09 14:05:42  amodigli
 * Fixed doxigen warnings
 *
 * Revision 1.56  2006/01/03 16:57:13  amodigli
 * Fixed bug
 *
 * Revision 1.55  2006/01/03 14:47:53  amodigli
 *
 * Added uves_physmod_chop_otab.h .c to match MIDAS
 *
 * Revision 1.54  2005/12/19 16:17:55  jmlarsen
 * Replaced bool -> int
 *
 */
#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

/*----------------------------------------------------------------------------*/
/**
 * @addtogroup uves_physmod
 */
/*----------------------------------------------------------------------------*/

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

/* Self */
#include <uves_physmod_body.h>

/* called related functions */
#include <uves_physmod_plotmod.h>
#include <uves_physmod_create_table.h>

#include <uves_physmod_qc1pmtbl.h>
#include <uves_physmod_calmap.h>
#include <uves_physmod_msrawxy.h>
#include <uves_physmod_chop_otab.h>
#include <uves_physmod_stability_check.h>

/* Utility functions */
#include <uves_utils.h>
#include <uves_utils_polynomial.h>
#include <uves_utils_wrappers.h>
#include <uves_pfits.h>
#include <uves_dfs.h>
#include <uves_parameters.h>
#include <uves_qclog.h>
#include <uves_recipe.h>
#include <uves_error.h>
#include <uves_msg.h>
/* Library */
#include <cpl.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
/*-----------------------------------------------------------------------------
                                Defines
 -----------------------------------------------------------------------------*/

#define UVES_PHYSMOD_ITER_MAX 5
/*-----------------------------------------------------------------------------
                            Functions prototypes
 ----------------------------------------------------------------------------*/

static int 
uves_physmod_qclog(cpl_table* line_table,
		   cpl_table* order_table,
		   cpl_table* qclog,
		   const uves_propertylist *raw_header,
		   enum uves_chip chip,
                   bool flames,
                   const int iter,
                   const int plate_no);

static int 
uves_physmod_qclog_sc(const double med_dx, 
		      const double med_dy,
		      const double avg_dx,
                      const double avg_dy,
                      const uves_propertylist *raw_header,
                      const uves_propertylist *ref_header,
                      enum  uves_chip chip,
		      bool flames,
		      const int iter,
		      cpl_table* qclog);



static int
flames_get_physmod_shift(const int plate_no,
                         const int wavec,
                         enum uves_chip chip,
			 double* physmod_shift_x,
                         double* physmod_shift_y,
			 double* rot_1,
                         double* rot_2,
                         double* rot_3);


/*-----------------------------------------------------------------------------
                            Recipe standard code
 -----------------------------------------------------------------------------*/

const char * const uves_physmod_desc_short = "Implements the UVES physical model";
const char * const uves_physmod_desc =
"This recipe implements the UVES physical model\n"
"Input files are BLUE or RED arm formatcheck frames identified by the tag\n"
"ARC_LAMP_FORM_xxxx, xxxx=BLUE or RED and a ThAr line reference table\n"
"identified by the tag LINE_REFER_TABLE\n"
"The recipe extracts from the input files FITS header data indicating the\n"
"instrument setting and ambiental atmospheric conditions, then using the\n"
"model predicts X,Y position of the lines listed in the LINE_REFER_TABLE\n"
"table which are imaging on the detector and stores this information in an\n"
"guess order and a guess line table.\n"
"Output are a guess order table and a guess line table per chip.\n"
"If the user provides in input also master format checks having tag\n"
"MASTER_FORM_xxxx, xxxx=BLUE or REDL and REDU the recipe performs also a\n"
"stability check\n";

/**@{*/
/*-----------------------------------------------------------------------------
                            Functions code
 -----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------*/
/**
  @brief    Setup the recipe options    
  @param    parameters        the parameterlist to fill
  @return   0 if everything is ok
 */
/*----------------------------------------------------------------------------*/
int
uves_physmod_define_parameters_body(cpl_parameterlist *parameters, 
                                    const char *recipe_id)
{
    const char *subcontext = NULL;

    /*****************
     *    General    *
     *****************/

    if (uves_define_global_parameters(parameters) != CPL_ERROR_NONE)
    {
        return -1;
    }
    
    uves_par_new_range("mbox_x",
                 CPL_TYPE_INT,
                 "Match box X size",
                 40,10,100);

    uves_par_new_range("mbox_y",
                 CPL_TYPE_INT,
                 "Match box Y size",
                 40,10,100);

    uves_par_new_value("trans_x",
                 CPL_TYPE_DOUBLE,
                 "Detector translation along X",
                 0.);

    uves_par_new_value("trans_y",
                 CPL_TYPE_DOUBLE,
                 "Detector translation along Y",
                 0.);

    uves_par_new_value("ech_angle_off",
                 CPL_TYPE_DOUBLE,
                 "Offset on echelle angle",
                 0.);

    uves_par_new_value("cd_angle_off",
                 CPL_TYPE_DOUBLE,
                 "Offset on cross disperser angle",
                 0.);

    uves_par_new_value("ccd_rot_angle_off",
                 CPL_TYPE_DOUBLE,
                 "Offset on CCD rotation angle",
                 0.);

    uves_par_new_value("compute_regression_sw",
                 CPL_TYPE_BOOL,
                 "Compute regression?",
                 true);

/*  we decided to remove those params as we always have them set to 0
    uves_par_new_value("x_axis_scale",
                 CPL_TYPE_DOUBLE,
                 "Scale X axis",
                 0.);

    uves_par_new_value("y_axis_scale",
                 CPL_TYPE_DOUBLE,
                 "Scale Y axis",
                 0.);
*/
    uves_par_new_value("def_pol1",
                 CPL_TYPE_INT,
                 "Polynomial X deg",
                 4);

    uves_par_new_value("def_pol2",
                 CPL_TYPE_INT,
                 "Polynomial Y deg",
                 5);

    uves_par_new_value("kappa",
                 CPL_TYPE_DOUBLE,
                 "Kappa value in kappa sigma clipping "
                 "on RESIDUAL between YFIT and Y columns",
                 4.5);

    uves_par_new_value("tol",
                 CPL_TYPE_DOUBLE,
                 "Tolerance in kappa sigma clipping "
                 "on RESIDUAL between YFIT and Y columns",
                 2.0);

    return (int) cpl_error_get_code();
}
/*----------------------------------------------------------------------------*/
/**
  @brief    Process a single chip
  @param    raw_image   The input raw images
  @param    raw_header  An array containing the input image headers. 
                         The ordering must be the same as the ordering 
                         of images in the input image list
  @param    raw_filename The name of the input raw fits file
  @param    chip         CCD chip
  @param    recipe_id    recipe name
  @param    debug_mode        Debug mode flag
  @param    parameters   The recipe parameter list
  @param    line_refer   The reference line table
  @param    physmod_shift_x Correction to physical model
  @param    physmod_shift_y Correction to physical model
  @param    lin_tbl      The output guess line table
  @param    ord_tbl      The output guess order table
  @param    mline_tbl    The output table with results from measurements on
                         the input image frame
  @param    abs_ord_min  The minimum of the orders detected
  @param    abs_ord_max  The maximum of the orders detected
  @param    absolute_order_poly2d   A polynomial with order trace coefficients
  @return   Returns guess line and order tables, minimum, maximum order, 
  order trace coefficients

  Executes the several macro steps coded in uves_physmod_*.c sources 
  for processing a single chip 
*/
/*----------------------------------------------------------------------------*/

static cpl_table *
uves_physmod_process_chip(const cpl_image *raw_image, 
                          const uves_propertylist *raw_header, 
                          const char *raw_filename, 
                          enum uves_chip chip,
			  bool flames,
                          const char *recipe_id,
                          const int debug_mode, 
                          const cpl_parameterlist* parameters, 
                          cpl_table* line_refer,
                          const double physmod_shift_x,
                          const double physmod_shift_y,
                          cpl_table** tmp_mod_tbl,
                          cpl_table** lin_tbl,
                          cpl_table** ord_tbl,
                          cpl_table**  mline_tbl,
                          int* abs_ord_min,
                          int* abs_ord_max,
                          polynomial** absolute_order_poly2d,
                          const int stability_cnt)
{

    cpl_table *tmp_fsr_tbl = NULL;
    cpl_table *tmp_m_tbl = NULL;
    cpl_table *tmp_p_tbl = NULL;
    cpl_table *tmp_w_tbl = NULL;
    cpl_table *tmp_s_tbl = NULL;
    cpl_table *tmp_rline_tbl = NULL;
    cpl_table *tmp_npline_tbl = NULL;


    cpl_table * result=NULL;
    const char *product_filename = NULL;

    /* Start processing this chip */
    uves_msg("stability counter=%d",stability_cnt);
    if(stability_cnt == 0) {
       uves_msg("offsetx=%f offsety=%f",physmod_shift_x,physmod_shift_y);
       check( uves_physmod_create_table(raw_header, 
                                        chip,
                                        flames,
                                        recipe_id,
                                        parameters, 
                                        line_refer, 
                                        physmod_shift_x,
                                        physmod_shift_y,
                                        tmp_mod_tbl,
                                        &tmp_fsr_tbl), 
              "Could not run UVES physical model on the raw image %s", 
              raw_filename);

       if (debug_mode) {

          const char *product_filename = NULL;
          product_filename = "model_prediction";
          check( uves_save_table_local("Physical model table", 
                                       product_filename, *tmp_mod_tbl, chip, -1, -1, raw_header, NULL),
                 "Error saving physical model table");

   
       }
    }




    uves_free_table(&tmp_rline_tbl);
    check( uves_physmod_msrawxy(raw_image, 
                raw_header, 
                recipe_id,
                parameters, 
                *tmp_mod_tbl,
                lin_tbl,
                &tmp_m_tbl,
                &tmp_p_tbl,
                &tmp_rline_tbl,
                mline_tbl,
                &tmp_npline_tbl), 
       "Could not run uves_msrawxy to measure arc line position on raw image %s", 
       raw_filename);

/*
    product_filename = "tmp_mod_tbl";
        check( uves_save_table_local("tmp_mod_tbl table", 
               product_filename, *tmp_mod_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving tmp_mod_tbl table");
*/

    check(uves_physmod_plotmod(tmp_rline_tbl,raw_header,recipe_id,
                               parameters,chip),
          "Could not run uves_physmod_plotmod");
  
    if(stability_cnt == 0) {
      uves_free_table(&tmp_w_tbl);
      uves_free_table(&tmp_s_tbl);
      check(uves_physmod_calmap(raw_header,
                    chip,
                    recipe_id,
                    parameters, 
                    tmp_npline_tbl,
                    ord_tbl,
                    lin_tbl,
                    &tmp_w_tbl,
                    &tmp_s_tbl,
                    abs_ord_min,
                    abs_ord_max,
                    absolute_order_poly2d), 
        "Could not run uves_calmap on raw image %s", raw_filename);

      //cpl_table_save(*lin_tbl, NULL, NULL, "pippo4.fits", CPL_IO_DEFAULT);
   

      check(uves_physmod_chop_otab(raw_header,chip,lin_tbl,"Order",
                   abs_ord_min,abs_ord_max),
            "Could not run uves_physmod_chop_otab on raw image %s",
            raw_filename);


      check(uves_physmod_qc1pmtbl(&tmp_rline_tbl,lin_tbl), 
       "Could not run uves_qc1pmtbl on raw image %s", raw_filename);

    
      check(uves_physmod_chop_otab(raw_header,chip,ord_tbl,"ORDER",
                   abs_ord_min,abs_ord_max),
            "Could not run uves_physmod_chop_otab on raw image %s",
            raw_filename);
    }

    if (debug_mode) {
        /* Temporary products (to debug_mode) */

    /* Basic info about orders */
    if(stability_cnt==0) {
      product_filename = "arclampform";
    } else {
      product_filename = "ref_arclampform";
    }
        check( uves_save_image_local("Physical model table", 
               product_filename, raw_image, chip, -1, -1, raw_header, true),
              "Error saving arc lamp form image");

    product_filename = "pline";
        check( uves_save_table_local("Physical model table", 
               product_filename, *tmp_mod_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving physical model table");

      
     if(stability_cnt == 0) {
      product_filename = "free_spectral_range";
      check( uves_save_table_local("FSR table",
                       product_filename, tmp_fsr_tbl,
                                       chip, -1, -1, raw_header, NULL),
         "Error saving free spectral range table");

    }
        
    product_filename = "midduml";
        check( uves_save_table_local("midduml table", 
               product_filename, *lin_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving midduml table");


 
    product_filename = "middumm";
        check( uves_save_table_local("middumm table", 
               product_filename, tmp_m_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving middumm table");


    
    product_filename = "middumrline";
        check( uves_save_table_local("middumrline table", 
               product_filename, tmp_rline_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving middumrline table");


    product_filename = "middummline";
        check( uves_save_table_local("middummline table", 
               product_filename, *mline_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving middummline table");


    product_filename = "middump";
        check( uves_save_table_local("middump table", 
               product_filename, tmp_p_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving middump table");

       
    product_filename = "middumnpline";
        check( uves_save_table_local("middumnpline table", 
               product_filename, tmp_npline_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving middumnpline table");
      
       
    /* Calmap */
    if(stability_cnt== 0) {
      product_filename = "middumw";
      check( uves_save_table_local("middumw table", 
                       product_filename, tmp_w_tbl, 
                                       chip, -1, -1, raw_header, NULL),
         "Error saving middumw table");
     
      product_filename = "middums";
      check( uves_save_table_local("middums table", 
                       product_filename, tmp_s_tbl, 
                                       chip, -1, -1, raw_header, NULL),
         "Error saving middums table");
     
       
      product_filename = "order";
      check( uves_save_table_local("order table", 
                       product_filename, *ord_tbl, 
                                       chip, -1, -1, raw_header, NULL),
         "Error saving order table");
      uves_msg("Order table saved to file %s", 
           product_filename);

    }
    product_filename = "line";
        check( uves_save_table_local("line table", 
               product_filename, *lin_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving uves_line table");
        uves_msg("Line table saved to file %s", 
                                product_filename);
    
     
    
    }
    
  cleanup:
    uves_free_table(&tmp_fsr_tbl);
    uves_free_table(&tmp_m_tbl);
    uves_free_table(&tmp_p_tbl);
    uves_free_table(&tmp_w_tbl);
    uves_free_table(&tmp_s_tbl);
    uves_free_table(&tmp_rline_tbl);
     uves_free_table(&tmp_npline_tbl);
     
    uves_msg_debug("end %s",__func__);
    return result;
}



/*---------------------------------------------------------------------------*/
/**
  @brief    Get the command line options and execute the data reduction
  @param    parameters  the parameters list
  @param    flames      FLAMES mode?
  @param    recipe_id   recipe name
  @param    frames      the frames list
  @return   CPL_ERROR_NONE if everything is ok
 */
/*---------------------------------------------------------------------------*/
void
uves_physmod_exe_body(cpl_frameset *frames,
		      bool flames,
		      const char *recipe_id,
		      const cpl_parameterlist *parameters,
		      const char *starttime)
{
  /* Input image */
  cpl_image        *raw_image[2]      = {NULL, NULL};
  uves_propertylist *raw_header[2]     = {NULL, NULL};
  uves_propertylist *rotated_header[2] = {NULL, NULL};
  uves_propertylist *master_formatcheck_header[2] = {NULL, NULL};

  /* Physical Model guess table products */
  cpl_table        *line_table     = NULL;
  cpl_table        *order_table     = NULL;
  cpl_table        *mline_table     = NULL;
  cpl_table        *m_mline_table     = NULL;
  cpl_table        *model_table = NULL;

  cpl_table        *r_mline_table     = NULL;
  cpl_table        *mst_line_table     = NULL;
  cpl_table        *mst_mline_table     = NULL;
  cpl_table        *mst_order_table     = NULL;


  uves_propertylist *product_header = NULL;
  uves_propertylist *table_header = NULL;
  cpl_table        *line_refer            = NULL;
  polynomial       *absolute_order_poly2d=NULL;      
  polynomial       *mst_absolute_order_poly2d=NULL;      


  /* Local variables */
  int      debug_mode=0;
  int abs_ord_min=0;
  int abs_ord_max=0;
  int mst_abs_ord_min=0;
  int mst_abs_ord_max=0;
  double avg_dx=0;
  double avg_dy=0;

  const char *raw_filename = "";
  char *product_filename = NULL;
    
  bool blue = false;
  enum uves_chip chip;    
  const char *line_refer_filename = "";
  const char *master_formatcheck_filename = "";
  cpl_image        *master_formatcheck    = NULL;
  int nordpred=0;
  int plate_no=0;
  int iter=1;
  int it=0;

  int iter_max=UVES_PHYSMOD_ITER_MAX;
  /* QC tables for iter_max*(TEST1+TEST2) and a NULL pointer */
  cpl_table* qclog[iter_max*2+1];


  double physmod_shift_x=0;
  double physmod_shift_y=0;
  double ref_frame_physmod_shift_x=0;
  double ref_frame_physmod_shift_y=0;
  const double max_shift_x=0.4;
  const double max_shift_y=0.2;
  double med_dx=2*max_shift_x;
  double med_dy=2*max_shift_y;
  const char* PROCESS_CHIP=NULL;
  /* Master bias */
  cpl_image *master_bias               = NULL;
  uves_propertylist *master_bias_header = NULL;

  double rot_1=0;
  double rot_2=0;
  double rot_3=0;
  double wlen=0;
  int wavec=0;
  int stab_check=0;
  int stability_cnt=1;
  const char *chip_name = "";
  int raw_index = 0;
  const char *master_bias_filename = "";

  double trans_x=0;
  double trans_y=0;
  char extname[80];
  for( iter=0 ; iter < 2*iter_max+1 ; iter++) {
    qclog[iter]=NULL;
  }

  if(flames) {
    iter_max=1;  //Temporally changed to 1
  } else {
    iter_max=1;
  }
  check( uves_get_parameter(parameters, NULL, "uves", "debug",  
			    CPL_TYPE_BOOL, &debug_mode),
	 "Could not read parameter");
  check( uves_get_parameter(parameters, NULL, "uves", "process_chip", 
			    CPL_TYPE_STRING, &PROCESS_CHIP),
	 "Could not read parameter");
  uves_string_toupper((char*)PROCESS_CHIP);
  /* Load raw image and header, and identify input frame as red or blue */
  check( uves_load_formatcheck(frames, flames, &raw_filename, raw_image, 
			       raw_header, rotated_header, &blue), 
	 "Error loading raw frame");

  /* Load reference line table */
  check( uves_load_linerefertable(frames, &line_refer_filename, 
				  &line_refer, NULL), 
	 "Could not load line reference table");
  uves_msg("Using line reference table in '%s'", line_refer_filename);

  check( uves_get_parameter(parameters, NULL, recipe_id,
			    "trans_x", CPL_TYPE_DOUBLE, &trans_x )  ,
	 "Could not read parameter");

  check( uves_get_parameter(parameters, NULL, recipe_id, 
			    "trans_y", CPL_TYPE_DOUBLE, &trans_y )  ,
	 "Could not read parameter");



  /* Loop over one or two chips */
  for (chip = uves_chip_get_first(blue); 
       chip != UVES_CHIP_INVALID; 
       chip = uves_chip_get_next(chip))
    {
      /* following init to have at least one model iteration on both chips */ 
      med_dx=2*max_shift_x;
      med_dy=2*max_shift_y;
      if(strcmp(PROCESS_CHIP,"REDU") == 0) {
	chip = uves_chip_get_next(chip);
      }

      stab_check=0;
      stability_cnt=1;
      raw_index = uves_chip_get_index(chip);
        

      uves_msg("Processing %s chip in '%s'", 
	       uves_chip_tostring_upper(chip), raw_filename);

      check_nomsg( chip_name = uves_pfits_get_chipid(raw_header[raw_index], chip));


      physmod_shift_x=0;
      physmod_shift_y=0;
      if(flames) {
	check(plate_no = uves_flames_pfits_get_plateid(raw_header[raw_index]),
	      "Error reading plate id");
        check_nomsg(wlen=uves_pfits_get_gratwlen(raw_header[raw_index],chip));
	wavec=(int)wlen;
        

	ck0_nomsg(flames_get_physmod_shift(plate_no,wavec,chip,
					   &physmod_shift_x,&physmod_shift_y,
					   &rot_1,&rot_2,&rot_3));

        ref_frame_physmod_shift_x=physmod_shift_x;
        ref_frame_physmod_shift_y=physmod_shift_y;



	uves_msg("shift_x=%f shift_y=%f",physmod_shift_x,physmod_shift_y);
	if( trans_x != 0 ) {
	  physmod_shift_x+=trans_x;
	}

	if( trans_y != 0 ) {
	  physmod_shift_y+=trans_y;
	}
	uves_msg("shift_x=%f shift_y=%f",physmod_shift_x,physmod_shift_y);

      } else {

	if( trans_x != 0 ) {
	  physmod_shift_x=trans_x;
	}

	if( trans_y != 0 ) {
	  physmod_shift_y=trans_y;
	}

      }
      uves_msg("Using physmod shifts: %g %g",physmod_shift_x,physmod_shift_y);
      /* Check if a stability check can be done */
      if (cpl_frameset_find(frames, UVES_MASTER_ARC_FORM(chip)) != NULL) {
	  
	uves_free_image (&master_formatcheck);
	uves_free_propertylist(&master_formatcheck_header[raw_index]);
	check( uves_load_master_formatcheck(frames, 
					    chip_name,
					    &master_formatcheck_filename, 
					    &master_formatcheck,
					    &master_formatcheck_header[raw_index],                  
					    chip),
	       "Could not load master formatcheck frm");
            

	stab_check=1;

      } else {
	uves_msg_low("No master format check frm in SOF.");
	uves_msg_low("Stability check not done");
      }

      /* Load master bias, set pointer to NULL if not present */
      uves_free_image(&master_bias);
      uves_free_propertylist(&master_bias_header);
      if (cpl_frameset_find(frames, UVES_MASTER_BIAS(chip)) != NULL)
        {
	  uves_free_image(&master_bias);
	  uves_free_propertylist(&master_bias_header);
	  check( uves_load_mbias(frames,
				 chip_name,
				 &master_bias_filename, &master_bias,
				 &master_bias_header, chip), 
		 "Error loading master bias");
            
	  uves_msg_low("Using master bias in '%s' and '%s'", 
		       master_bias_filename,master_formatcheck_filename);
	  check_nomsg(cpl_image_subtract(raw_image[raw_index],master_bias));
	  if(stab_check==1) {
	    check_nomsg(cpl_image_subtract(master_formatcheck,master_bias));
	  }     

        }
      else
        {
	  uves_msg_low("No master bias in SOF. Bias subtraction not done");
        }

      /* Init QC-Log: before starting the stability check as in 
	 FLAMES-UVES one may have several iterations to be dumped 
	 on the different tables
      */

      for(iter=1,it=0;
	  iter<=iter_max &&
	    (fabs(med_dx) > max_shift_x || 
	     fabs(med_dy) > max_shift_y ) ;
	  iter++,it+=2) {
	uves_msg("iter=%d it=%d",iter,it);

	uves_qclog_delete(&qclog[it]);
	uves_qclog_delete(&qclog[it+1]);
	qclog[it]   = uves_qclog_init(raw_header[raw_index], chip);
	qclog[it+1] = uves_qclog_init(raw_header[raw_index], chip);

  
	//Run the physical model on the raw frame
	uves_free_table(&model_table);
	uves_free_table(&line_table);
	uves_free_table(&order_table);
	uves_free_table(&mline_table);

	uves_polynomial_delete(&absolute_order_poly2d);
	uves_msg("Run the physical model on the raw frame");
        uves_msg("physmod shift x %f y %f",physmod_shift_x,physmod_shift_y);
	check( uves_physmod_process_chip(raw_image[raw_index], 
					 raw_header[raw_index],
					 raw_filename,
					 chip,
					 flames,
					 recipe_id,
					 debug_mode,
					 parameters,
					 line_refer,
					 physmod_shift_x,
					 physmod_shift_y,
					 &model_table,
					 &line_table,
					 &order_table,
					 &mline_table,
					 &abs_ord_min,
					 &abs_ord_max,
					 &absolute_order_poly2d,0),
	       "Error processing chip");

	nordpred=abs_ord_max-abs_ord_min+1;
	uves_msg("No of predicted orders %d",nordpred);


	/* add QC log */
	uves_msg("add QC log on raw frame");
	ck0(uves_physmod_qclog(line_table,order_table,qclog[it],
			       raw_header[raw_index], chip,
			       flames,iter,plate_no),"qc-log dump");


	   
	uves_msg("iter_max=%d",iter_max);
	if(stab_check) {
	  uves_free_table(&mst_line_table);
	  uves_free_table(&mst_order_table);
	  uves_free_table(&mst_mline_table);
	  uves_polynomial_delete(&mst_absolute_order_poly2d);

	  uves_msg("Run the physical model on the Master formatcheck frame");
          uves_msg("ref physmod shift x %f y %f",
		   ref_frame_physmod_shift_x,ref_frame_physmod_shift_y);

	  uves_msg("Stability counter=%d",stability_cnt);
	  check(uves_physmod_process_chip(master_formatcheck,
					  master_formatcheck_header[raw_index], 
					  master_formatcheck_filename,
					  chip,
					  flames,
					  recipe_id,
					  debug_mode,
					  parameters,
					  line_refer,
					  ref_frame_physmod_shift_x,
					  ref_frame_physmod_shift_y,
					  &model_table,
					  &mst_line_table,
					  &mst_order_table,
					  &mst_mline_table,
					  &mst_abs_ord_min,
					  &mst_abs_ord_max,
					  &mst_absolute_order_poly2d,
					  stability_cnt),
		"Error processing chip");
	  stability_cnt+=1;            
	  uves_msg("Stability check");
	  uves_msg("Using master format check frm '%s'", 
		   master_formatcheck_filename);
	  check_nomsg( uves_physmod_stability_check(
						    mline_table,
						    mst_mline_table,
						    &med_dx,
						    &med_dy,
						    &avg_dx,
						    &avg_dy) );


            
	  uves_physmod_qclog_sc(med_dx,med_dy,avg_dx,avg_dy, 
				raw_header[raw_index],
				master_formatcheck_header[raw_index],
				chip,flames,iter,
				qclog[it+1]);
	  uves_msg("iter=%d med_dx=%g med_dy=%g",
		   iter,fabs(med_dx),fabs(med_dy));
	  uves_msg("iter=%d max_shift_x=%g max_shift_y=%g",
		   iter,max_shift_x,max_shift_y);


	  nordpred=abs_ord_max-abs_ord_min+1;
	  physmod_shift_x-=med_dx;
	  physmod_shift_y-=med_dy;

	} // end of stability check
      
      } // end of iterations
         
        
        /* Finished. Now save the products */
      uves_msg("Saving products...");
       
        
      /* QC parameters should go here.
	 Other mandatory keywords (FITS + dfs) are
	 automatically added. */

      uves_free_propertylist(&product_header);
      uves_free_propertylist(&table_header);
      product_header = uves_propertylist_new();
      table_header = uves_propertylist_new();
      check( uves_pfits_set_traceid     ( table_header, 0),
	     "Error writing trace ID to product header");
      check( uves_pfits_set_windownumber( table_header, 2),
	     "Error window number to product header");

      check( uves_pfits_set_firstabsorder(table_header, abs_ord_min),
	     "Error window number to product header");

      check( uves_pfits_set_lastabsorder(table_header, abs_ord_max),
	     "Error window number to product header");

      check_nomsg(uves_pfits_set_ordpred(product_header,nordpred));


      if (flames) {
            
	check_nomsg(uves_flames_pfits_set_newplateid(product_header, 
						     plate_no));
      }

      cpl_free(product_filename);
      //uves_pfits_set_extname(product_header,"Guess line table");
      sprintf(extname,"LINE_GUESS_TAB");
      uves_pfits_set_extname(table_header,extname);
      check(( product_filename = uves_guess_line_table_filename(chip),
	      uves_frameset_insert(frames,
				   line_table,
				   CPL_FRAME_GROUP_PRODUCT,
				   CPL_FRAME_TYPE_TABLE,
				   CPL_FRAME_LEVEL_INTERMEDIATE,
				   product_filename,
				   UVES_GUESS_LINE_TABLE(flames, chip),
				   raw_header[raw_index], 
				   product_header,
				   table_header,
				   parameters,
				   recipe_id,
				   PACKAGE "/" PACKAGE_VERSION,
				   qclog,
				   starttime, 
				   true, 
				   0)),
	    "Could not add line guess table %s to frameset", 
	    product_filename);
                
      /* Save in next extension */

      sprintf(extname,"LINE_GUESS_POL1");
      uves_pfits_set_extname(table_header,extname);
      check( uves_save_polynomial(absolute_order_poly2d, 
				  product_filename, table_header),
	     "Could not write polynomial to file '%s'", product_filename);
               
      sprintf(extname,"LINE_GUESS_POL2");
       uves_pfits_set_extname(table_header,extname);
      check( uves_save_polynomial(absolute_order_poly2d, 
				  product_filename, table_header), 
	     "Could not write polynomial to file '%s'", product_filename);
            


      uves_msg("Line table %s added to frameset", product_filename);
        
      /* Save guess order table, re-use product header */

      cpl_free(product_filename);        
      //uves_pfits_set_extname(product_header,"Guess order table");
      sprintf(extname,"ORD_GUESS_TAB");
      uves_pfits_set_extname(table_header,extname);
      check(( product_filename = uves_guess_order_table_filename(chip),
	      uves_frameset_insert(frames,
				   order_table,
				   CPL_FRAME_GROUP_PRODUCT,
				   CPL_FRAME_TYPE_TABLE,
				   CPL_FRAME_LEVEL_INTERMEDIATE,
				   product_filename,
				   UVES_GUESS_ORDER_TABLE(flames, chip),
				   raw_header[raw_index],
				   product_header,
				   table_header,
				   parameters,
				   recipe_id,
				   PACKAGE "/" PACKAGE_VERSION,
				   NULL,
				   starttime, 
				   false, 
				   0)), 
	    "Could not add order guess table %s to frameset", 
	    product_filename);
        
      uves_msg("Order guess table %s added to frameset", 
	       product_filename);

      for(it=0;it<2*iter_max+1;it++) {
	uves_qclog_delete(&qclog[it]);
      }

      if(strcmp(PROCESS_CHIP,"REDL") == 0) {
	chip = uves_chip_get_next(chip);
      }

    }/* For each chip */

 cleanup:
  for(it=0;it<2*iter_max+1;it++) {
    uves_qclog_delete(&qclog[it]);
  }
   
  /* Master bias */
  uves_free_image(&master_bias);
  uves_free_propertylist(&master_bias_header);

  uves_free_image (&raw_image[0]);
  uves_free_image (&raw_image[1]);
  uves_free_propertylist(&raw_header[0]);
  uves_free_propertylist(&raw_header[1]);
  uves_free_propertylist(&rotated_header[0]);
  uves_free_propertylist(&rotated_header[1]);

  uves_free_image (&master_formatcheck);
  uves_free_propertylist(&master_formatcheck_header[0]);
  uves_free_propertylist(&master_formatcheck_header[1]);

  uves_free_table(&model_table);
  uves_free_table(&line_table);
  uves_free_table(&mst_line_table);
  uves_free_table(&order_table);
  uves_free_table(&mst_order_table);
  uves_free_table(&line_refer);

  uves_free_table(&mline_table);
  uves_free_table(&m_mline_table);
  uves_free_table(&r_mline_table);
  uves_free_table(&mst_mline_table);

  uves_free_propertylist(&product_header);
  uves_free_propertylist(&table_header);
  uves_polynomial_delete(&absolute_order_poly2d);
  uves_polynomial_delete(&mst_absolute_order_poly2d);
  cpl_free(product_filename); 
          
  uves_msg_debug("end %s",__func__);
  return;
}


/**
@brief computes QC parameters
@param line_table         input table
@param line_table         input table
@param qclog              output QC table
@param raw_header         input raw_header
@param chip               CCD chip
@return QC parameters on tables
*/
static int 
uves_physmod_qclog(cpl_table* line_table,
                   cpl_table* order_table,
                   cpl_table* qclog,
                   const uves_propertylist *raw_header,
                   enum uves_chip chip,
                   bool flames,
                   const int iter,
                   const int plate_no)
{
  int nlinsel=0;
  cpl_table *xline_table=NULL;
  char key_value[25];


  check_nomsg( uves_qclog_add_common_wave(raw_header,
                                          chip, qclog) );


  if(flames) {
     ck0_nomsg(uves_qclog_add_string(qclog,
                     "QC TEST1 ID",
                     "Fibre-Physical-Model-Prediction-Results",
                     "Name of QC test",
                     "%s"));
  } else {
     ck0_nomsg(uves_qclog_add_string(qclog,
                     "QC TEST1 ID",
                     "Physical-Model-Prediction-Results",
                     "Name of QC test",
                     "%s"));
  }
  ck0_nomsg(uves_qclog_add_string(qclog,
                  "QC MODEL ID",
                  "UVES_phys_mod/1.1.0",
                  "Physmod Model Id",
                  "%s"));

  ck0_nomsg(uves_qclog_add_string(qclog,
                  "QC MODEL DATE",
                  "2000:03:18T00:00:00.000",
                  "Physmod Model Parameters Last Change",
                  "%s"));

  if(flames) {

    sprintf(key_value,"%s%d","QC MODEL ITER",iter);
    ck0_nomsg(uves_qclog_add_int(qclog,
                 key_value,
                 iter,
                 "Model iteration",
                 "%d"));

    ck0_nomsg(uves_qclog_add_int(qclog,
                 "QC MODEL ORDMIN",
                 cpl_table_get_column_min(line_table,"Order"),
                 "minimum predicted order value",
                 "%d"));

    ck0_nomsg(uves_qclog_add_int(qclog,
                 "QC MODEL ORDMAX",
                 cpl_table_get_column_max(line_table,"Order"),
                 "maximum predicted order value",
                 "%d"));


    ck0_nomsg(uves_qclog_add_double(qclog,
                 "QC MODEL WLENMIN",
                 cpl_table_get_column_min(line_table,"WAVEC")/10.,
                 "minimum predicted order value",
                 "%f"));

    ck0_nomsg(uves_qclog_add_double(qclog,
                 "QC MODEL WLENMAX",
                 cpl_table_get_column_max(line_table,"WAVEC")/10.,
                 "maximum predicted order value",
                 "%f"));


  } /* in case of flames-uves */

  ck0_nomsg(uves_qclog_add_int(qclog,
                   "QC MODEL NLINALL",
                   cpl_table_get_nrow(line_table),
                   "Number of predicted lines",
                   "%d"));

  check_nomsg(nlinsel=cpl_table_and_selected_int(line_table,"SELPLOT",
                                                 CPL_EQUAL_TO,1));
  check_nomsg(xline_table=cpl_table_extract_selected(line_table));

  ck0_nomsg(uves_qclog_add_int(qclog,
                   "QC MODEL NLINSEL",
                   nlinsel,
                   "Number of lines selected",
                   "%d"));

  if(iter == 1) {
     ck0_nomsg(uves_qclog_add_double(qclog,
                     "QC MODEL DIFFXRMS",
                     cpl_table_get_column_stdev(xline_table,"XDIF"),
                     "Std dev of X difference to physical model",
                     "%8.4f"));

     ck0_nomsg(uves_qclog_add_double(qclog,
                     "QC MODEL DIFFXAVG",
                     cpl_table_get_column_mean(xline_table,"XDIF"),
                     "Average of X difference to physical model",
                     "%8.4f"));

     ck0_nomsg(uves_qclog_add_double(qclog,"QC MODEL DIFFXMED",
                     cpl_table_get_column_median(xline_table,"XDIF"),
                     "Median of X difference to physical model",
                     "%8.4f"));

     ck0_nomsg(uves_qclog_add_double(qclog,
                     "QC MODEL DIFFYRMS",
                     cpl_table_get_column_stdev(xline_table,"YDIF"),
                     "Std dev of Y difference to physical model",
                     "%8.4f"));

     ck0_nomsg(uves_qclog_add_double(qclog,
                     "QC MODEL DIFFYAVG",
                     cpl_table_get_column_mean(xline_table,"YDIF"),
                     "Average of Y difference to physical model",
                     "%8.4f"));

     ck0_nomsg(uves_qclog_add_double(qclog,"QC MODEL DIFFYMED",
                     cpl_table_get_column_median(xline_table,"YDIF"),
                     "Median of Y difference to physical model",
                     "%8.4f"));
  }

  if ( flames == 1 ) {


       sprintf(key_value,"%s%d","QC MODEL RESXRMS",iter);
       ck0_nomsg(uves_qclog_add_double(qclog,
                    key_value,
                    cpl_table_get_column_stdev(xline_table,"XDIF"),
                    "Std dev of X difference to physical model",
                    "%8.4f"));


       sprintf(key_value,"%s%d","QC MODEL RESXAVG",iter);
       ck0_nomsg(uves_qclog_add_double(qclog,
                    key_value,
                    cpl_table_get_column_mean(xline_table,"XDIF"),
                    "Average of X difference to physical model",
                    "%8.4f"));

       sprintf(key_value,"%s%d","QC MODEL RESXMED",iter);
       ck0_nomsg(uves_qclog_add_double(qclog,
                    key_value,
                    cpl_table_get_column_median(xline_table,"XDIF"),
                    "Median of X difference to physical model",
                    "%8.4f"));



       sprintf(key_value,"%s%d","QC MODEL RESYRMS",iter);
       ck0_nomsg(uves_qclog_add_double(qclog,
                    key_value,
                    cpl_table_get_column_stdev(xline_table,"YDIF"),
                    "Std dev of Y difference to physical model",
                    "%8.4f"));


       sprintf(key_value,"%s%d","QC MODEL RESYAVG",iter);
       ck0_nomsg(uves_qclog_add_double(qclog,
                    key_value,
                    cpl_table_get_column_mean(xline_table,"YDIF"),
                    "Average of Y difference to physical model",
                    "%8.4f"));

       sprintf(key_value,"%s%d","QC MODEL RESYMED",iter);
       ck0_nomsg(uves_qclog_add_double(qclog,
                    key_value,
                    cpl_table_get_column_median(xline_table,"YDIF"),
                    "Median of Y difference to physical model",
                    "%8.4f"));


  }


  cpl_table_unselect_all(line_table);

  /* we divide by 10 as line_table contains values in Angstrom and we want
     nanometers */
  ck0_nomsg(uves_qclog_add_double(qclog,
                  "QC MODEL WLENMIN",
                  cpl_table_get_column_min(xline_table,"WAVEC")/10.,
                  "minimum predicted wavelength value",
                  "%8.4f"));

 ck0_nomsg(uves_qclog_add_double(qclog,
                 "QC MODEL WLENMAX",
                 cpl_table_get_column_max(xline_table,"WAVEC")/10.,
                 "maximum predicted wavelength value",
                 "%8.4f"));


  ck0_nomsg(uves_qclog_add_int(qclog,
                   "QC MODEL ORDMIN",
                   (int)cpl_table_get_column_min(xline_table,"Order"),
                   "minimum predicted order value",
                   "%d"));

  ck0_nomsg(uves_qclog_add_int(qclog,
                   "QC MODEL ORDMAX",
                   (int)cpl_table_get_column_max(xline_table,"Order"),
                   "maximum predicted order value",
                   "%d"));


 
  /* we divide by 10 as line_table contains values in Angstrom and we want
     nanometers */
  ck0_nomsg(uves_qclog_add_double(qclog,
                  "QC WLENMIN",
                  cpl_table_get_column_min(line_table,"WAVEC")/10.,
                  "minimum wavelength",
                  "%8.4f"));

  ck0_nomsg(uves_qclog_add_double(qclog,
                  "QC WLENMAX",
                  cpl_table_get_column_max(line_table,"WAVEC")/10.,
                  "maximum wavelength",
                  "%8.4f"));
  
  ck0_nomsg(uves_qclog_add_int(qclog,
                   "QC ORDMIN",
                   cpl_table_get_column_min(order_table,"ORDER"),
                   "minimum order number",
                   "%d"));

  ck0_nomsg(uves_qclog_add_int(qclog,
                   "QC ORDMAX",
                   cpl_table_get_column_max(order_table,"ORDER"),
                   "maximum order number",
                   "%d"));


  if (flames) {
    /*
stat/ima {wlc} {SESSOUTV}
tot_int = outputr(7)
exp_time = {{wlc},{h_dit1}}
rel_int = tot_int / exp_time
    */

     ck0_nomsg(uves_qclog_add_double(qclog,
                  "QC FIB1 ABSTRANS",
                  cpl_table_get_column_max(order_table,"ORDER"),
                  "abs. trans. countrate",
                  "%f"));
     /*
@p flames_check_sat_lev {wlc} {DRS_PTHRE_MIN} {DRS_PTHRE_MAX}
sat_lev = {q1}
n_hpix  = {q2}
     */

    ck0_nomsg(uves_qclog_add_int(qclog,
                 "QC NHOTPIX",
                 cpl_table_get_column_max(order_table,"ORDER"),
                 "no. of hot pixels",
                 "%d"));


    ck0_nomsg(uves_qclog_add_int(qclog,
                 "QC PLATENO",
                 plate_no,
                 "Plate Id.",
                 "%d"));
  }

  /* The number of orders predicted is already written to another
     keyword, and this is not need for QC logging, so it is commented out
  uves_qclog_add_int(qclog,"QC NORDGUE",???,"No of predicted orders","%d");
  */

 cleanup:
  uves_free_table(&xline_table);

  if (cpl_error_get_code() != CPL_ERROR_NONE) {
    return -1;

  } else {

    return 0;
  }



}




/**
@brief computes stability check QC parameters
@param 
@param 
@param  raw_header    raw frame FITS header
@param  chip          CCD chip
@parameter qclog      output QC table
@return QC parameters on tables
*/
static int 
uves_physmod_qclog_sc(const double med_dx, 
                      const double med_dy,
                      const double avg_dx,
                      const double avg_dy,
                      const uves_propertylist *raw_header,
                      const uves_propertylist *ref_header,
                      enum  uves_chip chip,
                      bool flames,
                      const int iter,
                      cpl_table* qclog)
{

  char key_value[25];

    if(flames) {
        ck0_nomsg(uves_qclog_add_string(qclog,
					"QC TEST2 ID",
					"Fibre-Stability-Check-Results",
					"Name of QC test",
				        "%s"));
    } else {
        ck0_nomsg(uves_qclog_add_string(qclog,
					"QC TEST2 ID",
					"Stability-Check-Results",
					"Name of QC test",
					"%s"));
    }
    
    ck0_nomsg(uves_qclog_add_string(qclog,
              "QC MODEL ID",
              "UVES_phys_mod/1.1.0",
              "Physmod Model Id",
              "%s"));
    
    ck0_nomsg(uves_qclog_add_string(qclog,
              "QC MODEL DATE",
              "2000:03:18T00:00:00.000",
              "Physmod Model Parameters Last Change",
              "%s"));

    check_nomsg( uves_qclog_add_common_wave(raw_header,
                                            chip, qclog) );
    

    ck0_nomsg(uves_qclog_add_string(qclog,
              "QC REF PNAME",
              uves_pfits_get_arcfile(ref_header),
              "Reference file name",
              "%s"));

    ck0_nomsg(uves_qclog_add_double(qclog,
              "QC AMBI PRES",
              uves_pfits_get_ambipress(raw_header),
              "Ambient pressure [mm] Hg.",
              "%8.4f"));


    if(flames) {

       sprintf(key_value,"%s%d","QC MODEL ITER",iter);
       ck0_nomsg(uves_qclog_add_int(qclog,
                 key_value,
                 iter,
                 "Model iteration",
                 "%d"));


    }

  if(iter == 1) {
    ck0_nomsg(uves_qclog_add_double(qclog,
              "QC SHFTXAVG",
              avg_dx,
              "mean shift in x",
              "%8.4f"));

    ck0_nomsg(uves_qclog_add_double(qclog,
              "QC SHFTXMED",
              med_dx,
              "median shift in x",
              "%8.4f"));

    ck0_nomsg(uves_qclog_add_double(qclog,
              "QC SHFTYAVG",
              avg_dy,
              "mean shift in y",
              "%8.4f"));

    ck0_nomsg(uves_qclog_add_double(qclog,
              "QC SHFTYMED",
              med_dy,
              "median shift in y",
              "%8.4f"));

  }
 cleanup:

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


/*---------------------------------------------------------------------------*/
/**
   @brief    Get the physical model shifts in FIBER mode
   @param    plate_no  plate number
   @param    wavec     central wavelength
   @param    trans_x   out physical model X shift
   @param    trans_y   out physical model Y shift
   @param    rot_1     out rot angle 1st component
   @param    rot_2     out rot angle 2nd component
   @param    rot_3     out rot angle 3rd component
   @return   0 if everything is ok
*/
/*---------------------------------------------------------------------------*/


static int
flames_get_physmod_shift(const int plate_no,
                         const int wavec,
                         enum uves_chip chip,
                         double* trans_x,
                         double* trans_y,
                         double* rot_1,
                         double* rot_2,
                         double* rot_3)
{

  //For the moment rot angle default is assumed always 0,0,0
  *rot_1=0;
  *rot_2=0;
  *rot_3=0;

  uves_msg("plate_no=%d,wavec=%d,chip=%d",plate_no,wavec,chip);
  switch(plate_no){

  case 1:
    if(chip==UVES_CHIP_REDL) {
      switch(wavec){

      case 520:
	*trans_x=-15.330;
	*trans_y=-40.461;
	uves_msg("case 520 REDL pt1");
	break;

      case 580:
	*trans_x=-17.972;
	*trans_y=-39.200;
	uves_msg("case 580 REDL pt1");
	break;

      case 860:
	*trans_x=-12.212;
	*trans_y=-49.370;
	uves_msg("case 860 REDL pt1");
	break;

      }
    } else {

      switch(wavec){

      case 520:
	*trans_x=-14.237;
	*trans_y=-40.337;
	uves_msg("case 520 REDU pt1");
	break;

      case 580:
	*trans_x=-14.738;
	*trans_y=-38.831;
	uves_msg("case 580 REDU pt1");
	break;

      case 860:
	*trans_x=-08.253;
	*trans_y=-45.385;
	uves_msg("case 860 REDU pt1");
	break;

      }
      break;
  
    }
    break;


  case 2:
    if(chip==UVES_CHIP_REDL) {

    case UVES_CHIP_REDL:
      switch(wavec){

      case 520:
	*trans_x=+10.136;
	*trans_y=-41.420;
	uves_msg("case 520 REDL pt2");
	break;

      case 580:
	*trans_x=+09.000;
	*trans_y=-38.289;
	uves_msg("case 580 REDL pt2");
	break;

      case 860:
	*trans_x=+16.386;
	*trans_y=-47.519;
	uves_msg("case 860 REDL pt2");
	break;

      }
      break;

    } else {

      switch(wavec){

      case 520:
	*trans_x=+12.244;
	*trans_y=-41.970;
	uves_msg("case 520 REDU pt2");
	break;

      case 580:
	*trans_x=+12.023;
	*trans_y=-38.165;
	uves_msg("case 580 REDU pt2");
	break;

      case 860:
	*trans_x=+18.241;
	*trans_y=-43.889;
	uves_msg("case 860 REDU pt2");
	break;

      }
      break;

    }
    break;


  default:
    *trans_x=0;
    *trans_y=0;
  


  }


  uves_msg("Physical Model shifts trans=%f,%f rot=%f,%f,%f",
	   *trans_x,*trans_y,*rot_1,*rot_2,*rot_3);
  return 0;
}



/**@}*/
