File: cusp_neighborhoods.c

package info (click to toggle)
snappea 3.0d3-20.1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 5,896 kB
  • ctags: 3,582
  • sloc: ansic: 33,469; sh: 8,293; python: 7,623; makefile: 240
file content (4233 lines) | stat: -rw-r--r-- 128,115 bytes parent folder | download | duplicates (11)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
/*
 *	cusp_neighborhoods.c
 *
 *	This file provides the following functions for creating and manipulating
 *	horospherical cross sections of a manifold's cusps, and computing the
 *	triangulation dual to the corresponding Ford complex.  These functions
 *	communicate with the UI by passing pointers to CuspNeighborhoods
 *	data structures;  but even though the UI may keep pointers to
 *	CuspNeighborhoods, the structure's internal details are private
 *	to this file.
 *
 *		CuspNeighborhoods *initialize_cusp_neighborhoods(
 *								Triangulation		*manifold);
 *
 *		void free_cusp_neighborhoods(
 *								CuspNeighborhoods	*cusp_neighborhoods);
 *
 *	[Many other externally available functions are provided -- please see
 *	SnapPea.h for details.]
 *
 *	When the canonical cell decomposition dual to the Ford complex is not
 *	a triangulation, it is arbitrarily subdivided into tetrahedra.
 *
 *	Note:  This file uses the fields "displacement" and "displacement_exp"
 *	in the Cusp data structure to keep track of where the cusp cross
 *	sections are (details appear below).  Manifolds not under the care
 *	of a CuspNeighborhoods structure should keep the "displacement" set
 *	to 0 and the "displacement_exp" set to 1 at all times, so that
 *	canonical cell decompositions will be computed relative to cusps
 *	cross sections of equal volume.
 */

/*
 *	Proposition 1.  The area of a horospherical cusp cross section is
 *	exactly twice the volume it contains.
 *
 *	Proof.  Do an integral in the upper half space model of hyperbolic
 *	3-space.  Consider a unit square in the horosphere z == 1, and calculate
 *	the volume lying above it as the integral of 1/z^3 dz from z = 1 to
 *	z = infinity.  QED
 *
 *	Comment.  This proposition relies on the hyperbolic manifold having
 *	curvature -1.  If the curvature had some other value, the proportionality
 *	constant would be something other than 2.
 *
 *	Comment.  The proportionality constant has units of 1 / distance.
 *	Normally, though, one doesn't have to think about units in hyperbolic
 *	geometry, because one uses the canonical ones.  I just wanted to make
 *	sure that nobody is bothered by the fact that we're specifying an area
 *	as twice a volume.
 *
 *	Comment.  We can measure the size of a cusp cross section by area or
 *	by volume.  The two measures are the same modulo a factor of two.
 *
 *
 *	Proposition 2.  If we choose a manifold's cusp cross sections to each
 *	have area (3/8)sqrt(3), then their interiors cannot overlap themselves
 *	or each other.
 *
 *	Proof.  By Lemma A below, we can choose a set of cusp cross sections
 *	with nonoverlapping interiors.  Advance each cusp cross section into
 *	the fat part of the manifold, until it bumps into itself or another
 *	cross section.  Look at the horoball packing as seen from a given cusp.
 *	Because the cusp is tangent to itself or some other cusp, there'll be
 *	a maximally large horoball.  If we draw the given cusp as the plane
 *	z == 1 in the upper half space model, the maximal horoball (and each of
 *	its translates) will appear as a sphere of diameter 1.  The view as
 *	seen from the given cusp therefore includes a packing of disjoint circles
 *	of diameter 1/2.  If it's a hexagonal packing the area of the cusp will
 *	equal the area of a hexagon of outradius 1/2, which works out to be
 *	(3/8)sqrt(3).  If it's not a hexagonal packing, the cusp's area will be
 *	even greater.  In the latter case, we retract the cusp cross section
 *	until its area is exactly (3/8)sqrt(3).  QED
 *
 *	Lemma A.  We can choose a set of cusp cross sections with nonoverlapping
 *	interiors.
 *
 *	Comment.  One expects the proof of this lemma to be completely trivial,
 *	but I don't think it is.
 *
 *	Proof #1.  Lemma A follows directly from the Margulis Lemma.  The
 *	required cusp cross sections are portions of the boundary of the thin
 *	part of the manifold.  QED
 *
 *	Proof #2.  Start with any decomposition of the manifold into positively
 *	oriented 3-cells.  For example, we could start with the canonical cell
 *	decomposition constructed in
 *
 *		J. Weeks, Convex hulls and isometries of cusped hyperbolic
 *			3-manifolds, Topology Appl. 52 (1993) 127-149.
 *
 *	Choose arbitrary cusp cross sections.  Retract each cusp as necessary
 *	so that its intersection with each 3-cell is "standard".  (I don't want
 *	to spend a lot of time fussing over the wording of this -- the idea is
 *	that the cross section shouldn't be so far forward that it has
 *	unnecessary intersections with other faces of the 3-cell.)  Then further
 *	retract each cusp cross section so that it doesn't intersect the other
 *	cross sections incident to the same 3-call.  This gives the nonoverlapping
 *	cross sections, as required.  QED
 *
 *
 *	Definition.  The "home position" of a cusp cross section is the one
 *	at which its area is (3/8)sqrt(3) and its enclosed volume is (3/16)sqrt(3).
 *
 *	By Proposition 2 above, when all the cusps are at their home positions,
 *	their interiors are disjoint.
 *
 *	The displacement field in the Cusp data structure measures how far
 *	a cusp cross section is from its home position.  The displacement is
 *	measured towards the fat part of the manifold, so a positive displacement
 *	means the cusp cross section is larger, and a negative displacement
 *	means it is smaller.
 *
 *	If we visualize a cusp's home position as a plane at height z == 1 in
 *	the upper half space model, then after a displacement d > 0 it will be
 *	at some height h < 1.  Set d equal to the integral of dz/z from z = h
 *	to z = 1 to obtain d = - log h, or h = exp(-d).  It follows that a cusp's
 *	linear dimensions vary as exp(d), while its area (and therefore its
 *	enclosed volume) vary as exp(2d).  The Cusp data structure stores the
 *	quantity exp(d) in its displacement_exp field, to avoid excessive
 *	recomputation.
 *
 *
 *	Definition.  The "reach" of a cusp is the distance from the cross
 *	section's home position to the position at which it first bumps into
 *	itself.
 *
 *	Note that the reach is half the distance from the cusp to itself,
 *	measured along the shortest homotopically nontrivial path.
 *	Proposition 2 implies that the reach of each cusp will be nonnegative.
 *
 *	Definition.  As a given cusp cross section moves forward into the
 *	fat part of the manifold, the first cusp cross section it bumps into
 *	is called its "stopper".  The displacement (measured from the home
 *	position) at which the given cusp meets its stopper is called the
 *	"stopping displacement".
 *
 *	Comment.  Unlike the reach, the stopper and the stopping displacement
 *	depend on the current displacements of all the cusps in the triangulation.
 *	They vary dynamically as the user moves the cusp cross sections.
 *
 *
 *	Sometimes the user may wish to change two or more cusp displacements
 *	in unison.  The Cusp's is_tied field supports this.  The displacements
 *	of "tied" cusps always stay the same -- when one changes they all do.
 *	The tie_group_reach keeps track of the reach of the tied cusps:
 *	it tells the displacement at which some cusp in the group first
 *	bumps into itself or some other cusp in the group.  Note that the
 *	tie_group_reach might be less than the stopping displacement of any
 *	of its constituent cusps;  this is because when a cusp moves forward
 *	its (ordinary) stopper stays still, but members of its tie group
 *	move towards it.
 */

#include "kernel.h"
#include "canonize.h"
#include <stdlib.h>		/* needed for qsort() and rand() */

/*
 *	Report all horoballs higher than the requested cutoff_height
 *	minus CUTOFF_HEIGHT_EPSILON.  For example, if the user wants to see
 *	all horoballs of height at least 0.25, we should report a horoball
 *	of height 0.249999999963843.
 */ 
#define CUTOFF_HEIGHT_EPSILON		1e-6

/*
 *	A horoball is considered to be "maximal" iff it's distance from a fixed
 *	cusp is within INTERCUSP_EPSILON of being minimal.  (The idea is that
 *	if there are several different maximal cusps, whose distances from the
 *	fixed cusp differ only by roundoff error, we want to consider all them
 *	to be maximal.)
 */
#define INTERCUSP_EPSILON			1e-6

/*
 *	If a given cusp does not have a maximal horoball, all other cusp cross
 *	sections are retracted in increments of DELTA_DISPLACEMENT until it does.
 *	The value of DELTA_DISPLACEMENT should be large enough that the algorithm
 *	has a fair shot at the getting a maximal horoball on the first try,
 *	but not so large that the canonization algorithm has to do a lot of
 *	thrasing around (in particular, we don't want it to have to randomize
 *	very often).
 */
#define DELTA_DISPLACEMENT			0.5

/*
 *	If the longitudinal translation has length zero,
 *	something has gone very, very wrong.
 */
#define LONGITUDE_EPSILON			1e-2

/*
 *	contains_north_pole() uses NORTH_POLE_EPSILON to decide when a face
 *	of a tetrahedron stands vertically over a vertex.
 */
#define NORTH_POLE_EPSILON			1e-6

/*
 *	A complex number of modulus greater than KEY_INFINITY is considered
 *	to be infinite, at least for the purpose of computing key values.
 */
#define KEY_INFINITY				1e+6

/*
 *	tiling_tet_on_tree() will compare two TilingTets iff their key values
 *	are within KEY_EPSILON of each other.  KEY_EPSILON can be fairly large;
 *	other than a loss of speed there is no harm in having the program make
 *	some occasional unnecessary comparisons.
 */
#define KEY_EPSILON					1e-4

/*
 *	Two TilingTets are considered equivalent under the Z + Z action of
 *	the cusp translations iff their corresponding (transformed) corners
 *	lie within CORNER_EPSILON of each other.
 */
#define CORNER_EPSILON				1e-6

/*
 *	cull_duplicate_horoballs() checks whether two horoballs are equivalent
 *	iff their radii differ by less than DUPLICATE_RADIUS_EPSILON.
 *	We should make DUPLICATE_RADIUS_EPSILON fairly large, to be sure we
 *	don't miss any horoballs even when their precision is low.
 */
#define DUPLICATE_RADIUS_EPSILON	1e-3


typedef int MinDistanceType;
enum
{
	dist_self_to_self,
	dist_self_to_any,
	dist_group_to_group,
	dist_group_to_any
};

typedef struct
{
	Tetrahedron			*tet;
	Orientation			h;
	VertexIndex			v;
} CuspTriangle;

typedef struct TilingHoroball
{
	CuspNbhdHoroball		data;
	struct TilingHoroball	*next;
} TilingHoroball;

typedef struct TilingTet
{
	/*
	 *	Which Tetrahedron in the original manifold lifts to this TilingTet?
	 */
	Tetrahedron			*underlying_tet;

	/*
	 *	Does it appear with the left_handed or right_handed orientation?
	 */
	Orientation			orientation;

	/*
	 *	Where are its four corners on the boundary of upper half space?
	 */
	Complex				corner[4];

	/*
	 *	What is the Euclidean diameter of the horoball at each corner?
	 */
	double				horoball_height[4];

	/*
	 *	If the neighboring TilingTet incident to face f has already been
	 *	found, neighbor_found[f] is set to TRUE so we won't waste time
	 *	finding it again.  More importantly, we won't have to worry about
	 *	the special case of "finding" the initial TilingTets incident to
	 *	the "horoball of infinite Euclidean radius".
	 */
	Boolean				neighbor_found[4];

	/*
	 *	Pointer for the NULL-terminated queue.
	 */
	struct TilingTet	*next;

	/*
	 *	Pointers for the tree.
	 */

	/*
	 *	The left child and right child pointers implement the binary tree.
	 */
	struct TilingTet	*left,
						*right;

	/*
	 *	The sort key is a continuous function of the TilingTet's corners,
	 *	and is well defined under the Z + Z action of the group of
	 *	covering transformations of the cusp.
	 */
	double				key;

	/*
	 *	We don't want our tree handling functions to be recursive,
	 *	for fear of stack/heap collisions.  So we implement them using
	 *	our own private stack, which is a NULL-terminated linked list
	 *	using the next_subtree pointer.  Unlike the "left" and "right"
	 *	fields (which are maintained throughout the algorithm) the
	 *	"next_subtree" field is used only locally within a given tree
	 *	handling function.
	 */
	struct TilingTet	*next_subtree;

} TilingTet;

typedef struct
{
	TilingTet	*begin,
				*end;
} TilingQueue;



static void					initialize_cusp_displacements(CuspNeighborhoods *cusp_neighborhoods);
static void					compute_cusp_reaches(CuspNeighborhoods *cusp_neighborhoods);
static void					compute_one_reach(CuspNeighborhoods *cusp_neighborhoods, Cusp *cusp);
static void					compute_tie_group_reach(CuspNeighborhoods *cusp_neighborhoods);
static Cusp					*some_tied_cusp(CuspNeighborhoods *cusp_neighborhoods);
static void					compute_cusp_stoppers(CuspNeighborhoods *cusp_neighborhoods);
static void					compute_intercusp_distances(Triangulation *manifold);
static void					compute_one_intercusp_distance(EdgeClass *edge);
static double				compute_min_dist(Triangulation *manifold, Cusp *cusp, MinDistanceType min_distance_type);
static void					initialize_cusp_ties(CuspNeighborhoods *cusp_neighborhoods);
static void					initialize_cusp_nbhd_positions(CuspNeighborhoods *cusp_neighborhoods);
static void					allocate_cusp_nbhd_positions(CuspNeighborhoods *cusp_neighborhoods);
static void					compute_cusp_nbhd_positions(CuspNeighborhoods *cusp_neighborhoods);
static Boolean				contains_meridian(Tetrahedron *tet, Orientation h, VertexIndex v);
static void					set_one_component(Tetrahedron *tet, Orientation h, VertexIndex v, int max_triangles);
static CuspNbhdHoroballList	*get_quick_horoball_list(CuspNeighborhoods *cusp_neighborhoods, Cusp *cusp);
static void					get_quick_edge_horoballs(Triangulation *manifold, Cusp *cusp, CuspNbhdHoroball **next_horoball);
static void					get_quick_face_horoballs(Triangulation *manifold, Cusp *cusp, CuspNbhdHoroball **next_horoball);
static CuspNbhdHoroballList	*get_full_horoball_list(CuspNeighborhoods *cusp_neighborhoods, Cusp *cusp, double cutoff_height);
static void					compute_exp_min_d(Triangulation *manifold);
static void					compute_parallelogram_to_square(Complex meridian, Complex longitude, double parallelogram_to_square[2][2]);
static void					read_initial_tetrahedra(Triangulation *manifold, Cusp *cusp, TilingQueue *tiling_queue, TilingTet **tiling_tree_root, TilingHoroball **horoball_linked_list, double cutoff_height);
static TilingTet			*get_tiling_tet_from_queue(TilingQueue *tiling_queue);
static void					add_tiling_tet_to_queue(TilingTet *tiling_tet, TilingQueue *tiling_queue);
static void					add_tiling_horoball_to_list(TilingTet *tiling_tet, VertexIndex v, TilingHoroball **horoball_linked_list);
static Boolean				face_contains_useful_edge(TilingTet *tiling_tet, FaceIndex f, double cutoff_height);
static TilingTet			*make_neighbor_tiling_tet(TilingTet *tiling_tet, FaceIndex f);
static void					prepare_sort_key(TilingTet *tiling_tet, double parallelogram_to_square[2][2]);
static Boolean				tiling_tet_on_tree(TilingTet *tiling_tet, TilingTet *tiling_tree_root, Complex meridian, Complex longitude);
static Boolean				same_corners(TilingTet *tiling_tet1, TilingTet *tiling_tet2, Complex meridian, Complex longitude);
static void					add_tiling_tet_to_tree(TilingTet *tiling_tet, TilingTet **tiling_tree_root);
static void					add_horoball_if_necessary(TilingTet *tiling_tet, TilingHoroball **horoball_linked_list, double cutoff_height);
static Boolean				contains_north_pole(TilingTet *tiling_tet, VertexIndex v);
static void					free_tiling_tet_tree(TilingTet *tiling_tree_root);
static CuspNbhdHoroballList	*transfer_horoballs(TilingHoroball **horoball_linked_list);
static int CDECL			compare_horoballs(const void *horoball0, const void *horoball1);
static void					cull_duplicate_horoballs(Cusp *cusp, CuspNbhdHoroballList *aHoroballList);

/*
 *	Conceptually, the CuspNeighborhoods structure stores cross sections
 *	of a manifold's cusps, and also keeps a Triangulation dual to the
 *	corresponding Ford complex.  In the present implementation, the
 *	information about the cross sections is stored entriely within the
 *	copy of the triangulation (specifically, in the Cusp's displacment,
 *	displacement_exp and reach fields, the EdgeClass's intercusp_distance
 *	field, and the Triangulation's max_reach field).
 *
 *	SnapPea.h (the only header file common to the user interface and the
 *	computational kernel) contains the opaque typedef
 *
 *		typedef struct CuspNeighborhoods	CuspNeighborhoods;
 *
 *	This opaque typedef allows the user interface to declare and pass
 *	a pointer to a CuspNeighborhoods structure, without being able to
 *	access a CuspNeighborhoods structure's fields directly.  Here is
 *	the actual definition, which is private to this file.
 */

struct CuspNeighborhoods
{
	/*
	 *	We'll keep our own private copy of the Triangulation, to avoid
	 *	messing up the original one.
	 */
	Triangulation	*its_triangulation;
};


