/*===========================================================================
  Copyright (C) 2001 European Southern Observatory (ESO)

  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., 675 Massachusetss Ave, Cambridge, 
  MA 02139, USA.

  Corresponding concerning ESO-MIDAS should be addressed as follows:
  Internet e-mail: midas@eso.org
  Postal address: European Southern Observatory
  Data Management Division 
  Karl-Schwarzschild-Strasse 2
  D 85748 Garching bei Muenchen 
  GERMANY
  ===========================================================================*/

/**
 * @defgroup flames_fillholes EsoRex File Utility Functions
 *
 * Utility functions for hadling files.
 *
 */


#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif
/*---------------------------------------------------------------------------
  Includes
  --------------------------------------------------------------------------*/

#include <flames.h>
#include <flames_midas_def.h>
#include <flames_freeback.h>
#include <flames_computeback.h>
#include <flames_def_drs_par.h>
#include <flames_scatter.h>
#include <flames_uves.h>
#include <flames_newmatrix.h>
#include <flames_shiftcommon.h>
#include <flames_shiftall.h>
#include <flames_uves.h>
#include <flames_dfs.h>
#include <flames_dointerpolate.h>
#include <flames_getordpos.h>
#include <flames_getordslope.h>
#include <flames_readslitflats.h>
#include <flames_readback.h>
#include <flames_slitdivide.h>
#include <flames_freeslitflats.h>

#include <flames_fillholes.h> //fixme: This header should contain only the definition of flames_fillholes()
#include <uves_msg.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
/**@{*/

/**
   @name  flames_fillholes()  
   @short  This function try to fill missing (bad) pixels with interpolated 
   values. 2D frames are normalized (and any x, order the integrated flux over
   a fibre is 1). 
   @author G. Mulas  -  ITAL_FLAMES Consortium. Ported to CPL by A. Modigliani


   @param  allflatsin         input all slit flat field
   @param  ordpos             input order pos rtable
   @param  slitsname          slit name prefix
   @param  backname           background table name
   @param  bxdegree           inter-order background poly degree X
   @param  bydegree           inter-order background poly degree X
   @param  bkgswitch          parameter to control background subtraction algorithm
   @param  bkgswitch2         parameter to control background subtraction algorithm
   @param  badwinxsize        X size of inter-order background window
   @param  badwinysize        Y size of inter-order background window
   @param  badfracthres       Background table bad pixel frame scanning threshold fraction
   @param  badtotthres        Background table bad pixel frame scanning threshold number
   @param  kappa2             square of kappa value in kappa-sigma clip
   @param  decentSNR          How large must the SNR on a fibre be in a calibration frame, at a given order and x, for that slice to be
                              considered "good"?
   @param  maxbackiters This is the maximum number of kappa-sigma clipping iterations which we are willing to perform in background fitting
   @param  maxdiscardfract This is the maximum fraction of windows/pixels which we are willing to  discard by kappa-sigma clipping in each
                           iteration of the background fitting loop
   @param  maxcleaniters   This is the maximum number of cleaning iterations to be tried on a given slice in flames_prep_fibre, before
                            giving up on its normalise-ability and falling back to the second cleaning strategy
   @param  maxsinglepixelfrac maximum acceptable fraction of the flux in a given slices in one single pixel; a higher fraction than this means
                              that there was some numerical instability and/or unmasked bad pixel, and that it must be discarded
   @param  fracslicesthres  defines the minimum fraction of slices that must be good, for a fibre to be considered covered enough at the end
                            of fillholes, in flames_prep_fibreff, to avoid stupid instabilities in gaussselfcorrel if a fibre is only very
                            barely covered by the slit FF frames
   @param  OUTPUTI


   @return success or failure code, 


   DRS Functions called:          
   none


   Pseudocode:                                                             


   @note
   @doc  This function takes a pointer to an allflats structure (all memory
   allocations are assumed to have been done already) and tries to fill
   missing (bad) pixels with interpolated values. Moreover, in the 2D frames
   each pixel is normalised so that for any given x, and order the integrated
   value over one fibre equals 1, and the normalisation factor is stored in
   appropriate structure members, to make shifting more efficient later. 

   -computes the halfibrewidth in pixel units

   -subtracts inter-order background (the error of the estimated background is assumed to be negligible)
         scan the frame for any negative pixel values; if any are found, compare them to the
         standard deviation: if the negative value is compatible with zero, set that pixel to zero,
         otherwise mark that pixel as bad

   -allocate the Slit_FF structure, to be used later on

   -starts to clean bad pixels (normalisation factors are computed as part of this not including bad pixels)
    via interpolation of good ones. Clip negative values may wreak havoc in iterative interpolations

   -normalise to 1 the integral over y of each order/fibre/x of the fibre FF frames
   -compute the fibre coverage over newly cleaned pixels, to see whether
    they may be labelled as half-good, i.e. good profile but no normalisation factor

 */

