File: segment.cpp

package info (click to toggle)
plink 1.07%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 3,036 kB
  • sloc: cpp: 69,728; makefile: 123; sh: 12
file content (2486 lines) | stat: -rw-r--r-- 57,704 bytes parent folder | download | duplicates (6)
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


//////////////////////////////////////////////////////////////////
//                                                              //
//           PLINK (c) 2005-2009 Shaun Purcell                  //
//                                                              //
// This file is distributed under the GNU General Public        //
// License, Version 2.  Please see the file COPYING for more    //
// details                                                      //
//                                                              //
//////////////////////////////////////////////////////////////////


#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cmath>
#include "plink.h"
#include "helper.h"
#include "options.h"
#include "perm.h"
#include "fisher.h"
#include "stats.h"

void Plink::findSegments(int i1, int i2, vector_t & p, ofstream & SEG)
{

  Individual * p1 = sample[i1];
  Individual * p2 = sample[i2];
  
  bool inseg = false;
  
  Segment s;
  s.p1 = p1;
  s.p2 = p2;
  int npos = p.size();
		
  // Marker if minimal segment output file is selected
  bool already_seen_pair = false;
  
  for (int l=0; l<npos; l++)
    {
      
      ///////////////////////////
      // Start of a new segment?
      
      if ( (!inseg) && p[l] >= par::segment_threshold_start)
	{
	  inseg = true;

	  if (m1[l] != -1)
	    s.start = m1[l];
	  else
	    s.start = par::run_start;
	}
      
      
        ///////////////////////////
	// End of existing segment?
		    		    
	if ( inseg && 
	     ( p[l] < par::segment_threshold_finish || l == npos-1 ) )
	  {
	    inseg = false;

	    if (m2[l-1] != -1)
	      s.finish = m2[l-1];
	    else
	      s.finish = par::run_end;

	    // Do we like this segment?
	    if ( locus[s.finish]->bp - locus[s.start]->bp 
		 >= par::segment_length  
		 &&
		 s.finish-s.start+1 >= par::segment_snp  
		 )
	      {
		
		// Add segment to list
		segment.push_back(s);
		
		// Display?
		if (par::segment_output)
		  {
		    if ( par::segment_minimal )
		      {			
			if ( ! already_seen_pair )
			  {
			    already_seen_pair = true;
			    SEG << i1 << " " << i2 << " ";
			  }
			
			SEG << s.start << " "
			    << s.finish << " ";
		      }
		    else
		      {
			
			// Long format
			
			SEG << setw(par::pp_maxfid) << s.p1->fid << " "
			    << setw(par::pp_maxiid) << s.p1->iid << " "
			    << setw(par::pp_maxfid) << s.p2->fid << " "
			    << setw(par::pp_maxiid) << s.p2->iid << " ";
			
			if (par::bt)
			  {
			    if ( (!p1->aff) && (!p2->aff) ) 
			      SEG << setw(4) << "-1" << " ";
			    else if ( p1->aff && p2->aff )
			      SEG << setw(4) << "1" << " ";
			    else if ((!p1->aff) && p2->aff)
			      SEG << setw(4) << "0" << " ";
			    else if (p1->aff && !p2->aff)
			      SEG << setw(4) << "0" << " ";
			    else
			      SEG << setw(4) << "NA" << " ";
			  }
			else
			  SEG << setw(4) << "NA" << " ";
			
			Locus * start = locus[s.start];
			Locus * finish = locus[s.finish];
			
			SEG << setw(4) << par::run_chr << " "
			    << setw(10) << start->bp << " "
			    << setw(10) << finish->bp << " "
			    << setw(par::pp_maxsnp) << start->name << " "
			    << setw(par::pp_maxsnp) << finish->name << " "
			    << setw(6) << s.finish-s.start+1 << " "
			    << setw(10) << (double)(finish->bp - start->bp)/(double)1000 
			    << "\n";
			
			SEG.flush();
			
		      }
		  }
		
		
	      }
	    
	  }
    }

  // If we have found segments for this pair, then 
   // record a end-of-pair code if in minimal output mode

  if ( par::segment_minimal && already_seen_pair )
    SEG << "-1 -1\n";

}


void Plink::segmentIndividualTest(Perm & perm)
{
  
  printLOG("Writing individual-based segment tests to [ " 
	   + par::output_file_name + ".segtest1 ]\n");
  
  int total_cases = 0, total_controls = 0;

  for (int i=0; i<n; i++)
    if ( sample[i]->aff ) 
      total_cases++;
    else
      total_controls++;

  
  map<Individual*,int> ip;
  for (int i=0; i<n; i++)
    ip.insert(make_pair( sample[i],i ));
  

  if ( par::permute ) 
    {
      perm.setTests(nl_all);
      perm.setPermClusters(*this);
      perm.originalOrder();
    }
  
  
  
  /////////////////////////////////////
  // Generate original test statistics
  
  vector_t original = perm_segmentIndividualTest(perm,
						 true,
						 total_cases,
						 total_controls,
						 ip);
  
  if ( ! par::permute ) 
    return;
  

  //////////////////////////
  // Enter permutation stage
  
  bool finished = false;
  
  while(!finished)
    {
      
      perm.permuteInCluster();
      
      vector_t pr = perm_segmentIndividualTest(perm,
					       false,
					       total_cases,
					       total_controls,
					       ip);
      
      ////////////////////////////////
      // Standard permutation counting
      
      finished = perm.update(pr,original);
      
    }
  
  if (!par::silent)
    cout << "\n\n";


  printLOG("Writing individual-based segment permutation results to [ " 
	   + par::output_file_name + ".segtest1.mperm ]\n");
  
  ofstream SEGS;
  
  SEGS.open( (par::output_file_name+".segtest1.mperm").c_str() , ios::out );

  SEGS << setw(4)  << "CHR" << " "
       << setw(par::pp_maxsnp) << "SNP" << " "
       << setw(12) << "EMP1" << " "      
       << setw(12) << "EMP2" << "\n";      
  
  
  for ( int l=0; l<nl_all; l++)
    {
      SEGS << setw(4) << locus[l]->chr << " "
	   << setw(par::pp_maxsnp) << locus[l]->name << " "
	   << setw(12) << perm.pvalue(l) << " "
	   << setw(12) << perm.max_pvalue(l) << "\n";      
    }

  SEGS.close();
 
}

