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

// clang-format off
#include <math.h>
#include <complex.h>
#include <gsl/gsl_deriv.h>

#include <lal/LALSimInspiral.h>
#include <lal/LALSimIMR.h>
#include <lal/Date.h>
#include <lal/TimeSeries.h>
#include <lal/LALAdaptiveRungeKuttaIntegrator.h>
#include <lal/SphericalHarmonics.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_sf_gamma.h>
#include <lal/Units.h>
#include <lal/VectorOps.h>
#include "LALSimIMREOBNRv2.h"
#include "LALSimIMRSpinEOB.h"
#include "LALSimInspiralPrecess.h"
#include "LALSimBlackHoleRingdownPrec.h"
#include "LALSimFindAttachTime.h"

// clang-format on

/* Include all the static function files we need */
#include "LALSimIMREOBHybridRingdownPrec.c"
#include "LALSimIMREOBNQCCorrection.c"
#include "LALSimIMREOBNewtonianMultipole.c"
#include "LALSimIMRSpinAlignedEOBHcapDerivative.c"
#include "LALSimIMRSpinEOBAuxFuncs.c"
#include "LALSimIMRSpinEOBFactorizedFluxPrec.c"
#include "LALSimIMRSpinEOBFactorizedWaveformCoefficientsPrec.c"
#include "LALSimIMRSpinEOBFactorizedWaveformPrec.c"
#include "LALSimIMRSpinEOBHamiltonian.c"
#include "LALSimIMRSpinEOBHamiltonianPrec.c"
#include "LALSimIMRSpinEOBHcapNumericalDerivativePrec.c"
#include "LALSimIMRSpinEOBInitialConditions.c"
#include "LALSimIMRSpinEOBInitialConditionsPrec.c"
#include "LALSimIMRSpinPrecEOBEulerAngles.c"
#include "LALSimInspiraldEnergyFlux.c"

/* Begin OPTv3 */
//#include "LALSimIMRSpinPrecEOBGSLOptimizedInterpolation.c"
#include "LALSpinPrecHcapRvecDerivative_v3opt.c"
//#include "LALSimIMRSpinPrecEOBWfGen.c"
/* End OPTv3 */

#define debugOutput 0

#ifdef __GNUC__
#ifndef UNUSED
#define UNUSED __attribute__((unused))
#endif
#else
#define UNUSED
#endif

/* Maximum l allowed in the SEOB model -- input ModeArray will only be scanned
 * up to this value of l */
#define _SEOB_MODES_LMAX 5

/* Version flag used in XLALSimIMREOBCalcSpinPrecFacWaveformCoefficients */
#define v4Pwave 451

/* Structure containing the approximant name and its number in LALSimInspiral.c
 */
struct approximant {
  const char *name;
  UINT4 number;
};
struct approximant v4P = {.name = "SEOBNRv4P", .number = 401};
struct approximant v4PHM = {.name = "SEOBNRv4PHM", .number = 402};

/* Number of dynamics variables stored by v4P */
#define v4PdynamicsVariables 26

#define FREE_ALL                                                               \
  if (ICvalues != NULL)                                                        \
    XLALDestroyREAL8Vector(ICvalues);                                          \
  if (dynamicsAdaS != NULL)                                                    \
    XLALDestroyREAL8Array(dynamicsAdaS);                                       \
  if (seobdynamicsAdaS != NULL)                                                \
    SEOBdynamics_Destroy(seobdynamicsAdaS);                                    \
  if (seobvalues_tstartHiS != NULL)                                            \
    XLALDestroyREAL8Vector(seobvalues_tstartHiS);                              \
  if (ICvaluesHiS != NULL)                                                     \
    XLALDestroyREAL8Vector(ICvaluesHiS);                                       \
  if (dynamicsHiS != NULL)                                                     \
    XLALDestroyREAL8Array(dynamicsHiS);                                        \
  if (chi1L_tPeakOmega != NULL)                                                \
    XLALDestroyREAL8Vector(chi1L_tPeakOmega);                                  \
  if (chi2L_tPeakOmega != NULL)                                                \
    XLALDestroyREAL8Vector(chi2L_tPeakOmega);                                  \
  if (seobdynamicsHiS != NULL)                                                 \
    SEOBdynamics_Destroy(seobdynamicsHiS);                                     \
  if (seobvalues_tPeakOmega != NULL)                                           \
    XLALDestroyREAL8Vector(seobvalues_tPeakOmega);                             \
  if (Jfinal != NULL)                                                          \
    XLALDestroyREAL8Vector(Jfinal);                                            \
  if (listhPlm_HiS != NULL)                                                    \
    SphHarmListCAmpPhaseSequence_Destroy(listhPlm_HiS);                        \
  if (listhPlm_HiSRDpatch != NULL)                                             \
    SphHarmListCAmpPhaseSequence_Destroy(listhPlm_HiSRDpatch);                 \
  if (listhPlm_AdaS != NULL)                                                   \
    SphHarmListCAmpPhaseSequence_Destroy(listhPlm_AdaS);                       \
  if (*tVecPmodes != NULL)                                                     \
    XLALDestroyREAL8Vector(*tVecPmodes);                                       \
  if (seobdynamicsAdaSHiS != NULL)                                             \
    SEOBdynamics_Destroy(seobdynamicsAdaSHiS);                                 \
  if (listhPlm != NULL)                                                        \
    SphHarmListCAmpPhaseSequence_Destroy(listhPlm);                            \
  if (*hP22_amp != NULL)                                                       \
    XLALDestroyREAL8Vector(*hP22_amp);                                         \
  if (*hP22_phase != NULL)                                                     \
    XLALDestroyREAL8Vector(*hP22_phase);                                       \
  if (*hP21_amp != NULL)                                                       \
    XLALDestroyREAL8Vector(*hP21_amp);                                         \
  if (*hP21_phase != NULL)                                                     \
    XLALDestroyREAL8Vector(*hP21_phase);                                       \
  if (*alphaJ2P != NULL)                                                       \
    XLALDestroyREAL8Vector(*alphaJ2P);                                         \
  if (*betaJ2P != NULL)                                                        \
    XLALDestroyREAL8Vector(*betaJ2P);                                          \
  if (*gammaJ2P != NULL)                                                       \
    XLALDestroyREAL8Vector(*gammaJ2P);                                         \
  if (*hJlm != NULL)                                                           \
    XLALDestroySphHarmTimeSeries(*hJlm);                                       \
  if (*hIlm != NULL)                                                           \
    XLALDestroySphHarmTimeSeries(*hIlm);                                       \
  if (hplusTS != NULL)                                                         \
    XLALDestroyREAL8TimeSeries(hplusTS);                                       \
  if (hcrossTS != NULL)                                                        \
    XLALDestroyREAL8TimeSeries(hcrossTS);                                      \
  if (*mergerParams != NULL)                                                   \
    XLALDestroyREAL8Vector(*mergerParams);                                     \
  if (*seobdynamicsAdaSVector != NULL)                                         \
    XLALDestroyREAL8Vector(*seobdynamicsAdaSVector);                           \
  if (*seobdynamicsHiSVector != NULL)                                          \
    XLALDestroyREAL8Vector(*seobdynamicsHiSVector);                            \
  if (*seobdynamicsAdaSHiSVector != NULL)                                      \
    XLALDestroyREAL8Vector(*seobdynamicsAdaSHiSVector);
#define PRINT_ALL_PARAMS                                                       \
  do {                                                                         \
    XLALPrintError(                                                            \
        "--approximant SEOBNRv4P --f-min %.16e --m1 %.16e --m2 %.16e "         \
        "--spin1x %.16e --spin1y %.16e --spin1z %.16e  --spin2x %.16e "        \
        "--spin2y %.16e --spin2z %.16e --inclination %.16e --distance %.16e "  \
        "--phiRef %.16e --sample-rate %.16e\n",                                \
        fMin, m1SI / LAL_MSUN_SI, m2SI / LAL_MSUN_SI, chi1x, chi1y, chi1z,     \
        chi2x, chi2y, chi2z, inc, r / (1e6 * LAL_PC_SI), phi, 1. / INdeltaT);  \
  } while (0);

/* Compute the highest initial frequency (of the 22 mode):
 * at which the code will generate a waveform. We choose an initial minimum
 * separation of 10.5M as a compromise between reliability of initial conditions
 * and length of the waveform. We use Newtonian Kepler's law. Refuse to
 * generate waveforms shorter than that.
 */
int XLALEOBHighestInitialFreq(
    REAL8 *freqMinRad /**<< OUTPUT, lowest initial 22 mode frequency*/,
    REAL8 mTotal /**<< Total mass in units of solar masses */) {
  REAL8 mTScaled = mTotal * LAL_MTSUN_SI;
  *freqMinRad = pow(10.5, -1.5) / (LAL_PI * mTScaled);
  return XLAL_SUCCESS;
}

/* Implements the standard argmax function for an array of reals */
UNUSED static UINT4 argmax(REAL8Vector *vec) {
  REAL8 max = vec->data[0];
  UINT4 idx_max = 0;
  for (UINT4 i = 0; i < vec->length; i++) {
    if (vec->data[i] > max) {
      max = vec->data[i];
      idx_max = i;
    }
  }
  return idx_max;
}

/* Return a slice of the given vector, not including the higher index,
i.e. parroting Python behaviour */
UNUSED static REAL8Vector *get_slice(REAL8Vector *vec, UINT4 lo, UINT4 hi) {
  UINT4 size = hi - lo;
  REAL8Vector *slice = XLALCreateREAL8Vector(size);
  for (UINT4 jj = 0; jj < size; jj++) {
    slice->data[jj] = vec->data[lo + jj];
  }
  return slice;
}

/* Function to find robustly the peak of a quantity given as an array of
samples. The idea is the scan the samples with a window [w_1,w_2] and find the
local max in each window, where local max has to not lie at the boundaries of
the window. One then keeps track of all the local maxes and picks the largest
one. Finally, one compares this value to the global argmax. If there is a clean
critical point which is also a global max then these 2 values have to agree */
UNUSED static int XLALEOBFindRobustPeak(REAL8 *tPeakQuant, REAL8Vector *tVec,
                                        REAL8Vector *quantVec,
                                        UINT4 window_width) {
  // We begin at the end and go backwards
  UINT4 vlen = tVec->length;
  UINT4 local_argmax = 0;
  UINT4 idx_global = 0;
  UINT4 lo, hi; // Bounds of local window
  // Global argmax over the entire array
  UINT4 global_arg_max = argmax(quantVec);
  UNUSED REAL8 global_max = quantVec->data[global_arg_max];
  REAL8Vector *sl = NULL;
  REAL8 curr_max = 0;
  for (UINT4 kk = vlen - window_width - 1; kk > window_width; kk--) {
    lo = kk - window_width;
    hi = kk + window_width +
         1; // Slice function does not return the value at the end
    sl = get_slice(quantVec, lo, hi);
    local_argmax = argmax(sl);
    if (sl->data[local_argmax] > sl->data[0] &&
        sl->data[local_argmax] > sl->data[sl->length - 1]) {
      // We have *a* local max, figure out it's global index
      // Is the local argmax the largest local argmax so far?
      if (sl->data[local_argmax] > curr_max) {
        curr_max = sl->data[local_argmax];
        idx_global = lo + local_argmax;
      }
    }
    XLALDestroyREAL8Vector(sl);
  }
  *tPeakQuant = 0;
  // Conditions under which we pick the last point of the dynamics:
  // i) we found no local maxes at all
  // ii) the global arg max is larger than the largest of the local maxes
  // by more than 2 % of the largest maxes value (ideally they should be equal)
  // iii) the  peak is  so close to end that we can't interpolate below.

  if (idx_global == 0 ||
      ((quantVec->data[global_arg_max] - quantVec->data[idx_global]) /
           quantVec->data[idx_global] >
       0.1) ||
      (idx_global > tVec->length - 4)) {
    XLAL_PRINT_WARNING("Warning no local max found, using last point\n");
    *tPeakQuant = tVec->data[tVec->length - 1];
    return XLAL_SUCCESS;
  }
  // We have a well-behaved local max. Get the time more accurately.
  // Now we need to interpolate and then set the derivative of the interpolant
  // to 0. We solve this via bisection in an interval of 3 points to the left
  // and right of the argmax.
  gsl_spline *spline = NULL;
  gsl_interp_accel *acc = NULL;
  spline = gsl_spline_alloc(gsl_interp_cspline, quantVec->length);
  acc = gsl_interp_accel_alloc();

  REAL8 time1 = tVec->data[idx_global - 3];
  REAL8 time2 = tVec->data[idx_global + 3];
  REAL8 timePeak = 0;
  REAL8 omegaDerivMid = 0;
  gsl_spline_init(spline, tVec->data, quantVec->data, quantVec->length);
  REAL8 omegaDeriv1 = gsl_spline_eval_deriv(spline, time1, acc);
  do {
    timePeak = (time1 + time2) / 2.;
    omegaDerivMid = gsl_spline_eval_deriv(spline, timePeak, acc);

    if (omegaDerivMid * omegaDeriv1 < 0.0) {
      time2 = timePeak;
    } else {
      omegaDeriv1 = omegaDerivMid;
      time1 = timePeak;
    }
  } while (time2 - time1 > 1.0e-8);
  *tPeakQuant = timePeak;
  gsl_spline_free(spline);
  gsl_interp_accel_free(acc);
  return XLAL_SUCCESS;
}

/* The stopping condition used for the high sampling part of SEOBNRv4P
Will set the termination reason to 1 if terminates normally(i.e. 5 steps
after peak of omega found). Will set it to -1 if something has become nan.
*/
UNUSED static int XLALEOBSpinPrecStopCondition_v4(double UNUSED t,
                                                  const double values[],
                                                  double dvalues[],
                                                  void UNUSED *funcParams) {
  UINT4 counter;
  INT4 i;
  SpinEOBParams UNUSED *params = (SpinEOBParams *)funcParams;

  REAL8 r2 = 0;
  REAL8 p[3], r[3], pdotVec[3], rdotVec[3];
  REAL8 omega, omega_xyz[3];

  memcpy(r, values, 3 * sizeof(REAL8));
  memcpy(p, values + 3, 3 * sizeof(REAL8));
  memcpy(rdotVec, dvalues, 3 * sizeof(REAL8));
  memcpy(pdotVec, dvalues + 3, 3 * sizeof(REAL8));

  r2 = inner_product(r, r);
  cross_product(values, dvalues, omega_xyz);
  omega = sqrt(inner_product(omega_xyz, omega_xyz)) / r2;
  counter = params->eobParams->omegaPeaked;
  if (r2 < 36. && omega < params->eobParams->omega) {
    params->eobParams->omegaPeaked = counter + 1;
  }

  if (params->eobParams->omegaPeaked == 5) {
    return 1;
  }
  for (i = 0; i < 12; i++) {
    if (isnan(dvalues[i]) || isnan(values[i])) {
      params->termination_reason = -1;
      return 1;
    }
  }
  params->eobParams->omega = omega;
  return GSL_SUCCESS;
}

/**
 * Stopping conditions for dynamics integration for SEOBNRv4P
 */
