File: utils.c

package info (click to toggle)
iqtree 1.5.3%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 9,780 kB
  • ctags: 11,529
  • sloc: cpp: 96,162; ansic: 59,874; python: 242; sh: 189; makefile: 45
file content (3735 lines) | stat: -rw-r--r-- 113,730 bytes parent folder | download | duplicates (2)
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
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
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
2902
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
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
/** 
 * PLL (version 1.0.0) a software library for phylogenetic inference
 * Copyright (C) 2013 Tomas Flouri and Alexandros Stamatakis
 *
 * Derived from 
 * RAxML-HPC, a program for sequential and parallel estimation of phylogenetic
 * trees by Alexandros Stamatakis
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * For any other enquiries send an Email to Tomas Flouri
 * Tomas.Flouri@h-its.org
 *
 * When publishing work that uses PLL please cite PLL
 * 
 * @file utils.c
 *  
 * @brief Miscellaneous general utility and helper functions
 */
#ifdef WIN32
#include <direct.h>
#endif

#ifndef WIN32
#include <sys/times.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#endif

#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdarg.h>
#include <limits.h>
#include <assert.h>
#include <errno.h>
#include "cycle.h"


#if ! (defined(__ppc) || defined(__powerpc__) || defined(PPC))
#if (defined(__AVX) || defined(__SSE3))
#include <xmmintrin.h>
#endif
/*
   special bug fix, enforces denormalized numbers to be flushed to zero,
   without this program is a tiny bit faster though.
#include <emmintrin.h> 
#define MM_DAZ_MASK    0x0040
#define MM_DAZ_ON    0x0040
#define MM_DAZ_OFF    0x0000
*/
#endif

#include "pll.h"
#include "pllInternal.h"

#define GLOBAL_VARIABLES_DEFINITION

#include "globalVariables.h"

/* mappings of BIN/DNA/AA alphabet to numbers */

static const char PLL_MAP_BIN[256] =
 {
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  3, -1, -1,
    1,  2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  3,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
  };

static const char PLL_MAP_NT[256] =
 {
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15,
   -1,  1, 14,  2, 13, -1, -1,  4, 11, -1, -1, 12, -1,  3, 15, 15,
   -1, -1,  5,  6,  8,  8,  7,  9, 15, 10, -1, -1, -1, -1, -1, -1,
   -1,  1, 14,  2, 13, -1, -1,  4, 11, -1, -1, 12, -1,  3, 15, 15,
   -1, -1,  5,  6,  8,  8,  7,  9, 15, 10, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
 };

static const char PLL_MAP_AA[256] =
 {
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 22, -1, -1, 22, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 22,
   -1,  0, 20,  4,  3,  6, 13,  7,  8,  9, -1, 11, 10, 12,  2, -1,
   14,  5,  1, 15, 16, -1, 19, 17, 22, 18, 21, -1, -1, -1, -1, -1,
   -1,  0, 20,  4,  3,  6, 13,  7,  8,  9, -1, 11, 10, 12,  2, -1,
   14,  5,  1, 15, 16, -1, 19, 17, 22, 18, 21, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
 };





static void pllTreeInitDefaults (pllInstance * tr, int tips);
static void getInnerBranchEndPointsRecursive (nodeptr p, int tips, int * i, node **nodes);
#if (!defined(_FINE_GRAIN_MPI) && !defined(_USE_PTHREADS))
static void initializePartitionsSequential(pllInstance *tr, partitionList *pr);
#endif

/** @defgroup instanceLinkingGroup Linking topology, partition scheme and alignment to the PLL instance
    
    This set of functions handles the linking of topology, partition scheme and multiple sequence alignment
    with the PLL instance
*/
/***************** UTILITY FUNCTIONS **************************/

#if (!defined(_SVID_SOURCE) && !defined(_BSD_SOURCE) && !defined(_POSIX_C_SOURCE) && !defined(_XOPEN_SOURCE) && !defined(_POSIX_SOURCE))
static char *
my_strtok_r (char * s, const char * delim, char **save_ptr)
{  
  char *token;
   
  /* Scan leading delimiters */
  if (s == NULL)
    s = *save_ptr;
   
  s += strspn (s, delim);
  if (*s == '\0')
   {
     *save_ptr = s;
     return NULL;
   }
   
  /* Find the end of the token. */
  token = s;
  s = strpbrk (token, delim);
  if (!s)
    *save_ptr = strchr (token, '\0');
  else
   {
     /* Terminate the token and make *SAVE_PTR point past it */
     *s = '\0';
     *save_ptr = s + 1;
   }
   
  return token;
}
#endif

#if (defined(_SVID_SOURCE) || defined(_BSD_SOURCE) || defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) || defined(_POSIX_SOURCE))
#define STRTOK_R strtok_r
#else
#define STRTOK_R my_strtok_r
#endif




void storeExecuteMaskInTraversalDescriptor(pllInstance *tr, partitionList *pr)
{
  int model;

  for(model = 0; model < pr->numberOfPartitions; model++)
    tr->td[0].executeModel[model] = pr->partitionData[model]->executeModel;

}

void storeValuesInTraversalDescriptor(pllInstance *tr, partitionList *pr, double *value)
{
  int model;

  for(model = 0; model < pr->numberOfPartitions; model++)
    tr->td[0].parameterValues[model] = value[model];
}

const unsigned int *getBitVector(int dataType)
{
  assert(PLL_MIN_MODEL < dataType && dataType < PLL_MAX_MODEL);

  return pLengths[dataType].bitVector;
}

/*
int getStates(int dataType)
{
  assert(PLL_MIN_MODEL < dataType && dataType < PLL_MAX_MODEL);

  return pLengths[dataType].states;
}
*/

int getUndetermined(int dataType)
{
  assert(PLL_MIN_MODEL < dataType && dataType < PLL_MAX_MODEL);

  return pLengths[dataType].undetermined;
}

const partitionLengths *getPartitionLengths(pInfo *p)
{
  int 
    dataType  = p->dataType,
              states    = p->states,
              tipLength = p->maxTipStates;

  assert(states != -1 && tipLength != -1);

  assert(PLL_MIN_MODEL < dataType && dataType < PLL_MAX_MODEL);

  /*pLength.leftLength = pLength.rightLength = states * states;
    pLength.eignLength = states;
    pLength.evLength   = states * states;
    pLength.eiLength   = states * states;
    pLength.substRatesLength = (states * states - states) / 2;
    pLength.frequenciesLength = states;
    pLength.tipVectorLength   = tipLength * states;
    pLength.symmetryVectorLength = (states * states - states) / 2;
    pLength.frequencyGroupingLength = states;
    pLength.nonGTR = PLL_FALSE;*/
  return (&pLengths[dataType]); 
}

size_t discreteRateCategories(int rateHetModel)
{
  size_t 
    result;

  switch(rateHetModel)
  {
    case PLL_CAT:
      result = 1;
      break;
    case PLL_GAMMA:
      result = 4;
      break;
    default:
      assert(0);
  }

  return result;
}



double gettime(void)
{
#ifdef WIN32
  time_t tp;
  struct tm localtm;
  tp = time(NULL);
  localtm = *localtime(&tp);
  return 60.0*localtm.tm_min + localtm.tm_sec;
#else
  struct timeval ttime;
  gettimeofday(&ttime , NULL);
  return ttime.tv_sec + ttime.tv_usec * 0.000001;
#endif
}

int gettimeSrand(void)
{
#ifdef WIN32
  time_t tp;
  struct tm localtm;
  tp = time(NULL);
  localtm = *localtime(&tp);
  return 24*60*60*localtm.tm_yday + 60*60*localtm.tm_hour + 60*localtm.tm_min  + localtm.tm_sec;
#else
  struct timeval ttime;
  gettimeofday(&ttime , NULL);
  return ttime.tv_sec + ttime.tv_usec;
#endif
}

double randum (long  *seed)
{
  long  sum, mult0, mult1, seed0, seed1, seed2, newseed0, newseed1, newseed2;
  double res;

  mult0 = 1549;
  seed0 = *seed & 4095;
  sum  = mult0 * seed0;
  newseed0 = sum & 4095;
  sum >>= 12;
  seed1 = (*seed >> 12) & 4095;
  mult1 =  406;
  sum += mult0 * seed1 + mult1 * seed0;
  newseed1 = sum & 4095;
  sum >>= 12;
  seed2 = (*seed >> 24) & 255;
  sum += mult0 * seed2 + mult1 * seed1;
  newseed2 = sum & 255;

  *seed = newseed2 << 24 | newseed1 << 12 | newseed0;
  res = 0.00390625 * (newseed2 + 0.000244140625 * (newseed1 + 0.000244140625 * newseed0));

  return res;
}


/********************* END UTILITY FUNCTIONS ********************/


/******************************some functions for the likelihood computation ****************************/


/** @brief Check whether a node is a tip.
    
    Checks whether the node with number \a number is a tip.
    
    @param number
     Node number to be checked
   
    @param maxTips
     Number of tips in the tree
   
    @return
      \b PLL_TRUE if tip, \b PLL_FALSE otherwise
  */
pllBoolean isTip(int number, int maxTips)
{
  assert(number > 0);

  if(number <= maxTips)
    return PLL_TRUE;
  else
    return PLL_FALSE;
}

/** @brief Set the orientation of a node

    Sets the orientation of node \a p. That means, it will reset the orientation
    \a p->next->x and \a p->next->next->x to 0 and of \a p->x to 1, meaning that
    the conditional likelihood vector for that node is oriented on \a p, i.e.
    the conditional likelihood vector represents the subtree rooted at \a p and
    not any other of the two nodes.

    @param p
      Node which we want to orient
*/
void getxnode (nodeptr p)
{
  nodeptr  s;

  if ((s = p->next)->x || (s = s->next)->x)
  {
    p->x = s->x;
    s->x = 0;
  }

  assert(p->x);
}


/** @brief Connect two nodes and assign branch lengths 
  * 
  * Connect the two nodes \a p and \a q in each partition \e i with a branch of
  * length \a z[i]
  *
  * @param p
  *   Node \a p
  * 
  * @param q
  *   Node \a q
  *
  * @param numBranches
  *   Number of partitions
  */
void hookup (nodeptr p, nodeptr q, double *z, int numBranches)
{
  int i;

  p->back = q;
  q->back = p;

  for(i = 0; i < numBranches; i++)
    p->z[i] = q->z[i] = z[i];
}

/* connects node p with q and assigns the branch lengths z for the whole vector*/
void hookupFull (nodeptr p, nodeptr q, double *z)
{
  //int i;

  p->back = q;
  q->back = p;

  memcpy(p->z, z, PLL_NUM_BRANCHES*sizeof(double) );
  memcpy(q->z, z, PLL_NUM_BRANCHES*sizeof(double) );
  //for(i = 0; i < numBranches; i++)
  //  p->z[i] = q->z[i] = z[i];

}

/* connect node p with q and assign the default branch lengths */
void hookupDefault (nodeptr p, nodeptr q)
{
  int i;

  p->back = q;
  q->back = p;

// TODO: fix: this make parsimony tree computation very slow with increasing PLL_NUM_BRANCHES
//  for(i = 0; i < PLL_NUM_BRANCHES; i++)
//    p->z[i] = q->z[i] = PLL_DEFAULTZ;
    p->z[0] = q->z[0] = PLL_DEFAULTZ;
}


/***********************reading and initializing input ******************/



pllBoolean whitechar (int ch)
{
  return (ch == ' ' || ch == '\n' || ch == '\t' || ch == '\r');
}
/*
static unsigned int KISS32(void)
{
  static unsigned int 
    x = 123456789, 
      y = 362436069,
      z = 21288629,
      w = 14921776,
      c = 0;

  unsigned int t;

  x += 545925293;
  y ^= (y<<13); 
  y ^= (y>>17); 
  y ^= (y<<5);
  t = z + w + c; 
  z = w; 
  c = (t>>31); 
  w = t & 2147483647;

  return (x+y+w);
}
*/

/** @brief Get a random subtree

    Returns the root node of a randomly picked subtree of the tree in PLL
    instance \a tr. The picked subtree is guaranteed to have height over
    1, that is, the direct descendents of the returned (root) node are not tips.

    @param tr
      PLL instance

    @return
      The root node of the randomly picked subtree
*/
nodeptr pllGetRandomSubtree(pllInstance *tr)
{
  nodeptr p;
  do
  {
    int exitDirection = rand() % 3; 
    p = tr->nodep[(rand() % (tr->mxtips - 2)) + 1 + tr->mxtips];
    switch(exitDirection)
    {
      case 0:
        break;
      case 1:
        p = p->next;
        break;
      case 2:
        p = p->next->next;
        break;
      default:
        assert(0);
    }
  }
  while(isTip(p->next->back->number, tr->mxtips) && isTip(p->next->next->back->number, tr->mxtips));
  assert(!isTip(p->number, tr->mxtips));
  return p;
}
/* small example program that executes ancestral state computations 
   on the entire subtree rooted at p.

   Note that this is a post-order traversal.
*/

  
void computeAllAncestralVectors(nodeptr p, pllInstance *tr, partitionList *pr)
{
  /* if this is not a tip, for which evidently it does not make sense 
     to compute the ancestral sequence because we have the real one ....
  */

  if(!isTip(p->number, tr->mxtips))
    {
      /* descend recursively to compute the ancestral states in the left and right subtrees */

      computeAllAncestralVectors(p->next->back, tr, pr);
      computeAllAncestralVectors(p->next->next->back, tr, pr);
      
      /* then compute the ancestral state at node p */

      pllUpdatePartialsAncestral(tr, pr, p);

      /* and print it to terminal, the two booleans that are set to PLL_TRUE here 
         tell the function to print the marginal probabilities as well as 
         a discrete inner sequence, that is, ACGT etc., always selecting and printing 
         the state that has the highest probability */

      printAncestralState(p, PLL_TRUE, PLL_TRUE, tr, pr);
    }
}



