File: vimos_ima_standard.c

package info (click to toggle)
cpl-plugin-vimos 4.1.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 28,228 kB
  • sloc: ansic: 169,271; cpp: 16,177; sh: 4,344; python: 3,678; makefile: 1,138; perl: 10
file content (2093 lines) | stat: -rw-r--r-- 83,142 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
/* $Id: vimos_ima_standard.c,v 1.31 2015/11/27 12:15:33 jim Exp $
 *
 * This file is part of the VIMOS Pipeline
 * Copyright (C) 2015 European Southern Observatory
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * $Author: jim $
 * $Date: 2015/11/27 12:15:33 $
 * $Revision: 1.31 $
 * $Name:  $
 */

/* Includes */

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

#include <stdio.h>
#include <libgen.h>
#include <string.h>

#include <cpl.h>
#include <math.h>

#include "vmutils.h"
#include "vimos_imaging_utils.h"
#include "vimos_pfits.h"
#include "vimos_dfs.h"
#include "vimos_mods.h"
#include "vimos_var.h"
#include "casu_utils.h"
#include "casu_stats.h"
#include "casu_fits.h"
#include "casu_mask.h"
#include "casu_wcsutils.h"
#include "casu_mods.h"

/* Structure definitions */

typedef struct {

    /* Input */

    int         preview_only;
    int         minphotom;
    int         prettynames;
    int         cdssearch_astrom;
    int         cdssearch_photom;
    int         savemstd;
    int         ignore_fringe;
    char        *cacheloc;
    float       magerrcut;

    /* Source catalogue extraction parameters */

    int         src_cat_ipix;
    float       src_cat_thresh;
    int         src_cat_icrowd;
    float       src_cat_rcore;
    int         src_cat_nbsize;

} configstruct;

typedef struct {
    cpl_size         *labels;
    cpl_size         *labels2;
    cpl_frame        *master_bias;
    cpl_frame        *master_dark;
    cpl_frame        *master_twilight_flat;
    cpl_frame        *master_conf;
    cpl_frame        *master_fringe;
    cpl_frame        *master_fringe_var;
    cpl_frame        *readgain;
    casu_mask        *mask;
    cpl_frame        *phottab;
    cpl_table        *tphottab;
    cpl_frameset     *science_frames;
    cpl_frame        **product_frames_simple;
    cpl_frame        **product_frames_vars;
    cpl_frame        **product_frames_cats;
    cpl_frame        **product_frames_mstd_a;
    cpl_frame        **product_frames_mstd_p;
    float            *gaincors;
    char             *catpath_a;
    char             *catname_a;
    char             *catpath_p;
    char             *catname_p;
    cpl_frame        *schlf_n;
    cpl_frame        *schlf_s;
    casu_fits        *dummyfits;

    /* Level 1 stuff */

    casu_fits        *fbias;
    casu_fits        *fdark;
    casu_fits        *fflat;
    casu_fits        *fconf;
    casu_fits        *ffringe;
    casu_fits        *ffringe_var;

    int              nscience;
    casu_fits        *sci_fits[VIMOS_NEXTN];
    casu_fits        *sci_vars[VIMOS_NEXTN];
    casu_tfits       *sci_cats[VIMOS_NEXTN];
    casu_tfits       *sci_mstd_a[VIMOS_NEXTN];
    casu_tfits       *sci_mstd_p[VIMOS_NEXTN];

} memstruct;

/* List of data products types */

enum {SIMPLE_FILE,
      SIMPLE_VAR,
      SIMPLE_CAT,
      MSTDS_ASTROM,
      MSTDS_PHOTOM
};

/* Recipe name */

#define VIMOS_RECIPENAME "vimos_ima_standard"

/* Function prototypes */

static int vimos_ima_standard_create(cpl_plugin *) ;
static int vimos_ima_standard_exec(cpl_plugin *) ;
static int vimos_ima_standard_destroy(cpl_plugin *) ;
static int vimos_ima_standard(cpl_parameterlist *, cpl_frameset *) ;

static int vimos_std_save_simple(casu_fits *obj, cpl_frameset *framelist,
                                 cpl_parameterlist *parlist, 
                                 cpl_frame *template, int isfirst,
                                 const char *tag, char *fname, char *cname,
                                 char *assoc, char *photosys,
                                 cpl_frame **product_frame);
static int vimos_std_save_cat(casu_tfits *obj, cpl_frameset *framelist,
                              cpl_parameterlist *parlist, 
                              cpl_frame *template, int isfirst,
                              const char *tag, char *fname, char *cname,
                              char *photosys, cpl_frame **product_frame);
static void vimos_std_product_name(char *template, int producttype, 
                                   int nametype, int fnumber, char *outfname);

static void vimos_std_init(memstruct *ps);
static void vimos_std_tidy(memstruct *ps, int level);

static char vimos_ima_standard_description[] =
"vimos_ima_standard -- VIMOS standard star recipe.\n\n"
"Take a list of standard frames and correct them to remove bias, dark\n"
"and flat field signatures. Optionally defringe the reddest filter\n"
"images. Astrometrically and photometrically calibrate the individual\n"
"images, but do no stacking\n\n"
"The program accepts the following files in the SOF:\n\n"
"    Tag                   Description\n"
"    -----------------------------------------------------------------------\n"
"    %-21s A list of raw standard images\n"
"    %-21s A master bias frame\n"
"    %-21s A master dark frame\n"
"    %-21s A master flat frame\n"
"    %-21s A master confidence map\n"
"    %-21s A master fringe map (optional)\n"
"    %-21s A master fringe variance map (optional)\n"
"    %-21s A master readgain table\n"
"    %-21s A master 2MASS index for astrometry or\n"
"    %-21s A master PPMXL index for astrometry or\n"
"    %-21s A master APASS index for astrometry or\n"
"    %-21s A master local catalogue index for astrometry\n"
"    %-21s A master APASS index for photometry or\n"
"    %-21s A master local catalogue index for photometry\n"
"    %-21s A photometric calibration table\n"
"    %-21s Northern Schlegel Map\n"
"    %-21s Southern Schlegel Map\n"
"All of these are required unless specified otherwise."
"\n";

/**@{*/

/**
    \ingroup recipelist
    \defgroup vimos_ima_standard vimos_ima_standard
    \brief VIMOS standard recipe

    \par Name: 
        vimos_ima_standard
    \par Purpose: 
        Reduce a full pawprint of VIMOS standard data
    \par Description: 
        A single sequence of VIMOS standard data in a single filter is 
        corrected for instrumental signature. The images are not stacked.
        All images are astrometrically calibrated using a standard astrometric
        catalogue and photometrically calibrated using either the APASS
        catalogue or a local catalogue.
    \par Language:
        C
    \par Parameters:
        - General reduction parameters:
            - \b preview_only (bool): If set we only get a preview of the reduction
            - \b minphotom (int): The minimum number of standards for photometry
            - \b prettynames (bool): True if we're using nice file names       
            - \b savemstd (bool) True if we're going to save the matched 
                 standards catalogues for astrometry and photometry
            - \b cdssearch_astrom (string): Use CDS for astrometric standards?
                - none: Use no CDS catalogues. Use local catalogues instead
                - 2mass: 2MASS PSC
                - usnob: USNOB catalogue
                - ppmxl: PPMXL catalogue
                - wise: WISE catalogue
            - \b cdssearch_photom (string): Use CDS for photometric standards?
                - none: Use no CDS catalogues. Use local catalogues instead
                - apass: APASS catalogue
            - \b ignore_fringe (bool): Flag to ignore a provided fringe frame
            - \b cacheloc (string): A directory where we can put the standard
                 star cache
            - \b magerrcut (float): A cut in the magnitude error for 
                 photometric standard stars
        - Parameters for source detection on exposure frames:
            - \b src_cat_ipix (int): The minimum allowable size of an object
            - \b src_cat_thresh (float): The detection threshold in sigma above sky
            - \b src_cat_icrowd (int): If set then the deblending software will be used
            - \b src_cat_rcore (float): The core radius in pixels
            - \b src_cat_nbsize (int): The smoothing box size for background map estimation        
    \par Input File Types:
        The following list gives the file types that can appear in the SOF
        file. The word in bold is the DO category value.
        - \b STD (required): A list of raw standard images for processing
        - \b MASTER_BIAS (required): A master bias frame. This is needed 
             for the bias correction of the input images.
        - \b MASTER_DARK (required): A master dark frame. This is needed 
             for the dark correction of the input images.
        - \b MASTER_TWILIGHT_FLAT (required): A master twilight flat frame
             appropriate for the filter used in the science observations.
             This is used to remove the flat field effects from the science
             frames and also for the detector level gain correction.
        - \b MASTER_FRINGE (optional): A master fringe map
        - \b MASTER_FRINGE_VAR (optional): A master fringe variance map
        - \b MASTER_READGAIN (required): A master read/gain table
        - \b MASTER_CONF (required): A master confidence map 
             appropriate for the filter used in the science observations.
             This is used for weighting and to mark bad pixels.
        - \b MASTER_2MASS_CATLAOGUE_ASTROM or \b MASTER_PPMXL_CATALOGUE_ASTROM
             or \b MASTER_APASS_CATALOGUE_ASTROM or \b MASTER_LOCCAT_ASTROM
             (required): A master standard star catalogue for astrometry
        - \b MASTER_APASS_CATALOGUE_PHOTOM or \b MASTER_LOCCAT_PHOTOM
             (required): A master standard star catalogue for photometry
        - \b SCHLEGEL_MAP_NORTH (required): The Northern Schlegel dust map
        - \b SCHLEGEL_MAP_SOUTH (required): The Southern Schlegel dust map
    \par Output Products:
        The following list gives the output data products that are generated
        by this recipe. The word in bold gives the DPR CATG keyword value for
        each product:
        - The instrumentally corrected and astrometerically calibrated 
          individual science exposures. (\b BASIC_CALIBRATED_STD).
        - The variance maps for the calibrated individual science
          exposures. (\b BASIC_VAR_MAP_STD).
        - The source catalogue for a calibrated input image
          (\b OBJECT_CATALOGUE_STD).
        - A matched standards catalogue for astrometry, if desired
          (\b MATCHSTD_ASTROM)
        - A matched standards catalogue for photometry, if desired
          (\b MATCHSTD_PHOTOM)
    \par Output QC Parameters:
        - \b SATURATION
             The saturation level in ADUs.
        - \b MEAN_SKY
             The mean level of the background sky over the image in ADUs.
        - \b SKY_NOISE
             The RMS of the background sky over the image in ADUs
        - \b IMAGE_SIZE
             The average size of stellar images on the image in pixels
        - \b ELLIPTICITY
             The average ellipticity of stellar images on the image
        - \b POSANG
             The average position angle in degrees from North towards East.
             NB: this value only makes sense if the ellipticity is significant
        - \b APERTURE_CORR
             The aperture correction for an aperture of radius rcore.
        - \b NOISE_OBJ
             The number of noise objects found in the image
        - \b MAGZPT
             The photometric zero point
        - \b MAGZERR
             The internal error in the photometric zero point
        - \b MAGNZPT
             The number of stars used to determine the magnitude zero point
        - \b MAGNCUT
             The number of stars cut from magnitude zero point calculation
        - \b SKYBRIGHT
             The sky brightness in mag/arcsec**2
        - \b LIMITING_MAG
             The limiting magnitude for this image for a 5 sigma detection.
        - \b WCS_DCRVAL1
             The offset of the equatorial coordinate represented by CRVAL1 
             from the raw frame to the reduced one (degrees).
        - \b WCS_DCRVAL2
             The offset of the equatorial coordinate represented by CRVAL2
             from the raw frame to the reduced one (degrees).
        - \b WCS_DTHETA
             The change in the WCS coordinate system rotation from the raw
             to the reduced frame (degrees)
        - \b WCS_SCALE
             The scale of the pixels in the reduced frames in arcseconds per
             pixel
        - \b WCS_SHEAR
             The shear of the astrometric solution in the form of the 
             difference between the rotation of the x solution and the rotation
             of the y solution (abs(xrot) - abs(yrot) in degrees)
        - \b WCS_RMS
             The average error in the WCS fit (arcsec)
    \par Notes
        None.
    \par Fatal Error Conditions:
        - NULL input frameset
        - Input frameset headers incorrect meaning that RAW and CALIB frame
          can't be distinguished
        - No standard frames in the input frameset
        - No master bias, dark, flat or confidence map frame in input frameset
        - Unable to save data products
        - Unable to load images
    \par Non-Fatal Error Conditions:
        - None
    \par Conditions Leading To Dummy Products:
        - Master calibration images flagged as dummys
        - Detector for the current image is flagged as dead in all 
          standard images
        - Failure of one of the processing steps
    \par Author:
        Jim Lewis, CASU
    \par Code Reference: 
        vimos_ima_standard.c
*/