UNUSED static int
XLALEOBSpinPrecStopConditionBasedOnPR(double UNUSED t, const double values[],
                                      double dvalues[],
                                      void UNUSED *funcParams) {
  int debugPK = 0;
  int debugPKverbose = 0;
  INT4 i;
  SpinEOBParams UNUSED *params = (SpinEOBParams *)funcParams;

  REAL8 r2, pDotr = 0;
  REAL8 p[3], r[3], pdotVec[3], rdotVec[3];
  REAL8 omega, omega_xyz[3], L[3], dLdt1[3], dLdt2[3];

  memcpy(r, values, 3 * sizeof(REAL8));
  memcpy(p, values + 3, 3 * sizeof(REAL8));
  memcpy(rdotVec, dvalues, 3 * sizeof(REAL8));
  memcpy(pdotVec, dvalues + 3, 3 * sizeof(REAL8));

  r2 = inner_product(r, r);
  cross_product(values, dvalues, omega_xyz);
  omega = sqrt(inner_product(omega_xyz, omega_xyz)) / r2;
  pDotr = inner_product(p, r) / sqrt(r2);
  if (debugPK) {
    XLAL_PRINT_INFO("XLALEOBSpinPrecStopConditionBasedOnPR:: r = %e %e\n",
                    sqrt(r2), omega);
  }
  if (debugPK) {
    XLAL_PRINT_INFO(
        "XLALEOBSpinPrecStopConditionBasedOnPR:: values = %e %e %e %e %e %e\n",
        values[6], values[7], values[8], values[9], values[10], values[11]);
  }
  if (debugPK) {
    XLAL_PRINT_INFO(
        "XLALEOBSpinPrecStopConditionBasedOnPR:: dvalues = %e %e %e %e %e %e\n",
        dvalues[6], dvalues[7], dvalues[8], dvalues[9], dvalues[10],
        dvalues[11]);
  }
  REAL8 rdot;
  // this is d(r)/dt obtained by differentiating r2 (see above)
  rdot = inner_product(rdotVec, r) / sqrt(r2);
  // This is d/dt(pDotr) see pDotr above.
  double prDot = -inner_product(p, r) * rdot / r2 +
                 inner_product(pdotVec, r) / sqrt(r2) +
                 inner_product(rdotVec, p) / sqrt(r2);

  cross_product(r, pdotVec, dLdt1);
  cross_product(rdotVec, p, dLdt2);
  cross_product(r, p, L);

  /* ********************************************************** */
  /* *******  Different termination conditions Follow  ******** */
  /* ********************************************************** */

  /* Table of termination conditions

    Value                   Reason
    -1                   Any of the derivatives are Nan
    0                    r < 8 and pDotr >= 0 (outspiraling)
    1                    r < 8 and rdot >= 0 (outspiraling)
    2                    r < 2 and prDot > 0 (dp_r/dt is growing)
    3                    r < 8 and |p_vec| > 10 (the momentum vector is large)
    4                    r < 8 and |p_vec| < 1e-10 (momentum vector is small)
    5                    r < 2 and omega has a another peak
    6                    r < 8 and omega < 0.04 or (r < 2. and  omega < 0.14 and
    omega has a peak) 7                    r < 8 and omega > 1 (unphysical
    omega) 8                    r < 5 and any of  |dp_i/dt| > 10 9 r < 8 and
    pphi > 10
    10                   r < 3 and rdot increases
  */

  /* Terminate if any derivative is Nan */
  for (i = 0; i < 12; i++) {
    if (isnan(dvalues[i]) || isnan(values[i])) {
      if (debugPK) {
        XLAL_PRINT_INFO("\n  isnan reached. r2 = %f\n", r2);
        fflush(NULL);
      }
      XLALPrintError("XLAL Error - %s: nan reached at r2 = %f \n", __func__,
                     r2);
      XLAL_ERROR(XLAL_EINVAL);
      params->termination_reason = -1;
      return 1;
    }
  }

  /* ********************************************************** */
  /* *******  Unphysical orbital conditions  ******** */
  /* ********************************************************** */

  /* Terminate if p_r points outwards */
  if (r2 < 16 && pDotr >= 0) {
    if (debugPK) {
      XLAL_PRINT_INFO(
          "\n Integration stopping, p_r pointing outwards -- out-spiraling!\n");
      fflush(NULL);
    }
    params->termination_reason = 0;

    return 1;
  }

  /* Terminate if rdot is >0 (OUTspiraling) for separation <4M */
  if (r2 < 16 && rdot >= 0) {
    if (debugPK) {
      XLAL_PRINT_INFO("\n Integration stopping, dr/dt>0 -- out-spiraling!\n");
      fflush(NULL);
    }
    params->termination_reason = 1;

    return 1;
  }

  /* Terminate if dp_R/dt > 0, i.e. radial momentum is increasing for separation
   * <2M */
  if (r2 < 4. && prDot > 0.) {
    if (debugPK) {
      XLAL_PRINT_INFO("\n Integration stopping as prDot = %lf at r = %lf\n",
                      prDot, sqrt(r2));
      fflush(NULL);
    }
    params->termination_reason = 2;

    return 1;
  }

  if (r2 < 16. && (sqrt(values[3] * values[3] + values[4] * values[4] +
                        values[5] * values[5]) > 10.)) {
    if (debugPK)
      XLAL_PRINT_INFO("\n Integration stopping |pvec|> 10\n");
    fflush(NULL);
    params->termination_reason = 3;

    return 1;
  }

  if (r2 < 16. && (sqrt(values[3] * values[3] + values[4] * values[4] +
                        values[5] * values[5]) < 1.e-10)) {
    if (debugPK)
      XLAL_PRINT_INFO("\n Integration stopping |pvec|<1e-10\n");
    fflush(NULL);
    params->termination_reason = 4;

    return 1;
  }

  /* **************************************************************** */
  /*                         Omega related                            */
  /* **************************************************************** */
  /* Terminate when omega reaches peak, and separation is < 4M */
  if (r2 < 16. && omega < params->eobParams->omega)
    params->eobParams->omegaPeaked = 1;

  /* If omega has gone through a second extremum, break */
  if (r2 < 4. && params->eobParams->omegaPeaked == 1 &&
      omega > params->eobParams->omega) {
    if (debugPK) {
      XLAL_PRINT_INFO(
          "\n Integration stopping, omega reached second extremum\n");
      fflush(NULL);
    }
    params->termination_reason = 5;

    return 1;
  }

  /* If Momega did not evolve above 0.01 even though r < 4 or omega<0.14 for
   * r<2, break */
  if ((r2 < 16. && omega < 0.04) ||
      (r2 < 4. && omega < 0.14 && params->eobParams->omegaPeaked == 1)) {
    if (debugPK) {
      XLAL_PRINT_INFO("\n Integration stopping for omega below threshold, "
                      "omega=%f at r = %f\n",
                      omega, sqrt(r2));
      fflush(NULL);
    }
    params->termination_reason = 6;

    return 1;
  }

  if (r2 < 16. && omega > 1.) {
    if (debugPK) {
      XLAL_PRINT_INFO("\n Integration stopping, omega>1 at r = %f\n", sqrt(r2));
      fflush(NULL);
    }
    params->termination_reason = 7;

    return 1;
  }
  params->eobParams->omega = omega;

  /* **************************************************************** */
  /*              related to Numerical values of x/p/derivatives      */
  /* **************************************************************** */

  /* If momentum derivatives are too large numerically, break */
  if (r2 < 25 && (fabs(dvalues[3]) > 10 || fabs(dvalues[4]) > 10 ||
                  fabs(dvalues[5]) > 10)) {
    if (debugPK) {
      XLAL_PRINT_INFO("\n Integration stopping, dpdt > 10 -- too large!\n");
      fflush(NULL);
    }
    params->termination_reason = 8;

    return 1;
  }

  /* If p_\Phi is too large numerically, break */
  if (r2 < 16. && values[5] > 10) {
    if (debugPK) {
      XLAL_PRINT_INFO("Integration stopping, Pphi > 10 now\n\n");
      fflush(NULL);
    }
    params->termination_reason = 9;

    return 1;
  }
  /* If rdot inclreases, break */
  if (r2 < 9. && rdot > params->prev_dr) {
    if (debugPK) {
      XLAL_PRINT_INFO("\n Integration stopping, dr/dt increasing!\n");
      fflush(NULL);
    }
    params->prev_dr = rdot;
    params->termination_reason = 10;

    return 1;
  }
  params->prev_dr = rdot;

  /* **************************************************************** */
  /*              Last resort conditions                              */
  /* **************************************************************** */

  /* Very verbose output */
  if (debugPKverbose && r2 < 16.) {
    XLAL_PRINT_INFO("%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f\n", t,
                    values[0], values[1], values[2], values[3], values[4],
                    values[5], values[6], values[7], values[8], values[9],
                    values[10], values[11], values[12], values[13], omega);
  }

  return GSL_SUCCESS;
}

/**
 * Stopping condition for the regular resolution SEOBNRv1/2 orbital evolution
 * -- stop when reaching max orbital frequency in strong field.
 * At each test,
 * if omega starts to decrease, return 1 to stop evolution;
 * if not, update omega with current value and return GSL_SUCCESS to continue
 * evolution.
 */
static int XLALEOBSpinPrecAlignedStopCondition(
    double UNUSED t,       /**< UNUSED */
    const double values[], /**< dynamical variable values */
    double dvalues[],      /**< dynamical variable time derivative values */
    void *funcParams       /**< physical parameters */
) {
  int debugPK = 0;
  REAL8 omega, r;
  SpinEOBParams *params = (SpinEOBParams *)funcParams;

  r = values[0];
  omega = dvalues[1];
  if (debugPK) {
    XLAL_PRINT_INFO("XLALEOBSpinPrecAlignedStopCondition:: r = %e\n", r);
  }

  if (r < 6. && omega < params->eobParams->omega) {
    return 1;
  }

  params->eobParams->omega = omega;
  return GSL_SUCCESS;
}

/**
 * Stopping condition for the high resolution SEOBNRv4.
 */
static int XLALSpinPrecAlignedHiSRStopCondition(
    double UNUSED t,              /**< UNUSED */
    const double UNUSED values[], /**< dynamical variable values */
    double dvalues[],       /**< dynamical variable time derivative values */
    void UNUSED *funcParams /**< physical parameters */
) {

  REAL8 omega, r;
  UINT4 counter;
  SpinEOBParams *params = (SpinEOBParams *)funcParams;
  r = values[0];
  omega = dvalues[1];
  counter = params->eobParams->omegaPeaked;

  if (r < 6. && omega < params->eobParams->omega) {

    params->eobParams->omegaPeaked = counter + 1;
  }
  if (dvalues[2] >= 0. || params->eobParams->omegaPeaked == 5 ||
      isnan(dvalues[3]) || isnan(dvalues[2]) || isnan(dvalues[1]) ||
      isnan(dvalues[0])) {

    return 1;
  }
  params->eobParams->omega = omega;
  return GSL_SUCCESS;
}

/**
 * ModeArray is a structure which allows to select the the co-precessing frame
 * modes to include in the waveform. This function will create a structure with
 * the default modes for every model
 */
static INT4 XLALSetup_EOB__std_mode_array_structure(LALValue *ModeArray,
                                                    UINT4 PrecEOBversion) {

  /* setup ModeArray */

  if (PrecEOBversion == v4PHM.number) {
    /* Adding all the modes of SEOBNRv4PHM
    * i.e. [(2,2),(2,1),(3,3),(4,4),(5,5)]
    the relative -m modes are added automatically*/
    XLALSimInspiralModeArrayActivateMode(ModeArray, 2, 2);
    XLALSimInspiralModeArrayActivateMode(ModeArray, 2, 1);
    XLALSimInspiralModeArrayActivateMode(ModeArray, 3, 3);
    XLALSimInspiralModeArrayActivateMode(ModeArray, 4, 4);
    XLALSimInspiralModeArrayActivateMode(ModeArray, 5, 5);
  }
  if (PrecEOBversion == v4P.number) {
    /* Adding all the modes of SEOBNRv4P
    * i.e. [(2,2),(2,1)]
    the relative -m modes are added automatically*/
    XLALSimInspiralModeArrayActivateMode(ModeArray, 2, 2);
    XLALSimInspiralModeArrayActivateMode(ModeArray, 2, 1);
  }

  return XLAL_SUCCESS;
}

/**
 * ModeArray is a structure which allows to select the the co-precessing frame
 * modes to include in the waveform. This function check if the selected modes
 * are available for a given model
 */
static INT4 XLALCheck_EOB_mode_array_structure(LALValue *ModeArray,
                                               UINT4 PrecEOBversion) {
  INT4 flagTrue = 0;
  UINT4 modeL;
  UINT4 modeM;
  UINT4 nModes;
  const UINT4 lmModes[5][2] = {{2, 2}, {2, 1}, {3, 3}, {4, 4}, {5, 5}};
  if (PrecEOBversion == v4PHM.number) {
    /*If one select SEOBNRv4PHM all the modes above are selected to check
     */
    nModes = 5;
  } else {
    /*If not only the modes 22 and 21 are selected to check
     */
    nModes = 2;
  }
  /* First check if the user is entering a mode with negative m */
  /* This function only takes positive m and then selects automatically +- m */
  for (UINT4 ELL = 2; ELL <= _SEOB_MODES_LMAX; ELL++) {
    for (INT4 EMM = -ELL; EMM < 0; EMM++) {
      if (XLALSimInspiralModeArrayIsModeActive(ModeArray, ELL, EMM) == 1) {
        XLALPrintError("Mode (%d,%d) has a negative m. \
        In mode array you should specify (l,|m|). The code will automatically return +- m modes\n",
                       ELL, EMM);
        return XLAL_FAILURE;
      }
    }
  }

  /*Loop over all the possible modes
   *we only check +m modes, when one select (l,m) mode is actually
   *selecting (l,|m|) mode
   */
  for (UINT4 ELL = 2; ELL <= _SEOB_MODES_LMAX; ELL++) {
    for (UINT4 EMM = 0; EMM <= ELL; EMM++) {
      if (XLALSimInspiralModeArrayIsModeActive(ModeArray, ELL, EMM) == 1) {
        for (UINT4 k = 0; k < nModes; k++) {
          modeL = lmModes[k][0];
          modeM = lmModes[k][1];
          if ((modeL == ELL) && (modeM == EMM)) {
            flagTrue = 1;
          }
        }
        /*For each active mode check if is available for the selected model
         */
        if (flagTrue != 1) {
          if (PrecEOBversion == v4PHM.number) {
            XLALPrintError("Mode (%d,%d) is not available for the model %s.\n",
                           ELL, EMM, v4PHM.name);
            return XLAL_FAILURE;
          }
          if (PrecEOBversion == v4P.number) {
            XLALPrintError("Mode (%d,%d) is not available for the model %s.\n",
                           ELL, EMM, v4P.name);
            return XLAL_FAILURE;
          }
        }
        flagTrue = 0;
      }
    }
  }

  return XLAL_SUCCESS;
}

/**
 * Standard interface for SEOBNRv4P waveform generator: calls
 * XLALSimIMRSpinPrecEOBWaveformAll
 */
