File: vmifu.c

package info (click to toggle)
cpl-plugin-vimos 4.1.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 28,228 kB
  • sloc: ansic: 169,271; cpp: 16,177; sh: 4,344; python: 3,678; makefile: 1,138; perl: 10
file content (7024 lines) | stat: -rw-r--r-- 192,052 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
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
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
/* $Id: vmifu.c,v 1.13 2013-08-23 10:13:51 cgarcia Exp $
 *
 * This file is part of the VIMOS Pipeline
 * Copyright (C) 2002-2004 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/*
 * $Author: cgarcia $
 * $Date: 2013-08-23 10:13:51 $
 * $Revision: 1.13 $
 * $Name: not supported by cvs2svn $
 */

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <math.h>
#include <float.h> /* for DBL_EPSILON, added by Peter Weilbacher */

#include <vmmath.h>
#include <vmfit.h>
#include <vmifu.h>

/* #include <qfits.h> */
#include "vmextractiontable.h"
#include <vmmoswavecalib.h>
#include <cpl_type.h>
#include <cpl_propertylist.h>
#include <cpl_error.h>
#include <cpl_memory.h>
#include <pilmemory.h>
#include <pilmessages.h>
#include <cpl_msg.h>


#define N_SLITS          (4)
#define N_BLOCKS         (5)
#define FIBERS_PER_BLOCK (80)
#define FIBERS_STEP      (5)

#define MAX_COLNAME      (15)

/**
 * @name vmifu
 *
 * @doc
 *   The module vmifu collects low/medium level functions related to 
 *   IFU data reduction.
 */

/*@{*/

static double modelValue1D(double *c, int order, double position)
{

  double value  = 0.0;
  double factor = 1.0;
  int    j;

  
  for (j = 0; j <= order; j++) {
    value += c[j] * factor;
    factor *= position;
  }

  return value;

}

/***  Commented to avoid warning from the compiler (because unused)

static double modelValue2D(double *c, int order, double xpos, double ypos)
{

  double value  = 0.0;
  int    i, j, k;


  for (k = 0, j = 0; j <= order; j++)
    for (i = 0; i <= order - j; i++, k++)
      value += c[k] * ipow(xpos, i) * ipow(ypos, j);

  return value;

}

***/


static void drawModel(cpl_table *model, 
                      const char *colName, double *c, int order) 
{

  int    i;
  int    range;
  int   *idata;
  float *fdata;

  fdata = cpl_table_get_data_float(model, colName);
  idata = cpl_table_get_data_int(model, "y");
  range = cpl_table_get_nrow(model);
  cpl_table_fill_column_window_float(model, colName, 0, range, 0.0);

  for (i = 0; i < range; i++)
    fdata[i] = modelValue1D(c, order, idata[i]);

}


static int countRejections(VimosDpoint *list, 
                           int npix, double *c, int order, float tolerance)
{

  int    i, j;
  int    rejected = 0;
  double value;


  j = 0;
  for (i = 0; i < npix; i++) {

    value = modelValue1D(c, order, list[i].x);

    if (fabs(list[i].y - value) > tolerance)
      rejected++;
    else {
      if (j < i) {
        list[j].x = list[i].x;
        list[j].y = list[i].y;
      }
      j++;
    }

  }

  return rejected;

}


/*** 
 *** This is just a version of VmFrMedFil() adapted to a cpl_image.
 *** It should be removed as soon as a general median filtering for
 *** images is implemented in CPL.
 ***/

cpl_image *cpl_image_general_median_filter(cpl_image *ima_in, 
                                           int filtsizex, 
                                           int filtsizey,
                                           int excludeCenter) 
{

  char          task[] = "cpl_image_general_median_filter";

  cpl_image    *filt_img = NULL;
  int           col, row;
  float        *buf = NULL;
  float        *data;
  float        *fdata;
  int           medsize, upright_x, loleft_x, upright_y, loleft_y;
  int           uprightuse_x, loleftuse_x;
  int           i, j;
  int           xIsEven = !(filtsizex - (filtsizex/2)*2);
  int           yIsEven = !(filtsizey - (filtsizey/2)*2);
  float        *inpt;
  float        *outpt;
  int           f2x, f2y;
  int           nx = cpl_image_get_size_x(ima_in);
  int           ny = cpl_image_get_size_y(ima_in);


  if (xIsEven) filtsizex++;
  if (yIsEven) filtsizey++;

  if (nx <= filtsizex || ny <= filtsizey) {
    cpl_msg_error(task, "Median filter size: %dx%d, image size: %d,%d",
                filtsizex, filtsizey, nx, ny);
    return NULL;
  }

  if (excludeCenter) excludeCenter = 1;

  f2x = filtsizex / 2;
  f2y = filtsizey / 2;

  filt_img = cpl_image_duplicate(ima_in);
  buf = cpl_malloc(filtsizex * filtsizey * sizeof(float));
  data = cpl_image_get_data(ima_in);
  fdata = cpl_image_get_data(filt_img);

  for (row = 0; row < ny; row++) {
    loleft_y = row - f2y;
    upright_y = row + f2y + 1;

    for (col = 0; col < nx; col++) {
      loleft_x = col - f2x;
      loleftuse_x = MAX(loleft_x, 0);    /* Lowest x-value on image */
      medsize = filtsizex * filtsizey - excludeCenter;
      upright_x = col + f2x + 1;
      uprightuse_x = MIN(upright_x, nx); /* Highest x-value on image */

      /* Optimized extraction */

      outpt = buf;
      if (excludeCenter) {
        for (j = loleft_y; j < upright_y; j++) {

          if (j < 0)
            inpt = data + loleftuse_x;
          else if (j > ny - 1)
            inpt = data + loleftuse_x + (ny - 1) * nx;
          else
            inpt = data + loleftuse_x + j * nx;

          for (i = loleft_x; i < loleftuse_x; i++)
            *outpt++ = *inpt;

          for (i = loleftuse_x; i < uprightuse_x; i++) {
            if (i == col && j == row)
              inpt++;                /*** Skip "central" pixel value ***/
            else
              *outpt++ = *inpt++;
          }

          for (i = uprightuse_x; i < upright_x; i++)
            *outpt++ = *inpt;
        }
      }
      else {
        for (j = loleft_y; j < upright_y; j++) {

          if (j < 0)
            inpt = data + loleftuse_x;
          else if (j > ny - 1)
            inpt = data + loleftuse_x + (ny - 1) * nx;
          else
            inpt = data + loleftuse_x + j * nx;

          for (i = loleft_x; i < loleftuse_x; i++)
            *outpt++ = *inpt;

          for (i = loleftuse_x; i < uprightuse_x; i++)
            *outpt++ = *inpt++;

          for (i = uprightuse_x; i < upright_x; i++)
            *outpt++ = *inpt;
        }
      }

      fdata[col + row * nx] = medianPixelvalue(buf, medsize);
    }
  }

  cpl_free(buf);

  return filt_img;

}


/*** 
 *** This is a variation of cpl_image_general_median_filter,
 *** applying a median filter only in the vertical direction.
 ***/

cpl_image *cpl_image_vertical_median_filter(cpl_image *ima_in, 
                                            int filtsizey, int refrow, 
                                            int above, int below, int step)
{

  char       task[] = "cpl_image_general_median_filter";

  cpl_image *filt_img = NULL;
  int        col, row;
  float     *buf = NULL;
  float     *data;
  float     *fdata;
  int        upright_y, loleft_y;
  int        j;
  int        yIsEven = !(filtsizey - (filtsizey/2)*2);
  int        f2y;
  int        nx = cpl_image_get_size_x(ima_in);
  int        ny = cpl_image_get_size_y(ima_in);
  int        firstRow;


  if (yIsEven) filtsizey++;

  if (ny <= filtsizey) {
    cpl_msg_error(task, "Median filter size: %d, image size: %d", filtsizey, ny);
    return NULL;
  }

  f2y = filtsizey / 2;

  filt_img = cpl_image_duplicate(ima_in);
  buf = cpl_malloc(filtsizey * sizeof(float));
  data = cpl_image_get_data(ima_in);
  fdata = cpl_image_get_data(filt_img);

  firstRow = refrow - step * (below / step);
  if (firstRow < f2y)
    firstRow += step;

  for (col = 0; col < nx; col++) {
    for (row = firstRow; row < refrow + above; row += step) {
      if (row >= ny - f2y)
        break;
      loleft_y = row - f2y;
      upright_y = row + f2y + 1;
      for (j = loleft_y; j < upright_y; j++)
        buf[j - loleft_y] = data[col + j * nx];
      fdata[col + row * nx] = medianPixelvalue(buf, filtsizey);
    }
  }

  cpl_free(buf);

  return filt_img;

}


/*** 
 ***  This should go to CPL some day... Currently works just with
 ***  float columns, it should work also for other numerical column.
 ***  The radius of the smooth box is hw (half width). No NULL elements
 ***  are allowed! Also this should be fixed.
 ***/

static int cpl_table_median_filter_column(cpl_table *table, 
                                          char *colName, int hw)
{

  int    box  = 2 * hw + 1;
  int    nrow = cpl_table_get_nrow(table);
  float *data = cpl_table_get_data_float(table, colName);
  float *smoo = cpl_malloc(nrow * sizeof(float));
  float *row  = cpl_malloc(box * sizeof(float));

  int    i, j;


  /* 
   * Copy first hw and last hw items 
   */

  for (i = 0; i < hw; i++) 
    smoo[i] = data[i];

  for (i = nrow - hw; i < nrow; i++) 
    smoo[i] = data[i];

  /* 
   * Median filtering
   */

  for (i = hw; i < nrow - hw; i++) {
    for (j = -hw; j <= hw; j++) 
      row[j + hw] = data[i + j];
    smoo[i] = median(row, box);
  }

  cpl_free(row);

  cpl_table_copy_data_float(table, colName, smoo);

  cpl_free(smoo);

  return 0;

}


/***
 ***  Also this should go to CPL some day... Currently works just with 
 ***  float columns, it should work also for other numerical columns. 
 ***  The radius of the filter box is hw (half width). No NULL elements
 ***  are allowed! Also this should be fixed.
 ***/

static int cpl_table_min_filter_column(cpl_table *table, 
                                       char *in_col, char *out_col, int hw)
{

  int    nrow = cpl_table_get_nrow(table);
  float *data = cpl_table_get_data_float(table, in_col);
  float *smoo;

  float  min;
  int    i, j;


  cpl_table_duplicate_column(table, out_col, table, in_col);
  smoo = cpl_table_get_data_float(table, out_col);


  /*
   * Min filtering. First and last part of the buffer are left untouched.
   */

  for (i = hw; i < nrow - hw; i++) {
    min = data[i];
    for (j = -hw; j <= hw; j++) {
      if (min > data[i + j])
        min = data[i + j];
    }
    smoo[i] = min;
  }

  return 0;

}

/*
 *  The following static function determines the quantity dx to be 
 *  added to the position of the highest pixel of a fiber profile,
 *  to get the true position of the profile maximum. All is needed 
 *  is the maximum observed value v2 in the profile, and the observed 
 *  values v1 and v3 of the previous and the next pixels in the profile.
 *
 *  The following ratio is defined:
 *
 *      R = 0.5 (v3 - v1) / (2*v2 - v3 - v1)
 *  
 *  This is a conventional ratio that wouldn't diverge for any set of 
 *  pixel values, and that would not depend on the presence of background
 *  (with the assumption that the background level is the same for the 
 *  three pixels). R has also been chosen in such a way that its value 
 *  is already quite close to the real dx. It should be noted that the
 *  following condition should be fulfilled:
 *
 *           v1  <= v2   and   v3  <  v2
 *  or
 *           v1  <  v2   and   v3  <=  v2
 *
 *  This implies that dx varies between -0.5 and 0.5 pixels. In such 
 *  boundary cases, one has:
 *
 *           v2 = v1   and   R = dx = -0.5
 *           v2 = v3   and   R = dx =  0.5
 * 
 *  Another special case is when the observed pixel values are perfectly
 *  symmetrical:
 *
 *           v1 = v3   and   R = dx =  0.0
 *
 *  In all the intermediate cases the relation between R and dx depends 
 *  on the shape of the fiber profile, that has been determined elsewhere. 
 *  Using the accurate reconstruction of the fiber profile obtained by the 
 *  functions ifuProfile() and rebinProfile(), an empirical relation has 
 *  been obtained. This function computes the value of R from the three 
 *  input values, and derives the corresponding value of dx by linear 
 *  interpolation on the tabulated values. If the condition 
 *
 *           v1  <= v2   and   v3  <  v2
 *  or
 *           v1  <  v2   and   v3  <=  v2
 *
 *  is not fulfilled, then this function returns the value 2.0.
 */

/*** Commented out because the correction r to dx is so small to be
     negligible.

static double values_to_dx(double v1, double v2, double v3)
{

  static double rt[] = {
    -0.50000000,
    -0.47308246,
    -0.42050084,
    -0.36780536,
    -0.32124185,
    -0.26728730,
    -0.22053576,
    -0.17183302,
    -0.12233649,
    -0.07436058,
    -0.02070184,
     0.00000000,
     0.02070184,
     0.07436058,
     0.12233649,
     0.17183302,
     0.22053576,
     0.26728730,
     0.32124185,
     0.36780536,
     0.42050084,
     0.47308246,
     0.50000000
  };

  static double dxt[] = {
    -0.500,
    -0.475,
    -0.425,
    -0.375,
    -0.325,
    -0.275,
    -0.225,
    -0.175,
    -0.125,
    -0.075,
    -0.025,
     0.000,
     0.025,
     0.075,
     0.125,
     0.175,
     0.225,
     0.275,
     0.325,
     0.375,
     0.425,
     0.475,
     0.500,
  };

  static int    n = sizeof(rt) / sizeof(double);
  static double epsilon = 0.00000001;

  double dx = 2.0;
  double r;
  int    i;


  if (v1 > v2 || v3 > v2) 
    return dx;

  if (2 * v2 - v1 - v3 < epsilon)
    return dx;

  r = 0.5 * (v3 - v1) / (2 * v2 - v3 - v1);

  for (i = 0; i < n; i++) {
    if (r > rt[i]) 
      continue;
    dx = dxt[i - 1] 
       + (r - rt[i - 1]) / (rt[i] - rt[i - 1]) * (dxt[i] - dxt[i - 1]);
    break;
  }

  return dx;

}

***/

/*
 *  The following static function determines the quantity dx to be
 *  added to the position of the highest pixel of a fiber profile,
 *  to get the true position of the profile maximum. All is needed
 *  is the maximum observed value v2 in the profile, and the observed
 *  values v1 and v3 of the previous and the next pixels in the profile.
 *  
 *  The following ratio is defined:
 *  
 *      R = 0.5 (v3 - v1) / (2*v2 - v3 - v1)
 *      
 *  This is a conventional ratio that wouldn't diverge for any set of
 *  pixel values, and that would not depend on the presence of background
 *  (with the assumption that the background level is the same for the 
 *  three pixels). R has also been chosen in such a way that its value
 *  is already quite close to the real dx. It should be noted that the
 *  following condition should be fulfilled:
 *
 *           v1  <= v2   and   v3  <  v2
 *  or
 *           v1  <  v2   and   v3  <=  v2
 *
 *  This implies that dx varies between -0.5 and 0.5 pixels. In such
 *  boundary cases, one has:
 *
 *           v2 = v1   and   R = dx = -0.5
 *           v2 = v3   and   R = dx =  0.5
 *
 *  Another special case is when the observed pixel values are perfectly
 *  symmetrical:
 *
 *           v1 = v3   and   R = dx =  0.0
 *
 *  In all the intermediate cases the relation between R and dx depends
 *  on the shape of the fiber profile, that has been determined elsewhere.
 *  Using the accurate reconstruction of the fiber profile obtained by 
 *  the *  functions ifuProfile() and rebinProfile(), it can be shown 
 *  that R differs from dx always less than 0.01 pixels. If the condition
 *
 *           v1  <= v2   and   v3  <  v2
 *  or
 *           v1  <  v2   and   v3  <=  v2
 *
 *  is not fulfilled, then this function returns the value 2.0.
 */

static double values_to_dx(double v1, double v2, double v3)
{

  static double epsilon = 0.00000001;
  double        r       = 2.0;


  if (v1 > v2 || v3 > v2)
    return r;

  if (2 * v2 - v1 - v3 < epsilon)
    return r;

  r = 0.5 * (v3 - v1) / (2 * v2 - v3 - v1);

  return r;

}


/*
 *  For a pixel at a distance dx from the spectral profile center, this
 *  function returns its theoretical value based on the modelled fiber
 *  profile. This value is normalized to the profile maximum value, i.e.,
 *  for dx = 0 this function returns 1. There are no limits to the value
 *  given for dx, but it's clear that beyond a certain distance this 
 *  function will just return 0.0. The returned value is computed from 
 *  an empirical table, linearly interpolating between values.
 */

static double dx_to_value(double dx)
{

/*  static double norm   = 3.017532;   */
  static double offset = 0.025;
  static double step   = 0.05;
  static double p[]    = {
    1.00000,
    0.99996,
    0.99600,
    0.99363,
    0.99024,
    0.98371,
    0.97754,
    0.96946,
    0.95954,
    0.94931,
    0.93719,
    0.92335,
    0.90941,
    0.89560,
    0.87707,
    0.86130,
    0.84158,
    0.82178,
    0.80195,
    0.77927,
    0.76022,
    0.73276,
    0.70892,
    0.68236,
    0.65778,
    0.63209,
    0.60109,
    0.57527,
    0.54045,
    0.51107,
    0.48302,
    0.45345,
    0.42497,
    0.39587,
    0.36674,
    0.34252,
    0.31339,
    0.28750,
    0.26153,
    0.24057,
    0.21730,
    0.19604,
    0.17451,
    0.15626,
    0.13760,
    0.12041,
    0.10540,
    0.09260,
    0.07954,
    0.06847,
    0.05968,
    0.05272,
    0.04530,
    0.04062,
    0.03373,
    0.02871,
    0.02387,
    0.02167,
    0.01669,
    0.01503,
    0.01247,
    0.00993,
    0.00758,
    0.00669,
    0.00526,
    0.00301,
    0.00289,
    0.00123,
    0.00065
  };

  static int n = sizeof(p) / sizeof(double);

  int   i;


  dx = fabs(dx);

  if (dx < offset)
    return 1.0;

  i = (dx - offset) / step;

  if (i < 0)
    i = 0;                            /* Safety belt */

  if (i >= n)
    return 0.0;

  return (p[i] + (dx - offset - step * i) / step * (p[i + 1] - p[i])); 
                         /* / norm;  */

}


/*
 * Internal utility, to derive the correct normalization factor
 * of the fiber profile model used by dx_to_value(). The sum of
 * the values of this model taken from a regular grid of step 1
 * should be 1. The actual constant is returned.
 */

void flux_constant()
{

  int     i, j, count;
  int     nvalues = 10;
  double  dx;
  double  step = 1./nvalues;
  double  total, subtotal;


  count = 0;
  total = 0.0;
  for (i = 0; i < nvalues; i++) {
    subtotal = 0.0;
    for (j = -4; j < 5; j++) {
      dx = j + i * step;
      subtotal += dx_to_value(dx);
    }
    printf("Subtotal = %f\n", subtotal);
    total += subtotal;
    count++;
  }
  printf("Total = %f\n", total / 3.017532 / count);

}


/*
 * alternative findPeak() using Gaussian fitting
 * (added by Peter Weilbacher)
 *
 * buffer: data buffer
 * npix:   length of data buffer
 * level:  min peak value
 * pos:    return peak center
 * Returns 0 if a failure occurs, 1 for success
 */

static int findPeakGaussian(double *buffer, int npix, double level, 
                            double *pos)
{
  cpl_vector *v = cpl_vector_wrap(npix, buffer),
             *p = cpl_vector_new(npix);
  int i, rc = CPL_ERROR_NONE;
  double center, sigma, area, bglevel, mse;

#ifdef DEBUG_PEAK
  cpl_bivector* biv;
#endif

  /* If at least one pixel of the profile is equal to zero,
   * a failure is returned.
   */
  for (i = 0; i < npix; i++) {
    if (fabs(buffer[i]) < DBL_EPSILON) {
      return 0;
    }
  }

  /* If two contiguous pixels of the profile
   * are identical, a failure is returned (suspected saturated line).
   */
  for (i = 1; i < npix; i++) {
    if (fabs(buffer[i] - buffer[i - 1]) < DBL_EPSILON) {
      return 0;
    }
  }

  /* fill positions into vector */
  for (i = 0; i < npix; i++) {
     cpl_vector_set(p, i, (double)i);
  }
#ifdef DEBUG_PEAK
  biv = cpl_bivector_wrap_vectors(p, v);
  cpl_bivector_dump(biv, stdout);
  cpl_bivector_unwrap_vectors(biv);
#endif

  rc = cpl_vector_fit_gaussian(p, NULL, v, NULL,
                               CPL_FIT_ALL,
                               &center, &sigma, &area, &bglevel, &mse,
                               NULL, NULL);
  buffer = cpl_vector_unwrap(v);

  if (rc == CPL_ERROR_NONE || rc == CPL_ERROR_CONTINUE ||
      rc == CPL_ERROR_SINGULAR_MATRIX) {
    cpl_error_reset();
    if (buffer[(int)floor(center)] < level &&
        buffer[(int)ceil(center)] < level) {
      /* Insignificant peak */
      return 0;
    }
    *pos = center; /* save only the measured center */
    return 1; /* it worked */
  } else {
    cpl_error_reset();
    return 0;
  }

}


/*
 *  This function can be used just to find the peak of an arc lamp line.
 *  It works under the assumption that the S/N is typically high. The
 *  peak is defined as a pixel having a value that is higher then the
 *  previous and the next pixels. The idea is to look for the peak
 *  with the highest value in the interval, and determine its position
 *  using a parabolic interpolation. The same will be repeated with
 *  findPeakGaussian(), and if the two positions will differ more
 *  than one pixel the parabolic interpolation result will be preferred
 *  (suspecting a blend between lines). This function returns 0 in case
 *  of failure. If at least one pixel of the profile is equal to zero, 
 *  a failure is returned. If two contiguous pixels of the profile
 *  are identical, a failure is returned (suspected saturated line).
 */

static int findPeak(double *buffer, int npix, double level, double *pos)
{

  double diffprev, diffnext;
  double max = 0;
  int    maxpos = 0;
  double gpos;
  int    i;

  npix--;

  for (i = 0; i < npix; i++)
    if (fabs(buffer[i]) < 0.000001)
      return 0;

  for (i = 1; i < npix; i++)
    if (fabs(buffer[i] - buffer[i - 1]) < 0.000001)
      return 0;

  for (i = 1; i < npix; i++) {
#ifdef DEBUG_PEAK
    printf("i=%d, buffer=%f\n",i,buffer[i]);
#endif
    if (buffer[i] > buffer[i - 1]) {
      if (buffer[i] > buffer[i + 1]) {
        if (buffer[i] > max || maxpos == 0) {
          max = buffer[i];
          maxpos = i;
        }
      }
    }
  }

#ifdef DEBUG_PEAK
  fflush(stdout);
#endif

  if (maxpos == 0)            /* No peaks - monotonic sequence of values */
    return 0;

  if (max < level)            /* Unsignificant peak                      */
    return 0;

  diffnext = buffer[maxpos + 1] - buffer[maxpos];
  diffprev = buffer[maxpos - 1] - buffer[maxpos];
  *pos = maxpos + 0.5 * (diffprev - diffnext) / (diffnext + diffprev);

  /*
   * Try to improve accuracy
   */

/* */
  npix++;
  if (findPeakGaussian(buffer, npix, level, &gpos)) {
    if (fabs(*pos - gpos) < 1.0) {
       *pos = gpos;
    }
  }
/* */

  return 1;

}


/*
 * This function just returns the position of the maximum value along 
 * the buffer.
 */

static int whereMax(double *buffer, int npix)
{

  double max    = buffer[0];
  int    maxpos = 0;
  int    i;


  for (i = 1; i < npix; i++) {
    if (buffer[i] > max) {
      max = buffer[i];
      maxpos = i;
    }
  }

  return maxpos;
  
}


/**
 * @memo
 *   Get IFU spectra extraction parameters.
 *
 * @return First guess fiber positions.
 *
 * @param grism    Grism identifier.
 * @param quadrant Quadrant number [1-4].
 * @param slit     IFU slit number [0-3].
 * @param mode     CCD or wavelength oriented extraction parameters.
 * @param row      Returned reference row.
 * @param above    Returned pixels to extract above reference row.
 * @param below    Returned pixels to extract below reference row.
 * @param zero     Returned expected position of zero order contamination.
 *
 * @doc
 *   This function returns the system default spectral extraction parameters,
 *   to be used when no configuration file is found. The returned parameters
 *   corresponding to HR grisms can be either CCD oriented or wavelength 
 *   oriented. When @em mode is set to 0, the returned values are CCD 
 *   oriented: this means that the pixels above and below the reference 
 *   row are chosen so that any spectrum is extracted in its whole extension 
 *   on the CCD. Alternatively, when @em mode is set to 1, the returned 
 *   values are wavelength oriented: this means that the pixels above and 
 *   below the reference row are chosen so that roughly the same wavelength 
 *   interval is covered in the four quadrants for a given grism, i.e., 
 *   only the overlapping spectral ranges in the four quadrants would be 
 *   extracted. For MR and LR grisms the @em mode is ignored, and the 
 *   parameters are always wavelength oriented.
 * 
 *   The grism identifier is a number with the following meaning:
 *
 *     0 = LR_red
 *     1 = LR_blue
 *     2 = MR
 *     3 = HR_red
 *     4 = HR_orange
 *     5 = HR_blue
 *     6 = HR_red holographic
 *     7 = HR_blue holographic
 *
 *   The reference row is chosen roughly within a region that is free from
 *   sky emission lines.
 *
 * @author C. Izzo
 */