/* Function code */

/*---------------------------------------------------------------------------*/
/**
  @brief    Build the list of available plugins, for this module.
  @param    list    the plugin list
  @return   0 if everything is ok

  This function is exported.
 */
/*---------------------------------------------------------------------------*/

int cpl_plugin_get_info(cpl_pluginlist *list) {
    cpl_recipe  *recipe = cpl_calloc(1,sizeof(*recipe));
    cpl_plugin  *plugin = &recipe->interface;
    char alldesc[SZ_ALLDESC];
    (void)snprintf(alldesc,SZ_ALLDESC,vimos_ima_standard_description,
                   VIMOS_STD_OBJECT_RAW,VIMOS_CAL_BIAS,VIMOS_CAL_DARK,
                   VIMOS_CAL_TWILIGHT_FLAT,VIMOS_CAL_CONF,VIMOS_CAL_FRINGE,
                   VIMOS_CAL_FRINGE_VAR,VIMOS_CAL_READGAIN,VIMOS_CAL_2MASS_A,
                   VIMOS_CAL_PPMXL_A,VIMOS_CAL_APASS_A,VIMOS_CAL_LOCCAT_A,
                   VIMOS_CAL_APASS_P,VIMOS_CAL_LOCCAT_P,VIMOS_CAL_PHOTTAB,
                   VIMOS_CAL_SCHL_N,VIMOS_CAL_SCHL_S);

    cpl_plugin_init(plugin,
                    CPL_PLUGIN_API,
                    VIMOS_BINARY_VERSION,
                    CPL_PLUGIN_TYPE_RECIPE,
                    "vimos_ima_standard",
                    "Standard field processing for imaging",
                    alldesc,
                    "Jim Lewis",
                    "jrl@ast.cam.ac.uk",
                    vimos_get_license(),
                    vimos_ima_standard_create,
                    vimos_ima_standard_exec,
                    vimos_ima_standard_destroy);

    cpl_pluginlist_append(list,plugin);

    return(0);
}

/*---------------------------------------------------------------------------*/
/**
  @brief    Setup the recipe options
  @param    plugin  the plugin
  @return   0 if everything is ok

  Create the recipe instance and make it available to the application using the
  interface.
 */
/*---------------------------------------------------------------------------*/

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

    /* Get the recipe out of the plugin */

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

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

    recipe->parameters = cpl_parameterlist_new();

    /* Fill in flag to just print out how the data will be processed and 
       then exit */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.preview_only",
                                CPL_TYPE_BOOL,"Preview only?",
                                "vimos.vimos_ima_standard",FALSE);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"preview_only");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Fill in flag to just print out how the data will be processed and 
       then exit */

    p = cpl_parameter_new_range("vimos.vimos_ima_standard.minphotom",
                                CPL_TYPE_INT,
                                "Minimum stars for photometry solution",
                                "vimos.vimos_ima_standard",1,1,100000);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"minphotom");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Fill in flag to decide whether use predictable names or nice
       names based on input file names */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.prettynames",
                                CPL_TYPE_BOOL,"Use pretty product names?",
                                "vimos.vimos_ima_standard",FALSE);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"prettynames");
    cpl_parameterlist_append(recipe->parameters,p);
 
    /* Fill in flag to use save the matched standard catalogues */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.savemstd",
                                CPL_TYPE_BOOL,
                                "Save matched standard catalogues?",
                                "vimos.vimos_ima_standard",FALSE);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"savemstd");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Flag to decide how we get the astrometric standard star information. If 
       none, then use the local catalogues specified in the sof. If not none, 
       then use one of the selection of catalogues available from CDS */

    p = cpl_parameter_new_enum("vimos.vimos_ima_standard.cdssearch_astrom",
                               CPL_TYPE_STRING,
                               "CDS astrometric catalogue",
                               "vimos.vimos_ima_standard",
                               "none",5,"none","2mass","usnob","ppmxl","wise");
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"cdssearch_astrom");
    cpl_parameterlist_append(recipe->parameters,p);

    /* The same for photometric standards */

    p = cpl_parameter_new_enum("vimos.vimos_ima_standard.cdssearch_photom",
                               CPL_TYPE_STRING,
                               "CDS photometric catalogue",
                               "vimos.vimos_ima_standard",
                               "none",2,"none","apass");
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"cdssearch_photom");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Flag to ignore the provided fringe frame */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.ignore_fringe",
                                CPL_TYPE_BOOL,"Ignore provided fringe frame?",
                                "vimos.vimos_ima_standard",FALSE);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"ignore_fringe");
    cpl_parameterlist_append(recipe->parameters,p);

   /* ***Special parameters for object detection*** */

    /* Fill in the minimum object size */

    p = cpl_parameter_new_range("vimos.vimos_ima_standard.src_cat_ipix",
                                CPL_TYPE_INT,
                                "Minimum pixel area for each detected object",
                                "vimos.vimos_ima_standard",5,1,100000);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"src_cat_ipix");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Fill in the detection threshold parameter */

    p = cpl_parameter_new_range("vimos.vimos_ima_standard.src_cat_thresh",
                                CPL_TYPE_DOUBLE,
                                "Detection threshold in sigma above sky",
                                "vimos.vimos_ima_standard",2.5,1.0e-6,
                                1.0e10);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"src_cat_thresh");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Fill in flag to use deblending software or not */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.src_cat_icrowd",
                                CPL_TYPE_BOOL,"Use deblending?",
                                "vimos.vimos_ima_standard",TRUE);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"src_cat_icrowd");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Fill in core radius */

    p = cpl_parameter_new_range("vimos.vimos_ima_standard.src_cat_rcore",
                                CPL_TYPE_DOUBLE,"Value of Rcore in pixels",
                                "vimos.vimos_ima_standard",5.0,1.0e-6,
                                1024.0);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"src_cat_rcore");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Fill in background smoothing box size */

    p = cpl_parameter_new_range("vimos.vimos_ima_standard.src_cat_nbsize",
                                CPL_TYPE_INT,"Background smoothing box size",
                                "vimos.vimos_ima_standard",128,1,2048);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"src_cat_nbsize");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Location for standard star cache */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.cacheloc",
                                CPL_TYPE_STRING,
                                "Location for standard star cache",
                                "vimos.vimos_ima_standard",".");
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"cacheloc");
    cpl_parameterlist_append(recipe->parameters,p);  

    /* A cut in the magnitude error */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.magerrcut",
                                CPL_TYPE_DOUBLE,
                                "A cut in the magnitude error",
                                "vimos.vimos_ima_standard",100.0);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"magerrcut");
    cpl_parameterlist_append(recipe->parameters,p);  


    /* STD stars with magnitudes BRIGHTER than this are removed. */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.lthr_mag",
                                CPL_TYPE_DOUBLE,
                                "STD stars with magnitudes BRIGHTER than this are removed.",
                                "vimos.vimos_ima_standard",15.0);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"lthr_mag");
    cpl_parameterlist_append(recipe->parameters,p);

    /* STD stars with magnitudes FAINTER than this are removed. */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.hthr_mag",
                                CPL_TYPE_DOUBLE,
                                "STD stars with magnitudes FAINTER than this are removed.",
                                "vimos.vimos_ima_standard",32.0);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"hthr_mag");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Get out of here */

    return(0);
}
        