int XLALSimIMRSpinPrecEOBWaveform(
    REAL8TimeSeries **hplus,  /**<< OUTPUT, +-polarization waveform */
    REAL8TimeSeries **hcross, /**<< OUTPUT, x-polarization waveform */
    const REAL8 phiC,         /**<< coalescence orbital phase (rad) */
    const REAL8 deltaT,       /**<< sampling time step */
    const REAL8 m1SI,         /**<< mass-1 in SI unit (kg) */
    const REAL8 m2SI,         /**<< mass-2 in SI unit (kg) 8*/
    const REAL8 fMin,         /**<< starting frequency (Hz) */
    const REAL8 r,            /**<< luminosity distance in SI unit (m) */
    const REAL8 inc,          /**<< inclination angle */
    const REAL8 INspin1[],    /**<< spin1 */
    const REAL8 INspin2[],    /**<< spin2 */
    UNUSED const UINT4
        PrecEOBversion, /**<< Precessing EOB waveform generator model */
    LALDict *LALParams  /**<< Dictionary of additional wf parameters */
) {

  REAL8Vector *dyn_Low = NULL;
  REAL8Vector *dyn_Hi = NULL;
  REAL8Vector *dyn_all = NULL;
  REAL8Vector *t_vec_modes = NULL;
  REAL8Vector *hP22_amp = NULL;
  REAL8Vector *hP22_phase = NULL;
  REAL8Vector *hP21_amp = NULL;
  REAL8Vector *hP21_phase = NULL;
  REAL8Vector *hP33_amp = NULL;
  REAL8Vector *hP33_phase = NULL;
  REAL8Vector *hP44_amp = NULL;
  REAL8Vector *hP44_phase = NULL;
  REAL8Vector *hP55_amp = NULL;
  REAL8Vector *hP55_phase = NULL;
  REAL8Vector *alphaJ2P = NULL;
  REAL8Vector *betaJ2P = NULL;
  REAL8Vector *gammaJ2P = NULL;
  REAL8Vector *AttachPars = NULL;

  /** This time series contains harmonics in precessing (P) frame, no RD, for
   * the end of the signal (high samling part)*/
  SphHarmTimeSeries *hIlm = NULL;
  /** This stores harmonics in J-frame, no RD, for the end of the signal (high
   * sampling part) */
  SphHarmTimeSeries *hJlm = NULL;

  /* Import the set of modes requested by the user if available, if not
  load the default modes  */
  LALValue *modearray = XLALSimInspiralWaveformParamsLookupModeArray(LALParams);
  if (modearray == NULL) {
    modearray = XLALSimInspiralCreateModeArray();
    XLALSetup_EOB__std_mode_array_structure(modearray, PrecEOBversion);
  }
  /*Check that the modes chosen are available for the given model*/
  if (XLALCheck_EOB_mode_array_structure(modearray, PrecEOBversion) ==
      XLAL_FAILURE) {
    XLALPrintError("Not available mode chosen.\n");
    XLAL_ERROR(XLAL_EFUNC);
  }

  /* Set of SEOB flags */
  LALDict *seobflags = XLALCreateDict();
  /* Spin-aligned model v4 */
  XLALDictInsertINT4Value(seobflags, "SEOBNRv4P_SpinAlignedEOBversion", 4);
  /* Generate P-frame modes m<0 with the symmetry hP_l-m ~ (-1)^l hP_lm* */
  XLALDictInsertINT4Value(seobflags, "SEOBNRv4P_SymmetrizehPlminusm", 1);
  /* Use numerical or analytical derivatives of the Hamiltonian
   Default is numerical with the flag 1*/
  INT4 NumericalOrAnalyticalHamiltonianDerivative =
      XLALSimInspiralWaveformParamsLookupEOBChooseNumOrAnalHamDer(LALParams);
  /* NumericalOrAnalyticalHamiltonianDerivative can only be 0 (analytical) or 1
   * (numerical), let's check! */
  if ((NumericalOrAnalyticalHamiltonianDerivative != 0) &&
      (NumericalOrAnalyticalHamiltonianDerivative != 1)) {
    XLALPrintError("XLAL Error - %s: Unknown value for the derivative of the "
                   "Hamiltonian flag. \nAt present only "
                   "1 (numerical derivative) or 0 (analytical derivative) are "
                   "available.\n",
                   __func__);
    XLAL_ERROR(XLAL_EINVAL);
  }
  if (NumericalOrAnalyticalHamiltonianDerivative ==
      FLAG_SEOBNRv4P_HAMILTONIAN_DERIVATIVE_NUMERICAL) {
    XLALDictInsertINT4Value(seobflags, "SEOBNRv4P_HamiltonianDerivative",
                            FLAG_SEOBNRv4P_HAMILTONIAN_DERIVATIVE_NUMERICAL);
  } else {
    XLALDictInsertINT4Value(seobflags, "SEOBNRv4P_HamiltonianDerivative",
                            NumericalOrAnalyticalHamiltonianDerivative);
  }
  /* Extension of Euler angles post-merger: simple precession around final J at
   * a rate set by QNMs */
  XLALDictInsertINT4Value(seobflags, "SEOBNRv4P_euler_extension",
                          FLAG_SEOBNRv4P_EULEREXT_QNM_SIMPLE_PRECESSION);
  /* Z-axis of the radiation frame L */
  XLALDictInsertINT4Value(seobflags, "SEOBNRv4P_Zframe",
                          FLAG_SEOBNRv4P_ZFRAME_L);
  /* No debug output */
  XLALDictInsertINT4Value(seobflags, "SEOBNRv4P_debug", 0);
  int ret = XLAL_SUCCESS;
  XLAL_TRY(XLALSimIMRSpinPrecEOBWaveformAll(
               hplus, hcross, &hIlm, &hJlm, &dyn_Low, &dyn_Hi, &dyn_all,
               &t_vec_modes, &hP22_amp, &hP22_phase, &hP21_amp, &hP21_phase,
               &hP33_amp, &hP33_phase, &hP44_amp, &hP44_phase, &hP55_amp,
               &hP55_phase, &alphaJ2P, &betaJ2P, &gammaJ2P, &AttachPars, phiC,
               deltaT, m1SI, m2SI, fMin, r, inc, INspin1[0], INspin1[1],
               INspin1[2], INspin2[0], INspin2[1], INspin2[2], modearray,
               seobflags),
           ret);
  /*
  if (ret == XLAL_SUCCESS) {
    if (*hplus == NULL || *hcross == NULL) {
      XLALPrintError(
          "Houston-2, we've got a problem SOS, SOS, SOS, the waveform "
          "generator returns NULL!!!... m1 = %.18e, m2 = %.18e, fMin = %.18e, "
          "inclination = %.18e,   spin1 = {%.18e, %.18e, %.18e},   spin2 = "
          "{%.18e, %.18e, %.18e} \n",
          m1SI / LAL_MSUN_SI, m2SI / LAL_MSUN_SI, (double)fMin, (double)inc,
          INspin1[0], INspin1[1], INspin1[2], INspin2[0], INspin2[1],
          INspin2[2]);
      XLAL_ERROR(XLAL_ENOMEM);
    }
    if ((*hplus)->data == NULL || (*hcross)->data == NULL) {
      XLALPrintError(
          "Houston-3, we've got a problem SOS, SOS, SOS, the waveform "
          "generator returns NULL!!!... m1 = %.18e, m2 = %.18e, fMin = %.18e, "
          "inclination = %.18e,   spin1 = {%.18e, %.18e, %.18e},   spin2 = "
          "{%.18e, %.18e, %.18e} \n",
          m1SI / LAL_MSUN_SI, m2SI / LAL_MSUN_SI, (double)fMin, (double)inc,
          INspin1[0], INspin1[1], INspin1[2], INspin2[0], INspin2[1],
          INspin2[2]);
      XLAL_ERROR(XLAL_ENOMEM);
    }
    }*/
  if (modearray)
    XLALDestroyValue(modearray);
  if (seobflags)
    XLALDestroyDict(seobflags);
  if (dyn_Low)
    XLALDestroyREAL8Vector(dyn_Low);
  if (dyn_Hi)
    XLALDestroyREAL8Vector(dyn_Hi);
  if (dyn_all)
    XLALDestroyREAL8Vector(dyn_all);

  if (t_vec_modes)
    XLALDestroyREAL8Vector(t_vec_modes);
  if (hP22_amp)
    XLALDestroyREAL8Vector(hP22_amp);
  if (hP22_phase)
    XLALDestroyREAL8Vector(hP22_phase);
  if (hP21_amp)
    XLALDestroyREAL8Vector(hP21_amp);
  if (hP21_phase)
    XLALDestroyREAL8Vector(hP21_phase);
  if (hP33_amp)
    XLALDestroyREAL8Vector(hP33_amp);
  if (hP33_phase)
    XLALDestroyREAL8Vector(hP33_phase);
  if (hP44_amp)
    XLALDestroyREAL8Vector(hP44_amp);
  if (hP44_phase)
    XLALDestroyREAL8Vector(hP44_phase);
  if (hP55_amp)
    XLALDestroyREAL8Vector(hP55_amp);
  if (hP55_phase)
    XLALDestroyREAL8Vector(hP55_phase);

  if (alphaJ2P)
    XLALDestroyREAL8Vector(alphaJ2P);
  if (betaJ2P)
    XLALDestroyREAL8Vector(betaJ2P);
  if (gammaJ2P)
    XLALDestroyREAL8Vector(gammaJ2P);
  if (AttachPars)
    XLALDestroyREAL8Vector(AttachPars);
  if (hIlm)
    XLALDestroySphHarmTimeSeries(hIlm);
  if (hJlm)
    XLALDestroySphHarmTimeSeries(hJlm);
  if (ret != XLAL_SUCCESS) {
    XLAL_ERROR(ret);
  }
  return ret;
}
/**
 * This function returns the maximum ell in the mode array.
 * Note that m<=0 modes are ignored and a warning given.
 */
static int
SEOBGetLMaxInModeArray(LALValue *modearray, /**<< Input: ModeArray structure */
                       int lmax /**<< Input: maximum value of l to explore --
                                   possible modes with l>lmax will be ignored */
) {
  /* Populate array */
  INT4 lmax_array = 0;
  for (INT4 l = 2; l <= lmax; l++) {
    for (INT4 m = l; m >= -l; m--) {
      if (m > 0) {
        if (XLALSimInspiralModeArrayIsModeActive(modearray, l, m)) {
          if (lmax_array < l)
            lmax_array = l;
        }
      } else {
        XLAL_PRINT_WARNING(
            "XLAL Warning - %s: mode (l,m)=(%d,%d) present in mode array -- "
            "in our conventions, we only consider m>0. Mode ignored for "
            "counting.\n",
            __func__, l, m);
      }
    }
  }

  return lmax_array;
}

/**
 * Standard interface for SEOBNRv4P modes generator: calls
 * XLALSimIMRSpinPrecEOBWaveformAll
 */
SphHarmTimeSeries *XLALSimIMRSpinPrecEOBModes(
    const REAL8 deltaT,    /**<< sampling time step */
    const REAL8 m1SI,      /**<< mass-1 in SI unit (kg) */
    const REAL8 m2SI,      /**<< mass-2 in SI unit (kg) 8*/
    const REAL8 fMin,      /**<< starting frequency (Hz) */
    const REAL8 r,         /**<< luminosity distance in SI unit (m) */
    const REAL8 INspin1[], /**<< spin1 */
    const REAL8 INspin2[], /**<< spin2 */
    UNUSED const UINT4
        PrecEOBversion, /**<< Precessing EOB waveform generator model */
    LALDict *LALParams  /**<< Dictionary of additional wf parameters */
) {

  REAL8Vector *dyn_Low = NULL;
  REAL8Vector *dyn_Hi = NULL;
  REAL8Vector *dyn_all = NULL;
  REAL8Vector *t_vec_modes = NULL;
  REAL8Vector *hP22_amp = NULL;
  REAL8Vector *hP22_phase = NULL;
  REAL8Vector *hP21_amp = NULL;
  REAL8Vector *hP21_phase = NULL;
  REAL8Vector *hP33_amp = NULL;
  REAL8Vector *hP33_phase = NULL;
  REAL8Vector *hP44_amp = NULL;
  REAL8Vector *hP44_phase = NULL;
  REAL8Vector *hP55_amp = NULL;
  REAL8Vector *hP55_phase = NULL;
  REAL8Vector *alphaJ2P = NULL;
  REAL8Vector *betaJ2P = NULL;
  REAL8Vector *gammaJ2P = NULL;
  REAL8Vector *AttachPars = NULL;
  REAL8TimeSeries *hplus = NULL;
  REAL8TimeSeries *hcross = NULL;

  /** This time series contains harmonics in precessing (P) frame, no RD, for
   * the end of the signal (high samling part)*/
  SphHarmTimeSeries *hIlm = NULL;
  /** This stores harmonics in J-frame, no RD, for the end of the signal (high
   * sampling part) */
  SphHarmTimeSeries *hJlm = NULL;

  /* Import the set of modes requested by the user if available, if not
  load the default modes  */
  LALValue *modearray = XLALSimInspiralWaveformParamsLookupModeArray(LALParams);
  if (modearray == NULL) {
    modearray = XLALSimInspiralCreateModeArray();
    XLALSetup_EOB__std_mode_array_structure(modearray, PrecEOBversion);
  }
  /*Check that the modes chosen are available for the given model*/
  if (XLALCheck_EOB_mode_array_structure(modearray, PrecEOBversion) ==
      XLAL_FAILURE) {
    XLALPrintError("Not available mode chosen.\n");
    XLAL_ERROR_NULL(XLAL_EFUNC);
  }

  /* Set of SEOB flags */
  LALDict *seobflags = XLALCreateDict();
  /* Spin-aligned model v4 */
  XLALDictInsertINT4Value(seobflags, "SEOBNRv4P_SpinAlignedEOBversion", 4);
  /* Generate P-frame modes m<0 with the symmetry hP_l-m ~ (-1)^l hP_lm* */
  XLALDictInsertINT4Value(seobflags, "SEOBNRv4P_SymmetrizehPlminusm", 1);
  /* Use numerical or analytical derivatives of the Hamiltonian
   Default is numerical with the flag 1*/
  INT4 NumericalOrAnalyticalHamiltonianDerivative =
      XLALSimInspiralWaveformParamsLookupEOBChooseNumOrAnalHamDer(LALParams);
  /* NumericalOrAnalyticalHamiltonianDerivative can only be 0 (analytical) or 1
   * (numerical), let's check! */
  if ((NumericalOrAnalyticalHamiltonianDerivative != 0) &&
      (NumericalOrAnalyticalHamiltonianDerivative != 1)) {
    XLALPrintError("XLAL Error - %s: Unknown value for the derivative of the "
                   "Hamiltonian flag. \nAt present only "
                   "1 (numerical derivative) or 0 (analytical derivative) are "
                   "available.\n",
                   __func__);
    XLAL_ERROR_NULL(XLAL_EFUNC);
  }
  if (NumericalOrAnalyticalHamiltonianDerivative ==
      FLAG_SEOBNRv4P_HAMILTONIAN_DERIVATIVE_NUMERICAL) {
    XLALDictInsertINT4Value(seobflags, "SEOBNRv4P_HamiltonianDerivative",
                            FLAG_SEOBNRv4P_HAMILTONIAN_DERIVATIVE_NUMERICAL);
  } else {
    XLALDictInsertINT4Value(seobflags, "SEOBNRv4P_HamiltonianDerivative",
                            NumericalOrAnalyticalHamiltonianDerivative);
  }
  /* Extension of Euler angles post-merger: simple precession around final J at
   * a rate set by QNMs */
  XLALDictInsertINT4Value(seobflags, "SEOBNRv4P_euler_extension",
                          FLAG_SEOBNRv4P_EULEREXT_QNM_SIMPLE_PRECESSION);
  /* Z-axis of the radiation frame L */
  XLALDictInsertINT4Value(seobflags, "SEOBNRv4P_Zframe",
                          FLAG_SEOBNRv4P_ZFRAME_L);
  /* No debug output */
  XLALDictInsertINT4Value(seobflags, "SEOBNRv4P_debug", 0);
  int ret = XLAL_SUCCESS;
  XLAL_TRY(XLALSimIMRSpinPrecEOBWaveformAll(
               &hplus, &hcross, &hIlm, &hJlm, &dyn_Low, &dyn_Hi, &dyn_all,
               &t_vec_modes, &hP22_amp, &hP22_phase, &hP21_amp, &hP21_phase,
               &hP33_amp, &hP33_phase, &hP44_amp, &hP44_phase, &hP55_amp,
               &hP55_phase, &alphaJ2P, &betaJ2P, &gammaJ2P, &AttachPars, 0.,
               deltaT, m1SI, m2SI, fMin, r, 0., INspin1[0], INspin1[1],
               INspin1[2], INspin2[0], INspin2[1], INspin2[2], modearray,
               seobflags),
           ret);

  /* Here we multiply the appropriate factor to the modes to convert them in
   * dimensional units */
  REAL8 m1 = m1SI / LAL_MSUN_SI;
  REAL8 m2 = m2SI / LAL_MSUN_SI;
  REAL8 mTotal = m1 + m2;
  REAL8 mTScaled = mTotal * LAL_MTSUN_SI;

  /* Initialize amplitude factor */
  REAL8 amp0 = mTotal * LAL_MRSUN_SI / r;
  char mode_string[32];

  INT4 modes_lmax = SEOBGetLMaxInModeArray(modearray, _SEOB_MODES_LMAX);
  UINT4 retLen = hIlm->tdata->length;
  SphHarmTimeSeries *hIlm_dimfull = NULL;
  LIGOTimeGPS tGPS = LIGOTIMEGPSZERO;
  XLALGPSAdd(&tGPS, -mTScaled * AttachPars->data[2]);

  for (INT4 l = 2; l <= modes_lmax; l++) {
    for (INT4 m = -l; m <= l; m++) {

      /* Get dimensionless mode hIlm */
      COMPLEX16TimeSeries *mode_dimless =
          XLALSphHarmTimeSeriesGetMode(hIlm, l, m);

      /* Time series for dimensionful mode */
      COMPLEX16TimeSeries *mode_dimfull = XLALCreateCOMPLEX16TimeSeries(
          mode_string, &tGPS, 0., deltaT, &lalStrainUnit, retLen);
      memset(mode_dimfull->data->data, 0, retLen * sizeof(COMPLEX16));

      for (UINT4 i = 0; i < mode_dimless->data->length; i++) {
        /* The factor -1 here is to rotate EOB modes in LAL convention
         * see https://dcc.ligo.org/LIGO-G1900275  */
        mode_dimfull->data->data[i] =
            -1. * (COMPLEX16)amp0 * mode_dimless->data->data[i];
      }
      hIlm_dimfull =
          XLALSphHarmTimeSeriesAddMode(hIlm_dimfull, mode_dimfull, l, m);
      XLALDestroyCOMPLEX16TimeSeries(mode_dimless);
      XLALDestroyCOMPLEX16TimeSeries(mode_dimfull);
    }
  }

  /*
  if (ret == XLAL_SUCCESS) {
    if (*hplus == NULL || *hcross == NULL) {
      XLALPrintError(
          "Houston-2, we've got a problem SOS, SOS, SOS, the waveform "
          "generator returns NULL!!!... m1 = %.18e, m2 = %.18e, fMin = %.18e, "
          "inclination = %.18e,   spin1 = {%.18e, %.18e, %.18e},   spin2 = "
          "{%.18e, %.18e, %.18e} \n",
          m1SI / LAL_MSUN_SI, m2SI / LAL_MSUN_SI, (double)fMin, (double)inc,
          INspin1[0], INspin1[1], INspin1[2], INspin2[0], INspin2[1],
          INspin2[2]);
      XLAL_ERROR(XLAL_ENOMEM);
    }
    if ((*hplus)->data == NULL || (*hcross)->data == NULL) {
      XLALPrintError(
          "Houston-3, we've got a problem SOS, SOS, SOS, the waveform "
          "generator returns NULL!!!... m1 = %.18e, m2 = %.18e, fMin = %.18e, "
          "inclination = %.18e,   spin1 = {%.18e, %.18e, %.18e},   spin2 = "
          "{%.18e, %.18e, %.18e} \n",
          m1SI / LAL_MSUN_SI, m2SI / LAL_MSUN_SI, (double)fMin, (double)inc,
          INspin1[0], INspin1[1], INspin1[2], INspin2[0], INspin2[1],
          INspin2[2]);
      XLAL_ERROR(XLAL_ENOMEM);
    }
    }*/

  if (modearray)
    XLALDestroyValue(modearray);
  if (seobflags)
    XLALDestroyDict(seobflags);
  if (dyn_Low)
    XLALDestroyREAL8Vector(dyn_Low);
  if (dyn_Hi)
    XLALDestroyREAL8Vector(dyn_Hi);
  if (dyn_all)
    XLALDestroyREAL8Vector(dyn_all);

  if (t_vec_modes)
    XLALDestroyREAL8Vector(t_vec_modes);
  if (hP22_amp)
    XLALDestroyREAL8Vector(hP22_amp);
  if (hP22_phase)
    XLALDestroyREAL8Vector(hP22_phase);
  if (hP21_amp)
    XLALDestroyREAL8Vector(hP21_amp);
  if (hP21_phase)
    XLALDestroyREAL8Vector(hP21_phase);
  if (hP33_amp)
    XLALDestroyREAL8Vector(hP33_amp);
  if (hP33_phase)
    XLALDestroyREAL8Vector(hP33_phase);
  if (hP44_amp)
    XLALDestroyREAL8Vector(hP44_amp);
  if (hP44_phase)
    XLALDestroyREAL8Vector(hP44_phase);
  if (hP55_amp)
    XLALDestroyREAL8Vector(hP55_amp);
  if (hP55_phase)
    XLALDestroyREAL8Vector(hP55_phase);

  if (alphaJ2P)
    XLALDestroyREAL8Vector(alphaJ2P);
  if (betaJ2P)
    XLALDestroyREAL8Vector(betaJ2P);
  if (gammaJ2P)
    XLALDestroyREAL8Vector(gammaJ2P);
  if (AttachPars)
    XLALDestroyREAL8Vector(AttachPars);
  if (hJlm)
    XLALDestroySphHarmTimeSeries(hJlm);
  if (ret != XLAL_SUCCESS) {
    XLAL_ERROR_NULL(XLAL_EFUNC);
  }
  return hIlm_dimfull;
}