int ifuExtractionParameters(int grism, int quadrant, int slit, int mode, 
                            int *row, int *above, int *below, int *zero)
{

  char       task[] = "ifuExtractionParameters";

  int        rows[4];
  int        aboves[4];
  int        zeros[4];
  int        exception;
  int        min, max;
  int        i;


  switch(grism) {
  case 0:
    switch(slit) {
    case 0:
      rows[0] = 1030;           /* LR red, quadrant 1, slit 0 (lowest)  */
      rows[1] = 1019;           /* LR red, quadrant 2, slit 0 (lowest)  */
      rows[2] = 3097;           /* LR red, quadrant 3, slit 0 (highest) */
      rows[3] = 2947;           /* LR red, quadrant 4, slit 0 (highest) */
      aboves[0] = 304;          /* 312; */
      aboves[1] = 304;          /* 311; */
      aboves[2] = 304;          /* 307; */
      aboves[3] = 303;
      zeros[0] = 1210;
      zeros[1] = 1196;
      zeros[2] = 0;
      zeros[3] = 0;
      *above = aboves[quadrant - 1];
      *below = 500 - *above;
      *row = rows[quadrant - 1];
      *zero = zeros[quadrant - 1];
      break;

    case 1:
      rows[0] = 2157;           /* LR red, quadrant 1, slit 1 */
      rows[1] = 2144;           /* LR red, quadrant 2, slit 1 */
      rows[2] = 1974;           /* LR red, quadrant 3, slit 1 */
      rows[3] = 1819;           /* LR red, quadrant 4, slit 1 */
      aboves[0] = 308;
      aboves[1] = 306;
      aboves[2] = 308;
      aboves[3] = 309;
      zeros[0] = 2356;
      zeros[1] = 2340;
      zeros[2] = 2159;
      zeros[3] = 2007;
      *above = aboves[quadrant - 1];
      *below = 500 - *above;
      *row = rows[quadrant - 1];
      *zero = zeros[quadrant - 1];
      break;

    case 2:
      rows[0] = 2726;           /* LR red, quadrant 1, slit 2 */
      rows[1] = 2710;           /* LR red, quadrant 2, slit 2 */
      rows[2] = 1405;           /* LR red, quadrant 3, slit 2 */
      rows[3] = 1252;           /* LR red, quadrant 4, slit 2 */
      aboves[0] = 304;
      aboves[1] = 304;
      aboves[2] = 310;
      aboves[3] = 310;
      zeros[0] = 0;
      zeros[1] = 0;
      zeros[2] = 0;
      zeros[3] = 0;
      *above = aboves[quadrant - 1];
      *below = 500 - *above;
      *row = rows[quadrant - 1];
      *zero = zeros[quadrant - 1];
      break;

    case 3:
      rows[0] = 3292;           /* LR red, quadrant 1, slit 3 (highest)  */
      rows[1] = 3276;           /* LR red, quadrant 2, slit 3 (highest)  */
      rows[2] = 835;            /* LR red, quadrant 3, slit 3 (lowest) */
      rows[3] = 679;            /* LR red, quadrant 4, slit 3 (lowest) */
      aboves[0] = 303;
      aboves[1] = 304;
      aboves[2] = 305;     /* 315 */
      aboves[3] = 305;     /* 315 */
      zeros[0] = 0;
      zeros[1] = 0;
      zeros[2] = 1021;
      zeros[3] = 866;
      *above = aboves[quadrant - 1];
      *below = 500 - *above;
      *row = rows[quadrant - 1];
      *zero = zeros[quadrant - 1];
      break;

    default:
      cpl_msg_error(task, "Wrong slit number");
      return 1;
    }
    break;

  case 1:
    switch(slit) {
    case 0:
      rows[0] = 1191;           /* LR blue, quadrant 1, slit 0 (lowest)  */
      rows[1] = 1181;           /* LR blue, quadrant 2, slit 0 (lowest)  */
      rows[2] = 3250;           /* LR blue, quadrant 3, slit 0 (highest) */
      rows[3] = 3098;           /* LR blue, quadrant 4, slit 0 (highest) */
      zeros[0] = 1361;
      zeros[1] = 1356;
      zeros[2] = 0;
      zeros[3] = 0;
      *above = 269;
      *below = 269;
      *row = rows[quadrant - 1];
      *zero = zeros[quadrant - 1];
      break;

    case 1:
      rows[0] = 2314;           /* LR blue, quadrant 1, slit 1 */
      rows[1] = 2304;           /* LR blue, quadrant 2, slit 1 */
      rows[2] = 2130;           /* LR blue, quadrant 3, slit 1 */
      rows[3] = 1974;           /* LR blue, quadrant 4, slit 1 */
      zeros[0] = 2504;
      zeros[1] = 2497;
      zeros[2] = 2318;
      zeros[3] = 2162;
      *above = 269;
      *below = 269;
      *row = rows[quadrant - 1];
      *zero = zeros[quadrant - 1];
      break;

    case 2:
      rows[0] = 2877;           /* LR blue, quadrant 1, slit 2 */
      rows[1] = 2867;           /* LR blue, quadrant 2, slit 2 */
      rows[2] = 1565;           /* LR blue, quadrant 3, slit 2 */
      rows[3] = 1411;           /* LR blue, quadrant 4, slit 2 */
      zeros[0] = 0;
      zeros[1] = 0;
      zeros[2] = 0;
      zeros[3] = 0;
      *above = 269;
      *below = 269;
      *row = rows[quadrant - 1];
      *zero = zeros[quadrant - 1];
      break;

    case 3:
      rows[0] = 3440;           /* LR blue, quadrant 1, slit 3 (highest)  */
      rows[1] = 3430;           /* LR blue, quadrant 2, slit 3 (highest)  */
      rows[2] = 1001;           /* LR blue, quadrant 3, slit 3 (lowest) */
      rows[3] = 848;            /* LR blue, quadrant 4, slit 3 (lowest) */
      zeros[0] = 0;
      zeros[1] = 0;
      zeros[2] = 1182;
      zeros[3] = 1026;
      *above = 269;
      *below = 269;
      *row = rows[quadrant - 1];
      *zero = zeros[quadrant - 1];
      break;

    default:
      cpl_msg_error(task, "Wrong slit number");
      return 1;
    }
    break;

  case 2:
    rows[0] = 2244;           /* MR, quadrant 1, slit 1 */
    rows[1] = 2234;           /* MR, quadrant 2, slit 1 */
    rows[2] = 2058;           /* MR, quadrant 3, slit 1 */
    rows[3] = 1895;           /* MR, quadrant 4, slit 1 */
    zeros[0] = 0;
    zeros[1] = 0;
    zeros[2] = 0;
    zeros[3] = 0;
    *above = 1175;
    *below = 918;
    *row = rows[quadrant - 1];
    *zero = zeros[quadrant - 1];
    break;
    
  case 6:
  case 3:
    rows[0] = 1718;           /* HR red, quadrant 1, slit 1 */
    rows[1] = 1712;           /* HR red, quadrant 2, slit 1 */
    rows[2] = 1514;           /* HR red, quadrant 3, slit 1 */
    rows[3] = 1560;           /* HR !!!orange!!!, quadrant 4, slit 1 */
    zeros[0] = 0;
    zeros[1] = 0;
    zeros[2] = 0;
    zeros[3] = 0;
    *row = rows[quadrant - 1];
    *zero = zeros[quadrant - 1];
    break;

  case 4:
    rows[0] = 1900;           /* HR orange, quadrant 1, slit 1 */
    rows[1] = 1893;           /* HR orange, quadrant 2, slit 1 */
    rows[2] = 1691;           /* HR orange, quadrant 3, slit 1 */
    rows[3] = 1515;           /* HR orange, quadrant 4, slit 1 */
    zeros[0] = 0;
    zeros[1] = 0;
    zeros[2] = 0;
    zeros[3] = 0;
    *row = rows[quadrant - 1];
    *zero = zeros[quadrant - 1];
    break;

  case 5:
    rows[0] = 3398;           /* HR blue, quadrant 1, slit 1 */
    rows[1] = 3388;           /* HR blue, quadrant 2, slit 1 */
    rows[2] = 3236;           /* HR blue, quadrant 3, slit 1 */
    rows[3] = 3080;           /* HR blue, quadrant 4, slit 1 */
    zeros[0] = 0;
    zeros[1] = 0;
    zeros[2] = 0;
    zeros[3] = 0;
    *row = rows[quadrant - 1];
    *zero = zeros[quadrant - 1];
    break;
  case 7:
    rows[0] = 3398;           /* HR blue holog, quadrant 1, slit 1 */
    rows[1] = 3450;           /* HR blue holog, quadrant 2, slit 1 */
    rows[2] = 3228;           /* HR blue holog, quadrant 3, slit 1 */
    rows[3] = 3046;           /* HR blue holog, quadrant 4, slit 1 */
    zeros[0] = 0;
    zeros[1] = 0;
    zeros[2] = 0;
    zeros[3] = 0;
    *above = 640;
    *below = 1900;
    *row = rows[quadrant - 1];
    *zero = zeros[quadrant - 1];
    break;

  default:
    cpl_msg_error(task, "Wrong grism");
    return 1;
  }

  /* For grism = 7 the spectra do not cover the whole CCD */
  if (grism > 2 && grism < 7) {

    /*
     *  The exception consists in having an HR orange grism on quadrant 4
     *  when HR red grism is used in all other quadrants. In this case the 
     *  definition for a common wavelength interval has not much sense, 
     *  and the whole CCD range is always returned, even if mode == 1. 
     *  In addition to that, the computation of the common wavelength 
     *  interval is limited to the first three quadrants.
     */

    exception = (grism == 3 && quadrant == 4);

    if (mode == 0 || exception) {
      *above = 4096 - *row - 5;
      *below = *row - 5;
    }
    else {
      min = max = rows[0];
      for (i = 1; i < 4; i++) {
        if (rows[i] < min)
          min = rows[i];
        if (rows[i] > max)
          max = rows[i];
        if (i == 2 && exception) /* Leave at quadrant 3 in HR orange case */
          break;
      }
      *above = 4096 - max - 5;
      *below = min - 5;
    }
  }

  return 0;

}


/**
 * @memo
 *   Get IFU wavelength calibration first guess.
 *
 * @return Coefficients of IDS polynomial.
 *
 * @param grism    Grism identifier.
 * @param quadrant Quadrant number [1-4].
 * @param slit     IFU slit number [0-3].
 * @param order    Returned order of the IDS polynomial.
 * @param lambda   Returned reference wavelength.
 *
 * @doc
 *   This function returns the system default spectral IDS coefficients,
 *   to be used when no configuration file is found. The same set of
 *   coefficients is returned for a given grism, quadrant, and pseudo-slit.
 *
 *   The grism identifier is a number with the following meaning:
 *
 *     0 = LR_red
 *     1 = LR_blue
 *     2 = MR
 *     3 = HR_red
 *     4 = HR_orange
 *     5 = HR_blue
 *     6 = HR_red holographic
 *     7 = HR_blue holographic
 *
 *   The pseudo-slit 0 is the one that is most separated from the others.
 *   For MR anf HR grisms the slit number has no effect, as it is always
 *   assumed to be 1. The returned polynomial transforms the wavelength
 *   difference from the reference wavelength to a CCD pixel position
 *   along the dispersion direction.
 *
 * @author C. Izzo
 */

double *ifuFirstIds(int grism, int quadrant, int slit, 
                    int *order, double *lambda)
{

  double *c;


  if (grism > 1 && grism != 7)
    *order = 4;
  else
    *order = 3;

  c = cpl_malloc((*order + 1) * sizeof(double));

  switch (grism) {
  case 0:                                /* LR_red */
    *lambda = 7635.105;
    switch (quadrant) {
    case 1:
      switch (slit) {
      case 0:
        c[0] = 1106;
        c[1] = 1.42721E-01;
        c[2] = -1.39587E-06;
        c[3] = 2.05069E-10;
        break;
      case 1:
        c[0] = 2232;
        c[1] = 1.40079E-01;
        c[2] = -1.41532E-06;
        c[3] = 1.91742E-10;
        break;
      case 2:
        c[0] = 2802;
        c[1] = 1.39292E-01;
        c[2] = -1.36808E-06;
        c[3] = 1.82394E-10;
        break;
      case 3:
        c[0] = 3366;
        c[1] = 1.38695E-01;
        c[2] = -1.52763E-06;
        c[3] = 1.73369E-10;
        break;
      default:
        cpl_free(c);
        return NULL;
      }
      break;
    case 2:
      switch (slit) {
      case 0:
        c[0] = 1092;
        c[1] = 1.42768E-01;
        c[2] = -1.50645E-06;
        c[3] = 2.16611E-10;
        break;
      case 1:
        c[0] = 2214;
        c[1] = 1.40184E-01;
        c[2] = -1.44645E-06;
        c[3] = 1.89765E-10;
        break;
      case 2:
        c[0] = 2780;
        c[1] = 1.39336E-01;
        c[2] = -1.32686E-06;
        c[3] = 2.39379E-10;
        break;
      case 3:
        c[0] = 3350;
        c[1] = 1.38752E-01;
        c[2] = -1.45132E-06;
        c[3] = 2.13249E-10;
        break;
      default:
        cpl_free(c);
        return NULL;
      }
      break;
    case 3:
      switch (slit) {
      case 0:
        c[0] = 3168;
        c[1] = 1.39195E-01;
        c[2] = -1.42261E-06;
        c[3] = 1.69776E-10;
        break;
      case 1:
        c[0] = 2046;
        c[1] = 1.40507E-01;
        c[2] = -1.36907E-06;
        c[3] = 3.15178E-10;
        break;
      case 2:
        c[0] = 1480;
        c[1] = 1.42087E-01;
        c[2] = -1.50725E-06;
        c[3] = 1.90814E-10;
        break;
      case 3:
        c[0] = 912;
        c[1] = 1.43513E-01;
        c[2] = -1.44775E-06;
        c[3] = 1.90265E-10;
        break;
      default:
        cpl_free(c);
        return NULL;
      }
      break;
    case 4:
      switch (slit) {
      case 0:
        c[0] = 3018;
        c[1] = 1.39187E-01;
        c[2] = -1.39253E-06;
        c[3] = 2.44681E-10;
        break;
      case 1:
        c[0] = 1894;
        c[1] = 1.40789E-01;
        c[2] = -1.43792E-06;
        c[3] = 2.71668E-10;
        break;
      case 2:
        c[0] = 1326;
        c[1] = 1.42259E-01;
        c[2] = -1.49931E-06;
        c[3] = 2.32267E-10;
        break;
      case 3:
        c[0] = 754;
        c[1] = 1.43676E-01;
        c[2] = -1.37310E-06;
        c[3] = 2.04999E-10;
        break;
      default:
        cpl_free(c);
        return NULL;
      }
      break;
    default:
      cpl_free(c);
      return NULL;
    }
    break;
  case 1:                                /* LR_blue */
    *lambda = 5015.675;
    switch (quadrant) {
    case 1:
      switch (slit) {
      case 0:
        c[0] = 1128;
        c[1] = 1.92205E-01;
        c[2] = -3.71742E-06;
        c[3] = 6.87774E-10;
        break;
      case 1:
        c[0] = 2252;
        c[1] = 1.88831E-01;
        c[2] = -3.38905E-06;
        c[3] = 6.43705E-10;
        break;
      case 2:
        c[0] = 2820;
        c[1] = 1.87606E-01;
        c[2] = -2.69320E-06;
        c[3] = 3.23760E-10;
        break;
      case 3:
        c[0] = 3386;
        c[1] = 1.87251E-01;
        c[2] = -3.24139E-06;
        c[3] = 5.89868E-10;
        break;
      default:
        cpl_free(c);
        return NULL;
      }
      break;
    case 2:
      switch (slit) {
      case 0:
        c[0] = 1120;
        c[1] = 1.92105E-01;
        c[2] = -3.74334E-06;
        c[3] = 7.80496E-10;
        break;
      case 1:
        c[0] = 2244;
        c[1] = 1.88911E-01;
        c[2] = -3.54657E-06;
        c[3] = 7.73775E-10;
        break;
      case 2:
        c[0] = 2810;
        c[1] = 1.88185E-01;
        c[2] = -3.83450E-06;
        c[3] = 7.98968E-10;
        break;
      case 3:
        c[0] = 3372;
        c[1] = 1.87408E-01;
        c[2] = -3.24542E-06;
        c[3] = 5.89129E-10;
        break;
      default:
        cpl_free(c);
        return NULL;
      }
      break;
    case 3:
      switch (slit) {
      case 0:
        c[0] = 3196;
        c[1] = 1.87613E-01;
        c[2] = -3.64721E-06;
        c[3] = 6.93420E-10;
        break;
      case 1:
        c[0] = 2070;
        c[1] = 1.89155E-01;
        c[2] = -3.48750E-06;
        c[3] = 6.66328E-10;
        break;
      case 2:
        c[0] = 1500;
        c[1] = 1.90859E-01;
        c[2] = -4.25190E-06;
        c[3] = 9.84393E-10;
        break;
      case 3:
        c[0] = 936;
        c[1] = 1.92296E-01;
        c[2] = -3.22008E-06;
        c[3] = 5.27671E-10;
        break;
      default:
        cpl_free(c);
        return NULL;
      }
      break;
    case 4:
      switch (slit) {
      case 0:
        c[0] = 3040;
        c[1] = 1.87776E-01;
        c[2] = -3.55411E-06;
        c[3] = 6.93461E-10;
        break;
      case 1:
        c[0] = 1916;
        c[1] = 1.89409E-01;
        c[2] = -3.64742E-06;
        c[3] = 7.44002E-10;
        break;
      case 2:
        c[0] = 1350;
        c[1] = 1.91058E-01;
        c[2] = -3.59109E-06;
        c[3] = 6.58365E-10;
        break;
      case 3:
        c[0] = 782;
        c[1] = 1.92951E-01;
        c[2] = -3.81789E-06;
        c[3] = 7.85007E-10;
        break;
      default:
        cpl_free(c);
        return NULL;
      }
      break;
    default:
      cpl_free(c);
      return NULL;
    }
    break;
  case 2:                                       /* MR */
    *lambda = 7635.105;
    switch (quadrant) {
    case 1:
      c[0] = 2428;
      c[1] = 3.85953E-01;
      c[2] = -2.93889E-06;
      c[3] = 4.44543E-10;
      c[4] = -9.78740E-14;
      break;
    case 2:
      c[0] = 2420;
      c[1] = 3.87053E-01;
      c[2] = -2.99889E-06;
      c[3] = 4.76732E-10;
      c[4] = -8.91030E-14;
      break;
    case 3:
      c[0] = 2252;
      c[1] = 3.89297E-01;
      c[2] = -3.27377E-06;
      c[3] = 4.68983E-10;
      c[4] = -7.18225E-14;
      break;
    case 4:
      c[0] = 2094;
      c[1] = 3.89315E-01;
      c[2] = -3.15185E-06;
      c[3] = 5.11989E-10;
      c[4] = -8.92864E-14;
      break;
    default:
      cpl_free(c);
      return NULL;
    }
    break;
  case 3:                                /* HR_red */
    *lambda = 7245.167;
    switch (quadrant) {
    case 1:
      c[0] = 1944;
      c[1] = 1.69035;
      c[2] = -1.12423E-04;
      c[3] = 2.11259E-08;
      c[4] = -3.69459E-12;
      break;
    case 2:
      c[0] = 1942;
      c[1] = 1.68526;
      c[2] = -1.10435E-04;
      c[3] = 2.10878E-08;
      c[4] = -4.26251E-12;
      break;
    case 3:
      c[0] = 1762;
      c[1] = 1.71871;
      c[2] = -1.18593E-04;
      c[3] = 2.14324E-08;
      c[4] = -3.37848E-12;
      break;
    case 4:                     /* This is actually an HR_orange */
      *lambda = 6598.953;
      c[0] = 2434;
      c[1] = 1.60816;
      c[2] = -8.77165E-05;
      c[3] = 1.52295E-08;
      c[4] = -5.61383E-12;
      break;
    default:
      cpl_free(c);
      return NULL;
    }
    break;
  case 4:                              /* HR_orange */
    *lambda = 6598.953;
    switch (quadrant) {
    case 1:
      c[0] = 2744;
      c[1] = 1.60;                     /* 1.59241; */
      c[2] = -8.51278E-05;
      c[3] = 1.30080E-08;
      c[4] = -5.93688E-12;
      break;
    case 2:
      c[0] = 2748;
      c[1] = 1.58803;
      c[2] = -8.39732E-05;
      c[3] = 1.27792E-08;
      c[4] = -5.26719E-12;
      break;
    case 3:
      c[0] = 2574;
      c[1] = 1.60;                     /* 1.59546;  */
      c[2] = -8.65212E-05;
      c[3] = 1.41364E-08;
      c[4] = -4.32910E-12;
      break;
    case 4:
      c[0] = 2434;
      c[1] = 1.60816;
      c[2] = -8.77165E-05;
      c[3] = 1.52295E-08;
      c[4] = -5.61383E-12;
      break;
    default:
      cpl_free(c);
      return NULL;
    }
    break;
  case 5:                             /* HR_blue */
    *lambda = 5015.675;
    switch (quadrant) {
    case 1:
      c[0] = 2056;
      c[1] = 1.79965;
      c[2] = -1.14937E-04;
      c[3] = 2.95681E-08;
      c[4] = -8.40936E-12;
      break;
    case 2:
      c[0] = 2046;
      c[1] = 1.80073;
      c[2] = -1.14859E-04;
      c[3] = 2.72775E-08;
      c[4] = -6.89394E-12;
      break;
    case 3:
      c[0] = 1876;
      c[1] = 1.83359;
      c[2] = -1.23169E-04;
      c[3] = 2.94921E-08;
      c[4] = -6.77784E-12;
      break;
    case 4:
      c[0] = 1726;
      c[1] = 1.83450;
      c[2] = -1.24277E-04;
      c[3] = 3.10028E-08;
      c[4] = -6.91772E-12;
      break;
    default:
      cpl_free(c);
      return NULL;
    }
    break;
  case 6:                           /* HR_red holographic */
    *lambda = 7245.167;
    switch (quadrant) {
    case 1:
      c[0] = 1804;
      c[1] = 1.67;
      c[2] = -0.00004015;
      c[3] = 1.0E-08;
      c[4] = -1.75E-12;
      break;
    case 2:
      c[0] = 1777;
      c[1] = 1.672;
      c[2] = -0.00004011;
      c[3] = 1.0E-08;
      c[4] = -1.8E-12;
      break;
    case 3:
      c[0] = 1597;
      c[1] = 1.677;
      c[2] = -0.0000426;
      c[3] = 9.0E-09;
      c[4] = -1.0E-12;
      break;
    case 4:
      c[0] = 1447;
      c[1] = 1.6765;
      c[2] = -0.0000425;
      c[3] = 1.0E-08;
      c[4] = -1.5E-12;
      break;
    default:
      cpl_free(c);
      return NULL;
    }
    break;
  case 7:                             /* HR_blue holographic */
      *lambda = 5015.675;
      switch (quadrant) {
      case 1:
        c[0] = 3312;
        c[1] = 1.3561;
        c[2] = -4.4e-5;
        c[3] = 1.7e-8;
        break;
      case 2:
        c[0] = 3312;
        c[1] = 1.3561;
        c[2] = 0;
        c[3] = 0;
        break;
      case 3:
        c[0] = 3312;
        c[1] = 1.3561;
        c[2] = 0;
        c[3] = 0;
        break;
      case 4:
        c[0] = 3312;
        c[1] = 1.3561;
        c[2] = 0;
        c[3] = 0;
        break;
      default:
        cpl_free(c);
        return NULL;
      }
      break;
  }

  return c;

}


/**
 * @memo
 *   Get default IFU spectra resampling parameters.
 *
 * @return 0 on success.
 *
 * @param grism       Grism identifier.
 * @param startLambda Returned conventional start wavelength.
 * @param endLambda   Returned conventional end wavelength.
 * @param stepLambda  Returned constant sampling step.
 *
 * @doc
 *   This function returns the system default spectral resampling
 *   parameters, i.e., the wavelength range, and the constant
 *   resampling wavelength step for a given grism.
 *
 *   The grism identifier is a number with the following meaning:
 *
 *     0 = LR_red
 *     1 = LR_blue
 *     2 = MR
 *     3 = HR_red
 *     4 = HR_orange
 *     5 = HR_blue
 *     6 = HR_red holographic
 *     7 = HR_blue holographic
 *
 * @author C. Izzo
 */

int ifuRange(int grism, 
             double *startLambda, double *endLambda, double *stepLambda)
{

  switch (grism) {
  case 0:                          /* LR_red */
    *startLambda = 5500.;
    *endLambda = 10000.;
    *stepLambda = 7.0;
    break;
  case 1:                          /* LR_blue */
    *startLambda = 3500.;
    *endLambda = 7000.;
    *stepLambda = 5.2;
    break;
  case 2:                          /* MR */
    *startLambda = 4000.;
    *endLambda = 11000.;
    *stepLambda = 2.6;
    break;
  case 6:                          /* HR_red holographic */
  case 3:                          /* HR_red */
    *startLambda = 6100.;
    *endLambda = 8900.;
    *stepLambda = 0.58;
    break;
  case 4:                          /* HR_orange */
    *startLambda = 5100.;
    *endLambda = 7700.;
    *stepLambda = 0.62;
    break;
  case 5:                          /* HR_blue */
    *startLambda = 4000.;
    *endLambda = 6300.;
    *stepLambda = 0.54;
    break;
  case 7:                          /* HR_blue holographic */ 
    *startLambda = 3450.;
    *endLambda = 5350.;
    *stepLambda = 0.71;
    break;
  default:
    return 1;
  }
  return 0;

}


