GTools.cpp 57.2 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
/***************************************************************************
 *                       GTools.cpp - GammaLib tools                       *
 * ----------------------------------------------------------------------- *
 *  copyright (C) 2008-2016 by 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/>.  *
 *                                                                         *
 ***************************************************************************/
/**
 * @file GTools.cpp
 * @brief Gammalib tools implementation
 * @author Juergen Knoedlseder
 */

/* __ Includes ___________________________________________________________ */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <unistd.h>        // access() functions
#include <fcntl.h>         // fcntl() functions
#include <sys/stat.h>
#include <sys/time.h>      // timeval
#include <sys/select.h>    // select() function
#include <sys/types.h>
#include <sys/socket.h>    // recv() function
#include <pwd.h>
#include <cmath>
#include <cfloat>
#include <cctype>
#include <cstdlib>         // std::getenv() function
#include <cstring>         // std::strlen() function
#include <iostream>
#include <sstream>
#include <algorithm>
#include "GTools.hpp"
#include "GException.hpp"
#include "GFits.hpp"
#include "GEnergy.hpp"
#include "GFilename.hpp"
#include "GXmlElement.hpp"

/* __ Compile options ____________________________________________________ */

/* __ Function name definitions __________________________________________ */
#define G_XML2STRING                     "gammalib::xml2string(std::string&)"

/* __ Coding definitions _________________________________________________ */
#define G_PARFORMAT_LENGTH 29


/***********************************************************************//**
 * @brief Strip leading and trailing whitespace from string
 *
 * @param[in] arg String from which whitespace should be stripped.
 * @return String with stripped whitespace.
 ***************************************************************************/
std::string gammalib::strip_whitespace(const std::string& arg)
{
    // Return result
    return (strip_chars(arg, " "));
}


/***********************************************************************//**
 * @brief Strip leading and trailing character from string
 *
 * @param[in] arg String from which character should be stripped.
 * @param[in] chars Character(s) to be stripped.
 * @return String with stripped characters.
 ***************************************************************************/