flames_err 
fillholes(
                allflats *allflatsin,
                orderpos *ordpos,
                const cpl_frameset *slitsname,
                char *backname,
                int bxdegree,
                int bydegree,
                scatterswitch bkgswitch,
                scatterswitch2 bkgswitch2,
                int badwinxsize,
                int badwinysize,
                double badfracthres,
                int badtotthres,
                double kappa2,
                double decentSNR,
                int32_t maxbackiters,
                double maxdiscardfract,
                int32_t maxcleaniters,
                double maxsinglepixelfrac,
                double fracslicesthres,
                int *OUTPUTI)
{
    char output[CATREC_LEN+1];
    allflats *allflatsout=0;
    allslitflats *slitflats=0;
    flames_frame *framebuffer=0;
    frame_data **backframe;
    shiftstruct **shiftdata=0;
    shiftstruct *shiftbuffer=0;
    shiftstruct *shiftbufferix=0;
    badifibrestruct *badifibre=0;
    badifibrestruct *mybadifibre=0;
    badixstruct *mybadixs=0;
    normstruct normdata[8];
    fitstruct fitdata;
    double phalfibrewidth=0;

    double x=0;
    double ordercentre=0;
    double orderslope=0;
    double normfactor=0;
    double normfactor2=0;
    double normsigma=0;
    double pfibrecentre=0;
    double plowlimit=0;
    double phighlimit=0;
    double fraction=0;
    double totslices=0;
    double fracslices=0;
    int32_t ix=0, iy=0;
    int32_t iorder=0, iframe=0, lfibre=0, ifibre=0;
    int32_t badtotal=0, oldbadtotal=0, goodslices=0;
    int32_t ixindex=0, newbadixcount=0, k=0, fillednumber=0, i=0;
    int32_t badpixels=0;
    int32_t ifibreixtotlimit=0;
    flames_err status=0;
    int32_t *newfibres=0;
    int32_t newnumfibres=0;
    double decentSNR2=0;
    double dbuffer=0;
    int32_t cleaniters=0;
    frame_data pixelvalue=0;
    frame_data pixelsigma=0;
    frame_data fdmaxsinglepixelfrac=0;

    int32_t iyixend=0;
    int32_t iyixindex=0;
    int32_t iorderifibreindex=0;
    int32_t iorderifibreixindex=0;
    int32_t ifibreixindex=0;
    int32_t *lvecbuf1=0;


    frame_data *fdvecbuf1=0;
    frame_data *fdvecbuf2=0;
    frame_data *fdvecbuf3=0;

    frame_data *fdvecbuf5=0;
    frame_data *fdvecbuf6=0;
    frame_mask *fmvecbuf1=0;
    frame_mask *fmvecbuf2=0;
    frame_mask *fmvecbuf3=0;


    int actvals=0;
    char drs_verbosity[10];
    char drs_id[20];

    int mid_stat=0;

    memset(drs_verbosity, 0, 10);
    memset(drs_id, 0, 20);
    strcpy(drs_id,"fillholes");


#if FLAMES_DEBUG
    {int i, j;
    for (j = 0; j < 2; j++)
        for (i = 0; i <=4; i++) {
            fprintf(stderr, "%d %d %d %d\n", i,
                            allflatsin->flatdata[j].data[0],
                            allflatsin->flatdata[j].sigma[0],
                            allflatsin->flatdata[j].badpixel[0]);
            //                      allflatsout->flatdata[j].data[0],
            //                      allflatsout->flatdata[j].sigma[0],
            //                      allflatsout->flatdata[j].badpixel[0]);

            fprintf(stderr, "%d %f %f %d\n", i,
                    allflatsin->flatdata[j].data[0][i*i*i*i],
                    allflatsin->flatdata[j].sigma[0][i*i*i*i],
                    allflatsin->flatdata[j].badpixel[0][i*i*i*i]);
            //                      allflatsout->flatdata[j].data[0][i*i*i*i],
            //                      allflatsout->flatdata[j].sigma[0][i*i*i*i],
            //                      allflatsout->flatdata[j].badpixel[0][i*i*i*i]);
        }
    }
#endif

    if ((mid_stat=SCKGETC(DRS_VERBOSITY, 1, 3, &actvals, drs_verbosity))
                    != 0) {
        /* the keyword seems undefined, protest... */
        return flames_midas_fail();
    }

    memset(output, 0, CATREC_LEN+1);

    /* since it happens to have almost null fibre values on unmasked bad
     columns, try to avoid them */
    decentSNR2=decentSNR*decentSNR;

    fdmaxsinglepixelfrac = (frame_data) maxsinglepixelfrac;

    fitdata.availpixels=0;
    fitdata.offset = calloc((size_t) 8, sizeof(double));
    fitdata.value = calloc((size_t) 8, sizeof(double));
    fitdata.sigma = calloc((size_t) 8, sizeof(double));
    for (i=0; i<=7; i++) {
        fitdata.offset[i]=0;
        fitdata.value[i]=0;
        fitdata.sigma[i]=0;
        normdata[i].normfactor=0;
        normdata[i].normsigma=0;
        normdata[i].goodoverlap=0;
    }

    SCTPUT("Initialising internal structures...");

    /* allocate the local shiftdata array of structures */
    shiftdata =
                    (shiftstruct **) calloc((size_t)(ordpos->lastorder+1-ordpos->firstorder),
                                    sizeof(shiftstruct*));
    shiftdata[0] =
                    (shiftstruct *) calloc((size_t)(allflatsin->subcols*
                                    (ordpos->lastorder+1-ordpos->firstorder)),
                                    sizeof(shiftstruct));
    for (i=1; i<=ordpos->lastorder-ordpos->firstorder; i++)
        shiftdata[i] = shiftdata[i-1]+allflatsin->subcols;
    for (i=0; i<=ordpos->lastorder-ordpos->firstorder; i++) {
        shiftbuffer = shiftdata[i];
        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
            shiftbufferix = shiftbuffer+ix;
            shiftbufferix->ixoffsets = calloc((size_t) 8, sizeof(int32_t));
            shiftbufferix->yfracoffsets = calloc((size_t) 8, sizeof(double));
            shiftbufferix->yintoffsets = calloc((size_t) 8, sizeof(int32_t));
            shiftbufferix->normfactor = calloc((size_t) 8, sizeof(double));
            shiftbufferix->normsigma = calloc((size_t) 8, sizeof(double));
            shiftbufferix->goodoverlap = calloc((size_t) 8, sizeof(double));
        }
    }


    /* compute the halfibrewidth in pixel units */
    phalfibrewidth = (allflatsin->halfibrewidth)/(allflatsin->substepy);
    ifibreixtotlimit = (allflatsin->maxfibres*allflatsin->subcols)-1;
    /* begin looping over orders at first */
    for (iorder=0; iorder <= ((ordpos->lastorder)-(ordpos->firstorder));
                    iorder++) {
        double order = (double) (iorder+(ordpos->firstorder));
        shiftbuffer = shiftdata[iorder];
        /* loop over x... */
        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
            shiftbufferix = shiftbuffer+ix;
            /* convert the ix pixel coordinate to the x world coordinate */
            x = allflatsin->substartx+(allflatsin->substepx)*((double) ix);
            /* find the unshifted central position and slope of this order at this x */
            /* bail out if the function call return an error status */
            if ((status = get_ordpos(ordpos, order, x, &ordercentre))!=NOERR) {
                free(shiftdata);
                free(fitdata.offset);
                free(fitdata.sigma);
                free(fitdata.value);
                return(status);
            }
            shiftbufferix->ordercentre = ordercentre;
            if ((status = get_ordslope(ordpos, order, x, &orderslope))!=NOERR) {
                free(shiftdata);
                free(fitdata.offset);
                free(fitdata.sigma);
                free(fitdata.value);
                return(status);
            }
            shiftbufferix->orderslope = orderslope;
            /* compute the pixel coordinates of the pixels to be used for interpolation */
        }
        /* calcfillshifts depends on all the shiftdata stuff to have been
       properly initialised already, therefore it needs to rune in a separate
       loop over ix */
        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
            if ((status=calcfillshifts(allflatsin, shiftbuffer, ix))
                            != NOERR) {
                free(shiftdata);
                free(fitdata.offset);
                free(fitdata.sigma);
                free(fitdata.value);
                return(status);
            }
        }
        /* since we are at it, completely clean up normfactors and normsigmas */
        fdvecbuf1 = allflatsin->normfactors[iorder][0];
        fdvecbuf2 = allflatsin->normsigmas[iorder][0];
        for (ix=0; ix<=ifibreixtotlimit; ix++) {
            fdvecbuf1[ix] = 0;
            fdvecbuf2[ix] = 0;
        }
        /* loop over FF frames */
        for (iframe=0; iframe<=allflatsin->nflats-1;iframe++) {
            /* loop over lit fibres in this frame */
            for (lfibre=0; lfibre<=((allflatsin->flatdata)[iframe]).numfibres-1;
                            lfibre++) {
                ifibre = (((allflatsin->flatdata)[iframe]).fibres)[lfibre];
                /* loop over ix... */
                for (ix=0; ix<=(allflatsin->subcols-1); ix++){
                    /* find this fibre centre and boundaries */
                    if ((status=locatefillfibre(allflatsin, ordpos, shiftbuffer,
                                    iorder, ifibre, ix)) != NOERR) {
                    	free(shiftdata);
                    	free(fitdata.offset);
                        free(fitdata.sigma);
                    	free(fitdata.value);
                        return(status);
                    }
                }
            }
        }
    }

    /* split the order loop in two parts, so that we can fit and subtract the
     background from fibre FF frames */

    SCTPUT("Background fitting and subtraction starting...");

    /* background fitting and subtraction section starts here */
    framebuffer = calloc(1, sizeof(flames_frame));
    framebuffer->subrows = allflatsin->subrows;
    framebuffer->subcols = allflatsin->subcols;
    framebuffer->substepx = allflatsin->substepx;
    framebuffer->substepy = allflatsin->substepy;
    framebuffer->substartx = allflatsin->substartx;
    framebuffer->substarty = allflatsin->substarty;
    framebuffer->nflats = 0;
    framebuffer->maxfibres = allflatsin->maxfibres;
    framebuffer->fibremask = cvector(0, framebuffer->maxfibres-1);
    iyixend = (allflatsin->subrows*allflatsin->subcols)-1;
    /* allocate and initialise the frame which will contain the
     estimated background */
    backframe = fdmatrix(0, framebuffer->subrows-1, 0, framebuffer->subcols-1);
    memset(backframe[0], 0,
           framebuffer->subrows*framebuffer->subcols*sizeof(frame_data));
    //uves_msg_debug("process frame %s",allflatsin->flatdata[iframe].framename);
    for (iframe=0; iframe<=allflatsin->nflats-1;iframe++) {
        /* build the fibremask for the framebuffer */
        for (ifibre=0; ifibre<=framebuffer->maxfibres-1; ifibre++)
            framebuffer->fibremask[ifibre]=FALSE;
        for (lfibre=0; lfibre<=allflatsin->flatdata[iframe].numfibres-1; lfibre++)
            framebuffer->fibremask[allflatsin->flatdata[iframe].fibres[lfibre]]=TRUE;
        /* assign pointers to the frame data, sigma and badpixel masks */
        framebuffer->frame_array = allflatsin->flatdata[iframe].data;
        framebuffer->frame_sigma = allflatsin->flatdata[iframe].sigma;
        framebuffer->badpixel = allflatsin->flatdata[iframe].badpixel;
        /* read in the background table */
        if ((status=readback(&(framebuffer->back), backname, bxdegree, bydegree))
                        != NOERR) {
            /* something went wrong while reading the background table */
            SCTPUT("Error while reading the background table");
            free(fitdata.offset);
            free(fitdata.sigma);
            free(fitdata.value);
            return flames_midas_fail();
        }
        if (framebuffer->back.Window_Number > 0) {
            if (scatter(framebuffer, ordpos, bkgswitch, bkgswitch2, badwinxsize,
                            badwinysize, badfracthres, badtotthres, kappa2,
                            maxbackiters, maxdiscardfract, OUTPUTI)) {
                SCTPUT("Error executing the scatter function");
                free(fitdata.offset);
                free(fitdata.sigma);
                free(fitdata.value);
                return flames_midas_fail();
            }
            /* compute the estimated background */
            if (computeback(framebuffer, backframe) != NOERR) {
                SCTPUT("Error computing fitted background");
                free(fitdata.offset);
                free(fitdata.sigma);
                free(fitdata.value);
                return flames_midas_fail();
            }
            if (freeback(&(framebuffer->back)) != NOERR) {
                SCTPUT("Error freeing framebuffer->back");
                free(fitdata.offset);
                free(fitdata.sigma);
                free(fitdata.value);
                return flames_midas_fail();
            }
            /* subtract the estimated background from the data frame */
            /* the error of the estimated background is assumed to be negligible */
            SCTPUT("Subtracting fitted background from fibre FF frame\n");
            fdvecbuf1 = framebuffer->frame_array[0];
            fdvecbuf2 = backframe[0];

#if FLAMES_DEBUG
            {int i;
            for (i = 0; i <= 10; i++) {
                fprintf(stderr, "backsub %d %d %f %f %f\n", __LINE__, i,
                                fdvecbuf1[i*i*i*i],
                                fdvecbuf2[i*i*i*i],
                                framebuffer->frame_sigma[0][i*i*i*i]);
            }
            }
#endif



            for (iyixindex=0; iyixindex<=iyixend; iyixindex++) {
                fdvecbuf1[iyixindex] -= fdvecbuf2[iyixindex];
            }
            /* some more black magic to make the thing more robust: scan the frame
	       for any negative pixel values; if any are found, compare them to the
	       standard deviation: if the negative value is compatible with zero,
	       set that pixel to zero, otherwise mark that pixel as bad */
            fmvecbuf1 = framebuffer->badpixel[0];
            fdvecbuf1 = framebuffer->frame_array[0];
            fdvecbuf2 = framebuffer->frame_sigma[0];
            for (iyixindex=0; iyixindex<=iyixend; iyixindex++) {
                if (fmvecbuf1[iyixindex]==0 && (pixelvalue=fdvecbuf1[iyixindex])<0) {
                    if ((pixelvalue*pixelvalue)<4*(fdvecbuf2[iyixindex])) {
                        fdvecbuf1[iyixindex]=0;
                    }
                    else {
                        fmvecbuf1[iyixindex]=1;
                    }
                }
            }
            /*
	      for (ifibre=0; ifibre<=framebuffer->maxfibres-1; ifibre++) {
	      framebuffer->fibremask[ifibre] = ordpos->fibremask[ifibre];
	}
             */
        }
        else {
            SCTPUT("Error: no regions available for background estimation");
            free(fitdata.offset);
            free(fitdata.sigma);
            free(fitdata.value);
            return flames_midas_fail();
        }
    }