vector_t Plink::perm_segmentIndividualTest(Perm & perm, 
					   bool display,
					   int total_cases,
					   int total_controls,
					   map<Individual*,int> & ip)
{
  
  vector_t results;

  ofstream SEGS;
  
  if ( display ) 
    {
      SEGS.open( (par::output_file_name+".segtest1").c_str() , ios::out );
      SEGS.precision(4);

      SEGS << setw(4)  << "CHR" << " "
	   << setw(par::pp_maxsnp) << "SNP" << " "
	   << setw(5) << "TEST" << " " 
	   << setw(8) << "AFF" << " " 
	   << setw(8) << "UNAFF" << " " 
	   << setw(8) << "PHAT" << " " 
	   << setw(8) << "P0" << " "
	   << setw(8) << "Z" << " "
	   << setw(8) << "P" << "\n";      
    }

  // Consider each SNP position
  // Count : number of cases with at least one segment
  //         number of controls with at least one segment
  //  versus : equivalent counts of those w/out a segment

  // Calculate genome-wide means for cases and controls

  // Tests:

  // 1) Number of cases with at least one segment versus 
  //    number of contorls with at least one segment

  // 2) Number of case segments versus numbr of control segments
  
  // Options:
  //    Make 1-sided (i.e. more case sharing expected)
  //    Adjust for genome-wide sharing level
  //    Use Fisher's exact versus use standard chi-square

  //    Use permutation or not (permute individuals)
  //    CHECK: okay to have floating point values for fisher's test?


  ///////////////////////////////////////////////////////
  // Calculate mean levels of sharing in cases and controls

  long int ncases = 0;
  long int ncontrols = 0;

  for (int l=0; l<nl_all; l++)
    {
      
      set<Individual*> people;
      
      vector<Segment>::iterator s = segment.begin();
      while ( s != segment.end() )
	{          
	  if ( s->start <= l && s->finish >= l )
	    {
	      
	      if ( people.find( s->p1 ) == people.end() )
		{
		  people.insert( s->p1 );
		  if ( s->p1->pperson->aff )
		    ncases++;
		  else
		    ncontrols++;
		}
	      
	      // Only consider second individual for IBD sharing test
	      if ( ! par::homo_run )
		{
		  if ( people.find( s->p2 ) == people.end() )

		    {
		      people.insert( s->p2 );
		      if ( s->p2->pperson->aff )
			ncases++;
		      else
			ncontrols++;
		    }
		} 
	    }
	  
	  s++;
	  
	} // next segment
    }
  
  double mean_case_sharing = (double)ncases / (double)(nl_all);
  double mean_control_sharing = (double)ncontrols / (double)(nl_all);
  
  
  
  /////////////////////////////////////////
  // Consider this position
  
  for (int l=0; l<nl_all; l++)
    {
      
      int ncases = 0, ncontrols = 0;
      set<Individual*> people;
      

      ///////////////////////////////////////////////////////
      // Consider all segments that might span this position
      
      vector<Segment>::iterator s = segment.begin();
      while ( s != segment.end() )
	{          
	  if ( s->start <= l && s->finish >= l )
	    {
	      
	      if ( people.find( s->p1 ) == people.end() )
		{
		  people.insert( s->p1 );
		  if ( s->p1->pperson->aff )
		    ncases++;
		  else
		    ncontrols++;
		}

	      // Only consider second individual for IBD sharing test
	      if ( ! par::homo_run )
		{
		  if ( people.find( s->p2 ) == people.end() )
		    {
		      people.insert( s->p2 );
		      if ( s->p2->pperson->aff )
			ncases++;
		      else
			ncontrols++;
		    }
		} 
	    }

	  s++;

	} // next segment
      

      //////////////////////////////////////////////////
      // Adjust table by the genome-wide means for case 
      // sharing and control sharing

      // Scale adjustment to be proportional to total amount of
      // sharing at this particular locus
      
//       double expected_cases = (ncases+ncontrols) * 
// 	( mean_case_sharing/(mean_case_sharing+mean_control_sharing) );
      
//       double expected_controls = (ncases+ncontrols) * 
// 	( mean_control_sharing/(mean_case_sharing+mean_control_sharing) );
      
//       double pvalue = 1;
      
//       if ( ncases > expected_cases )
// 	{
// 	  double chi1 = ncases - expected_cases;
// 	  chi1 *= chi1;
// 	  chi1 /= expected_cases;
	  
// 	  double chi2 = ncontrols - expected_controls;
// 	  chi2 *= chi2;
// 	  chi2 /= expected_controls;

// 	  double chisq = chi1 + chi2;
// 	  pvalue = chiprobP(chisq,1);
// 	}

      // Scale 
      

      //////////////////////////////////////////////////
      // Fisher's exact test, as counts might be small, 
      // or standard chi-sq

//       matrix_t t;
//       sizeMatrix(t,2,2);
//       t[0][0] = ncases_adj;
//       t[0][1] = ncontrols_adj;
//       t[1][0] = total_cases - ncases_adj;
//       t[1][1] = total_controls - ncontrols_adj;

//       cout << t[0][0] << "\t" 
// 	   << t[0][1] << "\t" 
// 	   << t[1][0] << "\t" 
// 	   << t[1][1] << "\n";

      //////////////////////////////////////////////////
      // Either chi-square of Fisher's exact for a p-value
      
//       double pvalue = 1;
      
//       // A one sided t-test:
      
//       if ( ncases_adj > ncontrols_adj )  
// 	   && (double)ncases/(double)total_cases 
// 	   > (double)ncontrols/(double)total_controls ) 
//	{	  
// 	  pvalue = par::segment_test_fisher 
// 	    ? 
// 	    fisher(t) : 
// 	    chiprobP(chi2x2(t),1);

// 	  pvalue = chiprobP(chi2x2(t),1);

// 	}
      

 
      //////////////////////////////////////////////////////////////
      // 1-sided test of proportions with the normal approximation
      
      // z = (p_hat - p0) / sqrt( ( p0*(1-p0) ) / N ) 
      // where N is total number of individuals
      // N*p should be > 5, 
      
      
      double p0 = mean_case_sharing/(mean_case_sharing+mean_control_sharing);
      double phat = (double)ncases/double(ncases+ncontrols);
      double z = (phat - p0) / sqrt( ( p0*(1-p0) ) / (ncases+ncontrols) ); 
      double pvalue = z < 0 ? 1 : normdist(-z);

      //      cout << "STAT: " << p0 << "\t" << phat << "\t" << z << "\n";


      ///////////////////
      // Store results?
      
      if ( ! realnum(p0) )
	{
	  pvalue = 1;
	}
      
      results.push_back(1-pvalue);

      
      ////////////////////
      // Display results?
      
      if ( display )
	{
	  if ( ! realnum(p0) )
	    SEGS << setw(4)  << locus[l]->chr << " " 
		 << setw(par::pp_maxsnp) << locus[l]->name << " "
		 << setw(5) << "ALL" << " " 
		 << setw(8) << ncases << " " 
		 << setw(8) << ncontrols << " " 
		 << setw(8) << "NA" << " "	    
		 << setw(8) << p0 << " "	    
		 << setw(8) << 0 << " " 
		 << setw(8) << 1 << "\n";      
	  else
	      SEGS << setw(4)  << locus[l]->chr << " " 
	       << setw(par::pp_maxsnp) << locus[l]->name << " "
	       << setw(5) << "ALL" << " " 
	       << setw(8) << ncases << " " 
	       << setw(8) << ncontrols << " " 
	       << setw(8) << phat << " "	    
	       << setw(8) << p0 << " "	    
	       << setw(8) << z << " " 
	       << setw(8) << pvalue << "\n";      
	}
      


      ////////////////////////////////////////////////////////////
      // Consider allele-specific segments spanning this position 
      // (groups of)

      // NEED TO ADJUST TEST STATISTIC BELOW, IF ABOVE FIX WORKS

      if ( false && par::segment_test_specific_segs ) 
	{
	  
	  groupSegmentsSpanning(l);
	  
	  map<int,int> groupCount;
	  
	  for ( int i = 0; i < n ; i++ )
	    {
	      
	      if ( indivSegmentGroup[i] == -1 )
		continue;
	      
	      map<int,int>::iterator gi = groupCount.find( indivSegmentGroup[i] );
	      
	      if ( gi == groupCount.end() ) 
		groupCount.insert(make_pair( indivSegmentGroup[i] , 1 ) );
	      else
		gi->second++;	  
	    }
	  
	  // Consider all allelically-matching groups with more than a 
	  // set number of segments
	  
	  map<int,int>::iterator gi = groupCount.begin();
	  
	  while ( gi != groupCount.end() )
	    {
	      if ( gi->second < 10 ) 
		{
		  gi++;
		  continue;
		}
	      
	      int group = gi->first;
	      
	      int ncases = 0, ncontrols = 0;
	      set<Individual*> people;
	      
	      // Consider all segments that might span this position
	      
	      vector<Segment>::iterator s = segment.begin();
	      while ( s != segment.end() )
		{          
		  if ( s->start <= l && s->finish >= l )
		    {
		      
		      if ( people.find( s->p1 ) == people.end() )
			{
			  if ( indivSegmentGroup[ ip.find( s->p1 )->second ] == group ) 
			    {
			      people.insert( s->p1 );		      
			      if ( s->p1->pperson->aff )
				ncases++;
			      else
				ncontrols++;
			    }
			}
		      
		      if ( ! par::homo_run )
			{
			  if ( people.find( s->p2 ) == people.end() )
			    {
			      if ( indivSegmentGroup[ ip.find( s->p2 )->second ] == group ) 
				{
				  people.insert( s->p2 );
				  if ( s->p2->pperson->aff )
				    ncases++;
				  else
				    ncontrols++;
				}
			    }
			} 
		    }
		  
		  s++;
		  
		} // next segment
	      
	      
	      // Fisher's exact test, as counts might be small
	      
	      table_t t;
	      sizeTable(t,2,2);
	      t[0][0] = ncases;
	      t[0][1] = ncontrols;
	      t[1][0] = total_cases - ncases;
	      t[1][1] = total_controls - ncontrols;

	      double pvalue = 1;

	      if ( ncases > 0 
		   && (double)ncases/(double)total_cases 
		   > (double)ncontrols/(double)total_controls ) 
		{	  
		  pvalue = par::segment_test_fisher ? fisher(t) : chiprobP(chi2x2(t),1);
		}

	      if ( display ) 
		{
		  SEGS << setw(4)  << locus[l]->chr << " "
		       << setw(par::pp_maxsnp) << locus[l]->name << " "
		       << setw(5) << group << " "
		       << setw(12) << ncases << " "
		       << setw(12) << ncontrols << " "
		       << setw(12) << pvalue << "\n";
		}

	      gi++;
	    }
	  
	} //end of specific segment section
    } // Next SNP  


  if (display)
    SEGS.close();


  return results;
  
}

