File: BorderFile.cxx

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

#include <QGlobalStatic>
#ifdef Q_OS_WIN32
#define NOMINMAX
#endif

#include <algorithm>
#include <cmath>
#include <iostream>
#include <limits>
#include <sstream>

#include "BorderFile.h"
#include "ColorFile.h"
#include "CoordinateFile.h"
#include "DebugControl.h"
#include "FileUtilities.h"
#include "GiftiLabelTable.h"
#include "MathUtilities.h"
#include "StatisticDataGroup.h"
#include "StatisticMeanAndDeviation.h"
#include "TopologyFile.h"
#include "TransformationMatrixFile.h"
#include "Caret6ProjectedItem.h"

/** 
 * Constructor.
 */
Border::Border(const QString& nameIn, const float* centerIn, 
               const float samplingDensityIn, const float varianceIn,
               const float topographyIn, const float arealUncertaintyIn)
{
   borderFile = NULL;
   displayFlag = true;
   nameDisplayFlag = true;
   borderColorIndex = 0;
   borderProjectionID = -1;
   float center[3] = { 0.0, 0.0, 0.0 };
   if (centerIn != NULL) {
      center[0] = centerIn[0];
      center[1] = centerIn[1];
      center[2] = centerIn[2];
   }
   setData(nameIn, center, samplingDensityIn,
           varianceIn, topographyIn, arealUncertaintyIn);
}

/**
 * determine if two borders are the same (same name and links).
 */
bool 
Border::operator==(const Border& b) const
{
   const int numLinks = getNumberOfLinks();
   if (numLinks != b.getNumberOfLinks()) {
      return false;
   }
   
   if (getName() != b.getName()) {
      return false;
   }
   
   for (int i = 0 ; i < numLinks; i++) {
      float me[3], other[3];
      getLinkXYZ(i, me);
      b.getLinkXYZ(i, other);
      
      for (int j = 0; j < 3; j++) {
         if (me[j] != other[j]) {
            return false;
         }
      }
   }
      
   return true;
}

/**
 * Apply transformation matrix to a border.
 */
void
Border::applyTransformationMatrix(TransformationMatrix& tm)
{ 
   const int numLinks = getNumberOfLinks();
   for (int j = 0; j < numLinks; j++) {
      float xyz[3];
      getLinkXYZ(j, xyz);
      double p[4] = { xyz[0], xyz[1], xyz[2], 1.0 };
      tm.multiplyPoint(p);
      xyz[0]   = p[0];
      xyz[1] = p[1];
      xyz[2] = p[2];
      setLinkXYZ(j, xyz);
   }
   if (borderFile != NULL) {
      borderFile->setModified();
   }
}  

/**
 * append a border this "this" one.
 */
void 
Border::appendBorder(const Border& b)
{
   const int numLinks = b.getNumberOfLinks();
   for (int j = 0; j < numLinks; j++) {
      this->addBorderLink(b.getLinkXYZ(j), b.getLinkSectionNumber(j));
   }
}      

/** 
 * Get the data from a border.
 */
void 
Border::getData(QString& nameOut, float centerOut[3], 
                float& samplingDensityOut, float& varianceOut,
                float& topographyOut, float& arealUncertaintyOut) const
{
   nameOut = name;
   centerOut[0] = center[0];
   centerOut[1] = center[1];
   centerOut[2] = center[2];
   samplingDensityOut = samplingDensity;
   varianceOut = variance;
   topographyOut = topographyValue;
   arealUncertaintyOut = arealUncertainty;
}                  

/** 
 * Set the data in a border.
 */
void
Border::setData(const QString& nameIn, const float centerIn[3], 
                const float samplingDensityIn, const float varianceIn,
                const float topographyIn, const float arealUncertaintyIn)
{
   name = nameIn;
   center[0] = centerIn[0];
   center[1] = centerIn[1];
   center[2] = centerIn[2];
   samplingDensity = samplingDensityIn;
   variance = varianceIn;
   topographyValue = topographyIn;
   arealUncertainty = arealUncertaintyIn;
   if (borderFile != NULL) {
      borderFile->setModified();
   }
}

/** 
 * Get the position of a link.
 */
void
Border::getLinkXYZ(const int linkNumber, float xyz[3]) const
{
   xyz[0] = linkXYZ[linkNumber * 3];
   xyz[1] = linkXYZ[linkNumber * 3 + 1];
   xyz[2] = linkXYZ[linkNumber * 3 + 2];
}

/**
 * Set the position of a link.
 */
void
Border::setLinkXYZ(const int linkNumber, const float xyz[3])
{
   linkXYZ[linkNumber * 3]     = xyz[0];
   linkXYZ[linkNumber * 3 + 1] = xyz[1];
   linkXYZ[linkNumber * 3 + 2] = xyz[2];
   if (borderFile != NULL) {
      borderFile->setModified();
   }
}

/**
 * get the radius for a link.
 */
float 
Border::getLinkRadius(const int linkNumber) const
{
   const float r = linkRadii[linkNumber];
   return r;
}

/**
 * set the radius for a link.
 */
void 
Border::setLinkRadius(const int linkNumber, const float radius)
{
   linkRadii[linkNumber] = radius;
   if (borderFile != NULL) {
      borderFile->setModified();
   }
}      

/**
 * set the uncertainty.
 */
void 
Border::setArealUncertainty(const float uncertainty)
{
   arealUncertainty = uncertainty;
   if (borderFile != NULL) {
      borderFile->setModified();
   }
}

/**
 * find first link in "this" border that is within "tolerance" distance
 * of a link in "other border".
 */
bool 
Border::intersection3D(const Border* otherBorder,
                       const float intersectionTolerance,
                       int& myLinkIntersect, 
                       int& otherLinkIntersect) const
{
   const float intersectionToleranceSquared = intersectionTolerance
                                              * intersectionTolerance;
   myLinkIntersect    = -1;
   otherLinkIntersect = -1;
   
   const int myNumLinks = getNumberOfLinks();
   const int otherNumLinks = otherBorder->getNumberOfLinks();
   for (int i = 0; i < myNumLinks; i++) {
      for (int j = 0; j < otherNumLinks; j++) {
         if (MathUtilities::distanceSquared3D(getLinkXYZ(i),
                                              otherBorder->getLinkXYZ(j))
               < intersectionToleranceSquared) {
            myLinkIntersect = i;
            otherLinkIntersect = j;
            return true;
         }
      }
   }
   
   return false;
}
      
/**
 * find links where another border intersects this border (2D borders in X-Y plane).
 */
bool 
Border::intersection2D(const Border* otherBorder, 
                       const bool thisBorderIsClosed,
                       const bool otherBorderIsClosed,
                       int& myLinkIntersect, 
                       int& otherLinkIntersect) const
{
   myLinkIntersect    = -1;
   otherLinkIntersect = -1;
   
   const int myNumLinks = getNumberOfLinks();
   const int otherNumLinks = otherBorder->getNumberOfLinks();
   float intersection[2];
   
   for (int i = 0; i < myNumLinks; i++) {
      int iNext = i + 1;
      if (i == (myNumLinks - 1)) {
         if (thisBorderIsClosed) {
            iNext = 0;
         }
         else {
            continue;
         }
      }
      for (int j = 0; j < (otherNumLinks - 1); j++) {
         int jNext = j + 1;
         if (j == (otherNumLinks - 1)) {
            if (otherBorderIsClosed) {
               jNext = 0;
            }
            else {
               continue;
            }
         }
         if (MathUtilities::lineIntersection2D(getLinkXYZ(i), 
                                               getLinkXYZ(iNext),
                                               otherBorder->getLinkXYZ(j), 
                                               otherBorder->getLinkXYZ(jNext),
                                               intersection)) {
            myLinkIntersect    = i;
            otherLinkIntersect = j;
            return true;
         }
      }
   }
   
   return false;
}      

/**
 * create a border with a subset of the border's links from linkStart to
 * linkEnd (inclusive).
 */
Border* 
Border::getSubSet(const int linkStart, const int linkEnd) const
{
   Border* b = new Border(name, center, samplingDensity, variance, 
                          topographyValue, arealUncertainty);
   if (linkEnd > linkStart) {
      for (int i = linkStart; i <= linkEnd; i++) {
         b->addBorderLink(getLinkXYZ(i), getLinkSectionNumber(i));
      }
   }
   else {
      const int numLinks = getNumberOfLinks();
      for (int i = linkStart; i < numLinks; i++) {
         b->addBorderLink(getLinkXYZ(i), getLinkSectionNumber(i));
      }
      for (int i = 0; i <= linkEnd; i++) {
         b->addBorderLink(getLinkXYZ(i), getLinkSectionNumber(i));
      }
   }
   
   if (b->getNumberOfLinks() > 0) {
      return b;
   }
   else {
      delete b;
      return NULL;
   }
}      

/**
 * Set the flat normal for a link.
 */
void
Border::setLinkFlatNormal(const int linkNumber, const float normal[3])
{
   linkFlatNormal[linkNumber * 2]     = normal[0];
   linkFlatNormal[linkNumber * 2 + 1] = normal[1];
   linkFlatNormal[linkNumber * 2 + 2] = normal[2];
   if (borderFile != NULL) {
      borderFile->setModified();
   }
}

/**
 * Set the section number of a link.
 */
void
Border::setLinkSectionNumber(const int linkNumber, const int section)
{
   linkSection[linkNumber] = section;
   if (borderFile != NULL) {
      borderFile->setModified();
   }
}

/**
 * Distance between two links.
 */