#if FLAMES_DEBUG
    {int i, j;
    for (j = 0; j < 3; j++)
        for (i = 0; i <= 1000; i += 10) {
            fprintf(stderr, "threshold done: %d %d %f %f %d\n", __LINE__, i,
                            allflatsin->flatdata[j].data[0][i*i],
                            allflatsin->flatdata[j].sigma[0][i*i],
                            allflatsin->flatdata[j].badpixel[0][i*i]);
            //                      allflatsout->flatdata[j].data[0][i*i],
            //                      allflatsout->flatdata[j].sigma[0][i*i],
            //                      allflatsout->flatdata[j].badpixel[0][i*i]);
        }
    }
#endif





    /* now allocate the Slit_FF structure, we'll be using it from now on */
    slitflats = (allslitflats *) calloc(1, sizeof(allslitflats));
    if ((status = readslitflats(slitsname, slitflats)) != NOERR) {
        /* problems reading slitflats members from disk */
        SCTPUT("Error while reading the slit Flat Field frames");
        free(fitdata.offset);
        free(fitdata.sigma);
        free(fitdata.value);
        return flames_midas_fail();
    }
    /* uncorrect for the previous ycorrection, if present */
    if (ordpos->corrected=='t') {
        for (iframe=0; iframe<=(slitflats->nflats-1);iframe++)
            slitflats->slit[iframe].yshift -= ordpos->ycorrection;
    }
    for (iframe=0; iframe<=allflatsin->nflats-1;iframe++) {
        /* build the fibremask for the framebuffer */
        for (ifibre=0; ifibre<=framebuffer->maxfibres-1; ifibre++)
            framebuffer->fibremask[ifibre]=FALSE;
        for (lfibre=0; lfibre<=allflatsin->flatdata[iframe].numfibres-1; lfibre++)
            framebuffer->fibremask[allflatsin->flatdata[iframe].fibres[lfibre]]=TRUE;
        /* assign pointers to the frame data, sigma and badpixel masks */
        framebuffer->frame_array = allflatsin->flatdata[iframe].data;
        framebuffer->frame_sigma = allflatsin->flatdata[iframe].sigma;
        framebuffer->badpixel = allflatsin->flatdata[iframe].badpixel;
        /* divide the resulting frame by the slit FF */
        sprintf(output, "divide fibre FF frame %d by slit FF\n", iframe+1);
        SCTPUT(output);


#if FLAMES_DEBUG
        {int i, j;
        for (j = 0; j < 3; j++)
            for (i = 0; i <= 1000; i += 10) {
                fprintf(stderr, "before divide: %d %d %f %f %d\n", __LINE__, i,
                                allflatsin->flatdata[j].data[0][i*i],
                                allflatsin->flatdata[j].sigma[0][i*i],
                                allflatsin->flatdata[j].badpixel[0][i*i]);
                //                      allflatsout->flatdata[j].data[0][i*i],
                //                      allflatsout->flatdata[j].sigma[0][i*i],
                //                      allflatsout->flatdata[j].badpixel[0][i*i]);
            }
        }
#endif        



        if (slitdivide(slitflats, ordpos, framebuffer, framebuffer)!=NOERR) {
            /* something went wrong in slitdivide */
            SCTPUT("Error while dividing the Science Frame by the slit frame(s)");
            free(fitdata.offset);
            free(fitdata.sigma);
            free(fitdata.value);
            return flames_midas_fail();
        }


#if FLAMES_DEBUG
        {int i, j;
        for (j = 0; j < 3; j++)
            for (i = 0; i <= 1000; i += 10) {
                fprintf(stderr, "after divide: %d %d %f %f %d\n", __LINE__, i,
                                allflatsin->flatdata[j].data[0][i*i],
                                allflatsin->flatdata[j].sigma[0][i*i],
                                allflatsin->flatdata[j].badpixel[0][i*i]);
                //                      allflatsout->flatdata[j].data[0][i*i],
                //                      allflatsout->flatdata[j].sigma[0][i*i],
                //                      allflatsout->flatdata[j].badpixel[0][i*i]);
            }
        }
#endif

    }
    /* free the slit flats */
    if (freeslitflats(slitflats)!=NOERR) {
        SCTPUT("Error while freeing the memory for the Slit_FF structure\n");
        free(fitdata.offset);
        free(fitdata.sigma);
        free(fitdata.value);
        return flames_midas_fail();
    }
    free(slitflats);
    /* free the background frame */
    free_fdmatrix(backframe, 0, framebuffer->subrows-1, 0,
                  framebuffer->subcols-1);
    /* free the framebuffer */
    free_cvector(framebuffer->fibremask, 0, framebuffer->maxfibres-1);
    free(framebuffer);

    SCTPUT("Background fitting and subtraction done");


