/* -*- 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) 2018-19 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>
#include <string.h>
#include <strings.h>

/*----------------------------------------------------------------------------*/
/**
 * @defgroup tools_musedarkimagemodel       Tool muse_dark_image_model
 *
 * <b>muse_dark_image_model</b>: Compute model from bias-subtracted master dark.
 *
 * Combine cubes that were resampled onto the same output grid but using data of
 * different wavelength ranges into a single output cube.
 *
 * <b>Command line arguments:</b>
 *   - <tt>-i IFU</tt> (optional)\n
 *     load data of the given IFU; if not given, try to loop through all IFUs
 *   - <tt><b>IMAGE</b></tt>\n
 *     the filename of the input MASTER_DARK
 *   - <tt><b>MODEL</b></tt>\n
 *     the filename of the output dark model; if no IFU number is given, the
 *     name is interpreted as basename and the -NN is added before .fits for
 *     all IFUs.
 *
 * <b>Return values:</b>
 *   - <tt> 0</tt>\n   Success
 *   - <tt> 1</tt>\n   less than two filenames given
 *   - <tt> 2</tt>\n   argument <tt>-i</tt> given without IFU number
 *   - <tt> 9</tt>\n   unknown option given
 *   - <tt>10</tt>\n   no output filename found
 *   - <tt>11</tt>\n   loading data from input filename failed
 */
/*----------------------------------------------------------------------------*/

/**@{*/

#define PRINT_USAGE(rc)                                                        \
  fprintf(stderr, "Usage: %s [ -i IFU ] IMAGE MODEL\n", argv[0]);              \
  cpl_end(); return (rc);

int main(int argc, char **argv)
{
  cpl_init(CPL_INIT_DEFAULT);
  cpl_errorstate state = cpl_errorstate_get();
  muse_processing_recipeinfo(NULL);
  cpl_msg_set_level(CPL_MSG_DEBUG);

  if (argc < 3) {
    /* two filenames are needed at least */
    PRINT_USAGE(1);
  }

  char *iname = NULL, /* image name */
       *oname = NULL; /* output name */
  unsigned char ifu = 0;

  /* argument processing */
  int i;
  for (i = 1; i < argc; i++) {
    if (strncmp(argv[i], "-i", 3) == 0) {
      /* skip to next arg to get sigma value */
      i++;
      if (i < argc) {
        ifu = atoi(argv[i]);
      } else {
        PRINT_USAGE(2);
      }
    } else if (strncmp(argv[i], "-", 1) == 0) { /* unallowed options */
      PRINT_USAGE(9);
    } else {
      if (iname && oname) {
        break; /* we have the possible names, skip the rest */
      }
      if (iname) {
        oname = argv[i] /* set the name for the output */;
        break;
      }
      iname = argv[i] /* set the name for the image */;
    }
  } /* for i (all arguments) */

  if (!oname) {
    PRINT_USAGE(10);
  }

  if (ifu > 0) {
    muse_image *image = muse_image_load_from_extensions(iname, ifu);
    if (!image) {
      PRINT_USAGE(11);
    }
    muse_basicproc_darkmodel(image);
    muse_image_save(image, oname);
    cpl_msg_info(__func__, "Saved to \"%s\".", oname);
    muse_image_delete(image);
  } else {
    unsigned int nifu = 0;
    for (ifu = 1; ifu <= kMuseNumIFUs; ifu++) {
      muse_image *image = muse_image_load_from_extensions(iname, ifu);
      if (!image) {
        continue;
      }
      cpl_msg_info(__func__, "Modeling the master dark in IFU %02hhu:", ifu);
      cpl_msg_indent_more();
      muse_basicproc_darkmodel(image);
      char *name = cpl_strdup(oname),
           *p = strstr(name, ".fits");
      *p = '\0'; /* strip off the extension */
      char *outfn = cpl_sprintf("%s-%02hhu.fits", name, ifu);
      cpl_free(name);
      muse_image_save(image, outfn);
      cpl_msg_info(__func__, "Saved to \"%s\".", outfn);
      muse_image_delete(image);
      cpl_msg_indent_less();
      cpl_free(outfn);
      nifu++;
    } /* for ifu (all IFUs) */
    if (nifu < 1) {
      cpl_msg_error(__func__, "Could not load the data of any IFU from \"%s\"",
                    iname);
      PRINT_USAGE(12);
    }
    cpl_msg_info(__func__, "Processed data of %u IFUs", nifu);
  } /* else: all IFUs */

  if (!cpl_errorstate_is_equal(state)) {
    muse_cplerrorstate_dump_some(0, 0, 0);
  }
  cpl_memory_dump();
  cpl_end();
  return 0;
}

/**@}*/
