/*===========================================================================
  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_gausscorrel This function finds the shift for the FF to 
 use them to model the fibres PSF on the CCD
 *
 */
/*-------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------
  Includes
  --------------------------------------------------------------------------*/

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


#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#include <flames_lfit.h>
#include <flames_getordpos.h>
#include <flames_gausscorrel.h>
#include <flames_gausscorrelFF.h>
#include <flames_singlecorrel.h>
#include <flames_correl.h>
#include <flames_midas_tblsys.h>
#include <flames_midas_tbldef.h>
#include <flames_midas_tblerr.h>
#include <flames_midas_atype.h>
#include <flames_midas_macrogen.h>
#include <flames_midas_def.h>
#include <flames_def_drs_par.h>
#include <flames_uves.h>
#include <flames_newmatrix.h>
#include <flames_mvfit.h>
#include <uves_msg.h>

/* this is the numeric value of the golden section, used in the brent 
   algorithm */
#define CGOLD 0.3819660

static int imaxarg1,imaxarg2;
#define IMAX(a,b) (imaxarg1=(a),imaxarg2=(b),(imaxarg1) > (imaxarg2) ? (imaxarg1) : (imaxarg2))
#define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a))

/*
static double 
get_max_poly(double a[],const int m,double* x,double* y);
*/

static double 
poly(double x,double a[], int ma);

static void 
fpoly(double x,double poly[],int ma);


static double 
get_max_cubic(double a[],double* x,double* y);

/*

static void 
balanc2(double** a,int n);

static void 
hqr(double** a,int n, double wr[], double wi[]);

static void 
zrpoly(double a[],int m, double rtr[], double rti[]);


static void 
hqr(double** a,int n, double wr[], double wi[])
{
  
    //Finds all eigenvalues of an upper Hassemberg matrix a[1..n][1..n].
    //On input a can be exactly as output from elhmes; on output it is destroyed;
    //The real and imaginary parts of the eigenvalues are returned in wr[1..n] and 
    //wi[1..n], respectively.
  

  int nn=0;
  int m=0;
  int l=0;
  int k=0;
  int j=0;
  int its=0;
  int i=0;
  int mmin=0;

  double z=0;
  double y=0;
  double x=0;
  double w=0;
  double v=0;
  double u=0;
  double t=0;
  double s=0;
  double r=0;
  double q=0;
  double p=0;
  double anorm=0;

  // compute matrix norm for possible use in locating single small 
  //   subdiagonal element
  anorm=0.0;
  for (i=1;i<=n;i++){
    for (j=IMAX(i-1,1);j<=n;j++){  // IMAX 
      anorm += fabs(a[i][j]);
    }
  }
  nn=n;
  t=0.0;
  // Get changed only by an exceptional shift 

  while (nn >= 1 ) {
    // Begin search for next eigenvalue 

    its=0;
    do {
      for (l=nn;l>=2;l--){
	// Begin iteration: look for single small subdiagonal element 
        s=fabs(a[l-1][l-1])+fabs(a[l][l]);
        if (s == 0.0) {
	  s=anorm;
        }
        if ((float)(fabs(a[l][l-1])+s) == s ){
	  break;
	}
      }
      x=a[nn][nn];
      if (l == nn) {
      // One root found 
        wr[nn]=x+t;
        wi[nn--]=0.0;
      } else {
        y=a[nn-1][nn-1];
        w=a[nn][nn-1]*a[nn-1][nn];
        if (l == (nn-1)) {
	// Two roots found...
	  p=0.5*(y-x);
	  q=p*p+w;
	  z=sqrt(fabs(q));
	  x += t;
	  if ( q >= 0.0 ) {
	  // a real part 
            z=p+SIGN(z,p);
            wr[nn-1]=wr[nn]=x+z;
            if (z) {
	      wr[nn]=x-w/z;
            }
            wi[nn-1]=wi[nn]=0.0;
	  } else {
	  // a complex pair .. 
            wr[nn-1]=wr[nn]=x+p;
            wi[nn-1]= -(wi[nn]=z);
	  }
	  nn -= 2;
        } else {
	// No roots found. Continue iteration. 
	  if (its == 30 ) {
            printf ("Too many iterations in hqr\n");
	  }
	  if (its == 10 || its == 20) {
	  // Form exceptional shift 
	    t += x;
            for (i=1; i<= nn; i++) {
	      a[i][i] -= x;
            }
            s=fabs(a[nn][nn-1])+fabs(a[nn-1][nn-2]);
            y=x=0.75*s;
            w = -0.4375*s*s;
	  }
	  ++its;
	  for (m=(nn-2); m>=l;m--) {
	  // Form shift and then look for 2 consecutive small subdiagonal elements 
            z=a[m][m];
            r=x-z;
            s=y-z;
            p=(r*s-w)/a[m+1][m]+a[m][m+1];
            q=a[m+1][m+1]-z-r-s;
            r=a[m+2][m+1];
            s=fabs(p)+fabs(q)+fabs(r);
	    // scale to prevent overflow or underflow 
            p /=s;
            q /= s;
            r /= s;
            if ( m ==1 ) {
	      break;
            }
            u = fabs(a[m][m-1])*(fabs(q)+fabs(r));
            v=fabs(p)*(fabs(a[m-1][m-1])+fabs(z)+fabs(a[m+1][m+1]));
            if ((float)(u+v) == v) {
	      break;
            }
	  }
	  for (i=m+2; i<= nn; i++) {
            a[i][i-2]=0.0;
            if (i != (m+2)) {
	      a[i][i-3]=0.0;
            }
	  }
	  for (k=m; k<= nn-1; k++) {
	  // Double QR step on rows 1 to nn and columns m to nn. 
            if (k != m) {
	    // Begin setup of Hauseholder vector 
	      p=a[k][k-1];
	      q=a[k+1][k-1];
	      r=0.0;
	      if (k != (nn-1)) {
                r=a[k+2][k-1];
	      }
	      if ((x=fabs(p)+fabs(q)+fabs(r)) != 0.0) {
	      // scale to prevent overflow or underflow 
		p /= x;
		q /= x;
		r /= x;
	      }
            }
            if (( s=SIGN(sqrt(p*p+q*q+r*r),p)) != 0.0) {
	      if( k == m) {
		if (l != m) {
		  a[k][k-1] = -a[k][k-1];
                } 
	      } else {
                a[k][k-1] = -s*x;
	      }
	      p += s;
	      x=p/s;
	      y=q/s;
	      z=r/s;
	      q /= p;
	      r /= p;
	      // Row modification 
	      for (j=k;j<=nn;j++) {
                p=a[k][j]+q*a[k+1][j];
                if( k != (nn-1)) {
		  p += r*a[k+2][j];
		  a[k+2][j] -= p*z;
                }
                a[k+1][j] -= p*y;
                a[k][j] -= p*x;
	      }
	      mmin = nn<k+3 ? nn : k+3;
	      // Column modification 
	      for (i=l;i<=mmin;i++) {
                p=x*a[i][k]+y*a[i][k+1];
                if (k != (nn-1)) {
		  p += z*a[i][k+2];
		  a[i][k+2] -= p*r;
                }
                a[i][k+1] -= p*q;
                a[i][k] -= p;
	      }
            }
	  }
        }
      }
    } while (l < nn-1);
  }
                    
}
*/