/*---------------------------------------------------------------------------*/
/**
  @brief    Execute the plugin instance given by the interface
  @param    plugin  the plugin
  @return   0 if everything is ok
 */
/*---------------------------------------------------------------------------*/

static int vimos_ima_standard_exec(cpl_plugin *plugin) {
    cpl_recipe  *recipe;

    /* Get the recipe out of the plugin */

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

    return(vimos_ima_standard(recipe->parameters,recipe->frames));
}
                                
/*---------------------------------------------------------------------------*/
/**
  @brief    Destroy what has been created by the 'create' function
  @param    plugin  the plugin
  @return   0 if everything is ok
 */
/*---------------------------------------------------------------------------*/

static int vimos_ima_standard_destroy(cpl_plugin *plugin) {
    cpl_recipe *recipe ;

    /* Get the recipe out of the plugin */

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

    cpl_parameterlist_delete(recipe->parameters);
    return(0);
}

/*---------------------------------------------------------------------------*/
/**
  @brief    The recipe data reduction part is implemented here 
  @param    parlist     the parameters list
  @param    framelist   the frames list
  @return   0 if everything is ok
 */
/*---------------------------------------------------------------------------*/

static int vimos_ima_standard(cpl_parameterlist *parlist, 
                                  cpl_frameset *framelist) {
    const char *fctid="vimos_ima_standard";
    configstruct cs;
    memstruct ps;
    cpl_parameter *p;
    cpl_size nlab,nlab2;
    int nfail,status,i,j,isfirst,n,match;
    float gaincor_fac,texp,gain,readnoise,fac;
    cpl_frame *catindex_a,*catindex_p,*frm,*tmpl;
    cpl_frameset *chiplist;
    cpl_image *dummyim;
    cpl_propertylist *pp;
    casu_fits *ff,*ffv;
    casu_tfits *tab;
    cpl_table *t,*stdscat,*dummytab;
    char filt[16],projid[16],*fname,bname[BUFSIZ],*junk1,*junk2,*pcat;
    char *vimos_names[VIMOS_NEXTN],*assoc,photosys[8];

    /* Check validity of input frameset */

    if (framelist == NULL || cpl_frameset_get_size(framelist) <= 0) {
        cpl_msg_error(fctid,"Input framelist NULL or has no input data");
        return(-1);
    }

    /* Initialise some things */

    vimos_std_init(&ps);

    /* Get the parameters */

    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.preview_only");
    cs.preview_only = cpl_parameter_get_bool(p);
    p = cpl_parameterlist_find(parlist,"vimos.vimos_ima_standard.minphotom");
    cs.minphotom = cpl_parameter_get_int(p);
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.prettynames");
    cs.prettynames = (cpl_parameter_get_bool(p) ? 1 : 0);
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.savemstd");
    cs.savemstd = cpl_parameter_get_bool(p);
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.cdssearch_astrom");
    if (! strcmp(cpl_parameter_get_string(p),"none")) 
        cs.cdssearch_astrom = 0;
    else if (! strcmp(cpl_parameter_get_string(p),"2mass")) 
        cs.cdssearch_astrom = 1;
    else if (! strcmp(cpl_parameter_get_string(p),"usnob")) 
        cs.cdssearch_astrom = 2;
    else if (! strcmp(cpl_parameter_get_string(p),"ppmxl")) 
        cs.cdssearch_astrom = 3;
    else if (! strcmp(cpl_parameter_get_string(p),"wise")) 
        cs.cdssearch_astrom = 5;
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.cdssearch_photom");
    if (! strcmp(cpl_parameter_get_string(p),"none")) 
        cs.cdssearch_photom = 0;
    else if (! strcmp(cpl_parameter_get_string(p),"apass")) 
        cs.cdssearch_photom = 6;
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.ignore_fringe");
    cs.ignore_fringe = cpl_parameter_get_bool(p);

    /* Object detection special parameters */

    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.src_cat_ipix");
    cs.src_cat_ipix = cpl_parameter_get_int(p);
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.src_cat_thresh");
    cs.src_cat_thresh = (float)cpl_parameter_get_double(p);
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.src_cat_icrowd");
    cs.src_cat_icrowd = cpl_parameter_get_bool(p);
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.src_cat_rcore");
    cs.src_cat_rcore = (float)cpl_parameter_get_double(p);
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.src_cat_nbsize");
    cs.src_cat_nbsize = cpl_parameter_get_int(p);

    /* Cache location */

    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.cacheloc");
    cs.cacheloc = (char *)cpl_parameter_get_string(p);

    /* Magnitude error cut */

    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.magerrcut");
    cs.magerrcut = (float)cpl_parameter_get_double(p);

    p = cpl_parameterlist_find(parlist, "vimos.vimos_ima_standard.lthr_mag");
    const float lthr_mag = (float)cpl_parameter_get_double(p);

    p = cpl_parameterlist_find(parlist, "vimos.vimos_ima_standard.hthr_mag");
    const float hthr_mag = (float)cpl_parameter_get_double(p);

    /* Sort out raw from calib frames */

    if (vimos_dfs_set_groups(framelist) != CASU_OK) {
        cpl_msg_error(fctid,"Cannot identify RAW and CALIB frames");
        vimos_std_tidy(&ps,0);
        return(-1);
    }

    /* Label the input frames */

    if ((ps.labels = cpl_frameset_labelise(framelist,casu_compare_tags,
                                           &nlab)) == NULL) {
        cpl_msg_error(fctid,"Cannot labelise the input frames");
        vimos_std_tidy(&ps,0);
        return(-1);
    }

    /* Get the input science frames */

    nfail = 0;
    if ((ps.science_frames = 
         casu_frameset_subgroup(framelist,ps.labels,nlab,
                                VIMOS_STD_OBJECT_RAW)) == NULL) {
        cpl_msg_error(fctid,"No science images to process!");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    /* nfail += vimos_std_testfrms(ps.science_frames,1,1,1); */

    /* Now labelise the input frameset so that we separate them by the
       observation time. This links the four detectors together */

    if ((ps.labels2 = cpl_frameset_labelise(ps.science_frames,
                                            vimos_compare_tpl_start,
                                            &nlab2)) == NULL) {
        cpl_msg_error(fctid,"Cannot labelise the science frames");
        vimos_std_tidy(&ps,0);
        return(-1);
    }


    /* See what chip set this is */

    if (vimos_load_names(cpl_frameset_get_position(ps.science_frames,0),
                         vimos_names) != CASU_OK) {
        cpl_msg_error(fctid,"Cannot get the name set");
        vimos_std_tidy(&ps,0);
        return(-1);
    }

    /* Check to see if there is a master bias frame */

    if ((ps.master_bias = 
         casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                  VIMOS_CAL_BIAS)) == NULL) {
        cpl_msg_error(fctid,"No master bias found");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    nfail += vimos_testfrm_1(ps.master_dark,VIMOS_NEXTN,1,0);
        
    /* Check to see if there is a master dark frame */

    if ((ps.master_dark = 
         casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                  VIMOS_CAL_DARK)) == NULL) {
        cpl_msg_error(fctid,"No master dark found");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    nfail += vimos_testfrm_1(ps.master_dark,VIMOS_NEXTN,1,0);
                
    /* Check to see if there is a master twilight flat frame */

    if ((ps.master_twilight_flat = 
         casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                  VIMOS_CAL_TWILIGHT_FLAT)) == NULL) {
        cpl_msg_error(fctid,"No master twilight flat found");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    nfail += vimos_testfrm_1(ps.master_twilight_flat,VIMOS_NEXTN,1,0);

    /* Get the gain corrections */

    status = CASU_OK;
    if (casu_gaincor_calc(ps.master_twilight_flat,&i,&(ps.gaincors),
                          &status) != CASU_OK) {
        cpl_msg_error(fctid,"Error calculating gain corrections");
        vimos_std_tidy(&ps,0);
        return(-1);
    }

    /* Check to see if there is a master confidence map. */

    if ((ps.master_conf = 
        casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                 VIMOS_CAL_CONF)) == NULL) {
        cpl_msg_error(fctid,"No master confidence map file found");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    nfail += vimos_testfrm_1(ps.master_conf,VIMOS_NEXTN,1,0);
    ps.mask = casu_mask_define(framelist,ps.labels,nlab,VIMOS_CAL_CONF,
                               "NONE");

    /* Look for a master fringe map. It's not a problem if it doesn't 
       exist */

    ps.master_fringe = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                                VIMOS_CAL_FRINGE);
    if (ps.master_fringe != NULL)
        nfail += vimos_testfrm_1(ps.master_fringe,VIMOS_NEXTN,1,0);

    /* Look for a master fringe variance map. It's not a problem if it doesn't 
       exist */

    ps.master_fringe_var = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                                    VIMOS_CAL_FRINGE_VAR);
    if (ps.master_fringe_var != NULL)
        nfail += vimos_testfrm_1(ps.master_fringe_var,VIMOS_NEXTN,1,0);

   /* Check to see if there is a master read/gain table */

    if ((ps.readgain = 
        casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                 VIMOS_CAL_READGAIN)) == NULL) {
        cpl_msg_error(fctid,"No master readgain table file found");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    nfail += vimos_testrdgn(ps.master_conf,ps.readgain);

    /* Is the 2mass/ppmxl index file specified for astrom? */

    catindex_a = NULL;
    if (cs.cdssearch_astrom == 0) {
        if ((catindex_a = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                                   VIMOS_CAL_2MASS_A)) == NULL) {
            if ((catindex_a = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                                       VIMOS_CAL_PPMXL_A)) == NULL) {
                if ((catindex_a = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                                           VIMOS_CAL_APASS_A)) == NULL) {
                    if ((catindex_a = casu_frameset_subgroup_1(framelist,ps.labels,
                                                               nlab,VIMOS_CAL_LOCCAT_A)) == NULL) {
        
                        cpl_msg_error(fctid,
                                      "No astrometric standard catalogue found -- cannot continue");
                        vimos_std_tidy(&ps,0);
                        return(-1);
                    }
                }
            }
        }
        nfail += vimos_testfrm_1(catindex_a,1,0,0);
    } else {
        (void)casu_getstds_cdslist(cs.cdssearch_astrom,&junk1,&junk2,&status);
        freespace(junk1);
        freespace(junk2);
        if (status != CASU_OK) {
            status = CASU_OK;
            nfail++;
        }
    }

    /* Is the 2mass/ppmxl index file specified for photom? */

    catindex_p = NULL;
    if (cs.cdssearch_photom == 0) {
        if ((catindex_p = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                                   VIMOS_CAL_APASS_P)) == NULL) {
            if ((catindex_p = casu_frameset_subgroup_1(framelist,ps.labels,
                                                       nlab,VIMOS_CAL_LOCCAT_P)) == NULL) {
                cpl_msg_error(fctid,
                              "No photometric standard catalogue found -- cannot continue");
                vimos_std_tidy(&ps,0);
                return(-1);
            }
        }
        nfail += vimos_testfrm_1(catindex_p,1,0,0);
        pp = cpl_propertylist_load(cpl_frame_get_filename(catindex_p),1);
        if (cpl_propertylist_has(pp,"EXTNAME")) {
            pcat = cpl_strdup((char *)cpl_propertylist_get_string(pp,"EXTNAME"));
        } else {
            cpl_msg_error(fctid,"No extension name in %s",
                          cpl_frame_get_filename(catindex_p));
            nfail++;
        }
        cpl_propertylist_delete(pp);
    } else {
        (void)casu_getstds_cdslist(cs.cdssearch_photom,&pcat,&junk2,&status);
        freespace(junk2);
        if (status != CASU_OK) {
            status = CASU_OK;
            nfail++;
        }
    }
        
    /* Check to see if there is a photometric table */

    if ((ps.phottab = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                               VIMOS_CAL_PHOTTAB)) == NULL) {
        cpl_msg_error(fctid,"No photometric table found");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    n = cpl_frame_get_nextensions(ps.phottab);
    nfail += vimos_testfrm_1(ps.phottab,n,0,0);

    /* Check the photometric table to see if it contains information 
       about the photometric source we want to use */

    match = 0;
    for (i = 1; i <= n; i++) {
        pp = cpl_propertylist_load(cpl_frame_get_filename(ps.phottab),i);
        if (cpl_propertylist_has(pp,"EXTNAME") &&
            strcmp(pcat,cpl_propertylist_get_string(pp,"EXTNAME")) == 0) {
            if (cpl_propertylist_has(pp,"PHOTOSYS")) {
                strncpy(photosys,cpl_propertylist_get_string(pp,"PHOTOSYS"),8);
            } else {
                cpl_msg_error(fctid,
                              "Photcal table missing PHOTOSYS information in extension %d",i);
                cpl_propertylist_delete(pp);
                break;
            }
            ps.tphottab = cpl_table_load(cpl_frame_get_filename(ps.phottab),
                                         i,0);
            cpl_propertylist_delete(pp);
            match = 1;
            break;
        }
        cpl_propertylist_delete(pp);
    }
    if (! match) {
        cpl_msg_error(fctid,"Photcal table has no information on %s",pcat);
        nfail++;
    }
    freespace(pcat);

    /* Is the Northern Schlegel file specified? */

    if ((ps.schlf_n = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                               VIMOS_CAL_SCHL_N)) == NULL) {
        cpl_msg_error(fctid,"Schlegel North map not found -- cannot continue");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    nfail += vimos_testfrm_1(ps.schlf_n,0,1,0);

    /* Is the Southern Schlegel file specified? */

    if ((ps.schlf_s = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                               VIMOS_CAL_SCHL_S)) == NULL) {
        cpl_msg_error(fctid,"Schlegel South map not found -- cannot continue");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    nfail += vimos_testfrm_1(ps.schlf_s,0,1,0);

    /* Check the cache location is writable */

    if (access(cs.cacheloc,R_OK+W_OK+X_OK) != 0) {
        cpl_msg_error(fctid,"Cache location %s inacessible",cs.cacheloc);
        nfail++;
    }

    /* Ok if any of this failed, then get out of here. This makes it a bit 
       simpler later on since we now know that all of the specified files 
       have the correct number of extensions and will load properly */

    if (nfail > 0) {
        cpl_msg_error(fctid,
                      "There are %" CPL_SIZE_FORMAT " input file errors -- cannot continue",
                      (cpl_size)nfail);
        freeframe(catindex_a);
        freeframe(catindex_p);
        vimos_std_tidy(&ps,0);
        return(-1);
    }

    /* Get catalogue parameters */

    if (cs.cdssearch_astrom == 0) {
        if (casu_catpars(catindex_a,&(ps.catpath_a),
                         &(ps.catname_a)) == CASU_FATAL) {
            vimos_std_tidy(&ps,0);
            cpl_frame_delete(catindex_a);
            return(-1);
        }
        cpl_frame_delete(catindex_a);
    } else {
        ps.catpath_a = NULL;
        ps.catname_a = NULL;
    }
    if (cs.cdssearch_photom == 0) {
        if (casu_catpars(catindex_p,&(ps.catpath_p),
                         &(ps.catname_p)) == CASU_FATAL) {
            vimos_std_tidy(&ps,0);
            cpl_frame_delete(catindex_p);
            return(-1);
        }
        cpl_frame_delete(catindex_p);
    } else {
        ps.catpath_p = NULL;
        ps.catname_p = NULL;
    }

    /* Print out some stuff if you want a preview */

    if (cs.preview_only) {
        fprintf(stdout,"This is a paw group with %" CPL_SIZE_FORMAT " files\n",
                cpl_frameset_get_size(ps.science_frames));
        frm = cpl_frameset_get_position(ps.science_frames,0);
        ff = casu_fits_load(frm,CPL_TYPE_FLOAT,cpl_frame_get_nextensions(frm));
        pp = casu_fits_get_phu(ff);
        (void)vimos_pfits_get_filter(pp,filt);
        (void)vimos_pfits_get_projid(pp,projid);
        freefits(ff);

        fprintf(stdout,"Filter: %8s, Project: %s\n",filt,projid);
        fprintf(stdout,"Bias: %s\n",cpl_frame_get_filename(ps.master_bias));
        fprintf(stdout,"Dark: %s\n",cpl_frame_get_filename(ps.master_dark));
        fprintf(stdout,"Flat: %s\n",
                cpl_frame_get_filename(ps.master_twilight_flat));
        fprintf(stdout,"CPM: %s\n",cpl_frame_get_filename(ps.master_conf));
        if (ps.master_fringe != NULL && ! cs.ignore_fringe) {
            fprintf(stdout,"Fringe: %s\n",
                    cpl_frame_get_filename(ps.master_fringe));
        } else {
            fprintf(stdout,"No defringing to be done\n");
        }
        n = cpl_frameset_get_size(ps.science_frames);
        for (j = 0; j < n; j++) {
            frm = cpl_frameset_get_position(ps.science_frames,j);
            fprintf(stdout,"%s\n",cpl_frame_get_filename(frm));
        }
        if (cs.cdssearch_astrom != 0) {
            p = cpl_parameterlist_find(parlist,
                                       "vimos.vimos_ima_standard.cdssearch_astrom");
            fprintf(stdout,"Astrometry will be done using CDS catalogue: %s\n",
                    cpl_parameter_get_string(p));
        } else {
            fprintf(stdout,"Astrometry will be done using local catalogue %s in %s\n",
                    ps.catname_a,ps.catpath_a);
        }
        if (cs.cdssearch_photom != 0) {
            p = cpl_parameterlist_find(parlist,
                                       "vimos.vimos_ima_standard.cdssearch_photom");
            fprintf(stdout,"Photometry will be done using CDS catalogue: %s\n",
                    cpl_parameter_get_string(p));
        } else {
            fprintf(stdout,"Photometry will be done using local catalogue %s in %s\n",
                    ps.catname_p,ps.catpath_p);
        }        vimos_std_tidy(&ps,0);
        return(0);
    }

    /* Get some workspace for the product frames */

    ps.nscience = nlab2;
    ps.product_frames_simple = cpl_malloc(ps.nscience*sizeof(cpl_frame *));
    ps.product_frames_vars = cpl_malloc(ps.nscience*sizeof(cpl_frame *));
    ps.product_frames_cats = cpl_malloc(ps.nscience*sizeof(cpl_frame *));
    ps.product_frames_mstd_a = cpl_malloc(ps.nscience*sizeof(cpl_frame *));
    ps.product_frames_mstd_p = cpl_malloc(ps.nscience*sizeof(cpl_frame *));
    for (i = 0; i < ps.nscience; i++) {
        ps.product_frames_simple[i] = NULL;
        ps.product_frames_vars[i] = NULL;
        ps.product_frames_cats[i] = NULL;
        ps.product_frames_mstd_a[i] = NULL;
        ps.product_frames_mstd_p[i] = NULL;
    }

    /* Create a dummy in case we need it */

    dummyim = cpl_image_new(1,1,CPL_TYPE_FLOAT);
    ps.dummyfits = casu_fits_wrap(dummyim,NULL,NULL,NULL);
    casu_dummy_property(casu_fits_get_phu(ps.dummyfits));
    casu_dummy_property(casu_fits_get_ehu(ps.dummyfits));

    /* Loop for each of the observation labels. If there are no missing 
       files, then this should be four separate images that will 
       ultimately be combined into a single output MEF */

    for (i = 0; i < nlab2; i++) {
        chiplist = vimos_get_obs_frameset(ps.science_frames,ps.labels2,
                                          nlab2,(cpl_size)i,vimos_names);
        tmpl = NULL;
        
        /* Now loop for each detector. Check that it's not a dummy */

        cpl_msg_info(fctid,"Stage 1 corrections %d of %d",i+1,(int)nlab2);
        for (j = 0; j < VIMOS_NEXTN; j++) {
            frm = cpl_frameset_get_position(chiplist,(cpl_size)j);
            if (strncmp(cpl_frame_get_tag(frm),"DUMMY",5) == 0) {
                ps.sci_fits[j] = casu_fits_duplicate(ps.dummyfits);
                ps.sci_vars[j] = casu_fits_duplicate(ps.dummyfits);
                dummytab = casu_dummy_catalogue(2);
                ps.sci_cats[j] = casu_tfits_wrap(dummytab,NULL,NULL,NULL);
                casu_dummy_property(casu_tfits_get_phu(ps.sci_cats[j]));
                casu_dummy_property(casu_tfits_get_ehu(ps.sci_cats[j]));
                ps.sci_mstd_a[j] = NULL;
                ps.sci_mstd_p[j] = NULL;
                continue;
            }
            if (tmpl == NULL) 
                tmpl = frm;
            ff = casu_fits_load(frm,CPL_TYPE_FLOAT,
                                cpl_frame_get_nextensions(frm));

            /* Right, we want to 2d correct. So load the calib files */

            ps.fbias = casu_fits_load(ps.master_bias,CPL_TYPE_FLOAT,j+1);
            ps.fdark = casu_fits_load(ps.master_dark,CPL_TYPE_FLOAT,j+1);
            ps.fflat = casu_fits_load(ps.master_twilight_flat,
                                      CPL_TYPE_FLOAT,j+1);
            ps.fconf = casu_fits_load(ps.master_conf,CPL_TYPE_INT,j+1);
            casu_mask_load(ps.mask,j+1,
                           (int)cpl_image_get_size_x(casu_fits_get_image(ps.fconf)),
                           (int)cpl_image_get_size_y(casu_fits_get_image(ps.fconf)));
            if (ps.master_fringe != NULL && ! cs.ignore_fringe) {
                ps.ffringe = casu_fits_load(ps.master_fringe,CPL_TYPE_FLOAT,
                                            j+1);
                if (ps.master_fringe_var != NULL) 
                    ps.ffringe_var = casu_fits_load(ps.master_fringe_var,
                                                    CPL_TYPE_FLOAT,j+1);
            } else {
                ps.ffringe = NULL;
                ps.ffringe_var = NULL;
            }

            /* Gain corrections are in the same order as vimos_names so 
               there's no trouble making sure we have the right one... */

            gaincor_fac = (ps.gaincors)[j];

            /* Get the readnoise and gain estimates */

            vimos_getrdgn(ps.readgain,casu_fits_get_extname(ps.fflat),
                              &readnoise,&gain);

            /* Loop for each image and do the stage 1 corrections. */

            status = CASU_OK;
            vimos_biascor(ff,ps.fbias,1,1,&status);
            vimos_pfits_get_exptime(casu_fits_get_ehu(ff),&texp);
            casu_darkcor(ff,ps.fdark,texp,&status);
            ffv = vimos_var_create(ff,ps.mask,readnoise,gain);
            casu_flatcor(ff,ps.fflat,&status);
            vimos_var_div_im(ffv,ps.fflat);
            casu_gaincor(ff,gaincor_fac,&status);
            vimos_var_divk(ffv,gaincor_fac);
            casu_fits_set_error(ff,status);
            cpl_propertylist_update_float(casu_fits_get_ehu(ff),"READNOIS",
                                          readnoise);
            cpl_propertylist_set_comment(casu_fits_get_ehu(ff),"READNOIS",
                                         "[ADU] Read noise used in reduction");
            cpl_propertylist_update_float(casu_fits_get_ehu(ff),"GAIN",
                                          gain);
            cpl_propertylist_set_comment(casu_fits_get_ehu(ff),"GAIN",
                                         "[e-/ADU] gain used in reduction");

            /* Do the defringing if we want it */
        
            if (ps.ffringe != NULL && ! cs.ignore_fringe) {
                casu_defringe(&ff,1,&(ps.ffringe),1,ps.mask,512,&status);
                if (ps.ffringe_var != NULL) {
                    fac = cpl_propertylist_get_float(casu_fits_get_ehu(ff),
                                                     "ESO DRS FRNGSC1");
                    vimos_var_scaledsubt(ffv,ps.ffringe_var,fac);
                }
            }
           
            /* Do the catalogue extraction and WCS fit */

            (void)casu_imcore(ff,ps.fconf,cs.src_cat_ipix,cs.src_cat_thresh,
                              cs.src_cat_icrowd,cs.src_cat_rcore,
                              cs.src_cat_nbsize,6,2.0,&tab,gain,&status);
            if (status == CASU_OK) {
                vimos_wcsfit(&ff,&tab,1,ps.catname_a,
                             ps.catpath_a,cs.cdssearch_astrom,cs.cacheloc,
                             cs.savemstd,j+1,&(ps.sci_mstd_a[j]));
                vimos_copywcs(casu_fits_get_ehu(ff),casu_fits_get_ehu(ffv));
                (void)casu_getstds(casu_fits_get_ehu(ff),1,ps.catpath_p,
                                   ps.catname_p,cs.cdssearch_photom,
                                   cs.cacheloc,&stdscat,&status);
                vimos_pfits_get_filter(casu_fits_get_phu(ff),filt);
            } else {
                t = casu_dummy_catalogue(2);
                tab = casu_tfits_wrap(t,NULL,
                                      cpl_propertylist_duplicate(casu_fits_get_phu(ff)),
                                      cpl_propertylist_duplicate(casu_fits_get_ehu(ff)));
                casu_tfits_set_status(tab,CASU_FATAL);
                stdscat = NULL;
                if (cs.savemstd) 
                    ps.sci_mstd_a[j] = casu_tfits_wrap(casu_dummy_catalogue(2),
                                                       tab,NULL,NULL);
                else
                    ps.sci_mstd_a[j] = NULL;
            }
            if (stdscat != NULL) {
                (void)casu_matchstds(casu_tfits_get_table(tab),
                                     stdscat,300.0,&t,&status);
                ps.sci_mstd_p[j] = casu_tfits_wrap(t,NULL,
                                                   cpl_propertylist_duplicate(casu_fits_get_phu(ff)),
                                                   cpl_propertylist_duplicate(casu_fits_get_ehu(ff)));
            } else {
                ps.sci_mstd_p[j] = NULL;
            }
            freetable(stdscat);
            (ps.sci_fits)[j] = ff;
            (ps.sci_vars)[j] = ffv;
            (ps.sci_cats)[j] = tab;
            
            /* Clean up and go on to the next extension */

            vimos_std_tidy(&ps,2);
        }

        /* Now do the photometric calibration */

        status = CASU_OK;
        vimos_pfits_get_filter(casu_fits_get_phu(ps.sci_fits[0]),filt);
        const int n_removed_stars = casu_remove_mag_outside_range(ps.sci_mstd_p, VIMOS_NEXTN, filt, ps.tphottab, lthr_mag, hthr_mag);
        if(n_removed_stars == -1)
        {
            cpl_msg_error(fctid,"Cannot filter stars in magnitude range");
            vimos_std_tidy(&ps,0);
            return(-1);
        }
        cpl_msg_info(cpl_func, "Removed %i stars outside magnitue range %f %f",
                     n_removed_stars, lthr_mag, hthr_mag);
        casu_photcal_extinct(ps.sci_fits,ps.sci_mstd_p,ps.sci_cats,VIMOS_NEXTN,
                             filt,ps.tphottab,cs.minphotom,ps.schlf_n,
                             ps.schlf_s,"EXPTIME","ESO TEL AIRM START",
                             cs.magerrcut,&status);

        /* Check whether there is at least one star used for the photometric
           zeropoints */
        int magnzptall = cpl_propertylist_get_int(casu_fits_get_ehu(ps.sci_fits[0]),"ESO DRS MAGNZPTALL");
        if(magnzptall == 0)
        {
            cpl_msg_error(cpl_func, "No photometric stars could be found "
                          "among all VIMOS chips");
            vimos_std_tidy(&ps,0);
            return(-1);
        }

        /* Now save the products */

        status = CASU_OK;
        cpl_msg_info(fctid,"Saving products");
        for (j = 1; j <= VIMOS_NEXTN; j++) {
            isfirst = (j == 1);

            /* Save the variance map */

            assoc = NULL;
            if (j == 1) {
                fname = cpl_strdup(cpl_frame_get_filename(tmpl));
                vimos_std_product_name(fname,SIMPLE_VAR,cs.prettynames,i+1,
                                       bname);
                freespace(fname);
            } else {
                strcpy(bname,
                       cpl_frame_get_filename((ps.product_frames_vars)[i]));
            }
            if (vimos_std_save_simple((ps.sci_vars)[j-1],framelist,parlist,
                                      tmpl,isfirst,VIMOS_PRO_VAR_STD,bname,
                                      vimos_names[j-1],assoc,photosys,
                                      ps.product_frames_vars+i) != CASU_OK) {
                cpl_msg_error(fctid,"Unable to save product %s[%d]",bname,j);
                cpl_frameset_delete(chiplist);
                vimos_std_tidy(&ps,0);
                return(-1);
            }

            /* Save the image */

            if (j == 1) {
                fname = cpl_strdup(cpl_frame_get_filename(tmpl));
                vimos_std_product_name(fname,SIMPLE_FILE,cs.prettynames,i+1,
                                       bname);
                freespace(fname);
                assoc = cpl_strdup(cpl_frame_get_filename(ps.product_frames_vars[i]));
            } else {
                strcpy(bname,
                       cpl_frame_get_filename((ps.product_frames_simple)[i]));
            }
            if (vimos_std_save_simple((ps.sci_fits)[j-1],framelist,parlist,
                                      tmpl,isfirst,VIMOS_PRO_SIMPLE_STD,
                                      bname,vimos_names[j-1],assoc,photosys,
                                      ps.product_frames_simple+i) != CASU_OK) {
                cpl_msg_error(fctid,"Unable to save product %s[%d]",bname,j);
                cpl_frameset_delete(chiplist);
                vimos_std_tidy(&ps,0);
                return(-1);
            }
            if (j == 1)
                freespace(assoc);

            /* Save the catalogues */

            if (j == 1) {
                fname = cpl_strdup(cpl_frame_get_filename(tmpl));
                vimos_std_product_name(fname,SIMPLE_CAT,cs.prettynames,i+1,
                                       bname);
                freespace(fname);
            } else {
                strcpy(bname,
                       cpl_frame_get_filename((ps.product_frames_cats)[i]));
            }
            if (vimos_std_save_cat((ps.sci_cats)[j-1],framelist,parlist,
                                   frm,isfirst,VIMOS_PRO_OBJCAT_STD,
                                   bname,vimos_names[j-1],photosys,
                                   ps.product_frames_cats+i) != CASU_OK) {
                cpl_msg_error(fctid,"Unable to save product %s[%d]",bname,j);
                cpl_frameset_delete(chiplist);
                vimos_std_tidy(&ps,0);
                return(-1);
            }

            /* Save the matched standards catalogues if you want to  */

            if (cs.savemstd) {
                if (j == 1) {
                    fname = cpl_strdup(cpl_frame_get_filename(tmpl));
                    vimos_std_product_name(fname,MSTDS_ASTROM,cs.prettynames,
                                           i+1,bname);
                    freespace(fname);
                } else {
                    strcpy(bname,
                           cpl_frame_get_filename((ps.product_frames_mstd_a)[i]));
                }
                if (vimos_std_save_cat(ps.sci_mstd_a[j-1],framelist,parlist,
                                       frm,isfirst,VIMOS_PRO_MATCHSTD_ASTROM,
                                       bname,vimos_names[j-1],photosys,
                                       ps.product_frames_mstd_a+i) != CASU_OK) {
                    cpl_msg_error(fctid,"Unable to save product %s[%d]",
                                  bname,j);
                    cpl_frameset_delete(chiplist);
                    vimos_std_tidy(&ps,0);
                    return(-1);
                }
                if (j == 1) {
                    fname = cpl_strdup(cpl_frame_get_filename(tmpl));
                    vimos_std_product_name(fname,MSTDS_PHOTOM,cs.prettynames,
                                           i+1,bname);
                    freespace(fname);
                } else {
                    strcpy(bname,
                           cpl_frame_get_filename((ps.product_frames_mstd_p)[i]));
                }
                if (vimos_std_save_cat(ps.sci_mstd_p[j-1],framelist,parlist,
                                       frm,isfirst,VIMOS_PRO_MATCHSTD_PHOTOM,
                                       bname,vimos_names[j-1],photosys,
                                       ps.product_frames_mstd_p+i) != CASU_OK) {
                    cpl_msg_error(fctid,"Unable to save product %s[%d]",
                                  bname,j);
                    cpl_frameset_delete(chiplist);
                    vimos_std_tidy(&ps,0);
                    return(-1);
                }
            }
        }
        cpl_frameset_delete(chiplist);
        vimos_std_tidy(&ps,1);
    }

    /* Get out of here */

    vimos_std_tidy(&ps,0);
    return(0);
}