/*
 *	Technical musings.
 *
 *	There are different approaches to maintaining a canonical
 *	triangulation as the cusp displacements change.
 *
 *	Low-level approach.
 *		Handle the 2-3 and 3-2 moves explicitly.  Calculate which
 *		move will be required next as the given cusp moves towards
 *		the requested displacement.
 *
 *	High-level approach.
 *		Set the requested cusp displacement directly, and call the
 *		standard proto_canonize() function to compute the corresponding
 *		canonical triangulation.
 *
 *	The low-level approach would be much more efficient at run time.
 *	The overhead of setting up the cusp cross sections at the beginning,
 *	and polishing the hyperbolic structure at the end, would be done
 *	only once.  It would also be efficient in that it tracks the convex
 *	hull (i.e. the canonical triangulation) precisely as the cusp moves
 *	toward the requested displacement.  (At each step it finds the next
 *	2-3 or 3-2 move which would be required as the cusp cross section
 *	moves continuously towards the requested displacement.)
 *
 *	The drawback of the low-level approach is that it would require
 *	a lot of low-level programming, which is time consuming, tends to
 *	make a mess, and can be error prone.  The high-level approach keeps
 *	the code cleaner, even though it's less efficient at run time.
 *
 *	For now I have implemented the high-level approach.  If it turns
 *	out that it is too slow, I can consider replacing it with the
 *	low-level approach.  An even better approach might be to make
 *	some simple changes to speed up the high-level approach.  For example,
 *	I was concerned that for large manifolds proto_canonize()'s bottleneck
 *	might be polishing the hyperbolic structure at the end.  I modified
 *	proto_canonize() to polish the hyperbolic structure iff the
 *	triangulation has been changed.
 */


CuspNeighborhoods *initialize_cusp_neighborhoods(
	Triangulation	*manifold)
{
	Triangulation		*simplified_manifold;
	CuspNeighborhoods	*cusp_neighborhoods;

	/*
	 *	If the space isn't a manifold, return NULL.
	 */
	if (all_Dehn_coefficients_are_relatively_prime_integers(manifold) == FALSE)
		return NULL;

	/*
	 *	Get rid of "unnecessary" cusps.
	 *	If we encounter topological obstructions, return NULL.
	 */
	simplified_manifold = fill_reasonable_cusps(manifold);
	if (simplified_manifold == NULL)
		return NULL;

	/*
	 *	If the manifold is closed, free it and return NULL.
	 */
	if (all_cusps_are_filled(simplified_manifold) == TRUE)
	{
		free_triangulation(simplified_manifold);
		return NULL;
	}

	/*
	 *	Attempt to canonize the manifold.
	 */
	if (proto_canonize(simplified_manifold) == func_failed)
	{
		free_triangulation(simplified_manifold);
		return NULL;
	}

	/*
	 *	Our manifold has passed all its tests,
	 *	so set up a CuspNeighborhoods structure.
	 */
	cusp_neighborhoods = NEW_STRUCT(CuspNeighborhoods);

	/*
	 *	Install our private copy of the triangulation.
	 */
	cusp_neighborhoods->its_triangulation = simplified_manifold;
	simplified_manifold = NULL;

	/*
	 *	Most likely the displacements will be zero already,
	 *	but we set them anyhow, just to be safe.
	 */
	initialize_cusp_displacements(cusp_neighborhoods);

	/*
	 *	Compute all cusp reaches.
	 */
	compute_cusp_reaches(cusp_neighborhoods);

	/*
	 *	Find the stoppers.
	 */
	compute_cusp_stoppers(cusp_neighborhoods);

	/*
	 *	Initially no cusps are tied.
	 */
	initialize_cusp_ties(cusp_neighborhoods);

	/*
	 *	Set up an implicit coordinate system on each cusp cross section
	 *	so that we can report the position of horoballs etc. consistently,
	 *	even as the canonical triangulation changes.
	 */
	initialize_cusp_nbhd_positions(cusp_neighborhoods);

	/*
	 *	Record the volume so we don't have to recompute it
	 *	over and over in real time.
	 */
	cusp_neighborhoods->its_triangulation->volume = volume(cusp_neighborhoods->its_triangulation, NULL);

	/*
	 *	Done.
	 */
	return cusp_neighborhoods;
}


void free_cusp_neighborhoods(
	CuspNeighborhoods	*cusp_neighborhoods)
{
	if (cusp_neighborhoods != NULL)
	{
		free_triangulation(cusp_neighborhoods->its_triangulation);
		my_free(cusp_neighborhoods);
	}
}


static void initialize_cusp_displacements(
	CuspNeighborhoods	*cusp_neighborhoods)
{
	Cusp	*cusp;

	for (cusp = cusp_neighborhoods->its_triangulation->cusp_list_begin.next;
		 cusp != &cusp_neighborhoods->its_triangulation->cusp_list_end;
		 cusp = cusp->next)
	{
		cusp->displacement		= 0.0;
		cusp->displacement_exp	= 1.0;
	}
}


static void compute_cusp_reaches(
	CuspNeighborhoods	*cusp_neighborhoods)
{
	Cusp	*cusp;

	cusp_neighborhoods->its_triangulation->max_reach = 0.0;

	for (cusp = cusp_neighborhoods->its_triangulation->cusp_list_begin.next;
		 cusp != &cusp_neighborhoods->its_triangulation->cusp_list_end;
		 cusp = cusp->next)
	{
		compute_one_reach(cusp_neighborhoods, cusp);

		if (cusp->reach > cusp_neighborhoods->its_triangulation->max_reach)
			cusp_neighborhoods->its_triangulation->max_reach = cusp->reach;
	}
}


static void compute_one_reach(
	CuspNeighborhoods	*cusp_neighborhoods,
	Cusp				*cusp)
{
	/*
	 *	The key observation is the following.  Think of a horoball
	 *	packing corresponding to the cusp cross sections in their home
	 *	positions, with the given cusp lifting to the plane z == 1 in
	 *	the upper half space model.  The vertical line passing through
	 *	the top of a maximally (Eucliean-)large round horoball is
	 *	guaranteed to be an edge in the canonical triangulation.
	 *	(Proof:  As the horoballs expand equivariantly, the largest round
	 *	horoball(s) is(are) the first one(s) to touch the z == 1 horoball.)
	 *	So by measuring the distance between cusp cross sections along the
	 *	edges of the canonical triangulation, we can deduce the distance
	 *	from the given cusp to the largest round horoball(s).  If a largest
	 *	round horoball corresponds to the given cusp, then we know the
	 *	cusp's reach and we're done.  If the largest horoballs all belong
	 *	to other cusps, then we retract the other cusps a bit (i.e. give
	 *	them a negative displacement) and try again.  Eventually a horoball
	 *	corresponding to the given cusp will be maximal.
	 */

	Triangulation	*triangulation_copy;
	Cusp			*cusp_copy,
					*other_cusp;
	double			dist_any,
					dist_self;

	/*
	 *	Make a copy of the triangulation, so we don't disturb the original.
	 */
	copy_triangulation(cusp_neighborhoods->its_triangulation, &triangulation_copy);
	cusp_copy = find_cusp(triangulation_copy, cusp->index);

	/*
	 *	Carry out the algorithm described above.
	 */
	while (TRUE)
	{
		/*
		 *	Compute the distances between cusp cross sections along each
		 *	edge of the (already canonical) triangulation, and store the
		 *	results in the EdgeClass's intercusp_distance field.
		 *
		 *	Technical note:  There is a small inefficiency here in that
		 *	proto_canonize() creates and discards the cusp cross sections,
		 *	and here we create and discard them again.  If this turns out
		 *	to be a problem we could have proto_canonize() compute the
		 *	intercusp distances when it does the canonization, but for
		 *	now I'll put up with the inefficiency to keep the code clean.
		 */
		compute_intercusp_distances(triangulation_copy);

		/*
		 *	Does a maximally large round horoball belong to the given cusp?
		 *	If so, we know the reach and we're done.
		 */
		dist_self = compute_min_dist(triangulation_copy, cusp_copy, dist_self_to_self);
		dist_any  = compute_min_dist(triangulation_copy, cusp_copy, dist_self_to_any);
		if (dist_self < dist_any + INTERCUSP_EPSILON)
		{
			cusp->reach = 0.5 * dist_self;
			break;
		}

		/*
		 *	Otherwise, retract all cross sections except the given one,
		 *	recanonize, and continue with the loop.
		 *
		 *	Note:  initialize_cusp_neighborhoods() has already checked
		 *	that the manifold is hyperbolic, so proto_canonize() should
		 *	not fail.
		 */

		for (other_cusp = triangulation_copy->cusp_list_begin.next;
			 other_cusp != &triangulation_copy->cusp_list_end;
			 other_cusp = other_cusp->next)

			if (other_cusp != cusp_copy)
			{
				other_cusp->displacement -= DELTA_DISPLACEMENT;
				other_cusp->displacement_exp = exp(other_cusp->displacement);
			}

		if (proto_canonize(triangulation_copy) != func_OK)
			uFatalError("compute_one_reach", "cusp_neighborhoods.c");
	}

	/*
	 *	Free the copy of the triangulation.
	 */
	free_triangulation(triangulation_copy);
}


static void compute_tie_group_reach(
	CuspNeighborhoods	*cusp_neighborhoods)
{
	/*
	 *	This function is similar to compute_one_reach(), but instead of
	 *	computing the reach of a single cusp, it computes the reach of
	 *	a group of tied cusps (that is a group of cusp neighborhoods which
	 *	move forward and backward in unison).  Please see compute_one_reach()
	 *	above for detailed documentation.
	 */

	Triangulation	*triangulation_copy;
	double			dist_any,
					dist_self;
	Cusp			*cusp;

	/*
	 *	If no cusps are tied, there is nothing to be done.
	 */
	if (some_tied_cusp(cusp_neighborhoods) == NULL)
	{
		cusp_neighborhoods->its_triangulation->tie_group_reach = 0.0;
		return;
	}

	/*
	 *	Make a copy of the triangulation, so we don't disturb the original.
	 *	copy_triangulation() copies the is_tied field, even though it is
	 *	in some sense private to this file.
	 */
	copy_triangulation(cusp_neighborhoods->its_triangulation, &triangulation_copy);

	/*
	 *	Carry out the algorithm described in compute_one_reach().
	 */

	while (TRUE)
	{
		compute_intercusp_distances(triangulation_copy);

		dist_self = compute_min_dist(triangulation_copy, NULL, dist_group_to_group);
		dist_any  = compute_min_dist(triangulation_copy, NULL, dist_group_to_any);

		if (dist_self < dist_any + INTERCUSP_EPSILON)
		{
			cusp_neighborhoods->its_triangulation->tie_group_reach
				= some_tied_cusp(cusp_neighborhoods)->displacement
				+ 0.5 * dist_self;
			break;
		}

		for (cusp = triangulation_copy->cusp_list_begin.next;
			 cusp != &triangulation_copy->cusp_list_end;
			 cusp = cusp->next)

			if (cusp->is_tied == FALSE)
			{
				cusp->displacement -= DELTA_DISPLACEMENT;
				cusp->displacement_exp = exp(cusp->displacement);
			}

		if (proto_canonize(triangulation_copy) != func_OK)
			uFatalError("compute_tie_group_reach", "cusp_neighborhoods.c");
	}

	free_triangulation(triangulation_copy);
}


static Cusp *some_tied_cusp(
	CuspNeighborhoods	*cusp_neighborhoods)
{
	Cusp	*cusp;

	for (cusp = cusp_neighborhoods->its_triangulation->cusp_list_begin.next;
		 cusp != &cusp_neighborhoods->its_triangulation->cusp_list_end;
		 cusp = cusp->next)

		if (cusp->is_tied)

			return cusp;

	return NULL;
}


static void compute_cusp_stoppers(
	CuspNeighborhoods	*cusp_neighborhoods)
{
	/*
	 *	Think of a horoball packing corresponding to the cusp cross sections
	 *	in their current positions, with a given cusp lifting to the plane
	 *	z == 1 in the upper half space model.  The vertical line passing
	 *	through the top of a maximally (Eucliean-)large round horoball is
	 *	guaranteed to be an edge in the canonical cell decomposition.
	 *	(Proof:  As the horoballs expand equivariantly, the largest
	 *	round horoballs will be the first to touch the z == 1 horoball.)
	 *
	 *	Case 1.  The maximal horoball belongs to the given cusp.
	 *
	 *		In this case, the given cusp is its own stopper, and the
	 *		stopping displacement is its reach.
	 *
	 *	Case 2.  The maximal horoball belongs to some other cusp.
	 *
	 *		The displacement at which the given cusp meets the other cusp
	 *		may or may not be less than the given cusp's reach.
	 *		(A less-than-maximal horoball belonging to the given cusp may
	 *		overtake a formerly maximal cusp, because horoballs belonging
	 *		to the given cusp grow as the given cusp moves forward, while
	 *		other horoballs do not.)  If the stopping displacement is
	 *		less than the given cusp's reach, then we've found a stopper
	 *		cusp and stopping displacement (the stopping displacement is
	 *		unique, even though the stopper cusp may not be).  If the
	 *		stopping is greater than or equal to the given cusp's reach,
	 *		then the cusp is its own stopper, as in case 1.
	 */

	Cusp		*cusp,
				*c[2];
	EdgeClass	*edge;
	int			i;
	double		possible_stopping_displacement;

	/*
	 *	Initialize each stopper to be the cusp itself, and the stopping
	 *	displacement to be its reach.
	 */

	for (cusp = cusp_neighborhoods->its_triangulation->cusp_list_begin.next;
		 cusp != &cusp_neighborhoods->its_triangulation->cusp_list_end;
		 cusp = cusp->next)
	{
		cusp->stopper_cusp			= cusp;
		cusp->stopping_displacement	= cusp->reach;
	}

	/*
	 *	Now look at each edge of the canonical triangulation, to see
	 *	whether some other cusp cross section is closer.
	 *
	 *	cusp_neighborhoods->its_triangulation is always the canonical
	 *	triangulation (or an arbitrary subdivision of the canonical
	 *	cell decomposition).
	 */

	compute_intercusp_distances(cusp_neighborhoods->its_triangulation);

	for (edge = cusp_neighborhoods->its_triangulation->edge_list_begin.next;
		 edge != &cusp_neighborhoods->its_triangulation->edge_list_end;
		 edge = edge->next)
	{
		c[0] = edge->incident_tet->cusp[  one_vertex_at_edge[edge->incident_edge_index]];
		c[1] = edge->incident_tet->cusp[other_vertex_at_edge[edge->incident_edge_index]];

		for (i = 0; i < 2; i++)
		{
			possible_stopping_displacement =
				c[i]->displacement + edge->intercusp_distance;

			if (possible_stopping_displacement < c[i]->stopping_displacement)
			{
				c[i]->stopping_displacement	= possible_stopping_displacement;
				c[i]->stopper_cusp			= c[!i];
			}
		}
	}
}


static void compute_intercusp_distances(
	Triangulation	*manifold)
{
	/*
	 *	In the present context we may assume the triangulation is
	 *	canonical (although all we really need to know is that it
	 *	has a geometric_solution).
	 */

	EdgeClass	*edge;

	/*
	 *	Set up the cusp cross sections.
	 */
	allocate_cross_sections(manifold);
	compute_cross_sections(manifold);

	/*
	 *	Compute the intercusp_distances.
	 */

	for (edge = manifold->edge_list_begin.next;
		 edge != &manifold->edge_list_end;
		 edge = edge->next)

		compute_one_intercusp_distance(edge);

	/*
	 *	Release the cusp cross sections.
	 */
	free_cross_sections(manifold);
}


static void compute_one_intercusp_distance(
	EdgeClass	*edge)
{
	int			i,
				j;
	Tetrahedron	*tet;
	EdgeIndex	e;
	VertexIndex	v[2];
	FaceIndex	f[2];
	double		length[2][2],
				product;

	/*
	 *	Find an arbitrary Tetrahedron incident to the given EdgeClass.
	 */
	tet = edge->incident_tet;
	e = edge->incident_edge_index;

	/*
	 *	Note which vertices and faces are incident to the EdgeClass.
	 */
	v[0] =   one_vertex_at_edge[e];
	v[1] = other_vertex_at_edge[e];
	f[0] =     one_face_at_edge[e];
	f[1] =   other_face_at_edge[e];

	/*
	 *	The vertex cross section at each vertex v[i] is a triangle.
	 *	Note the lengths of the triangle's edges incident to the EdgeClass.
	 */
	for (i = 0; i < 2; i++)
		for (j = 0; j < 2; j++)
			length[i][j] = tet->cusp[v[i]]->displacement_exp
							* tet->cross_section->edge_length[v[i]][f[j]];

	/*
	 *	Our task is to compute the distance between the vertex cross sections
	 *	as a function of the length[][]'s.  Fortunately this is easier than
	 *	you might except.  I recommend you make sketches for yourself as
	 *	you read through the following.  (It's much simpler in pictures
	 *	than it is in words.)
	 *
	 *	Proposition.  There is a unique common perpendicular to a pair of
	 *	opposite edges of an ideal tetrahedron.
	 *
	 *	Proof.  Consider the line segment which minimizes the distance
	 *	between the two opposite edges.  If it weren't perpendicular to
	 *	each edge, then a shorter line segement could be found.  QED
	 *
	 *	Definition.  The "midpoint" of an edge of an ideal tetrahedron is
	 *	the point where the edge intersects the unique common perpendicular
	 *	to the opposite edge.
	 *
	 *	Proposition.  A half turn about the aforementioned unique common
	 *	perpendicular is a symmetry of the ideal tetrahedron.
	 *
	 *	Proof.  It preserves (setwise) a pair of opposite edges.  Therefore
	 *	it preserves (setwise) the tetrahedron's four ideal vertices, and
	 *	therefore the whole tetrahedron.  QED
	 *
	 *	Proposition.  Consider a vertex cross section which passes through
	 *	the midpoint of an edge.  The two sides of the vertex cross section
	 *	which are incident to the given edge of the tetrahedron have lengths
	 *	which are reciprocals of one another.
	 *
	 *	Proof.  Position the tetrahedron in the upper half space model so
	 *	that the given edge is vertical and its midpoint is at height one.
	 *
	 *	Let P1 be the unique plane which contains the aforementioned unique
	 *		common perpendicular and also contains the edge itself.
	 *
	 *	Let P2 be the unique plane which contains the aforementioned unique
	 *		common perpendicular and is orthogonal to the edge itself.
	 *
	 *	Let S be the symmetry defined by a reflection in P1 followed by a
	 *		reflection in P2.
	 *
	 *	S is equivalent to a half turn about the unique common perpendicular
	 *	(proof:  P1 and P2 are orthogonal to each other, and both contain
	 *	the unique common perpendicular).  Therefore S is a symmetry of the
	 *	ideal tetrahedron, by the preceding proposition.
	 *
	 *	Let L1 and L2 be the lengths of the two sides of the vertex cross
	 *	section which are incident to the given edge.  Because the vertex
	 *	cross section is at height one in the upper half space model,
	 *	L1 and L2 also represent the Euclidean lengths of two sides of the
	 *	triangle obtained by projecting the ideal tetrahedron onto the
	 *	plane z == 0 in the upper half space model.  Reflection in the
	 *	plane P1 does not change the lengths of those two sides of the
	 *	triangle, while reflection in the plane P2 (which, in Euclidean
	 *	terms, is inversion in a hemisphere of radius one) sends each
	 *	length to its inverse.  Since the composition S of the two
	 *	reflections preserves the triangle, it follows that L1 and L2
	 *	must be inverses of one another.  QED
	 *
	 *	If a vertex cross section passes through the midpoint of an edge,
	 *	then the product of the lengths L1 and L2 (using the notation of
	 *	the preceding proof) is L1 L2 = 1.  Now consider a vertex cross
	 *	section which is a distance d away from the midpoint (towards
	 *	the fat part of the manifold if d is positive, towards the cusp
	 *	if d is negative).  According to the documentation at the top of
	 *	this file, a cusp cross section's linear dimensions vary as exp(d),
	 *	so the lengths of the corresponding sides of the new vertex cross
	 *	section will be exp(d)L1 and exp(d)L2.  Their product is
	 *	exp(d)L1 exp(d)L2 = exp(2d) L1 L2 = exp(2d).
	 *
	 *	If the lengths of the sides of the vertex cross section at the
	 *	other end of the given edge are exp(d')L1 and exp(d')L2, then
	 *	their product is exp(2d').  The product of all four lengths is
	 *
	 *		exp(d)L1 exp(d)L2 exp(d')L1 exp(d')L2 = exp(2(d + d')).
	 *
	 *	This is exactly what we need to know:  d + d' is the negative
	 *	of the intercusp distance.  (Note that the midpoint has dropped
	 *	out of the picture!)
	 */

	product = 1.0;
	for (i = 0; i < 2; i++)
		for (j = 0; j < 2; j++)
			product *= length[i][j];

	edge->intercusp_distance = -0.5 * log(product);
}