float
Border::distanceBetweenLinks(const int link1, const int link2) const
{
   const float dx = linkXYZ[link1 * 3]     - linkXYZ[link2 * 3];
   const float dy = linkXYZ[link1 * 3 + 1] - linkXYZ[link2 * 3 + 1];
   const float dz = linkXYZ[link1 * 3 + 2] - linkXYZ[link2 * 3 + 2];
   const float dist = std::sqrt(dx*dx + dy*dy + dz*dz);
   return dist;
}

/** 
 * Add a link to the border.
 */
void
Border::addBorderLink(const float xyz[3],
                      const int section, 
                      const float radius)
{
   //
   // Note: Links are placed at origin when they cannot be projected successfully so ignore them
   //
   if ((xyz[0] != 0.0) || (xyz[1] != 0.0) || (xyz[2] != 0.0)) {
      linkXYZ.push_back(xyz[0]);
      linkXYZ.push_back(xyz[1]);
      linkXYZ.push_back(xyz[2]);
      linkRadii.push_back(radius);
      linkFlatNormal.push_back(0.0);
      linkFlatNormal.push_back(0.0);
      linkFlatNormal.push_back(1.0);
      linkSection.push_back(section);
      if (borderFile != NULL) {
         borderFile->setModified();
      }
   }
}

/**
 * insert a border link before the specified link number (use number of links for end).
 */
void 
Border::insertBorderLink(const int linkIndex,
                         const float xyz[3], 
                         const int section, 
                         const float radius)
{
   if (linkIndex >= getNumberOfLinks()) {
      addBorderLink(xyz, section, radius);
   }
   else if (linkIndex >= 0) {
      const int offset3 = linkIndex * 3;
      linkXYZ.insert(linkXYZ.begin() + offset3, xyz[2]);
      linkXYZ.insert(linkXYZ.begin() + offset3, xyz[1]);
      linkXYZ.insert(linkXYZ.begin() + offset3, xyz[0]);
      linkRadii.insert(linkRadii.begin() + linkIndex, radius);
      linkSection.insert(linkSection.begin() + linkIndex, section);
      linkFlatNormal.insert(linkFlatNormal.begin() + offset3, 0.0);
      linkFlatNormal.insert(linkFlatNormal.begin() + offset3, 0.0);
      linkFlatNormal.insert(linkFlatNormal.begin() + offset3, 1.0);
      if (borderFile != NULL) {
         borderFile->setModified();
      }
   }
}

/** 
 * Get the length of border.
 */
float
Border::getBorderLength() const
{
   float len = 0;
   const int numLinks = getNumberOfLinks();
   for (int i = 1; i < numLinks; i++) {
      len += distanceBetweenLinks(i, i - 1);
   }
   return len;
}

/**
 * Clear border links
 */
void
Border::clearLinks()
{
   linkXYZ.clear();
   linkRadii.clear();
   linkFlatNormal.clear();
   linkSection.clear();
   if (borderFile != NULL) {
      borderFile->setModified();
   }
}

/**
 * remove links on negative side of plane.
 */
void 
Border::removePointsOnNegativeSideOfPlane(const float planeNormal[3],
                                          const float pointInPlane[3])
{
   const int num = getNumberOfLinks();
   for (int i = (num - 1); i >= 0; i--) {
      const float signedDistance = 
         MathUtilities::signedDistanceToPlane(planeNormal,
                                              pointInPlane,
                                              getLinkXYZ(i));
      if (signedDistance < 0.0) {
         removeLink(i);
      }
   }
}
      

/**
 * Remove a border link
 */
void
Border::removeLink(const int linkNumber)
{
   if (linkNumber < getNumberOfLinks()) {
      const int offset3 = linkNumber * 3;
      linkXYZ.erase(linkXYZ.begin() + offset3, linkXYZ.begin() + offset3 + 3);
      const int offset2 = linkNumber * 3;
      linkFlatNormal.erase(linkFlatNormal.begin() + offset2, linkFlatNormal.begin() + offset2 + 3);
      linkSection.erase(linkSection.begin() + linkNumber);
      linkRadii.erase(linkRadii.begin() + linkNumber);
      if (borderFile != NULL) {
         borderFile->setModified();
      }
   }
}

/**
 * remove intersecting loops in a border.
 */
void 
Border::removeIntersectingLoops(const char axisXYZ) throw (FileException)
{
   if ((axisXYZ != 'X') &&
       (axisXYZ != 'Y') &&
       (axisXYZ != 'Z')) {
      throw FileException("PROGRAM ERROR axis passed to \"Border::removeIntersectingLoops\""
                          "must be one of X, Y, or Z");
   }
   
   bool done = false;
   while (done == false) {
      done = true;
      const int numLinks = getNumberOfLinks();
      
      //
      // Loop through links
      //
      bool foundIntersectionFlag = false;
      for (int i = 0; i < (numLinks - 3); i++) {    
         const float* p13D = getLinkXYZ(i);
         const float* p23D = getLinkXYZ(i + 1);     
         
         //
         // Loop through links after "i"
         //
         for (int j = i + 2; j < (numLinks - 1); j++) {
            //
            // Do not test first and last
            //
            if ((i == 0) &&
                (j == (numLinks - 2))) {
               continue;
            }
            
            const float* q13D = getLinkXYZ(j);
            const float* q23D = getLinkXYZ(j + 1);
            
            //
            // Convert 3D to Planar 2D
            //
            float p1[2], p2[2], q1[2], q2[2];
            switch (axisXYZ) {
               case 'X':
                  p1[0] = p13D[1];
                  p1[1] = p13D[2];
                  p2[0] = p23D[1];
                  p2[1] = p23D[2];
                  q1[0] = q13D[1];
                  q1[1] = q13D[2];
                  q2[0] = q23D[1];
                  q2[1] = q23D[2];
                  break;
               case 'Y':
                  p1[0] = p13D[0];
                  p1[1] = p13D[2];
                  p2[0] = p23D[0];
                  p2[1] = p23D[2];
                  q1[0] = q13D[0];
                  q1[1] = q13D[2];
                  q2[0] = q23D[0];
                  q2[1] = q23D[2];
                  break;
               case 'Z':
                  p1[0] = p13D[0];
                  p1[1] = p13D[1];
                  p2[0] = p23D[0];
                  p2[1] = p23D[1];
                  q1[0] = q13D[0];
                  q1[1] = q13D[1];
                  q2[0] = q23D[0];
                  q2[1] = q23D[1];
                  break;
            }
            
            //
            // Do the segments intersect?
            //
            float intersection[2];
            if (MathUtilities::lineIntersection2D(p1, p2, q1, q2, intersection)) {
               //
               // Remove links between intersection
               //
               for (int k = j; k >= (i + 1); k--) {
                  removeLink(k);
               }
               foundIntersectionFlag = true;
               done = false;
               break;
            }
         } // for j...
         
         if (foundIntersectionFlag) {
            break;
         }
      } // for i...
   }
}
      
/**
 * smooth the border links.
 */
void 
Border::smoothBorderLinks(const int numberOfIterations,
                          const bool closedBorderFlag,
                          const std::vector<bool>* smoothTheseLinksOnlyIn)
{
   const int numLinks = getNumberOfLinks();
   if (numLinks <= 2) {
      return;
   }
   std::vector<bool> smoothFlags(numLinks, true);
   if (smoothTheseLinksOnlyIn != NULL) {
      if (static_cast<int>(smoothTheseLinksOnlyIn->size()) != numLinks) {
         return;
      }
      smoothFlags = *smoothTheseLinksOnlyIn;
   }
   
   int jStart = 1;
   int jEnd   = numLinks - 1;
   if (closedBorderFlag) {
      jStart = 0;
      jEnd = numLinks;
   }
  
   if (DebugControl::getDebugOn()) {
      std::cout << "Smoothing: ";
      for (int j = jStart; j < jEnd; j++) {
         if (smoothFlags[j]) {
            std::cout << j << " ";
         }
      }
      std::cout << std::endl;
   }
   
   for (int i = 0; i < numberOfIterations; i++) {
      for (int j = jStart; j < jEnd; j++) {
         if (smoothFlags[j]) {
            int jPrev = j - 1;
            if (jPrev < 0) {
               jPrev = numLinks - 1;
            }
            int jNext = j + 1;
            if (jNext >= numLinks) {
               jNext = 0;
            }
            
            const float* xyzPrev = getLinkXYZ(jPrev);
            const float* xyzNext = getLinkXYZ(jNext);
            float xyz[3];
            getLinkXYZ(j, xyz);
            for (int k = 0; k < 3; k++) {
               xyz[k] = (xyzPrev[k] + xyzNext[k] + xyz[k]) / 3.0;
            }
            
            setLinkXYZ(j, xyz);
         }
      }
   }
}
                             
/** 
 * Resample a border to a specified density.
 */
