File: uves_physmod_body.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 (1917 lines) | stat: -rw-r--r-- 59,286 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
/*                                                                              *
 *   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.60 $
 * $Name: not supported by cvs2svn $
 * $Log: not supported by cvs2svn $
 * Revision 1.59  2013/07/29 12:38:25  amodigli
 * set med_dx, med_dy to proper values to have at least a model iteration on both chips (PIPE-4666)
 *
 * Revision 1.58  2013/07/01 15:37:10  amodigli
 * Rename DEBUG to debug_mode to remove compiler error on some platforms (that name is reserved to special compiler options)
 *
 * Revision 1.57  2010/09/27 08:00:41  amodigli
 * removed x_axis_scale and y_axis_scal params from interface as always kept constant
 *
 * Revision 1.56  2010/09/24 09:32:06  amodigli
 * put back QFITS dependency to fix problem spot by NRI on FIBER mode (with MIDAS calibs) data
 *
 * Revision 1.54  2010/08/30 14:17:20  amodigli
 * moved declaration product_filename variable up to eventually used to dump an extra QC product
 *
 * Revision 1.53  2010/06/15 15:46:26  amodigli
 * removed useless second call to uves_save_table_local of the same temporary product already saved
 *
 * Revision 1.52  2010/05/06 14:21:06  amodigli
 * increase mbox_x/y min to 10 to improve recipe robustness
 *
 * Revision 1.51  2010/05/01 16:01:27  amodigli
 * clearer error message
 *
 * Revision 1.50  2010/03/09 15:27:49  amodigli
 * removed generation of tmp product 'pippo4.fits'
 *
 * Revision 1.49  2010/03/01 18:17:22  amodigli
 * now model_prediction prediction table is generated only in debug mode
 *
 * Revision 1.48  2009/08/03 12:48:10  amodigli
 * some messaging to monitor physmodel shifts
 *
 * Revision 1.47  2009/07/13 07:56:21  amodigli
 * insert proper offsets for new CCD  echelle standard modes
 *
 * Revision 1.46  2009/07/13 06:38:41  amodigli
 * moved functions to get new CCD shifts in uves_physmod_create_table.c
 *
 * Revision 1.45  2009/04/27 08:32:59  amodigli
 * fixed trans_x/y setting in FIBER mode
 *
 * Revision 1.44  2009/04/14 07:02:07  amodigli
 * set explicit filename to distingush if physmod is executed on a normal formatcheck or on a reference one
 *
 * Revision 1.43  2008/09/29 06:58:03  amodigli
 * add #include <string.h>
 *
 * Revision 1.42  2008/05/01 09:57:03  amodigli
 * fixed compiler warnings
 *
 * Revision 1.41  2008/05/01 09:46:06  amodigli
 * modify x-y shift (if flames) if trans_x/y are set
 *
 * Revision 1.40  2008/02/15 12:43:49  amodigli
 * allow lower/upper chip for parameter process_chip
 *
 * Revision 1.39  2007/12/05 14:12:43  amodigli
 * if stability_cnt=0 does not do certain steps as in MIDAS
 *
 * Revision 1.38  2007/12/03 17:00:14  amodigli
 * removed dependency from flames and fixed a warning
 *
 * Revision 1.37  2007/12/03 10:43:00  amodigli
 * added flames_get_physmod_shift and set itermax to 1 to fix problems on flames-uves
 *
 * Revision 1.36  2007/10/23 07:37:43  amodigli
 * if provided subtract MASTER_BIAS from input raw and reference formatchecks
 *
 * Revision 1.35  2007/10/05 16:01:45  amodigli
 * using proces_chip parameter to process or not a given RED chip
 *
 * Revision 1.34  2007/08/21 13:08:26  jmlarsen
 * Removed irplib_access module, largely deprecated by CPL-4
 *
 * Revision 1.33  2007/08/10 15:24:11  amodigli
 * fixed seg fault with flames-uves
 *
 * Revision 1.32  2007/06/26 15:08:17  amodigli
 * changes to make work flames and uves physmod in simple way
 *
 * Revision 1.31  2007/06/22 09:30:22  jmlarsen
 * Changed interface of uves_save_image
 *
 * Revision 1.30  2007/06/13 15:13:48  amodigli
 * fixed mem leaks in case of fiber mode data
 *
 * Revision 1.29  2007/06/06 08:17:33  amodigli
 * replace tab with 4 spaces
 *
 * Revision 1.28  2007/05/22 14:34:32  jmlarsen
 * Removed unnecessary includes
 *
 * Revision 1.27  2007/05/14 09:38:38  amodigli
 * removed call to irplib_error_dump
 *
 * Revision 1.26  2007/04/25 08:38:40  amodigli
 * chnaged interface uves_physmod_plotmod
 *
 * Revision 1.25  2007/04/24 14:08:53  jmlarsen
 * Log more QC parameters (DFS03805)
 *
 * Revision 1.24  2007/04/24 12:50:29  jmlarsen
 * Replaced cpl_propertylist -> uves_propertylist which is much faster
 *
 * Revision 1.23  2007/04/14 05:55:19  amodigli
 * warning of flames,iter demoted to debug message
 *
 * Revision 1.22  2007/04/12 12:03:10  jmlarsen
 * Fixed doc. typo
 *
 * Revision 1.21  2007/03/05 10:18:55  jmlarsen
 * Do QC-log INS.SLITi.WID
 *
 * Revision 1.20  2007/02/26 10:16:22  jmlarsen
 * Do not QC log slit width
 *
 * Revision 1.19  2007/01/15 14:28:44  jmlarsen
 * Write default stability QC-parameters, only when master frame is provided
 *
 * Revision 1.18  2007/01/15 08:43:15  jmlarsen
 * Fixed missing plots
 *
 * Revision 1.17  2007/01/13 09:52:22  amodigli
 * fixed some problems on flames QC log
 *
 * Revision 1.16  2007/01/09 17:46:03  amodigli
 * fixed a problem in echelle mode
 *
 * Revision 1.15  2007/01/08 16:59:18  amodigli
 * changes to make flames-uves iterations to recover physical model
 *
 * Revision 1.14  2006/12/07 08:26:04  jmlarsen
 * Added uves_pfits_get_readspeed
 *
 * Revision 1.13  2006/12/01 12:29:21  jmlarsen
 * Factored out FLAMES plate-id code
 *
 * Revision 1.12  2006/11/22 08:42:20  jmlarsen
 * Set traceid = 1, not 0 for UVES
 *
 * Revision 1.10  2006/11/22 08:22:29  jmlarsen
 * Set message level according to preprocessor symbol
 *
 * Revision 1.9  2006/11/16 14:12:21  jmlarsen
 * Changed undefined trace number from 0 to -1, to support zero as an actual trace number
 *
 * Revision 1.8  2006/11/16 09:49:25  jmlarsen
 * Fixed doxygen bug
 *
 * Revision 1.7  2006/11/15 15:02:14  jmlarsen
 * Implemented const safe workarounds for CPL functions
 *
 * Revision 1.5  2006/11/15 14:04:08  jmlarsen
 * Removed non-const version of parameterlist_get_first/last/next which is already
 * in CPL, added const-safe wrapper, unwrapper and deallocator functions
 *
 * Revision 1.4  2006/11/06 15:19:41  jmlarsen
 * Removed unused include directives
 *
 * Revision 1.3  2006/10/26 14:03:48  jmlarsen
 * Fixed position of const modifier
 *
 * Revision 1.2  2006/10/25 11:43:32  amodigli
 * fixed problem running physmod in debug mode
 *
 * Revision 1.1  2006/10/24 14:09:56  jmlarsen
 * Factored out common UVES/FLAMES code
 *
 * Revision 1.30  2006/10/19 13:53:25  jmlarsen
 * Changed guess line table tag to LINE_GUESS_TAB
 *
 * Revision 1.29  2006/10/17 12:33:02  jmlarsen
 * Added semicolon at UVES_RECIPE_DEFINE invocation
 *
 * Revision 1.28  2006/10/11 12:22:36  amodigli
 * now the stability check consist only i the msrawxy and the table comparison, as in MIDAS
 *
 * Revision 1.27  2006/10/09 13:01:13  jmlarsen
 * Use macro to define recipe interface functions
 *
 * Revision 1.26  2006/09/19 14:31:38  jmlarsen
 * uves_insert_frame(): use bitmap to specify which image statistics keywords must be computed
 *
 * Revision 1.25  2006/09/19 06:55:39  jmlarsen
 * Changed interface of uves_frameset to optionally write image statistics kewwords
 *
 * Revision 1.24  2006/08/24 11:36:37  jmlarsen
 * Write recipe start/stop time to header
 *
 * Revision 1.23  2006/08/18 13:35:42  jmlarsen
 * Fixed/changed QC parameter formats
 *
 * Revision 1.22  2006/08/17 13:56:53  jmlarsen
 * Reduced max line length
 *
 * Revision 1.21  2006/08/11 14:56:05  amodigli
 * removed Doxygen warnings
 *
 * Revision 1.20  2006/08/07 11:35:35  jmlarsen
 * Disabled parameter environment variable mode
 *
 * Revision 1.19  2006/08/01 14:42:34  amodigli
 * fixed bugs getting raw header from master formatcheck
 *
 * Revision 1.18  2006/07/31 06:29:26  amodigli
 * added QC on stability test
 *
 * Revision 1.17  2006/07/28 14:51:26  amodigli
 * fixed some bugs on improper table selection
 *
 * Revision 1.16  2006/07/14 12:19:28  jmlarsen
 * Support multiple QC tests per product
 *
 * Revision 1.15  2006/07/03 12:46:34  amodigli
 * updated description
 *
 * Revision 1.14  2006/06/28 13:28:29  amodigli
 * improved output
 *
 * Revision 1.13  2006/06/20 09:06:39  amodigli
 * correct input tag info in man page
 *
 * Revision 1.12  2006/06/16 08:25:45  jmlarsen
 * Manually propagate ESO.DET. keywords from 1st/2nd input header
 *
 * Revision 1.11  2006/06/13 11:57:02  jmlarsen
 * Check that calibration frames are from the same chip ID
 *
 * Revision 1.10  2006/06/07 13:06:28  jmlarsen
 * Changed doxygen tag addtogroup -> defgroup
 *
 * Revision 1.9  2006/06/07 09:01:28  amodigli
 * added some doc
 *
 * Revision 1.8  2006/05/08 15:42:16  amodigli
 * allow to specify order column label
 *
 * Revision 1.7  2006/04/20 10:47:39  amodigli
 * added qclog
 *
 * Revision 1.6  2006/04/07 07:11:12  jmlarsen
 * Minor doc. fix
 *
 * Revision 1.5  2006/04/06 09:48:15  amodigli
 * changed uves_frameset_insert interface to have QC log
 *
 * Revision 1.4  2006/04/06 08:42:19  jmlarsen
 * Changed indentation
 *
 * Revision 1.3  2006/03/03 13:54:11  jmlarsen
 * Changed syntax of check macro
 *
 * Revision 1.2  2006/02/28 09:15:22  jmlarsen
 * Minor update
 *
 * Revision 1.1  2006/02/03 07:46:30  jmlarsen
 * Moved recipe implementations to ./uves directory
 *
 * Revision 1.66  2006/01/25 10:09:18  jmlarsen
 * Added doxygen end marker
 *
 * Revision 1.65  2006/01/20 10:36:25  amodigli
 *
 * Fixed warings from doxigen
 *
 * Revision 1.64  2006/01/19 10:03:06  amodigli
 * Fixed leaks
 *
 * Revision 1.62  2006/01/16 13:52:58  jmlarsen
 * Removed memory leak
 *
 * Revision 1.61  2006/01/16 08:01:57  amodigli
 *
 * Added stability check
 *
 * Revision 1.60  2006/01/13 13:43:15  jmlarsen
 * Removed memory leak
 *
 * Revision 1.59  2006/01/13 09:54:42  amodigli
 * Fixed some bugs: improved agreement with MIDAS version
 *
 * Revision 1.58  2006/01/09 15:23:06  jmlarsen
 * Removed some warnings
 *
 * Revision 1.57  2006/01/09 14:05:42  amodigli
 * Fixed doxigen warnings
 *
 * Revision 1.56  2006/01/03 16:57:13  amodigli
 * Fixed bug
 *
 * Revision 1.55  2006/01/03 14:47:53  amodigli
 *
 * Added uves_physmod_chop_otab.h .c to match MIDAS
 *
 * Revision 1.54  2005/12/19 16:17:55  jmlarsen
 * Replaced bool -> int
 *
 */