/**
 * @memo
 *   Get default IFU spectra range where transmission is determined.
 *
 * @return 0 on success.
 *
 * @param grism       Grism identifier.
 * @param startLambda Returned start wavelength.
 * @param endLambda   Returned end wavelength.
 *
 * @doc
 *   This function returns the system default spectral interval where
 *   the fiber-to-fiber transmission correction is determined on a
 *   flat field exposure for a given grism. Such wavelength intervals
 *   are meant to select the brightest part of the spectra, avoiding
 *   possible zero order contaminations.
 *
 *   The grism identifier is a number with the following meaning:
 *
 *     0 = LR_red
 *     1 = LR_blue
 *     2 = MR
 *     3 = HR_red
 *     4 = HR_orange
 *     5 = HR_blue
 *     6 = HR_red holographic 
 *     7 = HR_blue holographic 
 *
 * @author C. Izzo
 */

int ifuRangeTransmission(int grism, double *startLambda, double *endLambda)
{

  switch (grism) {
  case 0:                          /* LR_red */
    *startLambda = 6500.;
    *endLambda = 8000.;
    break;
  case 1:                          /* LR_blue */
    *startLambda = 4600.;
    *endLambda = 6100.;
    break;
  case 2:                          /* MR */
    *startLambda = 6500.;
    *endLambda = 8000.;
    break;
  case 6:                          /* HR_red holographic */
  case 3:                          /* HR_red */
    *startLambda = 7000.;
    *endLambda = 8000.;
    break;
  case 4:                          /* HR_orange */
    *startLambda = 6000.;
    *endLambda = 7000.;
    break;
  case 7:                          /* HR_blue holographic TODO: Review*/
    *startLambda = 4000.;
    *endLambda = 5000.;
    break;
  case 5:                          /* HR_blue */
    *startLambda = 4700.;
    *endLambda = 5700.;
    break;
  default:
    return 1;
  }
  return 0;

}


/**
 * @memo
 *   Bias subtraction.
 *
 * @return Pointer to the bias subtracted image.
 *
 * @param image   Image of an IFU exposure.
 * @param bias    Master bias.
 *
 * @doc
 *   This is just a quick replacement of the VIMOS DRS bias
 *   subtraction function, adapted to CPL images. This function
 *   assumes that the master bias has the overscan regions trimmed,
 *   so they are grown back before subtraction. After this, an
 *   overscan correction is applied to the result, and finally 
 *   the overscan regions are trimmed. The new image is returned.
 *
 * @author C. Izzo
 */

cpl_image *removeBias(cpl_image *image, cpl_image *mbias)
{

  int     nx    = cpl_image_get_size_x(image);
  int     ny    = cpl_image_get_size_y(image);
  float  *data  = cpl_image_get_data(image);
  int     bnx   = cpl_image_get_size_x(mbias);
  int     bny   = cpl_image_get_size_y(mbias);
  float  *bdata = cpl_image_get_data(mbias);

  cpl_image *grown;
  float     *gdata;
  float     *edata;

  int     dx;
  float   residual;


  if (mbias) {

    /*
     *  Overscans are assumed to lay on the right and left sides of image,
     *  and to have equal width. Then this is the width of one overscan 
     *  region:
     */

    dx = (nx - bnx) / 2;

    grown = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);
    gdata = cpl_image_get_data(grown);

    insertFloatImage(gdata, nx, ny, dx, 0, bnx, bny, bdata);

    edata = extractFloatImage(bdata, bnx, bny, 0, 0, dx, bny);
    insertFloatImage(gdata, nx, ny, 0, 0, dx, ny, edata);
    free(edata);

    edata = extractFloatImage(bdata, bnx, bny, bnx - dx - 1, 0, dx, bny);
    insertFloatImage(gdata, nx, ny, nx - dx - 1, 0, dx, ny, edata);
    free(edata);

    cpl_image_subtract(image, grown);

    cpl_image_delete(grown);

  }
  else
    dx = 50;  /*  It should be read from the header, but what the hell...  */

  edata = extractFloatImage(data, nx, ny, 0, 0, dx, ny);
  residual = medianPixelvalue(edata, dx * ny);
  free(edata);

  edata = extractFloatImage(data, nx, ny, nx - dx - 1, 0, dx, ny);
  residual += medianPixelvalue(edata, dx * ny);
  free(edata);

  residual /= 2;

  cpl_image_subtract_scalar(image, residual);

  return cpl_image_extract(image, dx + 1, 1, nx - dx, ny);

}


/**
 * @memo
 *   Remove the bias constant from an image.
 * 
 * @return Pointer to the bias subtracted image.
 * 
 * @param image   Image of an IFU exposure.
 * 
 * @doc
 *   The mean bias level is evaluated from the overscan regions of
 *   the input frame. Currently the values are hardcoded - 50 pixels
 *   in the X direction for each overscan are taken. After subtraction
 *   the overscan regions are trimmed and the new image is returned.
 *   
 * @author C. Izzo
 */

cpl_image *removeBiasLevel(cpl_image *image)
{

  int     nx    = cpl_image_get_size_x(image);
  int     ny    = cpl_image_get_size_y(image);
  float  *data  = cpl_image_get_data(image);

  float     *edata;

  int     dx = 50; 
  float   residual;


  edata = extractFloatImage(data, nx, ny, 0, 0, dx, ny);
  residual = medianPixelvalue(edata, dx * ny);
  free(edata);

  edata = extractFloatImage(data, nx, ny, nx - dx - 1, 0, dx, ny);
  residual += medianPixelvalue(edata, dx * ny);
  free(edata);

  residual /= 2;

  cpl_image_subtract_scalar(image, residual);

  return cpl_image_extract(image, dx + 1, 1, nx - dx, ny);

}


/**
 * @memo
 *   Identify fibers. 
 *
 * @return 0 on success.
 *
 * @param image    Image of an IFU flat field exposure.
 * @param refrow   Image row where the fibers are to be identified.
 * @param refdata  Reference image row with identified fiber peaks.
 * @param ident    Identified fibers positions table.
 * @param radius   Correlation radius.
 * @param wradius  Correlation half-window.
 *
 * @doc
 *   Identifying the IFU fibers here means to give an approximate
 *   position for each IFU fiber along the specified image row.
 *   This means to give the expected positions for dead fibers too.
 *   @em refdata and @em ident are typically produced from a task
 *   external to the automatic pipeline, where the fibers are identified
 *   interactively, through a trial-and-error procedure.
 *
 *   The algorithm is based on the cross-correlation between the
 *   flat field image at the reference row, and the reference
 *   image consisting of a row of peaks where the corresponding
 *   fiber spectra were already identified. The flat field image 
 *   at the reference row is divided into 5 contiguous sections 
 *   of 409 pixels each. The first section begins at the second
 *   pixel on the left (pixel 1). The correlation window is twice
 *   the value of @em wradius plus 1. The correlation is made on
 *   an interval of twice the value of @em radius plus 1. For this
 *   reason, 2 * (@em radius + @em wradius ) + 1 must be less than
 *   409, or an error will be returned. The correlation is tried
 *   for each one of the sections. The median of the 5 offsets
 *   obtained from the correlations is applied to the positions
 *   listed in the @em ident table.
 *
 * @author C. Izzo
 */

int ifuIdentifyUpgrade(cpl_image *image, int refrow, float *refdata,
                       cpl_table *ident, int radius, int wradius)
{

  char    task[]   = "ifuIdentifyUpgrade";

  int     nx       = cpl_image_get_size_x(image);
  float  *data     = cpl_image_get_data(image);
  float  *line     = data + refrow * nx;
  double *normdata = NULL;
  double *normref  = NULL;
  double *cross    = NULL;

  int     countFibers = N_BLOCKS * FIBERS_PER_BLOCK;
  int     count = 0;
  int     firstpix = 1;
  int     secSize  = 680;
  int     secCount = 3;
  float   offset[5];                   /* Size equal to secCount */
  float   shift;
  float   fpos, max;
  float   dx;
  float  *posdata;
  int     maxpos;
  double  sum;
  int     length   = 2 * radius + 1;
  int     wlength  = 2 * wradius + 1;
  int     start;
  int     i, j, k;


  normdata = cpl_malloc(secSize * sizeof(double));
  normref = cpl_malloc(wlength * sizeof(double));
  cross = cpl_malloc(length * sizeof(double));

  for (i = 0; i < secCount; i++) {

    /*
     *  Load data from current section, and normalize them.
     */

    start = firstpix + i * secSize;
    max = line[start];
    for (j = 0; j < secSize; j++) {
      normdata[j] = line[start + j];
      if (normdata[j] > max)
        max = normdata[j];
    }

    if (fabs(max) < 0.000001) {
      cpl_free(normdata);
      cpl_free(normref);
      cpl_free(cross);
      return 1;
    }

    for (j = 0; j < secSize; j++)
      normdata[j] /= max;

    /*
     *  Load data from the corresponding reference image section,
     *  and normalize them.
     */

    start += secSize / 2 - wradius;
    max = refdata[start];
    for (j = 0; j < wlength; j++) {
      normref[j] = refdata[start + j];
      if (normref[j] > max)
        max = normref[j];
    }

    if (fabs(max) < 0.000001) {
      cpl_free(normdata);
      cpl_free(normref);
      cpl_free(cross);
      return 1;
    }

    for (j = 0; j < wlength; j++) 
      normref[j] /= max;

    /*
     *  Cross-correlation of normalized data.
     */

    start = secSize / 2 - wradius - radius;
    for (j = 0; j < length; j++) {
      sum = 0.0;
      for (k = 0; k < wlength; k++) 
        sum += normref[k] * normdata[start + j + k];
      cross[j] = sum;
    }

    max = cross[0];
    maxpos = 0;
    for (j = 1; j < length; j++) {
      if (cross[j] > max) {
        max = cross[j];
        maxpos = j;
      }
    }

    /*
     * The offset is set to a value greater than the correlation
     * radius in case of error.
     */

    offset[i] = radius + 1;
    if (maxpos != 0 && maxpos != length - 1) {
      dx = values_to_dx(cross[maxpos - 1], cross[maxpos], cross[maxpos + 1]);
      if (dx < 1.0)
        offset[i] = maxpos - radius + dx;
    }

  }


  /*
   *  Find median offset among good offsets
   */

  j = 0;
  for (i = 0; i < secCount; i++) {
    if (offset[i] < radius) {
      if (i > j)
        offset[j] = offset[i];
      ++j;
    }
  }

  if (j == 0) {
    cpl_free(normdata);
    cpl_free(normref);
    cpl_free(cross);
    return 1;
  }

  shift = median(offset, j);

  /*
   *  Ensure that missing data (marked by zeroes) are not brought in
   *  by a positive shift.
   */

  posdata = cpl_table_get_data_float(ident, "Position");
  for (i = 0; i < countFibers; i++) {
    if (posdata[i] < 0.0001) {
      posdata[i] -= length;
      count++;
    }
  }

  if (count == countFibers) {
    cpl_free(normdata);
    cpl_free(normref);
    cpl_free(cross);
    return 1;
  }

  cpl_msg_info(task, "Cross-correlation offset "
             "with reference identification: %f", shift);

  cpl_table_add_scalar(ident, "Position", shift);

  for (i = 0; i < countFibers; i++) {
    fpos = cpl_table_get_float(ident, "Position", i, NULL);
    if (!fiberPeak(image, refrow, &fpos, NULL))
      cpl_table_set_float(ident, "Position", i, fpos);
  }

  cpl_free(normdata);
  cpl_free(normref);
  cpl_free(cross);

  return 0;

}


/**
 * @memo
 *   Identify fibers.
 *
 * @return Pointer to the identification table.
 *
 * @param image   Image of an IFU flat field exposure.
 * @param row     Image row where the fibers are to be identified.
 *
 * @doc
 *   Identifying the IFU fibers here means to give an approximate
 *   position for each IFU fiber along the specified image row.
 *   This means to give the expected positions for dead fibers too.
 *   The algorithm is implemented in two basic steps: 1) determination
 *   of the position of the gaps between blocks, and 2) determination
 *   of the fibers positions within each block. The first step is 
 *   carried out with a folding analysis, and the second by correlating
 *   the fiber signal of each block with a "comb" of 80 equally spaced 
 *   teeth. Ambiguities may arise for the first and the last blocks, 
 *   in case they are vignetted: for a bullet-proof identification a 
 *   first-guess identification should be prepared, and passed to the 
 *   function ifuIdentifyUpgrade(). The advantage of ifuIdentify() lays 
 *   in its generality, that permits to reduce IFU data also when a 
 *   first-guess fiber identification is missing, turning out to be 
 *   especially useful in the preparation of such first guesses.
 *
 * @author C. Izzo
 */

cpl_table *ifuIdentify(cpl_image *image, int refrow)
{

  char    task[] = "ifuIdentify";

  int     nx   = cpl_image_get_size_x(image);
  int     ny   = cpl_image_get_size_y(image);
  float  *data = cpl_image_get_data(image);
  float  *line = data + refrow * nx;

  cpl_table *ident;
  cpl_table *folds;
  cpl_table *stats;
  float     *folded;
  int       *position;
  int       *count;
  int        p, i, j, k, n, pos;
#ifdef CPL_SIZE_FORMAT
  cpl_size   row;
#else
  int        row;
#endif
  int        startp     = 402;
  int        endp       = 412;
  int        interval;
  int        ntrials;
  int        ups, downs;
  float      period;
  float      gap[N_BLOCKS];
  float      min, frow;
  float      meanLevel1, meanLevel2, meanLevel3;
  double     level, plevel;
  char       colName[MAX_COLNAME];

  float      fpos;
  float      max;
  float      candidate[20];
  int        peak[20];


  cpl_msg_debug(task, "Identify fibers in image row %d", refrow);

  if (refrow < 0 || refrow >= ny) {
    cpl_msg_error(task, "Image row %d out of bounds.", refrow);
    return NULL;
  }

  /*
   *  A row of the input image is pointed by 'line'. The signal in
   *  this line is folded with different periods, starting from
   *  'startp' and ending with 'endp' (included). This is done to
   *  obtain the mean pattern for each IFU block, and determine
   *  the positions of the gaps between blocks. The pattern of a
   *  block is expected to be as long as the distance between 80 - 1 
   *  fibers plus the width of a gap. Being the fiber-to-fiber 
   *  distance about 5 pixels, and a gap width about 10 pixels,
   *  the pattern of a block should be around 405 pixels long. 
   *  The choice of 'startp' and 'endp' is constrained by this.
   *  A table containing all the obtained folded profiles is
   *  created. The folded profile containing the minimum value
   *  is found, and the position of this minimum is determined.
   *  This position roughly corresponds to the X coordinate of 
   *  the first gap in the image. 
   */

  folds = cpl_table_new(endp);
  cpl_table_new_column(folds, "count", CPL_TYPE_INT);
  count = cpl_table_get_data_int(folds, "count");

  /*
   *  The "count" column is used to normalize the folded profile.
   */

  for (i = 0, p = startp; p <= endp; i++, p++) {
    snprintf(colName, MAX_COLNAME, "p%d", p);
    cpl_table_fill_column_window_int(folds, "count", 0, p, 0);
    cpl_table_new_column(folds, colName, CPL_TYPE_FLOAT);
    cpl_table_fill_column_window_float(folds, colName, 0, p, 0.0);
    folded = cpl_table_get_data_float(folds, colName);
    for (j = 0; j < nx; j++) {
      folded[j % p] += line[j];
      count[j % p]++;
    }
    cpl_table_divide_columns(folds, colName, "count");
  }

  cpl_table_erase_column(folds, "count");

  /*
   *  For each folded profile i the position M_i of the minimum value
   *  is determined. Then the folded profile j containing the minimum 
   *  of all the minima is selected. The position of the first gap in
   *  the image line is given either by the position M_j of this lowest
   *  minimum value, or by the sum (M_j + P_j) (i.e. of this value with
   *  the period of the selected folded profile). To decide which one 
   *  is the value to prefer, it is checked whether the mean level of 
   *  a pixel interval before the first position is significantly above 
   *  the background level. Currently it is just checked whether the 
   *  signal is above a conventional level of 500 ADU.
   */

  stats = cpl_table_new(endp - startp + 1);
  cpl_table_new_column(stats, "Period", CPL_TYPE_INT);
  cpl_table_new_column(stats, "Minimum", CPL_TYPE_FLOAT);
  cpl_table_new_column(stats, "Position", CPL_TYPE_INT);

  for (i = 0, p = startp; p <= endp; i++, p++) {

    snprintf(colName, MAX_COLNAME, "p%d", p);
    cpl_table_get_column_minpos(folds, colName, &row);
    min = cpl_table_get_float(folds, colName, row, NULL);

    cpl_table_set_int(stats, "Period", i, p);
    cpl_table_set_int(stats, "Position", i, row);
    cpl_table_set_float(stats, "Minimum", i, min);

  }

  /*
   *  Fit the trend of the minima as a function of the folding period, 
   *  to find the best folding period. If the fit fails, take the
   *  folding period producing the profile with the deepest minimum.
   */

  data = cpl_table_get_data_float(stats, "Minimum");

  if (findDip1D(data, endp - startp + 1, &frow, 1) == VM_TRUE)
    row = frow;
  else {
    cpl_table_get_column_minpos(stats, "Minimum", &row);
    frow = row;
  }

  /*
   *  Best period, and beginning of first 80-fibers block.
   */

  period = cpl_table_get_int(stats, "Period", row, NULL);
  period += frow - row;

  cpl_msg_debug(task, "Best period: %f", period);

  gap[0] = cpl_table_get_int(stats, "Position", row, NULL);

  /*
   *  Here we try to eliminate the ambiguity inherent to the folding
   *  analysis, that gives just the phase of the gap positions along 
   *  the folding period. The position of the first gap along the 
   *  image line may coincide with the phase, or with the phase plus 
   *  or minus the folding period. To determine the right case, average
   *  the signal external to all fiber blocks (5 periods), considering
   *  the three different starting positions. The start position returning 
   *  the lowest value for the average is the right one.
   */

  n = 0;
  meanLevel1 = 0.0;
  interval = gap[0] - period;
  for (i = 0; i < interval; i++) {
    meanLevel1 += line[i];
    n++;
  }
  for (i = interval + N_BLOCKS * period; i < nx; i++) {
    meanLevel1 += line[i];
    n++;
  }

  meanLevel1 /= n;

  n = 0;
  meanLevel2 = 0.0;
  interval = gap[0];
  for (i = 0; i < interval; i++) {
    meanLevel2 += line[i];
    n++;
  }
  for (i = interval + N_BLOCKS * period; i < nx; i++) {
    meanLevel2 += line[i];
    n++;
  }

  meanLevel2 /= n;

  n = 0;
  meanLevel3 = 0.0;
  interval = gap[0] + period;
  for (i = 0; i < interval; i++) {
    meanLevel3 += line[i];
    n++;
  }
  for (i = interval + N_BLOCKS * period; i < nx; i++) {
    meanLevel3 += line[i];
    n++;
  }

  meanLevel3 /= n;

  if (meanLevel1 < meanLevel2 && meanLevel1 < meanLevel3)
    gap[0] -= period;
  else if (meanLevel2 > meanLevel3)
    gap[0] += period;

  gap[0] -= 1.0;  /* Start search position (fuzz parameter). */

  /*
   *  Now the 80 fibers of each block are "combed", i.e., they are
   *  correlated with a 80-teeth "comb" starting for the assigned
   *  position for the gaps. The number of correlation steps are
   *  defined as the folding period minus the distance between the
   *  first and the last peaks of a block. This is exactly the
   *  length where it makes sense to look for the max correlation
   *  factor without invading the correlation intervals of the other
   *  blocks.
   */

  ntrials = period - FIBERS_STEP * (FIBERS_PER_BLOCK - 1);

  for (i = 0; i < N_BLOCKS; i++) {

    /*
     *  After the first block position is determined, the start search
     *  of the next block is set at the last peak of the previous block
     *  (minus one pixel tolerance).
     */

    if (i)
      gap[i] = gap[i - 1] + FIBERS_STEP * FIBERS_PER_BLOCK - 1.0;

    /*
     *  The following code is nothing more than the search for the
     *  highest correlation factor. The ups and downs counters are
     *  just used for screening false maxima, coming from descending
     *  tails at the beginning of the interval (i.e., only maxima
     *  found after an ascending trend are considered).
     */

    n = 0;
    ups = 1;  /* Setting this to 1 (instead of 0) eliminates the screening */
    downs = 0;
    for (j = 0; j < ntrials; j++) {
      level = 0.0;
      for (k = 0; k < FIBERS_PER_BLOCK; k++) {
        pos = gap[i] + j + FIBERS_STEP * k;
        if (pos >= 0 && pos < nx)
          level += line[pos];
      }
      if (j) {
        if (level < plevel) {
          if (ups > 0) {
            max = plevel;
            downs++;
          }
          else {
            ups = 0;
          }
 
          if (downs > 0) {
            candidate[n] = max;
            peak[n] = j - 1;
            n++;
            ups = 0;
            downs = 0;
            continue;
          }
        }
        else {
          ups++;
        }
      }
      plevel = level;
    }

    row = peak[0];
    max = 0;
    for (j = 1; j < n; j++) {
      if (candidate[j] > max) {
        max = candidate[j];
        row = peak[j];
      }
    }

    /*
     *  To the start search position is added the offset where the
     *  max correlation was found.
     */

    gap[i] += row;

    cpl_msg_debug(task, "First peak of block %d: %f", i, gap[i]);

  }

  ident = cpl_table_new(N_BLOCKS * FIBERS_PER_BLOCK);
  cpl_table_new_column(ident, "Position", CPL_TYPE_INT);
  cpl_table_fill_column_window_int(ident, "Position", 0, 
                            N_BLOCKS * FIBERS_PER_BLOCK, 0);
  position = cpl_table_get_data_int(ident, "Position");

  for (k = 0, i = 0; i < N_BLOCKS; i++)
    for (j = 0; j < FIBERS_PER_BLOCK; j++, k++)
      position[k] = gap[i] + 5 * j;

  /* 
   *  Tables are written to disk just for debug purposes - keep the 
   *  destructors... 
   */

/*  cpl_table_save(folds, NULL, NULL, "folds.fits", CPL_IO_CREATE);  */
  cpl_table_delete(folds);

/*  cpl_table_save(stats, NULL, NULL, "stats.fits", CPL_IO_CREATE);  */
  cpl_table_delete(stats);

  /*
   *  Refine positions
   */

  cpl_table_name_column(ident, "Position", "FirstGuess");
  cpl_table_cast_column(ident, "FirstGuess", "Position", CPL_TYPE_FLOAT);

  for (i = 0; i < N_BLOCKS * FIBERS_PER_BLOCK; i++) {
    fpos = cpl_table_get_float(ident, "Position", i, NULL);
    if (!fiberPeak(image, refrow, &fpos, NULL))
      cpl_table_set_float(ident, "Position", i, fpos);
  }

  return ident;

}


/**
 * @memo
 *   Improve peak position.
 *
 * @return 0 on success.
 *
 * @param image    Image of an IFU flat field exposure.
 * @param row      Image row where the peak is.
 * @param position First-guess position of the peak (pixel).
 *
 * @doc
 *   In the assumption of high S/N, the peak is obtained by parabolic
 *   interpolation of the three highest pixels values within the peak.
 *
 * @author C. Izzo
 */

int fiberPeak(cpl_image *image, int row, float *position, float *max)
{

  char    task[] = "fiberPeak";

  int     nx   = cpl_image_get_size_x(image);
  int     ny   = cpl_image_get_size_y(image);
  float  *data = cpl_image_get_data(image);
  float  *line = data + row * nx;

  int     pos = *position + 0.5;    /* Nearest integer */
  int     ipos = pos;
  int     step;
  float   fpos;
  float   rpos;


  if (row < 0 || row >= ny) {
    cpl_msg_debug(task, "Image row %d out of bounds.", row);
    return 1;
  }
  
  if (!(pos > 0 && pos < nx - 1)) {
    cpl_msg_debug(task, "Peak position %f out of bounds.", *position);
    return 1;
  }

  /*
   *  Follow the gradient to find the highest peak.
   */

  if (line[pos] < line[pos - 1] && line[pos] > line[pos + 1])
    step = -1;
  else if (line[pos] > line[pos - 1] && line[pos] < line[pos + 1])
    step = 1;
  else if (line[pos] < line[pos - 1] && line[pos] < line[pos + 1])
    return 1;
  else
    step = 0;

  if (step) {
    while (line[pos] < line[pos + step]) {
      pos += step;
      if (!(pos > 0 && pos < nx - 1)) {
        cpl_msg_debug(task, "Peak position %f out of bounds.", *position);
        return 1;
      }
      if (abs(pos - ipos) > 2) {
        cpl_msg_debug(task, "Dead fiber at position %f.", *position);
        return 1;
      }
    }
  }

/*  if (line[pos] < 300) {    FIXME:  300 = too-low-signal threshold */
/*    cpl_msg_error(task, "Dead fiber at position %f.", *position);  */
/*    return 1;                                                      */
/*  }                                                                */

  /*
   * The peak position, and the value that a pixel would have at that
   * position, are determined on the basis of a mean fiber profile
   * model.
   */

  rpos = values_to_dx(line[pos - 1], line[pos], line[pos + 1]); 
  fpos = pos + rpos;

  if (fabs(*position - fpos) > 1.9)
    return 1;

  *position = fpos;

  if (max) {
    rpos = dx_to_value(rpos);
    *max = line[pos] / rpos;
  }

  return 0;
  
}