/*
#define BALANC_RADIX 2.0

static void 
balanc2(double** a,int n)
{
  
  //  Given a matrix a[1..n][1..n], this routine replaces it by a balanced matrix 
  //  with identical eigenvalues. A symmetric matrix is already balanced and is 
  //  unaffected by this procedure. The parameter BLANC_RADIX should be the 
  //  machine's floating-point radix.
  
  int last=0;
  int j=0;
  int i=0;
  double s=0;
  double r=0;
  double g=0;
  double f=0;
  double c=0;
  double sqrdx=0;

  sqrdx=BALANC_RADIX*BALANC_RADIX;
  last=0.;
  while (last == 0) {
    last=1;
    for (i=1;i<=n;i++) {
      // Calculate row and column norms 
      r=c=0.0;
      for (j=1;j<=n;j++){
        if (j != i) {
	  c += fabs(a[j][i]);
	  r += fabs(a[i][j]);
        }
      }
      if (c && r ) {
	// if both are nonzero 
        g=r/BALANC_RADIX;
        f=1.0;
        s=c+r;
        while (c<g) {
	  f /= BALANC_RADIX;
	  c /= sqrdx;
        }
        if ((c+r)/f <0.95*s) {
	  last=0;
	  g=1.0/f;
	  // apply similarity transformation 
	  for (j=1;j<=n;j++) { 
            a[i][j] *= g;
	  }
	  for (j=1;j<=n;j++) {
            a[j][i] *= f;
	  }
        }
      }
    }
  }
}
*/

