File: fors_calib.cc

package info (click to toggle)
cpl-plugin-fors 5.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 10,664 kB
  • ctags: 3,906
  • sloc: ansic: 68,347; cpp: 16,320; sh: 11,458; python: 1,123; makefile: 823
file content (3767 lines) | stat: -rw-r--r-- 151,777 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
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
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
/* $Id: fors_calib.cc,v 1.14 2013/10/24 16:46:53 cgarcia Exp $
 *
 * This file is part of the FORS Data Reduction Pipeline
 * Copyright (C) 2002-2010 European Southern Observatory
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

/*
 * $Author: cgarcia $
 * $Date: 2013/10/24 16:46:53 $
 * $Revision: 1.14 $
 * $Name:  $
 */

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

#include <cmath>
#include <limits>
#include <string>
#include <sstream>
#include <exception>
#include <math.h>
#include <string.h>
#include <cpl.h>
#include <moses.h>
#include <fors_image.h>
#include <fors_flat_normalise.h>
#include <fors_detected_slits.h>
#include <fors_stack.h>
#include <fors_dfs.h>
#include <fors_header.h>
#include <fors_utils.h>
#include "fors_detmodel.h"
#include "fors_ccd_config.h"
#include "fors_subtract_bias.h"
#include "fors_saturation_mos.h"
#include "fors_overscan.h"
#include "flat_combine.h"
#include "fiera_config.h"
#include "fors_grism.h"
#include "fors_bpm.h"

struct fors_calib_config 
{
    /* Input parameters */
    double        dispersion;
    double        peakdetection;
    int           wdegree;
    int           wradius;
    double        wreject;
    int           wmode;
    int           wmosmode;
    int           cdegree;
    int           cmode;
    double        startwavelength;
    double        endwavelength;
    int           slit_ident;
    int           spa_polyorder;
    int           disp_nknots;
    int           sradius;
    int           dradius;
    float         fit_threshold;
    const char   *stack_method;
    int           min_reject;
    int           max_reject;
    double        klow;
    double        khigh;
    int           kiter;
    const char   *ignore_lines;
    const char   *used_linesets;
    double        nonlinear_level;
    double        max_nonlinear_ratio;
};

static int fors_calib_create(cpl_plugin *);
static int fors_calib_exec(cpl_plugin *);
static int fors_calib_destroy(cpl_plugin *);
static int fors_calib(cpl_parameterlist *, cpl_frameset *);
int fors_calib_retrieve_input_param(cpl_parameterlist * parlist, 
                                     cpl_frameset * frameset,
                                     fors_calib_config * config);
cpl_vector * fors_calib_get_reference_lines(cpl_frameset * frameset, 
                                            const char * arctag,
                                            const char * ignore_lines,
                                            const char * used_linesets);
std::auto_ptr<mosca::image> fors_calib_flat_mos_create_master_flat
(fors::calibrated_slits& calibrated_slits, 
 const mosca::wavelength_calibration& wave_cal,
 const mosca::grism_config& grism_cfg,
 fors_image *master_bias, const cpl_frame * bias_frame,
 struct fors_calib_config& config, cpl_frameset * frameset,
 const char * flat_tag, 
 double nonlinear_level, double max_nonlinear_ratio,
 std::vector<std::vector<double> >& slit_sat_ratio,
 std::vector<std::vector<int> >& slit_sat_count,
 cpl_mask **& nonlinear_flat_masks,
 cpl_mask **& saturated_flat_masks,
 std::auto_ptr<mosca::fiera_config>& ccd_config);
int fors_calib_flat_mos_normalise
(std::auto_ptr<mosca::image>& master_flat_d,
 const mosca::wavelength_calibration& wave_cal,
 cpl_table * slits, cpl_table * polytraces, cpl_image * coordinate, 
 struct fors_calib_config& config,
 std::auto_ptr<mosca::image>& norm_flat,
 cpl_image ** wave_profiles,
 std::vector<float>& sed_norm);
int fors_calib_flat_mos_rect_mapped
(std::auto_ptr<mosca::image>& master_flat_d, 
 std::auto_ptr<mosca::image>& norm_flat,
 cpl_table * slits,
 cpl_table *idscoeff, cpl_table * polytraces, 
 double reference, struct fors_calib_config& config,
 cpl_image *& mapped_flat, 
 cpl_image *& mapped_nflat);
cpl_mask * fors_calib_mask_rect_mapped
(cpl_mask * mask,
 cpl_table * slits, cpl_table *idscoeff, cpl_table * polytraces,
 double reference, struct fors_calib_config& config);
int fors_calib_flats_save
(std::auto_ptr<mosca::image>& master_flat_d,
 cpl_image * flat_mask,
 std::auto_ptr<mosca::image>& norm_flat,
 cpl_image * mapped_flat,  cpl_image * mapped_nflat,
 const fors::detected_slits detected_slits,
 const std::vector<std::vector<double> >& slit_sat_ratio,
 const std::vector<std::vector<int> >& slit_sat_count,
 struct fors_calib_config& config,
 cpl_frameset * frameset, const char * flat_tag, 
 const char * master_screen_flat_tag, const char * master_norm_flat_tag, 
 const char * mapped_screen_flat_tag, const char * mapped_norm_flat_tag, 
 cpl_parameterlist * parlist, const cpl_frame * ref_flat_frame,
 const mosca::ccd_config& ccd_config);
void fors_calib_qc_saturation
(cpl_propertylist * header, const fors::detected_slits detected_slits,
 const std::vector<std::vector<double> >& slit_sat_ratio,
 const std::vector<std::vector<int> >& slit_sat_count);



static char fors_calib_description[] =
"This recipe is used to identify reference lines on LSS, MOS and MXU arc lamp\n"
"exposures, and trace the spectral edges on the corresponding flat field\n"
"exposures. This information is used to determine the spectral extraction\n"
"mask to be applied in the scientific data reduction, performed with the\n"
"recipe fors_science.\n"
"This recipe accepts both FORS1 and FORS2 frames. The input arc lamp and\n"
"flat field exposures are assumed to be obtained quasi-simultaneously, so\n"
"that they would be described by exactly the same instrument distortions.\n"
"A line catalog must be specified, containing the wavelengths of the\n"
"reference arc lamp lines used for the wavelength calibration. A grism\n"
"table (typically depending on the instrument mode, and in particular on\n"
"the grism used) may also be specified: this table contains a default\n"
"recipe parameter setting to control the way spectra are extracted for\n"
"a specific instrument mode, as it is used for automatic run of the\n"
"pipeline on Paranal and in Garching. If this table is specified, it\n"
"will modify the default recipe parameter setting, with the exception of\n"
"those parameters which have been explicitly modified on the command line.\n"
"If a grism table is not specified, the input recipe parameters values\n"
"will always be read from the command line, or from an esorex configuration\n"
"file if present, or from their generic default values (that are rarely\n"
"meaningful). Finally a master bias frame must be input to this recipe.\n" 
"In the table below the MXU acronym can be read alternatively as MOS\n"
"and LSS, with the exception of CURV_COEFF_LSS, CURV_TRACES_LSS,\n"
"SPATIAL_MAP_LSS, SPECTRA_DETECTION_LSS, and and SLIT_MAP_LSS, which are\n" 
"never created. The products SPECTRA_DETECTION_MXU, SLIT_MAP_MXU, and\n" 
"DISP_RESIDUALS_MXU, are just created if the --check parameter is set to\n" 
"true. The product GLOBAL_DISTORTION_TABLE is just created if more than 12\n" 
"separate spectra are found in the CCD.\n\n"
"Input files:\n\n"
"  DO category:             Type:       Explanation:         Required:\n"
"  SCREEN_FLAT_MXU          Raw         Flat field exposures    Y\n"
"  LAMP_MXU                 Raw         Arc lamp exposure       Y\n"
"  MASTER_BIAS              Calib       Master Bias frame       Y\n"
"  MASTER_LINECAT           Calib       Line catalog            Y\n"
"  GRISM_TABLE              Calib       Grism table             .\n\n"
"Output files:\n\n"
"  DO category:             Data type:  Explanation:\n"
"  MASTER_SCREEN_FLAT_MXU   FITS image  Combined (sum) flat field\n"
"  MASTER_NORM_FLAT_MXU     FITS image  Normalised flat field\n"
"  MAPPED_SCREEN_FLAT_MXU   FITS image  Wavelength calibrated flat field\n"
"  MAPPED_NORM_FLAT_MXU     FITS image  Wavelength calibrated normalised flat\n"
"  REDUCED_LAMP_MXU         FITS image  Wavelength calibrated arc spectrum\n"
"  DISP_COEFF_MXU           FITS table  Inverse dispersion coefficients\n"
"  DISP_RESIDUALS_MXU       FITS image  Residuals in wavelength calibration\n"
"  DISP_RESIDUALS_TABLE_MXU FITS table  Residuals in wavelength calibration\n"
"  DELTA_IMAGE_MXU          FITS image  Offset vs linear wavelength calib\n"
"  WAVELENGTH_MAP_MXU       FITS image  Wavelength for each pixel on CCD\n"
"  SPECTRA_DETECTION_MXU    FITS image  Check for preliminary detection\n"
"  SLIT_MAP_MXU             FITS image  Map of central wavelength on CCD\n"
"  CURV_TRACES_MXU          FITS table  Spectral curvature traces\n"
"  CURV_COEFF_MXU           FITS table  Spectral curvature coefficients\n"
"  SPATIAL_MAP_MXU          FITS image  Spatial position along slit on CCD\n"
"  SPECTRAL_RESOLUTION_MXU  FITS table  Resolution at reference arc lines\n"
"  DETECTED_LINES_MXU       FITS table  All the lines detected in the arc\n"
"  ARC_RECTIFIED_MXU        FITS iamge  The spatial rectified arc\n"
"  SLIT_LOCATION_MXU        FITS table  Slits on product frames and CCD\n"
"  GLOBAL_DISTORTION_TABLE  FITS table  Global distortions table\n\n";

#define fors_calib_exit(message)                      \
{                                                     \
if ((const char *)message != NULL ) cpl_msg_error(recipe, message);  \
cpl_free(fiterror);                                   \
cpl_free(fitlines);                                   \
fors_image_delete(&master_bias);                        \
cpl_image_delete(coordinate);                         \
cpl_image_delete(checkwave);                          \
cpl_image_delete(flat);                               \
cpl_image_delete(master_flat);                        \
cpl_image_delete(added_flat);                         \
cpl_image_delete(rainbow);                            \
cpl_image_delete(rectified);                          \
cpl_image_delete(residual);                           \
cpl_image_delete(smo_flat);                           \
cpl_image_delete(spatial);                            \
cpl_image_delete(spectra);                            \
cpl_image_delete(wavemap);                            \
cpl_image_delete(delta);                              \
cpl_image_delete(rect_flat);                          \
cpl_image_delete(rect_nflat);                         \
cpl_image_delete(mapped_flat);                        \
cpl_image_delete(mapped_nflat);                       \
cpl_mask_delete(refmask);                             \
cpl_propertylist_delete(header);                      \
cpl_propertylist_delete(save_header);                 \
cpl_propertylist_delete(qclist);                      \
cpl_table_delete(idscoeff);                           \
cpl_table_delete(idscoeff_all);                       \
cpl_table_delete(restable);                           \
cpl_table_delete(maskslits);                          \
cpl_table_delete(overscans);                          \
cpl_table_delete(traces);                             \
cpl_table_delete(polytraces);                         \
cpl_table_delete(slits);                              \
cpl_table_delete(restab);                             \
cpl_table_delete(global);                             \
cpl_table_delete(wavelengths);                        \
cpl_vector_delete(lines);                             \
cpl_msg_indent_less();                                \
return -1;                                            \
}

#define fors_calib_exit_memcheck(message)              \
{                                                      \
if ((const char *)message !=NULL ) cpl_msg_info(recipe, message);    \
printf("free fiterror (%p)\n", fiterror);              \
cpl_free(fiterror);                                    \
printf("free fitlines (%p)\n", fitlines);              \
cpl_free(fitlines);                                    \
printf("free bias (%p)\n", bias);                      \
cpl_image_delete(bias);                                \
printf("free master_bias (%p)\n", master_bias);        \
fors_image_delete(&master_bias);                         \
printf("free coordinate (%p)\n", coordinate);          \
cpl_image_delete(coordinate);                          \
printf("free checkwave (%p)\n", checkwave);            \
cpl_image_delete(checkwave);                           \
printf("free flat (%p)\n", flat);                      \
cpl_image_delete(flat);                                \
printf("free master_flat (%p)\n", master_flat);        \
cpl_image_delete(master_flat);                         \
printf("free norm_flat (%p)\n", norm_flat);            \
cpl_image_delete(norm_flat);                           \
printf("free mapped_flat (%p)\n", mapped_flat);        \
cpl_image_delete(mapped_flat);                         \
printf("free mapped_nflat (%p)\n", mapped_nflat);      \
cpl_image_delete(mapped_nflat);                        \
printf("free rainbow (%p)\n", rainbow);                \
cpl_image_delete(rainbow);                             \
printf("free rectified (%p)\n", rectified);            \
cpl_image_delete(rectified);                           \
printf("free residual (%p)\n", residual);              \
cpl_image_delete(residual);                            \
printf("free smo_flat (%p)\n", smo_flat);              \
cpl_image_delete(smo_flat);                            \
printf("free spatial (%p)\n", spatial);                \
cpl_image_delete(spatial);                             \
printf("free spectra (%p)\n", spectra);                \
cpl_image_delete(spectra);                             \
printf("free wavemap (%p)\n", wavemap);                \
cpl_image_delete(wavemap);                             \
printf("free delta (%p)\n", delta);                    \
cpl_image_delete(delta);                               \
printf("free rect_flat (%p)\n", rect_flat);            \
cpl_image_delete(rect_flat);                           \
printf("free rect_nflat (%p)\n", rect_nflat);          \
cpl_image_delete(rect_nflat);                          \
printf("free refmask (%p)\n", refmask);                \
cpl_mask_delete(refmask);                              \
printf("free header (%p)\n", header);                  \
cpl_propertylist_delete(header);                       \
printf("free save_header (%p)\n", save_header);        \
cpl_propertylist_delete(save_header);                  \
printf("free qclist (%p)\n", qclist);                  \
cpl_propertylist_delete(qclist);                       \
printf("free grism_table (%p)\n", grism_table);        \
cpl_table_delete(grism_table);                         \
printf("free idscoeff (%p)\n", idscoeff);              \
cpl_table_delete(idscoeff);                            \
printf("free idscoeff_all (%p)\n", idscoeff_all);      \
cpl_table_delete(idscoeff_all);                        \
printf("free restable (%p)\n", restable);              \
cpl_table_delete(restable);                            \
printf("free maskslits (%p)\n", maskslits);            \
cpl_table_delete(maskslits);                           \
printf("free overscans (%p)\n", overscans);            \
cpl_table_delete(overscans);                           \
printf("free traces (%p)\n", traces);                  \
cpl_table_delete(traces);                              \
printf("free polytraces (%p)\n", polytraces);          \
cpl_table_delete(polytraces);                          \
printf("free slits (%p)\n", slits);                    \
cpl_table_delete(slits);                               \
printf("free restab (%p)\n", restab);                  \
cpl_table_delete(restab);                              \
printf("free global (%p)\n", global);                  \
cpl_table_delete(global);                              \
printf("free wavelengths (%p)\n", wavelengths);        \
cpl_table_delete(wavelengths);                         \
printf("free lines (%p)\n", lines);                    \
cpl_vector_delete(lines);                              \
return 0;                                              \
}


/**
 * @brief    Build the list of available plugins, for this module. 
 *
 * @param    list    The plugin list
 *
 * @return   0 if everything is ok, -1 otherwise
 *
 * Create the recipe instance and make it available to the application 
 * using the interface. This function is exported.
 */

int cpl_plugin_get_info(cpl_pluginlist *plist)
{
    cpl_recipe *recipe = static_cast<cpl_recipe *>(cpl_calloc(1, sizeof *recipe ));
    cpl_plugin *plugin = &recipe->interface;

    cpl_plugin_init(plugin,
                    CPL_PLUGIN_API,
                    FORS_BINARY_VERSION,
                    CPL_PLUGIN_TYPE_RECIPE,
                    "fors_calib",
                    "Determination of the extraction mask",
                    fors_calib_description,
                    "Carlo Izzo",
                    PACKAGE_BUGREPORT,
    "This file is currently part of the FORS Instrument Pipeline\n"
    "Copyright (C) 2002-2010 European Southern Observatory\n\n"
    "This program is free software; you can redistribute it and/or modify\n"
    "it under the terms of the GNU General Public License as published by\n"
    "the Free Software Foundation; either version 2 of the License, or\n"
    "(at your option) any later version.\n\n"
    "This program is distributed in the hope that it will be useful,\n"
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
    "GNU General Public License for more details.\n\n"
    "You should have received a copy of the GNU General Public License\n"
    "along with this program; if not, write to the Free Software Foundation,\n"
    "Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n",
                    fors_calib_create,
                    fors_calib_exec,
                    fors_calib_destroy);

    cpl_pluginlist_append(plist, plugin);
    
    return 0;
}


/**
 * @brief    Setup the recipe options    
 *
 * @param    plugin  The plugin
 *
 * @return   0 if everything is ok
 *
 * Defining the command-line/configuration parameters for the recipe.
 */