std::string gammalib::strip_chars(const std::string& arg,
                                  const std::string& chars)
{
    // Initialise empty result string
    std::string result;

    // Continue only if argument is not empty
    if (!arg.empty()) {

        // Get start and stop
        std::string::size_type start = arg.find_first_not_of(chars);
        std::string::size_type stop  = arg.find_last_not_of(chars);

        // Continue only if start and stop are valid
        if (start != std::string::npos && stop != std::string::npos) {

            // Continue only if stop is larger then or equal to  start
            if (start <= stop) {
                result = arg.substr(start, stop-start+1);
            }

        } // endif: start and stop were valid

    } // endif: argument was not empty

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Strip trailing character from string
 *
 * @param[in] arg String from which character should be stripped.
 * @param[in] chars Character(s) to be stripped.
 * @return String with stripped characters.
 ***************************************************************************/
std::string gammalib::rstrip_chars(const std::string& arg,
                                   const std::string& chars)
{
    // Initialise empty result string
    std::string result;

    // Continue only if argument is not empty
    if (!arg.empty()) {

        // Get stop
        std::string::size_type stop = arg.find_last_not_of(chars);

        // Continue only if stop is valid
        if (stop != std::string::npos) {
            result = arg.substr(0, stop+1);
        }

    } // endif: argument was not empty

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Expand environment variables in string
 *
 * @param[in] arg String.
 * @return String with expected environment variables.
 *
 * Expands any environment variable that is found in a string. Valid
 * delimiters for environment variables are $ENV{\<name\>}, $ENV(\<name\>),
 * ${\<name\>}, $(\<name\>) and $\<name\> (in the last case the terminating
 * delimiter is either a / or a blank character or the end of the string).
 * Environment variables occuring within single quotes (') are ignored.
 * Environment variables that do not exist will be kept as specified.
 *
 * The method also replaces ~ or ~user by the user's home directory, ~+
 * by the value of the PWD environment variable and ~- by the value of the
 * OLDPWD variable. If the user or the PWD or OLDPWD variable are not found,
 * no replacement is done.
 *
 * This function has been inspired by the function ape_util_expand_env_var
 * from ape_util.c in the ape software developed at HEASARC.
 ***************************************************************************/
std::string gammalib::expand_env(const std::string& arg)
{
    // Set environment variable delimiters
    static const char* begin_delim[] = { "$ENV{", "$ENV(", "${", "$(", "$", "~" };
    static const char* end_delim[]   = { "}", ")", "}", ")", "/", "/" };
    static const int   num_delim     = 6;

    // Initialise result with argument
    std::string result = arg;

    // Initialise parse parameters
    size_t index    = 0;
    bool   in_quote = false;

    // Loop over string
    while (index < result.length()) {

        // If we have an escaped character then skip the current character
        // and the next one
        if (result[index] == '\\') {
            index += 2;
            continue;
        }

        // If we have a single quote then toggle the quote state
        if (result[index] == '\'') {
            in_quote = !in_quote;
            index++;
            continue;
        }

        // Don't expand environment variables inside single quotes. Note
        // that double quotes are ok.
        if (in_quote) {
            index++;
            continue;
        }

        // Find delimiter which indicates beginning of an environment variable
        size_t begin_length = 0;
        int    delim_idx    = 0;
        for (; delim_idx < num_delim; ++delim_idx) {
            size_t len = std::strlen(begin_delim[delim_idx]);
            if (result.compare(index, len, begin_delim[delim_idx]) == 0) {
                begin_length = len;
                break;
            }
        }

        // If we found a delimiter then process the environment variable
        if (begin_length > 0) {

            // Search for the termination delimiter of the environment
            // variable. There is a special case for delimiters 4 and 5:
            // It has always an end_length of zero as the / is not a real
            // delimiter, but just an indicator that the environment variable
            // ends. Another indicator is a blank. If the end of the
            // string has been reached this is also acceptable.
            size_t i_start    = index + begin_length;
            size_t i_end      = i_start;
            size_t end_length = 0;
            if (delim_idx == 4 || delim_idx == 5) {
                while (i_end < result.length() &&
                       result.compare(i_end, 1, "/") != 0 &&
                       result.compare(i_end, 1, " ") != 0) {
                    i_end++;
                }
            }
            else {
                end_length = std::strlen(end_delim[delim_idx]);
                while (i_end < result.length() &&
                       result.compare(i_end, end_length, end_delim[delim_idx]) != 0) {
                    i_end++;
                }
            }

            // If termination delimiter has been found then expand the
            // environment variable
            if (i_end < result.length() || delim_idx == 4 || delim_idx == 5) {

                // Extract environment variable name
                std::string name        = result.substr(i_start, i_end-i_start);
                size_t      name_length = name.length();

                // Initialise pointer on environment variable
                const char* env = NULL;

                // Handle ~
                if (delim_idx == 5) {
                    if (name_length == 0) {
                        if ((env = std::getenv("HOME")) == NULL) {
                            struct passwd *pw = getpwuid(getuid());
                            if (pw != NULL) {
                                env = pw->pw_dir;
                            }
                        }
                    }
                    else {
                        if (name == "+") {
                            env = std::getenv("PWD");
                        }
                        else if (name == "-") {
                            env = std::getenv("OLDPWD");
                        }
                        else {
                            struct passwd *pw = getpwnam(name.c_str());
                            if (pw != NULL) {
                                env = pw->pw_dir;
                            }
                        }
                    }
                }

                // ... otherwise get the environment variable
                else {
                    env = std::getenv(name.c_str());
                }

                // If the environment variable has been found then replace
                // it by its value
                if (env != NULL) {

                    // Erase delimiters and environment variable
                    result.erase(index, begin_length+name_length+end_length);

                    // Set replacement string and its length
                    std::string replace(env);
                    size_t      replace_length = replace.length();

                    // Insert replacement string
                    result.insert(index, replace);

                    // Advance pointer
                    index += replace_length;

                } // endif: environment variable has been found

                // If no environment variable has been found then set
                // index=i_end+1
                else {
                    index = i_end + 1;
                }

            } // endif: termination delimiter found

            // If no environment variable has been found then set index=i_end+1
            else {
                index = i_end + 1;
            }

        } // endif: we found an environment variable delimiter

        // ... otherwise advance to next character
        else {
            index++;
        }

    } // endwhile: looped over string

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Build file path from path name and file name
 *
 * @param[in] pathname Path name.
 * @param[in] filename File name.
 * @return File path.
 *
 * Builds a file path by combining the @p pathname and the @p filename
 * following
 *
 *      filepath = pathname/filename
 *
 * If @p pathname is an empty string, the method simply returns the
 * @p filename.
 ***************************************************************************/
std::string gammalib::filepath(const std::string& pathname,
                               const std::string& filename)
{
    // Initialise filepath
    std::string filepath;

    // If path name is empty, simply return the file name
    if (pathname.empty()) {
        filepath = filename;
    }

    // ... otherwise combine both
    else {
        filepath = pathname + "/" + filename;
    }

    // Return the file path
    return filepath;
}


/***********************************************************************//**
 * @brief Convert unsigned short integer value into string
 *
 * @param[in] value Unsigned short integer to be converted into string.
 * @return String with unsigned short integer value.
 ***************************************************************************/
std::string gammalib::str(const unsigned short int& value)
{
    std::ostringstream s_value;
    s_value << value;
    return s_value.str();
}


/***********************************************************************//**
 * @brief Convert unsigned integer value into string
 *
 * @param[in] value Unsigned integer to be converted into string.
 * @return String with unsigned integer value.
 ***************************************************************************/
std::string gammalib::str(const unsigned int& value)
{
    std::ostringstream s_value;
    s_value << value;
    return s_value.str();
}


/***********************************************************************//**
 * @brief Convert unsigned long integer value into string
 *
 * @param[in] value Unsigned long integer to be converted into string.
 * @return String with unsigned long integer value.
 ***************************************************************************/
std::string gammalib::str(const unsigned long int& value)
{
    std::ostringstream s_value;
    s_value << value;
    return s_value.str();
}


/***********************************************************************//**
 * @brief Convert unsigned long long integer value into string
 *
 * @param[in] value Unsigned long long integer to be converted into string.
 * @return String with unsigned long long integer value.
 ***************************************************************************/
std::string gammalib::str(const unsigned long long int& value)
{
    std::ostringstream s_value;
    s_value << value;
    return s_value.str();
}


/***********************************************************************//**
 * @brief Convert short integer value into string
 *
 * @param[in] value Short integer to be converted into string.
 * @return String with short integer value.
 ***************************************************************************/
std::string gammalib::str(const short int& value)
{
    std::ostringstream s_value;
    s_value << value;
    return s_value.str();
}


/***********************************************************************//**
 * @brief Convert integer value into string
 *
 * @param[in] value Integer to be converted into string.
 * @return String with integer value.
 ***************************************************************************/
std::string gammalib::str(const int& value)
{
    std::ostringstream s_value;
    s_value << value;
    return s_value.str();
}


/***********************************************************************//**
 * @brief Convert long integer value into string
 *
 * @param[in] value Long integer to be converted into string.
 * @return String with long integer value.
 ***************************************************************************/
std::string gammalib::str(const long int& value)
{
    std::ostringstream s_value;
    s_value << value;
    return s_value.str();
}


/***********************************************************************//**
 * @brief Convert long long integer value into string
 *
 * @param[in] value Long long integer to be converted into string.
 * @return String with long long integer value.
 ***************************************************************************/
std::string gammalib::str(const long long int& value)
{
    std::ostringstream s_value;
    s_value << value;
    return s_value.str();
}

  
/***********************************************************************//**
 * @brief Convert single precision value into string
 *
 * @param[in] value Single precision value to be converted into string.
 * @param[in] precision Floating point precision.
 * @return String with single precision value.
 *
 * Converts a single precision value into a string. Any positive
 * @p precision argument specifies the exact number of digits after the
 * comma.
 ***************************************************************************/
std::string gammalib::str(const float& value, const int& precision)
{
    // Allocate output stream
    std::ostringstream s_value;

    // If specified then set the requested fixed point precision. Otherwise
    // use a precision that should be sufficient for floating point values.
    if (precision > 0) {
        s_value.precision(precision);
        s_value.setf(std::ios::fixed, std::ios::floatfield);
    }
    else {
        s_value.precision(7);
    }

    // Put floating point value in stream
    s_value << value;

    // Convert to a string
    std::string result = s_value.str();

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Convert double precision value into string
 *
 * @param[in] value Double precision value to be converted into string.
 * @param[in] precision Floating point precision.
 * @return String with double precision value.
 *
 * Converts a double precision value into a string. Any positive
 * @p precision argument specifies the exact number of digits after the
 * comma.
 ***************************************************************************/
std::string gammalib::str(const double& value, const int& precision)
{
    // Allocate output stream
    std::ostringstream s_value;

    // If specified then set the requested fixed point precision. Otherwise
    // use a precision that should be sufficient for floating point values.
    if (precision > 0) {
        s_value.precision(precision);
        s_value.setf(std::ios::fixed, std::ios::floatfield);
    }
    else {
        s_value.precision(15);
    }

    // Put double precision floating point value in stream
    s_value << value;

    // Convert to a string
    std::string result = s_value.str();

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Convert complex value into string
 *
 * @param[in] value Complex value to be converted into string.
 * @param[in] precision Floating point precision.
 * @return String with complex value.
 *
 * Converts a complex value into a string. Any positive @p precision argument
 * specifies the exact number of digits after the comma.
 ***************************************************************************/
std::string gammalib::str(const std::complex<double>& value,
                          const int&                  precision)
{
    // Allocate output stream
    std::ostringstream s_value;

    // If specified then set the requested fixed point precision. Otherwise
    // use a precision that should be sufficient for floating point values.
    if (precision > 0) {
        s_value.precision(precision);
        s_value.setf(std::ios::fixed, std::ios::floatfield);
    }
    else {
        s_value.precision(15);
    }

    // Put double precision floating point value in stream
    s_value << value.real();
    if (value.imag() < 0.0) {
        s_value << "-";
    }
    else {
        s_value << "+";
    }
    s_value << std::abs(value.imag()) << "j";

    // Convert to a string
    std::string result = s_value.str();

    // Return result
    return result;
}



/***********************************************************************//**
 * @brief Convert string to C string
 *
 * @param[in] arg String to be converted.
 * @return C string.
 *
 * Allocates a C string with the content of a C++ string.
 ***************************************************************************/
char* gammalib::tochar(const std::string& arg)
{
    // Allocate C string
    char* str = new char[arg.length()+1];

    // Copy characters
    for (std::size_t i = 0; i < arg.length(); ++i) {
        str[i] = arg[i];
    }

    // Set line end character
    str[arg.length()] = '\0';

    // Return C string
    return str;
}


/***********************************************************************//**
 * @brief Convert string into short value
 *
 * @param[in] arg String to be converted.
 * @return Short value.
 ***************************************************************************/
short gammalib::toshort(const std::string& arg)
{
    std::istringstream iss(arg);
    short              result;
    iss >> std::dec >> result;
    return result;
}


/***********************************************************************//**
 * @brief Convert string into unsigned short value
 *
 * @param[in] arg String to be converted.
 * @return Unsigned short value.
 ***************************************************************************/
unsigned short gammalib::toushort(const std::string& arg)
{
    std::istringstream iss(arg);
    unsigned short     result;
    iss >> std::dec >> result;
    return result;
}


/***********************************************************************//**
 * @brief Convert string into integer value
 *
 * @param[in] arg String to be converted.
 * @return Integer value.
 ***************************************************************************/
int gammalib::toint(const std::string& arg)
{
    std::istringstream iss(arg);
    int                result;
    iss >> std::dec >> result;
    return result;
}


/***********************************************************************//**
 * @brief Convert string into unsigned integer value
 *
 * @param[in] arg String to be converted.
 * @return Unsigned integer value.
 ***************************************************************************/
unsigned int gammalib::touint(const std::string& arg)
{
    std::istringstream iss(arg);
    unsigned int       result;
    iss >> std::dec >> result;
    return result;
}


/***********************************************************************//**
 * @brief Convert string into long value
 *
 * @param[in] arg String to be converted.
 * @return Long value.
 ***************************************************************************/
long gammalib::tolong(const std::string& arg)
{
    std::istringstream iss(arg);
    long               result;
    iss >> std::dec >> result;
    return result;
}


/***********************************************************************//**
 * @brief Convert string into unsigned long value
 *
 * @param[in] arg String to be converted.
 * @return Unsigned long value.
 ***************************************************************************/
unsigned long gammalib::toulong(const std::string& arg)
{
    std::istringstream iss(arg);
    unsigned long      result;
    iss >> std::dec >> result;
    return result;
}


/***********************************************************************//**
 * @brief Convert string into long long value
 *
 * @param[in] arg String to be converted.
 * @return Long long value.
 ***************************************************************************/
long long gammalib::tolonglong(const std::string& arg)
{
    std::istringstream iss(arg);
    long long          result;
    iss >> std::dec >> result;
    return result;
}


/***********************************************************************//**
 * @brief Convert string into unsigned long long value
 *
 * @param[in] arg String to be converted.
 * @return Unsigned long long value.
 ***************************************************************************/
unsigned long long gammalib::toulonglong(const std::string& arg)
{
    std::istringstream iss(arg);
    unsigned long long result;
    iss >> std::dec >> result;
    return result;
}


/***********************************************************************//**
 * @brief Convert string into single precision value
 *
 * @param[in] arg String to be converted.
 * @return Single precision value.
 ***************************************************************************/
float gammalib::tofloat(const std::string& arg)
{
    std::istringstream iss(arg);
    float              result;
    iss >> std::dec >> result;
    return result;
}


/***********************************************************************//**
 * @brief Convert string into double precision value
 *
 * @param[in] arg String to be converted.
 * @return Double precision value.
 ***************************************************************************/
double gammalib::todouble(const std::string& arg)
{
    std::istringstream iss(arg);
    double             result;
    iss >> std::dec >> result;
    return result;
}


/***********************************************************************//**
 * @brief Convert string to upper case
 *
 * @param[in] arg String to be converted to upper case.
 * @return String converted to upper case.
 ***************************************************************************/
std::string gammalib::toupper(const std::string& arg)
{
    std::string s = arg;
    std::transform(s.begin(), s.end(), s.begin(), ::toupper);
    return s;
}


/***********************************************************************//**
 * @brief Convert string to lower case
 *
 * @param[in] arg String to be converted to upper case.
 * @return String converted to lower case.
 ***************************************************************************/
std::string gammalib::tolower(const std::string& arg)
{
    std::string s = arg;
    std::transform(s.begin(), s.end(), s.begin(), ::tolower);
    return s;
}


/***********************************************************************//**
 * @brief Split string
 *
 * @param[in] s String to be splitted.
 * @param[in] sep Separator(s).
 * @return Vector of split strings.
 *
 * Splits a string on the basis of one or multiple separator characters. The
 * separator characters are provided by the @p sep argument. Subsequent
 * separator characters that are not seperated by some other characters will
 * lead to an empty string element, except for a blank separator where
 * subsequent blanks are takens as a single separator. Below a few examples
 * that illustrate how the function will split a given string.
 *
 *     "Name;RA;DEC" => ["Name","RA","DEC"] (sep=";")
 *     "My house is    red" => ["My","house","is","red"] (sep=" ")
 *     "IRF::FRONT" => ["IRF","","FRONT"] (sep=":")
 *     "Fields;RA,DEC,Flux" => ["Fields","RA","DEC","Flux"] (sep=";,")
 *     "Last;Field;" => ["Last","Field",""] (sep=";")
 ***************************************************************************/
std::vector<std::string> gammalib::split(const std::string& s,
                                         const std::string& sep)
{
    // Allocate result string vector
    std::vector<std::string> result;

    // Initialise counters
    std::size_t pos = 0;
    std::size_t len = s.length();

    // Loop over string
    while (pos < len && pos != std::string::npos) {

        // Get index of first separator occurence and preset the length
        // of the substring to the end of the string
        std::size_t index = s.find_first_of(sep, pos);
        std::size_t n     = std::string::npos;

        // If we did not reach the end then compute now the length of the
        // substring
        if (index != std::string::npos) {
            n = index-pos;
        }

        // If we have no whitespace separator and the length of the
        // substring is zero then push back an empty string. If the
        // length of the substring is positive then push back the
        // substring.
        if (sep != " " && n == 0) {
            result.push_back("");
        }
        else if (n > 0) {
            result.push_back(s.substr(pos, n));
        }

        // Go to the string position after the last separator
        pos = (index != std::string::npos) ? index + 1 : std::string::npos;

        // If the position is pointing right beyong the last string
        // character we terminated with a separator, hence we need to push
        // back one more empty string before we leave
        if (sep != " " && pos == len) {
            result.push_back("");
        }

    } // endwhile: there were still characters in the string

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Fill string with n strings of same type
 *
 * @param[in] s String to be filled.
 * @param[in] n Number of fillings.
 * @return Filled strings.
 *
 * Replicates a given string n time.
 ***************************************************************************/
std::string gammalib::fill(const std::string& s, const int& n)
{
    // Initialise result
    std::string result = "";

    // Replicate string
    for (int i = 0; i < n; ++i) {
        result.append(s);
    }

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Left justify string to achieve a length of n characters
 *
 * @param[in] s String to be centred.
 * @param[in] n Requested total width.
 * @param[in] c Fill character.
 * @return Left justified string.
 *
 * Left justify string by adding whitespace to the right to achieve a length
 * of n characters.
 ***************************************************************************/
std::string gammalib::left(const std::string& s, const int& n, const char& c)
{
    // Compute number of characters to fill right
    int n_right  = n - s.length();

    // Set result
    std::string result = s + fill(std::string(1,c), n_right);

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Right justify string to achieve a length of n characters
 *
 * @param[in] s String to be centred.
 * @param[in] n Requested total width.
 * @param[in] c Fill character.
 * @return Right justified string.
 *
 * Right justify string by adding whitespace to the left to achieve a length
 * of n characters.
 ***************************************************************************/
std::string gammalib::right(const std::string& s, const int& n, const char& c)
{
    // Compute number of characters to fill right
    int n_left  = n - s.length();

    // Set result
    std::string result = fill(std::string(1,c), n_left) + s;

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Centre string to achieve a length of n characters
 *
 * @param[in] s String to be centred.
 * @param[in] n Requested total width.
 * @param[in] c Left fill character.
 * @return Centred string.
 *
 * Centre string by adding whitespace to the left and the right to achieve a
 * length of n characters.
 ***************************************************************************/
std::string gammalib::centre(const std::string& s, const int& n, const char& c)
{
    // Compute number of characters to fill left and right
    int n_right = (n-s.length()) / 2;
    int n_left  = n - s.length() - n_right;

    // Set result
    std::string result = fill(std::string(1,c), n_left) + s + 
                         fill(std::string(1,c), n_right);

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Convert string in parameter format
 *
 * @param[in] s String to be converted.
 * @param[in] indent Indentation of parameter.
 * @return Parameter string.
 *
 * Converts and string into the parameter format of type "s ......: " with a
 * total length of G_PARFORMAT_LENGTH.
 ***************************************************************************/
std::string gammalib::parformat(const std::string& s, const int& indent)
{
    // Compute number of characters to fill right. Do not clip the string if
    // it is too long since we do not want to loose information.
    int n_right = G_PARFORMAT_LENGTH - s.length() - 3 - indent;

    // Set result
    std::string result = " " + s + " " + fill(".", n_right) + ": ";

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Convert singular noun into number noun
 *
 * @param[in] noun Singular noun.
 * @param[in] number Number of instance of noun.
 * @return Converted noun.
 *
 * Converts a singular noun into a number noun by appending a "s" to the
 * noun if the @p number of the instances of the noun is not one.
 ***************************************************************************/
std::string gammalib::number(const std::string& noun, const int& number)
{
    // Copy input noun
    std::string result(noun);

    // Append "s" if number if not one
    if (number != 1) {
        result += "s";
    }

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Compute photon flux between two energies for a power law
 *
 * @param[in] emin Minimum energy.
 * @param[in] emax Maximum energy.
 * @param[in] epivot Pivot energy.
 * @param[in] gamma Spectral index.
 * @return Photon flux under power law.
 *
 * Analytically computes
 * \f[\int_{E_{\rm min}}^{E_{\rm max}} 
 *                             \left( E/E_{\rm pivot} \right)^{\gamma} dE\f]
 * where
 * \f$E_{\rm min}\f$ and \f$E_{\rm max}\f$ are the minimum and maximum
 * energy, respectively, and
 * \f$E_{\rm pivot}\f$ is the pivot energy, and
 * \f$\gamma\f$ is the spectral index.
 ***************************************************************************/
double gammalib::plaw_photon_flux(const double& emin, const double& emax,
                                  const double& epivot, const double& gamma)
{
    // Initialise flux
    double flux = 0.0;

    // Continue only if emax > emin
    if (emax > emin) {

        // Compute photon flux. Computations dependend on the exponent. We
        // add here a kluge to assure numerical accuracy.
        double xmin     = emin/epivot;
        double xmax     = emax/epivot;
        double exponent = gamma + 1.0;
        if (std::abs(exponent) > 1.0e-11) {
            flux = epivot / exponent * (std::pow(xmax, exponent) -
                                        std::pow(xmin, exponent));
        }
        else {
            flux = epivot * (std::log(xmax) - std::log(xmin));
        }

    } // endif: emax > emin

    // Return result
    return flux;
}


/***********************************************************************//**
 * @brief Compute energy flux between two energies for a power law
 *
 * @param[in] emin Minimum energy.
 * @param[in] emax Maximum energy.
 * @param[in] epivot Pivot energy.
 * @param[in] gamma Spectral index.
 * @return Energy flux under power law.
 *
 * Analytically computes
 * \f[\int_{E_{\rm min}}^{E_{\rm max}} 
 *                           \left( E/E_{\rm pivot} \right)^{\gamma} E dE\f]
 * where
 * \f$E_{\rm min}\f$ and \f$E_{\rm max}\f$ are the minimum and maximum
 * energy, respectively, and
 * \f$E_{\rm pivot}\f$ is the pivot energy, and
 * \f$\gamma\f$ is the spectral index.
 ***************************************************************************/
double gammalib::plaw_energy_flux(const double& emin, const double& emax,
                                  const double& epivot, const double& gamma)
{
    // Initialise flux
    double flux = 0.0;

    // Continue only if emax > emin
    if (emax > emin) {

        // Compute energy flux. Computations dependend on the exponent. We
        // add here a kluge to assure numerical accuracy.
        double xmin     = emin/epivot;
        double xmax     = emax/epivot;
        double exponent = gamma + 2.0;
        double epivot2  = epivot * epivot;
        if (std::abs(exponent) > 1.0e-11) {
            flux = epivot2 / exponent * (std::pow(xmax, exponent) -
                                         std::pow(xmin, exponent));
        }
        else {
            flux = epivot2 * (std::log(xmax) - std::log(xmin));
        }

    } // endif: emax > emin

    // Return result
    return flux;
}


/***********************************************************************//**
 * @brief Computes log mean energy
 *
 * @param[in] a First energy.
 * @param[in] b Second energy.
 * @return Log mean energy.
 *
 * Computes the logarithmic mean energy
 * \f$10^{0.5 * (\log E_{\rm a} + \log E_{\rm b})}\f$
 * for two energies.
 ***************************************************************************/
GEnergy gammalib::elogmean(const GEnergy& a, const GEnergy& b)
{
    // Compute logarithmic mean energy
    GEnergy elogmean;
    double  eloga = a.log10MeV();
    double  elogb = b.log10MeV();
    elogmean.MeV(std::pow(10.0, 0.5 * (eloga + elogb)));

    // Return
    return elogmean;
}


/***********************************************************************//**
 * @brief Checks if directory exists
 *
 * @param[in] dirname Directory name.
 * @return True if directory exists, false otherwise.
 *
 * Checks if a directory exists. The function expands any environment
 * variable prior to checking.
 ***************************************************************************/
bool gammalib::dir_exists(const std::string& dirname)
{
    // Initialise result
    bool result = false;

    // Allocate file information structure
    struct stat info;

    // Get file information structure
    int ret = stat(gammalib::expand_env(dirname).c_str(), &info);

    // Check if we have a directory
    if (ret == 0 && S_ISDIR(info.st_mode)) {
        result = true;
    }

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Checks if a substring is in a string
 *
 * @param[in] str String you want to search in.
 * @param[in] substring String you are looking for in @p str.
 * @return True if a string contains a sub string.
 *
 * Checks if substring is contained in str
 ***************************************************************************/
bool gammalib::contains(const std::string& str, const std::string& substring)
{
    // Initialise result
    bool result = false;

    // checks if substring is in str
    if (str.find(substring) != std::string::npos) {
        result = true;
    }

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Checks if a string is contained in a vector of strings
 *
 * @param[in] strings Vector of strings you want to search in.
 * @param[in] string string you are looking for in strings.
 * @return True if a string is contained a vector.
 *
 * Checks if a string is contained in a vector of strings
 ***************************************************************************/
bool gammalib::contains(const std::vector<std::string> strings,
                        const std::string&             string)
{
    // Compute result
    bool result = std::find(strings.begin(), strings.end(), string) !=
                  strings.end();

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Emits warning
 *
 * @param[in] origin Name of method that emits warning.
 * @param[in] message Warning message.
 *
 * Writes a warning to the console.
 ***************************************************************************/
void gammalib::warning(const std::string& origin,
                       const std::string& message)
{
    // Compile option: enable/disable warnings
    #if defined(G_WARNINGS)

    // Set warning message
    std::string warning = "+++ WARNING in " + origin + ": " + message;

    // Writes warning to the console
    std::cout << warning << std::endl;

    // End of compile option
    #endif

    // Return
    return;
}


/***********************************************************************//**
 * @brief Convert XML character references in string to characters
 *
 * @param[in] arg String containing XML character references.
 * @return String with character reference replaced by respective characters.
 *
 * Converts all character references found in a string in their respective
 * characters. For more information about XML character references read
 * http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
 ***************************************************************************/
std::string gammalib::xml2str(const std::string& arg)
{
    // Initialise string
    std::string result;

    // Iitialise position, lenghts and flags
    size_t length = arg.length();
    size_t pos    = 0;
    size_t start  = 0;
    size_t stop   = 0;
    size_t len    = 0;      // Length of string preceeding char. reference
    bool   found  = false;

    // Loop over string
    while (pos < length) {

        // If we have not yet found a character reference then search for
        // the next one. If we do not find one we break here.
        if (!found) {
            start = arg.find("&", pos);
            if (start != std::string::npos) {
                len   = start - pos;
                pos   = start;
                found = true;
            }
            else {
                break;
            }
        }

        // ... otherwise search for end of the actual character reference.
        // Throw an exception if no end is found.
        else {
            stop = arg.find(";", pos);
            if (stop != std::string::npos) {

                // First attach leading string to the result
                if (len > 0) {
                    result += arg.substr(start-len, len);
                }

                // Next extract character reference
                std::string cref = arg.substr(start+1, stop-start-1);
                len              = cref.length();

                // Check for a numerical character reference
                //TODO: Check that there are only valid characters in
                //      numerical field
                if (len >= 2 && cref[0] == '#') {
                    int number = -1;
                    if (cref[1] == 'x') {
                        number = (int)std::strtol(cref.substr(2,len-2).c_str(), NULL, 16);
                    }
                    else {
                        number = toint(cref.substr(1,len-1));
                    }
                    if (number != -1) {
                        result.push_back((char)number);
                    }
                    else {
                        std::string msg = "Could not extract number from "
                                          "numerical character reference &"+
                                          cref+";";
                        throw GException::invalid_argument(G_XML2STRING, msg);
                    }
                }

                // ... otherwise check for a character entity reference
                // and push back the corresponding character to the result
                // string
                else {
                    if (cref == "quot") {
                        result.push_back((char)34);
                    }
                    else if (cref == "amp") {
                        result.push_back((char)38);
                    }
                    else if (cref == "apos") {
                        result.push_back((char)39);
                    }
                    else if (cref == "lt") {
                        result.push_back((char)60);
                    }
                    else if (cref == "gt") {
                        result.push_back((char)62);
                    }
                    else {
                        std::string msg = "Unknown character entity reference "
                                          "&"+cref+"; encountered in XML string \""+
                                          arg+"\".";
                        throw GException::invalid_argument(G_XML2STRING, msg);
                    }
                }

                // Signal that we're done and that we search for the
                // next character reference
                found = false;
                pos   = stop + 1;

            } // endif: end of character reference found

            // ... otherwise throw an exception
            else {
                std::string msg = "Missing ; character at end of character "
                                  "reference in XML string \""+arg+"\".";
                throw GException::invalid_argument(G_XML2STRING, msg);
            }

        } // endelse: search for end of character reference

    } // endwhile

    // Append any pending string to the result
    if (pos < length) {
        len     = length - pos;
        result += arg.substr(pos, len);
    }

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Convert special characters in string to XML character references
 *
 * @param[in] arg String.
 * @return String with special characters replaced by character references.
 *
 * Converts all special characters found in a string into character
 * references. For more information about XML character references read
 * http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
 ***************************************************************************/
std::string gammalib::str2xml(const std::string& arg)
{
    // Initialise string
    std::string result;

    // Loop over string
    for (int i = 0; i < arg.length(); ++i) {

        // Initialize string to add
        std::string character = arg.substr(i, 1);

        // Replace special characters
        if (character == "\"") {
            character = "&quot;";
        }
        else if (character == "&") {
            character = "&amp;";
        }
        else if (character == "'") {
            character = "&apos;";
        }
        else if (character == "<") {
            character = "&lt;";
        }
        else if (character == ">") {
            character = "&gt;";
        }

        // Append character
        result += character;

    }

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Checks if parameter with given name in XML element exists
 *
 * @param[in] xml XML element.
 * @param[in] name Parameter name.
 * @return True if parameter exists, false otherwise.
 *
 * Checks whether a parameter with given @p name exists in XML element.
 ***************************************************************************/
bool gammalib::xml_has_par(const GXmlElement& xml, const std::string& name)
{
    // Initialize flag
    bool found = false;

    // Search for parameter with given name
    for (int i = 0; i < xml.elements("parameter"); ++i) {
        const GXmlElement* element = xml.element("parameter", i);
        if (element->attribute("name") == name) {
            found = true;
            break;
        }
    }

    // Return
    return found;
}


/***********************************************************************//**
 * @brief Return pointer to parameter with given name in XML element
 *
 * @param[in] origin Method requesting parameter.
 * @param[in] xml XML element.
 * @param[in] name Parameter name.
 * @return Pointer to parameter XML element.
 *
 * @exception GException::invalid_value
 *            Invalid XML format encountered.
 *
 * Returns pointer to parameter with given @p name in XML element. If the
 * @p name is not found, a parameter with the given @p name is added. In
 * that respect the function differs from xml_get_par which does not add a
 * parameter element.
 *
 * The function checks for multiple occurences of a parameter and throws an
 * exception in case that more than one parameter with a given name is found.
 ***************************************************************************/
GXmlElement* gammalib::xml_need_par(const std::string& origin,
                                    GXmlElement&       xml,
                                    const std::string& name)
{
    // Initialize XML element pointer
    GXmlElement* par = NULL;

    // Number of elements
    int number = 0;

    // Search for parameter with given name
    for (int i = 0; i < xml.elements("parameter"); ++i) {
        GXmlElement* element = xml.element("parameter", i);
        if (element->attribute("name") == name) {
            par = element;
            number++;
        }
    }

    // Create parameter if none was found
    if (number == 0) {
        par = static_cast<GXmlElement*>(xml.append(GXmlElement("parameter name=\""+name+"\"")));
        number++;
    }

    // Check that there are no multiple parameters
    gammalib::xml_check_par(origin, name, number);

    // Return
    return par;
}


/***********************************************************************//**
 * @brief Return pointer to parameter with given name in XML element
 *
 * @param[in] origin Method requesting parameter.
 * @param[in] xml XML element.
 * @param[in] name Parameter name.
 * @return Pointer to parameter XML element.
 *
 * @exception GException::invalid_value
 *            Invalid XML format encountered.
 *
 * Returns pointer to parameter with given @p name in XML element. The
 * function checks whether the parameter has been found and throws an
 * exception if no parameter or multiple occurences of a parameter with given
 * @p name are found.
 ***************************************************************************/
const GXmlElement* gammalib::xml_get_par(const std::string& origin,
                                         const GXmlElement& xml,
                                         const std::string& name)
{
    // Initialize XML element pointer
    const GXmlElement* par = NULL;

    // Number of elements
    int number = 0;

    // Search for parameter with given name
    for (int i = 0; i < xml.elements("parameter"); ++i) {
        const GXmlElement* element = xml.element("parameter", i);
        if (element->attribute("name") == name) {
            par = element;
            number++;
        }
    }

    // Check that there is at least one parameter and that there are no
    // multiple parameters
    gammalib::xml_check_par(origin, name, number);

    // Return
    return par;
}


/***********************************************************************//**
 * @brief Return attribute value for a given parameter in XML element
 *
 * @param[in] origin Method requesting parameter.
 * @param[in] xml XML element.
 * @param[in] name Parameter name.
 * @param[in] attribute Attribute name.
 * @return Value of attribute.
 *
 * @exception GException::invalid_value
 *            Attribute not found.
 *
 * Returns the value of @p attribute of parameter @p name in XML element.
 * The function checks whether the parameter has been found and throws an
 * exception if no parameter or multiple occurences of a parameter with given
 * @p name are found. The function furthermore checks whether the attribute
 * exists. 
 ***************************************************************************/
std::string gammalib::xml_get_attr(const std::string& origin,
                                   const GXmlElement& xml,
                                   const std::string& name,
                                   const std::string& attribute)
{
    // Initialise attribute value
    std::string value = "";

    // Get parameter
    const GXmlElement* par = gammalib::xml_get_par(origin, xml, name);

    // Throw an exception if a parameter has not the requested attribute
    if (!par->has_attribute(attribute)) {
        std::string msg = "Attribute \""+attribute+"\" not found in XML "
                          "parameter \""+name+"\". Please verify the XML "
                          "format.";
        throw GException::invalid_value(origin, msg);
    }

    // Extract attribute
    value = par->attribute(attribute);

    // Return attribute value
    return value;
}


/***********************************************************************//**
 * @brief Checks whether a parameter has occured once
 *
 * @param[in] origin Method performing the check.
 * @param[in] name Parameter name.
 * @param[in] number Number of occurences of parameter.
 *
 * @exception GException::invalid_value
 *            Invalid XML format encountered.
 *
 * Throws an exception if a given parameter has not exactly occured once.
 * The exception text is adapted to the case that none or multiple parameters
 * have been found.
 ***************************************************************************/
void gammalib::xml_check_par(const std::string& origin,
                             const std::string& name,
                             const int&         number)
{
    // Throw case dependent exception
    if (number < 1) {
        std::string msg = "Parameter \""+name+"\" not found in XML element."
                          " Please verify the XML format.";
         throw GException::invalid_value(origin, msg);
    }
    else if (number > 1) {
        std::string msg = "Parameter \""+name+"\" found "+
                          gammalib::str(number)+" times in XML element."
                          " Please verify the XML format.";
        throw GException::invalid_value(origin, msg);
    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Expand file name provided as XML attribute for loading
 *
 * @param[in] xml XML element.
 * @param[in] filename File name.
 * @return Expanded file name.
 *
 * Expands file name provided as XML attribute for loading. If the file name
 * is not empty and has no path it is assumed that the file is located in the
 * same directory as the XML file, and the XML file access path is prepended
 * to the file name.
 ***************************************************************************/
GFilename gammalib::xml_file_expand(const GXmlElement& xml,
                                    const std::string& filename)
{
    // Set file name
    GFilename fname(filename);

    // If the file name is not empty and has no path we assume that the file
    // name is a relative file name with respect to the XML file access path
    // and we therefore prepend the XML file access path to the file name
    if (!fname.is_empty() && fname.path().length() == 0) {
        fname = xml.filename().path() + fname;
    }

    // Return file name
    return fname;
}


/***********************************************************************//**
 * @brief Reduce file name provided for writing as XML attribute
 *
 * @param[in] xml XML element.
 * @param[in] filename File name.
 * @return Reduced file name.
 *
 * Reduces file name provided for writing as XML attribute. If the file name
 * is not empty and has the same access path as the XML file it is assumed
 * that both files are located in the same directory, and the access path is
 * stripped from the file name.
 ***************************************************************************/
GFilename gammalib::xml_file_reduce(const GXmlElement& xml,
                                    const std::string& filename)
{
    // Set file name
    GFilename fname(filename);

    // If the file name is not empty and has the same access path as the XML
    // file it is assumed that both files are located in the same directory,
    // and the access path is stripped from the file name.
    if (!fname.is_empty() && fname.path() == xml.filename().path()) {
        fname = fname.file();
    }

    // Return file name
    return fname;
}


/***********************************************************************//**
 * @brief Checks whether a parameter has occured once
 *
 * @param[in] fd Socket file descriptor.
 * @param[out] buffer Buffer to hold data.
 * @param[in] len Maximum number of bytes to recv().
 * @param[in] flags Flags (as the fourth param to recv() ).
 * @param[in] timeout Timeout in milliseconds.
 * @return recv() error code, -2 == timeout
 *
 * This function implements the recv() function with a timeout. The timeout
 * is specified in milliseconds.
 ***************************************************************************/
int gammalib::recv(int fd, char *buffer, int len, int flags, int timeout)
{
    // Initialise error code with time out
    int error = -2;
    
    // Initialize the set
    fd_set readset;
    FD_ZERO(&readset);
    FD_SET(fd, &readset);
   
    // Initialize time out struct
    struct timeval tv;
    if (timeout >= 1000) {
        tv.tv_sec  = timeout/1000;
        tv.tv_usec = 0;
    }
    else {
        tv.tv_sec  = 0;
        tv.tv_usec = timeout*1000;
    }
    
    // select()
    int result = select(fd+1, &readset, NULL, NULL, &tv);

    // Check status
    if (result < 0) {
        error = -1;
    }
    else if (result > 0 && FD_ISSET(fd, &readset)) {

        // Initialise flags
        int iof = -1;

        // Set non-blocking mode
        if ((iof = fcntl(fd, F_GETFL, 0)) != -1) {
            fcntl(fd, F_SETFL, iof | O_NONBLOCK);
        }
        
        // Receive data
        result = ::recv(fd, buffer, len, flags);
        
        // Set as before
        if (iof != -1) {
            fcntl(fd, F_SETFL, iof);
        }
        
        // Set error
        error = result;
    }
    
    // Return error
    return error;
}