/*===========================================================================
  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  : mainoptquickFF.c                                             */
/* Author   : G. Mulas  -  ITAL_FLAMES Consortium                          */
/* Date     :                                                              */
/*                                                                         */
/* Purpose  : to do quick and dirty optimal extraction on all fibres FF    */
/*                                                                         */
/*                                                                         */
/* 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                            */
/*-------------------------------------------------------------------------*/
/* C functions include files */ 

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

#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uves_msg.h>
/* MIDAS include files */
#include <flames_midas_def.h>
#include <flames_computeback.h>
/* FLAMES-UVES include files */ 
#include <flames_writenormfactors.h>
#include <flames_optsynth.h>
#include <flames_writesynth.h>
#include <flames_optimal.h>
#include <flames_quickoptimal.h>
#include <flames_readback.h>
#include <flames_readallff.h>
#include <flames_prepextract.h>
#include <flames_quickprepextract.h>
#include <flames_doquickoptimal.h>
#include <flames_readframe.h>
#include <flames_scatter.h>

#include <flames_freeordpos.h>
#include <flames_writeback.h>
#include <flames_striptblext.h>
#include <flames_freeallflats.h>
#include <flames_freeframe.h>
#include <flames_mainoptquickFF.h>
#include <flames_freespectrum.h>
#include <flames_newmatrix.h>
#include <flames_readordpos.h>