static int CAmpPhaseSequence_Init(
    CAmpPhaseSequence **campphase, /* Double pointer to campphase sequence */
    int size                       /* Size of data */
) {
  /* Check input pointer */
  if (!campphase) {
    XLALPrintError("XLAL Error - %s: input double pointer is NULL.\n",
                   __func__);
    XLAL_ERROR(XLAL_EINVAL);
  }
  if (*campphase) {
    XLALPrintError("XLAL Error - %s: input pointer is not NULL.\n", __func__);
    XLAL_ERROR(XLAL_EINVAL);
  }

  /* Allocate structure */
  *campphase = XLALMalloc(sizeof(CAmpPhaseSequence));

  /* Allocate storage for data and initialize to 0 */
  if (!((*campphase)->xdata = XLALCreateREAL8Vector(size))) {
    XLALPrintError("XLAL Error - %s: failed to create REAL8Vector xdata.\n",
                   __func__);
    XLAL_ERROR(XLAL_ENOMEM);
  }
  if (!((*campphase)->camp_real = XLALCreateREAL8Vector(size))) {
    XLALPrintError("XLAL Error - %s: failed to create REAL8Vector camp_real.\n",
                   __func__);
    XLAL_ERROR(XLAL_ENOMEM);
  }
  if (!((*campphase)->camp_imag = XLALCreateREAL8Vector(size))) {
    XLALPrintError("XLAL Error - %s: failed to create REAL8Vector camp_imag.\n",
                   __func__);
    XLAL_ERROR(XLAL_ENOMEM);
  }
  if (!((*campphase)->phase = XLALCreateREAL8Vector(size))) {
    XLALPrintError("XLAL Error - %s: failed to create REAL8Vector phase.\n",
                   __func__);
    XLAL_ERROR(XLAL_ENOMEM);
  }
  memset((*campphase)->xdata->data, 0, size * sizeof(REAL8));
  memset((*campphase)->camp_real->data, 0, size * sizeof(REAL8));
  memset((*campphase)->camp_imag->data, 0, size * sizeof(REAL8));
  memset((*campphase)->phase->data, 0, size * sizeof(REAL8));

  return XLAL_SUCCESS;
}

static int CAmpPhaseSequence_Destroy(
    CAmpPhaseSequence *campphase /* Pointer to structure to be destroyed */
) {
  /* Raise an error if NULL pointer */
  if (!campphase) {
    XLALPrintError("XLAL Error - %s: data is a NULL pointer.\n", __func__);
    XLAL_ERROR(XLAL_EINVAL);
  }
  if (campphase->xdata)
    XLALDestroyREAL8Vector(campphase->xdata);
  if (campphase->camp_real)
    XLALDestroyREAL8Vector(campphase->camp_real);
  if (campphase->camp_imag)
    XLALDestroyREAL8Vector(campphase->camp_imag);
  if (campphase->phase)
    XLALDestroyREAL8Vector(campphase->phase);
  XLALFree(campphase);

  return XLAL_SUCCESS;
}

static int SphHarmListEOBNonQCCoeffs_Destroy(
    SphHarmListEOBNonQCCoeffs *list /* Pointer to list to be destroyed */
) {
  SphHarmListEOBNonQCCoeffs *pop;
  while ((pop = list)) {
    if (pop->nqcCoeffs) { /* Internal EOBNonQCCoeffs is freed */
      XLALFree(pop->nqcCoeffs);
    }
    /* Go to next element */
    list = pop->next;
    /* Free structure itself */
    XLALFree(pop);
  }

  return XLAL_SUCCESS;
}

/* Note that we do NOT COPY the input mode */
/* The added data is simply passed by pointer */
/* The added data can therefore e.g. be destroyed if the list is destroyed */
static int SphHarmListEOBNonQCCoeffs_AddMode(
    SphHarmListEOBNonQCCoeffs *
        *list_prepended,       /* List structure to prepend to */
    EOBNonQCCoeffs *nqcCoeffs, /* Mode data to be added */
    UINT4 l,                   /*< Mode number l */
    INT4 m                     /*< Mode number m */
) {
  SphHarmListEOBNonQCCoeffs *list;
  /* Check if the node with this mode already exists */
  list = *list_prepended;
  while (list) {
    if (l == list->l && m == list->m) {
      break;
    }
    list = list->next;
  }
  if (list) { /* We don't allow for the case where the mode already exists in
                 the list*/
    XLALPrintError("XLAL Error - %s: tried to add an already existing mode to "
                   "a SphHarmListCAmpPhaseSequence.\n",
                   __func__);
    XLAL_ERROR(XLAL_EINVAL);
  } else {
    list = XLALMalloc(sizeof(SphHarmListEOBNonQCCoeffs));
  }
  list->l = l;
  list->m = m;
  if (nqcCoeffs) {
    list->nqcCoeffs = nqcCoeffs;
  } else {
    list->nqcCoeffs = NULL;
  }
  if (*list_prepended) {
    list->next = *list_prepended;
  } else {
    list->next = NULL;
  }
  *list_prepended = list;

  return XLAL_SUCCESS;
}

static SphHarmListEOBNonQCCoeffs *SphHarmListEOBNonQCCoeffs_GetMode(
    SphHarmListEOBNonQCCoeffs
        *list, /* List structure to get a particular mode from */
    UINT4 l,   /*< Mode number l */
    INT4 m     /*< Mode number m */
) {
  if (!list)
    return NULL;

  SphHarmListEOBNonQCCoeffs *itr = list;
  while (itr->l != l || itr->m != m) {
    itr = itr->next;
    if (!itr)
      return NULL;
  }
  /* Return a pointer to a SphHarmListCAmpPhaseSequence */
  return itr;
}

static int SphHarmListCAmpPhaseSequence_Destroy(
    SphHarmListCAmpPhaseSequence *list /* Pointer to list to be destroyed */
) {
  SphHarmListCAmpPhaseSequence *pop;
  while ((pop = list)) {
    if (pop->campphase) { /* Internal CAmpPhaseSequence is freed */
      if (CAmpPhaseSequence_Destroy(pop->campphase) == XLAL_FAILURE) {
        XLALPrintError(
            "XLAL Error - %s: failure in CAmpPhaseSequence_Destroy.\n",
            __func__);
        XLAL_ERROR(XLAL_EFUNC);
      }
    }
    /* Go to next element */
    list = pop->next;
    /* Free structure itself */
    XLALFree(pop);
  }

  return XLAL_SUCCESS;
}

/* Note that we do NOT COPY the input mode */
/* The added data is simply passed by pointer */
/* The added data can therefore e.g. be destroyed if the list is destroyed */
static int SphHarmListCAmpPhaseSequence_AddMode(
    SphHarmListCAmpPhaseSequence *
        *list_prepended,          /* List structure to prepend to */
    CAmpPhaseSequence *campphase, /* Mode data to be added */
    UINT4 l,                      /*< Mode number l */
    INT4 m                        /*< Mode number m */
) {
  SphHarmListCAmpPhaseSequence *list;
  /* Check if the node with this mode already exists */
  list = *list_prepended;
  while (list) {
    if (l == list->l && m == list->m) {
      break;
    }
    list = list->next;
  }
  if (list) { /* We don't allow for the case where the mode already exists in
                 the list*/
    XLALPrintError("XLAL Error - %s: tried to add an already existing mode to "
                   "a SphHarmListCAmpPhaseSequence.\n",
                   __func__);
    XLAL_ERROR(XLAL_EINVAL);
  } else {
    list = XLALMalloc(sizeof(SphHarmListCAmpPhaseSequence));
  }
  list->l = l;
  list->m = m;
  if (campphase) {
    list->campphase = campphase;
  } else {
    list->campphase = NULL;
  }
  if (*list_prepended) {
    list->next = *list_prepended;
  } else {
    list->next = NULL;
  }
  *list_prepended = list;

  return XLAL_SUCCESS;
}

static SphHarmListCAmpPhaseSequence *SphHarmListCAmpPhaseSequence_GetMode(
    SphHarmListCAmpPhaseSequence
        *list, /* List structure to get a particular mode from */
    UINT4 l,   /*< Mode number l */
    INT4 m     /*< Mode number m */
) {
  if (!list)
    return NULL;

  SphHarmListCAmpPhaseSequence *itr = list;
  while (itr->l != l || itr->m != m) {
    itr = itr->next;
    if (!itr)
      return NULL;
  }
  /* Return a pointer to a SphHarmListCAmpPhaseSequence */
  return itr;
}

static int SEOBdynamics_Destroy(SEOBdynamics *seobdynamics) {
  XLALDestroyREAL8Array(seobdynamics->array);
  XLALFree(seobdynamics);

  return XLAL_SUCCESS;
}

static int SEOBdynamics_Init(
    SEOBdynamics **seobdynamics, /**<< Output: pointer to the SOBdynamics */
    UINT4 retLen /**<< Input: length of dynamics data to allocate */
) {
  /* Check that the input double pointer is not NULL */
  if (!seobdynamics) {
    XLALPrintError("XLAL Error - %s: seobdynamics is a NULL double pointer.\n",
                   __func__);
    XLAL_ERROR(XLAL_EINVAL);
  }

  /* If double pointer points to an existing struct, destroy it first */
  if ((*seobdynamics)) {
    SEOBdynamics_Destroy(*seobdynamics);
  }

  /* Allocate struct */
  if (!(*seobdynamics = XLALMalloc(sizeof(SEOBdynamics)))) {
    XLALPrintError("XLAL Error - %s: failed to allocate struct SEOBdynamics.\n",
                   __func__);
    XLAL_ERROR(XLAL_ENOMEM);
  }

  /* Length of data */
  (*seobdynamics)->length = retLen;

  /* Allocate array for the data */
  if (!((*seobdynamics)->array =
            XLALCreateREAL8ArrayL(2, v4PdynamicsVariables, retLen))) {
    XLALPrintError(
        "XLAL Error - %s: failed to allocate REAL8Array seobdynamics->array.\n",
        __func__);
    XLAL_ERROR(XLAL_ENOMEM);
  }

  /* Set array pointers corresponding to the data vectors (successive vectors of
   * length retLen in the 1D array data) */
  (*seobdynamics)->tVec = (*seobdynamics)->array->data;
  (*seobdynamics)->posVecx = (*seobdynamics)->array->data + 1 * retLen;
  (*seobdynamics)->posVecy = (*seobdynamics)->array->data + 2 * retLen;
  (*seobdynamics)->posVecz = (*seobdynamics)->array->data + 3 * retLen;
  (*seobdynamics)->momVecx = (*seobdynamics)->array->data + 4 * retLen;
  (*seobdynamics)->momVecy = (*seobdynamics)->array->data + 5 * retLen;
  (*seobdynamics)->momVecz = (*seobdynamics)->array->data + 6 * retLen;
  (*seobdynamics)->s1Vecx = (*seobdynamics)->array->data + 7 * retLen;
  (*seobdynamics)->s1Vecy = (*seobdynamics)->array->data + 8 * retLen;
  (*seobdynamics)->s1Vecz = (*seobdynamics)->array->data + 9 * retLen;
  (*seobdynamics)->s2Vecx = (*seobdynamics)->array->data + 10 * retLen;
  (*seobdynamics)->s2Vecy = (*seobdynamics)->array->data + 11 * retLen;
  (*seobdynamics)->s2Vecz = (*seobdynamics)->array->data + 12 * retLen;
  (*seobdynamics)->phiDMod = (*seobdynamics)->array->data + 13 * retLen;
  (*seobdynamics)->phiMod = (*seobdynamics)->array->data + 14 * retLen;
  (*seobdynamics)->velVecx = (*seobdynamics)->array->data + 15 * retLen;
  (*seobdynamics)->velVecy = (*seobdynamics)->array->data + 16 * retLen;
  (*seobdynamics)->velVecz = (*seobdynamics)->array->data + 17 * retLen;
  (*seobdynamics)->polarrVec = (*seobdynamics)->array->data + 18 * retLen;
  (*seobdynamics)->polarphiVec = (*seobdynamics)->array->data + 19 * retLen;
  (*seobdynamics)->polarprVec = (*seobdynamics)->array->data + 20 * retLen;
  (*seobdynamics)->polarpphiVec = (*seobdynamics)->array->data + 21 * retLen;
  (*seobdynamics)->omegaVec = (*seobdynamics)->array->data + 22 * retLen;
  (*seobdynamics)->s1dotZVec = (*seobdynamics)->array->data + 23 * retLen;
  (*seobdynamics)->s2dotZVec = (*seobdynamics)->array->data + 24 * retLen;
  (*seobdynamics)->hamVec = (*seobdynamics)->array->data + 25 * retLen;

  return XLAL_SUCCESS;
}

/**
 * Functions to calculate symmetrized and antisymmetrized combinations
 * of the dimensionless spins projected on the radiation frame Z-axis (L or LN)
 */
static REAL8 SEOBCalculateChiS(REAL8 chi1dotZ, REAL8 chi2dotZ) {
  return 0.5 * (chi1dotZ + chi2dotZ);
}
static REAL8 SEOBCalculateChiA(REAL8 chi1dotZ, REAL8 chi2dotZ) {
  return 0.5 * (chi1dotZ - chi2dotZ);
}

/**
 * Function to calculate tplspin
 * See discussion below Eq. 4 of PRD 89, 061502(R) [arXiv:1311.2544] (2014)
 */
