/*===========================================================================
  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  : mainopt.c                                                    */
/* Author   : G. Mulas  -  ITAL_FLAMES Consortium                          */
/* Date     :                                                              */
/*                                                                         */
/* Purpose  : Missing                                                      */
/*                                                                         */
/*                                                                         */
/* Input:  see interface                                                   */ 
/*                                                                         */
/* Output:   Background table and frame (midduma.[tbl,bdf]                 */
/*           synthesized data frame to middummb.bdf                        */
/*           synthesized sigma frame to middummc.bdf                       */
/*           overall mask to middummd.bdf                                  */
/* 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 */ 
/* 020716    KB */
#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <irplib_utils.h>
/* MIDAS include files */
#include <flames_midas_def.h>
#include <flames_freeoneflats.h>
#include <flames_computeback.h>
#include <flames_initshiftedff.h>
#include <flames_readallff.h>
#include <flames_prepextract.h>
#include <flames_readback.h>
#include <uves_msg.h>
/* FLAMES-UVES include files */ 
#include <flames_optsynth.h>
#include <flames_writesynth.h>
#include <flames_gausscorrelFF.h>
#include <flames_gausscorrel.h>
#include <flames_optimal.h>
#include <flames_scatter.h>
#include <flames_readframe.h>
#include <flames_write_spectra.h>
#include <flames_writeback.h>
#include <flames_doptimal.h>
#include <flames_quickprepextract.h>
#include <flames_freeallflats.h>
#include <flames_freeordpos.h>
#include <flames_slitdivide.h>
#include <flames_ffslitmultiply.h>
#include <flames_freeslitflats.h>
#include <flames_freeframe.h>
#include <flames_mainopt.h>
#include <flames_shift_FF_n.h>
#include <flames_copy_FF_n.h>
#include <flames_freespectrum.h>
#include <flames_newmatrix.h>
#include <flames_readordpos.h>
#include <flames_readslitflats.h>