void initializePartitionData(pllInstance *localTree, partitionList * localPartitions)
{
  /* in ancestralVectorWidth we store the total length in bytes (!) of 
     one conditional likelihood array !
     we need to know this length such that in the pthreads version the master thread can actually 
     gather the scattered ancestral probabilities from the threads such that they can be printed to screen!
  */

  size_t 
    maxCategories = (size_t)localTree->maxCategories;

  size_t 
    ancestralVectorWidth = 0,
    model; 

  int 
    tid  = localTree->threadID,
    innerNodes = localTree->mxtips - 2;

  if(tid > 0)
      localTree->rateCategory    = (int *)    rax_calloc((size_t)localTree->originalCrunchedLength, sizeof(int));           

  for(model = 0; model < (size_t)localPartitions->numberOfPartitions; model++)
    {
      size_t 
        width = localPartitions->partitionData[model]->width;

      const partitionLengths 
        *pl = getPartitionLengths(localPartitions->partitionData[model]);

      /* 
         globalScaler needs to be 2 * localTree->mxtips such that scalers of inner AND tip nodes can be added without a case switch
         to this end, it must also be initialized with zeros -> calloc
      */

      localPartitions->partitionData[model]->globalScaler    = (unsigned int *)rax_calloc(2 *(size_t)localTree->mxtips, sizeof(unsigned int));

      rax_posix_memalign ((void **)&(localPartitions->partitionData[model]->left),  PLL_BYTE_ALIGNMENT, (size_t)pl->leftLength * (maxCategories + 1) * sizeof(double));
      rax_posix_memalign ((void **)&(localPartitions->partitionData[model]->right), PLL_BYTE_ALIGNMENT, (size_t)pl->rightLength * (maxCategories + 1) * sizeof(double));
      localPartitions->partitionData[model]->EIGN              = (double*)rax_malloc((size_t)pl->eignLength * sizeof(double));
      rax_posix_memalign ((void **)&(localPartitions->partitionData[model]->EV),    PLL_BYTE_ALIGNMENT, (size_t)pl->evLength * sizeof(double));
      localPartitions->partitionData[model]->EI                = (double*)rax_malloc((size_t)pl->eiLength * sizeof(double));
      localPartitions->partitionData[model]->substRates        = (double *)rax_malloc((size_t)pl->substRatesLength * sizeof(double));
      localPartitions->partitionData[model]->frequencies       = (double*)rax_malloc((size_t)pl->frequenciesLength * sizeof(double));
      localPartitions->partitionData[model]->freqExponents     = (double*)rax_malloc(pl->frequenciesLength * sizeof(double));
      localPartitions->partitionData[model]->empiricalFrequencies       = (double*)rax_malloc((size_t)pl->frequenciesLength * sizeof(double));
      rax_posix_memalign ((void **)&(localPartitions->partitionData[model]->tipVector), PLL_BYTE_ALIGNMENT, (size_t)pl->tipVectorLength * sizeof(double));
      //localPartitions->partitionData[model]->partitionName      = NULL;   // very imporatant since it is deallocated in pllPartitionDestroy
      
       if(localPartitions->partitionData[model]->dataType == PLL_AA_DATA
               && (localPartitions->partitionData[model]->protModels == PLL_LG4M || localPartitions->partitionData[model]->protModels == PLL_LG4X))
        {
          int 
            k;
          
          for(k = 0; k < 4; k++)
            {       
              localPartitions->partitionData[model]->EIGN_LG4[k]              = (double*)rax_malloc(pl->eignLength * sizeof(double));
              rax_posix_memalign ((void **)&(localPartitions->partitionData[model]->EV_LG4[k]), PLL_BYTE_ALIGNMENT, pl->evLength * sizeof(double));
              localPartitions->partitionData[model]->EI_LG4[k]                = (double*)rax_malloc(pl->eiLength * sizeof(double));
              localPartitions->partitionData[model]->substRates_LG4[k]        = (double *)rax_malloc(pl->substRatesLength * sizeof(double));
              localPartitions->partitionData[model]->frequencies_LG4[k]       = (double*)rax_malloc(pl->frequenciesLength * sizeof(double));
              rax_posix_memalign ((void **)&(localPartitions->partitionData[model]->tipVector_LG4[k]), PLL_BYTE_ALIGNMENT, pl->tipVectorLength * sizeof(double));
            }
        }

      localPartitions->partitionData[model]->symmetryVector    = (int *)rax_malloc((size_t)pl->symmetryVectorLength  * sizeof(int));
      localPartitions->partitionData[model]->frequencyGrouping = (int *)rax_malloc((size_t)pl->frequencyGroupingLength  * sizeof(int));

      localPartitions->partitionData[model]->perSiteRates      = (double *)rax_malloc(sizeof(double) * maxCategories);

      localPartitions->partitionData[model]->nonGTR = PLL_FALSE;

      localPartitions->partitionData[model]->gammaRates = (double*)rax_malloc(sizeof(double) * 4);
      localPartitions->partitionData[model]->yVector = (unsigned char **)rax_malloc(sizeof(unsigned char*) * ((size_t)localTree->mxtips + 1));


      localPartitions->partitionData[model]->xVector = (double **)rax_calloc(sizeof(double*), (size_t)localTree->mxtips);

      if (localPartitions->partitionData[model]->ascBias)
       {
         localPartitions->partitionData[model]->ascOffset    = 4 * localPartitions->partitionData[model]->states * localPartitions->partitionData[model]->states;
         localPartitions->partitionData[model]->ascVector    = (double *)rax_malloc(innerNodes * 
                                                                                    localPartitions->partitionData[model]->ascOffset * 
                                                                                    sizeof(double));
         localPartitions->partitionData[model]->ascExpVector = (int *)rax_calloc(innerNodes *
                                                                                 localPartitions->partitionData[model]->states,
                                                                                 sizeof(int));
         localPartitions->partitionData[model]->ascSumBuffer = (double *)rax_malloc(localPartitions->partitionData[model]->ascOffset * sizeof(double)); 
       }


      /* 
         Initializing the xVector array like this is absolutely required !!!!
         I don't know which programming genious removed this, but it must absolutely stay in here!!!!
      */
      
      {
        int k;
        
        for(k = 0; k < localTree->mxtips; k++)
              localPartitions->partitionData[model]->xVector[k] = (double*)NULL;       
      }


      localPartitions->partitionData[model]->xSpaceVector = (size_t *)rax_calloc((size_t)localTree->mxtips, sizeof(size_t));

      const size_t span = (size_t)(localPartitions->partitionData[model]->states) *
              discreteRateCategories(localTree->rateHetModel);

#ifdef __MIC_NATIVE

      // Alexey: sum buffer buffer padding for Xeon PHI
      const int aligned_width = width % PLL_VECTOR_WIDTH == 0 ? width : width + (PLL_VECTOR_WIDTH - (width % PLL_VECTOR_WIDTH));

      rax_posix_memalign ((void **)&(localPartitions->partitionData[model]->sumBuffer), PLL_BYTE_ALIGNMENT, aligned_width *
                                                                                      span *
                                                                                      sizeof(double));

      // Alexey: fill padding entries with 1. (will be corrected with site weights, s. below)
      {
          int k;
          for (k = width*span; k < aligned_width*span; ++k)
              localPartitions->partitionData[model]->sumBuffer[k] = 1.;
      }

#else

      rax_posix_memalign ((void **)&(localPartitions->partitionData[model]->sumBuffer), PLL_BYTE_ALIGNMENT, width *
                                              span *
                                              sizeof(double));
#endif

      /* Initialize buffers to store per-site log likelihoods */

      rax_posix_memalign ((void **)&(localPartitions->partitionData[model]->perSiteLikelihoods), PLL_BYTE_ALIGNMENT, width * sizeof(double));

      /* initialize data structures for per-site likelihood scaling */

      if(localTree->fastScaling)
        {
           localPartitions->partitionData[model]->expVector      = (int **)NULL;
           localPartitions->partitionData[model]->expSpaceVector = (size_t *)NULL;
        }
      else
        {        
          localPartitions->partitionData[model]->expVector      = (int **)rax_malloc(sizeof(int*) * innerNodes);
           
          /* 
             Initializing the expVector array like this is absolutely required !!!!
             Not doing this can (and did) cause segmentation faults !!!!
          */
          
          {
            int k;

            for(k = 0; k < innerNodes; k++)
              localPartitions->partitionData[model]->expVector[k] = (int*)NULL; 
          }

          localPartitions->partitionData[model]->expSpaceVector = (size_t *)rax_calloc(innerNodes, sizeof(size_t));
        }

      /* data structure to store the marginal ancestral probabilities in the sequential version or for each thread */

      rax_posix_memalign ((void **)&(localPartitions->partitionData[model]->ancestralBuffer), PLL_BYTE_ALIGNMENT, width *
                                                                                 (size_t)(localPartitions->partitionData[model]->states) *
                                                                                 sizeof(double));

      /* count and accumulate how many bytes we will need for storing a full ancestral vector. for this we addf over the per-partition space requirements in bytes */
      /* ancestralVectorWidth += ((size_t)(pr->partitionData[model]->upper - pr->partitionData[model]->lower) * (size_t)(localPartitions->partitionData[model]->states) * sizeof(double)); */
      ancestralVectorWidth += ((size_t)(localPartitions->partitionData[model]->upper - localPartitions->partitionData[model]->lower) * (size_t)(localPartitions->partitionData[model]->states) * sizeof(double));
      /* :TODO: do we have to use the original tree for that   */

#ifdef __MIC_NATIVE

      rax_posix_memalign ((void **)&(localPartitions->partitionData[model]->wgt), PLL_BYTE_ALIGNMENT, aligned_width * sizeof(int));

      // Alexey: fill padding entries with 0.
      {
          int k;
          for (k = width; k < aligned_width; ++k)
              localPartitions->partitionData[model]->wgt[k] = 0;
      }
#else
      rax_posix_memalign ((void **)&(localPartitions->partitionData[model]->wgt), PLL_BYTE_ALIGNMENT, width * sizeof(int));
#endif

      /* rateCategory must be assigned using rax_calloc() at start up there is only one rate category 0 for all sites */

      localPartitions->partitionData[model]->rateCategory = (int *)rax_calloc(width, sizeof(int));

      if(width > 0 && localTree->saveMemory)
        {
          localPartitions->partitionData[model]->gapVectorLength = ((int)width / 32) + 1;
          assert(4 == sizeof(unsigned int));
          localPartitions->partitionData[model]->gapVector = (unsigned int*)rax_calloc((size_t)localPartitions->partitionData[model]->gapVectorLength * 2 * (size_t)localTree->mxtips, sizeof(unsigned int));
          rax_posix_memalign ((void **)&(localPartitions->partitionData[model]->gapColumn),PLL_BYTE_ALIGNMENT, ((size_t)localTree->mxtips) *
                                                                               ((size_t)(localPartitions->partitionData[model]->states)) *
                                                                               discreteRateCategories(localTree->rateHetModel) * sizeof(double));
        }
      else
        {
          localPartitions->partitionData[model]->gapVectorLength = 0;
          localPartitions->partitionData[model]->gapVector = (unsigned int*)NULL;
          localPartitions->partitionData[model]->gapColumn = (double*)NULL;
        }              
    }
}

int virtual_width( int n ) {
    const int global_vw = 2;
    return (n+1) / global_vw * global_vw;
}


void initMemorySavingAndRecom(pllInstance *tr, partitionList *pr)
{
  pllInstance  
    *localTree = tr; 
  partitionList
    *localPartitions = pr;
  size_t model; 

  /* initialize gap bit vectors at tips when memory saving option is enabled */

  if(localTree->saveMemory)
    {
      for(model = 0; model < (size_t)localPartitions->numberOfPartitions; model++)
        {
          int        
            undetermined = getUndetermined(localPartitions->partitionData[model]->dataType);

          size_t
            i,
            j,
            width =  localPartitions->partitionData[model]->width;

          if(width > 0)
            {                                        
              for(j = 1; j <= (size_t)(localTree->mxtips); j++)
                for(i = 0; i < width; i++)
                  if(localPartitions->partitionData[model]->yVector[j][i] == undetermined)
                    localPartitions->partitionData[model]->gapVector[localPartitions->partitionData[model]->gapVectorLength * j + i / 32] |= mask32[i % 32];
            }     
        }
    }
  /* recom */
  if(localTree->useRecom)
    allocRecompVectorsInfo(localTree);
  else
    localTree->rvec = (recompVectors*)NULL;
  /* E recom */
}

/** @brief Get the length of a specific branch

    Get the length of the branch specified by node \a p and \a p->back
    of partition \a partition_id.
    The branch length is decoded from the PLL representation.

    @param tr
      PLL instance

    @param p
      Specifies one end-point of the branch. The other one is \a p->back

    @param partition_id
      Specifies the partition

    @return
      The branch length
*/
double pllGetBranchLength (pllInstance *tr, nodeptr p, int partition_id)
{
  //assert(partition_id < tr->numBranches);
  assert(partition_id < PLL_NUM_BRANCHES);
  assert(partition_id >= 0);
  assert(tr->fracchange != -1.0);
  double z = p->z[partition_id];
  if(z < PLL_ZMIN) z = PLL_ZMIN;
  if(z > PLL_ZMAX) z = PLL_ZMAX;
  return (-log(z) * tr->fracchange);
}

/** @brief Set the length of a specific branch

    Set the length of the branch specified by node \a p and \a p->back
    of partition \a partition_id.
    The function encodes the branch length to the PLL representation.

    @param tr
      PLL instance

    @param p
      Specifies one end-point of the branch. The other one is \a p->back

    @param partition_id
      Specifies the partition

    @param bl
      Branch length
*/
void pllSetBranchLength (pllInstance *tr, nodeptr p, int partition_id, double bl)
{
  //assert(partition_id < tr->numBranches);
  assert(partition_id < PLL_NUM_BRANCHES);
  assert(partition_id >= 0);
  assert(tr->fracchange != -1.0);
  double z;
  z = exp((-1 * bl)/tr->fracchange);
  if(z < PLL_ZMIN) z = PLL_ZMIN;
  if(z > PLL_ZMAX) z = PLL_ZMAX;
  p->z[partition_id] = z;
}

#if (!defined(_FINE_GRAIN_MPI) && !defined(_USE_PTHREADS))
static void initializePartitionsSequential(pllInstance *tr, partitionList *pr)
{ 
  size_t
    model;

  for(model = 0; model < (size_t)pr->numberOfPartitions; model++)
    assert(pr->partitionData[model]->width == pr->partitionData[model]->upper - pr->partitionData[model]->lower);

  initializePartitionData(tr, pr);

  /* figure in tip sequence data per-site pattern weights */ 
  for(model = 0; model < (size_t)pr->numberOfPartitions; model++)
  {
    size_t
      j;
    size_t lower = pr->partitionData[model]->lower;
    size_t width = pr->partitionData[model]->upper - lower;

    for(j = 1; j <= (size_t)tr->mxtips; j++)
    {
      pr->partitionData[model]->yVector[j] = &(tr->yVector[j][pr->partitionData[model]->lower]);
    }

    memcpy((void*)(&(pr->partitionData[model]->wgt[0])),         (void*)(&(tr->aliaswgt[lower])),      sizeof(int) * width);
  }  

  initMemorySavingAndRecom(tr, pr);
}
#endif


