/* $Id: xsh_detmon.c,v 1.11 2013-07-19 12:00:24 jtaylor Exp $
 *
 * This file is part of the irplib package
 * Copyright (C) 2002, 2003 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 St, Fifth Floor, Boston, MA 02111-1307 USA
 */

/*
 * $Author: jtaylor $
 * $Date: 2013-07-19 12:00:24 $
 * $Revision: 1.11 $
 * $Name: not supported by cvs2svn $
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <complex.h>

/*---------------------------------------------------------------------------
                                  Includes
 ---------------------------------------------------------------------------*/

#include <math.h>
#include <string.h>
#include <assert.h>
#include <float.h>

#include <cpl.h>

#include "xsh_ksigma_clip.h"


static cpl_error_code
xsh_ksigma_clip_double(const double  * pi,
		       cpl_binary * pm,
		       int               llx,
			  int               lly,
			  int               urx,
			  int               ury,
			  int               nx,
			  double            var_sum,
			  int               npixs,
			  double            kappa,
			  int               nclip,
			  double            tolerance,
			  double          * mean,
			  double          * stdev);

static cpl_error_code
xsh_ksigma_clip_float(const float     * pi,
		      cpl_binary * pm,
			 int               llx,
			 int               lly,
			 int               urx,
			 int               ury,
			 int               nx,
			 double            var_sum,
			 int               npixs,
			 double            kappa,
			 int               nclip,
			 double            tolerance,
			 double          * mean,
			 double          * stdev);

static cpl_error_code
xsh_ksigma_clip_int(const int       * pi,
		    cpl_binary * pm,
		       int               llx,
		       int               lly,
		       int               urx,
		       int               ury,
		       int               nx,
		       double            var_sum,
		       int               npixs,
		       double            kappa,
		       int               nclip,
		       double            tolerance,
		       double          * mean,
		       double          * stdev);


/*---------------------------------------------------------------------------*/
/**
  @brief    Apply kappa-sigma clipping on input image
  @param    img      Input image
  @param    llx      Lower left x position (FITS convention)
  @param    lly      Lower left y position (FITS convention)
  @param    urx      Upper right x position (FITS convention)
  @param    ury      Upper right y position (FITS convention)
  @param    kappa    Kappa value for the clipping
  @param    nclip    Number of clipping iterations
  @param    kmean    Mean after clipping (output)
  @param    kstdev   Stdev after clipping (output)
  @return   CPL_ERROR_NONE or the relevant #_cpl_error_code_ on error

  This function applies an iterative kappa-sigma clipping on the image and
  returns mean and stdev after the clipping.

  The function takes as a starting point the "standard" values of mean and
  stdev from cpl_stats.

  On each iteration, the contribution of pixels outside the range
  [mean - kappa * stdev, mean + kappa * stdev] is removed, the values of
  mean and stdev are updated, and so are the limits of the range to be used
  in the next iteration as well.

  The algorithm stops after nclip iterations or when the variation of the
  range between two consecutive iterations is smaller (absolute value) than
  the tolerance.

  The effectiveness of this function resides on the way the update of the
  values of mean and stdev is done.

  The contribution of a single pixel in variance can be removed as follows:

  \sum_{i=1}^{N-1} (x_i - \overline{x}_{n-1})^2 =
  \sum_{i=1}^ N    (x_i - \overline{x}_n    )^2 -
  \frac{N}{N-1} \,( \, \overline{x}_n - x_{n} )^2

  For further details on the mathematical aspects, please refer to DFS05126.

  Possible #_cpl_error_code_ set in this function:
   - CPL_ERROR_NULL_INPUT if img or kmean is NULL
   - CPL_ERROR_ILLEGAL_INPUT if
       a) the window specification is illegal (llx > urx or lly > ury)
       b) the window specification is outside the image
       c) the tolerance is negative
       d) kappa is <= 1.0
       e) nclip is <= 0.

  The values of kmean and kstdev is undefined on error.
*/
/*---------------------------------------------------------------------------*/
cpl_error_code
xsh_ksigma_clip(const cpl_image * img,
		   int               llx,
		   int               lly,
		   int               urx,
		   int               ury,
		   double            kappa,
		   int               nclip,
		   double            tolerance,
		   double          * kmean,
		   double          * kstdev)
{

    int nx, ny;

    double      mean, stdev;
    //int         npixs;
    cpl_image* sub_ima=NULL;
    double kappa2=0;
    double thresh=0;
    double thresh_p=0;
    cpl_binary * pm=0;
    const float* pi=0;

    int pix=0;
    int i=0;
    int j=0;
    int k=0;

    cpl_ensure_code(img != NULL, CPL_ERROR_NULL_INPUT);

    nx = cpl_image_get_size_x(img);
    ny = cpl_image_get_size_y(img);

    cpl_ensure_code(llx > 0 && urx > llx && urx <= nx &&
		    lly > 0 && ury > lly && ury <= ny,
		    CPL_ERROR_ILLEGAL_INPUT);

    cpl_ensure_code(tolerance >= 0.0, CPL_ERROR_ILLEGAL_INPUT);
    cpl_ensure_code(kappa     >  1.0, CPL_ERROR_ILLEGAL_INPUT);
    cpl_ensure_code(nclip     >    0, CPL_ERROR_ILLEGAL_INPUT);
 
    sub_ima=cpl_image_extract(img,llx, lly, urx, ury);
   //npixs= nx*ny-cpl_image_count_rejected(sub_ima);
   cpl_image_delete(sub_ima);
   mean    = cpl_image_get_mean_window(img,llx, lly, urx, ury);
   stdev    = cpl_image_get_stdev_window(img,llx, lly, urx, ury);
   pi=cpl_image_get_data_float_const(img);
   pm=cpl_mask_get_data(cpl_image_get_bpm((cpl_image*)img));
 

   kappa2=kappa*kappa;
   thresh_p=-1;
   for(k=0;k<nclip;k++) {
     mean    = cpl_image_get_mean_window(img,llx, lly, urx, ury);
     stdev    = cpl_image_get_stdev_window(img,llx, lly, urx, ury);
     thresh=stdev*stdev*kappa2;
     for(j=lly;j<ury;j++) {
       for(i=llx;i<urx;i++) {
	 pix=i+j*nx;
	 if( 
             (pm[pix] != CPL_BINARY_1) && 
	     ((pi[pix]-mean)*(pi[pix]-mean) > thresh ) ) {
	   pm[pix]=CPL_BINARY_1;
	 } /* end check if pix is outlier */
       } /* loop over i */
     } /* loop over j */
     if((fabs(thresh_p-thresh)) < tolerance) {
       break;
     } else {
       thresh_p=thresh;
     }
   } /* loop over niter */

    *kmean = mean;
    if (kstdev != NULL) *kstdev = stdev; /* Optional */


    return cpl_error_get_code();
}

#define CONCAT(a,b) a ## _ ## b
#define CONCAT2X(a,b) CONCAT(a,b)

#define CPL_TYPE double
#include "xsh_detmon_body.h"
#undef CPL_TYPE

#define CPL_TYPE float
#include "xsh_detmon_body.h"
#undef CPL_TYPE

#define CPL_TYPE int
#include "xsh_detmon_body.h"
#undef CPL_TYPE

/**@}*/