/*---------------------------------------------------------------------------*/
/**
    \par Name:
        vimos_std_save_simple
    \par Purpose:
        Save the simple image products
    \par Description:
        An extension of a simple image product is saved here
    \par Language:
        C
    \param obj
        The casu_fits structure for the image to be saved
    \param framelist
        The input recipe frameset
    \param parlist
        The input recipe parameter list
    \param template
        A template to be used in the cpl saving routine
    \param isfirst
        Set of this is the first extension to be written to the file
    \param tag
        The product tag for the saved file
    \param fname
        The output file name
    \param cname
        The detector name
    \param assoc
        The name of the associated files for the simple images
    \param photosys
        The photometric system
    \param product_frame
        The output product frame
    \retval CASU_OK if everything is ok
    \retval CASU_FATAL if something failed
    \author
        Jim Lewis, CASU
 */
/*---------------------------------------------------------------------------*/

static int vimos_std_save_simple(casu_fits *obj, cpl_frameset *framelist,
                                 cpl_parameterlist *parlist, 
                                 cpl_frame *template, int isfirst,
                                 const char *tag, char *fname, char *cname,
                                 char *assoc, char *photosys,
                                 cpl_frame **product_frame) {
    cpl_propertylist *plist;
    int isdummy;
    float texp;
    char filt[32];
    const char *fctid = "vimos_std_save_simple";

    /* Get some information about this guy */

    isdummy = (casu_fits_get_status(obj) != CASU_OK);

    /* If we need to make a PHU then do that now based on the first frame
       in the input frame list. Get rid of the file if it already exists */

    if (isfirst) {
        if (access(fname,F_OK)) 
            remove(fname);

        /* Create a new product frame object and define some tags */

        *product_frame = cpl_frame_new();
        cpl_frame_set_filename(*product_frame,fname);

        /* Tag the product */

        cpl_frame_set_tag(*product_frame,tag);
        cpl_frame_set_type(*product_frame,CPL_FRAME_TYPE_IMAGE);
        cpl_frame_set_group(*product_frame,CPL_FRAME_GROUP_PRODUCT);
        cpl_frame_set_level(*product_frame,CPL_FRAME_LEVEL_FINAL);

        /* Set some PhaseIII parameters */

        plist = casu_fits_get_phu(obj);
        cpl_propertylist_update_string(plist,"RADECSYS","ICRS");
        cpl_propertylist_update_string(plist,"ORIGIN","ESO-PARANAL");
        cpl_propertylist_set_comment(plist,"ORIGIN",
                                     "European Southern Observatory");
        cpl_propertylist_update_string(plist,"TELESCOP","ESO-VLT-U3");
        cpl_propertylist_set_comment(plist,"TELESCOP","ESO telescope name");
        cpl_propertylist_update_string(plist,"INSTRUME","VIMOS");
        cpl_propertylist_set_comment(plist,"INSTRUME","Instrument used");
        cpl_propertylist_update_string(plist,"OBSTECH","IMAGE");
        cpl_propertylist_set_comment(plist,"OBSTECH","Observation Technique");
        cpl_propertylist_update_string(plist,"IMATYPE","PAWPRINT");
        cpl_propertylist_update_bool(plist,"ISAMP",1);
        cpl_propertylist_set_comment(plist,"ISAMP",
                                     "TRUE if image represents partially sampled sky");
        cpl_propertylist_update_bool(plist,"SINGLEXP",1);
        cpl_propertylist_set_comment(plist,"SINGLEXP",
                                     "TRUE if resulting from a single exposure");
        cpl_propertylist_update_string(plist,"PROV1",
                                       cpl_propertylist_get_string(plist,"ARCFILE"));
        cpl_propertylist_set_comment(plist,"PROV1","Originating raw science file");
        cpl_propertylist_update_int(plist,"NCOMBINE",1);
        cpl_propertylist_set_comment(plist,"NCOMBINE","Number of input images");
        if (strcmp(tag,VIMOS_PRO_SIMPLE_STD) == 0) {
            cpl_propertylist_update_string(plist,"PRODCATG","SCIENCE.MEFIMAGE");
            cpl_propertylist_set_comment(plist,"PRODCATG","Data product category");
            cpl_propertylist_update_string(plist,"ASSON1",assoc);
            cpl_propertylist_set_comment(plist,"ASSON1","Associated file");
            cpl_propertylist_update_string(plist,"ASSOC1","ANCILLARY.VARMAP");
            cpl_propertylist_set_comment(plist,"ASSOC1","Associated file category");
        } else {
            cpl_propertylist_erase(plist,"PRODCATG");
            cpl_propertylist_erase(plist,"ASSON1");
            cpl_propertylist_erase(plist,"ASSOC1");
        }
        vimos_pfits_get_filter(plist,filt);
        cpl_propertylist_update_string(plist,"FILTER",filt);
        cpl_propertylist_set_comment(plist,"FILTER","Filter used in observation"); 
        cpl_propertylist_erase_regexp(plist,"FILTER[0-9]+",0);
        vimos_pfits_get_exptime(plist,&texp);
        cpl_propertylist_update_double(plist,"EXPTIME",(double)texp);
        cpl_propertylist_update_double(plist,"TEXPTIME",(double)texp);
        cpl_propertylist_update_double(plist,"MJD-END",
                                       cpl_propertylist_get_double(plist,"MJD-OBS") +
                                       (double)texp/86400.0);
        cpl_propertylist_set_comment(plist,"MJD-END","End of observations");
        cpl_propertylist_update_string(plist,"PROG_ID",
                                       cpl_propertylist_get_string(plist,"ESO OBS PROG ID"));
        cpl_propertylist_set_comment(plist,"PROG_ID","ESO programme identification");
        cpl_propertylist_update_int(plist,"OBID1",
                                    cpl_propertylist_get_int(plist,"ESO OBS ID"));
        cpl_propertylist_set_comment(plist,"OBID1","Observation block ID");
        cpl_propertylist_update_bool(plist,"M_EPOCH",0);
        cpl_propertylist_set_comment(plist,"M_EPOCH",
                                     "TRUE if resulting from multiple epochs");
        cpl_propertylist_update_string(plist,"REFERENC","");
        cpl_propertylist_set_comment(plist,"REFERENC","Bibliographic Reference");
        if (cpl_propertylist_get_bool(casu_fits_get_ehu(obj),"ZPFUDGED")) {
            cpl_propertylist_update_string(plist,"FLUXCAL","UNCALIBRATED");
        } else {
            cpl_propertylist_update_string(plist,"FLUXCAL","ABSOLUTE");
        }
        cpl_propertylist_set_comment(plist,"FLUXCAL",
                                     "Certifies the validity of PHOTZP");
        cpl_propertylist_update_double(plist,"DIT",(double)texp);
        cpl_propertylist_set_comment(plist,"DIT","Detector integration time");

        /* Set up the PHU header */

        vimos_dfs_set_product_primary_header(plist,*product_frame,framelist,
                                             parlist,VIMOS_RECIPENAME,
                                             "PRO-1.15",template,1);

        /* 'Save' the PHU image */                         

        if (cpl_image_save(NULL,fname,CPL_TYPE_UCHAR,plist,CPL_IO_DEFAULT) != 
            CPL_ERROR_NONE) {
            cpl_msg_error(fctid,"Cannot save product PHU");
            cpl_frame_delete(*product_frame);
            return(CASU_FATAL);
        }
        cpl_frameset_insert(framelist,*product_frame);
    }

    /* Get the extension property list */

    plist = casu_fits_get_ehu(obj);
    if (isdummy)
        casu_dummy_property(plist);

    /* Add some PhaseIII stuff */

    cpl_propertylist_update_string(plist,"BUNIT","ADU");
    cpl_propertylist_set_comment(plist,"BUNIT","Physical unit of array values");
    cpl_propertylist_update_string(plist,"PHOTSYS",photosys);
    cpl_propertylist_set_comment(plist,"PHOTSYS","Photometric System");

    /* Fiddle with the header now */

    cpl_propertylist_update_string(plist,"EXTNAME",cname);
    vimos_dfs_set_product_exten_header(plist,*product_frame,framelist,parlist,
                                       VIMOS_RECIPENAME,"PRO-1.15",template);
    if (cpl_image_save(casu_fits_get_image(obj),fname,CPL_TYPE_FLOAT,plist,
                       CPL_IO_EXTEND) != CPL_ERROR_NONE) {
        cpl_msg_error(fctid,"Cannot save product image extension -- %s",
                      cpl_error_get_message());
        return(CASU_FATAL);
    }

    /* Get out of here */

    return(CASU_OK);
}