/* interface to outside  */
//void initializePartitions(pllInstance *tr, pllInstance *localTree, partitionList *pr, partitionList *localPr, int tid, int n)
//{
//#if (defined(_FINE_GRAIN_MPI) || defined(_USE_PTHREADS))
//  initializePartitionsMaster(tr,localTree,pr,localPr,tid,n);
//#else
//  initializePartitionsSequential(tr, pr);
//#endif
//}

static void freeLinkageList( linkageList* ll)
{
  int i;    

  for(i = 0; i < ll->entries; i++)    
    rax_free(ll->ld[i].partitionList);         

  rax_free(ll->ld);
  rax_free(ll);   
}

/** @brief free all data structures associated to a partition
    
    frees all data structures allocated for this partition

    @param partitions
      the pointer to the partition list

    @param tips  
       number of tips in the tree      
*/
void 
pllPartitionsDestroy (pllInstance * tr, partitionList ** partitions)
{
  int i, j, tips;
  partitionList * pl = *partitions;

#ifdef _USE_PTHREADS
  int tid = tr->threadID;
  if (MASTER_P) {
     pllMasterBarrier (tr, pl, PLL_THREAD_EXIT_GRACEFULLY);
     pllStopPthreads (tr);
    }
#endif

  tips = tr->mxtips;

#ifdef _USE_PTHREADS
  if (MASTER_P) {
#endif
#ifdef _FINE_GRAIN_MPI
if (MASTER_P) {
     pllMasterBarrier (tr, pl, PLL_THREAD_EXIT_GRACEFULLY);
#endif
  freeLinkageList(pl->alphaList);
  freeLinkageList(pl->freqList); 
  freeLinkageList(pl->rateList);
#ifdef _FINE_GRAIN_MPI
}
#endif

#ifdef _USE_PTHREADS
  }
#endif
  for (i = 0; i < pl->numberOfPartitions; ++ i)
   {
     rax_free (pl->partitionData[i]->gammaRates);
     rax_free (pl->partitionData[i]->perSiteRates);
     rax_free (pl->partitionData[i]->globalScaler);
     rax_free (pl->partitionData[i]->left);
     rax_free (pl->partitionData[i]->right);
     rax_free (pl->partitionData[i]->EIGN);
     rax_free (pl->partitionData[i]->EV);
     rax_free (pl->partitionData[i]->EI);
     rax_free (pl->partitionData[i]->substRates);
     rax_free (pl->partitionData[i]->frequencies);
     rax_free (pl->partitionData[i]->freqExponents);
     rax_free (pl->partitionData[i]->empiricalFrequencies);
     rax_free (pl->partitionData[i]->tipVector);
     rax_free (pl->partitionData[i]->symmetryVector);
     rax_free (pl->partitionData[i]->frequencyGrouping);
     for (j = 0; j < tips; ++ j)
       rax_free (pl->partitionData[i]->xVector[j]);
     rax_free (pl->partitionData[i]->xVector);
     rax_free (pl->partitionData[i]->yVector);
     rax_free (pl->partitionData[i]->xSpaceVector);
     rax_free (pl->partitionData[i]->sumBuffer);
     rax_free (pl->partitionData[i]->ancestralBuffer);
     rax_free (pl->partitionData[i]->wgt);
     rax_free (pl->partitionData[i]->rateCategory);
     rax_free (pl->partitionData[i]->gapVector);
     rax_free (pl->partitionData[i]->gapColumn);
     rax_free (pl->partitionData[i]->perSiteLikelihoods);
     rax_free (pl->partitionData[i]->partitionName);
     rax_free (pl->partitionData[i]->expSpaceVector);
     /*TODO: Deallocate all entries of expVector */
     if (pl->partitionData[i]->expVector)
      {
        for (j = 0; j < tips - 2; ++ j)
          rax_free (pl->partitionData[i]->expVector[j]);
      }
     rax_free (pl->partitionData[i]->expVector);
     rax_free (pl->partitionData[i]);
   }
  rax_free (pl->partitionData);
  rax_free (pl);

  *partitions = NULL;

#if (defined(_USE_PTHREADS) || defined(_FINE_GRAIN_MPI))
     rax_free (tr->y_ptr);
#endif
}

/** @ingroup instanceLinkingGroup
    @brief Correspondance check between partitions and alignment

    This function checks whether the partitions to be created and the given
    alignment correspond, that is, whether each site of the alignment is
    assigned to exactly one partition.

    @param parts
      A list of partitions suggested by the caller

    @param alignmentData
      The multiple sequence alignment
    
    @return
      Returns \a 1 in case of success, otherwise \a 0
*/
int
pllPartitionsValidate (pllQueue * parts, pllAlignmentData * alignmentData)
{
  int nparts;
  char * used;
  struct pllQueueItem * elm;
  struct pllQueueItem * regionItem;
  pllPartitionRegion * region;
  pllPartitionInfo * pi;
  int i;

  /* check if the list contains at least one partition */
  nparts = pllQueueSize (parts);
  if (!nparts)          
    return (0);   

  /* pllBoolean array for marking that a site was assigned a partition */
  used = (char *) rax_calloc (alignmentData->sequenceLength, sizeof (char));

  /* traverse all partitions and their respective regions and mark sites */
  for (elm = parts->head; elm; elm = elm->next)
   {
     pi = (pllPartitionInfo *) elm->item;
     
     for (regionItem = pi->regionList->head; regionItem; regionItem = regionItem->next)
      {
        region = (pllPartitionRegion *) regionItem->item;
        
        if (region->start < 1 || region->end > alignmentData->sequenceLength) 
         {
           rax_free (used);
           return (0);
         }

        for (i = region->start - 1; i < region->end; i += region->stride)
         {
           if (used[i])
            {
              rax_free (used);
              return (0);
            }
           used[i] = 1; 
         }
      }
   }

  /* check whether all sites were assigned a partition */
  for (i = 0; i < alignmentData->sequenceLength; ++ i)
    if (used[i] != 1)
     {
       rax_free (used);
       return (0);
     }

  rax_free (used);
  return (1);
}

/** @brief Swap two sites in a buffer
    
    Swaps sites \a s1 and \a s2 in buffer \a buf which consists of \a nTaxa + 1
    taxa (i.e. rows), and the first row contains no information, i.e. it is not
    accessed.

    @param buffer
      Memory buffer

    @param s1
      First site

    @param s2
      Second site

    @param nTaxa
      Number of taxa, i.e. size of site
*/
static __inline void
swapSite (unsigned char ** buf, int s1, int s2, int nTaxa)
{
  int i;
  int x;

  for (i = 1; i <= nTaxa; ++ i)
  {
    x = buf[i][s1];
    buf[i][s1] = buf[i][s2];
    buf[i][s2] = x;
  }
}

/** @brief Constructs the list of partitions according to the proposed partition scheme
    
    A static function that construcs the \a partitionList structure according to
    the partition scheme \b AFTER the sites have been repositioned in contiguous
    regions according to the partition scheme.

    @param bounds  An array of the new starting and ending posititons of sites
    in the alignment for each partition.  This array is of size 2 * \a nparts.
    The elements are always couples (lower,upper). The upper bounds is a site
    that is not included in the partition

    @param nparts The number of partitions to be created

    @todo Fix the bug in PLL 
*/
static partitionList * createPartitions (pllQueue * parts, int * bounds)
{
  partitionList * pl;
  pllPartitionInfo * pi;
  struct pllQueueItem * elm;
  int i, j;

  pl = (partitionList *) rax_malloc (sizeof (partitionList));
  
  // TODO: fix this
  pl->perGeneBranchLengths =      0;

  // TODO: change PLL_NUM_BRANCHES to number of partitions I guess
  pl->partitionData = (pInfo **) rax_calloc (PLL_NUM_BRANCHES, sizeof (pInfo *));
  
  for (i = 0, elm = parts->head; elm; elm = elm->next, ++ i)
   {
     pi = (pllPartitionInfo *) elm->item;

     /* check whether the data type is valid, and in case it's not, deallocate
        and return NULL */
     if (pi->dataType <= PLL_MIN_MODEL || pi->dataType >= PLL_MAX_MODEL)
      {
        for (j = 0; j < i; ++ j)
         {
           rax_free (pl->partitionData[j]->partitionName);
           rax_free (pl->partitionData[j]);
         }
        rax_free (pl->partitionData);
        rax_free (pl);
        return (NULL);
      }

     pl->partitionData[i] = (pInfo *) rax_malloc (sizeof (pInfo));

     pl->partitionData[i]->lower = bounds[i << 1];
     pl->partitionData[i]->upper = bounds[(i << 1) + 1];
     pl->partitionData[i]->width = bounds[(i << 1) + 1] - bounds[i << 1];
     pl->partitionData[i]->partitionWeight = 1.0 * (double) pl->partitionData[i]->width;

     //the two flags below are required to allow users to set 
     //alpha parameters and substitution rates in the Q matrix 
     //to fixed values. These parameters will then not be optimized 
     //in the model parameter optimization functions
     //by default we assume that all parameters are being optimized, i.e., 
     //this has to be explicitly set by the user 
     
     pl->partitionData[i]->optimizeAlphaParameter    = PLL_TRUE;
     pl->partitionData[i]->optimizeSubstitutionRates = PLL_TRUE;
     pl->partitionData[i]->dataType                  = pi->dataType;
     pl->partitionData[i]->protModels                = -1;
     pl->partitionData[i]->protUseEmpiricalFreqs     = -1;
     pl->partitionData[i]->maxTipStates              = pLengths[pi->dataType].undetermined + 1;
     pl->partitionData[i]->optimizeBaseFrequencies   = pi->optimizeBaseFrequencies;
     pl->partitionData[i]->ascBias                   = pi->ascBias;
     pl->partitionData[i]->parsVect                  = NULL;



     if (pi->dataType == PLL_AA_DATA)
      {
        if(pl->partitionData[i]->protModels != PLL_GTR)
          pl->partitionData[i]->optimizeSubstitutionRates = PLL_FALSE;
        pl->partitionData[i]->protUseEmpiricalFreqs     = pi->protUseEmpiricalFreqs;
        pl->partitionData[i]->protModels                = pi->protModels;
      }

     pl->partitionData[i]->states                = pLengths[pl->partitionData[i]->dataType].states;
     pl->partitionData[i]->numberOfCategories    =        1;
     pl->partitionData[i]->autoProtModels        =        0;
     pl->partitionData[i]->nonGTR                =        PLL_FALSE;
     pl->partitionData[i]->partitionContribution =     -1.0;
     pl->partitionData[i]->partitionLH           =      0.0;
     pl->partitionData[i]->fracchange            =      1.0;
     pl->partitionData[i]->executeModel          =     PLL_TRUE;


     pl->partitionData[i]->partitionName         = (char *) rax_malloc ((strlen (pi->partitionName) + 1) * sizeof (char));
     strcpy (pl->partitionData[i]->partitionName, pi->partitionName);
   }

  return (pl);
}


/** @ingroup instanceLinkingGroup
    @brief Constructs the proposed partition scheme 

    This function constructs the proposed partition scheme. It assumes
    that the partition scheme is correct.

    @note This function \b does \b not validate the partition scheme.
    The user must manually call the ::pllPartitionsValidate function
    for validation
    
    @param parts
      A list of partitions suggested by the caller

    @param alignmentData
      The multiple sequence alignment

    @return
      Returns a pointer to \a partitionList structure of partitions in case of success, \b NULL otherwise
*/
partitionList * pllPartitionsCommit (pllQueue * parts, pllAlignmentData * alignmentData)
{
  int * oi;
  int i, j, dst;
  struct pllQueueItem * elm;
  struct pllQueueItem * regionItem;
  pllPartitionRegion * region;
  pllPartitionInfo * pi;
  partitionList * pl;
  int * newBounds;
  int k, nparts;
  int tmpvar;
 

  dst = k = 0;
  oi  = (int *) rax_malloc (alignmentData->sequenceLength * sizeof (int));
  for (i = 0; i < alignmentData->sequenceLength; ++ i) oi[i] = i;

  nparts = pllQueueSize (parts);
  newBounds = (int *) rax_malloc (2 * nparts * sizeof (int));

  /* reposition the sites in the alignment */
  for (elm = parts->head; elm; elm = elm->next, ++ k)
   {
     pi = (pllPartitionInfo *) elm->item;
     
     newBounds[k << 1] = dst;   /* set the lower column for this partition */
     for (regionItem = pi->regionList->head; regionItem; regionItem = regionItem->next)
      {
        region = (pllPartitionRegion *) regionItem->item;

        for (i = region->start - 1; i < region->end && i < alignmentData->sequenceLength; i += region->stride)
         {
           if (oi[i] == i)
            {
              swapSite (alignmentData->sequenceData, dst, i, alignmentData->sequenceCount);
              tmpvar = oi[i];
              oi[i] = oi[dst];
              oi[dst++] = tmpvar;
            }
           else
            {
              j = i;
              while (oi[j] != i) j = oi[j];

              swapSite (alignmentData->sequenceData, dst, j, alignmentData->sequenceCount);
              tmpvar = oi[j];
              oi[j] = oi[dst];
              oi[dst++] = tmpvar;
            }
         }
      }
     newBounds[(k << 1) + 1] = dst;    /* set the uppwer limit for this partition */
   }
  if ((pl = createPartitions (parts, newBounds)))
   { 
     pl->numberOfPartitions = nparts;
     pl->dirty = PLL_FALSE;
   }
  
  rax_free (newBounds);
  rax_free (oi);

  return (pl);
}

/** @brief Copy a site to another buffer

    Copies site \a from from buffer \a src to \a to in buffer \a dst. Both buffers
    must consist of \a nTaxa + 1 taxa and the first row contains no information, i.e.
    it is not accessed.

    @param dst
      Destination buffer

    @param src
      Source buffer

    @param to
      At which position in \a dst to copy the site to

    @param from
      Which site from \a src to copy

    @param nTaxa
      Number of taxa, i.e. size of site
*/
static __inline void
copySite (unsigned char ** dst, unsigned char ** src, int to, int from, int nTaxa)
{
  int i;

  for (i = 1; i <= nTaxa; ++ i)
   {
     dst[i][to] = src[i][from];
   }
}