/**
 * @memo
 *   Trace all fibers.
 * 
 * @return Tables of fibers positions and fluxes along the dispersion direction.
 *
 * @param image    Image of an IFU flat field exposure.
 * @param row      Image reference row.
 * @param above    Pixels to trace above reference row.
 * @param below    Pixels to trace below reference row.
 * @param ident    Fibers identification table.
 *
 * @doc
 *   A table having a column for each fiber and as long as the spectral
 *   extraction interval (above + below + 1) is produced. The columns
 *   contain the fibers X CCD positions for each Y CCD pixel starting
 *   from (row - below). Another table containing the peak value at each
 *   computed fiber position on the same range is also produced. The fiber 
 *   identification table in input should be the product of either the 
 *   ifuIdentify() or the ifuIdentifyUpgrade() functions.
 *
 * @author C. Izzo
 */

cpl_table **ifuTrace(cpl_image *image, int row, int above, int below, 
                     int step, cpl_table *ident)
{

  char        task[] = "ifuTrace";

  cpl_table  *trace;
  cpl_table  *signal;
  cpl_table **tables;
  float      *pdata;
  float      *fdata;
  float      *mdata;
  int        *idata;
  int         ny     = cpl_image_get_size_y(image);

  int         i, j, k;
  int         range, offset;
  float       position, prePosition;
  float       max;
  char        colName[MAX_COLNAME];

  
  if (row + above > ny - 1 || row - below < 0) {
    cpl_msg_error(task, "Spectral extraction interval out of bounds.");
    return NULL;
  }

  range = above + below + 1;
  offset = row - below;

  trace = cpl_table_new(range);

  cpl_table_new_column(trace, "y", CPL_TYPE_INT);
  cpl_table_fill_column_window_int(trace, "y", 0, range, 1);
  idata = cpl_table_get_data_int(trace, "y");

  for (i = 0; i < range; i++)
    idata[i] = i;

  cpl_table_add_scalar(trace, "y", offset);

  signal = cpl_table_new(range);

  cpl_table_new_column(signal, "y", CPL_TYPE_INT);
  cpl_table_fill_column_window_int(signal, "y", 0, range, 1);
  idata = cpl_table_get_data_int(signal, "y");

  for (i = 0; i < range; i++)
    idata[i] = i;

  cpl_table_add_scalar(signal, "y", offset);

  pdata = cpl_table_get_data_float(ident, "Position");

  for (i = 0; i < N_BLOCKS * FIBERS_PER_BLOCK; i++) {
    snprintf(colName, MAX_COLNAME, "f%d", i + 1);
    cpl_table_new_column(trace, colName, CPL_TYPE_FLOAT);

    if (step > 1) {
      for (j = 0, k = row; j <= above; j += step, k += step)
        cpl_table_set_float(trace, colName, k - offset, 0.0); 
      for (j = step, k = row - step; j <= below; j += step, k -= step)
        cpl_table_set_float(trace, colName, k - offset, 0.0); 
    }
    else 
      cpl_table_fill_column_window_float(trace, colName, 0, range, 0.0);

    fdata = cpl_table_get_data_float(trace, colName);

    cpl_table_new_column(signal, colName, CPL_TYPE_FLOAT);

    if (step > 1) {
      for (j = 0, k = row; j <= above; j += step, k += step)
        cpl_table_set_float(signal, colName, k - offset, 0.0); 
      for (j = step, k = row - step; j <= below; j += step, k -= step)
        cpl_table_set_float(signal, colName, k - offset, 0.0); 
    }
    else 
      cpl_table_fill_column_window_float(signal, colName, 0, range, 0.0);

    mdata = cpl_table_get_data_float(signal, colName);
    position = pdata[i];
    for (j = 0, k = row; j <= above; j += step, k += step) {
      prePosition = position;
      if (fiberPeak(image, k, &position, &max)) {
        cpl_table_set_invalid(trace, colName, k - offset);
        cpl_table_set_invalid(signal, colName, k - offset);
      }
      else {
        if (fabs(prePosition - position) < 0.9) {    /*  WAS 0.2, poi 0.4 */
          fdata[k - offset] = position;
          mdata[k - offset] = max;
        }
        else {
          cpl_table_set_invalid(trace, colName, k - offset);
          cpl_table_set_invalid(signal, colName, k - offset);
          position = prePosition;
        }
      }
    }
    position = pdata[i];
    for (j = step, k = row - step; j <= below; j += step, k -= step) {
      prePosition = position;
      if (fiberPeak(image, k, &position, &max)) {
        cpl_table_set_invalid(trace, colName, k - offset);
        cpl_table_set_invalid(signal, colName, k - offset);
      }
      else {
        if (fabs(prePosition - position) < 0.9) {     /*  ERA 0.2, poi 0.4 */
          fdata[k - offset] = position;
          mdata[k - offset] = max;
        }
        else {
          cpl_table_set_invalid(trace, colName, k - offset);
          cpl_table_set_invalid(signal, colName, k - offset);
          position = prePosition;
        }
      }
    }
  }

/*  cpl_image_save(image, "fibers.fits", -32, NULL);  */

  tables = cpl_malloc(2 * sizeof(cpl_table *));

  tables[0] = trace;
  tables[1] = signal;

  return tables;

}


/**
 * @memo
 *   Smooth fibers intensities along the traces.
 *
 * @return 0 on success.
 *
 * @param signal      Table with all fibers signals along the traces.
 * @param order       Polynomial order.
 * @param maxNulls    Max tolerated number of NULL values in fiber signal.
 *
 * @doc
 *   A polynomial fit is made to each fiber signal contained in the
 *   table produced by the function ifuTrace(). The fit is performed
 *   only if the number of NULL points in the fiber signal is less 
 *   than @em maxNulls. The data values are replaced by the model 
 *   values, otherwise the whole column is replaced by NULLs.
 *
 * @author C. Izzo
 */

int ifuSignal(cpl_table *signal, int order, int maxNulls) 
{

  VimosDpoint *list;
  cpl_table   *oneSignal;
  float       *fdata;
  int         *idata = cpl_table_get_data_int(signal, "y");
  int          range = cpl_table_get_nrow(signal);
  int          npix;
  double      *c = NULL;

  int          rejected;
  int          i, j;
  char         colName[MAX_COLNAME];


  for (i = 0; i < N_BLOCKS * FIBERS_PER_BLOCK; i++) {

    snprintf(colName, MAX_COLNAME, "f%d", i + 1);
    rejected = cpl_table_count_invalid(signal, colName);
    if (rejected > maxNulls) {
      cpl_table_set_column_invalid(signal, colName, 0, range);
      continue;
    }

    if (rejected) {
      oneSignal = cpl_table_new(range);
      cpl_table_duplicate_column(oneSignal, "y", signal, "y");
      cpl_table_duplicate_column(oneSignal, colName, signal, colName);
      cpl_table_erase_invalid(oneSignal);
      fdata = cpl_table_get_data_float(oneSignal, colName);
      idata = cpl_table_get_data_int(oneSignal, "y");
      npix = cpl_table_get_nrow(oneSignal);
    }
    else {
      fdata = cpl_table_get_data_float(signal, colName);
      idata = cpl_table_get_data_int(signal, "y");
      npix = range;
    }

    list = newDpoint(npix);

    for (j = 0; j < npix; j++) {
      list[j].x = idata[j];
      list[j].y = fdata[j];
    }

    if (rejected)
      cpl_table_delete(oneSignal);

    c = fit1DPoly(order, list, npix, NULL);

    if (c) {
      drawModel(signal, colName, c, order);
      free(c);
      c = NULL;
    }

    deleteDpoint(list);

  }

  return 0;

}


/**
 * @memo
 *   Fit all traces.
 *
 * @return Table with fit coefficients for each fiber.
 *
 * @param trace       Table with all fiber traces.
 * @param order       Polynomial order.
 * @param tolerance   Max residual (in pixels) for point rejection.
 * @param maxReject   Number of point rejections to flag a dead fiber.
 *
 * @doc
 *   A polynomial fit is made to each fiber trace contained in the 
 *   table produced by the function ifuTrace(). The fit is performed
 *   only if the number of NULL points in the tracing is less than
 *   @em maxReject. After the fit, all points deviating from the
 *   model more than @em tolerance are also excluded. If the total
 *   number of NULLs and rejected points is less than @em maxReject
 *   the fiber is flagged as "dead", and the corresponding row of
 *   the table of coefficients is left empty (NULL).
 *
 * @author C. Izzo
 */

cpl_table **ifuFit(cpl_table *trace, int order, float tolerance, int maxReject)
{

  char task[] = "ifuFit";

  cpl_table   *coeff;
  cpl_table   *model;
  cpl_table  **tables;
  VimosDpoint *list;
  double      *c = NULL;
  double       rms;
  float       *fdata;
  int         *idata;
  int          range, npix;
  int          rejected, moreRejected;
  int          i, j, k;
  char         colName[MAX_COLNAME];


  range = cpl_table_get_nrow(trace);
  model = cpl_table_new(range);
  cpl_table_copy_structure(model, trace);
  idata = cpl_table_get_data_int(trace, "y");
  cpl_table_copy_data_int(model, "y", idata);

  coeff = cpl_table_new(N_BLOCKS * FIBERS_PER_BLOCK);
  for (i = 0; i <= order; i++) {
    snprintf(colName, MAX_COLNAME, "c%d", i);
    cpl_table_new_column(coeff, colName, CPL_TYPE_DOUBLE);
  }
  cpl_table_new_column(coeff, "rms", CPL_TYPE_DOUBLE);

  list = newDpoint(range);

  idata = cpl_table_get_data_int(trace, "y");

  for (i = 0; i < N_BLOCKS * FIBERS_PER_BLOCK; i++) {
    snprintf(colName, MAX_COLNAME, "f%d", i + 1);
    rejected = cpl_table_count_invalid(trace, colName);
    if (rejected > maxReject) {
      cpl_msg_debug(task, "Rejected fiber: %d (%d NULLs)", i + 1, rejected);
      continue;
    }

    fdata = cpl_table_get_data_float(trace, colName);

    if (rejected) {
      cpl_table_fill_invalid_float(trace, colName, -1);
      npix = 0;
      for (j = 0; j < range; j++) {
        if (fdata[j] < 0.)
          continue;
        list[npix].x = idata[j];
        list[npix].y = fdata[j];
        npix++;
      }
    }
    else {
      npix = range;
      for (j = 0; j < npix; j++) {
        list[j].x = idata[j];
        list[j].y = fdata[j];
      }
    }

    c = fit1DPoly(order, list, npix, &rms);
    if (c) {
      moreRejected = countRejections(list, npix, c, order, tolerance);
      if (rejected + moreRejected > maxReject) {
        cpl_msg_debug(task, "Rejected fiber: %d (%d bad values)", 
                   i + 1, rejected + moreRejected);
        free(c);
        c = NULL;
        continue;
      }
      else if (moreRejected) {    /*  Iteration  */
        free(c);
        c = NULL;
        c = fit1DPoly(order, list, npix - moreRejected, &rms);
      }
      if (c) {
        drawModel(model, colName, c, order);
        for (k = 0; k <= order; k++) {
          snprintf(colName, MAX_COLNAME, "c%d", k);
          cpl_table_set_double(coeff, colName, i, c[k]);
        }
        cpl_table_set_double(coeff, "rms", i, sqrt(rms));
        free(c);
        c = NULL;
      }
    }

  }

  deleteDpoint(list);

  tables = cpl_malloc(2 * sizeof(cpl_table *));

  tables[0] = coeff;
  tables[1] = model;

  return tables;

}


/*
 * @memo
 *   Fill missing traces.
 *
 * @return 0 on success.
 *
 * @param coeff       Table with coefficients of all fitted traces.
 *
 * @doc
 *   The ifuFit() function may reject a number of fibers, flagging
 *   them as "dead" as soon as the fit of the tracing fails. The
 *   reason of the failure may be a bad CCD column, or a cosmic
 *   ray with a trace about parallel to the fiber traces. In both
 *   such cases a fiber is not really "dead", and it may be used
 *   in the extraction of science spectra. For this reason it makes
 *   sense that in the table carrying the coefficients of the
 *   successful traces, all the missing solutions are restored by 
 *   interpolation. The interpolation is based on a polynomial
 *   fit of all the available coefficients, as a function of the
 *   refined start position of each fiber...  (HOLD ON...)
 *
 * @author C. Izzo
 */


/**
 * @memo
 *   Create a background image.
 *   
 * @return Background image.
 * 
 * @param image   Input image.
 * @param hr      0 = low resolution, else middle or high resolution exposure.
 * @param coeffs  Tables with coefficients of all fitted traces.
 * @param start   Start Y positions of validity ranges for traces.
 * @param end     End Y positions of validity ranges for traces.
 * @param order   Order of the bivariate polynomial for background modeling.
 * 
 * @doc
 *   An input image and all its available tracing solutions are
 *   specified. For HR and MR observations just one tracing table
 *   is available, while for LR observation four different tracing 
 *   tables must be specified, one for each IFU slit containing 
 *   400 fibers. It is unimportant the order in which such tables
 *   are given. For each table also the start and the end positions 
 *   of the tracings validity ranges must be specified.
 *   The algorithm goes this way: The tracings of the first and 
 *   the last fibers of each block are used to delimit the regions 
 *   where the background signal will be evaluated. If any of these 
 *   tracings are missing (because of lost or damaged fibers), they 
 *   are reconstructed by shifting the closest tracing to their 
 *   expected positions. The background values are taken from all 
 *   image pixels that are distant from the border tracings more 
 *   than 4 pixels. The pixel values are fitted by a low degree
 *   bivariate polynomial, that is then used to construct the
 *   background image.
 *   
 * @author C. Izzo
 */

cpl_image *ifuBack(cpl_image *image, int hr, cpl_table **coeffs, 
                   int *start, int *end, int order)
{

  float *auxildata;   
  float *data        = cpl_image_get_data(image);
  int    xlen        = cpl_image_get_size_x(image);
  int    ylen        = cpl_image_get_size_y(image);
  int    npix        = xlen * ylen;
  int    nc          = cpl_table_get_ncol(coeffs[0]);
  int    null;
  float  value;

  int    tableCount;
 
  int    limit[]     = {0, 79, 80, 159, 160, 239, 240, 319, 320, 399};
  int    limitCount  = 10;

  char   colName[MAX_COLNAME];

/*  VimosPixel  *pixel;  */
  VimosDpoint *list;
  double      *bra;       /* Tracing coefficients for left limit  */
  double      *ket;       /* Tracing coefficients for right limit */
  double      *c = NULL;  /* Generic tracing coefficients         */
  double      *b = NULL;  /* Background fit surface coefficients  */

  int dir;
  int radius = 5;         /* In number of fibers                  */
  int N = 4;              /* Distance of background from centroid */
  int x1, x2;
  int i, j, k, m, n;

  cpl_image *background;
  cpl_image *sbackground;
  cpl_image *auxil;   


  if (hr)
    tableCount = 1;
  else
    tableCount = 4;

  /*
   *  The coefficients of the last and the first fibers of one block and
   *  the next are bracketing a background region, and are therefore
   *  quantistically called "bra" and "ket". Only the tracings of the
   *  first fiber of the first block, and the last fiber of the last
   *  block, are a ket without a bra, and a bra without a ket.
   *  (This is clear, uh?).
   */

  bra = (double *)cpl_malloc(nc * sizeof(double));
  ket = (double *)cpl_malloc(nc * sizeof(double));

  n = 0;

  auxil = cpl_image_duplicate(image);   
  auxildata = cpl_image_get_data(auxil);   

  for (i = 0; i < npix; i++)   
    auxildata[i] = -1.0;   

  for (i = 0; i < tableCount; i++) {
    for (j = 0; j < limitCount; j++) {

      if (j % 2)                            /* First fiber of block (bra)   */
        c = bra;
      else                                  /* Last fiber of block (ket)    */
        c = ket;

      k = 0;

      c[0] = cpl_table_get_double(coeffs[i], "c0", limit[j], &null);

      if (null) {                           /* Lost fiber                   */

        if (c == bra)
          dir = -1;                         /* Backward alternatives        */
        else
          dir = 1;                          /* Forward alternatives         */

        /*
         *  Since a fiber trace is missing, we try to replace it with
         *  a shifted trace from a nearby fiber. To to this it is enough
         *  to shift the nearest tracing to the expected position of the
         *  lost fiber. Nearby tracings are searched within the value
         *  specified in 'radius' (in number of fibers).
         */

        for (k = 1; k < radius; k++) {
          c[0] = cpl_table_get_double(coeffs[i], "c0", 
                                      limit[j] + k * dir, &null);
          if (!null) {                      /* Alternative found            */
            c[0] -= FIBERS_STEP * k * dir;  /* The only changed coefficient */
            break;
          }
        }
      }

      if (null) {                           /* No alternative was found     */
        if (c == bra)                       /* Skip also the associated ket */
          j++;
        c = NULL;
        continue;
      }

      if (c[0] < 10 || c[0] > xlen - 10) {  /* 10 = safety marging          */
        if (c == bra)
          j++;
        c = NULL;
        continue;
      }

      for (m = 1; m < nc; m++)  {           /* Other coeffs are just copied */

        snprintf(colName, MAX_COLNAME, "c%d", m);
        c[m] = cpl_table_get_double(coeffs[i], colName, 
                                    limit[j] + k * dir, NULL);
      }

      if (c == ket) {                       /* We have closed a bracket     */
        for (k = start[i]; k < end[i]; k++) {
          if (j == 0)                       /* First fiber of first block   */
            x1 = 0;
          else
            x1 = modelValue1D(bra, nc - 1, k) + N;

          x2 = modelValue1D(ket, nc - 1, k) - N;

          if (x1 < 0)
            x1 = 0;

          if (x2 > xlen)
            x2 = xlen;

          for (m = x1; m < x2; m++, n++)
            auxildata[k * xlen + m] = data[k * xlen + m];

        }
      }
    }

    if (c == bra) {
      for (k = start[i]; k < end[i]; k++) {
        x1 = modelValue1D(bra, nc - 1, k) + N;
  
        for (m = x1; m < xlen; m++, n++)
          auxildata[k * xlen + m] = data[k * xlen + m];

      }
    }

  }

  /*
   * One fit for each image row. The alternative is to fit a bivariate 
   * polynomial (see commented part). If that is used, all code from
   * HERE to THERE should be commented out.
   */

  /*** HERE ***/

  background = cpl_image_duplicate(image);
  data = cpl_image_get_data(background);

  list = newDpoint(xlen);

  for (j = 0; j < ylen; j++) {
    for (i = 0, m = 0; i < xlen; i++) {
      value = auxildata[j * xlen + i];
      if (value > 0.0) {
        list[m].x = i;
        list[m].y = value;
        m++;
      }
    }

    if (m > order + 1) {
      b = fit1DPoly(order, list, m, NULL);
      if (b) {
        for (i = 0; i < xlen; i++)
          data[j * xlen + i] = modelValue1D(b, order, i);
        free(b);
        b = NULL;
      }
    }

  }

  deleteDpoint(list);

  sbackground = cpl_image_general_median_filter(background, 1, 15, 0);

  cpl_image_delete(background);

/*** THERE ***/

/*** This part (up to FINIS) does the bivariate fitting:

  pixel = newPixel(n);

  for (j = 0, m = 0; j < ylen; j++) {
    for (i = 0; i < xlen; i++) {
      value = auxildata[j * xlen + i];
      if (value > 0.0) {
        pixel[m].x = i;
        pixel[m].y = j;
        pixel[m].i = value;
        m++;
      }
    }
  }

  cpl_image_save(auxil, "debug.fits", -32, NULL);   
  cpl_image_delete(auxil);   

  b = fitSurfacePolynomial(pixel, n, NULL, order, &n, NULL);

  deletePixel(pixel);

  background = cpl_image_duplicate(image);
  data = cpl_image_get_data(background);

  for (j = 0; j < ylen; j++)
    for (i = 0; i < xlen; i++)
      data[j * xlen + i] = modelValue2D(b, order, i, j);

 *** FINIS ***/

  cpl_image_delete(auxil);   
  return sbackground;

}


/**
 * @memo
 *   Model gap background.
 *   
 * @return Background table.
 * 
 * @param image   Input image.
 * @param coeffs  Table with coefficients of all fitted traces.
 * @param start   Start Y position of validity range for traces.
 * @param end     End Y position of validity range for traces.
 * @param sbox    Smooth box length (in pixel).
 * 
 * @doc
 *   An input image and the available tracing solutions for a given
 *   range (corresponding to one IFU slit) are specified. The start 
 *   and the end positions of the tracings validity ranges must be 
 *   specified. The algorithm goes this way: The tracings of the first 
 *   and the last fibers of each block are used to delimit the regions 
 *   where the background signal will be evaluated. If any of these 
 *   tracings are missing (because of lost or damaged fibers), they 
 *   are reconstructed by shifting the closest tracing to their 
 *   expected positions. The mean value of the pixels between the
 *   the two tracings of a gap (excluding a margin of N pixels from
 *   the tracings) at a given Y position is stored in an output table 
 *   column that is then median filtered. The table columns are named 
 *   b0 to b5, where b1 to b4 refers to the gaps between fibers blocks, 
 *   b0 to the background before the first block, and b5 to the background 
 *   after the last block. Some of the columns may be missing, either 
 *   because the background layed outside the image boundaries, or 
 *   because the appropriate tracings could not be found.
 *   
 * @author C. Izzo
 */

cpl_table *ifuGap(cpl_image *image, cpl_table *coeffs, 
                  int start, int end, int sbox)
{

  cpl_table *table;
  float     *data        = cpl_image_get_data(image);
  int        xlen        = cpl_image_get_size_x(image);
  int        nc          = cpl_table_get_ncol(coeffs);
  int        null;
  double     mean;
 
  int        limit[]     = {0, 79, 80, 159, 160, 239, 240, 319, 320, 399};
  int        limitCount  = 10;

  char       colName[MAX_COLNAME];

  double     *bra;       /* Tracing coefficients for left limit  */
  double     *ket;       /* Tracing coefficients for right limit */
  double     *c;         /* Generic tracing coefficients         */

  int dir;
  int radius = 5;        /* Given in number of fibers            */
  int N = 4;             /* Distance of background from centroid */
  int x1, x2;
  int j, k, m, n;
  int nrow;


  /*
   *  The coefficients of the last and the first fibers of one block and
   *  the next are bracketing a background region, and are therefore
   *  quantistically called "bra" and "ket". Only the tracings of the
   *  first fiber of the first block, and the last fiber of the last
   *  block, are a ket without a bra, and a bra without a ket.
   *  (This is clear, uh?).
   */

  bra = (double *)cpl_malloc(nc * sizeof(double));
  ket = (double *)cpl_malloc(nc * sizeof(double));

  nrow = end - start;
  table = cpl_table_new(nrow);
  cpl_table_new_column(table, "y", CPL_TYPE_INT);

  for (j = start; j < end; j++)
    cpl_table_set_int(table, "y", j - start, j);

  for (j = 0; j < limitCount; j++) {

    if (j % 2)                            /* First fiber of block (bra)   */
      c = bra;
    else                                  /* Last fiber of block (ket)    */
      c = ket;

    k = 0;

    c[0] = cpl_table_get_double(coeffs, "c0", limit[j], &null);

    if (null) {                           /* Lost fiber                   */

      if (c == bra)
        dir = -1;                         /* Backward alternatives        */
      else
        dir = 1;                          /* Forward alternatives         */

      /*
       *  Since a fiber trace is missing, we try to replace it with
       *  a shifted trace from a nearby fiber. To to this it is enough
       *  to shift the nearest tracing to the expected position of the
       *  lost fiber. Nearby tracings are searched within the value
       *  specified in 'radius' (in number of fibers).
       */

      for (k = 1; k < radius; k++) {
        c[0] = cpl_table_get_double(coeffs, "c0", limit[j] + k * dir, &null);
        if (!null) {                      /* Alternative found            */
          c[0] -= FIBERS_STEP * k * dir;  /* The only changed coefficient */
          break;
        }
      }
    }

    if (null) {                           /* No alternative was found     */
      if (c == bra)                       /* Skip also the associated ket */
        j++;
      c = NULL;
      continue;
    }

    if (c[0] < 10 || c[0] > xlen - 10) {  /* 10 = safety marging          */
      if (c == bra)
        j++;
      c = NULL;
      continue;
    }

    for (m = 1; m < nc; m++)  {           /* Other coeffs are just copied */

      snprintf(colName, MAX_COLNAME, "c%d", m);
      c[m] = cpl_table_get_double(coeffs, colName, limit[j] + k * dir, NULL);
    }

    if (c == ket) {                       /* We have closed a bracket     */

      snprintf(colName, MAX_COLNAME, "b%d", j / 2);
      cpl_table_new_column(table, colName, CPL_TYPE_FLOAT);

      for (k = start; k < end; k++) {

        x2 = modelValue1D(ket, nc - 1, k) - N;

        if (j == 0)                       /* First fiber of first block   */
          x1 = x2 - 10;
        else
          x1 = modelValue1D(bra, nc - 1, k) + N;

        if (x1 < 0)
          x1 = 0;

        if (x2 > xlen)
          x2 = xlen;

        mean = 0.0;
        for (m = x1, n = 0; m < x2; m++, n++)
          mean += data[k * xlen + m];

/* To exclude max value from mean: eliminated, because leads to background
   underestimation.

        if (n > 1) {
          max = data[k * xlen + x1];
          for (m = x1; m < x2; m++)
            if (data[k * xlen + m] > max)
              max = data[k * xlen + m];
          mean -= max;
          --n;
        }
*/

        mean /= n;
  
        cpl_table_set_float(table, colName, k - start, mean);

      }

      cpl_table_median_filter_column(table, colName, sbox / 2);

    }
  }

  if (c == bra) {

    snprintf(colName, MAX_COLNAME, "b%d", 5);
    cpl_table_new_column(table, colName, CPL_TYPE_FLOAT);

    for (k = start; k < end; k++) {
      x1 = modelValue1D(bra, nc - 1, k) + N;
      x2 = x1 + 10;

      if (x2 > xlen)
        x2 = xlen;

      mean = 0.0;
      for (m = x1, n = 0; m < x2; m++, n++)
        mean += data[k * xlen + m];

/* To exclude max value from mean: eliminated, because leads to background
   underestimation.

      if (n > 1) {
        max = data[k * xlen + x1];
        for (m = x1; m < x2; m++)
          if (data[k * xlen + m] > max)
            max = data[k * xlen + m];
        mean -= max;
        --n;
      }
*/

      mean /= n;
  
      cpl_table_set_float(table, colName, k - start, mean);

    }

    cpl_table_median_filter_column(table, colName, sbox / 2);

  }

  return table;

}