void Plink::segmentPermutationTest(Perm & perm, bool ibd, string f,
				   vector<int> & coverage_conc_aff,
				   vector<int> & coverage_disc,
				   vector<int> & coverage_conc_unaff )
{
  

  // IBD or IBS segment permutation test for case/control data
  // Calculate total number of concordant/discordant pairs
  
  int tot_conc_aff=0;
  int tot_not=0;
  
  for (int i1=0; i1<n-1; i1++)
    for (int i2=i1+1; i2<n; i2++)
	if ( sample[i1]->aff && sample[i2]->aff ) tot_conc_aff++;
	else
	{
	    if ( par::segment_test_ignore_discordant ) 
	      {
		if ( (!sample[i1]->aff) && (!sample[i2]->aff) )
		  tot_not++;
	      }
	    else
	      tot_not++;
	}
  
  printLOG(int2str(tot_conc_aff)+" concordant affected pairs out of "
	   +int2str(tot_not+tot_conc_aff)+" in total\n");
  
  if ( par::segment_test_ignore_discordant ) 
      printLOG("Comparing case/case to control/control pairs\n");
  else
      printLOG("Comparing case/case to non-case/case pairs\n");


  int nt = nl_all;  // IBS mode
  if (ibd) { nt = nl; } 
  
  perm.setTests(nt);
  perm.setPermClusters(*this);
  perm.originalOrder();

  vector_t original(nt);
  vector_t origSC(nt);
  vector_t origSD(nt);

  // Get genome-wide means

  double SCg = 0;
  double SDg = 0;
  for (int l=0; l<nt; l++)
    {
      SCg += coverage_conc_aff[l];
      SDg += coverage_conc_unaff[l];
      if ( ! par::segment_test_ignore_discordant )
	  SDg += coverage_disc[l];
    }
  
  SCg /= (double)nt;
  SDg /= (double)nt;

  if ( par::segment_test_ignore_discordant )
    printLOG("Genome-wide average sharing (#segs, AA : UU) is " + dbl2str(SCg) + " : " + dbl2str(SDg) + "\n");
  else
    printLOG("Genome-wide average sharing (#segs, AA : AU+UU ) is " + dbl2str(SCg) + " : " + dbl2str(SDg) + "\n");

  for (int l=0; l<nt; l++)
    {
      
      double SC = coverage_conc_aff[l];
      double SD = coverage_conc_unaff[l];
      if ( ! par::segment_test_ignore_discordant )
	  SD += coverage_disc[l];

      // Correct for genome-wide average
//       SC = SC-SCg < 0 ? 0 : SC - SCg;
//       SD = SD-SDg < 0 ? 0 : SD - SDg;

      SC -= SCg;
      SD -= SDg;

      double statistic = SC / (double)tot_conc_aff  -  SD / (double)tot_not ;
//       original[l] = statistic < 0 ? 0 : statistic;
//       original[l] = (SC+SD) >0 ? statistic / (SC+SD) : statistic;
      original[l] = statistic;
      origSC[l] = SC;
      origSD[l] = SD;
    }
  
  
    //////////////////////
    // Begin permutations
    
    // Edit 'fringe' status if in IBD mode
    
     if (ibd)
       {
 	vector<Segment>::iterator s = segment.begin();
 	while ( s != segment.end() )
 	  {
 	    
	    if ( s->start == -1 ) s->start = par::run_start;
 	    if ( s->finish == -1 ) s->finish = par::run_end;
 	    
	    // Edit to make positions relative to start of this chromosome
 	    s->start -= par::run_start;
 	    s->finish -= par::run_start;
	    
	    s++;
 	  }
       }



    bool finished = false;
    while(!finished)
      {
	
	// Store permuted results
	
	vector<double> pr(nt);
	
	// Permute
	
	perm.permuteInCluster();
	
	// Retest
	
	vector<int> coverage_conc_aff(nt,0);
	vector<int> coverage_conc_unaff(nt,0);
	vector<int> coverage_disc(nt,0);
	
	vector<Segment>::iterator s = segment.begin();
	
	while ( s != segment.end() )
	  {    
	    
	    if (s->p1->pperson->aff == s->p2->pperson->aff)
	      {
		if ( s->p1->pperson->aff) 
		  for (int l = s->start ; l <= s->finish; l++) coverage_conc_aff[l]++;
		else
		  for (int l = s->start ; l <= s->finish; l++) coverage_conc_unaff[l]++;
	      }
	    else
	      for (int l = s->start ; l <= s->finish; l++) coverage_disc[l]++;
	    
	    s++;
	  }
	
	double SCg = 0;
	double SDg = 0;
	for (int l=0; l<nt; l++)
	{
	    SCg += coverage_conc_aff[l];
	    SDg += coverage_conc_unaff[l];
	    if ( ! par::segment_test_ignore_discordant )
		SDg += coverage_disc[l];
	}
	
	SCg /= (double)nt;
	SDg /= (double)nt;

	for (int l=0; l<nt; l++)
	  {
	    
	    double SC = coverage_conc_aff[l];
	    double SD = coverage_conc_unaff[l];
	    if ( ! par::segment_test_ignore_discordant )
		SD += coverage_disc[l];

	    // Correct for genome-wide average
//  	    SC = (SC-SCg < 0) ? 0 : SC - SCg;
//  	    SD = (SD-SDg < 0) ? 0 : SD - SDg;
	    
	    SC -= SCg;
	    SD -= SDg;
    
	    double statistic = SC / (double)tot_conc_aff - (double)SD / tot_not ;
// 	    pr[l] = statistic < 0 ? 0 : statistic;
// 	    pr[l] = (SC+SD) > 0 ? statistic / (SC+SD) : statistic;
	    pr[l] = statistic;
	  }
	
	
	
	////////////////////////////////
	// Standard permutation counting
	
	finished = perm.update(pr,original);
	
      }
    
    if (!par::silent)
      cout << "\n\n";
  
  
    ////////////////////////////
    // Display permuted p-values
    
    f += ".mperm";
    printLOG("Writing segment test permutation results to [ "+f+" ]\n");
    
    ofstream SIBS;
    SIBS.open( f.c_str() , ios::out );
    SIBS.precision(4);

    SIBS << setw(4) << "CHR" << " "
	 << setw(par::pp_maxsnp) << "SNP" << " "
	 << setw(10) << "STAT" << " "
	 << setw(10) << "CONA" << " "
	 << setw(10) << "OTHER" << " "
	 << setw(10) << "EMP1" << " " 
	 << setw(10) << "EMP2" << "\n";

    for (int l=0; l<nt; l++)
      {	
	
	if (!ibd)
	  SIBS << setw(4)  << locus[l]->chr << " " 
	       << setw(par::pp_maxsnp) << locus[l]->name << " ";
	  
	  SIBS << setw(10) << original[l]  << " " 
	       << setw(10) << origSC[l] << " " 
	       << setw(10) << origSD[l] << " " 
	       << setw(10) << perm.pvalue(l) << " "
	       << setw(10) << perm.max_pvalue(l) << "\n";      
	
    }

  SIBS.close();

}