static int fors_calib_create(cpl_plugin *plugin)
{
    cpl_recipe    *recipe;
    cpl_parameter *p;


    /* 
     * Check that the plugin is part of a valid recipe 
     */

    if (cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE) 
        recipe = (cpl_recipe *)plugin;
    else 
        return -1;

    /* 
     * Create the parameters list in the cpl_recipe object 
     */

    recipe->parameters = cpl_parameterlist_new(); 


    /*
     * Dispersion
     */

    p = cpl_parameter_new_value("fors.fors_calib.dispersion",
                                CPL_TYPE_DOUBLE,
                                "Expected spectral dispersion (Angstrom/pixel)",
                                "fors.fors_calib",
                                0.0);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "dispersion");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Peak detection level
     */

    p = cpl_parameter_new_value("fors.fors_calib.peakdetection",
                                CPL_TYPE_DOUBLE,
                                "Initial peak detection threshold (ADU)",
                                "fors.fors_calib",
                                0.0);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "peakdetection");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /* 
     * Degree of wavelength calibration polynomial
     */

    p = cpl_parameter_new_value("fors.fors_calib.wdegree",
                                CPL_TYPE_INT,
                                "Degree of wavelength calibration polynomial",
                                "fors.fors_calib",
                                0);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "wdegree");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Reference lines search radius
     */

    p = cpl_parameter_new_value("fors.fors_calib.wradius",
                                CPL_TYPE_INT,
                                "Search radius if iterating pattern-matching "
                                "with first-guess method",
                                "fors.fors_calib",
                                4);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "wradius");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Rejection threshold in dispersion relation polynomial fitting
     */

    p = cpl_parameter_new_value("fors.fors_calib.wreject",
                                CPL_TYPE_DOUBLE,
                                "Rejection threshold in dispersion "
                                "relation fit (pixel)",
                                "fors.fors_calib",
                                0.7);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "wreject");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Wavelength solution interpolation (for LSS data)
     */

    p = cpl_parameter_new_value("fors.fors_calib.wmode",
                                CPL_TYPE_INT,
                                "Interpolation mode of wavelength solution "
                                "applicable to LSS-like data (0 = no "
                                "interpolation, 1 = fill gaps, 2 = global "
                                "model)",
                                "fors.fors_calib",
                                2);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "wmode");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Wavelength solution interpolation (for MOS data)
     */

    p = cpl_parameter_new_value("fors.fors_calib.wmosmode",
                                CPL_TYPE_INT,
                                "Interpolation mode of wavelength solution "
                                "(0 = no interpolation, 1 = local (slit) "
                                "solution, 2 = global model)",
                                "fors.fors_calib",
                                0);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "wmosmode");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Catalog lines to ignore in wavelength calibration
     */

    p = cpl_parameter_new_value("fors.fors_calib.ignore_lines",
                                CPL_TYPE_STRING,
                                "Catalog lines nearest to wavelengths in this "
                                "list will be ignored for wavelength calibration",
                                "fors.fors_calib",
                                "");
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "ignore_lines");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Linesets to use
     */

    p = cpl_parameter_new_value("fors.fors_calib.used_linesets",
                                CPL_TYPE_STRING,
                                "Linesets to use. Valid are 'standard' and"
                                "'extended' (see column LINE_SET in the "
                                "line catalogue)",
                                "fors.fors_calib",
                                "standard");
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "used_linesets");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Degree of spectral curvature polynomial
     */

    p = cpl_parameter_new_value("fors.fors_calib.cdegree",
                                CPL_TYPE_INT,
                                "Degree of spectral curvature polynomial",
                                "fors.fors_calib",
                                -1);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "cdegree");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Curvature solution interpolation (for MOS-like data)
     */
 
    p = cpl_parameter_new_value("fors.fors_calib.cmode",
                                CPL_TYPE_INT,
                                "Interpolation mode of curvature solution "
                                "applicable to MOS-like data (0 = no "
                                "interpolation, 1 = fill gaps, 2 = global "
                                "model)",
                                "fors.fors_calib",
                                1);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "cmode");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Start wavelength for spectral extraction
     */

    p = cpl_parameter_new_value("fors.fors_calib.startwavelength",
                                CPL_TYPE_DOUBLE,
                                "Start wavelength in spectral extraction",
                                "fors.fors_calib",
                                0.0);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "startwavelength");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * End wavelength for spectral extraction
     */

    p = cpl_parameter_new_value("fors.fors_calib.endwavelength",
                                CPL_TYPE_DOUBLE,
                                "End wavelength in spectral extraction",
                                "fors.fors_calib",
                                0.0);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "endwavelength");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Try slit identification
     */

    p = cpl_parameter_new_value("fors.fors_calib.slit_ident",
                                CPL_TYPE_BOOL,
                                "Attempt slit identification for MOS or MXU",
                                "fors.fors_calib",
                                TRUE);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "slit_ident");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Stacking method
     */
    p = cpl_parameter_new_enum("fors.fors_calib.stack_method",
                                CPL_TYPE_STRING,
                                "Frames combination method",
                                "fors.fors_calib",
                                "sum", 4,
                                "sum", "mean", "median", "ksigma");
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "stack_method");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /* 
     * Threshold for the sigma clipping algorithm 
     */
    p = cpl_parameter_new_value("fors.fors_calib.ksigma",
                                CPL_TYPE_STRING,
                                "Low and high threshold in ksigma method",
                                "fors.fors_calib",
                                "-3.0,3.0");
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "ksigma");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /* 
     * Number of iterations for the sigma clipping algorithm 
     */
    p = cpl_parameter_new_value("fors.fors_calib.kiter",
                                CPL_TYPE_INT,
                                "Max number of iterations in ksigma method",
                                "fors.fors_calib",
                                999);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "kiter");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Number of knots in flat field fitting splines along spatial direction 
     */

    p = cpl_parameter_new_value("fors.fors_calib.s_degree",
                                CPL_TYPE_INT,
                                "Polynomial degree for the flat field fitting "
                                "along spatial direction",
                                "fors.fors_calib",
                                -1);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "s_degree");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Smooth box radius for flat field along spatial direction
     * (if s_knots < 0)
     */

    p = cpl_parameter_new_value("fors.fors_calib.sradius",
                                CPL_TYPE_INT,
                                "Smooth box radius for flat field along "
                                "spatial direction (used if s_knots < 0)",
                                "fors.fors_calib",
                                10);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "sradius");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Number of knots in flat field fitting splines along dispersion direction 
     */

    p = cpl_parameter_new_value("fors.fors_calib.d_nknots",
                                CPL_TYPE_INT,
                                "Number of knots in flat field fitting "
                                "splines along dispersion direction",
                                "fors.fors_calib",
                                -1);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "d_nknots");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Smooth box radius for flat field along dispersion direction
     */

    p = cpl_parameter_new_value("fors.fors_calib.dradius",
                                CPL_TYPE_INT,
                                "Smooth box radius for flat field along "
                                "dispersion direction (if d_knots < 0)",
                                "fors.fors_calib",
                                10);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "dradius");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Threshold percentage for flat spline fitting with respect to the maximum
     */

    p = cpl_parameter_new_value("fors.fors_calib.fit_threshold",
                                CPL_TYPE_DOUBLE,
                                "Threshold percentage for flat spline fitting"
                                "with respect to the maximum",
                                "fors.fors_calib",
                                0.01);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "fit_threshold");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /* 
     * Saturation level of the detector
     */
    p = cpl_parameter_new_value("fors.fors_calib.nonlinear_level",
                                CPL_TYPE_DOUBLE,
                                "Level above which the detector is not linear",
                                "fors.fors_calib",
                                60000.);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "nonlinear_level");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /* 
     * Maximum allowed ratio of saturated pixels per slit 
     */
    p = cpl_parameter_new_value("fors.fors_calib.max_nonlinear_ratio",
                                CPL_TYPE_DOUBLE,
                                "Maximum allowed ratio of non-linear pixels per slit",
                                "fors.fors_calib",
                                0.2);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "max_nonlinear_ratio");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    return 0;
}


/**
 * @brief    Execute the plugin instance given by the interface
 *
 * @param    plugin  the plugin
 *
 * @return   0 if everything is ok
 */

static int fors_calib_exec(cpl_plugin *plugin)
{
    cpl_recipe  *   recipe ;
    int             status = 1;

    /* Get the recipe out of the plugin */
    if (cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE)
        recipe = (cpl_recipe *)plugin ;
    else return -1 ;

    /* Issue a banner */
    fors_print_banner();

    try
    {
        status = fors_calib(recipe->parameters, recipe->frames);
    }
    catch(std::exception& ex)
    {
        cpl_msg_error(cpl_func, "Recipe error: %s", ex.what());
    }
    catch(...)
    {
        cpl_msg_error(cpl_func, "An uncaught error during recipe execution");
    }

    return status;
}


/**
 * @brief    Destroy what has been created by the 'create' function
 *
 * @param    plugin  The plugin
 *
 * @return   0 if everything is ok
 */

static int fors_calib_destroy(cpl_plugin *plugin)
{
    cpl_recipe *recipe;
    
    if (cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE) 
        recipe = (cpl_recipe *)plugin;
    else 
        return -1;

    cpl_parameterlist_delete(recipe->parameters); 

    return 0;
}


/**
 * @brief    Interpret the command line options and execute the data processing
 *
 * @param    parlist     The parameters list
 * @param    frameset    The set-of-frames
 *
 * @return   0 if everything is ok
 */