/** @brief Remove duplicate sites from alignment and update weights vector

    Removes duplicate sites from the alignment given the partitions list
    and updates the weight vector of the alignment and the boundaries
    (upper, lower, width) for each partition.

    @param alignmentData
      The multiple sequence alignment
    
    @param pl
      List of partitions

*/
void 
pllAlignmentRemoveDups (pllAlignmentData * alignmentData, partitionList * pl)
{
  int i, j, k, p;
  char *** sites;
  void ** memptr;
  int ** oi;
  int dups = 0;
  int lower;

  /* allocate space for the transposed alignments (sites) for every partition */
  sites  = (char ***) rax_malloc (pl->numberOfPartitions * sizeof (char **));
  memptr = (void **)  rax_malloc (pl->numberOfPartitions * sizeof (void *));
  oi     = (int **)   rax_malloc (pl->numberOfPartitions * sizeof (int *));

  /* transpose the sites by partition */
  for (p = 0; p < pl->numberOfPartitions; ++ p)
   {
     sites[p]  = (char **) rax_malloc (sizeof (char *) * pl->partitionData[p]->width);
     memptr[p] = rax_malloc (sizeof (char) * (alignmentData->sequenceCount + 1) * pl->partitionData[p]->width);

     for (i = 0; i < pl->partitionData[p]->width; ++ i)
      {
        sites[p][i] = (char *) ((char*)memptr[p] + sizeof (char) * i * (alignmentData->sequenceCount + 1));
      }

     for (i = 0; i < pl->partitionData[p]->width; ++ i)
      {
        for (j = 0; j < alignmentData->sequenceCount; ++ j)
         {
           sites[p][i][j] = alignmentData->sequenceData[j + 1][pl->partitionData[p]->lower + i]; 
         }
        sites[p][i][j] = 0;
      }

     oi[p] = pllssort1main (sites[p], pl->partitionData[p]->width);

     for (i = 0; i < pl->partitionData[p]->width; ++ i) oi[p][i] = 1;

     for (i = 1; i < pl->partitionData[p]->width; ++ i)
      {
        if (! strcmp (sites[p][i], sites[p][i - 1]))
         {
           ++ dups;
           oi[p][i] = 0;
         }
      }
   }

  /* allocate memory for the alignment without duplicates*/
  rax_free (alignmentData->sequenceData[1]);
  rax_free (alignmentData->siteWeights);

  alignmentData->sequenceLength = alignmentData->sequenceLength - dups;
  alignmentData->sequenceData[0] = (unsigned char *) rax_malloc ((alignmentData->sequenceLength + 1) * sizeof (unsigned char) * alignmentData->sequenceCount);
  for (i = 0; i < alignmentData->sequenceCount; ++ i)
   {
     alignmentData->sequenceData[i + 1] = (unsigned char *) (alignmentData->sequenceData[0] + sizeof (unsigned char) * i * (alignmentData->sequenceLength + 1));
     alignmentData->sequenceData[i + 1][alignmentData->sequenceLength] = 0;
   }

  alignmentData->siteWeights    = (int *) rax_malloc ((alignmentData->sequenceLength) * sizeof (int));
  alignmentData->siteWeights[0] = 1;

  /* transpose sites back to alignment */
  for (p = 0, k = 0; p < pl->numberOfPartitions; ++ p)
   {
     lower = k;
     for (i = 0; i < pl->partitionData[p]->width; ++ i)
      {
        if (!oi[p][i])
         {
           ++ alignmentData->siteWeights[k - 1];
         }
        else
         {
           alignmentData->siteWeights[k] = 1;
           for (j = 0; j < alignmentData->sequenceCount; ++ j)
            {
              alignmentData->sequenceData[j + 1][k] = sites[p][i][j];
            }
           ++ k;
         }
      }
     pl->partitionData[p]->lower = lower;
     pl->partitionData[p]->upper = k;
     pl->partitionData[p]->width = k - lower;
   }

  /* deallocate storage for transposed alignment (sites) */
  for (p = 0; p < pl->numberOfPartitions; ++ p)
   {
     rax_free (oi[p]);
     rax_free (memptr[p]);
     rax_free (sites[p]);
   }
  rax_free (oi);
  rax_free (sites);
  rax_free (memptr);
}


/** @brief Compute the empirical frequencies of a partition
  
    Compute the empirical frequencies of partition \a partition and store them in
    \a pfreqs.

    @param partition
      The partition for which to compute empirical frequencies

    @param alignmentData
      The multiple sequence alignment

    @param smoothFrequencies
      Not needed?

    @param bitMask
      The bitmask

    @param pfreqs
      Array of size \a partition->states where the empirical frequencies for this partition are stored
*/
static int genericBaseFrequenciesAlignment (pInfo * partition, 
                                              pllAlignmentData * alignmentData, 
                                              pllBoolean smoothFrequencies,
                                              const unsigned int * bitMask, 
                                              double * pfreqs)
{
  double 
    wj, 
    acc,
    sumf[64],   
    temp[64];
 
  int     
    i, 
    j, 
    k, 
    l,
    numFreqs,
    lower,
    upper;

  unsigned char  *yptr;  
  const char * map;
  
  switch (partition->dataType)
   {
     case PLL_BINARY_DATA:
       map = PLL_MAP_BIN;
     case PLL_DNA_DATA:
       map = PLL_MAP_NT;
       break;
     case PLL_AA_DATA:
       map = PLL_MAP_AA;
       break;
     default:
       assert(0);
   }

  numFreqs = partition->states;
  lower    = partition->lower;
  upper    = partition->upper;

  for(l = 0; l < numFreqs; l++)     
    pfreqs[l] = 1.0 / ((double)numFreqs);
          
  for (k = 1; k <= 8; k++) 
    {                                                   
      for(l = 0; l < numFreqs; l++)
        sumf[l] = 0.0;
              
      for (i = 1; i <= alignmentData->sequenceCount; i++) 
        {                
          yptr = alignmentData->sequenceData[i];
          
          for(j = lower; j < upper; j++) 
            {
              if (map[yptr[j]] < 0) return (0);
              unsigned int code = bitMask[(unsigned char)map[yptr[j]]];
              assert(code >= 1);
              
              for(l = 0; l < numFreqs; l++)
                {
                  if((code >> l) & 1)
                    temp[l] = pfreqs[l];
                  else
                    temp[l] = 0.0;
                }                             
              
              for(l = 0, acc = 0.0; l < numFreqs; l++)
                {
                  if(temp[l] != 0.0)
                    acc += temp[l];
                }
              
              wj = alignmentData->siteWeights[j] / acc;
              
              for(l = 0; l < numFreqs; l++)
                {
                  if(temp[l] != 0.0)                
                    sumf[l] += wj * temp[l];                                                                                               
                }
            }
        }                     
      
      for(l = 0, acc = 0.0; l < numFreqs; l++)
        {
          if(sumf[l] != 0.0)
            acc += sumf[l];
        }
              
      for(l = 0; l < numFreqs; l++)
        pfreqs[l] = sumf[l] / acc;           
    }

   /* TODO: What is that? */
/*
  if(smoothFrequencies)         
   {;
    smoothFreqs(numFreqs, pfreqs,  tr->partitionData[model].frequencies, &(tr->partitionData[model]));     
   }
  else    
    {
      pllBoolean
        zeroFreq = PLL_FALSE;

      char 
        typeOfData[1024];

      getDataTypeString(tr, model, typeOfData);  

      for(l = 0; l < numFreqs; l++)
        {
          if(pfreqs[l] == 0.0)
            {
              printBothOpen("Empirical base frequency for state number %d is equal to zero in %s data partition %s\n", l, typeOfData, tr->partitionData[model].partitionName);
              printBothOpen("Since this is probably not what you want to do, RAxML will soon exit.\n\n");
              zeroFreq = PLL_TRUE;
            }
        }

      if(zeroFreq)
        exit(-1);

      for(l = 0; l < numFreqs; l++)
        {
          assert(pfreqs[l] > 0.0);
          tr->partitionData[model].frequencies[l] = pfreqs[l];
        }     
    }  
*/
  return (1);
  
}

static void  genericBaseFrequenciesInstance (pInfo * partition, 
                                             pllInstance * tr, 
                                             pllBoolean smoothFrequencies,
                                             const unsigned int * bitMask, 
                                             double * pfreqs)
{
  double 
    wj, 
    acc,
    sumf[64],   
    temp[64];
 
  int     
    i, 
    j, 
    k, 
    l,
    numFreqs,
    lower,
    upper;

  unsigned char  *yptr;  

  numFreqs = partition->states;
  lower    = partition->lower;
  upper    = partition->upper;

  for(l = 0; l < numFreqs; l++)     
    pfreqs[l] = 1.0 / ((double)numFreqs);
          
  for (k = 1; k <= 8; k++) 
    {                                                   
      for(l = 0; l < numFreqs; l++)
        sumf[l] = 0.0;
              
      for (i = 1; i <= tr->mxtips; i++) 
        {                
          yptr = tr->yVector[i];
          
          for(j = lower; j < upper; j++) 
            {
              unsigned int code = bitMask[yptr[j]];
              assert(code >= 1);
              
              for(l = 0; l < numFreqs; l++)
                {
                  if((code >> l) & 1)
                    temp[l] = pfreqs[l];
                  else
                    temp[l] = 0.0;
                }                             
              
              for(l = 0, acc = 0.0; l < numFreqs; l++)
                {
                  if(temp[l] != 0.0)
                    acc += temp[l];
                }
              
              wj = tr->aliaswgt[j] / acc;
              
              for(l = 0; l < numFreqs; l++)
                {
                  if(temp[l] != 0.0)                
                    sumf[l] += wj * temp[l];                                                                                               
                }
            }
        }                     
      
      for(l = 0, acc = 0.0; l < numFreqs; l++)
        {
          if(sumf[l] != 0.0)
            acc += sumf[l];
        }
              
      for(l = 0; l < numFreqs; l++)
        pfreqs[l] = sumf[l] / acc;           
    }

   /* TODO: What is that? */
/*
  if(smoothFrequencies)         
   {;
    smoothFreqs(numFreqs, pfreqs,  tr->partitionData[model].frequencies, &(tr->partitionData[model]));     
   }
  else    
    {
      pllBoolean
        zeroFreq = PLL_FALSE;

      char 
        typeOfData[1024];

      getDataTypeString(tr, model, typeOfData);  

      for(l = 0; l < numFreqs; l++)
        {
          if(pfreqs[l] == 0.0)
            {
              printBothOpen("Empirical base frequency for state number %d is equal to zero in %s data partition %s\n", l, typeOfData, tr->partitionData[model].partitionName);
              printBothOpen("Since this is probably not what you want to do, RAxML will soon exit.\n\n");
              zeroFreq = PLL_TRUE;
            }
        }

      if(zeroFreq)
        exit(-1);

      for(l = 0; l < numFreqs; l++)
        {
          assert(pfreqs[l] > 0.0);
          tr->partitionData[model].frequencies[l] = pfreqs[l];
        }     
    }  
*/

  
}

/**  Compute the empirical base frequencies of an alignment

     Computes the empirical base frequencies per partition of an alignment \a alignmentData
     given the partition structure \a pl.

     @param alignmentData The alignment structure for which to compute the empirical base frequencies
     @param pl            List of partitions
     @return Returns a list of frequencies for each partition
*/
double ** pllBaseFrequenciesAlignment (pllAlignmentData * alignmentData, partitionList * pl)
{
  int
    i,
    model;

  double 
    **freqs = (double **) rax_malloc (pl->numberOfPartitions * sizeof (double *));

  for (model = 0; model < pl->numberOfPartitions; ++ model)
    {
      freqs[model] = (double *) rax_malloc (pl->partitionData[model]->states * sizeof (double));
      
      switch  (pl->partitionData[model]->dataType)
        {
        case PLL_BINARY_DATA:
        case PLL_AA_DATA:
        case PLL_DNA_DATA:
          if (!genericBaseFrequenciesAlignment (pl->partitionData[model], 
                                                alignmentData, 
                                                pLengths[pl->partitionData[model]->dataType].smoothFrequencies,
                                                pLengths[pl->partitionData[model]->dataType].bitVector,
                                                freqs[model]
                                               ))
            return (NULL);
          break;
        default:
          {
            errno = PLL_UNKNOWN_MOLECULAR_DATA_TYPE;
            for (i = 0; i <= model; ++ i) rax_free (freqs[i]);
            rax_free (freqs);
            return (double **)NULL;
          }
        }
    }
  
  return (freqs);
}

/**  Compute the empirical base frequencies of the alignment incorporated in the instance

     Computes the empirical base frequencies per partition of the alignment
     incorporated in the instance \a tr given the partition structure \a pl.

     @param tr The instance for which to compute the empirical base frequencies
     @param pl List of partitions
     @return Returns a list of frequencies for each partition
*/
double ** pllBaseFrequenciesInstance (pllInstance * tr, partitionList * pl)
{
  int
    i,
    model;

  double 
    **freqs = (double **) rax_malloc (pl->numberOfPartitions * sizeof (double *));

  for (model = 0; model < pl->numberOfPartitions; ++ model)
    {
      freqs[model] = (double *) rax_malloc (pl->partitionData[model]->states * sizeof (double));
      
      switch  (pl->partitionData[model]->dataType)
        {
        case PLL_AA_DATA:
        case PLL_DNA_DATA:
        case PLL_BINARY_DATA:
          genericBaseFrequenciesInstance (pl->partitionData[model], 
                                          tr, 
                                          pLengths[pl->partitionData[model]->dataType].smoothFrequencies,
                                          pLengths[pl->partitionData[model]->dataType].bitVector,
                                          freqs[model]
                                          );
          break;
        default:
          {
            errno = PLL_UNKNOWN_MOLECULAR_DATA_TYPE;
            for (i = 0; i <= model; ++ i) rax_free (freqs[i]);
            rax_free (freqs);
            return (double **)NULL;
          }
        }
    }
  
  return (freqs);
}

void
pllEmpiricalFrequenciesDestroy (double *** empiricalFrequencies, int models)
{
  int i;

  for (i = 0; i < models; ++ i)
   {
     rax_free ((*empiricalFrequencies)[i]);
   }
  rax_free (*empiricalFrequencies);

  *empiricalFrequencies = NULL;
}