#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

/*----------------------------------------------------------------------------*/
/**
 * @addtogroup uves_physmod
 */
/*----------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------
                                Includes
 -----------------------------------------------------------------------------*/

/* Self */
#include <uves_physmod_body.h>

/* called related functions */
#include <uves_physmod_plotmod.h>
#include <uves_physmod_create_table.h>

#include <uves_physmod_qc1pmtbl.h>
#include <uves_physmod_calmap.h>
#include <uves_physmod_msrawxy.h>
#include <uves_physmod_chop_otab.h>
#include <uves_physmod_stability_check.h>

/* Utility functions */
#include <uves_utils.h>
#include <uves_utils_polynomial.h>
#include <uves_utils_wrappers.h>
#include <uves_pfits.h>
#include <uves_dfs.h>
#include <uves_parameters.h>
#include <uves_qclog.h>
#include <uves_recipe.h>
#include <uves_error.h>
#include <uves_msg.h>
/* Library */
#include <cpl.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
/*-----------------------------------------------------------------------------
                                Defines
 -----------------------------------------------------------------------------*/

#define UVES_PHYSMOD_ITER_MAX 5
/*-----------------------------------------------------------------------------
                            Functions prototypes
 ----------------------------------------------------------------------------*/

static int 
uves_physmod_qclog(cpl_table* line_table,
		   cpl_table* order_table,
		   cpl_table* qclog,
		   const uves_propertylist *raw_header,
		   enum uves_chip chip,
                   bool flames,
                   const int iter,
                   const int plate_no);

static int 
uves_physmod_qclog_sc(const double med_dx, 
		      const double med_dy,
		      const double avg_dx,
                      const double avg_dy,
                      const uves_propertylist *raw_header,
                      const uves_propertylist *ref_header,
                      enum  uves_chip chip,
		      bool flames,
		      const int iter,
		      cpl_table* qclog);



static int
flames_get_physmod_shift(const int plate_no,
                         const int wavec,
                         enum uves_chip chip,
			 double* physmod_shift_x,
                         double* physmod_shift_y,
			 double* rot_1,
                         double* rot_2,
                         double* rot_3);


/*-----------------------------------------------------------------------------
                            Recipe standard code
 -----------------------------------------------------------------------------*/

