File: flames_mainoptFF.c

package info (click to toggle)
cpl-plugin-uves 6.1.3+dfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 23,128 kB
  • sloc: ansic: 171,056; sh: 4,359; python: 3,002; makefile: 1,322
file content (1525 lines) | stat: -rw-r--r-- 66,133 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
/*===========================================================================
  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  : mainoptFF.c                                                  */
/* Author   : G. Mulas  -  ITAL_FLAMES Consortium                          */
/* Date     :                                                              */
/*                                                                         */
/* Purpose  : to do optimal extraction                                     */
/*                                                                         */
/*                                                                         */
/* Input:  see interface                                                   */ 
/*                                                                      */
/* Output:                                                              */
/*                                                                         */
/* DRS Functions called:                                                   */
/* none                                                                    */ 
/*                                                                         */ 
/* Pseudocode:                                                             */
/* Missing                                                                 */ 
/*                                                                         */ 
/* Version  :                                                              */
/* Last modification date: 2002/08/05                                      */
/* Who     When        Why                Where                            */
/* AMo     02-08-05   Add header         header                            */
/*-------------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif
#include <flames_mainoptFF.h>
#include <flames_freeoneflats.h>
#include <flames_writenormfactors.h>
#include <flames_readallff.h>
#include <flames_initshiftedff.h>
#include <flames_prepextract.h>
#include <flames_doptimal.h>
#include <flames_quickprepextract.h>

#include <flames_optsynth.h>
#include <flames_writesynth.h>
#include <flames_gausscorrelFF.h>
#include <flames_optimal.h>
#include <flames_scatter.h>
#include <flames_shift_FF_n.h>
#include <flames_copy_FF_n.h>
#include <flames_midas_def.h>
#include <flames_uves.h>
#include <flames_newmatrix.h>
#include <flames_freespectrum.h>
#include <flames_computeback.h>
#include <flames_readback.h>
#include <flames_readframe.h>
#include <flames_freeordpos.h>
#include <flames_slitdivide.h>
#include <flames_ffslitmultiply.h>
#include <flames_freeslitflats.h>
#include <flames_writeback.h>
#include <flames_striptblext.h>
#include <flames_freeallflats.h>
#include <flames_freeframe.h>

#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <flames_readordpos.h>
#include <flames_readslitflats.h>

/**
 @brief prepares and normalise fibre flat field data

 @param IN_A  file name of input all fibre flat frame, bias subtracted
 @param IN_B  input fibreff* data set
 @param IN_C  input slitff* data set
 @param IN_D  inter-order background table file name
 @param IN_E  raw fibre order table file name
 @param IN_F  final fibre order table file name
 @param DECENTSNR How large must the SNR on a fibre be in a calibration frame, at a given order and x,
                  for that slice to be considered "good"?
 @param MAXDISCARDFRACT maximum fraction of windows/pixels which we are willing to  discard by kappa-sigma
                        clipping in each iteration of the background fitting loop
 @param MAXBACKITERS maximum number of kappa-sigma clipping iterations which we are willing to perform in
                     background fitting
 @param MAXCORRITERS maximum number of iterations which we are willing to perform in correlation
 @param MINOPTITERSINT minimum number of iterations which we are willing to perform in optimal extraction
 @param MAXOPTITERSINT maximum number of iterations which we are willing to perform in optimal extraction
 @param XKILLSIZE  When performing sigma-clipping in the optimal extraction, how many other adjacent pixels
                   in the x and/or y direction(s) should be  discarded along with the one exceeding the threshold?
                   A cosmic or cosmetic problem is likely to affect a spot larger than 1 pixel: XKILLSIZE,YKILLSIZE
 @param YKILLSIZE
 @param BKGPOL     Polynomial degree (X,Y) for inter-order background estimation
 @param BKGFITINLINE Inline background fitting
 @param BKGFITMETHOD Background fitting method
 @param BKGBADSCAN Background table bad pixel frame scanning switch (Values:none, fraction, absolute)
 @param BKGBADWIN  Background table bad pixel frame scanning window size BKGBADWIN (50,50)
 @param BKGBADMAXFRAC Background table bad pixel frame scanning threshold fraction
 @param BKGBADMAXTOT Background table bad pixel frame scanning threshold number
 @param SIGMA       output kappa for kappa-sigma clipping
 @param MAXYSHIFT  Half width of the interval to scan for correlation, when determining y shift
 @param CORRELTOL This is the absolute accuracy with which we require in the correlation to determine the y shift
 @param CORRELXSTEP This is the x step to use while computing the correlation: it must be a positive integer,
                    1 means "use all pixels", 2 means "use every other pixel", 3 means "use one every three" etc.
 @param OUTPUTD     computed chi-square
 @param OUTPUTI     computed number of degree of freedom

 @doc  -read input parameters
       -read the Science Frame
       -Read the table data and then put them in the C structures
       -use the readordpos function to read the descriptor
       -verifies that the order table match the Science frame chip

       -Step 1: background fitting and subtraction: also 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

       -Step 2: y shift determination and compensation:
            -read slit flats
            -divide the all fibres FF frame by the slit FF frame(s)
            -let's read the fibre FFs: is this fibre FF frames set shift-able?
                                       make sure we do not attempt extraction for uncovered fibres
            -Doing cross-correlation calculation. After correl, save the shifts to disk.
            -produce the shifted fibre FF frames, using the yshifts previously determined by correl
            -multiply the shifted FF frames by the slit FF
            -copy the normalisation factors from the slit FF structure
            -Reread the original AllFrame (now including the correct yshifts, undivided by the slit FF)
            -estimate background and subtract the estimated background from the data frame
            -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

       -Step 3: prepare merged bad pixel mask and final initialisations
            -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

       -Step 4: Performs the real spectrum optimal extraction
            -free the old bad pixel mask, replace it with the global mask
            -build the fitted all fibres FF Frame

       -Step 5: write normalisation factors to disk, clean up and exit
            -initially free the estimated background frame, as we don't need it any more
            -makes some checks on extracted fibres: was this a decent fibre at this x, before?
                                                    was I able to extract this with a decent SNR?
            -The fibres that could not be extracted are marked as DEMISLICE at best
            -now do write the normalisation factors
            -finally free for good the AllFrame (including the spectrum), Shifted_FF and Order

 @return void
 */