int pllLoadAlignment (pllInstance * tr, pllAlignmentData * alignmentData, partitionList * partitions)
{
  int i;
  nodeptr node;
  pllHashItem * hItem;

  if (tr->mxtips != alignmentData->sequenceCount) return (0);

  tr->aliaswgt = (int *) rax_malloc (alignmentData->sequenceLength * sizeof (int));
  memcpy (tr->aliaswgt, alignmentData->siteWeights, alignmentData->sequenceLength * sizeof (int));

  tr->originalCrunchedLength = alignmentData->sequenceLength;
  tr->rateCategory           = (int *)   rax_calloc (tr->originalCrunchedLength, sizeof (int));
  tr->patrat                 = (double*) rax_malloc((size_t)tr->originalCrunchedLength * sizeof(double));
  tr->patratStored           = (double*) rax_malloc((size_t)tr->originalCrunchedLength * sizeof(double));
  tr->lhs                    = (double*) rax_malloc((size_t)tr->originalCrunchedLength * sizeof(double));

  /* allocate memory for the alignment */
  tr->yVector    = (unsigned char **) rax_malloc ((alignmentData->sequenceCount + 1) * sizeof (unsigned char *));                                                                                                                                                                      

  tr->yVector[0] = (unsigned char *)  rax_malloc (sizeof (unsigned char) * (alignmentData->sequenceLength + 1) * alignmentData->sequenceCount);
  for (i = 1; i <= alignmentData->sequenceCount; ++ i) 
   {                     
     tr->yVector[i] = (unsigned char *) (tr->yVector[0] + (i - 1) * (alignmentData->sequenceLength + 1) * sizeof (unsigned char));
     tr->yVector[i][alignmentData->sequenceLength] = 0;
   }                     
                         
  /* place sequences to tips */                              
  for (i = 1; i <= alignmentData->sequenceCount; ++ i)                      
   {                     
     if (!pllHashSearch (tr->nameHash, alignmentData->sequenceLabels[i],(void **)&node)) 
      {
        //rax_free (tr->originalCrunchedLength);
        rax_free (tr->rateCategory);
        rax_free (tr->patrat);
        rax_free (tr->patratStored);
        rax_free (tr->lhs);
        rax_free (tr->yVector[0]);
        rax_free (tr->yVector);
        return (0);
      }
     memcpy (tr->yVector[node->number], alignmentData->sequenceData[i], alignmentData->sequenceLength);
   }

  /* Do the base substitution (from A,C,G....  ->   0,1,2,3....)*/
  pllBaseSubstitute (tr, partitions);

  /* Populate tipNames */
  tr->tipNames = (char **) rax_calloc(tr->mxtips + 1, sizeof (char *));
  for (i = 0; (unsigned int)i < tr->nameHash->size; ++ i)
   {
     hItem = tr->nameHash->Items[i];

     for (; hItem; hItem = hItem->next)
      {
        tr->tipNames[((nodeptr)hItem->data)->number] = hItem->str; 
      }
   }

  return (1);
}

pllInstance * pllCreateInstance (pllInstanceAttr * attr)
{
  pllInstance * tr;

  if (attr->rateHetModel != PLL_GAMMA && attr->rateHetModel != PLL_CAT) return NULL;

  tr = (pllInstance *) rax_calloc (1, sizeof (pllInstance));

  tr->threadID          = 0;
  tr->rateHetModel      = attr->rateHetModel;
  tr->fastScaling       = attr->fastScaling;
  tr->saveMemory        = attr->saveMemory;
  tr->useRecom          = attr->useRecom;
  tr->likelihoodEpsilon = 0.01;
  
  tr->randomNumberSeed = attr->randomNumberSeed;
  tr->parsimonyScore   = NULL;

  /* remove it from the library */
  tr->useMedian         = PLL_FALSE;

  tr->maxCategories     = (attr->rateHetModel == PLL_GAMMA) ? 4 : 25;

  tr->numberOfThreads   = attr->numberOfThreads;
  tr->rearrangeHistory  = NULL;

  /* Lock the slave processors at this point */
#ifdef _FINE_GRAIN_MPI
  pllLockMPI (tr);
#endif

  return (tr);
}

/** @brief Initialize PLL tree structure with default values
    
    Initialize PLL tree structure with default values and allocate 
    memory for its elements.

    @todo
      STILL NOT FINISHED
*/
static void pllTreeInitDefaults (pllInstance * tr, int tips)
{
  nodeptr p0, p, q;
  int i, j;
  int inner;

  

  /* TODO: make a proper static setupTree function */

  inner = tips - 1;

  tr->mxtips = tips;

  tr->bigCutoff = PLL_FALSE;
  tr->treeStringLength = tr->mxtips * (PLL_NMLNGTH + 128) + 256 + tr->mxtips * 2;
  tr->tree_string = (char *) rax_calloc ( tr->treeStringLength, sizeof(char));
  tr->tree0 = (char*)rax_calloc((size_t)tr->treeStringLength, sizeof(char));
  tr->tree1 = (char*)rax_calloc((size_t)tr->treeStringLength, sizeof(char));
  tr->constraintVector = (int *)rax_malloc((2 * tr->mxtips) * sizeof(int));
  
  p0 = (nodeptr) rax_malloc ((tips + 3 * inner) * sizeof (node));
  assert (p0);

  tr->nodeBaseAddress  = p0;

  tr->nameList         = (char **)   rax_malloc ((tips + 1) * sizeof (char *));
  tr->nodep            = (nodeptr *) rax_malloc ((2 * tips) * sizeof (nodeptr));

  tr->autoProteinSelectionType = PLL_AUTO_ML;

  assert (tr->nameList && tr->nodep);

  tr->nodep[0] = NULL;          


  /* TODO: The line below was commented... why? */
  tr->fracchange = -1;
  tr->rawFracchange = -1;

  for (i = 1; i <= tips; ++ i)
   {
     p = p0++;

     //p->hash      = KISS32();     
     p->x         = 0;
     p->xBips     = 0;
     p->number    = i;
     p->next      = p;
     p->back      = NULL;
     p->bInf      = NULL;
     tr->nodep[i]  = p;
   }

  for (i = tips + 1; i <= tips + inner; ++i)
   {
     q = NULL;
     for (j = 1; j <= 3; ++ j)
     {
       p = p0++;
       if (j == 1)
        {
          p->xBips = 1;
          p->x = 1; //p->x     = 1;
        }
       else
        {
          p->xBips = 0;
          p->x     = 0;
        }
       p->number = i;
       p->next   = q;
       p->bInf   = NULL;
       p->back   = NULL;
       p->hash   = 0;
       q         = p;
     }
    p->next->next->next = p;
    tr->nodep[i]         = p;
   }

  tr->likelihood  = PLL_UNLIKELY;
  tr->start       = NULL;
  tr->ntips       = 0;
  tr->nextnode    = 0;

  for (i = 0; i < PLL_NUM_BRANCHES; ++ i) tr->partitionSmoothed[i] = PLL_FALSE;

  tr->bitVectors = NULL;
  tr->vLength    = 0;
  //tr->h          = NULL;

  /* TODO: Fix hash type */
  tr->nameHash   = pllHashInit (10 * tr->mxtips);

  /* TODO: do these options really fit here or should they be put elsewhere? */
  tr->td[0].count            = 0;
  tr->td[0].ti               = (traversalInfo *) rax_malloc (sizeof(traversalInfo) * (size_t)tr->mxtips);
  tr->td[0].parameterValues  = (double *) rax_malloc(sizeof(double) * (size_t)PLL_NUM_BRANCHES);
  tr->td[0].executeModel     = (pllBoolean *) rax_malloc (sizeof(pllBoolean) * (size_t)PLL_NUM_BRANCHES);
  tr->td[0].executeModel[0]  = PLL_TRUE;                                                                                                                                                                                                                                    
  for (i = 0; i < PLL_NUM_BRANCHES; ++ i) tr->td[0].executeModel[i] = PLL_TRUE;
}


/* @brief Check a parsed tree for inclusion in the current tree
   
   Check whether the set of leaves (taxa) of the parsed tree \a nTree is a
   subset of the leaves of the currently loaded tree.

   @param pInst
     PLL instance

   @param nTree
     Parsed newick tree structure

   @return
     Returns \b PLL_TRUE in case it is a subset, otherwise \b PLL_FALSE
*/
static int
checkTreeInclusion (pllInstance * pInst, pllNewickTree * nTree)
{
  pllStack * sList;
  pllNewickNodeInfo * sItem;
  void * dummy;

  if (!pInst->nameHash) return (PLL_FALSE);

  for (sList = nTree->tree; sList; sList = sList->next)
   {
     sItem = (pllNewickNodeInfo *) sList->item;
     if (!sItem->rank)   /* leaf */
      {
        if (!pllHashSearch (pInst->nameHash, sItem->name, &dummy)) return (PLL_FALSE);
      }
   }

  return (PLL_TRUE);
}

static void
updateBranchLength (nodeptr p, double old_fracchange, double new_fracchange)
{
  double z;
  int j;

  for (j = 0; j < PLL_NUM_BRANCHES; ++ j)
   {
     z = exp ((log (p->z[j]) * old_fracchange) / new_fracchange);
     if (z < PLL_ZMIN) z = PLL_ZMIN;
     if (z > PLL_ZMAX) z = PLL_ZMAX;
     p->z[j] = p->back->z[j] = z;
   }
}

static void
updateAllBranchLengthsRecursive (nodeptr p, int tips, double old_fracchange, double new_fracchange)
{
  updateBranchLength (p, old_fracchange, new_fracchange);

  if (!isTip (p->number, tips))
   {
     updateAllBranchLengthsRecursive (p->next->back,       tips, old_fracchange, new_fracchange);
     updateAllBranchLengthsRecursive (p->next->next->back, tips, old_fracchange, new_fracchange);
   }
}

static void
updateAllBranchLengths (pllInstance * tr, double old_fracchange, double new_fracchange)
{
  nodeptr p;

  p = tr->start;
  assert (isTip(p->number, tr->mxtips));

  updateAllBranchLengthsRecursive (p->back, tr->mxtips, old_fracchange, new_fracchange);

}


/** @brief Relink the taxa
    
    Relink the taxa by performing a preorder traversal of the unrooted binary tree.
    We assume that the tree is rooted such that the root is the only node of
    out-degree 3 and in-degree 0, while all the other inner nodes have in-degree
    1 and out-degree 2. Finally, the leaves have in-degree 1 and out-degree 0.

    @param pInst
      PLL instance

    @param nTree
      Parsed newick tree structure

    @param taxaExist
      Is the set of taxa of \a nTree a subset of the taxa of the current tree

    @return
*/
static int
linkTaxa (pllInstance * pInst, pllNewickTree * nTree, int taxaExist)
{
  nodeptr 
    parent,
    child;
  pllStack 
    * nodeStack = NULL,
    * current;
  int
    i,
    j,
    inner = nTree->tips + 1,
    leaf  = 1;
  double z;
  pllNewickNodeInfo * nodeInfo;

  if (!taxaExist) pllTreeInitDefaults (pInst, nTree->tips);

  /* Place the ternary root node 3 times on the stack such that later on
     three nodes use it as their parent */
  current = nTree->tree;
  for (parent = pInst->nodep[inner], i  = 0; i < 3; ++ i, parent = parent->next)
    pllStackPush (&nodeStack, parent);
  ++ inner;

  /* now traverse the rest of the nodes */
  for (current = current->next; current; current = current->next)
   {
     parent   = (nodeptr) pllStackPop (&nodeStack);
     nodeInfo = (pllNewickNodeInfo *) current->item;

     /* if inner node place it twice on the stack (out-degree 2) */
     if (nodeInfo->rank)
      {
        child = pInst->nodep[inner ++];
        pllStackPush (&nodeStack, child->next);
        pllStackPush (&nodeStack, child->next->next);
      }
     else /* check if taxon already exists, i.e. we loaded another tree topology */
      {
        if (taxaExist)
         {
           assert (pllHashSearch (pInst->nameHash, nodeInfo->name, (void **) &child));
         }
        else
         {
           child = pInst->nodep[leaf];
           pInst->nameList[leaf] = strdup (nodeInfo->name);
           pllHashAdd (pInst->nameHash, pllHashString(pInst->nameList[leaf], pInst->nameHash->size), pInst->nameList[leaf], (void *) (pInst->nodep[leaf]));
           ++ leaf;
         }
      }
     assert (parent);
     /* link parent and child */
     parent->back = child;
     child->back  = parent;

     if (!taxaExist) pInst->fracchange = 1;

     /* set the branch length */
     z = exp ((-1 * atof (nodeInfo->branch)) / pInst->fracchange);
     if (z < PLL_ZMIN) z = PLL_ZMIN;
     if (z > PLL_ZMAX) z = PLL_ZMAX;
     for (j = 0; j < PLL_NUM_BRANCHES; ++ j)
       parent->z[j] = child->z[j] = z;
   }
  pllStackClear (&nodeStack);

  return PLL_TRUE;
}

/** @brief Get the instantaneous rate matrix
    
    Obtain the instantaneous rate matrix (Q) for partitionm \a model
    of the partition list \a pr, and store it in an array \a outBuffer.
    
    @param tr        PLL instance
    @param pr        List of partitions
    @param model     Index of partition to use
    @param outBuffer Where to store the instantaneous rate matrix 

    @todo Currently, the Q matrix can be only obtained for DNA GTR data.

    @return Returns \b PLL_TRUE in case of success, otherwise \b PLL_FALSE
*/
int pllGetInstRateMatrix (partitionList * pr, int model, double * outBuffer)
{
  if (pr->partitionData[model]->dataType != PLL_DNA_DATA) return (PLL_FALSE);

  int  i;
  double mean = 0;
  double * substRates = pr->partitionData[model]->substRates;
  double * freqs = pr->partitionData[model]->frequencies;
  
  /* normalize substitution rates */
  for (i = 0; i < 6; ++ i)  substRates[i] /= substRates[5];

  outBuffer[0 * 4 + 1] = (substRates[0] * freqs[1]);
  outBuffer[0 * 4 + 2] = (substRates[1] * freqs[2]);
  outBuffer[0 * 4 + 3] = (substRates[2] * freqs[3]);

  outBuffer[1 * 4 + 0] = (substRates[0] * freqs[0]);
  outBuffer[1 * 4 + 2] = (substRates[3] * freqs[2]);
  outBuffer[1 * 4 + 3] = (substRates[4] * freqs[3]);

  outBuffer[2 * 4 + 0] = (substRates[1] * freqs[0]);
  outBuffer[2 * 4 + 1] = (substRates[3] * freqs[1]);
  outBuffer[2 * 4 + 3] = (substRates[5] * freqs[3]);

  outBuffer[3 * 4 + 0] = (substRates[2] * freqs[0]);
  outBuffer[3 * 4 + 1] = (substRates[4] * freqs[1]);
  outBuffer[3 * 4 + 2] = (substRates[5] * freqs[2]);

  outBuffer[0 * 4 + 0] = -(substRates[0] * freqs[1] + substRates[1] * freqs[2] + substRates[2] * freqs[3]);
  outBuffer[1 * 4 + 1] = -(substRates[0] * freqs[0] + substRates[3] * freqs[2] + substRates[4] * freqs[3]);
  outBuffer[2 * 4 + 2] = -(substRates[1] * freqs[0] + substRates[3] * freqs[1] + substRates[5] * freqs[3]);
  outBuffer[3 * 4 + 3] = -(substRates[2] * freqs[0] + substRates[4] * freqs[1] + substRates[5] * freqs[2]);

  for (i = 0; i <  4; ++ i) mean         += freqs[i] * (-outBuffer[i * 4 + i]);
  for (i = 0; i < 16; ++ i) outBuffer[i] /= mean;

  return (PLL_TRUE);
}

