/* -*- 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_musetraceplotwidths      Tool muse_trace_plot_widths
 *
 * <b>muse_trace_plot_widths</b>: Plot tracing widths.
 *
 * Debug tracing issues using a graphical representation of the slice widhts
 * detected during tracing from information written into the TRACE_SAMPLES table
 * by the muse_flat recipe.
 *
 * <b>Command line arguments:</b>
 *   - <tt>-s1 first_slice</tt> (optional, default: 1)\n
 *     first slice number for plotting
 *   - <tt>-s2 last_slice</tt> (optional, default: 48)\n
 *     last slice number for plotting
 *   - <tt>-n nifu</tt> (optional, default: load first FITS extension with data)\n
 *     IFU/channel number to use
 *   - <tt><b>TRACE_SAMPLES</b></tt>\n
 *     the filename of the tracing samples 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>-s1</tt> without any number
 *   - <tt> 3</tt>\n   argument <tt>-s2</tt> without any number
 *   - <tt> 4</tt>\n   argument <tt>-n</tt> without any number
 *   - <tt> 5</tt>\n   argument <tt>-n</tt> with invalid IFU number
 *   - <tt> 9</tt>\n   unknown option given
 *   - <tt>10</tt>\n   samples table could not be loaded from file
 *   - <tt>11</tt>\n   file does not seem to contain a MUSE samples table
 *   - <tt>12</tt>\n   temporary file for plotting could not be created
 *   - <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 [ -s1 first_slice ] [ -s2 last_slice ] "          \
          "[ -n nifu ] TRACE_SAMPLES\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 *tsname = NULL; /* samples table */
  short slice1 = 1,
        slice2 = 48;
  unsigned char nifu = 0; /* IFU number to load */

  /* argument processing */
  int i;
  for (i = 1; i < argc; i++) {
    if (strncmp(argv[i], "-s1", 4) == 0) {
      /* skip to next arg to first slice number */
      i++;
      if (i < argc) {
        slice1 = atoi(argv[i]);
      } else {
        PRINT_USAGE(2);
      }
    } else if (strncmp(argv[i], "-s2", 4) == 0) {
      /* skip to next arg to last slice number */
      i++;
      if (i < argc) {
        slice2 = atoi(argv[i]);
      } else {
        PRINT_USAGE(3);
      }
    } 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(5);
        }
      } else {
        PRINT_USAGE(4);
      }
    } else if (strncmp(argv[i], "-", 1) == 0) { /* unallowed options */
      PRINT_USAGE(9);
    } else {
      if (tsname) {
        break; /* we have the possible names, skip the rest */
      }
      tsname = argv[i]; /* set the name for the samples table */
    }
  } /* for i (all arguments) */

  int iext = 1;
  if (nifu) {
    iext = muse_utils_get_extension_for_ifu(tsname, nifu);
  }
  cpl_table *ts = cpl_table_load(tsname, iext, 1);
  if (!ts) {
    fprintf(stderr, "%s: %s: %s\n", argv[0], tsname, cpl_error_get_message());
    /* fail, this is mandatory */
    PRINT_USAGE(10);
  }
  cpl_propertylist *header = cpl_propertylist_load(tsname, iext);
  char *extname = NULL;
  if (cpl_propertylist_has(header, "EXTNAME")) {
    extname = cpl_sprintf("[%s]", muse_pfits_get_extname(header));
  }
  printf("MUSE TRACE_SAMPLES table \"%s%s\", contains %"CPL_SIZE_FORMAT" rows\n",
         tsname, extname ? extname : "", cpl_table_get_nrow(ts));
  extname = NULL;
  cpl_propertylist_delete(header);

  cpl_error_code rc = muse_trace_plot_widths(ts, slice1, slice2, nifu);
  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 tracing "
            "samples table!\n", argv[0], tsname, extname ? extname : "");
    rc = 11;
    break;
  case CPL_ERROR_FILE_NOT_CREATED:
    /* use manipulated CPL error message to show the failing file name */
    fprintf(stderr, "%s: %s (temporary file for plotting)\n",
            argv[0], cpl_error_get_message());
    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(ts);
  cpl_end();
  return rc;
}

/**@}*/