void Plink::testGenomeIBDByCovariate(Perm & perm)
{
  
  // Calculate case/case, control/control and case/control
  // Comparisons:

  //   1) Case/case versus all others
  //   2) Case/control versus all others
  //   3) Control/control versus all others

  //   4) Case/case versus case/control
  //   5) Control/Control versus case/control
  //   6) Case/case versus control/control

  // Test based on yes/no dichotomy for % pairs above certain PIHAT threshold 
  
  int tot_conc_aff=0;
  int tot_conc_unaff=0;
  int tot_disc=0;
  
  for (int i1=0; i1<n-1; i1++)
    for (int i2=i1+1; i2<n; i2++)
      {
	if ( sample[i1]->aff )
	  {
	    if ( sample[i2]->aff ) 
	      tot_conc_aff++;
	    else tot_disc++;
	  }
	else
	  {
	    if ( sample[i2]->aff ) 
	      tot_disc++;
	    else tot_conc_unaff++;
	  }
      }

  printLOG(int2str(tot_conc_aff)+" concordant affected pairs\n");
  printLOG(int2str(tot_conc_unaff)+" concordant unaffected pairs\n");
  printLOG(int2str(tot_disc)+" discordant pairs\n");
  printLOG(int2str(tot_conc_aff+tot_conc_unaff+tot_disc)+" total pairs\n");
  
  int nt = 6;  // six tests (above)

  perm.setTests(nt);
  perm.setPermClusters(*this);
  perm.originalOrder();


  ///////////////////////////
  // Original test statistics

  vector<double> original(nt);

  
  // Iterate over all pairs
  
  double prop_11 = 0;
  double prop_01 = 0;
  double prop_00 = 0;

  int c=0;
  for (int i1=0; i1<n-1; i1++)
    for (int i2=i1+1; i2<n; i2++)
      {
	Individual * p1 = sample[i1];
	Individual * p2 = sample[i2];
	
	int2 pair;
	pair.p1 = i1;
	pair.p2 = i2;

	// 	cout << c << " of " << saved_IBDg.size() << " check : \n";
	// 	cout << saved_IBDg[c].z1/2+saved_IBDg[c].z2 << "\n";
	// 	c++;
	//	cout <<"\n";


	if ( related.find(pair) != related.end() )
	  {
	    if ( sample[i1]->aff )
	      {
		if ( sample[i2]->aff ) 
		  prop_11++;
		else prop_01++;
	      }
	    else
	      {
		if ( sample[i2]->aff ) 
		  prop_01++;
		else prop_00++;
	      }
	  }
	
      }
  
  //   1) Case/case versus all others
  //   2) Case/control versus all others
  //   3) Control/control versus all others

  //   4) Case/case versus case/control
  //   5) Control/Control versus case/control
  //   6) Case/case versus control/control

  
  original[0] = (double)prop_11/(double)tot_conc_aff -   double(prop_01+prop_00)/(double)(tot_disc+tot_conc_unaff) ;
  original[1] = (double)prop_01/(double)tot_disc -       double(prop_11+prop_00)/(double)(tot_conc_aff+tot_conc_unaff) ;
  original[2] = (double)prop_00/(double)tot_conc_unaff - double(prop_01+prop_11)/(double)(tot_disc+tot_conc_aff) ;
  
  original[3] = (double)prop_11/(double)tot_conc_aff -   double(prop_01)/(double)(tot_disc) ;
  original[4] = (double)prop_00/(double)tot_conc_unaff - double(prop_01)/(double)(tot_disc) ;
  original[5] = (double)prop_11/(double)tot_conc_aff -   double(prop_00)/(double)(tot_conc_unaff) ;


  ////////////////////
  // Begin permutations
  
  bool finished = false;
  while(!finished)
    {
      
      // Store permuted results
      
      vector<double> pr(nt,0);
      
      // Permute
      
      perm.permuteInCluster();
      
      // Retest
      
      double prop_11 = 0;
      double prop_01 = 0;
      double prop_00 = 0;
      
      for (int i1=0; i1<n-1; i1++)
	for (int i2=i1+1; i2<n; i2++)
	  {
	    Individual * p1 = sample[i1];
	    Individual * p2 = sample[i2];
	    
	    int2 pair;
	    pair.p1 = i1;
	    pair.p2 = i2;
	    
	    if ( related.find(pair) != related.end() )
	      {
		if ( sample[i1]->pperson->aff )
		  {
		    if ( sample[i2]->pperson->aff ) 
		      prop_11++;
		    else prop_01++;
		  }
		else
		  {
		    if ( sample[i2]->pperson->aff ) 
		      prop_01++;
		    else prop_00++;
		  }
	      }
	    
	  }
      
      //   1) Case/case versus all others
      //   2) Case/control versus all others
      //   3) Control/control versus all others
      
      //   4) Case/case versus case/control
      //   5) Control/Control versus case/control
      //   6) Case/case versus control/control

      pr[0] = (double)prop_11/(double)tot_conc_aff -   double(prop_01+prop_00)/(double)(tot_disc+tot_conc_unaff) ;
      pr[1] = (double)prop_01/(double)tot_disc -       double(prop_11+prop_00)/(double)(tot_conc_aff+tot_conc_unaff) ;
      pr[2] = (double)prop_00/(double)tot_conc_unaff - double(prop_01+prop_11)/(double)(tot_disc+tot_conc_aff) ;
      
      pr[3] = (double)prop_11/(double)tot_conc_aff -   double(prop_01)/(double)(tot_disc) ;
      pr[4] = (double)prop_00/(double)tot_conc_unaff - double(prop_01)/(double)(tot_disc) ;
      pr[5] = (double)prop_11/(double)tot_conc_aff -   double(prop_00)/(double)(tot_conc_unaff) ;
      	
      
      ////////////////////////////////
      // Standard permutation counting
      
      finished = perm.update(pr,original);
	
      }
    
    if (!par::silent)
      cout << "\n\n";
  
  
    ////////////////////////////
    // Display permuted p-values
    
    string f = par::output_file_name + ".genome.mperm";
    printLOG("Writing permuted results for genome-wide IBD test to [ "+f+" ]\n");
    
    ofstream SIBS;
    SIBS.open( f.c_str() , ios::out );
    
    for (int l=0; l<nt; l++)
      {	
	
	SIBS << setw(4) << l << " "  
	     << setw(12) << original[l]  << " " 
	     << setw(12) << perm.pvalue(l) << " "
	     << setw(12) << perm.max_pvalue(l) << "\n";      
	
    }

  SIBS.close();

}

void Plink::validateSegments()
{
  // Individual major
  if (par::SNP_major) SNP2Ind();

  // Consider all segments

  string f = par::output_file_name + ".sibs";

  printLOG("Writing segmental IBS information to [ " + f + " ]\n");

  ofstream SIBS;
  SIBS.open(f.c_str(), ios::out);

  SIBS << setw(10) << "IBS0" << " "
       << setw(10) << "IBS1" << " "
       << setw(10) << "IBS2" << " "
       << setw(10) << "MISS" << "\n";
  
  vector<Segment>::iterator s = segment.begin();

  while ( s != segment.end() )
    {
      
      int c2 = 0;
      int c1 = 0;
      int c0 = 0;
      int cx = 0;

      for (int l = s->start; 
	   l <= s->finish; 
	   l++)
	{
	  
	  bool a1 = s->p1->one[l];
	  bool a2 = s->p1->two[l];

	  bool b1 = s->p2->one[l];
	  bool b2 = s->p2->two[l];

	  bool ibs0 = false;
	  bool ibs1 = false;
	  bool miss = false;

	  if ( a1 == a2 &&
	       b1 == b2 &&
	       a1 != b1  ) ibs0 = true;
	  else if ( a1 && !(a2) ) miss = true;
	  else if ( b1 && !(b2) ) miss = true;
	  else if ( a1 != b1 ||
		    a2 != b2 ) ibs1 = true;

	  if (ibs0) c0++;
	  else if (ibs1) c1++;
	  else if (miss) cx++;
	  else c2++;
	}

      SIBS << setw(10) << c0 << " " 
	   << setw(10) << c1 << " " 
	   << setw(10) << c2 << " " 
	   << setw(10) << cx << "\n"; 
    
      // Next segment 
      s++;

    }

  SIBS.close();
  

}



//////////////////////////////////////////////
// General segmental permutation test routine