static double compute_min_dist(
	Triangulation	*manifold,
	Cusp			*cusp,	/* ignored for tie group distances	*/
	MinDistanceType	min_distance_type)
{
	/*
	 *	This function assumes the intercusp_distances
	 *	have already been computed.
	 */

	double		min_dist;
	EdgeClass	*edge;
	Cusp		*cusp1,
				*cusp2;

	min_dist = DBL_MAX;

	for (edge = manifold->edge_list_begin.next;
		 edge != &manifold->edge_list_end;
		 edge = edge->next)
	{
		cusp1 = edge->incident_tet->cusp[  one_vertex_at_edge[edge->incident_edge_index]];
		cusp2 = edge->incident_tet->cusp[other_vertex_at_edge[edge->incident_edge_index]];

		if (edge->intercusp_distance < min_dist)

			switch (min_distance_type)
			{
				case dist_self_to_self:
					if (cusp == cusp1 && cusp == cusp2)
						min_dist = edge->intercusp_distance;
					break;

				case dist_self_to_any:
					if (cusp == cusp1 || cusp == cusp2)
						min_dist = edge->intercusp_distance;
					break;

				case dist_group_to_group:
					if (cusp1->is_tied && cusp2->is_tied)
						min_dist = edge->intercusp_distance;
					break;

				case dist_group_to_any:
					if (cusp1->is_tied || cusp2->is_tied)
						min_dist = edge->intercusp_distance;
					break;
			}
	}

	return min_dist;
}


int get_num_cusp_neighborhoods(
	CuspNeighborhoods	*cusp_neighborhoods)
{
	if (cusp_neighborhoods == NULL)
		return 0;
	else
		return get_num_cusps(cusp_neighborhoods->its_triangulation);
}


CuspTopology get_cusp_neighborhood_topology(
	CuspNeighborhoods	*cusp_neighborhoods,
	int					cusp_index)
{
	return find_cusp(cusp_neighborhoods->its_triangulation, cusp_index)->topology;
}


double get_cusp_neighborhood_displacement(
	CuspNeighborhoods	*cusp_neighborhoods,
	int					cusp_index)
{
	return find_cusp(cusp_neighborhoods->its_triangulation, cusp_index)->displacement;
}


Boolean get_cusp_neighborhood_tie(
	CuspNeighborhoods	*cusp_neighborhoods,
	int					cusp_index)
{
	return find_cusp(cusp_neighborhoods->its_triangulation, cusp_index)->is_tied;
}


double get_cusp_neighborhood_cusp_volume(
	CuspNeighborhoods	*cusp_neighborhoods,
	int					cusp_index)
{
	/*
	 *	As explained in the documentation at the top of this file,
	 *	the volume will be the volume enclosed by the cusp in its
	 *	home position, multiplied by exp(2 * displacement).
	 */

	return 0.1875 * ROOT_3 * exp(2 * find_cusp(cusp_neighborhoods->its_triangulation, cusp_index)->displacement);
}


double get_cusp_neighborhood_manifold_volume(
	CuspNeighborhoods	*cusp_neighborhoods)
{
	return cusp_neighborhoods->its_triangulation->volume;
}


Triangulation *get_cusp_neighborhood_manifold(
	CuspNeighborhoods	*cusp_neighborhoods)
{
	Triangulation	*manifold_copy;
	Cusp			*cusp;

	/*
	 *	Make a copy of its_triangulation.
	 */
	copy_triangulation(cusp_neighborhoods->its_triangulation, &manifold_copy);

	/*
	 *	Reset the cusp displacements to zero, so if a canonical triangulation
	 *	is needed later it will be computed relative to cusp cross sections
	 *	of equal volume.
	 */
	for (cusp = manifold_copy->cusp_list_begin.next;
		 cusp != &manifold_copy->cusp_list_end;
		 cusp = cusp->next)
	{
		cusp->displacement		= 0.0;
		cusp->displacement_exp	= 1.0;
	}

	return manifold_copy;
}


double get_cusp_neighborhood_reach(
	CuspNeighborhoods	*cusp_neighborhoods,
	int					cusp_index)
{
	return find_cusp(cusp_neighborhoods->its_triangulation, cusp_index)->reach;
}


double get_cusp_neighborhood_max_reach(
	CuspNeighborhoods	*cusp_neighborhoods)
{
	return cusp_neighborhoods->its_triangulation->max_reach;
}


double get_cusp_neighborhood_stopping_displacement(
	CuspNeighborhoods	*cusp_neighborhoods,
	int					cusp_index)
{
	return find_cusp(cusp_neighborhoods->its_triangulation, cusp_index)->stopping_displacement;
}


int get_cusp_neighborhood_stopper_cusp_index(
	CuspNeighborhoods	*cusp_neighborhoods,
	int					cusp_index)
{
	return find_cusp(cusp_neighborhoods->its_triangulation, cusp_index)->stopper_cusp->index;
}


void set_cusp_neighborhood_displacement(
	CuspNeighborhoods	*cusp_neighborhoods,
	int					cusp_index,
	double				new_displacement)
{
	Cusp	*cusp,
			*other_cusp;

	/*
	 *	Get a pointer to the cusp whose displacement is being changed.
	 */

	cusp = find_cusp(cusp_neighborhoods->its_triangulation, cusp_index);

	/*
	 *	Clip the displacement to the feasible range.
	 */

	if (new_displacement < 0.0)
		new_displacement = 0.0;

	if (cusp->is_tied == FALSE)
	{
		/*
		 *	The stopping_displacement has already been set to be less than or
		 *	equal to the reach, so by clipping to the stopping_displacement
		 *	we know the cusp neighborhood won't overlap itself or any
		 *	other cusp neighborhood.
		 */ 

		if (new_displacement > cusp->stopping_displacement)
			new_displacement = cusp->stopping_displacement;

	}
	else	/*	cusp->is_tied == TRUE	*/
	{
		/*
		 *	Make sure the new_displacement doesn't exceed the tie_group_reach.
		 *	Other cusps in the tie group will be coming at us as we move
		 *	toward them, so collisions might not be detected by the
		 *	stopping_displacement alone.  (The latter assumes the other
		 *	cusp is stationary.)
		 */

		if (new_displacement > cusp_neighborhoods->its_triangulation->tie_group_reach)
			new_displacement = cusp_neighborhoods->its_triangulation->tie_group_reach;

		/*
		 *	Don't overlap untied stoppers either.
		 */

		for (other_cusp = cusp_neighborhoods->its_triangulation->cusp_list_begin.next;
			 other_cusp != &cusp_neighborhoods->its_triangulation->cusp_list_end;
			 other_cusp = other_cusp->next)

			if (other_cusp->is_tied
			 &&	new_displacement > other_cusp->stopping_displacement)

				new_displacement = other_cusp->stopping_displacement;
	}
		
	/*
	 *	Set the new displacement.
	 */

	if (cusp->is_tied == FALSE)
	{
		cusp->displacement		= new_displacement;
		cusp->displacement_exp	= exp(new_displacement);
	}
	else	/*	cusp->is_tied == TRUE	*/
	{
		for (other_cusp = cusp_neighborhoods->its_triangulation->cusp_list_begin.next;
			 other_cusp != &cusp_neighborhoods->its_triangulation->cusp_list_end;
			 other_cusp = other_cusp->next)

			if (other_cusp->is_tied)
			{
				other_cusp->displacement		= new_displacement;
				other_cusp->displacement_exp	= exp(new_displacement);
			}
	}

	/*
	 *	Compute the canonical cell decomposition
	 *	relative to the new displacement.
	 */

	if (proto_canonize(cusp_neighborhoods->its_triangulation) != func_OK)
		uFatalError("set_cusp_neighborhood_displacement", "cusp_neighborhoods");

	/*
	 *	The cusp reaches won't have changed, but the stoppers might have.
	 */

	compute_cusp_stoppers(cusp_neighborhoods);
}


void set_cusp_neighborhood_tie(
	CuspNeighborhoods	*cusp_neighborhoods,
	int					cusp_index,
	Boolean				new_tie)
{
	Cusp	*cusp,
			*other_cusp;
	double	min_displacement;

	/*
	 *	Get a pointer to the cusp which is being tied or untied.
	 */
	cusp = find_cusp(cusp_neighborhoods->its_triangulation, cusp_index);

	/*
	 *	Tie or untie the cusp.
	 */
	cusp->is_tied = new_tie;
	
	/*
	 *	If the cusp is being tied, bring it and its mates into line.
	 */

	if (cusp->is_tied == TRUE)
	{
		/*
		 *	Find the minimum displacement for a tied cusp . . .
		 */

		min_displacement = DBL_MAX;

		for (other_cusp = cusp_neighborhoods->its_triangulation->cusp_list_begin.next;
			 other_cusp != &cusp_neighborhoods->its_triangulation->cusp_list_end;
			 other_cusp = other_cusp->next)

			if (other_cusp->is_tied && other_cusp->displacement < min_displacement)

				min_displacement = other_cusp->displacement;

		/*
		 *	. . . and set all tied cusps to that minimum value.
		 */

		for (other_cusp = cusp_neighborhoods->its_triangulation->cusp_list_begin.next;
			 other_cusp != &cusp_neighborhoods->its_triangulation->cusp_list_end;
			 other_cusp = other_cusp->next)

			if (other_cusp->is_tied)
			{
				other_cusp->displacement		= min_displacement;
				other_cusp->displacement_exp	= exp(min_displacement);
			}

		/*
		 *	Compute the canonical cell decomposition
		 *	relative to the minimum displacement.
		 */
		if (proto_canonize(cusp_neighborhoods->its_triangulation) != func_OK)
			uFatalError("set_cusp_neighborhood_tie", "cusp_neighborhoods");

		/*
		 *	The cusp reaches won't have changed,
		 *	but the stoppers might have.
		 */
		compute_cusp_stoppers(cusp_neighborhoods);
	}

	/*
	 *	How far can the group of tied cusps go before bumping into itself?
	 */
	compute_tie_group_reach(cusp_neighborhoods);
}


static void initialize_cusp_ties(
	CuspNeighborhoods	*cusp_neighborhoods)
{
	Cusp	*cusp;

	/*
	 *	Initially no cusps are tied . . .
	 */
	for (cusp = cusp_neighborhoods->its_triangulation->cusp_list_begin.next;
		 cusp != &cusp_neighborhoods->its_triangulation->cusp_list_end;
		 cusp = cusp->next)

		cusp->is_tied = FALSE;

	/*
	 *	 . . . and the tie_group_reach is undefined.
	 */
	cusp_neighborhoods->its_triangulation->tie_group_reach = 0.0;
}


static void initialize_cusp_nbhd_positions(
	CuspNeighborhoods	*cusp_neighborhoods)
{
	/*
	 *	Install VertexCrossSections so that we know the size of each
	 *	vertex cross section in the cusp's home position.
	 */
	allocate_cross_sections(cusp_neighborhoods->its_triangulation);
	compute_cross_sections(cusp_neighborhoods->its_triangulation);

	/*
	 *	Allocate storage for the CuspNbhdPositions . . .
	 */
	allocate_cusp_nbhd_positions(cusp_neighborhoods);

	/*
	 *	. . . and then compute them.
	 */
	compute_cusp_nbhd_positions(cusp_neighborhoods);

	/*
	 *	Free the VertexCrossSections now that we're done with them.
	 *	(proto_canonize() will of course need them again, but it likes
	 *	to allocate them for itself -- this keeps its interaction with
	 *	the rest of the kernel cleaner.)
	 */
	free_cross_sections(cusp_neighborhoods->its_triangulation);
}


static void allocate_cusp_nbhd_positions(
	CuspNeighborhoods	*cusp_neighborhoods)
{
	Tetrahedron	*tet;

	for (tet = cusp_neighborhoods->its_triangulation->tet_list_begin.next;
		 tet != &cusp_neighborhoods->its_triangulation->tet_list_end;
		 tet = tet->next)
	{
		/*
		 *	Just for good measure, make sure no CuspNbhdPositions
		 *	are already allocated.
		 */
		if (tet->cusp_nbhd_position != NULL)
			uFatalError("allocate_cusp_nbhd_positions", "cusp_neighborhoods");

		/*
		 *	Allocate a CuspNbhdPosition structure.
		 */
		tet->cusp_nbhd_position = NEW_STRUCT(CuspNbhdPosition);
	}
}


