File: uves_reduce_scired.c

package info (click to toggle)
cpl-plugin-uves 6.1.3+dfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 23,128 kB
  • sloc: ansic: 171,056; sh: 4,359; python: 3,002; makefile: 1,322
file content (2660 lines) | stat: -rw-r--r-- 88,660 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
/*                                                                              *
 *   This file is part of the ESO UVES Pipeline                                 *
 *   Copyright (C) 2004,2005 European Southern Observatory                      *
 *                                                                              *
 *   This library 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, 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA       *
 *                                                                              */

/*
 * $Author: amodigli $
 * $Date: 2013-08-08 13:36:46 $
 * $Revision: 1.70 $
 * $Name: not supported by cvs2svn $
 *
 */

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

/*----------------------------------------------------------------------------*/
/**
 * @addtogroup uves_scired
 *
 */
/*----------------------------------------------------------------------------*/
/**@{*/


/*-----------------------------------------------------------------------------
                                Includes
 -----------------------------------------------------------------------------*/
#include <uves_reduce_scired.h>

#include <uves_reduce.h>
#include <uves_reduce_utils.h>
#include <uves_corrbadpix.h>

#include <uves_chip.h>
#include <uves_plot.h>
#include <uves_dfs.h>
#include <uves_pfits.h>
#include <uves_parameters.h>
#include <uves_msg.h>
#include <uves_utils.h>
#include <uves_utils_wrappers.h>
#include <uves_qclog.h>
#include <uves_error.h>
#include <uves_merge.h>
#include <uves.h>
#include <uves_dump.h>

#include <cpl.h>
#include <string.h>
#include <../hdrl/hdrl.h>
#include <uves_response_utils.h>
#define UVES_HDRL_USE_EXPERIMENTAL 0
/*-----------------------------------------------------------------------------
                            Functions prototypes
 -----------------------------------------------------------------------------*/

static void
scired_qclog(const cpl_table* info_tbl, 
         const uves_propertylist *raw_header,
         const cpl_image *raw_image,
         double slit,
         cpl_table* qclog);

static void
tflat_qclog(const cpl_image* ima,
        const uves_propertylist *raw_header,
        cpl_table* qclog);


/*-----------------------------------------------------------------------------
                            Implementation
 -----------------------------------------------------------------------------*/


static cpl_error_code
uves_flux_calibrate_spectra(const cpl_image *sci_ima_data,
		                    const cpl_image *sci_ima_errs,
							const uves_propertylist* rhead,
							const uves_propertylist* phead,
							const cpl_table* response,
        			        const cpl_table* atm_extinction,
							enum uves_chip chip,
					        cpl_table** fluxcal_sci_tab,
							cpl_image** fluxcal_ima_data,
							cpl_image** fluxcal_ima_errs,
							double* crval1,double* cdelt1);

static cpl_error_code
uves_flux_calibrate_spectra(const cpl_image *sci_ima_data,
		                    const cpl_image *sci_ima_errs,
							const uves_propertylist* rhead,
							const uves_propertylist* phead,
							const cpl_table* response,
        			        const cpl_table* atm_extinction,
							enum uves_chip chip,
					        cpl_table** fluxcal_sci_tab,
							cpl_image** fluxcal_ima_data,
							cpl_image** fluxcal_ima_errs,
							double* lambda_start,
							double* dlambda)
{
	/* Flux calibrate the spectrum */
	//Required inputs: scired, atm extiction, exptime, gain, response
	const char* fname;

	hdrl_spectrum1D_wave_scale scale = hdrl_spectrum1D_wave_scale_linear;

	//Get bin size
	int naxis1=cpl_image_get_size_x(sci_ima_data);
	double cdelt1 = uves_pfits_get_cdelt1(phead);
	double crval1 = uves_pfits_get_crval1(phead);
	double bin_size = cdelt1;
	uves_msg("bin_size=%g",bin_size);
	double AA2nm=0.1;
	double nm2AA=10.;
	double bin_size_scale_factor=bin_size*AA2nm*nm2AA;

	//double sci_wmin=cpl_table_get_column_min(spectra_tab,"wavelength");
	//double sci_wmax=cpl_table_get_column_max(spectra_tab,"wavelength");

    //AMO: create observed spectrum table
	cpl_table* spectra_tab=NULL;
	spectra_tab=cpl_table_new(naxis1);
	double* pdata = cpl_image_get_data_double_const(sci_ima_data);
	double* perrs = cpl_image_get_data_double_const(sci_ima_errs);
	cpl_table_wrap_double(spectra_tab, pdata, "flux");
	cpl_table_wrap_double(spectra_tab, perrs, "error");
	double* pwave = NULL;
	pwave = calloc(naxis1,sizeof(double));
	for(int i=0;i<naxis1;i++) {
		pwave[i]=crval1+i*cdelt1;
	}
	cpl_table_wrap_double(spectra_tab, pwave, "wavelength");

	double exptime = uves_pfits_get_exptime(rhead);
	double gain = uves_pfits_get_gain(rhead, chip);
    double airm = uves_pfits_get_airm_mean(phead);
    uves_msg("exptime = %g",exptime);
    uves_msg("gain = %g",gain);
    uves_msg("airm = %g",airm);
    uves_msg("bin_size_scale_factor = %g",bin_size_scale_factor);
    double factor=1./(gain*exptime*bin_size_scale_factor);
    //cpl_table_save(spectra_tab,NULL,NULL,"spectra_tab.fits",CPL_IO_DEFAULT);
    uves_msg("factor = %g",factor);
	hdrl_spectrum1D * obs_s1d =
			hdrl_spectrum1D_convert_from_table(spectra_tab, "flux",
					"wavelength", "error", NULL, scale);
	hdrl_spectrum1D * resp_s1d;
    cpl_table_dump_structure(response,stdout);
    if ( cpl_table_has_column(response,"response_smo_error") ) {
    	/* HDRL based instrument response */
       resp_s1d = hdrl_spectrum1D_convert_from_table(response, "FLUX_CONV",
				  "LAMBDA", "response_smo_error", "response_smo_bpm", scale);
    } else {
    	/* old UVES computed instrument response */
    	resp_s1d = hdrl_spectrum1D_convert_from_table(response, "FLUX_CONV",
    							"LAMBDA", NULL, NULL, scale);
    }

    double sci_wmin = cpl_array_get_min(hdrl_spectrum1D_get_wavelength(obs_s1d).wavelength);
    double sci_wmax = cpl_array_get_max(hdrl_spectrum1D_get_wavelength(obs_s1d).wavelength);

    hdrl_spectrum1D * ext_s1d =
				hdrl_spectrum1D_convert_from_table(atm_extinction, "LA_SILLA",
						"LAMBDA", NULL, NULL, scale);

    const hdrl_spectrum1D_wavelength spec_wav =
                        hdrl_spectrum1D_get_wavelength(obs_s1d);
    //Note: UVES spectra are already in Angstrom units!! 
    //hdrl_spectrum1D_wavelength_mult_scalar_linear(ext_s1d,nm2AA);
    hdrl_parameter *params = hdrl_spectrum1D_resample_interpolate_parameter_create(
        							hdrl_spectrum1D_interp_akima);
    hdrl_spectrum1D *ext_s1d_r = hdrl_spectrum1D_resample(ext_s1d, &spec_wav, params);
#if UVES_HDRL_USE_EXPERIMENTAL
	hdrl_spectrum1D_save(obs_s1d, "obs_s1d.fits");
    hdrl_spectrum1D_save(resp_s1d, "resp_s1d.fits");
    hdrl_spectrum1D_save(ext_s1d, "ext_s1d.fits");
    hdrl_spectrum1D_save(ext_s1d_r, "ext_s1d_r.fits");
#endif


    double resp_wmin = cpl_array_get_min(hdrl_spectrum1D_get_wavelength(resp_s1d).wavelength);
    double resp_wmax = cpl_array_get_max(hdrl_spectrum1D_get_wavelength(resp_s1d).wavelength);

    cpl_msg_warning("","%f %f", sci_wmin, sci_wmax);
    cpl_msg_warning("","%f %f", resp_wmin, resp_wmax);

    hdrl_spectrum1D* resp_s1d_resampled  = hdrl_spectrum1D_resample(resp_s1d, &spec_wav, params);
    /*
    hdrl_spectrum1D_resample_on_array(resp_s1d,
                           hdrl_spectrum1D_get_wavelength(obs_s1d).wavelength,
                                      hdrl_spectrum1D_resample_fit_parameter_create(3,100));
    */

    hdrl_spectrum1D* flux_s1d = hdrl_spectrum1D_mul_spectrum_create(obs_s1d, resp_s1d_resampled);
#if UVES_HDRL_USE_EXPERIMENTAL
    hdrl_spectrum1D_save(resp_s1d_resampled, "resp_s1d_resampled.fits");
    hdrl_spectrum1D_save(flux_s1d, "flux_s1d_0.fits");
#endif

    hdrl_spectrum1D_mul_scalar(flux_s1d,(hdrl_value){factor,0.});

#if UVES_HDRL_USE_EXPERIMENTAL
    hdrl_spectrum1D_save(flux_s1d, "flux_s1d_1.fits");
#endif

    double* pflux = cpl_image_get_data_double(hdrl_image_get_image(flux_s1d->flux));
    int sx=hdrl_image_get_size_x(flux_s1d->flux);
    double* pext = cpl_image_get_data_double(hdrl_image_get_image(ext_s1d_r->flux));
    for(int i=0;i<sx;i++) {
    	double exp=+0.4*airm*pext[i];
    	pflux[i] *= pow(10.,exp);
    }
    * fluxcal_sci_tab = hdrl_spectrum1D_convert_to_table(flux_s1d,
    		"flux", "wavelength", "flux_error", "flux_bpm");

    int nrow = cpl_table_get_nrow(*fluxcal_sci_tab);
    * fluxcal_ima_data = cpl_image_new(nrow,1,CPL_TYPE_DOUBLE);
    * fluxcal_ima_errs = cpl_image_new(nrow,1,CPL_TYPE_DOUBLE);

    pdata=cpl_image_get_data_double(*fluxcal_ima_data);
    perrs=cpl_image_get_data_double(*fluxcal_ima_errs);

    pflux = cpl_table_get_data_double(*fluxcal_sci_tab,"flux");
    double* pflux_error = cpl_table_get_data_double(*fluxcal_sci_tab,"flux_error");
    int* pflux_bpm = cpl_table_get_data_int(*fluxcal_sci_tab,"flux_bpm");
    cpl_mask* mdata = cpl_image_get_bpm(* fluxcal_ima_data);
    cpl_mask* merrs = cpl_image_get_bpm(* fluxcal_ima_errs);
    cpl_binary* pbpmd = cpl_mask_get_data(mdata);
    cpl_binary* pbpme = cpl_mask_get_data(merrs);
    /* Some points are flagged as bad pixels: we need to set some value in the image */
    for(int i=0;i<nrow;i++) {
    	if(pflux_bpm[i]>0) {
    		pbpmd[i]=CPL_BINARY_1;
    		pbpme[i]=CPL_BINARY_1;
    	} else {
    	    pdata[i]=pflux[i];
    	    perrs[i]=pflux_error[i];
    	}
    }

    int crpix1=1;
    crval1=pwave[0];
    cdelt1=pwave[1]-pwave[0];
    *lambda_start=crval1;
    *dlambda=cdelt1;
    cpl_propertylist* head = cpl_propertylist_duplicate(rhead);
    cpl_propertylist_append_int(head,"CRPIX1",crpix1);
    cpl_propertylist_append_double(head,"CRVAL1",crval1);
    cpl_propertylist_append_double(head,"CDELT1",cdelt1);

    const char* file;
#if UVES_HDRL_USE_EXPERIMENTAL
    file = uves_sprintf("spectrum_flux_ima_%s.fits",uves_chip_tostring_upper(chip));
    cpl_image_save(*fluxcal_ima_data, file, CPL_BPP_IEEE_FLOAT,head, CPL_IO_DEFAULT);
    file = uves_sprintf("spectrum_flux_err_%s.fits",uves_chip_tostring_upper(chip));
    cpl_image_save(*fluxcal_ima_errs, file, CPL_BPP_IEEE_FLOAT,head, CPL_IO_DEFAULT);
#endif

    uves_free_propertylist(&head);
#if UVES_HDRL_USE_EXPERIMENTAL
    hdrl_spectrum1D_save(flux_s1d, "flux_s1d_2.fits");
    file = uves_sprintf("spectrum_flux_%s.fits", uves_chip_tostring_upper(chip));
     cpl_table_save(*fluxcal_sci_tab,NULL,NULL,file,CPL_IO_DEFAULT);
#endif

    // SAVE RESULT
    hdrl_spectrum1D_delete(&obs_s1d);
    hdrl_spectrum1D_delete(&resp_s1d);
    hdrl_spectrum1D_delete(&ext_s1d);
    hdrl_spectrum1D_delete(&flux_s1d);

    cpl_table_unwrap(spectra_tab,"wavelength");
    cpl_table_unwrap(spectra_tab,"flux");
    cpl_table_unwrap(spectra_tab,"error");
    uves_free_table(&spectra_tab);
    cpl_free(pwave);

	uves_print_rec_status(0);
	return cpl_error_get_code();
}