void Plink::summaryIBSsegments(Perm & perm)
{

  vector<int> coverage_conc_aff(nl_all,0);
  vector<int> coverage_conc_unaff(nl_all,0);
  vector<int> coverage_disc(nl_all,0);
  
  vector<Segment>::iterator s = segment.begin();
  
  while ( s != segment.end() )
    {    
      
      if (s->p1->aff == s->p2->aff)
	{
	  if ( s->p1->aff) 
	    for (int l = s->start ; l <= s->finish; l++) 
	      coverage_conc_aff[l]++;
	  else
	    for (int l = s->start ; l <= s->finish; l++) 
	      coverage_conc_unaff[l]++;
	}
      else
	for (int l = s->start ; l <= s->finish; l++) 
	  coverage_disc[l]++;
      
      s++;
    }

  
  // Optionally, if we allow 'wings' to increase span 
  // of events (and so, each data point represents the 
  // number of events with X kb of that position)
  
  if ( ( par::homo_run || par::cnv_list ) && par::seg_test_window )
    {

      printLOG("Summarising segments within a window of " 
	       + int2str((int)(par::seg_test_window_bp/1000))
	       + " kb\n");

      
      vector<Segment>::iterator s = segment.begin();
      while ( s != segment.end() )
	{    	      
	  
	  // Shift left from start
	  
	  int l = s->start;
	  Locus * loc1 = locus[s->start];
	  while ( 1 )
	    {
	      --l;
	      if ( l < 0 ) break;
	      Locus * loc2 = locus[l];
	      if ( loc2->chr != loc1->chr ) break;
	      if ( loc1->bp - loc2->bp > par::seg_test_window_bp  ) break;
	      if ( s->p1->aff )
		++coverage_conc_aff[l];
	      else
		++coverage_conc_unaff[l];
	    }
	  
	  // Shift right from start
	  l = s->finish;
	  loc1 = locus[s->finish];
	  while ( 1 )
	    {
	      ++l;
	      if ( l == nl_all ) break;
	      Locus * loc2 = locus[l];
	      if ( loc2->chr != loc1->chr ) break;
	      if ( loc2->bp - loc1->bp > par::seg_test_window_bp  ) break;
	      if ( s->p1->aff )
		++coverage_conc_aff[l];
	      else
		++coverage_conc_unaff[l];
	    }
	  
	  // Next segment
	  s++;
	}	  
    }
  
  
  
  string f = par::output_file_name;

  if ( par::segment_output ) 
    f += ".segment.summary";
  else if ( par::homo_run )
    f += ".hom.summary";
  else if ( par::cnv_list )
    f += ".cnv.summary";
  else if ( par::ibs_2only )
    f += ".ibs2.summary";
  else
    f += ".ibs.summary";


  


  /////////////////////////////////////
  // Treat CNVs as homozygous segments
  // i.e. just a per-individual and not
  //      a per-pair phenomenon

  if ( par::cnv_list )
    par::homo_run = true;


  ofstream SIBS;
  SIBS.open( f.c_str() , ios::out );
  


  //////////////////////////////
  // And display

  if ( par::homo_run )
    SIBS << setw(4) << "CHR" << " " 
	 << setw(par::pp_maxsnp) << "SNP" << " " 
	 << setw(12) << "BP" << " "
	 << setw(8) << "AFF" << " " 
	 << setw(8) << "UNAFF" << "\n"; 
  else
    SIBS << setw(4) << "CHR" << " " 
	 << setw(par::pp_maxsnp) << "SNP" << " " 
	 << setw(12) << "BP" << " "
	 << setw(8) << "CONA" << " "
	 << setw(8) << "DISC" << " " 
	 << setw(8) << "CONU" << "\n";
  
  for (int l=0; l<nl_all; l++)
    {
      
      if ( par::homo_run )
	SIBS << setw(4) << locus[l]->chr << " " 
	     << setw(par::pp_maxsnp) << locus[l]->name << " " 
	     << setw(12) << locus[l]->bp << " "
	     << setw(8) << coverage_conc_aff[l] << " " 
	     << setw(8) << coverage_conc_unaff[l] << "\n"; 
      else
	SIBS << setw(4) << locus[l]->chr << " " 
	     << setw(par::pp_maxsnp) << locus[l]->name << " " 
	     << setw(12) << locus[l]->bp << " "
	     << setw(8) << coverage_conc_aff[l] << " "
	     << setw(8) << coverage_disc[l] << " " 
	     << setw(8) << coverage_conc_unaff[l] << "\n";       
    }
  
  SIBS.close();


  //////////////////////////////////
  // Permutation test, if C/C given?

  if (!par::permute) return;
  
  if (par::homo_run)
    homozygousSegmentPermutationTest(perm,f,coverage_conc_aff,coverage_conc_unaff);
  else
    segmentPermutationTest(perm,false,f,coverage_conc_aff,coverage_disc,coverage_conc_unaff);

  return;

}





void Plink::summaryIBDsegments(Perm & perm)
{

  // Number of map positions
  // (extra position for global IBD)
  int npos = m1.size() - 1;
  
  vector<int> coverage_conc_aff(nl,0);
  vector<int> coverage_conc_unaff(nl,0);
  vector<int> coverage_disc(nl,0);
  
  // pihat[pair][position]
  // check if, e.g. pihat>0.2 (i.e. atleast 80% chance of IBD1 sharing)
  // level set in options.cpp

      
  for (int l=0;l<npos;l++)
    {
      
      double p1, p2;
    
      if (m1[l]==-1) 
	{
	  p1 = locus[par::run_start]->pos - par::fringe;
	}
      else 
	{
	  p1 = locus[m1[l]]->pos;
	}
      
      if (m2[l]==-1) 
	{
	  p2 = locus[par::run_end]->pos + par::fringe;
	}
      else 
	{
	  p2 = locus[m2[l]]->pos;
	}
      
      if (m1[l]==-1 && m2[l]==-1)
	{
	  p1 = p2 = 0;
	}
      
      double d1 = p1 + pos[l] * (p2-p1);

      
      vector<Segment>::iterator s = segment.begin();
      
      while ( s != segment.end() )
	{    
	  
	  if ( locus[s->start]->chr != par::run_chr )
	    {
	      s++;
	      continue;
	    }
	  
	  
	  // In segment?
	  if (locus[s->start]->pos < d1 && locus[s->finish]->pos > d1  )
	    {
	      
	      if (s->p1->aff == s->p2->aff)
		{
		  if ( s->p1->aff) 
		    coverage_conc_aff[l]++;
		  else
		    coverage_conc_unaff[l]++;
		}
	      else
		coverage_disc[l]++;
	      
	    }
	  
	  s++;
	}
      
    }
  
  
  string f = par::output_file_name + ".segment.summary";

  ofstream SSEG;
  if (par::segment_output_started)
     SSEG.open( f.c_str() , ios::app );
  else
     SSEG.open( f.c_str() , ios::out );
  par::segment_output_started = true;

  //////////////////////////////
  // And display
  
  for (int l=0; l<npos; l++)
    {
      
      double p1, p2;
      string n1, n2;
      double fr=0;
      
      ////////////////////////////////
      // Single and multipoint output
      
      if (m1[l]==-1) 
	{
	  p1 = locus[par::run_start]->pos - par::fringe;
	  n1 = "fringe";
	}
      else 
	{
	  p1 = locus[m1[l]]->pos;
	  n1 = locus[m1[l]]->name;
	  fr = locus[m1[l]]->freq;
	}
      
      if (m2[l]==-1)
	{
	  p2 = locus[par::run_end]->pos + par::fringe;
	  n2 = "fringe";
	}
      else 
	{
	  p2 = locus[m2[l]]->pos;
	  n2 = locus[m2[l]]->name;
	}
      
      if (m1[l]==-1 && m2[l]==-1)
	{
	  p1 = p2 = 0;
	  n1 = "Genomewide";
	  n2 = "IBD";
	}

      double d1 = p1 + pos[l] * (p2-p1);

      SSEG << par::run_chr << " " 
	   << n1 << " " 
	   << n2 << " " 
	   << d1 << "  "
	   << fr << " " 
	   << coverage_conc_unaff[l] << " " 
	   << coverage_disc[l] << " " 
	   << coverage_conc_aff[l] << "\n"; 

    }

  SSEG.close();

  
  ////////////////////////
  // C/C permutation test?

  if (!par::permute) return;

  segmentPermutationTest(perm,true,f,coverage_conc_aff,coverage_disc,coverage_conc_unaff);

}



void Plink::summaryIBD()
{

  int npos = pihat[0].size();
  int npair = pihat.size();
  
  vector<int> coverage(npos,0);
  
  vector<int> coverage_conc_aff(npos,0);
  vector<int> coverage_conc_unaff(npos,0);
  vector<int> coverage_disc(npos,0);
  
  // pihat[pair][position]
  // check if, e.g. pihat>0.2 (i.e. atleast 80% chance of IBD1 sharing)
  // level set in options.cpp

  for (int i=0;i<pihat.size();i++)
    for (int j=0;j<npos;j++)
      {
	if (pihat[i][j] > par::IBD_threshold )
	  {
	    coverage[j]++;
	    
	    if (sample[pair1[i]]->phenotype 
		!= sample[pair2[i]]->phenotype) 
	      coverage_disc[j]++;
	    
	    if (sample[pair1[i]]->phenotype==1 
		&& sample[pair2[i]]->phenotype==1) 
	      coverage_conc_unaff[j]++;

	    if (sample[pair1[i]]->phenotype==2 
		&& sample[pair2[i]]->phenotype==2) 
	      coverage_conc_aff[j]++;
	  }
      }


  //////////////////////////////
  // And display
  
  for (int l=0; l<npos; l++)
    {
      
      double p1, p2;
      string n1, n2;
      double fr = 0;

      ////////////////////////////////
      // Single and multipoint output
      
      if (m1[l]==-1) 
	{
	  p1 = locus[par::run_start]->pos - par::fringe;
	  n1 = "fringe";
	}
      else 
	{
	  p1 = locus[m1[l]]->pos;
	  n1 = locus[m1[l]]->name;
	  fr = locus[m1[l]]->freq;
	}
      
      if (m2[l]==-1) 
	{
	  p2 = locus[par::run_end]->pos + par::fringe;
	  n2 = "fringe";
	}
      else 
	{
	  p2 = locus[m2[l]]->pos;
	  n2 = locus[m2[l]]->name;
	}
      
      if (m1[l]==-1 && m2[l]==-1)
	{
	  p1 = p2 = 0;
	  n1 = "Genomewide";
	  n2 = "IBD";
	}
      
      double d1 = p1 + pos[l] * (p2-p1);
      
      cout << "C " 
	   << par::run_chr << " " 
	   << n1 << " " 
	   << n2 << " " 
	   << d1 << "  "
	   << fr << " " 
	   << coverage[l] << " " 
	   << coverage_conc_unaff[l] << " " 
	   << coverage_disc[l] << " " 
	   << coverage_conc_aff[l] << " " 
	   << coverage[l]/(double)npair << "\n"; 
    }
}


