/*                                                                              *
 *   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: 2010-09-24 09:31:49 $
 * $Revision: 1.14 $
 * $Name: not supported by cvs2svn $
 * $Log: not supported by cvs2svn $
 * Revision 1.12  2007/09/11 17:10:49  amodigli
 * added uves_utils_polynomial.h
 *
 * Revision 1.11  2007/08/30 07:56:05  amodigli
 * fixed some doxygen warnings
 *
 * Revision 1.10  2007/06/26 14:51:00  jmlarsen
 * Fixed bug in load_linetable
 *
 * Revision 1.9  2007/06/20 15:55:37  jmlarsen
 * Parametrized assumption about MIDAS format
 *
 * Revision 1.8  2007/06/20 15:49:59  jmlarsen
 * Use MIDAS compatible column names
 *
 * Revision 1.7  2007/06/20 08:28:53  amodigli
 * updated interface to uves_polynomial_convert_from_plist_midas
 *
 * Revision 1.6  2007/05/22 11:28:14  jmlarsen
 * Removed unused variables
 *
 * Revision 1.5  2007/04/24 12:50:29  jmlarsen
 * Replaced cpl_propertylist -> uves_propertylist which is much faster
 *
 * Revision 1.4  2007/04/10 11:34:48  jmlarsen
 * More points per order in order table
 *
 * Revision 1.3  2007/04/10 07:22:07  jmlarsen
 * Changed interface of polynomial_regression_2d()
 *
 * Revision 1.2  2007/03/15 14:44:51  jmlarsen
 * Removed debugging dump
 *
 * Revision 1.1  2007/03/15 12:47:32  jmlarsen
 * Imported sources
 *
 *
 */

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

/*----------------------------------------------------------------------------*/
/**
 * @defgroup uves_test_simulate  Create mock-up objects for unit testing
 */
/*----------------------------------------------------------------------------*/
/**@{*/

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

#include <uves_test_simulate.h>
//#include <uves_utils_polynomial.h>
#include <uves_utils_wrappers.h>
#include <uves_wavecal_utils.h>
#include <uves_error.h>
#include <uves_dfs.h>

#include <cpl.h>

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

/*-----------------------------------------------------------------------------
                            Implementation
 -----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------*/
/**
   @brief    Create order table
   @param    ordertable      (output) order table
   @param    order_locations (output) the polynomial
   @param    tracetable      (output) fibre mask  
   @param    minorder        order range
   @param    maxorder        order range
   @param    nx              sampling step along x (?)

*/
/*----------------------------------------------------------------------------*/
void
create_order_table(cpl_table **ordertable, 
                   polynomial **order_locations, 
                   cpl_table **tracetable,
                   int minorder, 
                   int maxorder, 
                   int nx)
{
    uves_propertylist *header = NULL;
    
    /* Create polynomial */
    assure_nomsg(order_locations != NULL, CPL_ERROR_NULL_INPUT);
    
    {
        const char *data[] = {"",
                              "'COEFFI','I*4',1,7,'7I10'",
                              "     53889         2         3         2         1         4         5",
                              "",
                              "'COEFFR','R*4',1,5,'5E14.7'",
                              " 4.3300000E+02 4.0880000E+03 1.0000000E+00 2.1000000E+01 0.0000000E+00",
                              "",
                              "'COEFFD','R*8',1,30,'3E23.15'",
                              " -7.097005629698889E+01  4.050908371864904E-02 -2.886756545398909E-06",
                              "  5.504345508879626E-10 -5.583004967206025E-14  7.624532125635992E+01",
                              " -2.428213567964009E-03  1.819158447566360E-06 -5.090366383338846E-10",
                              "  5.198098506055602E-14  3.513177145982783E-01  5.570332137951829E-04",
                              " -3.876157463910250E-07  1.113253735718822E-10 -1.132455173423791E-14",
                              "  2.977232589499959E-02 -5.389240622889887E-05  3.777456726044612E-08",
                              " -1.083863050648735E-11  1.098450510939580E-15 -1.093309039442914E-03",		    
                              "  2.402609262989674E-06 -1.688416547941747E-09  4.839101712729582E-13",
                              " -4.884504488944702E-17  1.919853952642526E-05 -4.004133160220927E-08",
                              "  2.816206503824200E-11 -8.051313882805877E-15  8.090579180112579E-19",
                              " ",
                              "'TAB_IN_OUT_YSHIFT','R*8',1,1,'3E23.15'",
                              "  4.180818583555659E+01		    ",
                              " "};
            
        header = uves_propertylist_new();
        {
            unsigned i;
            for (i = 0; i < sizeof(data)/sizeof(char *); i++)
                {
                    uves_propertylist_append_string(header, "HISTORY",
                                                   data[i]);
                }
        }
            
        check_nomsg( *order_locations = uves_polynomial_convert_from_plist_midas(header, 
                                                                                 "COEFF",-1));
    }

    /* Fill order table */
    if (ordertable != NULL)
        {
            int order;
            int row = 0;

            *ordertable = cpl_table_new(5*(maxorder - minorder + 1));
            cpl_table_new_column(*ordertable, "Order", CPL_TYPE_INT);
            cpl_table_new_column(*ordertable, "X", CPL_TYPE_INT);
            cpl_table_new_column(*ordertable, "Yfit", CPL_TYPE_DOUBLE);

            for (order = minorder; order <= maxorder; order++)
                {
                    int x[5];
                    int i;
                    x[0] = (1*nx)/6+1;
                    x[1] = (2*nx)/6+1;
                    x[2] = (3*nx)/6+1;
                    x[3] = (4*nx)/6+1;
                    x[4] = (5*nx)/6+1;
                    
                    for (i = 0; i < 5; i++)
                        {
                            cpl_table_set_int(*ordertable, "Order", row, order);
                            cpl_table_set_int(*ordertable, "X", row, x[i]);
                            cpl_table_set_double(*ordertable, "Yfit", row, 
                                                 uves_polynomial_evaluate_2d(*order_locations,
                                                                             x[i], order));
                            row++;
                        }
                }
        }
  
  /* Not implemented: */
  /* Fill tracetable */
    tracetable = tracetable; /* suppress warnings */
  
 cleanup:
  uves_free_propertylist(&header);
  return;
}