/**
 * @memo
 *   Produce table of samplings of the fiber profile.
 *      
 * @return Table of samplings of the fiber profile.
 *
 * @param image   Input image.
 * @param model   Table with all fitted traces.
 * @param signal  Table with all fibers signal along the traces.
 * @param backs   Table with background values along each fiber block gap.
 * 
 * @doc
 *   The 10 half profiles of the 10 spectra siding the background
 *   regions are used to construct a table consisting of pixel
 *   values and their distances from the profile centroid (derived
 *   from the tracing solution), at each Y CCD coordinate within
 *   the specified range. The profile maximum contained in the
 *   signal table and the pixel values are corrected for the local 
 *   background contained in table backs, produced by the function
 *   ifuGap()). The pixel values are then normalized to the profile 
 *   maximum. 
 *
 * @author C. Izzo
 */

cpl_table *ifuProfile(cpl_image *image, cpl_table *model, cpl_table *signal,
                      cpl_table *backs)
{

  char task[] = "ifuProfile";

  cpl_table *table;

  float     *data   = cpl_image_get_data(image);
  int        xlen   = cpl_image_get_size_x(image);

  int       *idata  = cpl_table_get_data_int(model, "y");
  int       *iodata;                              /* Y coordinate on image  */
  float     *mdata;                               /* Centroid positions     */
  float     *sdata;                               /* Normalization factor   */
  float     *odata;                               /* Output pixel values    */
  float     *cdata;                               /* Distance from centroid */
  float     *bdata;                               /* Background data        */
  int        nrow   = cpl_table_get_nrow(model);

  int        i, j, k, m;
  int        x, y;
  float      fx;
  float      max;

  int        nsamples = 6;    /*  Points for each PSF profile  */

  int        limit[]     = {1, 80, 81, 160, 161, 240, 241, 320, 321, 400};
  int        limitCount  = 10;
  int        dir;

  double     (*myfloor)(double);

  char       colName[MAX_COLNAME];
  char       bakName[MAX_COLNAME];


  table = cpl_table_new(nrow * nsamples);
  cpl_table_new_column(table, "y", CPL_TYPE_INT);
  cpl_table_fill_column_window_int(table, "y", 0, nrow * nsamples, 0.0);
  iodata = cpl_table_get_data_int(table, "y");
  for (j = 0, m = 0; j < nrow; j++)
    for (k = 0; k < nsamples; k++, m++)
      iodata[m] = idata[j];

  for (i = 0; i < limitCount; i++) {

    if (i % 2) {
      dir = 1;
      myfloor = floor;
    }
    else {
      dir = -1;
      myfloor = ceil;
    }

    snprintf(colName, MAX_COLNAME, "f%d", limit[i]);

    if (cpl_table_has_invalid(model, colName)) {
      cpl_msg_debug(task, "Cannot build profile of fiber %d", limit[i]);
      continue;
    }

    /*
     *  The background values
     */

    snprintf(bakName, MAX_COLNAME, "b%d", (i + 1) / 2);
    bdata = cpl_table_get_data_float(backs, bakName);

    if (!bdata) {
      cpl_msg_debug(task, "Cannot build profile of fiber %d", limit[i]);
      continue;
    }

    /*
     *  The signal
     */

    cpl_table_fill_invalid_float(signal, colName, -1.0);
    sdata = cpl_table_get_data_float(signal, colName);

    /*
     *  The modeled traces
     */

    mdata = cpl_table_get_data_float(model, colName);

    /*
     *  The output data
     */

    cpl_table_new_column(table, colName, CPL_TYPE_INT);
    cpl_table_fill_column_window_float(table, colName, 0, nrow * nsamples, 0.0);
    odata = cpl_table_get_data_float(table, colName);

    /*
     *  The distances from the centroid
     */

    snprintf(colName, MAX_COLNAME, "d%d", limit[i]);
    cpl_table_new_column(table, colName, CPL_TYPE_FLOAT);
    cpl_table_fill_column_window_float(table, colName, 0, nrow * nsamples, 0.0);
    cdata = cpl_table_get_data_float(table, colName);

    /*
     *  Writing the result
     */

    for (j = 0, m = 0; j < nrow; j++) {
      y = idata[j];
      fx = mdata[j];
      x = myfloor(fx);
      max = sdata[j] - bdata[j];
      for (k = 0; k < nsamples; k++, x += dir, m++) {
        if (x > 0 && x < xlen && max > 0.0) {
          odata[m] = (data[y * xlen + x] - bdata[j]) / max;
          cdata[m] = fabs(x - fx);
        }
        else
          cpl_table_set_invalid(table, colName, m);
      }
    }
  }

  if (cpl_table_get_ncol(table) > 1)
    return table;

  cpl_msg_warning(task, "Table of fiber profiles not created!");
  cpl_table_delete(table);

  return NULL;

}


/**
 * @memo
 *   Build model profile table from table created by ifuProfile().
 *
 * @return Model profile table.
 *
 * @param profiles   Table created by ifuProfile().
 * @param start      Start Y position to select profile points (inclusive).
 * @param end        End Y position to select profile points (exlcusive).
 * @param length     Length of rebin interval (in pixel).
 * @param bin        Bin size (in pixel).
 *
 * @doc
 *   Within the specified range along the dispersion direction the
 *   pixel values are averaged. The obtained values are written to
 *   a table having the same column names of the input table (but 
 *   with column y removed). The "distance" column contains the
 *   distance of the center of each bin from the centroid of the 
 *   fiber profile. The number of rows in the output table is the
 *   integer part of length/bin.
 *
 * @author C. Izzo
 */