void Plink::displayGMULTI(Individual * p1, Individual * p2, int l, ofstream & GMULTI)
{

  Locus * loc = locus[l];

  bool a1 = p1->one[l];
  bool a2 = p1->two[l];

  bool b1 = p2->one[l];
  bool b2 = p2->two[l];

  bool miss = false;
  
  GMULTI << setw(par::pp_maxfid) << p1->fid << " "
	 << setw(par::pp_maxiid) << p1->iid << " "
	 << setw(par::pp_maxfid) << p2->fid << " "
	 << setw(par::pp_maxiid) << p2->iid << " "
	 << setw(par::pp_maxsnp) << loc->name << " ";

  // Minor allele and frequency 

  GMULTI << setw(2) << loc->allele1 << " "
	 << setw(8) << loc->freq << " ";

  // Genotypes

  if ((!a1) && (!a2)) 
    GMULTI << setw(4) 
	   << loc->allele1+"/"+loc->allele1 
	   << " ";
  else if ((!a1) && a2) 
    GMULTI << setw(4) 
	   << loc->allele1+"/"+loc->allele2
	   << " ";
  else if (a1 && a2) 
    GMULTI << setw(4) 
	   << loc->allele2+"/"+loc->allele2
	   << " ";
  else 
    {
      GMULTI << setw(4) << "0/0" << " ";
      miss = true; 
    }
  
  if ((!b1) && (!b2)) 
    GMULTI << setw(4) 
	   << loc->allele1+"/"+loc->allele1;
  else if ((!b1) && b2) 
    GMULTI << setw(4) 
	   << loc->allele1+"/"+loc->allele2;
  else if (b1 && b2) 
    GMULTI << setw(4) 
	   << loc->allele2+"/"+loc->allele2;
  else 
    {
      GMULTI << setw(4) << "0/0";
      miss = true;
    }

  // IBS count

  if (miss)
    GMULTI << setw(3) << "NA" << " ";
  else
    {
      int ibs=0;
      if (a1==b1) ibs++;
      if (a2==b2) ibs++;
      GMULTI << setw(3) << ibs << " ";
    }

  GMULTI << "\n";
  
}


void Plink::indivSegmentSummaryCalc(map<indivPair,int> & segmentCount,
				    map<indivPair,double> & segmentLength,
				    bool countCases, bool countControls )
{

  segmentCount.clear();
  segmentLength.clear();
  segmentCount2.clear();

  if ( par::cnv_count_baseline )
    segmentCount2Baseline.clear();

  vector<Segment>::iterator s = segment.begin();
  
  while ( s != segment.end() )
    {    
      
      indivPair p;
      p.p1 = s->p1;
      p.p2 = s->p2;

      // For now, assume that case/control masking only applies
      // to homozygosity and CNV tests

      if ( ! countCases && s->p1->pperson->aff )
	continue;
      
      if ( ( !countControls )  && ! s->p1->pperson->aff )
	continue;


      // We have not yet seen this indiv/pair
      
      map<indivPair,int>::iterator ip = segmentCount.find(p);
      map<indivPair,double>::iterator il = segmentLength.find(p);
      map<indivPair,double>::iterator ic2 = segmentCount2.find(p);
      
      // KB length

      double l = (double)(locus[s->finish]->bp 
			  - locus[s->start]->bp)/(double)1000;
      
      if ( ip  == segmentCount.end() )
	{
	  segmentCount.insert( make_pair( p, 1 ) );
	  segmentLength.insert( make_pair( p, l ) );
	  	  
	  if ( par::cnv_weighted_gene_test )
	    {
	      segmentCount2.insert( make_pair( p, s->weightedCount ));
	      if ( par::cnv_count_baseline )
		segmentCount2Baseline.insert( make_pair( p, s->weightedBaseline ));
	    }
	  else
	    {
	      segmentCount2.insert( make_pair( p, s->count ));
	      if ( par::cnv_count_baseline )
		segmentCount2Baseline.insert( make_pair( p, s->baseline ));
	    }
	}
      else
	{
	  (ip->second)++;
	  (il->second) += l;
	  
	  if ( par::cnv_weighted_gene_test )
	    {
	      (ic2->second) += s->weightedCount;
	      if ( par::cnv_count_baseline )
		{
		  map<indivPair,double>::iterator ic2b = segmentCount2Baseline.find(p);
		  (ic2b->second) += s->weightedBaseline;
		}
	    }
	  else
	    {

	      (ic2->second) += s->count;

	      if ( par::cnv_count_baseline )
		{
		  map<indivPair,double>::iterator ic2b = segmentCount2Baseline.find(p);
		  (ic2b->second) += s->baseline;
		}
	    }

	}

      s++;
    }

}


void Plink::indivSegmentSummary()
{
  
  // Again, this function works for both homozygous and shared
  // segments (individuals and pairs)
  
  // Now these are part of Plink class
  //map<indivPair,int> segmentCount;
  //map<indivPair,double> segmentLength;
  
  // Generate basic summary file for all people
  indivSegmentSummaryCalc(segmentCount, segmentLength, true, true);
  

  ////////////
  // Output

  string f = par::output_file_name;
  
  if ( par::segment_output ) 
    f += ".segment.indiv";
  else if ( par::cnv_list )
    f += ".cnv.indiv";
  else if ( par::homo_run )
    f += ".hom.indiv";

  ofstream HOM;
  HOM.open( f.c_str() , ios::out );
  
  if ( par::homo_run )
    HOM << setw(par::pp_maxfid) << "FID" << " " 
	<< setw(par::pp_maxiid) << "IID" << " " 
	<< setw(4) << "PHE" << " "
	<< setw(8) << "NSEG" << " " 
	<< setw(8) << "KB" << " "
	<< setw(8) << "KBAVG" << "\n"; 
  else if ( par::cnv_list )
    {    
      HOM << setw(par::pp_maxfid) << "FID" << " " 
	  << setw(par::pp_maxiid) << "IID" << " " 
	  << setw(4) << "PHE" << " "
	  << setw(8) << "NSEG" << " "
	  << setw(8) << "KB" << " "
	  << setw(8) << "KBAVG" << " ";
      if ( par::cnv_count ) 
	HOM << setw(8) << "COUNT" << " ";
      HOM << "\n";
    }
  else
    HOM << setw(par::pp_maxfid) << "FID1" << " " 
	<< setw(par::pp_maxiid) << "IID2" << " " 
	<< setw(par::pp_maxfid) << "FID1" << " " 
	<< setw(par::pp_maxiid) << "IID2" << " " 
	<< setw(4) << "PHE" << " "
	<< setw(8) << "NSEG" << " " 
	<< setw(8) << "KB" << " " 
	<< setw(8) << "KBAVG" << "\n"; 

  
  // Output all individuals in homozygous segment mode

  if ( par::homo_run || par::cnv_list ) 
    {
      
      for ( int i = 0; i < n; i++)
	{
	
	  indivPair t;
	  t.p1 = t.p2 = sample[i];

	  map<indivPair,int>::iterator ic = segmentCount.find(t);
	  map<indivPair,double>::iterator il = segmentLength.find(t);
	  map<indivPair,double>::iterator ic2 = segmentCount2.find(t);
	  
	  indivPair p = ic->first;
	  
	  HOM << setw(par::pp_maxfid) << sample[i]->fid << " " 
	      << setw(par::pp_maxiid) << sample[i]->iid << " "
	      << setw(4) << sample[i]->phenotype << " ";
	  
	  if ( ic != segmentCount.end() ) 
	    {
	      HOM << setw(8) << ic->second << " " 
		  << setw(8) << il->second << " "
		  << setw(8) << il->second / (double)ic->second << " ";
	      if ( par::cnv_count )
		HOM << setw(8) << ic2->second << " ";
	      HOM << "\n";
	    }
	  else
	    {
	      HOM << setw(8) << 0 << " " 
		  << setw(8) << 0 << " ";
	      if ( par::cnv_count )
		HOM << setw(8) << 0 << " ";
	      HOM << setw(8) << 0 << "\n";
	    }

	}  // Next individual
    }
  else
    {
      // For now, just output obsevred pairs in segment mode
      // (i.e. typically too many pairs)

      map<indivPair,int>::iterator ic = segmentCount.begin();
      map<indivPair,double>::iterator il = segmentLength.begin();
      
      while ( ic != segmentCount.end() )
	{
	  indivPair p = ic->first;
	  
	  HOM << setw(par::pp_maxfid) << p.p1->fid << " " 
	      << setw(par::pp_maxiid) << p.p1->iid << " ";
	  
	  if ( p.p1 != p.p2 )
	    {
	      int pcode = 0;
	      if ( p.p1->aff ) 
		{
		  if ( p.p2->aff ) 
		    pcode = 1;
		  else 
		    pcode = 0;
		}
	      else
		{
		  if ( p.p2->aff ) 
		    pcode = 0;
		  else 
		    pcode = -1;
		}	    
	      
	      HOM << setw(par::pp_maxfid) << p.p2->fid << " " 
		  << setw(par::pp_maxiid) << p.p2->iid << " "
		  << setw(4) << pcode << " "; 
	    }
	  else
	    HOM << setw(4) << p.p1->phenotype << " ";
	  
	  HOM << setw(8) << ic->second << " " 
	      << setw(8) << il->second << " "
	      << setw(8) << il->second / (double)ic->second << "\n";
	  
	  ++ic;
	  ++il;
	}
    }
  
  HOM.close();
    
}