int flames_mainoptFF(const char *IN_A,
                     const cpl_frameset* IN_B,
                     const cpl_frameset* IN_C,
                     const char *IN_D,
                     const char *IN_E,
                     const char *IN_F,
                     const double *DECENTSNR,
                     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,
                     const char *BKGFITMETHOD,
                     const char *BKGBADSCAN,
                     const int *BKGBADWIN,
                     const double *BKGBADMAXFRAC,
                     const int *BKGBADMAXTOT,
                     const double *SIGMA,
                     const double *MAXYSHIFT,
                     const double *CORRELTOL,
                     const int *CORRELXSTEP,
                     double *OUTPUTD,
                     int *OUTPUTI)
{ 

    char output[200];
    char repeatflag=0;
    int i=0;
    int tid=0;
    int fileid=0;
    int nflats=0;
    int unit=0;
    int actvals=0;
    frame_mask **mask=0;
    int bxdegree=0, bydegree=0;
    int maxbackiters=0;
    double maxdiscardfract=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 *AllFrame=0;

    allslitflats *Slit_FF=0;

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

    orderpos *Order=0;

    const cpl_frameset *allfile;
    char backfile[CATREC_LEN+2];
    char infile[CATREC_LEN+2];
    const cpl_frameset *slitsfile;
    char dummyfile[CATREC_LEN+2];
    char inorderfile[CATREC_LEN+2];
    char outorderfile[CATREC_LEN+2];
    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;
    int ibuf=0;
    int32_t minoptitersint=0;
    int32_t maxoptitersint=0;
    int32_t xkillsize=0;
    int32_t ykillsize=0;
    int32_t lfibre=0, ifibre=0, firstfibre=0, lastfibre=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 *deltas;
    frame_mask *deltamask;
    double ycentre=0;
    double decentSNR=0;
    frame_data decentSNR2=0;
    int32_t orderoffset=0;
    int32_t realfirstorder=0;
    int32_t reallastorder=0;
    int32_t slitfirstorder=0;
    int32_t slitlastorder=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_mask *fmvecbuf1=0;
    frame_mask *fmvecbuf2=0;
    frame_data pixelvalue=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("optnorm"); /* 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);

    /* get the slit FF catalog name from MIDAS env.*/
    SCKGETC_fs(IN_C,1,CATREC_LEN+1,&nval,&slitsfile);

    /* 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 MAX_DISCARD_FRACT */
        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 MAX_BACK_ITERS */
        SCTPUT("Error reading the MAX_BACK_ITERS keyword");
        return flames_midas_fail();
    }

    /* initialise MAXCORRITERS from keyword */
    if (SCKRDI(MAXCORRITERS, 1, 1, &actvals, &imaxcorriters, &unit, 
                    &null) != 0) {
        /* problems reading MAX_CORR_ITERS */
        SCTPUT("Error reading the MAX_CORR_ITERS keyword");
        return flames_midas_fail();
    }

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

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

    /* 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 */
    if (SCKRDD(MAXYSHIFT, 1, 1, &actvals, &shiftwindow, &unit, &null) != 0) {
        /* problems reading MAXYSHIFT */
        SCTPUT("Error reading the MAXYSHIFT (P8) parameter");
        return flames_midas_fail();
    }
    if (shiftwindow<0) {
        SCTPUT("Warning: illegal value for MAXYSHIFT (P8), fall back to 0");
        shiftwindow = 0;
    }
    /* read the CORRELTOL keyword */
    if (SCKRDD(CORRELTOL, 1, 1, &actvals, &shifttol, &unit, &null) != 0) {
        /* problems reading CORRELTOL */
        SCTPUT("Error reading the CORRELTOL keyword");
        return flames_midas_fail();
    }
    if (shifttol<0) {
        SCTPUT("Error: illegal (negative) value for CORRELTOL");
        return flames_midas_fail();
    }
    /* read the CORRELXSTEP keyword */
    if (SCKRDI(CORRELXSTEP, 1, 1, &actvals, &icorrelxstep, &unit, &null) != 0) {
        /* problems reading CORRELXSTEP */
        SCTPUT("Error reading the CORRELXSTEP keyword");
        return flames_midas_fail();
    }
    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 = (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");
            }
        }
        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();
        }

        /* ycorrection is not needed here, since the order table must be
           uncorrected thus far */

        /* divide the all fibres FF 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 all fibres FF Frame by slit FF frame(s)");
        SCTPUT(output);
        /* Let's divide the all fibres FF Frame by the full slit FF, in place */

        if (slitdivide(Slit_FF, Order, AllFrame, AllFrame)!=NOERR) {
            /* something went wrong in slitdivide */
            SCTPUT("Error while dividing the all fibres FF 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;
            }
        }

        double oldyshift = 0;
        if (AllFrame->nflats != 0) {
            for (iframe=0; iframe<=(AllFrame->nflats-1); iframe++) 
                oldyshift += AllFrame->yshift[iframe];
            oldyshift /= (double) AllFrame->nflats;
            /* I need to deallocate the yshift vector and to reallocate it with
               a different size */
            free_dvector(AllFrame->yshift, 0, AllFrame->nflats-1);
        }
        /* set AllFrame->nflats equal to Single_FF->nflats, and allocate 
           AllFrame->yshift accordingly */
        AllFrame->nflats = Single_FF->nflats;
        AllFrame->yshift = dvector(0, AllFrame->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++)
            AllFrame->yshift[iframe]=0;   

        /* calculation of the needed shifts by cross-correlation */ 
        SCTPUT("Doing cross-correlation calculation");
        deltas = dvector(0, Single_FF->nflats-1);
        deltamask = fmvector(0, Single_FF->nflats-1);
        if (gausscorrelFF(AllFrame, Single_FF, Order, maxcorriters, shiftwindow, 
                        shifttol, correlxstep, "middumma.fits", deltas,
                        deltamask)) {
            SCTPUT("Error during cross-correlation calculation");
            return flames_midas_fail();
        }

        /* check whether we need to repeat steps later */
        repeatflag=0;
        newyshift = 0;
        for (iframe=0; iframe<=(AllFrame->nflats-1); iframe++)
            newyshift += deltas[iframe];
        newyshift /= (double)AllFrame->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 assumed to be zero ***\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 (AllFrame->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(AllFrame->yshift, 0, AllFrame->nflats-1);
            /* set AllFrame->nflats equal to Single_FF->nflats, and allocate 
               AllFrame->yshift accordingly */
            AllFrame->nflats = Single_FF->nflats;
            AllFrame->yshift = dvector(0, AllFrame->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++) {
                AllFrame->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]=AllFrame->yshift[iframe];
                deltamask[iframe]=TRUE;
            }
        }
    }


    /* After correl, save the shifts to disk */
    /* is there anything to save? */
    if (AllFrame->nflats > 0) {
        for (iframe=0; iframe<=(Single_FF->nflats-1); iframe++) {
            /* we measured the shifts of the all fibres FF frame with respect
               to the single fibre FF frames, but we now want to store the 
               shift of the latter with respect to the former; to say it briefly,
               we must reverse the sign */
            Single_FF->flatdata[iframe].yshift = -deltas[iframe];
            AllFrame->yshift[iframe]=0;
            /* try to open the single FF frame */
            if (SCFOPN(Single_FF->flatdata[iframe].framename, FLAMESDATATYPE, 0, 
                            F_IMA_TYPE, &fileid) != 0) {
                /* I could not open the frame */
                return flames_midas_fail();
            }
            if (SCDWRD(fileid, "YSHIFT", &Single_FF->flatdata[iframe].yshift,
                            1, 1, &unit) != 0) {
                /* error writing YSHIFT */
                return flames_midas_fail();
            }
            if (SCFCLO(fileid) != 0) {
                /* I could not close the frame */
                return flames_midas_fail();
            }
        }

        /* try to open the all fibres FF frame */
        if (SCFOPN(AllFrame->framename, FLAMESDATATYPE, 0, F_IMA_TYPE, 
                        &fileid) != 0) {
            /* I could not open the frame */
            return flames_midas_fail();
        }
        nflats = (int) AllFrame->nflats;
        if (SCDWRI(fileid, "NFLATS", &nflats, 1, 1, &unit) != 0) {
            /* error writing descriptor */
            return flames_midas_fail();
        }
        if (SCDWRD(fileid, "YSHIFT", AllFrame->yshift, 1, 
                        nflats, &unit) != 0) {
            /* error writing descriptor */
            return flames_midas_fail();
        }
        if (SCFCLO(fileid) != 0) {
            /* I could not close the frame */
            return flames_midas_fail();
        }
        /* Now we must appropriately correct the fibre positions for the shift, 
           so that the polynomial in Order traces them at zero shift */
        for (iframe=0; iframe<=Single_FF->nflats-1; iframe++) {
            for (lfibre=0; lfibre<=Single_FF->flatdata[iframe].numfibres-1; lfibre++){
                ifibre=Single_FF->flatdata[iframe].fibres[lfibre];
                Order->fibrepos[ifibre] -= Single_FF->flatdata[iframe].yshift;
            }
        }
        /* find the extremal lit fibres */
        for (ifibre=0; (ifibre<=Single_FF->maxfibres-1) && 
        (Single_FF->fibremask[ifibre]!=TRUE); ifibre++);
        if (ifibre<=Single_FF->maxfibres-1) {
            firstfibre = lastfibre = ifibre;
            for (ifibre++; ifibre<=Single_FF->maxfibres-1; ifibre++)
                if (Single_FF->fibremask[ifibre]==TRUE) lastfibre=ifibre;
            ycentre = (Order->fibrepos[firstfibre]+Order->fibrepos[lastfibre])/2;
            Order->ycorrection = ycentre;
            Order->orderpol[0][0] += ycentre;
            Order->tab_io_yshift += ycentre;
            for (ifibre=0; ifibre<=Single_FF->maxfibres-1; ifibre++)
                if (Single_FF->fibremask[ifibre]==TRUE) 
                    Order->fibrepos[ifibre] -= ycentre;
        }
        if ((status = TCTOPN(outorderfile, F_D_MODE, &tid)) != 0) {
            /* I could not open the output order table: protest... */
            sprintf(output, "Error: I couldn't open the %s table", outorderfile);
            SCTPUT(output);
            return flames_midas_fail();   
        }
        /* now write the changed descriptors */
        if (SCDWRD(tid, "FIBREPOS", Order->fibrepos, 1, Order->maxfibres, &unit) 
                        != 0) {
            SCTPUT("Error writing corrected FIBREPOS descriptor");
            return flames_midas_fail();
        }
        if (SCDWRD(tid, "COEFFD", Order->orderpol[0], 1, 1, &unit) !=0) {
            SCTPUT("Error writing corrected COEFFD descriptor");
            return flames_midas_fail();
        }
        if (SCDWRD(tid, "YCORRECTION", &ycentre, 1, 1, &unit) !=0) {
            SCTPUT("Error writing YCORRECTION descriptor");
            return flames_midas_fail();
        }
        if (SCDWRD(tid, "TAB_IN_OUT_YSHIFT", &Order->tab_io_yshift, 1, 1, &unit) 
                        !=0) {
            SCTPUT("Error updating TAB_IN_OUT_YSHIFT descriptor");
            return flames_midas_fail();
        }
        if (SCDWRC(tid, "CORRECTED", 1, "t", 1, 1, &unit) != 0) {
            SCTPUT("Error updating the CORRECTED flag");
            return flames_midas_fail();
        }
        if (TCTCLO(tid) != 0) {
            SCTPUT("Error closing order table");
            return flames_midas_fail();
        }
        Order->corrected='t';
    }

    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, 0, iframe, Shifted_FF);
            else
                copy_FF_n(Single_FF, Order, 0, iframe, Shifted_FF);
            /* 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, 0, iframe, Shifted_FF);
        else
            copy_FF_n(Single_FF, Order, 0, 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, 0, iframe, Shifted_FF);
            else
                copy_FF_n(Single_FF, Order, 0, 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 all fibres FF frame, later we will need the
       original one */
    if (freeframe(AllFrame) != NOERR) {
        SCTPUT("Error freeing AllFrame");
        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();   
    }
    /* the ycorrection is necessarily needed here, since we previously corrected
       the order table */
    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 AllFrame (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(AllFrame, infile) != NOERR) {
        SCTPUT("Error while re-reading the all fibres FF Frame");
        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;

    if ((repeatflag != 0) && (bkginline == TRUE)) {
        /* read in the old background table */
        SCTPUT("A significant drift was detected:\n refit the background");
        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();
        }
        if (AllFrame->back.Window_Number > 0) {
            if (scatter(AllFrame, 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(AllFrame, backframe) != NOERR) {
                SCTPUT("Error 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 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");
    }


    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();
    }

    /* 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 (prepextract(AllFrame, Shifted_FF, Order, normcover, orderoffset, 
                    realfirstorder, reallastorder, mask)!=NOERR) {
        /* something went wrong in prepextract */
        SCTPUT("Error in prepextract");
        return flames_midas_fail();
    }

    /* Going to do the real spectrum extraction */
    SCTPUT("\n*** Step 4: optimal extraction proper ***\n");
    if (doptimal(AllFrame, 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(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();
    }
    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");

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

    /* free the normcover array */
    free_fdmatrix(normcover, 0, slitlastorder-slitfirstorder, 
                  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;
                }
            }
        }
    }

    /* 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 complete ***\n");

    return SCSEPI();

}