#if FLAMES_DEBUG
    {int i, j;
    for (j = 0; j < 3; j++)
        for (i = 0; i <= 1000; i += 10) {
            fprintf(stderr, "backsub done: %d %d %f %f %d\n", __LINE__, i,
                            allflatsin->flatdata[j].data[0][i*i],
                            allflatsin->flatdata[j].sigma[0][i*i],
                            allflatsin->flatdata[j].badpixel[0][i*i]);
            //                      allflatsout->flatdata[j].data[0][i*i],
            //                      allflatsout->flatdata[j].sigma[0][i*i],
            //                      allflatsout->flatdata[j].badpixel[0][i*i]);
        }
    }
#endif

    /* allocate and clone from allflatsin the local allflatsout structure */
    allflatsout = (allflats *) calloc(1, sizeof(allflats));
    if ((status = cloneallflats(allflatsin, allflatsout)) != NOERR) {
    	free(fitdata.offset);
    	free(fitdata.sigma);
    	free(fitdata.value);
        return(status);
    }

    SCTPUT("Cleaning stage started...");

    /* allocate the local badifibre array of structures and badixstruct
     arrays therein */
    badifibre = (badifibrestruct *)
                        calloc((size_t)(allflatsin->maxfibres), sizeof(badifibrestruct));
    for (ifibre=0; ifibre<=allflatsin->maxfibres-1; ifibre++) {
        badifibre[ifibre].badixs = (badixstruct *)
                          calloc((size_t)(allflatsin->subcols), sizeof(badixstruct));
    }



#if FLAMES_DEBUG
    {int i;
    for (i = 0; i < 10; i++) {
        fprintf(stderr, "%d %f %f %d\n", i,
                        allflatsin->flatdata[0].data[0][i*i*i*i],
                        allflatsin->flatdata[0].sigma[0][i*i*i*i],
                        allflatsin->flatdata[0].badpixel[0][i*i*i*i]);
        //                        allflatsout->flatdata[0].data[0][i*i*i*i],
        //                        allflatsout->flatdata[0].sigma[0][i*i*i*i],
        //                        allflatsout->flatdata[0].badpixel[0][i*i*i*i]);
    }
    }