/** @ingroup instanceLinkingGroup
    @brief Initializes the PLL tree topology according to a parsed newick tree

    Set the tree topology based on a parsed and validated newick tree

    @param tree
      The PLL instance

    @param nt
      The \a pllNewickTree wrapper structure that contains the parsed newick tree

    @param useDefaultz
      If set to \b PLL_TRUE then the branch lengths will be reset to the default
      value.
*/
void
pllTreeInitTopologyNewick (pllInstance * tr, pllNewickTree * newick, int useDefaultz)
{
  linkTaxa (tr, newick, tr->nameHash && checkTreeInclusion (tr, newick));

  tr->start = tr->nodep[1];

  if (useDefaultz == PLL_TRUE)
    resetBranches (tr);
}

/** @brief Get the node oriented pointer from a round-about node

    Returns the pointer of the round-about node $p$ that has the orientation, i.e.
    has the \a x flag set to 1. In case a tip is passed, then the returned pointer
    is the same as the input.

    @param pInst  PLL instance
    @param p      One of the three pointers of a round-about node

    @return  Returns the the pointer that has the orientation
*/
nodeptr pllGetOrientedNodePointer (pllInstance * pInst, nodeptr p)
{
  if (p->number <= pInst->mxtips || p->x) return p;

  if (p->next->x) return p->next;

  return p->next->next;
}


//void
//pllTreeInitTopologyNewick (pllInstance * tr, pllNewickTree * nt, int useDefaultz)
//{
//  pllStack * nodeStack = NULL;
//  pllStack * head;
//  pllNewickNodeInfo * item;
//  int i, j, k;
//  
///*
//  for (i = 0; i < partitions->numberOfPartitions; ++ i)
//   {
//     partitions->partitionData[i] = (pInfo *) rax_malloc (sizeof (pInfo));
//     partitions->partitionData[i]->partitionContribution = -1.0;
//     partitions->partitionData[i]->partitionLH           =  0.0;
//     partitions->partitionData[i]->fracchange            =  1.0;
//   }
//*/
// 
//
// if (tr->nameHash)
//  {
//    if (checkTreeInclusion (tr, nt))
//     {
//       printf ("It is a subset\n");
//     }
//    else
//     {
//       printf ("It is not a subset\n");
//     }
//  }
//  
//  pllTreeInitDefaults (tr, nt->tips);
//
//  i = nt->tips + 1;
//  j = 1;
//  nodeptr v;
//  
//  
//  for (head = nt->tree; head; head = head->next)
//  {
//    item = (pllNewickNodeInfo *) head->item;
//    if (!nodeStack)
//     {
//       pllStackPush (&nodeStack, tr->nodep[i]);
//       pllStackPush (&nodeStack, tr->nodep[i]->next);
//       pllStackPush (&nodeStack, tr->nodep[i]->next->next);
//       ++i;
//     }
//    else
//     {
//       v = (nodeptr) pllStackPop (&nodeStack);
//       if (item->rank)  /* internal node */
//        {
//          v->back           = tr->nodep[i];
//          tr->nodep[i]->back = v; //t->nodep[v->number]
//          pllStackPush (&nodeStack, tr->nodep[i]->next);
//          pllStackPush (&nodeStack, tr->nodep[i]->next->next);
//          double z = exp((-1 * atof(item->branch))/tr->fracchange);
//          if(z < PLL_ZMIN) z = PLL_ZMIN;
//          if(z > PLL_ZMAX) z = PLL_ZMAX;
//          for (k = 0; k < PLL_NUM_BRANCHES; ++ k)
//             v->z[k] = tr->nodep[i]->z[k] = z;
//
//          ++ i;
//        }
//       else             /* leaf */
//        {
//          v->back           = tr->nodep[j];
//          tr->nodep[j]->back = v; //t->nodep[v->number];
//
//          double z = exp((-1 * atof(item->branch))/tr->fracchange);
//          if(z < PLL_ZMIN) z = PLL_ZMIN;
//          if(z > PLL_ZMAX) z = PLL_ZMAX;
//          for (k = 0; k < PLL_NUM_BRANCHES; ++ k)
//            v->z[k] = tr->nodep[j]->z[k] = z;
//            
//          //t->nameList[j] = strdup (item->name);
//          tr->nameList[j] = (char *) rax_malloc ((strlen (item->name) + 1) * sizeof (char));
//          strcpy (tr->nameList[j], item->name);
//          
//          pllHashAdd (tr->nameHash, tr->nameList[j], (void *) (tr->nodep[j]));
//          ++ j;
//        }
//     }
//  }
//  
//  tr->start = tr->nodep[1];
//  
//  pllStackClear (&nodeStack);
//
//  if (useDefaultz == PLL_TRUE) 
//    resetBranches (tr);
//}

/** @brief Initialize PLL tree with a random topology

    Initializes the PLL tree with a randomly created topology

    @todo
      Perhaps pass a seed?

    @param tr
      The PLL instance

    @param tips
      Number of tips

    @param nameList
      A set of \a tips names representing the taxa labels
*/
void 
pllTreeInitTopologyRandom (pllInstance * tr, int tips, char ** nameList)
{
  int i;
  pllTreeInitDefaults (tr, tips);

  for (i = 1; i <= tips; ++ i)
   {
     tr->nameList[i] = (char *) rax_malloc ((strlen (nameList[i]) + 1) * sizeof (char));
     strcpy (tr->nameList[i], nameList[i]);
     pllHashAdd (tr->nameHash, pllHashString(tr->nameList[i], tr->nameHash->size), tr->nameList[i], (void *) (tr->nodep[i]));
   }
  

  pllMakeRandomTree (tr);
}


/** @brief Initialize a tree that corresponds to a given (already parsed) alignment 

    Initializes the PLL tree such that it corresponds to the given alignment

    @todo
      nothing 

    @param tr
      The PLL instance

    @param alignmentData
      Parsed alignment
*/
void 
pllTreeInitTopologyForAlignment (pllInstance * tr, pllAlignmentData * alignmentData)
{
  int
    tips = alignmentData->sequenceCount,
    i;

  char 
    **nameList = alignmentData->sequenceLabels;
  
  pllTreeInitDefaults (tr, tips);

  for (i = 1; i <= tips; ++ i)
   {
     tr->nameList[i] = (char *) rax_malloc ((strlen (nameList[i]) + 1) * sizeof (char));
     strcpy (tr->nameList[i], nameList[i]);
     pllHashAdd (tr->nameHash, pllHashString(tr->nameList[i], tr->nameHash->size), tr->nameList[i], (void *) (tr->nodep[i]));
   }
}


/** @brief Compute a randomized stepwise addition oder parsimony tree

    Implements the RAxML randomized stepwise addition order algorithm 

    @todo
      check functions that are invoked for potential memory leaks!

    @param tr
      The PLL instance

    @param partitions
      The partitions

    @param sprDist
      SPR distance for the SPR search in parsimony
*/
void pllComputeRandomizedStepwiseAdditionParsimonyTree(pllInstance * tr, partitionList * partitions, int sprDist)
{
  allocateParsimonyDataStructures(tr, partitions);
  pllMakeParsimonyTreeFast(tr, partitions, sprDist);
  pllFreeParsimonyDataStructures(tr, partitions);
}

/** @brief Encode the alignment data to the PLL numerical representation
    
    Transforms the alignment to the PLL internal representation by substituting each base 
    with a specific digit.

    @param alignmentData  Multiple sequence alignment
    @param partitions     List of partitions
*/
void pllBaseSubstitute (pllInstance * tr, partitionList * partitions)
{
  const char * d;
  int i, j, k;

  for (i = 0; i < partitions->numberOfPartitions; ++ i)
   {
     switch (partitions->partitionData[i]->dataType)
      {
        case PLL_DNA_DATA:
          d = PLL_MAP_NT;
          break;
        case PLL_BINARY_DATA:
          d = PLL_MAP_BIN;
          break;
        case PLL_AA_DATA:
          d = PLL_MAP_AA;
          break;
        default:
          assert(0);
      }
     
     for (j = 1; j <= tr->mxtips; ++ j)
      {
        for (k = partitions->partitionData[i]->lower; k < partitions->partitionData[i]->upper; ++ k)
         {
           tr->yVector[j][k] = d[tr->yVector[j][k]];
         }
      }
   }
}

/** Clears the rearrangements history from PLL instance
    
    Clears the rearrangements rollback information (history) from the PLL instance \a tr.

    @param tr
      PLL instance
*/
void pllClearRearrangeHistory (pllInstance * tr)
{
  pllRollbackInfo * ri;

  while ((ri = (pllRollbackInfo *)pllStackPop (&(tr->rearrangeHistory))))
   {
     rax_free (ri);
   }
}

/** @brief Deallocate the PLL instance

    Deallocates the library instance and all its elements.

    @param tr
      The PLL instance
*/
void
pllDestroyInstance (pllInstance * tr)
{
  int i;

  for (i = 1; i <= tr->mxtips; ++ i)
    rax_free (tr->nameList[i]);
  
  pllHashDestroy (&(tr->nameHash), NULL);
  if (tr->yVector)
   {
     if (tr->yVector[0]) rax_free (tr->yVector[0]);
     rax_free (tr->yVector);
   }
  rax_free (tr->aliaswgt);
  rax_free (tr->rateCategory);
  rax_free (tr->patrat);
  rax_free (tr->patratStored);
  rax_free (tr->lhs);
  rax_free (tr->td[0].parameterValues);
  rax_free (tr->td[0].executeModel);
  rax_free (tr->td[0].ti);
  rax_free (tr->nameList);
  rax_free (tr->nodep);
  rax_free (tr->nodeBaseAddress);
  rax_free (tr->tree_string);
  rax_free (tr->tree0);
  rax_free (tr->tree1);
  rax_free (tr->tipNames);
  rax_free (tr->constraintVector);
  pllClearRearrangeHistory (tr);

  rax_free (tr);

#ifdef _FINE_GRAIN_MPI
  pllFinalizeMPI ();
#endif

}

/* initializwe a parameter linkage list for a certain parameter type (can be whatever).
   the input is an integer vector that contaions NumberOfModels (numberOfPartitions) elements.

   if we want to have all alpha parameters unlinked and have say 4 partitions the input 
   vector would look like this: {0, 1, 2, 3}, if we want to link partitions 0 and 3 the vector 
   should look like this: {0, 1, 2, 0} 
*/



static int init_Q_MatrixSymmetries(char *linkageString, partitionList * pr, int model)
{
  int 
    states = pr->partitionData[model]->states,
    numberOfRates = ((states * states - states) / 2), 
    *list = (int *)rax_malloc(sizeof(int) * numberOfRates),
    j,
    max = -1;

  char
    *str1,
    *saveptr,
    *ch,
    *token;

  ch = (char *) rax_malloc (strlen (linkageString) + 1);
  strcpy (ch, linkageString);


  for(j = 0, str1 = ch; ;j++, str1 = (char *)NULL) 
    {
      token = STRTOK_R(str1, ",", &saveptr);
      if(token == (char *)NULL)
        break;
      if(!(j < numberOfRates))
        {
          errno = PLL_SUBSTITUTION_RATE_OUT_OF_BOUNDS;
          return PLL_FALSE;
        }
      list[j] = atoi(token);     
    }
  
  rax_free(ch);

  for(j = 0; j < numberOfRates; j++)
    {
      if(!(list[j] <= j))
        {
          errno = PLL_INVALID_Q_MATRIX_SYMMETRY;
          return PLL_FALSE;
        }
      
      if(!(list[j] <= max + 1))
        {
          errno = PLL_Q_MATRIX_SYMMETRY_OUT_OF_BOUNDS;
          return PLL_FALSE;
        }
      
      if(list[j] > max)
        max = list[j];
    }  
  
  for(j = 0; j < numberOfRates; j++)  
    pr->partitionData[model]->symmetryVector[j] = list[j];    

  //less than the maximum possible number of rate parameters

  if(max < numberOfRates - 1)    
    pr->partitionData[model]->nonGTR = PLL_TRUE;

  pr->partitionData[model]->optimizeSubstitutionRates = PLL_TRUE;

  rax_free(list);

  return PLL_TRUE;
}

/** @brief Check parameter linkage across partitions for consistency
 *
 * Checks that linked alpha, substitution rate and frequency model parameters 
 * across several partitions are consistent. E.g., when two partitions are linked 
 * via the alpha parameter, the alpha parameter should either be set to the same 
 * fixed value or it should be estimated!
 *
 * @param pr
 *   List of partitions
 *
 * @todo
 *   Call this in more functions, right now it's only invoked in the wrapper 
 *   for modOpt() 
 */