void
Border::resampleBorderToDensity(const float densityIn,
                                const int minimumNumberOfLinks,
                                int& newNumberOfLinks)
{
   float density = densityIn;
   const float borderLength = getBorderLength();
   newNumberOfLinks = static_cast<int>(borderLength / density) + 1;
   if (minimumNumberOfLinks > 1) {
      if (newNumberOfLinks < minimumNumberOfLinks) {
         newNumberOfLinks = minimumNumberOfLinks;
         //density = borderLength / (minimumNumberOfLinks - 1);
      }
   }
   
   // recompute density so that starting and ending points of border are used
   density = borderLength / (newNumberOfLinks - 1);
   
   const int oldNumberOfLinks = static_cast<int>(getNumberOfLinks());
   
   float* x1 = new float[oldNumberOfLinks];
   float* y1 = new float[oldNumberOfLinks];
   float* z1 = new float[oldNumberOfLinks];
   float* x2 = new float[newNumberOfLinks];
   float* y2 = new float[newNumberOfLinks];
   float* z2 = new float[newNumberOfLinks];
   
   for (int j = 0; j < oldNumberOfLinks; j++) {
      const float* xyz = getLinkXYZ(j);
      x1[j] = xyz[0];
      y1[j] = xyz[1];
      z1[j] = xyz[2];
   }
   
   resampleBorder(x1, y1, z1, oldNumberOfLinks, density,
                  x2, y2, z2, newNumberOfLinks);
   
   Border savedCopy = *this;
   clearLinks();
   for (int i = 0; i < newNumberOfLinks; i++) {
      float xyz[3] = { x2[i], y2[i], z2[i] };
      addBorderLink(xyz, 0, savedCopy.getLinkRadius(
                              savedCopy.getLinkNumberNearestToCoordinate(xyz)));
   }
   
   delete[] x1;
   delete[] y1;
   delete[] z1;
   delete[] x2;
   delete[] y2;
   delete[] z2;
   
   if (borderFile != NULL) {
      borderFile->setModified();
   }
}

/** 
 * Resample a border to a specified number of links.
 */
void
Border::resampleBorderToNumberOfLinks(const int newNumberOfLinks)
{
   const float borderLength = getBorderLength();
   const int oldNumberOfLinks = static_cast<int>(getNumberOfLinks());
   const float density = borderLength / static_cast<float>(newNumberOfLinks - 1);
   
   float* x1 = new float[oldNumberOfLinks];
   float* y1 = new float[oldNumberOfLinks];
   float* z1 = new float[oldNumberOfLinks];
   float* x2 = new float[newNumberOfLinks];
   float* y2 = new float[newNumberOfLinks];
   float* z2 = new float[newNumberOfLinks];
   
   for (int j = 0; j < oldNumberOfLinks; j++) {
      const float* xyz = getLinkXYZ(j);
      x1[j] = xyz[0];
      y1[j] = xyz[1];
      z1[j] = xyz[2];
   }
   
   resampleBorder(x1, y1, z1, oldNumberOfLinks, density, 
                  x2, y2, z2, newNumberOfLinks);
   
   Border savedCopy = *this;
   clearLinks();
   for (int i = 0; i < newNumberOfLinks; i++) {
      const float xyz[3] = { x2[i], y2[i], z2[i] };
      addBorderLink(xyz, 0, savedCopy.getLinkRadius(
                              savedCopy.getLinkNumberNearestToCoordinate(xyz)));
   }
   
   delete[] x1;
   delete[] y1;
   delete[] z1;
   delete[] x2;
   delete[] y2;
   delete[] z2;
   
   if (borderFile != NULL) {
      borderFile->setModified();
   }
}

/**
 * orient the links counter-clockwise.
 */
void 
Border::orientLinksCounterClockwise()
{
   orientLinksClockwise();
   reverseBorderLinks();
}      

/**
 * Orient the links in the border clockwise.
 */
void
Border::orientLinksClockwise()
{
   float minX = std::numeric_limits<float>::max();
   int minXIndex = -1;
   
   const int num = getNumberOfLinks();
   for (int i = 0; i < num; i++) {
      const float *pos = getLinkXYZ(i);
      if (i == 0) {
         minX = pos[0];
         minXIndex = i;
      }
      else if (pos[0] < minX) {
         minX = pos[0];
         minXIndex = i;
      }
   }
   
   if (minXIndex >= 0) {
      int iNext = minXIndex + 1;
      if (iNext >= num) {
         iNext = 0;
      }
      
      const float *nextPos = getLinkXYZ(iNext);
      const float *minPos  = getLinkXYZ(minXIndex);
      if (nextPos[1] < minPos[1]) {
         reverseBorderLinks();
      }
   }
   if (borderFile != NULL) {
      borderFile->setModified();
   }
}

/**
 * Compute the flat normals for a border.
 */
void
Border::computeFlatNormals()
{
   const int numLinks = getNumberOfLinks();
   for (int i = 0; i < numLinks; i++) {
      int iNext = i + 1;
      if (iNext >= numLinks) iNext = 0;
      int iPrev = i - 1;
      if (iPrev < 0) iPrev = numLinks - 1;
      
      float vec[3];
      MathUtilities::subtractVectors(getLinkXYZ(iNext), getLinkXYZ(iPrev), vec);
      MathUtilities::normalize(vec);
      
      // points 90 to right
      const int i3 = i * 3;
      linkFlatNormal[i3]   =  vec[1];
      linkFlatNormal[i3+1] = -vec[0];
      linkFlatNormal[i3+2] = 0.0;
   }
}

/** 
 * Reverse the order of the links in a border.
 */
void 
Border::reverseBorderLinks()
{
   std::vector<float> xyz;
   std::vector<float> normal;
   std::vector<int> section;
   std::vector<float> radii;
   
   for (int i = getNumberOfLinks() - 1; i >= 0; i--) {
      const float* pos = getLinkXYZ(i);
      const float* norm = getLinkFlatNormal(i);
      const int sect = getLinkSectionNumber(i);
      const float radius = getLinkRadius(i);
      
      xyz.push_back(pos[0]);
      xyz.push_back(pos[1]);
      xyz.push_back(pos[2]);
      radii.push_back(radius);
      normal.push_back(norm[0]);
      normal.push_back(norm[1]);
      normal.push_back(norm[2]);
      section.push_back(sect);
   }
   
   linkXYZ = xyz;
   linkRadii = radii;
   linkFlatNormal = normal;
   linkSection = section;
   
   if (borderFile != NULL) {
      borderFile->setModified();
   }
}

/**
 * remove landmark rater from name of border.
 */
void 
Border::removeLandmarkRaterInfoFromBorderName()
{
   const int landmarkChar = Border::getLandmarkRaterFirstChar();
   const int indx = name.indexOf(landmarkChar);
   if (indx >= 0) {
      name = name.left(indx);
   }
}

/**
 * compare the name of two landmark borders
 * only compares text before the semi-colon in the name.
 */
bool 
Border::compareLandmarkBorderNames(const QString& name1, const QString& name2)
{
   //
   // for comparison, use substring of name up to but not including the colon
   //
   const char landmarkChar = Border::getLandmarkRaterFirstChar();
   int name1Length = name1.indexOf(landmarkChar);
   if (name1Length < 0) {
      name1Length = name1.length();
   }
   int name2Length = name2.indexOf(landmarkChar);
   if (name2Length < 0) {
      name2Length = name2.length();
   }
   
   //
   // Only need to compare if same length
   //
   if (name1Length == name2Length) {
      return (name1.left(name1Length) == name2.left(name2Length));
   }
   return false;
}

/* distance between two points */
static double 
dist (const float x1, const float y1, const float z1, 
      const float x2, const float y2, const float z2)
{
   const float dxyz[3] = { x2 - x1,
                           y2 - y1,	
                           z2 - z1 };	
   return MathUtilities::vectorLength(dxyz);
}

/** 
 * Helpful resample function.
 */
void 
Border::resampleBorder(const float* xorig, const float* yorig, 
                       const float* zorig, 
                        const int numPointsIn, 
                       const float density,
                       float* xout, float* yout, float* zout,
                       const int numPointsOut)
{
   /* Now find the next point dist away from the previous point */
   xout [0] = xorig [0];
   yout [0] = yorig [0];
   zout [0] = zorig [0];

   int j = 0; /* index of the points processed */
   //05/07/01 for (int i = 0; i < numPointsOut-1; i++){
   for (int i = 0; i < numPointsOut-2; i++){
      float x1 = xout [i];
      float y1 = yout [i];
      float z1 = zout [i];

      float dj1 = 0;
      float dj = dist (x1, y1, z1, xorig [j], yorig [j], zorig [j]);
      int k = j;
      /* find the distance to the jth point */
      while (dj < density){
         dj1 = dj;
         dj = dj+dist (xorig [j], yorig [j], zorig [j],
                       xorig [j+1], yorig [j+1], zorig [j+1]);
         j++;
      }
      /* The new point lies in the jth segment */
      float frac = (density - dj1)/(dj-dj1);

      if (k != j) {
         x1 = xorig [j-1];
         y1 = yorig [j-1];
         z1 = zorig [j-1];
      }
      xout [i+1] = (1-frac)*x1 + frac*xorig[j];
      yout [i+1] = (1-frac)*y1 + frac*yorig[j];
      zout [i+1] = (1-frac)*z1 + frac*zorig[j];
   }
   
   // last point
   xout[numPointsOut-1] = xorig[numPointsIn-1];
   yout[numPointsOut-1] = yorig[numPointsIn-1];
   zout[numPointsOut-1] = zorig[numPointsIn-1];
}

/**
 * Determine the bounds of a border.
 */
void
Border::getBounds(float bounds[6]) const
{
   bounds[0] =  std::numeric_limits<float>::max();
   bounds[1] = -std::numeric_limits<float>::max();
   bounds[2] =  std::numeric_limits<float>::max();
   bounds[3] = -std::numeric_limits<float>::max();
   bounds[4] =  std::numeric_limits<float>::max();
   bounds[5] = -std::numeric_limits<float>::max();
   
   const int numLinks = getNumberOfLinks();
   for (int i = 0; i < numLinks; i++) {
      const float* pos = getLinkXYZ(i);
      bounds[0] = std::min(bounds[0], pos[0]);
      bounds[1] = std::max(bounds[1], pos[0]);
      bounds[2] = std::min(bounds[2], pos[1]);
      bounds[3] = std::max(bounds[3], pos[1]);
      bounds[4] = std::min(bounds[4], pos[2]);
      bounds[5] = std::max(bounds[5], pos[2]);
   }   
}