#endif


    /* begin looping over orders at first */
    for (iorder=0; iorder <= ((ordpos->lastorder)-(ordpos->firstorder));
                    iorder++) {
        if ( strcmp(drs_verbosity,"LOW") == 0 ){
        } else {
            sprintf(output, "First cleaning step, order %d", iorder+1);
            SCTPUT(output);
        }
        shiftbuffer = shiftdata[iorder];
        lvecbuf1 = allflatsin->lowfibrebounds[iorder][0];
        int32_t* lvecbuf2 = allflatsin->highfibrebounds[iorder][0];
        frame_data* fdvecbuf3 = allflatsin->normfactors[iorder][0];
        frame_data* fdvecbuf4 = allflatsin->normsigmas[iorder][0];
        fmvecbuf1 = allflatsin->goodfibres[iorder][0];
        /* loop over FF frames */
        for (iframe=0; iframe<=allflatsin->nflats-1;iframe++) {
            fdvecbuf1 = allflatsout->flatdata[iframe].data[0];
            fdvecbuf2 = allflatsout->flatdata[iframe].sigma[0];
            fmvecbuf2 = allflatsout->flatdata[iframe].badpixel[0];
            fmvecbuf3 = allflatsin->flatdata[iframe].badpixel[0];
            badtotal = 0;
            /* loop over lit fibres in this frame */
            for (lfibre=0; lfibre<=((allflatsin->flatdata)[iframe]).numfibres-1;
                            lfibre++) {
                ifibre = (((allflatsin->flatdata)[iframe]).fibres)[lfibre];
                iorderifibreindex = (iorder*allflatsin->maxfibres)+ifibre;
                mybadifibre = badifibre+ifibre;
                mybadifibre->badixcount = 0;
                mybadifibre->firstbadixindex = 0;
                /* loop over ix... */
                for (ix=0; ix<=(allflatsin->subcols-1); ix++){
                    ifibreixindex = (ifibre*allflatsin->subcols)+ix;
                    /* initialise data structures */
                    if (fmvecbuf1[ifibreixindex]==GOODSLICE) {
                        if ((status=initfillfibre(allflatsin, iorder, iframe, ifibre, ix,
                                        badifibre, &badtotal)) != NOERR){
                        	free(fitdata.offset);
                        	free(fitdata.sigma);
                        	free(fitdata.value);
                            return(status);
                        }
                    }
                }
            }

            /* do the cleansing here, within the same order loop, to reduce the
	       required sizes of temporary variables, in this way I need to keep
	       only one order at a time in memory */
            /* keep looping until we cleaned it all or we were unable to clean any further */
            oldbadtotal = badtotal+1;
            for (cleaniters=1; (cleaniters<=maxcleaniters) && (badtotal>0) &&
            (badtotal<oldbadtotal) ; cleaniters++) {
                oldbadtotal = badtotal;
                /* loop over lit fibres in this frame */
                for (lfibre=0; lfibre<=((allflatsin->flatdata)[iframe]).numfibres-1;
                                lfibre++) {
                    ifibre = (((allflatsin->flatdata)[iframe]).fibres)[lfibre];
                    iorderifibreindex = (iorder*allflatsin->maxfibres)+ifibre;
                    mybadifibre = badifibre+ifibre;
                    /* any bad ix's on this fibre? */
                    if (mybadifibre->badixcount> 0) {
                        ixindex =  mybadifibre->firstbadixindex;
                        mybadixs = mybadifibre->badixs+ixindex;
                        newbadixcount = mybadifibre->badixcount;
                        for (k=0; k<=mybadifibre->badixcount-1; k++) {
                            ix = mybadixs->badix;
                            shiftbufferix = shiftbuffer+ix;
                            /* is this fibre good at all at this ix, and do we have any shifts to use? */
                            if (shiftbufferix->numoffsets>0) {
                                /* it seems good enough, go ahead, calculate normalisation
		               factors and locate bad pixels in this slice */
                                if ((status =
                                                fillnormfactors(allflatsin, shiftbuffer, badifibre,
                                                                iorder, iframe, ifibre, ix, ixindex,
                                                                normdata)) != NOERR) {
                                	free(fitdata.offset);
                                	free(fitdata.sigma);
                                	free(fitdata.value);
                                    return(status);
                                }
                                /* now we have normalisation factors and we know which bad
		               pixels to correct */
                                /* run on the list of pixels to correct */
                                fillednumber = 0;
                                for (i=0; i<=(mybadixs->badiycount-1); i++) {
                                    iy = mybadixs->badiy[i];
                                    iyixindex = (allflatsin->subcols*iy)+ix;
                                    /* build the list of pixels to use for interpolation */
                                    if ((status =
                                                    selectfillavail(allflatsin, shiftbuffer,
                                                                    normdata, &fitdata, iorder, iframe,
                                                                    ix, iy)) != NOERR) {
                                    	free(fitdata.offset);
                                    	free(fitdata.sigma);
                                    	free(fitdata.value);
                                        return(status);
                                    }
                                    /* Do the interpolation (if possible) and put interpolated
		                 data back in frames. While data and sigmas are put directly in the frames
		                 contained in allflatsin, the badpixel mask pixels are
		                 cleaned in a separate temporary frame; in this way,
		                 filled pixels can be used for more interpolation only
		                 starting from the next cleansing pass. I want to avoid
		                 the possibility to find different interpolated values
		                 depending on the order in which pixels are filled. */
                                    if ((status =
                                                    dointerpolate(allflatsout, &fitdata, iorder, iframe,
                                                                    ifibre, ix, iy)) !=NOERR) {
                                    	free(fitdata.offset);
                                    	free(fitdata.sigma);
                                    	free(fitdata.value);
                                        return(status);
                                    }
                                    /* was the correction successful? */
                                    if (fmvecbuf2[iyixindex] == 0) {
                                        /* negative values may wreak havoc in iterative
		                   interpolations, i.e. other pixels interpolated
		                   using this value, therefore clip them */
                                        if ((pixelvalue = fdvecbuf1[iyixindex])<0) {
                                            if ((pixelvalue*pixelvalue)>(4*fdvecbuf2[iyixindex])) {
                                                pixelsigma = (frame_data)
			                      pow(fdvecbuf2[iyixindex],.5);

                                                if ( strcmp(drs_verbosity,"LOW") == 0 ){
                                                } else {
                                                    sprintf(output, "%s", drs_id);
                                                    SCTPUT(output);
                                                    SCTPUT("Warning: interpolated large negative value:");
                                                    sprintf(output, "pixel=%g and sigma=%g at x=%d, \
y=%d", pixelvalue, pixelsigma, ix+1, iy+1);
                                                    SCTPUT(output);
                                                    SCTPUT("marking it bad");
                                                }
                                                fdvecbuf2[iyixindex] = pixelvalue*pixelvalue;
                                                fdvecbuf1[iyixindex] = 0;
                                                fmvecbuf2[iyixindex] = 1;
                                            }
                                            else {
                                                /* we are within error, just clip it silently */
                                                fdvecbuf1[iyixindex] = 0;
                                            }
                                        }
                                        /* increase the number of successfully corrected badpixels */
                                        fillednumber++;
                                        badtotal--;
                                    }
                                }
                                /* free dynamic temporary arrays */
                                if (mybadixs->badiy!=0) {
                                    free(mybadixs->badiy);
                                    mybadixs->badiy=0;
                                }
                                /* did we fill all bad pixels in this ix slice? */
                                if (fillednumber == mybadixs->badiycount) {
                                    /* yes, we did: take this ix out of the list of the ones containing bad pixels */
                                    newbadixcount--;
                                    /* set up pointers to prev and next ixindex */
                                    /* is this the first ixindex in the list? */
                                    if (ixindex == mybadifibre->firstbadixindex) {
                                        /* there is no ixindex before this, change firstbadindex instead */
                                        mybadifibre->firstbadixindex =
                                                        mybadixs->nextbadindex;
                                    }
                                    else {
                                        mybadifibre->badixs[mybadixs->prevbadindex].nextbadindex =
                                                        mybadixs->nextbadindex;
                                    }
                                    /* is this the last ixindex in the list? */
                                    if (k != mybadifibre->badixcount-1) {
                                        /* this is not the last one */
                                        mybadifibre->badixs[mybadixs->nextbadindex].prevbadindex =
                                                        mybadixs->prevbadindex;
                                    }
                                }
                            }
                            /* fetch the next ix with bad pixels in the list */
                            ixindex = mybadixs->nextbadindex;
                            mybadixs = mybadifibre->badixs+ixindex;
                        }
                        /* hopefully some ixs have been removed from the list, hence update the counter */
                        mybadifibre->badixcount = newbadixcount;
                        /* update the badpixel mask in allflatsin with corrected pixels */
                        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
                            ifibreixindex = (ifibre*allflatsin->subcols)+ix;
                            for (iy=lvecbuf1[ifibreixindex]; iy<=lvecbuf2[ifibreixindex];
                                            iy++) {
                                fmvecbuf3[iyixindex] = fmvecbuf2[iyixindex];
                            }
                        }
                    }
                }
            }
        }

#if FLAMES_DEBUG
        {int i;
        for (i = 0; i < 10; i++) {
            fprintf(stderr, "%d %f %f %d\n", i,
                            allflatsin->flatdata[0].data[0][i*i*i*i],
                            allflatsin->flatdata[0].sigma[0][i*i*i*i],
                            allflatsin->flatdata[0].badpixel[0][i*i*i*i]);
            //                        allflatsout->flatdata[0].data[0][i*i*i*i],
            //                        allflatsout->flatdata[0].sigma[0][i*i*i*i],
            //                        allflatsout->flatdata[0].badpixel[0][i*i*i*i]);
        }
        }