static void compute_cusp_nbhd_positions(
	CuspNeighborhoods	*cusp_neighborhoods)
{
	Tetrahedron		*tet;
	Orientation		h;
	VertexIndex		v;
	int				max_triangles;
	Cusp			*cusp;
	PeripheralCurve	c;
	Complex			(*x)[4][4],
					*translation;
	Boolean			(*in_use)[4];
	FaceIndex		f,
					f0,
					f1,
					f2;
	int				strands1,
					strands2,
					flow;
	double			length;
	Complex			factor;

	/*
	 *	Initialize all the tet->in_use[][] fields to FALSE,
	 *	and all tet->x[][][] to Zero.
	 */

	for (tet = cusp_neighborhoods->its_triangulation->tet_list_begin.next;
		 tet != &cusp_neighborhoods->its_triangulation->tet_list_end;
		 tet = tet->next)

		for (h = 0; h < 2; h++)		/* h = right_handed, left_handed */

			for (v = 0; v < 4; v++)
			{
				for (f = 0; f < 4; f++)
					tet->cusp_nbhd_position->x[h][v][f] = Zero;

				tet->cusp_nbhd_position->in_use[h][v] = FALSE;
			}

	/*
	 *	For each vertex cross section which has not yet been set, set the
	 *	positions of its three vertices, and then recursively set the
	 *	positions of neighboring vertex cross sections.  The positions
	 *	are relative to each cusp cross section's home position.
	 *	(Recall that initialize_cusp_nbhd_positions() has already called
	 *	compute_cross_sections() for us.)  For torus cusps, do only the
	 *	sheet of the double cover which contains the peripheral curves
	 *	(this will be the right_handed sheet if the manifold is orientable).
	 */

	max_triangles = 2 * 4 * cusp_neighborhoods->its_triangulation->num_tetrahedra;

	for (tet = cusp_neighborhoods->its_triangulation->tet_list_begin.next;
		 tet != &cusp_neighborhoods->its_triangulation->tet_list_end;
		 tet = tet->next)

		for (v = 0; v < 4; v++)

			if (tet->cusp_nbhd_position->in_use[right_handed][v] == FALSE
			 && tet->cusp_nbhd_position->in_use[ left_handed][v] == FALSE)
			{
				/*
				 *	Use the sheet which contains the peripheral curves.
				 *	If neither does, do nothing for now.  They'll show
				 *	up eventually.
				 */

				for (h = 0; h < 2; h++)		/* h = right_handed, left_handed */

					if (contains_meridian(tet, h, v) == TRUE)
					{
						set_one_component(tet, h, v, max_triangles);
						break;
					}
			}

	/*
	 *	Compute the meridional and longitudinal translation on each
	 *	cusp cross section.  For Klein bottle cusps, the longitude
	 *	will actually be that of the double cover.  The translations
	 *	are stored in the Cusp data structure as translation[M] and
	 *	translation[L].
	 */

	/*
	 *	The Algorithm
	 *
	 *	The calls to set_one_component() have assigned coordinates to all
	 *	the triangles in the induced triangulation of the cusp cross section.
	 *	The problem is that these coordinates are well defined only up
	 *	to translations in the covering transformation group (or the
	 *	orientation preserving subgroup, in the case of a Klein bottle cusp).
	 *	So we want an algorithm which uses only the local coordinates within
	 *	each triangle, without requiring global consistency.
	 *
	 *	Imagine following a peripheral curve around the cusp cross section,
	 *	and look at the sides of the triangles it passes through.  As we
	 *	go along, we can keep track of the coordinates of the left and
	 *	right hand edges.  When we "veer left" the left hand endpoint stays
	 *	constant, while the right hand endpoint moves forward, and vice
	 *	versa when we "veer right".  By adding up all the displacements to
	 *	each endpoint, by the time we get back to our starting point we will
	 *	have computed the total translation along the curve.  Actually,
	 *	it suffices to compute the total displacement for only one endpoint
	 *	(left or right) since both will give the same answer.
	 *
	 *	Finally, note that it doesn't matter in what order we sum the
	 *	displacements.  We can just iterate through all tetrahedra in the
	 *	triangulation without explicitly tracing curves.
	 */

	/*
	 *	Initialize all translations to (0.0, 0.0), and then . . .
	 */

	for (cusp = cusp_neighborhoods->its_triangulation->cusp_list_begin.next;
		 cusp != &cusp_neighborhoods->its_triangulation->cusp_list_end;
		 cusp = cusp->next)

		for (c = 0; c < 2; c++)

			cusp->translation[c] = Zero;

	/*
	 *	. . . add in the contribution of each piece of each curve.
	 */

	for (tet = cusp_neighborhoods->its_triangulation->tet_list_begin.next;
		 tet != &cusp_neighborhoods->its_triangulation->tet_list_end;
		 tet = tet->next)
	{
		x		= tet->cusp_nbhd_position->x;
		in_use	= tet->cusp_nbhd_position->in_use;

		for (v = 0; v < 4; v++)
		{
			cusp = tet->cusp[v];

			for (c = 0; c < 2; c++)
			{
				translation = &cusp->translation[c];

				for (f0 = 0; f0 < 4; f0++)
				{
					if (f0 == v)
						continue;

					/*
					 *	Relative to the right_handed Orientation, the faces
					 *	f0, f1 and f2 are arranged around the ideal vertex v
					 *	like this
					 *
					 *					/\
					 *				f1 /  \ f0
					 *				  /____\
					 *					f2
					 *
					 *	The triangles corners inherit the indices of the
					 *	opposite sides.
					 */
					f1 = remaining_face[f0][v];
					f2 = remaining_face[v][f0];

					for (h = 0; h < 2; h++)	/* h = right_handed, left_handed */
					{
						if (in_use[h][v] == FALSE)
							continue;

						strands1 = tet->curve[c][h][v][f1];
						strands2 = tet->curve[c][h][v][f2];

						flow = FLOW(strands2, strands1);

						/*
						 *	We're interested only in displacements of the
						 *	left hand endpoint (cf. above), which occur when
						 *	the flow is negative (if h == right_handed) or
						 *	the flow is positive (if h == left_handed).
						 */
						if ((h == right_handed) ? (flow < 0) : (flow > 0))
							*translation = complex_plus(
								*translation,
								complex_real_mult(
									flow,
									complex_minus(x[h][v][f2], x[h][v][f1])));
					}
				}
			}
		}
	}

	/*
	 *	Rotate the coordinates so that the longitudes point in the
	 *	direction of the positive x-axis.
	 */

	/*
	 *	Find the rotation needed for each cusp,
	 *	and use it to rotate the meridian and longitude.
	 */

	for (cusp = cusp_neighborhoods->its_triangulation->cusp_list_begin.next;
		 cusp != &cusp_neighborhoods->its_triangulation->cusp_list_end;
		 cusp = cusp->next)
	{
		cusp->scratch = cusp->translation[L];
		length = complex_modulus(cusp->scratch);
		if (length < LONGITUDE_EPSILON)
			uFatalError("compute_cusp_nbhd_positions", "cusp_neighborhoods");
		cusp->scratch = complex_real_mult(1.0/length, cusp->scratch);
		cusp->scratch = complex_div(One, cusp->scratch);

		cusp->translation[M] = complex_mult(cusp->scratch, cusp->translation[M]);
		cusp->translation[L] = complex_mult(cusp->scratch, cusp->translation[L]);

		cusp->translation[L].imag = 0.0;	/* kill the roundoff error */
	}

	/*
	 *	Use the same rotation (stored in cusp->scratch) to rotate
	 *	the coordinates in the triangulation of the cusp.
	 */

	for (tet = cusp_neighborhoods->its_triangulation->tet_list_begin.next;
		 tet != &cusp_neighborhoods->its_triangulation->tet_list_end;
		 tet = tet->next)
	{
		x		= tet->cusp_nbhd_position->x;
		in_use	= tet->cusp_nbhd_position->in_use;

		for (h = 0; h < 2; h++)		/* h = right_handed, left_handed */

			for (v = 0; v < 4; v++)
			{
				if (in_use[h][v] == FALSE)
					continue;

				factor = tet->cusp[v]->scratch;

				for (f = 0; f < 4; f++)
				{
					if (f == v)
						continue;

					x[h][v][f] = complex_mult(factor, x[h][v][f]);
				}
			}
	}
}


static Boolean contains_meridian(
	Tetrahedron		*tet,
	Orientation		h,
	VertexIndex		v)
{
	/*
	 *	It suffices to check any two sides, because the meridian
	 *	can't possibly intersect only one side of a triangle.
	 *	(These are signed intersection numbers.)
	 */

	VertexIndex	w0,
				w1;

	w0 = ! v;
	w1 = remaining_face[v][w0];

	return (tet->curve[M][h][v][w0] != 0
		 || tet->curve[M][h][v][w1] != 0);
}


static void set_one_component(
	Tetrahedron		*tet,
	Orientation		h,
	VertexIndex		v,
	int				max_triangles)
{
	/*
	 *		FaceIndices are the natural way to index the corners
	 *					of a vertex cross section.
	 *
	 *	The VertexIndex v tells which vertex cross section we're at.
	 *	The vertex cross section is (a triangular component of) the
	 *	intersection of a cusp cross section with the ideal tetrahedron.
	 *	Each side of the triangle is the intersection of the cusp cross
	 *	section with some face of the ideal tetrahedron, so FaceIndices
	 *	may naturally be used to index them.  Each corner of the triangle
	 *	then inherits the FaceIndex of the opposite side.
	 */

	FaceIndex			f[3],
						ff,
						nbr_f[3];
	int					i;
	CuspTriangle		*queue,
						tri,
						nbr;
	int					queue_begin,
						queue_end;
	Permutation			gluing;
	CuspNbhdPosition	*our_data,
						*nbr_data;

	/*
	 *	Find the three FaceIndices for the corners of the triangle.
	 *	(f == v is excluded.)
	 */
	for (	i = 0, ff = 0;
			i < 3;
			i++, ff++)
	{
		if (ff == v)
			ff++;
		f[i] = ff;
	}

	/*
	 *	Let the corner f[0] be at the origin.
	 */
	tet->cusp_nbhd_position->x[h][v][f[0]] = Zero;

	/*
	 *	Let the corner f[1] be on the positive x-axis.
	 */
	tet->cusp_nbhd_position->x[h][v][f[1]].real = tet->cross_section->edge_length[v][f[2]];
	tet->cusp_nbhd_position->x[h][v][f[1]].imag = 0.0;

	/*
	 *	Use the TetShape to find the position of corner f[2].
	 */
	cn_find_third_corner(tet, h, v, f[0], f[1], f[2]);

	/*
	 *	Mark this triangle as being in_use.
	 */
	tet->cusp_nbhd_position->in_use[h][v] = TRUE;

	/*
	 *	We'll now "recursively" set the remaining triangles of this
	 *	cusp cross section.  We'll keep a queue of the triangles whose
	 *	positions have been set, but whose neighbors have not yet
	 *	been examined.
	 */

	queue = NEW_ARRAY(max_triangles, CuspTriangle);

	queue[0].tet	= tet;
	queue[0].h		= h;
	queue[0].v		= v;

	queue_begin = 0;
	queue_end   = 0;

	while (queue_begin <= queue_end)
	{
		/*
		 *	Pull a CuspTriangle off the queue.
		 */
		tri = queue[queue_begin++];

		/*
		 *	Consider each of its three neighbors.
		 */
		for (ff = 0; ff < 4; ff++)
		{
			if (ff == tri.v)
				continue;

			gluing = tri.tet->gluing[ff];

			nbr.tet	= tri.tet->neighbor[ff];
			nbr.h	= (parity[gluing] == orientation_preserving) ? tri.h : ! tri.h;
			nbr.v	= EVALUATE(gluing, tri.v);

			our_data = tri.tet->cusp_nbhd_position;
			nbr_data = nbr.tet->cusp_nbhd_position;

			/*
			 *	If the neighbor hasn't been set . . .
			 */

			if (nbr_data->in_use[nbr.h][nbr.v] == FALSE)
			{
				/*
				 *	. . . set it . . .
				 */

				f[0] = remaining_face[tri.v][ff];
				f[1] = remaining_face[ff][tri.v];
				f[2] = ff;

				for (i = 0; i < 3; i++)
					nbr_f[i] = EVALUATE(gluing, f[i]);

				for (i = 0; i < 2; i++)
					nbr_data->x[nbr.h][nbr.v][nbr_f[i]] = our_data->x[tri.h][tri.v][f[i]];

				cn_find_third_corner(nbr.tet, nbr.h, nbr.v, nbr_f[0], nbr_f[1], nbr_f[2]);

				nbr_data->in_use[nbr.h][nbr.v] = TRUE;

				/*
				 *	. . . and put it on the queue.
				 */
				queue[++queue_end] = nbr;
			}
		}
	}

	/*
	 *	An "unnecessary" error check.
	 */
	if (queue_begin > max_triangles)
		uFatalError("set_one_component", "cusp_neighborhoods");

	/*
	 *	Free the queue.
	 */
	my_free(queue);
}


void cn_find_third_corner(
	Tetrahedron		*tet,	/*	which tetrahedron					*/
	Orientation		h,		/*	right_handed or left_handed sheet	*/
	VertexIndex		v,		/*	which ideal vertex					*/
	FaceIndex		f0,		/*	known corner						*/
	FaceIndex		f1,		/*	known corner						*/
	FaceIndex		f2)		/*	corner to be computed				*/
{
	/*
	 *	We want to position the Tetrahedron so that the following
	 *	two conditions hold.
	 *
	 *	(1)	The corners f0, f1 and f2 are arranged counterclockwise
	 *		around the triangle's perimeter.
	 *
	 *							f2
	 *						   /  \
	 *						  /    \
	 *						f0------f1
	 *
	 *	(2)	The cusp cross section is seen with its preferred orientation.
	 *		(Cf. the discussion in the second paragraph of section (2) in
	 *		the documentation at the top of the file peripheral_curves.c.)
	 *		If this is the right handed sheet (h == right_handed),
	 *		the Tetrahedron should appear right handed.
	 *		(Cf. the definition of Orientation in kernel_typedefs.h.)
	 *		If this is the left handed sheet (h == left_handed), the
	 *		Tetrahedron should appear left handed (the left_handed sheet has
	 *		the opposite orientation of the Tetrahedron, so if this is the
	 *		left handed sheet and the Tetrahedron is viewed in a left handed
	 *		position, the sheet will be appear right handed -- got that?).
	 *
	 *	Of course these two conditions may not be compatible.
	 *	If we position the corners as in (1) and then find that (2) doesn't
	 *	hold (or vice versa), then we must swap the indices f0 and f1.
	 *
	 *	Note:  We could force the conditions to hold by making our
	 *	recursive calls carefully and consistently, but fixing the
	 *	ordering of f0 and f1 as needed is simpler and more robust.
	 */

	Orientation	tet_orientation;
	FaceIndex	temp;
	Complex		s,
				t,
				z;

	/*
	 *	Position the tetrahedron as in Condition (1) above.
	 *	If the tetrahedron appears in its right_handed Orientation,
	 *	then remaining_face[f0][f1] == f2, according to the definition of
	 *	remaining_face[][] in tables.c.  If the tetrahedron appears in
	 *	its left_handed Orientation, then remaining_face[f0][f1] == v.
	 */
	tet_orientation =	(remaining_face[f0][f1] == f2) ?
						right_handed :
						left_handed;

	/*
	 *	Does the vertex cross section appear with its preferred orientation,
	 *	as discussed in Condition (2) above?  If not, fix it.
	 */
	if (h != tet_orientation)
	{
		temp = f0;
		f0   = f1;
		f1   = temp;

		tet_orientation = ! tet_orientation;
	}

	/*
	 *	Let s be the vector from f0 to f1,
	 *		t be the vector from f0 to f2,
	 *		z be the complex edge angle v/u.
	 */

	s = complex_minus(	tet->cusp_nbhd_position->x[h][v][f1],
						tet->cusp_nbhd_position->x[h][v][f0]);

	/*
	 *	TetShapes are always stored relative to the right_handed Orientation.
	 *	If we're viewing the tetrahedron relative to the left_handed
	 *	Orientation, we need to use the conjugate-inverse instead.
	 */
	z = tet->shape[complete]->cwl[ultimate][edge3_between_vertices[v][f0]].rect;
	if (tet_orientation == left_handed)
		z = complex_conjugate(complex_div(One, z));

	t = complex_mult(z, s);

	tet->cusp_nbhd_position->x[h][v][f2]
		= complex_plus(tet->cusp_nbhd_position->x[h][v][f0], t);
}


void get_cusp_neighborhood_translations(
	CuspNeighborhoods	*cusp_neighborhoods,
	int					cusp_index,
	Complex				*meridian,
	Complex				*longitude)
{
	Cusp	*cusp;

	cusp = find_cusp(cusp_neighborhoods->its_triangulation, cusp_index);

	*meridian  = complex_real_mult(cusp->displacement_exp, cusp->translation[M]);
	*longitude = complex_real_mult(cusp->displacement_exp, cusp->translation[L]);
}


CuspNbhdSegmentList *get_cusp_neighborhood_triangulation(
	CuspNeighborhoods	*cusp_neighborhoods,
	int					cusp_index)
{
	Cusp				*cusp;
	CuspNbhdSegmentList	*theSegmentList;
	CuspNbhdSegment		*next_segment;
	Tetrahedron			*tet,
						*nbr_tet;
	Complex				(*x)[4][4];
	Boolean				(*in_use)[4];
	VertexIndex			v;
	Orientation			h;
	FaceIndex			f,
						nbr_f;

	/*
	 *	Make sure the EdgeClasses are numbered.
	 */
	number_the_edge_classes(cusp_neighborhoods->its_triangulation);
	
	/*
	 *	Find the requested Cusp.
	 */
	cusp = find_cusp(cusp_neighborhoods->its_triangulation, cusp_index);

	/*
	 *	Allocate the wrapper for the array.
	 */
	theSegmentList = NEW_STRUCT(CuspNbhdSegmentList);

	/*
	 *	We don't know ahead of time exactly how many CuspNbhdSegments
	 *	we'll need.  Torus cusps report each segment once, but Klein
	 *	bottle cusps report each segment twice, once for each sheet.
	 *
	 *	To get an upper bound on the number of segments,
	 *	assume all cusps are Klein bottle cusps.
	 *
	 *		  n tetrahedra
	 *		* 4 vertices/tetrahedron
	 *		* 2 triangles/vertex		(left_handed and right_handed)
	 *		* 3 sides/triangle
	 *		/ 2 sides/visible side		(no need to draw each edge twice)
	 *
	 *		= 12n visible sides
	 */
	theSegmentList->segment = NEW_ARRAY(12*cusp_neighborhoods->its_triangulation->num_tetrahedra, CuspNbhdSegment);

	/*
	 *	Keep a pointer to the first empty CuspNbhdSegment.
	 */
	next_segment = theSegmentList->segment;

	for (tet = cusp_neighborhoods->its_triangulation->tet_list_begin.next;
		 tet != &cusp_neighborhoods->its_triangulation->tet_list_end;
		 tet = tet->next)
	{
		x		= tet->cusp_nbhd_position->x;
		in_use	= tet->cusp_nbhd_position->in_use;

		for (v = 0; v < 4; v++)
		{
			/*
			 *	If this isn't the cusp the user wants, ignore it.
			 */
			if (tet->cusp[v] != cusp)
				continue;

			for (h = 0; h < 2; h++)		/* h = right_handed, left_handed */
			{
				if (in_use[h][v] == FALSE)
					continue;

				for (f = 0; f < 4; f++)
				{
					if (f == v)
						continue;

					nbr_tet	= tet->neighbor[f];
					nbr_f	= EVALUATE(tet->gluing[f], f);

					/*
					 *	We want to report each segment only once, so we
					 *	make the (arbitrary) convention that we report
					 *	a segment only from the Tetrahedron whose address
					 *	in memory is less.  In the case of a Tetrahedron
					 *	glued to itself, we report it from the lower
					 *	FaceIndex.
					 */
					if (tet > nbr_tet || (tet == nbr_tet && f > nbr_f))
						continue;

					/*
					 *	Don't report edges which are part of the arbitrary
					 *	subdivision of the canonical cell decomposition
					 *	into tetrahdra.  We rely on the fact that
					 *	proto_canonize() has computed the tilts and left
					 *	them in place.  The sum of the tilts will never be
					 *	positive for a subdivision of the canonical cell
					 *	decomposition.  If it's close to zero, ignore that
					 *	face.
					 */
					if (tet->tilt[f] + nbr_tet->tilt[nbr_f] > -CONCAVITY_EPSILON)
						continue;

					/*
					 *	This edge has passed all its tests, so record it.
					 */
					next_segment->endpoint[0]	= complex_real_mult(cusp->displacement_exp, x[h][v][remaining_face[f][v]]);
					next_segment->endpoint[1]	= complex_real_mult(cusp->displacement_exp, x[h][v][remaining_face[v][f]]);
					next_segment->start_index	= tet->edge_class[edge_between_vertices[v][remaining_face[f][v]]]->index;
					next_segment->middle_index	= tet->edge_class[edge_between_faces[v][f]]->index;
					next_segment->end_index		= tet->edge_class[edge_between_vertices[v][remaining_face[v][f]]]->index;

					/*
					 *	Move on.
					 */
					next_segment++;
				}
			}
		}
	}

	/*
	 *	How many segments did we find?
	 *
	 *	(ANSI C will subtract the pointers correctly, automatically
	 *	dividing by sizeof(CuspNbhdSegment).)
	 */
	theSegmentList->num_segments = next_segment - theSegmentList->segment;

	/*
	 *	Did we find more segments than we had allocated space for?
	 *	This should be impossible, but it doesn't hurt to check.
	 */
	if (theSegmentList->num_segments > 12*cusp_neighborhoods->its_triangulation->num_tetrahedra)
		uFatalError("get_cusp_neighborhood_triangulation", "cusp_neighborhoods");

	return theSegmentList;
}