/**
 * get the center of gravity of the border (returns true if valid).
 */
bool 
Border::getCenterOfGravity(float cogXYZOut[3]) const
{
   double sum[3] = { 0.0, 0.0, 0.0 };
   double numSum = 0.0;
   
   const int numLinks = getNumberOfLinks();
   for (int i = 0; i < numLinks; i++) {
      const float* pos = getLinkXYZ(i);
      sum[0] += pos[0];
      sum[1] += pos[1];
      sum[2] += pos[2];
      numSum += 1.0;
   }
   
   if (numSum >= 1.0) {
      cogXYZOut[0] = sum[0] / numSum;
      cogXYZOut[1] = sum[1] / numSum;
      cogXYZOut[2] = sum[2] / numSum;
      return true;
   }
   
   return false;
}      

/**
 * get the link number nearest to a coordinate.
 */
int 
Border::getLinkNumberNearestToCoordinate(const float xyz[3]) const
{
   int nearestLinkNumber = -1;
   float nearestDistanceSQ = std::numeric_limits<float>::max();
   
   const int numLinks = getNumberOfLinks();
   for (int i = 0; i < numLinks; i++) {
      const float* pos = getLinkXYZ(i);
      const float distSQ = MathUtilities::distanceSquared3D(xyz, pos);
      if (distSQ < nearestDistanceSQ) {
         nearestDistanceSQ = distSQ;
         nearestLinkNumber = i;
      }
   }
   
   return nearestLinkNumber;
}
      
/**
 * get the link number furthest from a coordinate.
 */
int 
Border::getLinkNumberFurthestFromCoordinate(const float xyz[3]) const
{
   int furthestLinkNumber = -1;
   float furthestDistanceSQ = -1.0;
   
   const int numLinks = getNumberOfLinks();
   for (int i = 0; i < (numLinks - 1); i++) {
      const float* pos = getLinkXYZ(i);
      const float distSQ = MathUtilities::distanceSquared3D(xyz, pos);
      if (distSQ > furthestDistanceSQ) {
         furthestDistanceSQ = distSQ;
         furthestLinkNumber = i;
      }
   }
   
   return furthestLinkNumber;
}
      
/**
 * See if 3D points are inside a 3D border (transform all to screen axis).
 */
void 
Border::pointsInsideBorder3D(const GLdouble* modelMatrix,
                             const GLdouble* projectionMatrix,
                             const GLint* viewport,
                             const float* points, 
                             const int numPoints,
                             std::vector<bool>& insideFlags,
                             const bool checkNonNegativeScreenZPointsOnly) const
{
   if (static_cast<int>(insideFlags.size()) < numPoints) {
      insideFlags.resize(numPoints);
   }
   std::fill(insideFlags.begin(), insideFlags.end(), false);
   
   //
   // Since the coordinates are typically less than 100, this can cause
   // problems with the point in polygon algorithm (it will report a
   // degenerate polygon).  Scaling all coordinates elminates this problem.
   // Using every other point in the border also helps.
   //
   const float scaleFactor = 1000.0;

   const int numLinks = getNumberOfLinks();

   float bounds[6];
   bounds[0] =  std::numeric_limits<float>::max();
   bounds[1] = -std::numeric_limits<float>::max();
   bounds[2] =  std::numeric_limits<float>::max();
   bounds[3] = -std::numeric_limits<float>::max();
   bounds[4] = -1.0;
   bounds[5] =  1.0;
   
   //
   // Create a polygon consisting of the border links projection to screen space
   //
   std::vector<float> polygon;
   int numToSkip = 1;
   int numInPolygon = 0;
   for (int i = 0; i < (numLinks - 1); i++) {
      const float* pos = getLinkXYZ(i);
      GLdouble x = pos[0];
      GLdouble y = pos[1];
      GLdouble z = pos[2];
      GLdouble sx = 0.0, sy = 0.0, sz = 0.0;
      gluProject(x, y, z,
                 modelMatrix, projectionMatrix, viewport,
                 &sx, &sy, &sz);
      polygon.push_back(sx * scaleFactor);
      polygon.push_back(sy * scaleFactor);
      polygon.push_back(0.0); // test in plane so do not need Z
      numInPolygon++;
      i += numToSkip; 
      
      bounds[0] = std::min(bounds[0], static_cast<float>(sx * scaleFactor));
      bounds[1] = std::max(bounds[1], static_cast<float>(sx * scaleFactor));
      bounds[2] = std::min(bounds[2], static_cast<float>(sy * scaleFactor));
      bounds[3] = std::max(bounds[3], static_cast<float>(sy * scaleFactor));
   }
   if (numInPolygon < 3) {
      return;
   }
   
   float normal[3] = { 0.0, 0.0, 1.0 };
   
   for (int i = 0; i < numPoints; i++) {
      GLdouble x = points[i*3];
      GLdouble y = points[i*3+1];
      GLdouble z = points[i*3+2];
      GLdouble sx = 0.0, sy = 0.0, sz = 0.0;
      gluProject(x, y, z,
                 modelMatrix, projectionMatrix, viewport,
                 &sx, &sy, &sz);
      int result = 0;

      bool checkIt = true;
      if (checkNonNegativeScreenZPointsOnly) {
         if (sz >= 0.5) {  // Z ranges 0 to 1 with 0 closest to viewer
            checkIt = false;
         }
      }
      if (checkIt) {
         float xyz[3] = { sx * scaleFactor, sy * scaleFactor, 0.0 };  // use 0 for Z 
         result = MathUtilities::pointInPolygon(xyz,
                                             numInPolygon,
                                             (float*)&polygon[0],
                                             bounds,
                                             normal);
      }

      if (result > 0) {
         insideFlags[i] = true;
      }
      else if (result < 0)  {
         std::cerr << "Border polygon passed to MathUtilities::pointInPolygon "
                      " is degenerate." << std::endl;
         std::cerr << "Polygon: " << std::endl;
         for (int j = 0; j < numInPolygon; j++) {
            std::cerr << "   " 
                      << j << " "
                      << polygon[j*3] << " "
                      << polygon[j*3+1] << " "
                      << polygon[j*3+2] << std::endl;

         }
         break;
      }
   }
}

/**
 * Determine if points are inside this border.
 * The border is assumed to be flat, in the X-Y plane.
 */
void
Border::pointsInsideBorder2D(const float* points, const int numPoints,
                             std::vector<bool>& insideFlags,
                             const bool checkNonNegativeZPointsOnly,
                             const float zMinimum) const
{
   if (static_cast<int>(insideFlags.size()) < numPoints) {
      insideFlags.resize(numPoints);
   }
   std::fill(insideFlags.begin(), insideFlags.end(), false);
   
   //
   // Since the coordinates are typically less than 100, this can cause
   // problems with the point in polygon algorithm (it will report a
   // degenerate polygon).  Scaling all coordinates elminates this problem.
   // Using every other point in the border also helps.
   //
   const float scaleFactor = 1000.0;

   //
   // Copy the border and orient CCW
   //
   Border border = *this;
   const int numLinks = border.getNumberOfLinks();
   for (int i = 0; i < numLinks; i++) {
      float pos[3];
      border.getLinkXYZ(i, pos);
      pos[2] = 0.0;
      border.setLinkXYZ(i, pos);
   }
   border.orientLinksCounterClockwise();

   std::vector<float> polygon;
   int numToSkip = 1;
   int numInPolygon = 0;
   for (int i = 0; i < (numLinks - 1); i++) {
      const float* pos = border.getLinkXYZ(i);
      polygon.push_back(pos[0] * scaleFactor);
      polygon.push_back(pos[1] * scaleFactor);
      polygon.push_back(0.0); //JWH 5/14/2008 pos[2] * scaleFactor);
      numInPolygon++;
      i += numToSkip; 
   }
   if (numInPolygon < 3) {
      return;
   }
      
   float bounds[6];
   border.getBounds(bounds);
   bounds[0] *= scaleFactor - 1.0;
   bounds[1] *= scaleFactor + 1.0;
   bounds[2] *= scaleFactor - 1.0;
   bounds[3] *= scaleFactor + 1.0;
   bounds[4] = -1.0;
   bounds[5] =  1.0;
   
   float normal[3] = { 0.0, 0.0, 1.0 };
   
   for (int i = 0; i < numPoints; i++) {
      float xyz[3];
      xyz[0] = points[i*3];
      xyz[1] = points[i*3+1];
      xyz[2] = points[i*3+2];

      bool checkIt = true;
      if (checkNonNegativeZPointsOnly) {
         if (xyz[2] < zMinimum) {
            checkIt = false;
         }
      }

      int result = 0;
      if (checkIt) {
         xyz[0] *= scaleFactor;
         xyz[1] *= scaleFactor;
         xyz[2]  = 0.0;
         result = MathUtilities::pointInPolygon(xyz,
                                             numInPolygon,
                                             (float*)&polygon[0],
                                             bounds,
                                             normal);
      }

      if (result > 0) {
         insideFlags[i] = true;
      }
      else if (result < 0)  {
         std::cerr << "Border polygon passed to MathUtilities::pointInPolygon "
                      " is degenerate." << std::endl;
         std::cerr << "Polygon: " << std::endl;
         for (int j = 0; j < numInPolygon; j++) {
            std::cerr << "   " 
                      << j << " "
                      << polygon[j*3] << " "
                      << polygon[j*3+1] << " "
                      << polygon[j*3+2] << std::endl;

         }
         break;
      }
   }
}