static int checkLinkageConsistency(partitionList *pr)
{
  if(pr->dirty)
    {
      int 
        i;
      
      linkageList 
        *ll;

      /* first deal with rates */

      ll = pr->rateList;
        
      for(i = 0; i < ll->entries; i++)
        {
          int
            partitions = ll->ld[i].partitions,
            reference = ll->ld[i].partitionList[0];
          
          if(pr->partitionData[reference]->dataType == PLL_AA_DATA)
            {
              if(pr->partitionData[reference]->protModels == PLL_GTR || pr->partitionData[reference]->nonGTR)                             
                {
                  if(!(pr->partitionData[reference]->optimizeSubstitutionRates == PLL_TRUE))
                    {
                      errno = PLL_INCONSISTENT_SUBST_RATE_OPTIMIZATION_SETTING;
                      return PLL_FALSE;
                    }
                }
              else              
                {
                  if(!(pr->partitionData[reference]->optimizeSubstitutionRates == PLL_FALSE))
                    {
                      errno = PLL_INCONSISTENT_SUBST_RATE_OPTIMIZATION_SETTING;
                      return PLL_FALSE;
                    }
                }                 
            }

          if(partitions > 1)
            {
              int
                j,
                k;
              
              for(k = 1; k < partitions; k++)
                {
                  int 
                    index = ll->ld[i].partitionList[k];
                  
                  int
                    states = pr->partitionData[index]->states,
                    rates = ((states * states - states) / 2);
                  
                  if(!(pr->partitionData[reference]->nonGTR == pr->partitionData[index]->nonGTR))
                    {
                      errno = PLL_INCONSISTENT_SUBST_RATE_OPTIMIZATION_SETTING;
                      return PLL_FALSE;
                    }
                  if(!(pr->partitionData[reference]->optimizeSubstitutionRates == pr->partitionData[index]->optimizeSubstitutionRates))
                    {
                      errno = PLL_INCONSISTENT_SUBST_RATE_OPTIMIZATION_SETTING;
                      return PLL_FALSE;
                    }
                
                  
                  if(pr->partitionData[reference]->nonGTR)
                    {              
                      
                      for(j = 0; j < rates; j++)                        
                        {
                          if(!(pr->partitionData[reference]->symmetryVector[j] == pr->partitionData[index]->symmetryVector[j]))
                            {
                              errno = PLL_INCONSISTENT_Q_MATRIX_SYMMETRIES_ACROSS_LINKED_PARTITIONS;
                              return PLL_FALSE;
                            }
                        }
                    }
                  
                 
                  for(j = 0; j < rates; j++)
                    {
                      if(!(pr->partitionData[reference]->substRates[j] == pr->partitionData[index]->substRates[j]))
                        {
                          errno = PLL_INCONSISTENT_Q_MATRIX_ENTRIES_ACROSS_LINKED_PARTITIONS;
                          return PLL_FALSE;
                        }
                    }
                }           
            }
        }
      
      /* then deal with alpha parameters */

      ll = pr->alphaList;

      for(i = 0; i < ll->entries; i++)
        {
          int
            partitions = ll->ld[i].partitions;
          
          if(partitions > 1)
            {
              int
                k, 
                reference = ll->ld[i].partitionList[0];
              
              for(k = 1; k < partitions; k++)
                {
                  int 
                    index = ll->ld[i].partitionList[k];                          

                  if(!(pr->partitionData[reference]->optimizeAlphaParameter == pr->partitionData[index]->optimizeAlphaParameter))
                    {
                      errno = PLL_INCONSISTENT_ALPHA_STATES_ACROSS_LINKED_PARTITIONS;
                      return PLL_FALSE;
                    }
                  if(!(pr->partitionData[reference]->alpha == pr->partitionData[index]->alpha))
                    {
                      errno = PLL_INCONSISTENT_ALPHA_VALUES_ACROSS_LINKED_PARTITIONS;
                      return PLL_FALSE;
                    }
                }           
            }
        }

      /* and then deal with base frequencies */

      ll = pr->freqList;

      for(i = 0; i < ll->entries; i++)
        {
          int     
            partitions = ll->ld[i].partitions;
          
          if(partitions > 1)
            {
              int               
                k, 
                reference = ll->ld[i].partitionList[0];
              
              for(k = 1; k < partitions; k++)
                {
                  int
                    j,
                    index = ll->ld[i].partitionList[k],
                    states = pr->partitionData[index]->states;                           

                  if(!(pr->partitionData[reference]->optimizeBaseFrequencies == pr->partitionData[index]->optimizeBaseFrequencies))
                    {
                      errno = PLL_INCONSISTENT_FREQUENCY_STATES_ACROSS_LINKED_PARTITIONS;
                      return PLL_FALSE;
                    }

                  for(j = 0; j < states; j++)
                    {
                      if(!(pr->partitionData[reference]->frequencies[j] == pr->partitionData[index]->frequencies[j]))
                        {
                          errno = PLL_INCONSISTENT_FREQUENCY_VALUES_ACROSS_LINKED_PARTITIONS;
                          return PLL_FALSE;
                        }
                    }
                }           
            }
        }
      
      pr->dirty = PLL_FALSE;
    }

  return PLL_TRUE;
}
/** @brief Set symmetries among parameters in the Q matrix
    
    Allows to link some or all rate parameters in the Q-matrix 
    for obtaining simpler models than GTR

    @param string
      string describing the symmetry pattern among the rates in the Q matrix

    @param pr
      List of partitions
      
    @param model
      Index of the partition for which we want to set the Q matrix symmetries

    @todo
      nothing
*/
int pllSetSubstitutionRateMatrixSymmetries(char *string, partitionList * pr, int model)
{
  int 
    result = init_Q_MatrixSymmetries(string, pr, model);

  pr->dirty = PLL_TRUE;

  return result;
}

/** @defgroup modelParamsGroup Model parameters setup and retrieval
    
    This set of functions is responsible for setting, retrieving, and optimizing
    model parameters. It also contains functions for linking model parameters
    across partitions.
*/

/** @ingroup modelParamsGroups
    @brief Set the alpha parameter of the Gamma model to a fixed value for a partition
    
    Sets the alpha parameter of the gamma model of rate heterogeneity to a fixed value
    and disables the optimization of this parameter 

    @param alpha
      alpha value

    @param model
      Index of the partition for which we want to set the alpha value

    @param pr
      List of partitions
      
    @param tr
      Library instance for which we want to fix alpha 

    @todo
      test if this works with the parallel versions
*/
void pllSetFixedAlpha(double alpha, int model, partitionList * pr, pllInstance *tr)
{
  //make sure that we are swetting alpha for a partition within the current range 
  //of partitions
  double old_fracchange = tr->fracchange;

  assert(model >= 0 && model < pr->numberOfPartitions);

  assert(alpha >= PLL_ALPHA_MIN && alpha <= PLL_ALPHA_MAX);

  //set the alpha paremeter 
  
  pr->partitionData[model]->alpha = alpha;

  //do the discretization of the gamma curve

  pllMakeGammaCats(pr->partitionData[model]->alpha, pr->partitionData[model]->gammaRates, 4, tr->useMedian);

  //broadcast the changed parameters to all threads/MPI processes 

#if (defined(_FINE_GRAIN_MPI) || defined(_USE_PTHREADS))
  pllMasterBarrier(tr, pr, PLL_THREAD_COPY_ALPHA);
#endif

  pr->partitionData[model]->optimizeAlphaParameter = PLL_FALSE;

  pr->dirty = PLL_FALSE;
  updateAllBranchLengths (tr, old_fracchange, tr->fracchange);
}

/** @ingroup modelParamsGroups
    @brief Get the rate categories of the Gamma model of a partition

    Gets the gamma rate categories of the Gamma model of rate heterogeneity
    of partition \a pid from partition list \a pr.

    @param pr   List of partitions
    @param pid  Index of partition to use
    @param outBuffer  Output buffer where to store the rates
*/
void pllGetGammaRates (partitionList * pr, int pid, double * outBuffer)
{
  /* TODO: Change the hardcoded 4 and also add a check that this partition
     really uses gamma. Currently, instance is also not required */
  memcpy (outBuffer, pr->partitionData[pid]->gammaRates, 4 * sizeof (double));
}

/** @ingroup modelParamsGroups
    @brief Get the alpha parameter of the Gamma model of a partition

    Returns the alpha parameter of the gamma model of rate heterogeneity
    of partition \a pid from partition list \a pr.

    @param pr   List of partitions
    @param pid  Index of partition to use

    @return
      Alpha parameter
*/
double pllGetAlpha (partitionList * pr, int pid)
{
  /* TODO: check if the partition uses gamma */
  return (pr->partitionData[pid]->alpha);
}


/** @ingroup modelParamsGroups
    @brief Get the base frequencies of a partition

    Gets the base frequencies of partition \a model from partition list
    \a partitionList and stores them in \a outBuffer. Note that \outBuffer
    must be of size s, where s is the number of states.

    @param  tr       PLL instance
    @param pr        List of partitions
    @param model     Index of the partition for which we want to get the base frequencies
    @param outBuffer Buffer where to store the base frequencies
*/
void pllGetBaseFrequencies(partitionList * pr, int model, double * outBuffer)
{
  memcpy (outBuffer, pr->partitionData[model]->frequencies, pr->partitionData[model]->states * sizeof (double));
}


/** @ingroup modelParamsGroups
    @brief Set all base frequencies to a fixed value for a partition
    
    Sets all base freuqencies of a partition to fixed values and disables 
    ML optimization of these parameters 

    @param f
      array containing the base frequencies

    @param  length
      length of array f, this needs to be as long as the number of 
      states in the model, otherwise an assertion will fail!

    @param model
      Index of the partition for which we want to set the frequencies 

    @param pr
      List of partitions
      
    @param tr
      Library instance for which we want to fix the base frequencies

    @todo
      test if this works with the parallel versions
*/
void pllSetFixedBaseFrequencies(double *f, int length, int model, partitionList * pr, pllInstance *tr)
{
  int 
    i;

  double 
    acc = 0.0,
    old_fracchange;

  old_fracchange = tr->fracchange;

  //make sure that we are setting the base frequencies for a partition within the current range 
  //of partitions
  assert(model >= 0 && model < pr->numberOfPartitions);

  //make sure that the length of the input array f containing the frequencies 
  //is as long as the number of states in the model 
  assert(length == pr->partitionData[model]->states);


  //make sure that the base frequencies sum approximately to 1.0
  
  for(i = 0; i < length; i++)
    acc += f[i];

  if(fabs(acc - 1.0) > 0.000001)
    assert(0);

  //copy the base frequencies 
  memcpy(pr->partitionData[model]->frequencies, f, sizeof(double) * length);

  //re-calculate the Q matrix 
  pllInitReversibleGTR(tr, pr, model);


  //broadcast the new Q matrix to all threads/processes 
#if (defined(_FINE_GRAIN_MPI) || defined(_USE_PTHREADS))
  pllMasterBarrier (tr, pr, PLL_THREAD_COPY_RATES);
#endif
  
  pr->partitionData[model]->optimizeBaseFrequencies = PLL_FALSE;

  pr->dirty = PLL_TRUE;
  updateAllBranchLengths (tr, old_fracchange, tr->fracchange);
}

/** @ingroup modelParamsGroups
    @brief Set that the base freuqencies are optimized under ML
    
    The base freuqencies for partition model will be optimized under ML    

    @param model
      Index of the partition for which we want to optimize base frequencies 

    @param pr
      List of partitions
      
    @param tr
      Library instance for which we want to fix the base frequencies

    @todo
      test if this works with the parallel versions
*/
int pllSetOptimizeBaseFrequencies(int model, partitionList * pr, pllInstance *tr)
{
  int
    states,
    i;

  double 
    initialFrequency,
    acc = 0.0;

  //make sure that we are setting the base frequencies for a partition within the current range 
  //of partitions
  if(!(model >= 0 && model < pr->numberOfPartitions))
    {
      errno = PLL_PARTITION_OUT_OF_BOUNDS;
      return PLL_FALSE;
    }

  //set the number of states/ferquencies in this partition 
  states = pr->partitionData[model]->states;

  //set all frequencies to 1/states
  
  initialFrequency = 1.0 / (double)states;

  for(i = 0; i < states; i++)
    pr->partitionData[model]->frequencies[i] = initialFrequency;

  //make sure that the base frequencies sum approximately to 1.0
  
  for(i = 0; i < states; i++)
    acc += pr->partitionData[model]->frequencies[i];

  if(fabs(acc - 1.0) > 0.000001)
    {
      errno = PLL_BASE_FREQUENCIES_DO_NOT_SUM_TO_1;
      return PLL_FALSE;
    }

  //re-calculate the Q matrix 
  pllInitReversibleGTR(tr, pr, model);

  //broadcast the new Q matrix to all threads/processes 
#if (defined(_FINE_GRAIN_MPI) || defined(_USE_PTHREADS))
  pllMasterBarrier (tr, pr, PLL_THREAD_COPY_RATES);
#endif
  
  pr->partitionData[model]->optimizeBaseFrequencies = PLL_TRUE;

  pr->dirty = PLL_TRUE;

  return PLL_TRUE;
}




/** @ingroup modelParamsGroups
    @brief Get the substitution rates for a specific partition

    Gets the substitution rates of partition \a model from partition list
    \a partitionList and stores them in \a outBuffer. Note that \outBuffer
    must be of size (2 * s - s) / 2, where s is the number of states, i.e.
    the number of upper diagonal entries of the Q matrix.

    @param tr        PLL instance
    @param pr        List of partitions
    @param model     Index of partition for which we want to get the substitution rates
    @param outBuffer Buffer where to store the substitution rates.
*/
void pllGetSubstitutionMatrix (partitionList * pr, int model, double * outBuffer)
{
  int 
    rates,
    states;
  
  states = pr->partitionData[model]->states;
  rates = (states * states - states) / 2;

  memcpy (outBuffer, pr->partitionData[model]->substRates, rates * sizeof (double));
}

/** @ingroup modelParamsGroups
     @brief Set all substitution rates for a specific partition and disable ML optimization for them
    
    Sets all substitution rates of a partition to fixed values and disables 
    ML optimization of these parameters. It will automatically re-scale the relative rates  
    such that the last rate is 1.0 

    @param f
      array containing the substitution rates

    @param length
      length of array f, this needs to be as long as: (s * s - s) / 2,
      i.e., the number of upper diagonal entries of the Q matrix

    @param model
      Index of the partition for which we want to set/fix the substitution rates

    @param pr
      List of partitions
      
    @param tr
      Library instance for which we want to fix the substitution rates 

    @todo
      test if this works with the parallel versions
*/
void pllSetFixedSubstitutionMatrix(double *q, int length, int model, partitionList * pr,  pllInstance *tr)
{
  pllSetSubstitutionMatrix(q, length, model, pr, tr);
  pr->partitionData[model]->optimizeSubstitutionRates = PLL_FALSE;
}