/*---------------------------------------------------------------------------*/
/**
    \par Name:
        vimos_std_save_cat
    \par Purpose:
        Save the simple image products
    \par Description:
        An extension of a simple image product is saved here
    \par Language:
        C
    \param obj
        The casu_tfits structure for the catalogue to be saved
    \param framelist
        The input recipe frameset
    \param parlist
        The input recipe parameter list
    \param template
        A template to be used in the cpl saving routine
    \param isfirst
        Set of this is the first extension to be written to the file
    \param tag
        The product tag for the saved file
    \param fname
        The output file name
    \param cname
        The detector name
    \param photosys
        The photometric system
    \param product_frame
        The output product frame
    \retval CASU_OK if everything is ok
    \retval CASU_FATAL if something failed
    \author
        Jim Lewis, CASU
 */
/*---------------------------------------------------------------------------*/

static int vimos_std_save_cat(casu_tfits *obj, cpl_frameset *framelist,
                              cpl_parameterlist *parlist, 
                              cpl_frame *template, int isfirst,
                              const char *tag, char *fname, char *cname,
                              char *photosys, cpl_frame **product_frame) {
    cpl_propertylist *plist;
    int isdummy;
    char filt[32];
    float texp;
    const char *fctid = "vimos_std_save_cat";

    /* Get some information about this guy */

    isdummy = (casu_tfits_get_status(obj) != CASU_OK);

    /* If we need to make a PHU then do that now based on the first frame
       in the input frame list. Get rid of the file if it already exists */

    if (isfirst) {
        if (access(fname,F_OK)) 
            remove(fname);

        /* Create a new product frame object and define some tags */

        *product_frame = cpl_frame_new();
        cpl_frame_set_filename(*product_frame,fname);

        /* Tag the output frame */

        cpl_frame_set_tag(*product_frame,tag);
        cpl_frame_set_type(*product_frame,CPL_FRAME_TYPE_IMAGE);
        cpl_frame_set_group(*product_frame,CPL_FRAME_GROUP_PRODUCT);
        cpl_frame_set_level(*product_frame,CPL_FRAME_LEVEL_FINAL);

        /* Phase III headers */

        plist = casu_tfits_get_phu(obj);
        if (strcmp(tag,VIMOS_PRO_OBJCAT_STD) == 0) {
            cpl_propertylist_update_string(plist,"RADECSYS","ICRS");
            cpl_propertylist_update_string(plist,"ORIGIN","ESO-PARANAL");
            cpl_propertylist_set_comment(plist,"ORIGIN",
                                         "European Southern Observatory");
            cpl_propertylist_update_string(plist,"TELESCOP","ESO-VLT-U3");
            cpl_propertylist_set_comment(plist,"TELESCOP","ESO telescope name");
            cpl_propertylist_update_string(plist,"INSTRUME","VIMOS");
            cpl_propertylist_set_comment(plist,"INSTRUME","Instrument used");
            cpl_propertylist_update_string(plist,"PRODCATG","SCIENCE.SRCTBL");
            cpl_propertylist_set_comment(plist,"PRODCATG","Data product category");
            cpl_propertylist_update_string(plist,"OBSTECH","IMAGE");
            cpl_propertylist_set_comment(plist,"OBSTECH","Observation Technique");
            cpl_propertylist_update_string(plist,"PROG_ID",
                                           cpl_propertylist_get_string(plist,"ESO OBS PROG ID"));
            cpl_propertylist_set_comment(plist,"PROG_ID","ESO programme identification");
            cpl_propertylist_update_int(plist,"OBID1",
                                        cpl_propertylist_get_int(plist,"ESO OBS ID"));
            cpl_propertylist_set_comment(plist,"OBID1","Observation block ID");
            cpl_propertylist_set_bool(plist,"M_EPOCH",0);
            cpl_propertylist_set_comment(plist,"M_EPOCH",
                                         "TRUE if resulting from multiple epochs");
            cpl_propertylist_update_string(plist,"REFERENC","");
            cpl_propertylist_set_comment(plist,"REFERENC","Bibliographic Reference");
            vimos_pfits_get_filter(plist,filt);
            cpl_propertylist_update_string(plist,"FILTER",filt);
            cpl_propertylist_set_comment(plist,"FILTER","Filter used in observation"); 
            cpl_propertylist_erase_regexp(plist,"FILTER[0-9]+",0);
            vimos_pfits_get_exptime(plist,&texp);
            cpl_propertylist_update_double(plist,"EXPTIME",(double)texp);
            cpl_propertylist_update_double(plist,"TEXPTIME",(double)texp);
            cpl_propertylist_update_double(plist,"MJD-END",
                                           cpl_propertylist_get_double(plist,"MJD-OBS") +
                                           (double)texp/86400.0);
            cpl_propertylist_set_comment(plist,"MJD-END","End of observations");

            cpl_propertylist_update_bool(plist,"M_EPOCH",0);
            cpl_propertylist_set_comment(plist,"M_EPOCH",
                                         "TRUE if resulting from multiple epochs");
            cpl_propertylist_update_string(plist,"PROV1",
                                           cpl_propertylist_get_string(plist,"ARCFILE"));
            cpl_propertylist_set_comment(plist,"PROV1",
                                         "Originating raw science file");
            cpl_propertylist_update_string(plist,"IMATYPE","PAWPRINT");
            cpl_propertylist_update_bool(plist,"ISAMP",1);
            cpl_propertylist_set_comment(plist,"ISAMP",
                                         "TRUE if image represents partially sampled sky");
            cpl_propertylist_erase(plist,"ASSON1");
            cpl_propertylist_erase(plist,"ASSOC1");
        }

        /* Set up output headers */

        vimos_dfs_set_product_primary_header(plist,*product_frame,framelist,
                                             parlist,VIMOS_RECIPENAME,
                                             "PRO-1.15",template,1);

        /* 'Save' the PHU image */                         

        if (cpl_image_save(NULL,fname,CPL_TYPE_UCHAR,plist,CPL_IO_DEFAULT) != 
            CPL_ERROR_NONE) {
            cpl_msg_error(fctid,"Cannot save product PHU");
            cpl_frame_delete(*product_frame);
            return(CASU_FATAL);
        }
        cpl_frameset_insert(framelist,*product_frame);
    }

    /* Get the extension property list */

    plist = casu_tfits_get_ehu(obj);
    if (isdummy)
        casu_dummy_property(plist);

    /* Fiddle with the header now */

    cpl_propertylist_update_string(plist,"PHOTSYS",photosys);
    cpl_propertylist_set_comment(plist,"PHOTSYS","Photometric System");
    cpl_propertylist_erase(plist,"BUNIT");
    cpl_propertylist_update_string(plist,"EXTNAME",cname);
    vimos_dfs_set_product_exten_header(plist,*product_frame,framelist,parlist,
                                       VIMOS_RECIPENAME,"PRO-1.15",template);
    if (cpl_table_save(casu_tfits_get_table(obj),NULL,plist,fname,
                       CPL_IO_EXTEND) != CPL_ERROR_NONE) {
        cpl_msg_error(fctid,"Cannot save product table extension -- %s",
                      cpl_error_get_message());
        return(CASU_FATAL);
    }

    /* Get out of here */

    return(CASU_OK);
}