const char * const uves_physmod_desc_short = "Implements the UVES physical model";
const char * const uves_physmod_desc =
"This recipe implements the UVES physical model\n"
"Input files are BLUE or RED arm formatcheck frames identified by the tag\n"
"ARC_LAMP_FORM_xxxx, xxxx=BLUE or RED and a ThAr line reference table\n"
"identified by the tag LINE_REFER_TABLE\n"
"The recipe extracts from the input files FITS header data indicating the\n"
"instrument setting and ambiental atmospheric conditions, then using the\n"
"model predicts X,Y position of the lines listed in the LINE_REFER_TABLE\n"
"table which are imaging on the detector and stores this information in an\n"
"guess order and a guess line table.\n"
"Output are a guess order table and a guess line table per chip.\n"
"If the user provides in input also master format checks having tag\n"
"MASTER_FORM_xxxx, xxxx=BLUE or REDL and REDU the recipe performs also a\n"
"stability check\n";

/**@{*/
/*-----------------------------------------------------------------------------
                            Functions code
 -----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------*/
/**
  @brief    Setup the recipe options    
  @param    parameters        the parameterlist to fill
  @return   0 if everything is ok
 */
/*----------------------------------------------------------------------------*/
int
uves_physmod_define_parameters_body(cpl_parameterlist *parameters, 
                                    const char *recipe_id)
{
    const char *subcontext = NULL;

    /*****************
     *    General    *
     *****************/

    if (uves_define_global_parameters(parameters) != CPL_ERROR_NONE)
    {
        return -1;
    }
    
    uves_par_new_range("mbox_x",
                 CPL_TYPE_INT,
                 "Match box X size",
                 40,10,100);

    uves_par_new_range("mbox_y",
                 CPL_TYPE_INT,
                 "Match box Y size",
                 40,10,100);

    uves_par_new_value("trans_x",
                 CPL_TYPE_DOUBLE,
                 "Detector translation along X",
                 0.);

    uves_par_new_value("trans_y",
                 CPL_TYPE_DOUBLE,
                 "Detector translation along Y",
                 0.);

    uves_par_new_value("ech_angle_off",
                 CPL_TYPE_DOUBLE,
                 "Offset on echelle angle",
                 0.);

    uves_par_new_value("cd_angle_off",
                 CPL_TYPE_DOUBLE,
                 "Offset on cross disperser angle",
                 0.);

    uves_par_new_value("ccd_rot_angle_off",
                 CPL_TYPE_DOUBLE,
                 "Offset on CCD rotation angle",
                 0.);

    uves_par_new_value("compute_regression_sw",
                 CPL_TYPE_BOOL,
                 "Compute regression?",
                 true);

/*  we decided to remove those params as we always have them set to 0
    uves_par_new_value("x_axis_scale",
                 CPL_TYPE_DOUBLE,
                 "Scale X axis",
                 0.);

    uves_par_new_value("y_axis_scale",
                 CPL_TYPE_DOUBLE,
                 "Scale Y axis",
                 0.);
*/
    uves_par_new_value("def_pol1",
                 CPL_TYPE_INT,
                 "Polynomial X deg",
                 4);

    uves_par_new_value("def_pol2",
                 CPL_TYPE_INT,
                 "Polynomial Y deg",
                 5);

    uves_par_new_value("kappa",
                 CPL_TYPE_DOUBLE,
                 "Kappa value in kappa sigma clipping "
                 "on RESIDUAL between YFIT and Y columns",
                 4.5);

    uves_par_new_value("tol",
                 CPL_TYPE_DOUBLE,
                 "Tolerance in kappa sigma clipping "
                 "on RESIDUAL between YFIT and Y columns",
                 2.0);

    return (int) cpl_error_get_code();
}
/*----------------------------------------------------------------------------*/
/**
  @brief    Process a single chip
  @param    raw_image   The input raw images
  @param    raw_header  An array containing the input image headers. 
                         The ordering must be the same as the ordering 
                         of images in the input image list
  @param    raw_filename The name of the input raw fits file
  @param    chip         CCD chip
  @param    recipe_id    recipe name
  @param    debug_mode        Debug mode flag
  @param    parameters   The recipe parameter list
  @param    line_refer   The reference line table
  @param    physmod_shift_x Correction to physical model
  @param    physmod_shift_y Correction to physical model
  @param    lin_tbl      The output guess line table
  @param    ord_tbl      The output guess order table
  @param    mline_tbl    The output table with results from measurements on
                         the input image frame
  @param    abs_ord_min  The minimum of the orders detected
  @param    abs_ord_max  The maximum of the orders detected
  @param    absolute_order_poly2d   A polynomial with order trace coefficients
  @return   Returns guess line and order tables, minimum, maximum order, 
  order trace coefficients

  Executes the several macro steps coded in uves_physmod_*.c sources 
  for processing a single chip 
*/
/*----------------------------------------------------------------------------*/

