/*===========================================================================
  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_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>
#include <flames_lsfit.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 
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 
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_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 **ordercentres=0;

    int32_t **ilowlimits=0;

    int32_t **iuplimits=0;

    int32_t ix=0;

    double x=0;
    double pordercentre=0;


    double ashift=0;
    double bshift=0;
    double ushift=0;
    double vshift=0;
    double wshift=0;
    double xshift=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;

    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;



    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++) {
        double dorder = (double)(iorder+Order->firstorder);
        /* find the y positions of the order centres once and for all */
        double* ordercentresiorder = ordercentres[iorder];
        int32_t* ilowlimitsiorder = ilowlimits[iorder];
        int32_t* 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);

        double 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 (int 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;
        cpl_vector* vx=cpl_vector_wrap(sz_fit,&xfit[0]);
        cpl_vector* vy=cpl_vector_wrap(sz_fit,&yfit[0]);
        cpl_vector* vs=cpl_vector_wrap(sz_fit,&sfit[0]);
        flames_lfit(vx,vy,vs,sz_fit,aa,ia,ndeg,covar,&chisq,fpoly);
        //lsqfit_nr(xfit,yfit,sfit,sz_fit,aa,ndeg,fpoly);

        cpl_vector_unwrap(vx);
        cpl_vector_unwrap(vy);
        cpl_vector_unwrap(vs);

        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); */
        double fit_par[4];
        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++) {

        double 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 */
        double tol2 = 2*shifttol;

        if (fabs(xshift-xmshift)+0.5*(bshift-ashift) <= tol2) {
            /* did we get close enough to the maximum? */
            *ydelta = xshift;
            double 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;

}

/**@}*/