/*---------------------------------------------------------------------------*/
/**
    \par Name:
        vimos_std_product_name
    \par Purpose:
        Set up an output product file name
    \par Description:
        An output file name is defined based on a template name,  a
        'predictable' name or a temporary file name.
    \par Language:
        C
    \param template
        If the pretty file name option is used or if this is a temporary
        file name, then the this will be used as a reference name.
    \param producttype
        The type of product you are writing out. These are enumerated above.
    \param nametype
        This is: 0 -> predictable names, 1 -> pretty names based on input
        file names or 2 -> temporary file names.
    \param fnumber
        If the predictable file names are going to be used, then this is 
        a number that is appended to a file name root.
    \param outfname
        The output file name
    \return
        Nothing
    \author
        Jim Lewis, CASU
 */
/*---------------------------------------------------------------------------*/

static void vimos_std_product_name(char *template, int producttype, 
                                   int nametype, int fnumber, char *outfname) {
    const char *esonames[] = {"exp_","exp_var_","exp_cat_","exp_mstd_a_",
                              "exp_mstd_p_"};
    const char *suffix[] = {"_ex","_ex_var","_ex_cat","_ex_mstd_a",
                            "_ex_mstd_p"};
    char *fname,*bname,*dot;

    /* If the name type is the ESO predictable sort, then it's easy. Just
       use the esonames defined above and append the correct number */

    switch (nametype) {
    case 0:
        (void)sprintf(outfname,"%s%d.fits",esonames[producttype],fnumber);
        break;

    /* If this is a temporary file, then just append tmp_ to the template
       name and return that */

    case 2:
        fname = cpl_strdup(template);
        bname = basename(fname);
        (void)sprintf(outfname,"tmp_%s",bname);
        freespace(fname);
        break;

    /* Ok, we want a pretty name... */

    case 1:
        fname = cpl_strdup(template);
        bname = basename(fname);
        (void)sprintf(outfname,"%s",bname);
        dot = strrchr(outfname,'.');
        (void)sprintf(dot,"%s.fits",suffix[producttype]);
        freespace(fname);
        break;

    /* something else ?? */

    default:
        (void)strcpy(outfname,"");
        break;
    }
    return;
}   