const char * const uves_scired_desc_short = "Reduces a science frame";
const char * const uves_scired_desc =
"This recipe reduces a science frame (SCIENCE_BLUE or SCIENCE_RED, or\n"
"SCI_POINT_BLUE or SCI_POINT_RED, or \n"
"SCI_EXTND_BLUE or SCI_EXTND_RED or \n"
"SCI_SLICER_BLUE or SCI_SLICER_RED) using "
"a combination (depending on recipe parameters and provided input frames) of "
"the steps:\n"
" - bias subtraction,\n"
" - dark subtraction,\n"
" - background subtraction,\n"
" - extraction/cosmic ray removal,\n"
" - flat field correction,\n"
" - wavelength rebinning,\n"
" - sky subtraction,\n"
" - order merging,\n"
" - response correction (if response curve is provided).\n"
"\n"
"Additional input for this recipe are: \n"
"order table(s) for each chip, ORDER_TABLE_xxxx (where xxxx=BLUE, REDL, REDU),\n"
"line table(s) for each chip, LINE_TABLE_xxxx, a master bias frame,\n"
"MASTER_BIAS_xxxx, a master flat, MASTER_FLAT_xxxx, \n"
"optionally an instrument response table, INSTR_RESPONSE_FINE_xxx,\n"
"optionally an master response table, MASTER_RESPONSE_xxx, and\n"
"optionally a table describing the atmospheric extinction,\n"
"EXTCOEFF_TABLE. \n"
"\n"
"For each chip (xxxx = BLUE, REDL, REDU) the recipe produces a combination of "
"the products:\n"
" 'RED_SCIENCE_xxxx'        Reduced science spectrum\n"
" 'MERGED_SCIENCE_xxxx'     Merged spectrum, no sky subtraction\n"
" 'WCALIB_SCIENCE_xxxx'     Extracted, wavelength calibrated frame in\n"
"                           (wavelength, order) space\n"
" 'WCALIB_FF_SCIENCE_xxxx'  Extracted, flat-fielded, wave.cal. frame in\n"
"                           (wavelength, order) space\n"
"                           (Only if flatfielding done)\n"
" 'WCALIB_FLAT_OBJ_xxxx'    Extracted, wavelength calibrated flat field\n"
"                           in (wavelength, order) space\n"
"                           (Only if flatfielding done)\n"
" 'ERRORBAR_SCIENCE_xxxx'   Error bars of 'RED_SCIENCE_xxxx'\n"
" 'VARIANCE_SCIENCE_xxxx'   Variance of extracted, flatfielded object in\n"
"                           (pixel, order) space\n"
" 'ORDER_TRACE_xxxx'        Table describing the spatial profile\n"
" 'FLUXCAL_SCIENCE_xxxx'    Flux-calibrated science spectrum\n"
" 'FLUXCAL_ERROR_xxxx'      Error bars of 'FLUXCAL_SCIENCE_xxxx'\n"
" 'BKG_SCI_xxxx'            The subtracted background image\n"
" 'CRMASK_xxxx'             List of cosmic ray hits\n"
" 'MERGED_SKY_xxxx'         The merged sky spectrum\n"
" 'EXT_2D_SCIENCE_xxxx'     The 2d extracted spectrum\n"
" 'FF2D_SCIENCE_xxxx'       The 2d extracted, flat-fielded spectrum\n"
" 'WCAL2D_SCIENCE_xxxx'     The 2d extracted, flat-fielded, wave.cal. spectrum\n"
" 'MER2D_SCIENCE_xxxx'      The 2d reduced, flux-calibrated (if possible) \n"
"                           science spectrum\n";





static uves_propertylist*
uves_paste_wave_accuracy(const uves_propertylist* header_from)
{
  uves_propertylist* header_add=NULL;




  const char* key_comm=NULL;
  char key_name_i[40];
  char key_name_o[40];
  uves_msg("paste wave accuracy");
  header_add=uves_propertylist_new();

  sprintf(key_name_o,"CUNIT1");
  key_comm="Wavelength units";
  uves_propertylist_append_c_string(header_add,key_name_o,"Angstrom",key_comm);

  sprintf(key_name_i,"ESO QC LINE RESIDRMS WLU");
  sprintf(key_name_o,"LAMRMS");
  key_comm="RMS of wavelength solution [CUNIT1]";

  if(uves_propertylist_has(header_from,key_name_i)) {
    double waverms=uves_propertylist_get_double(header_from,key_name_i);
    uves_propertylist_append_c_double(header_add,key_name_o,waverms,key_comm);

  }


  sprintf(key_name_i,"ESO QC NLINSOL");
  sprintf(key_name_o,"LAMNLIN");
  key_comm="No. of lines used in wavelength solution";

  if(uves_propertylist_has(header_from,key_name_i)) {
    double wavenlin=uves_propertylist_get_int(header_from,key_name_i);
    uves_propertylist_append_c_int(header_add,key_name_o,wavenlin,key_comm);

  }


  sprintf(key_name_i,"ESO QC LINE WAVEERR");
  sprintf(key_name_o,"CRDER1");
  key_comm="Wavelength uncertainty [CUNIT1]";
  if(uves_propertylist_has(header_from,key_name_i)) {
    double waveerr=uves_propertylist_get_double(header_from,key_name_i);
    uves_propertylist_append_c_double(header_add,key_name_o,waveerr,key_comm);

  }


  sprintf(key_name_i,"ESO QC LINE SYSERR");
  sprintf(key_name_o,"CSYER1");
  key_comm="Typical systematic wavelength error [CUNIT1]";
  if(uves_propertylist_has(header_from,key_name_i)) {
    double wavesys=uves_propertylist_get_double(header_from,key_name_i);
    uves_propertylist_append_c_double(header_add,key_name_o,wavesys,key_comm);

  }

  return header_add;

}




/*----------------------------------------------------------------------------*/
/**
  @brief    Setup the recipe options    
  @param    parameters        the parameterlist to fill
  @param    recipe_id         name of calling recipe
  @return   0 if everything is ok
 */
/*----------------------------------------------------------------------------*/
int uves_scired_define_parameters_body(cpl_parameterlist *parameters,
                       const char *recipe_id)
{

    /*****************
     *    General    *
     *****************/
    if (uves_define_global_parameters(parameters) != CPL_ERROR_NONE)
        {
            return -1;
        }

    /**************************************
     *  detector's trap correction        *
     **************************************/
 
    if (uves_corr_traps_define_parameters(parameters,recipe_id) 
        != CPL_ERROR_NONE)
        {
            return -1;
        }

    /*******************
     *  Reduce.        *
     ******************/
    if (uves_propagate_parameters_step(UVES_REDUCE_ID, parameters,
                                       recipe_id, NULL) != 0)
        {
            return -1;
        }
    
    return (cpl_error_get_code() != CPL_ERROR_NONE);
}


