/*
 * This file is part of the ESO UVES Pipeline
 * Copyright (C) 2004,2005 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, 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
 */

/*
 * $Author: amodigli $
 * $Date: 2010-09-24 09:32:03 $
 * $Revision: 1.58 $
 * $Name: not supported by cvs2svn $
 * $Log: not supported by cvs2svn $
 * Revision 1.56  2007/08/21 11:08:10  jmlarsen
 * Readded checks for pre-existing error which was provided by irplib_error_assure but not by cpl_error_ensure
 *
 * Revision 1.55  2007/08/13 12:15:58  amodigli
 * support of CPL4
 *
 * Revision 1.54  2007/06/06 08:17:33  amodigli
 * replace tab with 4 spaces
 *
 * Revision 1.53  2007/01/08 16:58:52  amodigli
 * added ck0 and cknull
 *
 * Revision 1.52  2006/11/06 15:19:41  jmlarsen
 * Removed unused include directives
 *
 * Revision 1.51  2006/08/17 13:56:52  jmlarsen
 * Reduced max line length
 *
 * Revision 1.50  2006/06/01 14:43:17  jmlarsen
 * Added missing documentation
 *
 * Revision 1.49  2006/05/05 13:54:11  jmlarsen
 * Added assure_mem
 *
 * Revision 1.48  2006/04/24 09:19:25  jmlarsen
 * Minor message change
 *
 * Revision 1.47  2006/04/06 08:31:52  jmlarsen
 * Dump trace on CPL_MSG_ERROR level
 *
 * Revision 1.46  2006/03/09 10:57:57  jmlarsen
 * Added check_nomsg macro
 *
 * Revision 1.45  2006/03/03 13:54:11  jmlarsen
 * Changed syntax of check macro
 *
 * Revision 1.44  2006/02/28 09:15:22  jmlarsen
 * Minor update
 *
 * Revision 1.43  2006/02/23 16:07:59  jmlarsen
 * Using irplib_assert_msg
 *
 * Revision 1.42  2006/02/21 14:26:54  jmlarsen
 * Minor changes
 *
 * Revision 1.41  2006/02/08 07:52:16  jmlarsen
 * Added function returning library version
 *
 * Revision 1.40  2006/02/03 07:46:30  jmlarsen
 * Moved recipe implementations to ./uves directory
 *
 * Revision 1.39  2006/01/24 07:49:31  jmlarsen
 * Removed spaces between backslash and newline
 *
 * Revision 1.38  2006/01/23 08:08:53  jmlarsen
 * Updated documentation
 *
 * Revision 1.37  2005/12/19 16:17:56  jmlarsen
 * Replaced bool -> int
 *
 */

#ifndef UVES_ERROR_H
#define UVES_ERROR_H

/*----------------------------------------------------------------------------*/
/**
    @defgroup uves_error  Error handling
*/
/*----------------------------------------------------------------------------*/
/**@{*/

/*-----------------------------------------------------------------------------
                    Includes
 -----------------------------------------------------------------------------*/
#include <uves_utils.h>
#include <uves_msg.h>

#if defined CPL_VERSION_CODE && CPL_VERSION_CODE < CPL_VERSION(4, 0, 0)
#include <irplib_error.h>
#endif

#include <cpl_error.h>

/*-----------------------------------------------------------------------------
                             Defines
 -----------------------------------------------------------------------------*/
/* To save some key-strokes, use the irplib error handling macros
   under different (shorter) names.
   Additionally, irplib macros require the VA_ARGS to be enclosed in (),
*/

#if defined CPL_VERSION_CODE && CPL_VERSION_CODE >= CPL_VERSION(4, 0, 0)

/** Condition + message */

#define assure(BOOL, CODE, ...) \
do {                                                              \
    cpl_error_ensure(cpl_error_get_code() == CPL_ERROR_NONE,      \
                     cpl_error_get_code(), goto cleanup,          \
                     "An error occurred that was not caught: %s", \
                     cpl_error_get_where() );                     \
    cpl_error_ensure(BOOL, CODE, goto cleanup, __VA_ARGS__);      \
} while (0)

/** Condition */
#define assure_nomsg(BOOL, CODE) \
    assure(BOOL, CODE, " ")

/** Memory allocation */
#define assure_mem(PTR) \
    assure((PTR) != NULL, CPL_ERROR_ILLEGAL_OUTPUT, "Memory allocation failure!")

#define ck0(IEXP, ...) \
    assure((IEXP) == 0, CPL_ERROR_UNSPECIFIED, __VA_ARGS__)

#define ck0_nomsg(IEXP) ck0(IEXP, " ")

#define cknull(NULLEXP, ...)  \
    assure((NULLEXP) != NULL, CPL_ERROR_UNSPECIFIED, __VA_ARGS__)

#define cknull_nomsg(NULLEXP) cknull(NULLEXP, " ")


/** cpl_error_code + message */
#define  check(CMD, ...) \
    assure((uves_msg_softer(), (CMD), uves_msg_louder(),  \
            cpl_error_get_code() == CPL_ERROR_NONE),      \
            cpl_error_get_code(), __VA_ARGS__)

