/* -*- 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-2015 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>

/*----------------------------------------------------------------------------*/
/**
 * @defgroup tools_musewaveplotresiduals    Tool muse_wave_plot_residuals
 *
 * <b>muse_wave_plot_residuals</b>: Plot wavelength calibration residuals.
 *
 * Debug wavelength calibration issues using a graphical representation of the
 * wavelength calibration fit residuals written into the WAVECAL_RESIDUALS table
 * by the muse_wavecal recipe.
 *
 * <b>Command line arguments:</b>
 *   - <tt>-n nifu</tt> (optional, default: load first FITS extension with data)\n
 *     IFU/channel number to use
 *   - <tt>-s slice</tt> (optional, default: 0 = all slices)\n
 *     slice number for plotting
 *   - <tt>-i iteration</tt> (optional, default: 0 = last iteration)\n
 *     iteration to plot
 *   - <tt>-l</tt> (optional)\n
 *     plot over lambda rather than over vertical pixel coordinate
 *   - <tt>-c</tt> (optional)\n
 *     two values to determine the color cuts for the plot
 *   - <tt><b>WAVECAL_RESIDUALS</b></tt>\n
 *     the filename of the wavelength calibration residuals file to use
 *
 * <b>Return values:</b>
 *   - <tt> 0</tt>\n   Success
 *   - <tt> 1</tt>\n   no filename given
 *   - <tt> 2</tt>\n   argument <tt>-s</tt> without any number
 *   - <tt> 3</tt>\n   argument <tt>-i</tt> without any number
 *   - <tt> 4</tt>\n   argument <tt>-c</tt> without numbers
 *   - <tt> 5</tt>\n   argument <tt>-n</tt> without any number
 *   - <tt> 6</tt>\n   argument <tt>-n</tt> with invalid IFU number
 *   - <tt> 9</tt>\n   unknown option given
 *   - <tt>10</tt>\n   residuals table could not be loaded from file
 *   - <tt>11</tt>\n   file does not seem to contain a MUSE residuals table
 *   - <tt>12</tt>\n   requested iteration not found in the table
 *   - <tt>20</tt>\n   the platform does not support pipes [popen()/pclose()]
 *   - <tt>21</tt>\n   gnuplot could not be opened
 *   - <tt>50</tt>\n   unknown error
 *
 * @note This program only works, if the gnuplot plotting program is installed.
 */
/*----------------------------------------------------------------------------*/

/**@{*/

#define PRINT_USAGE(rc)                                                        \
  fprintf(stderr, "Usage: %s [ -n nifu ] [ -s slice ] [ -i iteration ] [ -l ] "\
          "[ -c c1 c2 ] WAVECAL_RESIDUALS\n", argv[0]);                        \
  cpl_end(); return (rc);

int main(int argc, char **argv)
{
  cpl_init(CPL_INIT_DEFAULT);
  muse_processing_recipeinfo(NULL);

  if (argc <= 1) {
    /* filename is needed at least */
    PRINT_USAGE(1);
  }

  char *tname = NULL;
  unsigned char nifu = 0; /* IFU number to load */
  unsigned short slice = 0;
  unsigned int iteration = 0;
  cpl_boolean lambda = CPL_FALSE;
  cpl_vector *cuts = NULL;

  /* argument processing */
  int i;
  for (i = 1; i < argc; i++) {
    if (strncmp(argv[i], "-s", 3) == 0) {
      /* skip to next arg to get slice number */
      i++;
      if (i < argc) {
        slice = atol(argv[i]);
      } else {
        PRINT_USAGE(2);
      }
    } else if (strncmp(argv[i], "-i", 3) == 0) {
      /* skip to next arg to get iteration value */
      i++;
      if (i < argc) {
        iteration = atol(argv[i]);
      } else {
        cpl_vector_delete(cuts);
        PRINT_USAGE(3);
      }
    } else if (strncmp(argv[i], "-c", 3) == 0) {
      cuts = cpl_vector_new(2);
      /* skip to next arg to get iteration value */
      i++;
      if (i + 1 < argc) {
        cpl_vector_set(cuts, 0, atof(argv[i++]));
        cpl_vector_set(cuts, 1, atof(argv[i]));
      } else {
        PRINT_USAGE(4);
      }
    } else if (strncmp(argv[i], "-n", 3) == 0) {
      /* skip to next arg to get extension name */
      i++;
      if (i < argc) {
        nifu = atoi(argv[i]);
        if (nifu == 0 || nifu > kMuseNumIFUs) {
          PRINT_USAGE(6);
        }
      } else {
        PRINT_USAGE(5);
      }
    } else if (strncmp(argv[i], "-l", 3) == 0) {
      lambda = CPL_TRUE;
    } else if (strncmp(argv[i], "-", 1) == 0) { /* unallowed options */
      PRINT_USAGE(9);
    } else {
      tname = argv[i];
      break; /* we have the required name, skip the rest */
    }
  }

  int iext = 1;
  if (nifu) {
    iext = muse_utils_get_extension_for_ifu(tname, nifu);
  }
  cpl_table *table = cpl_table_load(tname, iext, 1);
  if (!table) {
    PRINT_USAGE(10);
  }
  /* get extension names for the output messages */
  char *extname = NULL;
  cpl_propertylist *header = cpl_propertylist_load(tname, iext);
  if (cpl_propertylist_has(header, "EXTNAME")) {
    extname = cpl_sprintf("[%s]", muse_pfits_get_extname(header));
  }
  cpl_propertylist_delete(header);

  printf("MUSE WAVECAL_RESIDUALS table \"%s%s\", contains %"CPL_SIZE_FORMAT
         " rows\n", tname, extname ? extname : "", cpl_table_get_nrow(table));
  cpl_error_code rc = muse_wave_plot_residuals(table, nifu, slice, iteration,
                                               lambda, cuts);
  cpl_vector_delete(cuts);
  switch (rc) {
  case CPL_ERROR_NONE:
    rc = 0;
    break;
  case CPL_ERROR_ILLEGAL_INPUT:
    fprintf(stderr, "%s: \"%s%s\" does not seem to contain a MUSE wavelength "
            "calibration residuals table!\n", argv[0], tname,
            extname ? extname : "");
    rc = 11;
    break;
  case CPL_ERROR_DATA_NOT_FOUND:
    if (iteration > 0) {
      fprintf(stderr, "%s: \"%s%s\" does not seem to contain data for slice %d "
              "and iteration %d!\n", argv[0], tname, extname ? extname : "",
              slice, iteration);
    } else {
      fprintf(stderr, "%s: \"%s%s\" does not seem to contain data for slice %d "
              "and the last iteration!\n", argv[0], tname,
              extname ? extname : "", slice);
    }
    rc = 12;
    break;
  case CPL_ERROR_UNSUPPORTED_MODE:
    fprintf(stderr, "%s: your platform does not seem to support pipes "
            "[popen()/pclose()]!\n", argv[0]);
    rc = 20;
    break;
  case CPL_ERROR_ASSIGNING_STREAM:
    fprintf(stderr, "%s: could not open gnuplot (this tool uses it for "
            "plotting)!\n", argv[0]);
    rc = 21;
    break;
  default:
    rc = 50;
  } /* switch */
  cpl_free(extname);

  cpl_table_delete(table);
  cpl_end();
  return rc;
}

/**@}*/