/**
 * interpolate two borders to create new borders.
 */
void 
Border::createInterpolatedBorders(Border* b1,
                                  Border* b2,
                                  const QString& namePrefix,
                                  const int numberOfNewBorders,
                                  const float sampling,
                                  std::vector<Border*>& outputInterpolatedBorders) throw (FileException)
{
   outputInterpolatedBorders.clear();
   
   //
   // Check inputs
   //
   if (b1 == NULL) {
      throw FileException("Border 1 is invalid.");
   }
   if (b2 == NULL) {
      throw FileException("Border 2 is invalid.");
   }
   if (b1->getNumberOfLinks() < 2) {
      throw FileException("Border 1 must have at least two links.");
   }
   if (b2->getNumberOfLinks() < 2) {
      throw FileException("Border 2 must have at least two links.");
   }
   if (numberOfNewBorders < 1) {
      throw FileException("Number of new borders must be at least one.");
   }
   if (sampling <= 0.0) {
      throw FileException("Sampling must be greater than zero.");
   }
   if (namePrefix.isEmpty()) {
      throw FileException("Name prefix contains no characters.");
   }
   
   //
   // resample the longest border to the specified sampling and resample the other
   // border to the same number of links
   //
   Border* longestBorder = NULL;
   Border* shortestBorder = NULL;
   if (b1->getBorderLength() > b2->getBorderLength()) {
      longestBorder  = b1;
      shortestBorder = b2;
   }
   else {
      shortestBorder = b1;
      longestBorder  = b2;
   }
   
   //
   // Resample the borders
   //
   int numLinks = 0;
   longestBorder->resampleBorderToDensity(sampling, 2, numLinks);
   if (numLinks < 2) {
      throw FileException("PROGRAM ERROR: Resampling of first border resulted in less than two links.");
   }
   shortestBorder->resampleBorderToNumberOfLinks(numLinks);
   if (b1->getNumberOfLinks() != b2->getNumberOfLinks()) {
      throw FileException("PROGRAM ERROR: After resampling the borders have a different number of links.");
   }
   
   //
   // Create the specified number of interpolated borders
   //
   const float totalSteps = numberOfNewBorders + 1;
   for (int i = 0; i < numberOfNewBorders; i++) {
      const float stepNum = i + 1;
      
      //
      // Create the new border
      //
      const QString borderName(namePrefix + "." + QString::number(i + 1));
      Border* newBorder = new Border(borderName);
      
      //
      // Create and add new links to new border
      //
      const float stepDelta = stepNum / totalSteps;
      for (int j = 0; j < numLinks; j++) {
         //
         // Determine the offset from link in first border to corresponding link in second border
         //
         const float* b1XYZ = b1->getLinkXYZ(j);
         const float* b2XYZ = b2->getLinkXYZ(j);
         const float dxyz[3] = { 
            b2XYZ[0] - b1XYZ[0],
            b2XYZ[1] - b1XYZ[1],
            b2XYZ[2] - b1XYZ[2]
         };
         
         //
         // Create XYZ of point in new border
         //
         const float xyz[3] = {
            b1XYZ[0] + dxyz[0] * stepDelta,
            b1XYZ[1] + dxyz[1] * stepDelta,
            b1XYZ[2] + dxyz[2] * stepDelta
         };
         
         //
         // Add a link to the new border
         //
         newBorder->addBorderLink(xyz);
      }
      
      //
      // Add the new border
      //
      outputInterpolatedBorders.push_back(newBorder);
   }
   
}
                                     
//--------------------------------------------------------------------------------
/** 
 * Constructor.
 */
BorderFile::BorderFile(const QString& descriptiveName,
                       const QString& defaultExtensionIn)
   : AbstractFile(descriptiveName, defaultExtensionIn)
{
   clear();
}

/**
 * Constructor that creates a BorderFile from the coordinates in a coordinate file.
 * If "maxLinksPerBorder" is negative one border containing all coordinates will
 * be created.  Otherwise, multiple borders will be created no more than
 * "maxLinksPerBorder" points.
 */
BorderFile::BorderFile(const CoordinateFile* cf, const int maxLinksPerBorder)
   : AbstractFile("Border File", SpecFile::getBorderFileExtension())
{
   if (cf == NULL) {
      return;
   }
   
   const int numCoords = cf->getNumberOfCoordinates();
   if (maxLinksPerBorder > 0) {
      Border border("Nodes");
      for (int i = 0; i < numCoords; i++) {
         border.addBorderLink(cf->getCoordinate(i));
         if (border.getNumberOfLinks() >= maxLinksPerBorder) {
            addBorder(border);
            border.clearLinks();
         }
      }
      if (border.getNumberOfLinks() > 0) {
         addBorder(border);
      }
   }
   else {
      Border border("Nodes");
      for (int i = 0; i < numCoords; i++) {
         border.addBorderLink(cf->getCoordinate(i));
      }
      addBorder(border);
   }
}

/**
 * Constructor that creates a BorderFile from the tiles in a Topology and Coordinate File.
 */
BorderFile::BorderFile(const TopologyFile* tf, const CoordinateFile* cf)
   : AbstractFile("Border File", SpecFile::getBorderFileExtension())
{
   //
   // Get topology and coordinate information
   //
   if ((tf == NULL) || (cf == NULL)) {
      return;
   }
   const int numTiles = tf->getNumberOfTiles();
   
   for (int i = 0; i < numTiles; i++) {
      //
      // Get the nodes in the tile
      //
      int p1, p2, p3;
      tf->getTile(i, p1, p2, p3);
      
      //
      // Create a closed border with the tiles vertices
      //
      Border b("Tile");
      b.addBorderLink(cf->getCoordinate(p1));
      b.addBorderLink(cf->getCoordinate(p2));
      b.addBorderLink(cf->getCoordinate(p3));
      b.addBorderLink(cf->getCoordinate(p1));  // closes the border
      
      addBorder(b);
   }
}

/**
 * copy all the links into a coordinate file.
 */
void 
BorderFile::copyLinksToCoordinateFile(CoordinateFile* cf)
{
   //
   // Set the number of coordinates
   //
   cf->setNumberOfCoordinates(getTotalNumberOfLinks());
   
   //
   // Set the coordinates with the links
   //
   int ctr = 0;
   for (int i = 0; i < getNumberOfBorders(); i++) {
      Border* border = getBorder(i);
      const int numLinks = border->getNumberOfLinks();
      for (int j = 0; j < numLinks; j++) {
         float xyz[3];
         border->getLinkXYZ(j, xyz);
         cf->setCoordinate(ctr, xyz);
         ctr++;
      }
   }
}

/** 
 * Destructor.
 */
BorderFile::~BorderFile()
{
   clear();
}

/**
 * Append a border file to this one.
 */
void
BorderFile::append(BorderFile& bf)
{
   const int numProj = bf.getNumberOfBorders();
   for (int i = 0; i < numProj; i++) {
      Border* b = bf.getBorder(i);
      addBorder(*b);
   }
   
   //
   // transfer the file's comment
   //
   appendFileComment(bf);

}

/**
 * Assign colors to these borders.
 */
void 
BorderFile::assignColors(const ColorFile& colorFile)
{
   const int numProj = getNumberOfBorders();
   for (int i = 0; i < numProj; i++) {
      Border* b = getBorder(i);
      bool match;
      b->setBorderColorIndex(colorFile.getColorIndexByName(b->getName(), match));
   }
}

/**
 * resample to match landmark border file (borders with same names have same number of points).
 */
void 
BorderFile::resampleToMatchLandmarkBorders(const BorderFile& landmarkBorderFile) throw (FileException)
{
   const int numBorders = getNumberOfBorders();
   for (int i = 0; i < numBorders; i++) {
      Border* myBorder = getBorder(i);
      const QString name = myBorder->getName();
      
      //
      // Find matching landmark border
      //
      const Border* landmarkBorder = landmarkBorderFile.getBorderByName(name, true);
      if (landmarkBorder == NULL) {
         throw FileException("Matching landmark border not found for border named "
                             + name);
      }
      
      //
      // resample this border to the same number of links as landmark border
      //
      const int numLinks = landmarkBorder->getNumberOfLinks();
      myBorder->resampleBorderToNumberOfLinks(numLinks);
      
      //
      // Set variability ratio for this border
      //
      for (int j = 0; j < numLinks; j++) {
         const float dist = MathUtilities::distance3D(myBorder->getLinkXYZ(j),
                                                      landmarkBorder->getLinkXYZ(j));
         const float landmarkVariability = landmarkBorder->getLinkRadius(j);
         float ratio = 0.0;
         if (landmarkVariability != 0.0) {
            ratio = dist / landmarkVariability;
         }
         myBorder->setLinkRadius(j, ratio);
      }
   }
}

/**
 * compute landmark variability.
 */
