/* -*- 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) 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_sky_master_test_XXXXXX"

/*----------------------------------------------------------------------------*/
/**
  @brief    Test program for the sky_master related public functions.

  This is basically a simple re-work of muse_create_sky.
 */
/*----------------------------------------------------------------------------*/
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);

  int res;
  muse_pixtable *pixtable = muse_pixtable_load(BASEFILENAME"_pixtable.fits");
  double binning_spectrum = 0.3125;
  cpl_table *spectrum = muse_resampling_spectrum(pixtable, binning_spectrum);
  cpl_table *lines = cpl_table_load(BASEFILENAME"_lines.fits", 1, 1);
  muse_lsf_cube *lsfCube = muse_lsf_cube_load(BASEFILENAME"_lsf_cube.fits", 7);
  cpl_image *lsfImage = cpl_imagelist_get(lsfCube->img, 12);
  muse_wcs *lsfWCS = lsfCube->wcs;

  cpl_table_unselect_all(lines);
  cpl_table_or_selected_double(lines, "lambda", CPL_GREATER_THAN,
                               cpl_table_get_column_max(spectrum, "lambda"));
  cpl_table_or_selected_double(lines, "lambda", CPL_LESS_THAN,
                               cpl_table_get_column_min(spectrum, "lambda"));
  cpl_table_erase_selected(lines);

  muse_sky_lines_fit(spectrum, lines, lsfImage, lsfWCS);

  // test estimated line fluxes and wavelengths, one per line group
  struct {
    const char *name;
    double lambda;
    double flux;
  } ref[] = {
    { "OH(1601)X -X (07-03)Q11(01.5f)", 8825, 2553.},
    { "OH(1601)X -X (06-02)Q11(01.5f)", 8343, 1523.},
    { "O2(1616)b -X (00-01)P12(07.0 )", 8659, 502.},
    { NULL,   -1,   -1}  // end marker
  };
  cpl_size i;
  for (i = 0; ref[i].name != NULL; i++) {
    cpl_size i_row;
    cpl_size n_rows = cpl_table_get_nrow(lines);
    for (i_row = 0; i_row < n_rows; i_row++) {
      if (strcmp(ref[i].name, cpl_table_get_string(lines, "name", i_row)) == 0) {
        break;
      }
    }
    cpl_test_rel(cpl_table_get(lines, "flux", i_row, &res),
                 ref[i].flux, 0.05);
    cpl_test_eq(res, 0);
    cpl_test_abs(cpl_table_get(lines, "lambda", i_row, &res),
                 ref[i].lambda, 1.0);
    cpl_test_eq(res, 0);
  }

  double binning_continuum = 1.25;
  cpl_table *continuum = muse_sky_continuum_create(spectrum, lines,
                                                   lsfImage, lsfWCS,
                                                   binning_continuum);
  // test continuum binning
  cpl_test_abs(cpl_table_get(continuum, "lambda", 0, &res) + binning_continuum,
               cpl_table_get(continuum, "lambda", 1, &res), 0.01);
  cpl_test_eq(res, 0);

  // test flux conservation
  double flux_orig = cpl_table_get_column_mean(spectrum, "data")
    * cpl_table_get_nrow(spectrum) * binning_spectrum;
  double flux_continuum = cpl_table_get_column_mean(continuum, "flux")
    * cpl_table_get_nrow(continuum) * binning_continuum;
  double flux_lines = cpl_table_get_column_mean(lines, "flux")
    * cpl_table_get_nrow(lines);
  cpl_test_rel(flux_orig, flux_lines + flux_continuum, 0.02);

  // test (reasonable) standard deviation. This is not too tight since the
  // used LSF does not really fit to the data.
  cpl_test_leq(cpl_table_get_column_stdev(continuum, "flux"), 30);

  // cleanup
  cpl_table_delete(continuum);
  cpl_table_delete(spectrum);
  cpl_table_delete(lines);
  muse_lsf_cube_delete(lsfCube);
  muse_pixtable_delete(pixtable);

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