/*===========================================================================
  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
===========================================================================*/
/* Program  : singlecorrel.c                                               */
/* Author   : G. Mulas  -  ITAL_FLAMES Consortium                          */
/* Date     :                                                              */
/*                                                                         */
/* Purpose  : Missing                                                      */
/*                                                                         */
/*                                                                         */
/* Input:  see interface                                                   */ 
/*                                                                      */
/* Output:                                                              */
/*                                                                         */
/* DRS Functions called:                                                   */
/* none                                                                    */ 
/*                                                                         */ 
/* Pseudocode:                                                             */
/* Missing                                                                 */ 
/*                                                                         */ 
/* Version  :                                                              */
/* Last modification date: 2002/08/05                                      */
/* Who     When        Why                Where                            */
/* AMo     02-08-05   Add header         header                            */
/*-------------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif


#include <stdlib.h>
#include <math.h>
#include <flames_midas_def.h>
#include <flames_singlecorrel.h>
#include <flames_uves.h>


/**
  @brief    Compute the correlation of the science frame with the odd-even base
  @param    ScienceFrame the science frame
  @param    Orderpos     the orderposition structure
  @param    fibrelist    array with fibre indexes
  @param    nlitfibres   number of lit fibres
  @param    ordercentre  array with order centres for each fibre
  @param    ilowlimits   array with lower limits for each fibre
  @param    iuplimits    array with upper limits for each fibre
  @param    correlxstep  step to compute correlation
  @param    yshift       shift at which the correlation is computed
  @return   the correlation value if everything is ok
  @doc
  For each fibre, for each order, for each x, 
            perform a correlation between the scince frame and a gaussian
            at the corresponding x,y position and the sigma
     
  
 */
/*--------------------------------------------------------------------------*/
double 
singlecorrel(flames_frame *ScienceFrame, 
         orderpos *Order, 
         int32_t *fibrelist,
         int32_t nlitfibres,
         double **ordercentres,
         int32_t **ilowlimits,
         int32_t **iuplimits,
         int32_t correlxstep, 
         double yshift)
{

  double correlvalue=0;
  int32_t lfibre=0;
  int32_t ifibre=0;
  double fibreshift=0;
  double fibrecontrib=0;
  int32_t iorder=0;
  double orderfibrecontrib=0;
  double orderfibreixcontrib=0;
  int32_t ix=0;
  double fibrecentre=0;
  double pfibrecentre=0;
  int32_t plowfibrelim=0;
  int32_t pupfibrelim=0;
  int32_t iy=0;
  double dy=0;
  /* char goodfibreix=FALSE; */

  double *dvecbuf1=0;
  int32_t *lvecbuf1=0;
  int32_t *lvecbuf2=0;
  frame_data *fdvecbuf1=0;
  frame_mask *fmvecbuf1=0;
  int32_t iorderixoffset=0;
  int32_t iorderixindex=0;
  int32_t iyixindex=0;


  dvecbuf1 = ordercentres[0];
  lvecbuf1 = ilowlimits[0];
  lvecbuf2 = iuplimits[0];
  fdvecbuf1 = ScienceFrame->frame_array[0];
  fmvecbuf1 = ScienceFrame->badpixel[0];

  /* initialise the correlvalue */
  correlvalue=0;

 
  for (lfibre=0; lfibre<=(nlitfibres-1); lfibre++) {
    ifibre = fibrelist[lfibre];
    /* compute the yshifted position of each fibre here, to spare a few
       cycles in inner loops */
    fibreshift = Order->fibrepos[ifibre]+Order->gaussselfshift[ifibre]+yshift;
    /* to make sure we do not lose contributions to the correlation
       due to rounding errors, especially since we will be summing a few 
       hundred thousend contributions or more, add them up hierarchically, 
       one fibre at a time and, within each fibre, one order at a time */
    fibrecontrib = 0;
    for (iorder=0; iorder<=(Order->lastorder-Order->firstorder); iorder++) {
      iorderixoffset = iorder*ScienceFrame->subcols;
      orderfibrecontrib = 0;
      for (ix=0; ix<=(ScienceFrame->subcols-1); ix+=correlxstep) {
    iorderixindex = iorderixoffset+ix;
    orderfibreixcontrib = 0;
           /* goodfibreix = TRUE; */
    /* before the innest loop, I might check goodfibres[iorder][ifibre][ix]
       to see whether this fibre is good at this iorder and ix, in order 
       to spare some useless operations if it is not; it 
       might be argued that since this will be seldom the case, it would 
       be better to remove this test (which would be executed in any 
       case) and accept to waste some time doing useless operations when
       it would fail; we will investigate this later on, but I suspect
       that the difference will be small anyway. Right now, we skip
       the test. */
    /* find the fibre centre in world coordinates */
    fibrecentre = dvecbuf1[iorderixindex]+fibreshift;
    /* convert the fibre centre to pixel coordinates */
    pfibrecentre = (fibrecentre-ScienceFrame->substarty)/
      ScienceFrame->substepy;
    /* define the interval in pixels out of which we assume the 
       "gaussian" fibre to be negligible */
    plowfibrelim = (int32_t) floor(pfibrecentre-Order->pgausshalfwidth);
    pupfibrelim = (int32_t) ceil(pfibrecentre+Order->pgausshalfwidth);
    /* find the intersection between the above interval and the 
       interval (not determined here) over which we sample this order */
    if (plowfibrelim<lvecbuf1[iorderixindex])
      plowfibrelim = lvecbuf1[iorderixindex];
    if (pupfibrelim>lvecbuf2[iorderixindex])
      pupfibrelim = lvecbuf2[iorderixindex];
    for (iy=plowfibrelim; iy<=pupfibrelim; iy++) {
      iyixindex = (iy*ScienceFrame->subcols)+ix;
      /* of course, avoid including known bad pixels in the count */
      if (fmvecbuf1[iyixindex]==0) {
        dy = (pfibrecentre-(double)iy)/Order->pgausssigma;
        orderfibreixcontrib += exp(-dy*dy)*((double)fdvecbuf1[iyixindex]);
      }
      /* else goodfibreix = FALSE; */
    }
    /* if (goodfibreix==TRUE) orderfibrecontrib += orderfibreixcontrib; */
    orderfibrecontrib += orderfibreixcontrib;
      }
      fibrecontrib += orderfibrecontrib;
    }
    correlvalue += fibrecontrib;
  }

  return correlvalue;

}