static REAL8 SEOBCalculatetplspin(REAL8 m1, REAL8 m2, REAL8 eta, REAL8 chi1dotZ,
                                  REAL8 chi2dotZ, INT4 SpinAlignedEOBversion) {
  REAL8 chiS, chiA, tplspin;
  chiS = SEOBCalculateChiS(chi1dotZ, chi2dotZ);
  chiA = SEOBCalculateChiA(chi1dotZ, chi2dotZ);

  switch (SpinAlignedEOBversion) {
  case 1:
    /* See below Eq. 17 of PRD 86, 024011 (2012) [arXiv:1202.0790] */
    tplspin = 0.0;
    break;
  case 2:
  case 4:
    /* See below Eq. 4 of PRD 89, 061502(R) (2014) [arXiv:1311.2544] */
    tplspin = (1. - 2. * eta) * chiS + (m1 - m2) / (m1 + m2) * chiA;
    break;
  default:
    XLALPrintError("XLAL Error - %s: Unknown SEOBNR version!\nAt present only "
                   "v1, v2 and v4 are available.\n",
                   __func__);
    XLAL_ERROR(XLAL_EINVAL);
    break;
  }
  return tplspin;
}

/**
 * Function to calculate normalized spin of the deformed-Kerr background in
 * SEOBNRv1. Eq. 5.2 of Barausse and Buonanno PRD 81, 084024 (2010) [arXiv:0912.3517].
 * Identical to XLALSimIMRSpinEOBCalculateSigmaKerr, except that the input spins are in
 * units of mTotal^2
 */
static int SEOBCalculateSigmaKerr(
    REAL8Vector *sigmaKerr, /**<< OUTPUT, normalized (to total mass) spin of
                               deformed-Kerr */
    REAL8Vector *s1,        /**<< spin vector 1, in units of mTotal^2 */
    REAL8Vector *s2         /**<< spin vector 2, in units of mTotal^2 */
) {
  for (UINT4 i = 0; i < 3; i++) {
    sigmaKerr->data[i] = (s1->data[i] + s2->data[i]);
  }
  return XLAL_SUCCESS;
}

/**
 * Function to calculate normalized spin of the test particle in SEOBNRv1.
 * Eq. 5.3 of Barausse and Buonanno PRD 81, 084024 (2010) [arXiv:0912.3517].
 * Identical to XLALSimIMRSpinEOBCalculateSigmaStar, except that the input spins
 * are in units of mTotal^2
 */
static int SEOBCalculateSigmaStar(
    REAL8Vector *sigmaStar, /**<< OUTPUT, normalized (to total mass) spin of
                               test particle */
    REAL8 mass1,            /**<< mass 1 */
    REAL8 mass2,            /**<< mass 2 */
    REAL8Vector *s1,        /**<< spin vector 1, in units of mTotal^2 */
    REAL8Vector *s2         /**<< spin vector 2, in units of mTotal^2 */
) {
  for (UINT4 i = 0; i < 3; i++) {
    sigmaStar->data[i] =
        (mass2 / mass1 * s1->data[i] + mass1 / mass2 * s2->data[i]);
  }
  return XLAL_SUCCESS;
}

/**
 * This function computes quantities (polardynamics, omega, s1dotZ, s2dotZ,
 * hamiltonian) derived from the dynamics as output by the integrator, and
 * returns a SEOBdynamics struct. Two choices for Z: L or LN. Note: this
 * function also applies when the spins are almost aligned and v4 is used.
 */
static int SEOBComputeExtendedSEOBdynamics(
    SEOBdynamics **seobdynamics, /**<< Output, double pointer to SEOBdynamics
                                    struct. If points to an existing struct, the
                                    latter will be destroyed */
    REAL8Array *dynamics, /**<< Input, array containing the dynamics as output
                             by the integrator */
    UINT4 retLen,         /**<< Input, length of the dynamics */
    SpinEOBParams *seobParams, /**<< SEOB parameters */
    flagSEOBNRv4P_hamiltonian_derivative
        flagHamiltonianDerivative, /**<< flag to choose between numerical and
                                      analytical Hamiltonian derivatives */
    flagSEOBNRv4P_Zframe
        flagZframe /**<< flag to choose Z direction of the frame, LN or L */
) {

  /* Create structure SEOBdynamics */
  SEOBdynamics_Init(seobdynamics, retLen);
  SEOBdynamics *seobdyn = *seobdynamics;

  /* Local variables */
  REAL8 rvec[3] = {0, 0, 0};
  REAL8 pvec[3] = {0, 0, 0};
  REAL8 spin1vec[3] = {0, 0, 0}; /* in units of mTotal^2 */
  REAL8 spin2vec[3] = {0, 0, 0}; /* in units of mTotal^2 */
  REAL8 rdotvec[3] = {0, 0, 0};
  REAL8 rcrossrdot[3] = {0, 0, 0};
  REAL8 rcrossp[3] = {0, 0, 0};
  REAL8 LNhat[3] = {0, 0, 0};
  REAL8 Lhat[3] = {0, 0, 0};
  REAL8 polarr, polarphi, polarpr, polarpphi, omega, s1dotZ, s2dotZ, ham;

  /* Allocate temporary vectors values, dvalues */
  REAL8Vector *values = NULL;
  REAL8Vector *dvalues = NULL;
  if (!(values = XLALCreateREAL8Vector(14)) ||
      !(dvalues = XLALCreateREAL8Vector(14))) {
    XLALPrintError(
        "XLAL Error - %s: failed to allocate REAL8Vector values, dvalues.\n",
        __func__);
    XLAL_ERROR(XLAL_ENOMEM);
  }
  memset(values->data, 0, (values->length) * sizeof(REAL8));
  memset(dvalues->data, 0, (dvalues->length) * sizeof(REAL8));

  /* Masses and coeffs from SpinEOBParams */
  REAL8 m1 = seobParams->eobParams->m1;
  REAL8 m2 = seobParams->eobParams->m2;
  REAL8 eta = seobParams->eobParams->eta;
  SpinEOBHCoeffs *seobCoeffs = seobParams->seobCoeffs;

  /* Copying directly the dynamics data in seobdynamics - 15 vectors of length
   * retLen */
  memcpy(seobdyn->array->data, dynamics->data, 15 * retLen * sizeof(REAL8));

  /* We will need a vector structure for sigmaKerr and sigmaStar */
  REAL8Vector *sigmaStar = NULL, *sigmaKerr = NULL;
  sigmaStar = XLALCreateREAL8Vector(3);
  sigmaKerr = XLALCreateREAL8Vector(3);
  memset(sigmaStar->data, 0, 3 * sizeof(REAL8));
  memset(sigmaKerr->data, 0, 3 * sizeof(REAL8));

  /* Loop to compute the derived quantities from the dynamics */
  UINT4 i, j;
  for (i = 0; i < retLen; i++) {

    /* Copy dynamics values in the temporary vector values -- time excepted */
    for (j = 0; j < 14; j++) {
      values->data[j] = dynamics->data[i + (j + 1) * retLen];
    }

    /* Computing velocity from Hamiltonian derivatives */
    if (flagHamiltonianDerivative ==
        FLAG_SEOBNRv4P_HAMILTONIAN_DERIVATIVE_ANALYTICAL) {
      if (XLALSpinPrecHcapRvecDerivative_exact(0, values->data, dvalues->data,
                                               (void *)seobParams) ==
          XLAL_FAILURE) {
        XLALPrintError("XLAL Error - %s: failure in "
                       "XLALSpinPrecHcapRvecDerivative_exact.\n",
                       __func__);
        XLAL_ERROR(XLAL_EDOM);
      }
    } else if (flagHamiltonianDerivative ==
               FLAG_SEOBNRv4P_HAMILTONIAN_DERIVATIVE_NUMERICAL) {
      if (XLALSpinPrecHcapRvecDerivative(0, values->data, dvalues->data,
                                         (void *)seobParams) == XLAL_FAILURE) {
        XLALPrintError(
            "XLAL Error - %s: failure in XLALSpinPrecHcapRvecDerivative.\n",
            __func__);
        XLAL_ERROR(XLAL_EDOM);
      }
    } else {
      XLALPrintError(
          "XLAL Error - %s: flagHamiltonianDerivative not recognized.\n",
          __func__);
      XLAL_ERROR(XLAL_EINVAL);
    }

    /* Compute omega and LNhat */
    for (j = 0; j < 3; j++) {
      rvec[j] = values->data[j];
      pvec[j] = values->data[3 + j];
      spin1vec[j] = values->data[6 + j];
      spin2vec[j] = values->data[9 + j];
      rdotvec[j] = dvalues->data[j];
    }
    cross_product(rvec, pvec, rcrossp);
    cross_product(rvec, rdotvec, rcrossrdot);
    REAL8 rcrossrdotNorm = sqrt(inner_product(rcrossrdot, rcrossrdot));
    for (j = 0; j < 3; j++) {
      LNhat[j] = rcrossrdot[j] / rcrossrdotNorm;
    }

    /* Polar dynamics */
    polarr = sqrt(inner_product(rvec, rvec));
    polarpr = inner_product(rvec, pvec) / polarr;
    polarphi = values->data[12] + values->data[13];
    REAL8 magL = sqrt(inner_product(rcrossp, rcrossp));
    for (j = 0; j < 3; j++) {
      Lhat[j] = rcrossp[j] / magL;
    }
    polarpphi = magL;

    /* Computing omega */
    omega = rcrossrdotNorm / (polarr * polarr);

    /* Projections of the spin vectors onto the Z-axis of the precessing frame,
     * L or LN */
    if (flagZframe == FLAG_SEOBNRv4P_ZFRAME_L) {
      s1dotZ = inner_product(spin1vec, Lhat);
      s2dotZ = inner_product(spin2vec, Lhat);
    } else if (flagZframe == FLAG_SEOBNRv4P_ZFRAME_LN) {
      s1dotZ = inner_product(spin1vec, LNhat);
      s2dotZ = inner_product(spin2vec, LNhat);
    } else {
      XLALPrintError("XLAL Error - %s: flagZframe not recognized.\n", __func__);
      XLAL_ERROR(XLAL_EINVAL);
    }

    /* Compute Hamiltonian */
    UINT4 SpinAlignedEOBversion = seobParams->seobCoeffs->SpinAlignedEOBversion;
    REAL8Vector cartPosVec, cartMomVec, s1Vec, s2Vec;
    cartPosVec.length = cartMomVec.length = s1Vec.length = s2Vec.length = 3;
    cartPosVec.data = rvec;
    cartMomVec.data = pvec;
    s1Vec.data = spin1vec; /* in units of mTotal^2 */
    s2Vec.data = spin2vec; /* in units of mTotal^2 */
    SEOBCalculateSigmaStar(sigmaStar, m1, m2, &s1Vec, &s2Vec);
    SEOBCalculateSigmaKerr(sigmaKerr, &s1Vec, &s2Vec);

    // Compute the augmented spin used in the Hamiltonian calibration
    // coefficients. See LIGO-T1900601-v1.

    REAL8 tempS1_p = inner_product(s1Vec.data, Lhat);
    REAL8 tempS2_p = inner_product(s2Vec.data, Lhat);
    REAL8 S1_perp[3] = {0, 0, 0};
    REAL8 S2_perp[3] = {0, 0, 0};
    for (UINT4 jj = 0; jj < 3; jj++) {
      S1_perp[jj] = spin1vec[jj] - tempS1_p * Lhat[jj];
      S2_perp[jj] = spin2vec[jj] - tempS2_p * Lhat[jj];
    }
    UNUSED REAL8 sKerr_norm =
        sqrt(inner_product(sigmaKerr->data, sigmaKerr->data));
    REAL8 S_con = 0.0;
    if (sKerr_norm > 1e-6) {
      S_con = sigmaKerr->data[0] * Lhat[0] + sigmaKerr->data[1] * Lhat[1] +
              sigmaKerr->data[2] * Lhat[2];
      S_con /= (1 - 2 * eta);
      S_con += (inner_product(S1_perp, sigmaKerr->data) +
                inner_product(S2_perp, sigmaKerr->data)) /
               sKerr_norm / (1 - 2 * eta) / 2.;
    }

    REAL8 a = sqrt(inner_product(sigmaKerr->data, sigmaKerr->data));
    if (XLALSimIMRCalculateSpinPrecEOBHCoeffs_v2(
            seobCoeffs, eta, a, S_con, SpinAlignedEOBversion) == XLAL_FAILURE) {
      XLAL_PRINT_ERROR("XLAL Error: Something went wrong evaluating "
                       "XLALSimIMRCalculateSpinPrecEOBHCoeffs_v2 in step %d of "
                       "the main loop.\n",
                       i);
      XLAL_ERROR(XLAL_EFUNC);
    }
    ham = XLALSimIMRSpinPrecEOBHamiltonian(eta, &cartPosVec, &cartMomVec,
                                           &s1Vec, &s2Vec, sigmaKerr, sigmaStar,
                                           seobParams->tortoise, seobCoeffs);
    /* Output values in seobdynamics */
    seobdyn->velVecx[i] = rdotvec[0];
    seobdyn->velVecy[i] = rdotvec[1];
    seobdyn->velVecz[i] = rdotvec[2];
    seobdyn->polarrVec[i] = polarr;
    seobdyn->polarphiVec[i] = polarphi;
    seobdyn->polarprVec[i] = polarpr;
    seobdyn->polarpphiVec[i] = polarpphi;
    seobdyn->omegaVec[i] = omega;
    seobdyn->s1dotZVec[i] = s1dotZ;
    seobdyn->s2dotZVec[i] = s2dotZ;
    seobdyn->hamVec[i] = ham;
  }

  /* Cleanup */
  XLALDestroyREAL8Vector(values);
  XLALDestroyREAL8Vector(dvalues);
  XLALDestroyREAL8Vector(sigmaStar);
  XLALDestroyREAL8Vector(sigmaKerr);

  return XLAL_SUCCESS;
}

/**
 * This function computes initial conditions for SEOBNRv4P.
 */