/** cpl_error_code */
#define  check_nomsg(CMD) check(CMD, " ")

/** assertion + message */
#define passure(BOOL, ...) \
    assure(BOOL, CPL_ERROR_UNSPECIFIED, \
           "Internal error. Please report to " PACKAGE_BUGREPORT " " __VA_ARGS__ )
           /*  Assumes that PACKAGE_BUGREPORT
               contains no formatting special characters  */

/** reset */   
#define uves_error_reset() cpl_error_reset()


#else // if we still test CPL31


#define assure(BOOL, CODE, ...) \
  irplib_error_assure(BOOL, CODE, (__VA_ARGS__), goto cleanup)

/** Condition */
#define assure_nomsg(BOOL, CODE) \
  irplib_error_assure(BOOL, CODE, (" "), goto cleanup)

/** Memory allocation */
#define assure_mem(PTR) \
  irplib_error_assure((PTR) != NULL, CPL_ERROR_ILLEGAL_OUTPUT, \
  ("Memory allocation failure!"), goto cleanup)
#define ck0(IEXP, ...) \
  irplib_error_assure(IEXP == 0, CPL_ERROR_UNSPECIFIED, \
  (__VA_ARGS__), goto cleanup)

#define ck0_nomsg(IEXP) ck0(IEXP," ")

#define cknull(NULLEXP, ...) \
  irplib_error_assure((NULLEXP) != NULL, \
  CPL_ERROR_UNSPECIFIED, (__VA_ARGS__), goto cleanup)

#define cknull_nomsg(NULLEXP) cknull(NULLEXP," ")


/** cpl_error_code + message */
#define  check(CMD, ...)                                                 \
  irplib_error_assure((uves_msg_softer(), (CMD), uves_msg_louder(),      \
              cpl_error_get_code() == CPL_ERROR_NONE),       \
                       cpl_error_get_code(), (__VA_ARGS__), goto cleanup)

/** cpl_error_code */
#define  check_nomsg(CMD) check(CMD, " ")

/** assertion + message */
#define passure(BOOL, ...)                                               \
  irplib_error_assure(BOOL, CPL_ERROR_UNSPECIFIED,                       \
                     ("Internal error. Please report to "                \
                      PACKAGE_BUGREPORT " " __VA_ARGS__), goto cleanup)
                       /*  Assumes that PACKAGE_BUGREPORT
               contains no formatting special characters  */

/** reset */   
#define uves_error_reset()   \
      irplib_error_reset()

/** dump */
#define uves_error_dump()  \
      irplib_error_dump(CPL_MSG_ERROR, CPL_MSG_ERROR)

#endif //end check on CPL version
/**@}*/








