comgendb.py 68.5 KB
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
#! /usr/bin/env python
# ==========================================================================
# Generate COMPTEL database from HEASARC archive
#
# Copyright (C) 2022 Juergen Knoedlseder
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
#
# ==========================================================================
import sys
import glob
import os
from distutils.spawn import find_executable
import gammalib
import ctools
from cscripts import modutils


# ============== #
# comgendb class #
# ============== #
class comgendb(ctools.cscript):
    """
    Generate COMPTEL database from HEASARC archive
    """
    # Constructor
    def __init__(self, *argv):
        """
        Constructor
        """
        # Initialise application by calling the base class constructor
        self._init_cscript(self.__class__.__name__, ctools.__version__, argv)

        # Initialise members
        self._evp_list = []
        self._oad_list = []
        self._tim_list = []
        self._xml_list = []

        # Return
        return

    # Private methods
    def _get_parameters(self):
        """
        Get parameters from parfile
        """
        # Query parameters
        self['archive'].string()
        self['refdata'].query()
        self['quality'].integer()
        self['download'].boolean()

        # Query ahead output model filename
        if self._read_ahead():
            self['dbase'].string()

        #  Write input parameters into logger
        self._log_parameters(gammalib.TERSE)

        # Return
        return

    def _download(self):
        """
        Download COMPTEL HEASARC archive
        """
        # Log header
        self._log_header1(gammalib.TERSE, 'Download HEASARC archive')

        # Check whether wget executable exists
        if find_executable('wget') is None:
            msg = ('"wget" command not found on system, unable to download '
                   'COMPTEL HEASARC archive.')
            raise RuntimeError(msg)

        # Set archive directory name
        dirname = gammalib.expand_env(self['archive'].string())

        # Build wget command string
        cmd = ('wget -r -N -nH --cut-dirs=4 -A "*.fits,*.fits.gz" -e robots=off '
               '-P %s -q https://heasarc.gsfc.nasa.gov/FTP/compton/data/comptel/' %
               (dirname))

        # Launch download
        os.system(cmd)

        # Return
        return

    def _get_phases(self):
        """
        Get available phases
        """
        # Set archive directory name
        dirname = gammalib.expand_env(self['archive'].string())

        # Raise an exception if the archive does not exist
        if not os.path.isdir(dirname):
            msg = ('Archive directory "%s" does not exist.' % dirname)
            raise RuntimeError(msg)

        # Set search pattern
        pattern = '%s/phase*' % (gammalib.expand_env(self['archive'].string()))

        # Get available phases
        phases = glob.glob(pattern)
        phases.sort()

        # Return phases
        return phases

    def _get_relpath(self, path, dest):
        """
        Get relative path with respect to dest

        Parameters
        ----------
        path : str
            Full path name
        dest : str
            Destination path name

        Returns
        -------
        relpath : str
            Relative path
        """
        # Split path and destination in segments
        path_split = path.split('/')
        dest_split = dest.split('/')

        # Get index of last agreement
        index = -1
        for i, segment in enumerate(dest_split):
            if segment == path_split[i]:
                index = i

        # Set relative path
        if index == -1:
            relpath = path
        else:
            relpath = ''
            for i in range(index+1,len(path_split)):
                if relpath != '':
                    relpath += '/'
                relpath += path_split[i]

        # Return relative path
        return relpath

    def _get_evp_list(self):
        """
        Get EVP list

        Returns
        -------
        evp_list : list of dict
            EVP database
        """
        # Initialse EVP list
        evp_list = []

        # Get available phases
        phases = self._get_phases()

        # Loop over phases
        for phase in phases:

            # Get available VPs
            vps = glob.glob('%s/vp*' % phase)
            vps.sort()

            # Loop over VPs
            for vp in vps:

                # Get EVPs for VP
                evps = self._get_evps_for_vp(vp)

                # Append EVPs to list
                evp_list.extend(evps)

        # Sort EVP list by start day
        evp_list = sorted(evp_list, key=lambda k: k['tjd_start'])

        # Return EVP list
        return evp_list

    def _get_evps_for_vp(self, vp):
        """
        Build EVP database entries for Viewing Period

        Parameters
        ----------
        vp : str
            VP path

        Returns
        -------
        evp_list : list of dict
            EVP database entries
        """
        # Get archive name and expanded path
        archive      = self['archive'].string()
        archive_path = gammalib.expand_env(archive)

        # Get VP name
        vpname = os.path.basename(vp)

        # Initialse EVP list
        evp_list = []

        # Get EVP files
        evps = glob.glob('%s/*evp.fits*' % vp)

        # Loop over all EVP files
        for evp in evps:

            # Set EVP filename
            evpname = archive+'/'+self._get_relpath(evp, archive_path).strip('.gz')

            # Try opening file
            try:
                fits = gammalib.GFits(evpname)
            except:
                self._log_string(gammalib.NORMAL, '*** Unable to open EVP file'
                                 ' "%s". Skip file.' % (evpname))
                continue

            # Get information from EVP file
            evp_dict = self._get_evp_info(evpname)

            # Skip file if it has a negative quality
            if evp_dict['quality'] < 0:
                self._log_string(gammalib.NORMAL, '*** EVP file "%s" has negative '
                                 'quality %d. Skip file.' % (evpname, evp_dict['quality']))
                continue

            # Skip file if the duration derived from the events is not consistent
            # with the duration derived from the header
            duration_evt = evp_dict['tjd_stop'] - evp_dict['tjd_start']
            duration_hdr = evp_dict['vieday']   - evp_dict['visday']
            difference   = abs(duration_evt-duration_hdr)
            if difference > 3:
                self._log_string(gammalib.NORMAL, '*** EVP file "%s" has inconsistent '
                                 'duration between events (%d days) and header '
                                 '(%d days). Skip file.' % \
                                 (evpname, duration_evt, duration_hdr))
                continue
            if duration_hdr > duration_evt:
                self._log_string(gammalib.NORMAL, '--- EVP file "%s" header indicates '
                                 'duration of %d days, but events cover only %d days.' % \
                                 (evpname, duration_hdr, duration_evt))
            elif duration_hdr < duration_evt:
                self._log_string(gammalib.NORMAL, '--- EVP file "%s" header indicates '
                                 'duration of %d days, but events cover %d days.' % \
                                 (evpname, duration_hdr, duration_evt))

            # Set VP
            evp_dict['vp'] = vpname

            # Append dictionary
            evp_list.append(evp_dict)

        # Sort EVP list by start day
        evp_list = sorted(evp_list, key=lambda k: k['tjd_start'])

        # Return EVP list
        return evp_list

    def _get_evp_info(self, evpname):
        """
        Build EVP database entry from EVP file

        Parameters
        ----------
        evpname : str
            EVP filename

        Returns
        -------
        evp_dict : dict
            EVP database entry
        """
        # Open EVP file
        fits = gammalib.GFits(evpname)

        # Get event table
        events  = fits.table(1)
        nevents = events.nrows()

        # Extract attributes for EVP file
        obs_id   = events.real('OBS_ID')
        object   = events.string('OBJECT')
        visday   = events.integer('VISDAY')
        vistim   = events.integer('VISTIM')
        vieday   = events.integer('VIEDAY')
        vietim   = events.integer('VIETIM')
        glon_scz = events.real('GLON_SCZ')
        glat_scz = events.real('GLAT_SCZ')
        verno    = events.integer('DSD_REP')
        quality  = events.integer('DSD_QUA')
        if events.has_card('TITLE'):
            title = events.string('TITLE')
        elif events.has_card('TITLE1') and events.has_card('TITLE2'):
            title = events.string('TITLE1') + events.string('TITLE2')
        dsd_id = '%s-%s-%d' % (events.string('DSD_SB'), events.string('DSTID'),
                               events.integer('DSD_NO'))

        # Get time columns
        tjd  = events['TJD']
        tics = events['TICS']

        # Get start and end time. Catch any errors since files may be corrupt.
        # In case of errors, use times from file header.
        try:
            tjd_start  = tjd[0]
            tics_start = tics[0]
            tjd_stop   = tjd[nevents-1]
            tics_stop  = tics[nevents-1]
        except:
            self._log_string(gammalib.NORMAL, '*** Corrupt EVP file "%s" encountered. '
                             'Set EVP quality to -200.' % (evpname))
            tjd_start  = visday
            tics_start = vistim
            tjd_stop   = vieday
            tics_stop  = vietim
            quality    = -200

        # Compute GTime of first and last event
        tstart = gammalib.com_time(tjd_start, tics_start)
        tstop  = gammalib.com_time(tjd_stop, tics_stop)

        # Check that start time is before stop time
        if tstart >= tstop:
            quality = -200
            gti     = gammalib.GGti()
            self._log_string(gammalib.NORMAL, '*** Corrupt EVP file "%s" encountered. '
                             'Start time %s is later than stop time %s. Set EVP '
                             'quality to -200.' % (evpname, tstart.utc(), tstop.utc()))

        # Set GTI for EVP
        else:
            gti = gammalib.GGti(tstart, tstop)

        # Build dictionary
        evp_dict = {'filename':   evpname,
                    'nevents':    nevents,
                    'obs_id':     obs_id,
                    'dsd_id':     dsd_id,
                    'object':     object,
                    'glon_scz':   glon_scz,
                    'glat_scz':   glat_scz,
                    'date_start': tstart.utc(),
                    'date_stop':  tstop.utc(),
                    'tjd_start':  tjd_start,
                    'tics_start': tics_start,
                    'tjd_stop':   tjd_stop,
                    'tics_stop':  tics_stop,
                    'tstart':     tstart,
                    'tstop':      tstop,
                    'visday':     visday,
                    'vistim':     vistim,
                    'vieday':     vieday,
                    'vietim':     vietim,
                    'gti':        gti,
                    'quality':    quality,
                    'verno':      verno,
                    'title':      title}

        # Close FITS file
        fits.close()

        # Correct quality flags for some files according to database reports
        if evp_dict['dsd_id'] == 'M-EVP-26342' or \
           evp_dict['dsd_id'] == 'M-EVP-24955' or \
           evp_dict['dsd_id'] == 'M-EVP-24963':
            self._log_string(gammalib.NORMAL, '*** Quality flag for "%s" changed '
                             'from %s to 50 according to database reports.' %
                             (evp_dict['filename'], evp_dict['quality']))
            evp_dict['quality'] = 50

        # Return information
        return evp_dict

    def _get_oad_list(self):
        """
        Get OAD list

        Returns
        -------
        oad_list : list of dict
            OAD database
        """
        # Initialse OAD list
        oad_list = []

        # Get available phases
        phases = self._get_phases()

        # Loop over phases
        for phase in phases:

            # Get available VPs
            vps = glob.glob('%s/vp*' % phase)
            vps.sort()

            # Loop over VPs
            for vp in vps:

                # Get OADs for VP
                oads = self._get_oads_for_vp(vp)

                # Append OADs to list
                oad_list.extend(oads)

        # Sort OAD list by start day
        oad_list = sorted(oad_list, key=lambda k: k['tjd_start'])

        # Return OAD list
        return oad_list

    def _get_oads_for_vp(self, vp):
        """
        Build OAD database entries for Viewing Period

        Parameters
        ----------
        vp : str
            VP path

        Returns
        -------
        oad_list : list of dict
            OAD database entries
        """
        # Get archive name and expanded path
        archive      = self['archive'].string()
        archive_path = gammalib.expand_env(archive)

        # Get VP name
        vpname = os.path.basename(vp)

        # Initialse OAD list
        oad_list = []

        # Get OAD files
        oads = glob.glob('%s/*oad.fits*' % vp)

        # Loop over all OAD files
        for oad in oads:

            # Set OAD filename
            oadname = archive+'/'+self._get_relpath(oad, archive_path).strip('.gz')

            # Try opening file
            try:
                fits = gammalib.GFits(oadname)
            except:
                self._log_string(gammalib.NORMAL, '*** Unable to open OAD file "%s". '
                                 'Skip file.' % (oadname))
                continue

            # Get information from OAD file
            oad_dict = self._get_oad_info(oadname)

            # Skip file if it has a negative quality
            if oad_dict['quality'] < 0:
                self._log_string(gammalib.NORMAL, '*** OAD file "%s" has quality %d. '
                                 'Skip file.' % (oadname, oad_dict['quality']))
                continue

            # Set VP
            oad_dict['vp'] = vpname

            # Append dictionary
            oad_list.append(oad_dict)

        # Sort OAD list by start day
        oad_list = sorted(oad_list, key=lambda k: k['tjd_start'])

        # Return OAD list
        return oad_list

    def _get_oad_info(self, oadname):
        """
        Build OAD database entry from OAD file

        Parameters
        ----------
        oadname : str
            OAD filename

        Returns
        -------
        oad_dict : dict
            OAD database entry
        """
        # Open OAD file
        fits = gammalib.GFits(oadname)

        # Get superpacket table
        records  = fits.table(1)
        nrecords = records.nrows()

        # Extract attributes for OAD file
        obs_id   = records.real('OBS_ID')
        object   = records.string('OBJECT')
        if records.has_card('GLON_SCZ'):
            glon_scz = records.real('GLON_SCZ')
        else:
            glon_scz = -1000.0
        if records.has_card('GLAT_SCZ'):
            glat_scz = records.real('GLAT_SCZ')
        else:
            glat_scz = -1000.0
        quality = records.integer('DSD_QUA')
        dsd_id  = '%s-%s-%d' % (records.string('DSD_SB'), records.string('DSTID'),
                                records.integer('DSD_NO'))

        # Get time columns
        tjd  = records['TJD']
        tics = records['TICS']

        # Get start and end time. Catch any errors since files may be corrupt.
        # In case of errors, use times from file header.
        try:
            tjd_start  = tjd[0]
            tics_start = tics[0]
            tjd_stop   = tjd[nrecords-1]
            tics_stop  = tics[nrecords-1]
        except:
            self._log_string(gammalib.NORMAL, '*** Corrupt OAD file "%s" encountered. '
                             'Set OAD quality to -200.' % (evpname))
            tjd_start  = records.integer('VISDAY')
            tics_start = records.integer('VISTIM')
            tjd_stop   = records.integer('VIEDAY')
            tics_stop  = records.integer('VIETIM')
            quality    = -200

        # Compute GTime of first and last superpacket
        tstart = gammalib.com_time(tjd_start, tics_start)
        tstop  = gammalib.com_time(tjd_stop, tics_stop)

        # Set GTI for OAD
        gti = gammalib.GGti(tstart, tstop)

        # Build dictionary
        oad_dict = {'filename':     oadname,
                    'superpackets': nrecords,
                    'obs_id':       obs_id,
                    'dsd_id':       dsd_id,
                    'object':       object,
                    'glon_scz':     glon_scz,
                    'glat_scz':     glat_scz,
                    'date_start':   tstart.utc(),
                    'date_stop':    tstop.utc(),
                    'tjd_start':    tjd_start,
                    'tics_start':   tics_start,
                    'tjd_stop':     tjd_stop,
                    'tics_stop':    tics_stop,
                    'tstart':       tstart,
                    'tstop':        tstop,
                    'gti':          gti,
                    'quality':      quality}

        # Close FITS file
        fits.close()

        # Return information
        return oad_dict

    def _get_tim_list(self):
        """
        Get TIM list

        Returns
        -------
        tim_list : list of dict
            TIM database
        """
        # Initialse TIM list
        tim_list = []

        # Get available phases
        phases = self._get_phases()

        # Loop over phases
        for phase in phases:

            # Get available VPs
            vps = glob.glob('%s/vp*' % phase)
            vps.sort()

            # Loop over VPs
            for vp in vps:

                # Get TIMs for VP
                tims = self._get_tims_for_vp(vp)

                # Append TIMs to list
                tim_list.extend(tims)

        # Sort TIM list by start day
        tim_list = sorted(tim_list, key=lambda k: k['tjd_start'])

        # Return TIM list
        return tim_list

    def _get_tims_for_vp(self, vp):
        """
        Build TIM database entries for Viewing Period

        Parameters
        ----------
        vp : str
            VP path

        Returns
        -------
        tim_list : list of dict
            TIM database entries
        """
        # Get archive name and expanded path
        archive      = self['archive'].string()
        archive_path = gammalib.expand_env(archive)

        # Get VP name
        vpname = os.path.basename(vp)

        # Initialse TIM list
        tim_list = []

        # Get TIM files
        tims = glob.glob('%s/*tim.fits*' % vp)

        # Loop over all TIM files
        for tim in tims:

            # Set TIM filename
            timname = archive+'/'+self._get_relpath(tim, archive_path).strip('.gz')

            # Try opening file
            try:
                fits = gammalib.GFits(timname)
            except:
                self._log_string(gammalib.NORMAL, '*** Unable to open TIM file "%s". '
                                 'Skip file.' % (timname))
                continue

            # Get information from TIM file
            tim_dict = self._get_tim_info(timname)

            # Skip file if it has a negative quality
            if tim_dict['quality'] < 0:
                self._log_string(gammalib.NORMAL, '*** TIM file "%s" has quality %d. '
                                 'Skip file.' % (timname, tim_dict['quality']))
                continue

            # Set VP
            tim_dict['vp'] = vpname

            # Append dictionary
            tim_list.append(tim_dict)

        # Sort OAD list by start day
        tim_list = sorted(tim_list, key=lambda k: k['tjd_start'])

        # Return TIM list
        return tim_list

    def _get_tim_info(self, timname):
        """
        Build TIM database entry from TIM file

        Parameters
        ----------
        timname : str
            TIM filename

        Returns
        -------
        tim_dict : dict
            TIM database entry
        """
        # Open TIM file
        fits = gammalib.GFits(timname)

        # Get superpacket table
        records  = fits.table(1)
        nrecords = records.nrows()

        # Extract attributes for TIM file
        obs_id   = records.real('OBS_ID')
        object   = records.string('OBJECT')
        visday   = records.integer('VISDAY')
        vistim   = records.integer('VISTIM')
        vieday   = records.integer('VIEDAY')
        vietim   = records.integer('VIETIM')
        glon_scz = records.real('GLON_SCZ')
        glat_scz = records.real('GLAT_SCZ')
        quality  = records.integer('DSD_QUA')
        dsd_id   = '%s-%s-%d' % (records.string('DSD_SB'), records.string('DSTID'),
                                 records.integer('DSD_NO'))

        # Get time columns
        start_tjd = records['START_TJD']
        start_tic = records['START_TIC']
        end_tjd   = records['END_TJD']
        end_tic   = records['END_TIC']

        # Get start and end time. Catch any errors since files may be corrupt.
        # In case of errors, use times from file header.
        try:
            tjd_start  = start_tjd[0]
            tics_start = start_tic[0]
            tjd_stop   = end_tjd[nrecords-1]
            tics_stop  = end_tic[nrecords-1]
        except:
            self._log_string(gammalib.NORMAL, '*** Corrupt TIM file "%s" encountered. '
                             'Set TIM quality to -200.' % (evpname))
            tjd_start  = visday
            tics_start = vistim
            tjd_stop   = vieday
            tics_stop  = vietim
            quality    = -200

        # Close FITS file
        fits.close()

        # Compute GTime of first and last superpacket
        tstart = gammalib.com_time(tjd_start, tics_start)
        tstop  = gammalib.com_time(tjd_stop, tics_stop)

        # Set GTI for TIM
        gti = gammalib.GGti(tstart, tstop)

        # Get telapse and ontime
        tim     = gammalib.GCOMTim(timname)
        telapse = tim.gti().telapse()
        ontime  = tim.gti().ontime()

        # Build dictionary
        tim_dict = {'filename':   timname,
                    'intervals':  nrecords,
                    'obs_id':     obs_id,
                    'dsd_id':     dsd_id,
                    'object':     object,
                    'glon_scz':   glon_scz,
                    'glat_scz':   glat_scz,
                    'date_start': tstart.utc(),
                    'date_stop':  tstop.utc(),
                    'tjd_start':  tjd_start,
                    'tics_start': tics_start,
                    'tjd_stop':   tjd_stop,
                    'tics_stop':  tics_stop,
                    'visday':     visday,
                    'vistim':     vistim,
                    'vieday':     vieday,
                    'vietim':     vietim,
                    'tstart':     tstart,
                    'tstop':      tstop,
                    'telapse':    telapse,
                    'ontime':     ontime,
                    'gti':        gti,
                    'quality':    quality}

        # Return information
        return tim_dict

    def _get_xml_list(self, evp_list, tim_list, oad_list):
        """
        Build XML database from EVP, TIM and OAD database

        Parameters
        ----------
        evp_list : list of dict
            EVP database
        tim_list : list of dict
            TIM database
        oad_list : list of dict
            OAD database

        Returns
        -------
        xml_list : list of dict
            XML database
        """
        # Initialse XML list
        xml_list = []

        # Get filtered TIM list
        filtered_tim_list = self._filter_tim_list(tim_list)

        # Get available phases
        phases = self._get_phases()

        # Loop over phases
        for phase in phases:

            # Get available VPs
            vps = glob.glob('%s/vp*' % phase)
            vps.sort()

            # Loop over VPs
            for vp in vps:

                # Get XML for VP
                xml = self._get_xml_for_vp(vp, evp_list, filtered_tim_list, oad_list)

                # Append XML to list
                if xml is not None:
                    xml_list.append(xml)

        # Sort XML list by start day
        xml_list = sorted(xml_list, key=lambda k: k['tjd_start'])

        # Return XML list
        return xml_list

    def _filter_tim_list(self, tim_list):
        """
        Removes all invalid TIMs from TIM database

        For a given VP only the TIMs with the maximum quality will be kept. This
        is needed since some of the TIM dataset cover periods well beyond a given
        VP, and these TIMs are marked with data quality 135. On the other hand,
        there are VPs with valid TIMs of data quality 135, hence we cannot simply
        filter on data quality.

        Parameters
        ----------
        tim_list : list of dict
            TIM database

        Returns
        -------
        filtered_tim_list : list of dict
            Filtered TIM database
        """
        # Initialise filtered TIM list
        filtered_tim_list = []

        # Get available phases
        phases = self._get_phases()

        # Loop over phases
        for phase in phases:

            # Get available VPs
            vps = glob.glob('%s/vp*' % phase)
            vps.sort()

            # Loop over VPs
            for vp in vps:

                # Get VP name
                vpname = os.path.basename(vp)

                # Get all TIMs for VP
                tims = list(filter(lambda k: k['vp'] == vpname, tim_list))

                # Continue if list is empty
                if len(tims) < 1:
                    continue

                # Get maximum quality of all TIMs in VP
                quality = max([tim['quality'] for tim in tims])

                # Get all TIMs for VP with maximum quality
                best_tims = list(filter(lambda k: k['quality'] == quality, tims))

                # Append these TIMs to the filtered list
                filtered_tim_list.extend(best_tims)

        # Return
        return filtered_tim_list

    def _get_xml_for_vp(self, vp, evp_list, tim_list, oad_list):
        """
        Build XML database entry for Viewing Period

        Parameters
        ----------
        vp : str
            Viewing Period directory
        evp_list : list of dict
            EVP database
        tim_list : list of dict
            TIM database
        oad_list : list of dict
            OAD database

        Returns
        -------
        xml_dict : dictionary
            XML database entry
        """
        # Get database directory
        path = self['dbase'].string()

        # Set VP name
        vpname  = os.path.basename(vp)

        # Get EVP for VP
        evp = self._get_evp(vp, evp_list)
        if evp is None:
            if vpname == 'vp0225_0' or \
               vpname == 'vp0303_5' or \
               vpname == 'vp0308_3' or \
               vpname == 'vp0311_3' or \
               vpname == 'vp0617_2' or \
               vpname == 'vp0617_4' or \
               vpname == 'vp0617_6' or \
               vpname == 'vp0619_5':
                self._log_string(gammalib.NORMAL, '--- No EVP file found for "%s due '
                                 'to Reboost". Skip VP.' % (vp))
            elif vpname == 'vp0229_3':
                self._log_string(gammalib.NORMAL, '--- No EVP file found for "%s due '
                                 'to Perseids". Skip VP.' % (vp))
            elif vpname == 'vp0833_7':
                self._log_string(gammalib.NORMAL, '--- No EVP file found for "%s due '
                                 'to Leonid Shower". Skip VP.' % (vp))
            else:
                self._log_string(gammalib.NORMAL, '*** No EVP file found for "%s". '
                                 'Skip VP.' % (vp))
            return None

        # Get TIM for EVP
        tim = self._get_tim(evp, tim_list)
        if tim is None:
            self._log_string(gammalib.NORMAL, '*** No TIM file found for "%s". '
                             'Skip VP.' % (vp))
            return None

        # Get OADs for EVP
        oads = self._get_oads(evp, oad_list)
        if len(oads) == 0:
            self._log_string(gammalib.NORMAL, '*** No OAD files found for "%s". '
                             'Skip VP.' % (vp))
            return None

        # Get oadnames and oad qualities
        oadnames     = [oad['filename'] for oad in oads]
        oadqualities = [oad['quality']  for oad in oads]

        # Build dictionary
        xml_dict = {'vp':          vpname,
                    'evpname':     evp['filename'],
                    'timname':     tim['filename'],
                    'oadnames':    oadnames,
                    'xmlname':     '%s/xml/%s.xml' % (path, vpname),
                    'nevents':     evp['nevents'],
                    'obs_id':      evp['obs_id'],
                    'object':      evp['object'],
                    'glon_scz':    evp['glon_scz'],
                    'glat_scz':    evp['glat_scz'],
                    'date_start':  tim['date_start'],
                    'date_stop':   tim['date_stop'],
                    'tjd_start':   tim['tjd_start'],
                    'tics_start':  tim['tics_start'],
                    'tjd_stop':    tim['tjd_stop'],
                    'tics_stop':   tim['tics_stop'],
                    'evp_tstart':  evp['tstart'],
                    'evp_tstop':   evp['tstop'],
                    'visday':      tim['visday'],
                    'vistim':      tim['vistim'],
                    'vieday':      tim['vieday'],
                    'vietim':      tim['vietim'],
                    'telapse':     tim['telapse'],
                    'ontime':      tim['ontime'],
                    'evp_verno':   evp['verno'],
                    'evp_quality': evp['quality'],
                    'tim_quality': tim['quality'],
                    'oad_quality': oadqualities}

        # Return XML list
        return xml_dict

    def _get_evp(self, vp, evp_list):
        """
        Get EVP database entry for Viewing Period

        Parameters
        ----------
        vp : str
            Viewing Period directory
        evp_list : list of dict
            EVP database

        Returns
        -------
        best_evp : dict
            EVP database entry
        """
        # Get quality flag
        qf = self['quality'].integer()

        # Get VP name
        vpname = os.path.basename(vp)

        # Get all EVPs for VP
        evps = list(filter(lambda k: k['vp'] == vpname, evp_list))

        # Initialise best EVP
        best_verno_evp   = None
        best_quality_evp = None
        best_verno       = 0
        best_quality     = 0

        # Initialise choosen flag
        choosen = False

        # First find EVP with target QF and highest version number
        for evp in evps:
            if evp['quality'] == qf:
                if evp['verno'] > best_verno:
                    choosen    = True
                    best_evp   = evp
                    best_verno = evp['verno']

        # Continue only if no EVP was found
        if not choosen:

            # Find EVP with highest version number
            for evp in evps:
                if evp['verno'] > best_verno:
                    best_verno     = evp['verno']
                    best_verno_evp = evp

            # Find EVP with best quality
            for evp in evps:
                if evp['quality'] > best_quality:
                    best_quality     = evp['quality']
                    best_quality_evp = evp

            # Initialise best EVP with best quality EVP
            best_evp = best_quality_evp

            # If highest version number is not the EVP with the best quality then
            # select the EVP with the highest version number
            if best_verno_evp != None and best_quality_evp != None:
                if best_verno_evp['filename'] != best_quality_evp['filename']:
                    if best_quality_evp['verno'] < best_verno:

                        # Signal issue
                        self._log_string(gammalib.NORMAL, '*** EVP "%s" with best '
                                         'quality has version %d which is not the '
                                         'highest version %d.' %
                                         (best_quality_evp['filename'],
                                          best_quality_evp['verno'],
                                          best_verno))

                        # If there are several EVPs with highest version then select
                        # the one with the best quality
                        evps = list(filter(lambda k: k['vp'] == vpname and k['verno'] == best_verno, evp_list))
                        if len(evps) > 1:
                            self._log_string(gammalib.NORMAL, '--- Several EVPs for %s '
                                             'have highest version' % (vpname))
                            best = 0
                            for evp in evps:
                                if evp['quality'] > best:
                                    best     = evp['quality']
                                    best_evp = evp
                            for evp in evps:
                                if best_evp['filename'] == evp['filename']:
                                    choose  = '+'
                                    choosen = True
                                else:
                                    choose = ' '
                                self._log_string(gammalib.NORMAL, '  %s "%s" (verno=%d, '
                                                 'quality=%d)' %
                                                 (choose,
                                                  evp['filename'],
                                                  evp['verno'],
                                                  evp['quality']))

                        # ... otherwise use the EVP with the best version number
                        else:
                            best_evp = best_verno_evp
                            choosen  = True
                            self._log_string(gammalib.NORMAL, '--- Choose "%s" (verno=%d, '
                                             'quality=%d)' %
                                             (best_evp['filename'],
                                              best_evp['verno'],
                                              best_evp['quality']))

            # Continue only if no file was choosen
            if not choosen:

                # If there are several EVPs with the best quality then select the one
                # with the highest version
                evps = list(filter(lambda k: k['vp'] == vpname and k['quality'] == best_quality, evp_list))
                if len(evps) > 1:
                    self._log_string(gammalib.NORMAL, '--- Several EVPs for %s have '
                                     'best quality' % (vpname))
                    best = 0
                    for evp in evps:
                        if evp['verno'] > best:
                            best     = evp['verno']
                            best_evp = evp
                    for evp in evps:
                        if best_evp['filename'] == evp['filename']:
                            choose = '+'
                        else:
                            choose = ' '
                        self._log_string(gammalib.NORMAL, '  %s "%s" (verno=%d, '
                                         'quality=%d)' %
                                         (choose,
                                          evp['filename'],
                                          evp['verno'],
                                          evp['quality']))

        # Return best EVP
        return best_evp

    def _get_tim(self, evp, tim_list):
        """
        Get TIM database entry for EVP database entry

        Parameters
        ----------
        evp : dict
            EVP dictionary
        tim_list : list of dict
            TIM database

        Returns
        -------
        best_tim : dict
            TIM database entry for EVP database entry
        """
        # Initialise maximum overlap
        max_overlap = 0.0
        min_dtabs   = 1.0e30
        best_tim    = None

        # Loop over all TIMs
        for tim in tim_list:

            # Compute time difference to EVP start time and stop time
            dtstart = evp['tstart'] - tim['tstart']
            dtstop  = evp['tstop']  - tim['tstop']

            # Compute absolute time difference
            dtabs = abs(dtstart) + abs(dtstop)

            # Keep smallest time difference
            if dtabs < min_dtabs:
                min_dtabs = dtabs
                best_tim  = tim

        # Return best TIM
        return best_tim

    def _get_oads(self, evp, oad_list):
        """
        Get OAD database entry for EVP database entry

        Parameters
        ----------
        evp : dict
            EVP dictionary
        oad_list : list of dict
            OAD database

        Returns
        -------
        oads : list of dict
            OAD database entries for EVP database entry
        """
        # Initialise list of OADs
        oads = []

        # Loop over all OADs
        for oad in oad_list:

            # Compute overlap between EVP and OAD
            overlap = evp['gti'].overlap(oad['tstart'], oad['tstop'])

            # If we have overlap then check if the file already exists
            if overlap > 0.0:

                # First check if OAD is already in OAD list. If this is the case,
                # and the current OAD corresponds to the VP of the EVP, then replace
                # the existing OAD by the current OAD since we prefer having the
                # OAD in the same folder as the EVP. Otherwise we keep the
                exists = False
                for i, oad_exist in enumerate(oads):
                    if oad_exist['dsd_id'] == oad['dsd_id']:
                        exists = True
                        if oad['vp'] == evp['vp']:
                            oads[i] = oad
                            break
                        else:
                            break

                # If the OAD does not yet exist then append it now
                if not exists:
                    oads.append(oad)

        # Sort OAD list by start day
        oads = sorted(oads, key=lambda k: k['tjd_start'])

        # Return OADs
        return oads

    def _check_xml_list(self, xml_list):
        """
        Check XML list against COMPASS database

        Returns
        -------
        xml_list : list of dict
            XML database with mode and status information
        """
        # Load COMPASS database
        database = self._get_compass_database()

        # Loop over XML list
        for xml_dict in xml_list:

            # Add mode and status to XML list
            xml_dict['mode']   = '???'
            xml_dict['status'] = 'unknown'

            # Continue only if there are entries
            if len(database) > 0:

                # Find VP in COMPASS database
                compass = None
                for entry in database:
                    if entry['vp'] == xml_dict['vp']:
                        compass = entry
                        break

                # Signal if VP was not found in COMPASS database
                if compass == None:
                    xml_dict['status'] = 'not found'
                    self._log_string(gammalib.NORMAL, '--- VP "%s" not found in COMPASS '
                                     'database.' % (xml_dict['vp']))
                    continue

                # Set mode and status
                xml_dict['mode']   = compass['mode']
                xml_dict['status'] = 'found'

                # Check EVP filename
                evp = os.path.basename(xml_dict['evpname'])[1:].rstrip('_evp.fits')
                if evp != compass['evp']:
                    self._log_string(gammalib.NORMAL, '--- VP "%s": EVP "%s" in COMPASS '
                                     'database differs from EVP "%s" in XML database.' %
                                     (xml_dict['vp'], compass['evp'], evp))

                # Check TIM filename
                tim = os.path.basename(xml_dict['timname'])[1:].rstrip('_tim.fits')
                if tim != compass['tim']:
                    self._log_string(gammalib.NORMAL, '--- VP "%s": TIM "%s" in COMPASS '
                                     'database differs from TIM "%s" in XML database.' %
                                     (xml_dict['vp'], compass['tim'], tim))

        # Return
        return xml_list

    def _get_compass_database(self):
        """
        Get COMPASS database

        Returns
        -------
        database : list of dict
            COMPASS database
        """
        # Initialise database
        database = []

        # Continue only if database was specified
        if self['refdata'].is_valid():

            # Read ASCII file
            f = open(gammalib.expand_env(self['refdata'].filename().url()), 'r')
            for line in f:

                # Skip comment lines
                if line[0:1] == 'C':
                    continue

                # Format VP
                vp = ('vp%06.1f' % (float(line[1:6]))).replace('.', '_')

                # Extract fields
                record = {'vp':   vp,
                          'evp':  gammalib.strip_whitespace(line[13:19]),
                          'tim':  gammalib.strip_whitespace(line[21:27]),
                          'oad':  gammalib.strip_whitespace(line[29:35]),
                          'mode': gammalib.strip_whitespace(line[66:70])}

                # Append record to database
                database.append(record)

        # Return database
        return database

    def _create_dbase_dirs(self):
        """
        Create database directory structure
        """
        # Get database directory
        path = self['dbase'].string()

        # Create database directory
        try:
            os.makedirs(gammalib.expand_env(path))
        except OSError:
            self._log_string(gammalib.NORMAL, '--- Directory "%s" exists' % path)
        try:
            os.makedirs('%s/xml' % gammalib.expand_env(path))
        except OSError:
            self._log_string(gammalib.NORMAL, '--- Directory "%s/xml" exists' % path)
        try:
            os.makedirs('%s/tim' % gammalib.expand_env(path))
        except OSError:
            self._log_string(gammalib.NORMAL, '--- Directory "%s/tim" exists' % path)

        # Return
        return

    def _build_tim_file(self, xml_dict):
        """
        Build TIM file for XML database entry

        Parameters
        ----------
        xml_dict : dict
            XML database entry
        """
        # Get database directory
        path = self['dbase'].string()

        # Get TIM from database
        tim = gammalib.GCOMTim(xml_dict['timname'])

        # Extract GTIs
        gti_heasarc = tim.gti()

        # Get tstart and tstop from first and last event
        tstart = xml_dict['evp_tstart']
        tstop  = xml_dict['evp_tstop']

        # Kluge for VP vp0411_1 which overlaps with vp0411_5
        if xml_dict['vp'] == 'vp0411_1':
            tstop = gammalib.com_time(9769, 444782835)
            self._log_string(gammalib.NORMAL, '*** Stop date for "%s" changed from %s '
                             'to %s.' %
                             (xml_dict['vp'], xml_dict['evp_tstop'].utc(), tstop.utc()))

        # Initialise GTI
        gti = gammalib.GGti()

        # Select GTIs
        search_start = True
        for i in range(len(gti_heasarc)):

            # Case A: search for start
            if search_start:

                # If event start time is after GTI stop time then skip this GTI
                if tstart > gti_heasarc.tstop(i):
                    continue

                # ... otherwise stop searching for start and set first GTI
                else:
                    # Stop searching for start
                    search_start = False

                    # Get first GTI
                    if tstart < gti_heasarc.tstart(i):
                        t_start = gti_heasarc.tstart(i)
                        t_stop  = gti_heasarc.tstop(i)
                    else:
                        t_start = tstart
                        t_stop  = gti_heasarc.tstop(i)

                    # Append GTI
                    gti.append(t_start, t_stop)

            # Case B: search for stop
            else:

                # If event stop time after GTI stop time then and this GTI
                if tstop > gti_heasarc.tstop(i):
                    t_start = gti_heasarc.tstart(i)
                    t_stop  = gti_heasarc.tstop(i)
                    gti.append(t_start, t_stop)

                # ... otherwise, if the event stop time is before the GTI start
                # time then stop appending GTIs
                elif tstop < gti_heasarc.tstart(i):
                    break

                # ... otherwise append last GTI
                else:
                    t_start = gti_heasarc.tstart(i)
                    t_stop  = tstop
                    gti.append(t_start, t_stop)
                    break

        # Set new GTIs for TIM
        tim.gti(gti)

        # Set new TIM filename
        xml_dict['timname'] = '%s/tim/%s_tim.fits' % (path, xml_dict['vp'])

        # Save TIM
        tim.save(xml_dict['timname'], True)

        # Return
        return

    def _build_xml_file(self, xml_dict):
        """
        Build observation definition XML file for XML database entry

        Parameters
        ----------
        xml_dict : dict
            XML database entry
        """
        # Create XML object
        xml = gammalib.GXml()

        # Append observation list
        obslist = xml.append('observation_list title="observation list"')

        # Append observation
        obs = obslist.append('observation name="%s" id="%s" instrument="COM"' % \
                             (xml_dict['object'], xml_dict['vp']))

        # Append EVP file
        obs.append('parameter name="EVP" file="%s"' % (xml_dict['evpname']))

        # Append TIM file
        obs.append('parameter name="TIM" file="%s"' % (xml_dict['timname']))

        # Append OAD files
        for oadname in xml_dict['oadnames']:
            obs.append('parameter name="OAD" file="%s"' % (oadname))

        # Save XML file
        xml.save(xml_dict['xmlname'])

        # Return
        return

    def _check_database(self, xml_list):
        """
        Check database

        Parameters
        ----------
        xml_list : list of dict
            XML database
        """
        # Determine number of database entries
        nrows = len(xml_list)

        # Check that stop dates are after start dates
        for i in range(nrows):
            tstart = gammalib.GTime()
            tstop  = gammalib.GTime()
            tstart.utc(xml_list[i]['date_start'])
            tstop.utc(xml_list[i]['date_stop'])
            if tstart > tstop:
                self._log_string(gammalib.NORMAL, '*** Start date %s of VP %s later '
                                 'than stop date %s.' %
                                 (xml_list[i]['date_start'],
                                  xml_list[i]['vp'],
                                  xml_list[i]['date_stop']))

        # Check that stop dates of VP is before start date of next VP. If this is
        # not the case, events may be double counted.
        for i in range(nrows-1):
            tstart = gammalib.GTime()
            tstop  = gammalib.GTime()
            tstop.utc(xml_list[i]['date_stop'])
            tstart.utc(xml_list[i+1]['date_start'])
            if tstop >= tstart:
                self._log_string(gammalib.NORMAL, '*** Stop date %s of VP %s later '
                                 'than start date %s of VP %s.' %
                                 (xml_list[i]['date_stop'],
                                  xml_list[i]['vp'],
                                  xml_list[i+1]['date_start'],
                                  xml_list[i+1]['vp']))

        # Return
        return

    def _build_database_file(self, evp_list, oad_list, tim_list, xml_list):
        """
        Build database file

        Parameters
        ----------
        evp_list : list of dict
            EVP database
        oad_list : list of dict
            OAD database
        tim_list : list of dict
            TIM database
        xml_list : list of dict
            XML database
        """
        # Setup filename
        filename = '%s/dbase.fits' % (self['dbase'].string())

        # Create FITS file
        fits = gammalib.GFits()

        # Get tables
        evp_table = self._build_evp_table(evp_list)
        oad_table = self._build_oad_table(oad_list)
        tim_table = self._build_tim_table(tim_list)
        xml_table = self._build_xml_table(xml_list)

        # Append tables
        fits.append(evp_table)
        fits.append(oad_table)
        fits.append(tim_table)
        fits.append(xml_table)

        # Save database
        fits.saveto(filename, True)

        # Close FITS file
        fits.close()

        # Return
        return

    def _build_evp_table(self, evp_list):
        """
        Build EVP FITS table

        Parameters
        ----------
        evp_list : list of dict
            EVP database

        Returns
        -------
        table : `~gammalib.GFitsBinTable`
            EVP FITS table
        """
        # Determine number of rows in table
        nrows = len(evp_list)

        # Create FITS table columns
        col_vp         = gammalib.GFitsTableStringCol('VP',         nrows, 9)
        col_object     = gammalib.GFitsTableStringCol('OBJECT',     nrows, 20)
        col_obs_id     = gammalib.GFitsTableStringCol('OBS_ID',     nrows, 9)
        col_dsd_id     = gammalib.GFitsTableStringCol('DSD_ID',     nrows, 15)
        col_glon_scz   = gammalib.GFitsTableFloatCol('GLON_SCZ',    nrows)
        col_glat_scz   = gammalib.GFitsTableFloatCol('GLAT_SCZ',    nrows)
        col_date_start = gammalib.GFitsTableStringCol('DATE_START', nrows, 20)
        col_date_stop  = gammalib.GFitsTableStringCol('DATE_STOP',  nrows, 20)
        col_tjd_start  = gammalib.GFitsTableShortCol('TJD_START',   nrows)
        col_tics_start = gammalib.GFitsTableLongCol('TICS_START',   nrows)
        col_tjd_stop   = gammalib.GFitsTableShortCol('TJD_STOP',    nrows)
        col_tics_stop  = gammalib.GFitsTableLongCol('TICS_STOP',    nrows)
        col_visday     = gammalib.GFitsTableShortCol('VISDAY',      nrows)
        col_vistim     = gammalib.GFitsTableLongCol('VISTIM',       nrows)
        col_vieday     = gammalib.GFitsTableShortCol('VIEDAY',      nrows)
        col_vietim     = gammalib.GFitsTableLongCol('VIETIM',       nrows)
        col_verno      = gammalib.GFitsTableShortCol('VERNO',       nrows)
        col_quality    = gammalib.GFitsTableShortCol('QUALITY',     nrows)
        col_evp        = gammalib.GFitsTableStringCol('EVP',        nrows, 60)
        col_nevents    = gammalib.GFitsTableLongCol('NEVENTS',      nrows)

        # Set column units
        col_glon_scz.unit('deg')
        col_glat_scz.unit('deg')
        col_tjd_start.unit('days')
        col_tics_start.unit('0.000125 s')
        col_tjd_stop.unit('days')
        col_tics_stop.unit('0.000125 s')
        col_visday.unit('days')
        col_vistim.unit('0.000125 s')
        col_vieday.unit('days')
        col_vietim.unit('0.000125 s')

        # Fill columns
        for i, evp_record in enumerate(evp_list):
            col_vp[i]         = evp_record['vp']
            col_object[i]     = evp_record['object']
            col_obs_id[i]     = '%.1f' % evp_record['obs_id']
            col_dsd_id[i]     = evp_record['dsd_id']
            col_glon_scz[i]   = evp_record['glon_scz']
            col_glat_scz[i]   = evp_record['glat_scz']
            col_date_start[i] = evp_record['date_start']
            col_date_stop[i]  = evp_record['date_stop']
            col_tjd_start[i]  = evp_record['tjd_start']
            col_tics_start[i] = evp_record['tics_start']
            col_tjd_stop[i]   = evp_record['tjd_stop']
            col_tics_stop[i]  = evp_record['tics_stop']
            col_visday[i]     = evp_record['visday']
            col_vistim[i]     = evp_record['vistim']
            col_vieday[i]     = evp_record['vieday']
            col_vietim[i]     = evp_record['vietim']
            col_verno[i]      = evp_record['verno']
            col_quality[i]    = evp_record['quality']
            col_evp[i]        = evp_record['filename']
            col_nevents[i]    = evp_record['nevents']

        # Create FITS table
        table = gammalib.GFitsBinTable()

        # Append columns to table
        table.append(col_vp)
        table.append(col_object)
        table.append(col_obs_id)
        table.append(col_dsd_id)
        table.append(col_glon_scz)
        table.append(col_glat_scz)
        table.append(col_date_start)
        table.append(col_date_stop)
        table.append(col_tjd_start)
        table.append(col_tics_start)
        table.append(col_tjd_stop)
        table.append(col_tics_stop)
        table.append(col_visday)
        table.append(col_vistim)
        table.append(col_vieday)
        table.append(col_vietim)
        table.append(col_verno)
        table.append(col_quality)
        table.append(col_evp)
        table.append(col_nevents)

        # Set extension name
        table.extname('EVP')

        # Return table
        return table

    def _build_oad_table(self, oad_list):
        """
        Build OAD FITS table

        Parameters
        ----------
        oad_list : list of dict
            OAD database

        Returns
        -------
        table : `~gammalib.GFitsBinTable`
            OAD FITS table
        """
        # Determine number of rows in table
        nrows = len(oad_list)

        # Create FITS table columns
        col_vp           = gammalib.GFitsTableStringCol('VP',         nrows, 9)
        col_object       = gammalib.GFitsTableStringCol('OBJECT',     nrows, 20)
        col_obs_id       = gammalib.GFitsTableStringCol('OBS_ID',     nrows, 9)
        col_dsd_id       = gammalib.GFitsTableStringCol('DSD_ID',     nrows, 15)
        col_glon_scz     = gammalib.GFitsTableFloatCol('GLON_SCZ',    nrows)
        col_glat_scz     = gammalib.GFitsTableFloatCol('GLAT_SCZ',    nrows)
        col_date_start   = gammalib.GFitsTableStringCol('DATE_START', nrows, 20)
        col_date_stop    = gammalib.GFitsTableStringCol('DATE_STOP',  nrows, 20)
        col_tjd_start    = gammalib.GFitsTableShortCol('TJD_START',   nrows)
        col_tics_start   = gammalib.GFitsTableLongCol('TICS_START',   nrows)
        col_tjd_stop     = gammalib.GFitsTableShortCol('TJD_STOP',    nrows)
        col_tics_stop    = gammalib.GFitsTableLongCol('TICS_STOP',    nrows)
        col_quality      = gammalib.GFitsTableShortCol('QUALITY',     nrows)
        col_oad          = gammalib.GFitsTableStringCol('OAD',        nrows, 60)
        col_superpackets = gammalib.GFitsTableLongCol('SUPERPACKETS', nrows)

        # Set column units
        col_glon_scz.unit('deg')
        col_glat_scz.unit('deg')
        col_tjd_start.unit('days')
        col_tics_start.unit('0.000125 s')
        col_tjd_stop.unit('days')
        col_tics_stop.unit('0.000125 s')

        # Fill columns
        for i, oad_record in enumerate(oad_list):
            col_vp[i]           = oad_record['vp']
            col_object[i]       = oad_record['object']
            col_obs_id[i]       = '%.1f' % oad_record['obs_id']
            col_dsd_id[i]       = oad_record['dsd_id']
            col_glon_scz[i]     = oad_record['glon_scz']
            col_glat_scz[i]     = oad_record['glat_scz']
            col_date_start[i]   = oad_record['date_start']
            col_date_stop[i]    = oad_record['date_stop']
            col_tjd_start[i]    = oad_record['tjd_start']
            col_tics_start[i]   = oad_record['tics_start']
            col_tjd_stop[i]     = oad_record['tjd_stop']
            col_tics_stop[i]    = oad_record['tics_stop']
            col_quality[i]      = oad_record['quality']
            col_oad[i]          = oad_record['filename']
            col_superpackets[i] = oad_record['superpackets']

        # Create FITS table
        table = gammalib.GFitsBinTable()

        # Append columns to table
        table.append(col_vp)
        table.append(col_object)
        table.append(col_obs_id)
        table.append(col_dsd_id)
        table.append(col_glon_scz)
        table.append(col_glat_scz)
        table.append(col_date_start)
        table.append(col_date_stop)
        table.append(col_tjd_start)
        table.append(col_tics_start)
        table.append(col_tjd_stop)
        table.append(col_tics_stop)
        table.append(col_quality)
        table.append(col_oad)
        table.append(col_superpackets)

        # Set extension name
        table.extname('OAD')

        # Return table
        return table

    def _build_tim_table(self, tim_list):
        """
        Build TIM FITS table

        Parameters
        ----------
        tim_list : list of dict
            TIM database

        Returns
        -------
        table : `~gammalib.GFitsBinTable`
            TIM FITS table
        """
        # Determine number of rows in table
        nrows = len(tim_list)

        # Create FITS table columns
        col_vp         = gammalib.GFitsTableStringCol('VP',         nrows, 9)
        col_object     = gammalib.GFitsTableStringCol('OBJECT',     nrows, 20)
        col_obs_id     = gammalib.GFitsTableStringCol('OBS_ID',     nrows, 9)
        col_dsd_id     = gammalib.GFitsTableStringCol('DSD_ID',     nrows, 15)
        col_glon_scz   = gammalib.GFitsTableFloatCol('GLON_SCZ',    nrows)
        col_glat_scz   = gammalib.GFitsTableFloatCol('GLAT_SCZ',    nrows)
        col_date_start = gammalib.GFitsTableStringCol('DATE_START', nrows, 20)
        col_date_stop  = gammalib.GFitsTableStringCol('DATE_STOP',  nrows, 20)
        col_tjd_start  = gammalib.GFitsTableShortCol('TJD_START',   nrows)
        col_tics_start = gammalib.GFitsTableLongCol('TICS_START',   nrows)
        col_tjd_stop   = gammalib.GFitsTableShortCol('TJD_STOP',    nrows)
        col_tics_stop  = gammalib.GFitsTableLongCol('TICS_STOP',    nrows)
        col_telapse    = gammalib.GFitsTableDoubleCol('TELAPSE',    nrows)
        col_ontime     = gammalib.GFitsTableDoubleCol('ONTIME',     nrows)
        col_quality    = gammalib.GFitsTableShortCol('QUALITY',     nrows)
        col_tim        = gammalib.GFitsTableStringCol('TIM',        nrows, 60)
        col_intervals  = gammalib.GFitsTableLongCol('INTERVALS',    nrows)

        # Set column units
        col_glon_scz.unit('deg')
        col_glat_scz.unit('deg')
        col_tjd_start.unit('days')
        col_tics_start.unit('0.000125 s')
        col_tjd_stop.unit('days')
        col_tics_stop.unit('0.000125 s')
        col_telapse.unit('s')
        col_ontime.unit('s')

        # Fill columns
        for i, tim_record in enumerate(tim_list):
            col_vp[i]         = tim_record['vp']
            col_object[i]     = tim_record['object']
            col_obs_id[i]     = '%.1f' % tim_record['obs_id']
            col_dsd_id[i]     = tim_record['dsd_id']
            col_glon_scz[i]   = tim_record['glon_scz']
            col_glat_scz[i]   = tim_record['glat_scz']
            col_date_start[i] = tim_record['date_start']
            col_date_stop[i]  = tim_record['date_stop']
            col_tjd_start[i]  = tim_record['tjd_start']
            col_tics_start[i] = tim_record['tics_start']
            col_tjd_stop[i]   = tim_record['tjd_stop']
            col_tics_stop[i]  = tim_record['tics_stop']
            col_telapse[i]    = tim_record['telapse']
            col_ontime[i]     = tim_record['ontime']
            col_quality[i]    = tim_record['quality']
            col_tim[i]        = tim_record['filename']
            col_intervals[i]  = tim_record['intervals']

        # Create FITS table
        table = gammalib.GFitsBinTable()

        # Append columns to table
        table.append(col_vp)
        table.append(col_object)
        table.append(col_obs_id)
        table.append(col_dsd_id)
        table.append(col_glon_scz)
        table.append(col_glat_scz)
        table.append(col_date_start)
        table.append(col_date_stop)
        table.append(col_tjd_start)
        table.append(col_tics_start)
        table.append(col_tjd_stop)
        table.append(col_tics_stop)
        table.append(col_telapse)
        table.append(col_ontime)
        table.append(col_quality)
        table.append(col_tim)
        table.append(col_intervals)

        # Set extension name
        table.extname('TIM')

        # Return table
        return table

    def _build_xml_table(self, xml_list):
        """
        Build XML FITS table

        Parameters
        ----------
        xml_list : list of dict
            XML database

        Returns
        -------
        table : `~gammalib.GFitsBinTable`
            XML FITS table
        """
        # Determine number of rows in table
        nrows = len(xml_list)

        # Create FITS table columns
        col_vp          = gammalib.GFitsTableStringCol('VP',         nrows, 9)
        col_object      = gammalib.GFitsTableStringCol('OBJECT',     nrows, 20)
        col_obs_id      = gammalib.GFitsTableStringCol('OBS_ID',     nrows, 9)
        col_glon_scz    = gammalib.GFitsTableFloatCol('GLON_SCZ',    nrows)
        col_glat_scz    = gammalib.GFitsTableFloatCol('GLAT_SCZ',    nrows)
        col_date_start  = gammalib.GFitsTableStringCol('DATE_START', nrows, 20)
        col_date_stop   = gammalib.GFitsTableStringCol('DATE_STOP',  nrows, 20)
        col_tjd_start   = gammalib.GFitsTableShortCol('TJD_START',   nrows)
        col_tics_start  = gammalib.GFitsTableLongCol('TICS_START',   nrows)
        col_tjd_stop    = gammalib.GFitsTableShortCol('TJD_STOP',    nrows)
        col_tics_stop   = gammalib.GFitsTableLongCol('TICS_STOP',    nrows)
        col_visday      = gammalib.GFitsTableShortCol('VISDAY',      nrows)
        col_vistim      = gammalib.GFitsTableLongCol('VISTIM',       nrows)
        col_vieday      = gammalib.GFitsTableShortCol('VIEDAY',      nrows)
        col_vietim      = gammalib.GFitsTableLongCol('VIETIM',       nrows)
        col_telapse     = gammalib.GFitsTableDoubleCol('TELAPSE',    nrows)
        col_ontime      = gammalib.GFitsTableDoubleCol('ONTIME',     nrows)
        col_evp_verno   = gammalib.GFitsTableShortCol('EVP_VERNO',   nrows)
        col_evp_quality = gammalib.GFitsTableShortCol('EVP_QUALITY', nrows)
        col_tim_quality = gammalib.GFitsTableShortCol('TIM_QUALITY', nrows)
        col_oad_quality = gammalib.GFitsTableShortCol('OAD_QUALITY', nrows, 43)
        col_xml         = gammalib.GFitsTableStringCol('XML',        nrows, 60)
        col_evp         = gammalib.GFitsTableStringCol('EVP',        nrows, 60)
        col_tim         = gammalib.GFitsTableStringCol('TIM',        nrows, 60)
        col_oad         = gammalib.GFitsTableStringCol('OAD',        nrows, 60, 43)
        col_nevents     = gammalib.GFitsTableLongCol('NEVENTS',      nrows)
        col_model       = gammalib.GFitsTableStringCol('MODE',       nrows, 8)

        # Set column units
        col_glon_scz.unit('deg')
        col_glat_scz.unit('deg')
        col_tjd_start.unit('days')
        col_tics_start.unit('0.000125 s')
        col_tjd_stop.unit('days')
        col_tics_stop.unit('0.000125 s')
        col_visday.unit('days')
        col_vistim.unit('0.000125 s')
        col_vieday.unit('days')
        col_vietim.unit('0.000125 s')
        col_telapse.unit('s')
        col_ontime.unit('s')

        # Fill columns
        for i, xml_record in enumerate(xml_list):
            col_vp[i]          = xml_record['vp']
            col_object[i]      = xml_record['object']
            col_obs_id[i]      = '%.1f' % xml_record['obs_id']
            col_glon_scz[i]    = xml_record['glon_scz']
            col_glat_scz[i]    = xml_record['glat_scz']
            col_date_start[i]  = xml_record['date_start']
            col_date_stop[i]   = xml_record['date_stop']
            col_tjd_start[i]   = xml_record['tjd_start']
            col_tics_start[i]  = xml_record['tics_start']
            col_tjd_stop[i]    = xml_record['tjd_stop']
            col_tics_stop[i]   = xml_record['tics_stop']
            col_visday[i]      = xml_record['visday']
            col_vistim[i]      = xml_record['vistim']
            col_vieday[i]      = xml_record['vieday']
            col_vietim[i]      = xml_record['vietim']
            col_telapse[i]     = xml_record['telapse']
            col_ontime[i]      = xml_record['ontime']
            col_evp_verno[i]   = xml_record['evp_verno']
            col_evp_quality[i] = xml_record['evp_quality']
            col_tim_quality[i] = xml_record['tim_quality']
            col_xml[i]         = xml_record['xmlname']
            col_evp[i]         = xml_record['evpname']
            col_tim[i]         = xml_record['timname']
            col_nevents[i]     = xml_record['nevents']
            for k, oad_quality in enumerate(xml_record['oad_quality']):
                col_oad_quality[i,k] = oad_quality
            for k, oadname in enumerate(xml_record['oadnames']):
                col_oad[i,k] = oadname
            mode = 'UNKNOWN'
            if xml_record['mode'] == 'STD':
                mode = 'STANDARD'
            elif xml_record['mode'] == 'S80':
                mode = 'SOLAR80'
            col_model[i] = mode

        # Create FITS table
        table = gammalib.GFitsBinTable()

        # Append columns to table
        table.append(col_vp)
        table.append(col_object)
        table.append(col_obs_id)
        table.append(col_glon_scz)
        table.append(col_glat_scz)
        table.append(col_date_start)
        table.append(col_date_stop)
        table.append(col_tjd_start)
        table.append(col_tics_start)
        table.append(col_tjd_stop)
        table.append(col_tics_stop)
        table.append(col_visday)
        table.append(col_vistim)
        table.append(col_vieday)
        table.append(col_vietim)
        table.append(col_telapse)
        table.append(col_ontime)
        table.append(col_nevents)
        table.append(col_evp_verno)
        table.append(col_evp_quality)
        table.append(col_tim_quality)
        table.append(col_oad_quality)
        table.append(col_xml)
        table.append(col_evp)
        table.append(col_tim)
        table.append(col_oad)

        # Set extension name
        table.extname('XML')

        # Return table
        return table


    # Public methods
    def process(self):
        """
        Process the script
        """
        # Get parameters
        self._get_parameters()

        # Optionally download COMPTEL HEASARC archive
        if self['download'].boolean():
            self._download()

        # Log header
        self._log_header1(gammalib.TERSE, 'Get list of EVP files')

        # Get EVP list
        self._evp_list = self._get_evp_list()

        # Log header
        self._log_header1(gammalib.TERSE, 'Get list of OAD files')

        # Get OAD list
        self._oad_list = self._get_oad_list()

        # Log header
        self._log_header1(gammalib.TERSE, 'Get list of TIM files')

        # Get TIM list
        self._tim_list = self._get_tim_list()

        # Log header
        self._log_header1(gammalib.TERSE, 'Generate list of XML files')

        # Get XML list
        xml_list = self._get_xml_list(self._evp_list, self._tim_list, self._oad_list)

        # Log header
        self._log_header1(gammalib.TERSE, 'Compare with COMPASS database')

        # Check XML list
        self._xml_list = self._check_xml_list(xml_list)

        # Return
        return

    def save(self):
        """ 
        Save database file
        """
        # Write header
        self._log_header1(gammalib.TERSE, 'Save database')

        # Create database directory structure
        self._create_dbase_dirs()

        # Generate TIM and XML files
        for xml in self._xml_list:
            self._build_tim_file(xml)
            self._build_xml_file(xml)

        # Check database
        self._check_database(self._xml_list)

        # Build database file
        self._build_database_file(self._evp_list, self._oad_list,
                                  self._tim_list, self._xml_list)

        # Return
        return


# ======================== #
# Main routine entry point #
# ======================== #
if __name__ == '__main__':

    # Create instance of application
    app = comgendb(sys.argv)

    # Execute application
    app.execute()