aboutsummaryrefslogtreecommitdiff
path: root/src/gemma.cpp
blob: 2c54672dfdf3bcfd391fef9dba5e85c9191e0369 (plain)
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
/*
    Genome-wide Efficient Mixed Model Association (GEMMA)
    Copyright (C) 2011-2017, Xiang Zhou

    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/>.
*/

#include <cmath>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iostream>
#include <string>
#include <sys/stat.h>
#ifdef OPENBLAS
#pragma message "Compiling with OPENBLAS"
extern "C" {
  // these functions are defined in cblas.h - but if we include that we
  // conflicts with other BLAS includes
  int openblas_get_num_threads(void);
  int openblas_get_parallel(void);
  char* openblas_get_config(void);
  char* openblas_get_corename(void);
}
#endif

#include "gsl/gsl_blas.h"
#include "gsl/gsl_cdf.h"
#include "gsl/gsl_eigen.h"
#include "gsl/gsl_linalg.h"
#include "gsl/gsl_matrix.h"
#include "gsl/gsl_vector.h"
#include "gsl/gsl_version.h"

#include "bslmm.h"
#include "bslmmdap.h"
#include "gemma.h"
#include "io.h"
#include "lapack.h"
#include "ldr.h"
#include "lm.h"
#include "lmm.h"
#include "mathfunc.h"
#include "mvlmm.h"
#include "prdt.h"
#include "varcov.h"
#include "vc.h"
#include "debug.h"
#include "version.h"

using namespace std;

GEMMA::GEMMA(void) : version(GEMMA_VERSION), date(GEMMA_DATE), year(GEMMA_YEAR) {}

void gemma_gsl_error_handler (const char * reason,
                              const char * file,
                              int line, int gsl_errno) {
  cerr << "GSL ERROR: " << reason << " in " << file
       << " at line " << line << " errno " << gsl_errno <<endl;
  exit(22);
}

void GEMMA::PrintHeader(void) {
  cout << endl;
  cout << "*********************************************************" << endl;
  cout << "  Genome-wide Efficient Mixed Model Association (GEMMA)  " << endl;
  cout << "  Version " << version << ", " << date
       << "                              " << endl;
  cout << "  Visit http://www.xzlab.org/software.html For Updates   " << endl;
  cout << "  (C) " << year << " Xiang Zhou                                   "
       << endl;
  cout << "  GNU General Public License                             " << endl;
  cout << "  For Help, Type ./gemma -h                              " << endl;
  cout << "*********************************************************" << endl;
  cout << endl;

  return;
}

void GEMMA::PrintLicense(void) {
  cout << endl;
  cout << "The Software Is Distributed Under GNU General Public "
       << "License, But May Also Require The Following Notifications." << endl;
  cout << endl;

  cout << "Including Lapack Routines In The Software May Require"
       << " The Following Notification:" << endl;
  cout << "Copyright (c) 1992-2010 The University of Tennessee and "
       << "The University of Tennessee Research Foundation.  All rights "
       << "reserved." << endl;
  cout << "Copyright (c) 2000-2010 The University of California "
       << "Berkeley. All rights reserved." << endl;
  cout << "Copyright (c) 2006-2010 The University of Colorado Denver. "
       << "All rights reserved." << endl;
  cout << endl;

  cout << "$COPYRIGHT$" << endl;
  cout << "Additional copyrights may follow" << endl;
  cout << "$HEADER$" << endl;
  cout << "Redistribution and use in source and binary forms, with or "
       << "without modification, are permitted provided that the following "
       << " conditions are met:" << endl;
  cout << "- Redistributions of source code must retain the above "
       << "copyright notice, this list of conditions and the following "
       << "disclaimer." << endl;
  cout << "- Redistributions in binary form must reproduce the above "
       << "copyright notice, this list of conditions and the following "
       << "disclaimer listed in this license in the documentation and/or "
       << "other materials provided with the distribution." << endl;
  cout << "- Neither the name of the copyright holders nor the names "
       << "of its contributors may be used to endorse or promote products "
       << "derived from this software without specific prior written "
       << "permission." << endl;
  cout << "The copyright holders provide no reassurances that the "
       << "source code provided does not infringe any patent, copyright, "
       << "or any other "
       << "intellectual property rights of third parties. "
       << "The copyright holders disclaim any liability to any recipient "
       << "for claims brought against "
       << "recipient by any third party for infringement of that parties "
       << "intellectual property rights. " << endl;
  cout << "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND "
       << "CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, "
       << "INCLUDING, BUT NOT "
       << "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND "
       << "FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT "
       << "SHALL THE COPYRIGHT "
       << "OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, "
       << "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES "
       << "(INCLUDING, BUT NOT "
       << "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; "
       << "LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) "
       << "HOWEVER CAUSED AND ON ANY "
       << "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, "
       << "OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY "
       << "OUT OF THE USE "
       << "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF "
       << "SUCH DAMAGE." << endl;
  cout << endl;

  return;
}