/**@}*/

/*---------------------------------------------------------------------------*/
/**
    \par Name:
        vimos_std_init
    \par Purpose:
        Initialise pointers in the global memory structure.
    \par Description:
        Initialise pointers in the global memory structure.
    \par Language:
        C
    \param ps
        The memory structure
    \return
        Nothing
    \author
        Jim Lewis, CASU
 */
/*---------------------------------------------------------------------------*/

static void vimos_std_init(memstruct *ps) {
    int i;

    /* Level 0 stuff */

    ps->labels = NULL;
    ps->labels2 = NULL;
    ps->master_bias = NULL;
    ps->master_dark = NULL;
    ps->master_twilight_flat = NULL;
    ps->master_conf = NULL;
    ps->master_fringe = NULL;
    ps->master_fringe_var = NULL;
    ps->readgain = NULL;
    ps->mask = NULL;
    ps->phottab = NULL;
    ps->tphottab = NULL;
    ps->science_frames = NULL;
    ps->product_frames_simple = NULL;
    ps->product_frames_vars = NULL;
    ps->product_frames_cats = NULL;
    ps->product_frames_mstd_a = NULL;
    ps->product_frames_mstd_p = NULL;
    ps->gaincors = NULL;
    ps->catpath_a = NULL;
    ps->catname_a = NULL;
    ps->catpath_p = NULL;
    ps->catname_p = NULL;
    ps->schlf_n = NULL;
    ps->schlf_s = NULL;
    ps->dummyfits = NULL;

    /* Level 1 stuff */

    ps->nscience = 0;
    for (i = 0; i < VIMOS_NEXTN; i++) {
        ps->sci_fits[i] = NULL;
        ps->sci_vars[i] = NULL;
        ps->sci_cats[i] = NULL;
        ps->sci_mstd_a[i] = NULL;
        ps->sci_mstd_p[i] = NULL;
    }

    /* Level 2 stuff */

    ps->fbias = NULL;
    ps->fdark = NULL;
    ps->fflat = NULL;
    ps->fconf = NULL;
    ps->ffringe = NULL;
    ps->ffringe_var = NULL;
}