const char*
uves_get_pro_catg_special(bool extract_is_2d, merge_method m_method) {
   const char* result=NULL;
   if(extract_is_2d && m_method == MERGE_NOAPPEND) {
      result="";
   } else if (!extract_is_2d && 
              m_method == MERGE_NOAPPEND) {
      result="_NONMERGED";
   } else {
      result="";
   }

   return result;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Change tag of RAW frames to NONE
  @param    frames         frame set to change
  @return   NULL terminated array of pointers to the frames that were changed
 */
/*----------------------------------------------------------------------------*/
static cpl_frame **
set_all_raw_none(cpl_frameset *frames)
{
    cpl_frame **result = NULL;
    cpl_frame *f;
    int i=0;

    result = cpl_calloc( cpl_frameset_get_size(frames) + 1,
                         sizeof(*result) );

    int nframes = cpl_frameset_get_size(frames);
    for (int k = 0; k < nframes; k++) {
        f = cpl_frameset_get_position(frames, k);
        if (cpl_frame_get_group(f) == CPL_FRAME_GROUP_RAW)
        {
            // Change + remember this frame
            cpl_frame_set_group(f, CPL_FRAME_GROUP_NONE);
            result[i] = f;
            i++;
        }

    }

    /* 'result' is now a NULL-terminated array of the frames that were changed */

    return result;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Reduce one chip of a UVES science frame
  @param    raw_image         The raw image
  @param    raw_header        FITS header of raw image
  @param    rotated_header    Header describing the geometry of the raw image after
                              rotation and removal of pre- and overscan areas
  @param    master_bias       The master bias image for this chip, or NULL
  @param    master_dark       The master bias image for this chip, or NULL
  @param    mdark_header      FITS header of master dark frame
  @param    master_flat       The master flat image for this chip, or NULL
  @param    mflat_header      FITS header of master flat frame
  @param    mdark_header      FITS header of master dark frame
  @param    ordertable        Order table describing the order locations on the raw image
  @param    order_locations   The polynomial describing the order positions
  @param    linetable         Length 3 array of linetables for sky, object, sky.
  @param    linetable_header  Length 3 array of linetable headers for sky, object, sky.
  @param    response_curve    The response curve (image of height 1) used for flux correction
                              If non-NULL this is used for flux correction
  @param    master_response   response curve as a table. If response_curve is NULL and this
                              is non-NULL, it is used for flux correction
  @param    response_curve_header  Header describing the geometry of the @em response_curve.
  @param    atm_extinction    Table of atmospheric extinction coefficients. 
  @param    dispersion_relation  Length 3 array of dispersion relations for sky, object, sky.
  @param    chip              CCD chip
  @param    debug_mode             If set to true, intermediate results are saved to the 
                              current directory
  @param    parameters        The recipe parameter list containing parameters
                              for background subtraction, flat-fielding, extraction, rebinning
  @param    recipe_id         name of calling recipe
  @param    x2d               (output) In 2d extraction mode, the extracted spectrum
  @param    x2d_header        (output) In 2d extraction mode, header of extracted spectrum
  @param    fx2d              (output) In 2d extraction mode, the flat-fielded, 
                              extracted spectrum
  @param    background        (output) The background that was subtracted from the raw image
  @param    flatfielded_variance (output) Variance of extracted, flat-fielded spectrum
  @param    flatfielded_variance_header (output) Header of @em flatfielded_variance
  @param    resampled_science (output) The extracted, rebinned spectrum. If flat-field method
                              is 'extract', this spectrum was @em not flat-fielded.
  @param    resampled_mf      (output) As @em resampled_science, but for the master flat-field
  @param    rebinned_science  (output) The extracted, flat-fielded, rebinned spectrum
  @param    rebinned_header   (output) Header of @em rebinned_science
  @param    merged_sky        (output) The extracted, rebinned, merged sky spectrum
  @param    merged_science    (output) The extracted, rebinned, merged object spectrum
  @param    merged_header     (output) Header of @em merged_science, also applies to @em
                              @em reduced_science and @em reduced_science_error
  @param    reduced_science   (output) The extracted, flat-fielded, rebinned, merged,
                              sky-subtracted spectrum
  @param    reduced_science_error  (output) The error (1 sigma) of @em reduced_science
  @param    cosmic_mask       (output) In optimal extraction mode, the list of hot pixels
  @param    fluxcal_science   (output) As @em reduced_science but also response corrected
                              (if response curve was provided)
  @param    fluxcal_error     (output) Error (1 sigma) of @em fluxcal_science
                              (if response curve was provided)
  @param    fluxcal_header    (output) Header describing the geometry of @em fluxcal_science
                              and @em fluxcal_error
  @param    info_tbl          (output) optimal extraction QC parameters
  @param    extraction_slit   (output) extraction slit length used
  @param    order_trace       (output) In optimal extraction mode, table describing the
                              measured spatial profile
                               
                                    
  @return   CPL_ERROR_NONE iff okay

  This function does a science reduction (see @c uves_reduce) and, if a response curve
  if provided, corrects for the instrument response (by moving the science spectrum
  to the top of the atmosphere (see @em uves_normalize_spectrum) and multiplying be
  the response function).

 */
/*----------------------------------------------------------------------------*/

static cpl_error_code
uves_scired_process_chip(const cpl_image *raw_image, 
                         const uves_propertylist *raw_header,
                         const uves_propertylist *rotated_header,
                         const cpl_image *master_bias,
                         const uves_propertylist *mbias_header,
                         const cpl_image *master_dark, 
                         const uves_propertylist *mdark_header,
                         const cpl_image *master_flat, 
                         const uves_propertylist *mflat_header,
                         const cpl_table *ordertable, 
                         const polynomial *order_locations,
                         const cpl_table *linetable[3], 
                         const uves_propertylist *linetable_header[3], 
                         const polynomial *dispersion_relation[3],
                         const cpl_image *response_curve, 
             const cpl_table *master_response,
                         const uves_propertylist *response_curve_header,
                         const cpl_table *atm_extinction,
                         enum uves_chip chip,
                         /* General */
                         bool   debug_mode,
                         /* Backsub */
                         /* Flat fielding */
                         /* Extraction */
                         /* Rebinning  */
                         const cpl_parameterlist *parameters,
             const char *recipe_id,
                         /* Output     */
                         cpl_image **x2d, uves_propertylist **x2d_header,
                         cpl_image **fx2d,
                         cpl_image **background,
                         cpl_image **flatfielded_variance,
                         uves_propertylist **flatfielded_variance_header,
                         cpl_image **resampled_science,
                         cpl_image **resampled_mf,
                         cpl_image **rebinned_science, 
                         cpl_image **rebinned_noise,
                         uves_propertylist **rebinned_header,
                         cpl_image **merged_sky,
                         cpl_image **merged_science, 
                         uves_propertylist **merged_header,
                         cpl_image **reduced_science,
                         cpl_image **reduced_science_error,
                         cpl_table **cosmic_mask,
                         cpl_image **wave_map,
                         cpl_table **fluxcal_science_table,
						 cpl_image **fluxcal_science,
						 cpl_image **fluxcal_science_error,
                         uves_propertylist **fluxcal_header,
                         cpl_table **info_tbl,
             double *extraction_slit,
                         cpl_table **order_trace)
{

	cpl_image *merged_noise   = NULL;

	cpl_image *reduced_rebinned = NULL;
	cpl_image *reduced_rebinned_noise = NULL;

	cpl_table *response_table = NULL;

	/* Do the science reduction. Produces wave.cal. spectra. */
	uves_msg("Reducing science object");

	check( uves_reduce(raw_image,
			raw_header,
			rotated_header,
			master_bias,
			mbias_header,
			master_dark,
			mdark_header,
			master_flat,
			mflat_header,
			ordertable,
			order_locations,
			linetable,
			linetable_header,
			dispersion_relation,
			chip,
			debug_mode,
			parameters,
			recipe_id,
			"",
			/* Output */
			x2d,
			x2d_header,
			fx2d,
			cosmic_mask,
			wave_map,
			background,
			flatfielded_variance,
			flatfielded_variance_header,
			resampled_science,
			resampled_mf,
			merged_sky,
			rebinned_science,
			rebinned_noise,
			rebinned_header,
			merged_science,
			&merged_noise,
			merged_header,
			&reduced_rebinned,
			&reduced_rebinned_noise,
			reduced_science,
			reduced_science_error,
			info_tbl,
			extraction_slit,
			order_trace),
			"Could not reduce frame");

	/* Plot middle row */
	check( uves_plot_image_rows(*reduced_science,
			1 + cpl_image_get_size_y(*reduced_science)/2,
			1 + cpl_image_get_size_y(*reduced_science)/2, 1,
			"Wavelength (arbitrary units)", "Relative flux",
			"Reduced science spectrum"),
			"Plotting failed");


	/*
	 * Flux calibrate the reduced spectrum
	 * (which is an image of height 1, or more if extract.method=2d)
	 */
	double median_flux=0;
	if (response_curve != NULL || master_response != NULL)
	{
		double lambda_start;
		double dlambda;
		int bin;

		/* Number of spatial traces (> 1 for 2d extraction) */
		int n_traces = cpl_image_get_size_y(*reduced_science);

		uves_msg("Flux calibrating spectrum");

		/* We cannot be certain that the formats (wavelength start, bin width)
               of the science spectrum and the response curve are identical.
               Therefore we interpolate the response curve at the wavelengths 
               defined by the bins of the science spectrum. */



		/* If the response curve is an image, convert to table.
           This is needed for the interpolation */
		if (response_curve != NULL) {


			uves_msg("use instrument response table");
			response_table = cpl_table_new(cpl_image_get_size_x(response_curve));
			cpl_table_new_column(response_table, "LAMBDA", CPL_TYPE_DOUBLE);
			cpl_table_new_column(response_table, "FLUX_CONV", CPL_TYPE_DOUBLE);

			check( lambda_start = uves_pfits_get_crval1(response_curve_header),
					"Error reading response curve start wavelength from header");

			check( dlambda = uves_pfits_get_cdelt1(response_curve_header),
					"Error reading bin width from header");

			for (bin = 1; bin <= cpl_image_get_size_x(response_curve); bin++) {
				double lambda;
				double response;
				int pis_rejected;

				lambda = lambda_start + (bin-1) * dlambda;

				check( response = cpl_image_get(response_curve, bin, 1, &pis_rejected),
						"Error reading response curve bin = %d", bin);

				check((cpl_table_set_double(response_table, "LAMBDA", bin - 1, lambda),
						cpl_table_set_double(response_table, "FLUX_CONV", bin - 1, response)),
						"Error updating response table at row %d", bin - 1);
			}


		}
		else {
			uves_msg("use master response table");
			response_table = cpl_table_duplicate( master_response );
		} /* Response table created */


		{
			uves_msg("HDRL based flux calibration");
			uves_flux_calibrate_spectra(*reduced_science,*reduced_science_error,
					raw_header, *merged_header,response_table,atm_extinction,chip,
					fluxcal_science_table,fluxcal_science,fluxcal_science_error,
					&lambda_start,&dlambda);
			cpl_table_dump_structure(response_table,stdout);
			median_flux = cpl_table_get_column_median(response_table,"FLUX_CONV");
			const char* units;

			if(median_flux > 1.e-5) {
				/* we know that HDRL based response with STD star catalog gives
				 * values of the order of 10^-14---10^-13. OLD Catalog give
				 * response values of the order of 100-1000. 1e-5 lies
				 * logaritmically in the middle
				 */
				units = "10^-16 erg/cm^2/Angstrom/s";
			} else {
				units = "erg/cm^2/Angstrom/s";
			}
			*fluxcal_header = uves_initialize_image_header("AWAV", " ",
								"Angstrom", NULL,units,1,
								lambda_start, 1.0,1.0, 1.0, dlambda, 1.0);

		}


		/*
		 * Correct for exposure time, gain, binning, atm. ext.
		 *

            check( *fluxcal_science = uves_normalize_spectrum(*reduced_science,
		 *reduced_science_error,
		 *merged_header,
                                                              raw_header,
                                                              n_traces,
                                                              chip,
                                                              atm_extinction,
                                                              true,    // Divide by binning?
                                                              fluxcal_error), 
                   "Error normalizing reduced spectrum");
		 */

		/*
		 * Flux calibrate reduced spectrum
		 *  flux := flux * response
		 */

		uves_msg("Multiplying by response function");
		uves_print_rec_status(0);
		{
			/*
			int nbins   = cpl_image_get_size_x(*fluxcal_science);
			int ntraces = cpl_image_get_size_y(*fluxcal_science);
			double *fluxcal_science_data  = cpl_image_get_data_double(*fluxcal_science);
			double *fluxcal_science_noise = cpl_image_get_data_double(*fluxcal_error);

			check( lambda_start = uves_pfits_get_crval1(*merged_header),
					"Error reading start wavelength from reduced science header");

			check( dlambda = uves_pfits_get_cdelt1(*merged_header),
					"Error reading bin width from header");

			for (bin = 1; bin <= nbins; bin++)
			{
				double lambda;
				double response;
				int trace; // Spatial traces (for 2d extracted spectra)
				int istart = 0;

				lambda = lambda_start + (bin-1) * dlambda;

				check( response =
						uves_spline_hermite_table(lambda, response_table,
								"LAMBDA", "FLUX_CONV", &istart),
								"Error interpolating response curve at lambda = %f wlu", lambda);

				for (trace = 1; trace <= ntraces; trace++)
				{
					// Don't check for bad pixels here, also correct those.
					// The fluxcal image has the same bad pixels as the reduced_science
					// image

					fluxcal_science_data [(bin-1) + (trace-1)*nbins] *= response;
					fluxcal_science_noise[(bin-1) + (trace-1)*nbins] *= response;

					// Do not propagate the error of the response
					//   curve which is negligibly small (and unknown at this point!).

				}
			}

			uves_print_rec_status(1);
			// Plot middle row
			check( uves_plot_image_rows(*fluxcal_science,
					1 + cpl_image_get_size_y(*fluxcal_science)/2,
					1 + cpl_image_get_size_y(*fluxcal_science)/2, 1,
					"Wavelength (arbitrary units)",
					"Flux (10^-16 erg/cm^2/Angstrom/s)",
					"Flux calibrated science spectrum"),
					"Plotting failed");

			check( *fluxcal_header = uves_initialize_image_header("AWAV", " ",
					"Angstrom", NULL,
					"10^-16 erg/cm^2/Angstrom/s",
					1,
					lambda_start, 1.0,
					1.0, 1.0,
					dlambda, 1.0),
					"Error initializing flux calibrated spectrum header");
					*/
		} /// Done multiplying by response curve
		uves_print_rec_status(2);

	}
	else
	{
		uves_msg("Skipping absolute flux calibration");
	}

	cleanup:
	uves_print_rec_status(3);
	uves_free_image(&merged_noise);
	uves_free_image(&reduced_rebinned_noise);
	uves_free_image(&reduced_rebinned);
	uves_free_table(&response_table);

	if (cpl_error_get_code() != CPL_ERROR_NONE)
	{
	}

	return cpl_error_get_code();
}


/*----------------------------------------------------------------------------*/
/**
  @brief    Get the command line options and execute the data reduction
  @param    parameters  the parameters list
  @param    frames      the frames list
  @param    recipe_id   the recipe name (will be written to FITS headers)
  @param    starttime   time when calling recipe started
  @return   CPL_ERROR_NONE if everything is ok
 */
/*----------------------------------------------------------------------------*/
void uves_reduce_scired(cpl_frameset *frames, const cpl_parameterlist *parameters, 
		const char *recipe_id, const char *starttime)
{
	/* Recipe parameters */
	bool debug_mode;
	bool CLEAN_TRAPS;
	bool extract_is_2d = false;     /* Are we doing a 2d reduction? */

	/* Input, raw */
	cpl_image        *raw_image[2]      = {NULL, NULL};
	uves_propertylist *raw_header[2]     = {NULL, NULL};
	uves_propertylist *rotated_header[2] = {NULL, NULL};

	/* Input, calib */
	cpl_image        *master_bias        = NULL;
	uves_propertylist *master_bias_header = NULL;

	cpl_image        *master_flat        = NULL;
	uves_propertylist *master_flat_header = NULL;

	cpl_image        *master_dark        = NULL;
	uves_propertylist *master_dark_header = NULL;

	cpl_table        *ordertable       = NULL;
	uves_propertylist *ordertable_header= NULL;
	polynomial       *order_locations  = NULL;
	cpl_table        *traces           = NULL;

	/* Line tables for sky, object, sky (UVES specific) */
	const cpl_table        *linetable[3]           = {NULL, NULL, NULL};
	const uves_propertylist *linetable_header[3]    = {NULL, NULL, NULL};
	const polynomial       *dispersion_relation[3] = {NULL, NULL, NULL};

	cpl_image        *response_curve        = NULL;
	uves_propertylist *response_curve_header = NULL;
	cpl_table        *master_response       = NULL;

	cpl_table        *atm_extinction        = NULL;

	/* Output */
	/*  BKG_SCI           */
	cpl_image        *background            = NULL;

	/*  VARIANCE_SCIENCE                 */
	cpl_image        *flatfielded_variance  = NULL;
	uves_propertylist *flatfielded_variance_header = NULL;

	/*  WCALIB_SCIENCE    */
	cpl_image        *resampled_science     = NULL;     /* extracted -> rebinned */
	/*  WCALIB_FLAT_OBJ   */
	cpl_image        *resampled_mf          = NULL;
	/*  WCALIB_FF_SCIENCE */
	cpl_image        *rebinned_science      = NULL;     /* extracted -> ff -> rebinned */
	cpl_image        *rebinned_science_error = NULL;
	uves_propertylist *rebinned_header       = NULL;

	/*  MERGED_SKY        */
	cpl_image        *merged_sky            = NULL;

	/*  MERGED_SCIENCE / MER2D_SCIENCE   */
	/*  RED_SCIENCE                      */
	/*  ERRORBAR_SCIENCE                 */
	cpl_image        *merged_science        = NULL;
	uves_propertylist *merged_header         = NULL;
	cpl_image        *reduced_science       = NULL;
	cpl_image        *reduced_science_error = NULL;


	/*  FLUXCAL_SCIENCE / FLUXCAL_ERROR */
	cpl_table        *fluxcal_science_table       = NULL;
	cpl_image        *fluxcal_science         = NULL;
	cpl_image        *fluxcal_error         = NULL;
	uves_propertylist *fluxcal_header       = NULL;

	/*  ORDER_TRACE       */
	cpl_table         *order_trace        = NULL;
	uves_propertylist *order_trace_header = NULL;


	/* EXT_2D_SCIENCE */
	cpl_image        *x2d        = NULL;
	uves_propertylist *x2d_header = NULL;
	/* FF2D_SCIENCE */
	cpl_image        *fx2d       = NULL;

	/*  CRMASK            */
	cpl_table        *cosmic_mask           = NULL;
	uves_propertylist *cosmic_mask_header    = NULL;

	/* QC */
	cpl_table* qclog[2] = {NULL, NULL};
	cpl_table *qclog_tflat = NULL;

	/* Local variables */
	const char *raw_filename = "";
	const char *atm_ext_filename = "";
	const char *sci_type = "";
	cpl_frame **raw_frames = NULL;  /* Array of cpl_frame pointers */
	char *product_tag = NULL;
	char *product_filename = NULL;
	char *context = NULL;
	double extraction_slit;

	bool blue  = false;
	enum uves_chip chip;
	int binx = 0;
	int biny = 0;

	cpl_table* info_tbl = NULL;
	const char* PROCESS_CHIP=NULL;
	bool red_ccd_is_new=0;
	merge_method m_method;
	const char* catg_is_noappend=NULL;
	cpl_image* wave_map=NULL;
	uves_propertylist* wave_map_header=NULL;
	uves_propertylist* wave_acc_header=NULL;
	char extname[80];
	uves_propertylist* table_header=NULL;
    double median_flux=0;
	/* Read recipe parameters */
	{
		const char *ex_method = "";

		/* General */
		check( uves_get_parameter(parameters, NULL, "uves", "debug", CPL_TYPE_BOOL, &debug_mode),
				"Could not read parameter");



		check( uves_get_parameter(parameters, NULL, "uves", "debug", CPL_TYPE_BOOL, &debug_mode),
				"Could not read parameter");



		check( uves_get_parameter(parameters, NULL, "uves", "process_chip", CPL_TYPE_STRING, &PROCESS_CHIP),
				"Could not read parameter");
		uves_string_toupper((char*)PROCESS_CHIP);


		check( uves_get_parameter(parameters,NULL,recipe_id, "clean_traps", CPL_TYPE_BOOL, &CLEAN_TRAPS),
				"Could not read parameter");



		/* Reduction method */
		context = uves_sprintf("%s.%s.%s", recipe_id, UVES_REDUCE_ID, UVES_EXTRACT_ID);

		check( uves_get_parameter(parameters, NULL,
				context, "method",
				CPL_TYPE_STRING, &ex_method),
				"Could not read parameter");

		extract_is_2d = (strcmp(ex_method, "2d") == 0);

		/* Load raw image and header, and identify input frame as red or blue */
		check( uves_load_science(frames, &raw_filename, raw_image, raw_header, rotated_header,
				&blue, &sci_type),
				"Error loading raw frame");

		if ((strcmp(sci_type, "SCI_SLICER") == 0 ||
				strcmp(sci_type, "SCI_EXTND" ) == 0) &&
				strcmp(ex_method, "optimal") == 0)
		{
			uves_msg_warning("Going to optimally extract an extended object (%s). "
					"This may not work because the sky cannot be "
					"reliably determined",
					sci_type);
		}
	}

	/* Load atmospheric extinction table if present */
	if (cpl_frameset_find(frames, UVES_EXTCOEFF_TABLE) != NULL)
	{
		check( uves_load_atmo_ext(frames, &atm_ext_filename, &atm_extinction),
				"Error loading atm. extinction coefficients");

		uves_msg_low("Using atmospheric extinction table in '%s'", atm_ext_filename);
	}
	else
	{
		uves_msg_low("No atmospheric extinction table. Flux calibration not done");
	}

	check( m_method = uves_get_merge_method(parameters, recipe_id, "reduce"),
			"Could not get merging method");

	/* Adjust parameters according to binning
	 * (note that x- and y-directions are swapped later by uves_crop_and_rotate())
	 */
	check (binx = uves_pfits_get_binx(raw_header[0]),
			"Could not read x binning factor from input header");
	check (biny = uves_pfits_get_biny(raw_header[0]),
			"Could not read y binning factor from input header");

	check_nomsg(red_ccd_is_new=uves_ccd_is_new(raw_header[0]));
	/* Loop over one or two chips, over traces and
       over extraction windows */
	for (chip = uves_chip_get_first(blue);
			chip != UVES_CHIP_INVALID;
			chip = uves_chip_get_next(chip))
	{



		if(strcmp(PROCESS_CHIP,"REDU") == 0) {
			chip = uves_chip_get_next(chip);
		}
		table_header=uves_propertylist_new();
		cpl_frame *mflat_frame = NULL;
		const char *ordertable_filename = "";
		const char *linetable_filename = "";
		const char *master_bias_filename = "";
		const char *master_dark_filename = "";
		const char *master_flat_filename = "";
		const char *response_curve_filename = "";
		const char *chip_name = "";
		/* const char *drs_filename        = "";    not used */
		/* Do this to skip REDL chip: chip = uves_chip_get_next(chip); */
		int raw_index = uves_chip_get_index(chip);
		int tracerow;                      /* Index of table row */

		uves_msg("Processing %s chip in '%s'",
				uves_chip_tostring_upper(chip), raw_filename);

		check_nomsg( chip_name = uves_pfits_get_chipid(raw_header[raw_index], chip));

		uves_msg_debug("Binning = %dx%d", binx, biny);


		/* Load master bias, set pointer to NULL if not present */
		uves_free_image(&master_bias);
		uves_free_propertylist(&master_bias_header);
		if (cpl_frameset_find(frames, UVES_MASTER_BIAS(chip)) != NULL)
		{
			uves_free_image(&master_bias);
			uves_free_propertylist(&master_bias_header);

			check( uves_load_mbias(frames, chip_name, &master_bias_filename,
					&master_bias, &master_bias_header,
					chip),
					"Error loading master bias");

			uves_msg_low("Using master bias in '%s'", master_bias_filename);
		}
		else
		{
			uves_msg_low("No master bias in SOF. Bias subtraction not done");
		}

		/* Load master dark, set pointer to NULL if not present */
		uves_free_image(&master_dark);
		uves_free_propertylist(&master_dark_header);
		if (cpl_frameset_find(frames, UVES_MASTER_DARK(chip))  != NULL ||
				cpl_frameset_find(frames, UVES_MASTER_PDARK(chip)) != NULL)

		{
			check( uves_load_mdark(frames, chip_name, &master_dark_filename,
					&master_dark, &master_dark_header, chip),
					"Error loading master dark");

			uves_msg_low("Using master dark in '%s'", master_dark_filename);
		}
		else
		{
			uves_msg_low("No master dark in SOF. Dark subtraction not done");
		}

		/* Load master flat */
		uves_free_image(&master_flat);
		uves_free_propertylist(&master_flat_header);
		check( uves_load_mflat(frames, chip_name, &master_flat_filename, &master_flat,
				&master_flat_header, chip, &mflat_frame),
				"Error loading master flat");

		uves_msg_low("Using master flat in '%s'", master_flat_filename);


		/* Load the order table for this chip */
		uves_free_table       (&ordertable);
		uves_free_propertylist(&ordertable_header);
		uves_polynomial_delete(&order_locations);
		uves_free_table       (&traces);

		check( uves_load_ordertable(frames,
				false,  /* FLAMES? */
						chip_name,
						&ordertable_filename,
						&ordertable,
						&ordertable_header,
						NULL,
						&order_locations,
						&traces,
						NULL, NULL,
						NULL, NULL, /* fibre_pos,fibre_mask */
						chip, false),
				"Could not load order table");
		uves_msg_low("Using order table in '%s'", ordertable_filename);

		/* Load response curve, if present.
               Only if atm. extinction table was present. */
		if (atm_extinction != NULL)
		{
			if (cpl_frameset_find(frames, UVES_INSTR_RESPONSE(chip)) != NULL ||
					cpl_frameset_find(frames, UVES_INSTR_RESPONSE_FINE(chip)) != NULL ||
					cpl_frameset_find(frames, UVES_MASTER_RESPONSE(chip)) != NULL)
			{
				uves_free_image(&response_curve);
				uves_free_table(&master_response);
				uves_free_propertylist(&response_curve_header);
				check( uves_load_response_curve(frames, chip_name,
						&response_curve_filename,
						&response_curve,
						&master_response,
						&response_curve_header,
						chip),
						"Error loading response curve");

				uves_msg_low("Using %sresponse curve in '%s'",
						master_response != NULL ? "master " : "",
								response_curve_filename);
				median_flux = cpl_table_get_column_median(master_response,"FLUX_CONV");
			}
			else
			{
				uves_msg_low("No response curve in SOF. "
						"Flux calibration not done");
				uves_free_image(&response_curve);
				uves_free_table(&master_response);
				uves_free_propertylist(&response_curve_header);
			}
		}
		else
		{
			uves_msg_debug("There is no atmospheric extinction table. "
					"Do not look for response curve");
		}

		/* Loop over all traces (1 trace for UVES) */
		for(tracerow = 0; tracerow < cpl_table_get_nrow(traces); tracerow++)
		{
			double trace_offset;
			int trace_number;
			int trace_enabled;
			int badpixels_cleaned;
			trace_offset  = cpl_table_get_double(traces, "Offset"    , tracerow, NULL);
			trace_number  = cpl_table_get_int   (traces, "TraceID"   , tracerow, NULL);
			trace_enabled = cpl_table_get_int   (traces, "Tracemask" , tracerow, NULL);

			if (trace_enabled != 0)
			{
				int window;          /* window number */

				if (cpl_table_get_nrow(traces) > 1) {
					uves_msg("Processing trace %d", trace_number);
				}

				/* This is UVES specific. Load linetable for the
                               two sky windows (number 1, 3) and for the object
                               window (number 2) */

				for (window = 1; window <= 3; window ++) {
					uves_free_table_const ( &(linetable[window-1]) );
					uves_free_propertylist_const( &(linetable_header[window-1]) );
					uves_polynomial_delete_const( &(dispersion_relation[window-1]) );
					check( uves_load_linetable_const(frames,
							false,  /* FLAMES? */
									chip_name,
									order_locations,
									cpl_table_get_column_min(
											ordertable, "Order"),
											cpl_table_get_column_max(
													ordertable, "Order"),
													&linetable_filename,
													&(linetable          [window-1]),
													&(linetable_header   [window-1]),
													&(dispersion_relation[window-1]),
													NULL,
													chip,
													trace_number,
													window),
							"Could not load line table, window #%d", window);

					uves_msg_low("Using line table(s) in '%s'", linetable_filename);

				}
				uves_propertylist* plist=uves_propertylist_load(linetable_filename,0);
				uves_free_propertylist(&wave_acc_header);
				wave_acc_header=uves_paste_wave_accuracy(plist);
				uves_free_propertylist(&plist);
				/* end, UVES specific */

				/* Do the science reduction + flux calibration */
				uves_free_image(&x2d);
				uves_free_image(&fx2d);
				uves_free_propertylist(&x2d_header);
				uves_free_image(&background);
				uves_free_image(&flatfielded_variance);
				uves_free_propertylist(&flatfielded_variance_header);
				uves_free_image(&resampled_science);
				uves_free_image(&resampled_mf);
				uves_free_image(&rebinned_science);
				uves_free_image(&rebinned_science_error);
				uves_free_propertylist(&rebinned_header);
				uves_free_image(&merged_sky);
				uves_free_image(&merged_science);
				uves_free_propertylist(&merged_header);
				uves_free_image(&reduced_science);
				uves_free_image(&reduced_science_error);
				uves_free_table(&cosmic_mask);
				uves_free_table(&fluxcal_science_table);
				uves_free_image(&fluxcal_science);
				uves_free_image(&fluxcal_error);

				uves_free_propertylist(&fluxcal_header);
				uves_free_table(&info_tbl);
				uves_free_table(&order_trace);

				if(CLEAN_TRAPS) {

					check( badpixels_cleaned =
							uves_correct_badpix_all(raw_image[raw_index],
									raw_header[raw_index],
									chip, binx, biny,
									false,red_ccd_is_new),
									"Error replacing bad pixels");

					uves_msg("%d bad pixels replaced",
							badpixels_cleaned);
				}

				check( uves_scired_process_chip(
						raw_image[raw_index],
						raw_header[raw_index],           /* Raw         */
						rotated_header[raw_index],
						master_bias,           /* Calibration */
						master_bias_header,
						master_dark,
						master_dark_header,
						master_flat,
						master_flat_header,
						ordertable,
						order_locations,
						linetable,
						linetable_header,
						dispersion_relation,
						response_curve,
						master_response,
						response_curve_header,
						atm_extinction,
						chip,
						debug_mode,
						parameters,
						recipe_id,
						&x2d,
						&x2d_header,
						&fx2d,            /* Products      */
						&background,
						&flatfielded_variance,
						&flatfielded_variance_header,
						&resampled_science,
						&resampled_mf,
						&rebinned_science,
						&rebinned_science_error,
						&rebinned_header,
						&merged_sky,
						&merged_science,
						&merged_header,
						&reduced_science,
						&reduced_science_error,
						&cosmic_mask,
						&wave_map,
						&fluxcal_science_table,
						&fluxcal_science,
						&fluxcal_error,
						&fluxcal_header,
						&info_tbl,
						&extraction_slit,
						&order_trace),
						"Science reduction failed");

				if (!extract_is_2d)
				{
					uves_qclog_delete(&qclog[0]);
					qclog[0] = uves_qclog_init(raw_header[raw_index], chip);

					check( scired_qclog(info_tbl,
							raw_header[raw_index],
							raw_image[raw_index],
							extraction_slit,
							qclog[0]),
							"Could not compute QC parameters");
				}

				uves_msg("Saving products...");
				/* It is important to save products in the correct
				 * order, because users want to identify products depending on
				 * their number rather than the PRO-CATG (which would perhaps
				 * make more sense).
				 */

				/* Save RED_SCIENCE / RED2D_SCIENCE =
                               (reduced_science, merged_header) */
				cpl_free(product_filename);
				check( product_filename =
						(extract_is_2d) ?
								uves_scired_red_2d_science_filename(chip) :
								((m_method == MERGE_NOAPPEND) ?
										uves_scired_red_noappend_science_filename(chip): uves_scired_red_science_filename(chip)),
										"Error getting filename");

				//cpl_free(product_tag);
				catg_is_noappend=uves_get_pro_catg_special(extract_is_2d,m_method);
				product_tag = uves_sprintf(
						"RED%s%s_%s_%s",
						catg_is_noappend,
						(extract_is_2d) ? "_2D" : "",
								sci_type, uves_chip_tostring_upper(chip));

				uves_propertylist_append(merged_header,wave_acc_header);
				//uves_pfits_set_extname(merged_header,"reduced 1d spectrum");
				check( uves_frameset_insert(frames,
						reduced_science,
						CPL_FRAME_GROUP_PRODUCT,
						CPL_FRAME_TYPE_IMAGE,
						CPL_FRAME_LEVEL_FINAL,
						product_filename,
						product_tag,
						raw_header[raw_index],
						merged_header,
						NULL,
						parameters,
						recipe_id,
						PACKAGE "/" PACKAGE_VERSION,
						qclog,
						starttime,
						false,    /* Do not create QC log */
						UVES_ALL_STATS),
						"Could not add reduced science spectrum '%s' (%s) to frameset",
						product_filename, product_tag);

				uves_msg("Reduced science spectrum '%s' (%s) added to frameset",
						product_filename, product_tag);

				if (extract_is_2d)
				{
					/* Save EXT_2D_SCIENCE_xxxx = (x2d, x2d_header) */
					cpl_free(product_filename);
					check( product_filename = uves_scired_ext2d_filename(chip),
							"Error getting filename");

					cpl_free(product_tag);
					product_tag =
							uves_sprintf("EXT_2D_%s_%s", sci_type,
									uves_chip_tostring_upper(chip));


					//uves_pfits_set_extname(x2d_header,"Extracted 2d spectrum");
					check( uves_frameset_insert(frames,
							x2d,
							CPL_FRAME_GROUP_PRODUCT,
							CPL_FRAME_TYPE_IMAGE,
							CPL_FRAME_LEVEL_FINAL,
							product_filename,
							product_tag,
							raw_header[raw_index],
							x2d_header,
							NULL,
							parameters,
							recipe_id,
							PACKAGE "/" PACKAGE_VERSION,
							qclog,
							starttime, false,
							UVES_ALL_STATS),
							"Could not add 2d extracted "
							"spectrum '%s' (%s) to frameset",
							product_filename, product_tag);

					uves_msg("2d extracted spectrum '%s' (%s) added to frameset",
							product_filename, product_tag);

				}

				/* Save MERGED_SCIENCE / MER2D_SCIENCE =
                               (merged_science, merged_header) */
				cpl_free(product_filename);
				check( product_filename = (extract_is_2d) ?
						uves_scired_merged_2d_science_filename(chip) :
						uves_scired_merged_science_filename(chip),
						"Error getting filename");
				cpl_free(product_tag);
				product_tag = uves_sprintf(
						"%s_%s_%s",
						(extract_is_2d) ? "MER_2D" : "MERGED",
								sci_type, uves_chip_tostring_upper(chip));

				uves_propertylist_append(merged_header,wave_acc_header);
				//uves_pfits_set_extname(merged_header,"merged 1d spectrum");
				check( uves_frameset_insert(frames,
						merged_science,
						CPL_FRAME_GROUP_PRODUCT,
						CPL_FRAME_TYPE_IMAGE,
						CPL_FRAME_LEVEL_FINAL,
						product_filename,
						product_tag,
						raw_header[raw_index],
						merged_header,
						NULL,
						parameters,
						recipe_id,
						PACKAGE "/" PACKAGE_VERSION,
						qclog,
						starttime, false,
						UVES_ALL_STATS),
						"Could not add merged science spectrum '%s' (%s) to frameset",
						product_filename, product_tag);

				uves_msg("Merged science spectrum '%s' (%s) added to frameset",
						product_filename, product_tag);

				if (!extract_is_2d)
				{
					/* Save WCALIB_SCIENCE = (resampled_science, rebinned_header)
					 * If ff_method = extract, this product was not flat-fielded
					 */
					cpl_free(product_filename);
					check( product_filename = (extract_is_2d) ?
							uves_scired_resampled_2d_filename(chip) :
							uves_scired_resampled_filename(chip),
							"Error getting filename");

					cpl_free(product_tag);
					product_tag =
							uves_sprintf("WCALIB_%s_%s", sci_type,
									uves_chip_tostring_upper(chip));

					uves_propertylist_append(rebinned_header,wave_acc_header);
					//uves_pfits_set_extname(rebinned_header,"Rebinned 2d spectrum");
					check( uves_frameset_insert(frames,
							resampled_science,
							CPL_FRAME_GROUP_PRODUCT,
							CPL_FRAME_TYPE_IMAGE,
							CPL_FRAME_LEVEL_FINAL,
							product_filename,
							product_tag,
							raw_header[raw_index],
							rebinned_header,
							NULL,
							parameters,
							recipe_id,
							PACKAGE "/" PACKAGE_VERSION,
							qclog,
							starttime, false,
							UVES_ALL_STATS),
							"Could not add wavelength calibrated science "
							"spectrum '%s' (%s) to frameset", product_filename,
							product_tag);

					uves_msg("Wavelength calibrated science spectrum '%s' "
							"(%s) added to frameset", product_filename,
							product_tag);


					cpl_free(product_filename);

					check( product_filename =
							uves_order_extract_qc_standard_filename(chip),
							"Error getting filename");

					//uves_pfits_set_extname(rotated_header[raw_index],"QC on extraction");

					sprintf(extname,"QC_INFO");
					uves_pfits_set_extname(table_header,extname);

					check( uves_frameset_insert(frames,
							info_tbl,
							CPL_FRAME_GROUP_PRODUCT,
							CPL_FRAME_TYPE_TABLE,
							CPL_FRAME_LEVEL_INTERMEDIATE,
							product_filename,
							UVES_ORDER_EXTRACT_QC(chip),
							raw_header[raw_index],
							rotated_header[raw_index],
							table_header,
							parameters,
							recipe_id,
							PACKAGE "/" PACKAGE_VERSION,
							NULL,
							starttime, true,
							0),
							"Could not add extraction quality table %s (%s)"
							, product_filename,
							UVES_ORDER_EXTRACT_QC(chip));

					uves_msg("Extraction quality table '%s' "
							"(%s) added to frameset", product_filename,
							UVES_ORDER_EXTRACT_QC(chip));


				} /* if not 2d extracted */


				{
					const char *ff = "";

					/* Read uves_scired.reduce.ffmethd */
					cpl_free(context);
					context = uves_sprintf("%s.%s", recipe_id, UVES_REDUCE_ID);
					check( uves_get_parameter(parameters, NULL,
							context,
							"ffmethod",
							CPL_TYPE_STRING, &ff),
							"Could not read parameter");

					/* If flat-fielding was done */
					if (strcmp(ff, "no") != 0)
					{
						/* Save WCALIB_FF_SCIENCE / WCAL2D_SCIENCE =
                                           (rebinned_science, rebinned_header) */
						cpl_table *qc_tabs[] = {NULL, NULL, NULL};

						/* QC consists of usual science QC and
                       optionally TFLAT QC
						 */

						if ( strcmp(recipe_id, make_str(UVES_TFLAT_ID)) == 0 )
						{
							uves_qclog_delete(&qclog_tflat);
							qclog_tflat =
									uves_qclog_init(raw_header[raw_index], chip);

							check( tflat_qclog(resampled_science,
									raw_header[raw_index],
									qclog_tflat),
									"Could not compute QC parameters");

							qc_tabs[0] = qclog_tflat;
							qc_tabs[1] = qclog[0];
						}
						else
						{
							qc_tabs[0] = qclog[0];
							qc_tabs[1] = NULL;
						}

						cpl_free(product_filename);
						check( product_filename =
								(extract_is_2d) ?
										uves_scired_rebinned_2d_filename(chip) :
										uves_scired_rebinned_filename(chip),
										"Error getting filename");

						cpl_free(product_tag);
						product_tag = uves_sprintf(
								"%s_%s_%s",
								(extract_is_2d) ? "WCAL_2D" : "WCALIB_FF",
										sci_type, uves_chip_tostring_upper(chip));

						uves_propertylist_append(rebinned_header,wave_acc_header);
						//uves_pfits_set_extname(rebinned_header,"Rebinned 2d spectrum");
						check( uves_frameset_insert(frames,
								rebinned_science,
								CPL_FRAME_GROUP_PRODUCT,
								CPL_FRAME_TYPE_IMAGE,
								CPL_FRAME_LEVEL_FINAL,
								product_filename,
								product_tag,
								raw_header[raw_index],
								rebinned_header,
								NULL,
								parameters,
								recipe_id,
								PACKAGE "/"
								PACKAGE_VERSION,
								qc_tabs,
								starttime, true,
								UVES_ALL_STATS),
								"Could not add wavelength calibrated flat-fielded "
								"science spectrum '%s' (%s) to frameset",
								product_filename, product_tag);

						uves_msg("Wavelength calibrated flat-fielded science "
								"spectrum '%s' (%s) added to frameset",
								product_filename, product_tag);

						cpl_free(product_filename);
						check( product_filename =
								(extract_is_2d) ?
										uves_scired_rebinned_2d_error_filename(chip) :
										uves_scired_rebinned_error_filename(chip),
										"Error getting filename");

						cpl_free(product_tag);
						product_tag = uves_sprintf(
								"%s_%s_%s",
								(extract_is_2d) ? "ERRORBAR_WCAL_2D" : "ERRORBAR_WCALIB_FF",
										sci_type, uves_chip_tostring_upper(chip));


						/* not needed as done before
                //uves_propertylist_append(rebinned_header,wave_acc_header);
						 */
						//uves_pfits_set_extname(rebinned_header,"Error reduced spectrum");
						check( uves_frameset_insert(frames,
								rebinned_science_error,
								CPL_FRAME_GROUP_PRODUCT,
								CPL_FRAME_TYPE_IMAGE,
								CPL_FRAME_LEVEL_FINAL,
								product_filename,
								product_tag,
								raw_header[raw_index],
								rebinned_header,
								NULL,
								parameters,
								recipe_id,
								PACKAGE "/"
								PACKAGE_VERSION,
								qc_tabs,
								starttime, true,
								UVES_ALL_STATS),
								"Could not add wavelength calibrated flat-fielded "
								"science spectrum '%s' (%s) to frameset",
								product_filename, product_tag);

						uves_msg("Wavelength calibrated flat-fielded science "
								"spectrum error '%s' (%s) added to frameset",
								product_filename, product_tag);



						if (!extract_is_2d)
						{
							/* Save WCALIB_FLAT_OBJ_xxxx =
                                                   (resampled_mf, rebinned_header) */
							cpl_free(product_filename);
							check( product_filename =
									uves_scired_resampledmf_filename(chip),
									"Error getting filename");

							cpl_free(product_tag);
							product_tag =
									uves_sprintf(
											"WCALIB_FLAT_OBJ_%s",
											uves_chip_tostring_upper(chip));
							/* Independent of sci_type */


							/* !!!Exception!!!
							 *
							 * For this reduced master flat frame we
							 * want to propagate the keywords *not*
							 * from the first raw input frame but
							 * from the master flat field itself.
							 *
							 * For that to work we temporarily set
							 *
							 * all raw frames    := NONE
							 * master.flat frame := RAW
							 *
							 * This will make cpl_dfs_setup_product_header()
							 * find the proper "raw" frame (i.e. the mf)
							 * Also the required 'raw_header' must be
							 * that of the master flat frame, not science.
							 * After propagating keywords, we change back
							 * to normal:
							 *
							 * all raw frames    := RAW
							 * master.flat frame := CALIB
							 *
							 * (Since there could be more than 1 raw frame,
							 *  simply changing the first raw frame would
							 *  not work)
							 */

							cpl_free(raw_frames);
							check_nomsg( raw_frames =
									set_all_raw_none(frames) );

							cpl_frame_set_group(mflat_frame,
									CPL_FRAME_GROUP_RAW);

							uves_propertylist_append(rebinned_header,wave_acc_header);
							//uves_pfits_set_extname(rebinned_header,"Rebinned master flat");
							check( uves_frameset_insert(
									frames,
									resampled_mf,
									CPL_FRAME_GROUP_PRODUCT,
									CPL_FRAME_TYPE_IMAGE,
									CPL_FRAME_LEVEL_FINAL,
									product_filename,
									product_tag,
									master_flat_header,  /* Note! */
									rebinned_header,
									NULL,
									parameters,
									recipe_id,
									PACKAGE "/"
									PACKAGE_VERSION,
									NULL, /* No QC: qclog */
									starttime, false,
									CPL_STATS_MIN | CPL_STATS_MAX),
									"Could not add wavelength calibrated "
									"flat-field '%s' (%s) to frameset",
									product_filename, product_tag);

							uves_msg("Wavelength calibrated flat-field "
									"spectrum '%s' (%s) added to frameset",
									product_filename, product_tag);

							/* Change frames groups back to normal */
							{
								int i;
								for (i = 0;
										raw_frames[i] != NULL;
										i++)
								{
									cpl_frame_set_group(
											raw_frames[i],
											CPL_FRAME_GROUP_RAW);
								}
							}
							cpl_frame_set_group(mflat_frame,
									CPL_FRAME_GROUP_CALIB);
						}

						if (extract_is_2d)
						{
							/* Save FF2D_SCIENCE_xxxx = (fx2d, x2d_header) */
							cpl_free(product_filename);
							check( product_filename =
									uves_scired_ff2d_filename(chip),
									"Error getting filename");

							cpl_free(product_tag);
							product_tag =
									uves_sprintf(
											"FF_2D_%s_%s", sci_type,
											uves_chip_tostring_upper(chip));

							//uves_pfits_set_extname(x2d_header,"Extracted 2d spectrum");
							check( uves_frameset_insert(
									frames,
									fx2d,
									CPL_FRAME_GROUP_PRODUCT,
									CPL_FRAME_TYPE_IMAGE,
									CPL_FRAME_LEVEL_FINAL,
									product_filename,
									product_tag,
									raw_header[raw_index],
									x2d_header,
									NULL,
									parameters,
									recipe_id,
									PACKAGE "/"
									PACKAGE_VERSION,
									qclog,
									starttime, false,
									UVES_ALL_STATS),
									"Could not add 2d extracted, flat-fielded "
									"spectrum '%s' (%s) to frameset",
									product_filename, product_tag);

							uves_msg("2d extracted, flat-fielded spectrum "
									"'%s' (%s) added to frameset",
									product_filename, product_tag);

						}

					}/* If flat-fielding != no */

					check( uves_pfits_set_bunit(merged_header, "ADU"),
							"Error writing error spectrum header");

					/* Save ERRORBAR_SCIENCE_xxxx =
                                       (reduced_science_error, merged_header) */
					cpl_free(product_filename);

					check( product_filename =
							(extract_is_2d) ?
									uves_scired_red_2d_error_filename(chip) :
									((m_method == MERGE_NOAPPEND) ?
											uves_scired_red_noappend_error_filename(chip): uves_scired_red_error_filename(chip)),
											"Error getting filename");


					cpl_free(product_tag);
					catg_is_noappend=uves_get_pro_catg_special(extract_is_2d,m_method);
					product_tag = uves_sprintf("%s%s_%s_%s",
							(extract_is_2d) ? "ERR_2D" : "ERRORBAR",catg_is_noappend,
									sci_type, uves_chip_tostring_upper(chip));

					/*
                                    product_tag = uves_sprintf(
                                       "%s%s_%s_%s",
                                       (m_method == MERGE_NOAPPEND) ? "ERRORBAR_NONMERGED" : "ERRORBAR",
                                       (extract_is_2d) ? "_2D" : "",
                                       sci_type, uves_chip_tostring_upper(chip));

					 */
					uves_propertylist_append(merged_header,wave_acc_header);
					//uves_pfits_set_extname(merged_header,"Error reduced spectrum");
					check( uves_frameset_insert(
							frames,
							reduced_science_error,
							CPL_FRAME_GROUP_PRODUCT,
							CPL_FRAME_TYPE_IMAGE,
							CPL_FRAME_LEVEL_FINAL,
							product_filename,
							product_tag,
							raw_header[raw_index],
							merged_header,
							NULL,
							parameters,
							recipe_id,
							PACKAGE "/" PACKAGE_VERSION,
							qclog,
							starttime, false,
							CPL_STATS_MIN | CPL_STATS_MAX),
							"Could not add error bars '%s' (%s) to frameset",
							product_filename, product_tag);

					uves_msg("Science spectrum error '%s' (%s) "
							"added to frameset",
							product_filename, product_tag);

                    uves_print_rec_status(0);
					if (!extract_is_2d)
					{


						/* Save VARIANCE_SCIENCE_xxxx =
                                       (flatfielded_variance, flatfielded_variance_header) */
						cpl_free(product_filename);
						check( product_filename =
								uves_scired_ff_variance_filename(chip),
								"Error getting filename");

						cpl_free(product_tag);
						product_tag =
								uves_sprintf("VARIANCE_%s_%s", sci_type,
										uves_chip_tostring_upper(chip));



						//uves_pfits_set_extname(flatfielded_variance_header,"Variance reduced spectrum");
						check( uves_frameset_insert(frames,
								flatfielded_variance,
								CPL_FRAME_GROUP_PRODUCT,
								CPL_FRAME_TYPE_IMAGE,
								CPL_FRAME_LEVEL_FINAL,
								product_filename,
								product_tag,
								raw_header[raw_index],
								flatfielded_variance_header,
								NULL,
								parameters,
								recipe_id,
								PACKAGE "/" PACKAGE_VERSION,
								qclog,
								starttime, false,
								CPL_STATS_MIN | CPL_STATS_MAX),
								"Could not add flat-fielded spectrum variance "
								"'%s' (%s) to frameset",
								product_filename, product_tag);

						uves_msg("Flat-fielded spectrum variance '%s' (%s) "
								"added to frameset",
								product_filename, product_tag);

					} /* if not 2d extraction */
				}
				uves_print_rec_status(1);
				if (!extract_is_2d)
				{
					/* Save BKG_SCI_xxxx = (background, rotated_header) */
					cpl_free(product_filename);
					check( product_filename =
							uves_scired_background_filename(chip),
							"Error getting filename");

					cpl_free(product_tag);
					product_tag =
							uves_sprintf("BKG_SCI_%s",
									uves_chip_tostring_upper(chip));


					check( uves_frameset_insert(frames,
							background,
							CPL_FRAME_GROUP_PRODUCT,
							CPL_FRAME_TYPE_IMAGE,
							CPL_FRAME_LEVEL_FINAL,
							product_filename,
							product_tag,
							raw_header[raw_index],
							rotated_header[raw_index],
							NULL,
							parameters,
							recipe_id,
							PACKAGE "/" PACKAGE_VERSION,
							NULL, /* QC */
							starttime, false,
							CPL_STATS_MIN | CPL_STATS_MAX),
							"Could not add background image '%s' (%s) "
							"to frameset", product_filename, product_tag);

					uves_msg("Background image '%s' (%s) added to frameset",
							product_filename, product_tag);

					/* If optimal extraction, also save
                                       cosmic_mask, order_trace */
									   if (order_trace != NULL)
									   {
										   /* Save ORDER_TRACE_xxxx  */
										   uves_free_propertylist(&order_trace_header);
										   order_trace_header = uves_propertylist_new();


										   /* !WARNING!: Duplicate code follows, be careful if/when
                                               changing. These parameters should be calculated
                                               the same way as in uves_qclog_add_sci().

                                               The MIDAS pipeline wrote these parameters only
                                               in this product, and for backwards compatibility
                                               do the same here.
										    */

										   uves_propertylist_update_int(
												   order_trace_header, "ESO QC OPTEX NORD",
												   uves_round_double(
														   cpl_table_get_column_max(ordertable, "Order")-
														   cpl_table_get_column_min(ordertable, "Order")+1));

										   uves_propertylist_update_int(
												   order_trace_header, "ESO QC OPTEX XSIZE",
												   cpl_image_get_size_x(raw_image[raw_index]));

										   uves_propertylist_update_int(
												   order_trace_header, "ESO QC OPTEX YSIZE",
												   uves_round_double(extraction_slit));


										   cpl_free(product_filename);
										   check( product_filename =
												   uves_scired_ordertrace_filename(chip),
												   "Error getting filename");

										   cpl_free(product_tag);
										   product_tag =
												   uves_sprintf("ORDER_TRACE_%s",
														   uves_chip_tostring_upper(chip));

										   //uves_pfits_set_extname(order_trace_header,"Order trace info");
										   sprintf(extname,"TRACE_INFO");
										   uves_pfits_set_extname(table_header,extname);
										   check( uves_frameset_insert(frames,
												   order_trace,
												   CPL_FRAME_GROUP_PRODUCT,
												   CPL_FRAME_TYPE_TABLE,
												   CPL_FRAME_LEVEL_FINAL,
												   product_filename,
												   product_tag,
												   raw_header[raw_index],
												   order_trace_header,
												   table_header,
												   parameters,
												   recipe_id,
												   PACKAGE "/"
												   PACKAGE_VERSION,
												   qclog,
												   starttime, false,
												   0),
												   "Could not add sky spectrum '%s' (%s) "
												   "to frameset",
												   product_filename, product_tag);

										   uves_msg("Order trace table '%s' (%s) "
												   "added to frameset",
												   product_filename, product_tag);
									   }



									   if (cosmic_mask != NULL)
									   {
										   /* Save CRMASK_xxxx  */
										   uves_free_propertylist(&cosmic_mask_header);
										   cosmic_mask_header = uves_propertylist_new();

										   cpl_free(product_filename);
										   check( product_filename =
												   uves_scired_crmask_filename(chip),
												   "Error getting filename");

										   cpl_free(product_tag);
										   product_tag =
												   uves_sprintf("CRMASK_%s",
														   uves_chip_tostring_upper(chip));

										   //uves_pfits_set_extname(cosmic_mask_header,"CRH mask");
										   sprintf(extname,"CRH_MASK");
										   uves_pfits_set_extname(table_header,extname);

										   check( uves_frameset_insert(frames,
												   cosmic_mask,
												   CPL_FRAME_GROUP_PRODUCT,
												   CPL_FRAME_TYPE_TABLE,
												   CPL_FRAME_LEVEL_FINAL,
												   product_filename,
												   product_tag,
												   raw_header[raw_index],
												   cosmic_mask_header,
												   table_header,
												   parameters,
												   recipe_id,
												   PACKAGE "/"
												   PACKAGE_VERSION,
												   NULL, /* qc */
												   starttime, false,
												   0),
												   "Could not add cosmic ray table "
												   "'%s' (%s) to frameset",
												   product_filename, product_tag);

										   uves_msg("Cosmic ray table '%s' (%s) "
												   "added to frameset",
												   product_filename, product_tag);
									   }








									   if (wave_map != NULL)
									   {
										   /* Save WAVE_MAP_xxxx  */
										   uves_free_propertylist(&wave_map_header);
										   wave_map_header = uves_propertylist_new();

										   cpl_free(product_filename);
										   check( product_filename =
												   uves_scired_wmap_filename(chip),
												   "Error getting filename");

										   cpl_free(product_tag);
										   product_tag =
												   uves_sprintf("WAVE_MAP_%s",
														   uves_chip_tostring_upper(chip));
										   uves_pfits_set_ctype1(wave_map_header,"PIXEL");
										   uves_pfits_set_ctype2(wave_map_header,"PIXEL");
										   check( uves_frameset_insert(frames,
												   wave_map,
												   CPL_FRAME_GROUP_PRODUCT,
												   CPL_FRAME_TYPE_IMAGE,
												   CPL_FRAME_LEVEL_FINAL,
												   product_filename,
												   product_tag,
												   raw_header[raw_index],
												   wave_map_header,
												   NULL,
												   parameters,
												   recipe_id,
												   PACKAGE "/"
												   PACKAGE_VERSION,
												   NULL, /* qc */
												   starttime, false,
												   0),
												   "Could not add wave map "
												   "'%s' (%s) to frameset",
												   product_filename, product_tag);

										   uves_msg("Wave map '%s' (%s) "
												   "added to frameset",
												   product_filename, product_tag);
									   } else {
										   uves_msg("no wave map!!!!!!!!!");
									   }
									   uves_free_image(&wave_map);


									   if (merged_sky != NULL)
										   /* In slicer mode / 2d mode, no sky
                                           spectrum is extracted */
									   {
										   /* Save MERGED_SKY_xxxx =
                                               (merged_sky, merged_header) */
										   cpl_free(product_filename);
										   check( product_filename =
												   uves_scired_merged_sky_filename(chip),
												   "Error getting filename");

										   cpl_free(product_tag);
										   product_tag =
												   uves_sprintf("MERGED_SKY_%s",
														   uves_chip_tostring_upper(chip));

										   uves_propertylist_append(merged_header,wave_acc_header);


										   check( uves_frameset_insert(
												   frames,
												   merged_sky,
												   CPL_FRAME_GROUP_PRODUCT,
												   CPL_FRAME_TYPE_IMAGE,
												   CPL_FRAME_LEVEL_FINAL,
												   product_filename,
												   product_tag,
												   raw_header[raw_index],
												   merged_header,
												   NULL,
												   parameters,
												   recipe_id,
												   PACKAGE "/"
												   PACKAGE_VERSION,
												   NULL, /* QC */
												   starttime, false,
												   CPL_STATS_MIN | CPL_STATS_MAX),
												   "Could not add sky spectrum "
												   "'%s' (%s) to frameset",
												   product_filename, product_tag);

										   uves_msg("Sky spectrum '%s' (%s) added to frameset",
												   product_filename, product_tag);
									   }
									   else
									   {
										   uves_msg_low("No sky spectrum to save");
									   }

				}/* if extract is 2d */
				uves_print_rec_status(2);
				if (fluxcal_science != NULL &&
						(response_curve !=NULL || master_response != NULL) )
				{
					uves_msg("response %p",response_curve);
					uves_msg("master response %p",master_response);

					/* Save FLUXCAL_SCIENCE =
                                       (fluxcal_science, fluxcal_header) */
					cpl_free(product_filename);
                    uves_print_rec_status(10);
					check( product_filename =
							(extract_is_2d) ?
									uves_scired_fluxcal_science_2d_filename(chip) :
									((m_method == MERGE_NOAPPEND) ?
											uves_scired_fluxcal_science_noappend_filename(chip): uves_scired_fluxcal_science_filename(chip)),
											"Error getting filename");


					cpl_free(product_tag);


					uves_print_rec_status(11);
					catg_is_noappend=uves_get_pro_catg_special(extract_is_2d,m_method);
					product_tag = uves_sprintf("FLUXCAL%s%s_%s_%s",
							(extract_is_2d) ? "_2D" : "",catg_is_noappend,
									sci_type, uves_chip_tostring_upper(chip));


					/* Always _SCIENCE_, independent of sci_type */

					uves_propertylist_append(fluxcal_header,wave_acc_header);
                    uves_print_rec_status(12);

                    /* This for HDRL table
                    check( uves_frameset_insert(frames,
                    		                  fluxcal_science_table,
                                              CPL_FRAME_GROUP_PRODUCT,
                                              CPL_FRAME_TYPE_TABLE,
                                              CPL_FRAME_LEVEL_FINAL,
                                              product_filename,
											  product_tag,
											  raw_header[raw_index],
											  fluxcal_header,
                                              fluxcal_header,
                                              parameters,
                                              recipe_id,
                                              PACKAGE "/" PACKAGE_VERSION,
                                              qclog, starttime, true, 0),
							"Could not add flux-calibrated science "
							"spectrum '%s' (%s) to frameset",
							product_filename, product_tag);
                 */
                    /* Image format data */

    				check( uves_frameset_insert(frames,
    						fluxcal_science,
    						CPL_FRAME_GROUP_PRODUCT,
    						CPL_FRAME_TYPE_IMAGE,
    						CPL_FRAME_LEVEL_FINAL,
    						product_filename,
    						product_tag,
    						raw_header[raw_index],
    						fluxcal_header,
    						NULL,
    						parameters,
    						recipe_id,
    						PACKAGE "/" PACKAGE_VERSION,
    						qclog,
    						starttime, false,
    						UVES_ALL_STATS),
                            "Could not add flux-calibrated science "
                            "spectrum '%s' (%s) to frameset",
                            product_filename, product_tag);


                    uves_msg("Flux-calibrated science spectrum "
                             "'%s' (%s) added to frameset",
                             product_filename, product_tag);


                    /* Save FLUXCAL_ERRORBAR = (fluxcal_error, fluxcal_header) */
                    const char* units;
                    if(median_flux > 1.e-5) {
                    	/* we know that HDRL based response with STD star catalog gives
                    	 * values of the order of 10^-14---10^-13. OLD Catalog give
                    	 * response values of the order of 100-1000. 1e-5 lies
                    	 * logaritmically in the middle
                    	 */
                    	units = "10^-16 erg/cm^2/Angstrom/s";
                    } else {
                    	units = "erg/cm^2/Angstrom/s";
                    }
                    check( uves_pfits_set_bunit(fluxcal_header,units),
                    		"Error writing error spectrum header");

					cpl_free(product_filename);
					uves_print_rec_status(13);
					check( product_filename =
							(extract_is_2d) ?
									uves_scired_fluxcal_error_2d_filename(chip) :
									((m_method == MERGE_NOAPPEND) ?
											uves_scired_fluxcal_error_noappend_filename(chip): uves_scired_fluxcal_error_filename(chip)),
											"Error getting filename");

					uves_print_rec_status(14);
					cpl_free(product_tag);

                    /* */
					catg_is_noappend=uves_get_pro_catg_special(extract_is_2d,m_method);
					product_tag = uves_sprintf("FLUXCAL_ERRORBAR%s%s_%s_%s",
							(extract_is_2d) ? "_2D" : "",catg_is_noappend,
									sci_type, uves_chip_tostring_upper(chip));

					uves_propertylist_append(fluxcal_header,wave_acc_header);

					check( uves_frameset_insert(frames,
							fluxcal_error,
							CPL_FRAME_GROUP_PRODUCT,
							CPL_FRAME_TYPE_IMAGE,
							CPL_FRAME_LEVEL_FINAL,
							product_filename,
							product_tag,
							raw_header[raw_index],
							fluxcal_header,
							NULL,
							parameters,
							recipe_id,
							PACKAGE "/"
							PACKAGE_VERSION,
							qclog,
							starttime, false,0),
							//CPL_STATS_MIN | CPL_STATS_MAX),
							"Could not add flux-calibrated science "
							"spectrum error '%s' (%s) to frameset",
							product_filename, product_tag);

					uves_msg("Flux-calibrated science spectrum error "
							"'%s' (%s) added to frameset",
							product_filename, product_tag);


				} /* If flux calibration done */

			}/* if trace is enabled */
			else
			{
				uves_msg("Skipping trace number %d", trace_number);
			}

			uves_print_rec_status(15);

		}/* for each trace */
		uves_print_rec_status(16);

		if(strcmp(PROCESS_CHIP,"REDL") == 0) {
			chip = uves_chip_get_next(chip);
		}
		uves_free_propertylist(&table_header);

	}/* For each chip */
	uves_print_rec_status(17);

	cleanup:
	/* Input */
	uves_free_table(&info_tbl);

	uves_free_image(&raw_image[0]);
	uves_free_image(&raw_image[1]);

	uves_free_propertylist(&raw_header[0]);
	uves_free_propertylist(&raw_header[1]);

	uves_free_propertylist(&rotated_header[0]);
	uves_free_propertylist(&rotated_header[1]);

	uves_free_propertylist(&wave_map_header);
	uves_free_propertylist(&wave_acc_header);

	/* Input, calib */
	uves_free_image(&master_bias);
	uves_free_propertylist(&master_bias_header);

	uves_free_image(&master_dark);
	uves_free_propertylist(&master_dark_header);

	uves_free_image(&master_flat);
	uves_free_propertylist(&master_flat_header);

	uves_free_table(&ordertable);
	uves_free_propertylist(&ordertable_header);
	uves_polynomial_delete(&order_locations);
	uves_free_table(&traces);

	uves_free_table_const( &(linetable[0]) );
	uves_free_table_const( &(linetable[1]) );
	uves_free_table_const( &(linetable[2]) );
	uves_free_propertylist_const( &(linetable_header[0]) );
	uves_free_propertylist_const( &(linetable_header[1]) );
	uves_free_propertylist_const( &(linetable_header[2]) );
	uves_polynomial_delete_const( &(dispersion_relation[0]) );
	uves_polynomial_delete_const( &(dispersion_relation[1]) );
	uves_polynomial_delete_const( &(dispersion_relation[2]) );

	uves_free_image(&response_curve);
	uves_free_propertylist(&response_curve_header);
	uves_free_table(&master_response);

	uves_free_table(&atm_extinction);

	/* Output */
	uves_qclog_delete(&qclog[0]);
	uves_qclog_delete(&qclog_tflat);
	uves_free_image(&background);
	uves_free_image(&flatfielded_variance);
	uves_free_propertylist(&flatfielded_variance_header);
	uves_free_image(&rebinned_science);
	uves_free_image(&rebinned_science_error);
	uves_free_propertylist(&rebinned_header);
	uves_free_image(&resampled_science);
	uves_free_image(&resampled_mf);
	uves_free_image(&merged_sky);

	uves_free_image(&merged_science);
	uves_free_propertylist(&merged_header);
	uves_free_image(&reduced_science);
	uves_free_image(&reduced_science_error);
	uves_free_table(&fluxcal_science_table);
	uves_free_image(&fluxcal_science);
	uves_free_image(&fluxcal_error);

	uves_free_propertylist(&fluxcal_header);
	uves_free_table(&cosmic_mask);
	uves_free_propertylist(&cosmic_mask_header);

	uves_free_table(&order_trace);
	uves_free_propertylist(&order_trace_header);

	uves_free_image(&x2d);
	uves_free_image(&fx2d);
	uves_free_propertylist(&x2d_header);

	cpl_free(raw_frames);

	cpl_free(product_filename);

	cpl_free(context);

	//cpl_free(product_tag);

	uves_print_rec_status(18);
	return;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    compute science QC
  @param    info_tbl     parameters from optimal extraction
  @param    raw_header   input frame FITS header
  @param    raw_image    input image
  @param    slit         extraction slit length
  @param    qclog        QC parameters are written here
 */
/*----------------------------------------------------------------------------*/
static void
scired_qclog(const cpl_table* info_tbl, 
		const uves_propertylist *raw_header,
		const cpl_image *raw_image,
		double slit,
		cpl_table* qclog)
{
	/* This test does not exist as an official QC-TEST in the MIDAS pipeline. But
     the QC parameters are written to the product header */

	check_nomsg(uves_qclog_add_string(qclog,
			"QC TEST1 ID",
			"Science-Reduction-Test-Results",
			"Name of QC test",
			"%s"));

	check_nomsg( uves_qclog_add_sci(qclog,
			raw_header,
			raw_image,
			slit,
			info_tbl) );

	cleanup:
	return;

}

/*----------------------------------------------------------------------------*/
/**
  @brief    compute tflat QC
  @param    ima          resampled science in wavelength, order space
  @param    raw_header   raw frame header
  @param    qclog        QC parameters are written here
 */
/*----------------------------------------------------------------------------*/
static void
tflat_qclog(const cpl_image* ima,
		const uves_propertylist *raw_header,
		cpl_table* qclog)
{
	char key_name[80];
	cpl_image *window = NULL;

	double exptime;
	int nx;
	int ny;
	int i;

	check_nomsg(uves_qclog_add_string(qclog,
			"QC TEST1 ID",
			"TFLAT-QC",
			"Name of QC test",
			"%s"));


	check_nomsg(uves_qclog_add_string(qclog,
			uves_remove_string_prefix(UVES_INSMODE, "ESO "),
			uves_pfits_get_insmode(raw_header),
			"Instrument mode used.",
			"%s"));

	check_nomsg(uves_qclog_add_string(qclog,
			uves_remove_string_prefix(UVES_INSPATH, "ESO "),
			uves_pfits_get_inspath(raw_header),
			"Optical path used.",
			"%s"));

	check_nomsg(uves_qclog_add_string(qclog,
			uves_remove_string_prefix(UVES_SLIT1NAME, "ESO "),
			uves_pfits_get_slit1_name(raw_header),
			"Slit common name.",
			"%s"));

	check( exptime = uves_pfits_get_exptime(raw_header),
			"Error reading exposure time");

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

	for (i = 1; i <= ny; i++)
		/* Always count order numbers from 1, like MIDAS */
	{
		int size = 100;
		int xlo = uves_max_int(1 , (nx+1)/2 - size);
		int xhi = uves_min_int(nx, (nx+1)/2 + size);

		double min, max, avg, rms, med;

		uves_free_image(&window);
		window = cpl_image_extract(ima, xlo, i, xhi, i);
		assure_mem( window );

		if (cpl_image_count_rejected(window) >= cpl_image_get_size_x(window) - 2)
		{
			min = max = avg = rms = med = 0;
		}
		else
		{
			min = cpl_image_get_min   (window) / exptime;
			max = cpl_image_get_max   (window) / exptime;
			avg = cpl_image_get_mean  (window) / exptime;
			rms = cpl_image_get_stdev (window) / exptime;
			med = cpl_image_get_median(window) / exptime;
		}

		sprintf(key_name, "QC ORD%d DATAMIN", i);
		check_nomsg(uves_qclog_add_double(qclog,
				key_name,
				min,
				"extracted order datamin",
				"%f"));

		sprintf(key_name, "QC ORD%d DATAMAX", i);
		check_nomsg(uves_qclog_add_double(qclog,
				key_name,
				max,
				"extracted order datamax",
				"%f"));

		sprintf(key_name, "QC ORD%d DATAAVG", i);
		check_nomsg(uves_qclog_add_double(qclog,
				key_name,
				avg,
				"extracted order datamean",
				"%f"));

		sprintf(key_name, "QC ORD%d DATARMS", i);
		check_nomsg(uves_qclog_add_double(qclog,
				key_name,
				rms,
				"extracted order datarms",
				"%f"));

		sprintf(key_name, "QC ORD%d DATAMED", i);
		check_nomsg(uves_qclog_add_double(qclog,
				key_name,
				med,
				"extracted order datamed",
				"%f"));
	}

	cleanup:
	uves_free_image(&window);
	return;

}

/**@}*/