void free_cusp_neighborhood_segment_list(
	CuspNbhdSegmentList	*segment_list)
{
	if (segment_list != NULL)
	{
		if (segment_list->segment != NULL)
			my_free(segment_list->segment);

		my_free(segment_list);
	}
}


CuspNbhdHoroballList *get_cusp_neighborhood_horoballs(
	CuspNeighborhoods	*cusp_neighborhoods,
	int					cusp_index,
	Boolean				full_list,
	double				cutoff_height)
{
	Cusp					*cusp;
	CuspNbhdHoroballList	*theHoroballList;

	/*
	 *	Find the requested Cusp.
	 */
	cusp = find_cusp(cusp_neighborhoods->its_triangulation, cusp_index);

	/*
	 *	Provide a small margin to allow for roundoff error.
	 */
	cutoff_height -= CUTOFF_HEIGHT_EPSILON;

	/*
	 *	Use the appropriate algorithm for finding
	 *	the quick or full list of horoballs.
	 */
	if (full_list == FALSE)
		theHoroballList = get_quick_horoball_list(cusp_neighborhoods, cusp);
	else
		theHoroballList = get_full_horoball_list(cusp_neighborhoods, cusp, cutoff_height);

	/*
	 *	Sort the horoballs in order of increasing size.
	 */
	qsort(	theHoroballList->horoball,
			theHoroballList->num_horoballs,
			sizeof(CuspNbhdHoroball),
			&compare_horoballs);

	/*
	 *	There's a chance that get_full_horoball_list() may produce duplicate
	 *	horoballs (when a 2-cell passes through a horoball's north pole) or
	 *	that get_quick_horoball_list() may produce duplicatate horoballs
	 *	(when face horoballs coincide).  Remove any such duplications.
	 */
	cull_duplicate_horoballs(cusp, theHoroballList);

	return theHoroballList;
}


static CuspNbhdHoroballList *get_quick_horoball_list(
	CuspNeighborhoods	*cusp_neighborhoods,
	Cusp				*cusp)
{
	CuspNbhdHoroballList	*theHoroballList;
	CuspNbhdHoroball		*next_horoball;

	/*
	 *	Allocate the wrapper for the array.
	 */
	theHoroballList = NEW_STRUCT(CuspNbhdHoroballList);

	/*
	 *	We don't know ahead of time exactly how many CuspNbhdHoroballs
	 *	we'll need.  Torus cusps report each horoball once, but Klein
	 *	bottle cusps report each horoball twice, once for each sheet.
	 *	To get an upper bound on the number of horoballs, assume all
	 *	cusps are Klein bottle cusps.  We report two types of horoballs.
	 *
	 *	Edge Horoballs
	 *
	 *		Edge horoballs are horoballs which the given cusp sees along an
	 *		edge of the canonical triangulation (i.e. along a vertical edge
	 *		in the usual upper half space picture).  The total number of
	 *		edges in the canonical triangulation is the same as the number
	 *		of tetrahedra (by an Euler characteristic argument), so the
	 *		following gives an upper bound on the number of edge horoballs.
	 *
	 *			  n edges
	 *			* 2 endpoints/edge
	 *			* 2 sheets/endpoint			(left_handed and right_handed)
	 *
	 *			= 4n edge horoballs
	 *
	 *	Face Horoballs
	 *
	 *		Face horoballs are horoballs which the given cusp sees across
	 *		a face of the canonical triangulation.  The number of triangles
	 *		in the cusp triangulation provides an upper bound on the number
	 *		of face horoballs.
	 *
	 *			  n tetrahedra
	 *			* 4 vertices/tetrahedron
	 *			* 2 triangles/vertex		(left_handed and right_handed)
	 *
	 *			= 8n visible sides
	 *
	 *	Therefore the total number of horoballs we will report will be
	 *	at most 4n + 8n = 12n.  (The maximum will be realized in the case
	 *	of a manifold like the Gieseking with one nonorientable cusp.)
	 */
	theHoroballList->horoball = NEW_ARRAY(12*cusp_neighborhoods->its_triangulation->num_tetrahedra, CuspNbhdHoroball);

	/*
	 *	Keep a pointer to the first empty CuspNbhdHoroball.
	 */
	next_horoball = theHoroballList->horoball;

	/*
	 *	Find the edge horoballs.
	 */
	get_quick_edge_horoballs(	cusp_neighborhoods->its_triangulation,
								cusp,
								&next_horoball);

	/*
	 *	Find the face horoballs.
	 */
	get_quick_face_horoballs(	cusp_neighborhoods->its_triangulation,
								cusp,
								&next_horoball);

	/*
	 *	How many horoballs did we find?
	 *
	 *	(ANSI C will subtract the pointers correctly, automatically
	 *	dividing by sizeof(CuspNbhdHoroball).)
	 */
	theHoroballList->num_horoballs = next_horoball - theHoroballList->horoball;

	/*
	 *	Did we find more horoballs than we had allocated space for?
	 *	This should be impossible, but it doesn't hurt to check.
	 */
	if (theHoroballList->num_horoballs > 12*cusp_neighborhoods->its_triangulation->num_tetrahedra)
		uFatalError("get_cusp_neighborhood_triangulation", "cusp_neighborhoods");

	return theHoroballList;
}


static void get_quick_edge_horoballs(
	Triangulation		*manifold,
	Cusp				*cusp,
	CuspNbhdHoroball	**next_horoball)
{
	EdgeClass				*edge;
	double					radius;
	Tetrahedron				*tet;
	Complex					(*x)[4][4];
	Boolean					(*in_use)[4];
	VertexIndex				v[2];
	int						i;
	int						other_index;
	Orientation				h;

	for (edge = manifold->edge_list_begin.next;
		 edge != &manifold->edge_list_end;
		 edge = edge->next)
	{
		/*
		 *	Consider a horosphere of Euclidean height h in the upper half
		 *	space model.  Integrate along a vertical edge connecting the
		 *	horosphere to the horosphere at infinity to compute the distance
		 *	between the two as
		 *
		 *		d = integral of dz/z from z=h to z=1
		 *		  = log 1 - log h
		 *		  = - log h
		 *	or
		 *		h = exp(-d)
		 *
		 *	set_cusp_neighborhood_displacement() calls compute_cusp_stoppers(),
		 *	which in turn calls compute_intercusp_distances(), so we may use
		 *	the edge->intercusp_distance fields for d.
		 */
		radius = 0.5 * exp( - edge->intercusp_distance);

		/*
		 *	Dereference tet, x and in_use for clarity.
		 */
		tet		= edge->incident_tet;
		x		= tet->cusp_nbhd_position->x;
		in_use	= tet->cusp_nbhd_position->in_use;

		/*
		 *	Consider each of the edge's endpoints.
		 */
		v[0] =   one_vertex_at_edge[edge->incident_edge_index];
		v[1] = other_vertex_at_edge[edge->incident_edge_index];

		for (i = 0; i < 2; i++)
		{
			/*
			 *	Are we at the right cusp?
			 */
			if (tet->cusp[v[i]] != cusp)
				continue;

			/*
			 *	What is the index of the other cusp?
			 */
			other_index = tet->cusp[v[!i]]->index;

			for (h = 0; h < 2; h++)		/* h = right_handed, left_handed */
			{
				if (in_use[h][v[i]] == FALSE)
					continue;

				(*next_horoball)->center		= complex_real_mult(cusp->displacement_exp, x[h][v[i]][v[!i]]);
				(*next_horoball)->radius		= radius;
				(*next_horoball)->cusp_index	= other_index;

				(*next_horoball)++;
			}
		}
	}
}


static void get_quick_face_horoballs(
	Triangulation		*manifold,
	Cusp				*cusp,
	CuspNbhdHoroball	**next_horoball)
{
	/*
	 *	There are several ways we might find the location and size of
	 *	the face horoballs.
	 *
	 *	(1)	Use the TetShape to locate the center, and then use the
	 *		lemma below to find the size.
	 *
	 *		This method is fairly efficient computationally, and lets
	 *		us use the existing function compute_fourth_corner() from
	 *		choose_generators.c.
	 *
	 *	(2)	Ignore the TetShape, and rely entirely on the intercusp_distances
	 *		to find both the location and size.
	 *
	 *		This method is conceptually straightforward.  Using the lemma
	 *		below, one obtains three equations involving the location (x,y)
	 *		and the height h of the face horoball.  The equations are
	 *		quadratic in x and y, but they are monic, so subtracting
	 *		equations gives linear dependencies between x, y and h.
	 *		One can solve for x and y in terms of h, and obtain a quadratic
	 *		equation to solve for h.  It's easy to prove that the lesser
	 *		value of h will be the desired solution.  Confession:  I haven't
	 *		actually worked out the equation for h.  It seems like it would
	 *		be messy.
	 *
	 *	(3)	Work in the Minkowski space model, and use linear algebra
	 *		to compute the horoball as a vector on the light cone.
	 *
	 *		For background ideas, see
	 *
	 *			Weeks, Convex hulls and isometries of cusped hyperbolic
	 *				3-manifolds, Topology Appl. 52 (1993) 127-149
	 *		and
	 *			Sakuma and Weeks, The generalized tilt formula,
	 *				Geometriae Dedicata 55 (1995) 115-123.
	 *
	 *		The method might prove to be more-or-less equivalent to (2).
	 *		By Lemma 4.2(c) of Weeks, the equation <u,v> = constant gives
	 *		all the horospheres v a fixed distance from a horosphere u.
	 *		So to find a horosphere a given distance from three given
	 *		horospheres, one ends up intersecting three hyperplanes in
	 *		E^(3,1) to get a line, and then intersecting the line with the
	 *		upper light cone.  As in approach (2), the calculations are
	 *		initially linear, but become quadratic at the end.  Again, I
	 *		haven't worked through the details.
	 *
	 *	(4)	Find a matrix in PSL(2,C) which takes an ideal tetrahedron
	 *		in standard position to the desired ideal tetrahedron.
	 *
	 *		This is the approach used in snappea 1.3.  The formulas are
	 *		simpler than you might expect.  The main disadvantage is that
	 *		the 1.3 treatment applies only to orientable manifolds.  It
	 *		might be possible to fix it up using MoebiusTransformations.
	 *
	 *	We use method (1), because it seems simplest.
	 *
	 *	Lemma.  Consider two horospheres of Euclidean height h1 and h2 (resp.)
	 *	in the upper half space model of hyperbolic 3-space.  If the
	 *	Euclidean distances between their centers (on the sphere at infinity)
	 *	is c, then the hyperbolic distance d between the horospheres is
	 *
	 *						d = log( c^2 / h1*h2 )
	 *
	 *	Proof.  Draw yourself a picture of the horospheres (or horocycles --
	 *	a 2D cross sectional picture will serve just as well).  Label the
	 *	distances h1, h2, c and d.  Now sketch a Euclidean hemisphere of
	 *	radius c centered at the base of the first horosphere;  this is
	 *	a plane in hyperbolic space.  Reflect the whole picture in this
	 *	plane (in Euclidean terms, the reflection is an inversion in the
	 *	hemisphere).  One of the horospheres gets taken to a horizontal
	 *	Euclidean plane at height c^2/h1.  The other horosphere remains
	 *	(setwise) invariant.  It is now obvious that the shortest distance
	 *	from one horosphere to the other is along the vertical arc connecting
	 *	them.  The distance is the integral of dz/z from h=h2 to h=c^2/h1,
	 *	which works out to be log( c^2 / h1*h2 ).  QED
	 *
	 *	Comment.  We don't need it for the present code, but I can't
	 *	resist pointing out that the above lemma has a nice intrinsic
	 *	formulation, which doesn't rely on the upper half space model.
	 *	Let H be the horosphere which appears as a horizontal plane z == 1
	 *	in the upper half space model, and draw in the vertical geodesics
	 *	connecting it to each of the two horospheres mentioned in the lemma.
	 *	Let a = -log(h1) and b = -log(h2) be the respective distances from
	 *	H to each of the old horospheres.  Interpret c as the distance along
	 *	H from one of those segments to the other.  Now redraw the picture
	 *	in, say, the Poincare ball model.  It'll be more symmetric now,
	 *	since there's no longer a preferred "horosphere at infinity".
	 *	You'll have an ideal triangle, with a horosphere at each vertex.
	 *	The quantities a, b and d are the length of the shortest geodesics
	 *	between horospheres, while c is the distance along a horosphere
	 *	between two such geodesics.  The above lemma becomes
	 *
	 *	Lemma.  2 log c = d - a - b.
	 *
	 *	With better notation, namely a, b and c are the distances between
	 *	cusp cross sections, and A, B and C are the distances along the
	 *	cusps, the lemma becomes
	 *
	 *					2 log A = a - b - c
	 *					2 log B = b - c - a
	 *					2 log C = c - a - b
	 *
	 *	Add two of those equations (say the first two) to get
	 *
	 *					log AB = -c
	 *
	 *	As a special case, when c == 0, AB = 1.
	 */

	Tetrahedron		*tet;
	Complex			(*x)[4][4];
	Boolean			(*in_use)[4];
	VertexIndex		u,
					v,
					w,
					missing_corner;
	Permutation		gluing;
	Complex			corner[4];
	Orientation		h;
	double			height_u,
					exp_d,
					c_squared;

	for (tet = manifold->tet_list_begin.next;
		 tet != &manifold->tet_list_end;
		 tet = tet->next)
	{
		x		= tet->cusp_nbhd_position->x;
		in_use	= tet->cusp_nbhd_position->in_use;

		for (v = 0; v < 4; v++)
		{
			/*
			 *	Are we at the right cusp?
			 */
			if (tet->cusp[v] != cusp)
				continue;

			gluing = tet->gluing[v];

			for (h = 0; h < 2; h++)		/* h = right_handed, left_handed */
			{
				if (in_use[h][v] == FALSE)
					continue;

				/*
				 *	Prepare for a call to compute_fourth_corner().
				 */
				for (w = 0; w < 4; w++)
					if (w != v)
						corner[EVALUATE(gluing, w)] = complex_real_mult(cusp->displacement_exp, x[h][v][w]);
				missing_corner = EVALUATE(gluing, v);

				/*
				 *	Call compute_fourth_corner() to compute
				 *	corner[missing_corner].
				 */
				compute_fourth_corner(
					corner,
					missing_corner,
					(parity[gluing] == orientation_preserving) ? h : !h,
					tet->neighbor[v]->shape[complete]->cwl[ultimate]);

				/*
				 *	The missing_corner gives us the horoball's center.
				 */
				(*next_horoball)->center = corner[missing_corner];

				/*
				 *	Prepare to use the above lemma to compute the radius.
				 */

				/*
				 *	Let u be any vertex of the original Tetrahedron except v.
				 */
				u = !v;

				/*
				 *	According to the explanation in get_quick_edge_horoballs(),
				 *	the height of the edge horoball at vertex u is
				 *	exp( - intercusp_distance).
				 */
				height_u = exp( - tet->edge_class[edge_between_vertices[u][v]]->intercusp_distance);

				/*
				 *	A different intercusp_distance gives the distance d
				 *	in the lemma.
				 */
				exp_d = exp(tet->neighbor[v]->edge_class[edge_between_vertices[EVALUATE(gluing,u)][missing_corner]]->intercusp_distance);

				/*
				 *	Compute the squared distance between the edge horoball
				 *	at vertex u and the face horoball we are interested in.
				 */
				c_squared = complex_modulus_squared(complex_minus(
								(*next_horoball)->center,
								complex_real_mult(cusp->displacement_exp, x[h][v][u])));

				/*
				 *	Apply the lemma.
				 *
				 *			exp(d) = c^2 / h1*h2
				 *	=>
				 *			h1 = c^2 / exp(d)*h2
				 */
				(*next_horoball)->radius = 0.5 * c_squared / (exp_d * height_u);

				/*
				 *	Note the cusp index of the new horoball.
				 */
				(*next_horoball)->cusp_index = tet->neighbor[v]->cusp[missing_corner]->index;

				/*
				 *	Move on.
				 */
				(*next_horoball)++;
			}
		}
	}
}