void 
BorderFile::evaluateLandmarkVariability(const BorderFile& indivBorderFile,
                                        const BorderFile& atlasBorderFile,
                                        const float badThreshold,
                                        const float extremeThreshold,
                                        const bool useAbsoluteDistanceFlag,
                                        BorderFile& outputBorderFile,
                                        QString& outputTextReport) throw (FileException)
{
   outputBorderFile.clear();
   outputTextReport = "";
   
   //
   // Copy and resample the atlas border
   //
   BorderFile resampledAtlasBorderFile(atlasBorderFile);
   resampledAtlasBorderFile.resampleAllBorders(0.25);
   
   //
   // Set individual border variability
   //
   int longestBorderNameLength = 0;
   int numIndivBorders = indivBorderFile.getNumberOfBorders();
   for (int i = 0; i < numIndivBorders; i++) {
      //
      // Copy indiv border and find atlas border with same name
      //
      Border indivBorder = *(indivBorderFile.getBorder(i));
      const Border* atlasBorder = resampledAtlasBorderFile.getBorderByName(indivBorder.getName());
      if (atlasBorder == NULL) {
         throw FileException("No atlas border named " 
                             + indivBorder.getName()
                             + " found.");
      }
      
      //
      // Track longest border name length
      //
      longestBorderNameLength = std::max(longestBorderNameLength, 
                                         indivBorder.getName().length());
                                         
      //
      // Loop through indiv border points
      //
      int numLinks = indivBorder.getNumberOfLinks();
      for (int j = 0; j < numLinks; j++) {
         //
         // Find nearest atlas link to indiv link
         //
         const float* xyz = indivBorder.getLinkXYZ(j);
         const int atlasLinkNumber = atlasBorder->getLinkNumberNearestToCoordinate(xyz);
         if (atlasLinkNumber >= 0) {
            //
            // Compute and set indiv variability
            //
            const float distance = MathUtilities::distance3D(xyz, 
                                      atlasBorder->getLinkXYZ(atlasLinkNumber));
            if (useAbsoluteDistanceFlag) {
               indivBorder.setLinkRadius(j, distance);
            }
            else {
               float atlasVariability = atlasBorder->getLinkRadius(atlasLinkNumber);
               if (atlasVariability <= 0.0) {
                  atlasVariability = 1.0;
               }
               const float indivVariability = distance / atlasVariability;
               indivBorder.setLinkRadius(j, indivVariability);
            }
         }
         else {
            throw FileException("No nearest point in atlas border named "
                                + atlasBorder->getName());
         }
      }
      
      //
      // Add indiv border to output border file
      //
      outputBorderFile.addBorder(indivBorder);
   }
   
   //
   // Copy and resample the atlas border
   //
   BorderFile resampledIndivBorderFile(indivBorderFile);
   resampledIndivBorderFile.resampleAllBorders(0.25);
   
   //
   // Set atlas border variability
   //
   int numAtlasBorders = atlasBorderFile.getNumberOfBorders();
   for (int i = 0; i < numAtlasBorders; i++) {
      //
      // Copy atlas border and find indiv border with same name
      //
      Border atlasBorder = *(atlasBorderFile.getBorder(i));
      const Border* indivBorder = resampledIndivBorderFile.getBorderByName(atlasBorder.getName());
      if (indivBorder == NULL) {
         throw FileException("No indiv border named " 
                             + atlasBorder.getName()
                             + " found.");
      }
      
      //
      // Loop through atlas border points
      //
      int numLinks = atlasBorder.getNumberOfLinks();
      for (int j = 0; j < numLinks; j++) {
         //
         // Find nearest indiv link to atlas link
         //
         const float* xyz = atlasBorder.getLinkXYZ(j);
         const int indivLinkNumber = indivBorder->getLinkNumberNearestToCoordinate(xyz);
         if (indivLinkNumber >= 0) {
            //
            // Compute and set atlas variability which is distance from
            // indiv to atlas divided by ATLAS (yes ATLAS) variability
            //
            const float distance = MathUtilities::distance3D(xyz, 
                                      indivBorder->getLinkXYZ(indivLinkNumber));
            if (useAbsoluteDistanceFlag) {
               atlasBorder.setLinkRadius(j, distance);
            }
            else {
               float atlasVariability = atlasBorder.getLinkRadius(j);
               if (atlasVariability <= 0.0) {
                  atlasVariability = 1.0;
               }
               atlasVariability = distance / atlasVariability;
               atlasBorder.setLinkRadius(j, atlasVariability);
            }
         }
         else {
            throw FileException("No nearest point in indiv border named "
                                + indivBorder->getName());
         }
      }
      
      //
      // Add atlas border to output border file
      //
      outputBorderFile.addBorder(atlasBorder);
   }
   
   //
   // Header for text report
   //
   const QString borderNameHeader("Border Name");
   const QString badCountHeader("Bad Count");
   const int badCountLength = badCountHeader.length();
   const QString extremeCountHeader("Extreme Count");
   const int extremeCountLength = extremeCountHeader.length();
   const QString overlapPercentageHeader("Overlap Percentage");
   const int overlapPercentageLength = overlapPercentageHeader.length();
   longestBorderNameLength = std::max(longestBorderNameLength,
                                      borderNameHeader.length());
   QString s =
      QString("%1  %2  %3  %4\n").arg(borderNameHeader, longestBorderNameLength)
                              .arg(badCountHeader, badCountLength)
                              .arg(extremeCountHeader, extremeCountLength)
                              .arg(overlapPercentageHeader, overlapPercentageLength);
   outputTextReport.append(s);
   
   //
   // Loop through indiv borders in output border file
   //
   int totalNumberOfBorders = outputBorderFile.getNumberOfBorders();
   for (int i = 0; i < numIndivBorders; i++) {
      Border* indivBorder = outputBorderFile.getBorder(i);
      const QString name = indivBorder->getName();
      
      //
      // Find corresponding atlas border
      //
      Border* atlasBorder = NULL;
      for (int j = numIndivBorders; j < totalNumberOfBorders; j++) {
         Border* b = outputBorderFile.getBorder(j);
         if (b->getName() == name) {
            atlasBorder = b;
            break;
         }
      }
      if (atlasBorder == NULL) {
         throw FileException("Unable to find atlas border named "
                             + name
                             + " in output border file. ");
      }
      
      //
      // Count bad and extreme points in atlas and indiv borders
      //
      int badCount = 0;
      int extremeCount = 0;
      for (int j = 0; j < indivBorder->getNumberOfLinks(); j++) {
         if (indivBorder->getLinkRadius(j) > badThreshold) {
            badCount++;
         }
         if (indivBorder->getLinkRadius(j) > extremeThreshold) {
            extremeCount++;
         }
      }
      for (int j = 0; j < atlasBorder->getNumberOfLinks(); j++) {
         if (atlasBorder->getLinkRadius(j) > badThreshold) {
            badCount++;
         }
         if (atlasBorder->getLinkRadius(j) > extremeThreshold) {
            extremeCount++;
         }
      }
      
      //
      // Determine bad and extreme counts
      //
      const int totalPoints = indivBorder->getNumberOfLinks()
                            + atlasBorder->getNumberOfLinks();
      const float overlapPercentage = 
         (static_cast<float>(totalPoints - badCount)
          / static_cast<float>(totalPoints))
         * 100.0;
         
      //
      // Add to text report
      //
      QString s =
         QString("%1  %2  %3  %4\n").arg(name, longestBorderNameLength)
                                    .arg(badCount, badCountLength)
                                    .arg(extremeCount, extremeCountLength)
                                    .arg(overlapPercentage, overlapPercentageLength, 'f', 1);
      outputTextReport.append(s);
      
      //
      // Change the atlas border name
      //
      atlasBorder->setName("ATLAS_" + name);
   }
}
                                       
/**
 * Create a border file that is an average of a group of border files.
 * Returns NULL if error.
 */