cpl_table *rebinProfile(cpl_table *profiles, int start, int end, 
                        double length, double bin)
{

  char       task[]  = "rebinProfile";
  int        nbin       = length / bin;
  cpl_table *table      = cpl_table_new(nbin);
  cpl_table *selected;

  double     xvalue, yvalue;
  double    *buffer;
  int       *count;
  int        null;

  int        limit[]    = {1, 80, 81, 160, 161, 240, 241, 320, 321, 400};
  int        limitCount = 10;

  char       distance[MAX_COLNAME];
  char       flux[MAX_COLNAME];

  int        nrow;
  int        i, j, pos;


  cpl_table_copy_structure(table, profiles);


  /*
   *  Extract just the indicated interval along the dispersion direction
   */

  cpl_table_and_selected_int(profiles, "y", CPL_NOT_LESS_THAN, start);
  nrow = cpl_table_and_selected_int(profiles, "y", CPL_LESS_THAN, end);

  selected = cpl_table_extract_selected(profiles);
  cpl_table_select_all(profiles);

  cpl_table_erase_column(table, "y");

  /*
   *  Initialize the "distance" column of the rebinned profiles.
   *  It contains the distance of the midpoint of each bin from the
   *  fiber profile centroid.
   */

  cpl_table_new_column(table, "distance", CPL_TYPE_FLOAT);
  for (j = 0; j < nbin; j++)
    cpl_table_set_float(table, "distance", j, bin * (j + 0.5));

  /*
   *  Auxiliary buffers
   */

  buffer = cpl_malloc(nbin * sizeof(double));
  count = cpl_malloc(nbin * sizeof(int));

  /*
   *  Loop on available profiles.
   */

  for (i = 0; i < limitCount; i++) {
  
    snprintf(distance, MAX_COLNAME, "d%d", limit[i]);
    snprintf(flux, MAX_COLNAME, "f%d", limit[i]);
  
    cpl_error_reset();
  
    if (!cpl_table_has_valid(selected, distance)) {
      if (CPL_ERROR_DATA_NOT_FOUND == cpl_error_get_code()) 
        cpl_msg_debug(task, "Missing profile for fiber %d", limit[i]);
      else
        cpl_msg_debug(task, "Cannot rebin profile of fiber %d", limit[i]);
      continue;
    }    

    /*
     *  Cleaning from output table useless columns as we go...
     */

    cpl_table_erase_column(table, distance);

    for (j = 0; j < nbin; j++) {
      buffer[j] = 0.0;
      count[j] = 0;
    }
  
    for (j = 0; j < nrow; j++) {
      xvalue = cpl_table_get_float(selected, distance, j, &null);
      yvalue = cpl_table_get_float(selected, flux, j, NULL);
      if (!null) {
        pos = floor(xvalue / bin);
        if (pos < nbin) {
          buffer[pos] += yvalue;
          count[pos]++;
        }
      }
    }

    for (j = 0; j < nbin; j++)
      if (count[j] > 0)
        cpl_table_set_float(table, flux, j, buffer[j] / count[j]);

    /*
     * Elements left at NULL are linearly interpolated:
     */

    /* %%%%%%%%%%%%%%%%%%%%%%%%%% DA FARE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
  
  }

  cpl_free(buffer);
  cpl_free(count);

  return table;

}


/**
 * @memo
 *   Fit a gaussian model to IFU fiber empirical profiles.
 *
 * @return Table with model coefficients (scale, mean, sigma).
 *
 * @param profiles   Table created by ifuProfile().
 * @param start      Start Y position to select profile points (inclusive).
 * @param end        End Y position to select profile points (excusive).
 *
 * @doc
 *   Within the specified range along the dispersion direction the
 *   pixel values are used for a gaussian fit. The model coefficients
 *   when available are stored at a row of the output table. In theory
 *   the scale should always be 1.0 and the mean 0.0, so any deviation
 *   from these values indicates a bad fit.
 *
 * @author C. Izzo
 */

cpl_table *ifuGauss(cpl_table *table, int start, int end)
{

  char task[] = "ifuGauss";

  cpl_table       *models;
  cpl_table       *selected;
  VimosFloatArray *x;
  VimosFloatArray *y;
  float            coeff[3];

  int    limit[]     = {1, 80, 81, 160, 161, 240, 241, 320, 321, 400};
  int    limitCount  = 10;

  int    minCount = 100;   /* Minimum number of points for fit */
  int    count;

  char   distance[MAX_COLNAME];
  char   flux[MAX_COLNAME];

  int    nrow;
  int    null;
  int    i, j;

  float  xvalue, yvalue;


  cpl_table_and_selected_int(table, "y", CPL_NOT_LESS_THAN, start);
  nrow = cpl_table_and_selected_int(table, "y", CPL_LESS_THAN, end);

  if (nrow < minCount)
    return NULL;

  selected = cpl_table_extract_selected(table);
  cpl_table_select_all(table);

  models = cpl_table_new(limitCount);
  cpl_table_new_column(models, "max", CPL_TYPE_FLOAT);
  cpl_table_new_column(models, "mean", CPL_TYPE_FLOAT);
  cpl_table_new_column(models, "sigma", CPL_TYPE_FLOAT);

  x = newFloatArray(nrow);
  y = newFloatArray(nrow);

  for (i = 0; i < limitCount; i++) {

    snprintf(distance, MAX_COLNAME, "d%d", limit[i]);
    snprintf(flux, MAX_COLNAME, "f%d", limit[i]);

    cpl_error_reset();

    if (!cpl_table_has_valid(selected, distance)) {
      cpl_msg_debug(task, "Cannot fit profile of fiber %d", limit[i]);
      continue;
    }

    if (CPL_ERROR_DATA_NOT_FOUND == cpl_error_get_code()) {
      cpl_msg_debug(task, "Missing profile for fiber %d", limit[i]);
      continue;
    }

    count = cpl_table_count_invalid(selected, distance);
    count = nrow - count;

    if (count < minCount)
      continue;

    x->len = y->len = count;  /* Use just a part of the allocated array */
    
    count = 0;
    for (j = 0; j < nrow; j++) {
      xvalue = cpl_table_get_float(selected, distance, j, &null);
      yvalue = cpl_table_get_float(selected, flux, j, NULL);
      if (!null) {
        x->data[count] = xvalue;
        y->data[count] = yvalue;
        count++;
      }
    }

    fit1DGauss(x, y, coeff, 3);

    cpl_msg_debug(task, "Profile %d: max = %f, mean = %f, sigma = %f",
               i, coeff[0], coeff[1], coeff[2]);

    cpl_table_set_float(models, "max", i, coeff[0]);
    cpl_table_set_float(models, "mean", i, coeff[1]);
    cpl_table_set_float(models, "sigma", i, coeff[2]);

  }

  deleteFloatArray(x);
  deleteFloatArray(y);

  cpl_table_delete(selected);

  return models;

}


/**
 * @memo
 *   Fit a gaussian model to IFU fiber empirical profiles.
 *
 * @return Table with model coefficients (scale, mean, sigma).
 *
 * @param profiles   Table created by ifuProfile().
 * @param start      Start Y position to select profile points (inclusive).
 * @param end        End Y position to select profile points (excusive).
 *
 * @doc
 *   Within the specified range along the dispersion direction the
 *   pixel values are used for a gaussian fit. The model coefficients
 *   when available are stored at a row of the output table. In theory
 *   the scale should always be 1.0 and the mean 0.0, so any deviation
 *   from these values indicates a bad fit.
 *
 * @author C. Izzo
 */

cpl_table *ifuGauss2(cpl_table *table, int start, int end)
{

  char task[] = "ifuGauss";

  cpl_table       *models;
  cpl_table       *selected;
  VimosFloatArray *x;
  VimosFloatArray *y;
  float            coeff[3];

  int    limit[]     = {1, 80, 81, 160, 161, 240, 241, 320, 321, 400};
  int    limitCount  = 10;

  int    minCount = 100;   /* Minimum number of points for fit */
  int    count;

  char   distance[MAX_COLNAME];
  char   flux[MAX_COLNAME];

  int    nrow;
  int    null;
  int    i, j;

  float  xvalue, yvalue;


  cpl_table_and_selected_int(table, "y", CPL_NOT_LESS_THAN, start);
  nrow = cpl_table_and_selected_int(table, "y", CPL_LESS_THAN, end);

  if (nrow < minCount)
    return NULL;

  selected = cpl_table_extract_selected(table);
  cpl_table_select_all(table);

  models = cpl_table_new(limitCount);
  cpl_table_new_column(models, "max", CPL_TYPE_FLOAT);
  cpl_table_new_column(models, "mean", CPL_TYPE_FLOAT);
  cpl_table_new_column(models, "sigma", CPL_TYPE_FLOAT);

  x = newFloatArray(2 * nrow);
  y = newFloatArray(2 * nrow);

  for (i = 0; i < limitCount; i++) {

    snprintf(distance, MAX_COLNAME, "d%d", limit[i]);
    snprintf(flux, MAX_COLNAME, "f%d", limit[i]);

    cpl_error_reset();

    if (!cpl_table_has_valid(selected, distance)) {
      cpl_msg_debug(task, "Cannot fit profile of fiber %d", limit[i]);
      continue;
    }

    if (CPL_ERROR_DATA_NOT_FOUND == cpl_error_get_code()) {
      cpl_msg_debug(task, "Missing profile for fiber %d", limit[i]);
      continue;
    }

    count = cpl_table_count_invalid(selected, distance);
    count = nrow - count;

    if (count < minCount)
      continue;

    x->len = y->len = 2 * count;  /* Use just a part of the allocated array */
    
    count = 0;
    for (j = 0; j < nrow; j++) {
      xvalue = cpl_table_get_float(selected, distance, j, &null);
      yvalue = cpl_table_get_float(selected, flux, j, NULL);
      if (!null) {
        x->data[count] = xvalue;
        y->data[count] = yvalue;
        count++;
        x->data[count] = -xvalue;
        y->data[count] = yvalue;
        count++;
      }
    }

    fit1DGauss(x, y, coeff, 3);

    cpl_msg_debug(task, "Profile %d: max = %f, mean = %f, sigma = %f",
               i, coeff[0], coeff[1], coeff[2]);

    cpl_table_set_float(models, "max", i, coeff[0]);
    cpl_table_set_float(models, "mean", i, coeff[1]);
    cpl_table_set_float(models, "sigma", i, coeff[2]);

  }

  deleteFloatArray(x);
  deleteFloatArray(y);

  cpl_table_delete(selected);

  return models;

}


/**
 * @memo 
 *   Detect traceable spectra on image.
 *
 * @return Table with cross-dispersion positions of traceable spectra.
 *
 * @param image     Bias subtracted image containing IFU spectra.
 * @param row       Image row where to run peak detection.
 * @param minSignal Min peak signal above mean minimum.
 *  
 * @doc
 *   Along the specified image row significant signal peaks are detected
 *   and analysed. A peak is considered significant when it rises above 
 *   the background level more than a given amount (currently, 70 ADU),
 *   and it is a sequence of 3 increasing values and 4 decreasing, or 
 *   a sequence of 4 increasing values and 3 decreasing. This is a secure
 *   protection against the effects of bad pixels, hot CCD columns and
 *   cosmic rays. The backgound level is taken as the mean of the output 
 *   of a min-filter with running box size of 7 pixels applied to the 
 *   image row data.
 *
 * @author C. Izzo
 */
  
cpl_table *ifuDetect(cpl_image *image, int row, float minSignal)
{

  int        nx     = cpl_image_get_size_x(image);
  float     *data   = cpl_image_get_data(image);
  float     *line   = data + row * nx;
  float     *fdata;
  int       *idata;
  int       *mask1;
  int       *mask2;

  cpl_table *imageRow;
  cpl_table *ident;

  char       colXpos[]   = "x";
  char       colSvalue[] = "svalue";
  char       colValue[]  = "value";
  float      mean, fpos;
  /* float      minSignal   = 70.0;  Removed by Peter Weilbacher */
  int        hw          = 3;
  int        count, countTraceable;
  int        i;

  cpl_propertylist *reflist;

  /*
   *  Create a table containing the selected image row data.
   *  A light median filter is passed to eliminate possible hot 
   *  columns. One column contains the x positions and another 
   *  the values of the corresponding pixels.
   */

  imageRow = cpl_table_new(nx);

  cpl_table_new_column(imageRow, colValue, CPL_TYPE_FLOAT);
  cpl_table_copy_data_float(imageRow, colValue, line);

  /*
   *  Originally a median filtering of the image row was added
   *  here, to eliminate contributes from hot CCD columns. This 
   *  was not a good idea, because it caused all peaks to have
   *  flat maxima, that introduced a bias on the peak positions.
   *  The call was:
   *
   *    cpl_table_median_filter_column(imageRow, colValue, 1);
   */

  cpl_table_new_column(imageRow, colXpos, CPL_TYPE_INT);
  idata = cpl_table_get_data_int(imageRow, colXpos);
  cpl_table_fill_column_window_int(imageRow, colXpos, 0, nx, 0);
  for (i = 0; i < nx; i++)
    idata[i] = i;

  /*
   *  Apply the min filter to estimate the mean backgound level.
   */

  cpl_table_min_filter_column(imageRow, colValue, colSvalue, hw);
  mean = cpl_table_get_column_mean(imageRow, colSvalue);
  cpl_table_subtract_scalar(imageRow, colValue, mean);
  cpl_table_erase_column(imageRow, colSvalue);

  /*
   *  Sort table according to pixel values, highest values on top.
   */

  reflist = cpl_propertylist_new();
  cpl_propertylist_append_bool(reflist, colValue, TRUE);
  cpl_table_sort(imageRow, reflist);
  cpl_propertylist_delete(reflist);

  idata = cpl_table_get_data_int(imageRow, colXpos);
  fdata = cpl_table_get_data_float(imageRow, colValue);

  /*
   *  Apply search method (first part, filling masks).
   */

  mask1 = cpl_calloc(nx, sizeof(int));
  mask2 = cpl_calloc(nx, sizeof(int));

  for (i = 0; i < nx; i++) {
    if (fdata[i] < minSignal)
      break;
    if (idata[i] > hw && idata[i] < nx - hw) {
      mask2[idata[i]] = 1;
      if (mask2[idata[i] - 1] == 0 && mask2[idata[i] + 1] == 0) 
        mask1[idata[i]] = 1;
    }
  }

  cpl_table_delete(imageRow);
  cpl_free(mask2);

  /*
   *  Search method (second part, selecting peaks having the right size).
   *  Among all the local maxima found, select just those that are the
   *  tip of a 5 pixels wide bell profile - i.e., if the peak is at
   *  position N and its value is S(N), then it must be:
   *
   *                S(N) > S(N+1) > S(N+2)
   *  and
   *                S(N) > S(N-1) > S(N-2)
   *
   *  Moreover, it must be either S(N+2) > S(N+3) or S(N-2) > S(N-3).
   *  It is not necessary to repeat in the code the comparison of S(N)
   *  with its immediate two neighbours, because this is ensured by the
   *  previous search.
   */

  countTraceable = 0;

  for (i = 0; i < nx; i++) {
    if (mask1[i]) {
      mask1[i] = 0;
      if (line[i + 1] > line[i + 2]) {
        if (line[i - 1] > line[i - 2]) {
          if (line[i + 2] > line[i + 3] || line[i - 2] > line[i - 3]) {
            countTraceable++;
            mask1[i] = 1;
          }
        }
      }
    }
  }

  if (countTraceable == 0) {
    cpl_free(mask1);
    return NULL;
  }

  ident = cpl_table_new(countTraceable);
  cpl_table_new_column(ident, "Position", CPL_TYPE_INT);
  for (count = 0, i = 0; i < nx; i++) {
    if (mask1[i] == 1) {
      cpl_table_set_int(ident, "Position", count, i);
      count++;
    }
  }

  cpl_free(mask1);

  /*
   *  Refine positions
   */

  cpl_table_name_column(ident, "Position", "FirstGuess");
  cpl_table_cast_column(ident, "FirstGuess", "Position", CPL_TYPE_FLOAT);

  for (i = 0; i < countTraceable; i++) {
    fpos = cpl_table_get_float(ident, "Position", i, NULL);
    if (!fiberPeak(image, row, &fpos, NULL))
      cpl_table_set_float(ident, "Position", i, fpos);
  }

  return ident;

}


/**
 * @memo
 *   Trace all detected fibers.
 * 
 * @return Table of fibers positions along the dispersion direction.
 *
 * @param image    Image of an IFU exposure (science).
 * @param row      Image reference row.
 * @param above    Pixels to trace above reference row.
 * @param below    Pixels to trace below reference row.
 * @param ident    Fibers detection table.
 *
 * @doc
 *   This function is pretty similar to the ifuTrace(), with the
 *   difference that it tries to trace just starting from positions
 *   of detected spectra. In practice, this function is used to
 *   trace spectra on science frames. A table having a column for 
 *   each fiber and as long as the spectral extraction interval 
 *   (above + below + 1) is produced. The columns contain the 
 *   fibers X CCD positions for each Y CCD pixel starting from 
 *   (row - below). The detected spectra table in input should 
 *   be the product of the ifuDetect() function.
 *
 * @author C. Izzo
 */

cpl_table *ifuTraceDetected(cpl_image *image, int row, int above, int below, 
                            int step, cpl_table *ident)
{

  char        task[] = "ifuTraceDetected";

  cpl_table  *trace;
  float      *pdata;
  float      *fdata;
  int        *idata;
  int         ny = cpl_image_get_size_y(image);
  int         countTraceable = cpl_table_get_nrow(ident);

  int         i, j, k;
  int         range, offset;
  float       position, prePosition;
  float       max;
  char        colName[MAX_COLNAME];

  
  if (row + above > ny - 1 || row - below < 0) {
    cpl_msg_error(task, "Spectral extraction interval out of bounds.");
    return NULL;
  }

  range = above + below + 1;
  offset = row - below;

  trace = cpl_table_new(range);

  cpl_table_new_column(trace, "y", CPL_TYPE_INT);
  cpl_table_fill_column_window_int(trace, "y", 0, range, 1);
  idata = cpl_table_get_data_int(trace, "y");

  for (i = 0; i < range; i++)
    idata[i] = i;

  cpl_table_add_scalar(trace, "y", offset);

  pdata = cpl_table_get_data_float(ident, "Position");

  for (i = 0; i < countTraceable; i++) {
    snprintf(colName, MAX_COLNAME, "t%d", i + 1);
    cpl_table_new_column(trace, colName, CPL_TYPE_FLOAT);

    if (step > 1) {
      for (j = 0, k = row; j <= above; j += step, k += step)
        cpl_table_set_float(trace, colName, k - offset, 0.0);
      for (j = step, k = row - step; j <= below; j += step, k -= step)
        cpl_table_set_float(trace, colName, k - offset, 0.0);
    }
    else
      cpl_table_fill_column_window_float(trace, colName, 0, range, 0.0);

    fdata = cpl_table_get_data_float(trace, colName);

    position = pdata[i];
    for (j = 0, k = row; j <= above; j += step, k += step) {
      prePosition = position;
      if (fiberPeak(image, k, &position, &max)) {
        cpl_table_set_invalid(trace, colName, k - offset);
      }
      else {
        if (fabs(prePosition - position) < 0.4) {    /*  ERA 0.2 */
          fdata[k - offset] = position;
        }
        else {
          cpl_table_set_invalid(trace, colName, k - offset);
          position = prePosition;
        }
      }
    }
    position = pdata[i];
    for (j = step, k = row - step; j <= below; j += step, k -= step) {
      prePosition = position;
      if (fiberPeak(image, k, &position, &max)) {
        cpl_table_set_invalid(trace, colName, k - offset);
      }
      else {
        if (fabs(prePosition - position) < 0.4) {     /*  ERA 0.2 */
          fdata[k - offset] = position;
        }
        else {
          cpl_table_set_invalid(trace, colName, k - offset);
          position = prePosition;
        }
      }
    }
  }

  return trace;

}


/**
 * @memo
 *   Fit all fiber tracings on a science exposure.
 *
 * @return Table with fit coefficients for each fiber.
 *
 * @param trace       Table with detected fiber traces ifuTraceDetected().
 * @param order       Polynomial order.
 * @param tolerance   Max residual (in pixels) for point rejection.
 * @param maxReject   Number of point rejections to flag a dead fiber.
 *
 * @doc
 *   This function is pretty similar to the ifuFit(), with the
 *   difference that it tries to fit the unidentified spectra
 *   traced on science frames. A polynomial fit is made to each 
 *   fiber trace contained in the table produced by the function 
 *   ifuTraceDetected(). 
 *
 * @author C. Izzo
 */

cpl_table *ifuFitDetected(cpl_table *trace, int order, 
                          float tolerance, int maxReject)
{

  char task[] = "ifuFitDetected";

  cpl_table   *oneTrace;
  cpl_table   *coeff;
  VimosDpoint *list;
  double      *c = NULL;
  float       *fdata;
  int         *idata;
  int          range, npix;
  int          rejected, moreRejected;
  int          countTraced = cpl_table_get_ncol(trace) - 1;
  int          i, j, k;
  char         colName[MAX_COLNAME];


  coeff = cpl_table_new(countTraced);
  for (i = 0; i <= order; i++) {
    snprintf(colName, MAX_COLNAME, "c%d", i);
    cpl_table_new_column(coeff, colName, CPL_TYPE_DOUBLE);
  }

  range = cpl_table_get_nrow(trace);
  list = newDpoint(range);

  for (i = 0; i < countTraced; i++) {
    snprintf(colName, MAX_COLNAME, "t%d", i + 1);
    rejected = cpl_table_count_invalid(trace, colName);
    if (rejected > maxReject) {
      cpl_msg_debug(task, "Rejected fiber: %d (%d NULLs)", i + 1, rejected);
      continue;
    }

    if (rejected) {
      oneTrace = cpl_table_new(range);
      cpl_table_duplicate_column(oneTrace, "y", trace, "y");
      cpl_table_duplicate_column(oneTrace, colName, trace, colName);
      cpl_table_erase_invalid(oneTrace);
      fdata = cpl_table_get_data_float(oneTrace, colName);
      idata = cpl_table_get_data_int(oneTrace, "y");
      npix = cpl_table_get_nrow(oneTrace);
    }
    else {
      fdata = cpl_table_get_data_float(trace, colName);
      idata = cpl_table_get_data_int(trace, "y");
      npix = range;
    }

    for (j = 0; j < npix; j++) {
      list[j].x = idata[j];
      list[j].y = fdata[j];
    }

    if (rejected)
      cpl_table_delete(oneTrace);

    c = fit1DPoly(order, list, npix, NULL);
    if (c) {
      moreRejected = countRejections(list, npix, c, order, tolerance);
      if (rejected + moreRejected > maxReject) {
        cpl_msg_debug(task, "Rejected fiber: %d (%d bad values)", 
                   i + 1, rejected + moreRejected);
        free(c);
        c = NULL;
        continue;
      }
      else if (moreRejected) {    /*  Iteration  */
        free(c);
        c = NULL;
        c = fit1DPoly(order, list, npix - moreRejected, NULL);
      }
      if (c) {
        for (k = 0; k <= order; k++) {
          snprintf(colName, MAX_COLNAME, "c%d", k);
          cpl_table_set_double(coeff, colName, i, c[k]);
        }
        free(c);
        c = NULL;
      }
    }

  }

  deleteDpoint(list);

  return coeff;

}


/**
 * @memo
 *   Match fibers traced on science with fibers traced on flat
 *
 * @return Table with matches
 *
 * @param short_fcoeff Table with fit to the short tracings on flats
 * @param short_coeff  Table with fit to the short tracings on science
 * @param row          Reference row
 * @param dc0          Output median offset between matching fibers
 * @param dc1          Output median slope difference between matching fibers
 *
 * @doc
 *   The X values at the reference row are computed for each set of
 *   coefficients, both for science and for flat tracings. The two
 *   sets of values are compared: for each science fiber X position,
 *   the closest flat fiber X position is searched. If this is at
 *   a distance greater than 2.5 pixels it is rejected. The set of
 *   accepted matches is further used, for computing the median
 *   difference between slopes. The returned table contains the
 *   tracing sequence number, the corresponding identified fiber 
 *   number, the position of the flat fibers at the reference row,
 *   and its offset position with the matching science tracing.
 *
 * @author C. Izzo
 */

cpl_table *ifuMatch(cpl_table *short_fcoeff, cpl_table *short_coeff, 
                    int row, double *dc0, double *dc1)
{
  
  cpl_table *matches;
  char       colName[MAX_COLNAME];
  double     fpos[N_BLOCKS * FIBERS_PER_BLOCK];
  double     fslope[N_BLOCKS * FIBERS_PER_BLOCK];
  double     position;
  double     slope;
  int        countTraced = cpl_table_get_nrow(short_coeff);
  int        countFibers = cpl_table_get_nrow(short_fcoeff);
  int        order       = cpl_table_get_ncol(short_fcoeff) - 2;
  int        fiber;
  int        null        = 0;
  int        i, j;
  double    *c;


  if (countFibers != N_BLOCKS * FIBERS_PER_BLOCK)
    return NULL;

  matches = cpl_table_new(countTraced);
  cpl_table_new_column(matches, "science", CPL_TYPE_INT);
  cpl_table_new_column(matches, "flat", CPL_TYPE_INT);
  cpl_table_new_column(matches, "position", CPL_TYPE_DOUBLE);
  cpl_table_new_column(matches, "offset", CPL_TYPE_DOUBLE);
  cpl_table_new_column(matches, "dslope", CPL_TYPE_DOUBLE);


  /*
   *  Compute all X positions of flat tracings at the reference row.
   */

  c = cpl_malloc((order + 1) * sizeof(double));

  for (i = 0; i < countFibers; i++) {
    for (j = 0; j <= order; j++) {
      snprintf(colName, MAX_COLNAME, "c%d", j);
      c[j] = cpl_table_get_double(short_fcoeff, colName, i, &null);
      if (null)
        break;
    }
    if (null) {
      null = 0;
      fpos[i] = -1.0;
      continue;
    }

    fpos[i] = modelValue1D(c, order, row);
    fslope[i] = c[1];
  }


  /*
   *  Loop on science tracings, finding their X position at the
   *  reference row. Then find the closest flat tracing, and accept
   *  it only if its offset is less than 2.5. Write matching fiber
   *  number to the output table, slope difference, and position
   *  of the science trace.
   */

  for (i = 0; i < countTraced; i++) {
    cpl_table_set_int(matches, "science", i, i + 1);
    for (j = 0; j <= order; j++) {
      snprintf(colName, MAX_COLNAME, "c%d", j);
      c[j] = cpl_table_get_double(short_coeff, colName, i, &null);
      if (null)
        break;
    }
    if (null) {
      null = 0;
      continue;
    }

    position = modelValue1D(c, order, row);
    slope = c[1];

    for (j = 0; j < countFibers; j++) {
      if (fpos[j] > 0.0) {
        if (fabs(fpos[j] - position) < 2.5) {
          cpl_table_set_int(matches, "flat", i, j + 1);
          cpl_table_set_double(matches, "position", i, position);
          cpl_table_set_double(matches, "dslope", i, slope - fslope[j]);
/*          cpl_table_set_double(matches, "offset", i, position);  */
          break;
        }
      }
    }
  }


  /*
   *  The median slope is simple.
   */

  *dc1 = cpl_table_get_column_median(matches, "dslope");

  /*
   *  The median X-shift between traces is a bit more complicated,
   *  because the rotation must be applied before to measure the offset.
   *  Recompute all X positions of flat tracings at the reference row.
   */

  for (i = 0; i < countFibers; i++) {
    for (j = 0; j <= order; j++) {
      snprintf(colName, MAX_COLNAME, "c%d", j);
      c[j] = cpl_table_get_double(short_fcoeff, colName, i, &null);
      if (null)
        break;
    }
    if (null) {
      null = 0;
      fpos[i] = -1.0;
      continue;
    }

    c[1] += *dc1;

    fpos[i] = modelValue1D(c, order, row);
  }

  cpl_free(c);


  /*
   *  Loop again on science tracings, finding their offset from the
   *  new (rotated) flat field tracings.
   */

  for (i = 0; i < countTraced; i++) {
    position = cpl_table_get_double(matches, "position", i, &null);
    if (null)
      continue;

    fiber = cpl_table_get_int(matches, "flat", i, &null);
    if (null)
      continue;

    position -= fpos[fiber - 1];
    cpl_table_set_double(matches, "offset", i, position);
  }

  /*
   *  Median offset.
   */

  *dc0 = cpl_table_get_column_median(matches, "offset");


  return matches;

}


/**
 * @memo
 *   Interpolate missing tracings.
 *
 * @return 0 on success.
 *
 * @param coeff Table with fits to the long tracings on flats
 *
 * @doc
 *   The input table is the main output of the function ifuFit(), the
 *   table containing the coefficients of all the fits to the flat field
 *   tracings. Some of these fits may be missing: their coefficients
 *   are added as an interpolation of the available nearby tracings.
 *   However, no interpolated solution is computed if the interpolation
 *   region includes one or more gaps between different fibers blocks.
 *
 * @author C. Izzo
 */

int ifuFillTracings(cpl_table *coeff, cpl_table *model)
{

  double *c1;
  double *c2;
  double *c3;
  int     countFibers = cpl_table_get_nrow(coeff);
  int     order       = cpl_table_get_ncol(coeff) - 2;
  int     null        = 0;
  int     skip        = 0;
  int     lastGood    = -1;
  int     firstGood   = 0;
  int     inNull      = 1;
  int     limit[]     = {0, 79, 80, 159, 160, 239, 240, 319, 320, 399};
  int     limitCount  = 10;
  int     i, j, k;
  char    colName[MAX_COLNAME];


  if (countFibers != N_BLOCKS * FIBERS_PER_BLOCK)
    return 1;

  c1 = cpl_malloc((order + 1) * sizeof(double));
  c2 = cpl_malloc((order + 1) * sizeof(double));
  c3 = cpl_malloc((order + 1) * sizeof(double));

  lastGood = -1;
  for (i = 0; i < countFibers; i++) {
    null = !cpl_table_is_valid(coeff, "c0", i);
    if (inNull) {
      if (!null) {
        inNull = 0;
        firstGood = i;

        /*
         *  Avoid interpolations across gaps
         */

        if (lastGood < 0)
          continue;

        for (j = 0, skip = 0; j < limitCount; j++) {
          if (limit[j] > lastGood && limit[j] < firstGood) {
            skip = 1;
            break;
          }
        }
        if (skip)
          continue;

        /*
         *  Interpolation of missing solutions
         */

        for (j = 0; j <= order; j++) {
          snprintf(colName, MAX_COLNAME, "c%d", j);
          c1[j] = cpl_table_get_double(coeff, colName, lastGood, NULL);
          c2[j] = cpl_table_get_double(coeff, colName, firstGood, NULL);
        }

        for (k = lastGood + 1; k < firstGood; k++) {
          for (j = 0; j <= order; j++) {
            snprintf(colName, MAX_COLNAME, "c%d", j);
            c3[j] = (k - lastGood) * c2[j] + (firstGood - k) * c1[j];
            c3[j] /= firstGood - lastGood;
            cpl_table_set_double(coeff, colName, k, c3[j]);
          }
          snprintf(colName, MAX_COLNAME, "f%d", k + 1);
          drawModel(model, colName, c3, order);
        }

      }
    }
    else {
      if (null) {
        inNull = 1;
        lastGood = i - 1;
      }
    }

  }

  cpl_free(c1);
  cpl_free(c2);
  cpl_free(c3);

  return 0;

}


/**
 * @memo
 *   Create table with tracing models.
 *
 * @return Table with tracing models.
 *
 * @param coeff Table with fit to the long tracings on flats
 *
 * @doc
 *   The input table is the first output of the function ifuFit().
 *   The coefficients are used to generate the new output model table
 *   with the computed tracings.
 *
 * @author C. Izzo
 */

cpl_table *ifuComputeTraces(cpl_table *coeff, int row, int above, int below)
{

  cpl_table *model;
  double    *c;
  int       *idata;
  int        countFibers = cpl_table_get_nrow(coeff);
  int        order       = cpl_table_get_ncol(coeff) - 2;
  int        null        = 0;
  int        range, offset;
  int        i, j;
  char       colName[MAX_COLNAME];


  if (countFibers != N_BLOCKS * FIBERS_PER_BLOCK)
    return NULL;

  range = above + below + 1;
  offset = row - below;

  model = cpl_table_new(range);

  cpl_table_new_column(model, "y", CPL_TYPE_INT);
  cpl_table_fill_column_window_int(model, "y", 0, range, 1);
  idata = cpl_table_get_data_int(model, "y");

  for (i = 0; i < range; i++)
    idata[i] = i;

  cpl_table_add_scalar(model, "y", offset);

  c = cpl_malloc((order + 1) * sizeof(double));

  for (i = 0; i < countFibers; i++) {
    for (j = 0; j <= order; j++) {
      snprintf(colName, MAX_COLNAME, "c%d", j);
      c[j] = cpl_table_get_double(coeff, colName, i, &null);
      if (null)
        break;
    }

    snprintf(colName, MAX_COLNAME, "f%d", i + 1);
    cpl_table_new_column(model, colName, CPL_TYPE_FLOAT);

    if (null) {
      null = 0;
      continue;
    }

    drawModel(model, colName, c, order);
  }

  cpl_free(c);

  return model;

}


/**
 * @memo
 *   Create table with shifted and rotated tracing models.
 *   
 * @return Table with shifted and rotated tracing models.
 * 
 * @param coeff Table with fit to the long tracings on flats
 * @param model Table with model of the long tracings on flats
 * @param dc0   Output median offset between matching fibers
 * @param dc1   Output median slope difference between matching fibers
 * 
 * @doc
 *   The two input tables are the outputs of the function ifuFit(). The 
 *   two input number are the offsets computed by the function ifuMatch(). 
 *   The @em model table is used just as a template for the output table, 
 *   and is left untouched. The alignment is accomplished by adding the 
 *   offset @em dc0 to the column "c0" of the @em coeff table, and the 
 *   median slope difference @em dc1 to the column "c1". After this, the 
 *   new tracings coefficients are used to generate the new output model 
 *   table with the flat tracings recomputed for the science exposure. 
 *
 * @author C. Izzo
 */

cpl_table *ifuAlign(cpl_table *coeff, cpl_table *model, double dc0, double dc1)
{

  cpl_table *amodel;
  double    *c;
  int        countFibers = cpl_table_get_nrow(coeff);
  int        order       = cpl_table_get_ncol(coeff) - 2;
  int        null        = 0;
  int        i, j;
  char       colName[MAX_COLNAME];


  if (countFibers != N_BLOCKS * FIBERS_PER_BLOCK)
    return NULL;

  amodel = cpl_table_duplicate(model);

  cpl_table_add_scalar(coeff, "c0", dc0);
  cpl_table_add_scalar(coeff, "c1", dc1);

  c = cpl_malloc((order + 1) * sizeof(double));

  for (i = 0; i < countFibers; i++) {
    for (j = 0; j <= order; j++) {
      snprintf(colName, MAX_COLNAME, "c%d", j);
      c[j] = cpl_table_get_double(coeff, colName, i, &null);
      if (null)
        break;
    }
    if (null) {
      null = 0;
      continue;
    }

    // c[0] += dc0;
    // c[1] += dc1;

    snprintf(colName, MAX_COLNAME, "f%d", i + 1);
    drawModel(amodel, colName, c, order);
  }

  cpl_free(c);

  return amodel;

}


/**
 * @memo
 *   Extraction of IFU spectra.
 *
 * @return Table with extracted spectra.
 *
 * @param image Bias subtracted IFU raw image.
 * @param model Table with model of tracings for all fibers.
 *
 * @doc
 *   For each fiber having a tracing model, a spectrum is extracted
 *   and written to the output table as a function of the CCD pixel
 *   along the dispersion direction (Y). For a given fiber, the 
 *   extracted value for each CCD pixel is obtained from the values 
 *   of the 3 pixels along the cross-dispersion direction (X) that 
 *   are closest to the position of the centroid obtained from the 
 *   tracing model. These values are divided by the normalized fiber
 *   profile values obtained with the function dx_to_value(). The model
 *   of the spatial profile is tuned (by horizontal stretching/shrinking)
 *   to an estimate of the true spatial profile of each fiber spectrum.
 *   The three values will require typically no cross-talk correction
 *   (with the only possible exception of extremely bright spectra
 *   close to extremely dim ones, that never happens), and would 
 *   provide 3 independent estimates of the total flux. In the 
 *   approximation of this function, a simple average of these three 
 *   values is taken as the extracted value.
 *
 * @note
 *   Typically, if the input image is an IFU science exposure, then
 *   the input table is the product of the function ifuAlign(); if
 *   the input image is an IFU flat field exposure, then the input
 *   table is the second product of the function ifuFit().
 *
 * @author C. Izzo
 */

cpl_table *ifuExtraction(cpl_image *image, cpl_table *model)
{

  char       task[]      = "ifuExtraction";

  int        nx          = cpl_image_get_size_x(image);
  float     *data        = cpl_image_get_data(image);
  float     *line;

  int        countFibers = cpl_table_get_ncol(model) - 1;
  int        range       = cpl_table_get_nrow(model);
  double    *spectrum;
  double    *fdata;
  float     *cdata;

  double  c;             /* Running position of the centroid                */
  int     x1, x2, x3;    /* Positions of the pixels closest to the centroid */
  double  d1, d2, d3;    /* Distances of the above pixels from the centroid */
  double  v1, v2, v3;    /* Values of the above pixels                      */
  double  c1, c2, c3;    /* Normalized values of the above pixels           */
  double  value;         /* Estimated spectral flux                         */

  double  norm = 3.017532; /* This is the normalization for transforming
                            * the normalized pixel value to an estimate of
                            * the total spectral flux, obtained from the
                            * flux_constant() function.
                            */

  int        i, j, k;
  int        offset      = cpl_table_get_int(model, "y", 0, NULL);
  double     variance, factor, step, f, min, sum_weights;
  char       colTrace[MAX_COLNAME];
  char       colSpectrum[MAX_COLNAME];


  if (countFibers != N_BLOCKS * FIBERS_PER_BLOCK)
    return NULL;

  cpl_table *spectra     = cpl_table_new(range);
  cpl_table_duplicate_column(spectra, "y", model, "y");

  cpl_table *factors = cpl_table_new(range);
  cpl_table_duplicate_column(factors, "y", model, "y");

  for (i = 0; i < countFibers; i++) {                   /* Loop on fibers */

    snprintf(colTrace, MAX_COLNAME, "f%d", i + 1);
    snprintf(colSpectrum, MAX_COLNAME, "s%d", i + 1);

    if (cpl_table_has_invalid(model, colTrace)) {
      cpl_msg_debug(task, "Trace not available for spectrum %d\n", i + 1);
      continue;
    }
    cdata = cpl_table_get_data_float(model, colTrace);

    cpl_table_new_column(factors, colSpectrum, CPL_TYPE_DOUBLE);
    cpl_table_fill_column_window_double(factors, colSpectrum, 0, range, 0.0);
    fdata = cpl_table_get_data_double(factors, colSpectrum);

    /*
     * First iteration, looking for the best "stretching" of the
     * standard spatial profile adapting to the current fibre.
     */

    for (j = 0; j < range; j++) {    /* Loop along the dispersion */

      line = data + (j + offset) * nx;
/* Too slow:
      c = cpl_table_get_float(model, colTrace, j, NULL);
*/
      c = cdata[j];                  /* Centroid                */
      x1 = c - 0.5;                  /* Intentional truncation  */
      x2 = x1 + 1;
      x3 = x2 + 1;
      if (x1 > 0 && x3 < nx) {
        d1 = c - x1;                 /* Distances from centroid */ 
        d2 = c - x2;
        d3 = c - x3;
        v1 = line[x1];               /* Pixel values            */
        v2 = line[x2];
        v3 = line[x3];
        
        step = 0.05;
        for (k = 0; k < 22; k++) {
          f = 0.5 + k*step;
          c1 = v1 / dx_to_value(f*d1);        /* Normalization  */
          c2 = v2 / dx_to_value(f*d2);
          c3 = v3 / dx_to_value(f*d3);
          value = (c1 + c2 + c3) / 3;         /* Mean value     */
          variance = (value - c1)*(value - c1)
                   + (value - c2)*(value - c2)
                   + (value - c3)*(value - c3);
          if (k) {
            if (min > variance) {
              min = variance;
              factor = f;
            }
          }
          else {
            min = variance;
            factor = f;
          }
        }
        if (factor < 0.55 || factor > 1.5)
            cpl_table_set_invalid(factors, colSpectrum, j);
        else
            fdata[j] = factor;
/* Too slow:
            cpl_table_set_double(factors, colSpectrum, j, factor);
*/
      }

    } /* End loop along the dispersion */

    cpl_table_new_column(spectra, colSpectrum, CPL_TYPE_DOUBLE);
    cpl_table_fill_column_window_double(spectra, colSpectrum, 0, range, 0.0);
    spectrum = cpl_table_get_data_double(spectra, colSpectrum);
    f = cpl_table_get_column_median(factors, colSpectrum);
/* *+
    printf("median of fiber %d = %f\n", i, f);
+* */

    for (j = 0; j < range; j++) {            /* Loop along the dispersion */

      line = data + (j + offset) * nx;
/* Too slow:
      c = cpl_table_get_float(model, colTrace, j, NULL);
*/
      c = cdata[j];                  /* Centroid                */
      x1 = c - 0.5;                  /* Intentional truncation */
      x2 = x1 + 1;
      x3 = x2 + 1;
      if (x1 > 0 && x3 < nx) {
        d1 = c - x1;                 /* Distances from centroid */
        d2 = c - x2;
        d3 = c - x3;
        v1 = line[x1];               /* Pixel values            */
        v2 = line[x2];
        v3 = line[x3];
/*
 * Old, non-optimal code:

        c1 = v1 / dx_to_value(f*d1);   \* Normalization           *\
        c2 = v2 / dx_to_value(f*d2);
        c3 = v3 / dx_to_value(f*d3);
        value = (c1 + c2 + c3) / 3;  \* Mean value              *\
 End of old, non-optimal code */

 /* New, optimal code: */

        sum_weights = dx_to_value(f*d1) * dx_to_value(f*d1)
                    + dx_to_value(f*d2) * dx_to_value(f*d2)
                    + dx_to_value(f*d3) * dx_to_value(f*d3);

        /*
         * Here come the optimal estimate (assuming that the variance is
         * background dominated, and therefore constant, that is true for
         * weak objects, while for bright objects S/N is good anyway).
         * Note that the weights are dx_to_value(f*di) squared, and
         * IT IS CORRECT NOT TO SQUARE the profile in the sum of the
         * measured profile values - do the algebra if you want to see 
         * why...
         */

        c1 = v1 * dx_to_value(f*d1);
        c2 = v2 * dx_to_value(f*d2);
        c3 = v3 * dx_to_value(f*d3);
        value = (c1 + c2 + c3) / sum_weights;  /* Flux estimator */

        value *= norm*f;               /* ADU for each Y CCD pixel */
        spectrum[j] = value;
/* Too slow:
        cpl_table_set_double(spectra, colSpectrum, j, value);
*/
      }

    } /* End loop along the dispersion */

  } /* End loop on fibers */

/*
  cpl_table_save(factors, NULL, NULL, "factors.fits", CPL_IO_CREATE);
*/
  cpl_table_delete(factors);

  return spectra;

}


/**
 * @memo
 *   Simple extraction of IFU spectra.
 *
 * @return Table with extracted spectra.
 *
 * @param image Bias subtracted IFU raw image.
 * @param model Table with model of tracings for all fibers.
 *
 * @doc
 *   For each fiber having a tracing model, a spectrum is extracted
 *   and written to the output table as a function of the CCD pixel
 *   along the dispersion direction (Y). For a given fiber, the 
 *   extracted value for each CCD pixel is obtained from the values 
 *   of the 3 pixels along the cross-dispersion direction (X) that 
 *   are closest to the position of the centroid obtained from the 
 *   tracing model. These values are divided by the normalized fiber
 *   profile values obtained with the function dx_to_value(). These
 *   three values will require typically no cross-talk correction
 *   (with the only possible exception of extremely bright spectra
 *   close to extremely dim ones), and would provide 3 independent
 *   estimates of the total flux. In the simple approximation of
 *   this function, a simple average of these three values is taken 
 *   as the extracted value.
 *
 * @note
 *   Typically, if the input image is an IFU science exposure, then
 *   the input table is the product of the function ifuAlign(); if
 *   the input image is an IFU flat field exposure, then the input
 *   table is the second product of the function ifuFit().
 *
 * @author C. Izzo
 */

cpl_table *ifuSimpleExtraction(cpl_image *image, cpl_table *model)
{

  char       task[]      = "ifuSimpleExtraction";

  int        nx          = cpl_image_get_size_x(image);
  float     *data        = cpl_image_get_data(image);
  float     *line;

  int        countFibers = cpl_table_get_ncol(model) - 1;
  int        range       = cpl_table_get_nrow(model);
  cpl_table *spectra     = cpl_table_new(range);

  double  c;             /* Running position of the centroid                */
  int     x1, x2, x3;    /* Positions of the pixels closest to the centroid */
  double  d1, d2, d3;    /* Distances of the above pixels from the centroid */
  double  v1, v2, v3;    /* Values of the above pixels                      */
  double  c1, c2, c3;    /* Normalized values of the above pixels           */
  double  value;         /* Estimated spectral flux                         */

  double  norm = 3.017532; /* This is the normalization for transforming
                            * the normalized pixel value to an estimate of
                            * the total spectral flux, obtained from the
                            * flux_constant() function.
                            */

  int        i, j;
  int        offset      = cpl_table_get_int(model, "y", 0, NULL);
  char       colTrace[MAX_COLNAME];
  char       colSpectrum[MAX_COLNAME];


  if (countFibers != N_BLOCKS * FIBERS_PER_BLOCK)
    return NULL;

  cpl_table_duplicate_column(spectra, "y", model, "y");

  for (i = 0; i < countFibers; i++) {                   /* Loop on fibers */

    snprintf(colTrace, MAX_COLNAME, "f%d", i + 1);
    snprintf(colSpectrum, MAX_COLNAME, "s%d", i + 1);
    if (cpl_table_has_invalid(model, colTrace)) {
      cpl_msg_debug(task, "Trace not available for spectrum %d\n", i + 1);
      continue;
    }
    cpl_table_new_column(spectra, colSpectrum, CPL_TYPE_DOUBLE);
    cpl_table_fill_column_window_double(spectra, colSpectrum, 0, range, 0.0);

    for (j = 0; j < range; j++) {            /* Loop along the dispersion */

      line = data + (j + offset) * nx;
      c = cpl_table_get_float(model, colTrace, j, NULL);
      x1 = c - 0.5;                  /* Intentional truncation */
      x2 = x1 + 1;
      x3 = x2 + 1;
      if (x1 > 0 && x3 < nx) {
        d1 = c - x1;                 /* Distances from centroid */
        d2 = c - x2;
        d3 = c - x3;
        v1 = line[x1];               /* Pixel values            */
        v2 = line[x2];
        v3 = line[x3];
        c1 = v1 / dx_to_value(d1);   /* Normalization           */
        c2 = v2 / dx_to_value(d2);
        c3 = v3 / dx_to_value(d3);
        value = (c1 + c2 + c3) / 3;  /* Mean value              */
        value *= norm;               /* ADU for each Y CCD pixel */
        cpl_table_set_double(spectra, colSpectrum, j, value);
      }

    } /* End loop along the dispersion */

  } /* End loop on fibers */

  return spectra;

}


/**
 * @memo
 *   Very simple extraction of IFU spectra.
 *
 * @return Table with extracted spectra.
 *
 * @param image Bias subtracted IFU raw image.
 * @param model Table with model of tracings for all fibers.
 *
 * @doc
 *   For each fiber having a tracing model, a spectrum is extracted
 *   and written to the output table as a function of the CCD pixel
 *   along the dispersion direction (Y). For a given fiber, the 
 *   extracted value for each CCD pixel is obtained from the value 
 *   of the pixel along the cross-dispersion direction (X) that 
 *   is closest to the position of the centroid obtained from the 
 *   tracing model. This value is divided by the normalized fiber
 *   profile values obtained with the function dx_to_value(). This
 *   value will require typically no cross-talk correction (with 
 *   the only possible exception of extremely bright spectra close
 *   to extremely dim ones).
 *
 * @note
 *   Typically, if the input image is an IFU science exposure, then
 *   the input table is the product of the function ifuAlign(); if
 *   the input image is an IFU flat field exposure, then the input
 *   table is the second product of the function ifuFit().
 *
 * @author C. Izzo
 */

cpl_table *ifuVerySimpleExtraction(cpl_image *image, cpl_table *model)
{

  char       task[]      = "ifuVerySimpleExtraction";

  int        nx          = cpl_image_get_size_x(image);
  float     *data        = cpl_image_get_data(image);
  float     *line;

  int        countFibers = cpl_table_get_ncol(model) - 1;
  int        range       = cpl_table_get_nrow(model);
  cpl_table *spectra     = cpl_table_new(range);
  double    *spectrum;

  double     c;          /* Running position of the centroid              */
  int        x;          /* Position of the pixel closest to the centroid */
  double     d;          /* Distance of the above pixel from the centroid */
  double     v;          /* Value of the above pixel                      */
  double     value;      /* Estimated spectral flux                       */

  int        i, j;
  int        offset      = cpl_table_get_int(model, "y", 0, NULL);
  char       colTrace[MAX_COLNAME];
  char       colSpectrum[MAX_COLNAME];


  if (countFibers != N_BLOCKS * FIBERS_PER_BLOCK)
    return NULL;

  cpl_table_duplicate_column(spectra, "y", model, "y");

  for (i = 0; i < countFibers; i++) {                   /* Loop on fibers */

    snprintf(colTrace, MAX_COLNAME, "f%d", i + 1);
    snprintf(colSpectrum, MAX_COLNAME, "s%d", i + 1);
    if (cpl_table_has_invalid(model, colTrace)) {
      cpl_msg_debug(task, "Trace not available for spectrum %d\n", i + 1);
      continue;
    }
    cpl_table_new_column(spectra, colSpectrum, CPL_TYPE_DOUBLE);
    cpl_table_fill_column_window_double(spectra, colSpectrum, 0, range, 0.0);
    spectrum = cpl_table_get_data_double(spectra, colSpectrum);

    for (j = 0; j < range; j++) {            /* Loop along the dispersion */

      line = data + (j + offset) * nx;
      c = cpl_table_get_float(model, colTrace, j, NULL);
      x = c + 0.5;                           /* Intentional truncation    */
      if (x > 0 && x < nx) {
        d = c - x;                           /* Distances from centroid   */
        v = line[x];                         /* Pixel values              */
        value = v / dx_to_value(d);          /* Normalization             */
        cpl_table_set_double(spectra, colSpectrum, j, value);
      }

    } /* End loop along the dispersion */

  } /* End loop on fibers */

  return spectra;

}


/**
 * @memo
 *   Generate transmission correction from flat field spectra.
 *
 * @return 0 on success.
 *
 * @param image     Image containing wavelength calibrated flat field spectra.
 * @param startPix  Start integration pixel.
 * @param endPix    End integration pixel.
 * @param norm      Returned normalization factor (median value).
 *
 * @doc
 *   The input image contains the extracted and wavelength calibrated
 *   flat field spectra for each fiber. If the input image contains
 *   1600 spectra (LR grisms case), the first (bottom) 400 spectra
 *   refer to pseudo-slit 0, the next 400 to pseudo-slit 1, ..., and
 *   the last (top) 400 to pseudo-slit 3. If the input image contains
 *   400 spectra (MR and HR grisms case), the spectra refer to pseudo-
 *   slit 1 (the only one used). In all cases, the spectra of a pseudo-
 *   slit starting from the left side of the chip (lowest X CCD ccordinates)
 *   are stored from bottom to top in the output image.
 *
 *   The output table contains the fluxes integrated from each spectrum
 *   on the specified interval, and normalized to their median value.
 *
 * @author C. Izzo
 */

cpl_table *ifuTransmission(cpl_image *image, 
                           int startPix, int endPix, double *norm, double *err)
{

/*  char task[]      = "ifuTransmission";   */

  int        nx          = cpl_image_get_size_x(image);
  int        ny          = cpl_image_get_size_y(image);
  float     *data        = cpl_image_get_data(image);
  float     *line        = data;
  cpl_table *table       = cpl_table_new(ny);
  int        i, j;
  double     sum;
  double     level;


  cpl_table_new_column(table, "trans", CPL_TYPE_DOUBLE);

  for (i = 0; i < ny; i++, line += nx) {
    sum = 0.0;
    for (j = startPix; j < endPix; j++)
      sum += line[j];
    if (sum > 0.00001)
      cpl_table_set_double(table, "trans", i, sum);
  }

  level = cpl_table_get_column_median(table, "trans");

  cpl_table_divide_scalar(table, "trans", level);

  *norm = level;

  /* FIXME:
   * The statistical error on the computed total flux is extremely
   * small, since the flux is integrated on a wide spectral range
   * from all the available spectra. In order to compute the error 
   * rigorously, an error image should be compute at extraction
   * time, and passed to this function. Temporarily, a worst
   * scenario is adopted for an estimation of the error, setting
   * a very high value for the gain (3 e-/ADU), and assuming that
   * the spectral extraction operation did not improve the S/N ratio.
   */

  *err = sqrt(3*level);

  return table;

}


/**
 * @memo
 *   Apply transmission correction to extracted and wave-calibrated spectra
 *
 * @return 0 on success.
 *
 * @param image     Image containing wavelength calibrated spectra.
 * @param table     Table containing transmission correction factors.
 *
 * @doc
 *   The input image contains extracted and wavelength calibrated
 *   spectra for each fiber. Each image row is multiplied by the
 *   corresponding transmission factor.
 *
 * @author C. Izzo
 */

int ifuApplyTransmission(cpl_image *image, cpl_table *table)
{

  int        nx          = cpl_image_get_size_x(image);
  int        ny          = cpl_image_get_size_y(image);
  float     *data        = cpl_image_get_data(image);
  float     *line        = data;
  double     factor;
  int        null;
  int        i, j;


  for (i = 0; i < ny; i++, line += nx) {
    factor = cpl_table_get_double(table, "trans", i, &null);
    if (null)
      continue;
    if (factor < 0.00001)
      continue;
    for (j = 0; j < nx; j++)
      line[j] /= factor;
  }

  return 0;

}


/**
 * @memo
 *   Sum spectral signal.
 *
 * @return Array of integrated signals from each fiber spectrum.
 *
 * @param spectra Table with extracted spectra.
 * @param zero    Expected position of contamination.
 * @param skip    Number of pixels to skip around contamination (radius).
 *
 * @doc
 *   The input table may be the product of any IFU spectral extraction 
 *   function, from ifuSimpleExtraction() to [ADD FUNCTION NAME HERE].
 *   The only requirement is that the table contains 400 columns named
 *   "s1", "s2", "s3", ... , "s400", and one column "y" for the coordinate
 *   along the dispersion direction. Other columns may exist, and would
 *   be ignored. The values of each column are averaged and written to output. 
 *   Any column containing invalid values would be assigned a zero sum. 
 *   If the expected position of the contamination is zero, or outside 
 *   the extraction range, all the spectral values are integrated.
 *
 * @author C. Izzo
 */

double *ifuIntegrateSpectra(cpl_table *spectra, int zero, int skip)
{

/*  char    task[]      = "ifuIntegrateSpectra";   */

  char    colSpectrum[MAX_COLNAME];

  double *buffer;
  double *spectrum;
  double  sum;
  int    *y           = cpl_table_get_data_int(spectra, "y");
  int     countFibers = N_BLOCKS * FIBERS_PER_BLOCK;
  int     range       = cpl_table_get_nrow(spectra);
  int     dist;
  int     count;
  int     i, j;


  buffer = cpl_malloc(countFibers * sizeof(double));

  for (i = 0; i < countFibers; i++) {
    snprintf(colSpectrum, MAX_COLNAME, "s%d", i + 1);
    if (cpl_table_has_column(spectra, colSpectrum)) {
      if (cpl_table_has_invalid(spectra, colSpectrum)) {
        buffer[i] = 0.0;
      }
      else {
        spectrum = cpl_table_get_data_double(spectra, colSpectrum);
        for (j = 0, sum = 0.0, count = 0; j < range; j++) {
          dist = abs(y[j] - zero);
          if (dist > skip) {
            sum += spectrum[j];
            count++;
          }
        }
        buffer[i] = sum / count;
      }
    }
    else
      buffer[i] = 0.0;
  }

  return buffer;
  
}


/**
 * @memo
 *   Fill IFU reconstructed field.
 *
 * @return 0 on success.
 *
 * @param image     IFU field.
 * @param integrals Array with integrated spectral signals.
 * @param quadrant  Quadrant number [1-4].
 * @param slit      IFU slit number [0-3].
 *
 * @doc
 *   The input buffer, @em integrals, may be the product of any IFU 
 *   spectral signal integration function, from ifuIntegrateSpectra() 
 *   to [ADD FUNCTION NAME HERE]. The buffer must include 400 values, 
 *   each one of them is written to the appropriate position of the
 *   allocated 80x80 @em image given in input, according to the
 *   specified quadrant and IFU slit number.
 *
 * @author C. Izzo
 */

int ifuImage(cpl_image *image, double *integrals, int quadrant, int slit)
{

  char   task[] = "ifuImage";

  float *data   = cpl_image_get_data_float(image);
  int    lpos, mpos;
  int    startl[N_SLITS], startm[N_SLITS], dm[N_SLITS], jump[N_SLITS];
  int    dl;
  int    i, j, k;


  /*
   * Coding of the IFU table:
   *
   * Each block consists of 80 fibers.
   * Each IFU slit consists of 5 blocks.
   * Each quadrant accomodates 4 IFU slits.
   * Here all is counted starting from zero.
   * IFU slit 1 is the central one (the only one used with HR grisms).
   *
   * startl[L] indicates the start l coordinate of block 0 in IFU slit L.
   * startm[L] indicates the start m coordinate of block 0 in IFU slit L.
   * dm[L]     indicates whether the m coordinate increases or decreases
   *           during wrapping of IFU slit L.
   * jump[L]   indicates the m gap between m start positions of blocks
   *           of IFU slit L.
   */

  switch (quadrant) {
  case 1:
    dl = 1;
    startl[0] = 79;
    startl[1] = 59;
    startl[2] = 59;
    startl[3] = 79;
    startm[0] = 60;
    startm[1] = 43;             /* 43; CONSORTIUM,  56; Isabelle */
    startm[2] = 63;
    startm[3] = 43;
    dm[0] =  1;
    dm[1] = -1;                 /* -1; CONSORTIUM,   1; Isabelle */
    dm[2] = -1;
    dm[3] = -1;
    jump[0] =  4;
    jump[1] =  4;               /*  4; CONSORTIUM,  -4; Isabelle */
    jump[2] =  4;
    jump[3] =  4;
    break;
  case 2:
/*  Original setting!
    dl =  1;
    startl[0] = 19;
    startl[1] = 39;
    startl[2] = 39;
    startl[3] = 19;
    startm[0] = 76;
    startm[1] = 59;
    startm[2] = 79;
    startm[3] = 56;
    dm[0] =  1;
    dm[1] = -1;
    dm[2] = -1;
    dm[3] =  1;
    jump[0] = -4;
    jump[1] = -4;
    jump[2] = -4;
    jump[3] = -4;
    break;
*/
    dl =  1;
    startl[0] = 19;
    startl[1] = 39;
    startl[2] = 39;
    startl[3] = 19;
    startm[0] = 76;
    startm[1] = 59;
    startm[2] = 79;
    startm[3] = 59;
    dm[0] =  1;
    dm[1] = -1;
    dm[2] = -1;
    dm[3] = -1;
    jump[0] = -4;
    jump[1] = -4;
    jump[2] = -4;
    jump[3] = -4;
    break;
  case 3:
    dl = 1;
    startl[0] = 19;
    startl[1] = 39;
    startl[2] = 39;
    startl[3] = 19;
    startm[0] = 3;
    startm[1] = 20;
    startm[2] = 0;
    startm[3] = 20;
    dm[0] = -1;
    dm[1] =  1;
    dm[2] =  1;
    dm[3] =  1;
    jump[0] =  4;
    jump[1] =  4;
    jump[2] =  4;
    jump[3] =  4;
    break;
  case 4:
    dl = 1;
    startl[0] = 79;
    startl[1] = 59;
    startl[2] = 59;
    startl[3] = 79;
    startm[0] = 19;
    startm[1] = 36;             /* 36; CONSORTIUM, 23; Isabelle */
    startm[2] = 16;
    startm[3] = 36;
    dm[0] = -1;
    dm[1] =  1;                 /* 1; CONSORTIUM, -1; Isabelle */
    dm[2] =  1;
    dm[3] =  1;
    jump[0] = -4;
    jump[1] = -4;                /* -4; CONSORTIUM, 4; Isabelle */
    jump[2] = -4;
    jump[3] = -4;
    break;
  default:
    cpl_msg_error(task, "Wrong quadrant number (you should never get here!)");
    return 1;
  }

  /*
   *  Write values to image
   */

  lpos = startl[slit];

  k = 0;
  for (i = 0; i < N_BLOCKS; i++) {
    if (quadrant == 2 && slit == 3) {
      if (i == 4) {
        startm[slit] = 47;
        jump[slit] = 0;
        dm[slit] = -1;
      }
      if (i == 3) {
        startm[slit] = 43;
        jump[slit] = 0;
        dm[slit] = -1;
      }
    }
    mpos = startm[slit] + i * jump[slit];
    for (j = 0; j < FIBERS_PER_BLOCK / 4; j++) {
      data[lpos + mpos * FIBERS_PER_BLOCK] = integrals[k];
      k++;
/* printf("%d %d %d\n", k + slit * 400, lpos + 1, mpos + 1); */
/* printf("%d %d %d\n", k, lpos + 1, mpos + 1); */
      lpos -= dl;
    }
    mpos += dm[slit];
    for (j = 0; j < FIBERS_PER_BLOCK / 4; j++) {
      lpos += dl;
      data[lpos + mpos * FIBERS_PER_BLOCK] = integrals[k];
      k++;
/* printf("%d %d %d\n", k + slit * 400, lpos + 1, mpos + 1); */
/* printf("%d %d %d\n", k, lpos + 1, mpos + 1); */
    }
    mpos += dm[slit];
    for (j = 0; j < FIBERS_PER_BLOCK / 4; j++) {
      data[lpos + mpos * FIBERS_PER_BLOCK] = integrals[k];
      k++;
/* printf("%d %d %d\n", k + slit * 400, lpos + 1, mpos + 1); */
/* printf("%d %d %d\n", k, lpos + 1, mpos + 1); */
      lpos -= dl;
    }
    mpos += dm[slit];
    for (j = 0; j < FIBERS_PER_BLOCK / 4; j++) {
      lpos += dl;
      data[lpos + mpos * FIBERS_PER_BLOCK] = integrals[k];
      k++;
/* printf("%d %d %d\n", k + slit * 400, lpos + 1, mpos + 1); */
/* printf("%d %d %d\n", k, lpos + 1, mpos + 1); */
    }
  }

  return 0;

}


/**
 * @memo
 *   Compute wavelength calibration for each extracted arc lamp spectrum.
 *
 * @return Table with wavelength calibrations.
 *
 * @param spectra  Extracted arc lamp spectra for each fiber.
 * @param linecat  Line catalog.
 * @param coeff    First guess wavelength calibration.
 * @param order    Order of the IDS polynomial.
 * @param lambda   Reference wavelength.
 * @param zero     Expected position of the zero order contamination.
 *
 * @doc
 *   This function returns the inverse dispersion solution for each
 *   extracted arc lamp spectrum. The first guess wavelength calibration
 *   may come from the appropriate calibration file, or from the function 
 *   ifuFirstIds().
 *
 * @author C. Izzo
 */

cpl_table *ifuComputeIds(cpl_table *spectra, cpl_table *linecat, 
                         double *coeff, int order, double lambda, 
                         int zero, double maxRms)
{

/*  char       task[] = "ifuComputeIds";  */

  char         colName[MAX_COLNAME];
  int          countFibers = N_BLOCKS * FIBERS_PER_BLOCK;
  int          nrow        = cpl_table_get_nrow(spectra);
  int          nlines      = cpl_table_get_nrow(linecat);
  int          offset      = cpl_table_get_int(spectra, "y", 0, NULL);
  cpl_table   *coeffTable  = cpl_table_new(countFibers);
  float       *wdata       = cpl_table_get_data_float(linecat, "WLEN");
  VimosDpoint *list        = newDpoint(nlines);
  double      *data;
  double      *c = NULL;
  double       rms;
  int          contamRadius = 15;
  int          bigSearchRadius = 30;
  int          startSearchRadius = 3;
  int          endSearchRadius = 15;
  int          searchRadius;
  int          countLines;

  double       level;             /* Current detection level               */
  double       aboveLevel = 120.; /* Start detection level                 */
  double       thresRms = 1.0;    /* This is used by the iteration process */
  double       pos;
  int          ipos;
  int          maxIter = 4;
  int          yStart, yEnd, length;
  int          yStartShort, yEndShort, lengthShort;
  int          found, foundFirst;
  int          skipFirst = 1;
  int          i, j, k;


  for (i = 0; i <= order; i++) {
    snprintf(colName, MAX_COLNAME, "c%d", i);
    cpl_table_new_column(coeffTable, colName, CPL_TYPE_DOUBLE);
  }
  cpl_table_new_column(coeffTable, "rms", CPL_TYPE_DOUBLE);
  cpl_table_new_column(coeffTable, "nlines", CPL_TYPE_INT);
  cpl_table_fill_column_window_int(coeffTable, "nlines", 0, countFibers, 0);

repeat:

  /*
   *  Determine interval where to look for the reference arc line
   */

  yStart = coeff[0] - offset - bigSearchRadius;
  yEnd = coeff[0] - offset + bigSearchRadius;
  if (yStart < 0)
    yStart = 0;
  if (yEnd > nrow)
    yEnd = nrow;
  if (yEnd < 0 || yStart >= nrow)
    return NULL;

  length = yEnd - yStart;


  /*
   *  Lines identification
   */

  for (i = 0; i < countFibers; i++) {
    cpl_msg_debug(cpl_func,"Computing wavelength solution for fiber %d", i+1);
    snprintf(colName, MAX_COLNAME, "s%d", i + 1);

    if (!cpl_table_has_column(spectra, colName))
      continue;

    if (cpl_table_has_invalid(spectra, colName))
      continue;

    if (skipFirst) {
        skipFirst = 0;
        continue;
    }

    /*
     * Determine significant level for line detection at 5 * sigma.
     * Determine standard deviation from the median level using only
     * the negative deviations.
     */

    data = cpl_table_get_data_double(spectra, colName);
    level = cpl_table_get_column_median(spectra, colName);
    cpl_msg_debug(cpl_func,"The median level of fiber %d is %f", i+1, level);

    ipos = whereMax(data + yStart, length);
    coeff[0] = yStart + offset + ipos;

    for (k = 0; k < maxIter; k++) {
      level += aboveLevel;
      countLines = 0;
      for (j = 0; j < nlines; j++) {
        ipos = modelValue1D(coeff, order, wdata[j] - lambda);

        /*
         * Skip line if too close to zero order contamination
         */

        if (abs(ipos - zero) < contamRadius + endSearchRadius)
          continue;

        found = 0;
        for (searchRadius = startSearchRadius; searchRadius <= endSearchRadius;
             searchRadius++) {

          /*
           *  Determine interval where to look for the current arc line
           */

          yStartShort = ipos - offset - searchRadius;
          yEndShort = ipos - offset + searchRadius;
          if (yStartShort < 0)
            break;                              /* yStartShort = 0; */
          if (yEndShort > nrow)
            break;                              /* yEndShort = nrow; */
          if (yEndShort < 0 || yStartShort >= nrow)
            break;
          lengthShort = yEndShort - yStartShort;
    
          if (findPeak(data + yStartShort, lengthShort, level, &pos)) {
            found = 1;
            break;
          }
        }

        if (found) {
          list[countLines].x = wdata[j] - lambda;
          list[countLines].y = yStartShort + offset + pos;
          countLines++;
        }

      }

      /*
       *  The number of identified lines should be at least twice
       *  the degrees of freedom.
       */

      if (countLines < 2 * (order + 1))
        continue;

      c = fit1DPoly(order, list, countLines, &rms);
      if (c) {
        if (rms < thresRms)
          break;
        if (k == maxIter - 1)
          break;         /* If last, don't free(c) (keep the bad solution) */
        free(c);
        c = NULL;
      }
    }

    if (c) {
      if (rms < maxRms) {
        for (j = 0; j <= order; j++) {
          snprintf(colName, MAX_COLNAME, "c%d", j);
          cpl_table_set_double(coeffTable, colName, i, c[j]);
        }
        cpl_table_set_double(coeffTable, "rms", i, sqrt(rms));
        cpl_table_set_int(coeffTable, "nlines", i, countLines);
        for (j = 0; j <= order; j++)
          coeff[j] = c[j];
        if (!foundFirst) {
          foundFirst = 1;
          free(c);
          c = NULL;
          goto repeat;
        }
      }
      free(c);
      c = NULL;
    }
    else
    {
      cpl_msg_debug(cpl_func,
              "Wavelenght calibration failed for fiber %d", i+1);
      continue;
    }

  }

  deleteDpoint(list);

  return coeffTable;

}


/**
 * @memo
 *   Compute wavelength calibration for each extracted arc lamp spectrum.
 *
 * @return Table with wavelength calibrations.
 *
 * @param spectra    Extracted arc lamp spectra for each fiber.
 * @param linecat    Line catalog.
 * @param lambda2pix Rough expected inverse-dispersion (pixel/A).
 * @param order      Order of the IDS polynomial.
 * @param lambda     Reference wavelength.
 * @param zero       Expected position of the zero order contamination.
 *
 * @doc
 *   This function returns the inverse dispersion solution for each
 *   extracted arc lamp spectrum. There is no need of first-guess
 *   model - just a rough inverse-dispersion should be provided.
 *
 * @author C. Izzo
 */

double *ifuComputeIdsBlind(cpl_table *spectra, cpl_table *linecat, 
                           double lambda2pix, int order, double lambda, 
                           double maxRms)
{

/*  char       task[] = "ifuComputeIdsBlind";  */

  char         colName[MAX_COLNAME];
  int          countFibers = N_BLOCKS * FIBERS_PER_BLOCK;
  int          nrow        = cpl_table_get_nrow(spectra);
  int          nlines      = cpl_table_get_nrow(linecat);
  int          offset      = cpl_table_get_int(spectra, "y", 0, NULL);
  cpl_table   *coeffTable  = cpl_table_new(countFibers);
  float       *wdata       = cpl_table_get_data_float(linecat, "WLEN");
  double      *lines;
  VimosDpoint *list        = newDpoint(nlines);
  double      *peaks;
  double     **output;
  double      *data;
  double      *c = NULL;
  double      *coeff = NULL;
  double       rms;
  int          countLines;
  int          npeaks;

  double       level;             /* Spectral background level             */
  double       aboveLevel = 120.; /* Above background level                */
  double       max_disp, min_disp;
  
  int          i, j;


  for (i = 0; i <= order; i++) {
    snprintf(colName, MAX_COLNAME, "c%d", i);
    cpl_table_new_column(coeffTable, colName, CPL_TYPE_DOUBLE);
  }
  cpl_table_new_column(coeffTable, "rms", CPL_TYPE_DOUBLE);
  cpl_table_new_column(coeffTable, "nlines", CPL_TYPE_INT);
  cpl_table_fill_column_window_int(coeffTable, "nlines", 0, countFibers, 0);

  lines = cpl_malloc(nlines * sizeof(double));

  for (i = 0; i < nlines; i++)
    lines[i] = wdata[i];

  max_disp = min_disp = 1 / lambda2pix;
  max_disp += max_disp / 5.5;
  min_disp -= min_disp / 5.5;

  /*
   *  Peak detection and lines identification
   */

  for (i = 0; i < countFibers; i++) {
    snprintf(colName, MAX_COLNAME, "s%d", i + 1);

    if (!cpl_table_has_column(spectra, colName))
      continue;

    if (cpl_table_has_invalid(spectra, colName))
      continue;

    data = cpl_table_get_data_double(spectra, colName);
    level = cpl_table_get_column_median(spectra, colName);
    level += aboveLevel;

    peaks = collectPeaks_double(data, nrow, level, 1.0, &npeaks);
    cpl_msg_debug(cpl_func,"Found %d peaks for fiber %d", 
                  npeaks, i+1);

    if (peaks) {
      output = identPeaks(peaks, npeaks, lines, nlines, min_disp, max_disp,
                          0.07, &countLines);
      if (output) {
        for (j = 0; j < countLines; j++) {
          list[j].x = output[1][j] - lambda;
          list[j].y = output[0][j] + offset;
        }
        cpl_free(output[0]);
        cpl_free(output[1]);
        cpl_free(output);
      }
      cpl_free(peaks);
    }
    else
      countLines = 0;

    /*
     *  The number of identified lines should be at least twice
     *  the degrees of freedom.
     */
    cpl_msg_debug(cpl_func,"Number of identified lines for fiber %d: %d order %d", 
                  i+1, countLines, order);

    if (countLines < 2 * (order + 1))
    {
      cpl_msg_debug(cpl_func,
              "Number of lines (%d) not enough for blind fitting (%d)",
              countLines, 2 * (order + 1));
      continue;
    }

    c = fit1DPoly(order, list, countLines, &rms);

    if (c) {
      if (rms < maxRms) {
        for (j = 0; j <= order; j++) {
          snprintf(colName, MAX_COLNAME, "c%d", j);
          cpl_table_set_double(coeffTable, colName, i, c[j]);
        }
        cpl_table_set_double(coeffTable, "rms", i, sqrt(rms));
        cpl_table_set_int(coeffTable, "nlines", i, countLines);
      }
      free(c);
      c = NULL;
    }
    else
    {
        cpl_msg_debug(cpl_func, 
                "Fitting of wavelength polynomial failed for fiber %d",i+1);
    }

  }

  cpl_free(lines);
  deleteDpoint(list);

/*
 *  return coeffTable;
 */

  coeff = cpl_malloc((order + 1) * sizeof(double));
  cpl_msg_debug(cpl_func,"Mean blind wavelength ids:");
  for (i = 0; i <= order; i++) {
    snprintf(colName, MAX_COLNAME, "c%d", i);
    coeff[i] = cpl_table_get_column_median(coeffTable, colName);
    cpl_msg_debug(cpl_func,"  c[%d]: %f",i, coeff[i]);
  }

  cpl_table_delete(coeffTable);

  return coeff;

}


/**
 * @memo
 *   Resample all extracted spectra at a constant wavelength step.
 *   
 * @return Image with resampled spectra.
 * 
 * @param image       Allocated image to be filled with the resampled spectra.
 * @param spectra     Extracted arc lamp spectra for each fiber.
 * @param ids         IDS table.
 * @param slit        IFU pseudo-slit (from 0 to 3, with 0 the isolated slit).
 * @param lambda      Reference wavelength.
 * @param startLambda First wavelength.
 * @param stepLambda  Step of wavelength grid.
 * 
 * @doc
 *   This function fills an image with all the extracted fiber spectra 
 *   resampled at a constant wavelength step. The resampling is made 
 *   conserving the flux locally. Signal excessive undersampling is not 
 *   allowed: this function returns a NULL if the wavelength step is
 *   more than twice the maximum value of the inverse of the first order 
 *   coefficient in the IDS for all fibers. No limits are posed to signal 
 *   oversampling: however, it is recommended to choose a wavelength step 
 *   close to, or slightly less than, the mean spectral dispersion (in 
 *   A/pixel). The resampled spectra from fiber 1 to 400 are stored in
 *   the output image from bottom to top, with the 400 spectra coming 
 *   from the pseudo-slit 0 at the bottom, and those coming from the
 *   pseudo-slit 3 at the top.
 *
 * @author C. Izzo
 */

int ifuResampleSpectra(cpl_image *image, cpl_table *spectra, cpl_table *ids, 
                       int slit, double lambda, double startLambda, 
                       double stepLambda)
{

/*  char       task[] = "ifuResampleSpectra";  */

  int        countFibers = N_BLOCKS * FIBERS_PER_BLOCK;
  int        nx          = cpl_image_get_size_x(image);
  int        ny          = cpl_image_get_size_y(image);
  float     *data        = cpl_image_get_data(image);
  float     *line        = data;
  int        order       = cpl_table_get_ncol(ids) - 3;
  int        offset      = cpl_table_get_int(spectra, "y", 0, NULL);
  int        npix        = cpl_table_get_nrow(spectra);
  int        null        = 0;
  int        intPixel;
  double    *spectrum;
  double     pixel;
  double    *p;
  double     value;
  double    *v;
  double    *c;
  cpl_table *table;
  char       colName[MAX_COLNAME];
  int        i, j, k;


  /*
   *  Allocate the work table were each resampled spectrum is constructed.
   */

  table = cpl_table_new(nx);
  /* Pixels at each lambda    */
  cpl_table_new_column(table, "pixel", CPL_TYPE_DOUBLE);  

  /* Derivative of the above  */
  cpl_table_new_column(table, "dpixel", CPL_TYPE_DOUBLE); 

  /* Interpolated spec values */
  cpl_table_new_column(table, "values", CPL_TYPE_DOUBLE); 

  p = cpl_table_get_data_double(table, "pixel");
  v = cpl_table_get_data_double(table, "values");
  c = cpl_malloc((order + 1) * sizeof(double));

  if (ny > countFibers)
    line += slit * countFibers * nx;

  for (i = 0; i < countFibers; i++, line += nx) {

    /*
     *  Get the IDS for the current fiber
     */

    for (j = 0; j <= order; j++) {
      snprintf(colName, MAX_COLNAME, "c%d", j);
      c[j] = cpl_table_get_double(ids, colName, i, &null);
      if (null)
        break;
    }
    if (null) {
      null = 0;
      continue;
    }

    /*
     *  Determine the pixel positions corresponding to each wavelength
     *  of the sampling, and linearly interpolate the signal at those 
     *  positions.
     */

    snprintf(colName, MAX_COLNAME, "s%d", i + 1);
    spectrum = cpl_table_get_data_double(spectra, colName);

    if (spectrum == NULL) {
      cpl_error_reset();
      continue;
    }

    for (k = 0; k < nx; k++) {
      pixel = modelValue1D(c, order, startLambda + k * stepLambda - lambda);
      pixel -= offset;
      p[k] = pixel;

      /*
       *  Linear interpolation of the signal
       */

      intPixel = pixel;
      if (intPixel <= 0 || intPixel > npix - 2) {
        v[k] = 0.0;
        continue;
      }

      v[k] = spectrum[intPixel] * (1 - pixel + intPixel)
           + spectrum[intPixel + 1] * (pixel - intPixel);
    }


    /*
     *  Apply flux conservation correction. Compute the pixel positions 
     *  derivative, and multiply the interpolated values by it.
     */

    cpl_table_copy_data_double(table, "dpixel", p);
    cpl_table_shift_column(table, "dpixel", -1);
    cpl_table_subtract_columns(table, "dpixel", "pixel");
    value = cpl_table_get_double(table, "dpixel", nx - 2, NULL);
    cpl_table_set_double(table, "dpixel", nx - 1, value);
    cpl_table_multiply_columns(table, "values", "dpixel");

    for (k = 0; k < nx; k++)
      line[k] = v[k];
    
  }

  cpl_table_delete(table);
  cpl_free(c);

  return 0;

}


/**
 * @memo
 *   Read all extracted spectra from table to image
 *
 * @return Image with spectra.
 *
 * @param image       Allocated image to be filled with the spectra.
 * @param spectra     Extracted arc lamp spectra for each fiber.
 * @param slit        IFU pseudo-slit (from 0 to 3, with 0 the isolated slit).
 *
 * @doc
 *   This function fills an image with all the extracted fiber spectra.
 *   The extracted spectra from fiber 1 to 400 are stored in the
 *   output image from bottom to top, with the 400 spectra coming
 *   from the pseudo-slit 0 at the bottom, and those coming from the
 *   pseudo-slit 3 at the top.
 *
 * @author C. Izzo
 */


int ifuReadSpectra(cpl_image *image, cpl_table *spectra, int slit)
{ 
    
/*  char       task[] = "ifuReadSpectra";  */
  
  int        countFibers = N_BLOCKS * FIBERS_PER_BLOCK;
  int        nx          = cpl_image_get_size_x(image);
  int        ny          = cpl_image_get_size_y(image);
  int        nrow        = cpl_table_get_nrow(spectra);
  float     *line        = cpl_image_get_data(image);
  double    *spectrum;
  char       colName[MAX_COLNAME];
  int        i, k;


  if (ny > countFibers)
    line += slit * countFibers * nx;

  for (i = 0; i < countFibers; i++, line += nx) {

    snprintf(colName, MAX_COLNAME, "s%d", i + 1);
    spectrum = cpl_table_get_data_double(spectra, colName);

    if (spectrum == NULL) {
      cpl_error_reset();
      continue;
    }

    for (k = 0; k < nrow; k++)
      line[k] = spectrum[k];

  }

  return 0;

}


/**
 * @memo
 *   Correct arc calibration with offset of sky lines.
 *
 * @return Applied shift.
 *
 * @param spectra     Extracted scientific spectra for each fiber.
 * @param ids         IDS table.
 * @param lambda      Reference wavelength.
 *
 * @doc
 *   This function determine on extracted (but still uncalibrated)
 *   spectra the distance of the skylines from their expected
 *   position according to the given IDS. The median offset is
 *   then added to the constant term of the IDS. Currently, only
 *   skylines 5577.338, 6300.304, 6363.780, and 8344.602 are used. 
 *
 * @author C. Izzo
 */
    
double ifuAlignSkylines(cpl_table *spectra, cpl_table *ids, double lambda,
                        int individual)
{

  int        countFibers  = N_BLOCKS * FIBERS_PER_BLOCK;
  int        order        = cpl_table_get_ncol(ids) - 3;
  int        offset       = cpl_table_get_int(spectra, "y", 0, NULL);
  int        npix         = cpl_table_get_nrow(spectra);
  int        null         = 0;
  int        searchRadius = 7;  /* It was 4, Peter Weilbacher */
  int        nLines       = 4;  /* Number of skylines */
  double     line[]       = {5577.338, 6300.304, 6363.780, 8344.602};
  double     expected;
  double     detected;
  double     shift;
  int        iexpected;
  double    *spectrum;
  cpl_table *table;
  double    *c;
  /* double     maxShift = 2000.0;   Removed by Peter Weilbacher */

  /* Added by Peter Weilbacher: */
  double     maxShift = 30.0,
             maxResidShift = 2.0; /* everything beyond a 2px individual shift *
                                   * means that the wavelength calibration    *
                                   * was totally wrong (cosmic ray?)          */
  char       colName[MAX_COLNAME];
  int        found;
  int        startBin, endBin, length;
  int        countNulls;
  int        i, j;

#if DEBUG_SHIFTS
  char       tablename[1024];
#endif


  /*
   *  Allocate the work table an offset is determined for each spectrum.
   */

  table = cpl_table_new(countFibers); 
  cpl_table_new_column(table, "shift", CPL_TYPE_DOUBLE);

  c = cpl_malloc((order + 1) * sizeof(double));


  /*
   *  Compute expected position for skylines, and compare it to their
   *  real position.
   */

  for (i = 0; i < countFibers; i++) {

    /*
     *  Get the IDS for the current fiber
     */
    
    for (j = 0; j <= order; j++) {
      snprintf(colName, MAX_COLNAME, "c%d", j);
      c[j] = cpl_table_get_double(ids, colName, i, &null);
      if (null)
        break;
    }
    if (null) {
      null = 0;
      continue;
    }
    
    snprintf(colName, MAX_COLNAME, "s%d", i + 1);
    spectrum = cpl_table_get_data_double(spectra, colName);

    if (spectrum == NULL) {
      cpl_error_reset();
      continue;
    }

    found = 0;
    shift = 0.0;
    for (j = 0; j < nLines; j++) {
      expected = modelValue1D(c, order, line[j] - lambda);
      iexpected = expected;


      /*
       *  Determine interval where to look for the current sky line
       */

      startBin = iexpected - offset - searchRadius;
      endBin = iexpected - offset + searchRadius;
      if (startBin < 0)
        continue;
      if (endBin > npix)
        continue;
      length = endBin - startBin;

      if (findPeak(spectrum + startBin, length, 0.0, &detected)) {
        shift += startBin + offset + detected - expected;
        found++;
      }
    }

    if (found) {
      shift /= found;
      if (shift < maxShift) {
        cpl_table_set_double(table, "shift", i, shift);
      }
    }
  }

  cpl_free((void*)c);

  countNulls = cpl_table_count_invalid(table, "shift");

  if (countNulls == countFibers)
    return 0.0;

/* cpl_table_save(table, NULL, NULL, "shifts.fits", CPL_IO_CREATE); */

#if DEBUG_SHIFTS
  /* save for debugging */
  sprintf(tablename, "align_shifts1_%s.fits", individual ? "indi" : "norm");
  cpl_table_save(table, NULL, NULL, tablename, CPL_IO_CREATE);
  sprintf(tablename, "align_ids1_%s.fits", individual ? "indi" : "norm");
  cpl_table_save(ids, NULL, NULL, tablename, CPL_IO_CREATE);
#endif

  /*  
   *  Median shift.
   *  Apply this in any case, so that even fibers with invalid values
   *  are shifted by the extra zeropoint.
   */

  shift = cpl_table_get_column_median(table, "shift");
  cpl_msg_info("ifuAlignSkylines", "Applying median shift of %f px", shift);
  cpl_table_add_scalar(ids, "c0", shift); /* apply the median shift */

  /* Added by Peter Weilbacher: */

  if (individual) {
    cpl_msg_info("ifuAlignSkylines", "Now applying individual shifts...");

    /* subtract it from shift column to make those shift into residual shifts */
    cpl_table_subtract_scalar(table, "shift", shift);
#if DEBUG_SHIFTS
    cpl_table_save(table, NULL, NULL, "align_shifts2_indi.fits", CPL_IO_CREATE);
#endif

    /* now apply individual shift if available, one by one */
    for (i = 0; i < countFibers; i++) {
      if (cpl_table_is_valid(table, "shift", i) == 1 &&
          cpl_table_is_valid(ids, "c0", i) == 1) {
        double residualshift, c0;
        int rscheck = 0, c0check = 0;

        residualshift = cpl_table_get_double(table, "shift", i, &rscheck);
#if DEBUG_SHIFTS
        cpl_msg_debug("ifuAlignSkylines()", "%d: %f", i+1, residualshift);
#endif
        if (fabs(residualshift) <= maxResidShift) {
          c0 = cpl_table_get_double(ids, "c0", i, &c0check);
          if (rscheck || c0check) {
            continue;
          }
          cpl_table_set_double(ids, "c0", i, c0 + residualshift);
        }
      }
    }
  } else {
    cpl_msg_info("ifuAlignSkylines", "NOT applying individual shifts");
#if DEBUG_SHIFTS
    cpl_table_save(ids, NULL, NULL, "align_ids2_norm.fits", CPL_IO_CREATE);
#endif
  }
  /* End of addition by Peter Weilbacher */

  cpl_table_delete(table);

  return shift;

}


/**
 * @memo
 *   Return sequence number of active fiber closest to CCD center.
 *   
 * @return Sequence number of active fiber closest to CCD center.
 * 
 * @param short_coeff Coefficients of linear tracing around reference row.
 * @param row         Reference row.
 * 
 * @doc
 *   This function finds the active fiber that is closest to the CCD 
 *   coordinate X = 1024, and returns its sequence number (counted 
 *   starting from 0). The input table contains the coefficients of 
 *   a linear fit to the spectral tracings around the reference row, 
 *   i.e., at the CCD coordinate Y = @em row. In case of error, a 
 *   negative number is returned.
 *
 * @author C. Izzo
 */

int findCentralFiber(cpl_table *short_coeff, int row)
{

  int     countFibers = cpl_table_get_nrow(short_coeff);
  int     null        = 0;
  int     fiber       = -1;
  int     i;
  double  c[2];
  double  pos, prepos;


  if (countFibers != N_BLOCKS * FIBERS_PER_BLOCK)
    return fiber;

  /*
   *  Compute all X positions of tracings at the reference row.
   */

  for (i = 0; i < countFibers; i++) {
    c[0] = cpl_table_get_double(short_coeff, "c0", i, &null);
    if (null) {
      null = 0;
      continue;
    }
    c[1] = cpl_table_get_double(short_coeff, "c1", i, NULL);
    pos = modelValue1D(c, 1, row);

    if (pos > 1024.) {
      if ((pos - 1024.) < (1024. - prepos))
        fiber = i;
      else
        fiber = i - 1;
      break;
    }
    else
      prepos = pos;

  }

  return fiber;

}


/**
 * @memo
 *   Determine sky spectrum and subtract it from the data.
 *
 * @return Sky spectrum
 *
 * @param extracted Image of extracted spectra.
 *
 * @doc
 *   This function finds the sky as the median value along the cross
 *   dispersion direction (y coordinate), and subtract it from the data.
 *   This method is appropriately applied on data where more than 50%
 *   of the extracted spectra are coming from the sky, typically on a
 *   standard star exposure.
 *
 * @author C. Izzo
 */

cpl_image *ifuSubtractSky(cpl_image *extracted)
{

  float     *data = cpl_image_get_data(extracted);
  int        nx   = cpl_image_get_size_x(extracted);
  int        ny   = cpl_image_get_size_y(extracted);
  cpl_image *sky;
  float     *skydata;
  float     *column;
  int        i, j;


  sky = cpl_image_new(nx, 1, CPL_TYPE_FLOAT);
  skydata = cpl_image_get_data(sky);

  column = cpl_malloc(ny * sizeof(float));

  for (i = 0; i < nx; i++) {
    for (j = 0; j < ny; j++)
      column[j] = data[i + j * nx];
    skydata[i] = median(column, ny);
    for (j = 0; j < ny; j++)
      data[i + j * nx] -= skydata[i];
  }

  cpl_free(column);

  return sky;

}


/**
 * @memo
 *   Obtain total spectrum from IFU observation.
 *
 * @return Total spectrum
 *
 * @param extracted   Image of extracted spectra.
 *
 * @doc
 *   This function simply sum all the spectra and returns the sum
 *   spectrum.
 *
 * @author C. Izzo
 */

cpl_image *ifuSumSpectrum(cpl_image *extracted)
{

  float     *data = cpl_image_get_data(extracted);
  int        nx   = cpl_image_get_size_x(extracted);
  int        ny   = cpl_image_get_size_y(extracted);
  cpl_image *sum;
  float     *sumdata;
  double     value;
  int        i, j;


  sum = cpl_image_new(nx, 1, CPL_TYPE_FLOAT);
  sumdata = cpl_image_get_data(sum);

  for (i = 0; i < nx; i++) {
    value = 0.0;
    for (j = 0; j < ny; j++)
      value += data[i + j * nx];
    sumdata[i] = value;
  }

  return sum;

}


/**
 * @memo
 *   Obtain mean flux per extracted fiber per given wavelength.
 *   
 * @return 0 = success
 * 
 * @param extracted   Image of extracted spectra.
 * @param lambda      Wavelength of line to evaluate.
 * @param start       Wavelength of first pixel in image.
 * @param step        Wavelength interval per pixel.
 * @param flux        Mean flux per fiber.
 * @param flux_err    Error on mean flux per fiber.
 * 
 * @doc
 *   This function simply sums along the whole Y image dimension all ADUs 
 *   on a 11 pixel interval centered on the given wavelength along the 
 *   whole Y image dimension, and divides it by the number of image rows
 *   containing signal (value > 0.0).
 *   
 * @author C. Izzo
 */

int extractIfuFlux(cpl_image *extracted, double lambda, double start, 
                   double step, double *flux, double *flux_err)
{

  float      *data = cpl_image_get_data(extracted);
  int         nx   = cpl_image_get_size_x(extracted);
  int         ny   = cpl_image_get_size_y(extracted);
  int         pixcen, pixsta, pixend;
  int         pos;
  int         nfib;
  double     *buffer;
  double      value, rms;
  int         i, j;
  cpl_vector *vect;


  *flux = 0.0;
  *flux_err = 0.0;

  pixcen = (lambda - start) / step;

  pixsta = pixcen - 5;
  pixend = pixcen + 6;

  if (pixsta < 0 || pixend > nx)
    return 1;

  buffer = cpl_calloc(ny, sizeof(double));

  nfib = 0;
  for (i = 0; i < ny; i++) {
    value = 0.0;
    pos = i*nx + pixsta;
    for (j = pixsta; j < pixend; j++, pos++)
      value += data[pos];
    if (value > 0.0) {
      buffer[nfib] = value;
      nfib++;
    }
  }

  if (nfib < 3) {
    cpl_free(buffer);
    return 2;
  }

  vect = cpl_vector_wrap(nfib, buffer);
  value = cpl_vector_get_median_const(vect);
  *flux = cpl_vector_get_mean(vect);
  cpl_vector_unwrap(vect);

  rms = 0.0;
  for (i = 0; i < nfib; i++)
    rms += fabs(buffer[i] - value);

  cpl_free(buffer);

  rms /= nfib;
  rms *= MEANDEV_TO_SIGMA;

  *flux_err = rms;

  return 0;

}



/**
 * @memo
 *   Set to zero all background spectra.
 * 
 * @return 0 on success.
 * 
 * @param extracted   Image of extracted spectra.
 *
 * @doc
 *   This function simply set to zero all spectra that can be
 *   considered background spectra. A background spectrum is 
 *   detected under the assumption that the background level
 *   has already been subtracted: in such a case, a background
 *   spectrum is one that has enough negative values (more than
 *   a given percentage).
 *
 * @author C. Izzo
 */
 
int ifuSetZeroLevel(cpl_image *extracted)
{
 
  float     *data = cpl_image_get_data(extracted);
  int        nx   = cpl_image_get_size_x(extracted);
  int        ny   = cpl_image_get_size_y(extracted);
  int        count;
  int        i, j;
  double     ratio;


  for (j = 0; j < ny; j++) {
    count = 0;
    for (i = 0; i < nx; i++)
      if (data[i + j * nx] < 0.0)
        count++;
    ratio = ((double)count) / nx;
    if (ratio > 0.2)
    for (i = 0; i < nx; i++)
      data[i + j * nx] = 0.0;
  }

  return 0;

}

/*@}*/