/** @ingroup modelParamsGroups
     @brief Set all substitution rates for a specific partition
    
    Sets all substitution rates of a partition to the given values.
    It will automatically re-scale the relative rates such that the last rate is 1.0 

    @param f
      array containing the substitution rates

    @param length
      length of array f, this needs to be as long as: (s * s - s) / 2,
      i.e., the number of upper diagonal entries of the Q matrix

    @param model
      Index of the partition for which we want to set/fix the substitution rates

    @param pr
      List of partitions
      
    @param tr
      Library instance for which we want to fix the substitution rates 

    @todo
      test if this works with the parallel versions
*/
void pllSetSubstitutionMatrix(double *q, int length, int model, partitionList * pr,  pllInstance *tr)
{
  int 
    i,
    numberOfRates; 

  double
    scaler,
    old_fracchange;

  old_fracchange = tr->fracchange;

  //make sure that we are setting the Q matrix for a partition within the current range 
  //of partitions
  assert(model >= 0 && model < pr->numberOfPartitions);

  numberOfRates = (pr->partitionData[model]->states * pr->partitionData[model]->states - pr->partitionData[model]->states) / 2;

  //  make sure that the length of the array containing the subsitution rates 
  //  corresponds to the number of states in the model

  assert(length == numberOfRates);

  //automatically scale the last rate to 1.0 if this is not already the case

  if(q[length - 1] != 1.0)    
    scaler = 1.0 / q[length - 1]; 
  else
    scaler = 1.0;

  //set the rates for the partition and make sure that they are within the allowed bounds 

  for(i = 0; i < length; i++)
    {
      double
        r = q[i] * scaler;
      
      assert(r >= PLL_RATE_MIN && r <= PLL_RATE_MAX);
      
      pr->partitionData[model]->substRates[i] = r;
    }

  //re-calculate the Q matrix 
  pllInitReversibleGTR(tr, pr, model);

  //broadcast the new Q matrix to all threads/processes 
#if (defined(_FINE_GRAIN_MPI) || defined(_USE_PTHREADS))
  pllMasterBarrier (tr, pr, PLL_THREAD_COPY_RATES);
#endif
  

  pr->dirty = PLL_TRUE;
  updateAllBranchLengths (tr, old_fracchange, tr->fracchange);
}




/* initialize a parameter linkage list for a certain parameter type (can be whatever).
   the input is an integer vector that contaions NumberOfModels (numberOfPartitions) elements.

   if we want to have all alpha parameters unlinked and have say 4 partitions the input 
   vector would look like this: {0, 1, 2, 3}, if we want to link partitions 0 and 3 the vector 
   should look like this: {0, 1, 2, 0} 
*/

/** @ingroup modelParamsGroups
*/
linkageList* initLinkageList(int *linkList, partitionList *pr)
{
  int 
    k,
    partitions,
    numberOfModels = 0,
    i,
    pos;
  
  linkageList 
    *ll = (linkageList*)rax_malloc(sizeof(linkageList));
    
  /* figure out how many distinct parameters we need to estimate 
     in total, if all parameters are linked the result will be 1 if all 
     are unlinked the result will be pr->numberOfPartitions */
  
  for(i = 0; i < pr->numberOfPartitions; i++)
    {
      if(!(linkList[i] >= 0 && linkList[i] < pr->numberOfPartitions))
        {
          errno = PLL_LINKAGE_LIST_OUT_OF_BOUNDS;
          return (linkageList*)NULL;
        }

      if(!(linkList[i] <= i && linkList[i] <= numberOfModels + 1))
        {
          errno = PLL_LINKAGE_LIST_OUT_OF_BOUNDS;
          return (linkageList*)NULL;
        }

      if(linkList[i] > numberOfModels)
        numberOfModels = linkList[i];

    }

  numberOfModels++;
  
  /* allocate the linkage list data structure that containes information which parameters of which partition are 
     linked with each other.

     Note that we need a separate invocation of initLinkageList() and a separate linkage list 
     for each parameter type */

  ll->entries = numberOfModels;
  ll->ld      = (linkageData*)rax_malloc(sizeof(linkageData) * numberOfModels);

  /* noe loop over the number of free parameters and assign the corresponding partitions to each parameter */

  for(i = 0; i < numberOfModels; i++)
    {
      /* 
         the valid flag is used for distinguishing between DNA and protein data partitions.
         This can be used to enable/disable parameter optimization for the paremeter 
         associated to the corresponding partitions. This deature is used in optRatesGeneric 
         to first optimize all DNA GTR rate matrices and then all PROT GTR rate matrices */

      ll->ld[i].valid = PLL_TRUE;
      partitions = 0;

      /* now figure out how many partitions share this joint parameter */

      for(k = 0; k < pr->numberOfPartitions; k++)
        if(linkList[k] == i)
          partitions++;     

      /* assign a list to store the partitions that share the parameter */

      ll->ld[i].partitions = partitions;
      ll->ld[i].partitionList = (int*)rax_malloc(sizeof(int) * partitions);
      
      /* now store the respective partition indices in this list */
      
      for(k = 0, pos = 0; k < pr->numberOfPartitions; k++)
        if(linkList[k] == i)
          ll->ld[i].partitionList[pos++] = k;
    }

  /* return the linkage list for the parameter */

  return ll;
}



static linkageList* initLinkageListString(char *linkageString, partitionList * pr)
{
  int 
    *list = (int*)rax_malloc(sizeof(int) * pr->numberOfPartitions),
    j;

  linkageList 
    *l;

  char
    *str1,
    *saveptr,
//    *ch = strdup(linkageString),
    *ch,
    *token;
  
  ch = (char *) rax_malloc (strlen (linkageString) + 1);
  strcpy (ch, linkageString);

  for(j = 0, str1 = ch; ;j++, str1 = (char *)NULL) 
    {
      token = STRTOK_R(str1, ",", &saveptr);
      if(token == (char *)NULL)
        break;
      assert(j < pr->numberOfPartitions);
      list[j] = atoi(token);
    }
  
  rax_free(ch);

  l = initLinkageList(list, pr);
  
  rax_free(list);

  return l;
}

/** @ingroup modelParamsGroups
    @brief Link alpha parameters across partitions
    
    Links alpha paremeters across partitions (GAMMA model of rate heterogeneity)

    @param string
      string describing the linkage pattern    

    @param pr
      List of partitions

    @todo
      test behavior/impact/mem-leaks of this when PSR model is used 
      it shouldn't do any harm, but it would be better to check!
*/
int pllLinkAlphaParameters(char *string, partitionList *pr)
{
  //assumes that it has already been assigned once
  freeLinkageList(pr->alphaList);
  
  pr->alphaList = initLinkageListString(string, pr); 

  pr->dirty = PLL_TRUE;
  
  if(!pr->alphaList)
    return PLL_FALSE;
  else
    return PLL_TRUE;
}

/** @ingroup modelParamsGroups
    @brief Link base frequency parameters across partitions
    
    Links base frequency paremeters across partitions

    @param string
      string describing the linkage pattern    

    @param pr
      List of partitions

    @todo
      semantics of this function not clear yet: right now this only has an effect 
      when we do a ML estimate of base frequencies 
      when we use empirical or model-defined (protein data) base frequencies, one could 
      maybe average over the per-partition frequencies, but the averages would need to be weighted 
      accodring on the number of patterns per partition 
*/
int pllLinkFrequencies(char *string, partitionList *pr)
{
  //assumes that it has already been assigned once
  freeLinkageList(pr->freqList);

  pr->freqList = initLinkageListString(string, pr);

  pr->dirty = PLL_TRUE;

  if(!pr->freqList)
    return PLL_FALSE;
  else
    return PLL_TRUE;
}

/** @ingroup modelParamsGroups
    @brief Link Substitution matrices across partitions
    
    Links substitution matrices (Q matrices) across partitions

    @param string
      string describing the linkage pattern    

    @param pr
      List of partitions

    @todo
      re-think/re-design how this is done for protein
      models
*/
int pllLinkRates(char *string, partitionList *pr)
{
  //assumes that it has already been assigned once
  freeLinkageList(pr->rateList);
  
  pr->rateList = initLinkageListString(string, pr);
  
  pr->dirty = PLL_TRUE;  

  if(!pr->dirty)
    return PLL_FALSE;
  else
    return PLL_TRUE;
}




/** @ingroup modelParamsGroups
    @brief Initialize partitions according to model parameters
    
    Initializes partitions according to model parameters.

    @param tr              The PLL instance
    @param partitions      List of partitions
    @param alignmentData   The parsed alignment
    @return                Returns \b PLL_TRUE in case of success, otherwise \b PLL_FALSE
*/
int pllInitModel (pllInstance * tr, partitionList * partitions) 
{
  double ** ef;
  int
    i,
    *unlinked = (int *)rax_malloc(sizeof(int) * partitions->numberOfPartitions);
  double old_fracchange = tr->fracchange;

  ef = pllBaseFrequenciesInstance (tr, partitions);

  if(!ef)
    return PLL_FALSE;

  
#if ! (defined(__ppc) || defined(__powerpc__) || defined(PPC))
#if (defined(__AVX) || defined(__SSE3))
  _mm_setcsr( _mm_getcsr() | _MM_FLUSH_ZERO_ON);
#endif
#endif 

#ifdef _USE_PTHREADS
  tr->threadID = 0;
#ifndef _PORTABLE_PTHREADS
  /* not very portable thread to core pinning if PORTABLE_PTHREADS is not defined
     by defualt the cod ebelow is deactivated */
  pinToCore(0);
#endif
#endif

#if (defined(_FINE_GRAIN_MPI) || defined(_USE_PTHREADS))
  /* 
     this main function is the master thread, so if we want to run RAxML with n threads,
     we use pllStartPthreads to start the n-1 worker threads */
  
#ifdef _USE_PTHREADS
  pllStartPthreads (tr, partitions);
#endif

  /* via pllMasterBarrier() we invoke parallel regions in which all Pthreads work on computing something, mostly likelihood 
     computations. Have a look at execFunction() in axml.c where we siwtch of the different types of parallel regions.

     Although not necessary, below we copy the info stored on tr->partitionData to corresponding copies in each thread.
     While this is shared memory and we don't really need to copy stuff, it was implemented like this to allow for an easier 
     transition to a distributed memory implementation (MPI).
     */
#ifdef _FINE_GRAIN_MPI
  //MPI_Bcast (&(partitions->numberOfPartitions), 1, MPI_INT, MPI_ROOT, MPI_COMM_WORLD);
  MPI_Bcast (&(partitions->numberOfPartitions), 1, MPI_INT, 0, MPI_COMM_WORLD);
#endif
  
  /* mpi version now also uses the generic barrier */
  pllMasterBarrier (tr, partitions, PLL_THREAD_INIT_PARTITION);
#else  /* SEQUENTIAL */
  /* 
     allocate the required data structures for storing likelihood vectors etc 
     */

  //initializePartitions(tr, tr, partitions, partitions, 0, 0);
  initializePartitionsSequential (tr, partitions);
#endif
  
  //initializePartitions (tr, tr, partitions, partitions, 0, 0);
  
  initModel (tr, ef, partitions);

  pllEmpiricalFrequenciesDestroy (&ef, partitions->numberOfPartitions);

  for(i = 0; i < partitions->numberOfPartitions; i++)
    unlinked[i] = i;

  //by default everything is unlinked initially 
  partitions->alphaList = initLinkageList(unlinked, partitions);
  partitions->freqList  = initLinkageList(unlinked, partitions);
  partitions->rateList  = initLinkageList(unlinked, partitions);

  rax_free(unlinked);

  updateAllBranchLengths (tr, old_fracchange ? old_fracchange : 1,  tr->fracchange);
  pllEvaluateLikelihood (tr, partitions, tr->start, PLL_TRUE, PLL_FALSE);

  return PLL_TRUE;
}
 
/** @ingroup modelParamsGroups
    @brief Optimize all free model parameters of the likelihood model
    
    Initializes partitions according to model parameters.

    @param tr
      The PLL instance

    @param pr
      List of partitions

    @param likelihoodEpsilon
      Specifies up to which epsilon in likelihood values the iterative routine will 
      be optimizing the parameters  
*/
int pllOptimizeModelParameters(pllInstance *tr, partitionList *pr, double likelihoodEpsilon)
{
  //force the consistency check

  pr->dirty = PLL_TRUE;

  if(!checkLinkageConsistency(pr))
    return PLL_FALSE;

  modOpt(tr, pr, likelihoodEpsilon);

  return PLL_TRUE;
}

/** @brief Read the contents of a file
    
    Reads the ile \a filename and return its content. In addition
    the size of the file is stored in the input variable \a filesize.
    The content of the variable \a filesize can be anything and will
    be overwritten.

    @param filename
      Name of the input file

    @param filesize
      Input parameter where the size of the file (in bytes) will be stored

    @return
      Contents of the file
*/
char * 
pllReadFile (const char * filename, long * filesize)
{
  FILE * fp;
  char * rawdata;

  // FIX BUG: opening with "r" does not work on Windows
//  fp = fopen (filename, "r");
  printf("[PLL] Reading file %s...\n", filename);
  fp = fopen (filename, "rb");
  printf("[PLL] Success!\n");
  if (!fp) return (NULL);

  /* obtain file size */
  if (fseek (fp, 0, SEEK_END) == -1)
   {
     fclose (fp);
     return (NULL);
   }

  *filesize = ftell (fp);

  if (*filesize == -1) 
   {
     fclose (fp);
     return (NULL);
   }
  rewind (fp);

  /* allocate buffer and read file contents */
  rawdata = (char *) rax_malloc (((*filesize) + 1) * sizeof (char));
  if (rawdata) 
   {
     if (fread (rawdata, sizeof (char), *filesize, fp) != (size_t) *filesize) 
      {
        rax_free (rawdata);
        rawdata = NULL;
      }
     else
      {
        rawdata[*filesize] = 0;
      }
   }

  fclose (fp);

  return (rawdata);
}

static void getInnerBranchEndPointsRecursive (nodeptr p, int tips, int * i, node **nodes)
{
  if (!isTip (p->next->back->number, tips))
   {
     nodes[(*i)++] = p->next;
     getInnerBranchEndPointsRecursive(p->next->back, tips, i, nodes);
   }
  if (!isTip (p->next->next->back->number, tips))
   {
     nodes[(*i)++] = p->next->next;
     getInnerBranchEndPointsRecursive(p->next->next->back, tips, i, nodes);
   }
}

node ** pllGetInnerBranchEndPoints (pllInstance * tr)
{
  node ** nodes;
  nodeptr p;
  int i = 0;

  nodes = (node **) rax_calloc(tr->mxtips - 3, sizeof(node *));

  p = tr->start;
  assert (isTip(p->number, tr->mxtips));

  getInnerBranchEndPointsRecursive(p->back, tr->mxtips, &i, nodes);

  return nodes;
}

#if defined WIN32 || defined _WIN32 || defined __WIN32__
void* rax_calloc(size_t count, size_t size) {
	void* res = rax_malloc(size * count);
	memset(res,0,size * count);
	return res;
}
#endif