/*
#define ZRPOLY_MAXM 50
 

static void 
zrpoly(double a[],int m, double rtr[], double rti[])
{
  
  //  Find all the roots of a polynomial with real coefficients, SUM(0,m)a(i)*x^i,
  //  given the degree m and the coefficients a[0...m]. The method is to construct 
  //  an upper Hessenberg matrix whose eigenvalues are the desired roots, and then 
  //  use the routines balanc and hqr. The real and immaginary parts of the roots 
  //  are returned in rtr[1..m] and rti[1..m], respectively.

  

  int j=0;
  int k=0;
  double ** hess;
  double xr=0;
  double xi=0;

  hess=dmatrix(1,ZRPOLY_MAXM,1,ZRPOLY_MAXM);
  if( m> ZRPOLY_MAXM || a[m] == 0.0 ) {
    printf("Bad args in zrqr\n");
  }
  // construct the matrix 
  for (k=1;k<=m;k++){
    hess[1][k] = -a[m-k]/a[m];
    for(j=2;j<=m;j++){
      hess[j][k]=0.0;
    }
    if ( k != m) {
      hess[k+1][k]=1.0;
    }
  }
  // Finds its eigenvalues 
  balanc2(hess,m);
  for (j=2;j<=m;j++) {
    // sort roots by their real parts by straight insertion 
    xr=rtr[j];
    xi=rti[j];
    for (k=j-1;k>=1;k--){
      if (rtr[k] <= xr ){
        break;
      }
      rtr[k+1]=rtr[k];
      rti[k+1]=rti[k];
    }
    rtr[k+1]=xr;
    rtr[k+1]=xi;
  }
  free_dmatrix(hess,1,ZRPOLY_MAXM,1,ZRPOLY_MAXM);
}

*/

static void 
fpoly(double x,double vpoly[],int ma)
{
  int i=0;
  vpoly[1]=1.;
  for (i=2;i<=ma;i++) {
    vpoly[i]=vpoly[i-1]*x;
  }
  return;
}


static double 
poly(double x,double a[], int ma)
{
  int i=0;
  double p=0;
  p=a[1];
  for (i=2;i<=ma;i++) {
    p+=a[i]*pow(x,i-1);
  }
  return p;
}


/*
static double 
get_max_poly(double a[],const int m,double* x,double* y)
{
  int i=0;
  double* d;
  double* rtr;
  double* rti;
  double* ryr;
  double ymax=0;

  d=dvector(0,m-2);
  rtr=dvector(0,m-2);
  rti=dvector(0,m-2);
  ryr=dvector(0,m-2);

  // defines derivatives polynomial 
  for (i=0;i<m;i++) {
    d[i]=i*a[i+1];
  }
  // find roots 1st derivative 
  zrpoly(d,m-1,rtr,rti);

  // initialize a solution 
  ryr[0]=poly(rtr[0],a,m);
  *x=rtr[0];
  *y=rtr[0];
  ymax=rtr[0];

  // searches for maximum
  for (i=1;i<m;i++) {
    ryr[i]=poly(rtr[i],a,m);
    if (ryr[i] >= ymax){
      *x = rtr[i];
      *y = ryr[i];
    }
  }
  return *y;
}

*/

static double 
get_max_cubic(double a[],double* x,double* y)
{
  double x1,x2;
  double delta=a[3]*a[3]-3*a[2]*a[4];
  double s=sqrt(delta);
  double y1,y2;
  x1=(-a[3]-s)/(3*a[4]);
  x2=(-a[3]+s)/(3*a[4]);
  y1=poly(x1,a,4);
  y2=poly(x2,a,4);
  if (y2 <= y1){
    *x = x1;
    *y = y1;

  }
  else {
    *x = x2;
    *y = y2;
  }
  return *y;
}




/**@{*/

/*---------------------------------------------------------------------------
  Implementation
  ---------------------------------------------------------------------------*/
/**
   @name  flames_gausscorrel()  
   @short This function finds the optimal shift for the FF to use them to model
   the fibres PSF on the CCD
   @author G. Mulas  -  ITAL_FLAMES Consortium. Ported to CPL by A. Modigliani

   @param ScienceFrame 
   @param	Order
   @param	maxcorriters
   @param	shiftwindow
   @param	shifttol
   @param	correlxstep 
   @param	outtabname 
   @param	ydelta
   @param	COR_MAX_FND
   @param	COR_DEF_RNG
   @param	COR_DEF_PNT
   @param	COR_DEF_OFF
   @param	COR_TAB_SHP_ID

   @return success or failure code

   DRS Functions called:                                              
   singlecorrel                                                       
   free_dvector                                                       
   free_dmatrix                                                       
   free_lmmatrix                                                      
                                                                     
   Pseudocode:                                                        
   Missing 

   @doc This function finds the optimal shift for the FF 
   in order to use them as a physical model for the perpendicular
   shape of the PSF on the CCD by calculating the correlation 
   between Science Frame and FF. The correlation takes place between 
   a synthetic frame with gaussian-shaped fibres centered on 
   shifted fibre positions and the actual, real frame on which the shift is
   to be found.

   @note
*/