/*----------------------------------------------------------------------------*/
/**
   @addtogroup uves_error

   Warning: this documentation is outdated. Please refer to the documentation of
   the error handler in IRPLIB.

   This error handling module extends CPL's error handler by adding error 
   tracing and automatic memory deallocation in case of an error.
   Like in CPL the current error state is indicated by the @c cpl_error_code
   (returned by the function @c cpl_error_get_code() ).

   The error tracing makes it possible to see where (source file, 
   function name, line number)
   an error first occured, as well as the sequence of function calls preceding 
   the error. A typical output looks like:
   @code
   An error occured, dumping error trace:
   
   Wavelength calibration did not converge. After 13 iterations the RMS was 
   0.300812 pixels. Try to improve the initial guess solution (The iterative
   process did not converge)
     in [3]uves_wavecal_identify() at uves_wavecal_identify.c :101
    
   Could not calibrate orders
     in [2]uves_wavecal_process_chip() at uves_wavecal.c  :426
     
   Wavelength calibration failed
     in [1]uves_wavecal() at uves_wavecal.c  :679
   @endcode

   However, the main motivation of this extension is to simplify the error
   checking and handling. A single line of source code
   
   @code
   check( dispersion_relation = 
   uves_wavecal_identify(linetable[window-1],
                         line_refer,
             initial_dispersion, 
             WAVECAL_MODE, DEGREE, TOLERANCE, ALPHA, MAXERROR),
           "Could not calibrate orders");
   @endcode

   has the same effect as

   @code
   if (cpl_error_get_code() != CPL_ERROR_NONE) {
      cpl_msg_error(__func__, "An unexpected error (%s) has occurred in %s() at %-15s :%-3d",
                           cpl_error_get_message(),
                           __func__,
                           __FILE__,
                           __LINE__);
      uves_free_image(&spectrum);
      uves_free_image(&cropped_image);
      uves_free_image(&debug_image);
      uves_free_cpl(&relative_order);
      polynomial_delete(&initial_dispersion);
      polynomial_delete(&dispersion_relation);
      return NULL;
   }

   dispersion_relation = 
   uves_wavecal_identify(linetable[window-1],
                         line_refer,
             initial_dispersion, 
             WAVECAL_MODE, DEGREE, TOLERANCE, ALPHA, MAXERROR);

   if (cpl_error_get_code() != CPL_ERROR_NONE) {
      cpl_msg_error(__func__, "ERROR: Could not calibrate orders "
                              "(%s) in %s() at %-15s :%-3d",
                           cpl_error_get_message(),
                           __func__,
                           __FILE__,
                           __LINE__);
      uves_free_image(&spectrum);
      uves_free_image(&cropped_image);
      uves_free_image(&debug_image);
      uves_free_cpl(&relative_order);
      polynomial_delete(&initial_dispersion);
      polynomial_delete(&dispersion_relation);
      return NULL;
   }
   @endcode

   This of course makes the source code more compact and hence easier to read
   (and maintain) and allows for intensive error checking with minimal effort.

   Additionally, editing the @c check() macro (described below) allows
   for debugging/tracing information at every function entry and exit.

   @par Usage

   New errors are set with the macros @c assure() and @c passure(), 
   and sub-functions that might set a @c cpl_error_code
   are checked using the macros @c check() and @c pcheck() . 
   The function @c _uves_error_set() should never be called
   directly. These macros check if an error occured and, if so, jumps to
   the @c cleanup label which must be defined at the end of each function. 
   After the @c cleanup label every pointer used
   by the function is deallocated and the function returns. 
   Also a string variable named @c fctid (function
   identification), must be defined in every function and contain 
   the name of the current function.

   At the very end of a recipe the error state should be 
   checked and @c uves_error_dump() called on error:
   @code
   if ( cpl_error_get_code() != CPL_ERROR_NONE )
   {
      uves_error_dump(__func__);
   }
   @endcode

   When using this scheme:

   - There should be only one @c return statement per function 
     (after the @c cleanup label).

   - All pointers to dynamically allocated memory must be declared 
     at the beginning of a function.

   - Pointers must be initialized to NULL (which is a good idea anyway).

   - Pointers must be set to NULL when they are not used
     (which is a good idea anyway).

   Consider the example

   @code
   int function_name(...)
   {
      cpl_image * image = NULL;
      cpl_image * another_image;  / *  Wrong: Pointer must be initialized to NULL. On cleanup, 
                                              cpl_image_delete() will try to deallocate whatever
                                              this pointer points to. If the pointer is NULL,
                                              the deallocator function will do nothing.  * /
      :
      :

      {
         cpl_object * object = NULL;   / *  Wrong: Pointer must be declared at 
                                               the beginning of a function.
                                                   This object will not be deallocated, 
                           if the following
                                                   check() fails. * /
     
         object = cpl_object_new();

         :
         :
              
         check( ... );

         :
         :

         cpl_object_delete(object);    / *  Wrong: The pointer must be set to NULL after
                                               deallocation, or
                                                   the following assure() might cause the
                           already deallocated object
                                                   to be deallocated again.  * /
         :
         :
     
         assure( ... );

         return 7;                     / *  Wrong: Only one exit point per function. * /

      }
      
      :
      :

    cleanup:
      cpl_image_delete(image);
      cpl_image_delete(another_image);

      return 7;
   }
   @endcode

   This is easily fixed:

   @code
   int function_name(...)
   {
      cpl_image  * image         = NULL;  / *  All pointers are declared at the beginning  * /
      cpl_image  * another_image = NULL;  / *  of the function an initialized to NULL.     * /
      cpl_object * object        = NULL;

      :
      :

      {

         object = cpl_object_new();

         :
         :
              
         check( ... );

         :
         :

         uves_free_object(&object);            / *  The object is deallocated 
                                                and the pointer set to NULL.  * /

         :
         :
     
         assure( ... );

      }
      
      :
      :

    cleanup:
      uves_free_image (&image);                / *  All objects are deallocated here.  * /
      uves_free_image (&another_image);
      uves_free_object(&object);

      return 7;                           / *  This is the only exit point of the function. * /
   }
   @endcode

   (Note that @c uves_free_image() et al. can be used instead of @c cpl_image_delete() et al. 
   as a way to ensure that a pointer is always set to NULL after deallocation).

   @par Recovering from an error

   To recover from an error, call @c uves_error_reset(), not @c cpl_error_reset(). Example:

   @code
   n = cpl_table_get_nrow(t);
   if (cpl_error_get_code() == CPL_ERROR_NULL_INPUT)  / *  This error code 
                                                           is set if 't' is NULL.  * /
   {
      / *  Recover from this error  * /

      uves_error_reset();
      n = -3;
   }
   else  / *  Also check for unexpected errors  * /
   {
      assure( cpl_error_get_code() == CPL_ERROR_NONE, cpl_error_get_code(), 
              "Error reading table size");
   }
   @endcode

   However, error recovery is usually best avoided, and the functionality above
   is better written as:

   @code
   if (t != NULL)
   {
      check( n = cpl_table_get_nrow(t), "Error reading table size");
   }
   else
   {
      n = -3;
   }
   @endcode

      
*/
/*----------------------------------------------------------------------------*/

#endif























