File: flames_fillholes.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 (1368 lines) | stat: -rw-r--r-- 66,579 bytes parent folder | download
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
/*===========================================================================
  Copyright (C) 2001 European Southern Observatory (ESO)

  This program is free software; you can redistribute it and/or 
  modify it under the terms of the GNU General Public License as 
  published by the Free Software Foundation; either version 2 of 
  the License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public 
  License along with this program; if not, write to the Free 
  Software Foundation, Inc., 675 Massachusetss Ave, Cambridge, 
  MA 02139, USA.

  Corresponding concerning ESO-MIDAS should be addressed as follows:
  Internet e-mail: midas@eso.org
  Postal address: European Southern Observatory
  Data Management Division 
  Karl-Schwarzschild-Strasse 2
  D 85748 Garching bei Muenchen 
  GERMANY
  ===========================================================================*/

/**
 * @defgroup flames_fillholes EsoRex File Utility Functions
 *
 * Utility functions for hadling files.
 *
 */


#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif
/*---------------------------------------------------------------------------
  Includes
  --------------------------------------------------------------------------*/

#include <flames.h>
#include <flames_midas_def.h>
#include <flames_freeback.h>
#include <flames_computeback.h>
#include <flames_def_drs_par.h>
#include <flames_scatter.h>
#include <flames_uves.h>
#include <flames_newmatrix.h>
#include <flames_shiftcommon.h>
#include <flames_shiftall.h>
#include <flames_uves.h>
#include <flames_dfs.h>
#include <flames_dointerpolate.h>
#include <flames_getordpos.h>
#include <flames_getordslope.h>
#include <flames_readslitflats.h>
#include <flames_readback.h>
#include <flames_slitdivide.h>
#include <flames_freeslitflats.h>

#include <flames_fillholes.h> //fixme: This header should contain only the definition of flames_fillholes()
#include <uves_msg.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
/**@{*/

/**
   @name  flames_fillholes()  
   @short  This function try to fill missing (bad) pixels with interpolated 
   values. 2D frames are normalized (and any x, order the integrated flux over
   a fibre is 1). 
   @author G. Mulas  -  ITAL_FLAMES Consortium. Ported to CPL by A. Modigliani


   @param  allflatsin         input all slit flat field
   @param  ordpos             input order pos rtable
   @param  slitsname          slit name prefix
   @param  backname           background table name
   @param  bxdegree           inter-order background poly degree X
   @param  bydegree           inter-order background poly degree X
   @param  bkgswitch          parameter to control background subtraction algorithm
   @param  bkgswitch2         parameter to control background subtraction algorithm
   @param  badwinxsize        X size of inter-order background window
   @param  badwinysize        Y size of inter-order background window
   @param  badfracthres       Background table bad pixel frame scanning threshold fraction
   @param  badtotthres        Background table bad pixel frame scanning threshold number
   @param  kappa2             square of kappa value in kappa-sigma clip
   @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  maxbackiters This is the maximum number of kappa-sigma clipping iterations which we are willing to perform in background fitting
   @param  maxdiscardfract This is the maximum fraction of windows/pixels which we are willing to  discard by kappa-sigma clipping in each
                           iteration of the background fitting loop
   @param  maxcleaniters   This is the maximum number of cleaning iterations to be tried on a given slice in flames_prep_fibre, before
                            giving up on its normalise-ability and falling back to the second cleaning strategy
   @param  maxsinglepixelfrac maximum acceptable fraction of the flux in a given slices in one single pixel; a higher fraction than this means
                              that there was some numerical instability and/or unmasked bad pixel, and that it must be discarded
   @param  fracslicesthres  defines the minimum fraction of slices that must be good, for a fibre to be considered covered enough at the end
                            of fillholes, in flames_prep_fibreff, to avoid stupid instabilities in gaussselfcorrel if a fibre is only very
                            barely covered by the slit FF frames
   @param  OUTPUTI


   @return success or failure code, 


   DRS Functions called:          
   none


   Pseudocode:                                                             


   @note
   @doc  This function takes a pointer to an allflats structure (all memory
   allocations are assumed to have been done already) and tries to fill
   missing (bad) pixels with interpolated values. Moreover, in the 2D frames
   each pixel is normalised so that for any given x, and order the integrated
   value over one fibre equals 1, and the normalisation factor is stored in
   appropriate structure members, to make shifting more efficient later. 

   -computes the halfibrewidth in pixel units

   -subtracts inter-order background (the error of the estimated background is assumed to be negligible)
         scan the frame for any negative pixel values; if any are found, compare them to the
         standard deviation: if the negative value is compatible with zero, set that pixel to zero,
         otherwise mark that pixel as bad

   -allocate the Slit_FF structure, to be used later on

   -starts to clean bad pixels (normalisation factors are computed as part of this not including bad pixels)
    via interpolation of good ones. Clip negative values may wreak havoc in iterative interpolations

   -normalise to 1 the integral over y of each order/fibre/x of the fibre FF frames
   -compute the fibre coverage over newly cleaned pixels, to see whether
    they may be labelled as half-good, i.e. good profile but no normalisation factor

 */