static CuspNbhdHoroballList *get_full_horoball_list(
	CuspNeighborhoods	*cusp_neighborhoods,
	Cusp				*cusp,
	double				cutoff_height)
{
	/*
	 *	We want to find all horoballs of Euclidean height at least
	 *	cutoff_height, up to the Z + Z action of the group of covering
	 *	transformations of the cusp.  (We work with the double cover
	 *	of Klein bottle cusps, so in effect all cusps are torus cusps.)
	 *
	 *	Let M' be H^3 / (Z + Z), where the Z + Z is the group of covering
	 *	transformations of the cusp.  Visualize M' as a chimney in the
	 *	upper half space model;  when its sides are glued together its
	 *	parallelogram cross section becomes the torus cross section
	 *	of the cusp.
	 *
	 *	Our plan is to lift ideal tetrahedra from the original manifold M
	 *	to the chimney manifold M'.  We begin with the tetrahedra incident
	 *	to the chimney's cusp (i.e. its top end), and then gradually tile
	 *	our way downward.  Whenever a new tetrahedron introduces a new
	 *	ideal vertex, we consider the horoball centered at that vertex.
	 *	If its Euclidean height is greater than cutoff_height, we add it
	 *	to a list.  Our challenge is to find an algorithm which does as
	 *	little tiling as possible, yet still finds all horoballs higher
	 *	than the cutoff_height.
	 *
	 *	The Naive Algorithm
	 *
	 *	The naive algorithm is to consider the neighbors of each tetrahedron
	 *	already in the tiling.  If adding a neighbor would introduce no
	 *	new vertices, add it.  If adding a neighbor would introduce a new
	 *	vertex, add it iff the horoball at the new vertex is higher than
	 *	the cutoff_height.
	 *
	 *	Unfortunately the naive algorithm fails.  The Whitehead link
	 *	provides a counterexample.  Visualize the Whitehead link as an
	 *	octahedron with faces identified.  The ideal vertices at the
	 *	"north and south poles" form one cusp ("the red cusp") while the
	 *	"equatorial ideal vertices" form the other cusp ("the blue cusp").
	 *	Push the blue cusp cross section forward until it meets itself,
	 *	but retract the red cusp cross section until it's tiny.  The
	 *	canonical cell decomposition is a subdivision of the octahedron
	 *	into two square pyramids (a "northern" and a "southern" one).
	 *	SnapPea will, of course, arbitrarily subdivide each pyramid into
	 *	two tetrahedra.  Now consider what happens when we apply the naive
	 *	algorithm to this example, with the red cusp at infinity.  Each
	 *	of the initial tetrahedra has a red vertex at infinity, and three
	 *	blue vertices on the horizontal plane.  Its three neighbors to the
	 *	sides are other tetrahedra of the same type (red at infinity and
	 *	blue on the horizontal plane).  Its underneath neighbor shares the
	 *	same three blue vetices, and introduce a new red vertex on the
	 *	horizontal plane.  But because the red horoball is tiny, the naive
	 *	algorithm will say not to add this tetrahedron.  So no new tetrahedra
	 *	will be added, and the algorithm will terminate.  The naive
	 *	algorithm has therefore failed, because it's missed blue horoballs
	 *	of varying sizes.  (Assuming we've chosen the size of the tiny
	 *	red cusp cross section to be small enough that the largest red
	 *	horoballs are smaller than the medium sized blue one.)
	 *
	 *	The naive algorithm's failure was the bad news.  The good news
	 *	is that if we take into account the varying sizes of the horoballs,
	 *	the algorithm can be patched up and made to work.  First a few
	 *	background lemmas.
	 *
	 *	Lemma 1.  For each horoball H, there is (a lift of) an edge
	 *	of the canonical cell decompostion which connects H to some
	 *	larger horoball H'.
	 *
	 *	Proof.  The horoball H is surrounded by (lifts of) 2-cells
	 *	of the Ford complex.  Consider a 2-cell F which lies above some
	 *	point of H (in the upper half space model).  F is dual to an edge
	 *	of the canonical cell decomposition which connects H to some other
	 *	horoball H'.  F lies above H, so by Lemma 2 below, H' is larger
	 *	than H.  QED
	 *
	 *	Lemma 2.  Consider two horoballs H and H'.  If H' has a larger
	 *	Euclidean height than H when viewed in some fixed way in the upper
	 *	half space model of hyperbolic 3-space, then the plane P lying
	 *	midway between them appears as a Euclidean hemisphere enclosing
	 *	H and excluding H'.  In particular, every point of H is directly
	 *	below some point of P, while no point of H' is.
	 *
	 *	Proof.  Draw the horoballs and construct P.  QED
	 *
	 *	Definition.  Two horoballs are "edge-connected" if (a lift of) an
	 *	edge of the canonical cell decomposition connects one to the other.
	 *
	 *	Lemma 3.  Let H' be a horoball which is edge-connected to a smaller
	 *	horoball H.  Then the Euclidean distance c between their centers
	 *	(on the boundary plane of the upper half space model) is
	 *
	 *		             c = sqrt( a * b * exp(d) )
	 *
	 *	where
	 *			a = Euclidean height of H'
	 *			b = Euclidean height of H
	 *			d = hyperbolic distance from H' to H.
	 *
	 *	Proof.  The lemma in get_quick_face_horoballs() says that
	 *	d = log(c^2 / a*b).  Solve for c = sqrt( a * b * exp(d) ).  QED
	 *
	 *	Lemma 4.  Let H' be a horoball which is edge-connected to a smaller
	 *	horoball H.  If the Euclidean height of H is at least cutoff_height,
	 *	then the Euclidean distance c between the centers of H and H' is
	 *	at least
	 *				c >= sqrt( a * cutoff_height * exp(min_d) )
	 *
	 *	where a is the height of H' and min_d is the least distance from
	 *	the horoball H' to any other horoball.
	 *
	 *	Proof.  Follows immediately from Lemma 3.
	 *
	 *	Comment.  The exp(min_d) factor makes H' act like a bigger horoball
	 *	than it really is.  If you were to increase the cusp displacement
	 *	by min_d, the height of H' would increase to a*exp(min_d).
	 *
	 *	Definition.  (A lift of) an edge of the canonical triangulation
	 *	is "potentially useful" if one endpoint lies at the center of
	 *	a horoball H' of height at least cutoff_height, and the distance
	 *	between its two endpoints is at least c (as defined in Lemma 4).
	 *	(As a special case, vertical edges (in the upper half space) are
	 *	always "potentially useful".  The informal justification for this
	 *	is that the horosphere at infinity is infinity large and its center
	 *	is infinitely far away.)
	 *
	 *	Definition.  (A lift of) an ideal tetrahedron is "potentially useful"
	 *	iff it contains at least one potentially useful edge.
	 *
	 *	The Corrected Algorithm
	 *
	 *	As before, begin with the tetrahedra incident to the chimney's cusp
	 *	and gradually tile downward.  For each tetrahedron already in the
	 *	tiling, consider its four neighbors and add those which are
	 *	potentially useful.
	 *
	 *	Lemma 5.  Let H' be a horoball higher than the cutoff_height.
	 *	If the Corrected Algorithm adds one potentially useful tetrahedron
	 *	incident to H', then it adds them all.
	 *
	 *	Proof.  Look at the surface of the horoball H', which intrinsically
	 *	is a Euclidean plane E.  An edge of the triangulation intersects
	 *	the plane E in point P.  The edge is potentially useful iff P lies
	 *	within a disk D (of intrinsic radius a/c in the Euclidean geometry
	 *	of the horosphere E, but we don't need that fact).  A tetrahedron
	 *	incident to H' is potentially useful iff it intersects the disk D.
	 *	The set of all such tetrahedra forms a connected set (this follows
	 *	from the path connectedness of the disk D).  Therefore if the
	 *	algorithm adds one such tetrahedron, it will add them all.  QED
	 *
	 *	Proposition 6.  The Corrected Algorithm finds all horoballs higher
	 *	than the cutoff_height.
	 *
	 *	Proof.  Let H be a horoball of maximal height (greater than the
	 *	cutoff_height) which the algorithm missed.  By Lemma 1, there
	 *	is a higher horoball H', and an edge connecting H' to H.  The
	 *	edge is potentially useful, by Lemma 4 and the definition of a
	 *	potentially useful edge.  By the assumed maximal height of H
	 *	(among all horoballs which the Corrected Algorithm should have
	 *	found but didn't), we know that the algorithm did find H', i.e.
	 *	it added some potentially useful tetrahedron incident to the center
	 *	of H'.  By Lemma 5, it must have added all potentially useful
	 *	tetrahedra incident to H', and therefore must have found H.  QED
	 *
	 *	Corollary 7.  We can refine the Corrected Algorithm as follows.
	 *	For each tetrahedron T already added, we consider only those
	 *	neighbors T' incident to a face of T which contains at least
	 *	one potentially useful edge.
	 *
	 *	Proof.  The proof of Proposition 6 still works.  QED
	 */

	TilingHoroball			*horoball_linked_list;
	TilingQueue				tiling_queue;
	TilingTet				*tiling_tree_root,
							*tiling_tet,
							*tiling_nbr;
	Complex					meridian,
							longitude;
	double					parallelogram_to_square[2][2];
	FaceIndex				f;
	CuspNbhdHoroballList	*theHoroballList;

	/*
	 *	We don't know a priori how many horoballs we'll find.
	 *	So we temporarily keep them on a NULL-terminated linked list,
	 *	and transfer them to an array when we're done.
	 *
	 *	To avoid recording multiple copies of each horoball, we make the
	 *	convention that each horoball is recorded only by the TilingTet
	 *	which contains its north pole.  If the north pole lies on the
	 *	boundary of two TilingTets, they both record it.
	 *	get_cusp_neighborhood_horoballs() will remove the duplications.
	 *	If three or more TilingTets meet at the north pole, then a vertical
	 *	edge connects the horoball to infinity in the upper half space model;
	 *	read_initial_tetrahedra() records such horoballs without duplication.
	 *	(Other strategies are possible, like preferring the Tetrahedron
	 *	with the lower address in memory, but the present approach is
	 *	least vulnerable to roundoff error.)
	 */
	horoball_linked_list = NULL;

	/*
	 *	We'll need to store the potentially useful tetrahedra in two ways.
	 *
	 *	Queue
	 *		The Tetrahedra which have been added, but whose neighbors have
	 *		not been examined, go on a queue, so we know which one
	 *		to process next.  When we remove a tetrahedron from the queue
	 *		we examine its neighbors.  We use a queue rather than a stack
	 *		so that we tile generally downwards (rather than snaking around)
	 *		in hopes of obtaining the best numerical precision.
	 *
	 *	Tree
	 *		All tetrahedra which have been added are kept on a tree, so that
	 *		we can tell whether new tetrahedra are duplications of old ones
	 *		or not.  (Note:  Checking whether a tetrahedron is "the same as"
	 *		an old one means checking whether they are equivalent under
	 *		the Z + Z action of the covering transformations.
	 *
	 *	The TilingTet structure supports both the queue and the tree,
	 *	simultaneously and independently.
	 */

	/*
	 *	Initialize the data structures.
	 */
	tiling_queue.begin	= NULL;
	tiling_queue.end	= NULL;
	tiling_tree_root	= NULL;

	/*
	 *	For each cusp, compute the quantity exp(min_d) needed in Lemma 4.
	 */
	compute_exp_min_d(cusp_neighborhoods->its_triangulation);

	/*
	 *	Compute the current meridional and longitudinal translations.
	 */
	meridian  = complex_real_mult(cusp->displacement_exp, cusp->translation[M]);
	longitude = complex_real_mult(cusp->displacement_exp, cusp->translation[L]);

	/*
	 *	prepare_sort_key() will need a linear transformation which
	 *	maps a fundamental parallelogram for the cusp (or the double
	 *	cover, in the case of a Klein bottle cusp) to the unit square.
	 */
	compute_parallelogram_to_square(meridian, longitude, parallelogram_to_square);

	/*
	 *	Read in the tetrahedra incident to the vertex at infinity,
	 *	and record the incident horoballs.
	 *
	 *	Note:  We check the horoballs when we put TilingTets onto the
	 *	tiling_queue (rather than when we pull it off) so we can handle
	 *	the special case of the initial tetrahedra more efficiently.
	 */
	read_initial_tetrahedra(	cusp_neighborhoods->its_triangulation,
								cusp,
								&tiling_queue,
								&tiling_tree_root,
								&horoball_linked_list,
								cutoff_height);

	/*
	 *	Carry out the Corrected Algorithm, refined as in Lemma 7.
	 */
	while (tiling_queue.begin != NULL)
	{
		tiling_tet = get_tiling_tet_from_queue(&tiling_queue);

		for (f = 0; f < 4; f++)

			if (tiling_tet->neighbor_found[f] == FALSE
			 && face_contains_useful_edge(tiling_tet, f, cutoff_height) == TRUE)
			{
				tiling_nbr = make_neighbor_tiling_tet(tiling_tet, f);

				prepare_sort_key(tiling_nbr, parallelogram_to_square);

				if (tiling_tet_on_tree(tiling_nbr, tiling_tree_root, meridian, longitude) == FALSE)
				{
					add_horoball_if_necessary(tiling_nbr, &horoball_linked_list, cutoff_height);
					add_tiling_tet_to_tree(tiling_nbr, &tiling_tree_root);
					add_tiling_tet_to_queue(tiling_nbr, &tiling_queue);
				}
				else
					my_free(tiling_nbr);
			}
	}

	/*
	 *	Free the TilingTets.
	 */
	free_tiling_tet_tree(tiling_tree_root);

	/*
	 *	Transfer the horoballs from the linked list
	 *	to a CuspNbhdHoroballList, and free the linked list.
	 */
	theHoroballList = transfer_horoballs(&horoball_linked_list);

	return theHoroballList;
}


static void compute_exp_min_d(
	Triangulation	*manifold)
{
	/*
	 *	Compute the quantity exp(min_d) needed
	 *	in Lemma 4 of get_full_horoball_list().
	 */

	Cusp		*cusp;
	EdgeClass	*edge;
	double		exp_d;
	VertexIndex	v[2];
	int			i;

	/*
	 *	Initialize all exp_min_d's to infinity.
	 */

	for (cusp = manifold->cusp_list_begin.next;
		 cusp != &manifold->cusp_list_end;
		 cusp = cusp->next)

		cusp->exp_min_d = DBL_MAX;

	/*
	 *	The closest horoball to a given cusp will lie along an edge
	 *	of the canonical cell decomposition, so look at all edges
	 *	to find the true exp_min_d's.
	 */

	for (edge = manifold->edge_list_begin.next;
		 edge != &manifold->edge_list_end;
		 edge = edge->next)
	{
		/*
		 *	set_cusp_neighborhood_displacement() calls compute_cusp_stoppers(),
		 *	which in turn calls compute_intercusp_distances(), so we may use
		 *	the edge->intercusp_distance fields for exp_d.
		 */
		exp_d = exp(edge->intercusp_distance);

		v[0] =   one_vertex_at_edge[edge->incident_edge_index];
		v[1] = other_vertex_at_edge[edge->incident_edge_index];

		for (i = 0; i < 2; i++)
		{
			cusp = edge->incident_tet->cusp[v[i]];

			if (cusp->exp_min_d > exp_d)
				cusp->exp_min_d = exp_d;
		}
	}
}


static void compute_parallelogram_to_square(
	Complex	meridian,
	Complex	longitude,
	double	parallelogram_to_square[2][2])
{
	/*
	 *	prepare_sort_key() needs a linear transformation which takes
	 *	a meridian to (1,0) and a longitude to (0,1), so TilingTets which
	 *	are equivalent under the Z + Z action of the group of covering
	 *	translations of the cusp be assigned corner coordinates which
	 *	differ by integers.  The required linear transformation is
	 *	the inverse of
	 *
	 *				( meridian.real  longitude.real )
	 *				( meridian.imag  longitude.imag )
	 */

	double	det;

	det = meridian.real * longitude.imag  -  meridian.imag * longitude.real;

	parallelogram_to_square[0][0] =   longitude.imag / det;
	parallelogram_to_square[0][1] = - longitude.real / det;
	parallelogram_to_square[1][0] = - meridian.imag  / det;
	parallelogram_to_square[1][1] =   meridian.real  / det;
}


static void read_initial_tetrahedra(
	Triangulation	*manifold,
	Cusp			*cusp,
	TilingQueue		*tiling_queue,
	TilingTet		**tiling_tree_root,
	TilingHoroball	**horoball_linked_list,
	double			cutoff_height)
{
	Tetrahedron		*tet;
	Complex			(*x)[4][4];
	Boolean			(*in_use)[4];
	VertexIndex		v,
					w;
	Orientation		h;
	TilingTet		*tiling_tet;
	EdgeIndex		edge_index;
	EdgeClass		*edge;

	for (tet = manifold->tet_list_begin.next;
		 tet != &manifold->tet_list_end;
		 tet = tet->next)
	{
		x		= tet->cusp_nbhd_position->x;
		in_use	= tet->cusp_nbhd_position->in_use;

		for (v = 0; v < 4; v++)
		{
			if (tet->cusp[v] != cusp)
				continue;

			for (h = 0; h < 2; h++)		/* h = right_handed, left_handed */
			{
				if (in_use[h][v] == FALSE)
					continue;

				tiling_tet = NEW_STRUCT(TilingTet);

				tiling_tet->underlying_tet	= tet;
				tiling_tet->orientation		= h;

				for (w = 0; w < 4; w++)
					if (w != v)
					{
						/*
						 *	Please see get_quick_edge_horoballs() for
						 *	an explanation of the horoball height.
						 */
						edge_index = edge_between_vertices[v][w];
						edge = tet->edge_class[edge_index];

						tiling_tet->corner[w]			= complex_real_mult(cusp->displacement_exp, x[h][v][w]);
						tiling_tet->horoball_height[w]	= exp( - edge->intercusp_distance);
						tiling_tet->neighbor_found[w]	= TRUE;

						/*
						 *	To avoid duplications, record the TilingHoroball
						 *	iff this is the preferred tet and edge_index
						 *	to see it from.
						 */

						if (edge->incident_tet == tet
						 && edge->incident_edge_index == edge_index
						 && tiling_tet->horoball_height[w] >= cutoff_height)

							add_tiling_horoball_to_list(tiling_tet, w, horoball_linked_list);
					}
					else
					{
						tiling_tet->corner[w]			= Infinity;
						tiling_tet->horoball_height[w]	= DBL_MAX;
						tiling_tet->neighbor_found[w]	= FALSE;
					}

				/*
				 *	Give each tiling_tet a random value of the sort key,
				 *	to keep the tree broad.
				 */
				tiling_tet->key = 0.5 * ((double) rand() / (double) RAND_MAX);

				add_tiling_tet_to_queue(tiling_tet, tiling_queue);
				add_tiling_tet_to_tree(tiling_tet, tiling_tree_root);
			}
		}
	}
}


static TilingTet *get_tiling_tet_from_queue(
	TilingQueue	*tiling_queue)
{
	TilingTet	*tiling_tet;

	tiling_tet = tiling_queue->begin;

	if (tiling_queue->begin != NULL)
		tiling_queue->begin = tiling_queue->begin->next;

	if (tiling_queue->begin == NULL)
		tiling_queue->end = NULL;

	return tiling_tet;
}


