/*
 * This file is part of the ESO SINFONI 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: 2007-10-26 09:42:36 $
 * $Revision: 1.13 $
 * $Name: not supported by cvs2svn $
 * $Log: not supported by cvs2svn $
 * Revision 1.12  2007/08/14 10:01:41  amodigli
 * added sinfo_stop_if_error
 *
 * Revision 1.11  2007/08/11 10:46:18  amodigli
 * clean
 *
 * Revision 1.9  2007/08/08 11:17:26  amodigli
 * change to support CPL31 & CPL40
 *
 * Revision 1.8  2007/06/06 07:10:45  amodigli
 * replaced tab with 4 spaces
 *
 * Revision 1.7  2006/11/21 11:56:10  amodigli
 * replaced __func__ by cpl_func
 *
 * Revision 1.6  2006/10/16 07:26:23  amodigli
 * shortened line length
 *
 * Revision 1.5  2006/10/13 08:09:42  amodigli
 * shorten line length
 *
 * Revision 1.4  2006/10/13 06:34:40  amodigli
 * shorten line length
 *
 * Revision 1.3  2006/10/04 06:17:45  amodigli
 * added doxygen doc
 *
 * Revision 1.2  2006/07/31 06:33:34  amodigli
 * fixed  bug in ck0 macro
 *
 * Revision 1.1  2006/05/30 09:09:37  amodigli
 * added to repository
 *
 *
 */

#ifndef SINFO_ERROR_H
#define SINFO_ERROR_H
/**
    @defgroup sinfo_error  Error handling
*/
/**@{*/

/*-----------------------------------------------------------------------------
                    Includes
-----------------------------------------------------------------------------*/
#include <cpl_error.h>
#include <cpl.h>

#include <irplib_utils.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 (),
*/

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

#define assure_nomsg(BOOL, CODE, ...)				\
  cpl_error_ensure(BOOL, CODE, goto cleanup,__VA_ARGS__)

#define sinfo_stop_if_error() \
     do if(cpl_error_get_code()) { \
     cpl_msg_error(__func__,"Traced error"); \
     irplib_trace(); \
     goto cleanup; \
     } while (0) 

#define ck0(IEXP, ...) \
  cpl_error_ensure(IEXP == 0, CPL_ERROR_UNSPECIFIED, \
   goto cleanup,__VA_ARGS__)

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

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

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

#define  check(CMD, ...)                                                 \
  cpl_error_ensure((sinfo_msg_softer(), (CMD), sinfo_msg_louder(),      \
              cpl_error_get_code() == CPL_ERROR_NONE),       \
                       cpl_error_get_code(), goto cleanup,__VA_ARGS__)

#define  check_nomsg(CMD) check(CMD, " ")

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

/**@}*/


/**
   @addtogroup sinfo_error
 
   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]sinfo_wavecal_identify() at sinfo_wavecal_identify.c :101
    
   Could not calibrate orders
     in [2]sinfo_wavecal_process_chip() at sinfo_wavecal.c  :426
     
   Wavelength calibration failed
     in [1]sinfo_wavecal() at sinfo_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 = sinfo_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(cpl_func, 
                    "An unexpected error (%s) has occurred "
                    "in %s() at %-15s :%-3d",
                           cpl_error_get_message(),
                           cpl_func,
                           __FILE__,
                           __LINE__);
      sinfo_free_image(&spectrum);
      sinfo_free_image(&cropped_image);
      sinfo_free_image(&debug_image);
      sinfo_free_cpl(&relative_order);
      polynomial_delete(&initial_dispersion);
      polynomial_delete(&dispersion_relation);
      return NULL;
   }

   dispersion_relation = sinfo_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(cpl_func, "ERROR: Could not calibrate orders (%s) in %s() 
      at %-15s :%-3d",
                           cpl_error_get_message(),
                           cpl_func,
                           __FILE__,
                           __LINE__);
      sinfo_free_image(&spectrum);
      sinfo_free_image(&cropped_image);
      sinfo_free_image(&debug_image);
      sinfo_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 _sinfo_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 
   sinfo_error_dump() called on error:
   @code
   if ( cpl_error_get_code() != CPL_ERROR_NONE )
   {
      sinfo_error_dump(cpl_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( ... );

         :
         :

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

         :
         :
     
         assure( ... );

      }
      
      :
      :

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

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

   (Note that @c sinfo_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 sinfo_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  * /

      sinfo_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