flames_err 
fillholes(
                allflats *allflatsin,
                orderpos *ordpos,
                const cpl_frameset *slitsname,
                char *backname,
                int bxdegree,
                int bydegree,
                scatterswitch bkgswitch,
                scatterswitch2 bkgswitch2,
                int badwinxsize,
                int badwinysize,
                double badfracthres,
                int badtotthres,
                double kappa2,
                double decentSNR,
                int32_t maxbackiters,
                double maxdiscardfract,
                int32_t maxcleaniters,
                double maxsinglepixelfrac,
                double fracslicesthres,
                int *OUTPUTI)
{
    char output[CATREC_LEN+1];
    allflats *allflatsout=0;
    allslitflats *slitflats=0;
    flames_frame *framebuffer=0;
    frame_data **backframe;
    shiftstruct **shiftdata=0;
    shiftstruct *shiftbuffer=0;
    shiftstruct *shiftbufferix=0;
    badifibrestruct *badifibre=0;
    badifibrestruct *mybadifibre=0;
    badixstruct *mybadixs=0;
    normstruct normdata[8];
    fitstruct fitdata;
    double phalfibrewidth=0;

    double x=0;
    double ordercentre=0;
    double orderslope=0;
    double normfactor=0;
    double normfactor2=0;
    double normsigma=0;
    double pfibrecentre=0;
    double plowlimit=0;
    double phighlimit=0;
    double fraction=0;
    double totslices=0;
    double fracslices=0;
    int32_t ix=0, iy=0;
    int32_t iorder=0, iframe=0, lfibre=0, ifibre=0;
    int32_t badtotal=0, oldbadtotal=0, goodslices=0;
    int32_t ixindex=0, newbadixcount=0, k=0, fillednumber=0, i=0;
    int32_t badpixels=0;
    int32_t ifibreixtotlimit=0;
    flames_err status=0;
    int32_t *newfibres=0;
    int32_t newnumfibres=0;
    double decentSNR2=0;
    double dbuffer=0;
    int32_t cleaniters=0;
    frame_data pixelvalue=0;
    frame_data pixelsigma=0;
    frame_data fdmaxsinglepixelfrac=0;

    int32_t iyixend=0;
    int32_t iyixindex=0;
    int32_t iorderifibreindex=0;
    int32_t iorderifibreixindex=0;
    int32_t ifibreixindex=0;
    int32_t *lvecbuf1=0;


    frame_data *fdvecbuf1=0;
    frame_data *fdvecbuf2=0;
    frame_data *fdvecbuf3=0;

    frame_data *fdvecbuf5=0;
    frame_data *fdvecbuf6=0;
    frame_mask *fmvecbuf1=0;
    frame_mask *fmvecbuf2=0;
    frame_mask *fmvecbuf3=0;


    int actvals=0;
    char drs_verbosity[10];
    char drs_id[20];

    int mid_stat=0;

    memset(drs_verbosity, 0, 10);
    memset(drs_id, 0, 20);
    strcpy(drs_id,"fillholes");


#if FLAMES_DEBUG
    {int i, j;
    for (j = 0; j < 2; j++)
        for (i = 0; i <=4; i++) {
            fprintf(stderr, "%d %d %d %d\n", i,
                            allflatsin->flatdata[j].data[0],
                            allflatsin->flatdata[j].sigma[0],
                            allflatsin->flatdata[j].badpixel[0]);
            //                      allflatsout->flatdata[j].data[0],
            //                      allflatsout->flatdata[j].sigma[0],
            //                      allflatsout->flatdata[j].badpixel[0]);

            fprintf(stderr, "%d %f %f %d\n", i,
                    allflatsin->flatdata[j].data[0][i*i*i*i],
                    allflatsin->flatdata[j].sigma[0][i*i*i*i],
                    allflatsin->flatdata[j].badpixel[0][i*i*i*i]);
            //                      allflatsout->flatdata[j].data[0][i*i*i*i],
            //                      allflatsout->flatdata[j].sigma[0][i*i*i*i],
            //                      allflatsout->flatdata[j].badpixel[0][i*i*i*i]);
        }
    }
#endif

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

    memset(output, 0, CATREC_LEN+1);

    /* since it happens to have almost null fibre values on unmasked bad
     columns, try to avoid them */
    decentSNR2=decentSNR*decentSNR;

    fdmaxsinglepixelfrac = (frame_data) maxsinglepixelfrac;

    fitdata.availpixels=0;
    fitdata.offset = calloc((size_t) 8, sizeof(double));
    fitdata.value = calloc((size_t) 8, sizeof(double));
    fitdata.sigma = calloc((size_t) 8, sizeof(double));
    for (i=0; i<=7; i++) {
        fitdata.offset[i]=0;
        fitdata.value[i]=0;
        fitdata.sigma[i]=0;
        normdata[i].normfactor=0;
        normdata[i].normsigma=0;
        normdata[i].goodoverlap=0;
    }

    SCTPUT("Initialising internal structures...");

    /* allocate the local shiftdata array of structures */
    shiftdata =
                    (shiftstruct **) calloc((size_t)(ordpos->lastorder+1-ordpos->firstorder),
                                    sizeof(shiftstruct*));
    shiftdata[0] =
                    (shiftstruct *) calloc((size_t)(allflatsin->subcols*
                                    (ordpos->lastorder+1-ordpos->firstorder)),
                                    sizeof(shiftstruct));
    for (i=1; i<=ordpos->lastorder-ordpos->firstorder; i++)
        shiftdata[i] = shiftdata[i-1]+allflatsin->subcols;
    for (i=0; i<=ordpos->lastorder-ordpos->firstorder; i++) {
        shiftbuffer = shiftdata[i];
        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
            shiftbufferix = shiftbuffer+ix;
            shiftbufferix->ixoffsets = calloc((size_t) 8, sizeof(int32_t));
            shiftbufferix->yfracoffsets = calloc((size_t) 8, sizeof(double));
            shiftbufferix->yintoffsets = calloc((size_t) 8, sizeof(int32_t));
            shiftbufferix->normfactor = calloc((size_t) 8, sizeof(double));
            shiftbufferix->normsigma = calloc((size_t) 8, sizeof(double));
            shiftbufferix->goodoverlap = calloc((size_t) 8, sizeof(double));
        }
    }


    /* compute the halfibrewidth in pixel units */
    phalfibrewidth = (allflatsin->halfibrewidth)/(allflatsin->substepy);
    ifibreixtotlimit = (allflatsin->maxfibres*allflatsin->subcols)-1;
    /* begin looping over orders at first */
    for (iorder=0; iorder <= ((ordpos->lastorder)-(ordpos->firstorder));
                    iorder++) {
        double order = (double) (iorder+(ordpos->firstorder));
        shiftbuffer = shiftdata[iorder];
        /* loop over x... */
        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
            shiftbufferix = shiftbuffer+ix;
            /* convert the ix pixel coordinate to the x world coordinate */
            x = allflatsin->substartx+(allflatsin->substepx)*((double) ix);
            /* find the unshifted central position and slope of this order at this x */
            /* bail out if the function call return an error status */
            if ((status = get_ordpos(ordpos, order, x, &ordercentre))!=NOERR) {
                free(shiftdata);
                free(fitdata.offset);
                free(fitdata.sigma);
                free(fitdata.value);
                return(status);
            }
            shiftbufferix->ordercentre = ordercentre;
            if ((status = get_ordslope(ordpos, order, x, &orderslope))!=NOERR) {
                free(shiftdata);
                free(fitdata.offset);
                free(fitdata.sigma);
                free(fitdata.value);
                return(status);
            }
            shiftbufferix->orderslope = orderslope;
            /* compute the pixel coordinates of the pixels to be used for interpolation */
        }
        /* calcfillshifts depends on all the shiftdata stuff to have been
       properly initialised already, therefore it needs to rune in a separate
       loop over ix */
        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
            if ((status=calcfillshifts(allflatsin, shiftbuffer, ix))
                            != NOERR) {
                free(shiftdata);
                free(fitdata.offset);
                free(fitdata.sigma);
                free(fitdata.value);
                return(status);
            }
        }
        /* since we are at it, completely clean up normfactors and normsigmas */
        fdvecbuf1 = allflatsin->normfactors[iorder][0];
        fdvecbuf2 = allflatsin->normsigmas[iorder][0];
        for (ix=0; ix<=ifibreixtotlimit; ix++) {
            fdvecbuf1[ix] = 0;
            fdvecbuf2[ix] = 0;
        }
        /* loop over FF frames */
        for (iframe=0; iframe<=allflatsin->nflats-1;iframe++) {
            /* loop over lit fibres in this frame */
            for (lfibre=0; lfibre<=((allflatsin->flatdata)[iframe]).numfibres-1;
                            lfibre++) {
                ifibre = (((allflatsin->flatdata)[iframe]).fibres)[lfibre];
                /* loop over ix... */
                for (ix=0; ix<=(allflatsin->subcols-1); ix++){
                    /* find this fibre centre and boundaries */
                    if ((status=locatefillfibre(allflatsin, ordpos, shiftbuffer,
                                    iorder, ifibre, ix)) != NOERR) {
                    	free(shiftdata);
                    	free(fitdata.offset);
                        free(fitdata.sigma);
                    	free(fitdata.value);
                        return(status);
                    }
                }
            }
        }
    }

    /* split the order loop in two parts, so that we can fit and subtract the
     background from fibre FF frames */

    SCTPUT("Background fitting and subtraction starting...");

    /* background fitting and subtraction section starts here */
    framebuffer = calloc(1, sizeof(flames_frame));
    framebuffer->subrows = allflatsin->subrows;
    framebuffer->subcols = allflatsin->subcols;
    framebuffer->substepx = allflatsin->substepx;
    framebuffer->substepy = allflatsin->substepy;
    framebuffer->substartx = allflatsin->substartx;
    framebuffer->substarty = allflatsin->substarty;
    framebuffer->nflats = 0;
    framebuffer->maxfibres = allflatsin->maxfibres;
    framebuffer->fibremask = cvector(0, framebuffer->maxfibres-1);
    iyixend = (allflatsin->subrows*allflatsin->subcols)-1;
    /* allocate and initialise the frame which will contain the
     estimated background */
    backframe = fdmatrix(0, framebuffer->subrows-1, 0, framebuffer->subcols-1);
    memset(backframe[0], 0,
           framebuffer->subrows*framebuffer->subcols*sizeof(frame_data));
    //uves_msg_debug("process frame %s",allflatsin->flatdata[iframe].framename);
    for (iframe=0; iframe<=allflatsin->nflats-1;iframe++) {
        /* build the fibremask for the framebuffer */
        for (ifibre=0; ifibre<=framebuffer->maxfibres-1; ifibre++)
            framebuffer->fibremask[ifibre]=FALSE;
        for (lfibre=0; lfibre<=allflatsin->flatdata[iframe].numfibres-1; lfibre++)
            framebuffer->fibremask[allflatsin->flatdata[iframe].fibres[lfibre]]=TRUE;
        /* assign pointers to the frame data, sigma and badpixel masks */
        framebuffer->frame_array = allflatsin->flatdata[iframe].data;
        framebuffer->frame_sigma = allflatsin->flatdata[iframe].sigma;
        framebuffer->badpixel = allflatsin->flatdata[iframe].badpixel;
        /* read in the background table */
        if ((status=readback(&(framebuffer->back), backname, bxdegree, bydegree))
                        != NOERR) {
            /* something went wrong while reading the background table */
            SCTPUT("Error while reading the background table");
            free(fitdata.offset);
            free(fitdata.sigma);
            free(fitdata.value);
            return flames_midas_fail();
        }
        if (framebuffer->back.Window_Number > 0) {
            if (scatter(framebuffer, ordpos, bkgswitch, bkgswitch2, badwinxsize,
                            badwinysize, badfracthres, badtotthres, kappa2,
                            maxbackiters, maxdiscardfract, OUTPUTI)) {
                SCTPUT("Error executing the scatter function");
                free(fitdata.offset);
                free(fitdata.sigma);
                free(fitdata.value);
                return flames_midas_fail();
            }
            /* compute the estimated background */
            if (computeback(framebuffer, backframe) != NOERR) {
                SCTPUT("Error computing fitted background");
                free(fitdata.offset);
                free(fitdata.sigma);
                free(fitdata.value);
                return flames_midas_fail();
            }
            if (freeback(&(framebuffer->back)) != NOERR) {
                SCTPUT("Error freeing framebuffer->back");
                free(fitdata.offset);
                free(fitdata.sigma);
                free(fitdata.value);
                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 fibre FF frame\n");
            fdvecbuf1 = framebuffer->frame_array[0];
            fdvecbuf2 = backframe[0];

#if FLAMES_DEBUG
            {int i;
            for (i = 0; i <= 10; i++) {
                fprintf(stderr, "backsub %d %d %f %f %f\n", __LINE__, i,
                                fdvecbuf1[i*i*i*i],
                                fdvecbuf2[i*i*i*i],
                                framebuffer->frame_sigma[0][i*i*i*i]);
            }
            }
#endif



            for (iyixindex=0; iyixindex<=iyixend; iyixindex++) {
                fdvecbuf1[iyixindex] -= fdvecbuf2[iyixindex];
            }
            /* 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 compatible with zero,
	       set that pixel to zero, otherwise mark that pixel as bad */
            fmvecbuf1 = framebuffer->badpixel[0];
            fdvecbuf1 = framebuffer->frame_array[0];
            fdvecbuf2 = framebuffer->frame_sigma[0];
            for (iyixindex=0; iyixindex<=iyixend; iyixindex++) {
                if (fmvecbuf1[iyixindex]==0 && (pixelvalue=fdvecbuf1[iyixindex])<0) {
                    if ((pixelvalue*pixelvalue)<4*(fdvecbuf2[iyixindex])) {
                        fdvecbuf1[iyixindex]=0;
                    }
                    else {
                        fmvecbuf1[iyixindex]=1;
                    }
                }
            }
            /*
	      for (ifibre=0; ifibre<=framebuffer->maxfibres-1; ifibre++) {
	      framebuffer->fibremask[ifibre] = ordpos->fibremask[ifibre];
	}
             */
        }
        else {
            SCTPUT("Error: no regions available for background estimation");
            free(fitdata.offset);
            free(fitdata.sigma);
            free(fitdata.value);
            return flames_midas_fail();
        }
    }



#if FLAMES_DEBUG
    {int i, j;
    for (j = 0; j < 3; j++)
        for (i = 0; i <= 1000; i += 10) {
            fprintf(stderr, "threshold done: %d %d %f %f %d\n", __LINE__, i,
                            allflatsin->flatdata[j].data[0][i*i],
                            allflatsin->flatdata[j].sigma[0][i*i],
                            allflatsin->flatdata[j].badpixel[0][i*i]);
            //                      allflatsout->flatdata[j].data[0][i*i],
            //                      allflatsout->flatdata[j].sigma[0][i*i],
            //                      allflatsout->flatdata[j].badpixel[0][i*i]);
        }
    }
#endif





    /* now allocate the Slit_FF structure, we'll be using it from now on */
    slitflats = (allslitflats *) calloc(1, sizeof(allslitflats));
    if ((status = readslitflats(slitsname, slitflats)) != NOERR) {
        /* problems reading slitflats members from disk */
        SCTPUT("Error while reading the slit Flat Field frames");
        free(fitdata.offset);
        free(fitdata.sigma);
        free(fitdata.value);
        return flames_midas_fail();
    }
    /* uncorrect for the previous ycorrection, if present */
    if (ordpos->corrected=='t') {
        for (iframe=0; iframe<=(slitflats->nflats-1);iframe++)
            slitflats->slit[iframe].yshift -= ordpos->ycorrection;
    }
    for (iframe=0; iframe<=allflatsin->nflats-1;iframe++) {
        /* build the fibremask for the framebuffer */
        for (ifibre=0; ifibre<=framebuffer->maxfibres-1; ifibre++)
            framebuffer->fibremask[ifibre]=FALSE;
        for (lfibre=0; lfibre<=allflatsin->flatdata[iframe].numfibres-1; lfibre++)
            framebuffer->fibremask[allflatsin->flatdata[iframe].fibres[lfibre]]=TRUE;
        /* assign pointers to the frame data, sigma and badpixel masks */
        framebuffer->frame_array = allflatsin->flatdata[iframe].data;
        framebuffer->frame_sigma = allflatsin->flatdata[iframe].sigma;
        framebuffer->badpixel = allflatsin->flatdata[iframe].badpixel;
        /* divide the resulting frame by the slit FF */
        sprintf(output, "divide fibre FF frame %d by slit FF\n", iframe+1);
        SCTPUT(output);


#if FLAMES_DEBUG
        {int i, j;
        for (j = 0; j < 3; j++)
            for (i = 0; i <= 1000; i += 10) {
                fprintf(stderr, "before divide: %d %d %f %f %d\n", __LINE__, i,
                                allflatsin->flatdata[j].data[0][i*i],
                                allflatsin->flatdata[j].sigma[0][i*i],
                                allflatsin->flatdata[j].badpixel[0][i*i]);
                //                      allflatsout->flatdata[j].data[0][i*i],
                //                      allflatsout->flatdata[j].sigma[0][i*i],
                //                      allflatsout->flatdata[j].badpixel[0][i*i]);
            }
        }
#endif        



        if (slitdivide(slitflats, ordpos, framebuffer, framebuffer)!=NOERR) {
            /* something went wrong in slitdivide */
            SCTPUT("Error while dividing the Science Frame by the slit frame(s)");
            free(fitdata.offset);
            free(fitdata.sigma);
            free(fitdata.value);
            return flames_midas_fail();
        }


#if FLAMES_DEBUG
        {int i, j;
        for (j = 0; j < 3; j++)
            for (i = 0; i <= 1000; i += 10) {
                fprintf(stderr, "after divide: %d %d %f %f %d\n", __LINE__, i,
                                allflatsin->flatdata[j].data[0][i*i],
                                allflatsin->flatdata[j].sigma[0][i*i],
                                allflatsin->flatdata[j].badpixel[0][i*i]);
                //                      allflatsout->flatdata[j].data[0][i*i],
                //                      allflatsout->flatdata[j].sigma[0][i*i],
                //                      allflatsout->flatdata[j].badpixel[0][i*i]);
            }
        }
#endif

    }
    /* free the slit flats */
    if (freeslitflats(slitflats)!=NOERR) {
        SCTPUT("Error while freeing the memory for the Slit_FF structure\n");
        free(fitdata.offset);
        free(fitdata.sigma);
        free(fitdata.value);
        return flames_midas_fail();
    }
    free(slitflats);
    /* free the background frame */
    free_fdmatrix(backframe, 0, framebuffer->subrows-1, 0,
                  framebuffer->subcols-1);
    /* free the framebuffer */
    free_cvector(framebuffer->fibremask, 0, framebuffer->maxfibres-1);
    free(framebuffer);

    SCTPUT("Background fitting and subtraction done");


#if FLAMES_DEBUG
    {int i, j;
    for (j = 0; j < 3; j++)
        for (i = 0; i <= 1000; i += 10) {
            fprintf(stderr, "backsub done: %d %d %f %f %d\n", __LINE__, i,
                            allflatsin->flatdata[j].data[0][i*i],
                            allflatsin->flatdata[j].sigma[0][i*i],
                            allflatsin->flatdata[j].badpixel[0][i*i]);
            //                      allflatsout->flatdata[j].data[0][i*i],
            //                      allflatsout->flatdata[j].sigma[0][i*i],
            //                      allflatsout->flatdata[j].badpixel[0][i*i]);
        }
    }
#endif

    /* allocate and clone from allflatsin the local allflatsout structure */
    allflatsout = (allflats *) calloc(1, sizeof(allflats));
    if ((status = cloneallflats(allflatsin, allflatsout)) != NOERR) {
    	free(fitdata.offset);
    	free(fitdata.sigma);
    	free(fitdata.value);
        return(status);
    }

    SCTPUT("Cleaning stage started...");

    /* allocate the local badifibre array of structures and badixstruct
     arrays therein */
    badifibre = (badifibrestruct *)
                        calloc((size_t)(allflatsin->maxfibres), sizeof(badifibrestruct));
    for (ifibre=0; ifibre<=allflatsin->maxfibres-1; ifibre++) {
        badifibre[ifibre].badixs = (badixstruct *)
                          calloc((size_t)(allflatsin->subcols), sizeof(badixstruct));
    }



#if FLAMES_DEBUG
    {int i;
    for (i = 0; i < 10; i++) {
        fprintf(stderr, "%d %f %f %d\n", i,
                        allflatsin->flatdata[0].data[0][i*i*i*i],
                        allflatsin->flatdata[0].sigma[0][i*i*i*i],
                        allflatsin->flatdata[0].badpixel[0][i*i*i*i]);
        //                        allflatsout->flatdata[0].data[0][i*i*i*i],
        //                        allflatsout->flatdata[0].sigma[0][i*i*i*i],
        //                        allflatsout->flatdata[0].badpixel[0][i*i*i*i]);
    }
    }
#endif


    /* begin looping over orders at first */
    for (iorder=0; iorder <= ((ordpos->lastorder)-(ordpos->firstorder));
                    iorder++) {
        if ( strcmp(drs_verbosity,"LOW") == 0 ){
        } else {
            sprintf(output, "First cleaning step, order %d", iorder+1);
            SCTPUT(output);
        }
        shiftbuffer = shiftdata[iorder];
        lvecbuf1 = allflatsin->lowfibrebounds[iorder][0];
        int32_t* lvecbuf2 = allflatsin->highfibrebounds[iorder][0];
        frame_data* fdvecbuf3 = allflatsin->normfactors[iorder][0];
        frame_data* fdvecbuf4 = allflatsin->normsigmas[iorder][0];
        fmvecbuf1 = allflatsin->goodfibres[iorder][0];
        /* loop over FF frames */
        for (iframe=0; iframe<=allflatsin->nflats-1;iframe++) {
            fdvecbuf1 = allflatsout->flatdata[iframe].data[0];
            fdvecbuf2 = allflatsout->flatdata[iframe].sigma[0];
            fmvecbuf2 = allflatsout->flatdata[iframe].badpixel[0];
            fmvecbuf3 = allflatsin->flatdata[iframe].badpixel[0];
            badtotal = 0;
            /* loop over lit fibres in this frame */
            for (lfibre=0; lfibre<=((allflatsin->flatdata)[iframe]).numfibres-1;
                            lfibre++) {
                ifibre = (((allflatsin->flatdata)[iframe]).fibres)[lfibre];
                iorderifibreindex = (iorder*allflatsin->maxfibres)+ifibre;
                mybadifibre = badifibre+ifibre;
                mybadifibre->badixcount = 0;
                mybadifibre->firstbadixindex = 0;
                /* loop over ix... */
                for (ix=0; ix<=(allflatsin->subcols-1); ix++){
                    ifibreixindex = (ifibre*allflatsin->subcols)+ix;
                    /* initialise data structures */
                    if (fmvecbuf1[ifibreixindex]==GOODSLICE) {
                        if ((status=initfillfibre(allflatsin, iorder, iframe, ifibre, ix,
                                        badifibre, &badtotal)) != NOERR){
                        	free(fitdata.offset);
                        	free(fitdata.sigma);
                        	free(fitdata.value);
                            return(status);
                        }
                    }
                }
            }

            /* do the cleansing here, within the same order loop, to reduce the
	       required sizes of temporary variables, in this way I need to keep
	       only one order at a time in memory */
            /* keep looping until we cleaned it all or we were unable to clean any further */
            oldbadtotal = badtotal+1;
            for (cleaniters=1; (cleaniters<=maxcleaniters) && (badtotal>0) &&
            (badtotal<oldbadtotal) ; cleaniters++) {
                oldbadtotal = badtotal;
                /* loop over lit fibres in this frame */
                for (lfibre=0; lfibre<=((allflatsin->flatdata)[iframe]).numfibres-1;
                                lfibre++) {
                    ifibre = (((allflatsin->flatdata)[iframe]).fibres)[lfibre];
                    iorderifibreindex = (iorder*allflatsin->maxfibres)+ifibre;
                    mybadifibre = badifibre+ifibre;
                    /* any bad ix's on this fibre? */
                    if (mybadifibre->badixcount> 0) {
                        ixindex =  mybadifibre->firstbadixindex;
                        mybadixs = mybadifibre->badixs+ixindex;
                        newbadixcount = mybadifibre->badixcount;
                        for (k=0; k<=mybadifibre->badixcount-1; k++) {
                            ix = mybadixs->badix;
                            shiftbufferix = shiftbuffer+ix;
                            /* is this fibre good at all at this ix, and do we have any shifts to use? */
                            if (shiftbufferix->numoffsets>0) {
                                /* it seems good enough, go ahead, calculate normalisation
		               factors and locate bad pixels in this slice */
                                if ((status =
                                                fillnormfactors(allflatsin, shiftbuffer, badifibre,
                                                                iorder, iframe, ifibre, ix, ixindex,
                                                                normdata)) != NOERR) {
                                	free(fitdata.offset);
                                	free(fitdata.sigma);
                                	free(fitdata.value);
                                    return(status);
                                }
                                /* now we have normalisation factors and we know which bad
		               pixels to correct */
                                /* run on the list of pixels to correct */
                                fillednumber = 0;
                                for (i=0; i<=(mybadixs->badiycount-1); i++) {
                                    iy = mybadixs->badiy[i];
                                    iyixindex = (allflatsin->subcols*iy)+ix;
                                    /* build the list of pixels to use for interpolation */
                                    if ((status =
                                                    selectfillavail(allflatsin, shiftbuffer,
                                                                    normdata, &fitdata, iorder, iframe,
                                                                    ix, iy)) != NOERR) {
                                    	free(fitdata.offset);
                                    	free(fitdata.sigma);
                                    	free(fitdata.value);
                                        return(status);
                                    }
                                    /* Do the interpolation (if possible) and put interpolated
		                 data back in frames. While data and sigmas are put directly in the frames
		                 contained in allflatsin, the badpixel mask pixels are
		                 cleaned in a separate temporary frame; in this way,
		                 filled pixels can be used for more interpolation only
		                 starting from the next cleansing pass. I want to avoid
		                 the possibility to find different interpolated values
		                 depending on the order in which pixels are filled. */
                                    if ((status =
                                                    dointerpolate(allflatsout, &fitdata, iorder, iframe,
                                                                    ifibre, ix, iy)) !=NOERR) {
                                    	free(fitdata.offset);
                                    	free(fitdata.sigma);
                                    	free(fitdata.value);
                                        return(status);
                                    }
                                    /* was the correction successful? */
                                    if (fmvecbuf2[iyixindex] == 0) {
                                        /* negative values may wreak havoc in iterative
		                   interpolations, i.e. other pixels interpolated
		                   using this value, therefore clip them */
                                        if ((pixelvalue = fdvecbuf1[iyixindex])<0) {
                                            if ((pixelvalue*pixelvalue)>(4*fdvecbuf2[iyixindex])) {
                                                pixelsigma = (frame_data)
			                      pow(fdvecbuf2[iyixindex],.5);

                                                if ( strcmp(drs_verbosity,"LOW") == 0 ){
                                                } else {
                                                    sprintf(output, "%s", drs_id);
                                                    SCTPUT(output);
                                                    SCTPUT("Warning: interpolated large negative value:");
                                                    sprintf(output, "pixel=%g and sigma=%g at x=%d, \
y=%d", pixelvalue, pixelsigma, ix+1, iy+1);
                                                    SCTPUT(output);
                                                    SCTPUT("marking it bad");
                                                }
                                                fdvecbuf2[iyixindex] = pixelvalue*pixelvalue;
                                                fdvecbuf1[iyixindex] = 0;
                                                fmvecbuf2[iyixindex] = 1;
                                            }
                                            else {
                                                /* we are within error, just clip it silently */
                                                fdvecbuf1[iyixindex] = 0;
                                            }
                                        }
                                        /* increase the number of successfully corrected badpixels */
                                        fillednumber++;
                                        badtotal--;
                                    }
                                }
                                /* free dynamic temporary arrays */
                                if (mybadixs->badiy!=0) {
                                    free(mybadixs->badiy);
                                    mybadixs->badiy=0;
                                }
                                /* did we fill all bad pixels in this ix slice? */
                                if (fillednumber == mybadixs->badiycount) {
                                    /* yes, we did: take this ix out of the list of the ones containing bad pixels */
                                    newbadixcount--;
                                    /* set up pointers to prev and next ixindex */
                                    /* is this the first ixindex in the list? */
                                    if (ixindex == mybadifibre->firstbadixindex) {
                                        /* there is no ixindex before this, change firstbadindex instead */
                                        mybadifibre->firstbadixindex =
                                                        mybadixs->nextbadindex;
                                    }
                                    else {
                                        mybadifibre->badixs[mybadixs->prevbadindex].nextbadindex =
                                                        mybadixs->nextbadindex;
                                    }
                                    /* is this the last ixindex in the list? */
                                    if (k != mybadifibre->badixcount-1) {
                                        /* this is not the last one */
                                        mybadifibre->badixs[mybadixs->nextbadindex].prevbadindex =
                                                        mybadixs->prevbadindex;
                                    }
                                }
                            }
                            /* fetch the next ix with bad pixels in the list */
                            ixindex = mybadixs->nextbadindex;
                            mybadixs = mybadifibre->badixs+ixindex;
                        }
                        /* hopefully some ixs have been removed from the list, hence update the counter */
                        mybadifibre->badixcount = newbadixcount;
                        /* update the badpixel mask in allflatsin with corrected pixels */
                        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
                            ifibreixindex = (ifibre*allflatsin->subcols)+ix;
                            for (iy=lvecbuf1[ifibreixindex]; iy<=lvecbuf2[ifibreixindex];
                                            iy++) {
                                fmvecbuf3[iyixindex] = fmvecbuf2[iyixindex];
                            }
                        }
                    }
                }
            }
        }

#if FLAMES_DEBUG
        {int i;
        for (i = 0; i < 10; i++) {
            fprintf(stderr, "%d %f %f %d\n", i,
                            allflatsin->flatdata[0].data[0][i*i*i*i],
                            allflatsin->flatdata[0].sigma[0][i*i*i*i],
                            allflatsin->flatdata[0].badpixel[0][i*i*i*i]);
            //                        allflatsout->flatdata[0].data[0][i*i*i*i],
            //                        allflatsout->flatdata[0].sigma[0][i*i*i*i],
            //                        allflatsout->flatdata[0].badpixel[0][i*i*i*i]);
        }
        }
#endif

        /* we still have to normalise to 1 the integral over y of each
       order/fibre/x of the fibre FF frames */
        /* loop over x... */
        if ( strcmp(drs_verbosity,"LOW") == 0 ) {
        } else {
            sprintf(output, "Fibre normalisation step, order %d", iorder+1);
            SCTPUT(output);
        }
        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
            shiftbufferix = shiftbuffer+ix;
            /* loop over FF frames */
            for (iframe=0; iframe<=allflatsin->nflats-1;iframe++) {
                fdvecbuf1 = allflatsin->flatdata[iframe].data[0];
                fdvecbuf2 = allflatsin->flatdata[iframe].sigma[0];
                fmvecbuf2 = allflatsin->flatdata[iframe].badpixel[0];
                /* loop over lit fibres in this frame */
                for (lfibre=0; lfibre<=((allflatsin->flatdata)[iframe]).numfibres-1;
                                lfibre++) {
                    ifibre = (((allflatsin->flatdata)[iframe]).fibres)[lfibre];
                    ifibreixindex = (ifibre*allflatsin->subcols)+ix;
                    /* was this ix/order/fibre marked good altogether? otherwise skip
	     it */
                    if (fmvecbuf1[ifibreixindex] == GOODSLICE) {
                        /* try to normalise it */
                        normfactor = 0;
                        normsigma = 0;
                        badpixels = 0;
                        /* compute the fibre centre in pixel coordinates */
                        pfibrecentre =
                                        (shiftbufferix->ordercentre+ordpos->fibrepos[ifibre] -
                                                        allflatsin->substarty)/(allflatsin->substepy);
                        /* compute the precise integration limits in pixel coordinates */
                        plowlimit = pfibrecentre-phalfibrewidth;
                        phighlimit = pfibrecentre+phalfibrewidth;
                        /* loop over pixels belonging to the shifted fibre, only if
	             ishiftedyup>=ishiftedydown */
                        for (iy=lvecbuf1[ifibreixindex]; iy<=lvecbuf2[ifibreixindex];
                                        iy++) {
                            /* check that the pixel is not out of boundaries (should never happen) */
                            if ((iy<(phighlimit+0.5)) && (iy>(plowlimit-0.5))) {
                                /* not outside limits */
                                iyixindex = (iy*allflatsin->subcols)+ix;
                                fraction = 1;
                                if (iy<(plowlimit+0.5)) {
                                    /* close to lower limit, part of the pixel is outside */
                                    fraction -= plowlimit+0.5-(double)iy;
                                }
                                if (iy>(phighlimit-0.5)) {
                                    /* close to higher limit, part of the pixel is outside */
                                    fraction -= (double)iy-phighlimit+0.5;
                                }
                                /* check if this is a good pixel */
                                if (fmvecbuf2[iyixindex] == 0) {
                                    normfactor += fraction*fdvecbuf1[iyixindex];
                                    normsigma += (fraction*fraction)*fdvecbuf2[iyixindex];
                                }
                                else {
                                    /* still an uncorrected bad pixel in this ix slice of this fibre/order */
                                    badpixels++;
                                }
                            }
                        }
                        /* ok, now we either have a normalisation factor or found
	             hopelessly bad pixels */
                        normfactor2 = normfactor*normfactor;
                        if ((badpixels == 0) &&
                                        ((normfactor2/normsigma)>=decentSNR2)) {
                            /* do normalise this ix slice */
                            for (iy=lvecbuf1[ifibreixindex];
                                            iy<=lvecbuf2[ifibreixindex];
                                            iy++) {
                                iyixindex = (iy*allflatsin->subcols)+ix;
                                /* no pixel ought to be a too large fraction of the integral,
		               if we find any mark them bad (and the slice along with them */
                                if (fdvecbuf1[iyixindex] >
                                (frame_data)(maxsinglepixelfrac*normfactor)) {
                                    /* kill it */
                                    fmvecbuf2[iyixindex] = 1;
                                    badpixels++;
                                }
                                else {
                                    /* propagate sigma to the normalised pixel */
                                    dbuffer = (double)fdvecbuf1[iyixindex]/normfactor2;
                                    fdvecbuf2[iyixindex] =
                                                    fdvecbuf2[iyixindex]/(frame_data)normfactor2 +
                                                    (frame_data)(normsigma*dbuffer*dbuffer);
                                    /* normalise pixel */
                                    fdvecbuf1[iyixindex] /= (frame_data)normfactor;
                                }
                            }
                            fdvecbuf3[ifibreixindex] = (frame_data)normfactor;
                            fdvecbuf4[ifibreixindex] = (frame_data)normsigma;
                            if (badpixels != 0) {
                                /* we found a spike, kill the slice */
                                fmvecbuf1[ifibreixindex] = BADSLICE;
                                /* zero normfactors and normsigmas to make purify happy */
                                fdvecbuf3[ifibreixindex] = 0;
                                fdvecbuf4[ifibreixindex] = 0;
                                for (iy=lvecbuf1[ifibreixindex];
                                                iy<=lvecbuf2[ifibreixindex];
                                                iy++) {
                                    iyixindex = (iy*allflatsin->subcols)+ix;
                                    fdvecbuf1[iyixindex] = 0;
                                    fdvecbuf2[iyixindex] = allflatsin->gain*allflatsin->ron;
                                    fmvecbuf2[iyixindex] = 1;
                                }
                            }
                        }
                        else {
                            /* still badpixels: mark this ix/fibre/order as half bad */
                            fmvecbuf1[ifibreixindex] = BADSLICE;
                            /* zero normfactors and normsigmas to make purify happy */
                            fdvecbuf3[ifibreixindex] = 0;
                            fdvecbuf4[ifibreixindex] = 0;
                            for (iy=lvecbuf1[ifibreixindex];
                                            iy<=lvecbuf2[ifibreixindex];
                                            iy++) {
                                iyixindex = (iy*allflatsin->subcols)+ix;
                                fdvecbuf1[iyixindex] = 0;
                                fdvecbuf2[iyixindex] = allflatsin->gain*allflatsin->ron;
                                fmvecbuf2[iyixindex] = 1;
                            }
                        }
                    }
                    else {
                        /* this is a bad slice, zero it just in case */
                        for (iy=lvecbuf1[ifibreixindex];
                                        iy<=lvecbuf2[ifibreixindex];
                                        iy++) {
                            iyixindex = (iy*allflatsin->subcols)+ix;
                            fdvecbuf1[iyixindex] = 0;
                            fdvecbuf2[iyixindex] = allflatsin->gain*allflatsin->ron;
                            fmvecbuf2[iyixindex] = 1;
                        }
                        fdvecbuf3[ifibreixindex] = 0;
                        fdvecbuf4[ifibreixindex] = 0;
                    }
                }
            }
        }


        /* give up trying to clean normalisation factors, just try to
       give meaningful normalised values to remaining bad slices */
        /* loop over FF frames */
        if ( strcmp(drs_verbosity,"LOW") == 0 ){
        } else {
            sprintf(output, "Final cleaning step, order %d", iorder+1);
            SCTPUT(output);
        }
        for (iframe=0; iframe<=allflatsin->nflats-1;iframe++) {
            fdvecbuf1 = allflatsin->flatdata[iframe].data[0];
            fdvecbuf2 = allflatsin->flatdata[iframe].sigma[0];
            fmvecbuf2 = allflatsin->flatdata[iframe].badpixel[0];
            fdvecbuf5 = allflatsout->flatdata[iframe].data[0];
            fdvecbuf6 = allflatsout->flatdata[iframe].sigma[0];
            fmvecbuf3 = allflatsout->flatdata[iframe].badpixel[0];

#if FLAMES_DEBUG
            {int i;
            for (i = 0; i < 10; i++) {
                fprintf(stderr, "%d %f %f %d %f %f %d\n", i,
                                allflatsin->flatdata[iframe].data[0][i*i*i*i],
                                allflatsin->flatdata[iframe].sigma[0][i*i*i*i],
                                allflatsin->flatdata[iframe].badpixel[0][i*i*i*i],
                                allflatsout->flatdata[iframe].data[0][i*i*i*i],
                                allflatsout->flatdata[iframe].sigma[0][i*i*i*i],
                                allflatsout->flatdata[iframe].badpixel[0][i*i*i*i]);
            }
            }
#endif

            /* loop over lit fibres in this frame */
            for (lfibre=0; lfibre<=((allflatsin->flatdata)[iframe]).numfibres-1;
                            lfibre++) {
                ifibre = (((allflatsin->flatdata)[iframe]).fibres)[lfibre];
                /* any bad slices on this fibre? */
                badtotal = 0;
                goodslices = 0;
                for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
                    ifibreixindex = (ifibre*allflatsin->subcols)+ix;
                    /* is this a bad slice? */
                    if (fmvecbuf1[ifibreixindex] != GOODSLICE) {
                        /* yes, it is */
                        /* add its pixels to the badtotal counter */
                        for (iy=lvecbuf1[ifibreixindex];
                                        iy<=lvecbuf2[ifibreixindex];
                                        iy++) {
                            badtotal++;
                        }
                    }
                    else {
                        /* this specific slice (order/fibre/x) is good, we may attempt to
	             correct something */
                        goodslices++;
                    }
                }

                if (goodslices>0) {
                    /* there is at least one good slice in this fibre/order, do start
	           the correction loop */
                    /* start the final filling loop */
                    oldbadtotal = badtotal+1;
                    while ((badtotal > 0) && (badtotal < oldbadtotal)) {
                        oldbadtotal = badtotal;
                        /* scan the pixels belonging to this fibre/order */
                        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
                            ifibreixindex = (ifibre*allflatsin->subcols)+ix;
                            for (iy=lvecbuf1[ifibreixindex];
                                            iy<=lvecbuf2[ifibreixindex];
                                            iy++) {
                                iyixindex = (iy*allflatsin->subcols)+ix;
                                /* should we attempt to correct this pixel? */
                                if (fmvecbuf2[iyixindex] != 0) {
                                    /* yes, do try */
                                    /* build the list of pixels to use for interpolation */
                                    /* use selectavail instead of selectfillavail, since
		                 we do not care any more for normalisation factors */
                                    if ((status=selectavail(allflatsin, shiftbuffer,
                                                    &fitdata, iorder, iframe, ix, iy))
                                                    != NOERR) {
                                        return(status);
                                    }
                                    /* Do the interpolation (if possible) and put interpolated
		                 data back in frames.
		                 While data and sigmas are put directly in the frames
		                 contained in allflatsin, the badpixel mask pixels are
		                 cleaned in a separate temporary frame; in this way,
		                 filled pixels can be used for more interpolation only
		                 starting from the next cleansing pass. I want to avoid
		                 the possibility to find different interpolated values
		                 depending on the order in which pixels are filled. */
                                    if ((status = dointerpolate(allflatsout, &fitdata, iorder,
                                                    iframe, ifibre, ix, iy))
                                                    !=NOERR) {
                                        return(status);
                                    }
                                    /* was the correction successful? */
                                    if (fmvecbuf3[iyixindex] == 0) {
                                        /* negative values and/or anomalously large values
		                   may wreak havoc in iterative interpolations, i.e.
		                   other pixels interpolated using this value, therefore clip them */
                                        if ((pixelvalue = fdvecbuf5[iyixindex])<0) {
                                            if ((pixelvalue*pixelvalue)>(4*fdvecbuf6[iyixindex])) {
                                                pixelsigma = (frame_data) pow(fdvecbuf6[iyixindex],.5);


                                                if ( strcmp(drs_verbosity,"LOW") == 0 ) {
                                                } else {
                                                    sprintf(output, "%s", drs_id);
                                                    SCTPUT(output);
                                                    SCTPUT("Warning: interpolated large negative value:");
                                                    sprintf(output, "pixel=%g and sigma=%g at x=%d, \
y=%d", pixelvalue, pixelsigma, ix+1, iy+1);
                                                    SCTPUT(output);
                                                    SCTPUT("marking it bad");
                                                }


                                                fdvecbuf6[iyixindex] = pixelvalue*pixelvalue;
                                                fdvecbuf5[iyixindex] = 0;
                                                fmvecbuf3[iyixindex] = 1;
                                            }
                                            else {
                                                /* we are within error, just clip it silently */
                                                fdvecbuf5[iyixindex] = 0;
                                            }
                                        }
                                        else if (pixelvalue>fdmaxsinglepixelfrac) {
                                            /* no sensible way to clip this, just kill it */
                                            pixelsigma = (frame_data) pow(fdvecbuf6[iyixindex],.5);


                                            if ( strcmp(drs_verbosity,"LOW") == 0 ) {
                                            } else {
                                                sprintf(output, "%s", drs_id);
                                                SCTPUT(output);
                                                SCTPUT("Warning: interpolated too large normalised \
value:");
                                                sprintf(output, "pixel=%g and sigma=%g at x=%d, \
y=%d", pixelvalue, pixelsigma, ix+1, iy+1);
                                                SCTPUT(output);
                                                SCTPUT("marking it bad");
                                            }

                                            fdvecbuf6[iyixindex] = pixelvalue*pixelvalue;
                                            fdvecbuf5[iyixindex] = 0;
                                            fmvecbuf3[iyixindex] = 1;
                                        }
                                        /* increase the number of successfully corrected
		       badpixels */
                                        badtotal--;
                                    }
                                }
                            }
                        }
                        /* update the badpixel mask in allflatsin with corrected pixels */
                        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
                            ifibreixindex = (ifibre*allflatsin->subcols)+ix;
                            for (iy=lvecbuf1[ifibreixindex];
                                            iy<=lvecbuf2[ifibreixindex];
                                            iy++) {
                                iyixindex = (iy*allflatsin->subcols)+ix;
                                fmvecbuf2[iyixindex] =
                                                fmvecbuf3[iyixindex];
                            }
                        }
                    }
                }
            }
        }


        /* compute the coverage over newly cleaned pixels, to see whether
       they may be labelled as half-good, i.e. good profile but no
       normalisation factor*/
        /* loop over x... */
        for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
            shiftbufferix = shiftbuffer+ix;
            /* loop over FF frames */
            for (iframe=0; iframe<=allflatsin->nflats-1;iframe++) {
                fdvecbuf1 = allflatsin->flatdata[iframe].data[0];
                fdvecbuf2 = allflatsin->flatdata[iframe].sigma[0];
                fmvecbuf2 = allflatsin->flatdata[iframe].badpixel[0];
                /* loop over lit fibres in this frame */
                for (lfibre=0; lfibre<=((allflatsin->flatdata)[iframe]).numfibres-1;
                                lfibre++) {
                    ifibre = (((allflatsin->flatdata)[iframe]).fibres)[lfibre];
                    ifibreixindex = (ifibre*allflatsin->subcols)+ix;
                    /* run this check only on slices that were marked bad before */
                    if (fmvecbuf1[ifibreixindex] != GOODSLICE) {
                        normfactor = 0;
                        /* compute the fibre centre in pixel coordinates */
                        pfibrecentre =
                                        (shiftbufferix->ordercentre+ordpos->fibrepos[ifibre] -
                                                        allflatsin->substarty)/(allflatsin->substepy);
                        /* compute the precise integration limits in pixel coordinates */
                        plowlimit = pfibrecentre-phalfibrewidth;
                        phighlimit = pfibrecentre+phalfibrewidth;
                        /* loop over pixels belonging to the shifted fibre, only if
	             ishiftedyup>=ishiftedydown */
                        for (iy=lvecbuf1[ifibreixindex];
                                        iy<=lvecbuf2[ifibreixindex];
                                        iy++) {
                            /* check that the pixel is not out of boundaries (should never happen) */
                            if ((iy<(phighlimit+0.5)) && (iy>(plowlimit-0.5))) {
                                /* not outside limits */
                                iyixindex = (iy*allflatsin->subcols)+ix;
                                fraction = 1;
                                if (iy<(plowlimit+0.5)) {
                                    /* close to lower limit, part of the pixel is outside */
                                    fraction -= plowlimit+0.5-(double)iy;
                                }
                                if (iy>(phighlimit-0.5)) {
                                    /* close to higher limit, part of the pixel is outside */
                                    fraction -= (double)iy-phighlimit+0.5;
                                }
                                /* check if this is a good pixel */
                                if (fmvecbuf2[iyixindex] == 0) {
                                    normfactor += fraction*fdvecbuf1[iyixindex];
                                }
                            }
                        }
                        /* ok, see if the "normalisation fraction" found exceeds the
	             the minimum required to try extracting it */
                        if (normfactor<allflatsin->minfibrefrac) {
                            /* this slice is completely hopeless, mark it accordingly */
                            fmvecbuf1[ifibreixindex] = BADSLICE;
                            for (iy=lvecbuf1[ifibreixindex];
                                            iy<=lvecbuf2[ifibreixindex];
                                            iy++) {
                                iyixindex = (iy*allflatsin->subcols)+ix;
                                fdvecbuf1[iyixindex] = 0;
                                fdvecbuf2[iyixindex] = allflatsin->gain*allflatsin->ron;
                                fmvecbuf2[iyixindex] = 1;
                            }
                        }
                        else {
                            /* this slice can be somewhat used yet, mark it half-good */
                            fmvecbuf1[ifibreixindex] = DEMISLICE;
                        }
                    }
                }
            }
        }
    }

    SCTPUT("Cleaning stage finished.");

    /* ok, now let's check whether there is some fibre which is nominally
     lit but which is actually broken or otherwise unlit */
    fmvecbuf1 = allflatsin->goodfibres[0][0];
    for (ifibre=0; ifibre<=(allflatsin->maxfibres-1); ifibre++) {
        if (allflatsin->fibremask[ifibre]==TRUE) {
            uves_msg_debug("fibre %d", ifibre);
            totslices = fracslices = 0;
            for (iorder=0; iorder<=(ordpos->lastorder-ordpos->firstorder);
                            iorder++) {
                iorderifibreindex = (iorder*allflatsin->maxfibres)+ifibre;
                for (ix=0; ix<=(allflatsin->subcols-1); ix++) {
                    iorderifibreixindex = (iorderifibreindex*allflatsin->subcols)+ix;
                    totslices++;
#if FLAMES_DEBUG
                    fprintf(stderr, "fmvecbuf1[%d] = %d %f %f",
                            iorderifibreixindex,
                            fmvecbuf1[iorderifibreixindex],
                            fracslices,
                            totslices);
#endif
                    if (fmvecbuf1[iorderifibreixindex] == GOODSLICE) {
                        /* there is at least one good slice for this fibre, keep it */
                        fracslices++;
                    }
                }
            }
            fracslices /= totslices;
            if (fracslices < fracslicesthres) {
                /* we were unable to find any good slice for this fibre, discard it */
                allflatsin->fibremask[ifibre] = FALSE;
                ordpos->fibremask[ifibre] = FALSE;
                sprintf(output, "%s", drs_id);
                SCTPUT(output);
                sprintf(output, "fracslices=%f Warning: ignoring fibre %d which has poor coverage",
                        fracslices,ifibre+1);
                SCTPUT(output);
            }
        }
    }

    /* reset the fibres and numfibres terms within allflatsin, they may have
     been changed */
    for (iframe=0; iframe<=(allflatsin->nflats-1); iframe++) {
        newnumfibres = 0;
        newfibres = lvector(0,allflatsin->maxfibres-1);
        for (lfibre=0; lfibre<=allflatsin->flatdata[iframe].numfibres-1; lfibre++){
            ifibre = allflatsin->flatdata[iframe].fibres[lfibre];
            if (allflatsin->fibremask[ifibre]==TRUE) {
                /* this fibre is ok, add it */
                newfibres[newnumfibres] = ifibre;
                newnumfibres++;
            }
        }
        /* ok, free the old fibres and set it to the new vector */
        free_lvector(allflatsin->flatdata[iframe].fibres,
                     0, allflatsin->maxfibres-1);
        allflatsin->flatdata[iframe].fibres = newfibres;
        allflatsin->flatdata[iframe].numfibres = newnumfibres;
    }


    /* free dynamically allocated temporary variables here */
    for (iframe=0; iframe<=allflatsout->nflats-1; iframe++) {
        free_fmmatrix(allflatsout->flatdata[iframe].badpixel, 0,
                        (allflatsout->subrows)-1, 0,
                        (allflatsout->subcols)-1);
    }
    free(allflatsout->flatdata);
    free(allflatsout);
    for (i=0; i<=ordpos->lastorder-ordpos->firstorder; i++) {
        shiftbuffer = shiftdata[i];
        for (ix=0; ix<=(allflatsin->subcols-1); ix++){
            free(shiftbuffer[ix].ixoffsets);
            free(shiftbuffer[ix].yfracoffsets);
            free(shiftbuffer[ix].yintoffsets);
            free(shiftbuffer[ix].normfactor);
            free(shiftbuffer[ix].normsigma);
            free(shiftbuffer[ix].goodoverlap);
        }
    }
    free(shiftdata[0]);
    free(shiftdata);
    for (ifibre=0; ifibre<=allflatsin->maxfibres-1; ifibre++) {
        free(badifibre[ifibre].badixs);
    }
    free(badifibre);

    free(fitdata.offset);
    free(fitdata.value);
    free(fitdata.sigma);

    return(NOERR);

}
/**@}*/