void
BorderFile::createAverageBorderFile(const std::vector<BorderFile*>& inputBorderFiles,
                                    const float borderResampling,
                                    const bool sphereFlag,
                                    BorderFile& averageBorderFileOut)
                                               throw (FileException)
{
   //
   // Need at least two borders files to resample
   //
   if (inputBorderFiles.size() < 2) {
      throw FileException("There must be at least two border files.");
   }
   
   //
   // Clear the output border file
   //
   averageBorderFileOut.clear();
   
   //
   // Stuff for spherical borders
   //
   float sphereRadius = 1.0;
   bool sphereRadiusSet = false;
   
   //
   // Number of border files we have
   //
   const int numFiles = static_cast<int>(inputBorderFiles.size());
   
   //
   // Use the first border files and loop through its borders
   //
   const int numBorders = inputBorderFiles[0]->getNumberOfBorders();
   for (int i = 0; i < numBorders; i++) {
      //
      // Get a border from the first tile
      //
      Border b1 = *(inputBorderFiles[0]->getBorder(i));
      
      //
      // Set sphere radius
      //
      if (sphereRadiusSet == false) {
         for (int j = 0; j < b1.getNumberOfLinks(); j++) {
            float xyz[3];
            b1.getLinkXYZ(j, xyz);
            if ((xyz[0] != 0.0) || (xyz[1] != 0.0) || (xyz[2] != 0.0)) {
               sphereRadius = std::sqrt(xyz[0]*xyz[0] + xyz[1]*xyz[1] + xyz[2]*xyz[2]);
               sphereRadiusSet = true;
               break;
            }
         }
      }
      
      //
      // Resample it to the specified amount
      //
      int numLinks = 0;
      b1.resampleBorderToDensity(borderResampling, 2, numLinks);
      
      if (numLinks > 0) {
         //
         // Will contain the additional resampled borders
         //
         std::vector<Border> resampledBorders;
         
         //
         // Loop through the remaining files
         //
         for (int j = 1; j < numFiles; j++) {
            //
            // Find the border with the same name as from first file
            //
            Border* bj = inputBorderFiles[j]->getBorderByName(b1.getName(), true);
            if (bj != NULL) {
               //
               // Resmaple it and add to resampled borders
               //
               Border b = *bj;
               b.removeLandmarkRaterInfoFromBorderName();
               b.resampleBorderToNumberOfLinks(numLinks);
               resampledBorders.push_back(b);
            }
            else {
               //
               // bummer
               //
               QString errorMessage;
               errorMessage = "Unable to find border named ";
               errorMessage.append(b1.getName());
               errorMessage.append("in file ");
               errorMessage.append(inputBorderFiles[j]->getFileName());
               throw FileException(errorMessage);
            }
         }
      
         //
         // Compute the average at each link
         //
         const int numLinks = b1.getNumberOfLinks();
         for (int j = 0; j < numLinks; j++) {
            //
            // Position in first border file
            //
            float xyzSum[3] = { 0.0, 0.0, 0.0 };
            float xyz[3];
            b1.getLinkXYZ(j, xyz);
            xyzSum[0] += xyz[0];
            xyzSum[1] += xyz[1];
            xyzSum[2] += xyz[2];
            
            //
            // Add in positions of other resampled borders
            //
            const int numResampledBorders = static_cast<int>(resampledBorders.size());
            for (int k = 0; k < numResampledBorders; k++) {
               resampledBorders[k].getLinkXYZ(j, xyz);
               xyzSum[0] += xyz[0];
               xyzSum[1] += xyz[1];
               xyzSum[2] += xyz[2];
            }
            
            //
            // Average for this link
            //
            const float num = numResampledBorders + 1;
            const float average[3] = { 
               xyzSum[0] / num, 
               xyzSum[1] / num, 
               xyzSum[2] / num 
            };
            
            //
            // Compute mean distance from average
            //
            std::vector<float> distances;
            distances.push_back(MathUtilities::distance3D(b1.getLinkXYZ(j), average));
            for (int k = 0; k < numResampledBorders; k++) {
               distances.push_back(MathUtilities::distance3D(average, 
                                              resampledBorders[k].getLinkXYZ(j)));
            }
            
            StatisticDataGroup sdg(&distances,
                                   StatisticDataGroup::DATA_STORAGE_MODE_POINT);
            StatisticMeanAndDeviation smad;
            smad.addDataGroup(&sdg);
            try {
               smad.execute();
            }
            catch (StatisticException&) {
            }
            b1.setLinkRadius(j, smad.getMean());
            
            
            //
            // Set the average radius for this link
            //
            b1.setLinkXYZ(j, average);
         }
         
         //
         // add new average border to the border file that will be returned
         //
         averageBorderFileOut.addBorder(b1);
      }
   }
   
   //
   // Project to sphere if needed
   //
   if (averageBorderFileOut.getNumberOfBorders() > 0) {
      if (sphereFlag) {
         averageBorderFileOut.setSphericalBorderRadius(sphereRadius);
      }
   }
   
   QString comment("Average borders from: \n");
   for (int i = 0; i < numFiles; i++) {
      comment.append(FileUtilities::basename(inputBorderFiles[i]->getFileName()));
      comment.append("\n");
   }
   averageBorderFileOut.setFileComment(comment);
   averageBorderFileOut.setHeaderTag(AbstractFile::headerTagConfigurationID,
      inputBorderFiles[0]->getHeaderTag(AbstractFile::headerTagConfigurationID));
}

/** 
 * Clear the border file.
 */
void
BorderFile::clear()
{
   clearAbstractFile();
   borders.clear();
}

/** 
 * Add a border to this file.
 */
void
BorderFile::addBorder(const Border& b)
{
   borders.push_back(b);
   const int index = static_cast<int>(borders.size()) - 1;
   borders[index].borderFile = this;
   setModified();
}

/**
 * Get a border index from its name.
 */
int
BorderFile::getBorderIndexByName(const QString& nameToFind,
                                 const bool landmarkBordersFlag) const
{
   for (unsigned int i = 0; i < borders.size(); i++) {
      if (landmarkBordersFlag) {
         if (Border::compareLandmarkBorderNames(borders[i].getName(), nameToFind)) {
            return i;
         }
      }
      else {
         if (borders[i].getName() == nameToFind) {
            return i;
         }
      }
   }
   return -1;
}

/** 
 * Get a border by name (const method)
 */
const Border* 
BorderFile::getBorderByName(const QString& nameToFind,
                            const bool landmarkBordersFlag) const
{
   const int index = getBorderIndexByName(nameToFind, landmarkBordersFlag);
   if (index >= 0) {
      return &borders[index];
   }
   return NULL;
}

/** 
 * Get a border by name.
 */
Border* 
BorderFile::getBorderByName(const QString& nameToFind,
                            const bool landmarkBordersFlag)
{
   const int index = getBorderIndexByName(nameToFind, landmarkBordersFlag);
   if (index >= 0) {
      return &borders[index];
   }
   return NULL;
}

/**
 * Apply transformation matrix to border file.
 */
void
BorderFile::applyTransformationMatrix(TransformationMatrix& tm)
{ 
   for (int i = 0; i < getNumberOfBorders(); i++) {
      Border* border = getBorder(i);
      border->applyTransformationMatrix(tm);
/*
      const int numLinks = border->getNumberOfLinks();
      for (int j = 0; j < numLinks; j++) {
         float xyz[3];
         border->getLinkXYZ(j, xyz);
         double p[4] = { xyz[0], xyz[1], xyz[2], 1.0 };
         tm.multiplyPoint(p);
         xyz[0]   = p[0];
         xyz[1] = p[1];
         xyz[2] = p[2];
         border->setLinkXYZ(j, xyz);
      }
*/
   }
   setModified();
}  

/**
 * Get a border with the specified projection ID
 */
Border*
BorderFile::getBorderWithProjectionID(const int projectionID)
{
   const int index = getBorderIndexForBorderWithProjectionID(projectionID);
   if (index >= 0) {
      return getBorder(index);
   }
   return NULL;
}

/**
 * Get the index for the border with the specified projection ID
 */
int 
BorderFile::getBorderIndexForBorderWithProjectionID(const int projectionID) const
{
   const int num = getNumberOfBorders();
   for (int i = 0; i < num; i++) {
      const Border* b = getBorder(i);
      if (b->getBorderProjectionID() == projectionID) {
         return i;
      }
   }
   return -1;
}

/**
 * Remove a border at the specified index
 */
void
BorderFile::removeBorder(const int borderNumber)
{
   if (borderNumber < getNumberOfBorders()) {
      borders.erase(borders.begin() + borderNumber);
   }
   setModified();
}

/** 
 * remove borders with the specified indices.
 */
void 
BorderFile::removeBordersWithIndices(const std::vector<int>& borderIndicesIn)
{
   std::vector<int> borderIndices = borderIndicesIn;
   std::sort(borderIndices.begin(), borderIndices.end());
   const int num = static_cast<int>(borderIndices.size());
   for (int i = (num - 1); i >= 0; i--) {
      removeBorder(borderIndices[i]);
   }
}
      
/**
 * get the indices of borders that area duplicates of other borders.
 */
void 
BorderFile::getDuplicateBorderIndices(std::vector<int>& duplicateBorderIndices) const
{
   duplicateBorderIndices.clear();
   
   const int numBorders = getNumberOfBorders();
   for (int i = 0; i < (numBorders - 1); i++) {
      const Border* b = getBorder(i);
      
      for (int j = i + 1; j < numBorders; j++) {
         const Border* b2 = getBorder(j);
         if (*b == *b2) {
            duplicateBorderIndices.push_back(j);
         }
      }
   }
}
      
/**
 * Remove the border with the specified projection ID
 */
void
BorderFile::removeBorderWithProjectionID(const int projectionID)
{
   const int index = getBorderIndexForBorderWithProjectionID(projectionID);
   if (index >= 0) {
      removeBorder(index);
      setModified();
   }
}

/**
 * Reset the border projection IDs on all borders so that they do not
 * appear to be projected borders.
 */
void
BorderFile::resetBorderProjectionIDs()
{
   const int num = getNumberOfBorders();
   for (int i = 0; i < num; i++) {
      borders[i].setBorderProjectionID(-1);
   } 
}

/**
 * Remove all projected borders from this border file.
 */
void
BorderFile::removeAllProjectedBorders()
{
   std::vector<Border> temp;
   const int num = getNumberOfBorders();
   bool removedBorders = false;
   
   for (int i = 0; i < num; i++) {
      if (borders[i].getBorderProjectionID() >= 0) {
         removedBorders = true;
      }
      else {
         temp.push_back(borders[i]);
      }
   }
   
   if (removedBorders) {
      borders = temp;
      setModified();
   }
}

/**
 * Set the status of all border name display flags
 */
void 
BorderFile::setAllNameDisplayFlags(const bool status)
{
   const int num = getNumberOfBorders();
   for (int i = 0; i < num; i++) {
      getBorder(i)->setNameDisplayFlag(status);
   }
}

/**
 * Set the status of all border display flags for borders with the specified name.
 */
void
BorderFile::setNameDisplayFlagForBordersWithName(const QString& name, const bool flag)
{
   const int num = getNumberOfBorders();
   for (int i = 0; i < num; i++) {
      if (borders[i].getName() == name) {
         borders[i].setNameDisplayFlag(flag);
      }
   }
}

/**
 * Compute flat normals for borders.
 */
void
BorderFile::computeFlatNormals()
{
   const int num = getNumberOfBorders();
   for (int i = 0; i < num; i++) {
      Border* b = getBorder(i);
      b->computeFlatNormals();
   }
}