static int SEOBInitialConditions(
    REAL8Vector **ICvalues, /**<< Output: vector with initial conditions */
    REAL8 MfMin,       /**<< Input: dimensionless initial frequency (in units of
                          1/mTotal) */
    REAL8 m1,          /**<< Input: mass 1 (solar masses) */
    REAL8 m2,          /**<< Input: mass 2 (solar masses) */
    REAL8Vector *chi1, /**<< Input: dimensionless spin 1 (in units of m1^2) */
    REAL8Vector *chi2, /**<< Input: dimensionless spin 2 (in units of m2^2) */
    SpinEOBParams *seobParams, /**<< SEOB params */
    flagSEOBNRv4P_hamiltonian_derivative
        flagHamiltonianDerivative /**<< flag to decide wether to use analytical
                                     or numerical derivatives */
) {
  UINT4 j;

  /* Check that the input double pointer is not NULL */
  if (!ICvalues) {
    XLALPrintError(
        "XLAL Error - %s: pointer to REAL8Vector ICvalues is NULL.\n",
        __func__);
    XLAL_ERROR(XLAL_EINVAL);
  }

  /* Allocate vector for initial conditions at fMin */
  if (!(*ICvalues = XLALCreateREAL8Vector(14))) {
    XLALPrintError(
        "XLAL Error - %s: failed to allocate REAL8Vector ICvalues.\n",
        __func__);
    XLAL_ERROR(XLAL_ENOMEM);
  }
  memset((*ICvalues)->data, 0, ((*ICvalues)->length) * sizeof(REAL8));

  /* Masses in solar masses */
  REAL8 eta = m1 * m2 / (m1 + m2) / (m1 + m2);
  /* Flags */
  UINT4 SpinAlignedEOBversion = seobParams->seobCoeffs->SpinAlignedEOBversion;
  UINT4 SpinsAlmostAligned = seobParams->alignedSpins;

  /* Needed for the interface of the old code */
  REAL8 fMin = MfMin / (m1 + m2) / LAL_MTSUN_SI;
  REAL8 inc =
      0.; /* Not clear why XLALSimIMRSpinEOBInitialConditions,
             XLALSimIMRSpinEOBInitialConditionsPrec need an inclination */

  /* Flag for numerical or analytical derivatives */
  INT4 use_optimized = 0;
  if (flagHamiltonianDerivative ==
      FLAG_SEOBNRv4P_HAMILTONIAN_DERIVATIVE_ANALYTICAL)
    use_optimized = 1;
  else if (flagHamiltonianDerivative ==
           FLAG_SEOBNRv4P_HAMILTONIAN_DERIVATIVE_NUMERICAL)
    use_optimized = 0;
  else {
    XLALPrintError(
        "XLAL Error - %s: flagHamiltonianDerivative not recognized.\n",
        __func__);
    XLAL_ERROR(XLAL_EINVAL);
  }

  /* XLALSimIMRSpinEOBInitialConditions takes as input dimensionfull spins in
   * units of solar mass square */
  REAL8 mSpin1data[3] = {0., 0., 0.};
  REAL8 mSpin2data[3] = {0., 0., 0.};

  if (SpinsAlmostAligned) {
    /* Here the Z-frame axis is the original z, also direction of L and LN - no
     * precession */
    REAL8 chi1dotZ = chi1->data[2];
    REAL8 chi2dotZ = chi2->data[2];
    REAL8 chiS = SEOBCalculateChiS(chi1dotZ, chi2dotZ);
    REAL8 chiA = SEOBCalculateChiA(chi1dotZ, chi2dotZ);
    REAL8 tplspin = SEOBCalculatetplspin(m1, m2, eta, chi1dotZ, chi2dotZ,
                                         SpinAlignedEOBversion);
    if (XLALSimIMREOBCalcSpinFacWaveformCoefficients(
            seobParams->eobParams->hCoeffs, seobParams, m1, m2, eta, tplspin,
            chiS, chiA, SpinAlignedEOBversion) ==
        XLAL_FAILURE) /* This function returns XLAL_SUCCESS or calls XLAL_ERROR(
                         XLAL_EINVAL ) */
    {
      XLALPrintError("XLAL Error - %s: failure in "
                     "XLALSimIMREOBCalcSpinFacWaveformCoefficients.\n",
                     __func__);
      XLAL_ERROR(XLAL_EFUNC);
    }
    mSpin1data[2] = chi1->data[2] * m1 * m1;
    mSpin2data[2] = chi2->data[2] * m2 * m2;
    if (XLALSimIMRSpinEOBInitialConditions(*ICvalues, m1, m2, fMin, inc,
                                           mSpin1data, mSpin2data, seobParams,
                                           use_optimized) ==
        XLAL_FAILURE) /* This function returns XLAL_SUCCESS or calls XLAL_ERROR
                         with XLAL_EINVAL, XLAL_ENOMEM, or XLAL_EMAXITER */
    {
      XLALPrintError(
          "XLAL Error - %s: failure in XLALSimIMRSpinEOBInitialConditions.\n",
          __func__);
      XLAL_ERROR(XLAL_EFUNC);
    }
  } else {
    for (j = 0; j < 3; j++) {
      mSpin1data[j] = chi1->data[j] * m1 * m1;
      mSpin2data[j] = chi2->data[j] * m2 * m2;
    }
    /* This function returns XLAL_SUCCESS or calls XLAL_ERROR with XLAL_EINVAL,
     * XLAL_ENOMEM, or XLAL_EMAXITER */
    if (XLALSimIMRSpinEOBInitialConditionsPrec(
            *ICvalues, m1, m2, fMin, inc, mSpin1data, mSpin2data, seobParams,
            use_optimized) == XLAL_FAILURE) {
      XLALPrintError("XLAL Error - %s: failure in "
                     "XLALSimIMRSpinEOBInitialConditionsPrec.\n",
                     __func__);
      XLAL_ERROR(XLAL_EFUNC);
    }
  }

  /* Initial phases are set to 0 */
  (*ICvalues)->data[12] = 0.;
  (*ICvalues)->data[13] = 0.;

  return XLAL_SUCCESS;
}

/**
 * This function converts a spin-aligned dynamics as output by the Runge-Kutta
 * integrator to a generic-spin dynamics. Spin-aligned dynamics format: t, r,
 * phi, pr, pphi Generic-spin dynamics format: t, x, y, z, px, py, pz, s1x, s1y,
 * s1z, s2x, s2y, s2z, phiMod, phiDMod
 */
static int SEOBConvertSpinAlignedDynamicsToGenericSpins(
    REAL8Array **dynamics, /**<< Output: pointer to array for the generic-spin
                              dynamics */
    REAL8Array *dynamics_spinaligned, /**<< Input: array for the aligned-spin
                                         dynamics */
    UINT4 retLen,                     /**<< Input: length of dynamics */
    REAL8 chi1, /**<< Input: spin 1 aligned component (dimensionless) */
    REAL8 chi2, /**<< Input: spin 2 aligned component (dimensionless) */
    SpinEOBParams *seobParams /**<< SEOB params */
) {
  UINT4 i;

  /* Masses */
  REAL8 m1 = seobParams->eobParams->m1;
  REAL8 m2 = seobParams->eobParams->m2;
  REAL8 mTotal = m1 + m2;

  /* Create output dynamics */
  *dynamics = XLALCreateREAL8ArrayL(2, 15, retLen);

  /* Convert the spin-aligned dynamics to a generic-spins dynamics */
  REAL8Vector tVec, rVec, phiVec, prVec, pPhiVec;
  tVec.length = rVec.length = phiVec.length = prVec.length = pPhiVec.length =
      retLen;
  tVec.data = dynamics_spinaligned->data;
  rVec.data = dynamics_spinaligned->data + retLen;
  phiVec.data = dynamics_spinaligned->data + 2 * retLen;
  prVec.data = dynamics_spinaligned->data + 3 * retLen;
  pPhiVec.data = dynamics_spinaligned->data + 4 * retLen;
  for (i = 0; i < retLen; i++) {
    (*dynamics)->data[i] = tVec.data[i];
    (*dynamics)->data[retLen + i] = rVec.data[i] * cos(phiVec.data[i]);
    (*dynamics)->data[2 * retLen + i] = rVec.data[i] * sin(phiVec.data[i]);
    (*dynamics)->data[3 * retLen + i] = 0.;
    (*dynamics)->data[4 * retLen + i] =
        prVec.data[i] * cos(phiVec.data[i]) -
        pPhiVec.data[i] / rVec.data[i] * sin(phiVec.data[i]);
    (*dynamics)->data[5 * retLen + i] =
        prVec.data[i] * sin(phiVec.data[i]) +
        pPhiVec.data[i] / rVec.data[i] * cos(phiVec.data[i]);
    (*dynamics)->data[6 * retLen + i] = 0.;
    (*dynamics)->data[7 * retLen + i] = 0.;
    (*dynamics)->data[8 * retLen + i] = 0.;
    (*dynamics)->data[9 * retLen + i] = chi1 * (m1 * m1 / mTotal / mTotal);
    (*dynamics)->data[10 * retLen + i] = 0.;
    (*dynamics)->data[11 * retLen + i] = 0.;
    (*dynamics)->data[12 * retLen + i] = chi2 * (m2 * m2 / mTotal / mTotal);
    (*dynamics)->data[13 * retLen + i] = phiVec.data[i];
    (*dynamics)->data[14 * retLen + i] = 0.;
  }

  return XLAL_SUCCESS;
}

/**
 * This function integrates the SEOBNRv4P dynamics.
 * Output is given either on the adaptive sampling coming out of the Runge Kutta
 * integrator, with no interpolation being made, or on the constant sampling
 * specified by deltaT. Either analytical or numerical derivatives of the
 * Hamiltonian are used depending on the flag flagHamiltonianDerivative.
 * Only numerical derivatives have been shown to work as of June 2019.
 * When spins are flagged as almost aligned, falls back to
 * spin-aligned dynamics.
 */
static int SEOBIntegrateDynamics(
    REAL8Array **dynamics, /**<< Output: pointer to array for the dynamics */
    UINT4 *retLenOut,      /**<< Output: length of the output dynamics */
    REAL8Vector *ICvalues, /**<< Input: vector with initial conditions */
    REAL8 EPS_ABS, /**<< Input: absolute accuracy for adaptive Runge-Kutta
                      integrator */
    REAL8 EPS_REL, /**<< Input: relative accuracy for adaptive Runge-Kutta
                      integrator */
    REAL8 deltaT,  /**<< Input: timesampling step in geometric units - when
                      flagConstantSampling is False, used internally only to
                      initialize adaptive step */
    REAL8 deltaT_min,  /**<< Input: minimal timesampling step in geometric
                          units when using adaptive steps with
                          flagConstantSampling set to False -
                          set to 0 to ignore */
    REAL8 tstart,  /**<< Input: starting time of the integration */
    REAL8 tend,    /**<< Input: max time of the integration - normally, the
                      integration stops when stopping condition is met, and this is
                      ignored */
    SpinEOBParams *seobParams,  /**<< SEOB params */
    UINT4 flagConstantSampling, /**<< flag to decide wether to use constant
                                   sampling with deltaT in output instead of
                                   adaptive sampling */
    flagSEOBNRv4P_hamiltonian_derivative
        flagHamiltonianDerivative /**<< flag to decide wether to use analytical
                                     or numerical derivatives */
) {
  UINT4 retLen;

  /* Integrator */
  LALAdaptiveRungeKuttaIntegrator *integrator = NULL;

  /* Flags */
  UINT4 SpinsAlmostAligned = seobParams->alignedSpins;

  /* Dimensions of vectors of dynamical variables to be integrated */
  UINT4 nb_Hamiltonian_variables = 14;
  UINT4 nb_Hamiltonian_variables_spinsaligned = 4;

  /* Used only when falling back to spin-aligned dynamics */
  REAL8Array *dynamics_spinaligned = NULL;

  /* Initialize internal values vector for the generic-spin case */
  REAL8Vector *values = NULL;
  if (!(values = XLALCreateREAL8Vector(nb_Hamiltonian_variables))) {
    XLALPrintError("XLAL Error - %s: failed to create REAL8Vector values.\n",
                   __func__);
    XLAL_ERROR(XLAL_ENOMEM);
  }
  memcpy(values->data, ICvalues->data, values->length * sizeof(REAL8));
  /* Initialize internal values vector for the spin-aligned case -- not used in
   * the generic-spin case */
  REAL8Vector *values_spinaligned = NULL;
  if (!(values_spinaligned =
            XLALCreateREAL8Vector(nb_Hamiltonian_variables_spinsaligned))) {
    XLALPrintError(
        "XLAL Error - %s: failed to create REAL8Vector values_spinaligned.\n",
        __func__);
    XLAL_ERROR(XLAL_ENOMEM);
  }
  memset(values_spinaligned->data, 0,
         values_spinaligned->length * sizeof(REAL8));

  /* Initialization of the integrator */
  if (SpinsAlmostAligned) { /* If spins are almost aligned with LNhat, use
                               SEOBNRv4 dynamics */
    /* In SEOBNRv4 the dynamical variables are r, phi, p_r^*, p_phi */

    /* Construct the initial conditions */
    REAL8 temp_r = sqrt(ICvalues->data[0] * ICvalues->data[0] +
                        ICvalues->data[1] * ICvalues->data[1] +
                        ICvalues->data[2] * ICvalues->data[2]);
    REAL8 temp_phi = ICvalues->data[12];

    values_spinaligned->data[0] = temp_r;   // General form of r
    values_spinaligned->data[1] = temp_phi; // phi
    values_spinaligned->data[2] = ICvalues->data[3] * cos(temp_phi) +
                                  ICvalues->data[4] * sin(temp_phi); // p_r^*
    values_spinaligned->data[3] =
        temp_r * (ICvalues->data[4] * cos(temp_phi) -
                  ICvalues->data[3] * sin(temp_phi)); // p_phi

    /* We have to use different stopping conditions depending
       we are in the low-sampling or high-sampling portion
       of the waveform. We can tell this apart because for the low-sampling (or
       ada sampling) we always start at t=0
     */
    if (tstart > 0) {
      // High sampling
      integrator = XLALAdaptiveRungeKutta4Init(
          nb_Hamiltonian_variables_spinsaligned, XLALSpinAlignedHcapDerivative,
          XLALSpinPrecAlignedHiSRStopCondition, EPS_ABS, EPS_REL);
    } else {
      // Low sampling
      integrator = XLALAdaptiveRungeKutta4Init(
          nb_Hamiltonian_variables_spinsaligned, XLALSpinAlignedHcapDerivative,
          XLALEOBSpinPrecAlignedStopCondition, EPS_ABS, EPS_REL);
    }
  } else {
    if (flagHamiltonianDerivative ==
        FLAG_SEOBNRv4P_HAMILTONIAN_DERIVATIVE_ANALYTICAL) {
      integrator = XLALAdaptiveRungeKutta4Init(
          nb_Hamiltonian_variables, XLALSpinPrecHcapExactDerivative,
          XLALEOBSpinPrecStopConditionBasedOnPR, EPS_ABS, EPS_REL);
    } else if (flagHamiltonianDerivative ==
               FLAG_SEOBNRv4P_HAMILTONIAN_DERIVATIVE_NUMERICAL) {
      if (tstart > 0) {
        integrator = XLALAdaptiveRungeKutta4Init(
            nb_Hamiltonian_variables, XLALSpinPrecHcapNumericalDerivative,
            XLALEOBSpinPrecStopConditionBasedOnPR, EPS_ABS, EPS_REL);
      } else {
        integrator = XLALAdaptiveRungeKutta4Init(
            nb_Hamiltonian_variables, XLALSpinPrecHcapNumericalDerivative,
            XLALEOBSpinPrecStopConditionBasedOnPR, EPS_ABS, EPS_REL);
      }

    } else {
      XLALPrintError(
          "XLAL Error - %s: flagHamiltonianDerivative not recognized.\n",
          __func__);
      XLAL_ERROR(XLAL_EINVAL);
    }
  }
  if (!integrator) {
    XLALPrintError(
        "XLAL Error - %s: failure in the initialization of the integrator.\n",
        __func__);
    XLAL_ERROR(XLAL_EDOM);
  }
  /* Ensure that integration stops ONLY when the stopping condition is True */
  integrator->stopontestonly = 1;
  /* When this option is set to 0, the integration can be exceedingly slow for
   * spin-aligned systems */
  integrator->retries = 1;

  /* Computing the dynamical evolution of the system */
  // NOTE: XLALAdaptiveRungeKutta4NoInterpolate takes an EOBversion as input.
  INT4 EOBversion = 2; // NOTE: value 3 is specific to optv3 in
                       // XLALAdaptiveRungeKutta4NoInterpolate it determines
                       // what is stored. We set it to 2.
  if (SpinsAlmostAligned) {
    /* If spins are almost aligned with LNhat, use SEOBNRv4 dynamics */
    if (!flagConstantSampling) {
      retLen = XLALAdaptiveRungeKutta4NoInterpolate(
          integrator, seobParams, values_spinaligned->data, 0., tend - tstart,
          deltaT, deltaT_min, &dynamics_spinaligned, EOBversion);
    } else {
      retLen = XLALAdaptiveRungeKutta4(
          integrator, seobParams, values_spinaligned->data, 0., tend - tstart,
          deltaT, &dynamics_spinaligned);
    }
    if ((INT4)retLen == XLAL_FAILURE) {
      XLALPrintError("XLAL Error - %s: failure in the integration of the "
                     "spin-aligned dynamics.\n",
                     __func__);
      XLAL_ERROR(XLAL_EDOM);
    }

    /* Convert the spin-aligned dynamics to a generic-spins dynamics */
    if (SEOBConvertSpinAlignedDynamicsToGenericSpins(
            dynamics, dynamics_spinaligned, retLen, seobParams->chi1,
            seobParams->chi2, seobParams) == XLAL_FAILURE) {
      XLALPrintError("XLAL Error - %s: failure in "
                     "SEOBConvertSpinAlignedDynamicsToGenericSpins.\n",
                     __func__);
      XLAL_ERROR(XLAL_EDOM);
    }
  } else {
    if (!flagConstantSampling) {
      retLen = XLALAdaptiveRungeKutta4NoInterpolate(
          integrator, seobParams, values->data, 0., tend - tstart, deltaT,
          deltaT_min, dynamics, EOBversion);
    } else {
      retLen = XLALAdaptiveRungeKutta4(integrator, seobParams, values->data, 0.,
                                       tend - tstart, deltaT, dynamics);
    }
    if ((INT4)retLen == XLAL_FAILURE) {
      XLALPrintError("XLAL Error - %s: failure in the integration of the "
                     "generic-spin dynamics.\n",
                     __func__);
      XLAL_ERROR(XLAL_EDOM);
    }
  }

  // NOTE: functions like XLALAdaptiveRungeKutta4 would give nans if the times
  // do not start at 0 -- we have to adjust the starting time after integration
  /* Adjust starting time */
  for (UINT4 i = 0; i < retLen; i++)
    (*dynamics)->data[i] += tstart;

  /* Output length of dynamics */
  *retLenOut = retLen;

  /* Cleanup */
  if (dynamics_spinaligned)
    XLALDestroyREAL8Array(dynamics_spinaligned);
  XLALDestroyREAL8Vector(values_spinaligned);
  XLALDestroyREAL8Vector(values);
  XLALAdaptiveRungeKuttaFree(integrator);

  return XLAL_SUCCESS;
}