static void add_tiling_tet_to_queue(
	TilingTet	*tiling_tet,
	TilingQueue	*tiling_queue)
{
	tiling_tet->next = NULL;

	if (tiling_queue->end != NULL)
	{
		tiling_queue->end->next	= tiling_tet;
		tiling_queue->end		= tiling_tet;
	}
	else
	{
		tiling_queue->begin	= tiling_tet;
		tiling_queue->end	= tiling_tet;
	}
}


static void add_tiling_horoball_to_list(
	TilingTet		*tiling_tet,
	VertexIndex		v,
	TilingHoroball	**horoball_linked_list)
{
	TilingHoroball	*tiling_horoball;

	tiling_horoball = NEW_STRUCT(TilingHoroball);

	tiling_horoball->data.center		= tiling_tet->corner[v];
	tiling_horoball->data.radius		= 0.5 * tiling_tet->horoball_height[v];
	tiling_horoball->data.cusp_index	= tiling_tet->underlying_tet->cusp[v]->index;

	tiling_horoball->next = *horoball_linked_list;
	*horoball_linked_list = tiling_horoball;
}


static Boolean face_contains_useful_edge(
	TilingTet	*tiling_tet,
	FaceIndex	f,
	double		cutoff_height)
{
	/*
	 *	Note:  We may assume that the face f has no vertices at the point
	 *	at infinity in upper half space.  The reason is that the intial
	 *	tetrahedra have neighbor_found[] == TRUE for their side faces, and
	 *	get_full_horoball_list() calls us only if neighbor_found[f] is FALSE.
	 */

	/*
	 *	How many vertices incident to face f have horoballs
	 *	higher than cutoff_height?
	 */

	int			num_big_horoballs;
	VertexIndex	v,
				big_vertex;
	double		min_separation_sq;

	num_big_horoballs = 0;

	for (v = 0; v < 4; v++)
	{
		if (v == f)
			continue;

		if (tiling_tet->horoball_height[v] > cutoff_height)
		{
			num_big_horoballs++;
			big_vertex = v;
		}
	}

	/*
	 *	If there are no big horoballs,
	 *	the face cannot contain a useful edge.
	 */
	if (num_big_horoballs == 0)
		return FALSE;

	/*
	 *	If there are two or more big horoballs,
	 *	the face must contain a useful edge.
	 */
	if (num_big_horoballs >= 2)
		return TRUE;

	/*
	 *	At this point we know that the unique large horoball lies
	 *	at the vertex big_vertex.  There will be a useful edge iff
	 *	the distance from big_vertex to some other vertex of face f
	 *	is at least sqrt( height_of_big_vertex * cutoff_height * exp(min_d) ).
	 *	For a detailed explanation, please see Lemma 4 and the definition
	 *	of "useful edge" in get_full_horoball_list().
	 */

	min_separation_sq = tiling_tet->horoball_height[big_vertex]
					  * cutoff_height
					  * tiling_tet->underlying_tet->cusp[big_vertex]->exp_min_d;

	for (v = 0; v < 4; v++)
	{
		if (v == f  ||  v == big_vertex)
			continue;

		if (complex_modulus_squared(
				complex_minus(	tiling_tet->corner[big_vertex],
								tiling_tet->corner[v] )
				) > min_separation_sq)

			return TRUE;
	}

	return FALSE;
}


static TilingTet *make_neighbor_tiling_tet(
	TilingTet	*tiling_tet,
	FaceIndex	f)
{
	Tetrahedron	*tet,
				*nbr;
	Permutation	gluing;
	TilingTet	*tiling_nbr;
	VertexIndex	v,
				w,
				ff,
				some_vertex;
	double		exp_d,
				c_squared;

	/*
	 *	Find the underlying tetrahedra and the gluing between them.
	 */
	tet		= tiling_tet->underlying_tet;
	nbr		= tet->neighbor[f];
	gluing	= tet->gluing[f];

	/*
	 *	Set up the new TilingTet.
	 */

	tiling_nbr = NEW_STRUCT(TilingTet);

	tiling_nbr->underlying_tet	= nbr;
	tiling_nbr->orientation		= (parity[gluing] == orientation_preserving) ?
									tiling_tet->orientation :
								  ! tiling_tet->orientation;

	for (v = 0; v < 4; v++)
	{
		if (v == f)
			continue;

		w = EVALUATE(gluing, v);

		tiling_nbr->corner[w]			= tiling_tet->corner[v];
		tiling_nbr->horoball_height[w]	= tiling_tet->horoball_height[v];
		tiling_nbr->neighbor_found[w]	= FALSE;
	}

	/*
	 *	Deal with the remaining corner.
	 */

	ff = EVALUATE(gluing, f);

	/*
	 *	Call compute_fourth_corner() to locate the remaining ideal vertex.
	 */
	compute_fourth_corner(	tiling_nbr->corner,
							ff,
							tiling_nbr->orientation,
							nbr->shape[complete]->cwl[ultimate]);

	/*
	 *	Use the lemma from get_quick_face_horoballs() to compute
	 *	the height of the remaining horoball.
	 */
	some_vertex = ! ff;
	exp_d = exp(nbr->edge_class[edge_between_vertices[ff][some_vertex]]->intercusp_distance);
	c_squared = complex_modulus_squared(complex_minus(
					tiling_nbr->corner[ff],
					tiling_nbr->corner[some_vertex]));
	tiling_nbr->horoball_height[ff] =
		c_squared / (exp_d * tiling_nbr->horoball_height[some_vertex]);

	/*
	 *	Don't backtrack to the TilingTet we just came from.
	 */
	tiling_nbr->neighbor_found[ff] = TRUE;

	/*
	 *	get_full_horoball_list() will decide whether to add tiling_nbr
	 *	to the linked list and tree, and whether to add the new horoball
	 *	to the horoball list.
	 */
	tiling_nbr->next			= NULL;
	tiling_nbr->left			= NULL;
	tiling_nbr->right			= NULL;
	tiling_nbr->key				= 0.0;

	return tiling_nbr;
}


static void prepare_sort_key(
	TilingTet	*tiling_tet,
	double		parallelogram_to_square[2][2])
{
	VertexIndex	v;
	Complex		transformed_corner[4];

	static const double	coefficient[4][2] = {{37.0, 25.0}, {43.0, 13.0}, {2.0, 29.0}, {11.0, 7.0}};

	/*
	 *	Special case:  To avoid questions of numerical accuracy, assign
	 *	the "illegal" key value of -1 to TilingTets incident to infinity
	 *	in upper half space.  read_initial_tetrahedra() puts all such
	 *	TilingTets on the tree, so none need be added again.
	 */
	for (v = 0; v < 4; v++)
		if (complex_modulus(tiling_tet->corner[v]) > KEY_INFINITY)
		{
			tiling_tet->key = -1.0;
			return;
		}

	/*
	 *	Recall that we are tiling H^3 / (Z + Z), where the Z + Z is
	 *	the group of covering transformations of the cusp.  In other words,
	 *	two TilingTets are equivalent iff corresponding corners differ
	 *	by some combination of meridional and/or longitudinal translations.
	 *	The linear transformation parallelogram_to_square maps a meridian
	 *	to (1,0) and a longitude to (0,1).  We apply it to the TilingTets'
	 *	corners, so corresponding corners will differ by integers.
	 */
	for (v = 0; v < 4; v++)
	{
		transformed_corner[v].real = parallelogram_to_square[0][0] * tiling_tet->corner[v].real  +  parallelogram_to_square[0][1] * tiling_tet->corner[v].imag;
		transformed_corner[v].imag = parallelogram_to_square[1][0] * tiling_tet->corner[v].real  +  parallelogram_to_square[1][1] * tiling_tet->corner[v].imag;
	}

	/*
	 *	To implement a binary tree, we need a search key which is well
	 *	defined under the action of the meridional and longitudinal
	 *	translations.  In terms of the transformed_corners, it should be
	 *	well defined under integer translations.  Any integer linear
	 *	combination of the real and imaginary parts of the transformed
	 *	corners will do.  We choose a random looking one, to reduce the
	 *	chances that distinct points will be assigned the same value of
	 *	the search key.  (Of course the algorithm works correctly in any
	 *	case -- it's just faster if all the search key values are distinct.)
	 *	The linear combination provides a continuous map from the transformed
	 *	corners modulo integers to the reals modulo integers, i.e. to the
	 *	circle.  We then map the circle to the interval [0, 1/2] in a
	 *	continuous way.  (It's a two-to-one map, but that's unavoidable.)
	 */

	/*
	 *	Form a random looking integer combination of the corner coordinates.
	 */
	tiling_tet->key = 0.0;
	for (v = 0; v < 4; v++)
	{
		tiling_tet->key += coefficient[v][0] * transformed_corner[v].real;
		tiling_tet->key += coefficient[v][1] * transformed_corner[v].imag;
	}

	/*
	 *	Take the fractional part.
	 */
	tiling_tet->key -= floor(tiling_tet->key);

	/*
	 *	Fold the unit interval [0,1] onto the half interval [0, 1/2]
	 *	in ensure continuity.
	 */
	if (tiling_tet->key > 0.5)
		tiling_tet->key = 1.0 - tiling_tet->key;
}


static Boolean tiling_tet_on_tree(
	TilingTet	*tiling_tet,
	TilingTet	*tiling_tree_root,
	Complex		meridian,
	Complex		longitude)
{
	TilingTet	*subtree_stack,
				*subtree;
	double		delta;
	Boolean		left_flag,
				right_flag;
	FaceIndex	f;

	/*
	 *	As a special case, TilingTets incident to infinity in upper half
	 *	space are already all on the tree.  prepare_sort_key() marks
	 *	duplicates of such TilingTets with a key value of -1.  (Computing
	 *	and comparing the usual key value is awkward when some of the
	 *	numbers are infinite.)
	 */
	if (tiling_tet->key == -1.0)
		return TRUE;

	/*
	 *	Reliability is our first priority.  Speed is second.  So if
	 *	tiling_tet->key and subtree->key are close, we want to search both
	 *	the left and right subtrees.  Otherwise we search only one or the
	 *	other.  We implement the recursion using our own stack, rather than
	 *	the system stack, to avoid the possibility of a stack/heap collision
	 *	during deep recursions.
	 */

	/*
	 *	Initialize the stack to contain the whole tree.
	 */
	subtree_stack = tiling_tree_root;
	if (tiling_tree_root != NULL)
		tiling_tree_root->next_subtree = NULL;

	/*
	 *	Process the subtrees on the stack,
	 *	adding additional subtrees as needed.
	 */
	while (subtree_stack != NULL)
	{
		/*
		 *	Pull a subtree off the stack.
		 */
		subtree					= subtree_stack;
		subtree_stack			= subtree_stack->next_subtree;
		subtree->next_subtree	= NULL;

		/*
		 *	Compare the key values of the tiling_tet and the subtree's root.
		 */
		delta = tiling_tet->key - subtree->key;

		/*
		 *	Which side(s) should we search?
		 */
		left_flag	= (delta < +KEY_EPSILON);
		right_flag	= (delta > -KEY_EPSILON);

		/*
		 *	Put the subtrees we need to search onto the stack.
		 */
		if (left_flag && subtree->left)
		{
			subtree->left->next_subtree = subtree_stack;
			subtree_stack = subtree->left;
		}
		if (right_flag && subtree->right)
		{
			subtree->right->next_subtree = subtree_stack;
			subtree_stack = subtree->right;
		}

		/*
		 *	Check this TilingTet if the key values match.
		 */
		if (left_flag && right_flag)
			/*
			 *	Are the TilingTets translations of one another?
			 */
			if (same_corners(tiling_tet, subtree, meridian, longitude))
			{
				/*
				 *	*subtree is a TilingTet which may or may not have been
				 *	processed yet.  If not, then when we do process it, we
				 *	know there's no need to recreate tiling_tet's "parent".
				 */
				for (f = 0; f < 4; f++)
					subtree->neighbor_found[f] |= tiling_tet->neighbor_found[f];

				return TRUE;
			}
	}

	return FALSE;
}


static Boolean same_corners(
	TilingTet	*tiling_tet1,
	TilingTet	*tiling_tet2,
	Complex		meridian,
	Complex		longitude)
{
	/*
	 *	Are tiling_tet1 and tiling_tet2 translations of the same tetrahedron
	 *	in H^3/(Z + Z) ?
	 *
	 *	Note:  This function does *not* take into account the size of the
	 *	TilingTets.  Two TilingsTets which were very tiny and very close
	 *	could cause a false positive, and such TilingTets could be mistakenly
	 *	omitted from the tiling.  But that's not likely to happen for any
	 *	computationally feasible value of cutoff_epsilon.
	 */

	Complex		offset,
				fractional_part,
				diff;
	double		num_meridians,
				num_longitudes,
				error;
	VertexIndex	v;

	/*
	 *	Is the offset between a pair of corresponding vertices
	 *	an integer combination of meridians and longitudes?
	 */

	offset = complex_minus(	tiling_tet2->corner[0],
							tiling_tet1->corner[0]); 

	fractional_part = offset;

	num_meridians	= floor(fractional_part.imag / meridian.imag  + 0.5);
	fractional_part	= complex_minus(
								fractional_part,
								complex_real_mult(num_meridians, meridian));

	num_longitudes	= floor(fractional_part.real / longitude.real + 0.5);
	fractional_part	= complex_minus(
								fractional_part,
								complex_real_mult(num_longitudes, longitude));

	if (complex_modulus(fractional_part) > CORNER_EPSILON)
		return FALSE;

	/*
	 *	Do all pairs of corresponding vertices differ by the same offset?
	 */

	for (v = 1; v < 4; v++)
	{
		diff = complex_minus(	tiling_tet2->corner[v],
								tiling_tet1->corner[v]); 
		error = complex_modulus(complex_minus(offset, diff));
		if (error > CORNER_EPSILON)
			return FALSE;
	}

	return TRUE;
}


static void add_tiling_tet_to_tree(
	TilingTet	*tiling_tet,
	TilingTet	**tiling_tree_root)
{
	/*
	 *	tiling_tet_on_tree() has already checked that tiling_tet is not
	 *	a translation of any TilingTet already on the tree.  So here we
	 *	just add it in the appropriate spot, based on the key value.
	 */

	TilingTet	**location;
	
	location = tiling_tree_root;

	while (*location != NULL)
	{
		if (tiling_tet->key <= (*location)->key)
			location = &(*location)->left;
		else
			location = &(*location)->right;
	}

	*location = tiling_tet;

	tiling_tet->left  = NULL;
	tiling_tet->right = NULL;
}


static void add_horoball_if_necessary(
	TilingTet		*tiling_tet,
	TilingHoroball	**horoball_linked_list,
	double			cutoff_height)
{
	VertexIndex	v;

	for (v = 0; v < 4; v++)
	{
		/*
		 *	Ignore horoballs which are too small.
		 */
		if (tiling_tet->horoball_height[v] < cutoff_height)
			continue;

		/*
		 *	Recall the convention made in get_full_horoball_list() that
		 *	each horoball is recorded only by the TilingTet
		 *	which contains its north pole.  If the north pole lies on the
		 *	boundary of two TilingTets, they both record it.
		 */
		if (contains_north_pole(tiling_tet, v) == TRUE)
			add_tiling_horoball_to_list(tiling_tet, v, horoball_linked_list);
	}
}


static Boolean contains_north_pole(
	TilingTet	*tiling_tet,
	VertexIndex	v)
{
	/*
	 *	Check whether vertex v lies within the triangle defined
	 *	by the remaining three vertices.
	 */

	int			i;
	VertexIndex	w[3];
	Complex		u[3];
	double		s[3],
				det;

	/*
	 *	Label the remaining three vertices w[0], w[1] and w[2]
	 *	as you go counterclockwise around the triangle they define
	 *	on the boundary of upper half space.
	 *
	 *							w[2]
	 *						   /    \
	 *						  /      \
	 *						 /        \
	 *					   w[0]-------w[1]
	 *
	 *	If v lies inside that triangle we'll return TRUE;
	 *	otherwise we'll return FALSE.
	 */

	w[0] = !v;

	if (tiling_tet->orientation == right_handed)
	{
		w[1] = remaining_face[v][w[0]];
		w[2] = remaining_face[w[0]][v];
	}
	else
	{
		w[1] = remaining_face[w[0]][v];
		w[2] = remaining_face[v][w[0]];
	}

	/*
	 *	The vector u[i] runs from v to w[i].
	 *
	 *							w[2]
	 *						   / |  \
	 *						  /  v   \
	 *						 / /   \  \
	 *					   w[0]-------w[1]
	 */
	for (i = 0; i < 3; i++)
		u[i] = complex_minus(tiling_tet->corner[w[i]], tiling_tet->corner[v]);

	/*
	 *	s[i] is the squared length of the triangle's i-th side.
	 */
	for (i = 0; i < 3; i++)
		s[i] = complex_modulus_squared(complex_minus(tiling_tet->corner[w[(i+1)%3]], tiling_tet->corner[w[i]]));

	/*
	 *	If v lies in the triangle's interior, we of course return TRUE.
	 *	But if v lies (approximately) on one of the triangle's sides, we
	 *	also want to return TRUE, so that in ambiguous cases horoballs are
	 *	recorded twice, not zero times.
	 *
	 *	We need a scale invariant measure of the signed distance from v
	 *	to each side of the triangle, so that we can apply our error epsilon
	 *	in a meaningful way.  (We don't want to return TRUE for *all* tiny
	 *	triangles, simply because they are tiny!)  The determinant
	 *
	 *						| u[i].real   u[i+1].real |
	 *				det  =  |                         |
	 *						| u[i].imag   u[i+1].imag |
	 *
	 *	gives twice the area of the triangle (v, w[i], w[i+1]).
	 *	Therefore det/dist(w[i], w[i+1]) gives the triangle's altitude,
	 *	and det/dist(w[i], w[i+1])^2 = det/s[i] gives the ratio of
	 *	the altitude to the length of the side.  If that ratio is at least
	 *	-NORTH_POLE_EPSILON for all sides, we return TRUE.
	 */
	for (i = 0; i < 3; i++)
	{
		det = u[i].real * u[(i+1)%3].imag  -  u[i].imag * u[(i+1)%3].real;
		if (det / s[i] < -NORTH_POLE_EPSILON)
			return FALSE;
	}

	return TRUE;
}