/*---------------------------------------------------------------------------*/
/**
    \par Name:
        vimos_std_tidy
    \par Purpose:
        Free allocated workspace in the global memory structure
    \par Description:
        Free allocated workspace in the global memory structure. The tidy works
        on two levels. Level 1 is for items that are usually cleared up after
        each extension is processed. Level 2 is for cleaning up the whole
        recipe
    \par Language:
        C
    \param ps
        The memory structure
    \param level
        The level of the tidy to be done. 1: Tidy up after finishing an 
        extension, 0: Tidy up after finishing the recipe.
    \return
        Nothing
    \author
        Jim Lewis, CASU
 */
/*---------------------------------------------------------------------------*/

static void vimos_std_tidy(memstruct *ps, int level) {
    int i;

    /* Level 2 stuff */

    freefits(ps->fbias); 
    freefits(ps->fdark); 
    freefits(ps->fflat); 
    freefits(ps->fconf);
    freefits(ps->ffringe);
    freefits(ps->ffringe_var);

    if (level == 2) 
        return; 

    /* Level 1 stuff */

    ps->nscience = 0;
    for (i = 0; i < VIMOS_NEXTN; i++) {
        freefits(ps->sci_fits[i]);
        freefits(ps->sci_vars[i]);
        freetfits(ps->sci_cats[i]);
        freetfits(ps->sci_mstd_a[i]);
        freetfits(ps->sci_mstd_p[i]);
    }
    if (level == 1)
        return;
    
    /* Level 0 stuff */

    freespace(ps->labels);
    freespace(ps->labels2);
    freeframe(ps->master_bias);
    freeframe(ps->master_dark);
    freeframe(ps->master_twilight_flat);
    freeframe(ps->master_conf);
    freeframe(ps->master_fringe);
    freeframe(ps->master_fringe_var);
    freeframe(ps->readgain);
    freemask(ps->mask);
    freeframe(ps->phottab);
    freetable(ps->tphottab);
    freeframeset(ps->science_frames);
    freespace(ps->product_frames_simple);    /* NB: We only have to delete */
    freespace(ps->product_frames_cats);      /* the arrays and not the frames */
    freespace(ps->product_frames_vars);      /* as these get passed back */
    freespace(ps->product_frames_mstd_a);    /* to esorex */
    freespace(ps->product_frames_mstd_p);
    freespace(ps->gaincors);
    freespace(ps->catpath_a);
    freespace(ps->catname_a);
    freespace(ps->catpath_p);
    freespace(ps->catname_p);
    freeframe(ps->schlf_n);
    freeframe(ps->schlf_s);
    freefits(ps->dummyfits);
}

/*

$Log: vimos_ima_standard.c,v $
Revision 1.31  2015/11/27 12:15:33  jim
detabbed some lines

Revision 1.30  2015/11/19 12:44:44  jim
Fixed to remove offending keywords to keep ASG happy

Revision 1.29  2015/10/22 12:13:49  jim
A few touchups

Revision 1.28  2015/10/20 11:54:50  jim
removed landolt

Revision 1.27  2015/09/22 15:10:07  jim
fixed typo

Revision 1.26  2015/09/15 10:39:26  jim
Fixed so that variance arrays get same wcs as their science images

Revision 1.25  2015/09/11 09:48:16  jim
changed declaration of some parameters to ranges where appropriate

Revision 1.24  2015/08/07 13:07:15  jim
Fixed copyright to ESO

Revision 1.23  2015/07/29 09:19:53  jim
Fixed inconsistency in file naming in ugly mode

Revision 1.22  2015/07/02 12:30:15  jim
Fixed so that we get the correct value of FLUXCAL now...

Revision 1.21  2015/06/29 10:36:19  jim
photosys now comes from photcal table header

Revision 1.20  2015/06/08 09:46:31  jim
Added phase3 headers

Revision 1.19  2015/05/21 07:48:27  jim
Fixed bug where error was thrown if the photcal tab had more than one
extension

Revision 1.18  2015/05/13 12:00:07  jim
Added defringing

Revision 1.17  2015/05/01 09:02:22  jim
Modified to pass detector name information differently so that Mac compiler
doesn't gripe

Revision 1.16  2015/04/30 12:25:23  jim
Fixed manpage info

Revision 1.15  2015/03/13 10:22:59  jim
Fixed some compiler warnings

Revision 1.14  2015/03/10 13:37:14  jim
Another leak

Revision 1.13  2015/03/10 12:45:53  jim
More leaks

Revision 1.12  2015/03/10 11:06:39  jim
Fixed the way tidy works

Revision 1.11  2015/02/14 12:39:11  jim
Now allow the user to save matched standards catalogues

Revision 1.10  2015/01/29 12:10:23  jim
Modified comments, some command line arguments are now strings where it
makes sense to do so, some support routines moved to vimos_utils.c

Revision 1.9  2014/12/17 13:01:31  jim
Commented out testfrms on science images for the moment

Revision 1.8  2014/12/12 21:40:16  jim
changed so there is no inverse variance anymore

Revision 1.7  2014/12/11 12:27:28  jim
new version

Revision 1.6  2014/05/07 05:49:45  jim
Fixed product frame bug

Revision 1.5  2014/05/07 05:24:26  jim
Bug fixed where confidence map was still being read as integer

Revision 1.4  2014/05/06 15:55:28  jim
Fixed problem with cdssearch

Revision 1.3  2014/05/06 07:35:19  jim
modified to use new casu_getstds, to use readgain table and to create
modified confidence maps

Revision 1.2  2013/11/21 09:39:08  jim
detabbed

Revision 1.1  2013/11/04 05:55:17  jim
new entry


*/