#endif

        /* we still have to normalise to 1 the integral over y of each
       order/fibre/x of the fibre FF frames */
        /* loop over x... */
        if ( strcmp(drs_verbosity,"LOW") == 0 ) {
        } else {
            sprintf(output, "Fibre normalisation step, order %d", iorder+1);
            SCTPUT(output);
        }
        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
            shiftbufferix = shiftbuffer+ix;
            /* loop over FF frames */
            for (iframe=0; iframe<=allflatsin->nflats-1;iframe++) {
                fdvecbuf1 = allflatsin->flatdata[iframe].data[0];
                fdvecbuf2 = allflatsin->flatdata[iframe].sigma[0];
                fmvecbuf2 = allflatsin->flatdata[iframe].badpixel[0];
                /* loop over lit fibres in this frame */
                for (lfibre=0; lfibre<=((allflatsin->flatdata)[iframe]).numfibres-1;
                                lfibre++) {
                    ifibre = (((allflatsin->flatdata)[iframe]).fibres)[lfibre];
                    ifibreixindex = (ifibre*allflatsin->subcols)+ix;
                    /* was this ix/order/fibre marked good altogether? otherwise skip
	     it */
                    if (fmvecbuf1[ifibreixindex] == GOODSLICE) {
                        /* try to normalise it */
                        normfactor = 0;
                        normsigma = 0;
                        badpixels = 0;
                        /* compute the fibre centre in pixel coordinates */
                        pfibrecentre =
                                        (shiftbufferix->ordercentre+ordpos->fibrepos[ifibre] -
                                                        allflatsin->substarty)/(allflatsin->substepy);
                        /* compute the precise integration limits in pixel coordinates */
                        plowlimit = pfibrecentre-phalfibrewidth;
                        phighlimit = pfibrecentre+phalfibrewidth;
                        /* loop over pixels belonging to the shifted fibre, only if
	             ishiftedyup>=ishiftedydown */
                        for (iy=lvecbuf1[ifibreixindex]; iy<=lvecbuf2[ifibreixindex];
                                        iy++) {
                            /* check that the pixel is not out of boundaries (should never happen) */
                            if ((iy<(phighlimit+0.5)) && (iy>(plowlimit-0.5))) {
                                /* not outside limits */
                                iyixindex = (iy*allflatsin->subcols)+ix;
                                fraction = 1;
                                if (iy<(plowlimit+0.5)) {
                                    /* close to lower limit, part of the pixel is outside */
                                    fraction -= plowlimit+0.5-(double)iy;
                                }
                                if (iy>(phighlimit-0.5)) {
                                    /* close to higher limit, part of the pixel is outside */
                                    fraction -= (double)iy-phighlimit+0.5;
                                }
                                /* check if this is a good pixel */
                                if (fmvecbuf2[iyixindex] == 0) {
                                    normfactor += fraction*fdvecbuf1[iyixindex];
                                    normsigma += (fraction*fraction)*fdvecbuf2[iyixindex];
                                }
                                else {
                                    /* still an uncorrected bad pixel in this ix slice of this fibre/order */
                                    badpixels++;
                                }
                            }
                        }
                        /* ok, now we either have a normalisation factor or found
	             hopelessly bad pixels */
                        normfactor2 = normfactor*normfactor;
                        if ((badpixels == 0) &&
                                        ((normfactor2/normsigma)>=decentSNR2)) {
                            /* do normalise this ix slice */
                            for (iy=lvecbuf1[ifibreixindex];
                                            iy<=lvecbuf2[ifibreixindex];
                                            iy++) {
                                iyixindex = (iy*allflatsin->subcols)+ix;
                                /* no pixel ought to be a too large fraction of the integral,
		               if we find any mark them bad (and the slice along with them */
                                if (fdvecbuf1[iyixindex] >
                                (frame_data)(maxsinglepixelfrac*normfactor)) {
                                    /* kill it */
                                    fmvecbuf2[iyixindex] = 1;
                                    badpixels++;
                                }
                                else {
                                    /* propagate sigma to the normalised pixel */
                                    dbuffer = (double)fdvecbuf1[iyixindex]/normfactor2;
                                    fdvecbuf2[iyixindex] =
                                                    fdvecbuf2[iyixindex]/(frame_data)normfactor2 +
                                                    (frame_data)(normsigma*dbuffer*dbuffer);
                                    /* normalise pixel */
                                    fdvecbuf1[iyixindex] /= (frame_data)normfactor;
                                }
                            }
                            fdvecbuf3[ifibreixindex] = (frame_data)normfactor;
                            fdvecbuf4[ifibreixindex] = (frame_data)normsigma;
                            if (badpixels != 0) {
                                /* we found a spike, kill the slice */
                                fmvecbuf1[ifibreixindex] = BADSLICE;
                                /* zero normfactors and normsigmas to make purify happy */
                                fdvecbuf3[ifibreixindex] = 0;
                                fdvecbuf4[ifibreixindex] = 0;
                                for (iy=lvecbuf1[ifibreixindex];
                                                iy<=lvecbuf2[ifibreixindex];
                                                iy++) {
                                    iyixindex = (iy*allflatsin->subcols)+ix;
                                    fdvecbuf1[iyixindex] = 0;
                                    fdvecbuf2[iyixindex] = allflatsin->gain*allflatsin->ron;
                                    fmvecbuf2[iyixindex] = 1;
                                }
                            }
                        }
                        else {
                            /* still badpixels: mark this ix/fibre/order as half bad */
                            fmvecbuf1[ifibreixindex] = BADSLICE;
                            /* zero normfactors and normsigmas to make purify happy */
                            fdvecbuf3[ifibreixindex] = 0;
                            fdvecbuf4[ifibreixindex] = 0;
                            for (iy=lvecbuf1[ifibreixindex];
                                            iy<=lvecbuf2[ifibreixindex];
                                            iy++) {
                                iyixindex = (iy*allflatsin->subcols)+ix;
                                fdvecbuf1[iyixindex] = 0;
                                fdvecbuf2[iyixindex] = allflatsin->gain*allflatsin->ron;
                                fmvecbuf2[iyixindex] = 1;
                            }
                        }
                    }
                    else {
                        /* this is a bad slice, zero it just in case */
                        for (iy=lvecbuf1[ifibreixindex];
                                        iy<=lvecbuf2[ifibreixindex];
                                        iy++) {
                            iyixindex = (iy*allflatsin->subcols)+ix;
                            fdvecbuf1[iyixindex] = 0;
                            fdvecbuf2[iyixindex] = allflatsin->gain*allflatsin->ron;
                            fmvecbuf2[iyixindex] = 1;
                        }
                        fdvecbuf3[ifibreixindex] = 0;
                        fdvecbuf4[ifibreixindex] = 0;
                    }
                }
            }
        }


        /* give up trying to clean normalisation factors, just try to
       give meaningful normalised values to remaining bad slices */
        /* loop over FF frames */
        if ( strcmp(drs_verbosity,"LOW") == 0 ){
        } else {
            sprintf(output, "Final cleaning step, order %d", iorder+1);
            SCTPUT(output);
        }
        for (iframe=0; iframe<=allflatsin->nflats-1;iframe++) {
            fdvecbuf1 = allflatsin->flatdata[iframe].data[0];
            fdvecbuf2 = allflatsin->flatdata[iframe].sigma[0];
            fmvecbuf2 = allflatsin->flatdata[iframe].badpixel[0];
            fdvecbuf5 = allflatsout->flatdata[iframe].data[0];
            fdvecbuf6 = allflatsout->flatdata[iframe].sigma[0];
            fmvecbuf3 = allflatsout->flatdata[iframe].badpixel[0];

#if FLAMES_DEBUG
            {int i;
            for (i = 0; i < 10; i++) {
                fprintf(stderr, "%d %f %f %d %f %f %d\n", i,
                                allflatsin->flatdata[iframe].data[0][i*i*i*i],
                                allflatsin->flatdata[iframe].sigma[0][i*i*i*i],
                                allflatsin->flatdata[iframe].badpixel[0][i*i*i*i],
                                allflatsout->flatdata[iframe].data[0][i*i*i*i],
                                allflatsout->flatdata[iframe].sigma[0][i*i*i*i],
                                allflatsout->flatdata[iframe].badpixel[0][i*i*i*i]);
            }
            }
#endif

            /* loop over lit fibres in this frame */
            for (lfibre=0; lfibre<=((allflatsin->flatdata)[iframe]).numfibres-1;
                            lfibre++) {
                ifibre = (((allflatsin->flatdata)[iframe]).fibres)[lfibre];
                /* any bad slices on this fibre? */
                badtotal = 0;
                goodslices = 0;
                for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
                    ifibreixindex = (ifibre*allflatsin->subcols)+ix;
                    /* is this a bad slice? */
                    if (fmvecbuf1[ifibreixindex] != GOODSLICE) {
                        /* yes, it is */
                        /* add its pixels to the badtotal counter */
                        for (iy=lvecbuf1[ifibreixindex];
                                        iy<=lvecbuf2[ifibreixindex];
                                        iy++) {
                            badtotal++;
                        }
                    }
                    else {
                        /* this specific slice (order/fibre/x) is good, we may attempt to
	             correct something */
                        goodslices++;
                    }
                }

                if (goodslices>0) {
                    /* there is at least one good slice in this fibre/order, do start
	           the correction loop */
                    /* start the final filling loop */
                    oldbadtotal = badtotal+1;
                    while ((badtotal > 0) && (badtotal < oldbadtotal)) {
                        oldbadtotal = badtotal;
                        /* scan the pixels belonging to this fibre/order */
                        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
                            ifibreixindex = (ifibre*allflatsin->subcols)+ix;
                            for (iy=lvecbuf1[ifibreixindex];
                                            iy<=lvecbuf2[ifibreixindex];
                                            iy++) {
                                iyixindex = (iy*allflatsin->subcols)+ix;
                                /* should we attempt to correct this pixel? */
                                if (fmvecbuf2[iyixindex] != 0) {
                                    /* yes, do try */
                                    /* build the list of pixels to use for interpolation */
                                    /* use selectavail instead of selectfillavail, since
		                 we do not care any more for normalisation factors */
                                    if ((status=selectavail(allflatsin, shiftbuffer,
                                                    &fitdata, iorder, iframe, ix, iy))
                                                    != NOERR) {
                                        return(status);
                                    }
                                    /* Do the interpolation (if possible) and put interpolated
		                 data back in frames.
		                 While data and sigmas are put directly in the frames
		                 contained in allflatsin, the badpixel mask pixels are
		                 cleaned in a separate temporary frame; in this way,
		                 filled pixels can be used for more interpolation only
		                 starting from the next cleansing pass. I want to avoid
		                 the possibility to find different interpolated values
		                 depending on the order in which pixels are filled. */
                                    if ((status = dointerpolate(allflatsout, &fitdata, iorder,
                                                    iframe, ifibre, ix, iy))
                                                    !=NOERR) {
                                        return(status);
                                    }
                                    /* was the correction successful? */
                                    if (fmvecbuf3[iyixindex] == 0) {
                                        /* negative values and/or anomalously large values
		                   may wreak havoc in iterative interpolations, i.e.
		                   other pixels interpolated using this value, therefore clip them */
                                        if ((pixelvalue = fdvecbuf5[iyixindex])<0) {
                                            if ((pixelvalue*pixelvalue)>(4*fdvecbuf6[iyixindex])) {
                                                pixelsigma = (frame_data) pow(fdvecbuf6[iyixindex],.5);


                                                if ( strcmp(drs_verbosity,"LOW") == 0 ) {
                                                } else {
                                                    sprintf(output, "%s", drs_id);
                                                    SCTPUT(output);
                                                    SCTPUT("Warning: interpolated large negative value:");
                                                    sprintf(output, "pixel=%g and sigma=%g at x=%d, \
y=%d", pixelvalue, pixelsigma, ix+1, iy+1);
                                                    SCTPUT(output);
                                                    SCTPUT("marking it bad");
                                                }


                                                fdvecbuf6[iyixindex] = pixelvalue*pixelvalue;
                                                fdvecbuf5[iyixindex] = 0;
                                                fmvecbuf3[iyixindex] = 1;
                                            }
                                            else {
                                                /* we are within error, just clip it silently */
                                                fdvecbuf5[iyixindex] = 0;
                                            }
                                        }
                                        else if (pixelvalue>fdmaxsinglepixelfrac) {
                                            /* no sensible way to clip this, just kill it */
                                            pixelsigma = (frame_data) pow(fdvecbuf6[iyixindex],.5);


                                            if ( strcmp(drs_verbosity,"LOW") == 0 ) {
                                            } else {
                                                sprintf(output, "%s", drs_id);
                                                SCTPUT(output);
                                                SCTPUT("Warning: interpolated too large normalised \
value:");
                                                sprintf(output, "pixel=%g and sigma=%g at x=%d, \
y=%d", pixelvalue, pixelsigma, ix+1, iy+1);
                                                SCTPUT(output);
                                                SCTPUT("marking it bad");
                                            }

                                            fdvecbuf6[iyixindex] = pixelvalue*pixelvalue;
                                            fdvecbuf5[iyixindex] = 0;
                                            fmvecbuf3[iyixindex] = 1;
                                        }
                                        /* increase the number of successfully corrected
		       badpixels */
                                        badtotal--;
                                    }
                                }
                            }
                        }
                        /* update the badpixel mask in allflatsin with corrected pixels */
                        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
                            ifibreixindex = (ifibre*allflatsin->subcols)+ix;
                            for (iy=lvecbuf1[ifibreixindex];
                                            iy<=lvecbuf2[ifibreixindex];
                                            iy++) {
                                iyixindex = (iy*allflatsin->subcols)+ix;
                                fmvecbuf2[iyixindex] =
                                                fmvecbuf3[iyixindex];
                            }
                        }
                    }
                }
            }
        }


        /* compute the coverage over newly cleaned pixels, to see whether
       they may be labelled as half-good, i.e. good profile but no
       normalisation factor*/
        /* loop over x... */
        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
            shiftbufferix = shiftbuffer+ix;
            /* loop over FF frames */
            for (iframe=0; iframe<=allflatsin->nflats-1;iframe++) {
                fdvecbuf1 = allflatsin->flatdata[iframe].data[0];
                fdvecbuf2 = allflatsin->flatdata[iframe].sigma[0];
                fmvecbuf2 = allflatsin->flatdata[iframe].badpixel[0];
                /* loop over lit fibres in this frame */
                for (lfibre=0; lfibre<=((allflatsin->flatdata)[iframe]).numfibres-1;
                                lfibre++) {
                    ifibre = (((allflatsin->flatdata)[iframe]).fibres)[lfibre];
                    ifibreixindex = (ifibre*allflatsin->subcols)+ix;
                    /* run this check only on slices that were marked bad before */
                    if (fmvecbuf1[ifibreixindex] != GOODSLICE) {
                        normfactor = 0;
                        /* compute the fibre centre in pixel coordinates */
                        pfibrecentre =
                                        (shiftbufferix->ordercentre+ordpos->fibrepos[ifibre] -
                                                        allflatsin->substarty)/(allflatsin->substepy);
                        /* compute the precise integration limits in pixel coordinates */
                        plowlimit = pfibrecentre-phalfibrewidth;
                        phighlimit = pfibrecentre+phalfibrewidth;
                        /* loop over pixels belonging to the shifted fibre, only if
	             ishiftedyup>=ishiftedydown */
                        for (iy=lvecbuf1[ifibreixindex];
                                        iy<=lvecbuf2[ifibreixindex];
                                        iy++) {
                            /* check that the pixel is not out of boundaries (should never happen) */
                            if ((iy<(phighlimit+0.5)) && (iy>(plowlimit-0.5))) {
                                /* not outside limits */
                                iyixindex = (iy*allflatsin->subcols)+ix;
                                fraction = 1;
                                if (iy<(plowlimit+0.5)) {
                                    /* close to lower limit, part of the pixel is outside */
                                    fraction -= plowlimit+0.5-(double)iy;
                                }
                                if (iy>(phighlimit-0.5)) {
                                    /* close to higher limit, part of the pixel is outside */
                                    fraction -= (double)iy-phighlimit+0.5;
                                }
                                /* check if this is a good pixel */
                                if (fmvecbuf2[iyixindex] == 0) {
                                    normfactor += fraction*fdvecbuf1[iyixindex];
                                }
                            }
                        }
                        /* ok, see if the "normalisation fraction" found exceeds the
	             the minimum required to try extracting it */
                        if (normfactor<allflatsin->minfibrefrac) {
                            /* this slice is completely hopeless, mark it accordingly */
                            fmvecbuf1[ifibreixindex] = BADSLICE;
                            for (iy=lvecbuf1[ifibreixindex];
                                            iy<=lvecbuf2[ifibreixindex];
                                            iy++) {
                                iyixindex = (iy*allflatsin->subcols)+ix;
                                fdvecbuf1[iyixindex] = 0;
                                fdvecbuf2[iyixindex] = allflatsin->gain*allflatsin->ron;
                                fmvecbuf2[iyixindex] = 1;
                            }
                        }
                        else {
                            /* this slice can be somewhat used yet, mark it half-good */
                            fmvecbuf1[ifibreixindex] = DEMISLICE;
                        }
                    }
                }
            }
        }
    }

    SCTPUT("Cleaning stage finished.");

    /* ok, now let's check whether there is some fibre which is nominally
     lit but which is actually broken or otherwise unlit */
    fmvecbuf1 = allflatsin->goodfibres[0][0];
    for (ifibre=0; ifibre<=(allflatsin->maxfibres-1); ifibre++) {
        if (allflatsin->fibremask[ifibre]==TRUE) {
            uves_msg_debug("fibre %d", ifibre);
            totslices = fracslices = 0;
            for (iorder=0; iorder<=(ordpos->lastorder-ordpos->firstorder);
                            iorder++) {
                iorderifibreindex = (iorder*allflatsin->maxfibres)+ifibre;
                for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
                    iorderifibreixindex = (iorderifibreindex*allflatsin->subcols)+ix;
                    totslices++;
#if FLAMES_DEBUG
                    fprintf(stderr, "fmvecbuf1[%d] = %d %f %f",
                            iorderifibreixindex,
                            fmvecbuf1[iorderifibreixindex],
                            fracslices,
                            totslices);
#endif
                    if (fmvecbuf1[iorderifibreixindex] == GOODSLICE) {
                        /* there is at least one good slice for this fibre, keep it */
                        fracslices++;
                    }
                }
            }
            fracslices /= totslices;
            if (fracslices < fracslicesthres) {
                /* we were unable to find any good slice for this fibre, discard it */
                allflatsin->fibremask[ifibre] = FALSE;
                ordpos->fibremask[ifibre] = FALSE;
                sprintf(output, "%s", drs_id);
                SCTPUT(output);
                sprintf(output, "fracslices=%f Warning: ignoring fibre %d which has poor coverage",
                        fracslices,ifibre+1);
                SCTPUT(output);
            }
        }
    }

    /* reset the fibres and numfibres terms within allflatsin, they may have
     been changed */
    for (iframe=0; iframe<=(allflatsin->nflats-1); iframe++) {
        newnumfibres = 0;
        newfibres = lvector(0,allflatsin->maxfibres-1);
        for (lfibre=0; lfibre<=allflatsin->flatdata[iframe].numfibres-1; lfibre++){
            ifibre = allflatsin->flatdata[iframe].fibres[lfibre];
            if (allflatsin->fibremask[ifibre]==TRUE) {
                /* this fibre is ok, add it */
                newfibres[newnumfibres] = ifibre;
                newnumfibres++;
            }
        }
        /* ok, free the old fibres and set it to the new vector */
        free_lvector(allflatsin->flatdata[iframe].fibres,
                     0, allflatsin->maxfibres-1);
        allflatsin->flatdata[iframe].fibres = newfibres;
        allflatsin->flatdata[iframe].numfibres = newnumfibres;
    }


    /* free dynamically allocated temporary variables here */
    for (iframe=0; iframe<=allflatsout->nflats-1; iframe++) {
        free_fmmatrix(allflatsout->flatdata[iframe].badpixel, 0,
                        (allflatsout->subrows)-1, 0,
                        (allflatsout->subcols)-1);
    }
    free(allflatsout->flatdata);
    free(allflatsout);
    for (i=0; i<=ordpos->lastorder-ordpos->firstorder; i++) {
        shiftbuffer = shiftdata[i];
        for (ix=0; ix<=(allflatsin->subcols-1); ix++){
            free(shiftbuffer[ix].ixoffsets);
            free(shiftbuffer[ix].yfracoffsets);
            free(shiftbuffer[ix].yintoffsets);
            free(shiftbuffer[ix].normfactor);
            free(shiftbuffer[ix].normsigma);
            free(shiftbuffer[ix].goodoverlap);
        }
    }
    free(shiftdata[0]);
    free(shiftdata);
    for (ifibre=0; ifibre<=allflatsin->maxfibres-1; ifibre++) {
        free(badifibre[ifibre].badixs);
    }
    free(badifibre);

    free(fitdata.offset);
    free(fitdata.value);
    free(fitdata.sigma);

    return(NOERR);

}
/**@}*/