flames_err 
gausscorrel(
            flames_frame *ScienceFrame, 
	    orderpos *Order, 
	    int32_t maxcorriters,
	    double shiftwindow,
	    double shifttol,
	    int32_t correlxstep, 
	    const char *outtabname, 
	    double *ydelta,
	    const char *COR_MAX_FND,
	    const float *COR_DEF_RNG,
	    const int *COR_DEF_PNT,
	    const float *COR_DEF_OFF,
	    const char *COR_TAB_SHP_ID)
{

  char qc_y_shift_key[CATREC_LEN+1]; 
  char cor_shape_tab_name[80];

  int32_t *fibrelist;
  int32_t nlitfibres;
  int32_t minlitfibre=0;
  int32_t maxlitfibre=0;
  int outtid=0;
  int ctid =0;
  int yshiftcol=0;
  int correlcol=0;
  int y_shift_col=0;
  int correl_col=0;
  int row=0;

  double highshift=0;
  double lowshift=0;
  int32_t ifibre=0;
  double plowshift=0;
  double phighshift=0;
  int32_t iorder=0;
  double dorder=0;
  double **ordercentres=0;
  double *ordercentresiorder=0;
  int32_t **ilowlimits=0;
  int32_t *ilowlimitsiorder=0;
  int32_t **iuplimits=0;
  int32_t *iuplimitsiorder=0;
  int32_t ix=0;

  double x=0;
  double pordercentre=0;
  double tol2=0;
  double maxcorrel=0;
  double ashift=0;
  double bshift=0;
  double ushift=0;
  double vshift=0;
  double wshift=0;
  double xshift=0;
  double xmshift=0;
  double dshift=0;
  double eshift=0;
  double fashift=0;
  double fbshift=0;
  double fushift=0;
  double fvshift=0;
  double fwshift=0;
  double fxshift=0;
  double p=0;
  double q=0;
  double r=0;
  double s=0;
  double t=0;
  double etemp=0;
  double fit_par[4];
  flames_err done=0;
  int32_t iter=0;
  char output[CATREC_LEN+1];

  int actvals=0;
  char drs_verbosity[10];
  char drs_cor_max_fnd[10];
  float drs_cor_def_rng=0;
  float drs_cor_def_off=0;
  int  drs_cor_def_pnt=0;
  int mid_stat=0;
  int mid_unit=0;
  int mid_null=0;

  double step=0;
  int index=0;
  const int ndeg=4;
  int32_t sz_fit=0;
  double* yfit;
  double* xfit;
  double* sfit;
  double** covar;
  double y_shift_corr_max=0;
  double x_shift_corr_max=0;


  int ii=0;

  double* aa;
  int* ia;
  double chisq =0;


  /*
    int ia[ndeg];
  */

  memset(output, 0, CATREC_LEN+1);
  memset(qc_y_shift_key, '\0', CATREC_LEN+1);
  memset(drs_cor_max_fnd, '\0', 10);
  memset(cor_shape_tab_name, '\0', 80);



  /* allocate local arrays */

  aa = dvector(1,ndeg);
  ia = ivector(1,ndeg);
  covar = dmatrix(1,ndeg,1,ndeg);


  fibrelist = lvector(0, ScienceFrame->maxfibres-1);
  ordercentres = dmatrix(0, Order->lastorder-Order->firstorder, 
			 0, ScienceFrame->subcols-1);
  ilowlimits = lmatrix(0, Order->lastorder-Order->firstorder, 
		       0, ScienceFrame->subcols-1);
  iuplimits = lmatrix(0, Order->lastorder-Order->firstorder, 
		      0, ScienceFrame->subcols-1);

  uves_msg_debug("maxcorriters=%d",maxcorriters);
  uves_msg_debug("shiftwindow=%f",shiftwindow);
  uves_msg_debug("shifttol=%f",shifttol);
  uves_msg_debug("correlxstep=%d",correlxstep); 
  uves_msg_debug("outtabname=%s",outtabname); 
  uves_msg_debug("COR_MAX_FND=%s",COR_MAX_FND);
  uves_msg_debug("COR_DEF_RNG=%f",*COR_DEF_RNG);
  uves_msg_debug("COR_DEF_PNT=%d",*COR_DEF_PNT);
  uves_msg_debug("COR_DEF_OFF=%f",*COR_DEF_OFF);
  uves_msg_debug("COR_TAB_SHP_ID=%s",COR_TAB_SHP_ID);

  uves_msg_debug("Sci frame name: %s",ScienceFrame->framename);
  uves_msg_debug("Sci sigma name: %s",ScienceFrame->sigmaname);
  uves_msg_debug("Sci badpx name: %s",ScienceFrame->badname);

  /* We want to be able to output the correlation scans in a MIDAS table, 
     for debugging purposes */
  /* we only create the output table if we were given a name for it, so that
     it can be easily skipped if unnecessary */


  memset(drs_verbosity, 0, 10);
  memset(drs_cor_max_fnd, 0, 10);


  for (ii=1;ii<=ndeg;ii++) {
    ia[ii]=1;
    aa[ii]=1;
  }


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



  if ((mid_stat=SCKGETC(COR_MAX_FND, 1, 1, &actvals, drs_cor_max_fnd))
      != 0) {
    /* the keyword seems undefined, protest... */
    return(MAREMMA);
  }


  if ((mid_stat=SCKRDR(COR_DEF_RNG, 1, 1, &actvals, &drs_cor_def_rng,&mid_unit,&mid_null))
      != 0) {
    /* the keyword seems undefined, protest... */
    return(MAREMMA);
  }


  if ((mid_stat=SCKRDI(COR_DEF_PNT, 1, 1, &actvals, &drs_cor_def_pnt,&mid_unit,&mid_null))
      != 0) {
    /* the keyword seems undefined, protest... */
    return(MAREMMA);
  }


  if ((mid_stat=SCKRDR(COR_DEF_OFF, 1, 1, &actvals, &drs_cor_def_off,&mid_unit,&mid_null))
      != 0) {
    /* the keyword seems undefined, protest... */
    return(MAREMMA);
  }





  uves_msg_debug("drs_verbosity=%s",drs_verbosity);
  uves_msg_debug("drs_cor_max_fnd=%s",drs_cor_max_fnd);
  uves_msg_debug("drs_cor_def_rng=%f",drs_cor_def_rng);
  uves_msg_debug("drs_cor_def_pnt=%d",drs_cor_def_pnt);
  uves_msg_debug("drs_cor_def_off=%f",drs_cor_def_off);

  sz_fit = 2*drs_cor_def_pnt+1;
  yfit = dvector(1, sz_fit);
  xfit = dvector(1, sz_fit);
  sfit = dvector(1, sz_fit);


  if (outtabname != NULL) {

    /* we have a name */
    if (TCTINI(outtabname, F_O_MODE, maxcorriters+3, &outtid)
	!= 0) {
      SCTPUT("Warning: Error opening output MIDAS table for correlations");
      outtabname=NULL;
    }
    else {
      if ((TCCINI(outtid,D_R8_FORMAT,1,"G8.5","  ","YSHIFT",&yshiftcol)!=0)||
	  (TCCINI(outtid,D_R8_FORMAT,1,"G8.5","  ","CORRELATION",&correlcol)
	   !=0)) {
	SCTPUT("Warning: Error creating colums in MIDAS table for \
correlations");
	TCTCLO(outtid);
	outtabname=NULL;
      }
      else row=0;
    }
  }

  /* find the lowest and highest lit fibres in this frame */
  highshift = lowshift = 0;
  nlitfibres=0;
  for (ifibre=0; (ifibre<=(ScienceFrame->maxfibres-1)) && 
	 (ScienceFrame->fibremask[ifibre]!=TRUE); ifibre++);
  if (ifibre<=(ScienceFrame->maxfibres-1)) {
    minlitfibre = ifibre;
    lowshift = Order->fibrepos[minlitfibre];
    maxlitfibre = ifibre;
    fibrelist[0] = ifibre;
    nlitfibres = 1;
    for (ifibre++; ifibre<=(ScienceFrame->maxfibres-1); ifibre++) {
      if (ScienceFrame->fibremask[ifibre]==TRUE) {
	maxlitfibre=ifibre;
	fibrelist[nlitfibres]=ifibre;
	nlitfibres++;
      }
    }
    highshift = Order->fibrepos[maxlitfibre];
    highshift += (Order->halfibrewidth+shiftwindow);
    lowshift -= (Order->halfibrewidth+shiftwindow);
    if (ScienceFrame->substepy>0) {
      plowshift = lowshift/ScienceFrame->substepy;
      phighshift = highshift/ScienceFrame->substepy;
    }
    else {
      plowshift = highshift/ScienceFrame->substepy;
      phighshift = lowshift/ScienceFrame->substepy;
    }
  }
  else {
    SCTPUT("Correlation impossible: no lit fibres in Science Frame!");
    return flames_midas_fail();
  }


  for (iorder=0; iorder<=Order->lastorder-Order->firstorder; iorder++) {
    dorder = (double)(iorder+Order->firstorder);
    /* find the y positions of the order centres once and for all */
    ordercentresiorder = ordercentres[iorder];
    ilowlimitsiorder = ilowlimits[iorder];
    iuplimitsiorder = iuplimits[iorder];
    for (ix=0; ix<=(ScienceFrame->subcols-1); ix+=correlxstep) {
      x = ((double)ix+ScienceFrame->substartx)*ScienceFrame->substepx;
      if (get_ordpos(Order, dorder, x, ordercentresiorder+ix)!=NOERR) {
	SCTPUT("Error in get_ordpos() called by gausscorrel()");
	return flames_midas_fail();
      }
      /* convert the order centre to pixel coordinates */
      pordercentre = (ordercentresiorder[ix]-ScienceFrame->substarty)/
	ScienceFrame->substepy;
      /* here find order limits in pixel coordinates */
      ilowlimitsiorder[ix] = (int32_t) floor(pordercentre+plowshift);
      iuplimitsiorder[ix] = (int32_t) ceil(pordercentre+phighshift);
      if (ilowlimitsiorder[ix]<0) ilowlimitsiorder[ix]=0;
      if (iuplimitsiorder[ix]>(int32_t)(ScienceFrame->subrows-1))
	iuplimitsiorder[ix]=(int32_t)(ScienceFrame->subrows-1);
    }
  }

  /* 
     AMo: let's try to see what is the shape of the correlation over a 
     wide range of Y shifts.
  */

  if ( strcmp(drs_cor_max_fnd,"Y") == 0 )
    {




      sprintf(output, "Defining the correlation function's shape\n");
      SCTPUT(output);

      step=drs_cor_def_rng/(double)drs_cor_def_pnt;
      y_shift_corr_max=0;
      x_shift_corr_max=-drs_cor_def_rng;
   
      /* we have a name */
      SCKGETC(COR_TAB_SHP_ID, 1, 80, &actvals, cor_shape_tab_name);
      if (TCTINI(cor_shape_tab_name, F_O_MODE, (2*drs_cor_def_pnt+1), &ctid)!= 0) {
	SCTPUT("Warning: Error opening output MIDAS table for correlation shape");
      }
      TCCINI(ctid, D_R8_FORMAT,1,"G8.5","PIXEL","Y_SHIFT", &y_shift_col);
      TCCINI(ctid, D_R8_FORMAT,1,"G8.3","","CORREL", &correl_col);
  
      ii=1;
      for (index=-drs_cor_def_pnt;index<=drs_cor_def_pnt;index++){
	sfit[ii]=1;
	xshift=index*step+drs_cor_def_off;
	xfit[ii]=xshift;
	fxshift = singlecorrel(ScienceFrame, Order, fibrelist, nlitfibres, 
			       ordercentres, ilowlimits, iuplimits, 
			       correlxstep, xshift);
  
	yfit[ii]=fxshift;
	if(yfit[ii] >= y_shift_corr_max){
	  y_shift_corr_max=yfit[ii];
	  x_shift_corr_max=xfit[ii];
	}


	TCEWRD(ctid, ii, y_shift_col, &xfit[ii]);
	TCEWRD(ctid, ii, correl_col,  &yfit[ii]);

	/*
	sprintf(output, "correl(%g)=%g \n",xfit[ii],yfit[ii]);
	SCTPUT(output);
	*/
	ii++;
 
      }

      /*
	sprintf(output,"%s %f %d %f\n",
	drs_cor_max_fnd,drs_cor_def_rng,drs_cor_def_pnt,drs_cor_def_off);

	SCTPUT(output);
	sprintf(output, "correl(%g)=%g \n",x_shift_corr_max,y_shift_corr_max);
	SCTPUT(output);
      */  

      aa[1]=y_shift_corr_max;
      lfit(xfit,yfit,sfit,sz_fit,aa,ia,ndeg,covar,&chisq,fpoly); 
      sprintf(output, "a=%g %g %g %g \n",aa[1],aa[2],aa[3],aa[4]);
      SCTPUT(output);

      get_max_cubic(aa,&x_shift_corr_max,&y_shift_corr_max); 
      /* get_max_poly(aa,4,&x_shift_corr_max,&y_shift_corr_max); */
      fit_par[0]=aa[1];
      fit_par[1]=aa[2];
      fit_par[2]=aa[3];
      fit_par[3]=aa[4];

      SCDWRD(ctid, "COR_FIT_PAR", fit_par, 1, 4, &mid_unit);
      TCTCLO(ctid);

      sprintf(output, "correl(%g)=%g \n",x_shift_corr_max,y_shift_corr_max);
      SCTPUT(output);

      /* Ok, first of all let's see whether we can bracket the correlation
	 maximum within the limits we set for searching it */
      ashift = x_shift_corr_max-shiftwindow;
      xshift = x_shift_corr_max;
      bshift = x_shift_corr_max+shiftwindow;
    } else {
    ashift = -shiftwindow;
    xshift = 0;
    bshift = +shiftwindow;
  }
  fashift = singlecorrel(ScienceFrame, Order, fibrelist, nlitfibres, 
			 ordercentres, ilowlimits, iuplimits, 
			 correlxstep, ashift);
  fxshift = singlecorrel(ScienceFrame, Order, fibrelist, nlitfibres, 
			 ordercentres, ilowlimits, iuplimits, 
			 correlxstep, xshift);
  fbshift = singlecorrel(ScienceFrame, Order, fibrelist, nlitfibres, 
			 ordercentres, ilowlimits, iuplimits, 
			 correlxstep, bshift);
  /* be somewhat verbose */
  if ( strcmp(drs_verbosity,"LOW") == 0 ){
  } else {
    sprintf(output, "searching correlation maximum for shifts between %g and %g",
	    ashift, bshift);
    SCTPUT(output);
  }
  sprintf(output, "correl(%g)=%g, correl(%g)=%g, correl(%g)=%g", ashift, 
	  fashift, xshift, fxshift, bshift, fbshift);
  SCTPUT(output);
    
  /* should we output something to the MIDAS table? */
  if (outtabname != NULL) {
    TCEWRD(outtid, 1, yshiftcol, &ashift);
    TCEWRD(outtid, 1, correlcol, &fashift);
    TCEWRD(outtid, 2, yshiftcol, &bshift);
    TCEWRD(outtid, 2, correlcol, &fbshift);
    TCEWRD(outtid, 3, yshiftcol, &xshift);
    TCEWRD(outtid, 3, correlcol, &fxshift);
    row=3;
  }
  /* make sure that we are bracketing the maximum correlation between ashift
     and cshift */
  if ((fxshift<=fashift) || (fxshift<=fbshift)) {
    /* the maximum correlation is probably outside this interval, report
       with an error and exit */
    sprintf(output, 
	    "Error in gausscorrel: no maximum for yshift between %g and %g", 
	    ashift, bshift);
    SCTPUT(output);
    if (outtabname != NULL) TCTCLO(outtid);
    return flames_midas_fail();
  }

  /* begin searching, here follows an inlined, adapted version of the brent 
     function */

  /* give sensible values to the variables (added by Giacomo) so that we
     can try the parabolic approximation immediately */
  if (fbshift<fashift) {
    wshift = ashift;
    fwshift = fashift;
    vshift = bshift;
    fvshift = fbshift;
  }
  else {
    wshift = bshift;
    fwshift = fbshift;
    vshift = ashift;
    fvshift = fashift;
  }
  dshift = xshift-wshift;
  eshift = dshift/CGOLD;

  done = FALSE;

  for (iter=1; (iter<=maxcorriters) && (done==FALSE); iter++) {

    xmshift = 0.5*(ashift+bshift);
    /* differently from the NR implementation, we here use absolute 
       tolerances, since we know that the solution, if any, must be 
       in an interval of order unity, centered around zero, and we
       need an accuracy better than 0.1 pixels, but probably not 
       better than 0.01 pixels. This means that rounding errors are
       not a problem, regardless that we compute the correlation values
       in single or double precision */
    tol2 = 2*shifttol;

    if (fabs(xshift-xmshift)+0.5*(bshift-ashift) <= tol2) {
      /* did we get close enough to the maximum? */
      *ydelta = xshift;
      maxcorrel = fxshift;
      done = TRUE;
    }
    else {
      if (fabs(eshift) > shifttol) {
	/* compute a trial parabolic shift */
	s = xshift-wshift;
	t = xshift-vshift;
	r = s*(fxshift-fvshift);
	q = t*(fxshift-fwshift);
	p = t*q-s*r;
	q = 2*(q-r);
	if (q > 0) p = -p;
	q = fabs(q);
	etemp = eshift;
	eshift = dshift;
	/* if the parabolic shift is not acceptable, switch to a golden section
	   shift */
	if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(ashift-xshift) ||
	    p >= q*(bshift-xshift))
	  dshift = 
	    CGOLD*(eshift = (xshift >= xmshift ? ashift-xshift : 
			     bshift-xshift));
	else {
	  dshift = p/q;
	  ushift = xshift+dshift;
	  if (ushift-ashift < tol2 || bshift-ushift < tol2)
	    dshift = xmshift>=xshift ? shifttol : -shifttol;
	}
      }
      else {
	/* compute the golden section shift */
	dshift = 
	  CGOLD*(eshift = (xshift >= xmshift ? ashift-xshift : bshift-xshift));
      }
      ushift = (fabs(dshift) >= shifttol ? xshift+dshift : 
		xshift+(dshift >= 0 ? shifttol : -shifttol));
      /* here we evaluate the correlation at the new shift value */
      fushift = singlecorrel(ScienceFrame, Order, fibrelist, nlitfibres, 
			     ordercentres, ilowlimits, iuplimits, 
			     correlxstep, ushift);

      if ( strcmp(drs_verbosity,"LOW") == 0 ){
      } else {
	sprintf(output, "iteration %d, correl(%g)=%g", iter, ushift, fushift);
	SCTPUT(output);
      }

      if (outtabname != NULL) {
	row++;
	TCEWRD(outtid, row, yshiftcol, &ushift);
	TCEWRD(outtid, row, correlcol, &fushift);
      }

      /* decide what to do with the new point: is it closer than xshift to the
	 maximum? */
      if (fushift >= fxshift) {
	/* yes, ushift is at least as good as xshift */
	/* on which side of xshift is ushift? */
	if (ushift >= xshift) ashift=xshift; else bshift=xshift;
	vshift=wshift;
	wshift=xshift;
	xshift=ushift;
	fvshift=fwshift;
	fwshift=fxshift;
	fxshift=fushift;
      }
      else {
	if (ushift < xshift) ashift=ushift; else bshift=ushift;
	if (fushift >= fwshift || wshift == xshift) {
	  vshift=wshift;
	  wshift=ushift;
	  fvshift=fwshift;
	  fwshift=fushift;
	}
	else if (fushift >= fvshift || vshift == xshift || vshift == wshift) {
	  vshift=ushift;
	  fvshift=fushift;
	}
      }
    }
  }


  /* did we get a solution or did we run out of iterations? */
  if (done == FALSE) {
    sprintf(output, 
	    "Error: gausscorrel did not converge within %d iterations", 
	    maxcorriters);
    SCTPUT(output);
    return flames_midas_fail();
  }

  /* since we did find a solution, brag about it */
  sprintf(output, "y shift = %g", *ydelta);
  SCTPUT(output);

  sprintf(qc_y_shift_key,"%11s", "DRS_Y_SHIFT");
  SCDWRD(outtid,qc_y_shift_key,ydelta,1,1,&mid_unit);

  /* close the output table */
  if (outtabname != NULL) TCTCLO(outtid);


  /* we can free local arrays now */
  free_dvector(aa, 1, ndeg);
  free_ivector(ia, 1, ndeg);
  free_dmatrix(covar, 1, ndeg, 1, ndeg);

  free_dvector(yfit, 1, sz_fit);
  free_dvector(xfit, 1, sz_fit);

  free_dvector(sfit, 1, sz_fit);

  free_lvector(fibrelist, 0, ScienceFrame->maxfibres-1);

  free_dmatrix(ordercentres, 0, Order->lastorder-Order->firstorder, 
	       0, ScienceFrame->subcols-1);
  free_lmatrix(ilowlimits, 0, Order->lastorder-Order->firstorder, 
	       0, ScienceFrame->subcols-1);
  free_lmatrix(iuplimits, 0, Order->lastorder-Order->firstorder, 
	       0, ScienceFrame->subcols-1);

  return NOERR;

}

/**@}*/