/**
 * This function generates a waveform mode for a given SEOB dynamics.
 */
// NOTE: as is written here, the step
// XLALSimIMREOBCalcSpinPrecFacWaveformCoefficients in the loop will be repeated
// across modes -- would be more efficient to loop on modes inside the loop on
// times
static int SEOBCalculatehlmAmpPhase(
    CAmpPhaseSequence *
        *hlm, /**<< Output: hlm in complex amplitude / phase form */
    INT4 l,   /**<< Input: mode index l */
    INT4 m,   /**<< Input: mode index m */
    SEOBdynamics *seobdynamics, /**<< Input: SEOB dynamics */
    EOBNonQCCoeffs *nqcCoeffs,  /**<< Input: NQC coeffs */
    SpinEOBParams *seobParams,  /**<< SEOB params */
    // UINT4 SpinsAlmostAligned, /**<< flag to decide wether to fall back to
    // aligned spins  */
    UINT4 includeNQC /**<< flag to choose wether or not to include NQC */
) {
  /* Check that the input double pointer are not NULL */
  if (!hlm) {
    XLALPrintError(
        "XLAL Error - %s: pointer to CAmpPhaseSequence hlm is NULL.\n",
        __func__);
    XLAL_ERROR(XLAL_EINVAL);
  }

  /* Masses */
  REAL8 m1 = seobParams->eobParams->m1;
  REAL8 m2 = seobParams->eobParams->m2;
  REAL8 deltaT = seobdynamics->tVec[1] - seobdynamics->tVec[0];
  REAL8 eta = seobParams->eobParams->eta;
  REAL8 mtot = m1 + m2;
  UINT4 SpinAlignedEOBversion = seobParams->seobCoeffs->SpinAlignedEOBversion;
  UINT4 SpinAlignedEOBversionWaveform; // RC: I use this different variable
                                       // because the PN terms in the waveform
                                       // are different from those in the flux

  /* Length of dynamics data and sampling step */
  UINT4 retLen = seobdynamics->length;

  /* Allocate structure for complex amplitude and phase */
  if (CAmpPhaseSequence_Init(hlm, retLen) == XLAL_FAILURE) {
    XLALPrintError("XLAL Error - %s: failure in CAmpPhaseSequence_Init.\n",
                   __func__);
    XLAL_ERROR(XLAL_ENOMEM);
  }

  /* Workspace vectors */
  REAL8Vector values, polarDynamics;
  REAL8 valuesdata[14] = {0.};
  REAL8 polarDynamicsdata[4] = {0.};
  values.length = 14;
  polarDynamics.length = 4;
  values.data = valuesdata;
  polarDynamics.data = polarDynamicsdata;
  REAL8 tPeakOmega = seobParams->tPeakOmega;

  /* Calibration parameter */
  if (includeNQC == 0) {
    if (((l == 2) && (m == 1)) || ((l == 5) && (m == 5))) {
      if (XLALSimIMREOBCalcCalibCoefficientHigherModesPrec(
              seobParams, l, m, seobdynamics,
              tPeakOmega - seobdynamics->tVec[0], m1, m2,
              deltaT) == XLAL_FAILURE) {
        XLALPrintError("XLAL Error - %s: failure in "
                       "XLALSimIMREOBCalcCalibCoefficientHigherModesPrec.\n",
                       __func__);
        XLAL_ERROR(XLAL_EDOM);
      }
    }
  }

  /* Loop to compute compute amplitude and phase of the hlm mode */
  REAL8 s1dotZ, s2dotZ, chiS, chiA, tplspin, t, omega, ham, v;
  UINT4 i, j;
  for (i = 0; i < retLen; i++) {
    /* Compute waveform coefficients */
    t = seobdynamics->tVec[i];
    omega = seobdynamics->omegaVec[i];
    ham = seobdynamics->hamVec[i];
    s1dotZ = seobdynamics->s1dotZVec[i];
    s2dotZ = seobdynamics->s2dotZVec[i];
    REAL8 chi1dotZ = s1dotZ * mtot * mtot / (m1 * m1);
    REAL8 chi2dotZ = s2dotZ * mtot * mtot / (m2 * m2);
    chiS = SEOBCalculateChiS(chi1dotZ, chi2dotZ);
    chiA = SEOBCalculateChiA(chi1dotZ, chi2dotZ);

    tplspin = SEOBCalculatetplspin(m1, m2, eta, s1dotZ, s2dotZ,
                                   SpinAlignedEOBversion);
    if (SpinAlignedEOBversion == 4) {
      SpinAlignedEOBversionWaveform = v4Pwave;
    } else {
      SpinAlignedEOBversionWaveform = SpinAlignedEOBversion;
    }

    if (XLALSimIMREOBCalcSpinPrecFacWaveformCoefficients(
            seobParams->eobParams->hCoeffs, m1, m2, eta, tplspin, chiS, chiA,
            SpinAlignedEOBversionWaveform) == XLAL_FAILURE) {
      XLALPrintError("XLAL Error - %s: failure in "
                     "XLALSimIMREOBCalcSpinPrecFacWaveformCoefficients at step "
                     "%d of the loop.\n",
                     __func__, i);
      XLAL_ERROR(XLAL_EFUNC);
    }
    seobParams->eobParams->hCoeffs->f21v7c = seobParams->cal21;
    seobParams->eobParams->hCoeffs->f55v5c = seobParams->cal55;
    // printf("f21v7c = %.16f\n", seobParams->eobParams->hCoeffs->f21v7c);
    /* Dynamics, polar dynamics, omega */
    for (j = 0; j < 14; j++) {
      values.data[j] = seobdynamics->array->data[i + (j + 1) * retLen];
    }
    polarDynamics.data[0] = seobdynamics->polarrVec[i];
    polarDynamics.data[1] = seobdynamics->polarphiVec[i];
    polarDynamics.data[2] = seobdynamics->polarprVec[i];
    polarDynamics.data[3] = seobdynamics->polarpphiVec[i];
    v = cbrt(omega);
    COMPLEX16 hlm_val = 0.;
    if (XLALSimIMRSpinEOBGetPrecSpinFactorizedWaveform(
            &hlm_val, &polarDynamics, &values, v, ham, l, m, seobParams) ==
        XLAL_FAILURE) {
      XLALPrintError("XLAL Error - %s: failure in "
                     "XLALSimIMRSpinEOBGetPrecSpinFactorizedWaveform at step "
                     "%d of the loop.\n",
                     __func__, i);
      XLAL_ERROR(XLAL_EDOM);
    }
    /* NQC correction */
    COMPLEX16 factor_nqc = 1.;
    if (includeNQC) {
      if (XLALSimIMRSpinEOBNonQCCorrection(&factor_nqc, &values, omega,
                                           nqcCoeffs) == XLAL_FAILURE) {
        XLALPrintError(
            "XLAL Error - %s: failure in XLALSimIMRSpinEOBNonQCCorrection at "
            "step %d of the loop.\n",
            __func__, i);
        XLAL_ERROR(XLAL_EDOM);
      }
    } else
      factor_nqc = 1.;
    /* Result and output */
    COMPLEX16 hlmNQC = hlm_val * factor_nqc;
    (*hlm)->xdata->data[i] = t; /* Copy times */
    (*hlm)->camp_real->data[i] = cabs(hlmNQC);
    (*hlm)->camp_imag->data[i] = 0.; /* We use only real amplitudes */
    (*hlm)->phase->data[i] = carg(hlmNQC);
  }

  /* Unwrap the phase vector, in place */
  XLALREAL8VectorUnwrapAngle((*hlm)->phase, (*hlm)->phase);

  return XLAL_SUCCESS;
}

/**
 * This function generates all waveform modes as a list for a given SEOB
 * dynamics.
 */
static int SEOBCalculateSphHarmListhlmAmpPhase(
    SphHarmListCAmpPhaseSequence *
        *listhlm,               /**<< Output: list of modes for hlm */
    INT4 modes[][2],            /**<< Input: array of modes (l,m) */
    UINT4 nmodes,               /**<< Input: number of modes (l,m) */
    SEOBdynamics *seobdynamics, /**<< Input: SEOB dynamics */
    SphHarmListEOBNonQCCoeffs *listnqcCoeffs, /**<< Input: list of NQCs */
    SpinEOBParams *seobParams,                /**<< SEOB params */
    UINT4 flagNQC /**<< flag to choose wether or not to include NQC */
) {
  /* Read version of SEOB to be used */
  UINT4 SpinAlignedEOBversion = seobParams->seobCoeffs->SpinAlignedEOBversion;

  /* Flag for inclusion of NQC, useful for higher modes that have no NQC
   * implemented for some SpinAlignedEOBversion */
  UINT4 includeNQC = 0;

  /* Loop over modes */
  for (UINT4 nmode = 0; nmode < nmodes; nmode++) {

    INT4 l = modes[nmode][0];
    INT4 m = modes[nmode][1];

    if ((!(l == 2 && m == 2)) && (SpinAlignedEOBversion == 3)) {
      includeNQC = 0; /* For HM beyond 22, no NQC available for
                         SpinAlignedEOBversion==3 */
    } else
      includeNQC = flagNQC;

    EOBNonQCCoeffs *nqcCoeffs =
        SphHarmListEOBNonQCCoeffs_GetMode(listnqcCoeffs, l, m)->nqcCoeffs;

    CAmpPhaseSequence *hlm = NULL;
    SEOBCalculatehlmAmpPhase(&hlm, l, m, seobdynamics, nqcCoeffs, seobParams,
                             includeNQC);

    SphHarmListCAmpPhaseSequence_AddMode(listhlm, hlm, l, m);
  }

  return XLAL_SUCCESS;
}

/**
 * This function finds the peak of omega.
 * Note that there are various possibilities as of what is returned if
 * tPeakOmega is not found at first. In particular, by default,
 * if there is no peak found, the last point of the dynamics is used.
 */
static int SEOBLocateTimePeakOmega(
    REAL8 *tPeakOmega, /**<< Output: time of peak of Omega if found (see inside
        XLALSimLocateOmegaTime for what is returned otherwise) */
    INT4 *foundPeakOmega, /**<< Output: flag indicating wether tPeakOmega has
                 been found */
    UNUSED REAL8Array *dynamics,      /**<< Input: array for dynamics */
    SEOBdynamics *seobdynamics,       /**<< Input: SEOB dynamics object */
    UINT4 retLen,                     /**<< Input: length of dynamics */
    UNUSED SpinEOBParams *seobParams, /**<< SEOB params */
    UNUSED flagSEOBNRv4P_hamiltonian_derivative
        flagHamiltonianDerivative /**<< flag to decide wether to use analytical
                                     or numerical derivatives */
) {

  REAL8Vector tVec;
  tVec.length = retLen;
  tVec.data = seobdynamics->tVec;
  REAL8Vector omegaVec;
  omegaVec.length = retLen;
  omegaVec.data = seobdynamics->omegaVec;
  XLALEOBFindRobustPeak(tPeakOmega, &tVec, &omegaVec, 3);
  *foundPeakOmega = 1;

  /*
  // Uncomment this block to use old-style finding of the peak of Omega
  UNUSED REAL8 m1 = seobParams->eobParams->m1;
  UNUSED REAL8 m2 = seobParams->eobParams->m2;
  REAL8Vector radiusVec;
  radiusVec.length = retLen;
  radiusVec.data = seobdynamics->polarrVec;
  // Number of variables in the dynamics array (besides time)
  UINT4 numdynvars = 14;
  // A parameter we don't know what to do with
  REAL8 tMaxOmega = 0;    // Will not be used, and is not returned

  // Flag for numerical or analytical derivatives
  INT4 use_optimized = 0;
  if (flagHamiltonianDerivative ==
      FLAG_SEOBNRv4P_HAMILTONIAN_DERIVATIVE_ANALYTICAL)
    use_optimized = 1;
  else if (flagHamiltonianDerivative ==
           FLAG_SEOBNRv4P_HAMILTONIAN_DERIVATIVE_NUMERICAL)
    use_optimized = 0;
  else {
    XLALPrintError(
                   "XLAL Error - %s: flagHamiltonianDerivative not
  recognized.\n",
                   __func__);
    XLAL_ERROR(XLAL_EINVAL);
  }
  //Time of peak of Omega
  *tPeakOmega = XLALSimLocateOmegaTime(
      dynamics, numdynvars, retLen, *seobParams, *(seobParams->seobCoeffs), m1,
      m2, &radiusVec, foundPeakOmega, &tMaxOmega, use_optimized);
  */

  return XLAL_SUCCESS;
}

/**
 * This function looks for the peak of a mode amplitude.
 * Note that the internals are complicated, see XLALSimLocateAmplTime.
 */
UNUSED static int SEOBLocateTimePeakModeAmp(
    REAL8
        *tPeakAmp, /**<< Output: time of peak of amplitude if found (see inside
                      XLALSimLocateAmplTime for what is returned otherwise) */
    INT4 *foundPeakAmp, /**<< Output: flag indicating wether tPeakOmega has been
                           found */
    CAmpPhaseSequence *hlm, /**<< Input: mode in complex amplitude/phase form */
    SEOBdynamics *seobdynamics, /**<< Input: SEOB dynamics object */
    UINT4 retLen                /**<< Input: length of dynamics */
) {
  /* Vectors with times and radius from dynamics */
  REAL8Vector timeVec, radiusVec;
  timeVec.length = radiusVec.length = retLen;
  radiusVec.data = seobdynamics->polarrVec;
  timeVec.data = seobdynamics->tVec;

  /* Computing mode */
  // NOTE: computing Re/Im is redundant, as XLALSimLocateAmplTime will recompute
  // the amplitude internally
  COMPLEX16Vector *hmode = NULL;
  if (!(hmode = XLALCreateCOMPLEX16Vector(retLen))) {
    XLALPrintError(
        "XLAL Error - %s: failed to allocate COMPLEX16Vector hmode.\n",
        __func__);
    XLAL_ERROR(XLAL_ENOMEM);
  }
  for (UINT4 i = 0; i < retLen; i++) {
    hmode->data[i] = (hlm->camp_real->data[i] + I * hlm->camp_imag->data[i]) *
                     cexp(I * hlm->phase->data[i]);
  }

  /* Not clear what this is for, not used */
  // REAL8 tMaxAmp = 0.;

  /* Time of peak of amplitude */
  //*tPeakAmp = XLALSimLocateAmplTime( &timeVec, hmode, &radiusVec,
  // foundPeakAmp, &tMaxAmp );
  *tPeakAmp = XLALSimLocateMaxAmplTime(&timeVec, hmode, foundPeakAmp);

  /* Cleanup */
  XLALDestroyCOMPLEX16Vector(hmode);

  return XLAL_SUCCESS;
}

/**
 * This function computes all extended dynamics values at a given time by
 * interpolating the dynamics array. We build a cubic spline limited to +- 20
 * samples on each side of the time of interest.
 */
static int SEOBInterpolateDynamicsAtTime(
    REAL8Vector **seobdynamics_values, /**<< Output: pointer to vector for
                                          seobdynamics interpolated values */
    REAL8 t,                           /**<< Input: time at which to evaluate */
    SEOBdynamics *seobdynamics         /**<< Input: SEOB dynamics */
) {
  /* Create output vector */
  if (!((*seobdynamics_values) = XLALCreateREAL8Vector(v4PdynamicsVariables))) {
    XLALPrintError("XLAL Error - %s: failed to allocate REAL8Vector "
                   "seobdynamics_values.\n",
                   __func__);
    XLAL_ERROR(XLAL_ENOMEM);
  }
  memset((*seobdynamics_values)->data, 0,
         ((*seobdynamics_values)->length) * sizeof(REAL8));

  /* Check that the time asked for is in range */
  UINT4 retLen = seobdynamics->length;
  REAL8 *tVec = seobdynamics->tVec;
  if ((t < tVec[0]) || (t > tVec[retLen - 1])) {
    XLALPrintError(
        "XLAL Error - %s: time for interpolation is out of range of "
        "the SEOBdynamics data. t = %.17f, tVec[0]=%.17f, tVec[-1]=%.17f\n",
        __func__, t, tVec[0], tVec[retLen - 1]);
    XLAL_ERROR(XLAL_EINVAL);
  }

  /* Get the start and end indices that we will use to interpolate */
  /* indext max index such that tVec[indext] <= t */
  UINT4 indext = 0;
  while ((indext < retLen - 1) && (tVec[indext + 1] <= t))
    indext++;
  INT4 indexstart = indext - 20 > 0 ? indext - 20 : 0;
  INT4 indexend = indext + 20 < retLen - 1 ? indext + 20 : retLen - 1;
  INT4 interp_length = indexend - indexstart + 1;
  if (interp_length <= 0) {
    XLALPrintError("XLAL Error - %s: not finding a strictly positive number of "
                   "samples for interpolation.\n",
                   __func__);
    XLAL_ERROR(XLAL_EINVAL);
  }

  /* Spline allocation */
  gsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline, interp_length);
  gsl_interp_accel *acc = gsl_interp_accel_alloc();

  /* Interpolate all quantities */
  (*seobdynamics_values)->data[0] = t;
  for (UINT4 j = 1; j < v4PdynamicsVariables; j++) {
    gsl_spline_init(spline, &(tVec[indexstart]),
                    &(seobdynamics->array->data[j * retLen + indexstart]),
                    interp_length);
    (*seobdynamics_values)->data[j] = gsl_spline_eval(spline, t, acc);
  }

  /* Cleanup */
  gsl_spline_free(spline);
  gsl_interp_accel_free(acc);

  return XLAL_SUCCESS;
}