void GEMMA::PrintHelp(size_t option) {
  if (option == 0) {
    cout << endl;
    cout << " GEMMA version " << version << ", released on " << date << endl;
    cout << " implemented by Xiang Zhou" << endl;
    cout << endl;
    cout << " type ./gemma -h [num] for detailed helps" << endl;
    cout << " options: " << endl;
    cout << " 1: quick guide" << endl;
    cout << " 2: file I/O related" << endl;
    cout << " 3: SNP QC" << endl;
    cout << " 4: calculate relatedness matrix" << endl;
    cout << " 5: perform eigen decomposition" << endl;
    cout << " 6: perform variance component estimation" << endl;
    cout << " 7: fit a linear model" << endl;
    cout << " 8: fit a linear mixed model" << endl;
    cout << " 9: fit a multivariate linear mixed model" << endl;
    cout << " 10: fit a Bayesian sparse linear mixed model" << endl;
    cout << " 11: obtain predicted values" << endl;
    cout << " 12: calculate snp variance covariance" << endl;
    cout << " 13: note" << endl;
    cout << " 14: debug options" << endl;
    cout << endl;
  }

  if (option == 1) {
    cout << " QUICK GUIDE" << endl;
    cout << " to generate a relatedness matrix: " << endl;
    cout << "         ./gemma -bfile [prefix] -gk [num] -o [prefix]" << endl;
    cout << "         ./gemma -g [filename] -p [filename] -gk [num] -o [prefix]"
         << endl;
    cout << " to generate the S matrix: " << endl;
    cout << "         ./gemma -bfile [prefix] -gs -o [prefix]" << endl;
    cout << "         ./gemma -p [filename] -g [filename] -gs -o [prefix]"
         << endl;
    cout << "         ./gemma -bfile [prefix] -cat [filename] -gs -o [prefix]"
         << endl;
    cout << "         ./gemma -p [filename] -g [filename] -cat [filename] -gs "
            "-o [prefix]"
         << endl;
    cout << "         ./gemma -bfile [prefix] -sample [num] -gs -o [prefix]"
         << endl;
    cout << "         ./gemma -p [filename] -g [filename] -sample [num] -gs -o "
            "[prefix]"
         << endl;
    cout << " to generate the q vector: " << endl;
    cout << "         ./gemma -beta [filename] -gq -o [prefix]" << endl;
    cout << "         ./gemma -beta [filename] -cat [filename] -gq -o [prefix]"
         << endl;
    cout << " to generate the ldsc weigthts: " << endl;
    cout << "         ./gemma -beta [filename] -gw -o [prefix]" << endl;
    cout << "         ./gemma -beta [filename] -cat [filename] -gw -o [prefix]"
         << endl;
    cout << " to perform eigen decomposition of the relatedness matrix: "
         << endl;
    cout << "         ./gemma -bfile [prefix] -k [filename] -eigen -o [prefix]"
         << endl;
    cout << "         ./gemma -g [filename] -p [filename] -k [filename] -eigen "
            "-o [prefix]"
         << endl;
    cout << " to estimate variance components: " << endl;
    cout << "         ./gemma -bfile [prefix] -k [filename] -vc [num] -o "
            "[prefix]"
         << endl;
    cout << "         ./gemma -p [filename] -k [filename] -vc [num] -o [prefix]"
         << endl;
    cout << "         ./gemma -bfile [prefix] -mk [filename] -vc [num] -o "
            "[prefix]"
         << endl;
    cout
        << "         ./gemma -p [filename] -mk [filename] -vc [num] -o [prefix]"
        << endl;
    cout << "         ./gemma -beta [filename] -cor [filename] -vc [num] -o "
            "[prefix]"
         << endl;
    cout << "         ./gemma -beta [filename] -cor [filename] -cat [filename] "
            "-vc [num] -o [prefix]"
         << endl;
    cout << "         options for the above two commands: -crt -windowbp [num]"
         << endl;
    cout << "         ./gemma -mq [filename] -ms [filename] -mv [filename] -vc "
            "[num] -o [prefix]"
         << endl;
    cout << "         or with summary statistics, replace bfile with mbfile, "
            "or g or mg; vc=1 for HE weights and vc=2 for LDSC weights"
         << endl;
    cout << "         ./gemma -beta [filename] -bfile [filename] -cat "
            "[filename] -wsnp [filename] -wcat [filename] -vc [num] -o [prefix]"
         << endl;
    cout << "         ./gemma -beta [filename] -bfile [filename] -cat "
            "[filename] -wsnp [filename] -wcat [filename] -ci [num] -o [prefix]"
         << endl;
    cout << " to fit a linear mixed model: " << endl;
    cout << "         ./gemma -bfile [prefix] -k [filename] -lmm [num] -o "
            "[prefix]"
         << endl;
    cout << "         ./gemma -g [filename] -p [filename] -a [filename] -k "
            "[filename] -lmm [num] -o [prefix]"
         << endl;
    cout << " to fit a linear mixed model to test g by e effects: " << endl;
    cout << "         ./gemma -bfile [prefix] -gxe [filename] -k [filename] "
            "-lmm [num] -o [prefix]"
         << endl;
    cout << "         ./gemma -g [filename] -p [filename] -a [filename] -gxe "
            "[filename] -k [filename] -lmm [num] -o [prefix]"
         << endl;
    cout << " to fit a univariate linear mixed model with different residual "
            "weights for different individuals: "
         << endl;
    cout << "         ./gemma -bfile [prefix] -weight [filename] -k [filename] "
            "-lmm [num] -o [prefix]"
         << endl;
    cout << "         ./gemma -g [filename] -p [filename] -a [filename] "
            "-weight [filename] -k [filename] -lmm [num] -o [prefix]"
         << endl;
    cout << " to fit a multivariate linear mixed model: " << endl;
    cout << "         ./gemma -bfile [prefix] -k [filename] -lmm [num] -n "
            "[pheno cols...] -o [prefix]"
         << endl;
    cout << "         ./gemma -g [filename] -p [filename] -a [filename] -k "
            "[filename] -lmm [num] -n [pheno cols...] -o [prefix]"
         << endl;
    cout << " to fit a Bayesian sparse linear mixed model: " << endl;
    cout << "         ./gemma -bfile [prefix] -bslmm [num] -o [prefix]" << endl;
    cout << "         ./gemma -g [filename] -p [filename] -a [filename] -bslmm "
            "[num] -o [prefix]"
         << endl;
    cout << " to obtain predicted values: " << endl;
    cout << "         ./gemma -bfile [prefix] -epm [filename] -emu [filename] "
            "-ebv [filename] -k [filename] -predict [num] -o [prefix]"
         << endl;
    cout << "         ./gemma -g [filename] -p [filename] -epm [filename] -emu "
            "[filename] -ebv [filename] -k [filename] -predict [num] -o "
            "[prefix]"
         << endl;
    cout << " to calculate correlations between SNPs: " << endl;
    cout << "         ./gemma -bfile [prefix] -calccor -o [prefix]" << endl;
    cout << "         ./gemma -g [filename] -p [filename] -calccor -o [prefix]"
         << endl;
    cout << endl;
  }

  if (option == 2) {
    cout << " FILE I/O RELATED OPTIONS" << endl;
    cout << " -bfile    [prefix]       "
         << " specify input PLINK binary ped file prefix." << endl;
    cout << "          requires: *.fam, *.bim and *.bed files" << endl;
    cout << "          missing value: -9" << endl;
    cout << " -g        [filename]     "
         << " specify input BIMBAM mean genotype file name" << endl;
    cout << "          format: rs#1, allele0, allele1, genotype for individual "
            "1, genotype for individual 2, ..."
         << endl;
    cout << "                  rs#2, allele0, allele1, genotype for individual "
            "1, genotype for individual 2, ..."
         << endl;
    cout << "                  ..." << endl;
    cout << "          missing value: NA" << endl;
    cout << " -p        [filename]     "
         << " specify input BIMBAM-style phenotype file name (when used with PLINK .fam phenotypes are ignored)" << endl;
    cout << "          format: phenotype for individual 1" << endl;
    cout << "                  phenotype for individual 2" << endl;
    cout << "                  ..." << endl;
    cout << "          missing value: NA" << endl;
    cout << " -a        [filename]     "
         << " specify input BIMBAM SNP annotation file name (optional)" << endl;
    cout << "          format: rs#1, base_position, chr_number" << endl;
    cout << "                  rs#2, base_position, chr_number" << endl;
    cout << "                  ..." << endl;

    cout << " -gxe      [filename]     "
         << " specify input file that contains a column of environmental "
            "factor for g by e tests"
         << endl;
    cout << "          format: variable for individual 1" << endl;
    cout << "                  variable for individual 2" << endl;
    cout << "                  ..." << endl;
    cout << "          missing value: NA" << endl;
    cout << " -widv   [filename]     "
         << " weight file contains a column of positive values to be used "
         << "as weights for residuals---each weight corresponds to an "
         << "individual, in which a high weight corresponds to high "
         << "residual error variance for this individual (similar in "
	 << "format to phenotype file)"
         << endl;
    cout << "          format: variable for individual 1" << endl;
    cout << "                  variable for individual 2" << endl;
    cout << "                  ..." << endl;
    cout << "          missing value: NA" << endl;
    cout << " -k        [filename]     "
         << " specify input kinship/relatedness matrix file name" << endl;
    cout << " -mk       [filename]     "
         << " specify input file which contains a list of kinship/relatedness "
            "matrices"
         << endl;
    cout << " -u        [filename]     "
         << " specify input file containing the eigen vectors of the "
            "kinship/relatedness matrix"
         << endl;
    cout << " -d        [filename]     "
         << " specify input file containing the eigen values of the "
            "kinship/relatedness matrix"
         << endl;
    cout << " -c        [filename]     "
         << " specify input covariates file name (optional)" << endl;
    cout << " -cat      [filename]     "
         << " specify input category file name (optional), which contains rs "
            "cat1 cat2 ..."
         << endl;
    cout << " -beta     [filename]     "
         << " specify input beta file name (optional), which contains rs beta "
            "se_beta n_total (or n_mis and n_obs) estimates from a lm model"
         << endl;
    cout << " -cor      [filename]     "
         << " specify input correlation file name (optional), which contains "
            "rs window_size correlations from snps"
         << endl;
    cout << "          missing value: NA" << endl;
    cout << "          note: the intercept (a column of 1s) may need to be "
            "included"
         << endl;
    cout << " -epm      [filename]     "
         << " specify input estimated parameter file name" << endl;
    cout << " -en [n1] [n2] [n3] [n4]  "
         << " specify values for the input estimated parameter file (with a "
            "header)"
         << endl;
    cout << "          options: n1: rs column number" << endl;
    cout << "                   n2: estimated alpha column number (0 to ignore)"
         << endl;
    cout << "                   n3: estimated beta column number (0 to ignore)"
         << endl;
    cout << "                   n4: estimated gamma column number (0 to ignore)"
         << endl;
    cout << "          default: 2 4 5 6 if -ebv is not specified; 2 0 5 6 if "
            "-ebv is specified"
         << endl;
    cout << " -ebv      [filename]     "
         << " specify input estimated random effect (breeding value) file name"
         << endl;
    cout << "          format: value for individual 1" << endl;
    cout << "                  value for individual 2" << endl;
    cout << "                  ..." << endl;
    cout << "          missing value: NA" << endl;
    cout << " -emu      [filename]     "
         << " specify input log file name containing estimated mean" << endl;
    cout << " -mu       [num]          "
         << " specify input estimated mean value" << endl;
    cout << " -gene     [filename]     "
         << " specify input gene expression file name" << endl;
    cout << "          format: header" << endl;
    cout << "                  gene1, count for individual 1, count for "
            "individual 2, ..."
         << endl;
    cout << "                  gene2, count for individual 1, count for "
            "individual 2, ..."
         << endl;
    cout << "                  ..." << endl;
    cout << "          missing value: not allowed" << endl;
    cout << " -r        [filename]     "
         << " specify input total read count file name" << endl;
    cout << "          format: total read count for individual 1" << endl;
    cout << "                  total read count for individual 2" << endl;
    cout << "                  ..." << endl;
    cout << "          missing value: NA" << endl;
    cout
        << " -snps     [filename]     "
        << " specify input snps file name to only analyze a certain set of snps"
        << endl;
    cout << "          format: rs#1" << endl;
    cout << "                  rs#2" << endl;
    cout << "                  ..." << endl;
    cout << "          missing value: NA" << endl;
    cout << " -silence                 "
         << " silent terminal display" << endl;
    cout << " -km       [num]          "
         << " specify input kinship/relatedness file type (default 1)." << endl;
    cout << "          options: 1: \"n by n matrix\" format" << endl;
    cout << "                   2: \"id  id  value\" format" << endl;
    cout << " -n        [num]          "
         << " specify phenotype column in the phenotype/*.fam file (optional; "
            "default 1)"
         << endl;
    cout << " -pace     [num]          "
         << " specify terminal display update pace (default 1,000 SNPs or "
            "1,000 iterations)."
         << endl;
    cout << " -outdir   [path]         "
         << " specify output directory path (default \"./output/\")" << endl;
    cout << " -o        [prefix]       "
         << " specify output file prefix (default \"result\")" << endl;
    cout << "          output: prefix.cXX.txt or prefix.sXX.txt from "
            "kinship/relatedness matrix estimation"
         << endl;
    cout << "          output: prefix.assoc.txt and prefix.log.txt form "
            "association tests"
         << endl;
    cout << endl;
  }

  if (option == 3) {
    cout << " SNP QC OPTIONS" << endl;
    cout << " -miss     [num]          "
         << " specify missingness threshold (default 0.05)" << endl;
    cout << " -maf      [num]          "
         << " specify minor allele frequency threshold (default 0.01)" << endl;
    cout << " -hwe      [num]          "
         << " specify HWE test p value threshold (default 0; no test)" << endl;
    cout << " -r2       [num]          "
         << " specify r-squared threshold (default 0.9999)" << endl;
    cout << " -notsnp                  "
         << " minor allele frequency cutoff is not used" << endl;
    cout << endl;
  }

  if (option == 4) {
    cout << " RELATEDNESS MATRIX (K) CALCULATION OPTIONS" << endl;
    cout << " -ksnps    [filename]     "
         << " specify input snps file name to compute K" << endl;
    cout << " -loco     [chr]          "
         << " leave one chromosome out (LOCO) by name (requires -a annotation "
            "file)"
         << endl;
    cout << " -a        [filename]     "
         << " specify input BIMBAM SNP annotation file name (LOCO only)"
         << endl;
    cout << " -gk       [num]          "
         << " specify which type of kinship/relatedness matrix to generate "
            "(default 1)"
         << endl;
    cout << "          options: 1: centered XX^T/p" << endl;
    cout << "                   2: standardized XX^T/p" << endl;
    cout << "          note: non-polymorphic SNPs are excluded " << endl;
    cout << endl;
  }

  if (option == 5) {
    cout << " EIGEN-DECOMPOSITION OPTIONS" << endl;
    cout << " -eigen                   "
         << " specify to perform eigen decomposition of the loaded relatedness "
            "matrix"
         << endl;
    cout << endl;
  }

  if (option == 6) {
    cout << " VARIANCE COMPONENT ESTIMATION OPTIONS" << endl;
    cout << " -vc                      "
         << " specify to perform variance component estimation for the loaded "
            "relatedness matrix/matrices"
         << endl;
    cout
        << "          options (with kinship file):   1: HE regression (default)"
        << endl;
    cout << "                                         2: REML" << endl;
    cout << "          options (with beta/cor files): 1: Centered genotypes "
            "(default)"
         << endl;
    cout << "                                         2: Standardized genotypes"
         << endl;
    cout << "                                         -crt -windowbp [num]"
         << " specify the window size based on bp (default 1000000; 1Mb)"
         << endl;
    cout << "                                         -crt -windowcm [num]"
         << " specify the window size based on cm (default 0)" << endl;
    cout << "                                         -crt -windowns [num]"
         << " specify the window size based on number of snps (default 0)"
         << endl;
    cout << endl;
  }

  if (option == 7) {
    cout << " LINEAR MODEL OPTIONS" << endl;
    cout << " -lm       [num]         "
         << " specify analysis options (default 1)." << endl;
    cout << "          options: 1: Wald test" << endl;
    cout << "                   2: Likelihood ratio test" << endl;
    cout << "                   3: Score test" << endl;
    cout << "                   4: 1-3" << endl;
    cout << endl;
  }

  if (option == 8) {
    cout << " LINEAR MIXED MODEL OPTIONS" << endl;
    cout << " -lmm      [num]         "
         << " specify analysis options (default 1)." << endl;
    cout << "          options: 1: Wald test" << endl;
    cout << "                   2: Likelihood ratio test" << endl;
    cout << "                   3: Score test" << endl;
    cout << "                   4: 1-3" << endl;
    cout << "                   5: Parameter estimation in the null model only"
         << endl;
    cout << " -lmin     [num]          "
         << " specify minimal value for lambda (default 1e-5)" << endl;
    cout << " -lmax     [num]          "
         << " specify maximum value for lambda (default 1e+5)" << endl;
    cout
        << " -region   [num]          "
        << " specify the number of regions used to evaluate lambda (default 10)"
        << endl;
    cout << endl;
  }

  if (option == 9) {
    cout << " MULTIVARIATE LINEAR MIXED MODEL OPTIONS" << endl;
    cout << " -n [pheno cols...] - range of phenotypes" << endl;
    cout << " -pnr				     "
         << " specify the pvalue threshold to use the Newton-Raphson's method "
            "(default 0.001)"
         << endl;
    cout << " -emi				     "
         << " specify the maximum number of iterations for the PX-EM method in "
            "the null (default 10000)"
         << endl;
    cout << " -nri				     "
         << " specify the maximum number of iterations for the "
            "Newton-Raphson's method in the null (default 100)"
         << endl;
    cout << " -emp				     "
         << " specify the precision for the PX-EM method in the null (default "
            "0.0001)"
         << endl;
    cout << " -nrp				     "
         << " specify the precision for the Newton-Raphson's method in the "
            "null (default 0.0001)"
         << endl;
    cout << " -crt				     "
         << " specify to output corrected pvalues for these pvalues that are "
            "below the -pnr threshold"
         << endl;
    cout << endl;
  }

  if (option == 10) {
    cout << " MULTI-LOCUS ANALYSIS OPTIONS" << endl;
    cout << " -bslmm	  [num]			 "
         << " specify analysis options (default 1)." << endl;
    cout << "          options: 1: BSLMM" << endl;
    cout << "                   2: standard ridge regression/GBLUP (no mcmc)"
         << endl;
    cout << "                   3: probit BSLMM (requires 0/1 phenotypes)"
         << endl;
    cout
        << "                   4: BSLMM with DAP for Hyper Parameter Estimation"
        << endl;
    cout << "                   5: BSLMM with DAP for Fine Mapping" << endl;

    cout << " -ldr	  [num]			 "
         << " specify analysis options (default 1)." << endl;
    cout << "          options: 1: LDR" << endl;

    cout << "   MCMC OPTIONS" << endl;
    cout << "   Prior" << endl;
    cout << " -hmin     [num]          "
         << " specify minimum value for h (default 0)" << endl;
    cout << " -hmax     [num]          "
         << " specify maximum value for h (default 1)" << endl;
    cout << " -rmin     [num]          "
         << " specify minimum value for rho (default 0)" << endl;
    cout << " -rmax     [num]          "
         << " specify maximum value for rho (default 1)" << endl;
    cout << " -pmin     [num]          "
         << " specify minimum value for log10(pi) (default log10(1/p), where p "
            "is the number of analyzed SNPs )"
         << endl;
    cout << " -pmax     [num]          "
         << " specify maximum value for log10(pi) (default log10(1) )" << endl;
    cout << " -smin     [num]          "
         << " specify minimum value for |gamma| (default 0)" << endl;
    cout << " -smax     [num]          "
         << " specify maximum value for |gamma| (default 300)" << endl;

    cout << "   Proposal" << endl;
    cout << " -gmean    [num]          "
         << " specify the mean for the geometric distribution (default: 2000)"
         << endl;
    cout << " -hscale   [num]          "
         << " specify the step size scale for the proposal distribution of h "
            "(value between 0 and 1, default min(10/sqrt(n),1) )"
         << endl;
    cout << " -rscale   [num]          "
         << " specify the step size scale for the proposal distribution of rho "
            "(value between 0 and 1, default min(10/sqrt(n),1) )"
         << endl;
    cout << " -pscale   [num]          "
         << " specify the step size scale for the proposal distribution of "
            "log10(pi) (value between 0 and 1, default min(5/sqrt(n),1) )"
         << endl;

    cout << "   Others" << endl;
    cout << " -w        [num]          "
         << " specify burn-in steps (default 100,000)" << endl;
    cout << " -s        [num]          "
         << " specify sampling steps (default 1,000,000)" << endl;
    cout << " -rpace    [num]          "
         << " specify recording pace, record one state in every [num] steps "
            "(default 10)"
         << endl;
    cout << " -wpace    [num]          "
         << " specify writing pace, write values down in every [num] recorded "
            "steps (default 1000)"
         << endl;
    cout << " -seed     [num]          "
         << " specify random seed (a random seed is generated by default)"
         << endl;
    cout << " -mh       [num]          "
         << " specify number of MH steps in each iteration (default 10)"
         << endl;
    cout << "          requires: 0/1 phenotypes and -bslmm 3 option" << endl;
    cout << endl;
  }

  if (option == 11) {
    cout << " PREDICTION OPTIONS" << endl;
    cout << " -predict  [num]			 "
         << " specify prediction options (default 1)." << endl;
    cout << "          options: 1: predict for individuals with missing "
            "phenotypes"
         << endl;
    cout << "                   2: predict for individuals with missing "
            "phenotypes, and convert the predicted values to probability "
            "scale. Use only for files fitted with -bslmm 3 option"
         << endl;
    cout << endl;
  }

  if (option == 12) {
    cout << " CALC CORRELATION OPTIONS" << endl;
    cout << " -calccor       			 " << endl;
    cout << " -windowbp       [num]            "
         << " specify the window size based on bp (default 1000000; 1Mb)"
         << endl;
    cout << " -windowcm       [num]            "
         << " specify the window size based on cm (default 0; not used)"
         << endl;
    cout << " -windowns       [num]            "
         << " specify the window size based on number of snps (default 0; not "
            "used)"
         << endl;
    cout << endl;
  }

  if (option == 13) {
    cout << " NOTE" << endl;
    cout << " 1. Only individuals with non-missing phenotoypes and covariates "
            "will be analyzed."
         << endl;
    cout << " 2. Missing genotoypes will be repalced with the mean genotype of "
            "that SNP."
         << endl;
    cout << " 3. For lmm analysis, memory should be large enough to hold the "
            "relatedness matrix and to perform eigen decomposition."
         << endl;
    cout << " 4. For multivariate lmm analysis, use a large -pnr for each snp "
            "will increase computation time dramatically."
         << endl;
    cout << " 5. For bslmm analysis, in addition to 3, memory should be large "
            "enough to hold the whole genotype matrix."
         << endl;
    cout << endl;
  }

  if (option == 14) {
    cout << " DEBUG OPTIONS" << endl;
    cout << " -no-check                disable checks" << endl;
    cout << " -strict                  strict mode will stop when there is a problem" << endl;
    cout << " -silence                 silent terminal display" << endl;
    cout << " -debug                   debug output" << endl;
    cout << " -nind       [num]        read up to num individuals" << endl;
    cout << " -issue      [num]        enable tests relevant to issue tracker" << endl;
    cout << " -legacy                  run gemma in legacy mode" << endl;
    cout << endl;
  }

  return;
}

// OPTIONS
// -------
// gk:      21-22
// gs:      25-26
// gq:      27-28
// eigen:   31-32
// lmm:     1-5
// bslmm:   11-15
// predict: 41-43
// lm:      51
// vc:      61
// ci:      66-67
// calccor: 71
// gw:      72