static int fors_calib(cpl_parameterlist *parlist, cpl_frameset *frameset)
{

    const char *recipe = "fors_calib";

    /*
     * Input parameters
     */
    struct fors_calib_config config;

    /*
     * CPL objects
     */

    fors_image       *master_bias  = NULL;
    cpl_image        *multi_bias   = NULL;
    cpl_image        *flat         = NULL;
    cpl_image        *master_flat  = NULL;
    cpl_image        *added_flat   = NULL;
    cpl_image        *trace_flat   = NULL;
    cpl_image        *smo_flat     = NULL;
    cpl_image        *spectra      = NULL;
    cpl_image        *wavemap      = NULL;
    cpl_image        *delta        = NULL;
    cpl_image        *residual     = NULL;
    cpl_image        *checkwave    = NULL;
    cpl_image        *rectified    = NULL;
    cpl_image        *dummy        = NULL;
    cpl_image        *add_dummy    = NULL;
    cpl_image        *refimage     = NULL;
    cpl_image        *coordinate   = NULL;
    cpl_image        *rainbow      = NULL;
    cpl_image        *spatial      = NULL;
    cpl_image        *rect_flat    = NULL;
    cpl_image        *rect_nflat   = NULL;
    cpl_image        *mapped_flat  = NULL;
    cpl_image        *mapped_nflat = NULL;

    cpl_mask         *refmask      = NULL;

    cpl_table        *overscans    = NULL;
    cpl_table        *wavelengths  = NULL;
    cpl_table        *idscoeff     = NULL;
    cpl_table        *idscoeff_all = NULL;
    cpl_table        *restable     = NULL;
    cpl_table        *slits        = NULL;
    cpl_table        *positions    = NULL;
    cpl_table        *maskslits    = NULL;
    cpl_table        *traces       = NULL;
    cpl_table        *polytraces   = NULL;
    cpl_table        *restab       = NULL;
    cpl_table        *global       = NULL;

    cpl_vector       *lines        = NULL;

    cpl_propertylist *header       = NULL;
    cpl_propertylist *save_header  = NULL;
    cpl_propertylist *qclist       = NULL;

    const cpl_frame  *ref_flat_frame = NULL;
    const cpl_frame  *ref_arc_frame  = NULL;
    
    /*
     * Auxiliary variables
     */

    const char *arc_tag;
    const char *flat_tag;
    const char *master_screen_flat_tag;
    const char *master_norm_flat_tag;
    const char *reduced_lamp_tag;
    const char *disp_residuals_tag;
    const char *disp_coeff_tag;
    const char *wavelength_map_tag;
    const char *spectra_detection_tag;
    const char *spectral_resolution_tag;
    const char *slit_map_tag;
    const char *curv_traces_tag;
    const char *curv_coeff_tag;
    const char *spatial_map_tag;
    const char *slit_location_tag;
    const char *global_distortion_tag = "GLOBAL_DISTORTION_TABLE";
    const char *disp_residuals_table_tag;
    const char *detected_lines_tag;
    const char *arc_rectified_tag;
    const char *delta_image_tag;
    const char *mapped_screen_flat_tag;
    const char *mapped_norm_flat_tag;
    const char *flat_disp_profile_tag;
    const char *keyname;
    int         mxu, mos, lss;
    int         treat_as_lss = 0;
    int         nslits;
    float      *data;
    double      mxpos;
    double      mean_rms;
    double      mean_rms_err;
    double      alltime;
    int         nflats;
    int         nlines;
    int         rebin;
    double     *fiterror = NULL;
    int        *fitlines = NULL;
    cpl_size    nx, ny;
    cpl_size    size_spec;
    double      ref_wave;
    double      gain;
    int         compute_central_wave;
    int         ccd_xsize, ccd_ysize;
    int         i;

    cpl_errorstate   error_prevstate = cpl_errorstate_get();


    cpl_msg_set_indentation(2);

    /* 
     * Get configuration parameters
     */
    if (cpl_frameset_count_tags(frameset, "GRISM_TABLE") > 1)
        fors_calib_exit("Too many in input: GRISM_TABLE");

    if(fors_calib_retrieve_input_param(parlist, frameset, &config) != 0)
        fors_calib_exit("Failed to read input parameters");;
    
    /* Check input parameters */

    if (config.dispersion <= 0.0)
        fors_calib_exit("Invalid spectral dispersion value");

    if (config.peakdetection <= 0.0)
        fors_calib_exit("Invalid peak detection level");
    
    if (config.wdegree < 1)
        fors_calib_exit("Invalid polynomial degree");

    if (config.wdegree > 5)
        fors_calib_exit("Max allowed polynomial degree is 5");
    

    if (config.wradius < 0)
        fors_calib_exit("Invalid search radius");

    if (config.wreject <= 0.0)
        fors_calib_exit("Invalid rejection threshold");

    if (config.wmode < 0 || config.wmode > 2)
        fors_calib_exit("Invalid wavelength solution interpolation mode");

    if (config.wmosmode < 0 || config.wmosmode > 2)
        fors_calib_exit("Invalid wavelength solution interpolation mode");

    if (config.cdegree < 1)
        fors_calib_exit("Invalid polynomial degree");

    if (config.cdegree > 5)
        fors_calib_exit("Max allowed polynomial degree is 5");

    if (config.cmode < 0 || config.cmode > 2)
        fors_calib_exit("Invalid curvature solution interpolation mode");

    if (config.startwavelength > 1.0)
        if (config.startwavelength < 3000.0 || config.startwavelength > 13000.0)
            fors_calib_exit("Invalid wavelength");

    if (config.endwavelength > 1.0) {
        if (config.endwavelength < 3000.0 || config.endwavelength > 13000.0)
            fors_calib_exit("Invalid wavelength");
        if (config.startwavelength < 1.0)
            fors_calib_exit("Invalid wavelength interval");
    }

    if (config.startwavelength > 1.0)
        if (config.endwavelength - config.startwavelength <= 0.0)
            fors_calib_exit("Invalid wavelength interval");

    std::string stack_method_str = config.stack_method; 
    if(stack_method_str != "mean" && stack_method_str != "median" && 
       stack_method_str != "ksigma" && stack_method_str != "sum")
        throw std::invalid_argument(stack_method_str+" stacking algorithm invalid");

    if (strcmp(config.stack_method, "minmax") == 0) {
        if (config.min_reject < 0)
            fors_calib_exit("Invalid number of lower rejections");
        if (config.max_reject < 0)
            fors_calib_exit("Invalid number of upper rejections");
    }

    if (strcmp(config.stack_method, "ksigma") == 0) {
        if (config.klow < 0.1)
            fors_calib_exit("Invalid lower K-sigma");
        if (config.khigh < 0.1)
            fors_calib_exit("Invalid lower K-sigma");
        if (config.kiter < 1)
            fors_calib_exit("Invalid number of iterations");
    }

    if (cpl_error_get_code())
        fors_calib_exit("Failure getting the configuration parameters");


    /* 
     * Check input set-of-frames
     */

    cpl_msg_indent_less();
    cpl_msg_info(recipe, "Check input set-of-frames:");
    cpl_msg_indent_more();

    if (!dfs_equal_keyword(frameset, "ESO INS GRIS1 ID")) 
        cpl_msg_warning(cpl_func,"Input frames are not from the same grism");

    if (!dfs_equal_keyword(frameset, "ESO INS FILT1 ID")) 
        cpl_msg_warning(cpl_func,"Input frames are not from the same filter");

    if (!dfs_equal_keyword(frameset, "ESO DET CHIP1 ID")) 
        cpl_msg_warning(cpl_func,"Input frames are not from the same chip");

    mxu = cpl_frameset_count_tags(frameset, "LAMP_MXU");
    mos = cpl_frameset_count_tags(frameset, "LAMP_MOS");
    lss = cpl_frameset_count_tags(frameset, "LAMP_LSS");

    if (mxu + mos + lss == 0)
        fors_calib_exit("Missing input arc lamp frame");

    if (mxu + mos + lss > 1)
        fors_calib_exit("Just one input arc lamp frame is allowed"); 

    if (mxu) {
        cpl_msg_info(recipe, "MXU data found");
        arc_tag                  = "LAMP_MXU";
        flat_tag                 = "SCREEN_FLAT_MXU";
        master_screen_flat_tag   = "MASTER_SCREEN_FLAT_MXU";
        master_norm_flat_tag     = "MASTER_NORM_FLAT_MXU";
        reduced_lamp_tag         = "REDUCED_LAMP_MXU";
        disp_residuals_tag       = "DISP_RESIDUALS_MXU";
        disp_coeff_tag           = "DISP_COEFF_MXU";
        wavelength_map_tag       = "WAVELENGTH_MAP_MXU";
        spectra_detection_tag    = "SPECTRA_DETECTION_MXU";
        spectral_resolution_tag  = "SPECTRAL_RESOLUTION_MXU";
        slit_map_tag             = "SLIT_MAP_MXU";
        curv_traces_tag          = "CURV_TRACES_MXU";
        curv_coeff_tag           = "CURV_COEFF_MXU";
        spatial_map_tag          = "SPATIAL_MAP_MXU";
        slit_location_tag        = "SLIT_LOCATION_MXU";
        disp_residuals_table_tag = "DISP_RESIDUALS_TABLE_MXU";
        detected_lines_tag       = "DETECTED_LINES_MXU";
        arc_rectified_tag        = "ARC_RECTIFIED_MXU";
        delta_image_tag          = "DELTA_IMAGE_MXU";
        mapped_screen_flat_tag   = "MAPPED_SCREEN_FLAT_MXU";
        mapped_norm_flat_tag     = "MAPPED_NORM_FLAT_MXU";
        flat_disp_profile_tag    = "FLAT_SED_MXU";
    }

    if (lss) {
        cpl_msg_info(recipe, "LSS data found");
        arc_tag                  = "LAMP_LSS";
        flat_tag                 = "SCREEN_FLAT_LSS";
        master_screen_flat_tag   = "MASTER_SCREEN_FLAT_LSS";
        master_norm_flat_tag     = "MASTER_NORM_FLAT_LSS";
        reduced_lamp_tag         = "REDUCED_LAMP_LSS";
        spectral_resolution_tag  = "SPECTRAL_RESOLUTION_LSS";
        disp_residuals_tag       = "DISP_RESIDUALS_LSS";
        disp_coeff_tag           = "DISP_COEFF_LSS";
        slit_location_tag        = "SLIT_LOCATION_LSS";
        wavelength_map_tag       = "WAVELENGTH_MAP_LSS";
        slit_map_tag             = "SLIT_MAP_LSS";
        disp_residuals_table_tag = "DISP_RESIDUALS_TABLE_LSS";
        detected_lines_tag       = "DETECTED_LINES_LSS";
        arc_rectified_tag        = "ARC_RECTIFIED_LSS";
        delta_image_tag          = "DELTA_IMAGE_LSS";
        mapped_screen_flat_tag   = "MAPPED_SCREEN_FLAT_LSS";
        mapped_norm_flat_tag     = "MAPPED_NORM_FLAT_LSS";
        flat_disp_profile_tag    = "FLAT_SED_LSS";
    }

    if (mos) {
        cpl_msg_info(recipe, "MOS data found");
        arc_tag                  = "LAMP_MOS";
        flat_tag                 = "SCREEN_FLAT_MOS";
        master_screen_flat_tag   = "MASTER_SCREEN_FLAT_MOS";
        master_norm_flat_tag     = "MASTER_NORM_FLAT_MOS";
        reduced_lamp_tag         = "REDUCED_LAMP_MOS";
        disp_residuals_tag       = "DISP_RESIDUALS_MOS";
        disp_coeff_tag           = "DISP_COEFF_MOS";
        wavelength_map_tag       = "WAVELENGTH_MAP_MOS";
        spectra_detection_tag    = "SPECTRA_DETECTION_MOS";
        spectral_resolution_tag  = "SPECTRAL_RESOLUTION_MOS";
        slit_map_tag             = "SLIT_MAP_MOS";
        curv_traces_tag          = "CURV_TRACES_MOS";
        curv_coeff_tag           = "CURV_COEFF_MOS";
        spatial_map_tag          = "SPATIAL_MAP_MOS";
        slit_location_tag        = "SLIT_LOCATION_MOS";
        disp_residuals_table_tag = "DISP_RESIDUALS_TABLE_MOS";
        detected_lines_tag       = "DETECTED_LINES_MOS";
        arc_rectified_tag        = "ARC_RECTIFIED_MOS";
        delta_image_tag          = "DELTA_IMAGE_MOS";
        mapped_screen_flat_tag   = "MAPPED_SCREEN_FLAT_MOS";
        mapped_norm_flat_tag     = "MAPPED_NORM_FLAT_MOS";
        flat_disp_profile_tag    = "FLAT_SED_MOS";
    }

    if (cpl_frameset_count_tags(frameset, "MASTER_BIAS") == 0)
            fors_calib_exit("Missing required input: MASTER_BIAS");

    if (cpl_frameset_count_tags(frameset, "MASTER_BIAS") > 1)
        fors_calib_exit("Too many in input: MASTER_BIAS");

    if (cpl_frameset_count_tags(frameset, "MASTER_LINECAT") == 0)
        fors_calib_exit("Missing required input: MASTER_LINECAT");

    if (cpl_frameset_count_tags(frameset, "MASTER_LINECAT") > 1)
        fors_calib_exit("Too many in input: MASTER_LINECAT");

    nflats = cpl_frameset_count_tags(frameset, flat_tag);

    if (nflats < 1) {
        cpl_msg_error(recipe, "Missing required input: %s", flat_tag);
        fors_calib_exit(NULL);
    }

    /* 
     * Get the reference frames used to inherit all the saved products 
     */
    ref_flat_frame = cpl_frameset_find_const(frameset, flat_tag); 
    ref_arc_frame = cpl_frameset_find_const(frameset, arc_tag); 

    
    cpl_msg_indent_less();

    if (nflats > 1)
        cpl_msg_info(recipe, "Load %d flat field frames and stack them "
                     "with method \"%s\"", nflats, config.stack_method);
    else
        cpl_msg_info(recipe, "Load flat field exposure...");

    cpl_msg_indent_more();

    header = dfs_load_header(frameset, flat_tag, 0);

    if (header == NULL)
        fors_calib_exit("Cannot load flat field frame header");

    /*
     * Insert here a check on supported filters:
     */

    std::string wheel4 = 
         std::string(cpl_propertylist_get_string(header, "ESO INS OPTI9 TYPE"));
    if (cpl_error_get_code() != CPL_ERROR_NONE) {
        fors_calib_exit("Missing keyword ESO INS OPTI9 TYPE in flat header");
    }

    if (wheel4 == "FILT") {
        wheel4 = std::string(cpl_propertylist_get_string(header, 
                                                     "ESO INS OPTI9 NAME"));
        cpl_msg_error(recipe, "Unsupported filter: %s", wheel4.c_str());
        fors_calib_exit(NULL);
    }

    alltime = cpl_propertylist_get_double(header, "EXPTIME");

    if (cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit("Missing keyword EXPTIME in flat field frame header");

    cpl_propertylist_delete(header);

    for (i = 1; i < nflats; i++) {

        header = dfs_load_header(frameset, NULL, 0);

        if (header == NULL)
            fors_calib_exit("Cannot load flat field frame header");

        alltime += cpl_propertylist_get_double(header, "EXPTIME");

        if (cpl_error_get_code() != CPL_ERROR_NONE)
            fors_calib_exit("Missing keyword EXPTIME in flat field "
                            "frame header");

        cpl_propertylist_delete(header);

    }

    /* 
     * Creating master flat
     */ 
    master_flat = dfs_load_image(frameset, flat_tag, CPL_TYPE_FLOAT, 0, 0);

    if (master_flat == NULL)
        fors_calib_exit("Cannot load flat field");

    if (nflats > 1) {
        if (strcmp(config.stack_method, "sum") == 0) {
            for (i = 1; i < nflats; i++) {
                flat = dfs_load_image(frameset, NULL, CPL_TYPE_FLOAT, 0, 0);
                if (flat) {
                    cpl_image_add(master_flat, flat);
                    cpl_image_delete(flat); flat = NULL;
                }
                else
                    fors_calib_exit("Cannot load flat field");
            }

        /***
            if (nflats > 1)
                cpl_image_divide_scalar(master_flat, nflats);
        ***/

        }
        else {
            cpl_imagelist *flatlist = NULL;
            double rflux, flux;

            /*
             * added_flat is needed for tracing (masters obtained with
             * rejections are not suitable for tracing)
             */

            added_flat = cpl_image_duplicate(master_flat);

            flatlist = cpl_imagelist_new();
            cpl_imagelist_set(flatlist, master_flat, 
                              cpl_imagelist_get_size(flatlist));
            master_flat = NULL;

            /*
             * Stacking with rejection requires normalization
             * at the same flux. We normalise according to mean
             * flux. This is equivalent to determining the
             * flux ration for each image as the average of the
             * flux ratio of all pixels weighted on the actual
             * flux of each pixel.
             */

            rflux = cpl_image_get_mean(added_flat);

            for (i = 1; i < nflats; i++) {
                flat = dfs_load_image(frameset, NULL, CPL_TYPE_FLOAT, 0, 0);
                if (flat) {
                    cpl_image_add(added_flat, flat);
                    flux = cpl_image_get_mean(flat);
                    cpl_image_multiply_scalar(flat, rflux / flux);
                    cpl_imagelist_set(flatlist, flat, 
                                      cpl_imagelist_get_size(flatlist));
                    flat = NULL;
                }
                else {
                    fors_calib_exit("Cannot load flat field");
                }
            }

            if (strcmp(config.stack_method, "mean") == 0) {
                master_flat = cpl_imagelist_collapse_create(flatlist);
            }

            if (strcmp(config.stack_method, "median") == 0) {
                master_flat = cpl_imagelist_collapse_median_create(flatlist);
            }

            if (strcmp(config.stack_method, "minmax") == 0) {
                master_flat = cpl_imagelist_collapse_minmax_create(flatlist, 
                                                                   config.min_reject,
                                                                   config.max_reject);
            }

            if (strcmp(config.stack_method, "ksigma") == 0) {
                master_flat = mos_ksigma_stack(flatlist, 
                                               config.klow, config.khigh, config.kiter, NULL);
            }

            cpl_imagelist_delete(flatlist);
        }
    }

    /*
     * Get the reference wavelength and the rebin factor along the
     * dispersion direction from the arc lamp exposure
     */

    header = dfs_load_header(frameset, arc_tag, 0);

    if (header == NULL)
        fors_calib_exit("Cannot load arc lamp header");

    ref_wave = cpl_propertylist_get_double(header, "ESO INS GRIS1 WLEN");

    if (cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit("Missing keyword ESO INS GRIS1 WLEN in arc lamp "
                        "frame header");

    if (ref_wave < 3000.0)   /* Perhaps in nanometers... */
        ref_wave *= 10;

    if (ref_wave < 3000.0 || ref_wave > 13000.0) {
        cpl_msg_error(recipe, "Invalid central wavelength %.2f read from "
                      "keyword ESO INS GRIS1 WLEN in arc lamp frame header",
                      ref_wave);
        fors_calib_exit(NULL);
    }

    cpl_msg_info(recipe, "The central wavelength is: %.2f", ref_wave);

    rebin = cpl_propertylist_get_int(header, "ESO DET WIN1 BINX");

    if (cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit("Missing keyword ESO DET WIN1 BINX in arc lamp "
                        "frame header");

    if (rebin != 1) {
        config.dispersion *= rebin;
        cpl_msg_warning(recipe, "The rebin factor is %d, and therefore the "
                        "working dispersion used is %f A/pixel", rebin, 
                        config.dispersion);
    }

    gain = cpl_propertylist_get_double(header, "ESO DET OUT1 CONAD");

    if (cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit("Missing keyword ESO DET OUT1 CONAD in arc lamp "
                        "frame header");

    cpl_msg_info(recipe, "The gain factor is: %.2f e-/ADU", gain);

    if (mos || mxu) {
        int nslits_out_det = 0;


        cpl_msg_info(recipe, "Produce mask slit position table...");
        if (mos)
            maskslits = mos_load_slits_fors_mos(header, &nslits_out_det);
        else
            maskslits = mos_load_slits_fors_mxu(header);

        /*
         * Check if all slits have the same X offset: in such case, 
         * treat the observation as a long-slit one!
         */

        mxpos = cpl_table_get_column_median(maskslits, "xtop");
        nslits = cpl_table_get_nrow(maskslits);

        treat_as_lss = fors_mos_is_lss_like(maskslits,  nslits_out_det);

        if (treat_as_lss) {
            cpl_msg_warning(recipe, "All MOS slits have the same offset: %.2f\n"
                            "The LSS data reduction strategy is applied!", 
                            mxpos);
            cpl_table_delete(maskslits); maskslits = NULL;
            if (mos) {
                master_screen_flat_tag   = "MASTER_SCREEN_FLAT_LONG_MOS";
                master_norm_flat_tag     = "MASTER_NORM_FLAT_LONG_MOS";
                disp_residuals_table_tag = "DISP_RESIDUALS_TABLE_LONG_MOS";
                delta_image_tag          = "DELTA_IMAGE_LONG_MOS";
                spectral_resolution_tag  = "SPECTRAL_RESOLUTION_LONG_MOS";
                reduced_lamp_tag         = "REDUCED_LAMP_LONG_MOS";
                disp_coeff_tag           = "DISP_COEFF_LONG_MOS";
                detected_lines_tag       = "DETECTED_LINES_LONG_MOS";
                wavelength_map_tag       = "WAVELENGTH_MAP_LONG_MOS";
                slit_location_tag        = "SLIT_LOCATION_LONG_MOS";
                mapped_screen_flat_tag   = "MAPPED_SCREEN_FLAT_LONG_MOS";
                mapped_norm_flat_tag     = "MAPPED_NORM_FLAT_LONG_MOS";
                flat_disp_profile_tag    = "FLAT_SED_LONG_MOS";
            }
            else {
                master_screen_flat_tag   = "MASTER_SCREEN_FLAT_LONG_MXU";
                master_norm_flat_tag     = "MASTER_NORM_FLAT_LONG_MXU";
                disp_residuals_table_tag = "DISP_RESIDUALS_TABLE_LONG_MXU";
                delta_image_tag          = "DELTA_IMAGE_LONG_MXU";
                spectral_resolution_tag  = "SPECTRAL_RESOLUTION_LONG_MXU";
                reduced_lamp_tag         = "REDUCED_LAMP_LONG_MXU";
                disp_coeff_tag           = "DISP_COEFF_LONG_MXU";
                detected_lines_tag       = "DETECTED_LINES_LONG_MXU";
                wavelength_map_tag       = "WAVELENGTH_MAP_LONG_MXU";
                slit_location_tag        = "SLIT_LOCATION_LONG_MXU";
                mapped_screen_flat_tag   = "MAPPED_SCREEN_FLAT_LONG_MXU";
                mapped_norm_flat_tag     = "MAPPED_NORM_FLAT_LONG_MXU";
                flat_disp_profile_tag    = "FLAT_SED_LONG_MXU";
            }
        }
    }

    if (config.slit_ident == 0) {
        cpl_table_delete(maskslits); maskslits = NULL;
    }


    /* Leave the header on for the next step... */


    /*
     * Remove the master bias
     */

    //TODO: Remove all this. Create a trace_flat from scratch adding all flats 
    //and removing the overscan.
    const cpl_frame * bias_frame = 
            cpl_frameset_find_const(frameset, "MASTER_BIAS");
    master_bias = fors_image_load(bias_frame);
    if (master_bias == NULL)
        fors_calib_exit("Cannot load master bias");

    cpl_msg_info(recipe, "Remove the master bias...");

    overscans = mos_load_overscans_vimos(header, 1);

    if (nflats > 1) {
        multi_bias = cpl_image_multiply_scalar_create(master_bias->data, nflats);
        dummy = mos_remove_bias(master_flat, multi_bias, overscans);
        if (added_flat)
            add_dummy = mos_remove_bias(added_flat, multi_bias, overscans);
        cpl_image_delete(multi_bias);
    }
    else {
        dummy = mos_remove_bias(master_flat, master_bias->data, overscans);
    }
    cpl_table_delete(overscans); overscans = NULL;
    cpl_image_delete(master_flat);
    master_flat = dummy; //This master flat is only used for tracing, I think

    if (master_flat == NULL)
        fors_calib_exit("Cannot remove bias from flat field");

    if (added_flat) {
        cpl_image_delete(added_flat);
        added_flat = add_dummy;

        if (added_flat == NULL)
            fors_calib_exit("Cannot remove bias from added flat field");

        trace_flat = added_flat;
    }
    else
        trace_flat = master_flat;

    cpl_msg_indent_less();
    cpl_msg_info(recipe, "Load arc lamp exposure...");
    cpl_msg_indent_more();

    /* Load arc */
    mosca::fiera_config arc_ccd_config(header);
    cpl_propertylist_delete(header); header = NULL;
    fors_image * arc_raw = fors_image_load
                (cpl_frameset_find_const(frameset, arc_tag));

    /* Update RON estimation from bias */
    cpl_propertylist * master_bias_header =
       cpl_propertylist_load(cpl_frame_get_filename(bias_frame), 0);
    fors_update_ccd_ron(arc_ccd_config, master_bias_header);
    cpl_propertylist_delete(master_bias_header);
    if(!cpl_errorstate_is_equal(error_prevstate))
        fors_calib_exit("Could not get RON from master bias "
                "(missing QC DET OUT? RON keywords)");
    
    /* Create arc variances map */
    fors_image_variance_from_detmodel(arc_raw, arc_ccd_config);
    if(!cpl_errorstate_is_equal(error_prevstate))
        fors_calib_exit("Cannot create variances map");
    
    /* Get the non-linear pixels */
    cpl_mask * nonlinear_arc_mask = 
            cpl_mask_threshold_image_create(arc_raw->data,
                         config.nonlinear_level, std::numeric_limits<double>::max());
    /* Get the A/D saturated pixels */
    cpl_mask *  saturated_arc_mask = 
            cpl_mask_threshold_image_create(arc_raw->data,
                            65535., std::numeric_limits<double>::max());
    cpl_mask * saturated_0 = 
            cpl_mask_threshold_image_create(arc_raw->data,
                            -std::numeric_limits<double>::max(), 
                            std::numeric_limits<double>::min());
    cpl_mask_or(saturated_arc_mask, saturated_0);
    cpl_mask_delete(saturated_0);

    /* Subtract overscan */
    fors_image * arc_red = fors_subtract_prescan(arc_raw, arc_ccd_config);
    if(!cpl_errorstate_is_equal(error_prevstate))
        fors_calib_exit("Cannot subtract pre/overscan");

    /* Trimm pre/overscan */
    fors_trimm_preoverscan(arc_red, arc_ccd_config);
    fors_trimm_preoverscan(nonlinear_arc_mask, arc_ccd_config);
    fors_trimm_preoverscan(saturated_arc_mask, arc_ccd_config);
    fors_image_delete(&arc_raw);
    if(!cpl_errorstate_is_equal(error_prevstate))
        fors_calib_exit("Cannot trimm pre/overscan");

    /* Subtract bias */
    cpl_msg_info(recipe, "Remove the master bias from arc...");
    fors_subtract_bias(arc_red, master_bias);
    if(!cpl_errorstate_is_equal(error_prevstate))
        fors_calib_exit("Cannot remove bias from arc lamp exposure");
    
    /* Assigning the data buffer to the spectra */
    spectra = arc_red->data;
    size_spec = cpl_image_get_size_x(spectra);

    
    cpl_msg_indent_less();
    cpl_msg_info(recipe, "Load input line catalog...");
    cpl_msg_indent_more();

    /*
     * Get the reference lines
     */
    
    lines = fors_calib_get_reference_lines(frameset, arc_tag, 
                                           config.ignore_lines,
                                           config.used_linesets);
    if(lines == NULL)
        fors_calib_exit("Cannot get reference lines");
    nlines = cpl_vector_get_size(lines);
    

    /*
     * Start actual calibration
     */
    
    if (lss || treat_as_lss) {

        cpl_size first_row, last_row;
        cpl_size ylow, yhig;
        cpl_propertylist * wcs_header; 

        /* FIXME:
         * The LSS data calibration is still dirty: it doesn't apply
         * any spatial rectification, and only in future an external
         * spectral curvature model would be provided in input. Here
         * and there temporary solutions are adopted, such as accepting
         * the preliminary wavelength calibration.
         */


        /*
         * In the case of LSS data, extract the spectra directly
         * on the first attempt. The spectral curvature model may
         * be provided in input, in future releases.
         */

        cpl_msg_indent_less();
        cpl_msg_info(recipe, "Perform wavelength calibration...");
        cpl_msg_indent_more();

        nx = cpl_image_get_size_x(spectra);
        ny = cpl_image_get_size_y(spectra);

        wavemap = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);
        idscoeff_all = cpl_table_new(ny);

        if (mos_subtract_background(spectra))
            fors_calib_exit("Cannot subtract the background");

        rectified = mos_wavelength_calibration_raw(spectra, lines, config.dispersion,
                                                   config.peakdetection, config.wradius,
                                                   config.wdegree, config.wreject, ref_wave,
                                                   &config.startwavelength,
                                                   &config.endwavelength, NULL,
                                                   NULL, idscoeff_all, wavemap, 
                                                   NULL, NULL, NULL, NULL);

        if (rectified == NULL)
            fors_calib_exit("Wavelength calibration failure.");

        if (!cpl_table_has_valid(idscoeff_all, "c0"))
            fors_calib_exit("Wavelength calibration failure.");

        cpl_image_delete(rectified); rectified = NULL;

        first_row = 0;
        while (!cpl_table_is_valid(idscoeff_all, "c0", first_row))
            first_row++;

        last_row = ny - 1;
        while (!cpl_table_is_valid(idscoeff_all, "c0", last_row))
            last_row--;

        ylow = first_row + 1;
        yhig = last_row + 1;

        if (ylow >= yhig) {
            cpl_error_reset();
            fors_calib_exit("No spectra could be detected.");
        }

        cpl_msg_info(recipe, 
                     "Spectral pattern was detected on %"CPL_SIZE_FORMAT
                     " out of %"CPL_SIZE_FORMAT" CCD rows", 
                     yhig - ylow, ny);

        dummy = cpl_image_extract(spectra, 1, ylow, nx, yhig);
        cpl_image_delete(spectra); spectra = dummy;

        ccd_ysize = (int)ny;
        ny = cpl_image_get_size_y(spectra);

        residual = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);

        fiterror = static_cast<double *>(cpl_calloc(ny, sizeof(double)));
        fitlines = static_cast<int *>(cpl_calloc(ny, sizeof(int)));
        idscoeff = cpl_table_new(ny);
        restable = cpl_table_new(nlines);

       //Table with positions of the detected lines used for wavelength calibration
       cpl_table * detected_lines = cpl_table_new(1);

       rectified = mos_wavelength_calibration_raw(spectra, lines, config.dispersion,
                                                   config.peakdetection, config.wradius,
                                                   config.wdegree, config.wreject, ref_wave,
                                                   &config.startwavelength, 
                                                   &config.endwavelength, fitlines, 
                                                   fiterror, idscoeff, NULL,
                                                   residual, restable, NULL,
                                                   detected_lines);
       fors_dfs_save_table(frameset, detected_lines, detected_lines_tag, NULL,
                           parlist, recipe, ref_arc_frame);
       cpl_table_delete(detected_lines);
       if(cpl_error_get_code() != CPL_ERROR_NONE)
           fors_calib_exit(NULL);

        if (rectified == NULL)
            fors_calib_exit("Wavelength calibration failure.");

        if (!cpl_table_has_valid(idscoeff, "c0"))
            fors_calib_exit("Wavelength calibration failure.");

        /*
         * A dummy slit locations table
         */

        slits = cpl_table_new(1);
        const char *clab[6] = {"c0", "c1", "c2", "c3", "c4", "c5"};
        cpl_table_new_column(slits, "slit_id", CPL_TYPE_INT);
        cpl_table_new_column(slits, "xtop", CPL_TYPE_DOUBLE);
        cpl_table_new_column(slits, "ytop", CPL_TYPE_DOUBLE);
        cpl_table_new_column(slits, "xbottom", CPL_TYPE_DOUBLE);
        cpl_table_new_column(slits, "ybottom", CPL_TYPE_DOUBLE);
        cpl_table_new_column(slits, "position", CPL_TYPE_INT);
        cpl_table_new_column(slits, "length", CPL_TYPE_INT);
        cpl_table_set_column_unit(slits, "xtop", "pixel");
        cpl_table_set_column_unit(slits, "ytop", "pixel");
        cpl_table_set_column_unit(slits, "xbottom", "pixel");
        cpl_table_set_column_unit(slits, "ybottom", "pixel");
        cpl_table_set_column_unit(slits, "position", "pixel");
        cpl_table_set_column_unit(slits, "length", "pixel");
        cpl_table_set_int(slits, "slit_id", 0, 0);
        int cnull; //It is not checked because the first and last row should contain valid calibrations... I think
        cpl_polynomial * top_ids = cpl_polynomial_new(1);
        for (cpl_size k = 0; k <= config.wdegree; k++) {
            double c = cpl_table_get_double(idscoeff, clab[k], 0, &cnull);
            cpl_polynomial_set_coeff(top_ids, &k, c);
        }
        double xtop = cpl_polynomial_eval_1d(top_ids, 0.0, NULL) + 0.5;
        cpl_table_set_double(slits, "xtop", 0, xtop);
        cpl_table_set_double(slits, "ytop", 0, (double)last_row+1);
        cpl_polynomial * botom_ids = cpl_polynomial_new(1);
        for (cpl_size k = 0; k <= config.wdegree; k++) {
            double c = cpl_table_get_double(idscoeff, clab[k], cpl_table_get_nrow(idscoeff) -1, &cnull);
            cpl_polynomial_set_coeff(botom_ids, &k, c);
        }
        double xbottom = cpl_polynomial_eval_1d(botom_ids, 0.0, NULL) + 0.5;
        cpl_table_set_double(slits, "xbottom", 0, xbottom);
        cpl_table_set_double(slits, "ybottom", 0, (double)first_row+1);
        cpl_table_set_int(slits, "position", 0, 0);
        cpl_table_set_int(slits, "length", 0, (int)ny);

        fors_dfs_save_table(frameset, slits, slit_location_tag, NULL,
                            parlist, recipe, ref_flat_frame);
        if(cpl_error_get_code() != CPL_ERROR_NONE)
            fors_calib_exit(NULL);

        /*
         * A dummy tracing table
         */
        polytraces = cpl_table_new(2);
        cpl_table_new_column(polytraces, "slit_id", CPL_TYPE_INT);
        cpl_table_new_column(polytraces, "c0", CPL_TYPE_DOUBLE);
        cpl_table_new_column(polytraces, "c1", CPL_TYPE_DOUBLE);
        cpl_table_new_column(polytraces, "c2", CPL_TYPE_DOUBLE);
        
        cpl_table_set_int(polytraces, "slit_id", 0, 0);
        cpl_table_set_int(polytraces, "slit_id", 1, 0);
        cpl_table_set_double(polytraces, "c0", 0, (double)last_row);
        cpl_table_set_double(polytraces, "c0", 1, (double)first_row+1);
        cpl_table_set_double(polytraces, "c1", 0, 0.);
        cpl_table_set_double(polytraces, "c1", 1, 0.);
        cpl_table_set_double(polytraces, "c2", 0, 0.);
        cpl_table_set_double(polytraces, "c2", 1, 0.);

        fors_dfs_save_table(frameset, restable, disp_residuals_table_tag, NULL,
                            parlist, recipe, ref_arc_frame);
        if(cpl_error_get_code() != CPL_ERROR_NONE)
            fors_calib_exit(NULL);

        cpl_table_delete(restable); restable = NULL;

        if (config.wmode) {
            cpl_image_delete(rectified); rectified = NULL;
            cpl_image_delete(wavemap); wavemap = NULL;
            mos_interpolate_wavecalib(idscoeff, wavemap, config.wmode, 2);
            mos_interpolate_wavecalib(idscoeff_all, wavemap, config.wmode, 2);
            wavemap = mos_map_idscoeff(idscoeff_all, nx, ref_wave,
                                       config.startwavelength, config.endwavelength);
            rectified = mos_wavelength_calibration(spectra, ref_wave,
                                                   config.startwavelength, 
                                                   config.endwavelength, config.dispersion, 
                                                   idscoeff, 0);
        }

        cpl_table_delete(idscoeff_all); idscoeff_all = NULL;

        cpl_table_wrap_double(idscoeff, fiterror, "error"); fiterror = NULL;
        cpl_table_set_column_unit(idscoeff, "error", "pixel");
        cpl_table_wrap_int(idscoeff, fitlines, "nlines"); fitlines = NULL;

        for (i = 0; i < ny; i++)
            if (!cpl_table_is_valid(idscoeff, "c0", i))
                cpl_table_set_invalid(idscoeff, "error", i);

        delta = mos_map_pixel(idscoeff, ref_wave, config.startwavelength,
                              config.endwavelength, config.dispersion, 2);

        
        /* Get the mosca wave calib */
        mosca::wavelength_calibration wave_cal(idscoeff, ref_wave);
        
        /* Check that the wavelength solution is monotonically increasing */
        for(size_t spa_row = 0 ; spa_row < (size_t)ny; spa_row++)
            if(wave_cal.has_valid_cal((double)spa_row))
                if(!wave_cal.is_monotonical(spa_row, config.startwavelength,
                                            config.endwavelength, 
                                            config.dispersion))
                {
                    std::stringstream error_msg;
                    error_msg <<"The wavelength solution at row "<<spa_row<<
                         " does not increase monotonically, "
                         "which is physically impossible. Try with new parameters.";
                    throw std::range_error(error_msg.str());
                }

        
//%%%%%
        wcs_header = cpl_propertylist_new();
        cpl_propertylist_update_double(wcs_header, "CRPIX1", 1.0);
        cpl_propertylist_update_double(wcs_header, "CRPIX2", 1.0);
        cpl_propertylist_update_double(wcs_header, "CRVAL1",
                                       config.startwavelength + config.dispersion/2);
        cpl_propertylist_update_double(wcs_header, "CRVAL2", 1.0);
        /* cpl_propertylist_update_double(header, "CDELT1", config.dispersion);
        cpl_propertylist_update_double(header, "CDELT2", 1.0); */
        cpl_propertylist_update_double(wcs_header, "CD1_1", config.dispersion);
        cpl_propertylist_update_double(wcs_header, "CD1_2", 0.0);
        cpl_propertylist_update_double(wcs_header, "CD2_1", 0.0);
        cpl_propertylist_update_double(wcs_header, "CD2_2", 1.0);
        cpl_propertylist_update_string(wcs_header, "CTYPE1", "LINEAR");
        cpl_propertylist_update_string(wcs_header, "CTYPE2", "PIXEL");

        fors_dfs_save_image(frameset, delta, delta_image_tag,
                            wcs_header, parlist, recipe, ref_arc_frame);
        if(cpl_error_get_code() != CPL_ERROR_NONE)
            fors_calib_exit(NULL);

        cpl_image_delete(delta); delta = NULL;

        cpl_msg_info(recipe, "Valid solutions found: %"CPL_SIZE_FORMAT
                     " out of %"CPL_SIZE_FORMAT" rows", 
                     ny - cpl_table_count_invalid(idscoeff, "c0"), ny);

        cpl_image_delete(spectra); spectra = NULL;

        mean_rms = mos_distortions_rms(rectified, lines, config.startwavelength,
                                       config.dispersion, 6, 0);

        cpl_msg_info(recipe, "Mean residual: %f pixel", mean_rms);

        mean_rms = cpl_table_get_column_mean(idscoeff, "error");
        mean_rms_err = cpl_table_get_column_stdev(idscoeff, "error");

        cpl_msg_info(recipe, "Mean model accuracy: %f pixel (%f A)",
                     mean_rms, mean_rms * config.dispersion);

        restab = mos_resolution_table(rectified, config.startwavelength, config.dispersion,
                                      60000, lines);

        if (restab) {
            cpl_msg_info(recipe, "Mean spectral resolution: %.2f",
                  cpl_table_get_column_mean(restab, "resolution"));
            cpl_msg_info(recipe, 
                  "Mean reference lines FWHM: %.2f +/- %.2f pixel",
                  cpl_table_get_column_mean(restab, "fwhm") / config.dispersion,
                  cpl_table_get_column_mean(restab, "fwhm_rms") / config.dispersion);

            qclist = cpl_propertylist_new();


            /*
             * QC1 parameters
             */
            keyname = "QC.DID";

            if (fors_header_write_string(qclist,
                    keyname,
                    "2.0",
                    "QC1 dictionary")) {
                fors_calib_exit("Cannot write dictionary version "
                        "to QC log file");
            }

            if (mos)
                keyname = "QC.MOS.RESOLUTION";
            else
                keyname = "QC.LSS.RESOLUTION";

            if (fors_header_write_double(qclist, 
                    cpl_table_get_column_mean(restab,
                            "resolution"),
                            keyname, NULL, 
                            "Mean spectral resolution")) {
                fors_calib_exit("Cannot write mean spectral resolution to "
                        "QC log file");
            }

            if (mos)
                keyname = "QC.MOS.RESOLUTION.RMS"; 
            else
                keyname = "QC.LSS.RESOLUTION.RMS";

            if (fors_header_write_double(qclist,
                    cpl_table_get_column_stdev(restab,
                            "resolution"),
                            keyname, NULL, 
                            "Scatter of spectral resolution")) {
                fors_calib_exit("Cannot write spectral resolution scatter "
                        "to QC log file");
            }

            if (mos)
                keyname = "QC.MOS.RESOLUTION.NWAVE";
            else
                keyname = "QC.LSS.RESOLUTION.NWAVE";

            if (fors_header_write_int(qclist, cpl_table_get_nrow(restab) -
                    cpl_table_count_invalid(restab,
                            "resolution"),
                            keyname, NULL,
                            "Number of examined wavelengths "
                            "for resolution computation")) {
                fors_calib_exit("Cannot write number of lines used in "
                        "spectral resolution computation "
                        "to QC log file");
            }

            if (mos)
                keyname = "QC.MOS.RESOLUTION.MEANRMS";
            else
                keyname = "QC.LSS.RESOLUTION.MEANRMS";

            if (fors_header_write_double(qclist, 
                    cpl_table_get_column_mean(restab,
                            "resolution_rms"),
                            keyname, NULL,
                            "Mean error on spectral "
                            "resolution computation")) {
                fors_calib_exit("Cannot write mean error in "
                        "spectral resolution computation "
                        "to QC log file");
            }

            if (mos)
                keyname = "QC.MOS.RESOLUTION.NLINES";
            else
                keyname = "QC.LSS.RESOLUTION.NLINES";

            if (fors_header_write_int(qclist, 
                    cpl_table_get_column_mean(restab, "nlines") *
                    cpl_table_get_nrow(restab),
                    keyname, NULL,
                    "Number of lines for spectral "
                    "resolution computation")) {
                fors_calib_exit("Cannot write number of examined "
                        "wavelengths in spectral resolution computation "
                        "to QC log file");
            }

            fors_dfs_save_table(frameset, restab, spectral_resolution_tag, 
                                qclist, parlist, recipe, ref_arc_frame);
            if(cpl_error_get_code() != CPL_ERROR_NONE)
                fors_calib_exit(NULL);

            cpl_table_delete(restab); restab = NULL;
            cpl_propertylist_delete(qclist); qclist = NULL;

        }
        else
            fors_calib_exit("Cannot compute the spectral resolution table");

        cpl_vector_delete(lines); lines = NULL;
        cpl_msg_indent_less();

        /*
         * Save rectified arc lamp spectrum to disk
         */

        header = cpl_propertylist_new();
        cpl_propertylist_update_double(header, "CRPIX1", 1.0);
        cpl_propertylist_update_double(header, "CRPIX2", 1.0);
        cpl_propertylist_update_double(header, "CRVAL1", 
                                       config.startwavelength + config.dispersion/2);
        cpl_propertylist_update_double(header, "CRVAL2", 1.0);
        /* cpl_propertylist_update_double(header, "CDELT1", config.dispersion);
        cpl_propertylist_update_double(header, "CDELT2", 1.0); */
        cpl_propertylist_update_double(header, "CD1_1", config.dispersion);
        cpl_propertylist_update_double(header, "CD1_2", 0.0);
        cpl_propertylist_update_double(header, "CD2_1", 0.0);
        cpl_propertylist_update_double(header, "CD2_2", 1.0);
        cpl_propertylist_update_string(header, "CTYPE1", "LINEAR");
        cpl_propertylist_update_string(header, "CTYPE2", "PIXEL");
        cpl_propertylist_update_int(header, "ESO PRO DATANCOM", 1);

        /* Rectify the arc masks */
        cpl_mask * nonlinear_arc_mask_rect_mapped =
                fors_calib_mask_rect_mapped(nonlinear_arc_mask, slits, idscoeff,
                                            polytraces,ref_wave, config);

        cpl_mask * saturated_arc_mask_rect_mapped =
                fors_calib_mask_rect_mapped(saturated_arc_mask, slits, idscoeff,
                                            polytraces,ref_wave, config);

        cpl_image * combined_arc_mask = 
                fors_bpm_create_combined_bpm(nonlinear_arc_mask_rect_mapped,
                                             saturated_arc_mask_rect_mapped);
        
        /* Save the arc */
        fors_dfs_save_image_mask(frameset, rectified, combined_arc_mask,
                                 reduced_lamp_tag, header, 
                                 parlist, recipe, ref_arc_frame);
        if(cpl_error_get_code() != CPL_ERROR_NONE)
            fors_calib_exit(NULL);

        cpl_mask_delete(nonlinear_arc_mask);
        cpl_mask_delete(nonlinear_arc_mask_rect_mapped);
        cpl_mask_delete(saturated_arc_mask);
        cpl_mask_delete(saturated_arc_mask_rect_mapped);
        cpl_image_delete(combined_arc_mask);
        cpl_image_delete(rectified); rectified = NULL;
        cpl_propertylist_delete(header); header = NULL;

        fors_dfs_save_table(frameset, idscoeff, disp_coeff_tag, NULL, 
                            parlist, recipe, ref_arc_frame);
        if(cpl_error_get_code() != CPL_ERROR_NONE)
            fors_calib_exit(NULL);

        header = dfs_load_header(frameset, arc_tag, 0);

        if (header == NULL)
            fors_calib_exit("Cannot reload arc lamp header");

        compute_central_wave = 0;
        if (lss) {
            /***
                if (fabs(1.0 - cpl_propertylist_get_double(header,
                                             "ESO INS SLIT WID")) < 0.05)
             ***/
            compute_central_wave = 1;
        }
        else {
            if (fabs(mxpos) < 0.05)
                compute_central_wave = 1;
        }

        /*
         * QC1 parameters
         */
        keyname = "QC.DID";

        if (fors_header_write_string(header,
                keyname,
                "2.0",
                "QC1 dictionary")) {
            fors_calib_exit("Cannot write dictionary version "
                    "to QC log file");
        }

        if (fors_header_write_double(header,
                mean_rms,
                "QC.WAVE.ACCURACY",
                "pixel",
                "Mean accuracy of wavecalib model")) {
            fors_calib_exit("Cannot write mean wavelength calibration "
                    "accuracy to QC log file");
        }

        if (fors_header_write_double(header,
                mean_rms_err,
                "QC.WAVE.ACCURACY.ERROR",
                "pixel",
                "Error on accuracy of wavecalib model")) {
            fors_calib_exit("Cannot write error on wavelength calibration "
                    "accuracy to QC log file");
        }

        if (compute_central_wave) {

            data = cpl_image_get_data_float(wavemap);

            if (lss) {
                if (fors_header_write_double(header, 
                        data[nx/2 + ccd_ysize*nx/2],
                        "QC.LSS.CENTRAL.WAVELENGTH",
                        "Angstrom", 
                        "Wavelength at CCD center")) {
                    fors_calib_exit("Cannot write central wavelength to QC "
                            "log file");
                }
            }
            else {
                if (fors_header_write_double(header, 
                        data[nx/2 + ccd_ysize*nx/2],
                        "QC.MOS.CENTRAL.WAVELENGTH",
                        "Angstrom", 
                        "Wavelength at CCD center")) {
                    fors_calib_exit("Cannot write central wavelength to QC "
                            "log file");
                }
            }
        }

        fors_dfs_save_image(frameset, wavemap, wavelength_map_tag, header,
                            parlist, recipe, ref_arc_frame);
        if(cpl_error_get_code() != CPL_ERROR_NONE)
            fors_calib_exit(NULL);

        cpl_image_delete(wavemap); wavemap = NULL;

        cpl_propertylist_erase_regexp(header, "^ESO QC ", 0);

        cpl_propertylist_update_double(header, "CRPIX2", 1.0);
        cpl_propertylist_update_double(header, "CRVAL2", 1.0);
        /* cpl_propertylist_update_double(header, "CDELT2", 1.0); */
        cpl_propertylist_update_double(header, "CD1_1", 1.0);
        cpl_propertylist_update_double(header, "CD1_2", 0.0);
        cpl_propertylist_update_double(header, "CD2_1", 0.0);
        cpl_propertylist_update_double(header, "CD2_2", 1.0);
        cpl_propertylist_update_string(header, "CTYPE1", "LINEAR");
        cpl_propertylist_update_string(header, "CTYPE2", "PIXEL");

        fors_dfs_save_image(frameset, residual, disp_residuals_tag, header,
                            parlist, recipe, ref_arc_frame);
        if(cpl_error_get_code() != CPL_ERROR_NONE)
            fors_calib_exit(NULL);

        cpl_image_delete(residual); residual = NULL;

        cpl_propertylist_delete(header); header = NULL;
        
        /* Read grism configuration */
        //TODO: Add the waveref to the grism_tables
        cpl_propertylist * flat_header = dfs_load_header(frameset, flat_tag, 0);
        if (flat_header == NULL) {
            cpl_msg_error(recipe, "Cannot load header of %s frame", flat_tag);
            return 0;
        }
        double wave_ref =  cpl_propertylist_get_double(flat_header, "ESO INS GRIS1 WLEN");
        if (wave_ref < 3000.0)   /* Perhaps in nanometers... */
            wave_ref *= 10;
        cpl_propertylist_delete(flat_header);
        cpl_frameset * grism_frame = fors_frameset_extract(frameset, "GRISM_TABLE");
        std::auto_ptr<mosca::grism_config> grism_cfg = 
                fors_grism_config_from_frame(cpl_frameset_get_position(grism_frame, 0), wave_ref);
        cpl_frameset_delete(grism_frame);

        /* Get the detected slit locations */
        fors::detected_slits det_slits = 
            fors::detected_slits_from_tables(slits, polytraces, size_spec);
        
        /* Get the calibrated slits */
        fors::calibrated_slits calib_slits(det_slits, wave_cal, *grism_cfg,
                                           (size_t)nx, (size_t)ccd_ysize); 
        for(std::vector<mosca::calibrated_slit>::const_iterator 
                slit_it = calib_slits.begin();
            slit_it != calib_slits.end() ; slit_it++)
        {
            if(!slit_it->has_valid_wavecal())
                cpl_msg_warning(cpl_func, "Slit %d does not contain valid "
                        "wavelength calibration. Skipping it for master flat", 
                        slit_it->slit_id());
        }

        /* Flat field creation */
        cpl_msg_info(cpl_func, "Perform flat field combination");
        cpl_msg_indent_more();
        std::auto_ptr<mosca::image> master_flat_d;
        std::vector<std::vector<double> > slit_sat_ratio;
        std::vector<std::vector<int> > slit_sat_count;
        cpl_mask ** nonlinear_flat_masks;
        cpl_mask ** saturated_flat_masks;
        std::auto_ptr<mosca::fiera_config> ccd_config;
        master_flat_d = fors_calib_flat_mos_create_master_flat(calib_slits,
                wave_cal, *grism_cfg, master_bias, bias_frame,
                config, frameset, flat_tag, 
                config.nonlinear_level, config.max_nonlinear_ratio, 
                slit_sat_ratio, slit_sat_count,
                nonlinear_flat_masks, 
                saturated_flat_masks, ccd_config);
        if(master_flat_d.get() == 0)
            fors_calib_exit("Cannot combine flat frames");

        /* Getting combined mask */
        cpl_image * flat_mask = fors_bpm_create_combined_bpm(nonlinear_flat_masks,
                                                             saturated_flat_masks,
                                                             nflats);
        /*
         * Flat field normalisation is done directly on the master flat
         * field (without spatial rectification first). The spectral
         * curvature model may be provided in input, in future releases.
         */

        cpl_msg_indent_less();
        cpl_msg_info(recipe, "Perform LSS flat field normalisation...");
        cpl_msg_indent_more();
        std::auto_ptr<mosca::image> norm_flat(NULL);
        norm_flat.reset(new mosca::image(cpl_image_cast(master_flat_d->get_cpl_image(), CPL_TYPE_FLOAT),
                                         cpl_image_cast(master_flat_d->get_cpl_image_err(), CPL_TYPE_FLOAT), true));
        
        fors::flat_normaliser normaliser;
        normaliser.lss_normalise(*norm_flat, wave_cal, 
                config.sradius, config.dradius, 
                config.spa_polyorder, config.disp_nknots,
                config.fit_threshold);

        cpl_msg_indent_less();

        /* Getting slit dispersion profile */
        cpl_image * wave_profiles;
        wave_profiles = normaliser.get_wave_profiles_im();
        
        /* Getting the normalisation factors used in the SED */
        cpl_propertylist * sed_header = cpl_propertylist_new();
        const std::vector<float>& sed_norm = normaliser.get_wave_profiles_norm();
        for(size_t ised = 0 ; ised < sed_norm.size();ised++)
        {
            std::ostringstream norm_key;
            norm_key<< "ESO QC FLAT SED"<<ised+1<<" NORM ";
            cpl_propertylist_append_float(sed_header, norm_key.str().c_str(), 
                                          sed_norm[ised]);
        }

        /* Saving slit dispersion profiles */
        std::ostringstream prof_filename_oss;
        prof_filename_oss << flat_disp_profile_tag << ".fits";
        std::string prof_filename = prof_filename_oss.str();
        std::transform(prof_filename.begin(), prof_filename.end(), prof_filename.begin(), ::tolower);
        cpl_propertylist_append_string(sed_header, CPL_DFS_PRO_TYPE, "REDUCED");
        cpl_propertylist_append_string(sed_header, CPL_DFS_PRO_CATG, flat_disp_profile_tag);
        cpl_dfs_save_image(frameset, NULL, parlist, frameset, 
                           ref_flat_frame, wave_profiles, CPL_BPP_IEEE_FLOAT,
                           recipe, sed_header, NULL, PACKAGE "/" PACKAGE_VERSION,  
                           prof_filename.c_str());
        if(cpl_error_get_code() != CPL_ERROR_NONE)
            fors_calib_exit("Cannot save flats");
        cpl_propertylist_delete(sed_header);
        cpl_image_delete(wave_profiles);


        /* Computing mapped flats */
        cpl_msg_info(recipe, "Perform mapping of flats...");
        cpl_image * master_flat_f = cpl_image_cast(master_flat_d->get_cpl_image(), 
                                                   CPL_TYPE_FLOAT);
        cpl_image * master_flat_rect = cpl_image_extract(master_flat_f, 1, ylow, nx, yhig);

        mapped_flat = mos_wavelength_calibration(master_flat_rect , ref_wave,
                                      config.startwavelength, config.endwavelength,
                                      config.dispersion, idscoeff, 0);


        if(norm_flat.get() != NULL)
        {
            cpl_image * norm_flat_f = cpl_image_cast(norm_flat->get_cpl_image(), 
                                                     CPL_TYPE_FLOAT);
            cpl_image * norm_flat_rect = cpl_image_extract(norm_flat_f, 1, ylow, nx, yhig);

            mapped_nflat = mos_wavelength_calibration(norm_flat_rect, ref_wave,
                    config.startwavelength, config.endwavelength,
                    config.dispersion, idscoeff, 0);
            cpl_image_delete(norm_flat_rect); norm_flat_rect = NULL;
            cpl_image_delete(norm_flat_f); norm_flat_f = NULL;
        }

        /* Saving flats */
        if(fors_calib_flats_save(master_flat_d, flat_mask,
                norm_flat, mapped_flat, mapped_nflat, det_slits,
                slit_sat_ratio, slit_sat_count, config,
                frameset, flat_tag, master_screen_flat_tag, master_norm_flat_tag,
                mapped_screen_flat_tag, mapped_norm_flat_tag,
                parlist, ref_flat_frame, *ccd_config) != 0)
            fors_calib_exit("Cannot save flats");

        cpl_image_delete(master_flat_f); master_flat_f = NULL;
        cpl_image_delete(master_flat_rect); master_flat_rect = NULL;
        cpl_image_delete(mapped_flat); mapped_flat = NULL;
        cpl_image_delete(mapped_nflat); mapped_nflat = NULL;
        cpl_propertylist_delete(wcs_header); wcs_header = NULL;
        cpl_image_delete(master_flat); master_flat = NULL;
        cpl_image_delete(flat_mask); 
        cpl_table_delete(idscoeff); idscoeff = NULL;
        cpl_propertylist_delete(save_header); save_header = NULL;
        cpl_table_delete(slits); slits = NULL;
        cpl_table_delete(polytraces); polytraces = NULL;
        fors_image_delete(&master_bias); master_bias = NULL;
        for (size_t i_flat = 0; i_flat < nflats; i_flat++)
        {
            cpl_mask_delete(nonlinear_flat_masks[i_flat]);
            cpl_mask_delete(saturated_flat_masks[i_flat]);
        }
        cpl_free(nonlinear_flat_masks);
        cpl_free(saturated_flat_masks);

        return 0;         /* Successful LSS data reduction */

    }   /* End of LSS data reduction section */


    /*
     * Here the MOS and MXU calibration is carried out.
     */

    /*
     * Detecting spectra on the CCD
     */

    cpl_msg_indent_less();
    cpl_msg_info(recipe, "Detecting spectra on CCD...");
    cpl_msg_indent_more();

    ccd_xsize = nx = cpl_image_get_size_x(spectra);
    ccd_ysize = ny = cpl_image_get_size_y(spectra);

    refmask = cpl_mask_new(nx, ny);

    if (mos_subtract_background(spectra))
	fors_calib_exit("Cannot subtract the background");
 
    checkwave = mos_wavelength_calibration_raw(spectra, lines, 
                      config.dispersion, config.peakdetection, config.wradius, 
                      config.wdegree, config.wreject, ref_wave,
                      &config.startwavelength, &config.endwavelength,
                      NULL, NULL, NULL, NULL, NULL, NULL, refmask, NULL);

    if (checkwave == NULL)
        fors_calib_exit("Wavelength calibration failure.");

    /*
     * Save check image to disk
     */

    header = cpl_propertylist_new();
    cpl_propertylist_update_double(header, "CRPIX1", 1.0);
    cpl_propertylist_update_double(header, "CRPIX2", 1.0);
    cpl_propertylist_update_double(header, "CRVAL1", 
                                   config.startwavelength+config.dispersion/2);
    cpl_propertylist_update_double(header, "CRVAL2", 1.0);
    /* cpl_propertylist_update_double(header, "CDELT1", config.dispersion);
    cpl_propertylist_update_double(header, "CDELT2", 1.0); */
    cpl_propertylist_update_double(header, "CD1_1", config.dispersion);
    cpl_propertylist_update_double(header, "CD1_2", 0.0);
    cpl_propertylist_update_double(header, "CD2_1", 0.0);
    cpl_propertylist_update_double(header, "CD2_2", 1.0);
    cpl_propertylist_update_string(header, "CTYPE1", "LINEAR");
    cpl_propertylist_update_string(header, "CTYPE2", "PIXEL");

    fors_dfs_save_image(frameset, checkwave, spectra_detection_tag, header, 
                        parlist, recipe, ref_flat_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit(NULL);

    cpl_image_delete(checkwave); checkwave = NULL;
    cpl_propertylist_delete(header); header = NULL;

    cpl_msg_info(recipe, "Locate slits at reference wavelength on CCD...");
    slits = mos_locate_spectra(refmask);

    if (!slits) {
        cpl_msg_error(cpl_func, "Error found in %s: %s",
                      cpl_error_get_where(), cpl_error_get_message());
        fors_calib_exit("No slits could be detected!");
    }

    refimage = cpl_image_new_from_mask(refmask);
    cpl_mask_delete(refmask); refmask = NULL;

    save_header = dfs_load_header(frameset, arc_tag, 0);
    fors_dfs_save_image(frameset, refimage, slit_map_tag, save_header,
                        parlist, recipe, ref_flat_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit(NULL);

    cpl_propertylist_delete(save_header); save_header = NULL;

    cpl_image_delete(refimage); refimage = NULL;

    if (config.slit_ident) {

        /*
         * Attempt slit identification: this recipe may continue even
         * in case of failed identification (i.e., the position table is 
         * not produced, but an error is not set). In case of failure,
         * the spectra would be still extracted, even if they would not
         * be associated to slits on the mask.
         * 
         * The reason for making the slit identification an user option 
         * (via the parameter slit_ident) is to offer the possibility 
         * to avoid identifications that are only apparently successful, 
         * as it would happen in the case of an incorrect slit description 
         * in the data header.
         */

        cpl_msg_indent_less();
        cpl_msg_info(recipe, "Attempt slit identification (optional)...");
        cpl_msg_indent_more();

        positions = mos_identify_slits(slits, maskslits, NULL);

        if (positions) {
            cpl_table_delete(slits);
            slits = positions;

            /*
             * Eliminate slits which are _entirely_ outside the CCD
             */

            cpl_table_and_selected_double(slits, 
                                          "ybottom", CPL_GREATER_THAN, ny-1);
            cpl_table_or_selected_double(slits, 
                                          "ytop", CPL_LESS_THAN, 0);
            cpl_table_erase_selected(slits);

            nslits = cpl_table_get_nrow(slits);

            if (nslits == 0)
                fors_calib_exit("No slits found on the CCD");

            cpl_msg_info(recipe, "%d slits are entirely or partially "
                         "contained in CCD", nslits);

        }
        else {
            config.slit_ident = 0;
            cpl_table_delete(maskslits); maskslits = NULL;
            cpl_msg_info(recipe, "Global distortion model cannot be computed");
            if (cpl_error_get_code() != CPL_ERROR_NONE) {
                fors_calib_exit(NULL);
            }
        }
    }


    /*
     * Determination of spectral curvature
     */

    cpl_msg_indent_less();
    cpl_msg_info(recipe, "Determining spectral curvature...");
    cpl_msg_indent_more();

    cpl_msg_info(recipe, "Tracing master flat field spectra edges...");
    traces = mos_trace_flat(trace_flat, slits, ref_wave, 
                            config.startwavelength, config.endwavelength, 
                            config.dispersion);

    if (!traces)
        fors_calib_exit("Tracing failure");

    cpl_image_delete(added_flat); added_flat = NULL;

    cpl_msg_info(recipe, "Fitting flat field spectra edges...");
    polytraces = mos_poly_trace(slits, traces, config.cdegree);

    if (!polytraces)
        fors_calib_exit("Trace fitting failure");

    if (config.cmode) {
        cpl_msg_info(recipe, "Computing global spectral curvature model...");
        mos_global_trace(slits, polytraces, config.cmode);
    }

    fors_dfs_save_table(frameset, traces, curv_traces_tag, NULL, parlist,
                        recipe, ref_flat_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit(NULL);

    cpl_table_delete(traces); traces = NULL;

    coordinate = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);
    spatial = mos_spatial_calibration(spectra, slits, polytraces, ref_wave, 
                  config.startwavelength, config.endwavelength, 
                  config.dispersion, 0, coordinate);

    if (!config.slit_ident) {
        cpl_image_delete(spectra); spectra = NULL;
    }


    /*
     * Final wavelength calibration of spectra having their curvature
     * removed
     */

    cpl_msg_indent_less();
    cpl_msg_info(recipe, "Perform final wavelength calibration...");
    cpl_msg_indent_more();

    nx = cpl_image_get_size_x(spatial);
    ny = cpl_image_get_size_y(spatial);

    idscoeff = cpl_table_new(ny);
    restable = cpl_table_new(nlines);
    rainbow = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);
    residual = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);
    fiterror = static_cast<double*>(cpl_calloc(ny, sizeof(double)));
    fitlines = static_cast<int*>(cpl_calloc(ny, sizeof(int)));

    //Table with positions of the detected lines used for wavelength calibration
    cpl_table * detected_lines = cpl_table_new(1);
    
    rectified = mos_wavelength_calibration_final(spatial, slits, lines, 
                     config.dispersion, config.peakdetection, config.wradius, 
                     config.wdegree, config.wreject, ref_wave, 
                     &config.startwavelength, &config.endwavelength, fitlines, 
                     fiterror, idscoeff, rainbow, residual, restable, 
                     detected_lines);

        fors_dfs_save_image(frameset, spatial, arc_rectified_tag, header,
                        parlist, recipe, ref_arc_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit(NULL);

    if (rectified == NULL)
        fors_calib_exit("Wavelength calibration failure.");

    fors_dfs_save_table(frameset, restable, disp_residuals_table_tag, NULL,
                        parlist, recipe, ref_arc_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit(NULL);

    fors_dfs_save_table(frameset, detected_lines, detected_lines_tag, NULL,
                        parlist, recipe, ref_arc_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit(NULL);

    cpl_table_delete(restable); restable = NULL;
    cpl_table_delete(detected_lines); detected_lines = NULL;

    cpl_table_wrap_double(idscoeff, fiterror, "error"); fiterror = NULL;
    cpl_table_set_column_unit(idscoeff, "error", "pixel");
    cpl_table_wrap_int(idscoeff, fitlines, "nlines"); fitlines = NULL;

    for (i = 0; i < ny; i++)
        if (!cpl_table_is_valid(idscoeff, "c0", i))
            cpl_table_set_invalid(idscoeff, "error", i);

    if (config.wmosmode > 0) {
        mos_interpolate_wavecalib_slit(idscoeff, slits, 1, config.wmosmode - 1);

        cpl_image_delete(rectified);

        rectified = mos_wavelength_calibration(spatial, ref_wave,
                         config.startwavelength, config.endwavelength,
                         config.dispersion, idscoeff, 0);
    }

    cpl_image_delete(spatial); spatial = NULL;

    delta = mos_map_pixel(idscoeff, ref_wave, config.startwavelength,
                          config.endwavelength, config.dispersion, 2);

    /* Get the mosca wave calib */
    mosca::wavelength_calibration wave_cal(idscoeff, ref_wave);
    
    /* Check that the wavelength solution is monotonically increasing */
    for(size_t spa_row = 0 ; spa_row < (size_t)ny; spa_row++)
        if(wave_cal.has_valid_cal((double)spa_row))
            if(!wave_cal.is_monotonical(spa_row, config.startwavelength,
                                        config.endwavelength, 
                                        config.dispersion))
            {
                std::stringstream error_msg;
                error_msg <<"The wavelength solution at row "<<spa_row<<
                     " does not increase monotonically, "
                     "which is physically impossible. Try with new parameters.";
                throw std::range_error(error_msg.str());
            }

    header = cpl_propertylist_new();
    cpl_propertylist_update_double(header, "CRPIX1", 1.0);
    cpl_propertylist_update_double(header, "CRPIX2", 1.0);
    cpl_propertylist_update_double(header, "CRVAL1",
                                   config.startwavelength+config.dispersion/2);
    cpl_propertylist_update_double(header, "CRVAL2", 1.0);
    /* cpl_propertylist_update_double(header, "CDELT1", config.dispersion);
    cpl_propertylist_update_double(header, "CDELT2", 1.0); */
    cpl_propertylist_update_double(header, "CD1_1", config.dispersion);
    cpl_propertylist_update_double(header, "CD1_2", 0.0);
    cpl_propertylist_update_double(header, "CD2_1", 0.0);
    cpl_propertylist_update_double(header, "CD2_2", 1.0);
    cpl_propertylist_update_string(header, "CTYPE1", "LINEAR");
    cpl_propertylist_update_string(header, "CTYPE2", "PIXEL");

    fors_dfs_save_image(frameset, delta, delta_image_tag,
                        header, parlist, recipe, ref_arc_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit(NULL);

    cpl_image_delete(delta); delta = NULL;
    cpl_propertylist_delete(header); header = NULL;

    mean_rms = mos_distortions_rms(rectified, lines, config.startwavelength, 
                                   config.dispersion, 6, 0);

    cpl_msg_info(recipe, "Mean residual: %f pixel", mean_rms);

    mean_rms = cpl_table_get_column_mean(idscoeff, "error");
    mean_rms_err = cpl_table_get_column_stdev(idscoeff, "error");

    cpl_msg_info(recipe, "Mean model accuracy: %f pixel (%f A)", 
                 mean_rms, mean_rms * config.dispersion);

    restab = mos_resolution_table(rectified, config.startwavelength, 
                                  config.dispersion, 60000, lines);

    if (restab) {
        cpl_msg_info(recipe, "Mean spectral resolution: %.2f", 
                   cpl_table_get_column_mean(restab, "resolution"));
        cpl_msg_info(recipe, "Mean reference lines FWHM: %.2f +/- %.2f pixel",
             cpl_table_get_column_mean(restab, "fwhm") / config.dispersion,
             cpl_table_get_column_mean(restab, "fwhm_rms") / config.dispersion);

        qclist = cpl_propertylist_new();

        /*
         * QC1 parameters
         */
        keyname = "QC.DID";

        if (fors_header_write_string(qclist,
                keyname,
                "2.0",
                "QC1 dictionary")) {
            fors_calib_exit("Cannot write dictionary version "
                    "to QC log file");
        }

        if (mos)
            keyname = "QC.MOS.RESOLUTION";
        else
            keyname = "QC.MXU.RESOLUTION";

        if (fors_header_write_double(qclist, 
                cpl_table_get_column_mean(restab,
                        "resolution"),
                        keyname,
                        "Angstrom",
                        "Mean spectral resolution")) {
            fors_calib_exit("Cannot write mean spectral resolution to QC "
                    "log file");
        }

        if (mos)
            keyname = "QC.MOS.RESOLUTION.RMS";
        else
            keyname = "QC.MXU.RESOLUTION.RMS";

        if (fors_header_write_double(qclist, 
                cpl_table_get_column_stdev(restab, 
                        "resolution"),
                        keyname,
                        "Angstrom", 
                        "Scatter of spectral resolution")) {
            fors_calib_exit("Cannot write spectral resolution scatter "
                    "to QC log file");
        }

        if (mos)
            keyname = "QC.MOS.RESOLUTION.NWAVE";
        else
            keyname = "QC.MXU.RESOLUTION.NWAVE";

        if (fors_header_write_int(qclist, cpl_table_get_nrow(restab) -
                cpl_table_count_invalid(restab, 
                        "resolution"),
                        keyname,
                        NULL,
                        "Number of examined wavelengths "
                        "for resolution computation")) {
            fors_calib_exit("Cannot write number of lines used in "
                    "spectral resolution computation "
                    "to QC log file");
        }

        if (mos)
            keyname = "QC.MOS.RESOLUTION.MEANRMS";
        else
            keyname = "QC.MXU.RESOLUTION.MEANRMS";

        if (fors_header_write_double(qclist,
                cpl_table_get_column_mean(restab,
                        "resolution_rms"),
                        keyname, NULL,
                        "Mean error on spectral "
                        "resolution computation")) {
            fors_calib_exit("Cannot write mean error in "
                    "spectral resolution computation "
                    "to QC log file");
        }

        if (mos)
            keyname = "QC.MOS.RESOLUTION.NLINES";
        else
            keyname = "QC.MXU.RESOLUTION.NLINES";

        if (fors_header_write_int(qclist,
                cpl_table_get_column_mean(restab, "nlines") *
                cpl_table_get_nrow(restab),
                keyname, NULL,
                "Number of lines for spectral "
                "resolution computation")) {
            fors_calib_exit("Cannot write number of examined "
                    "wavelengths in spectral resolution computation "
                    "to QC log file");
        }

        fors_dfs_save_table(frameset, restab, spectral_resolution_tag, qclist,
                            parlist, recipe, ref_arc_frame);
        if(cpl_error_get_code() != CPL_ERROR_NONE)
            fors_calib_exit(NULL);

        cpl_table_delete(restab); restab = NULL;
        cpl_propertylist_delete(qclist); qclist = NULL;

    }
    else
        fors_calib_exit("Cannot compute the spectral resolution table");

    cpl_vector_delete(lines); lines = NULL;

    fors_dfs_save_table(frameset, idscoeff, disp_coeff_tag, NULL,
                        parlist, recipe, ref_arc_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit(NULL);
//%%%

//%%%

    /*
     * Global distortion models
     */

    if (config.slit_ident) {

        cpl_msg_info(recipe, "Computing global distortions model");
        global = mos_global_distortion(slits, maskslits, idscoeff, 
                                       polytraces, ref_wave);

        if (global && 0) {
            cpl_table *stest;
            cpl_table *ctest;
            cpl_table *dtest;
            cpl_image *itest;

            stest = mos_build_slit_location(global, maskslits, ccd_ysize);

            ctest = mos_build_curv_coeff(global, maskslits, stest);
            fors_dfs_save_table(frameset, ctest, "CURVS", NULL,
                                parlist, recipe, ref_flat_frame);
            if(cpl_error_get_code() != CPL_ERROR_NONE)
                fors_calib_exit(NULL);

            itest = mos_spatial_calibration(spectra, stest, ctest, 
                                            ref_wave, config.startwavelength, 
                                            config.endwavelength, 
                                            config.dispersion, 0, NULL);
            cpl_table_delete(ctest); ctest = NULL;
            cpl_image_delete(itest); itest = NULL;
            fors_dfs_save_table(frameset, stest, "SLITS", NULL,
                                parlist, recipe, ref_flat_frame);
            if(cpl_error_get_code() != CPL_ERROR_NONE)
                fors_calib_exit(NULL);

            dtest = mos_build_disp_coeff(global, stest);
            fors_dfs_save_table(frameset, dtest, "DISPS", NULL,
                                parlist, recipe, ref_flat_frame);
            if(cpl_error_get_code() != CPL_ERROR_NONE)
                fors_calib_exit(NULL);

            cpl_table_delete(dtest); dtest = NULL;
            cpl_table_delete(stest); stest = NULL;
        }

        if (global) {
            fors_dfs_save_table(frameset, global, global_distortion_tag, NULL,
                    parlist, recipe, ref_arc_frame);
            if(cpl_error_get_code() != CPL_ERROR_NONE)
                fors_calib_exit(NULL);

            cpl_table_delete(global); global = NULL;
        }

        cpl_image_delete(spectra); spectra = NULL;
        cpl_table_delete(maskslits); maskslits = NULL;
    }

    /* Create header for wavelength calibrated images */
    header = cpl_propertylist_new();
    cpl_propertylist_update_double(header, "CRPIX1", 1.0);
    cpl_propertylist_update_double(header, "CRPIX2", 1.0);
    cpl_propertylist_update_double(header, "CRVAL1", 
                                   config.startwavelength+config.dispersion/2);
    cpl_propertylist_update_double(header, "CRVAL2", 1.0);
    /* cpl_propertylist_update_double(header, "CDELT1", config.dispersion);
    cpl_propertylist_update_double(header, "CDELT2", 1.0); */
    cpl_propertylist_update_double(header, "CD1_1", config.dispersion);
    cpl_propertylist_update_double(header, "CD1_2", 0.0);
    cpl_propertylist_update_double(header, "CD2_1", 0.0);
    cpl_propertylist_update_double(header, "CD2_2", 1.0);
    cpl_propertylist_update_string(header, "CTYPE1", "LINEAR");
    cpl_propertylist_update_string(header, "CTYPE2", "PIXEL");
    cpl_propertylist_update_int(header, "ESO PRO DATANCOM", 1);

    /* Rectify the arc masks */
    cpl_mask * nonlinear_arc_mask_rect_mapped =
            fors_calib_mask_rect_mapped(nonlinear_arc_mask, slits, idscoeff,
                                        polytraces,ref_wave, config);

    cpl_mask * saturated_arc_mask_rect_mapped =
            fors_calib_mask_rect_mapped(saturated_arc_mask, slits, idscoeff,
                                        polytraces,ref_wave, config);

    cpl_image * combined_arc_mask = 
            fors_bpm_create_combined_bpm(nonlinear_arc_mask_rect_mapped,
                                         saturated_arc_mask_rect_mapped);
    
    /* Save the arc */
    fors_dfs_save_image_mask(frameset, rectified, combined_arc_mask,
                             reduced_lamp_tag, header, 
                             parlist, recipe, ref_arc_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit(NULL);

    cpl_mask_delete(nonlinear_arc_mask);
    cpl_mask_delete(nonlinear_arc_mask_rect_mapped);
    cpl_mask_delete(saturated_arc_mask);
    cpl_mask_delete(saturated_arc_mask_rect_mapped);
    cpl_image_delete(combined_arc_mask);
    cpl_image_delete(rectified); rectified = NULL;
    cpl_propertylist_delete(header); header = NULL;
    
    save_header = dfs_load_header(frameset, arc_tag, 0);

    cpl_propertylist_update_double(save_header, "CRPIX2", 1.0);
    cpl_propertylist_update_double(save_header, "CRVAL2", 1.0);
    /* cpl_propertylist_update_double(save_header, "CDELT2", 1.0); */
    cpl_propertylist_update_double(save_header, "CD1_1", 1.0);
    cpl_propertylist_update_double(save_header, "CD1_2", 0.0);
    cpl_propertylist_update_double(save_header, "CD2_1", 0.0);
    cpl_propertylist_update_double(save_header, "CD2_2", 1.0);
    cpl_propertylist_update_string(save_header, "CTYPE1", "LINEAR");
    cpl_propertylist_update_string(save_header, "CTYPE2", "PIXEL");

    fors_dfs_save_image(frameset, residual, disp_residuals_tag, save_header,
                        parlist, recipe, ref_arc_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit(NULL);

    cpl_image_delete(residual); residual = NULL;
    cpl_propertylist_delete(save_header); save_header = NULL;

    wavemap = mos_map_wavelengths(coordinate, rainbow, slits, polytraces, 
                                  ref_wave, config.startwavelength, 
                                  config.endwavelength, config.dispersion);

    cpl_image_delete(rainbow); rainbow = NULL;

    save_header = dfs_load_header(frameset, arc_tag, 0);

    /*
     * QC1 parameters
     */
    keyname = "QC.DID";

    if (fors_header_write_string(save_header,
            keyname,
            "2.0",
            "QC1 dictionary")) {
        fors_calib_exit("Cannot write dictionary version "
                "to QC log file");
    }

    if (fors_header_write_double(save_header,
            mean_rms,
            "QC.WAVE.ACCURACY",
            "pixel",
            "Mean accuracy of wavecalib model")) {
        fors_calib_exit("Cannot write mean wavelength calibration "
                "accuracy to QC log file");
    }


    if (fors_header_write_double(save_header,
            mean_rms_err,
            "QC.WAVE.ACCURACY.ERROR",
            "pixel",
            "Error on accuracy of wavecalib model")) {
        fors_calib_exit("Cannot write error on wavelength calibration "
                "accuracy to QC log file");
    }

    fors_dfs_save_image(frameset, wavemap, wavelength_map_tag, save_header,
            parlist, recipe, ref_arc_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit(NULL);

    cpl_image_delete(wavemap); wavemap = NULL;

    cpl_propertylist_erase_regexp(save_header, "^ESO QC ", 0);

    fors_dfs_save_image(frameset, coordinate, spatial_map_tag, save_header,
                        parlist, recipe, ref_flat_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit(NULL);

    cpl_propertylist_delete(save_header); save_header = NULL;

    header = NULL;    /* To be really, really, REALLY sure... */

    /*
     * QC1 parameters
     */
    double maxpos, maxneg, maxcurve, maxslope;

    header = dfs_load_header(frameset, arc_tag, 0);

    keyname = "QC.DID";

    if (fors_header_write_string(header,
            keyname,
            "2.0",
            "QC1 dictionary")) {
        fors_calib_exit("Cannot write dictionary version "
                "to QC log file");
    }

    maxpos = fabs(cpl_table_get_column_max(polytraces, "c2"));
    maxneg = fabs(cpl_table_get_column_min(polytraces, "c2"));
    maxcurve = maxpos > maxneg ? maxpos : maxneg;
    if (fors_header_write_double(header,
            maxcurve,
            "QC.TRACE.MAX.CURVATURE",
            "Y pixel / X pixel ^2",
            "Max observed curvature in "
            "spectral tracing")) {
        fors_calib_exit("Cannot write max observed curvature in spectral "
                "tracing to QC log file");
    }

    maxpos = fabs(cpl_table_get_column_max(polytraces, "c1"));
    maxneg = fabs(cpl_table_get_column_min(polytraces, "c1"));
    maxslope = maxpos > maxneg ? maxpos : maxneg;
    if (fors_header_write_double(header,
            maxslope,
            "QC.TRACE.MAX.SLOPE",
            "Y pixel / X pixel",
            "Max observed slope in spectral tracing")) {
        fors_calib_exit("Cannot write max observed slope in spectral "
                "tracing to QC log file");
    }
    
    /* Saving slits and polytraces */
    
    fors_dfs_save_table(frameset, polytraces, curv_coeff_tag, header,
                        parlist, recipe, ref_flat_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit(NULL);

    cpl_propertylist_delete(header); header = NULL;

    fors_dfs_save_table(frameset, slits, slit_location_tag, NULL,
                        parlist, recipe, ref_flat_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit(NULL);
    
    /* Read grism configuration */
    //TODO: Add the waveref to the grism_tables
    cpl_frameset * grism_frame = fors_frameset_extract(frameset, "GRISM_TABLE");
    std::auto_ptr<mosca::grism_config> grism_cfg = 
            fors_grism_config_from_frame(cpl_frameset_get_position(grism_frame, 0), ref_wave);
    cpl_frameset_delete(grism_frame);

    /* Get the detected slit locations */
    fors::detected_slits det_slits = 
        fors::detected_slits_from_tables(slits, polytraces, size_spec);
    
    /* Get the calibrated slits */
    fors::calibrated_slits calib_slits(det_slits, wave_cal, *grism_cfg,
                                       ccd_xsize, ccd_ysize); 
    for(std::vector<mosca::calibrated_slit>::const_iterator 
            slit_it = calib_slits.begin();
        slit_it != calib_slits.end() ; slit_it++)
    {
        if(!slit_it->has_valid_wavecal())
            cpl_msg_warning(cpl_func, "Slit %d does not contain valid "
                    "wavelength calibration. Skipping it for master flat", 
                    slit_it->slit_id());
    }
    
    /* Compute master flat.
     * TODO: master flat has already been computed above using the old method
     * Here we use the new method and is the one saved. The other is not yet
     * deleted in case it is used for something else.
     */
    cpl_msg_indent_less();
    cpl_msg_info(recipe, "Perform flat field combination...");
    
    cpl_image_delete(master_flat);
    std::auto_ptr<mosca::image> master_flat_d;
    std::vector<std::vector<double> > slit_sat_ratio;
    std::vector<std::vector<int> > slit_sat_count;
    cpl_mask ** nonlinear_flat_masks;
    cpl_mask ** saturated_flat_masks;
    std::auto_ptr<mosca::fiera_config> ccd_config;
    master_flat_d = fors_calib_flat_mos_create_master_flat(calib_slits,
            wave_cal, *grism_cfg, master_bias, bias_frame,
            config, frameset, flat_tag, 
            config.nonlinear_level, config.max_nonlinear_ratio, 
            slit_sat_ratio, slit_sat_count,
            nonlinear_flat_masks, 
            saturated_flat_masks, ccd_config);
    if(master_flat_d.get() == 0)
        fors_calib_exit("Cannot combine flat frames");

    /* Create flat bad pixel mask */
    cpl_image * flat_mask = fors_bpm_create_combined_bpm(nonlinear_flat_masks,
                                                         saturated_flat_masks,
                                                         nflats);
    
    /*
     * Flat field normalisation is done directly on the master flat
     * field (without spatial rectification first). The spectral
     * curvature model may be provided in input, in future releases.
     */
    cpl_msg_info(recipe, "Performing flat field normalisation");
    std::auto_ptr<mosca::image> norm_flat(NULL);
    cpl_image * wave_profiles;
    std::vector<float> sed_norm;
    if(fors_calib_flat_mos_normalise(master_flat_d, wave_cal, slits, 
            polytraces,  coordinate, config, 
            norm_flat, &wave_profiles, sed_norm) != 0)
        fors_calib_exit("Cannot normalise flat");

    cpl_msg_info(recipe, "Performing flat field distortion correction");
    if(fors_calib_flat_mos_rect_mapped(master_flat_d, norm_flat, 
            slits, idscoeff, polytraces, ref_wave, config, 
            mapped_flat, mapped_nflat) != 0)
        fors_calib_exit("Cannot correct flat field from distortion");

     /* Getting the normalisation factors used in the SED */
     cpl_propertylist * sed_header = cpl_propertylist_new();
     for(size_t ised = 0 ; ised < sed_norm.size();ised++)
     {
         std::ostringstream norm_key;
         norm_key<< "ESO QC FLAT SED"<<ised+1<<" NORM ";
         cpl_propertylist_append_float(sed_header, norm_key.str().c_str(),
                                       sed_norm[ised]);
     }

    /* Saving all flats */
    cpl_msg_info(recipe, "Saving flats");
    if(fors_calib_flats_save(master_flat_d, flat_mask,
            norm_flat, mapped_flat, mapped_nflat, det_slits,
            slit_sat_ratio, slit_sat_count, config,
            frameset, flat_tag, master_screen_flat_tag, master_norm_flat_tag,
            mapped_screen_flat_tag, mapped_norm_flat_tag,
            parlist, ref_flat_frame, *ccd_config) != 0)
        fors_calib_exit("Cannot save flats");

    /* Saving slit dispersion profiles */
    std::ostringstream prof_filename_oss;
    prof_filename_oss << flat_disp_profile_tag << ".fits";
    std::string prof_filename = prof_filename_oss.str();
    std::transform(prof_filename.begin(), prof_filename.end(), prof_filename.begin(), ::tolower);
    cpl_propertylist_append_string(sed_header, CPL_DFS_PRO_TYPE, "REDUCED");
    cpl_propertylist_append_string(sed_header, CPL_DFS_PRO_CATG, flat_disp_profile_tag);
    cpl_dfs_save_image(frameset, NULL, parlist, frameset, 
                       ref_flat_frame, wave_profiles, CPL_BPP_IEEE_FLOAT,
                       recipe, sed_header, NULL, PACKAGE "/" PACKAGE_VERSION,  
                       prof_filename.c_str());
    if(cpl_error_get_code() != CPL_ERROR_NONE)
        fors_calib_exit("Cannot save flats");
    cpl_propertylist_delete(sed_header); sed_header = NULL;

    cpl_table_delete(polytraces); polytraces = NULL;
    cpl_table_delete(slits); slits = NULL;
    cpl_table_delete(idscoeff); idscoeff = NULL;
    cpl_image_delete(coordinate); coordinate = NULL;
    fors_image_delete(&master_bias); master_bias = NULL;
    cpl_image_delete(mapped_flat);
    cpl_image_delete(mapped_nflat);
    cpl_image_delete(wave_profiles);
    cpl_image_delete(flat_mask);
    for (size_t i_flat = 0; i_flat < nflats; i_flat++)
    {
        cpl_mask_delete(nonlinear_flat_masks[i_flat]);
        cpl_mask_delete(saturated_flat_masks[i_flat]);
    }
    cpl_free(nonlinear_flat_masks);
    cpl_free(saturated_flat_masks);

    if (cpl_error_get_code()) {
        cpl_msg_error(cpl_func, "Error found in %s: %s",
                      cpl_error_get_where(), cpl_error_get_message());
        fors_calib_exit(NULL);
    }

    return 0;
}

int fors_calib_retrieve_input_param(cpl_parameterlist * parlist, 
                                     cpl_frameset * frameset,
                                     fors_calib_config * config)
{
    const char *recipe = "fors_calib";

    cpl_table        *grism_table  = NULL;

    cpl_msg_info(recipe, "Recipe %s configuration parameters:", recipe);
    cpl_msg_indent_more();
    
    grism_table = dfs_load_table(frameset, "GRISM_TABLE", 1);

    config->dispersion = dfs_get_parameter_double(parlist, 
                    "fors.fors_calib.dispersion", grism_table);


    config->peakdetection = dfs_get_parameter_double(parlist, 
                    "fors.fors_calib.peakdetection", grism_table);

    config->wdegree = dfs_get_parameter_int(parlist, 
                    "fors.fors_calib.wdegree", grism_table);

    config->wradius = dfs_get_parameter_int(parlist, "fors.fors_calib.wradius", NULL);

    config->wreject = dfs_get_parameter_double(parlist, 
                                       "fors.fors_calib.wreject", NULL);

    config->wmode = dfs_get_parameter_int(parlist, "fors.fors_calib.wmode", NULL);

    config->wmosmode = dfs_get_parameter_int(parlist,
                                     "fors.fors_calib.wmosmode", NULL);

    config->cdegree = dfs_get_parameter_int(parlist, "fors.fors_calib.cdegree", 
                                    grism_table);

    config->cmode = dfs_get_parameter_int(parlist, "fors.fors_calib.cmode", NULL);

    config->startwavelength = dfs_get_parameter_double(parlist, 
                    "fors.fors_calib.startwavelength", grism_table);

    config->endwavelength = dfs_get_parameter_double(parlist, 
                    "fors.fors_calib.endwavelength", grism_table);

    config->slit_ident = dfs_get_parameter_bool(parlist, 
                    "fors.fors_calib.slit_ident", NULL);

    config->stack_method = dfs_get_parameter_string(parlist, 
                                        "fors.fors_calib.stack_method", NULL);

    if (strcmp(config->stack_method, "ksigma") == 0) {
        std::string ksigma = dfs_get_parameter_string(parlist,
                                         "fors.fors_calib.ksigma", NULL);
        std::string::size_type comma = ksigma.find(',');
        std::istringstream klow(ksigma.substr(0, comma));
        std::istringstream khigh(ksigma.substr(comma+1));
        bool invalid_klow = !(klow >> config->klow) || !(klow.eof()  || (klow >> std::ws && klow.eof())); 
        bool invalid_khigh = !(khigh >> config->khigh) || !(khigh.eof()  || (khigh >> std::ws && khigh.eof()));
        if (comma == std::string::npos || invalid_klow || invalid_khigh)
            throw std::invalid_argument("ksigma must contain two "
                                        "comma-separated numbers");

        config->kiter = dfs_get_parameter_int(parlist, 
                                         "fors.fors_calib.kiter", NULL);
    }

    config->spa_polyorder = dfs_get_parameter_int(parlist, "fors.fors_calib.s_degree", NULL);

    config->disp_nknots = dfs_get_parameter_int(parlist, "fors.fors_calib.d_nknots", NULL);

    config->sradius = dfs_get_parameter_int(parlist, "fors.fors_calib.sradius", NULL);

    config->dradius = dfs_get_parameter_int(parlist, "fors.fors_calib.dradius", NULL);

    config->fit_threshold = dfs_get_parameter_double(parlist, 
            "fors.fors_calib.fit_threshold", NULL);
    
    config->ignore_lines= dfs_get_parameter_string(parlist, 
            "fors.fors_calib.ignore_lines", NULL);

    config->used_linesets= dfs_get_parameter_string(parlist, 
            "fors.fors_calib.used_linesets", NULL);

    config->nonlinear_level = dfs_get_parameter_double(parlist, 
            "fors.fors_calib.nonlinear_level", NULL);

    config->max_nonlinear_ratio = dfs_get_parameter_double(parlist, 
            "fors.fors_calib.max_nonlinear_ratio", NULL);
    
    cpl_table_delete(grism_table); grism_table = NULL;

    return 0; 
}

//functor to search substrings with find_if. C++11 lambdas would be shorter
struct contains_subtring : std::unary_function<std::string ,bool>
{
    contains_subtring(std::string& substr) : m_substr(substr) {};
    bool operator()(const std::string& string) 
    {
        return (string.find(m_substr) != std::string::npos); 
    }
    std::string m_substr;
};

//Get the list of lines after proper filtering
cpl_vector * fors_calib_get_reference_lines(cpl_frameset * frameset, 
                                            const char * arctag,
                                            const char * ignore_lines,
                                            const char * used_linesets)
{
    cpl_table        *wavelengths  = NULL;
    cpl_propertylist *archeader  = NULL;
    cpl_size          nlines_all;
    cpl_size          n_selected = 0;
    cpl_size          i;
    cpl_vector       *lines;
    double            lambda;
    int               null;
    const char *      wcolumn = "WLEN";
    const char *      ioncolumn = "CHEMICAL_ION";
    const char *      linesetcolumn = "LINE_SET";

    /*
     * Read the wavelengths table 
     */
    wavelengths = dfs_load_table(frameset, "MASTER_LINECAT", 1);
    archeader   = dfs_load_header(frameset, arctag, 0);

    if (wavelengths == NULL)
    {
        cpl_msg_error(cpl_func, "Cannot load line catalog");
        return NULL;
    }


    nlines_all = cpl_table_get_nrow(wavelengths);

    if (nlines_all == 0)
    {
        cpl_msg_error(cpl_func, "Empty input line catalog");
        cpl_table_delete(wavelengths);
        return NULL;
    }

    if (cpl_table_has_column(wavelengths, wcolumn) != 1 ||
        cpl_table_has_column(wavelengths, ioncolumn) != 1 || 
        cpl_table_has_column(wavelengths, linesetcolumn) != 1) 
    {
        cpl_msg_error(cpl_func, "Missing columns %s %s %s in input line catalog",
                      wcolumn, ioncolumn, linesetcolumn);
        cpl_table_delete(wavelengths);
        return NULL;
    }

    /*
     * Deselect lines which are not present in the lamps
     */
    std::vector<std::string> observed_lamps;
    for(size_t ikeylamp = 1; ikeylamp < 9; ++ikeylamp)
    {
        std::ostringstream oss;
        oss<<"ESO INS LAMP"<<ikeylamp<<" NAME";
        if(cpl_propertylist_has(archeader, oss.str().c_str()))
            observed_lamps.push_back
                (cpl_propertylist_get_string(archeader, oss.str().c_str()));
    }
    //Check line by line if the chemical element was part of any of the lamps
    for (cpl_size iline = 0; iline < nlines_all; iline++)
    {
        if(cpl_table_get_string(wavelengths, ioncolumn, iline) == NULL)
        {
            cpl_table_unselect_row(wavelengths, iline);
            break;
        }
        std::string chem_elem = 
            cpl_table_get_string(wavelengths, ioncolumn, iline);
        //Get up to the first space (i. e. from 'He I', get just 'He')
        std::string::size_type space = chem_elem.find(' ');
        if (space != std::string::npos)
            chem_elem = chem_elem.substr(0, space);
        //Check if the chemical element is contained in any of the lamps names
        if (std::find_if(observed_lamps.begin(), observed_lamps.end(), 
            contains_subtring(chem_elem)) == observed_lamps.end())
            cpl_table_unselect_row(wavelengths, iline);
    }

    /*
     * Deselect lines which are not in the lineset 
     */
    //Parse command line option used_linesets
    std::string used_linesets_str(used_linesets);
    std::vector<std::string> linesets;
    while(used_linesets_str.length() > 0)
    {
        //Parsing used_linesets (values are separated by comma)
        std::string::size_type found = used_linesets_str.find(',');
        std::string lineset;
        if(found != std::string::npos)
        {
            lineset = used_linesets_str.substr(0, found);
            used_linesets_str = used_linesets_str.substr(found+1);
        }
        else
        {
            lineset = used_linesets_str;
            used_linesets_str = "";
        }
        linesets.push_back(lineset);
    }
    for(cpl_size iline = 0; iline < nlines_all; iline++)
    {
        if(cpl_table_get_string(wavelengths, linesetcolumn, iline) == NULL)
        {
            cpl_table_unselect_row(wavelengths, iline);
            break;
        }
        std::string table_lineset = 
                cpl_table_get_string(wavelengths, linesetcolumn, iline);
        if(std::find(linesets.begin(), linesets.end(), table_lineset) == linesets.end())
            cpl_table_unselect_row(wavelengths, iline);
    }

    /*
     * Deselect lines which are present in ignore_lines 
     */
    std::string ignore_lines_str(ignore_lines);
    while(ignore_lines_str.length() > 0)
    {
        //Parsing ignore_lines (values are separated by comma)
        std::string::size_type found = ignore_lines_str.find(',');
        std::string lambda_str;
        if(found != std::string::npos)
        {
            lambda_str = ignore_lines_str.substr(0, found);
            ignore_lines_str = ignore_lines_str.substr(found+1);
        }
        else
        {
            lambda_str = ignore_lines_str;
            ignore_lines_str = "";
        }
        std::istringstream iss(lambda_str);
        if ( !(iss >> lambda) || !(iss.eof() || (iss >> std::ws && iss.eof())) )
        {
            cpl_msg_error(cpl_func, "Cannot interpret number in ignored_lines");
            cpl_table_delete(wavelengths);
            return NULL;
        }

        //Search for closest line in catalog. The line is unselected but
        //it will be checked again against the next ignored line. In this way,
        //if a value appears many times in the ignored_lines, only one line
        //will be removed
        cpl_size i_ignore = 0;
        double min_lambda_dif = 
             std::fabs(lambda - cpl_table_get(wavelengths, wcolumn, 0, &null));
        for (i = 1; i < nlines_all; i++)
        {
            double lambda_dif = 
              std::fabs(lambda - cpl_table_get(wavelengths, wcolumn, i, &null));
            if(lambda_dif < min_lambda_dif)
            {
                min_lambda_dif = lambda_dif;
                i_ignore = i;
            }
         }
        cpl_table_unselect_row(wavelengths, i_ignore);
    } 
    
    /* Create the final list of reference lines */
    n_selected = cpl_table_count_selected(wavelengths);
    lines = cpl_vector_new(n_selected);
    cpl_size i_line = 0;
    for (i = 0; i < nlines_all; i++)
    {
        lambda = cpl_table_get(wavelengths, wcolumn, i, &null);
        if(cpl_table_is_selected(wavelengths, i))
        {
            cpl_vector_set(lines, i_line, lambda);
            i_line++;
        }
    }

    cpl_table_delete(wavelengths);
    cpl_propertylist_delete(archeader);

    return lines;
}

int fors_calib_flat_mos_normalise
(std::auto_ptr<mosca::image>& master_flat_d,
 const mosca::wavelength_calibration& wave_cal,
 cpl_table * slits, cpl_table * polytraces, cpl_image * coordinate, 
 struct fors_calib_config& config,
 std::auto_ptr<mosca::image>& norm_flat, 
 cpl_image ** wave_profiles,
 std::vector<float>& sed_norm)
{
    cpl_msg_indent_more();

    norm_flat.reset(new mosca::image(cpl_image_cast(master_flat_d->get_cpl_image(), 
                                                    CPL_TYPE_FLOAT),
                                     cpl_image_cast(master_flat_d->get_cpl_image_err(), 
                                                    CPL_TYPE_FLOAT), true));
    
    /* Flat normalisation */
    fors::flat_normaliser normaliser;
    normaliser.mos_normalise(*norm_flat, wave_cal,
                             coordinate, slits, polytraces,
                             config.startwavelength, config.endwavelength,
                             config.dispersion, config.sradius, config.dradius,
                             config.spa_polyorder, config.disp_nknots, config.fit_threshold);

    /* Get the spectral shape of the slits and save it */
    *wave_profiles = normaliser.get_wave_profiles_im();

    /* Get the normalisation factors used */
    sed_norm = normaliser.get_wave_profiles_norm();

    cpl_msg_indent_less();

    return 0;
}

int fors_calib_flat_mos_rect_mapped
(std::auto_ptr<mosca::image>& master_flat_d, 
 std::auto_ptr<mosca::image>& norm_flat,
 cpl_table * slits,
 cpl_table *idscoeff, cpl_table * polytraces,
 double reference, struct fors_calib_config& config,
 cpl_image *& mapped_flat, 
 cpl_image *& mapped_nflat)
{
    cpl_image * rect_flat;
    cpl_image * rect_nflat = NULL;
    
    cpl_msg_indent_more();

    /* mos_spatial-calibration cannot accept doubles 
     * At the end I changed the master flat calibration for float, but the 
     * output is still double (see TODO comment on flat_combine) */
    cpl_image * master_flat = cpl_image_cast(master_flat_d->get_cpl_image(),
                                             CPL_TYPE_FLOAT);
    
    /* Flat spatial distortion correction */ 
    rect_flat = mos_spatial_calibration(master_flat, slits, polytraces, 
                                        reference, config.startwavelength, 
                                        config.endwavelength, config.dispersion,
                                        0, NULL);
    if(norm_flat.get() != NULL)
    {
        cpl_image * norm_flat_f = cpl_image_cast(norm_flat->get_cpl_image(),
                                                 CPL_TYPE_FLOAT);
        rect_nflat = mos_spatial_calibration(norm_flat_f, slits, polytraces, 
                                             reference, config.startwavelength, 
                                             config.endwavelength, 
                                             config.dispersion, 0, NULL);
        cpl_image_delete(norm_flat_f);
    }

    /* Flat wavelength calibration */
    mapped_flat = mos_wavelength_calibration(rect_flat, reference,
                                             config.startwavelength, 
                                             config.endwavelength,
                                             config.dispersion, idscoeff, 0);

    if(norm_flat.get() != NULL)
        mapped_nflat = mos_wavelength_calibration(rect_nflat, reference,
                                                  config.startwavelength, 
                                                  config.endwavelength, 
                                                  config.dispersion, idscoeff, 
                                                  0);

    cpl_image_delete(master_flat);
    cpl_image_delete(rect_flat);
    if(norm_flat.get() != NULL)
        cpl_image_delete(rect_nflat);
    cpl_msg_indent_less();

    return 0;
}

cpl_mask * fors_calib_mask_rect_mapped
(cpl_mask * mask,
 cpl_table * slits, cpl_table *idscoeff, cpl_table * polytraces,
 double reference, struct fors_calib_config& config)
{
    cpl_image * target_image = cpl_image_new_from_mask(mask);
        
    /* Spatial distortion correction */ 
    cpl_image * rect_image = mos_spatial_calibration(target_image, slits, 
                                                     polytraces, 
                                                     reference, 
                                                     config.startwavelength, 
                                                     config.endwavelength, 
                                                     config.dispersion,
                                                     0, NULL);

    /* Wavelength calibration */
    cpl_image * mapped_image = mos_wavelength_calibration(rect_image, reference,
                                                          config.startwavelength, 
                                                          config.endwavelength,
                                                          config.dispersion, 
                                                          idscoeff, 0);


    cpl_mask * rect_mapped_mask = 
            cpl_mask_threshold_image_create(mapped_image,
                            0, std::numeric_limits<double>::max());

    cpl_image_delete(rect_image);
    cpl_image_delete(mapped_image);
    cpl_image_delete(target_image);
    
    return rect_mapped_mask;
}

int fors_calib_flats_save
(std::auto_ptr<mosca::image>& master_flat_d, 
 cpl_image * flat_mask,
 std::auto_ptr<mosca::image>& norm_flat,
 cpl_image * mapped_flat,  cpl_image * mapped_nflat,
 const fors::detected_slits detected_slits,
 const std::vector<std::vector<double> >& slit_sat_ratio,
 const std::vector<std::vector<int> >& slit_sat_count,
 struct fors_calib_config& config,
 cpl_frameset * frameset, const char * flat_tag, 
 const char * master_screen_flat_tag, const char * master_norm_flat_tag, 
 const char * mapped_screen_flat_tag, const char * mapped_norm_flat_tag, 
 cpl_parameterlist * parlist, const cpl_frame * ref_flat_frame, 
 const mosca::ccd_config& ccd_config)
{
    cpl_propertylist * save_header;
    cpl_propertylist * wave_header;
    const char *recipe_name = "fors_calib";
    
    cpl_msg_indent_more();

    size_t nflats = cpl_frameset_get_size(frameset);
    save_header = dfs_load_header(frameset, flat_tag, 0);
    cpl_propertylist_update_int(save_header, "ESO PRO DATANCOM", nflats);

    /* Computing QC for saturation */
    fors_calib_qc_saturation(save_header, detected_slits,
                             slit_sat_ratio, slit_sat_count);
    
    /* Adding the trimming keywords */
    fors_trimm_fill_info(save_header, ccd_config);

    /* Saving regular flat */
    fors_image * fors_master_flat = fors_image_new(
            cpl_image_duplicate(master_flat_d->get_cpl_image()),
            cpl_image_power_create(master_flat_d->get_cpl_image_err(), 2.));
    fors_dfs_save_image_err_mask(frameset, fors_master_flat, flat_mask,
                                 master_screen_flat_tag, save_header, parlist,
                                 recipe_name, ref_flat_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
    {
        cpl_propertylist_delete(save_header);
        return -1;
    }

    /* Saving normalised flats */
    if(norm_flat.get() != NULL)
    {
        fors_image * fors_norm_flat = fors_image_new(
                cpl_image_duplicate(norm_flat->get_cpl_image()),
                cpl_image_power_create(norm_flat->get_cpl_image_err(), 2.));
        fors_dfs_save_image_err_mask(frameset, fors_norm_flat, flat_mask,
                                     master_norm_flat_tag, save_header, parlist,
                                     recipe_name, ref_flat_frame);
        if(cpl_error_get_code() != CPL_ERROR_NONE)
        {
            cpl_propertylist_delete(save_header);
            return -1;
        }
        fors_image_delete(&fors_norm_flat);
    }

    /* Create header for wavelength calibrated images */
    wave_header = cpl_propertylist_new();
    cpl_propertylist_update_double(wave_header, "CRPIX1", 1.0);
    cpl_propertylist_update_double(wave_header, "CRPIX2", 1.0);
    cpl_propertylist_update_double(wave_header, "CRVAL1", 
                                   config.startwavelength + config.dispersion/2);
    cpl_propertylist_update_double(wave_header, "CRVAL2", 1.0);
    /* cpl_propertylist_update_double(header, "CDELT1", config.dispersion);
    cpl_propertylist_update_double(header, "CDELT2", 1.0); */
    cpl_propertylist_update_double(wave_header, "CD1_1", config.dispersion);
    cpl_propertylist_update_double(wave_header, "CD1_2", 0.0);
    cpl_propertylist_update_double(wave_header, "CD2_1", 0.0);
    cpl_propertylist_update_double(wave_header, "CD2_2", 1.0);
    cpl_propertylist_update_string(wave_header, "CTYPE1", "LINEAR");
    cpl_propertylist_update_string(wave_header, "CTYPE2", "PIXEL");

    cpl_propertylist_update_int(wave_header, "ESO PRO DATANCOM", nflats);

    /* Saving mapped flat */
    fors_dfs_save_image(frameset, mapped_flat, mapped_screen_flat_tag,
                        wave_header, parlist, recipe_name, ref_flat_frame);
    if(cpl_error_get_code() != CPL_ERROR_NONE)
    {
        cpl_propertylist_delete(wave_header);
        cpl_propertylist_delete(save_header);
        return -1;
    }

    /* Saving normalised mapped flat */
    if(mapped_nflat != NULL)
    {
        fors_dfs_save_image(frameset, mapped_nflat, mapped_norm_flat_tag, 
                wave_header, parlist, recipe_name, ref_flat_frame);
        if(cpl_error_get_code() != CPL_ERROR_NONE)
        {
            cpl_propertylist_delete(wave_header);
            cpl_propertylist_delete(save_header);
            return -1;
        }
    }

    cpl_propertylist_delete(wave_header);
    cpl_propertylist_delete(save_header);
    fors_image_delete(&fors_master_flat);

    cpl_msg_indent_less();

    return 0;
}

std::auto_ptr<mosca::image> fors_calib_flat_mos_create_master_flat
(fors::calibrated_slits& calibrated_slits, 
 const mosca::wavelength_calibration& wave_cal,
 const mosca::grism_config& grism_cfg,
 fors_image *master_bias, const cpl_frame * bias_frame,
 struct fors_calib_config& config, cpl_frameset * frameset,
 const char * flat_tag, 
 double nonlinear_level, double max_nonlinear_ratio,
 std::vector<std::vector<double> >& slit_sat_ratio,
 std::vector<std::vector<int> >& slit_sat_count,
 cpl_mask **& nonlinear_flat_masks,
 cpl_mask **& saturated_flat_masks,
 std::auto_ptr<mosca::fiera_config>& ccd_config)
{
    const char     * recipe_name = "fors_calib";
    cpl_errorstate   error_prevstate = cpl_errorstate_get();
    std::auto_ptr<mosca::image> master_flat;

    cpl_msg_indent_more();

    ccd_config = 
           fors_ccd_config_read(cpl_frameset_find_const(frameset, flat_tag), 
                                bias_frame);

    if(ccd_config.get() == 0)
    {
        cpl_msg_error(recipe_name, "Cannot get CCD configuration from header "
                                   "or RON from master bias"
                                   "(missing QC DET OUT? RON keywords)");
        return master_flat;
    }

    /* Get the flat frames */
    cpl_frameset * flatframes = fors_frameset_extract(frameset, flat_tag);
    size_t nflats = cpl_frameset_get_size(flatframes);

    /* Allocate the bad pixel masks*/
    nonlinear_flat_masks = 
            (cpl_mask **)cpl_malloc(nflats* sizeof(cpl_mask*));; 
    saturated_flat_masks = 
            (cpl_mask **)cpl_malloc(nflats* sizeof(cpl_mask*));; 

    /* Reading individual raw flats */
    //TODO: This has copy overhead. Substitute with shared_ptr
    std::vector<mosca::image> basiccal_flats;
    for (size_t i_flat = 0; i_flat < nflats; i_flat++)
    {
        cpl_frame * flatframe = cpl_frameset_get_position(flatframes, i_flat);
        fors_image * flat_raw = fors_image_load(flatframe);

        if (!flat_raw)
            return master_flat;
        
        /* Create variances map */
        fors_image_variance_from_detmodel(flat_raw, *ccd_config);
        if(!cpl_errorstate_is_equal(error_prevstate))
            return master_flat;

        /* Get the non-linear pixels */
        nonlinear_flat_masks[i_flat] = 
                cpl_mask_threshold_image_create(flat_raw->data,
                                nonlinear_level, std::numeric_limits<double>::max());
        /* Get the A/D saturated pixels */
        saturated_flat_masks[i_flat] = 
                cpl_mask_threshold_image_create(flat_raw->data,
                                65535., std::numeric_limits<double>::max());
        cpl_mask * saturated_0 = 
                cpl_mask_threshold_image_create(flat_raw->data,
                                -std::numeric_limits<double>::max(), 
                                std::numeric_limits<double>::min());
        cpl_mask_or(saturated_flat_masks[i_flat], saturated_0);
        cpl_mask_delete(saturated_0);

        /* Subtract overscan */
        fors_image * flat = fors_subtract_prescan(flat_raw, *ccd_config);
        if(!cpl_errorstate_is_equal(error_prevstate))
            return master_flat;

        /* Trimm pre/overscan */
        fors_trimm_preoverscan(flat, *ccd_config);
        fors_trimm_preoverscan(nonlinear_flat_masks[i_flat], *ccd_config);
        fors_trimm_preoverscan(saturated_flat_masks[i_flat], *ccd_config);
        fors_image_delete(&flat_raw);
        if(!cpl_errorstate_is_equal(error_prevstate))
            return master_flat;

        /* Subtract master bias */
        fors_subtract_bias(flat, master_bias);
        if(!cpl_errorstate_is_equal(error_prevstate))
            return master_flat;

        /* Transforming into mosca::image, which takes ownership */
        cpl_image * flat_data = flat->data; 
        cpl_image * flat_err = flat->variance;
        cpl_image_power(flat_err, 0.5);

        mosca::image new_flat(flat_data, flat_err, true, mosca::X_AXIS);
        basiccal_flats.push_back(new_flat);
        //Only the structure is freed, the images are taken over by new_flat
        cpl_free(flat); 
    }

    if(!cpl_errorstate_is_equal(error_prevstate))
    {
        cpl_msg_error(recipe_name, "Could not read the flats");
        return master_flat;
    }
    
    /* Reject slits that have too many non-linear pixels */
    cpl_msg_info(cpl_func, "Computing saturation of flats");
    cpl_msg_indent_more();
    fors_saturation_reject_sat_slits(basiccal_flats, calibrated_slits, 
                                     nonlinear_flat_masks, 
                                     saturated_flat_masks, max_nonlinear_ratio,
                                     slit_sat_ratio, slit_sat_count);
    cpl_msg_indent_less();

    /* Computing master flat */
    cpl_msg_info(cpl_func, "Computing master flat");
    std::string stacking_method(config.stack_method);
    if(stacking_method == "mean" || stacking_method == "sum")
    {
        //TODO: Hardcoded value!! 
        int smooth_size = 10; 
        mosca::reduce_mean reduce_method;
        master_flat = mosca::flat_combine<float, mosca::reduce_mean>
            (basiccal_flats, calibrated_slits, wave_cal, grism_cfg, smooth_size, reduce_method);
        if(stacking_method == "sum")
        {
            cpl_image_multiply_scalar(master_flat->get_cpl_image(), nflats);
            cpl_image_multiply_scalar(master_flat->get_cpl_image_err(), nflats);
        }
    }
    else if(stacking_method == "median")
    {
        //TODO: Hardcoded value!! 
        int smooth_size = 10; 
        mosca::reduce_median reduce_method;
        master_flat = mosca::flat_combine<float, mosca::reduce_median>
            (basiccal_flats, calibrated_slits, wave_cal, grism_cfg, smooth_size, reduce_method);        
    }
    else if(stacking_method == "ksigma")
    {
        //TODO: Hardcoded value!! 
        int smooth_size = 10; 
        mosca::reduce_sigma_clipping reduce_method(config.khigh, config.klow, config.kiter);
        master_flat = mosca::flat_combine<float, mosca::reduce_sigma_clipping>
            (basiccal_flats, calibrated_slits, wave_cal, grism_cfg, smooth_size, reduce_method);    
    }

    //Cleanup
    cpl_frameset_delete(flatframes);

    cpl_msg_indent_less();
    return master_flat;
}

void fors_calib_qc_saturation
(cpl_propertylist * header, const fors::detected_slits detected_slits,
 const std::vector<std::vector<double> >& slit_sat_ratio,
 const std::vector<std::vector<int> >& slit_sat_count)
{
    size_t n_slits = slit_sat_ratio.size();
    size_t n_flats = slit_sat_ratio[0].size();
    std::vector<double> flat_sat_total_sat(n_flats);
    for(size_t i_slit = 0; i_slit < n_slits; i_slit++)
    {
        int slit_id = detected_slits[i_slit].slit_id();
        for(size_t i_flat = 0; i_flat < n_flats; i_flat++)
        {
            flat_sat_total_sat[i_flat] += slit_sat_count[i_slit][i_flat];
            char * keyname;
            keyname = cpl_sprintf("ESO QC FLAT%02zd SLIT%02d SAT RATIO",
                        i_flat + 1, slit_id);
            cpl_propertylist_append_double(header, keyname, 
                                           slit_sat_ratio[i_slit][i_flat]);
            cpl_free(keyname);
            keyname = cpl_sprintf("ESO QC FLAT%02zd SLIT%02d SAT COUNT",
                        i_flat + 1, slit_id);
            cpl_propertylist_append_double(header, keyname, 
                                           slit_sat_count[i_slit][i_flat]);
            cpl_free(keyname);
        }
    }
    
    for(size_t i_flat = 0; i_flat < n_flats; i_flat++)
    {
        char * keyname;
        keyname = cpl_sprintf("ESO QC FLAT%02zd SAT COUNT", i_flat + 1);
        cpl_propertylist_append_double(header, keyname, 
                                       flat_sat_total_sat[i_flat]);
        cpl_free(keyname);        
    }
}