int flames_mainopt(const char *IN_A,
                   const cpl_frameset* fibff_set,
                   const cpl_frameset* slitff_set,
                   const char *IN_D,
                   const char *IN_E,
                   const char *BASENAME,
                   const double *MAXDISCARDFRACT,
                   const int *MAXBACKITERS,
                   const int *MAXCORRITERS,
                   const int *MINOPTITERSINT,
                   const int *MAXOPTITERSINT,
                   const int *XKILLSIZE,
                   const int *YKILLSIZE,
                   const int *BKGPOL,  
                   const char *BKGFITINLINE,  // was int * , why?
                   const char *BKGFITMETHOD,
                   const char *BKGBADSCAN, // was int * , why?
                   const int *BKGBADWIN,
                   const double *BKGBADMAXFRAC,
                   const int  *BKGBADMAXTOT,
                   const double *SIGMA,
                   const double *MAXYSHIFT,
                   const double *CORRELTOL,
                   const int *CORRELXSTEP,
                   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,
                   double *OUTPUTD,
                   int *OUTPUTI)
{ 
 char output[200];
 char repeatflag=0;
 int i=0;
 int fileid=0;
 int nflats=0;
 int unit=0;
 int actvals=0;
 frame_mask **mask=0;
 int bxydegrees[2], bxdegree=0, bydegree=0;
 double shifthres=1;
 double kappa=0;
 double kappa2=0;
 int chisqpixels=0, nfittedparams=0;
 double chisquare=0;
 frame_data **backframe;
 frame_data **normcover;
 flames_err status=0;

 flames_frame *ScienceFrame=0;
 
 allslitflats *Slit_FF=0;

 allflats *Shifted_FF=0;
 allflats *Single_FF=0; 

 orderpos *Order=0;

 //int npix[2]={4096,2048};

 //char allfile[CATREC_LEN+2];
 //char slitsfile[CATREC_LEN+2];
 const cpl_frameset* allfile=fibff_set;
 const cpl_frameset* slitsfile=slitff_set;

 char backfile[CATREC_LEN+2];
 char infile[CATREC_LEN+2];
 char catfile[CATREC_LEN+2];
 char orderfile[CATREC_LEN+2];
 int32_t n=0;
 int32_t iframe=0;
 int nval=0;
 int null=0;
 int imaxcorriters=0;
 int32_t maxcorriters=0;
 double shiftwindow=0;
 double shifttol=0;
 int icorrelxstep=0;
 int32_t correlxstep=0;
 int32_t iorder=0, lfibre=0, ifibre=0, ix=0;
 int32_t maxfibres=0;
 scatterswitch bkgswitch=USEALL;
 scatterswitch2 bkgswitch2=NOBADSCAN;
 int badwinsize[2], badwinxsize=0;
 int badwinysize=0;
 double badfracthres=0;
 int badtotthres=0;
 char keytype=0;
 int noelem=0;
 int bytelem=0;
 int maxbackiters=0;
 double maxdiscardfract=0;
 int ibuf=0;
 int32_t minoptitersint=0;
 int32_t maxoptitersint=0;
 int32_t xkillsize=0;
 int32_t ykillsize=0;
 char bkgfitmethod[CATREC_LEN+1];
 frame_mask *fibremask=0;
 double *deltas;
 frame_mask *deltamask;
 int32_t orderoffset=0;
 int32_t realfirstorder=0;
 int32_t reallastorder=0;
 int32_t slitfirstorder=0;
 int32_t slitlastorder=0;
 double oldyshift=0;
 double newyshift=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_data *fdvecbuf5=0;
 frame_data *fdvecbuf6=0;
 frame_mask *fmvecbuf1=0;
 frame_mask *fmvecbuf2=0;
 frame_mask *fmvecbuf3=0;
 frame_data pixelvalue=0;
 frame_data normvalue=0;
 frame_data normvalue2=0;
 int32_t lastiyixindex=0;
 int32_t iorderifibreixstart=0;
 int32_t iorderifibreixend=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("optimal"); /* Get into MIDAS Env. + enable automatic error handling */
 
 /* by default, the application aborts, if an SC call fails,
    to make the code cleaner, 
    SCECNT has to be used, if you want to handle errors from the 
    SC routines yourself (see the Midas environment doc.)  */

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



 //AMO: conv to CPL: add a check on input strings to prevent MIDAS error
 /* get input frame name from MIDAS env.*/
 status = SCKGETC(IN_A,1,CATREC_LEN+1,&nval,infile);

 /* read input table name */
 status = SCKGETC(IN_D,1,160,&nval,backfile);

 /* read order table name */
 status = SCKGETC(IN_E,1,160,&nval,orderfile);


 /* read output base name */
 status = SCKGETC(BASENAME,1,160,&nval,catfile);

 /* initialise MAXDISCARDFRACT from keyword */
 status = SCKRDD(MAXDISCARDFRACT, 1, 1, &actvals, &maxdiscardfract, &unit, 
        &null);

 /* initialise MAXBACKITERS from keyword */
 status = SCKRDI(MAXBACKITERS, 1, 1, &actvals, &maxbackiters, &unit, 
        &null);
  
 /* initialise MAXCORRITERS from keyword */
 status = SCKRDI(MAXCORRITERS, 1, 1, &actvals, &imaxcorriters, &unit, 
        &null);
  
 /* read the MINOPTITERSINT keyword */
 status = SCKRDI(MINOPTITERSINT, 1, 1, &actvals, &ibuf, &unit, &null);
 if (ibuf<1) {
   SCTPUT("Warning: illegal (<1) value for MINOPTITERSINT, falling back to 1");
   ibuf=1;
 }


 minoptitersint = (int32_t) ibuf;
 /* read the MAXOPTITERSINT keyword */
 status = SCKRDI(MAXOPTITERSINT, 1, 1, &actvals, &ibuf, &unit, &null);
  
 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 */
 status = SCKRDI(XKILLSIZE, 1, 1, &actvals, &ibuf, &unit, &null);
 if (ibuf<0) {
   SCTPUT("Warning: illegal (negative) value for XKILLSIZE, falling \
back to 0");
   ibuf=0;
 }

 xkillsize = (int32_t) ibuf;
 /* read the YKILLSIZE keyword */
 status = SCKRDI(YKILLSIZE, 1, 1, &actvals, &ibuf, &unit, &null);
 if (ibuf<0) {
   SCTPUT("Warning: illegal (negative) value for YKILLSIZE, falling \
back to 0");
   ibuf=0;
 }
 ykillsize = (int32_t) ibuf;
 /* initialise background fitting scalars */
 status = SCKRDI(BKGPOL, 1, 2, &actvals, bxydegrees, &unit, &null);
 //status = SCKRDI(BKGPOLX, 1, 1, &actvals, &bxdegree, &unit, &null);
 //status = SCKRDI(BKGPOLY, 1, 1, &actvals, &bydegree, &unit, &null);
 bxdegree = bxydegrees[0];
 bydegree = bxydegrees[1];


 /* Is inline background fitting and subtraction required? */
 status = SCKFND_string(BKGFITINLINE, &keytype, &noelem, &bytelem);
 //strcpy(bkgfitmethod,BKGFITINLINE);
 //nval = strlen(bkgfitmethod);

 //Comment out superfluous stuff

if (keytype == ' ')
   SCTPUT("Warning: BKGFITINLINE is undefined, falling back to default");
 else
   {        /* it exists and it is a character keyword, do read it */
   status = SCKGETC(BKGFITINLINE, 1, CATREC_LEN, &nval, bkgfitmethod); 

   /* 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");
   }
 }


 /* before trying to read it, make sure that BKGFITMETHOD exists and it is
    of the appropriate type */
 status = SCKFND_string(BKGFITMETHOD, &keytype, &noelem, &bytelem);

 //strcpy(bkgfitmethod,BKGFITMETHOD);
 //Comment out superfluous stuff
 if (keytype == ' ')      /* the keyword does not exist at all */
   SCTPUT("Warning: BKGFITMETHOD is undefined, falling back to default");
 else
   {
   /* it exists and it is a character keyword, go ahead and read it */
   status = SCKGETC(BKGFITMETHOD, 1, CATREC_LEN, &nval, bkgfitmethod) ;
     /* 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");
     }
   }



   strcpy(bkgfitmethod,BKGBADSCAN);


 /* before trying to read it, make sure that BKGFITMETHOD exists and it is
    of the appropriate type */
 status = SCKFND_string(BKGBADSCAN, &keytype, &noelem, &bytelem);
 if(keytype==' ') {
   /* the keyword does not exist at all */
   SCTPUT("Warning: BKGBADSCAN is undefined, falling back to default");
 } else {
   /* it exists and it is a character keyword, go ahead and read it */
   status = SCKGETC(BKGBADSCAN, 1, CATREC_LEN, &nval, bkgfitmethod) ;
   /* 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");
   }
 }



 /* if neighborhood bad pixel scanning was requested, read the other 
    keywords needed */
 if (bkgswitch2 == FRACBADSCAN) {
   status = SCKRDI(BKGBADWIN, 1, 2, &actvals, badwinsize, &unit, &null);
   //status = SCKRDI(BKGBADWINX, 1, 1, &actvals, &badwinxsize, &unit, &null);
   //status = SCKRDI(BKGBADWINY, 1, 1, &actvals, &badwinysize, &unit, &null);
   badwinxsize = badwinsize[0];
   badwinysize = badwinsize[1];

   status = SCKRDD(BKGBADMAXFRAC, 1, 1, &actvals, &badfracthres, &unit, 
           &null);
 
   /* 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) {
   status = SCKRDI(BKGBADWIN, 1, 2, &actvals, badwinsize, &unit, &null);
   //status = SCKRDI(BKGBADWINX, 1, 1, &actvals, &badwinxsize, &unit, &null);
   //status = SCKRDI(BKGBADWINY, 1, 1, &actvals, &badwinysize, &unit, &null);
   badwinxsize = badwinsize[0];
   badwinysize = badwinsize[1];

   status = SCKRDI(BKGBADMAXTOT, 1, 1, &actvals, &badtotthres, &unit, 
           &null);
   /* 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 */
 status=SCKRDD(SIGMA, 1, 1, &actvals, &kappa, &unit, &null);
 /* 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(!(ScienceFrame = calloc(1, sizeof(flames_frame)))) {
  SCTPUT("Allocation error during ScienceFrame 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(ScienceFrame, 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(orderfile, 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 != ScienceFrame->chipchoice) {
   /* no, it doesn't */
   SCTPUT("Error: chip mismatch between Science frame and order table");
   return flames_midas_fail();
 }


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

 /* we define the pgausswidth to be proportional to halfibrewidth, 
    say a quarter of it or so, and this can be tuned by a parameter in 
    flames_uves.h */
 maxcorriters = (int32_t) imaxcorriters;

 /* read the MAXYSHIFT keyword */
 status = SCKRDD(MAXYSHIFT, 1, 1, &actvals, &shiftwindow, &unit, &null);
 if (shiftwindow<0) {
   SCTPUT("Warning: illegal value for MAXYSHIFT (P8), fall back to 0");
   shiftwindow = 0;
 }

 /* read the CORRELTOL keyword */

 status = SCKRDD(CORRELTOL, 1, 1, &actvals, &shifttol, &unit, &null);
 
 if (shifttol<0) {
   SCTPUT("Error: illegal (negative) value for CORRELTOL");
   return flames_midas_fail();
 }
 /* read the CORRELXSTEP keyword */
 status = SCKRDI(CORRELXSTEP, 1, 1, &actvals, &icorrelxstep, &unit, &null);
 if (icorrelxstep<1) {
   SCTPUT("Warning: illegal (<1) value for CORRELTOL, falling back to 1");
   icorrelxstep=1;
 }
 correlxstep = (int32_t) icorrelxstep;

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

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

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

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

   /* Get the Midas name of the frame to be read */
 
   sprintf(output, "I'm reading the background table %s", backfile);
   SCTPUT(output); /* Display text w/o storing it into MIDAS logfile */


   /* read in the background table */
   if ((status=readback(&(ScienceFrame->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 (ScienceFrame->back.Window_Number > 0) {


     if (scatter(ScienceFrame, 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(ScienceFrame, 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 Science Frame");
     fdvecbuf1 = ScienceFrame->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 = ScienceFrame->frame_array[0];
     fdvecbuf2 = ScienceFrame->frame_sigma[0];
     fmvecbuf1 = ScienceFrame->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");
     }
   }
   else {
     SCTPUT("Error: no regions available for background estimation");
     return flames_midas_fail();
   }


 }


 if (shiftwindow>0) {
   SCTPUT("\n*** Step 2: y shift determination and compensation ***\n");

   /* now allocate the Slit_FF structure, we'll be using it from now on */
   if(!(Slit_FF = calloc(1, sizeof(allslitflats)))) {
     SCTPUT("Allocation error during Slit_FF memory allocation");
     return flames_midas_fail();
   }

   /* let's read the slit FFs */


   sprintf(output, "I'm reading the slit FF frames");
   SCTPUT(output);


   if ((status = readslitflats(slitsfile, Slit_FF)) != NOERR) {
     /* problems reading slitflats members from disk */
     SCTPUT("Error while reading the slit Flat Field frames");
     return flames_midas_fail();
   }


   orderoffset = Slit_FF->tab_io_oshift-Order->tab_io_oshift;
   slitfirstorder = Slit_FF->firstorder;
   slitlastorder = Slit_FF->lastorder;
   realfirstorder = Order->firstorder;
   if (orderoffset > 0) realfirstorder += orderoffset;
   reallastorder = Slit_FF->lastorder+orderoffset;
   if (reallastorder > Order->lastorder) reallastorder = Order->lastorder;
   if (realfirstorder > reallastorder) {
     /* this should really never happen with sane data, complain and exit */
     strcpy(output, "Error: The orders in the slit FF(s) and in the order \
table being used do not overlap at all!");
     SCTPUT(output);
     return flames_midas_fail();
   }


   /* correct for the ycorrection, if present */
   if (Order->corrected=='t') {
     for (iframe=0; iframe<=(Slit_FF->nflats-1);iframe++)
       Slit_FF->slit[iframe].yshift -= Order->ycorrection;
   }


   /* divide the Science Frame by the slit FF frame(s), do it in place, 
      to save memory. Hopefully, this step will seldom need to
      be repeated, and in those few cases we reload the original frame from 
      disk */
   sprintf(output,"Dividing Science Frame by slit FF frame(s)");
   SCTPUT(output);
   /* Let's divide the Science Frame by the full slit FF, in place */

   //  for (ix=0; ix<=lastiyixindex; ix++) {
   //    uves_msg("fdvecbuf1[ix]=%f",fdvecbuf1[ix]);
   //  }

   if (slitdivide(Slit_FF, Order, ScienceFrame, ScienceFrame)!=NOERR) {
     /* something went wrong in slitdivide */
     SCTPUT("Error while dividing the Science Frame by the slit frame(s)");
     return flames_midas_fail();
   }


   /* since here we already performed the final division by the
      slit FF, we do not need any more the slit FF, so free the memory
      right here. Should we need to repeat the division, we will reload 
      things later */
   if (freeslitflats(Slit_FF)!=NOERR) {
     SCTPUT("Error while freeing the memory for the Slit_FF structure");
     return flames_midas_fail();
   }
   free(Slit_FF);

   /* Allocate memory for the Single_FF structure */
    if(!(Single_FF = calloc(1, sizeof(allflats)))) {
     SCTPUT("Allocation error during Single_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, Single_FF) != NOERR) {
     SCTPUT("Error while reading the fibre Flat Field frames");
     return flames_midas_fail();
   }
  
   /* is this fibre FF frames set shiftable? */
   if (Single_FF->shiftable != 'y') {
     sprintf(output, "The fibre FF set is not slit-flatfielded");
     SCTPUT(output);
     return flames_midas_fail();
   }

   /* make sure we do not attempt extraction for uncovered fibres */
   fmvecbuf1 = Single_FF->goodfibres[0][0];
   if (Order->firstorder<realfirstorder) {
     iorderifibreixstart = 0;
     iorderifibreixend = ((realfirstorder-Order->firstorder)*
              Single_FF->maxfibres*Single_FF->subcols)-1;
     for (ix=iorderifibreixstart; ix<=iorderifibreixend; ix++) {
       fmvecbuf1[ix] = BADSLICE;
     }
   }

   if (Order->lastorder>reallastorder) {
     iorderifibreixstart = (reallastorder-Order->firstorder+1)*
       Single_FF->maxfibres*Single_FF->subcols;
     iorderifibreixend = ((Order->lastorder-Order->firstorder)*
              Single_FF->maxfibres*Single_FF->subcols)-1;
     for (ix=iorderifibreixstart; ix<=iorderifibreixend; ix++) {
       fmvecbuf1[ix] = BADSLICE;
     }
   }

   oldyshift = 0;
   if (ScienceFrame->nflats != 0) {
     for (iframe=0; iframe<=(ScienceFrame->nflats-1); iframe++) 
       oldyshift += ScienceFrame->yshift[iframe];
     oldyshift /= (double) ScienceFrame->nflats;
     /* I need to deallocate the yshift vector and to reallocate it with
    a different size */
     free_dvector(ScienceFrame->yshift, 0, ScienceFrame->nflats-1);
   }
   /* set ScienceFrame->nflats equal to Single_FF->nflats, and allocate 
      ScienceFrame->yshift accordingly */
   ScienceFrame->nflats = Single_FF->nflats;
   ScienceFrame->yshift = dvector(0, ScienceFrame->nflats-1);
   /* for debugging purposes, initialise the yshifts to zero 
      with the simulated data the shifts ARE zero! */
   for (iframe=0; iframe <= (Single_FF->nflats-1); iframe++)
     ScienceFrame->yshift[iframe]=0;   

   /* calculation of the needed shifts by cross-correlation */ 


   SCTPUT("Doing cross-correlation calculation");

   /* I want to be able to extract the frame even if I did not have an
      all fibre FF frame available, with uncorrected throughputs */
   deltas = dvector(0, Single_FF->nflats-1);
   deltamask = fmvector(0, Single_FF->nflats-1);

   if (Order->corrected == 't') {
     if (gausscorrel(ScienceFrame, 
                     Order, 
                     maxcorriters, 
                     shiftwindow, 
             shifttol, 
                     correlxstep, 
                     "middumma.fits", 
                     deltas,
                     COR_MAX_FND,
                     COR_DEF_RNG,
                     COR_DEF_PNT,
                     COR_DEF_OFF,
                     COR_TAB_SHP_ID)) {
       SCTPUT("Error during cross-correlation calculation");
       return flames_midas_fail();
     }
     for (iframe=1; iframe<=(Single_FF->nflats-1); iframe++) 
       deltas[iframe]=deltas[0];
     for (iframe=0; iframe<=(Single_FF->nflats-1); iframe++)
       deltamask[iframe]=TRUE;
   }
   else {
     /* compute separate y shifts for the fibres in each frame of Single_FF */
     if (gausscorrelFF(ScienceFrame, 
                       Single_FF, 
                       Order, 
                       maxcorriters, 
		       shiftwindow, 
                       shifttol, 
                       correlxstep, 
                       "middumma.fits", 
		       deltas,
                       deltamask)) {
       SCTPUT("Error during cross-correlation calculation");
       return flames_midas_fail();
     }

     /* in this case, we are using the fibre positions as they were originally
    defined in the odd/even etc. FF frame, i.e. NOT corrected to their
    positions in one all FF frame; therefore, we must zero the y shifts in
    the allflats structure, otherwise we will incorrectly shift the 
    frames */
     for (iframe=0; iframe<=(Single_FF->nflats-1); iframe++) 
       Single_FF->flatdata[iframe].yshift=0;
     /* take into account the possibility to selectively extract only those
    fibres for which a y shift could be found */
     if (Single_FF->maxfibres>ScienceFrame->maxfibres) 
       maxfibres=Single_FF->maxfibres;
     else
       maxfibres=ScienceFrame->maxfibres;
     if (Order->maxfibres>maxfibres) maxfibres=Order->maxfibres;
     fibremask=fmvector(0, maxfibres-1);
     for (ifibre=0; ifibre<=(maxfibres-1); ifibre++)
       fibremask[ifibre]=FALSE;
     for (iframe=0; iframe<=(Single_FF->nflats-1); iframe++) {
       if (deltamask[iframe]==TRUE) {
     /* include only the fibres corresponding to fibre FF frames 
        with respect to which a well defined y shift was determined */
     for (lfibre=0; lfibre<=(Single_FF->flatdata[iframe].numfibres-1); 
          lfibre++) {
       ifibre=Single_FF->flatdata[iframe].fibres[lfibre];
       fibremask[ifibre]=TRUE;
     }
       }
       else {
     sprintf(output, "Warning: undetermined yshift for frame %d,", 
         iframe+1);
     SCTPUT(output);
     SCTPUT("some fibres may be unextractible");
       }
     }
     /* Now "turn off" in ScienceFrame->fibremask all the fibres for
    which no well defined y shift was determined */
     for (ifibre=0; ifibre<=(ScienceFrame->maxfibres-1); ifibre++)
       if (fibremask[ifibre]==FALSE) ScienceFrame->fibremask[ifibre]=FALSE;
     /* we don't need the temporary fibremask any more */
     free_fmvector(fibremask, 0, maxfibres-1);
   }



   /* check whether we need to repeat steps later */
   repeatflag=0;
   newyshift = 0;
   for (iframe=0; iframe<=(ScienceFrame->nflats-1); iframe++)
     newyshift += deltas[iframe];
   newyshift /= (double)ScienceFrame->nflats;
   /* do we need to repeat some steps? */
   if (fabs(newyshift-oldyshift)>shifthres) repeatflag=1;

   SCTPUT("Cross-correlation completed");

 }

 else {
   SCTPUT("\n*** Step 2: y shift determination skipped ***\n");
   repeatflag=0;

   /* now allocate the Slit_FF structure, we'll be using it from now on */
   if(!(Slit_FF = calloc(1, sizeof(allslitflats)))) {
     SCTPUT("Allocation error during Slit_FF memory allocation");
     return flames_midas_fail();
   }

   /* let's read the slit FFs */
   sprintf(output, "I'm reading the slit FF frames");
   SCTPUT(output);
   if ((status = readslitflats(slitsfile, Slit_FF)) != NOERR) {
     /* problems reading slitflats members from disk */
     SCTPUT("Error while reading the slit Flat Field frames");
     return flames_midas_fail();
   }
   orderoffset = Slit_FF->tab_io_oshift-Order->tab_io_oshift;
   slitfirstorder = Slit_FF->firstorder;
   slitlastorder = Slit_FF->lastorder;
   realfirstorder = Order->firstorder;
   if (orderoffset > 0) realfirstorder += orderoffset;
   reallastorder = Slit_FF->lastorder+orderoffset;
   if (reallastorder > Order->lastorder) reallastorder = Order->lastorder;
   if (realfirstorder > reallastorder) {
     /* this should really never happen with sane data, complain and exit */
     strcpy(output, "Error: The orders in the slit FF(s) and in the order \
table being used do not overlap at all!");
     SCTPUT(output);
     return flames_midas_fail();
   }
   /* correct for the ycorrection, if present */
   if (Order->corrected=='t') {
     for (iframe=0; iframe<=(Slit_FF->nflats-1);iframe++)
       Slit_FF->slit[iframe].yshift -= Order->ycorrection;
   }

   if (freeslitflats(Slit_FF)!=NOERR) {
     SCTPUT("Error while freeing the memory for the Slit_FF structure");
     return flames_midas_fail();
   }
   free(Slit_FF);

   /* Allocate memory for the Single_FF structure */
   if(!(Single_FF = calloc(1, sizeof(allflats)))) {
     SCTPUT("Allocation error during Single_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, Single_FF) != NOERR) {
     SCTPUT("Error while reading the fibre Flat Field frames");
     return flames_midas_fail();   
   }

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

   /* make sure we do not attempt extraction for uncovered fibres */
   fmvecbuf1 = Single_FF->goodfibres[0][0];
   if (Order->firstorder<realfirstorder) {
     iorderifibreixstart = 0;
     iorderifibreixend = (realfirstorder-Order->firstorder)*
       Single_FF->maxfibres*Single_FF->subcols-1;
     for (ix=iorderifibreixstart; ix<=iorderifibreixend; ix++) {
       fmvecbuf1[ix] = BADSLICE;
     }
   }
   if (Order->lastorder>reallastorder) {
     iorderifibreixstart = (reallastorder-Order->firstorder+1)*
       Single_FF->maxfibres*Single_FF->subcols;
     iorderifibreixend = (Order->lastorder-Order->firstorder)*
       Single_FF->maxfibres*Single_FF->subcols-1;
     for (ix=iorderifibreixstart; ix<=iorderifibreixend; ix++) {
       fmvecbuf1[ix] = BADSLICE;
     }
   }

   if (ScienceFrame->nflats != Single_FF->nflats) {
     /* I need to deallocate the yshift vector and to reallocate it with
    a different size */
     SCTPUT("Warning: yshift in frame incompatible with fibre FF frames");
     SCTPUT("falling back to zero yshifts");
     free_dvector(ScienceFrame->yshift, 0, ScienceFrame->nflats-1);
     /* set ScienceFrame->nflats equal to Single_FF->nflats, and allocate 
    ScienceFrame->yshift accordingly */
     ScienceFrame->nflats = Single_FF->nflats;
     ScienceFrame->yshift = dvector(0, ScienceFrame->nflats-1);
     /* initialise the yshifts to zero */
     deltas = dvector(0, Single_FF->nflats-1);
     deltamask = fmvector(0, Single_FF->nflats-1);
     for (iframe=0; iframe <= (Single_FF->nflats-1); iframe++) {
       ScienceFrame->yshift[iframe]=deltas[iframe]=0;
       deltamask[iframe]=TRUE;
     }
   }
   else {
     /* take the values read from disk as good ones */
     SCTPUT("Using the yshift values stored in frame");
     deltas = dvector(0, Single_FF->nflats-1);
     deltamask = fmvector(0, Single_FF->nflats-1);
     for (iframe=0; iframe <= (Single_FF->nflats-1); iframe++) {
       deltas[iframe]=ScienceFrame->yshift[iframe];
       deltamask[iframe]=TRUE;
     }
   }
 }



 /* After correl, save the shifts to disk */
 /* is there anything to save? */
 if (ScienceFrame->nflats > 0) {
   for (iframe=0; iframe<=(ScienceFrame->nflats-1); iframe++)
     ScienceFrame->yshift[iframe] = deltas[iframe];
   /* try to open the frame */
   status = SCFOPN(ScienceFrame->framename, FLAMESDATATYPE, 0, F_IMA_TYPE, 
          &fileid);
   nflats = (int) ScienceFrame->nflats;
   status = SCDWRI(fileid, "NFLATS", &nflats, 1, 1, &unit);
   status = SCDWRD(fileid, "YSHIFT", ScienceFrame->yshift, 1, 
          (int) ScienceFrame->nflats, &unit);

   status = SCFCLO(fileid) ;
 }



 SCTPUT("Allocating the Shifted_FF");
 /* Prepare the structure for allocation of the shifted FF */
 if (!(Shifted_FF=calloc(1, sizeof(allflats)))) {
   SCTPUT("Allocation while allocating memory for the shifted FF");
   return flames_midas_fail();   
 }

 /* allocate the arrays in Shifted_FF */
 if (!(initshiftedff(Single_FF,Shifted_FF)==NOERR)) {
   SCTPUT("Error while allocating internal arrays of the shifted \
FF structure");
   return flames_midas_fail();   
 }

 
 /* produce the shifted fibre FF frames, using the yshifts previously 
    determined by correl */
 SCTPUT("Shifting fibre FF Frames");
 /* to save memory, allocate just one iframe at a time, and recycle the 
    memory of the unshifted frames once they have been used */
 if (Shifted_FF->nflats >= 2) {
   for (iframe=0; iframe <= (Shifted_FF->nflats-2); iframe++) {
     /* Shift FF */
     sprintf(output,"Shifting fibre FF frame number %d", iframe);
     SCTPUT(output);
     if (deltamask[iframe]==TRUE) {
       shift_FF_n(Single_FF, Order, ScienceFrame->yshift[iframe], iframe, 
          Shifted_FF);
     }
     else {
       copy_FF_n(Single_FF, Order, ScienceFrame->yshift[iframe], iframe, 
         Shifted_FF);
     }
     uves_msg_debug("shift frame %d is %f",iframe,ScienceFrame->yshift[iframe]);

     /* the iframe which has been shifted already is not needed any more, we 
    can use it as next buffer in Shifted_FF, copy the pointers */
     Shifted_FF->flatdata[iframe+1].data = Single_FF->flatdata[iframe].data;
     Shifted_FF->flatdata[iframe+1].sigma = Single_FF->flatdata[iframe].sigma;
     Shifted_FF->flatdata[iframe+1].badpixel = 
       Single_FF->flatdata[iframe].badpixel;
     Shifted_FF->flatdata[iframe+1].framename = 
       Single_FF->flatdata[iframe].framename;
     Shifted_FF->flatdata[iframe+1].sigmaname = 
       Single_FF->flatdata[iframe].sigmaname;
     Shifted_FF->flatdata[iframe+1].badname = 
       Single_FF->flatdata[iframe].badname;
     Shifted_FF->flatdata[iframe+1].fibres = 
       Single_FF->flatdata[iframe].fibres;
   }
   /* handle the last iframe differently */
   iframe = Shifted_FF->nflats-1;
   sprintf(output,"Shifting fibre FF frame number %d", iframe);
   SCTPUT(output);
   if (deltamask[iframe]==TRUE) {
     shift_FF_n(Single_FF, Order, ScienceFrame->yshift[iframe], iframe, 
        Shifted_FF);
   }
   else {
     copy_FF_n(Single_FF, Order, ScienceFrame->yshift[iframe], iframe, 
           Shifted_FF);
   }
 
   /* this was the last one to shift, now turn the Single_FF in a dummy
      allflats structure which can be freed, as it is not needed any more */
   Single_FF->flatdata[0].data = Single_FF->flatdata[iframe].data;
   Single_FF->flatdata[0].sigma = Single_FF->flatdata[iframe].sigma;
   Single_FF->flatdata[0].badpixel = Single_FF->flatdata[iframe].badpixel;
   Single_FF->flatdata[0].framename = Single_FF->flatdata[iframe].framename;
   Single_FF->flatdata[0].sigmaname = Single_FF->flatdata[iframe].sigmaname;
   Single_FF->flatdata[0].badname = Single_FF->flatdata[iframe].badname;
   Single_FF->flatdata[0].fibres = Single_FF->flatdata[iframe].fibres;
 }
 else {
   /* in this case nflats appears to be at most 1, which simplifies things */
   for (iframe=0; iframe <= (Shifted_FF->nflats-1); iframe++) {
     /* Shift FF */
     sprintf(output,"Shifting fibre FF frame number %d", iframe);
     SCTPUT(output);
     if (deltamask[iframe]==TRUE)
       shift_FF_n(Single_FF, Order, ScienceFrame->yshift[iframe], iframe, 
          Shifted_FF);
     else 
       copy_FF_n(Single_FF, Order, ScienceFrame->yshift[iframe], iframe, 
          Shifted_FF);
   }
 }
 /* free the (now dummy) allflats structure of the unshifted fibre FF flats */
 if (freeoneflats(Single_FF) != NOERR) {
   SCTPUT("Error freeing the dummy fibre FF frame structure");
   return flames_midas_fail();
 }
 free(Single_FF);

 /* free the previously processed Science frame, later we will need the
    original one */
 if (freeframe(ScienceFrame) != NOERR) {
   SCTPUT("Error freeing ScienceFrame");
   return flames_midas_fail();   
 }
  

 /* free also deltas and deltamask, we do not need them any more */
 free_dvector(deltas, 0, Shifted_FF->nflats-1);
 free_fmvector(deltamask, 0, Shifted_FF->nflats-1);

 /* we must multiply the shifted FF frames by the slit FF, hence reallocate
    and reload the latter */
 if(!(Slit_FF = calloc(1, sizeof(allslitflats)))) {
   SCTPUT("Allocation error during Slit_FF memory allocation");
   return flames_midas_fail();
 }
 /* let's read the slit FFs */
 sprintf(output, "I'm reading the slit FF frames");
 SCTPUT(output);

 if ((status = readslitflats(slitsfile, Slit_FF)) != NOERR) {
   /* problems reading slitflats members from disk */
   SCTPUT("Error while reading the slit Flat Field frames");
   return flames_midas_fail();   
 }

 /* correct for the ycorrection, if present */
 if (Order->corrected=='t') {
   for (iframe=0; iframe<=(Slit_FF->nflats-1);iframe++)
     Slit_FF->slit[iframe].yshift -= Order->ycorrection;
 }
 /* do multiply the shifted fibre FF frames by the slit FF, in place
    to save memory */
 SCTPUT("Multiplying the shifted FF frame(s) by the slit FF frame(s)");
 if (ffslitmultiply(Slit_FF, Order, Shifted_FF, Shifted_FF) != NOERR) {
   SCTPUT("Error multiplying the shifted fibre FF by the slit FF");
   return flames_midas_fail();
 }
 /* copy the normalisation factors from the slit FF structure before 
    freeing it for good */
 normcover = fdmatrix(0, Slit_FF->lastorder-Slit_FF->firstorder, 
              0, Slit_FF->subcols-1);
 memcpy(normcover[0], Slit_FF->normfactor[0], 
    (size_t) ((Slit_FF->lastorder-Slit_FF->firstorder+1)*
          Slit_FF->subcols)*sizeof(frame_data));
 /* finally free for good the memory for the slit FF */
 if (freeslitflats(Slit_FF)!=NOERR) {
   SCTPUT("Error while freeing the memory for the Slit_FF structure");
   return flames_midas_fail();
 }
 free(Slit_FF);

 /* Reread the original ScienceFrame (now including the correct yshifts),
    undivided by the slit FF */
 sprintf(output, "I'm re-reading the original frame %s", infile);
 SCTPUT(output);
 if (readframe(ScienceFrame, infile) != NOERR) {
   SCTPUT("Error while re-reading the Science Frame");
   return flames_midas_fail();   
 }



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

 if ((repeatflag!=0 ) && (bkginline == TRUE)) {
   /* read in the old background table */
   SCTPUT("A significant drift was detected:\n refit the background");
   if ((status=readback(&(ScienceFrame->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();
   }
   if (ScienceFrame->back.Window_Number > 0) {
     if (scatter(ScienceFrame, Order, bkgswitch, bkgswitch2, badwinxsize, 
         badwinysize, badfracthres, badtotthres, kappa2, 
         (int32_t) maxbackiters, maxdiscardfract, OUTPUTI)) {
       SCTPUT("Error during the calculation of the scattered light");
       return flames_midas_fail();
     }
     /* compute the estimated background */
     if (computeback(ScienceFrame, backframe) != NOERR) {
       SCTPUT("Eccor computing fitted background");
       return flames_midas_fail();
     }
   }
   else {
     SCTPUT("Error: no regions available for background estimation");
     return flames_midas_fail();
   }
 }
 
 if (bkginline == TRUE) {
   /* subtract the estimated background from the data frame */
   /* the error of the estimated background is assumed to be negligible */
   SCTPUT("Subtracting fitted background from Science Frame");
   fdvecbuf1 = ScienceFrame->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 = ScienceFrame->frame_array[0];
   fdvecbuf2 = ScienceFrame->frame_sigma[0];
   fmvecbuf1 = ScienceFrame->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(ScienceFrame, "middumma.bdf", backframe)!=NOERR)
     SCTPUT("Warning: error writing background frame to disk");
 }

 SCTPUT("\n*** Step 3: prepare merged bad pixel mask and final \
initialisations ***\n");
 /* allocate the global, merged bad pixel mask */
 mask=fmmatrix(0,ScienceFrame->subrows-1,0,ScienceFrame->subcols-1);
 if(!mask) {
   SCTPUT("Error in allocating mask matrix");
 }
 
 /* initialise the global, merged bad pixel mask to be used 
    in the subsequent optimal extraction, initialise the lookup tables for 
    lit fibres in the ScienceFrame and allocate the arrays to store the 
    allocated spectra again in ScienceFrame */
 if (prepextract(ScienceFrame, Shifted_FF, Order, normcover, orderoffset, 
         realfirstorder, reallastorder, mask)!=NOERR) {
   /* something went wrong in prepextract */
   SCTPUT("Error in prepextract");
   return flames_midas_fail();
 }

 /* start from first order, then divide orders in non-overlapping subsets */


 /* Going to do the real spectrum extraction */
 SCTPUT("\n*** Step 4: optimal extraction proper ***\n");


 if (doptimal(ScienceFrame, Order, Shifted_FF, kappa2, mask, backframe, 
          normcover, orderoffset, realfirstorder, reallastorder, 
          minoptitersint, maxoptitersint, xkillsize, ykillsize)!=NOERR) {
   SCTPUT("Error in doptimal");
   return flames_midas_fail();
 }

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


 /* build the fitted Science Frame, do it in place to save memory */
 if (optsynth(ScienceFrame, Shifted_FF, Order, &backframe, &chisquare, 
          &chisqpixels, &nfittedparams)!=NOERR){
   SCTPUT("Error computing the fitted frame");
   return flames_midas_fail();
 }
 uves_msg("chisquare=%g",chisquare);
 uves_msg("chisqpixels=%d",chisqpixels);
 uves_msg("nfittedparams=%d",nfittedparams);
 uves_msg("Reduced chisquare=%f",chisquare/(chisqpixels-nfittedparams));
 if(irplib_isnan(chisquare)) {
    chisquare=-999;
 }
 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(ScienceFrame, "middummb.bdf", "middummc.bdf", "middummd.bdf")
     != NOERR)
   SCTPUT("Warning: error writing dummy debugging frames");

 SCTPUT("\n*** Step 5: write extrated spectra to disk, clean up and \
exit ***\n");

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

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

 /* free the normcover array */
 free_fdmatrix(normcover, 0, slitlastorder-slitfirstorder, 
           0, ScienceFrame->subcols-1);

 /* Creating the output catalog of the spectra extracted */ 
 //Fixme: the next 3 lines are useless as that catalog is not used elsewhere
 //SCTPUT("Creating catalog of the spectra extracted");
 //SCCCRE("spectra.cat",F_IMA_TYPE,0);
 //SCTPUT("Created catalog of Spectra");

 /* can these spectra be normalised? */
 if ((Order->corrected == 't')&&(Shifted_FF->normalised == 'y')) {
   /* yes, compensation was performed already */
   SCTPUT("Correcting for normalisation factors");
   fdvecbuf1 = Shifted_FF->normfactors[0][0];
   fdvecbuf2 = Shifted_FF->normsigmas[0][0];
   fmvecbuf1 = Shifted_FF->goodfibres[0][0];
   fdvecbuf3 = ScienceFrame->spectrum[0][0];
   fdvecbuf4 = ScienceFrame->normsigma[0][0];
   fdvecbuf5 = ScienceFrame->specsigma[0][0];
   fdvecbuf6 = ScienceFrame->normspec[0][0];
   fmvecbuf2 = ScienceFrame->specmask[0][0];
   fmvecbuf3 = ScienceFrame->normmask[0][0];
   for (ifibre=0; ifibre<=(ScienceFrame->maxfibres-1); ifibre++) {
     /* is this fibre lit? */
     if ((ScienceFrame->fibremask[ifibre] == TRUE) &&
     (Shifted_FF->fibremask[ifibre] == TRUE)) {
       for (iorder=0; iorder<=(Order->lastorder-Order->firstorder); iorder++) {
     iorderifibreindex = (iorder*ScienceFrame->maxfibres)+ifibre;
     iorderifibreixoffset = iorderifibreindex*ScienceFrame->subcols;
     for (ix=0; ix<=(ScienceFrame->subcols-1); ix++) {
       iorderifibreixindex = iorderifibreixoffset+ix;
       ixiorderifibreindex = (ix*(1+Order->lastorder-Order->firstorder)*
                  ScienceFrame->maxfibres)+iorderifibreindex;
       /* can this fibre be corrected here? */
       if ((fmvecbuf2[ixiorderifibreindex]==1) &&
           (fmvecbuf1[iorderifibreixindex]==GOODSLICE)) {
         /* yes, therefore correct and propagate errors */
         normvalue = fdvecbuf1[iorderifibreixindex];
         normvalue2 = normvalue*normvalue;
         pixelvalue = fdvecbuf3[ixiorderifibreindex];
         fdvecbuf4[ixiorderifibreindex] = 
           (fdvecbuf5[ixiorderifibreindex]/normvalue2) +
           ((pixelvalue*pixelvalue)*fdvecbuf2[iorderifibreixindex]/
        (normvalue2*normvalue2));
         fdvecbuf6[ixiorderifibreindex] =
           fdvecbuf3[ixiorderifibreindex]/normvalue;
         fmvecbuf3[ixiorderifibreindex] = 1;
       }
       /* no, mark this slice as bad and zero normalised spectra */
       else {
         fmvecbuf3[ixiorderifibreindex] = 0;
         fdvecbuf6[ixiorderifibreindex] = 0;
         fdvecbuf4[ixiorderifibreindex] = 0;
       }
     }
       }
     }
   }
 }
 else {
   SCTPUT("Warning: no correction factors available");
   fdvecbuf1 = ScienceFrame->normspec[0][0];
   fdvecbuf2 = ScienceFrame->normsigma[0][0];
   fmvecbuf1 = ScienceFrame->normmask[0][0];
   for (ifibre=0; ifibre<=(ScienceFrame->maxfibres-1); ifibre++) {
     /* is this fibre lit? */
     if ((ScienceFrame->fibremask[ifibre] == TRUE) &&
     (Shifted_FF->fibremask[ifibre] == TRUE)) {
       for (iorder=0; iorder<=(Order->lastorder-Order->firstorder); iorder++) {
     iorderifibreindex = (iorder*ScienceFrame->maxfibres)+ifibre;
     for (ix=0; ix<=(ScienceFrame->subcols-1); ix++) {
       ixiorderifibreindex = (ix*(1+Order->lastorder-Order->firstorder)*
                  ScienceFrame->maxfibres)+iorderifibreindex;
       fmvecbuf1[ixiorderifibreindex] = 0;
       fdvecbuf1[ixiorderifibreindex] = 0;
       fdvecbuf2[ixiorderifibreindex] = 0;
     }
       }
     }
   }
 }

 for (n=0; n<ScienceFrame->maxfibres; n++) {
   if(ScienceFrame->fibremask[n] == TRUE) {
     if (n==0) sprintf(output,"Writing spectrum for the first fibre...");
     else if (n==1) sprintf(output,"Writing spectrum for the second fibre...");
     else if (n==2) sprintf(output,"Writing spectrum for the third fibre...");
     else sprintf(output,"Writing spectrum for the %d-th fibre...", n+1);    
     SCTPUT(output);
     status=Write_Spectra(ScienceFrame, n, catfile);
     if (status) SCTPUT("Error during the writing on disk");
     else if (n==0) sprintf(output,"Spectrum for the first fibre written");
     else if (n==1) sprintf(output,"Spectrum for the second fibre written");
     else if (n==2) sprintf(output,"Spectrum for the third fibre written");
     else sprintf(output,"Spectrum for the %d-th fibre written", n+1);    
     SCTPUT(output);
   } 
 }

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

 if (freeframe(ScienceFrame)!=NOERR) {
   SCTPUT("Error while freeing the memory of the ScienceFrame structure");
   return flames_midas_fail();
 }

 free(ScienceFrame);
 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 complete ***\n");

 return SCSEPI();

}
