/* -*- 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) 2011-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_musewaveplotcolumn       Tool muse_wave_plot_column
 *
 * <b>muse_wave_plot_column</b>: Plot wavelength calibration for one CCD column.
 *
 * Debug wavelength calibration issues using a graphical representation of the
 * wavelength solution for a single CCD column using data written into the tables
 * WAVECAL_TABLE and WAVECAL_RESIDUALS 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, plots the central column of the slice
 *   - <tt>-i iteration</tt> (optional, default: 0 = last iteration)\n
 *     iteration to plot
 *   - <tt>-c column</tt> (optional, default: 0 = all slices)\n
 *     CCD column to plot
 *   - <tt>-r</tt> (optional)\n
 *     plot residuals rather than absolute values
 *   - <tt><b>WAVECAL_TABLE</b></tt>\n
 *     the filename of the wavelength calibration file to use
 *   - <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 any number
 *   - <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>12</tt>\n   requested slice number is invalid
 *   - <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 ] "       \
          "[ -c column ] [ -r ] WAVECAL_TABLE 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 *tcname = NULL,
       *trname = NULL;
  unsigned short slice = 24;
  unsigned char nifu = 0; /* IFU number to load */
  unsigned int iteration = 0,
               column = 0; /* default to central column of slice */
  cpl_boolean residuals = CPL_FALSE;

  /* 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 {
        PRINT_USAGE(3);
      }
    } else if (strncmp(argv[i], "-c", 3) == 0) {
      /* skip to next arg to get iteration value */
      i++;
      if (i < argc) {
        column = atol(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], "-r", 3) == 0) {
      residuals = CPL_TRUE;
    } else if (strncmp(argv[i], "-", 1) == 0) { /* unallowed options */
      PRINT_USAGE(9);
    } else {
      if (tcname && trname) {
        break; /* we have the possible names, skip the rest */
      }
      if (!tcname) {
        tcname = argv[i];
      } else {
        trname = argv[i];
      }
    }
  }

  int iextc = 1,
      iextr = 1;
  if (nifu) {
    iextc = muse_utils_get_extension_for_ifu(tcname, nifu);
    iextr = muse_utils_get_extension_for_ifu(trname, nifu);
  }
  cpl_table *ctable = cpl_table_load(tcname, iextc, 1),
            *rtable = cpl_table_load(trname, iextr, 1);
  if (!ctable || !rtable) {
    cpl_table_delete(ctable);
    cpl_table_delete(rtable);
    PRINT_USAGE(10);
  }

  /* get extension names for the output messages */
  char *extnamer = NULL,
       *extnamec = NULL;
  cpl_propertylist *header = cpl_propertylist_load(tcname, iextc);
  if (cpl_propertylist_has(header, "EXTNAME")) {
    extnamec = cpl_sprintf("[%s]", muse_pfits_get_extname(header));
  }
  cpl_propertylist_delete(header);
  header = cpl_propertylist_load(trname, iextr);
  if (cpl_propertylist_has(header, "EXTNAME")) {
    extnamer = cpl_sprintf("[%s]", muse_pfits_get_extname(header));
  }
  cpl_propertylist_delete(header);

  /* report success of loading the tables */
  printf("MUSE WAVECAL_TABLE table \"%s%s\", contains %"CPL_SIZE_FORMAT" rows\n",
         tcname, extnamec ? extnamec : "", cpl_table_get_nrow(ctable));
  printf("MUSE WAVECAL_RESIDUALS table \"%s%s\", contains %"CPL_SIZE_FORMAT
         " rows\n", trname, extnamer ? extnamer : "", cpl_table_get_nrow(rtable));

  cpl_error_code rc = muse_wave_plot_column(ctable, rtable, nifu, slice, column,
                                            iteration, residuals);
  switch (rc) {
  case CPL_ERROR_NONE:
    rc = 0;
    break;
  case CPL_ERROR_ILLEGAL_INPUT:
    fprintf(stderr, "%s: one of the tables \"%s%s\"/\"%s%s\" does not seem to "
            "contain valid MUSE information!\n", argv[0],
            tcname, extnamec ? extnamec : "", trname, extnamer ? extnamer : "");
    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 %u!\n", argv[0], trname, extnamer ? extnamer : "",
              slice, iteration);
    } else {
      fprintf(stderr, "%s: \"%s%s\" does not seem to contain data for slice %d "
              "and the last iteration!\n", argv[0], trname,
              extnamer ? extnamer : "", slice);
    }
    rc = 12;
    break;
  case CPL_ERROR_ACCESS_OUT_OF_RANGE:
    fprintf(stderr, "%s: the requested slice number (%d) is invalid!\n",
            argv[0], slice);
    rc = 13;
    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(extnamec);
  cpl_free(extnamer);

  cpl_table_delete(ctable);
  cpl_table_delete(rtable);
  cpl_end();
  return rc;
}

/**@}*/