static cpl_table *
uves_physmod_process_chip(const cpl_image *raw_image, 
                          const uves_propertylist *raw_header, 
                          const char *raw_filename, 
                          enum uves_chip chip,
			  bool flames,
                          const char *recipe_id,
                          const int debug_mode, 
                          const cpl_parameterlist* parameters, 
                          cpl_table* line_refer,
                          const double physmod_shift_x,
                          const double physmod_shift_y,
                          cpl_table** tmp_mod_tbl,
                          cpl_table** lin_tbl,
                          cpl_table** ord_tbl,
                          cpl_table**  mline_tbl,
                          int* abs_ord_min,
                          int* abs_ord_max,
                          polynomial** absolute_order_poly2d,
                          const int stability_cnt)
{

    cpl_table *tmp_fsr_tbl = NULL;
    cpl_table *tmp_m_tbl = NULL;
    cpl_table *tmp_p_tbl = NULL;
    cpl_table *tmp_w_tbl = NULL;
    cpl_table *tmp_s_tbl = NULL;
    cpl_table *tmp_rline_tbl = NULL;
    cpl_table *tmp_npline_tbl = NULL;


    cpl_table * result=NULL;
    const char *product_filename = NULL;

    /* Start processing this chip */
    uves_msg("stability counter=%d",stability_cnt);
    if(stability_cnt == 0) {
       uves_msg("offsetx=%f offsety=%f",physmod_shift_x,physmod_shift_y);
       check( uves_physmod_create_table(raw_header, 
                                        chip,
                                        flames,
                                        recipe_id,
                                        parameters, 
                                        line_refer, 
                                        physmod_shift_x,
                                        physmod_shift_y,
                                        tmp_mod_tbl,
                                        &tmp_fsr_tbl), 
              "Could not run UVES physical model on the raw image %s", 
              raw_filename);

       if (debug_mode) {

          const char *product_filename = NULL;
          product_filename = "model_prediction";
          check( uves_save_table_local("Physical model table", 
                                       product_filename, *tmp_mod_tbl, chip, -1, -1, raw_header, NULL),
                 "Error saving physical model table");

   
       }
    }




    uves_free_table(&tmp_rline_tbl);
    check( uves_physmod_msrawxy(raw_image, 
                raw_header, 
                recipe_id,
                parameters, 
                *tmp_mod_tbl,
                lin_tbl,
                &tmp_m_tbl,
                &tmp_p_tbl,
                &tmp_rline_tbl,
                mline_tbl,
                &tmp_npline_tbl), 
       "Could not run uves_msrawxy to measure arc line position on raw image %s", 
       raw_filename);

/*
    product_filename = "tmp_mod_tbl";
        check( uves_save_table_local("tmp_mod_tbl table", 
               product_filename, *tmp_mod_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving tmp_mod_tbl table");
*/

    check(uves_physmod_plotmod(tmp_rline_tbl,raw_header,recipe_id,
                               parameters,chip),
          "Could not run uves_physmod_plotmod");
  
    if(stability_cnt == 0) {
      uves_free_table(&tmp_w_tbl);
      uves_free_table(&tmp_s_tbl);
      check(uves_physmod_calmap(raw_header,
                    chip,
                    recipe_id,
                    parameters, 
                    tmp_npline_tbl,
                    ord_tbl,
                    lin_tbl,
                    &tmp_w_tbl,
                    &tmp_s_tbl,
                    abs_ord_min,
                    abs_ord_max,
                    absolute_order_poly2d), 
        "Could not run uves_calmap on raw image %s", raw_filename);

      //cpl_table_save(*lin_tbl, NULL, NULL, "pippo4.fits", CPL_IO_DEFAULT);
   

      check(uves_physmod_chop_otab(raw_header,chip,lin_tbl,"Order",
                   abs_ord_min,abs_ord_max),
            "Could not run uves_physmod_chop_otab on raw image %s",
            raw_filename);


      check(uves_physmod_qc1pmtbl(&tmp_rline_tbl,lin_tbl), 
       "Could not run uves_qc1pmtbl on raw image %s", raw_filename);

    
      check(uves_physmod_chop_otab(raw_header,chip,ord_tbl,"ORDER",
                   abs_ord_min,abs_ord_max),
            "Could not run uves_physmod_chop_otab on raw image %s",
            raw_filename);
    }

    if (debug_mode) {
        /* Temporary products (to debug_mode) */

    /* Basic info about orders */
    if(stability_cnt==0) {
      product_filename = "arclampform";
    } else {
      product_filename = "ref_arclampform";
    }
        check( uves_save_image_local("Physical model table", 
               product_filename, raw_image, chip, -1, -1, raw_header, true),
              "Error saving arc lamp form image");

    product_filename = "pline";
        check( uves_save_table_local("Physical model table", 
               product_filename, *tmp_mod_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving physical model table");

      
     if(stability_cnt == 0) {
      product_filename = "free_spectral_range";
      check( uves_save_table_local("FSR table",
                       product_filename, tmp_fsr_tbl,
                                       chip, -1, -1, raw_header, NULL),
         "Error saving free spectral range table");

    }
        
    product_filename = "midduml";
        check( uves_save_table_local("midduml table", 
               product_filename, *lin_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving midduml table");


 
    product_filename = "middumm";
        check( uves_save_table_local("middumm table", 
               product_filename, tmp_m_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving middumm table");


    
    product_filename = "middumrline";
        check( uves_save_table_local("middumrline table", 
               product_filename, tmp_rline_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving middumrline table");


    product_filename = "middummline";
        check( uves_save_table_local("middummline table", 
               product_filename, *mline_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving middummline table");


    product_filename = "middump";
        check( uves_save_table_local("middump table", 
               product_filename, tmp_p_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving middump table");

       
    product_filename = "middumnpline";
        check( uves_save_table_local("middumnpline table", 
               product_filename, tmp_npline_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving middumnpline table");
      
       
    /* Calmap */
    if(stability_cnt== 0) {
      product_filename = "middumw";
      check( uves_save_table_local("middumw table", 
                       product_filename, tmp_w_tbl, 
                                       chip, -1, -1, raw_header, NULL),
         "Error saving middumw table");
     
      product_filename = "middums";
      check( uves_save_table_local("middums table", 
                       product_filename, tmp_s_tbl, 
                                       chip, -1, -1, raw_header, NULL),
         "Error saving middums table");
     
       
      product_filename = "order";
      check( uves_save_table_local("order table", 
                       product_filename, *ord_tbl, 
                                       chip, -1, -1, raw_header, NULL),
         "Error saving order table");
      uves_msg("Order table saved to file %s", 
           product_filename);

    }
    product_filename = "line";
        check( uves_save_table_local("line table", 
               product_filename, *lin_tbl, chip, -1, -1, raw_header, NULL),
              "Error saving uves_line table");
        uves_msg("Line table saved to file %s", 
                                product_filename);
    
     
    
    }
    
  cleanup:
    uves_free_table(&tmp_fsr_tbl);
    uves_free_table(&tmp_m_tbl);
    uves_free_table(&tmp_p_tbl);
    uves_free_table(&tmp_w_tbl);
    uves_free_table(&tmp_s_tbl);
    uves_free_table(&tmp_rline_tbl);
     uves_free_table(&tmp_npline_tbl);
     
    uves_msg_debug("end %s",__func__);
    return result;
}



/*---------------------------------------------------------------------------*/
/**
  @brief    Get the command line options and execute the data reduction
  @param    parameters  the parameters list
  @param    flames      FLAMES mode?
  @param    recipe_id   recipe name
  @param    frames      the frames list
  @return   CPL_ERROR_NONE if everything is ok
 */
/*---------------------------------------------------------------------------*/
void
uves_physmod_exe_body(cpl_frameset *frames,
		      bool flames,
		      const char *recipe_id,
		      const cpl_parameterlist *parameters,
		      const char *starttime)
{
  /* Input image */
  cpl_image        *raw_image[2]      = {NULL, NULL};
  uves_propertylist *raw_header[2]     = {NULL, NULL};
  uves_propertylist *rotated_header[2] = {NULL, NULL};
  uves_propertylist *master_formatcheck_header[2] = {NULL, NULL};

  /* Physical Model guess table products */
  cpl_table        *line_table     = NULL;
  cpl_table        *order_table     = NULL;
  cpl_table        *mline_table     = NULL;
  cpl_table        *m_mline_table     = NULL;
  cpl_table        *model_table = NULL;

  cpl_table        *r_mline_table     = NULL;
  cpl_table        *mst_line_table     = NULL;
  cpl_table        *mst_mline_table     = NULL;
  cpl_table        *mst_order_table     = NULL;


  uves_propertylist *product_header = NULL;
  uves_propertylist *table_header = NULL;
  cpl_table        *line_refer            = NULL;
  polynomial       *absolute_order_poly2d=NULL;      
  polynomial       *mst_absolute_order_poly2d=NULL;      


  /* Local variables */
  int      debug_mode=0;
  int abs_ord_min=0;
  int abs_ord_max=0;
  int mst_abs_ord_min=0;
  int mst_abs_ord_max=0;
  double avg_dx=0;
  double avg_dy=0;

  const char *raw_filename = "";
  char *product_filename = NULL;
    
  bool blue = false;
  enum uves_chip chip;    
  const char *line_refer_filename = "";
  const char *master_formatcheck_filename = "";
  cpl_image        *master_formatcheck    = NULL;
  int nordpred=0;
  int plate_no=0;
  int iter=1;
  int it=0;

  int iter_max=UVES_PHYSMOD_ITER_MAX;
  /* QC tables for iter_max*(TEST1+TEST2) and a NULL pointer */
  cpl_table* qclog[iter_max*2+1];


  double physmod_shift_x=0;
  double physmod_shift_y=0;
  double ref_frame_physmod_shift_x=0;
  double ref_frame_physmod_shift_y=0;
  const double max_shift_x=0.4;
  const double max_shift_y=0.2;
  double med_dx=2*max_shift_x;
  double med_dy=2*max_shift_y;
  const char* PROCESS_CHIP=NULL;
  /* Master bias */
  cpl_image *master_bias               = NULL;
  uves_propertylist *master_bias_header = NULL;

  double rot_1=0;
  double rot_2=0;
  double rot_3=0;
  double wlen=0;
  int wavec=0;
  int stab_check=0;
  int stability_cnt=1;
  const char *chip_name = "";
  int raw_index = 0;
  const char *master_bias_filename = "";

  double trans_x=0;
  double trans_y=0;
  char extname[80];
  for( iter=0 ; iter < 2*iter_max+1 ; iter++) {
    qclog[iter]=NULL;
  }

  if(flames) {
    iter_max=1;  //Temporally changed to 1
  } else {
    iter_max=1;
  }
  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);
  /* Load raw image and header, and identify input frame as red or blue */
  check( uves_load_formatcheck(frames, flames, &raw_filename, raw_image, 
			       raw_header, rotated_header, &blue), 
	 "Error loading raw frame");

  /* Load reference line table */
  check( uves_load_linerefertable(frames, &line_refer_filename, 
				  &line_refer, NULL), 
	 "Could not load line reference table");
  uves_msg("Using line reference table in '%s'", line_refer_filename);

  check( uves_get_parameter(parameters, NULL, recipe_id,
			    "trans_x", CPL_TYPE_DOUBLE, &trans_x )  ,
	 "Could not read parameter");

  check( uves_get_parameter(parameters, NULL, recipe_id, 
			    "trans_y", CPL_TYPE_DOUBLE, &trans_y )  ,
	 "Could not read parameter");



  /* Loop over one or two chips */
  for (chip = uves_chip_get_first(blue); 
       chip != UVES_CHIP_INVALID; 
       chip = uves_chip_get_next(chip))
    {
      /* following init to have at least one model iteration on both chips */ 
      med_dx=2*max_shift_x;
      med_dy=2*max_shift_y;
      if(strcmp(PROCESS_CHIP,"REDU") == 0) {
	chip = uves_chip_get_next(chip);
      }

      stab_check=0;
      stability_cnt=1;
      raw_index = uves_chip_get_index(chip);
        

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


      physmod_shift_x=0;
      physmod_shift_y=0;
      if(flames) {
	check(plate_no = uves_flames_pfits_get_plateid(raw_header[raw_index]),
	      "Error reading plate id");
        check_nomsg(wlen=uves_pfits_get_gratwlen(raw_header[raw_index],chip));
	wavec=(int)wlen;
        

	ck0_nomsg(flames_get_physmod_shift(plate_no,wavec,chip,
					   &physmod_shift_x,&physmod_shift_y,
					   &rot_1,&rot_2,&rot_3));

        ref_frame_physmod_shift_x=physmod_shift_x;
        ref_frame_physmod_shift_y=physmod_shift_y;



	uves_msg("shift_x=%f shift_y=%f",physmod_shift_x,physmod_shift_y);
	if( trans_x != 0 ) {
	  physmod_shift_x+=trans_x;
	}

	if( trans_y != 0 ) {
	  physmod_shift_y+=trans_y;
	}
	uves_msg("shift_x=%f shift_y=%f",physmod_shift_x,physmod_shift_y);

      } else {

	if( trans_x != 0 ) {
	  physmod_shift_x=trans_x;
	}

	if( trans_y != 0 ) {
	  physmod_shift_y=trans_y;
	}

      }
      uves_msg("Using physmod shifts: %g %g",physmod_shift_x,physmod_shift_y);
      /* Check if a stability check can be done */
      if (cpl_frameset_find(frames, UVES_MASTER_ARC_FORM(chip)) != NULL) {
	  
	uves_free_image (&master_formatcheck);
	uves_free_propertylist(&master_formatcheck_header[raw_index]);
	check( uves_load_master_formatcheck(frames, 
					    chip_name,
					    &master_formatcheck_filename, 
					    &master_formatcheck,
					    &master_formatcheck_header[raw_index],                  
					    chip),
	       "Could not load master formatcheck frm");
            

	stab_check=1;

      } else {
	uves_msg_low("No master format check frm in SOF.");
	uves_msg_low("Stability check not done");
      }

      /* 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' and '%s'", 
		       master_bias_filename,master_formatcheck_filename);
	  check_nomsg(cpl_image_subtract(raw_image[raw_index],master_bias));
	  if(stab_check==1) {
	    check_nomsg(cpl_image_subtract(master_formatcheck,master_bias));
	  }     

        }
      else
        {
	  uves_msg_low("No master bias in SOF. Bias subtraction not done");
        }

      /* Init QC-Log: before starting the stability check as in 
	 FLAMES-UVES one may have several iterations to be dumped 
	 on the different tables
      */

      for(iter=1,it=0;
	  iter<=iter_max &&
	    (fabs(med_dx) > max_shift_x || 
	     fabs(med_dy) > max_shift_y ) ;
	  iter++,it+=2) {
	uves_msg("iter=%d it=%d",iter,it);

	uves_qclog_delete(&qclog[it]);
	uves_qclog_delete(&qclog[it+1]);
	qclog[it]   = uves_qclog_init(raw_header[raw_index], chip);
	qclog[it+1] = uves_qclog_init(raw_header[raw_index], chip);

  
	//Run the physical model on the raw frame
	uves_free_table(&model_table);
	uves_free_table(&line_table);
	uves_free_table(&order_table);
	uves_free_table(&mline_table);

	uves_polynomial_delete(&absolute_order_poly2d);
	uves_msg("Run the physical model on the raw frame");
        uves_msg("physmod shift x %f y %f",physmod_shift_x,physmod_shift_y);
	check( uves_physmod_process_chip(raw_image[raw_index], 
					 raw_header[raw_index],
					 raw_filename,
					 chip,
					 flames,
					 recipe_id,
					 debug_mode,
					 parameters,
					 line_refer,
					 physmod_shift_x,
					 physmod_shift_y,
					 &model_table,
					 &line_table,
					 &order_table,
					 &mline_table,
					 &abs_ord_min,
					 &abs_ord_max,
					 &absolute_order_poly2d,0),
	       "Error processing chip");

	nordpred=abs_ord_max-abs_ord_min+1;
	uves_msg("No of predicted orders %d",nordpred);


	/* add QC log */
	uves_msg("add QC log on raw frame");
	ck0(uves_physmod_qclog(line_table,order_table,qclog[it],
			       raw_header[raw_index], chip,
			       flames,iter,plate_no),"qc-log dump");


	   
	uves_msg("iter_max=%d",iter_max);
	if(stab_check) {
	  uves_free_table(&mst_line_table);
	  uves_free_table(&mst_order_table);
	  uves_free_table(&mst_mline_table);
	  uves_polynomial_delete(&mst_absolute_order_poly2d);

	  uves_msg("Run the physical model on the Master formatcheck frame");
          uves_msg("ref physmod shift x %f y %f",
		   ref_frame_physmod_shift_x,ref_frame_physmod_shift_y);

	  uves_msg("Stability counter=%d",stability_cnt);
	  check(uves_physmod_process_chip(master_formatcheck,
					  master_formatcheck_header[raw_index], 
					  master_formatcheck_filename,
					  chip,
					  flames,
					  recipe_id,
					  debug_mode,
					  parameters,
					  line_refer,
					  ref_frame_physmod_shift_x,
					  ref_frame_physmod_shift_y,
					  &model_table,
					  &mst_line_table,
					  &mst_order_table,
					  &mst_mline_table,
					  &mst_abs_ord_min,
					  &mst_abs_ord_max,
					  &mst_absolute_order_poly2d,
					  stability_cnt),
		"Error processing chip");
	  stability_cnt+=1;            
	  uves_msg("Stability check");
	  uves_msg("Using master format check frm '%s'", 
		   master_formatcheck_filename);
	  check_nomsg( uves_physmod_stability_check(
						    mline_table,
						    mst_mline_table,
						    &med_dx,
						    &med_dy,
						    &avg_dx,
						    &avg_dy) );


            
	  uves_physmod_qclog_sc(med_dx,med_dy,avg_dx,avg_dy, 
				raw_header[raw_index],
				master_formatcheck_header[raw_index],
				chip,flames,iter,
				qclog[it+1]);
	  uves_msg("iter=%d med_dx=%g med_dy=%g",
		   iter,fabs(med_dx),fabs(med_dy));
	  uves_msg("iter=%d max_shift_x=%g max_shift_y=%g",
		   iter,max_shift_x,max_shift_y);


	  nordpred=abs_ord_max-abs_ord_min+1;
	  physmod_shift_x-=med_dx;
	  physmod_shift_y-=med_dy;

	} // end of stability check
      
      } // end of iterations
         
        
        /* Finished. Now save the products */
      uves_msg("Saving products...");
       
        
      /* QC parameters should go here.
	 Other mandatory keywords (FITS + dfs) are
	 automatically added. */

      uves_free_propertylist(&product_header);
      uves_free_propertylist(&table_header);
      product_header = uves_propertylist_new();
      table_header = uves_propertylist_new();
      check( uves_pfits_set_traceid     ( table_header, 0),
	     "Error writing trace ID to product header");
      check( uves_pfits_set_windownumber( table_header, 2),
	     "Error window number to product header");

      check( uves_pfits_set_firstabsorder(table_header, abs_ord_min),
	     "Error window number to product header");

      check( uves_pfits_set_lastabsorder(table_header, abs_ord_max),
	     "Error window number to product header");

      check_nomsg(uves_pfits_set_ordpred(product_header,nordpred));


      if (flames) {
            
	check_nomsg(uves_flames_pfits_set_newplateid(product_header, 
						     plate_no));
      }

      cpl_free(product_filename);
      //uves_pfits_set_extname(product_header,"Guess line table");
      sprintf(extname,"LINE_GUESS_TAB");
      uves_pfits_set_extname(table_header,extname);
      check(( product_filename = uves_guess_line_table_filename(chip),
	      uves_frameset_insert(frames,
				   line_table,
				   CPL_FRAME_GROUP_PRODUCT,
				   CPL_FRAME_TYPE_TABLE,
				   CPL_FRAME_LEVEL_INTERMEDIATE,
				   product_filename,
				   UVES_GUESS_LINE_TABLE(flames, chip),
				   raw_header[raw_index], 
				   product_header,
				   table_header,
				   parameters,
				   recipe_id,
				   PACKAGE "/" PACKAGE_VERSION,
				   qclog,
				   starttime, 
				   true, 
				   0)),
	    "Could not add line guess table %s to frameset", 
	    product_filename);
                
      /* Save in next extension */

      sprintf(extname,"LINE_GUESS_POL1");
      uves_pfits_set_extname(table_header,extname);
      check( uves_save_polynomial(absolute_order_poly2d, 
				  product_filename, table_header),
	     "Could not write polynomial to file '%s'", product_filename);
               
      sprintf(extname,"LINE_GUESS_POL2");
       uves_pfits_set_extname(table_header,extname);
      check( uves_save_polynomial(absolute_order_poly2d, 
				  product_filename, table_header), 
	     "Could not write polynomial to file '%s'", product_filename);
            


      uves_msg("Line table %s added to frameset", product_filename);
        
      /* Save guess order table, re-use product header */

      cpl_free(product_filename);        
      //uves_pfits_set_extname(product_header,"Guess order table");
      sprintf(extname,"ORD_GUESS_TAB");
      uves_pfits_set_extname(table_header,extname);
      check(( product_filename = uves_guess_order_table_filename(chip),
	      uves_frameset_insert(frames,
				   order_table,
				   CPL_FRAME_GROUP_PRODUCT,
				   CPL_FRAME_TYPE_TABLE,
				   CPL_FRAME_LEVEL_INTERMEDIATE,
				   product_filename,
				   UVES_GUESS_ORDER_TABLE(flames, chip),
				   raw_header[raw_index],
				   product_header,
				   table_header,
				   parameters,
				   recipe_id,
				   PACKAGE "/" PACKAGE_VERSION,
				   NULL,
				   starttime, 
				   false, 
				   0)), 
	    "Could not add order guess table %s to frameset", 
	    product_filename);
        
      uves_msg("Order guess table %s added to frameset", 
	       product_filename);

      for(it=0;it<2*iter_max+1;it++) {
	uves_qclog_delete(&qclog[it]);
      }

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

    }/* For each chip */

 cleanup:
  for(it=0;it<2*iter_max+1;it++) {
    uves_qclog_delete(&qclog[it]);
  }
   
  /* Master bias */
  uves_free_image(&master_bias);
  uves_free_propertylist(&master_bias_header);

  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_image (&master_formatcheck);
  uves_free_propertylist(&master_formatcheck_header[0]);
  uves_free_propertylist(&master_formatcheck_header[1]);

  uves_free_table(&model_table);
  uves_free_table(&line_table);
  uves_free_table(&mst_line_table);
  uves_free_table(&order_table);
  uves_free_table(&mst_order_table);
  uves_free_table(&line_refer);

  uves_free_table(&mline_table);
  uves_free_table(&m_mline_table);
  uves_free_table(&r_mline_table);
  uves_free_table(&mst_mline_table);

  uves_free_propertylist(&product_header);
  uves_free_propertylist(&table_header);
  uves_polynomial_delete(&absolute_order_poly2d);
  uves_polynomial_delete(&mst_absolute_order_poly2d);
  cpl_free(product_filename); 
          
  uves_msg_debug("end %s",__func__);
  return;
}


/**
@brief computes QC parameters
@param line_table         input table
@param line_table         input table
@param qclog              output QC table
@param raw_header         input raw_header
@param chip               CCD chip
@return QC parameters on tables
*/
static int 
uves_physmod_qclog(cpl_table* line_table,
                   cpl_table* order_table,
                   cpl_table* qclog,
                   const uves_propertylist *raw_header,
                   enum uves_chip chip,
                   bool flames,
                   const int iter,
                   const int plate_no)
{
  int nlinsel=0;
  cpl_table *xline_table=NULL;
  char key_value[25];


  check_nomsg( uves_qclog_add_common_wave(raw_header,
                                          chip, qclog) );


  if(flames) {
     ck0_nomsg(uves_qclog_add_string(qclog,
                     "QC TEST1 ID",
                     "Fibre-Physical-Model-Prediction-Results",
                     "Name of QC test",
                     "%s"));
  } else {
     ck0_nomsg(uves_qclog_add_string(qclog,
                     "QC TEST1 ID",
                     "Physical-Model-Prediction-Results",
                     "Name of QC test",
                     "%s"));
  }
  ck0_nomsg(uves_qclog_add_string(qclog,
                  "QC MODEL ID",
                  "UVES_phys_mod/1.1.0",
                  "Physmod Model Id",
                  "%s"));

  ck0_nomsg(uves_qclog_add_string(qclog,
                  "QC MODEL DATE",
                  "2000:03:18T00:00:00.000",
                  "Physmod Model Parameters Last Change",
                  "%s"));

  if(flames) {

    sprintf(key_value,"%s%d","QC MODEL ITER",iter);
    ck0_nomsg(uves_qclog_add_int(qclog,
                 key_value,
                 iter,
                 "Model iteration",
                 "%d"));

    ck0_nomsg(uves_qclog_add_int(qclog,
                 "QC MODEL ORDMIN",
                 cpl_table_get_column_min(line_table,"Order"),
                 "minimum predicted order value",
                 "%d"));

    ck0_nomsg(uves_qclog_add_int(qclog,
                 "QC MODEL ORDMAX",
                 cpl_table_get_column_max(line_table,"Order"),
                 "maximum predicted order value",
                 "%d"));


    ck0_nomsg(uves_qclog_add_double(qclog,
                 "QC MODEL WLENMIN",
                 cpl_table_get_column_min(line_table,"WAVEC")/10.,
                 "minimum predicted order value",
                 "%f"));

    ck0_nomsg(uves_qclog_add_double(qclog,
                 "QC MODEL WLENMAX",
                 cpl_table_get_column_max(line_table,"WAVEC")/10.,
                 "maximum predicted order value",
                 "%f"));


  } /* in case of flames-uves */

  ck0_nomsg(uves_qclog_add_int(qclog,
                   "QC MODEL NLINALL",
                   cpl_table_get_nrow(line_table),
                   "Number of predicted lines",
                   "%d"));

  check_nomsg(nlinsel=cpl_table_and_selected_int(line_table,"SELPLOT",
                                                 CPL_EQUAL_TO,1));
  check_nomsg(xline_table=cpl_table_extract_selected(line_table));

  ck0_nomsg(uves_qclog_add_int(qclog,
                   "QC MODEL NLINSEL",
                   nlinsel,
                   "Number of lines selected",
                   "%d"));

  if(iter == 1) {
     ck0_nomsg(uves_qclog_add_double(qclog,
                     "QC MODEL DIFFXRMS",
                     cpl_table_get_column_stdev(xline_table,"XDIF"),
                     "Std dev of X difference to physical model",
                     "%8.4f"));

     ck0_nomsg(uves_qclog_add_double(qclog,
                     "QC MODEL DIFFXAVG",
                     cpl_table_get_column_mean(xline_table,"XDIF"),
                     "Average of X difference to physical model",
                     "%8.4f"));

     ck0_nomsg(uves_qclog_add_double(qclog,"QC MODEL DIFFXMED",
                     cpl_table_get_column_median(xline_table,"XDIF"),
                     "Median of X difference to physical model",
                     "%8.4f"));

     ck0_nomsg(uves_qclog_add_double(qclog,
                     "QC MODEL DIFFYRMS",
                     cpl_table_get_column_stdev(xline_table,"YDIF"),
                     "Std dev of Y difference to physical model",
                     "%8.4f"));

     ck0_nomsg(uves_qclog_add_double(qclog,
                     "QC MODEL DIFFYAVG",
                     cpl_table_get_column_mean(xline_table,"YDIF"),
                     "Average of Y difference to physical model",
                     "%8.4f"));

     ck0_nomsg(uves_qclog_add_double(qclog,"QC MODEL DIFFYMED",
                     cpl_table_get_column_median(xline_table,"YDIF"),
                     "Median of Y difference to physical model",
                     "%8.4f"));
  }

  if ( flames == 1 ) {


       sprintf(key_value,"%s%d","QC MODEL RESXRMS",iter);
       ck0_nomsg(uves_qclog_add_double(qclog,
                    key_value,
                    cpl_table_get_column_stdev(xline_table,"XDIF"),
                    "Std dev of X difference to physical model",
                    "%8.4f"));


       sprintf(key_value,"%s%d","QC MODEL RESXAVG",iter);
       ck0_nomsg(uves_qclog_add_double(qclog,
                    key_value,
                    cpl_table_get_column_mean(xline_table,"XDIF"),
                    "Average of X difference to physical model",
                    "%8.4f"));

       sprintf(key_value,"%s%d","QC MODEL RESXMED",iter);
       ck0_nomsg(uves_qclog_add_double(qclog,
                    key_value,
                    cpl_table_get_column_median(xline_table,"XDIF"),
                    "Median of X difference to physical model",
                    "%8.4f"));



       sprintf(key_value,"%s%d","QC MODEL RESYRMS",iter);
       ck0_nomsg(uves_qclog_add_double(qclog,
                    key_value,
                    cpl_table_get_column_stdev(xline_table,"YDIF"),
                    "Std dev of Y difference to physical model",
                    "%8.4f"));


       sprintf(key_value,"%s%d","QC MODEL RESYAVG",iter);
       ck0_nomsg(uves_qclog_add_double(qclog,
                    key_value,
                    cpl_table_get_column_mean(xline_table,"YDIF"),
                    "Average of Y difference to physical model",
                    "%8.4f"));

       sprintf(key_value,"%s%d","QC MODEL RESYMED",iter);
       ck0_nomsg(uves_qclog_add_double(qclog,
                    key_value,
                    cpl_table_get_column_median(xline_table,"YDIF"),
                    "Median of Y difference to physical model",
                    "%8.4f"));


  }


  cpl_table_unselect_all(line_table);

  /* we divide by 10 as line_table contains values in Angstrom and we want
     nanometers */
  ck0_nomsg(uves_qclog_add_double(qclog,
                  "QC MODEL WLENMIN",
                  cpl_table_get_column_min(xline_table,"WAVEC")/10.,
                  "minimum predicted wavelength value",
                  "%8.4f"));

 ck0_nomsg(uves_qclog_add_double(qclog,
                 "QC MODEL WLENMAX",
                 cpl_table_get_column_max(xline_table,"WAVEC")/10.,
                 "maximum predicted wavelength value",
                 "%8.4f"));


  ck0_nomsg(uves_qclog_add_int(qclog,
                   "QC MODEL ORDMIN",
                   (int)cpl_table_get_column_min(xline_table,"Order"),
                   "minimum predicted order value",
                   "%d"));

  ck0_nomsg(uves_qclog_add_int(qclog,
                   "QC MODEL ORDMAX",
                   (int)cpl_table_get_column_max(xline_table,"Order"),
                   "maximum predicted order value",
                   "%d"));


 
  /* we divide by 10 as line_table contains values in Angstrom and we want
     nanometers */
  ck0_nomsg(uves_qclog_add_double(qclog,
                  "QC WLENMIN",
                  cpl_table_get_column_min(line_table,"WAVEC")/10.,
                  "minimum wavelength",
                  "%8.4f"));

  ck0_nomsg(uves_qclog_add_double(qclog,
                  "QC WLENMAX",
                  cpl_table_get_column_max(line_table,"WAVEC")/10.,
                  "maximum wavelength",
                  "%8.4f"));
  
  ck0_nomsg(uves_qclog_add_int(qclog,
                   "QC ORDMIN",
                   cpl_table_get_column_min(order_table,"ORDER"),
                   "minimum order number",
                   "%d"));

  ck0_nomsg(uves_qclog_add_int(qclog,
                   "QC ORDMAX",
                   cpl_table_get_column_max(order_table,"ORDER"),
                   "maximum order number",
                   "%d"));


  if (flames) {
    /*
stat/ima {wlc} {SESSOUTV}
tot_int = outputr(7)
exp_time = {{wlc},{h_dit1}}
rel_int = tot_int / exp_time
    */

     ck0_nomsg(uves_qclog_add_double(qclog,
                  "QC FIB1 ABSTRANS",
                  cpl_table_get_column_max(order_table,"ORDER"),
                  "abs. trans. countrate",
                  "%f"));
     /*
@p flames_check_sat_lev {wlc} {DRS_PTHRE_MIN} {DRS_PTHRE_MAX}
sat_lev = {q1}
n_hpix  = {q2}
     */

    ck0_nomsg(uves_qclog_add_int(qclog,
                 "QC NHOTPIX",
                 cpl_table_get_column_max(order_table,"ORDER"),
                 "no. of hot pixels",
                 "%d"));


    ck0_nomsg(uves_qclog_add_int(qclog,
                 "QC PLATENO",
                 plate_no,
                 "Plate Id.",
                 "%d"));
  }

  /* The number of orders predicted is already written to another
     keyword, and this is not need for QC logging, so it is commented out
  uves_qclog_add_int(qclog,"QC NORDGUE",???,"No of predicted orders","%d");
  */

 cleanup:
  uves_free_table(&xline_table);

  if (cpl_error_get_code() != CPL_ERROR_NONE) {
    return -1;

  } else {

    return 0;
  }



}




/**
@brief computes stability check QC parameters
@param 
@param 
@param  raw_header    raw frame FITS header
@param  chip          CCD chip
@parameter qclog      output QC table
@return QC parameters on tables
*/
static int 
uves_physmod_qclog_sc(const double med_dx, 
                      const double med_dy,
                      const double avg_dx,
                      const double avg_dy,
                      const uves_propertylist *raw_header,
                      const uves_propertylist *ref_header,
                      enum  uves_chip chip,
                      bool flames,
                      const int iter,
                      cpl_table* qclog)
{

  char key_value[25];

    if(flames) {
        ck0_nomsg(uves_qclog_add_string(qclog,
					"QC TEST2 ID",
					"Fibre-Stability-Check-Results",
					"Name of QC test",
				        "%s"));
    } else {
        ck0_nomsg(uves_qclog_add_string(qclog,
					"QC TEST2 ID",
					"Stability-Check-Results",
					"Name of QC test",
					"%s"));
    }
    
    ck0_nomsg(uves_qclog_add_string(qclog,
              "QC MODEL ID",
              "UVES_phys_mod/1.1.0",
              "Physmod Model Id",
              "%s"));
    
    ck0_nomsg(uves_qclog_add_string(qclog,
              "QC MODEL DATE",
              "2000:03:18T00:00:00.000",
              "Physmod Model Parameters Last Change",
              "%s"));

    check_nomsg( uves_qclog_add_common_wave(raw_header,
                                            chip, qclog) );
    

    ck0_nomsg(uves_qclog_add_string(qclog,
              "QC REF PNAME",
              uves_pfits_get_arcfile(ref_header),
              "Reference file name",
              "%s"));

    ck0_nomsg(uves_qclog_add_double(qclog,
              "QC AMBI PRES",
              uves_pfits_get_ambipress(raw_header),
              "Ambient pressure [mm] Hg.",
              "%8.4f"));


    if(flames) {

       sprintf(key_value,"%s%d","QC MODEL ITER",iter);
       ck0_nomsg(uves_qclog_add_int(qclog,
                 key_value,
                 iter,
                 "Model iteration",
                 "%d"));


    }

  if(iter == 1) {
    ck0_nomsg(uves_qclog_add_double(qclog,
              "QC SHFTXAVG",
              avg_dx,
              "mean shift in x",
              "%8.4f"));

    ck0_nomsg(uves_qclog_add_double(qclog,
              "QC SHFTXMED",
              med_dx,
              "median shift in x",
              "%8.4f"));

    ck0_nomsg(uves_qclog_add_double(qclog,
              "QC SHFTYAVG",
              avg_dy,
              "mean shift in y",
              "%8.4f"));

    ck0_nomsg(uves_qclog_add_double(qclog,
              "QC SHFTYMED",
              med_dy,
              "median shift in y",
              "%8.4f"));

  }
 cleanup:

  if (cpl_error_get_code() != CPL_ERROR_NONE) {
    return -1;
  } else {
    return 0;
  }
}


/*---------------------------------------------------------------------------*/
/**
   @brief    Get the physical model shifts in FIBER mode
   @param    plate_no  plate number
   @param    wavec     central wavelength
   @param    trans_x   out physical model X shift
   @param    trans_y   out physical model Y shift
   @param    rot_1     out rot angle 1st component
   @param    rot_2     out rot angle 2nd component
   @param    rot_3     out rot angle 3rd component
   @return   0 if everything is ok
*/
/*---------------------------------------------------------------------------*/


static int
flames_get_physmod_shift(const int plate_no,
                         const int wavec,
                         enum uves_chip chip,
                         double* trans_x,
                         double* trans_y,
                         double* rot_1,
                         double* rot_2,
                         double* rot_3)
{

  //For the moment rot angle default is assumed always 0,0,0
  *rot_1=0;
  *rot_2=0;
  *rot_3=0;

  uves_msg("plate_no=%d,wavec=%d,chip=%d",plate_no,wavec,chip);
  switch(plate_no){

  case 1:
    if(chip==UVES_CHIP_REDL) {
      switch(wavec){

      case 520:
	*trans_x=-15.330;
	*trans_y=-40.461;
	uves_msg("case 520 REDL pt1");
	break;

      case 580:
	*trans_x=-17.972;
	*trans_y=-39.200;
	uves_msg("case 580 REDL pt1");
	break;

      case 860:
	*trans_x=-12.212;
	*trans_y=-49.370;
	uves_msg("case 860 REDL pt1");
	break;

      }
    } else {

      switch(wavec){

      case 520:
	*trans_x=-14.237;
	*trans_y=-40.337;
	uves_msg("case 520 REDU pt1");
	break;

      case 580:
	*trans_x=-14.738;
	*trans_y=-38.831;
	uves_msg("case 580 REDU pt1");
	break;

      case 860:
	*trans_x=-08.253;
	*trans_y=-45.385;
	uves_msg("case 860 REDU pt1");
	break;

      }
      break;
  
    }
    break;


  case 2:
    if(chip==UVES_CHIP_REDL) {

    case UVES_CHIP_REDL:
      switch(wavec){

      case 520:
	*trans_x=+10.136;
	*trans_y=-41.420;
	uves_msg("case 520 REDL pt2");
	break;

      case 580:
	*trans_x=+09.000;
	*trans_y=-38.289;
	uves_msg("case 580 REDL pt2");
	break;

      case 860:
	*trans_x=+16.386;
	*trans_y=-47.519;
	uves_msg("case 860 REDL pt2");
	break;

      }
      break;

    } else {

      switch(wavec){

      case 520:
	*trans_x=+12.244;
	*trans_y=-41.970;
	uves_msg("case 520 REDU pt2");
	break;

      case 580:
	*trans_x=+12.023;
	*trans_y=-38.165;
	uves_msg("case 580 REDU pt2");
	break;

      case 860:
	*trans_x=+18.241;
	*trans_y=-43.889;
	uves_msg("case 860 REDU pt2");
	break;

      }
      break;

    }
    break;


  default:
    *trans_x=0;
    *trans_y=0;
  


  }


  uves_msg("Physical Model shifts trans=%f,%f rot=%f,%f,%f",
	   *trans_x,*trans_y,*rot_1,*rot_2,*rot_3);
  return 0;
}



/**@}*/