void GEMMA::Assign(int argc, char **argv, PARAM &cPar) {
  string str;

  for (int i = 1; i < argc; i++) {
    if (strcmp(argv[i], "-bfile") == 0 || strcmp(argv[i], "--bfile") == 0 ||
        strcmp(argv[i], "-b") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_bfile = str;
    } else if (strcmp(argv[i], "-mbfile") == 0 ||
               strcmp(argv[i], "--mbfile") == 0 ||
               strcmp(argv[i], "-mb") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_mbfile = str;
    } else if (strcmp(argv[i], "-silence") == 0) {
      debug_set_quiet_mode(true);
    } else if (strcmp(argv[i], "-g") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_geno = str;
    } else if (strcmp(argv[i], "-mg") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_mgeno = str;
    } else if (strcmp(argv[i], "-p") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_pheno = str;
    } else if (strcmp(argv[i], "-a") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_anno = str;
    } else if (strcmp(argv[i], "-gxe") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_gxe = str;
    } else if (strcmp(argv[i], "-widv") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_weight = str;
    } else if (strcmp(argv[i], "-wsnp") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_wsnp = str;
    } else if (strcmp(argv[i], "-wcat") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_wcat = str;
    } else if (strcmp(argv[i], "-k") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_kin = str;
    } else if (strcmp(argv[i], "-mk") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_mk = str;
    } else if (strcmp(argv[i], "-u") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_ku = str;
    } else if (strcmp(argv[i], "-d") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_kd = str;
    } else if (strcmp(argv[i], "-c") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_cvt = str;
    } else if (strcmp(argv[i], "-cat") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_cat = str;
    } else if (strcmp(argv[i], "-mcat") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_mcat = str;
    } else if (strcmp(argv[i], "-catc") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_catc = str;
    } else if (strcmp(argv[i], "-mcatc") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_mcatc = str;
    } else if (strcmp(argv[i], "-beta") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_beta = str;
    } else if (strcmp(argv[i], "-bf") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_bf = str;
    } else if (strcmp(argv[i], "-hyp") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_hyp = str;
    } else if (strcmp(argv[i], "-cor") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_cor = str;
    } else if (strcmp(argv[i], "-study") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_study = str;
    } else if (strcmp(argv[i], "-ref") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_ref = str;
    } else if (strcmp(argv[i], "-mstudy") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_mstudy = str;
    } else if (strcmp(argv[i], "-mref") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_mref = str;
    } else if (strcmp(argv[i], "-epm") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_epm = str;
    } else if (strcmp(argv[i], "-en") == 0) {
      while (argv[i + 1] != NULL && argv[i + 1][0] != '-') {
        ++i;
        str.clear();
        str.assign(argv[i]);
        cPar.est_column.push_back(atoi(str.c_str()));
      }
    } else if (strcmp(argv[i], "-ebv") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_ebv = str;
    } else if (strcmp(argv[i], "-emu") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_log = str;
    } else if (strcmp(argv[i], "-mu") == 0) {
      if (argv[i + 1] == NULL) {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.pheno_mean = atof(str.c_str());
    } else if (strcmp(argv[i], "-gene") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_gene = str;
    } else if (strcmp(argv[i], "-r") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_read = str;
    } else if (strcmp(argv[i], "-snps") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_snps = str;
    } else if (strcmp(argv[i], "-km") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.k_mode = atoi(str.c_str());
    } else if (strcmp(argv[i], "-n") == 0) { // set pheno column (list/range)
      (cPar.p_column).clear();
      while (argv[i + 1] != NULL && argv[i + 1][0] != '-') {
        ++i;
        str.clear();
        str.assign(argv[i]);
        (cPar.p_column).push_back(atoi(str.c_str()));
      }
    } else if (strcmp(argv[i], "-pace") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.d_pace = atoi(str.c_str());
    } else if (strcmp(argv[i], "-outdir") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.path_out = str;
    } else if (strcmp(argv[i], "-o") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.file_out = str;
    } else if (strcmp(argv[i], "-miss") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.miss_level = atof(str.c_str());
    } else if (strcmp(argv[i], "-maf") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      if (cPar.maf_level != -1) {
        cPar.maf_level = atof(str.c_str());
      }
    } else if (strcmp(argv[i], "-hwe") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.hwe_level = atof(str.c_str());
    } else if (strcmp(argv[i], "-r2") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.r2_level = atof(str.c_str());
    } else if (strcmp(argv[i], "-notsnp") == 0) {
      cPar.maf_level = -1;
    } else if (strcmp(argv[i], "-loco") == 0) {
      assert(argv[i + 1]);
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.loco = str;
    } else if (strcmp(argv[i], "-gk") == 0) {
      if (cPar.a_mode != 0) {
        cPar.error = true;
        cout << "error! only one of -gk -gs -eigen -vc -lm -lmm -bslmm "
                "-predict -calccor options is allowed."
             << endl;
        break;
      }
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        cPar.a_mode = 21;
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.a_mode = 20 + atoi(str.c_str());
    } else if (strcmp(argv[i], "-gs") == 0) {
      if (cPar.a_mode != 0) {
        cPar.error = true;
        cout << "error! only one of -gk -gs -eigen -vc -lm -lmm -bslmm "
                "-predict -calccor options is allowed."
             << endl;
        break;
      }
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        cPar.a_mode = 25;
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.a_mode = 24 + atoi(str.c_str());
    } else if (strcmp(argv[i], "-gq") == 0) {
      if (cPar.a_mode != 0) {
        cPar.error = true;
        cout << "error! only one of -gk -gs -eigen -vc -lm -lmm -bslmm "
                "-predict -calccor options is allowed."
             << endl;
        break;
      }
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        cPar.a_mode = 27;
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.a_mode = 26 + atoi(str.c_str());
    } else if (strcmp(argv[i], "-gw") == 0) {
      if (cPar.a_mode != 0) {
        cPar.error = true;
        cout << "error! only one of -gk -gs -eigen -vc -lm -lmm -bslmm "
                "-predict -calccor options is allowed."
             << endl;
        break;
      }
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        cPar.a_mode = 72;
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.a_mode = 71 + atoi(str.c_str());
    } else if (strcmp(argv[i], "-sample") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.ni_subsample = atoi(str.c_str());
    } else if (strcmp(argv[i], "-eigen") == 0) {
      if (cPar.a_mode != 0) {
        cPar.error = true;
        cout << "error! only one of -gk -gs -eigen -vc -lm -lmm -bslmm "
                "-predict -calccor options is allowed."
             << endl;
        break;
      }
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        cPar.a_mode = 31;
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.a_mode = 30 + atoi(str.c_str());
    } else if (strcmp(argv[i], "-calccor") == 0) {
      if (cPar.a_mode != 0) {
        cPar.error = true;
        cout << "error! only one of -gk -gs -eigen -vc -lm -lmm -bslmm "
                "-predict -calccor options is allowed."
             << endl;
        break;
      }
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        cPar.a_mode = 71;
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.a_mode = 70 + atoi(str.c_str());
    } else if (strcmp(argv[i], "-vc") == 0) {
      if (cPar.a_mode != 0) {
        cPar.error = true;
        cout << "error! only one of -gk -gs -eigen -vc -lm -lmm -bslmm "
                "-predict -calccor options is allowed."
             << endl;
        break;
      }
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        cPar.a_mode = 61;
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.a_mode = 60 + atoi(str.c_str());
    } else if (strcmp(argv[i], "-ci") == 0) {
      if (cPar.a_mode != 0) {
        cPar.error = true;
        cout << "error! only one of -gk -gs -eigen -vc -lm -lmm -bslmm "
                "-predict -calccor options is allowed."
             << endl;
        break;
      }
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        cPar.a_mode = 66;
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.a_mode = 65 + atoi(str.c_str());
    } else if (strcmp(argv[i], "-pve") == 0) {
      double s = 0;
      while (argv[i + 1] != NULL &&
             (argv[i + 1][0] != '-' || !isalpha(argv[i + 1][1]))) {
        ++i;
        str.clear();
        str.assign(argv[i]);
        cPar.v_pve.push_back(atof(str.c_str()));
        s += atof(str.c_str());
      }
      if (s == 1) {
        cout << "summation of pve equals one." << endl;
      }
    } else if (strcmp(argv[i], "-blocks") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.n_block = atoi(str.c_str());
    } else if (strcmp(argv[i], "-noconstrain") == 0) {
      cPar.noconstrain = true;
    } else if (strcmp(argv[i], "-lm") == 0) {
      if (cPar.a_mode != 0) {
        cPar.error = true;
        cout << "error! only one of -gk -gs -eigen -vc -lm -lmm -bslmm "
                "-predict -calccor options is allowed."
             << endl;
        break;
      }
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        cPar.a_mode = 51;
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.a_mode = 50 + atoi(str.c_str());
    } else if (strcmp(argv[i], "-fa") == 0 || strcmp(argv[i], "-lmm") == 0) {
      if (cPar.a_mode != 0) {
        cPar.error = true;
        cout << "error! only one of -gk -gs -eigen -vc -lm -lmm -bslmm "
                "-predict -calccor options is allowed."
             << endl;
        break;
      }
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        cPar.a_mode = 1;
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.a_mode = atoi(str.c_str());
    } else if (strcmp(argv[i], "-lmin") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.l_min = atof(str.c_str());
    } else if (strcmp(argv[i], "-lmax") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.l_max = atof(str.c_str());
    } else if (strcmp(argv[i], "-region") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.n_region = atoi(str.c_str());
    } else if (strcmp(argv[i], "-pnr") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.p_nr = atof(str.c_str());
    } else if (strcmp(argv[i], "-emi") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.em_iter = atoi(str.c_str());
    } else if (strcmp(argv[i], "-nri") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.nr_iter = atoi(str.c_str());
    } else if (strcmp(argv[i], "-nind") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.ni_max = atoi(str.c_str()); // for testing purposes
      enforce(cPar.ni_max > 0);
    } else if (strcmp(argv[i], "-issue") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      auto issue = atoi(str.c_str()); // for testing purposes
      enforce(issue > 0);
      debug_set_issue(issue);
    } else if (strcmp(argv[i], "-emp") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.em_prec = atof(str.c_str());
    } else if (strcmp(argv[i], "-nrp") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.nr_prec = atof(str.c_str());
    } else if (strcmp(argv[i], "-crt") == 0) {
      cPar.crt = 1;
    } else if (strcmp(argv[i], "-bslmm") == 0) {
      if (cPar.a_mode != 0) {
        cPar.error = true;
        cout << "error! only one of -gk -gs -eigen -vc -lm -lmm -bslmm "
                "-predict -calccor options is allowed."
             << endl;
        break;
      }
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        cPar.a_mode = 11;
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.a_mode = 10 + atoi(str.c_str());
    } else if (strcmp(argv[i], "-hmin") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.h_min = atof(str.c_str());
    } else if (strcmp(argv[i], "-hmax") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.h_max = atof(str.c_str());
    } else if (strcmp(argv[i], "-rmin") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.rho_min = atof(str.c_str());
    } else if (strcmp(argv[i], "-rmax") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.rho_max = atof(str.c_str());
    } else if (strcmp(argv[i], "-pmin") == 0) {
      if (argv[i + 1] == NULL) {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.logp_min = atof(str.c_str()) * log(10.0);
    } else if (strcmp(argv[i], "-pmax") == 0) {
      if (argv[i + 1] == NULL) {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.logp_max = atof(str.c_str()) * log(10.0);
    } else if (strcmp(argv[i], "-smin") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.s_min = atoi(str.c_str());
    } else if (strcmp(argv[i], "-smax") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.s_max = atoi(str.c_str());
    } else if (strcmp(argv[i], "-gmean") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.geo_mean = atof(str.c_str());
    } else if (strcmp(argv[i], "-hscale") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.h_scale = atof(str.c_str());
    } else if (strcmp(argv[i], "-rscale") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.rho_scale = atof(str.c_str());
    } else if (strcmp(argv[i], "-pscale") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.logp_scale = atof(str.c_str()) * log(10.0);
    } else if (strcmp(argv[i], "-w") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.w_step = atoi(str.c_str());
    } else if (strcmp(argv[i], "-s") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.s_step = atoi(str.c_str());
    } else if (strcmp(argv[i], "-rpace") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.r_pace = atoi(str.c_str());
    } else if (strcmp(argv[i], "-wpace") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.w_pace = atoi(str.c_str());
    } else if (strcmp(argv[i], "-seed") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.randseed = atol(str.c_str());
    } else if (strcmp(argv[i], "-mh") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.n_mh = atoi(str.c_str());
    } else if (strcmp(argv[i], "-predict") == 0) {
      if (cPar.a_mode != 0) {
        cPar.error = true;
        cout << "error! only one of -gk -gs -eigen -vc -lm -lmm -bslmm "
                "-predict -calccor options is allowed."
             << endl;
        break;
      }
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        cPar.a_mode = 41;
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.a_mode = 40 + atoi(str.c_str());
    } else if (strcmp(argv[i], "-windowcm") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.window_cm = atof(str.c_str());
    } else if (strcmp(argv[i], "-windowbp") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.window_bp = atoi(str.c_str());
    } else if (strcmp(argv[i], "-windowns") == 0) {
      if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
        continue;
      }
      ++i;
      str.clear();
      str.assign(argv[i]);
      cPar.window_ns = atoi(str.c_str());
    } else if (strcmp(argv[i], "-debug") == 0) {
      // cPar.mode_debug = true;
      debug_set_debug_mode(true);
    } else if (strcmp(argv[i], "-no-check") == 0) {
      // cPar.mode_check = false;
      debug_set_no_check_mode(true);
    } else if (strcmp(argv[i], "-strict") == 0) {
      // cPar.mode_strict = true;
      debug_set_strict_mode(true);
    } else if (strcmp(argv[i], "-legacy") == 0) {
      debug_set_legacy_mode(true);
    } else {
      cout << "error! unrecognized option: " << argv[i] << endl;
      cPar.error = true;
      continue;
    }
  }

  // Change prediction mode to 43 if the epm file is not provided.
  if (cPar.a_mode == 41 && cPar.file_epm.empty()) {
    cPar.a_mode = 43;
  }

  return;
}

void GEMMA::BatchRun(PARAM &cPar) {
  clock_t time_begin, time_start;
  time_begin = clock();

  // Read Files.
  cout << "Reading Files ... " << endl;
  cPar.ReadFiles();
  if (cPar.error == true) {
    cout << "error! fail to read files. " << endl;
    return;
  }
  cPar.CheckData();
  if (cPar.error == true) {
    cout << "error! fail to check data. " << endl;
    return;
  }

  // Prediction for bslmm
  if (cPar.a_mode == 41 || cPar.a_mode == 42) {
    gsl_vector *y_prdt;

    y_prdt = gsl_vector_safe_alloc(cPar.ni_total - cPar.ni_test);

    // set to zero
    gsl_vector_set_zero(y_prdt);

    PRDT cPRDT;
    cPRDT.CopyFromParam(cPar);

    // add breeding value if needed
    if (!cPar.file_kin.empty() && !cPar.file_ebv.empty()) {
      cout << "Adding Breeding Values ... " << endl;

      gsl_matrix *G = gsl_matrix_safe_alloc(cPar.ni_total, cPar.ni_total);
      gsl_vector *u_hat = gsl_vector_safe_alloc(cPar.ni_test);

      // read kinship matrix and set u_hat
      vector<int> indicator_all;
      size_t c_bv = 0;
      for (size_t i = 0; i < cPar.indicator_idv.size(); i++) {
        indicator_all.push_back(1);
        if (cPar.indicator_bv[i] == 1) {
          gsl_vector_set(u_hat, c_bv, cPar.vec_bv[i]);
          c_bv++;
        }
      }

      ReadFile_kin(cPar.file_kin, indicator_all, cPar.mapID2num, cPar.k_mode,
                   cPar.error, G);
      if (cPar.error == true) {
        cout << "error! fail to read kinship/relatedness file. " << endl;
        return;
      }

      // read u
      cPRDT.AddBV(G, u_hat, y_prdt);

      gsl_matrix_free(G);
      gsl_vector_free(u_hat);
    }

    // add beta
    if (!cPar.file_bfile.empty()) {
      cPRDT.AnalyzePlink(y_prdt);
    } else {
      cPRDT.AnalyzeBimbam(y_prdt);
    }

    // add mu
    gsl_vector_add_constant(y_prdt, cPar.pheno_mean);

    // convert y to probability if needed
    if (cPar.a_mode == 42) {
      double d;
      for (size_t i = 0; i < y_prdt->size; i++) {
        d = gsl_vector_get(y_prdt, i);
        d = gsl_cdf_gaussian_P(d, 1.0);
        gsl_vector_set(y_prdt, i, d);
      }
    }

    cPRDT.CopyToParam(cPar);

    cPRDT.WriteFiles(y_prdt);

    gsl_vector_free(y_prdt);
  }

  // Prediction with kinship matrix only; for one or more phenotypes
  if (cPar.a_mode == 43) {
    // first, use individuals with full phenotypes to obtain estimates of Vg and
    // Ve
    gsl_matrix *Y = gsl_matrix_safe_alloc(cPar.ni_test, cPar.n_ph);
    gsl_matrix *W = gsl_matrix_safe_alloc(Y->size1, cPar.n_cvt);
    gsl_matrix *G = gsl_matrix_safe_alloc(Y->size1, Y->size1);
    gsl_matrix *U = gsl_matrix_safe_alloc(Y->size1, Y->size1);
    gsl_matrix *UtW = gsl_matrix_safe_alloc(Y->size1, W->size2);
    gsl_matrix *UtY = gsl_matrix_safe_alloc(Y->size1, Y->size2);
    gsl_vector *eval = gsl_vector_safe_alloc(Y->size1);

    gsl_matrix *Y_full = gsl_matrix_safe_alloc(cPar.ni_cvt, cPar.n_ph);
    gsl_matrix *W_full = gsl_matrix_safe_alloc(Y_full->size1, cPar.n_cvt);

    // set covariates matrix W and phenotype matrix Y
    // an intercept should be included in W,
    cPar.CopyCvtPhen(W, Y, 0);
    cPar.CopyCvtPhen(W_full, Y_full, 1);

    gsl_matrix *Y_hat = gsl_matrix_safe_alloc(Y_full->size1, cPar.n_ph);
    gsl_matrix *G_full = gsl_matrix_safe_alloc(Y_full->size1, Y_full->size1);
    gsl_matrix *H_full = gsl_matrix_safe_alloc(Y_full->size1 * Y_hat->size2,
                                          Y_full->size1 * Y_hat->size2);

    // read relatedness matrix G, and matrix G_full
    ReadFile_kin(cPar.file_kin, cPar.indicator_idv, cPar.mapID2num, cPar.k_mode,
                 cPar.error, G);
    if (cPar.error == true) {
      cout << "error! fail to read kinship/relatedness file. " << endl;
      return;
    }
    // This is not so elegant. Reads twice to select on idv and then cvt
    ReadFile_kin(cPar.file_kin, cPar.indicator_cvt, cPar.mapID2num, cPar.k_mode,
                 cPar.error, G_full);
    if (cPar.error == true) {
      cout << "error! fail to read kinship/relatedness file. " << endl;
      return;
    }

    // center matrix G
    CenterMatrix(G);
    CenterMatrix(G_full);
    validate_K(G);

    // eigen-decomposition and calculate trace_G
    cout << "Start Eigen-Decomposition..." << endl;
    time_start = clock();
    cPar.trace_G = EigenDecomp_Zeroed(G, U, eval, 0);
    cPar.time_eigen = (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);

    // calculate UtW and Uty
    CalcUtX(U, W, UtW);
    CalcUtX(U, Y, UtY);

    // calculate variance component and beta estimates
    // and then obtain predicted values
    if (cPar.n_ph == 1) {
      gsl_vector *beta = gsl_vector_safe_alloc(W->size2);
      gsl_vector *se_beta = gsl_vector_safe_alloc(W->size2);

      double lambda, logl, vg, ve;
      gsl_vector_view UtY_col = gsl_matrix_column(UtY, 0);

      // obtain estimates
      CalcLambda('R', eval, UtW, &UtY_col.vector, cPar.l_min, cPar.l_max,
                 cPar.n_region, lambda, logl);
      CalcLmmVgVeBeta(eval, UtW, &UtY_col.vector, lambda, vg, ve, beta,
                      se_beta);

      cout << "REMLE estimate for vg in the null model = " << vg << endl;
      cout << "REMLE estimate for ve in the null model = " << ve << endl;
      cPar.vg_remle_null = vg;
      cPar.ve_remle_null = ve;

      // obtain Y_hat from fixed effects
      gsl_vector_view Yhat_col = gsl_matrix_column(Y_hat, 0);
      gsl_blas_dgemv(CblasNoTrans, 1.0, W_full, beta, 0.0, &Yhat_col.vector);

      // obtain H
      gsl_matrix_set_identity(H_full);
      gsl_matrix_scale(H_full, ve);
      gsl_matrix_scale(G_full, vg);
      gsl_matrix_add(H_full, G_full);

      // free matrices
      gsl_vector_free(beta);
      gsl_vector_free(se_beta);
    } else {
      gsl_matrix *Vg = gsl_matrix_safe_alloc(cPar.n_ph, cPar.n_ph);
      gsl_matrix *Ve = gsl_matrix_safe_alloc(cPar.n_ph, cPar.n_ph);
      gsl_matrix *B = gsl_matrix_safe_alloc(cPar.n_ph, W->size2);
      gsl_matrix *se_B = gsl_matrix_safe_alloc(cPar.n_ph, W->size2);

      // obtain estimates
      CalcMvLmmVgVeBeta(eval, UtW, UtY, cPar.em_iter, cPar.nr_iter,
                        cPar.em_prec, cPar.nr_prec, cPar.l_min, cPar.l_max,
                        cPar.n_region, Vg, Ve, B, se_B);

      cout << "REMLE estimate for Vg in the null model: " << endl;
      for (size_t i = 0; i < Vg->size1; i++) {
        for (size_t j = 0; j <= i; j++) {
          cout << tab(j) << gsl_matrix_get(Vg, i, j);
        }
        cout << endl;
      }
      cout << "REMLE estimate for Ve in the null model: " << endl;
      for (size_t i = 0; i < Ve->size1; i++) {
        for (size_t j = 0; j <= i; j++) {
          cout << tab(j) << gsl_matrix_get(Ve, i, j);
        }
        cout << endl;
      }
      cPar.Vg_remle_null.clear();
      cPar.Ve_remle_null.clear();
      for (size_t i = 0; i < Vg->size1; i++) {
        for (size_t j = i; j < Vg->size2; j++) {
          cPar.Vg_remle_null.push_back(gsl_matrix_get(Vg, i, j));
          cPar.Ve_remle_null.push_back(gsl_matrix_get(Ve, i, j));
        }
      }

      // obtain Y_hat from fixed effects
      gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, W_full, B, 0.0, Y_hat);

      // obtain H
      KroneckerSym(G_full, Vg, H_full);
      for (size_t i = 0; i < G_full->size1; i++) {
        gsl_matrix_view H_sub = gsl_matrix_submatrix(
            H_full, i * Ve->size1, i * Ve->size2, Ve->size1, Ve->size2);
        gsl_matrix_add(&H_sub.matrix, Ve);
      }

      // free matrices
      gsl_matrix_free(Vg);
      gsl_matrix_free(Ve);
      gsl_matrix_free(B);
      gsl_matrix_free(se_B);
    }

    PRDT cPRDT;

    cPRDT.CopyFromParam(cPar);

    cout << "Predicting Missing Phentypes ... " << endl;
    time_start = clock();
    cPRDT.MvnormPrdt(Y_hat, H_full, Y_full);
    cPar.time_opt = (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);

    cPRDT.WriteFiles(Y_full);

    gsl_matrix_free(Y);
    gsl_matrix_free(W);
    gsl_matrix_free(G);
    gsl_matrix_free(U);
    gsl_matrix_free(UtW);
    gsl_matrix_free(UtY);
    gsl_vector_free(eval);

    gsl_matrix_free(Y_full);
    gsl_matrix_free(Y_hat);
    gsl_matrix_free(W_full);
    gsl_matrix_free(G_full);
    gsl_matrix_free(H_full);
  }

  // Generate Kinship matrix (optionally using LOCO)
  if (cPar.a_mode == 21 || cPar.a_mode == 22) {
    cout << "Calculating Relatedness Matrix ... " << endl;

    gsl_matrix *G = gsl_matrix_safe_alloc(cPar.ni_total, cPar.ni_total);
    enforce_msg(G, "allocate G"); // just to be sure

    time_start = clock();
    cPar.CalcKin(G);

    cPar.time_G = (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);
    if (cPar.error == true) {
      cout << "error! fail to calculate relatedness matrix. " << endl;
      return;
    }

    // Now we have the Kinship matrix test it
    validate_K(G);

    if (cPar.a_mode == 21) {
      cPar.WriteMatrix(G, "cXX");
    } else {
      cPar.WriteMatrix(G, "sXX");
    }

    gsl_matrix_free(G);
  }

  // Compute the LDSC weights (not implemented yet)
  if (cPar.a_mode == 72) {
    cout << "Calculating Weights ... " << endl;

    VARCOV cVarcov;
    cVarcov.CopyFromParam(cPar);

    if (!cPar.file_bfile.empty()) {
      cVarcov.AnalyzePlink();
    } else {
      cVarcov.AnalyzeBimbam();
    }

    cVarcov.CopyToParam(cPar);
  }

  // Compute the S matrix (and its variance), that is used for
  // variance component estimation using summary statistics.
  if (cPar.a_mode == 25 || cPar.a_mode == 26) {
    cout << "Calculating the S Matrix ... " << endl;

    gsl_matrix *S = gsl_matrix_safe_alloc(cPar.n_vc * 2, cPar.n_vc);
    gsl_vector *ns = gsl_vector_safe_alloc(cPar.n_vc + 1);
    gsl_matrix_set_zero(S);
    gsl_vector_set_zero(ns);

    gsl_matrix_view S_mat = gsl_matrix_submatrix(S, 0, 0, cPar.n_vc, cPar.n_vc);
    gsl_matrix_view Svar_mat =
        gsl_matrix_submatrix(S, cPar.n_vc, 0, cPar.n_vc, cPar.n_vc);
    gsl_vector_view ns_vec = gsl_vector_subvector(ns, 0, cPar.n_vc);

    gsl_matrix *K = gsl_matrix_safe_alloc(cPar.ni_test, cPar.n_vc * cPar.ni_test);
    gsl_matrix *A = gsl_matrix_safe_alloc(cPar.ni_test, cPar.n_vc * cPar.ni_test);
    gsl_matrix_set_zero(K);
    gsl_matrix_set_zero(A);

    gsl_vector *y = gsl_vector_safe_alloc(cPar.ni_test);
    gsl_matrix *W = gsl_matrix_safe_alloc(cPar.ni_test, cPar.n_cvt);

    cPar.CopyCvtPhen(W, y, 0);

    set<string> setSnps_beta;
    map<string, double> mapRS2wA, mapRS2wK;

    cPar.ObtainWeight(setSnps_beta, mapRS2wK);

    time_start = clock();
    cPar.CalcS(mapRS2wA, mapRS2wK, W, A, K, &S_mat.matrix, &Svar_mat.matrix,
               &ns_vec.vector);
    cPar.time_G = (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);
    if (cPar.error == true) {
      cout << "error! fail to calculate the S matrix. " << endl;
      return;
    }

    gsl_vector_set(ns, cPar.n_vc, cPar.ni_test);

    cPar.WriteMatrix(S, "S");
    cPar.WriteVector(ns, "size");
    cPar.WriteVar("snps");

    gsl_matrix_free(S);
    gsl_vector_free(ns);

    gsl_matrix_free(A);
    gsl_matrix_free(K);

    gsl_vector_free(y);
    gsl_matrix_free(K);
  }

  // Compute the q vector, that is used for variance component estimation using
  // summary statistics
  if (cPar.a_mode == 27 || cPar.a_mode == 28) {
    gsl_matrix *Vq = gsl_matrix_safe_alloc(cPar.n_vc, cPar.n_vc);
    gsl_vector *q = gsl_vector_safe_alloc(cPar.n_vc);
    gsl_vector *s = gsl_vector_safe_alloc(cPar.n_vc + 1);
    gsl_vector_set_zero(q);
    gsl_vector_set_zero(s);

    gsl_vector_view s_vec = gsl_vector_subvector(s, 0, cPar.n_vc);

    vector<size_t> vec_cat, vec_ni;
    vector<double> vec_weight, vec_z2;
    map<string, double> mapRS2weight;
    mapRS2weight.clear();

    time_start = clock();
    ReadFile_beta(cPar.file_beta, cPar.mapRS2cat, mapRS2weight, vec_cat, vec_ni,
                  vec_weight, vec_z2, cPar.ni_total, cPar.ns_total,
                  cPar.ns_test);
    cout << "## number of total individuals = " << cPar.ni_total << endl;
    cout << "## number of total SNPs/var = " << cPar.ns_total << endl;
    cout << "## number of analyzed SNPs/var = " << cPar.ns_test << endl;
    cout << "## number of variance components = " << cPar.n_vc << endl;
    cout << "Calculating the q vector ... " << endl;
    Calcq(cPar.n_block, vec_cat, vec_ni, vec_weight, vec_z2, Vq, q,
          &s_vec.vector);
    cPar.time_G = (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);

    if (cPar.error == true) {
      cout << "error! fail to calculate the q vector. " << endl;
      return;
    }

    gsl_vector_set(s, cPar.n_vc, cPar.ni_total);

    cPar.WriteMatrix(Vq, "Vq");
    cPar.WriteVector(q, "q");
    cPar.WriteVector(s, "size");
    gsl_matrix_free(Vq);
    gsl_vector_free(q);
    gsl_vector_free(s);
  }

  // Calculate SNP covariance.
  if (cPar.a_mode == 71) {
    VARCOV cVarcov;
    cVarcov.CopyFromParam(cPar);

    if (!cPar.file_bfile.empty()) {
      cVarcov.AnalyzePlink();
    } else {
      cVarcov.AnalyzeBimbam();
    }

    cVarcov.CopyToParam(cPar);
  }

  // LM.
  if (cPar.a_mode == 51 || cPar.a_mode == 52 || cPar.a_mode == 53 ||
      cPar.a_mode == 54) { // Fit LM
    gsl_matrix *Y = gsl_matrix_safe_alloc(cPar.ni_test, cPar.n_ph);
    gsl_matrix *W = gsl_matrix_safe_alloc(Y->size1, cPar.n_cvt);

    // set covariates matrix W and phenotype matrix Y
    // an intercept should be included in W,
    cPar.CopyCvtPhen(W, Y, 0);

    // Fit LM or mvLM
    if (cPar.n_ph == 1) {
      LM cLm;
      cLm.CopyFromParam(cPar);

      gsl_vector_view Y_col = gsl_matrix_column(Y, 0);

      if (!cPar.file_gene.empty()) {
        cLm.AnalyzeGene(W,
                        &Y_col.vector); // y is the predictor, not the phenotype
      } else if (!cPar.file_bfile.empty()) {
        cLm.AnalyzePlink(W, &Y_col.vector);
      } else {
        cLm.AnalyzeBimbam(W, &Y_col.vector);
      }

      cLm.WriteFiles();
      cLm.CopyToParam(cPar);
    }
    // release all matrices and vectors
    gsl_matrix_free(Y);
    gsl_matrix_free(W);
  }

  // VC estimation with one or multiple kinship matrices
  // REML approach only
  // if file_kin or file_ku/kd is provided, then a_mode is changed to 5 already,
  // in param.cpp
  // for one phenotype only;
  if (cPar.a_mode == 61 || cPar.a_mode == 62 || cPar.a_mode == 63) {
    if (!cPar.file_beta.empty()) {
      // need to obtain a common set of SNPs between beta file and the genotype
      // file; these are saved in mapRS2wA and mapRS2wK
      // normalize the weight in mapRS2wK to have an average of one; each
      // element of mapRS2wA is 1
      // update indicator_snps, so that the numbers are in accordance with
      // mapRS2wK
      set<string> setSnps_beta;
      ReadFile_snps_header(cPar.file_beta, setSnps_beta);

      map<string, double> mapRS2wA, mapRS2wK;
      cPar.ObtainWeight(setSnps_beta, mapRS2wK);

      cPar.UpdateSNP(mapRS2wK);

      // Setup matrices and vectors.
      gsl_matrix *S = gsl_matrix_safe_alloc(cPar.n_vc * 2, cPar.n_vc);
      gsl_matrix *Vq = gsl_matrix_safe_alloc(cPar.n_vc, cPar.n_vc);
      gsl_vector *q = gsl_vector_safe_alloc(cPar.n_vc);
      gsl_vector *s = gsl_vector_safe_alloc(cPar.n_vc + 1);

      gsl_matrix *K = gsl_matrix_safe_alloc(cPar.ni_test, cPar.n_vc * cPar.ni_test);
      gsl_matrix *A = gsl_matrix_safe_alloc(cPar.ni_test, cPar.n_vc * cPar.ni_test);

      gsl_vector *y = gsl_vector_safe_alloc(cPar.ni_test);
      gsl_matrix *W = gsl_matrix_safe_alloc(cPar.ni_test, cPar.n_cvt);

      gsl_matrix_set_zero(K);
      gsl_matrix_set_zero(A);

      gsl_matrix_set_zero(S);
      gsl_matrix_set_zero(Vq);
      gsl_vector_set_zero(q);
      gsl_vector_set_zero(s);

      cPar.CopyCvtPhen(W, y, 0);

      gsl_matrix_view S_mat =
          gsl_matrix_submatrix(S, 0, 0, cPar.n_vc, cPar.n_vc);
      gsl_matrix_view Svar_mat =
          gsl_matrix_submatrix(S, cPar.n_vc, 0, cPar.n_vc, cPar.n_vc);
      gsl_vector_view s_vec = gsl_vector_subvector(s, 0, cPar.n_vc);

      vector<size_t> vec_cat, vec_ni;
      vector<double> vec_weight, vec_z2;

      // read beta, based on the mapRS2wK
      ReadFile_beta(cPar.file_beta, cPar.mapRS2cat, mapRS2wK, vec_cat, vec_ni,
                    vec_weight, vec_z2, cPar.ni_study, cPar.ns_study,
                    cPar.ns_test);

      cout << "Study Panel: " << endl;
      cout << "## number of total individuals = " << cPar.ni_study << endl;
      cout << "## number of total SNPs/var = " << cPar.ns_study << endl;
      cout << "## number of analyzed SNPs/var = " << cPar.ns_test << endl;
      cout << "## number of variance components = " << cPar.n_vc << endl;

      // compute q
      Calcq(cPar.n_block, vec_cat, vec_ni, vec_weight, vec_z2, Vq, q,
            &s_vec.vector);

      // compute S
      time_start = clock();
      cPar.CalcS(mapRS2wA, mapRS2wK, W, A, K, &S_mat.matrix, &Svar_mat.matrix,
                 &s_vec.vector);
      cPar.time_G += (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);
      if (cPar.error == true) {
        cout << "error! fail to calculate the S matrix. " << endl;
        return;
      }

      // compute vc estimates
      CalcVCss(Vq, &S_mat.matrix, &Svar_mat.matrix, q, &s_vec.vector,
               cPar.ni_study, cPar.v_pve, cPar.v_se_pve, cPar.pve_total,
               cPar.se_pve_total, cPar.v_sigma2, cPar.v_se_sigma2,
               cPar.v_enrich, cPar.v_se_enrich);

      assert(!has_nan(cPar.v_se_pve));

      // if LDSC weights, then compute the weights and run the above steps again
      if (cPar.a_mode == 62) {
        // compute the weights and normalize the weights for A
        cPar.UpdateWeight(1, mapRS2wK, cPar.ni_study, &s_vec.vector, mapRS2wA);

        // read beta file again, and update weigths vector
        ReadFile_beta(cPar.file_beta, cPar.mapRS2cat, mapRS2wA, vec_cat, vec_ni,
                      vec_weight, vec_z2, cPar.ni_study, cPar.ns_total,
                      cPar.ns_test);

        // compute q
        Calcq(cPar.n_block, vec_cat, vec_ni, vec_weight, vec_z2, Vq, q,
              &s_vec.vector);

        // compute S
        time_start = clock();
        cPar.CalcS(mapRS2wA, mapRS2wK, W, A, K, &S_mat.matrix, &Svar_mat.matrix,
                   &s_vec.vector);
        cPar.time_G += (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);
        if (cPar.error == true) {
          cout << "error! fail to calculate the S matrix. " << endl;
          return;
        }

        // compute vc estimates
        CalcVCss(Vq, &S_mat.matrix, &Svar_mat.matrix, q, &s_vec.vector,
                 cPar.ni_study, cPar.v_pve, cPar.v_se_pve, cPar.pve_total,
                 cPar.se_pve_total, cPar.v_sigma2, cPar.v_se_sigma2,
                 cPar.v_enrich, cPar.v_se_enrich);
        assert(!has_nan(cPar.v_se_pve));
      }


      gsl_vector_set(s, cPar.n_vc, cPar.ni_test);

      cPar.WriteMatrix(S, "S");
      cPar.WriteMatrix(Vq, "Vq");
      cPar.WriteVector(q, "q");
      cPar.WriteVector(s, "size");

      gsl_matrix_free(S);
      gsl_matrix_free(Vq);
      gsl_vector_free(q);
      gsl_vector_free(s);

      gsl_matrix_free(A);
      gsl_matrix_free(K);
      gsl_vector_free(y);
      gsl_matrix_free(W);
    } else if (!cPar.file_study.empty() || !cPar.file_mstudy.empty()) {
      if (!cPar.file_study.empty()) {
        string sfile = cPar.file_study + ".size.txt";
        CountFileLines(sfile, cPar.n_vc);
      } else {
        string file_name;
        igzstream infile(cPar.file_mstudy.c_str(), igzstream::in);
        if (!infile) {
          cout << "error! fail to open mstudy file: " << cPar.file_study
               << endl;
          return;
        }

        safeGetline(infile, file_name);

        infile.clear();
        infile.close();

        string sfile = file_name + ".size.txt";
        CountFileLines(sfile, cPar.n_vc);
      }

      cPar.n_vc = cPar.n_vc - 1;

      gsl_matrix *S = gsl_matrix_safe_alloc(2 * cPar.n_vc, cPar.n_vc);
      gsl_matrix *Vq = gsl_matrix_safe_alloc(cPar.n_vc, cPar.n_vc);
      // gsl_matrix *V=gsl_matrix_safe_alloc (cPar.n_vc+1,
      // (cPar.n_vc*(cPar.n_vc+1))/2*(cPar.n_vc+1) );
      // gsl_matrix *Vslope=gsl_matrix_safe_alloc (n_lines+1,
      // (n_lines*(n_lines+1))/2*(n_lines+1) );
      gsl_vector *q = gsl_vector_safe_alloc(cPar.n_vc);
      gsl_vector *s_study = gsl_vector_safe_alloc(cPar.n_vc);
      gsl_vector *s_ref = gsl_vector_safe_alloc(cPar.n_vc);
      gsl_vector *s = gsl_vector_safe_alloc(cPar.n_vc + 1);

      gsl_matrix_set_zero(S);
      gsl_matrix_view S_mat =
          gsl_matrix_submatrix(S, 0, 0, cPar.n_vc, cPar.n_vc);
      gsl_matrix_view Svar_mat =
          gsl_matrix_submatrix(S, cPar.n_vc, 0, cPar.n_vc, cPar.n_vc);

      gsl_matrix_set_zero(Vq);
      // gsl_matrix_set_zero(V);
      // gsl_matrix_set_zero(Vslope);
      gsl_vector_set_zero(q);
      gsl_vector_set_zero(s_study);
      gsl_vector_set_zero(s_ref);

      if (!cPar.file_study.empty()) {
        ReadFile_study(cPar.file_study, Vq, q, s_study, cPar.ni_study);
      } else {
        ReadFile_mstudy(cPar.file_mstudy, Vq, q, s_study, cPar.ni_study);
      }

      if (!cPar.file_ref.empty()) {
        ReadFile_ref(cPar.file_ref, &S_mat.matrix, &Svar_mat.matrix, s_ref,
                     cPar.ni_ref);
      } else {
        ReadFile_mref(cPar.file_mref, &S_mat.matrix, &Svar_mat.matrix, s_ref,
                      cPar.ni_ref);
      }

      cout << "## number of variance components = " << cPar.n_vc << endl;
      cout << "## number of individuals in the sample = " << cPar.ni_study
           << endl;
      cout << "## number of individuals in the reference = " << cPar.ni_ref
           << endl;

      CalcVCss(Vq, &S_mat.matrix, &Svar_mat.matrix, q, s_study, cPar.ni_study,
               cPar.v_pve, cPar.v_se_pve, cPar.pve_total, cPar.se_pve_total,
               cPar.v_sigma2, cPar.v_se_sigma2, cPar.v_enrich,
               cPar.v_se_enrich);
      assert(!has_nan(cPar.v_se_pve));

      gsl_vector_view s_sub = gsl_vector_subvector(s, 0, cPar.n_vc);
      gsl_vector_memcpy(&s_sub.vector, s_ref);
      gsl_vector_set(s, cPar.n_vc, cPar.ni_ref);

      cPar.WriteMatrix(S, "S");
      cPar.WriteMatrix(Vq, "Vq");
      cPar.WriteVector(q, "q");
      cPar.WriteVector(s, "size");

      gsl_matrix_free(S);
      gsl_matrix_free(Vq);
      // gsl_matrix_free (V);
      // gsl_matrix_free (Vslope);
      gsl_vector_free(q);
      gsl_vector_free(s_study);
      gsl_vector_free(s_ref);
      gsl_vector_free(s);
    } else {
      gsl_matrix *Y = gsl_matrix_safe_alloc(cPar.ni_test, cPar.n_ph);
      gsl_matrix *W = gsl_matrix_safe_alloc(Y->size1, cPar.n_cvt);
      gsl_matrix *G = gsl_matrix_safe_alloc(Y->size1, Y->size1 * cPar.n_vc);

      // set covariates matrix W and phenotype matrix Y
      // an intercept should be included in W,
      cPar.CopyCvtPhen(W, Y, 0);

      // read kinship matrices
      if (!(cPar.file_mk).empty()) {
        ReadFile_mk(cPar.file_mk, cPar.indicator_idv, cPar.mapID2num,
                    cPar.k_mode, cPar.error, G);
        if (cPar.error == true) {
          cout << "error! fail to read kinship/relatedness file. " << endl;
          return;
        }

        // center matrix G, and obtain v_traceG
        double d = 0;
        (cPar.v_traceG).clear();
        for (size_t i = 0; i < cPar.n_vc; i++) {
          gsl_matrix_view G_sub =
              gsl_matrix_submatrix(G, 0, i * G->size1, G->size1, G->size1);
          CenterMatrix(&G_sub.matrix);
          d = 0;
          for (size_t j = 0; j < G->size1; j++) {
            d += gsl_matrix_get(&G_sub.matrix, j, j);
          }
          d /= (double)G->size1;
          (cPar.v_traceG).push_back(d);
        }
      } else if (!(cPar.file_kin).empty()) {
        ReadFile_kin(cPar.file_kin, cPar.indicator_idv, cPar.mapID2num,
                     cPar.k_mode, cPar.error, G);
        if (cPar.error == true) {
          cout << "error! fail to read kinship/relatedness file. " << endl;
          return;
        }

        // center matrix G
        CenterMatrix(G);
        validate_K(G);

        (cPar.v_traceG).clear();
        double d = 0;
        for (size_t j = 0; j < G->size1; j++) {
          d += gsl_matrix_get(G, j, j);
        }
        d /= (double)G->size1;
        (cPar.v_traceG).push_back(d);
      }
      // fit multiple variance components
      if (cPar.n_ph == 1) {
        //		  if (cPar.n_vc==1) {
        //		  } else {
        gsl_vector_view Y_col = gsl_matrix_column(Y, 0);
        VC cVc;
        cVc.CopyFromParam(cPar);
        if (cPar.a_mode == 61) {
          cVc.CalcVChe(G, W, &Y_col.vector);
        } else if (cPar.a_mode == 62) {
          cVc.CalcVCreml(cPar.noconstrain, G, W, &Y_col.vector);
        } else {
          cVc.CalcVCacl(G, W, &Y_col.vector);
        }
        cVc.CopyToParam(cPar);
        // obtain pve from sigma2
        // obtain se_pve from se_sigma2

        //}
      }
    }
  }

  // compute confidence intervals with additional summary statistics
  // we do not check the sign of z-scores here, but they have to be matched with
  // the genotypes
  if (cPar.a_mode == 66 || cPar.a_mode == 67) {
    // read reference file first
    gsl_matrix *S = gsl_matrix_safe_alloc(cPar.n_vc, cPar.n_vc);
    gsl_matrix *Svar = gsl_matrix_safe_alloc(cPar.n_vc, cPar.n_vc);
    gsl_vector *s_ref = gsl_vector_safe_alloc(cPar.n_vc);

    gsl_matrix_set_zero(S);
    gsl_matrix_set_zero(Svar);
    gsl_vector_set_zero(s_ref);

    if (!cPar.file_ref.empty()) {
      ReadFile_ref(cPar.file_ref, S, Svar, s_ref, cPar.ni_ref);
    } else {
      ReadFile_mref(cPar.file_mref, S, Svar, s_ref, cPar.ni_ref);
    }

    // need to obtain a common set of SNPs between beta file and the genotype
    // file; these are saved in mapRS2wA and mapRS2wK
    // normalize the weight in mapRS2wK to have an average of one; each element
    // of mapRS2wA is 1
    set<string> setSnps_beta;
    ReadFile_snps_header(cPar.file_beta, setSnps_beta);

    // obtain the weights for wA, which contains the SNP weights for SNPs used
    // in the model
    map<string, double> mapRS2wK;
    cPar.ObtainWeight(setSnps_beta, mapRS2wK);

    // set up matrices and vector
    gsl_matrix *Xz = gsl_matrix_safe_alloc(cPar.ni_test, cPar.n_vc);
    gsl_matrix *XWz = gsl_matrix_safe_alloc(cPar.ni_test, cPar.n_vc);
    gsl_matrix *XtXWz =
        gsl_matrix_safe_alloc(mapRS2wK.size(), cPar.n_vc * cPar.n_vc);
    gsl_vector *w = gsl_vector_safe_alloc(mapRS2wK.size());
    gsl_vector *w1 = gsl_vector_safe_alloc(mapRS2wK.size());
    gsl_vector *z = gsl_vector_safe_alloc(mapRS2wK.size());
    gsl_vector *s_vec = gsl_vector_safe_alloc(cPar.n_vc);

    vector<size_t> vec_cat, vec_size;
    vector<double> vec_z;

    map<string, double> mapRS2z, mapRS2wA;
    map<string, string> mapRS2A1;
    string file_str;

    // update s_vec, the number of snps in each category
    for (size_t i = 0; i < cPar.n_vc; i++) {
      vec_size.push_back(0);
    }

    for (map<string, double>::const_iterator it = mapRS2wK.begin();
         it != mapRS2wK.end(); ++it) {
      vec_size[cPar.mapRS2cat[it->first]]++;
    }

    for (size_t i = 0; i < cPar.n_vc; i++) {
      gsl_vector_set(s_vec, i, vec_size[i]);
    }

    // update mapRS2wA using v_pve and s_vec
    if (cPar.a_mode == 66) {
      for (map<string, double>::const_iterator it = mapRS2wK.begin();
           it != mapRS2wK.end(); ++it) {
        mapRS2wA[it->first] = 1;
      }
    } else {
      cPar.UpdateWeight(0, mapRS2wK, cPar.ni_test, s_vec, mapRS2wA);
    }

    // read in z-scores based on allele 0, and save that into a vector
    ReadFile_beta(cPar.file_beta, mapRS2wA, mapRS2A1, mapRS2z);

    // update snp indicator, save weights to w, save z-scores to vec_z, save
    // category label to vec_cat
    // sign of z is determined by matching alleles
    cPar.UpdateSNPnZ(mapRS2wA, mapRS2A1, mapRS2z, w, z, vec_cat);

    // compute an n by k matrix of X_iWz
    cout << "Calculating Xz ... " << endl;

    gsl_matrix_set_zero(Xz);
    gsl_vector_set_all(w1, 1);

    if (!cPar.file_bfile.empty()) {
      file_str = cPar.file_bfile + ".bed";
      PlinkXwz(file_str, cPar.d_pace, cPar.indicator_idv, cPar.indicator_snp,
               vec_cat, w1, z, 0, Xz);
    } else if (!cPar.file_geno.empty()) {
      BimbamXwz(cPar.file_geno, cPar.d_pace, cPar.indicator_idv,
                cPar.indicator_snp, vec_cat, w1, z, 0, Xz);
    } else if (!cPar.file_mbfile.empty()) {
      MFILEXwz(1, cPar.file_mbfile, cPar.d_pace, cPar.indicator_idv,
               cPar.mindicator_snp, vec_cat, w1, z, Xz);
    } else if (!cPar.file_mgeno.empty()) {
      MFILEXwz(0, cPar.file_mgeno, cPar.d_pace, cPar.indicator_idv,
               cPar.mindicator_snp, vec_cat, w1, z, Xz);
    }
    if (cPar.a_mode == 66) {
      gsl_matrix_memcpy(XWz, Xz);
    } else if (cPar.a_mode == 67) {
      cout << "Calculating XWz ... " << endl;

      gsl_matrix_set_zero(XWz);

      if (!cPar.file_bfile.empty()) {
        file_str = cPar.file_bfile + ".bed";
        PlinkXwz(file_str, cPar.d_pace, cPar.indicator_idv, cPar.indicator_snp,
                 vec_cat, w, z, 0, XWz);
      } else if (!cPar.file_geno.empty()) {
        BimbamXwz(cPar.file_geno, cPar.d_pace, cPar.indicator_idv,
                  cPar.indicator_snp, vec_cat, w, z, 0, XWz);
      } else if (!cPar.file_mbfile.empty()) {
        MFILEXwz(1, cPar.file_mbfile, cPar.d_pace, cPar.indicator_idv,
                 cPar.mindicator_snp, vec_cat, w, z, XWz);
      } else if (!cPar.file_mgeno.empty()) {
        MFILEXwz(0, cPar.file_mgeno, cPar.d_pace, cPar.indicator_idv,
                 cPar.mindicator_snp, vec_cat, w, z, XWz);
      }
    }
    // compute an p by k matrix of X_j^TWX_iWz
    cout << "Calculating XtXWz ... " << endl;
    gsl_matrix_set_zero(XtXWz);

    if (!cPar.file_bfile.empty()) {
      file_str = cPar.file_bfile + ".bed";
      PlinkXtXwz(file_str, cPar.d_pace, cPar.indicator_idv, cPar.indicator_snp,
                 XWz, 0, XtXWz);
    } else if (!cPar.file_geno.empty()) {
      BimbamXtXwz(cPar.file_geno, cPar.d_pace, cPar.indicator_idv,
                  cPar.indicator_snp, XWz, 0, XtXWz);
    } else if (!cPar.file_mbfile.empty()) {
      MFILEXtXwz(1, cPar.file_mbfile, cPar.d_pace, cPar.indicator_idv,
                 cPar.mindicator_snp, XWz, XtXWz);
    } else if (!cPar.file_mgeno.empty()) {
      MFILEXtXwz(0, cPar.file_mgeno, cPar.d_pace, cPar.indicator_idv,
                 cPar.mindicator_snp, XWz, XtXWz);
    }
    // compute confidence intervals
    CalcCIss(Xz, XWz, XtXWz, S, Svar, w, z, s_vec, vec_cat, cPar.v_pve,
             cPar.v_se_pve, cPar.pve_total, cPar.se_pve_total, cPar.v_sigma2,
             cPar.v_se_sigma2, cPar.v_enrich, cPar.v_se_enrich);
    assert(!has_nan(cPar.v_se_pve));

    gsl_matrix_free(S);
    gsl_matrix_free(Svar);
    gsl_vector_free(s_ref);

    gsl_matrix_free(Xz);
    gsl_matrix_free(XWz);
    gsl_matrix_free(XtXWz);
    gsl_vector_free(w);
    gsl_vector_free(w1);
    gsl_vector_free(z);
    gsl_vector_free(s_vec);
  }

  // LMM or mvLMM or Eigen-Decomposition
  if (cPar.a_mode == 1 || cPar.a_mode == 2 || cPar.a_mode == 3 ||
      cPar.a_mode == 4 || cPar.a_mode == 5 ||
      cPar.a_mode == 31) { // Fit LMM or mvLMM or eigen
    gsl_matrix *Y = gsl_matrix_safe_alloc(cPar.ni_test, cPar.n_ph);
    enforce_msg(Y, "allocate Y"); // just to be sure
    gsl_matrix *W = gsl_matrix_safe_alloc(Y->size1, cPar.n_cvt);
    gsl_matrix *B = gsl_matrix_safe_alloc(Y->size2, W->size2); // B is a d by c
                                                          // matrix
    gsl_matrix *se_B = gsl_matrix_safe_alloc(Y->size2, W->size2);
    gsl_matrix *G = gsl_matrix_safe_alloc(Y->size1, Y->size1);
    gsl_matrix *U = gsl_matrix_safe_alloc(Y->size1, Y->size1);
    gsl_matrix *UtW = gsl_matrix_calloc(Y->size1, W->size2);
    gsl_matrix *UtY = gsl_matrix_calloc(Y->size1, Y->size2);
    gsl_vector *eval = gsl_vector_calloc(Y->size1);
    gsl_vector *env = gsl_vector_safe_alloc(Y->size1);
    gsl_vector *weight = gsl_vector_safe_alloc(Y->size1);
    assert_issue(is_issue(26), UtY->data[0] == 0.0);

    // set covariates matrix W and phenotype matrix Y
    // an intercept should be included in W,
    cPar.CopyCvtPhen(W, Y, 0);
    if (!cPar.file_gxe.empty()) {
      cPar.CopyGxe(env);
    }

    // read relatedness matrix G
    if (!(cPar.file_kin).empty()) {
      ReadFile_kin(cPar.file_kin, cPar.indicator_idv, cPar.mapID2num,
                   cPar.k_mode, cPar.error, G);
      if (cPar.error == true) {
        cout << "error! fail to read kinship/relatedness file. " << endl;
        return;
      }

      // center matrix G
      CenterMatrix(G);
      validate_K(G);

      // is residual weights are provided, then
      if (!cPar.file_weight.empty()) {
        cPar.CopyWeight(weight);
        double d, wi, wj;
        for (size_t i = 0; i < G->size1; i++) {
          wi = gsl_vector_get(weight, i);
          for (size_t j = i; j < G->size2; j++) {
            wj = gsl_vector_get(weight, j);
            d = gsl_matrix_get(G, i, j);
            if (wi <= 0 || wj <= 0) {
              d = 0;
            } else {
              d /= sqrt(wi * wj);
            }
            gsl_matrix_set(G, i, j, d);
            if (j != i) {
              gsl_matrix_set(G, j, i, d);
            }
          }
        }
      }

      // eigen-decomposition and calculate trace_G
      cout << "Start Eigen-Decomposition..." << endl;
      time_start = clock();

      if (cPar.a_mode == 31) {
        cPar.trace_G = EigenDecomp_Zeroed(G, U, eval, 1);
      } else {
        cPar.trace_G = EigenDecomp_Zeroed(G, U, eval, 0);
      }

      if (!cPar.file_weight.empty()) {
        double wi;
        for (size_t i = 0; i < U->size1; i++) {
          wi = gsl_vector_get(weight, i);
          if (wi <= 0) {
            wi = 0;
          } else {
            wi = sqrt(wi);
          }
          gsl_vector_view Urow = gsl_matrix_row(U, i);
          gsl_vector_scale(&Urow.vector, wi);
        }
      }

      cPar.time_eigen =
          (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);
    } else {
      ReadFile_eigenU(cPar.file_ku, cPar.error, U);
      if (cPar.error == true) {
        cout << "error! fail to read the U file. " << endl;
        return;
      }

      ReadFile_eigenD(cPar.file_kd, cPar.error, eval);
      if (cPar.error == true) {
        cout << "error! fail to read the D file. " << endl;
        return;
      }

      cPar.trace_G = 0.0;
      for (size_t i = 0; i < eval->size; i++) {
        if (gsl_vector_get(eval, i) < 1e-10) {
          gsl_vector_set(eval, i, 0);
        }
        cPar.trace_G += gsl_vector_get(eval, i);
      }
      cPar.trace_G /= (double)eval->size;
    }

    if (cPar.a_mode == 31) {
      cPar.WriteMatrix(U, "eigenU");
      cPar.WriteVector(eval, "eigenD");
    } else if (!cPar.file_gene.empty()) {
      // calculate UtW and Uty
      CalcUtX(U, W, UtW);
      CalcUtX(U, Y, UtY);

      assert_issue(is_issue(26), ROUND(UtY->data[0]) == -16.6143);

      LMM cLmm;
      cLmm.CopyFromParam(cPar);

      gsl_vector_view Y_col = gsl_matrix_column(Y, 0);
      gsl_vector_view UtY_col = gsl_matrix_column(UtY, 0);

      cLmm.AnalyzeGene(U, eval, UtW, &UtY_col.vector, W,
                       &Y_col.vector); // y is the predictor, not the phenotype

      cLmm.WriteFiles();
      cLmm.CopyToParam(cPar);
    } else {
      // calculate UtW and Uty
      CalcUtX(U, W, UtW);
      CalcUtX(U, Y, UtY);
      assert_issue(is_issue(26), ROUND(UtY->data[0]) == -16.6143);

      // calculate REMLE/MLE estimate and pve for univariate model
      if (cPar.n_ph == 1) { // one phenotype
        gsl_vector_view beta = gsl_matrix_row(B, 0);
        gsl_vector_view se_beta = gsl_matrix_row(se_B, 0);
        gsl_vector_view UtY_col = gsl_matrix_column(UtY, 0);

        assert_issue(is_issue(26), ROUND(UtY->data[0]) == -16.6143);

        CalcLambda('L', eval, UtW, &UtY_col.vector, cPar.l_min, cPar.l_max,
                   cPar.n_region, cPar.l_mle_null, cPar.logl_mle_H0);
        assert(!std::isnan(UtY->data[0]));

        CalcLmmVgVeBeta(eval, UtW, &UtY_col.vector, cPar.l_mle_null,
                        cPar.vg_mle_null, cPar.ve_mle_null, &beta.vector,
                        &se_beta.vector);

        assert(!std::isnan(UtY->data[0]));

        cPar.beta_mle_null.clear();
        cPar.se_beta_mle_null.clear();
        assert(!std::isnan(B->data[0]));
        assert(!std::isnan(se_B->data[0]));
        for (size_t i = 0; i < B->size2; i++) {
          cPar.beta_mle_null.push_back(gsl_matrix_get(B, 0, i));
          cPar.se_beta_mle_null.push_back(gsl_matrix_get(se_B, 0, i));
        }
        assert(!std::isnan(UtY->data[0]));
        assert(!std::isnan(cPar.beta_mle_null.front()));
        assert(!std::isnan(cPar.se_beta_mle_null.front()));

        CalcLambda('R', eval, UtW, &UtY_col.vector, cPar.l_min, cPar.l_max,
                   cPar.n_region, cPar.l_remle_null, cPar.logl_remle_H0);
        CalcLmmVgVeBeta(eval, UtW, &UtY_col.vector, cPar.l_remle_null,
                        cPar.vg_remle_null, cPar.ve_remle_null, &beta.vector,
                        &se_beta.vector);

        cPar.beta_remle_null.clear();
        cPar.se_beta_remle_null.clear();
        assert(!std::isnan(B->data[0]));
        assert(!std::isnan(se_B->data[0]));

        for (size_t i = 0; i < B->size2; i++) {
          cPar.beta_remle_null.push_back(gsl_matrix_get(B, 0, i));
          cPar.se_beta_remle_null.push_back(gsl_matrix_get(se_B, 0, i));
        }

        CalcPve(eval, UtW, &UtY_col.vector, cPar.l_remle_null, cPar.trace_G,
                cPar.pve_null, cPar.pve_se_null);
        cPar.PrintSummary();

        // calculate and output residuals
        if (cPar.a_mode == 5) {
          gsl_vector *Utu_hat = gsl_vector_safe_alloc(Y->size1);
          gsl_vector *Ute_hat = gsl_vector_safe_alloc(Y->size1);
          gsl_vector *u_hat = gsl_vector_safe_alloc(Y->size1);
          gsl_vector *e_hat = gsl_vector_safe_alloc(Y->size1);
          gsl_vector *y_hat = gsl_vector_safe_alloc(Y->size1);

          // obtain Utu and Ute
          gsl_vector_memcpy(y_hat, &UtY_col.vector);
          gsl_blas_dgemv(CblasNoTrans, -1.0, UtW, &beta.vector, 1.0, y_hat);

          double d, u, e;
          for (size_t i = 0; i < eval->size; i++) {
            d = gsl_vector_get(eval, i);
            u = cPar.l_remle_null * d / (cPar.l_remle_null * d + 1.0) *
                gsl_vector_get(y_hat, i);
            e = 1.0 / (cPar.l_remle_null * d + 1.0) * gsl_vector_get(y_hat, i);
            gsl_vector_set(Utu_hat, i, u);
            gsl_vector_set(Ute_hat, i, e);
          }

          // obtain u and e
          gsl_blas_dgemv(CblasNoTrans, 1.0, U, Utu_hat, 0.0, u_hat);
          gsl_blas_dgemv(CblasNoTrans, 1.0, U, Ute_hat, 0.0, e_hat);

          // output residuals
          cPar.WriteVector(u_hat, "residU");
          cPar.WriteVector(e_hat, "residE");

          gsl_vector_free(u_hat);
          gsl_vector_free(e_hat);
          gsl_vector_free(y_hat);
        }
      }

      // Fit LMM or mvLMM (w. LOCO)
      if (cPar.a_mode == 1 || cPar.a_mode == 2 || cPar.a_mode == 3 ||
          cPar.a_mode == 4) {
        if (cPar.n_ph == 1) {
          LMM cLmm;
          cLmm.CopyFromParam(cPar);

          gsl_vector_view Y_col = gsl_matrix_column(Y, 0);
          gsl_vector_view UtY_col = gsl_matrix_column(UtY, 0);

          if (!cPar.file_bfile.empty()) {
            // PLINK analysis
            if (cPar.file_gxe.empty()) {
              cLmm.AnalyzePlink(U, eval, UtW, &UtY_col.vector, W,
                                &Y_col.vector, cPar.setGWASnps);
            }
            else {
              cLmm.AnalyzePlinkGXE(U, eval, UtW, &UtY_col.vector, W,
                                   &Y_col.vector, env);
            }
          }
          else {
            // BIMBAM analysis
            if (cPar.file_gxe.empty()) {
              cLmm.AnalyzeBimbam(U, eval, UtW, &UtY_col.vector, W,
                                 &Y_col.vector, cPar.setGWASnps);
            } else {
              cLmm.AnalyzeBimbamGXE(U, eval, UtW, &UtY_col.vector, W,
                                    &Y_col.vector, env);
            }
          }

          cLmm.WriteFiles();
          cLmm.CopyToParam(cPar);
        } else {
          MVLMM cMvlmm;
          cMvlmm.CopyFromParam(cPar);

          if (!cPar.file_bfile.empty()) {
            if (cPar.file_gxe.empty()) {
              cMvlmm.AnalyzePlink(U, eval, UtW, UtY);
            } else {
              cMvlmm.AnalyzePlinkGXE(U, eval, UtW, UtY, env);
            }
          } else {
            if (cPar.file_gxe.empty()) {
              cMvlmm.AnalyzeBimbam(U, eval, UtW, UtY);
            } else {
              cMvlmm.AnalyzeBimbamGXE(U, eval, UtW, UtY, env);
            }
          }

          cMvlmm.WriteFiles();
          cMvlmm.CopyToParam(cPar);
        }
      }
    }

    // release all matrices and vectors
    gsl_matrix_free(Y);
    gsl_matrix_free(W);
    gsl_matrix_free(B);
    gsl_matrix_free(se_B);
    gsl_matrix_free(G);
    gsl_matrix_free(U);
    gsl_matrix_free(UtW);
    gsl_matrix_free(UtY);
    gsl_vector_free(eval);
    gsl_vector_free(env);
  }

  // BSLMM
  if (cPar.a_mode == 11 || cPar.a_mode == 12 || cPar.a_mode == 13) {
    gsl_vector *y = gsl_vector_safe_alloc(cPar.ni_test);
    gsl_matrix *W = gsl_matrix_safe_alloc(y->size, cPar.n_cvt);
    gsl_matrix *G = gsl_matrix_safe_alloc(y->size, y->size);
    gsl_matrix *UtX = gsl_matrix_safe_alloc(y->size, cPar.ns_test);

    // set covariates matrix W and phenotype vector y
    // an intercept should be included in W,
    cPar.CopyCvtPhen(W, y, 0);

    // center y, even for case/control data
    cPar.pheno_mean = CenterVector(y);

    // run bvsr if rho==1
    if (cPar.rho_min == 1 && cPar.rho_max == 1) {
      // read genotypes X (not UtX)
      cPar.ReadGenotypes(UtX, G, false);

      // perform BSLMM analysis
      BSLMM cBslmm;
      cBslmm.CopyFromParam(cPar);
      time_start = clock();
      cBslmm.MCMC(UtX, y);
      cPar.time_opt = (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);
      cBslmm.CopyToParam(cPar);
      // else, if rho!=1
    } else {
      gsl_matrix *U = gsl_matrix_safe_alloc(y->size, y->size);
      gsl_vector *eval = gsl_vector_safe_alloc(y->size);
      gsl_matrix *UtW = gsl_matrix_safe_alloc(y->size, W->size2);
      gsl_vector *Uty = gsl_vector_safe_alloc(y->size);

      // read relatedness matrix G
      if (!(cPar.file_kin).empty()) {
        cPar.ReadGenotypes(UtX, G, false);

        // read relatedness matrix G
        ReadFile_kin(cPar.file_kin, cPar.indicator_idv, cPar.mapID2num,
                     cPar.k_mode, cPar.error, G);
        if (cPar.error == true) {
          cout << "error! fail to read kinship/relatedness file. " << endl;
          return;
        }

        // center matrix G
        CenterMatrix(G);
        validate_K(G);
      } else {
        cPar.ReadGenotypes(UtX, G, true);
      }

      // eigen-decomposition and calculate trace_G
      cout << "Start Eigen-Decomposition..." << endl;
      time_start = clock();

      cPar.trace_G = EigenDecomp_Zeroed(G, U, eval, 0);

      cPar.time_eigen =
          (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);

      // calculate UtW and Uty
      CalcUtX(U, W, UtW);
      CalcUtX(U, y, Uty);

      // calculate REMLE/MLE estimate and pve
      CalcLambda('L', eval, UtW, Uty, cPar.l_min, cPar.l_max, cPar.n_region,
                 cPar.l_mle_null, cPar.logl_mle_H0);
      CalcLambda('R', eval, UtW, Uty, cPar.l_min, cPar.l_max, cPar.n_region,
                 cPar.l_remle_null, cPar.logl_remle_H0);
      CalcPve(eval, UtW, Uty, cPar.l_remle_null, cPar.trace_G, cPar.pve_null,
              cPar.pve_se_null);

      cPar.PrintSummary();

      // Creat and calcualte UtX, use a large memory
      cout << "Calculating UtX..." << endl;
      time_start = clock();
      CalcUtX(U, UtX);
      cPar.time_UtX = (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);

      // perform BSLMM or BSLMMDAP analysis
      if (cPar.a_mode == 11 || cPar.a_mode == 12 || cPar.a_mode == 13) {
        BSLMM cBslmm;
        cBslmm.CopyFromParam(cPar);
        time_start = clock();
        if (cPar.a_mode == 12) { // ridge regression
          cBslmm.RidgeR(U, UtX, Uty, eval, cPar.l_remle_null);
        } else { // Run MCMC
          cBslmm.MCMC(U, UtX, Uty, eval, y);
        }
        cPar.time_opt =
            (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);
        cBslmm.CopyToParam(cPar);
      } else {
      }

      // release all matrices and vectors
      gsl_matrix_free(G);
      gsl_matrix_free(U);
      gsl_matrix_free(UtW);
      gsl_vector_free(eval);
      gsl_vector_free(Uty);
    }
    gsl_matrix_free(W);
    gsl_vector_free(y);
    gsl_matrix_free(UtX);
  }

  // BSLMM-DAP
  if (cPar.a_mode == 14 || cPar.a_mode == 15 || cPar.a_mode == 16) {
    if (cPar.a_mode == 14) {
      gsl_vector *y = gsl_vector_safe_alloc(cPar.ni_test);
      gsl_matrix *W = gsl_matrix_safe_alloc(y->size, cPar.n_cvt);
      gsl_matrix *G = gsl_matrix_safe_alloc(y->size, y->size);
      gsl_matrix *UtX = gsl_matrix_safe_alloc(y->size, cPar.ns_test);

      // set covariates matrix W and phenotype vector y
      // an intercept should be included in W,
      cPar.CopyCvtPhen(W, y, 0);

      // center y, even for case/control data
      cPar.pheno_mean = CenterVector(y);

      // run bvsr if rho==1
      if (cPar.rho_min == 1 && cPar.rho_max == 1) {
        // read genotypes X (not UtX)
        cPar.ReadGenotypes(UtX, G, false);

        // perform BSLMM analysis
        BSLMM cBslmm;
        cBslmm.CopyFromParam(cPar);
        time_start = clock();
        cBslmm.MCMC(UtX, y);
        cPar.time_opt =
            (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);
        cBslmm.CopyToParam(cPar);
        // else, if rho!=1
      } else {
        gsl_matrix *U = gsl_matrix_safe_alloc(y->size, y->size);
        gsl_vector *eval = gsl_vector_safe_alloc(y->size);
        gsl_matrix *UtW = gsl_matrix_safe_alloc(y->size, W->size2);
        gsl_vector *Uty = gsl_vector_safe_alloc(y->size);

        // read relatedness matrix G
        if (!(cPar.file_kin).empty()) {
          cPar.ReadGenotypes(UtX, G, false);

          // read relatedness matrix G
          ReadFile_kin(cPar.file_kin, cPar.indicator_idv, cPar.mapID2num,
                       cPar.k_mode, cPar.error, G);
          if (cPar.error == true) {
            cout << "error! fail to read kinship/relatedness file. " << endl;
            return;
          }

          // center matrix G
          CenterMatrix(G);
          validate_K(G);

        } else {
          cPar.ReadGenotypes(UtX, G, true);
        }

        // eigen-decomposition and calculate trace_G
        cout << "Start Eigen-Decomposition..." << endl;
        time_start = clock();
        cPar.trace_G = EigenDecomp_Zeroed(G, U, eval, 0);
        cPar.time_eigen =
            (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);

        // calculate UtW and Uty
        CalcUtX(U, W, UtW);
        CalcUtX(U, y, Uty);

        // calculate REMLE/MLE estimate and pve
        CalcLambda('L', eval, UtW, Uty, cPar.l_min, cPar.l_max, cPar.n_region,
                   cPar.l_mle_null, cPar.logl_mle_H0);
        CalcLambda('R', eval, UtW, Uty, cPar.l_min, cPar.l_max, cPar.n_region,
                   cPar.l_remle_null, cPar.logl_remle_H0);
        CalcPve(eval, UtW, Uty, cPar.l_remle_null, cPar.trace_G, cPar.pve_null,
                cPar.pve_se_null);

        cPar.PrintSummary();

        // Creat and calcualte UtX, use a large memory
        cout << "Calculating UtX..." << endl;
        time_start = clock();
        CalcUtX(U, UtX);
        cPar.time_UtX =
            (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);

        // perform analysis; assume X and y are already centered
        BSLMMDAP cBslmmDap;
        cBslmmDap.CopyFromParam(cPar);
        time_start = clock();
        cBslmmDap.DAP_CalcBF(U, UtX, Uty, eval, y);
        cPar.time_opt =
            (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);
        cBslmmDap.CopyToParam(cPar);

        // release all matrices and vectors
        gsl_matrix_free(G);
        gsl_matrix_free(U);
        gsl_matrix_free(UtW);
        gsl_vector_free(eval);
        gsl_vector_free(Uty);
      }

      gsl_matrix_free(W);
      gsl_vector_free(y);
      gsl_matrix_free(UtX);
    } else if (cPar.a_mode == 15) {
      // perform EM algorithm and estimate parameters
      vector<string> vec_rs;
      vector<double> vec_sa2, vec_sb2, wab;
      vector<vector<vector<double>>> BF;

      // read hyp and bf files (functions defined in BSLMMDAP)
      ReadFile_hyb(cPar.file_hyp, vec_sa2, vec_sb2, wab);
      ReadFile_bf(cPar.file_bf, vec_rs, BF);

      cPar.ns_test = vec_rs.size();
      if (wab.size() != BF[0][0].size()) {
        cout << "error! hyp and bf files dimension do not match" << endl;
      }

      // load annotations
      gsl_matrix *Ac;
      gsl_matrix_int *Ad;
      gsl_vector_int *dlevel;
      size_t kc, kd;
      if (!cPar.file_cat.empty()) {
        ReadFile_cat(cPar.file_cat, vec_rs, Ac, Ad, dlevel, kc, kd);
      } else {
        kc = 0;
        kd = 0;
      }

      cout << "## number of blocks = " << BF.size() << endl;
      cout << "## number of analyzed SNPs/var = " << vec_rs.size() << endl;
      cout << "## grid size for hyperparameters = " << wab.size() << endl;
      cout << "## number of continuous annotations = " << kc << endl;
      cout << "## number of discrete annotations = " << kd << endl;

      // DAP_EstimateHyper (const size_t kc, const size_t kd, const
      // vector<string> &vec_rs, const vector<double> &vec_sa2, const
      // vector<double> &vec_sb2, const vector<double> &wab, const
      // vector<vector<vector<double> > > &BF, gsl_matrix *Ac, gsl_matrix_int
      // *Ad, gsl_vector_int *dlevel);

      // perform analysis
      BSLMMDAP cBslmmDap;
      cBslmmDap.CopyFromParam(cPar);
      time_start = clock();
      cBslmmDap.DAP_EstimateHyper(kc, kd, vec_rs, vec_sa2, vec_sb2, wab, BF, Ac,
                                  Ad, dlevel);
      cPar.time_opt = (clock() - time_start) / (double(CLOCKS_PER_SEC) * 60.0);
      cBslmmDap.CopyToParam(cPar);

      gsl_matrix_free(Ac);
      gsl_matrix_int_free(Ad);
      gsl_vector_int_free(dlevel);
    } else {
      //
    }
  }

  cPar.time_total = (clock() - time_begin) / (double(CLOCKS_PER_SEC) * 60.0);

  return;
}

#include "Eigen/Dense"
#if defined(OPENBLAS) && !defined(OPENBLAS_LEGACY)
#include <openblas_config.h>
#endif

void GEMMA::WriteLog(int argc, char **argv, PARAM &cPar) {
  string file_str;
  file_str = cPar.path_out + "/" + cPar.file_out;
  file_str += ".log.txt";

  ofstream outfile(file_str.c_str(), ofstream::out);
  if (!outfile) {
    cout << "error writing log file: " << file_str.c_str() << endl;
    return;
  }

  outfile << "##" << endl;
  outfile << "## GEMMA Version    = " << version << " (" << date << ")" << endl;
  outfile << "## GSL Version      = " << GSL_VERSION << endl;
  outfile << "## Eigen Version    = " << EIGEN_WORLD_VERSION << "." << EIGEN_MAJOR_VERSION << "." << EIGEN_MINOR_VERSION << endl;
#ifdef OPENBLAS

  #ifndef OPENBLAS_LEGACY
  outfile << "## OpenBlas         =" << OPENBLAS_VERSION << " - " << openblas_get_config() << endl;
  outfile << "##   arch           = " << openblas_get_corename() << endl;
  outfile << "##   threads        = " << openblas_get_num_threads() << endl;
  #else
  outfile << "## OpenBlas         = " << openblas_get_config() << endl;
  #endif
  string* pStr = new string[4] { "sequential", "threaded", "openmp" };
  outfile << "##   parallel type  = " << pStr[openblas_get_parallel()] << endl;
#endif

  outfile << "##" << endl;
  outfile << "## Command Line Input = ";
  for (int i = 0; i < argc; i++) {
    outfile << argv[i] << " ";
  }
  outfile << endl;

  outfile << "##" << endl;
  time_t rawtime;
  time(&rawtime);
  tm *ptm = localtime(&rawtime);

  outfile << "## Date = " << asctime(ptm);

  outfile << "##" << endl;
  outfile << "## Summary Statistics:" << endl;
  if (!cPar.file_cor.empty() || !cPar.file_study.empty() ||
      !cPar.file_mstudy.empty()) {
    outfile << "## number of total individuals in the sample = "
            << cPar.ni_study << endl;
    outfile << "## number of total individuals in the reference = "
            << cPar.ni_ref << endl;
    outfile << "## number of variance components = " << cPar.n_vc << endl;

    outfile << "## pve estimates = ";
    for (size_t i = 0; i < cPar.v_pve.size(); i++) {
      outfile << "  " << cPar.v_pve[i];
    }
    outfile << endl;

    outfile << "## se(pve) = ";
    for (size_t i = 0; i < cPar.v_se_pve.size(); i++) {
      outfile << "  " << cPar.v_se_pve[i];
    }
    outfile << endl;
    assert(!has_nan(cPar.v_se_pve));

    if (cPar.n_vc > 1) {
      outfile << "## total pve = " << cPar.pve_total << endl;
      outfile << "## se(total pve) = " << cPar.se_pve_total << endl;
    }

    outfile << "## sigma2 per snp = ";
    for (size_t i = 0; i < cPar.v_sigma2.size(); i++) {
      outfile << "  " << cPar.v_sigma2[i];
    }
    outfile << endl;

    outfile << "## se(sigma2 per snp) = ";
    for (size_t i = 0; i < cPar.v_se_sigma2.size(); i++) {
      outfile << "  " << cPar.v_se_sigma2[i];
    }
    outfile << endl;

    outfile << "## enrichment = ";
    for (size_t i = 0; i < cPar.v_enrich.size(); i++) {
      outfile << "  " << cPar.v_enrich[i];
    }
    outfile << endl;

    outfile << "## se(enrichment) = ";
    for (size_t i = 0; i < cPar.v_se_enrich.size(); i++) {
      outfile << "  " << cPar.v_se_enrich[i];
    }
    outfile << endl;
  } else if (!cPar.file_beta.empty() &&
             (cPar.a_mode == 61 || cPar.a_mode == 62)) {
    outfile << "## number of total individuals in the sample = "
            << cPar.ni_study << endl;
    outfile << "## number of total individuals in the reference = "
            << cPar.ni_total << endl;
    outfile << "## number of total SNPs/var in the sample = " << cPar.ns_study
            << endl;
    outfile << "## number of total SNPs/var in the reference panel = "
            << cPar.ns_total << endl;
    outfile << "## number of analyzed SNPs/var = " << cPar.ns_test << endl;
    outfile << "## number of variance components = " << cPar.n_vc << endl;
  } else if (!cPar.file_beta.empty() &&
             (cPar.a_mode == 66 || cPar.a_mode == 67)) {
    outfile << "## number of total individuals in the sample = "
            << cPar.ni_total << endl;
    outfile << "## number of total individuals in the reference = "
            << cPar.ni_ref << endl;
    outfile << "## number of total SNPs/var in the sample = " << cPar.ns_total
            << endl;
    outfile << "## number of analyzed SNPs/var = " << cPar.ns_test << endl;
    outfile << "## number of variance components = " << cPar.n_vc << endl;

    outfile << "## pve estimates = ";
    for (size_t i = 0; i < cPar.v_pve.size(); i++) {
      outfile << "  " << cPar.v_pve[i];
    }
    outfile << endl;

    outfile << "## se(pve) = ";
    for (size_t i = 0; i < cPar.v_se_pve.size(); i++) {
      outfile << "  " << cPar.v_se_pve[i];
    }
    outfile << endl;

    if (cPar.n_vc > 1) {
      outfile << "## total pve = " << cPar.pve_total << endl;
      outfile << "## se(total pve) = " << cPar.se_pve_total << endl;
    }

    outfile << "## sigma2 per snp = ";
    for (size_t i = 0; i < cPar.v_sigma2.size(); i++) {
      outfile << "  " << cPar.v_sigma2[i];
    }
    outfile << endl;

    outfile << "## se(sigma2 per snp) = ";
    for (size_t i = 0; i < cPar.v_se_sigma2.size(); i++) {
      outfile << "  " << cPar.v_se_sigma2[i];
    }
    outfile << endl;

    outfile << "## enrichment = ";
    for (size_t i = 0; i < cPar.v_enrich.size(); i++) {
      outfile << "  " << cPar.v_enrich[i];
    }
    outfile << endl;

    outfile << "## se(enrichment) = ";
    for (size_t i = 0; i < cPar.v_se_enrich.size(); i++) {
      outfile << "  " << cPar.v_se_enrich[i];
    }
    outfile << endl;
  } else {
    outfile << "## number of total individuals = " << cPar.ni_total << endl;

    if (cPar.a_mode == 43) {
      outfile << "## number of analyzed individuals = " << cPar.ni_cvt << endl;
      outfile << "## number of individuals with full phenotypes = "
              << cPar.ni_test << endl;
    } else if (cPar.a_mode != 27 && cPar.a_mode != 28) {
      outfile << "## number of analyzed individuals = " << cPar.ni_test << endl;
    }

    outfile << "## number of covariates = " << cPar.n_cvt << endl;
    outfile << "## number of phenotypes = " << cPar.n_ph << endl;
    if (cPar.a_mode == 43) {
      outfile << "## number of observed data = " << cPar.np_obs << endl;
      outfile << "## number of missing data = " << cPar.np_miss << endl;
    }
    if (cPar.a_mode == 25 || cPar.a_mode == 26 || cPar.a_mode == 27 ||
        cPar.a_mode == 28 || cPar.a_mode == 61 || cPar.a_mode == 62 ||
        cPar.a_mode == 63 || cPar.a_mode == 66 || cPar.a_mode == 67) {
      outfile << "## number of variance components = " << cPar.n_vc << endl;
    }

    if (!(cPar.file_gene).empty()) {
      outfile << "## number of total genes = " << cPar.ng_total << endl;
      outfile << "## number of analyzed genes = " << cPar.ng_test << endl;
    } else if (cPar.file_epm.empty()) {
      outfile << "## number of total SNPs/var = " << cPar.ns_total << endl;
      outfile << "## number of analyzed SNPs/var = " << cPar.ns_test << endl;
    } else {
      outfile << "## number of analyzed SNPs/var = " << cPar.ns_test << endl;
    }

    if (cPar.a_mode == 13) {
      outfile << "## number of cases = " << cPar.ni_case << endl;
      outfile << "## number of controls = " << cPar.ni_control << endl;
    }
  }

  if ((cPar.a_mode == 61 || cPar.a_mode == 62 || cPar.a_mode == 63) &&
      cPar.file_cor.empty() && cPar.file_study.empty() &&
      cPar.file_mstudy.empty()) {
    //	        outfile<<"## REMLE log-likelihood in the null model =
    //"<<cPar.logl_remle_H0<<endl;
    if (cPar.n_ph == 1) {
      outfile << "## pve estimates = ";
      for (size_t i = 0; i < cPar.v_pve.size(); i++) {
        outfile << "  " << cPar.v_pve[i];
      }
      outfile << endl;

      outfile << "## se(pve) = ";
      for (size_t i = 0; i < cPar.v_se_pve.size(); i++) {
        outfile << "  " << cPar.v_se_pve[i];
      }
      outfile << endl;

      if (cPar.n_vc > 1) {
        outfile << "## total pve = " << cPar.pve_total << endl;
        outfile << "## se(total pve) = " << cPar.se_pve_total << endl;
      }

      outfile << "## sigma2 estimates = ";
      for (size_t i = 0; i < cPar.v_sigma2.size(); i++) {
        outfile << "  " << cPar.v_sigma2[i];
      }
      outfile << endl;

      outfile << "## se(sigma2) = ";
      for (size_t i = 0; i < cPar.v_se_sigma2.size(); i++) {
        outfile << "  " << cPar.v_se_sigma2[i];
      }
      outfile << endl;

      if (!cPar.file_beta.empty()) {
        outfile << "## enrichment = ";
        for (size_t i = 0; i < cPar.v_enrich.size(); i++) {
          outfile << "  " << cPar.v_enrich[i];
        }
        outfile << endl;

        outfile << "## se(enrichment) = ";
        for (size_t i = 0; i < cPar.v_se_enrich.size(); i++) {
          outfile << "  " << cPar.v_se_enrich[i];
        }
        outfile << endl;
      }
    }
  }

  if (cPar.a_mode == 1 || cPar.a_mode == 2 || cPar.a_mode == 3 ||
      cPar.a_mode == 4 || cPar.a_mode == 5 || cPar.a_mode == 11 ||
      cPar.a_mode == 12 || cPar.a_mode == 13) {
    outfile << "## REMLE log-likelihood in the null model = "
            << cPar.logl_remle_H0 << endl;
    outfile << "## MLE log-likelihood in the null model = " << cPar.logl_mle_H0
            << endl;
    if (cPar.n_ph == 1) {
      // outfile<<"## lambda REMLE estimate in the null (linear mixed) model =
      // "<<cPar.l_remle_null<<endl;
      // outfile<<"## lambda MLE estimate in the null (linear mixed) model =
      // "<<cPar.l_mle_null<<endl;
      outfile << "## pve estimate in the null model = " << cPar.pve_null
              << endl;
      outfile << "## se(pve) in the null model = " << cPar.pve_se_null << endl;
      outfile << "## vg estimate in the null model = " << cPar.vg_remle_null
              << endl;
      outfile << "## ve estimate in the null model = " << cPar.ve_remle_null
              << endl;
      outfile << "## beta estimate in the null model = ";
      for (size_t i = 0; i < cPar.beta_remle_null.size(); i++) {
        outfile << "  " << cPar.beta_remle_null[i];
      }
      outfile << endl;
      outfile << "## se(beta) = ";
      for (size_t i = 0; i < cPar.se_beta_remle_null.size(); i++) {
        outfile << "  " << cPar.se_beta_remle_null[i];
      }
      outfile << endl;

    } else {
      size_t c;
      outfile << "## REMLE estimate for Vg in the null model: " << endl;
      for (size_t i = 0; i < cPar.n_ph; i++) {
        for (size_t j = 0; j <= i; j++) {
          c = (2 * cPar.n_ph - min(i, j) + 1) * min(i, j) / 2 + max(i, j) -
              min(i, j);
          outfile << tab(j) << cPar.Vg_remle_null[c];
        }
        outfile << endl;
      }
      outfile << "## se(Vg): " << endl;
      for (size_t i = 0; i < cPar.n_ph; i++) {
        for (size_t j = 0; j <= i; j++) {
          c = (2 * cPar.n_ph - min(i, j) + 1) * min(i, j) / 2 + max(i, j) -
              min(i, j);
          outfile << tab(j) << sqrt(cPar.VVg_remle_null[c]);
        }
        outfile << endl;
      }
      outfile << "## REMLE estimate for Ve in the null model: " << endl;
      for (size_t i = 0; i < cPar.n_ph; i++) {
        for (size_t j = 0; j <= i; j++) {
          c = (2 * cPar.n_ph - min(i, j) + 1) * min(i, j) / 2 + max(i, j) -
              min(i, j);
          outfile << tab(j) << cPar.Ve_remle_null[c];
        }
        outfile << endl;
      }
      outfile << "## se(Ve): " << endl;
      for (size_t i = 0; i < cPar.n_ph; i++) {
        for (size_t j = 0; j <= i; j++) {
          c = (2 * cPar.n_ph - min(i, j) + 1) * min(i, j) / 2 + max(i, j) -
              min(i, j);
          outfile << tab(j) << sqrt(cPar.VVe_remle_null[c]);
        }
        outfile << endl;
      }

      outfile << "## MLE estimate for Vg in the null model: " << endl;
      for (size_t i = 0; i < cPar.n_ph; i++) {
        for (size_t j = 0; j < cPar.n_ph; j++) {
          c = (2 * cPar.n_ph - min(i, j) + 1) * min(i, j) / 2 + max(i, j) -
              min(i, j);
          outfile << tab(j) << cPar.Vg_mle_null[c];
        }
        outfile << endl;
      }
      outfile << "## se(Vg): " << endl;
      for (size_t i = 0; i < cPar.n_ph; i++) {
        for (size_t j = 0; j <= i; j++) {
          c = (2 * cPar.n_ph - min(i, j) + 1) * min(i, j) / 2 + max(i, j) -
              min(i, j);
          outfile << tab(j) << sqrt(cPar.VVg_mle_null[c]);
        }
        outfile << endl;
      }
      outfile << "## MLE estimate for Ve in the null model: " << endl;
      for (size_t i = 0; i < cPar.n_ph; i++) {
        for (size_t j = 0; j < cPar.n_ph; j++) {
          c = (2 * cPar.n_ph - min(i, j) + 1) * min(i, j) / 2 + max(i, j) -
              min(i, j);
          outfile << tab(j) << cPar.Ve_mle_null[c];
        }
        outfile << endl;
      }
      outfile << "## se(Ve): " << endl;
      for (size_t i = 0; i < cPar.n_ph; i++) {
        for (size_t j = 0; j <= i; j++) {
          c = (2 * cPar.n_ph - min(i, j) + 1) * min(i, j) / 2 + max(i, j) -
              min(i, j);
          outfile << tab(j) << sqrt(cPar.VVe_mle_null[c]);
        }
        outfile << endl;
      }
      outfile << "## estimate for B (d by c) in the null model (columns "
                 "correspond to the covariates provided in the file): "
              << endl;
      for (size_t i = 0; i < cPar.n_ph; i++) {
        for (size_t j = 0; j < cPar.n_cvt; j++) {
          c = i * cPar.n_cvt + j;
          outfile << tab(j) << cPar.beta_remle_null[c];
        }
        outfile << endl;
      }
      outfile << "## se(B): " << endl;
      for (size_t i = 0; i < cPar.n_ph; i++) {
        for (size_t j = 0; j < cPar.n_cvt; j++) {
          c = i * cPar.n_cvt + j;
          outfile << tab(j) << cPar.se_beta_remle_null[c];
        }
        outfile << endl;
      }
    }
  }

  if (cPar.a_mode == 11 || cPar.a_mode == 12 || cPar.a_mode == 13 ||
      cPar.a_mode == 14 || cPar.a_mode == 16) {
    outfile << "## estimated mean = " << cPar.pheno_mean << endl;
  }

  if (cPar.a_mode == 11 || cPar.a_mode == 13) {
    outfile << "##" << endl;
    outfile << "## MCMC related:" << endl;
    outfile << "## initial value of h = " << cPar.cHyp_initial.h << endl;
    outfile << "## initial value of rho = " << cPar.cHyp_initial.rho << endl;
    outfile << "## initial value of pi = " << exp(cPar.cHyp_initial.logp)
            << endl;
    outfile << "## initial value of |gamma| = " << cPar.cHyp_initial.n_gamma
            << endl;
    outfile << "## random seed = " << cPar.randseed << endl;
    outfile << "## acceptance ratio = "
            << (double)cPar.n_accept /
                   (double)((cPar.w_step + cPar.s_step) * cPar.n_mh)
            << endl;
  }

  outfile << "##" << endl;
  outfile << "## Computation Time:" << endl;
  outfile << "## total computation time = " << cPar.time_total << " min "
          << endl;
  outfile << "## computation time break down: " << endl;
  if (cPar.a_mode == 21 || cPar.a_mode == 22 || cPar.a_mode == 11 ||
      cPar.a_mode == 13 || cPar.a_mode == 14 || cPar.a_mode == 16) {
    outfile << "##      time on calculating relatedness matrix = "
            << cPar.time_G << " min " << endl;
  }
  if (cPar.a_mode == 31) {
    outfile << "##      time on eigen-decomposition = " << cPar.time_eigen
            << " min " << endl;
  }
  if (cPar.a_mode == 1 || cPar.a_mode == 2 || cPar.a_mode == 3 ||
      cPar.a_mode == 4 || cPar.a_mode == 5 || cPar.a_mode == 11 ||
      cPar.a_mode == 12 || cPar.a_mode == 13 || cPar.a_mode == 14 ||
      cPar.a_mode == 16) {
    outfile << "##      time on eigen-decomposition = " << cPar.time_eigen
            << " min " << endl;
    outfile << "##      time on calculating UtX = " << cPar.time_UtX << " min "
            << endl;
  }
  if ((cPar.a_mode >= 1 && cPar.a_mode <= 4) ||
      (cPar.a_mode >= 51 && cPar.a_mode <= 54)) {
    outfile << "##      time on optimization = " << cPar.time_opt << " min "
            << endl;
  }
  if (cPar.a_mode == 11 || cPar.a_mode == 13) {
    outfile << "##      time on proposal = " << cPar.time_Proposal << " min "
            << endl;
    outfile << "##      time on mcmc = " << cPar.time_opt << " min " << endl;
    outfile << "##      time on Omega = " << cPar.time_Omega << " min " << endl;
  }
  if (cPar.a_mode == 41 || cPar.a_mode == 42) {
    outfile << "##      time on eigen-decomposition = " << cPar.time_eigen
            << " min " << endl;
  }
  if (cPar.a_mode == 43) {
    outfile << "##      time on eigen-decomposition = " << cPar.time_eigen
            << " min " << endl;
    outfile << "##      time on predicting phenotypes = " << cPar.time_opt
            << " min " << endl;
  }
  outfile << "##" << endl;

  outfile.close();
  outfile.clear();
  return;
}