class SegmentSizeCmp {
public:  
  bool operator() (const Segment & s1, const Segment & s2) const 
  {
    int len1 = s1.finish - s1.start;
    int len2 = s2.finish - s2.start;
    
    if ( len1 < len2 ) 
      return true;
    if ( len1 > len2 ) 
      return false;

    if ( s1.p1 < s2.p1 ) 
      return true;
    
    if ( s1.p1 > s2.p1 ) 
      return false;

    return ( s1.start < s2.start );
  }
};




void Plink::displaySegmentsLong()
{
  
   printLOG("Writing long-format segment list to [ " 
 	   + par::output_file_name + ".cnv.seglist ]\n");

   ofstream SEG;
   string f = par::output_file_name + ".cnv.seglist";
   SEG.open( f.c_str(), ios::out );

   // Determine list of which chromosomes we need to report 
   // on

   set<int> chr;
   for (int l=0; l<nl_all; l++)
     chr.insert( locus[l]->chr );
   set<int>::iterator ichr = chr.begin();

   // Consider each chromosome, one at a time

   while ( ichr != chr.end() )
     {
    
       SEG << "\nChromosome " << *ichr << "\n\n";
    
       // Sort list of events in decreasing size
       // for this chromosome
    
       map<Segment,int,SegmentSizeCmp> smap;
       vector<Segment>::iterator s = segment.begin();      
       while ( s != segment.end() )
 	{
 	  if ( locus[ s->start ]->chr == *ichr )
 	    {
 	      smap.insert(make_pair(*s,0));
 	    }
 	  ++s;
 	}
    


       ///////////////////////////////////////////////////////
       // How many segments to consider on this chromosome?

       int nseg = smap.size();

       // For each segment, determine "height"
    
       map<Segment,int,SegmentSizeCmp>::iterator i1 = smap.begin();     

       while ( i1 != smap.end() )
 	{	  

 	  // Look at all smaller than this one
 	  map<Segment,int,SegmentSizeCmp>::iterator i2 = i1;

 	  while ( i2 != smap.end() )
 	    {
 	      if ( i1 == i2 )
 		{
 		  ++i2;
 		  continue;
 		}

 	      const Segment * s1 = &(i1->first);
 	      const Segment * s2 = &(i2->first);

//     	      cout << s1->start << " - " << s1->finish 
//     		   << " to " << s2->start << " - " << s2->finish << "\n";
//     	      cout << "overlap test\n";


 // 	      if ( ( s2->finish >= s1->start && s2->start <= s1->finish ) ||
 // 		   ( s1->finish >= s2->start && s1->start <= s2->finish ) )

 	      if ( s2->finish >= s1->start && s2->start <= s1->finish )     
 		{
 		  // Place this small segment one above the larger one
		  (i2->second) = (i1->second) + 1;
 		}
 	      ++i2;
 	    }
 	  ++i1;
 	}
    
       // Take smallest segment;
       // if any larger on overlaps

       // for (int i=1; i<nseg; i++)
       //  for (int j=i-1; j>=0; j--)
       // Use overlap <- function(x,y,k)
       //{ 
       // k$BP2[y] >= k$BP1[x] && k$BP1[y] <= k$BP2[x] 
       //}
       // if ( overlap(i,j,k) )
       // ++h[i];
  
 
       // Map into per-row logic

       // Find max height

       i1 = smap.begin();
       int maxh = 0;
       while ( i1 != smap.end() )
 	{
 	  if ( i1->second > maxh )
 	    maxh = i1->second;
 	  ++i1;
 	}

       ++maxh;

 //       cout << "Segs = \n";
 //       i1 = smap.begin();
 //       while ( i1 != smap.end() )
 // 	{
 // 	  const Segment * s = &(i1->first);
 // 	  cout << locus[ s->start ]->bp << " to " << locus[ s->finish ]->bp << ", h = " << i1->second << "\n";
 // 	  ++i1;
 // 	}
 //       cout << "-------\n";



       vector<bool> switches(maxh,false);
    
       // Display
       int chrmin = 0;
       int chrmax = 0;
       int tmp = 0;
       for (int l=0; l<nl_all; l++)
 	if ( locus[l]->chr == *ichr )
 	  {
 	    chrmin = chrmax = l;
 	    tmp = l;
 	    break;
 	  }
    
       for (int l=tmp; l<nl_all; l++)	
 	{
 	  if ( locus[l]->chr > *ichr )
 	    break;
 	  chrmax = l;
 	}

       int interval = 10 * 1000; // 10kb steps
       int fringe = 50 * 1000; // 50kb fringe

       bool done = false;
       int l = chrmin;
       int p = locus[ chrmin ]->bp - fringe;
       if ( p < 0 ) p = 0;

       // Track p (and move l along with it)
       bool firstPosition = true;

       while ( ! done )
 	{

 	  bool atLocus = false;
 	  if ( p == locus[l]->bp )
 	    atLocus = true;
	  
 	  vector<bool> starts(maxh,false);
 	  vector<bool> stops(maxh,false);	  
 	  vector<const Segment*> thisSeg(maxh);

 	  if ( atLocus )
 	    {
 	      i1 = smap.begin();
 	      while ( i1 != smap.end() )
 		{
 		  const Segment * s1 = &(i1->first);
 		  if ( s1->start == l ) 
 		    {
 		      starts[ i1->second ] = true;
 		      switches[ i1->second ] = true;
 		      thisSeg[ i1->second ] = s1;
 		    }
 		  else if ( s1->finish == l ) 
 		    {
 		      stops[ i1->second ] = true;
 		      switches[ i1->second ] = false;
 		      thisSeg[ i1->second ] = s1;
 		    }
 		  ++i1;
 		}
 	    }
	  

 	  //////////////
 	  // Output row
 	  bool display = atLocus;
	 
 	  if ( ! atLocus )
 	    {
 	      for (int j=0; j<maxh; j++)
 		if ( switches[j] )
 		  {
 		    display = true;
 		    break;
 		  }
 	    }
	  
 	  if ( display )
 	    {
 	      if ( atLocus )
 		SEG	<< setw(par::pp_maxsnp) << locus[l]->name << "     ";
 	      else
 		SEG << setw(par::pp_maxsnp) << "("+int2str(p)+")" << "     ";
	      
 	      // Symbols

 	      //  Duplication      +
 	      //  Deletion         -
 	      //  Case             A
               //  Control          U 

	      if ( par::cnv_write_freq )
		{
		  for (int j=0; j<maxh; j++)
		    {
		      if ( starts[j] ) 
			{
			  const Segment * seg = thisSeg[j];
			  if ( seg->freq > 9 ) 			    
			    SEG << seg->freq;	
			  else
			    SEG << seg->freq << " ";	
			}
		      else if ( stops[j] )
			{
			  const Segment * seg = thisSeg[j];
			  if ( seg->freq > 9 ) 			    
			    SEG << seg->freq;	
			  else
			    SEG << seg->freq << " ";	
			}
		      else if ( switches[j] )
			{
			  //const Segment * seg = thisSeg[j];
			  // if ( seg->freq > 9 ) 			    
// 			    SEG << seg->freq;	
// 			  else
			  // SEG << seg->freq << " ";	
			  SEG << "| ";
			}
		      else
			SEG << "  ";
		    }
		  SEG << "\n";
		}
	      else
		{
		  for (int j=0; j<maxh; j++)
		    {
		      if ( starts[j] ) 
			{
			  const Segment * seg = thisSeg[j];
			  if ( seg->type == 1 ) 
			    SEG << "+";
			  else
			    SEG << "-";
			}
		      else if ( stops[j] )
			{
			  const Segment * seg = thisSeg[j];
			  if ( seg->p1->aff ) 
			    SEG << "A";
			  else
			    SEG << "U";
			}
		      else if ( switches[j] )
			SEG << "|";
		      else
			SEG << " ";
		    }
		  SEG << "\n";
		}
	    }

 	  // Advance pointer
 	  p += interval;
	  
 	  // Are we done?	  
 	  if ( p > locus[chrmax]->bp + fringe )
 	    break;
	  
 	  // note -- we might have missed the first one...

 	  // Advance only as far as next SNP position
 	  if ( firstPosition && locus[l]->bp <= p )
 	    {
 	      p = locus[l]->bp;
 	      firstPosition = false;
 	    }
 	  else if ( l < chrmax && locus[l+1]->bp <= p )
 	    {
 	      ++l;
 	      firstPosition = false;
 	      p = locus[l]->bp;
 	    }
	  
 	}

       ++ichr;
     } // Next chromosome


   SEG.close();

}     