static void free_tiling_tet_tree(
	TilingTet	*tiling_tree_root)
{
	TilingTet	*subtree_stack,
				*subtree;

	/*
	 *	Implement the recursive freeing algorithm using our own stack
	 *	rather than the system stack, to avoid the possibility of a
	 *	stack/heap collision.
	 */

	/*
	 *	Initialize the stack to contain the whole tree.
	 */
	subtree_stack = tiling_tree_root;
	if (tiling_tree_root != NULL)
		tiling_tree_root->next_subtree = NULL;

	/*
	 *	Process the subtrees on the stack one at a time.
	 */
	while (subtree_stack != NULL)
	{
		/*
		 *	Pull a subtree off the stack.
		 */
		subtree					= subtree_stack;
		subtree_stack			= subtree_stack->next_subtree;
		subtree->next_subtree	= NULL;

		/*
		 *	If the subtree's root has nonempty left and/or right subtrees,
		 *	add them to the stack.
		 */
		if (subtree->left != NULL)
		{
			subtree->left->next_subtree = subtree_stack;
			subtree_stack = subtree->left;
		}
		if (subtree->right != NULL)
		{
			subtree->right->next_subtree = subtree_stack;
			subtree_stack = subtree->right;
		}

		/*
		 *	Free the subtree's root node.
		 */
		my_free(subtree);
	}
}


static CuspNbhdHoroballList *transfer_horoballs(
	TilingHoroball	**horoball_linked_list)
{
	CuspNbhdHoroballList	*theHoroballList;
	TilingHoroball			*the_tiling_horoball,
							*the_dead_horoball;
	int						i;

	/*
	 *	Allocate the wrapper.
	 */
	theHoroballList = NEW_STRUCT(CuspNbhdHoroballList);

	/*
	 *	Count the horoballs.
	 */
	for (	the_tiling_horoball = *horoball_linked_list,
				theHoroballList->num_horoballs = 0;
			the_tiling_horoball != NULL;
			the_tiling_horoball = the_tiling_horoball->next,
				theHoroballList->num_horoballs++)
		;

	/*
	 *	If we found some horoballs, allocate an array
	 *	for the CuspNbhdHoroballs.
	 */
	if (theHoroballList->num_horoballs > 0)
		theHoroballList->horoball = NEW_ARRAY(theHoroballList->num_horoballs, CuspNbhdHoroball);
	else
		theHoroballList->horoball = NULL;

	/*
	 *	Copy the data from the linked list to the array.
	 */
	for (	the_tiling_horoball = *horoball_linked_list, i = 0;
			the_tiling_horoball != NULL;
			the_tiling_horoball = the_tiling_horoball->next, i++)

		theHoroballList->horoball[i] = the_tiling_horoball->data;

	/*
	 *	Free the linked list.
	 */
	while (*horoball_linked_list != NULL)
	{
		the_dead_horoball		= *horoball_linked_list;
		*horoball_linked_list	= the_dead_horoball->next;
		my_free(the_dead_horoball);
		
	}

	return theHoroballList;
}


void free_cusp_neighborhood_horoball_list(
	CuspNbhdHoroballList	*horoball_list)
{
	if (horoball_list != NULL)
	{
		if (horoball_list->horoball != NULL)
			my_free(horoball_list->horoball);

		my_free(horoball_list);
	}
}


static int CDECL compare_horoballs(
	const void	*horoball0,
	const void	*horoball1)
{
	if (((CuspNbhdHoroball *)horoball0)->radius < ((CuspNbhdHoroball *)horoball1)->radius)
		return -1;
	else if (((CuspNbhdHoroball *)horoball0)->radius > ((CuspNbhdHoroball *)horoball1)->radius)
		return +1;
	else
		return 0;
}


static void cull_duplicate_horoballs(
	Cusp					*cusp,
	CuspNbhdHoroballList	*aHoroballList)
{
	int		original_num_horoballs,
			i,
			j,
			k;
	Complex	meridian,
			longitude,
			delta;
	double	cutoff_radius,
			mult;
	Boolean	distinct;

	/*
	 *	Note the meridional and longitudinal translations.
	 */
	meridian  = complex_real_mult(cusp->displacement_exp, cusp->translation[M]);
	longitude = complex_real_mult(cusp->displacement_exp, cusp->translation[L]);

	/*
	 *	Examine each horoball on the list.
	 *	If it's distinct from all previously examined horoballs, keep it.
	 *	Otherwise ignore it.
	 *
	 *	We could implement this algorithm by copying the horoballs
	 *	we want to keep from the array aHoroballList->horoball onto
	 *	a new array.  But it's simpler just to copy the array onto itself.
	 *	(This sounds distressing at first, but if you think it through
	 *	you'll realize that it's perfectly safe.)
	 *
	 *	The index i keeps track of the horoball we're examining.
	 *	The index j keeps track of where we're writing it to.
	 */

	original_num_horoballs = aHoroballList->num_horoballs;

	for (i = 0, j = 0; j < original_num_horoballs; j++)
	{
		/*
		 *	If the j-th horoball is distinct from all previous ones, copy
		 *	it into the i-th position of the array.  In practice, of course,
		 *	we compare it only to previous horoballs of the same radius.
		 *	We may assume that get_cusp_neighborhood_horoballs() has
		 *	already sorted the horoballs in order of increasing size.
		 */

		/*
		 *	Assume the j-th horoball is distinct from horoballs
		 *	0 through i - 1, unless we discover otherwise.
		 */
		distinct = TRUE;

		/*
		 *	What is the smallest radius we should consider?
		 */
		cutoff_radius = aHoroballList->horoball[j].radius - DUPLICATE_RADIUS_EPSILON;

		/*
		 *	Start with horoball i - 1, and work downwards until either
		 *	we reach horoball 0, or the radii drop below the cutoff_radius.
		 */
		for (k = i; --k >= 0; )
		{
			/*
			 *	If horoball k is too small, there is no need to examine
			 *	the remaining ones, which are even smaller.
			 */
			if (aHoroballList->horoball[k].radius < cutoff_radius)
				break;

			/*
			 *	Let delta be the difference between the center of j and
			 *	the center of k, modulo the Z + Z action of the group
			 *	of covering transformations of the cusp.
			 */
			delta	= complex_minus(aHoroballList->horoball[j].center,
									aHoroballList->horoball[k].center);
			mult	= floor(delta.imag / meridian.imag  + 0.5);
			delta	= complex_minus(delta, complex_real_mult(mult, meridian));
			mult	= floor(delta.real / longitude.real + 0.5);
			delta	= complex_minus(delta, complex_real_mult(mult, longitude));

			/*
			 *	If the distance between the centers of horoballs j and k is
			 *	less than the radius, then the horoballs must be equivalent.
			 */
			if (complex_modulus(delta) < cutoff_radius)
			{
				distinct = FALSE;
				break;
			}
		}

		if (distinct == TRUE)
		{
			aHoroballList->horoball[i] = aHoroballList->horoball[j];
			i++;
		}
		else
			aHoroballList->num_horoballs--;
	}
}


CuspNbhdSegmentList *get_cusp_neighborhood_Ford_domain(
	CuspNeighborhoods	*cusp_neighborhoods,
	int					cusp_index)
{
	Cusp				*cusp;
	CuspNbhdSegmentList	*theSegmentList;
	CuspNbhdSegment		*next_segment;
	Tetrahedron			*tet,
						*nbr_tet;
	Complex				(*x)[4][4];
	Boolean				(*in_use)[4];
	VertexIndex			v,
						nbr_v,
						u,
						nbr_u,
						w[3];
	Orientation			h,
						nbr_h;
	FaceIndex			f,
						nbr_f;
	Permutation			gluing;
	int					i;
	Complex				corner[3],
						delta,
						inward_normal,
						offset,
						p;
	double				length,
						tilt,
						a[2],
						b[2],
						c[2],
						det;

	/*
	 *	Find the requested Cusp.
	 */
	cusp = find_cusp(cusp_neighborhoods->its_triangulation, cusp_index);

	/*
	 *	Allocate the wrapper for the array.
	 */
	theSegmentList = NEW_STRUCT(CuspNbhdSegmentList);

	/*
	 *	We don't know ahead of time exactly how many CuspNbhdSegments
	 *	we'll need.  Torus cusps report each segment once, but Klein
	 *	bottle cusps report each segment twice, once for each sheet.
	 *
	 *	To get an upper bound on the number of segments,
	 *	assume all cusps are Klein bottle cusps.
	 *
	 *		  n tetrahedra
	 *		* 4 vertices/tetrahedron
	 *		* 2 triangles/vertex		(left_handed and right_handed)
	 *		* 3 sides/triangle
	 *		/ 2 Ford edges/side			(no need to draw each edge twice)
	 *
	 *		= 12n Ford edges
	 */
	theSegmentList->segment = NEW_ARRAY(12*cusp_neighborhoods->its_triangulation->num_tetrahedra, CuspNbhdSegment);

	/*
	 *	Keep a pointer to the first empty CuspNbhdSegment.
	 */
	next_segment = theSegmentList->segment;

	/*
	 *	Compute the Ford domain's vertices.
	 */
	for (tet = cusp_neighborhoods->its_triangulation->tet_list_begin.next;
		 tet != &cusp_neighborhoods->its_triangulation->tet_list_end;
		 tet = tet->next)
	{
		x		= tet->cusp_nbhd_position->x;
		in_use	= tet->cusp_nbhd_position->in_use;

		for (v = 0; v < 4; v++)
		{
			/*
			 *	If this isn't the cusp the user wants, ignore it.
			 */
			if (tet->cusp[v] != cusp)
				continue;

			for (h = 0; h < 2; h++)		/* h = right_handed, left_handed */
			{
				if (in_use[h][v] == FALSE)
					continue;

				/*
				 *	There are at least two ways to locate the Ford vertex.
				 *
				 *	(1)	Use Theorem 3.1 of
				 *
				 *			M. Sakuma and J. Weeks, The generalized tilt
				 *			formula, Geometriae Dedicata 55 (115-123) 1995,
				 *
				 *		which states that the Euclidean distance in the
				 *		cusp from (the projection of) the Ford vertex
				 *		to a side of the enclosing triangle equals the
				 *		tilt on that side.  (Or better yet, see the
				 *		preprint version of the article, which has a lot
				 *		more pictures and fuller explanations.)
				 *
				 *	(2)	Write down the equations for the three planes
				 *		which lie halfway between the cusp at infinity
				 *		and the cusp at each of the three remaining ideal
				 *		vertices.  Each such plane appears at a Euclidean
				 *		hemisphere.  Subtracting the equations for two
				 *		such hemispheres gives a linear equation, and
				 *		two such linear equations may be solved
				 *		simultaneously to locate the Ford vertex.
				 *
				 *	Either of the above approaches should work fine.
				 *	Here we choose approach (1) because it looks a tiny
				 *	bit simpler numerically.
				 */

				/*
				 *	Label the triangles corners w[0], w[1] and w[2],
				 *	going counterclockwise around the triangle.
				 *
				 *						w[2]
				 *					   /    \
				 *					  /      \
				 *					 /        \
				 *				   w[0]-------w[1]
				 */

				w[0] = !v;

				if (h == right_handed)
				{
					w[1] = remaining_face[w[0]][v];
					w[2] = remaining_face[v][w[0]];
				}
				else
				{
					w[1] = remaining_face[v][w[0]];
					w[2] = remaining_face[w[0]][v];
				}

				/*
				 *	Record the triangle's corners.
				 */
				for (i = 0; i < 3; i++)
					corner[i] = complex_real_mult(cusp->displacement_exp, x[h][v][w[i]]);

				/*
				 *						w[2]
				 *					   /    \
				 *				------/---*--\-------
				 *					 /        \
				 *				   w[0]-------w[1]
				 *
				 *	The Ford vertex lies on a line parallel to a side of
				 *	the triangle at a distance "tilt" away (by Theorem 3.1
				 *	of Sakuma & Weeks).  Find the equations of such lines
				 *	(the third is redundant -- it could perhaps be used
				 *	to enhance accuracy if desired).
				 */
				for (i = 0; i < 2; i++)
				{
					/*
					 *	Make yourself a sketch as you follow along.
					 */

					delta = complex_minus(corner[(i+1)%3], corner[i]);

					inward_normal.real = +delta.imag;
					inward_normal.imag = -delta.real;

					length = complex_modulus(inward_normal);

					tilt = tet->tilt[w[(i+2)%3]];

					offset = complex_real_mult(tilt/length, inward_normal);

					p = complex_plus(corner[i], offset);

					/*
					 *	The equation of the desired line is
					 *
					 *		y - p.imag       delta.imag
					 *		----------   =   ----------
					 *		x - p.real       delta.real
					 *
					 *	Cross multiply to get
					 *
					 *	delta.imag * x - delta.real * y
					 *		= delta.imag * p.real - delta.real * p.imag
					 *
					 *	This last equation also has a natural cross product
					 *	interpretation:  delta X (x,y) = p X (x,y).
					 *
					 *	Record the equation as ax + by = c.
					 */
					a[i] =  delta.imag;
					b[i] = -delta.real;
					c[i] = delta.imag * p.real  -  delta.real * p.imag;
				}

				/*
				 *	Solve the matrix equation
				 *
				 *		( a[0]  b[0] ) (x) = (c[0])
				 *		( a[1]  b[1] ) (y)   (c[1])
				 *	=>
				 *		(x) = _1_ ( b[1] -b[0] ) (c[0])
				 *		(y)   det (-a[1]  a[0] ) (c[1])
				 */

				det = a[0]*b[1] - a[1]*b[0];

				FORD_VERTEX(x,h,v).real = (b[1]*c[0] - b[0]*c[1]) / det;
				FORD_VERTEX(x,h,v).imag = (a[0]*c[1] - a[1]*c[0]) / det;
			}
		}
	}

	/*
	 *	Record the Ford domain edges.
	 */
	for (tet = cusp_neighborhoods->its_triangulation->tet_list_begin.next;
		 tet != &cusp_neighborhoods->its_triangulation->tet_list_end;
		 tet = tet->next)
	{
		x		= tet->cusp_nbhd_position->x;
		in_use	= tet->cusp_nbhd_position->in_use;

		for (v = 0; v < 4; v++)
		{
			/*
			 *	If this isn't the cusp the user wants, ignore it.
			 */
			if (tet->cusp[v] != cusp)
				continue;

			for (h = 0; h < 2; h++)		/* h = right_handed, left_handed */
			{
				if (in_use[h][v] == FALSE)
					continue;

				for (f = 0; f < 4; f++)
				{
					if (f == v)
						continue;

					gluing = tet->gluing[f];

					nbr_tet	= tet->neighbor[f];
					nbr_f	= EVALUATE(gluing, f);

					/*
					 *	We want to report each segment only once, so we
					 *	make the (arbitrary) convention that we report
					 *	a segment only from the Tetrahedron whose address
					 *	in memory is less.  In the case of a Tetrahedron
					 *	glued to itself, we report it from the lower
					 *	FaceIndex.
					 */
					if (tet > nbr_tet || (tet == nbr_tet && f > nbr_f))
						continue;

					/*
					 *	Don't report Ford edges dual to 2-cells which are
					 *	part of the arbitrary subdivision of the canonical
					 *	cell decomposition into tetrahdra.  (They'd have
					 *	length zero anyway, but we want to be consistent
					 *	with how we report the triangulation.  We rely on
					 *	the fact that proto_canonize() has computed the
					 *	tilts and left them in place.  The sum of the tilts
					 *	will never be positive for a subdivision of the
					 *	canonical cell decomposition.  If it's close to
					 *	zero, ignore the Ford edge dual to that face.
					 */
					if (tet->tilt[f] + nbr_tet->tilt[nbr_f] > -CONCAVITY_EPSILON)
						continue;

					/*
					 *	This edge has passed all its tests, so record it.
					 *	Keep in mind that the coordinate systems in
					 *	neighboring Tetrahedra may differing by translations.
					 */

					nbr_v = EVALUATE(gluing, v);
					nbr_h = (parity[gluing] == orientation_preserving) ? h : !h;

					next_segment->endpoint[0] = FORD_VERTEX(    tet->cusp_nbhd_position->x,     h,     v);
					next_segment->endpoint[1] = FORD_VERTEX(nbr_tet->cusp_nbhd_position->x, nbr_h, nbr_v);

					/*
					 *	The segment indices are currently used only
					 *	for the triangulation, not the Ford domain.
					 */
					next_segment->start_index	= -1;
					next_segment->middle_index	= -1;
					next_segment->end_index		= -1;

					/*
					 *	Compensate for the (possibly) translated
					 *	coordinate systems.  Compare the position of
					 *	a vertex u as seen by tet and nbr_tet.
					 */

					u		= remaining_face[v][f];
					nbr_u	= EVALUATE(gluing, u);

					next_segment->endpoint[1] = complex_plus
					(
						next_segment->endpoint[1],
						complex_real_mult
						(
							cusp->displacement_exp,
							complex_minus
							(
								    tet->cusp_nbhd_position->x[    h][    v][    u],
								nbr_tet->cusp_nbhd_position->x[nbr_h][nbr_v][nbr_u]
							)
						)
					);

					/*
					 *	Move on.
					 */
					next_segment++;
				}
			}
		}
	}

	/*
	 *	How many segments did we find?
	 *
	 *	(ANSI C will subtract the pointers correctly, automatically
	 *	dividing by sizeof(CuspNbhdSegment).)
	 */
	theSegmentList->num_segments = next_segment - theSegmentList->segment;

	/*
	 *	Did we find more segments than we had allocated space for?
	 *	This should be impossible, but it doesn't hurt to check.
	 */
	if (theSegmentList->num_segments > 12*cusp_neighborhoods->its_triangulation->num_tetrahedra)
		uFatalError("get_cusp_neighborhood_Ford_domain", "cusp_neighborhoods");

	return theSegmentList;
}