/**
 * Resample the displayed borders.
 */
void
BorderFile::resampleDisplayedBorders(const float density)
{
   const int num = getNumberOfBorders();
   for (int i = 0; i < num; i++) {
      Border* b = getBorder(i);
      if (b->getDisplayFlag()) {
         int dummy;
         b->resampleBorderToDensity(density, 2, dummy);
      }
   }
}

/**
 * Resample all borders.
 */
void
BorderFile::resampleAllBorders(const float density)
{
   const int num = getNumberOfBorders();
   for (int i = 0; i < num; i++) {
      Border* b = getBorder(i);
      int dummy;
      b->resampleBorderToDensity(density, 2, dummy);
   }
}

/**
 * Orient the displayed borders clockwise.
 */
void
BorderFile::orientDisplayedBordersClockwise()
{
   const int num = getNumberOfBorders();
   for (int i = 0; i < num; i++) {
      Border* b = getBorder(i);
      if (b->getDisplayFlag()) {
         b->orientLinksClockwise();
      }
   }
}

/**
 * Reverse the order of the links in the displayed borders.
 */
void
BorderFile::reverseDisplayedBorders()
{
   const int num = getNumberOfBorders();
   for (int i = 0; i < num; i++) {
      Border* b = getBorder(i);
      if (b->getDisplayFlag()) {
         b->reverseBorderLinks();
      }
   }
}

/** 
 * Read the border file data.
 */
void 
BorderFile::readFileData(QFile& /*file*/, 
                         QTextStream& stream, 
                         QDataStream&,
                         QDomElement& /* rootElement */) throw (FileException)
{
   //
   // Should reading data be skipped ?
   //
   if (getReadMetaDataOnlyFlag()) {
      return;
   }
   
   QString line;
   
   // 1st line contains number of borders
   readLine(stream, line);
   const int numBorders = line.toInt();
   
   for (int i = 0; i < numBorders; i++) {
      readLine(stream, line);
      int borderNumber;
      int numLinks = 0;
      QString borderName;
      float samplingDensity = 25.0, variance = 1.0, topography = 0.0, uncertainty = 1.0;
      
      QTextStream(&line, QIODevice::ReadOnly) >> borderNumber
                         >> numLinks
                         >> borderName
                         >> samplingDensity
                         >> variance
                         >> topography
                         >> uncertainty;
      
      // line containing the center (ignore)
      float center[3] = { 0.0, 0.0, 0.0 };
      readLine(stream, line);
      
      // create the border
      Border border(borderName, center, samplingDensity, variance, 
                    topography, uncertainty);
      
      for (int j = 0; j < numLinks; j++) {
         readLine(stream, line);
         
         int linkNumber, sectionNumber;
         float xyz[3];
         float radius = 0.0;
         
         QTextStream(&line, QIODevice::ReadOnly) >> linkNumber
                             >> sectionNumber
                             >> xyz[0]
                             >> xyz[1]
                             >> xyz[2]
                             >> radius;

         border.addBorderLink(xyz, sectionNumber, radius);
      }
      
      addBorder(border);
   }
}

/** 
 * Get the total number of links in a border.
 */
int 
BorderFile::getTotalNumberOfLinks()
{
   int total = 0;
   for (int i = 0; i < getNumberOfBorders(); i++) {
      Border *border = getBorder(i);
      total += border->getNumberOfLinks();
   }
   return total;
}
      
/** 
 * Write the border file data.
 */
void 
BorderFile::writeFileData(QTextStream& stream, QDataStream&,
                                 QDomDocument& /* xmlDoc */,
                          QDomElement& /* rootElement */) throw (FileException)
{
   int numBorders = getNumberOfBorders();

   //
   // only write borders that have links
   //
   int numBordersToWrite = 0;
   for (int i = 0; i < numBorders; i++) {
      if (getBorder(i)->getNumberOfLinks() > 0) {
         numBordersToWrite++;
      }
   }
   stream << numBordersToWrite << "\n";
   
   for (int i = 0; i < numBorders; i++) {
      Border* border = getBorder(i);
      const int numLinks = border->getNumberOfLinks();
      
      //
      // Only write border if it has links
      //
      if (numLinks <= 0) {
         continue;
      }
      
      // write border number, number links, name, sampling, variance, topography
      QString name;
      float center[3];
      float samplingDensity, variance, topography, uncertainty;
      border->getData(name, center, samplingDensity, variance, 
                      topography, uncertainty);
      stream << i << " "
             << numLinks << " "
             << name << " "
             << samplingDensity << " "
             << variance << " "
             << topography << " "
             << uncertainty << "\n";
              
      // write border center (unused)
      stream << center[0] << " " << center[1] << " " << center[2] << "\n";
      
      for (int j = 0; j < numLinks; j++) {         
         // write link number, section, and xyz
         const float* xyz = border->getLinkXYZ(j);
         stream << j << " "
                << border->getLinkSectionNumber(j) << " "
                << xyz[0] << " "
                << xyz[1] << " "
                << xyz[2] << " "
                << border->getLinkRadius(j) << "\n";
      }
   }
}

/**
 * Set the radius of all border links in a spherical border file.
 */
void 
BorderFile::setSphericalBorderRadius(const float newRadius)
{
   if (newRadius <= 0.0) {
      return;
   }
   
   const int numBorders = getNumberOfBorders();
   for (int i = 0; i < numBorders; i++) {
      Border* border = getBorder(i);
      const int numLinks = border->getNumberOfLinks();
      for (int j = 0; j < numLinks; j++) {
         float xyz[3];
         border->getLinkXYZ(j, xyz);
         const float oldRadius = sqrt(xyz[0]*xyz[0] + xyz[1]*xyz[1] + xyz[2]*xyz[2]);
         if (oldRadius != 0.0) {
            const float scale = newRadius / oldRadius;
            xyz[0] *= scale;
            xyz[1] *= scale;
            xyz[2] *= scale;
            border->setLinkXYZ(j, xyz);
         }
      }
   }
}

/**
 * convert configuration ID to spec file tag.
 */
QString
BorderFile::convertConfigurationIDToSpecFileTag(const QString& nameIn)
{  
   const QString name(nameIn.toUpper());
   if (name == "RAW") return SpecFile::getRawBorderFileTag();
   else if (name == "FIDUCIAL") return SpecFile::getFiducialBorderFileTag();
   else if (name == "INFLATED") return SpecFile::getInflatedBorderFileTag();
   else if (name == "VERY_INFLATED") return SpecFile::getVeryInflatedBorderFileTag();
   else if (name == "SPHERICAL") return SpecFile::getSphericalBorderFileTag();
   else if (name == "ELLIPSOIDAL") return SpecFile::getEllipsoidBorderFileTag();
   else if (name == "CMW") return SpecFile::getCompressedBorderFileTag();
   else if (name == "FLAT") return SpecFile::getFlatBorderFileTag();
   else if (name == "FLAT_LOBAR") return SpecFile::getLobarFlatBorderFileTag();
   else if (name == "HULL") return SpecFile::getHullBorderFileTag();
   else return SpecFile::getUnknownBorderFileMatchTag();
}

/**
 * Write the file's memory in caret6 format to the specified name.
 */
QString
BorderFile::writeFileInCaret6Format(const QString& filenameIn, Structure structure,const ColorFile* colorFileIn, const bool useCaret6ExtensionFlag) throw (FileException)
{
   int numBorders = this->getNumberOfBorders();
   if (numBorders <= 0) {
      throw FileException("Contains no borders");
   }

   QString name = FileUtilities::filenameWithoutExtension(filenameIn)
                + SpecFile::getBorderProjectionFileExtension();
   QFile file(name);
   if (file.open(QFile::WriteOnly) == false) {
      throw FileException("Unable to open for writing");
   }
   QTextStream stream(&file);

   XmlGenericWriter xmlWriter(stream);
   xmlWriter.writeStartDocument();

   XmlGenericWriterAttributes attributes;
   attributes.addAttribute("CaretFileType", "BorderProjection");
   attributes.addAttribute("xmlns:xsi",
                           "http://www.w3.org/2001/XMLSchema-instance");
   attributes.addAttribute("xsi:noNamespaceSchemaLocation",
                           "http://brainvis.wustl.edu/caret6/xml_schemas/BorderProjectionFileSchema.xsd");
   attributes.addAttribute("Version", "6.0");
   xmlWriter.writeStartElement("CaretDataFile", attributes);

   this->writeHeaderXMLWriter(xmlWriter);

   GiftiLabelTable labelTable;
   if (colorFileIn != NULL) {
      labelTable.createLabelsFromColors(*colorFileIn);
   }
   labelTable.writeAsXML(xmlWriter);

   for (int i = 0; i < numBorders; i++) {
      Border* b = this->getBorder(i);
      int numLinks = b->getNumberOfLinks();
      if (numLinks > 0) {

         XmlGenericWriterAttributes attributes;
         attributes.addAttribute("Index", i);
         xmlWriter.writeStartElement("BorderProjection", attributes);

         xmlWriter.writeElementCData("Name", b->getName());

         for (int j = 0; j < numLinks; j++) {
            Caret6ProjectedItem pi;
            pi.projectionType = Caret6ProjectedItem::UNPROJECTED;
            b->getLinkXYZ(j, pi.xyz);
            pi.structure = structure;
            pi.writeXML(xmlWriter);
         }

         xmlWriter.writeEndElement();
      }
   }

   xmlWriter.writeEndElement();

   xmlWriter.writeEndDocument();

   file.close();

   return name;
}