int flames_mainoptquickFF(const char *IN_A,
                          const cpl_frameset *IN_B,
                          const char *IN_D,
                          const char *IN_E,
                          const char *IN_F,
                          const double *DECENTSNR,                         
                          const double *MAXDISCARDFRACT,
                          const int *MAXBACKITERS,
                          const int *MINOPTITERSINT,
                          const int *MAXOPTITERSINT,
                          const int *XKILLSIZE,
                          const int *YKILLSIZE,
                          const int *BKGPOL,
                          const char *BKGFITINLINE,
                          const char *BKGFITMETHOD,
                          const char *BKGBADSCAN,
                          const int *BKGBADWIN,
                          const double *BKGBADMAXFRAC,
                          const int *BKGBADMAXTOT,
                          const double *SIGMA,
                          double *OUTPUTD,
                          int *OUTPUTI)
{
    char output[200];
    int i=0;
    int unit=0;
    int actvals=0;
    frame_mask **mask=0;
    int bxdegree=0, bydegree=0;
    int maxbackiters=0;
    double maxdiscardfract=0;
    double kappa=0;
    double kappa2=0;
    int chisqpixels=0, nfittedparams=0;
    double chisquare=0;
    frame_data **backframe;
    flames_err status=0;

    flames_frame *AllFrame=0;

    allflats *Shifted_FF=0;

    orderpos *Order=0;

    //char allfile[CATREC_LEN+2];
    const cpl_frameset *allfile;
    char backfile[CATREC_LEN+2];
    char infile[CATREC_LEN+2];
    char dummyfile[CATREC_LEN+2];
    char inorderfile[CATREC_LEN+2];
    char outorderfile[CATREC_LEN+2];
    int nval=0;
    int null=0;
    int ibuf=0;
    int32_t minoptitersint=0;
    int32_t maxoptitersint=0;
    int32_t xkillsize=0;
    int32_t ykillsize=0;
    int32_t ifibre=0, iorder=0, ix=0;
    scatterswitch bkgswitch=USEALL;
    scatterswitch2 bkgswitch2=NOBADSCAN;
    int badwinxsize=0;
    int badwinysize=0;
    double badfracthres=0;
    int badtotthres=0;
    char keytype=0;
    int noelem=0;
    int bytelem=0;
    char bkgfitmethod[CATREC_LEN+1];
    double decentSNR=0;
    frame_data decentSNR2=0;
    int32_t negativepixels=0;
    char bkginline=TRUE;

    frame_data *fdvecbuf1=0;
    frame_data *fdvecbuf2=0;
    frame_data *fdvecbuf3=0;
    frame_data *fdvecbuf4=0;
    frame_mask *fmvecbuf1=0;
    frame_mask *fmvecbuf2=0;
    frame_data pixelvalue=0;
    int32_t lastiyixindex=0;
    int32_t iorderifibreindex=0;
    int32_t iorderifibreixoffset=0;
    int32_t iorderifibreixindex=0;
    int32_t ixiorderifibreindex=0;

    memset(output, 0, 200);
    memset(bkgfitmethod, 0, CATREC_LEN+1);


    bkgswitch = USEALL;

    SCSPRO("optnormquick"); /* Get into MIDAS Env. */

    /* Read once and for all, here at the beginning, what MIDAS keywords we
     need */

    /* get input frame name from MIDAS env.*/
    SCKGETC(IN_A,1,CATREC_LEN+1,&nval,infile);

    /* get the fibre FF catalog name from MIDAS env.*/
    SCKGETC_fs(IN_B,1,CATREC_LEN+1,&nval,&allfile);

    /* read background inter-order table name */
    SCKGETC(IN_D,1,160,&nval,backfile);

    /* read input order table name */
    SCKGETC(IN_E,1,160,&nval,dummyfile);
    if (striptblext(dummyfile, inorderfile) != NOERR) {
        SCTPUT("Error stripping extension from input order table file name");
        return flames_midas_fail();
    }


    /* read output order table name */
    SCKGETC(IN_F,1,160,&nval,dummyfile);
    if (striptblext(dummyfile, outorderfile) != NOERR) {
        SCTPUT("Error stripping extension from output order table file name");
        return flames_midas_fail();
    }

    /* the input and output table names must be different */
    if (strncmp(inorderfile, outorderfile, CATREC_LEN+2) == 0) {
        SCTPUT("Error: the input and output order table files are equal");
        return flames_midas_fail();
    }

    /* initialise DECENTSNR from keyword */
    if (SCKRDD(DECENTSNR, 1, 1, &actvals, &decentSNR, &unit, &null) != 0) {
        /* problems reading DECENTSNR */
        SCTPUT("Error reading the minimum acceptable SNR");
        return flames_midas_fail();
    }
    /* since it happens to have almost null fibre values on unmasked bad
     columns, try to avoid them */
    decentSNR2 = (frame_data) decentSNR*decentSNR;


    /* initialise MAXDISCARDFRACT from keyword */
    if (SCKRDD(MAXDISCARDFRACT, 1, 1, &actvals, &maxdiscardfract, &unit,
                    &null) != 0) {
        /* problems reading MAXDISCARDFRACT */
        SCTPUT("Error reading the MAXDISCARDFRACT keyword");
        return flames_midas_fail();
    }
    /* initialise MAXBACKITERS from keyword */
    if (SCKRDI(MAXBACKITERS, 1, 1, &actvals, &maxbackiters, &unit,
                    &null) != 0) {
        /* problems reading MAXBACKITERS */
        SCTPUT("Error reading the MAXBACKITERS keyword");
        return flames_midas_fail();
    }


    /* read the MINOPTITERSINT keyword */
    if (SCKRDI(MINOPTITERSINT, 1, 1, &actvals, &ibuf, &unit, &null) != 0) {
        /* problems reading MINOPTITERSINT */
        SCTPUT("Error reading the MINOPTITERSINT keyword");
        return flames_midas_fail();
    }
    if (ibuf<1) {
        SCTPUT("Warning: illegal (<1) value for MINOPTITERSINT, falling back \
to 1");
        ibuf=1;
    }
    minoptitersint = (int32_t) ibuf;
    /* read the MAXOPTITERSINT keyword */
    if (SCKRDI(MAXOPTITERSINT, 1, 1, &actvals, &ibuf, &unit, &null) != 0) {
        /* problems reading MAXOPTITERSINT */
        SCTPUT("Error reading the MAXOPTITERSINT keyword");
        return flames_midas_fail();
    }
    maxoptitersint = (int32_t) ibuf;
    if (maxoptitersint<minoptitersint) {
        SCTPUT("Warning: illegal value (too low) for MAXOPTITERSINT, \
falling back to MINOPTITERSINT");
        maxoptitersint=minoptitersint;
    }

    /* read the XKILLSIZE keyword */
    if (SCKRDI(XKILLSIZE, 1, 1, &actvals, &ibuf, &unit, &null) != 0) {
        /* problems reading XKILLSIZE */
        SCTPUT("Error reading the XKILLSIZE keyword");
        return flames_midas_fail();
    }
    if (ibuf<0) {
        SCTPUT("Warning: illegal (negative) value for XKILLSIZE, falling \
back to 0");
        ibuf=0;
    }
    xkillsize = (int32_t) ibuf;
    /* read the YKILLSIZE keyword */
    if (SCKRDI(YKILLSIZE, 1, 1, &actvals, &ibuf, &unit, &null) != 0) {
        /* problems reading YKILLSIZE */
        SCTPUT("Error reading the YKILLSIZE keyword");
        return flames_midas_fail();
    }


    if (ibuf<0) {
        SCTPUT("Warning: illegal (negative) value for YKILLSIZE, falling \
back to 0");
        ibuf=0;
    }
    ykillsize = (int32_t) ibuf;

    /* initialise background fitting scalars */
    if (SCKRDI(BKGPOL, 1, 1, &actvals, &bxdegree, &unit, &null)
                    != 0) {
        /* problems reading xdegree */
        SCTPUT("Error reading the x degree of the background polynomial");
        return flames_midas_fail();
    }
    if (SCKRDI(BKGPOL, 2, 1, &actvals, &bydegree, &unit, &null)
                    != 0) {
        /* problems reading xdegree */
        SCTPUT("Error reading the y degree of the background polynomial");
        return flames_midas_fail();
    }



    /* Is inline background fitting and subtraction required? */
    if (SCKFND_string(BKGFITINLINE, &keytype, &noelem, &bytelem) != 0) {
        /* SCKFND failed, major problems */
        SCTPUT("Internal MIDAS error in mainopt: SCKFND failed");
        return flames_midas_fail();
    }
    switch(keytype) {
    case 'C':
        /* it exists and it is a character keyword, do read it */
        if (SCKGETC(BKGFITINLINE, 1, CATREC_LEN, &nval, bkgfitmethod)
                        != 0) {
            /* problems reading BKGFITINLINE */
            SCTPUT("Warning: error reading the BKGFITINLINE keyword, falling back \
to default");
        }
        else {
            /* is the string long enough to be unambiguous? */
            if (nval<1) {
                SCTPUT("Warning: BKGFITINLINE is ambiguous, falling back to default");
            }
            else {
                /* convert bkgfitmethod to upper case, to ease the subsequent check */
                for (i=0; i<=(nval-1); i++) bkgfitmethod[i] = toupper(bkgfitmethod[i]);
                /* compare as many letters as we have with the expected values */
                if (strncmp("YES", bkgfitmethod, (size_t) nval) == 0)
                    bkginline = TRUE;
                else if (strncmp("NO", bkgfitmethod, (size_t) nval)
                                == 0) bkginline = FALSE;
                else {
                    SCTPUT("Warning: unsupported BKGFITINLINE value, falling back to \
default");
                }
            }
        }
        break;
    case ' ':
        /* the keyword does not exist at all */
        SCTPUT("Warning: BKGFITINLINE is undefined, falling back to default");
        break;
    default:
        /* the keyword is of the wrong type */
        SCTPUT("Warning: BKGFITINLINE is not a string, falling back to default");
        break;
    }

    /* before trying to read it, make sure that BKGFITMETHOD exists and it is
     of the appropriate type */
    if (SCKFND_string(BKGFITMETHOD, &keytype, &noelem, &bytelem) != 0) {
        /* SCKFND failed, give up! */
        SCTPUT("Internal MIDAS error in mainopt: SCKFND failed");
        return flames_midas_fail();
    }
    uves_msg("qoptFFok7");

    switch(keytype) {
    case 'C':
        /* it exists and it is a character keyword, go ahead and read it */
        if (SCKGETC(BKGFITMETHOD, 1, CATREC_LEN, &nval, bkgfitmethod)
                        != 0) {
            /* problems reading BKGFITMETHOD */
            SCTPUT("Warning: error reading the BKGFITMETHOD keyword, falling back \
to default");
        }
        else {
            /* is the string long enough to be unambiguous? */
            if (nval<2) {
                /* no, fall back to the default */
                SCTPUT("Warning: BKGFITMETHOD is ambiguous, falling back to default");
            }
            else {
                /* convert bkgfitmethod to upper case, to ease the subsequent check */
                for (i=0; i<=(nval-1); i++) bkgfitmethod[i] = toupper(bkgfitmethod[i]);
                /* compare as many letters as we have with the expected values */
                if (strncmp("ALL", bkgfitmethod, (size_t) nval) == 0)
                    bkgswitch = USEALL;
                else if (strncmp("MEDIAN", bkgfitmethod, (size_t) nval)
                                == 0) bkgswitch = USEMEDIAN;
                else if (strncmp("MINIMUM", bkgfitmethod, (size_t) nval)
                                == 0) bkgswitch = USEMINIMUM;
                else if (strncmp("AVERAGE", bkgfitmethod, (size_t) nval)
                                == 0) bkgswitch = USEAVERAGE;
                else {
                    SCTPUT("Warning: unsupported BKGFITMETHOD value, falling back to \
default");
                }
            }
        }
        break;
    case ' ':
        /* the keyword does not exist at all */
        SCTPUT("Warning: BKGFITMETHOD is undefined, falling back to default");
        break;
    default:
        /* the keyword is of the wrong type */
        SCTPUT("Warning: BKGFITMETHOD is not a string, falling back to default");
        break;
    }


    /* before trying to read it, make sure that BKGFITMETHOD exists and it is
     of the appropriate type */
    if (SCKFND_string(BKGBADSCAN, &keytype, &noelem, &bytelem) != 0) {
        /* SCKFND failed, give up! */
        SCTPUT("Internal MIDAS error in mainopt: SCKFND failed");
        return flames_midas_fail();
    }
    switch(keytype) {
    case 'C':
        /* it exists and it is a character keyword, go ahead and read it */
        if (SCKGETC(BKGBADSCAN, 1, CATREC_LEN, &nval, bkgfitmethod)
                        != 0) {
            /* problems reading BKGFITMETHOD */
            SCTPUT("Warning: error reading the BKGBADSCAN keyword, falling back to \
default");
        }
        else {
            /* is the string long enough to be unambiguous? */
            if (nval<1) {
                /* no, fall back to the default */
                SCTPUT("Warning: BKGBADSCAN is ambiguous, falling back to default");
            }
            else {
                /* convert bkgfitmethod to upper case, to ease the subsequent check */
                for (i=0; i<=(nval-1); i++) bkgfitmethod[i] = toupper(bkgfitmethod[i]);
                /* compare as many letters as we have with the expected values */
                if (strncmp("NONE", bkgfitmethod, (size_t) nval) == 0)
                    bkgswitch2 = NOBADSCAN;
                else if (strncmp("FRACTION", bkgfitmethod, (size_t) nval)
                                == 0) bkgswitch2 = FRACBADSCAN;
                else if (strncmp("ABSOLUTE", bkgfitmethod, (size_t) nval)
                                == 0) bkgswitch2 = ABSBADSCAN;
                else {
                    SCTPUT("Warning: unsupported BKGBADSCAN value, falling back to \
default");
                }
            }
        }
        break;
    case ' ':
        /* the keyword does not exist at all */
        SCTPUT("Warning: BKGBADSCAN is undefined, falling back to default");
        break;
    default:
        /* the keyword is of the wrong type */
        SCTPUT("Warning: BKGBADSCAN is not a string, falling back to default");
        break;
    }


    /* if neighborhood bad pixel scanning was requested, read the other
     keywords needed */
    if (bkgswitch2 == FRACBADSCAN) {
        if ((SCKRDI(BKGBADWIN, 1, 1, &actvals, &badwinxsize, &unit, &null) != 0)
                        || (SCKRDI(BKGBADWIN, 2, 1, &actvals, &badwinysize, &unit, &null)
                                        != 0)) {
            SCTPUT("Error reading the BKGBADWIN keyword");
            return flames_midas_fail();
        }
        if (SCKRDD(BKGBADMAXFRAC, 1, 1, &actvals, &badfracthres, &unit,
                        &null) != 0) {
            SCTPUT("Error reading the BKGBADMAXFRAC keyword");
            return flames_midas_fail();
        }
        /* check the values read for consistence */
        if ((badwinxsize < 0) || (badwinysize < 0)) {
            SCTPUT("Warning: BKGBADWIN values must be non negative, disabling \
BKGBADSCAN");
            bkgswitch2 = NOBADSCAN;
        }
        if (badfracthres < 0) {
            SCTPUT("Warning: BKGBADMAXFRAC value must be non negative, disabling \
BKGBADSCAN");
            bkgswitch2 = NOBADSCAN;
        }
    }
    else if (bkgswitch2 == ABSBADSCAN) {
        if ((SCKRDI(BKGBADWIN, 1, 1, &actvals, &badwinxsize, &unit, &null) != 0)
                        || (SCKRDI(BKGBADWIN, 2, 1, &actvals, &badwinysize, &unit, &null)
                                        != 0)) {
            SCTPUT("Error reading the BKGBADWIN keyword");
            return flames_midas_fail();
        }
        if (SCKRDI(BKGBADMAXTOT, 1, 1, &actvals, &badtotthres, &unit,
                        &null) != 0) {
            SCTPUT("Error reading the BKGBADMAXTOT keyword");
            return flames_midas_fail();
        }
        /* check the values read for consistence */
        if ((badwinxsize < 0) || (badwinysize < 0)) {
            SCTPUT("Warning: BKGBADWIN values must be non negative, disabling \
BKGBADSCAN");
            bkgswitch2 = NOBADSCAN;
        }
        if (badtotthres < 0) {
            SCTPUT("Warning: BKGBADMAXTOT value must be non negative, disabling \
BKGBADSCAN");
            bkgswitch2 = NOBADSCAN;
        }
    }


    /* read the kappa factor to be used later in kappa-sigma clipping */
    if ((status=SCKRDD(SIGMA, 1, 1, &actvals, &kappa, &unit, &null))!=0) {
        /* something went wrong while reading the kappa-sigma factor */
        sprintf(output, "Error %d while reading SIGMA keyword", status);
        SCTPUT(output);
        return flames_midas_fail();
    }
    /* compute once and for all the square of kappa, as we will be using that */
    kappa2 = kappa*kappa;


    /* Link the MIDAS names of the frames to the physical ones */

    if(!(AllFrame = calloc(1, sizeof(flames_frame)))) {
        SCTPUT("Allocation error during AllFrame memory allocation");
        return flames_midas_fail();
    }

    /* let's read the Science Frame */
    sprintf(output, "I'm reading the frame %s", infile);
    SCTPUT(output);

    if (readframe(AllFrame, infile) != NOERR) {
        SCTPUT("Error while reading the frame");
        return flames_midas_fail();
    }

    /* Read the table data and then put them in the C structures */
    sprintf(output,"Reading the order/fibre table...");
    SCTPUT(output);
    if(!(Order = calloc(1, sizeof(orderpos)))) {
        SCTPUT("Allocation error during the allocation of Order structure");
        return flames_midas_fail();
    }
    /* use the readordpos function to read the descriptors */
    if (readordpos(inorderfile, Order) != NOERR) {
        SCTPUT("Error while reading the order table");
        return flames_midas_fail();
    }
    /* does the order table match the Science frame chip? */
    if(Order->chipchoice != AllFrame->chipchoice) {
        /* no, it doesn't */
        SCTPUT("Error: chip mismatch between Science frame and order table");
        return flames_midas_fail();
    }

    /* initialise firstorder and lastorder in AllFrame from Order */
    AllFrame->firstorder = Order->firstorder;
    AllFrame->lastorder = Order->lastorder;
    AllFrame->tab_io_oshift = Order->tab_io_oshift;


    /* allocate and initialise the frame which will contain the
     estimated background. This will remain zero if no background fitting 
     was required*/
    lastiyixindex = (AllFrame->subrows*AllFrame->subcols)-1;
    backframe = fdmatrix(0, AllFrame->subrows-1, 0,
                    AllFrame->subcols-1);
    memset(&backframe[0][0], 0,
           AllFrame->subrows*AllFrame->subcols*sizeof(frame_data));

    if (bkginline==TRUE) {
        /* Inline background fitting and subtraction required */

        /* Read the data of the frames and put them in the right C structures */

        SCTPUT("*** Step 1: Background fitting and subtraction ***\n");

        sprintf(output, "I'm reading the background table %s", backfile);
        SCTPUT(output);

        /* read in the background table */
        if ((status=readback(&(AllFrame->back), backfile, bxdegree, bydegree))
                        != NOERR) {
            /* something went wrong while reading the background table */
            sprintf(output, "Error %d while reading the background table", status);
            SCTPUT(output);
            return flames_midas_fail();
        }


        /* Calculate the fit model of the background */

        SCTPUT("Start the background fitting procedure");

        if (AllFrame->back.Window_Number > 0) {
            if (scatter(AllFrame, Order, bkgswitch, bkgswitch2, badwinxsize,
                            badwinysize, badfracthres, badtotthres, kappa2,
                            (int32_t) maxbackiters, maxdiscardfract, OUTPUTI)) {
                SCTPUT("Error executing the scatter function");
                return flames_midas_fail();
            }
            /* compute the estimated background */
            if (computeback(AllFrame, backframe) != NOERR) {
                SCTPUT("Error computing fitted background");
                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 all fibres FF Frame");
            fdvecbuf1 = AllFrame->frame_array[0];
            fdvecbuf2 = backframe[0];
            for (ix=0; ix<=lastiyixindex; ix++) {
                fdvecbuf1[ix] -= fdvecbuf2[ix];
            }
            /* 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 not compatible with 
	 zero, mark that pixel as bad */
            negativepixels=0;
            fdvecbuf1 = AllFrame->frame_array[0];
            fdvecbuf2 = AllFrame->frame_sigma[0];
            fmvecbuf1 = AllFrame->badpixel[0];
            for (ix=0; ix<=lastiyixindex; ix++) {
                if (fmvecbuf1[ix]==0 && (pixelvalue=fdvecbuf1[ix])<0) {
                    if ((pixelvalue*pixelvalue)>4*fdvecbuf2[ix]) {
                        fmvecbuf1[ix]=1;
                        negativepixels++;
                    }
                }
            }
            if (negativepixels!=0) {
                sprintf(output, "Warning: %d pixels result lower than fitted \
background", negativepixels);
                SCTPUT(output);
                SCTPUT("either they are unmasked bad pixels or some contamination is");
                SCTPUT("skewing background determination");
            }
            SCTPUT("Writing fitted background frame to middumma.bdf");
            if (writeback(AllFrame, "middumma.bdf", backframe)!=NOERR)
                SCTPUT("Warning: error writing background frame to disk");
        }
        else {
            SCTPUT("Error: no regions available for background estimation");
            return flames_midas_fail();
        }

    }


    /* Allocate memory for the Shifted_FF structure */
    if(!(Shifted_FF = calloc(1, sizeof(allflats)))) {
        SCTPUT("Allocation error during Shifted_FF structure memory allocation");
        return flames_midas_fail();
    }

    /* let's read the fibre FFs */
    sprintf(output, "I'm reading the fibre FF frames");
    SCTPUT(output);
    if (readallff(allfile, Shifted_FF) != NOERR) {
        SCTPUT("Error while reading the fibre Flat Field frames");
        return flames_midas_fail();
    }
    uves_msg("qoptFFok1");

    /* is this fibre FF frames set shiftable? */
    if (Shifted_FF->shiftable == 'y') {
        sprintf(output, "The fibre FF set is slit-flatfielded");
        SCTPUT(output);
        return flames_midas_fail();
    }
    uves_msg("qoptFFok2");


    SCTPUT("\n*** Step 3: prepare merged bad pixel mask and final \
initialisations ***\n");
    /* allocate the global, merged bad pixel mask */
    mask=fmmatrix(0,AllFrame->subrows-1,0,AllFrame->subcols-1);
    if(!mask) {
        SCTPUT("Error in allocating mask matrix");
        return flames_midas_fail();
    }
    uves_msg("qoptFFok3");

    /* initialise the global, merged bad pixel mask to be used
     in the subsequent optimal extraction, initialise the lookup tables for 
     lit fibres in the AllFrame and allocate the arrays to store the 
     allocated spectra again in AllFrame */
    if (quickprepextract(AllFrame, Shifted_FF, Order, mask)!=NOERR) {
        /* something went wrong in prepextract */
        SCTPUT("Error in quickprepextract");
        return flames_midas_fail();
    }
    uves_msg("qoptFFok4");

    /* Going to do the real spectrum extraction */
    SCTPUT("\n*** Step 4: optimal extraction proper ***\n");
    if (doquickoptimal(AllFrame, Order, Shifted_FF, kappa2, mask, backframe,
                    minoptitersint, maxoptitersint, xkillsize, ykillsize)
                    !=NOERR) {
        SCTPUT("Error in doquickoptimal");
        return flames_midas_fail();
    }
    uves_msg("qoptFFok5");

    /* free the old bad pixel mask, replace it with the global mask */
    free_fmmatrix(AllFrame->badpixel, 0, AllFrame->subrows-1, 0,
                  AllFrame->subcols-1);
    AllFrame->badpixel = mask;

    /* build the fitted all fibres FF Frame, do it in place to save memory */
    if (optsynth(AllFrame, Shifted_FF, Order, &backframe, &chisquare,
                    &chisqpixels, &nfittedparams)!=NOERR) {
        SCTPUT("Error computing the fitted frame");
        return flames_midas_fail();
    }
    uves_msg("qoptFFok6");

    SCKWRD(OUTPUTD, &chisquare, 1, 1, &unit);
    SCKWRI(OUTPUTI, &chisqpixels, 1, 1, &unit);
    SCKWRI(OUTPUTI, &nfittedparams, 2, 1, &unit);
    SCTPUT("Writing the synthesized data frame to middummb.bdf");
    SCTPUT("Writing the synthesized sigma frame to middummc.bdf");
    SCTPUT("Writing the overall mask to middummd.bdf");
    if (writesynth(AllFrame, "middummb.bdf", "middummc.bdf", "middummd.bdf")
                    != NOERR)
        SCTPUT("Warning: error writing dummy debugging frames");


    SCTPUT("\n*** Step 5: write normalisation factors to disk, clean up and \
exit ***\n");
    uves_msg("qoptFFok7");

    /* let's free a bit of memory */

    /* free the estimated background frame, we don't need it any more */
    free_fdmatrix(backframe, 0, AllFrame->subrows-1, 0,
                  AllFrame->subcols-1);

    fdvecbuf1 = Shifted_FF->normfactors[0][0];
    fdvecbuf2 = Shifted_FF->normsigmas[0][0];
    fmvecbuf1 = Shifted_FF->goodfibres[0][0];
    fdvecbuf3 = AllFrame->spectrum[0][0];
    fdvecbuf4 = AllFrame->specsigma[0][0];
    fmvecbuf2 = AllFrame->specmask[0][0];
    for (ifibre=0; ifibre<=(Shifted_FF->maxfibres-1); ifibre++) {
        if ((Shifted_FF->fibremask[ifibre]==TRUE) &&
                        (AllFrame->fibremask[ifibre]==TRUE)) {
            for (iorder=0; iorder<=(Order->lastorder-Order->firstorder); iorder++) {
                iorderifibreindex = (iorder*AllFrame->maxfibres)+ifibre;
                iorderifibreixoffset = iorderifibreindex*AllFrame->subcols;
                for (ix=0; ix<=(Shifted_FF->subcols-1); ix++) {
                    iorderifibreixindex = iorderifibreixoffset+ix;
                    ixiorderifibreindex = (ix*(1+Order->lastorder-Order->firstorder)*
                                    AllFrame->maxfibres)+iorderifibreindex;
                    /* was this a decent fibre at this x, before? */
                    if (fmvecbuf1[iorderifibreixindex] != BADSLICE) {
                        pixelvalue = fdvecbuf3[ixiorderifibreindex];
                        /* was I able to extract this with a decent SNR? */
                        if ((fmvecbuf2[ixiorderifibreindex]==1) &&
                                        ((pixelvalue*pixelvalue/fdvecbuf4[ixiorderifibreindex])
                                                        >=decentSNR2)){
                            fmvecbuf1[iorderifibreixindex] = GOODSLICE;
                            fdvecbuf1[iorderifibreixindex] = fdvecbuf3[ixiorderifibreindex];
                            fdvecbuf2[iorderifibreixindex] = fdvecbuf4[ixiorderifibreindex];
                        }
                        else {
                            fmvecbuf1[iorderifibreixindex] = DEMISLICE;
                        }
                    }
                }
            }
        }
        else {
            /* This fibre could not be possibly extracted, mark it DEMISLICE
	 at best */
            for (iorder=0; iorder<=(Order->lastorder-Order->firstorder); iorder++) {
                iorderifibreindex = (iorder*AllFrame->maxfibres)+ifibre;
                iorderifibreixoffset = iorderifibreindex*AllFrame->subcols;
                for (ix=0; ix<=(Shifted_FF->subcols-1); ix++) {
                    iorderifibreixindex = iorderifibreixoffset+ix;
                    /* was this a decent fibre at this x, before? */
                    if (fmvecbuf1[iorderifibreixindex] != BADSLICE)
                        fmvecbuf1[iorderifibreixindex] = DEMISLICE;
                }
            }
        }
    }
    uves_msg("qoptFFok8");

    /* now do write the normalisation factors */
    if (writenormfactors(allfile, Shifted_FF) != NOERR) {
        SCTPUT("Error in writenormfactors");
        return flames_midas_fail();
    }

    /* finally free for good the AllFrame (including the spectrum), Shifted_FF
     and Order */
    if (free_spectrum(AllFrame)!=NOERR) {
        SCTPUT("Error while freeing the spectrum in the AllFrame structure");
        return flames_midas_fail();
    }
    if (freeframe(AllFrame)!=NOERR) {
        SCTPUT("Error while freeing the memory of the AllFrame structure");
        return flames_midas_fail();
    }
    free(AllFrame);
    if (freeallflats(Shifted_FF)!=NOERR) {
        SCTPUT("Error while freeing the memory of the Shifted_FF structure");
        return flames_midas_fail();
    }
    free(Shifted_FF);
    if (freeordpos(Order)!=NOERR) {
        SCTPUT("Error while freeing the memory of the Order structure");
        return flames_midas_fail();
    }
    free(Order);

    SCTPUT("\n*** Optimal extraction of the normalisation factors complete \
***\n");
    uves_msg("qoptFFok9");

    return SCSEPI();

}