/*----------------------------------------------------------------------------*/
/**
   @brief    Create line table
   @param    linetable       (output) line table
   @param    dispersion      (output) dispersion
   @param    abs_orders      (output) map from relative to absolute orders (x,y)
   @param    firstabs        (output) if non-NULL, first absolute order number
                             abs_orders must be provided
   @param    lastabs         (output) if non-NULL, last absolute order number
                             abs_orders must be provided
   @param    minorder        minimum order
   @param    maxorder        maximum order
   @param    nx              sampling size
*/
/*----------------------------------------------------------------------------*/
void
create_line_table(cpl_table **linetable, 
                  polynomial **dispersion, 
                  polynomial **abs_orders,
                  int *firstabs, 
                  int *lastabs,
                  int minorder, 
                  int maxorder, 
                  int nx)
{
    polynomial *order_locations = NULL;
    cpl_table *ordertable = NULL;
    cpl_table *tracetable = NULL;
    const bool midas_format = false;

    const char *ORDER = midas_format ? "ORDER" : "Order";
    const char *IDENT = midas_format ? "IDENT" : "Ident";
    const char *YNEW = midas_format ? "YNEW" : "Ynew";

    create_order_table(&ordertable, &order_locations, &tracetable,
                       minorder, maxorder, nx);

    assure_nomsg(linetable != NULL, CPL_ERROR_NULL_INPUT);
    
    {
        int row = 0;
        *linetable = cpl_table_new(cpl_table_get_nrow(ordertable));
        cpl_table_new_column(*linetable, "X", CPL_TYPE_DOUBLE);
        cpl_table_new_column(*linetable, YNEW, CPL_TYPE_DOUBLE);
        cpl_table_new_column(*linetable, "Y", CPL_TYPE_INT);
        cpl_table_new_column(*linetable, ORDER, CPL_TYPE_INT);
        cpl_table_new_column(*linetable, LINETAB_LAMBDAC, CPL_TYPE_DOUBLE);
        cpl_table_new_column(*linetable, IDENT, CPL_TYPE_DOUBLE);
        cpl_table_new_column(*linetable, "Aux", CPL_TYPE_DOUBLE);
        for (row = 0; row < cpl_table_get_nrow(ordertable); row++)
            {
                int order = cpl_table_get_int(ordertable, "Order", row, NULL);
                double x  = cpl_table_get_int(ordertable, "X", row, NULL);
                double y  = cpl_table_get_double(ordertable, "Yfit", row, NULL);
                int m = 120 - order; /* absolute order number */
                double lambda = 3000 + 50*(order - minorder) + 80*(x*1.0/nx);
                
                cpl_table_set_double(*linetable, "X", row, x);
                cpl_table_set_double(*linetable, YNEW, row, y);
                cpl_table_set_int(*linetable, "Y", row, order);   /* it's correct! */
                cpl_table_set_int(*linetable, ORDER, row, m);
                cpl_table_set_double(*linetable, LINETAB_LAMBDAC, row, lambda);
                cpl_table_set_double(*linetable, IDENT, row, lambda); /* exact! */
                cpl_table_set_double(*linetable, "Aux", row, lambda*m);
            }
    }
    
    if (abs_orders != NULL)
        {
            /* Create polynomial
               absorders(x, y) = m
            */
            int degree = 2;
            check_nomsg(
            *abs_orders = uves_polynomial_regression_2d(*linetable,
                                                        "X", YNEW, ORDER, NULL,
                                                        degree, degree,
                                                        NULL, NULL, NULL, /* new columns */
                                                        NULL, NULL, /* mse, red_chisq */
                                                        NULL, -1, -1)); /* variance, kappa */
            if (firstabs != NULL) {
                double x = nx/2;
                double y = 
                    uves_polynomial_evaluate_2d(order_locations, x, minorder);
                
                *firstabs = uves_round_double(
                    uves_polynomial_evaluate_2d(*abs_orders, x, y));
            }
            if (lastabs != NULL) {
                double x = nx/2;
                double y = 
                    uves_polynomial_evaluate_2d(order_locations, x, maxorder);
                
                *lastabs = uves_round_double(
                    uves_polynomial_evaluate_2d(*abs_orders, x, y));
            }

        }

    if (dispersion != NULL)
        {
            /* Create polynomial of this form
               f(x, m) = lambda m
            */
            int degree = 2;
            check_nomsg(
            *dispersion = uves_polynomial_regression_2d(*linetable,
                                                        "X", ORDER, "Aux", NULL,
                                                        degree, degree,
                                                        NULL, NULL, NULL, /* new columns */
                                                        NULL, NULL, /* mse, red_chisq */
                                                        NULL, -1, -1)); /* variance, kappa */
        }
    
 cleanup:
    uves_polynomial_delete(&order_locations);
    uves_free_table(&ordertable);
    uves_free_table(&tracetable);
    return;
}
/**@}*/
