/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set sw=2 sts=2 et cin: */
/*
 * This file is part of the MUSE Instrument Pipeline
 * Copyright (C) 2007-2014 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#define _DEFAULT_SOURCE
#define _BSD_SOURCE /* get mkdtemp() from stdlib.h */
#include <unistd.h> /* rmdir() */
#include <stdio.h> /* remove() */
#include <sys/stat.h> /* mkdir() */
#include <string.h>

#include <muse.h>
#include <muse_instrument.h>

#define DIR_TEMPLATE "/tmp/muse_lsf_test_XXXXXX"

static void
test_lsf_apply(const char *aDir)
{
  UNUSED_ARGUMENT(aDir);
  char *sfilename = cpl_sprintf(BASEFILENAME"_cube.fits");
  muse_lsf_cube *lsfCube = muse_lsf_cube_load(sfilename, 11);
  cpl_free(sfilename);
  if (lsfCube == NULL) {
    return;
  }

  // Test that the values are within the some reasonable values. Also test that
  // we can use values within a certain range (+-20).
  cpl_array *lsf = cpl_array_new(5, CPL_TYPE_DOUBLE);
  cpl_array_set_double(lsf, 0, -20);
  cpl_array_set_double(lsf, 1, -2);
  cpl_array_set_double(lsf, 2, 0.1);
  cpl_array_set_double(lsf, 3, 2.7);
  cpl_array_set_double(lsf, 4, 20);

  double lambda = 6000;
  cpl_array *val = cpl_array_duplicate(lsf);
  muse_lsf_apply(cpl_imagelist_get(lsfCube->img, 0),
                 lsfCube->wcs, val, lambda);
  int res;
  cpl_test_leq(cpl_array_get(val, 0, &res), 1e-3);
  cpl_test_eq(res, 0);
  cpl_test_leq(cpl_array_get(val, 1, &res), 1e-1);
  cpl_test_eq(res, 0);
  cpl_test_leq(1e-1, cpl_array_get(val, 2, &res));
  cpl_test_eq(res, 0);
  cpl_test_leq(cpl_array_get(val, 3, &res), 1e-1);
  cpl_test_eq(res, 0);
  cpl_test_leq(cpl_array_get(val, 4, &res), 1e-3);
  cpl_test_eq(res, 0);

  cpl_array_delete(val);
  cpl_array_delete(lsf);

  // Test that the LSF is well centered and normalized
  cpl_size n_val = 1000;
  double step = 20./(n_val - 1);
  lsf = cpl_array_new(n_val, CPL_TYPE_DOUBLE);
  cpl_size i;
  for (i = 0; i < n_val; i++) {
    cpl_array_set(lsf, i, -10. + step * i);
  }
  for (lambda = 4500; lambda < 9500; lambda += 122) {
    val = cpl_array_duplicate(lsf);
    muse_lsf_apply(cpl_imagelist_get(lsfCube->img, 1),
                   lsfCube->wcs, val, lambda);
    cpl_test_abs(cpl_array_get_mean(val) * n_val * step, 1.0, 1e-3);
    cpl_array * v = cpl_array_duplicate(lsf);
    cpl_array_multiply(v, val);
    cpl_test_abs(cpl_array_get_mean(v)/cpl_array_get_mean(val), 0.0, 1e-4);
    cpl_array_delete(val);
    cpl_array_delete(v);
  }
  cpl_array_delete(lsf);

  muse_lsf_cube_delete(lsfCube);
}

static void
test_lsf_fit(const char *aDir)
{
  UNUSED_ARGUMENT(aDir);
  char *sfilename = cpl_sprintf(BASEFILENAME"_pixtable.fits");
  muse_pixtable *pixtable = cpl_calloc(1, sizeof(muse_pixtable));
  pixtable->table = cpl_table_load(sfilename, 1, 0);
  /* header can stay empty for this test */
  cpl_free(sfilename);
  if (pixtable == NULL) {
    return;
  }
  cpl_image *img = cpl_image_new(120, 30, CPL_TYPE_DOUBLE);
  muse_wcs *wcs = cpl_calloc(1, sizeof(muse_wcs));
  wcs->cd11 = 0.1;
  wcs->cd12 = 0;
  wcs->cd21 = 0;
  wcs->cd22 = 160;
  wcs->crval1 = -6;
  wcs->crval2 = kMuseNominalLambdaMin;
  wcs->crpix1 = 1;
  wcs->crpix2 = 1;

  double window = 0.7;
  if (!cpl_table_has_column(pixtable->table, "line_background")) {
    cpl_table_new_column(pixtable->table, "line_background", CPL_TYPE_FLOAT);
    cpl_table_fill_column_window_float(pixtable->table, "line_background",
                                       0, cpl_table_get_nrow(pixtable->table),
                                       0.0);
  }

  int res = muse_lsf_fit_slice(pixtable, img, wcs, window);
  cpl_test_eq(res, 0);

  // Test that the function raises on the left half and decreases
  // on the right half. Also check for some specific points.
  // (left border, center, right border)
  cpl_size nx = cpl_image_get_size_x(img);
  cpl_size ny = cpl_image_get_size_y(img);
  cpl_size y;
  for (y = 1; y <= ny; y++) {
    cpl_size x;
    double old = 0;
    int up = 1;
    cpl_test_lt(cpl_image_get(img, 1, y, &res), 2e-2);
    cpl_test_lt(cpl_image_get(img, nx, y, &res), 2e-2);
    cpl_test_lt(0.2, cpl_image_get(img, nx/2, y, &res));
    for (x = 1; x <= nx; x++) {
      double z = cpl_image_get(img, x, y, &res);
      cpl_test_eq(res, 0);
      if (x < 0.45 * nx) {
        cpl_test_leq(old, z + 1e-2);
      } else if (!up || (x > 0.55 * nx)) {
        cpl_test_leq(z, old + 1e-2);
      } else if (up && (old > z)) {
        up = 0;
      }
      old = z;
    }
  }

  cpl_free(wcs);
  cpl_image_delete(img);
  muse_pixtable_delete(pixtable);
}

/*----------------------------------------------------------------------------*/
/**
  @brief    short test program to check LSF-related stuff.
 */
/*----------------------------------------------------------------------------*/
int main(int argc, char **argv)
{
  UNUSED_ARGUMENTS(argc, argv);
  cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_INFO);

  char dirtemplate[FILENAME_MAX] = DIR_TEMPLATE;
  char *dir = mkdtemp(dirtemplate);
  test_lsf_apply(dir);
  test_lsf_fit(dir);

  cpl_test_zero(rmdir(dir));
  return cpl_test_end(0);
}