void Plink::displaySegmentsBED()
{


  //  BED format provides a flexible way to define the data lines that
  //  are displayed in an annotation track. BED lines have three
  //  required fields and nine additional optional fields. The number
  //  of fields per line must be consistent throughout any single set
  //  of data in an annotation track. The order of the optional fields
  //  is binding: lower-numbered fields must always be populated if
  //  higher-numbered fields are used.

  //The first three required BED fields are:

  // chrom - The name of the chromosome (e.g. chr3, chrY, chr2_random)
  // or scaffold (e.g. scaffold10671).

  // chromStart - The starting position of the feature in the
  // chromosome or scaffold. The first base in a chromosome is
  // numbered 0.

  // chromEnd - The ending position of the feature in the chromosome
  // or scaffold. The chromEnd base is not included in the display of
  // the feature. For example, the first 100 bases of a chromosome are
  // defined as chromStart=0, chromEnd=100, and span the bases
  // numbered 0-99.

  //      The 9 additional optional BED fields are:

  // name - Defines the name of the BED line. This label is displayed
  // to the left of the BED line in the Genome Browser window when the
  // track is open to full display mode or directly to the left of the item in pack mode.

  //  score - A score between 0 and 1000. If the track line useScore
  //  attribute is set to 1 for this annotation data set, the score
  //  value will determine the level of gray in which this feature is
  //  displayed (higher numbers = darker gray).

  // strand - Defines the strand - either '+' or '-'.

  // thickStart - The starting position at which the feature is drawn
  // thickly (for example, the start codon in gene displays).

  // thickEnd - The ending position at which the feature is drawn
  // thickly (for example, the stop codon in gene displays).

  // itemRgb - An RGB value of the form R,G,B (e.g. 255,0,0). If the
  // track line itemRgb attribute is set to "On", this RBG value will
  // determine the display color of the data contained in this BED
  // line. NOTE: It is recommended that a simple color scheme (eight
  // colors or less) be used with this attribute to avoid overwhelming
  // the color resources of the Genome Browser and your Internet
  // browser.

  // blockCount - The number of blocks (exons) in the BED line.

  // blockSizes - A comma-separated list of the block sizes. The
  // number of items in this list should correspond to blockCount.

  // blockStarts - A comma-separated list of block starts. All of the
  // blockStart positions should be calculated relative to
  // chromStart. The number of items in this list should correspond to
  // blockCount.
	
  // Here's an example of an annotation track that uses a complete BED definition:

  //  track name=pairedReads description="Clone Paired Reads" useScore=1
  //  chr22 1000 5000 cloneA 960 + 1000 5000 0 2 567,488, 0,3512
  //  chr22 2000 6000 cloneB 900 - 2000 6000 0 2 433,399, 0,3601
  
  
  printLOG("Writing CNV information as BED track to [ " 
	   + par::output_file_name 
	   + ".cnv.bed ]\n");

  ofstream MOUT;

  MOUT.open( ( par::output_file_name + ".cnv.bed").c_str() , ios::out );
  
  MOUT << "track name=delCases description=\"Deletions, cases (PLINK CNV track)\" visibility=4 priority=1 itemRgb=\"On\"\n"; 
  vector<Segment>::iterator s = segment.begin();
  while ( s != segment.end() )
    {
      
      Individual * person = s->p1;
      
      if ( s->type == 1 && person->aff ) 
	{

	  int pos1 = locus[s->start]->bp;
	  int pos2 = locus[s->finish]->bp+1;
            
	  MOUT << "chr" << chromosomeName( locus[s->start]->chr ) << " " 
	       << pos1 << " " << pos2 << " "
	       << (person->fid + "_" + person->iid ) << " " 
	       << s->score << " " 
	       << ". "
	       << pos1 << " " << pos2 << " ";
	  // Colour
	  
	  if ( par::cnv_col == 0 )
	    MOUT << "255,0,0\n";
	  else if ( par::cnv_col = 1 ) 
	    MOUT << "0,0,255\n";
	  else if ( par::cnv_col = 2 ) 
	    MOUT << "0,255,0\n";
	  else if ( par::cnv_col = 3 ) 
	    MOUT << "255,0,0\n";
	}

      ++s;
    }


  MOUT << "track name=dupCases description=\"Duplications, cases (PLINK CNV track)\" visibility=4 priority=3 itemRgb=\"On\"\n"; 

  s = segment.begin();
  while ( s != segment.end() )
    {
      
      Individual * person = s->p1;      
      if ( s->type == 2 && person->aff ) 
	{

	  int pos1 = locus[s->start]->bp;
	  int pos2 = locus[s->finish]->bp+1;
	  
	  MOUT << "chr" << chromosomeName( locus[s->start]->chr ) << " " 
	       << pos1 << " " << pos2 << " "
	       << (person->fid + "_" + person->iid ) << " " 
	       << s->score << " " 
	       << ". " << pos1 << " " << pos2 << " ";
	  
	  // Colour
	  if ( par::cnv_col == 0 )
	    MOUT << "0,0,255\n";
	  else if ( par::cnv_col = 1 ) 
	    MOUT << "0,0,255\n";
	  else if ( par::cnv_col = 2 ) 
	    MOUT << "0,255,0\n";
	  else if ( par::cnv_col = 3 ) 
	    MOUT << "255,0,0\n";
	} 
      ++s;
    }
  
  MOUT << "track name=delControls description=\"Deletions, controls (PLINK CNV track)\" visibility=4 priority=2 itemRgb=\"On\"\n"; 
  s = segment.begin();
  while ( s != segment.end() )
    {
      
      Individual * person = s->p1;      
      if ( s->type == 1 && ! person->aff ) 
	{

	  int pos1 = locus[s->start]->bp;
	  int pos2 = locus[s->finish]->bp+1;
	  
	  MOUT << "chr" << chromosomeName( locus[s->start]->chr ) << " " 
	       << pos1 << " " << pos2 << " "
	       << (person->fid + "_" + person->iid ) << " " 
	       << s->score << " " 
	       << ". " << pos1 << " " << pos2 << " ";
	  
	  // Colour
	  if ( par::cnv_col == 0 )
	    MOUT << "128,0,0\n";
	  else if ( par::cnv_col = 1 ) 
	    MOUT << "0,0,255\n";
	  else if ( par::cnv_col = 2 ) 
	    MOUT << "0,255,0\n";
	  else if ( par::cnv_col = 3 ) 
	    MOUT << "255,0,0\n";
	}
      ++s;
    }
  
  MOUT << "track name=dupControls description=\"Duplications, controls (PLINK CNV track)\" visibility=4 priority=4 itemRgb=\"On\"\n"; 
  s = segment.begin();
  while ( s != segment.end() )
    {
      
      Individual * person = s->p1;      
      if ( s->type == 2  && ! person->aff ) 
	{

	  int pos1 = locus[s->start]->bp;
	  int pos2 = locus[s->finish]->bp+1;
	  
	  MOUT << "chr" << chromosomeName( locus[s->start]->chr ) << " " 
	       << pos1 << " " << pos2 << " "
	       << (person->fid + "_" + person->iid ) << " " 
	       << s->score << " " 
	       << ". " << pos1 << " " << pos2 << " ";
	  
	  // Colour
	  if ( par::cnv_col == 0 )
	    MOUT << "0,0,128\n";
	  else if ( par::cnv_col = 1 ) 
	    MOUT << "0,0,255\n";
	  else if ( par::cnv_col = 2 ) 
	    MOUT << "0,255,0\n";
	  else if ( par::cnv_col = 3 ) 
	    MOUT << "255,0,0\n";
	}
      ++s;
    }
  
  MOUT.close();
  
}