static int SEOBLFrameVectors(
    REAL8Vector **S1,        /**<<Output: S1 in L-n frame */
    REAL8Vector **S2,        /**<<Output: S2 in L-n frame */
    REAL8Vector *seobvalues, /**<<Input: vector of extended dynamics */
    REAL8 m1, /**<<Input: mass of the first object in solar masses */
    REAL8 m2, /**<<Input: mass of the second object in solar masses */
    const flagSEOBNRv4P_Zframe
        flagZframe /**<<Input: whether to compute the L_N or L frame */
) {

  if ((!S1) || (!S2) || (!seobvalues)) {
    XLALPrintError("Passed null pointers to SEOBLFrameVectors!\n");
    XLAL_ERROR(XLAL_ENOMEM);
  }
  REAL8 mTotal = m1 + m2;
  // Scaled masses, useful to compute spins in sane units
  REAL8 m1_sc = m1 / mTotal;
  REAL8 m2_sc = m2 / mTotal;
  /* Create output vectors */
  if (!((*S1) = XLALCreateREAL8Vector(3))) {
    XLALPrintError("XLAL Error: failed to allocate REAL8Vector S1.\n");
    XLAL_ERROR(XLAL_ENOMEM);
  }
  if (!((*S2) = XLALCreateREAL8Vector(3))) {
    XLALDestroyREAL8Vector(*S1); // Free the memory above
    XLALPrintError("XLAL Error failed to allocate REAL8Vector S2.\n");
    XLAL_ERROR(XLAL_ENOMEM);
  }
  memset((*S1)->data, 0, 3 * sizeof(REAL8));
  memset((*S2)->data, 0, 3 * sizeof(REAL8));

  /* Local variables */
  REAL8 rvec[3] = {0, 0, 0};
  REAL8 drvec[3] = {0, 0, 0};
  REAL8 pvec[3] = {0, 0, 0};
  REAL8 spin1vec[3] = {0, 0, 0}; /* in units of mTotal^2 */
  REAL8 spin2vec[3] = {0, 0, 0}; /* in units of mTotal^2 */
  REAL8 crossp[3] = {0, 0, 0};
  REAL8 L_hat[3] = {0, 0, 0};
  REAL8 n_hat[3] = {0, 0, 0};
  REAL8 lambda_hat[3] = {0, 0, 0};
  /* Read from the extended dynamics values */
  for (int j = 0; j < 3; j++) {
    rvec[j] = seobvalues->data[1 + j];
    drvec[j] = seobvalues->data[15 + j];
    pvec[j] = seobvalues->data[4 + j];
    spin1vec[j] = seobvalues->data[7 + j] / m1_sc / m1_sc;
    spin2vec[j] = seobvalues->data[10 + j] / m2_sc / m2_sc;
  }
  if (flagZframe == FLAG_SEOBNRv4P_ZFRAME_L) {
    // Note: pvec is missing a factor of nu, but don't care about it's magnitide
    // anyway
    cross_product(rvec, pvec, crossp);
  } else if (flagZframe == FLAG_SEOBNRv4P_ZFRAME_LN) {
    cross_product(rvec, drvec, crossp);
  }
  REAL8 Lmag = sqrt(inner_product(crossp, crossp));
  REAL8 sep = sqrt(inner_product(rvec, rvec));

  for (int jj = 0; jj < 3; jj++) {
    L_hat[jj] = crossp[jj] / Lmag;
    n_hat[jj] = rvec[jj] / sep;
  }

  cross_product(L_hat, n_hat, lambda_hat);
  // Project onto the new frame
  (*S1)->data[0] = inner_product(spin1vec, n_hat);
  (*S2)->data[0] = inner_product(spin2vec, n_hat);

  (*S1)->data[1] = inner_product(spin1vec, lambda_hat);
  (*S2)->data[1] = inner_product(spin2vec, lambda_hat);

  (*S1)->data[2] = inner_product(spin1vec, L_hat);
  (*S2)->data[2] = inner_product(spin2vec, L_hat);
  return XLAL_SUCCESS;
}

/**
 * This function computes the J vector.
 */
static int SEOBJfromDynamics(
    REAL8Vector **J,         /**<< Output: pointer to vector J */
    REAL8Vector *seobvalues, /**<< Input: vector for extended dynamics values */
    SpinEOBParams *seobParams /**<< SEOB params */
) {
  UINT4 j;
  if ((!J) || (!seobvalues) || (!seobParams)) {
    XLALPrintError("Some pointers passed to SEOBJfromDynamics were null\n");
    XLAL_ERROR(XLAL_ENOMEM);
  }
  /* Create output vector */
  if (!((*J) = XLALCreateREAL8Vector(3))) {
    XLALPrintError("XLAL Error failed to allocate REAL8Vector J.\n");
    XLAL_ERROR(XLAL_ENOMEM);
  }
  memset((*J)->data, 0, 3 * sizeof(REAL8));

  /* Masses */
  REAL8 eta = seobParams->eobParams->eta;

  /* Local variables */
  REAL8 rvec[3] = {0, 0, 0};
  REAL8 pvec[3] = {0, 0, 0};
  REAL8 spin1vec[3] = {0, 0, 0}; /* in units of mTotal^2 */
  REAL8 spin2vec[3] = {0, 0, 0}; /* in units of mTotal^2 */
  REAL8 rcrossp[3] = {0, 0, 0};

  /* Read from the extended dynamics values */
  for (j = 0; j < 3; j++) {
    rvec[j] = seobvalues->data[1 + j];
    pvec[j] = seobvalues->data[4 + j];
    spin1vec[j] = seobvalues->data[7 + j];
    spin2vec[j] = seobvalues->data[10 + j];
  }
  cross_product(rvec, pvec, rcrossp);

  /* Compute J - restoring the factor eta in L (p stored in the dynamics is
   * p/mu) */
  for (j = 0; j < 3; j++) {
    (*J)->data[j] = eta * rcrossp[j] + spin1vec[j] + spin2vec[j];
  }

  return XLAL_SUCCESS;
}

2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
/**
 * This function computes the L-hat vector.
 */
static int SEOBLhatfromDynamics(
    REAL8Vector **L,         /**<< Output: pointer to vector L */
    REAL8Vector *seobvalues, /**<< Input: vector for extended dynamics values */
    SpinEOBParams *seobParams /**<< SEOB params */,
    const flagSEOBNRv4P_Zframe
        flagZframe /**<<Input: whether to compute the L_N or L frame */
)
{
  if ((!L) || (!seobvalues) || (!seobParams))
  {
    XLALPrintError("Some pointers passed to SEOBLfromDynamics were null\n");
    XLAL_ERROR(XLAL_ENOMEM);
  }
  /* Create output vector */
  if (!((*L) = XLALCreateREAL8Vector(3)))
  {
    XLALPrintError("XLAL Error failed to allocate REAL8Vector L.\n");
    XLAL_ERROR(XLAL_ENOMEM);
  }
  memset((*L)->data, 0, 3 * sizeof(REAL8));

  /* Local variables */
  REAL8 rvec[3] = {0, 0, 0};
  REAL8 drvec[3] = {0, 0, 0};
  REAL8 pvec[3] = {0, 0, 0};
  REAL8 crossp[3] = {0, 0, 0};

  /* Read from the extended dynamics values */
  for (int j = 0; j < 3; j++)
  {
    rvec[j] = seobvalues->data[1 + j];
    drvec[j] = seobvalues->data[15 + j];
    pvec[j] = seobvalues->data[4 + j];
  }
  if (flagZframe == FLAG_SEOBNRv4P_ZFRAME_L)
  {
    // Note: pvec is missing a factor of nu, but don't care about it's magnitide
    // anyway
    cross_product(rvec, pvec, crossp);
  }
  else if (flagZframe == FLAG_SEOBNRv4P_ZFRAME_LN)
  {
    cross_product(rvec, drvec, crossp);
  }
  REAL8 Lmag = sqrt(inner_product(crossp, crossp));

  for (int jj = 0; jj < 3; jj++)
  {
    (*L)->data[jj] = crossp[jj] / Lmag;
  }

  return XLAL_SUCCESS;
}

2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901
/**
 * This function computes the Jframe unit vectors, with e3J along Jhat.
 * Convention: if (ex, ey, ez) is the initial I-frame, e1J chosen such that ex
 * is in the plane (e1J, e3J) and ex.e1J>0.
 * In the case where e3J and x happen to be close to aligned, we continuously
 * switch to another prescription with y playing the role of x
 */
static int SEOBBuildJframeVectors(
    REAL8Vector *e1J, /**<< Output: vector for e1J, already allocated */
    REAL8Vector *e2J, /**<< Output: vector for e2J, already allocated */
    REAL8Vector *e3J, /**<< Output: vector for e3J, already allocated */
    REAL8Vector *JVec /**<< Input: vector J */
) {
  UINT4 j;

  /* Checking size and of input vectors */
  if ((!e1J) || (!e2J) || (!e3J) || (!JVec)) {
    XLALPrintError("XLAL Error: at least one input pointer is NULL.\n");
    XLAL_ERROR(XLAL_EINVAL);
  }
  if ((!(e1J->length == 3)) || (!(e2J->length == 3)) || (!(e2J->length == 3))) {
    XLALPrintError(
        "XLAL Error: at least one input vector is not of length 3.\n");
    XLAL_ERROR(XLAL_EINVAL);
  }

  /* Set e3J to Jhat */
  REAL8 Jnorm = sqrt(inner_product(JVec->data, JVec->data));
  for (j = 0; j < 3; j++) {
    e3J->data[j] = JVec->data[j] / Jnorm;
  }

  /* Set e1J to enforce the condition that x is in the plane (e1J, e3J) and
   * x.e1J>0 */
  /* Added a protection against the degenerate case where e3J, x are aligned:
   * let lambda = 1 - |ex.e3J|, measuring the alignment of e3J, x
   * for lambda < 1e-5 use y instead of x
   * for lambda > 1e-4 use x normally
   * for lambda in [1e-4, 1e-5] use a lambda-weighted combination of both
   * thresholds are arbitrary */
  REAL8 normfacx = 0.;
  REAL8 normfacy = 0.;
  REAL8 weightx = 0.;
  REAL8 weighty = 0.;
  REAL8 e1Jblendednorm = 0.;
  REAL8 exvec[3] = {1, 0, 0};
  REAL8 eyvec[3] = {0, 1, 0};
  REAL8 exdote3J = inner_product(exvec, e3J->data);
  REAL8 eydote3J = inner_product(eyvec, e3J->data);
  REAL8 lambda = 1. - fabs(exdote3J);
  if ((lambda < 0.) || (lambda > 1.)) {
    XLALPrintError("Problem: lambda=1-|e3J.ex|=%g, should be in [0,1]", lambda);
    XLAL_ERROR(XLAL_EINVAL);
  }
  if (lambda > 1e-4) {
    normfacx = 1. / sqrt(1. - exdote3J * exdote3J);
    for (j = 0; j < 3; j++) {
      e1J->data[j] = (exvec[j] - exdote3J * e3J->data[j]) / normfacx;
    }
  } else if (lambda < 1e-5) {
    normfacy = 1. / sqrt(1. - eydote3J * eydote3J);
    for (j = 0; j < 3; j++) {
      e1J->data[j] = (eyvec[j] - eydote3J * e3J->data[j]) / normfacy;
    }
  } else {
    weightx = (lambda - 1e-5) / (1e-4 - 1e-5);
    weighty = 1. - weightx;
    normfacx = 1. / sqrt(1. - exdote3J * exdote3J);
    normfacy = 1. / sqrt(1. - eydote3J * eydote3J);
    for (j = 0; j < 3; j++) {
      e1J->data[j] = weightx * (exvec[j] - exdote3J * e3J->data[j]) / normfacx +
                     weighty * (eyvec[j] - eydote3J * e3J->data[j]) / normfacy;
    }
    e1Jblendednorm = sqrt(inner_product(e1J->data, e1J->data));
    for (j = 0; j < 3; j++) {
      e1J->data[j] /= e1Jblendednorm;
    }
  }

  /* Get e2J = e3J * e1J */
  cross_product(e3J->data, e1J->data, e2J->data);

  /* Normally, vectors already of unit norm - we normalize again to eliminate
   * possible round-off error */
  REAL8 e1Jnorm = sqrt(inner_product(e1J->data, e1J->data));
  REAL8 e2Jnorm = sqrt(inner_product(e2J->data, e2J->data));
  REAL8 e3Jnorm = sqrt(inner_product(e3J->data, e3J->data));
  for (j = 0; j < 3; j++) {
    e1J->data[j] /= e1Jnorm;
    e2J->data[j] /= e2Jnorm;
    e3J->data[j] /= e3Jnorm;
  }

  return XLAL_SUCCESS;
}

/**
 * This function computes Euler angles I2J given the unit vectors of the Jframe.
 */
static int SEOBEulerI2JFromJframeVectors(
    REAL8 *alphaI2J,  /**<< Output: Euler angle alpha I2J */
    REAL8 *betaI2J,   /**<< Output: Euler angle beta I2J */
    REAL8 *gammaI2J,  /**<< Output: Euler angle gamma I2J */
    REAL8Vector *e1J, /**<< Input: unit Jframe vector e1J */
    REAL8Vector *e2J, /**<< Input: unit Jframe vector e2J */
    REAL8Vector *e3J  /**<< Input: unit Jframe vector e3J */
) {
  /* Active rotation matrix from frame (x,y,z) to frame (e1J,e2J,e3J) */
  /* The input vectors (eJ) are decomposed on the basis (x,y,z) */
  REAL8Array *R = XLALCreateREAL8ArrayL(2, 3, 3);
  if (!R) {
    XLALPrintError("Allocating the rotation matrix failed!");
    XLAL_ERROR(XLAL_ENOMEM);
  }
  RotationMatrixActiveFromBasisVectors(R, e1J->data, e2J->data, e3J->data);

  /* Compute Euler angles in the Z-Y-Z convention */
  EulerAnglesZYZFromRotationMatrixActive(alphaI2J, betaI2J, gammaI2J, R);

  /* Cleanup */
  XLALDestroyREAL8Array(R);

  return XLAL_SUCCESS;
}

/**
 * This function computes the NQC coefficients for a list of mode contributions.
 */
static int SEOBCalculateSphHarmListNQCCoefficientsV4(
    SphHarmListEOBNonQCCoeffs *
        *nqcCoeffsList, /**<< Output: non-quasi-circular coefficients as a list
                           for each mode */
    INT4 modes[][2],    /**<< Input: array of modes (l,m) */
    UINT4 nmodes,       /**<< Input: number of modes (l,m) */
    REAL8 tPeakOmega,   /**<< Input: time of peak of Omega */
    SEOBdynamics *seobdynamics,  /**<< Input: SEOB dynamics */
    SpinEOBParams *seobParams,   /**<< Input: SEOB params */
    REAL8Vector *chi1_omegaPeak, /**<< Input: dimensionless spin 1 at peak of
                                    omega in L_N frame */
2902
    REAL8Vector *chi2_omegaPeak /**<< Input: dimensionless spin 2 at peak of
2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958
                                    omega in L_N frame */
) {
  /* Masses */
  REAL8 m1 = seobParams->eobParams->m1;
  REAL8 m2 = seobParams->eobParams->m2;