/* -*- 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-2013 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.
 */

#include <muse.h>

/*----------------------------------------------------------------------------*/
/**
  @brief    short test program to check that muse_cosmics_dcr() does what it
            should when called on (part of) a (simulated) MUSE science exposure
            that has already been bias-corrected and trimmed.
 */
/*----------------------------------------------------------------------------*/
int main(int argc, char **argv)
{
  cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_DEBUG);

  muse_image *image = NULL;
  if (argc == 2) {
    /* assume that the file passed on the command line is an input image */
    cpl_msg_info(__func__, "command line argument detected, will try to load %s",
                 argv[1]);
    image = muse_image_load(argv[1]);
  } else {
    image = muse_image_load(BASEFILENAME"_in.fits");
  }

  if (!image->data) {
    cpl_msg_error(__func__, "Could not load test image: %s", cpl_error_get_message());
    muse_image_delete(image);
    return cpl_test_end(2);
  }

  /* use default values from muse_wavecal */
  int ncr = muse_cosmics_dcr(image, 15, 40, 2, 4.5);
  cpl_test(ncr > 0);
  if (ncr > 0) {
    cpl_msg_info(__func__, "Found %d pixels affected by cosmic rays", ncr);

    /* just for display, replace all affected pixels with NAN */
    float *data = cpl_image_get_data_float(image->data);
    int *dq = cpl_image_get_data_int(image->dq);
    int nx = cpl_image_get_size_x(image->data),
        ny = cpl_image_get_size_y(image->data);
    int i;
    for (i = 0; i < nx; i++) {
      int j;
      for (j = 0; j < ny; j++) {
        if (dq[i + j*nx] & EURO3D_COSMICRAY) {
          data[i + j*nx] = NAN;
        }
      } /* for j */
    } /* for i */
    muse_image_save(image, "cosmics_dcr.fits");
  }
  muse_image_delete(image);

  return cpl_test_end(0);
}
