File: asn2graphic.c

package info (click to toggle)
ncbi-tools6 6.1.20120620-8
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 241,628 kB
  • ctags: 101,236
  • sloc: ansic: 1,431,713; cpp: 6,248; pascal: 3,949; xml: 3,390; sh: 3,090; perl: 1,077; csh: 488; makefile: 449; ruby: 93; lisp: 81
file content (7155 lines) | stat: -rw-r--r-- 225,700 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
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
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
/*   asn2graphic.c
* ===========================================================================
*
*                            PUBLIC DOMAIN NOTICE
*            National Center for Biotechnology Information (NCBI)
*
*  This software/database is a "United States Government Work" under the
*  terms of the United States Copyright Act.  It was written as part of
*  the author's official duties as a United States Government employee and
*  thus cannot be copyrighted.  This software/database is freely available
*  to the public for use. The National Library of Medicine and the U.S.
*  Government do not place any restriction on its use or reproduction.
*  We would, however, appreciate having the NCBI and the author cited in
*  any work or product based on this material
*
*  Although all reasonable efforts have been taken to ensure the accuracy
*  and reliability of the software and data, the NLM and the U.S.
*  Government do not and cannot warrant the performance or results that
*  may be obtained by using this software or data. The NLM and the U.S.
*  Government disclaim all warranties, express or implied, including
*  warranties of performance, merchantability or fitness for any particular
*  purpose.
*
* ===========================================================================
*
* File Name:  asn2graphic.c
* Author:  Eric Northup
*
* Version Creation Date:   11/8/01
*
* $Revision: 6.132 $
*
* File Description:
*
* Modifications:
* --------------------------------------------------------------------------
*
* ==========================================================================
*/

#include <asn2graphicp.h>
#include <sequtil.h>
#include <sqnutils.h>
#include <explore.h>
#include <drawingp.h>
#include <alignmgr2.h>

/* type used to accumulate align score weights, should be small to save space, but large enough we do not overflow. */
typedef Int2 AccumValue_t;
typedef AccumValue_t PNTR AccumValuePtr_t;
#define ACCUMVALUE_MAX  INT2_MAX

/*
  Given a sequence alignment, look at its score
  and return a suitable integer (AccumValue_t) weight.'
  scoretype gives which part of the score to use.
*/
enum {
  NLM_SCORE_COUNT = 0,
  NLM_SCORE_SCORE,
  NLM_SCORE_BIT,
  NLM_SCORE_EVALUE,
  NLM_SCORE_NUMBER,
  NLM_SCORE_TOOBIG
};


#define RELEVANT_FEATS_PER_CHUNK 128

/* these do not apply to individual features; they are used, ie in "AddFeatureToFilter (FEATDEF_ANY_RNA. . .)
   that would make the filter include _all_ types of RNA */
#define FEATDEF_ANY_PROT (APPEARANCEITEM_MAX + 1)
#define FEATDEF_ANY_RNA (APPEARANCEITEM_MAX + 2)

typedef struct renderInput {
  AppearanceItemPtr AIP;
  FilterItemPtr     FIP;
  RelevantFeatureItemPtr RFIP;
  SegmenT         labelSeg;
  SegmenT         drawSeg;
  Int4            yStart;
  Int4            decorationLeft;
  Int4            decorationRight;
  Int4            decorationHeight;
  Uint2           featureOffset;
  Uint2           Height, rowHeight;
} RenderInput, PNTR RenderInputPtr;

typedef struct viewerInstanceData {
  BioseqPtr       BSP;
  Uint4           viewScale;
  Uint4           seqLength;
  Int4Ptr         ceiling;
  SeqAnnotPtr PNTR sapList;
  Uint2           sapCount;
  SeqAnnotPtr     currentSAP;
  SegmenT         drawOnMe;
  SegmenT         sanLevelSeg;
  SegmenT         topLevelSeg;
  Uint4           featureCount;
  ValNodePtr      featVNP;      /* data.ptrvalue == RelevantFeatureItem [RELEVANT_FEATS_PER_CHUNK] */
  ValNodePtr      BSPsegmentVNP;
  ValNodePtr      BSPsegmentTail;
  AppearancePtr   AppPtr;
  FilterPtr       FltPtr;
  LayoutAlgorithm overrideLayout;
  Int4            gphheight;
  SegmenT         gphseg;
  Int4            gphyOffset;
  Int4            from;
  Int4            to;
  Boolean         allFeatures;
  GraphicViewExtrasPtr extras;
} ViewerContext, PNTR ViewerContextPtr;

typedef struct featureFilterState {
  ValNodePtr       currentRFIPblockVNP;
  Uint4            featureBlockOffset;
  Uint2            indexInBlock;
} FeatureFilterState, PNTR FeatureFilterStatePtr;

#define MAX_ALIGN_SORT_LABEL  20
typedef struct seq_align_sort_info {
  SeqAlignPtr sap;
  Int4  start, stop;
  Uint1 strand;
  Char  label[MAX_ALIGN_SORT_LABEL + 1];
  AccumValue_t  normScore;
} SeqAlignSortInfo, PNTR SeqAlignSortInfoPtr;

typedef struct AlignmentFilterState {
 /* SeqAlignPtr      SAPhead, SAPcurrent; */ /* obsolete */
  SeqAlignSortInfoPtr alignSorted;  /* array of SeqAlignPtrs & Info about them, sorted */
  Int4             alignSortedLen;  /* len of alignSorted */
  Int4             alignIndex;      /* index of current alignment in alignSorted */
  Uint1            scoreType;       /* what kind of score will we filter and weight by? */
  Int2             cutoffPercent;   /* include alignments in alignSorted only if their score is in the top cutoffPercent */
  AccumValue_t     cutoffScore;     /* normalised score Below which aligns won't get into alignSorted. */
  AccumValue_t     cutoffScoreHi;   /* normalised score Above which aligns won't get into alignSorted. */
  Int4             minScore, maxScore;  /* un-normalised min & max scores seen on these alignments */
} AlignmentFilterState, PNTR AlignmentFilterStatePtr;

/*
Bioseq's are still special-case for now.  todo: make bioseq segments use this mechanism
*/

typedef union filterState {
  FeatureFilterState feat;
  AlignmentFilterState align;
} FilterState, PNTR FilterStatePtr;  

typedef struct filterProcessState {
  FilterState      state;
  FilterItemPtr    currentFIP;
  ValNodePtr       currentFilterVNP;
  ValNodePtr       needFreeList; /* things to be freed with ValNodeFreeData() after finishing this filter */
  ValNodePtr       lastInFreeList;
  SegmenT          labelSegs [APPEARANCEITEM_MAX];
  SegmenT          drawSegs [APPEARANCEITEM_MAX];
  Int4             ceiling;
  RenderInput      renderParm;
  Uint4            featuresProcessedCount;
  BoolPtr          featuresProcessed;    /*points to an array of boolean [vContext->featureCount] */
  ViewerContextPtr vContext;
  Boolean          groupBoxDrawn;
  Boolean          groupLabelDrawn;
  Boolean          annotBoxDrawn;
  Boolean          annotLabelDrawn;
} FilterProcessState, PNTR FilterProcessStatePtr;

typedef void (*RenderFuncPtr)    (RenderInputPtr rip, ViewerContextPtr vContext);
typedef void (*GetDimensionsPtr) (RenderInputPtr, Int4Ptr start, Int4Ptr stop, Uint2Ptr height, ViewerContextPtr vContext);

typedef struct renderClass {
  RenderFuncPtr RenderFunc;
  GetDimensionsPtr GetDimensions;
} RenderClass, PNTR RenderClassPtr;

typedef struct internalRow {
  Uint4           rowFeatureCount;
  DataVal         layoutData;
  ValNodePtr      feats;        /* data.ptrvalue == RelevantFeatureItemPtr */
  struct internalRow PNTR next;
} InternalRow, PNTR InternalRowPtr;

/* returns the total number of _rows_ */
typedef Uint2   (PNTR LayoutFunction) (InternalRowPtr firstRow, FilterProcessStatePtr FPSP);


static CharPtr LayoutStrings [] = {
  "Inherit", /* Do not override layout in filter */
  "Diagonal", /* One feature per row */
  /* "DiagonalSawtooth" */
  "ByType", /* like "compact", except that no row will contain _different_ types of features (this may use more rows) */
  "Smear", /* one row contains all features of a given type (overlapping features will render as an anonymous smear */
  /*  "Single Row", -- not working currently*/ /* _all_ features are rendered in a single row (equivalent to "smear" if given only one type of features)*/
  "Compact", /* Overlapping features are drawn in different rows, but this tries to minimize the number of rows, */
  "GeneProducts", /* Group associated mRNA and CDS regions . . . */
  "GeneProductsX", /* Like GeneProducts, but may display the same mRNA multiple times if it maps to multiple CDS regions. . . */
  NULL
};

static LayoutAlgorithm LayoutValues [] = {
  Layout_Inherit,
  Layout_Diagonal,
  /* Layout_DiagonalSawtooth, */
  Layout_FeatTypePerLineGroup,
  Layout_FeatTypePerLine,
  /*  Layout_AllInOneLine, not working currently (and not all that useful, either)*/
  Layout_PackUpward,
  Layout_GroupCorrespondingFeats,
  Layout_GroupCorrespondingFeatsRepeat
};

static CharPtr AlnScoreStrings [] = {
    "None",
    "Score",
    "Bit Score",
    "E-value",
    "Number",
    NULL
};

/*
static CharPtr AlnScoreCutoffStrings[] = {
    "100%",
    "50%",
    "20%",
    "10%",
    "5%",
    "2%",
    "1%",
    NULL
};

static Int2 AlnScoreCutoffValues [] = {
    100, 
    50,
    20, 
    10, 
    5, 
    2, 
    1, 
    0
};
*/


static CharPtr AlnScoreCutoffStrings[] = {
    "None",
    "40",
    "50",
    "60",
    "70",
    "80",
    "100",
    "200",
    "400",
    NULL
};

static Int2 AlnScoreCutoffValues [] = {
    -1,
    40,
    50,
    60,
    70,
    80,
    100,
    200,
    400,
    0
};

static CharPtr  LlocStrings [] = {
  "none",
  "clip",
  "cull",
  "inside",
  "above",
  "below",
  "left",
  "right",
  NULL
};

static LabelLocEnum LlocValues [] = {
  LabelNone,
  LabelAboveClip, /* above, but not wider than the feature*/
  LabelAboveCull, /* above, but only displayed iff wider than the feature */
  LabelInside,
  LabelAbove,
  LabelBelow,
  LabelLeft,
  LabelRight
};

static CharPtr  BoolStrings [] = {
  "yes",
  "true",
  "on",
  "no",
  "false",
  "off",
  NULL
};

static Boolean  BoolValues [] = {
  TRUE,
  TRUE,
  TRUE,
  FALSE,
  FALSE,
  FALSE
};

static CharPtr  RenderStrings [] = {
  "none",
  "line",
  "cappedline",
  "box",
  "outlinebox",
  NULL
};

static RenderAlgorithm RenderValues [] = {
  Do_Not_Render,
  Render_Line,
  Render_CappedLine,
  Render_Box,
  Render_OutlineBox
};

static CharPtr  GapStrings [] = {
  "none",
  "line",
  "angle",
  NULL
};

static GapEnum  GapValues [] = {
  NoGap,
  LineGap,
  AngleGap
};

static CharPtr GroupLabelLocations [] = {
  "above",
  "top",
  "left",
  "below",
  "none",
  NULL
};

static GroupLabelLocation GroupLabelLocationValues [] = {
  LabelOnTop,
  LabelOnTop,
  LabelOnSide,
  LabelOnBottom,
  NoLabel
};

static CharPtr BioseqFormat [] = {
  "accession",
  "accn",
  "fasta",
  "long",
  NULL
};

static Uint1 BioseqFormatValues [] = {
  PRINTID_TEXTID_ACC_VER,
  PRINTID_TEXTID_ACC_VER,
  PRINTID_FASTA_SHORT,
  PRINTID_FASTA_LONG
};

static CharPtr StrandStrings [] = {
  "both",
  "minus",
  "plus",
/* these could be added if people would find them useful. . .
   "-",
   "+",
*/
  NULL
};

static StrandChoice StrandValues [] = {
  BothStrands,
  MinusStrand,
  PlusStrand
};

static CharPtr ColorStrings [] = {
"black",    /*0,0,0*/
"blue",     /*0,0,255*/
"brown",    /*133,62,38*/
"coral",    /*255,127,80*/
"cyan",     /*0,255,255*/
"gray",     /*127,127,127*/
"green",    /*0,255,0*/
"grey",     /*127,127,127*/
"lavender", /*230,230,250*/
"magenta",  /*255,0,255*/
"maroon",   /*176,48,96*/
"orange",   /*255,165,0*/
"olive",    /*107,142,35*/
"pink",     /*255,192,203*/
"purple",   /*175,0,255*/
"red",      /*255,0,0*/
"white",    /*255,255,255*/
"yellow",   /*255,255,0*/
NULL
};

static Uint1 ColorValues[][3] = {
/*black*/    {0,   0,   0},
/*blue*/     {0,   0,   255},
/*brown*/    {133, 62,  38},
/*coral*/    {255, 127, 80},
/*cyan*/     {0,   255, 255},
/*gray*/     {127, 127, 127},
/*green*/    {0,   255, 0},
/*grey*/     {127, 127, 127},
/*lavender*/ {230, 230, 250},
/*magenta*/  {255, 0,   255},
/*maroon*/   {176, 48,  96},
/*orange*/   {255, 165, 0},
/*olive*/    {107, 142, 35},
/*pink*/     {255, 192, 203},
/*purple*/   {175, 0,   255},
/*red*/      {255, 0,   0},
/*white*/    {255, 255, 255},
/*yellow*/   {255, 255, 0}
};

static Char  config_filename [] = "asn2gph";

/*** Static function declarations ****/

static Int4 PixelsBetweenSeqCoords(Int4 left, Int4 right, Uint4 viewScale);
static Boolean IsInsertTic(RelevantFeatureItemPtr RFIP);
static void render_insert_tics(RenderInputPtr RIP);

/* functions for working with alignments */
/* perhaps some of these should be moved to the alignment manager. */
static Boolean SeqAlignContentLabel(SeqAlignPtr sap, SeqIdPtr notThisSID, CharPtr buf, Int4 buflen, Uint1 format);
AccumValue_t NormaliseScore(Int4 rawscore, Int4 min, Int4 max);
static Int4 WeightFromAlignScore(SeqAlignPtr sap, Uint1 scoreType);
static void FindCutoffScore(SeqAlignPtr sap, Int4 alignCnt, AlignmentFilterStatePtr afsp);
static void GatherAlignInfo(
  SeqAlignPtr sap, 
  Int4        alignCnt,
  SeqIdPtr    bioSeqId,
  AlignmentFilterStatePtr afsp
);
static Boolean AlignmentFilterStateInit(SeqAlignPtr sap, SeqIdPtr sid, AlignmentFilterStatePtr afsp, GraphicViewExtrasPtr extras);
static Boolean AlignmentFilterStateDone(AlignmentFilterStatePtr afsp);
static void AlignmentFilterStateFree( AlignmentFilterStatePtr afsp);

typedef struct align_seg_iterator {
  SeqAlignPtr sap;
  SeqIdPtr sip;
  
  Int4    nsegs;
  Int4    start, stop;  /* left and rightmost bioseq coords for this alignment. */
  Uint1   strand;   /* so we iterate the right direction */
  Int4    alignRow; /* from sip on non-stdseg aligns */
  Int4    currentSeg; /* for indexed aligns */
  StdSegPtr currentStdSeg;  /* for std seg aligns */
} AlignSegIterator, PNTR AlignSegIteratorPtr;

static Int4 AlignSegIteratorCreate(SeqAlignPtr sap, SeqIdPtr sip,  AlignSegIteratorPtr asi);
static Boolean AlignSegIteratorNext(AlignSegIteratorPtr asip, Int4Ptr start, Int4Ptr stop, Uint1Ptr strand, Uint1Ptr segType);


static Int1 StringIndexInStringList (CharPtr testString, CharPtr PNTR stringList) {

  Int1  i;

  if (testString == NULL || stringList == NULL) return -1;
  /*
  for (i = 0; stringList [i] != NULL; i++) {
    if (StringICmp (testString, stringList [i]) == 0) return i;
  }
  */
  i = 0;
  while (stringList [i] != NULL) {
    if (StringICmp (testString, stringList [i]) == 0) return i;
    i++;
  }
  return -1;
}

/* this parses fonts either in the format used by Vibrant's ParseFont, or allows "small" "meduim", etc. . . */
static FonT LocalParseFont (
  CharPtr FontSpec
)

{
  if (FontSpec == NULL) return NULL;
  if (StringICmp (FontSpec, "small") == 0) {
    return SetSmallFont ();
  } else if (StringICmp (FontSpec, "medium") == 0) {
    return SetMediumFont ();
  } else if (StringICmp (FontSpec, "large") == 0) {
    return SetLargeFont ();
  } else if (StringICmp (FontSpec, "system") == 0) {
    return systemFont;
  } else if (StringICmp (FontSpec, "program") == 0) {
    return programFont;
  } else {
    return ParseFont (FontSpec);
  }
}

static CharPtr ColorModifiers [] = {
"light",
"lt",
"dark",
"drk",
"dk",
NULL
};

/* COLOR must point to an array of Uint1 [3]; */
static Boolean ParseColor (
  CharPtr string,
  Uint1Ptr color
)

{
  unsigned  sscanfOffset, localColor [3] = { 0, 0, 0 }; /* "unsigned", to match %u and %n*/
  Uint1     offset = 0;
  Uint1     i;
  Boolean   isLight = FALSE, isDark = FALSE;
  Char      ch, modifierBuffer [8];
  CharPtr   tmp;


  if (string == NULL || color == NULL) return FALSE;

  /* first try to parse a human-readable color (ie, light blue)*/
  StringNCpy_0 (modifierBuffer, string, sizeof (modifierBuffer));
  /* truncate at space */
  tmp = modifierBuffer;
  ch = *tmp;
  while (ch != '\0' && ch != ' ') {
    tmp++;
    ch = *tmp;
  }
  *tmp = '\0';

  i = StringIndexInStringList (modifierBuffer, ColorModifiers);
  if (i > 0 && i < DIM (ColorModifiers)) {
    switch (i) {
      case 1 :
      case 2 :
        isLight = TRUE;
        offset = StringLen (modifierBuffer);
        break;
      case 3 :
      case 4 :
      case 5 :
        isDark = TRUE;
        offset = StringLen (modifierBuffer);
        break;
      default :
        break;
    }
  }
  while (string[offset] != '\0' && (! IS_ALPHA (string[offset]))) {
    offset ++;
  }

  i = StringIndexInStringList (string + offset, ColorStrings);
  if (i > 0 && i < DIM (ColorValues)) {
    color [0] = ColorValues [i] [0];
    color [1] = ColorValues [i] [1];
    color [2] = ColorValues [i] [2];
    if (isLight) {
      color [0] = MIN (((3 * color [0]) / 2), 255);
      color [1] = MIN (((3 * color [1]) / 2), 255);
      color [2] = MIN (((3 * color [2]) / 2), 255);
    } else if (isDark) {
      color [0] = (2 * color [0]) / 3;
      color [1] = (2 * color [1]) / 3;
      color [2] = (2 * color [2]) / 3;
    }
  } else {
    offset = 0;
    for (i = 0; i < 3; i++) {
      for (; string[offset] != '\0' && (! IS_DIGIT (string [offset])); offset++) continue;
      if (string [offset] == '\0') return FALSE;
      if (sscanf (string + offset, "%u%n", localColor + i, &sscanfOffset) == 0)  return FALSE;
      offset += sscanfOffset;
    }
    color [0] = localColor [0];
    color [1] = localColor [1];
    color [2] = localColor [2];
  }
  return TRUE;
}


NLM_EXTERN FilterPtr FindFilterByName (
  CharPtr name,
  ViewerConfigsPtr VCP
)

{
  Int1  i;

  if (VCP == NULL || StringHasNoText (name) || (! VCP->ArraysPopulated)) return NULL;
  i = StringIndexInStringList (name, VCP->FilterNameArray);
  if (i < VCP->FilterCount && i >= 0) return (VCP->FilterArray[i]);
  return NULL;
}

NLM_EXTERN AppearancePtr FindAppearanceByName (
  CharPtr name,
  ViewerConfigsPtr VCP
)

{
  Int1  i;

  if (VCP == NULL || StringHasNoText (name) || (! VCP->ArraysPopulated)) return NULL;
  i = StringIndexInStringList (name, VCP->AppearanceNameArray);
  if (i < VCP->AppearanceCount && i>= 0) return (VCP->AppearanceArray[i]);
  return NULL;
}

NLM_EXTERN LayoutAlgorithm FindLayoutByName (
  CharPtr name
)

{
  Int1  i;

  if (StringHasNoText (name)) return Layout_Inherit;
  i = StringIndexInStringList (name, LayoutStrings);
  if (i >= 0 && i < DIM (LayoutValues)) {
    return LayoutValues [i];
  }
  return Layout_Inherit;
}

static FilterPtr FindFilterByName_T (
  CharPtr name,
  ViewerConfigsPtr VCP
)

{
  ValNodePtr  nameVNP, filtVNP;

  if (VCP == NULL || StringHasNoText (name)) return NULL;
  for (nameVNP = VCP->FilterNameList, filtVNP = VCP->FilterList;
       nameVNP != NULL && filtVNP != NULL;
       nameVNP = nameVNP->next, filtVNP = filtVNP->next) {
    if (nameVNP->data.ptrvalue != NULL &&
        StringICmp (name, nameVNP->data.ptrvalue) == 0) {
      return ((FilterPtr) filtVNP->data.ptrvalue);
    }
  }
  return NULL;
}

static AppearancePtr FindAppearanceByName_T (
  CharPtr name,
  ViewerConfigsPtr VCP
)

{
  ValNodePtr  nameVNP, appVNP;

  if (VCP == NULL || StringHasNoText (name)) return NULL;
  for (nameVNP = VCP->AppearanceNameList, appVNP = VCP->AppearanceList;
       nameVNP != NULL && appVNP != NULL;
       nameVNP = nameVNP->next, appVNP = appVNP->next) {
    if (nameVNP->data.ptrvalue != NULL &&
        StringICmp (name, nameVNP->data.ptrvalue) == 0) {
      return ((AppearancePtr) appVNP->data.ptrvalue);
    }
  }
  return NULL;
}

static CharPtr FindFeatStrFromFeatDefType (Uint1 type)
{
  CharPtr featName;

  featName = FindKeyFromFeatDefType (type, FALSE);
  /* handle locally defined feature types. */
  if (type > FEATDEF_MAX)
  {
    switch (type) {
    case APPEARANCEITEM_Alignment:
      featName = "align";
      break;
    case APPEARANCEITEM_Segment:
      featName = "segment";
      break;
    case APPEARANCEITEM_Graph:
      featName = "graph";
      break;
    }
  }
  return featName;
}


NLM_EXTERN AppearancePtr CreateAppearance (
  CharPtr newname,
  ViewerConfigsPtr VCP
)

{
  AppearancePtr   AP;

  if (VCP == NULL || StringHasNoText (newname)) return NULL;
  if (FindAppearanceByName_T (newname, VCP) != NULL) return NULL;  /* don't allow duplicate names */
  AP = (AppearancePtr) MemNew (sizeof (Appearance));
  if (AP == NULL) return NULL;
  AP->name = StringSave (newname);
  VCP->AppearanceCount++;
  ValNodeAddPointer (&VCP->AppearanceList, VCP->AppearanceCount, AP);
  ValNodeAddPointer (&VCP->AppearanceNameList, VCP->AppearanceCount, AP->name);
  return AP;
}

static BioseqAppearanceItemPtr ParseBioseqAppearanceItem (
  CharPtr sect,
  ViewerConfigsPtr VCP
)

{
  Char                     buf [128];
  BioseqAppearanceItemPtr  bioseqAIP;
  Int2                     i;
  unsigned                 val; /* "unsigned" to match sscanf("%ud")*/

  bioseqAIP = MemNew (sizeof (BioseqAppearanceItem));
  if (bioseqAIP == NULL) return NULL;

  bioseqAIP->labelLoc = GroupLabelLocationValues [0];
  if (GetAppParam (config_filename, sect, "label", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, GroupLabelLocations);
    if (i >= 0 && i < DIM (GroupLabelLocationValues)) {
      bioseqAIP->labelLoc = GroupLabelLocationValues  [i];
    }
  }

  bioseqAIP->drawScale = TRUE;
  if (GetAppParam (config_filename, sect, "scale", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, BoolStrings);
    if (i >= 0 && i < DIM (BoolValues)) {
      bioseqAIP->drawScale = BoolValues [i];
    }
  }

  if (GetAppParam (config_filename, sect, "labelfont", NULL, buf, sizeof (buf))) {
    bioseqAIP->labelFont = LocalParseFont (buf);
  }
  if (bioseqAIP->labelFont == NULL) {
    bioseqAIP->labelFont = systemFont;
  }

  if (GetAppParam (config_filename, sect, "scalefont", NULL, buf, sizeof (buf))) {
    bioseqAIP->scaleFont = LocalParseFont (buf);
  }
  if (bioseqAIP->scaleFont == NULL) {
    bioseqAIP->scaleFont = SetSmallFont ();
  }

  if (GetAppParam (config_filename, sect, "height", NULL, buf, sizeof (buf))) {
    if (buf != NULL) {
      sscanf (buf, "%ud", &val);
      bioseqAIP->height = MIN (val, 16);
    }
  }
  if (bioseqAIP->height == 0) {
    bioseqAIP->height = 10;
  }

  if (GetAppParam (config_filename, sect, "scaleheight", NULL, buf, sizeof (buf))) {
    if (buf != NULL) {
      sscanf (buf, "%ud", &val);
      bioseqAIP->scaleHeight = MIN (val, 16);
    }
  }
  if (bioseqAIP->scaleHeight == 0) {
    bioseqAIP->scaleHeight = 10;
  }

  if (GetAppParam (config_filename, sect, "color", NULL, buf, sizeof (buf))) {
    ParseColor (buf, bioseqAIP->bioseqColor);
  }
  if (GetAppParam (config_filename, sect, "labelcolor", NULL, buf, sizeof (buf))) {
    ParseColor (buf, bioseqAIP->labelColor);
  }
  if (GetAppParam (config_filename, sect, "scalecolor", NULL, buf, sizeof (buf))) {
    ParseColor (buf, bioseqAIP->scaleColor);
  }

  bioseqAIP->format = BioseqFormatValues [0];
  if (GetAppParam (config_filename, sect, "format", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, BioseqFormat);
    if (i >= 0 && i < DIM (BioseqFormatValues)) {
      bioseqAIP->format = BioseqFormatValues  [i];
    }
  }

  return bioseqAIP;
}

static AppearanceItemPtr ParseFeatureAppearanceItem (
  CharPtr sect,
  AppearanceItemPtr inheritFromMe,
  Boolean recursing,
  ViewerConfigsPtr VCP
)

{
  Char               buf [128];
  AppearanceItemPtr  newAIP;
  Int2               i;
  Boolean            changed = FALSE;
  unsigned           val; /* "unsigned" to match sscanf("%ud")*/
  AppearanceItemPtr  namedAIP;

  if (! recursing) {
    if (GetAppParam (config_filename, sect, "usenamedstyle", NULL, buf, sizeof (buf))) {
      namedAIP = ParseFeatureAppearanceItem (buf, inheritFromMe, TRUE, VCP);
      if (namedAIP != NULL) {
        inheritFromMe = namedAIP;
        changed = TRUE; /* !!! this will use more memory than necessary */
      }
    }
  }
  newAIP = MemNew (sizeof (AppearanceItem));
  if (newAIP == NULL) return NULL;
  MemCopy (newAIP, inheritFromMe, sizeof (AppearanceItem));
  if (GetAppParam (config_filename, sect, "color", NULL, buf, sizeof (buf))) {
    changed = ParseColor (buf, newAIP->Color);
  }
  if (GetAppParam (config_filename, sect, "labelcolor", NULL, buf, sizeof (buf))) {
    changed = ParseColor (buf, newAIP->LabelColor);
  }

  newAIP->LabelLoc = LabelAbove;
  if (GetAppParam (config_filename, sect, "label", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, LlocStrings);
    if (i >= 0 && i < DIM (LlocValues)) {
      newAIP->LabelLoc = LlocValues [i];
    }
  }
  if (GetAppParam (config_filename, sect, "displaywith", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, RenderStrings);
    if (i >= 0 && i < DIM (RenderValues)) {
      newAIP->RenderChoice = RenderValues [i];
      changed = TRUE;
    }
  }
  if (GetAppParam (config_filename, sect, "showarrow", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, BoolStrings);
    if (i >= 0 && i < DIM (BoolValues)) {
      newAIP->ShowArrow = BoolValues [i];
      changed = TRUE;
    }
  }
  if (GetAppParam (config_filename, sect, "gap", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, GapStrings);
    if (i >= 0 && i < DIM (RenderValues)) {
      newAIP->GapChoice = GapValues [i];
      changed = TRUE;
    }
  }
  if (GetAppParam (config_filename, sect, "showtype", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, BoolStrings);
    if (i >= 0 && i < DIM (BoolValues)) {
      newAIP->AddTypeToLabel = BoolValues [i];
    }
  }
  if (GetAppParam (config_filename, sect, "showcontent", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, BoolStrings);
    if (i >= 0 && i < DIM (BoolValues)) {
      newAIP->AddDescToLabel = BoolValues [i];
    }
  }
  if (GetAppParam (config_filename, sect, "height", NULL, buf, sizeof (buf))) {
    if (buf != NULL) {
      sscanf (buf, "%ud", &val);
      newAIP->Height = MIN (val, 16);
      changed = TRUE;
    }
  }
  if (GetAppParam (config_filename, sect, "labelfont", NULL, buf, sizeof (buf))) {
    newAIP->LabelFont = LocalParseFont (buf);
  }
  if (newAIP->LabelFont == NULL) {
    newAIP->LabelFont = programFont;
  }
  if (newAIP->LabelFont != inheritFromMe->LabelFont) {
    changed = TRUE;
  }
  
  /* this is only meaningful for alignment styles to change the appearance of the alignment's label. */
  newAIP->format = BioseqFormatValues [0];
  if (GetAppParam (config_filename, sect, "format", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, BioseqFormat);
    if (i >= 0 && i < DIM (BioseqFormatValues)) {
      newAIP->format = BioseqFormatValues  [i];
    }
  }


  if (! changed) {
    MemFree (newAIP);
    return NULL;
  }
  return newAIP;
}

static AppearancePtr ParseAppearance (
  CharPtr appearanceNameInFile,
  ViewerConfigsPtr VCP
)

{
  AppearancePtr      AP;
  AppearanceItemPtr  AIP, impAIP, newAIP;
  Char               buf [128];
  Char               sect [128];
  Char               outputBuffer [128];
  AppearanceItem     DefaultAppearanceItem = {
    {0, 0, 0}, {64, 64, 64}, Render_Box, 0, 5, 0, FALSE, LineGap, TRUE, TRUE, NULL, LabelAbove
  };
  Int1               i;
  unsigned           val;

  if (appearanceNameInFile == NULL) return NULL;
  DefaultAppearanceItem.LabelFont = programFont;
  sprintf (sect, "%s.master", appearanceNameInFile);
  /* require all styles to have a name, since high-level interface uses the name to identify Filters */
  if (! GetAppParam (config_filename, sect, "name", NULL, buf, sizeof (buf))) return NULL;
  if (StringHasNoText (buf)) return NULL;
  AP = CreateAppearance (buf, VCP);
  if (AP == NULL) return NULL;
  AIP = ParseFeatureAppearanceItem (sect, &DefaultAppearanceItem, FALSE, VCP); /*parse xyz.master */
  if (AIP == NULL) {            /* require a "master" style */
    DestroyAppearance (AP, VCP);
    return NULL;
  }
  val = VCP->DefaultMaxScaleForArrow;
  if (GetAppParam (config_filename, sect, "maxarrowscale", NULL, buf, sizeof (buf))) {
    sscanf (buf, "%ud", &val);
  }
  AP->MaxScaleForArrow = val;
  val = VCP->DefaultMinPixelsForArrow;
  if (GetAppParam (config_filename, sect, "minarrowpixels", NULL, buf, sizeof (buf))) {
    sscanf (buf, "%ud", &val);
  }
  AP->MinPixelsForArrow = val;
  AP->ShadeSmears = VCP->DefaultShadeSmears;
  if (GetAppParam (config_filename, sect, "shadesmears", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, BoolStrings);
    if (i >= 0 && i < DIM (BoolValues)) {
      AP->ShadeSmears = BoolValues [i];
    }
  }

  /* group box settings */
  if (GetAppParam (config_filename, sect, "groupboxcolor", NULL, buf, sizeof (buf))) {
    ParseColor (buf, AP->GroupBoxColor);
  }

  if (GetAppParam (config_filename, sect, "grouplabelfont", NULL, buf, sizeof (buf))) {
    AP->GroupLabelFont = LocalParseFont (buf);
    if (AP->GroupLabelFont == NULL) {
      AP->GroupLabelFont = programFont;
    }
  }
  if (GetAppParam (config_filename, sect, "grouplabelcolor", NULL, buf, sizeof (buf))) {
    ParseColor (buf, AP->GroupLabelColor);
  }

  /* Named Annotation Style settings */
  if (GetAppParam (config_filename, sect, "annotboxcolor", NULL, buf, sizeof (buf))) {
    ParseColor (buf, AP->AnnotBoxColor);
  }

  if (GetAppParam (config_filename, sect, "annotlabelfont", NULL, buf, sizeof (buf))) {
    AP->AnnotLabelFont = LocalParseFont (buf);
    if (AP->AnnotLabelFont == NULL) {
      AP->AnnotLabelFont = programFont;
    }
  }
  if (GetAppParam (config_filename, sect, "annotlabelcolor", NULL, buf, sizeof (buf))) {
    ParseColor (buf, AP->AnnotLabelColor);
  }


  sprintf (outputBuffer, "%s.bioseq", appearanceNameInFile);
  AP->bioseqAIP = ParseBioseqAppearanceItem (outputBuffer, VCP);
  sprintf (outputBuffer, "%s.imp", appearanceNameInFile);
  impAIP = ParseFeatureAppearanceItem (outputBuffer, AIP, FALSE, VCP);
  if (impAIP == NULL) {
    sprintf (outputBuffer, "%s.import", appearanceNameInFile);
    impAIP = ParseFeatureAppearanceItem (outputBuffer, AIP, FALSE, VCP);
  }
  if (impAIP == NULL) {
    impAIP = AIP;
  } else {
    AddAppearanceItemToAppearance (impAIP, AP, FEATDEF_IMP, VCP);
  }
  for (i = 1; i < APPEARANCEITEM_MAX; i++) {
    if (i == FEATDEF_IMP) continue;
    sprintf (outputBuffer, "%s.%s", appearanceNameInFile, FindFeatStrFromFeatDefType (i));
    if (i >= FEATDEF_allele && i <= FEATDEF_35_signal) {        /* is it an imp-feat ? */
      newAIP = ParseFeatureAppearanceItem (outputBuffer, impAIP, FALSE, VCP);
      newAIP = newAIP ? newAIP : impAIP;
    } else {
      newAIP = ParseFeatureAppearanceItem (outputBuffer, AIP, FALSE, VCP);
      newAIP = newAIP ? newAIP : AIP;
    }
    if (newAIP != NULL) {
      AddAppearanceItemToAppearance (newAIP, AP, i, VCP);
    }
  }
  AddAppearanceItemToAppearance (AIP, AP, FEATDEF_BAD, VCP);
  return AP;
}

NLM_EXTERN FilterPtr CreateFilter (
  CharPtr name,
  ViewerConfigsPtr VCP
)

{
  FilterPtr  FP;

  if (VCP == NULL || StringHasNoText (name)) return NULL;
  if (FindFilterByName_T (name, VCP) != NULL) return NULL;  /* don't allow duplicate names */
  FP = MemNew (sizeof (Filter));
  if (FP == NULL) return FP;
  FP->name = StringSave (name);
  VCP->FilterCount++;
  ValNodeAddPointer (&VCP->FilterList, VCP->FilterCount, FP);
  ValNodeAddPointer (&VCP->FilterNameList, VCP->FilterCount, FP->name);
  return FP;
}

static void ChangeFeatureInFilterItem (
  FilterItemPtr FIP,
  Uint1 newFeatdef,
  Boolean includeMe,
  ViewerConfigsPtr VCP
)

{
  Uint1  i;
  Uint1  order = 0;
  Uint1  orderIncrement = 0;

  if (FIP == NULL) return;

  if (includeMe) {
    orderIncrement = 1;
    for (i = 0; i < APPEARANCEITEM_MAX; i++) {
      order = MAX (order, FIP->IncludeFeature [i]);
    }
    order++; /* the lowest available order index */
  }

  if (newFeatdef == FEATDEF_ANY) {
    for (i = 1; i < APPEARANCEITEM_MAX; i++) {  /* start at 1 since we do not want to ever include FEATDEF_BAD */
      FIP->IncludeFeature [i] = order;
      order += orderIncrement;
    }
  } else if (newFeatdef == FEATDEF_ANY_RNA) {
    for (i = FEATDEF_preRNA; i <= FEATDEF_otherRNA; i++) {
      FIP->IncludeFeature [i] = order;
      order += orderIncrement;
    }
    FIP->IncludeFeature [FEATDEF_misc_RNA] = order;
    order += orderIncrement;
    FIP->IncludeFeature [FEATDEF_precursor_RNA] = order;
    order += orderIncrement;
    FIP->IncludeFeature [FEATDEF_snoRNA] = order;
  } else if (newFeatdef == FEATDEF_ANY_PROT) {
    FIP->IncludeFeature [FEATDEF_PROT] = order;
    order += orderIncrement;
    for (i = FEATDEF_preprotein; i <= FEATDEF_transit_peptide_aa; i++) {
      FIP->IncludeFeature [i] = order;
      order += orderIncrement;
    }
  } else if (newFeatdef == FEATDEF_IMP) {
    for (i = FEATDEF_allele; i <= FEATDEF_35_signal; i++) {
      FIP->IncludeFeature [i] = order;
      order += orderIncrement;
    }
  } else if (newFeatdef < APPEARANCEITEM_MAX) {
    FIP->IncludeFeature [newFeatdef] = order;
  }
}

NLM_EXTERN void AddFeatureToFilterItem (
  FilterItemPtr FIP,
  Uint1 newFeatdef,
  ViewerConfigsPtr VCP
)

{
  ChangeFeatureInFilterItem (FIP, newFeatdef, TRUE, VCP);
}

NLM_EXTERN void RemoveFeatureFromFilterItem (
  FilterItemPtr FIP,
  Uint1 newFeatdef,
  ViewerConfigsPtr VCP
)

{
  ChangeFeatureInFilterItem (FIP, newFeatdef, FALSE, VCP);
}

static void AddFilterItemToFilter (
 FilterItemPtr newFIP,
  FilterPtr parent,
  ViewerConfigsPtr VCP
)

{
  ValNodePtr  newVNP, lastVNP;

  for (lastVNP = parent->FilterItemList;
       lastVNP != NULL && lastVNP->next != NULL;
       lastVNP = lastVNP->next) continue;
  newVNP = ValNodeAdd (&parent->FilterItemList);
  newVNP->data.ptrvalue = newFIP;
}

NLM_EXTERN FilterItemPtr CreateNewFilterItemInFilter (
  CharPtr name,
  FilterPtr parent,
  ViewerConfigsPtr VCP
)

{
  FilterItemPtr  FIP;

  FIP = MemNew (sizeof (FilterItem));
  if (FIP == NULL) return FIP;
  FIP->GroupLabel = StringSaveNoNull (name);
  AddFilterItemToFilter (FIP, parent, VCP);
  return FIP;
}

static CharPtr SpecialFeatures [] = {
"everything",
"all",
"every",
"any",
"imp",
"rna",
"prot",
"bioseq",
"graph",
"align",
NULL
};

static FilterItemPtr ParseFilterItem (
  CharPtr filterItemName,
  Uint2 defaultRowPadding,
  Uint2 defaultGroupPadding,
  LayoutAlgorithm defaultLayout,
  ViewerConfigsPtr VCP
)

{
  Char           sect [128];
  Char           featureNum [128];
  Char           buf [128];
  Uint4          featdeftype;
  Uint4          featureCount = 0;
  FilterItemPtr  FIP;
  Int2           i, j;
  unsigned       val;

  FIP = MemNew (sizeof (FilterItem));
  if (FIP == NULL) return FIP;
  FIP->DrawScale = TristateUnset;
  FIP->Type = FeatureFilter; /* this will get changed if a graph or alignment is discovered instead */
  sprintf (sect, "filters.%s", filterItemName);
  GetAppParam (config_filename, sect, "layout", "inherit", buf, sizeof (buf));
  i = StringIndexInStringList (buf, LayoutStrings);
  if (i >= 0 && i < DIM (LayoutStrings)) {
    FIP->LayoutChoice = LayoutValues [i];
  } else {
    FIP->LayoutChoice = defaultLayout;
  }

  FIP->GroupPadding = defaultGroupPadding;
  if (GetAppParam (config_filename, sect, "grouppadding", NULL, buf, sizeof (buf))) {
    sscanf (buf, "%ud", &val);
    val = MIN (val, 100);
    FIP->GroupPadding = val;
  }

  FIP->IntraRowPaddingPixels = defaultRowPadding;
  if (GetAppParam (config_filename, sect, "rowpadding", NULL, buf, sizeof (buf))) {
    sscanf (buf, "%ud", &val);
    val = MIN (val, 100);
    FIP->IntraRowPaddingPixels = val;
  }
  FIP->DrawGroupBox = FALSE;
  FIP->FillGroupBox = FALSE;
  if (GetAppParam (config_filename, sect, "groupbox", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, BoolStrings);
    if (i >= 0 && i < DIM (BoolValues) && i >= 0) {
      FIP->DrawGroupBox = BoolValues [i];
    }
  }
  if (FIP->DrawGroupBox) {
    if (GetAppParam (config_filename, sect, "groupboxcolor", NULL, buf, sizeof (buf))) {
      FIP->GroupBoxColorSet = TRUE;
      ParseColor (buf, FIP->GroupBoxColor);
    }
    if (GetAppParam (config_filename, sect, "fillbox", NULL, buf, sizeof (buf))) {
      i = StringIndexInStringList (buf, BoolStrings);
      if (i >= 0 && i < DIM (BoolValues)) {
        FIP->FillGroupBox = BoolValues[i];
      }
    }
  }

  FIP->GroupLabel = NoLabel;
  FIP->GroupLabelFont = programFont;
  if (GetAppParam (config_filename, sect, "name", NULL, buf, sizeof (buf))) {
    FIP->GroupLabel = StringSaveNoNull (buf);
    FIP->GroupLabelLoc = LabelOnTop;
    if (GetAppParam (config_filename, sect, "grouplabel", NULL, buf, sizeof (buf))) {
      i = StringIndexInStringList (buf, GroupLabelLocations);
      if (i >= 0 && i < DIM (GroupLabelLocationValues)) {
        FIP->GroupLabelLoc = GroupLabelLocationValues[i];
      }
    }
    if (GetAppParam (config_filename, sect, "grouplabelfont", NULL, buf, sizeof (buf))) {
      FIP->GroupLabelFontSet = TRUE;
      FIP->GroupLabelFont = LocalParseFont (buf);
      if (FIP->GroupLabelFont == NULL) {
        FIP->GroupLabelFont = programFont;
      }
    }
    if (GetAppParam (config_filename, sect, "grouplabelcolor", NULL, buf, sizeof (buf))) {
      FIP->GroupLabelColorSet = TRUE;
      ParseColor (buf, FIP->GroupLabelColor);
    }
  }

  FIP->LabelLoc = LabelAbove;
  if (GetAppParam (config_filename, sect, "label", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, LlocStrings);
    if (i >= 0 && i < DIM (LlocValues)) {
      FIP->LabelLoc = LlocValues [i];
    }
  }

  FIP->AddTypeToLabel = TristateUnset;
  if (FIP->LabelLoc != LabelNone && GetAppParam (config_filename, sect, "showtype", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, BoolStrings);
    if (i >= 0 && i < DIM (BoolValues)) {
      FIP->AddTypeToLabel = BOOL_TO_TRISTATE (BoolValues [i]);
    }
  }
  FIP->AddDescToLabel = TristateUnset;
  if (FIP->LabelLoc != LabelNone && GetAppParam (config_filename, sect, "showcontent", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, BoolStrings);
    if (i >= 0 && i < DIM (BoolValues)) {
      FIP->AddDescToLabel = BOOL_TO_TRISTATE (BoolValues [i]);
    }
  }

  FIP->MatchStrand = StrandValues [0];
  if (GetAppParam (config_filename, sect, "strand", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, StrandStrings);
    if (i >= 0 && i < DIM (StrandValues)) {
      FIP->MatchStrand = StrandValues [i];
    }
  }
  for (i = 1; i < APPEARANCEITEM_MAX; i++) {
    sprintf (featureNum, "feature%d", (unsigned) i);
    if (GetAppParam (config_filename, sect, featureNum, NULL, buf, sizeof (buf))) {
      featdeftype = FindFeatDefTypeFromKey (buf);
      if (featdeftype == FEATDEF_BAD) {
        /* special-case checks for types of features not found by FindFeatDefTypeFromKey () */
        j = StringIndexInStringList (buf, SpecialFeatures);
        /*
        if (j >= 0 && j < DIM (SpecialFeatures)) {
          switch (j) {
            case 1 :
            case 2 :
            case 3 :
            case 4 :
              featdeftype = FEATDEF_ANY;
              break;
            case 5 :
              featdeftype = FEATDEF_IMP;
              break;
            case 6 :
              featdeftype = FEATDEF_ANY_RNA;
              break;
            case 7 :
              featdeftype = FEATDEF_ANY_PROT;
              break;
            case 8 :
              FIP->Type = BioseqFilter;
              break;
            case 9 :
              FIP->Type = GraphFilter;
              break;
            case 10 :
              FIP->Type = AlignmentFilter;
              break;
            default :
              break;
          }
        } else continue; */
        /* insert special-case checks for types of features not found by FindFeatDefTypeFromKey () here */
        if (StringICmp (buf, "everything") == 0 ||
            StringICmp (buf, "all") == 0 ||
            StringICmp (buf, "every") == 0 ||
            StringICmp (buf, "any") == 0) {
          featdeftype = FEATDEF_ANY;
        } else if (StringICmp (buf, "imp") == 0) {
          featdeftype = FEATDEF_IMP; /* FindFeatDefTypeFromKey matches 'import', but not 'imp' */
        } else if (StringICmp (buf, "rna") == 0) {
          featdeftype = FEATDEF_ANY_RNA;
        } else if (StringICmp (buf, "prot") == 0) {
          featdeftype = FEATDEF_ANY_PROT;
        } else if (StringICmp (buf, "bioseq") == 0) {
          FIP->Type = BioseqFilter;
        } else if (StringICmp (buf, "graph") == 0) {
          featdeftype = APPEARANCEITEM_Graph;
          FIP->Type = GraphFilter;
        } else if (StringICmp (buf, "align") == 0) {
          featdeftype = APPEARANCEITEM_Alignment;
          FIP->Type = AlignmentFilter;
        } else continue; /* failed to find a match */
      }
      AddFeatureToFilterItem (FIP, featdeftype, VCP);
      featureCount++;
    }
  }
  if (FIP->Type == BioseqFilter) {
    FIP->DrawScale = TristateUnset;
    if (GetAppParam (config_filename, sect, "scale", NULL, buf, sizeof (buf))) {
      i = StringIndexInStringList (buf, BoolStrings);
      if (i >= 0 && i < DIM (BoolValues)) {
        FIP->DrawScale = BOOL_TO_TRISTATE (BoolValues [i]);
      }
    }
  }
  if (featureCount == 0) {
    MemFree (FIP);
    return NULL;
  }
  return FIP;
}

static FilterPtr ParseFilter (
  CharPtr filterNameInFile,
  ViewerConfigsPtr VCP
)

{

  FilterPtr       FP;
  FilterItemPtr   FIP;
  Int2            i;
  Uint1           filterItemCount = 0;
  Char            buf [128];     /* for input *from* GetAppParam */
  Char            outputBuffer [128];    /* paramater *to* GetAppParam */
  Char            sect [128];
  Boolean         foundBioseqFilter = FALSE;
  Boolean         foundGraphFilter = FALSE;
  Boolean         foundAlignmentFilter = FALSE;
  ValNodePtr      VNP;
  Boolean         createImplicitBioseq = TRUE;
  Boolean         createImplicitGraphs = TRUE;
  unsigned        val; /* to match sscanf ("%d"...)*/
  Uint2           defaultRowPadding;
  Uint2           defaultGroupPadding;
  LayoutAlgorithm defaultLayout;

  if (filterNameInFile == NULL) return NULL;
  sprintf (sect, "%s", filterNameInFile);
  /* require all styles to have a name, since high-level interface uses the name to identify Filters */
  if (! GetAppParam (config_filename, sect, "name", NULL, buf, sizeof (buf))) return NULL;
  FP = CreateFilter (buf, VCP); /* Createfilter will check for duplucate names */
  if (FP == NULL) return FP;
  val = VCP->DefaultMaxScaleWithLabels;
  if (GetAppParam (config_filename, sect, "maxlabelscale", NULL, buf, sizeof (buf))) {
    sscanf (buf, "%ud", &val);
  }
  FP->MaxScaleWithLabels = val;
  
  /* Group by Named Annotation stuff */
  FP->AnnotBoxColorSet = FALSE;
  FP->AnnotLabelFontSet = FALSE;
  FP->AnnotLabelColorSet = FALSE;
  
  FP->GroupByAnnot = TRUE;
  if (GetAppParam (config_filename, sect, "annotgroup", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, BoolStrings);
    if (i >= 0 && i < DIM (BoolStrings)) {
      FP->GroupByAnnot =  (BoolValues [i]);
    }
  }
  if (FP->GroupByAnnot) {
    FP->DrawAnnotBox = TRUE;
    if (GetAppParam (config_filename, sect, "annotbox", NULL, buf, sizeof (buf))) {
      i = StringIndexInStringList (buf, BoolStrings);
      if (i >= 0 && i < DIM (BoolStrings)) {
        FP->DrawAnnotBox =  (BoolValues [i]);
      }
    }
    if (FP->DrawAnnotBox) {
      if (GetAppParam (config_filename, sect, "annotboxcolor", NULL, buf, sizeof (buf))) {
        FP->AnnotBoxColorSet = TRUE;
        ParseColor (buf, FP->AnnotBoxColor);
      }
    }
    FP->AnnotLabelLoc = LabelOnTop;
    if (GetAppParam (config_filename, sect, "annotlabel", NULL, buf, sizeof (buf))) {
      i = StringIndexInStringList (buf, GroupLabelLocations);
      if (i >= 0 && i < DIM (GroupLabelLocationValues)) {
        FP->AnnotLabelLoc = GroupLabelLocationValues[i];
      }
    }
    if (FP->AnnotLabelLoc != NoLabel) {
      FP->AnnotLabelFont = programFont;
      if (GetAppParam (config_filename, sect, "annotlabelfont", NULL, buf, sizeof (buf))) {
        FP->AnnotLabelFont = LocalParseFont (buf);
        if (FP->AnnotLabelFont == NULL) {
          FP->AnnotLabelFont = programFont;
        } else {
          FP->AnnotLabelFontSet = TRUE;
        }
      }
      if (GetAppParam (config_filename, sect, "annotlabelcolor", NULL, buf, sizeof (buf))) {
        FP->AnnotLabelColorSet = TRUE;
        ParseColor (buf, FP->AnnotLabelColor);
      }
    }
  }
  
  /* other default values */
  GetAppParam (config_filename, sect, "layout", NULL, buf, sizeof (buf));
  i = StringIndexInStringList (buf, LayoutStrings);
  if (i >= 0 && i < DIM (LayoutValues)) {
    defaultLayout = LayoutValues [i];
  } else {
    defaultLayout = Layout_Inherit;
  }

  val = VCP->DefaultGroupPadding;
  if (GetAppParam (config_filename, sect, "grouppadding", NULL, buf, sizeof (buf))) {
    sscanf (buf, "%ud", &val);
    val = MIN (val, 100);
  }
  defaultGroupPadding = val;

  val = VCP->DefaultRowPadding;
  if (GetAppParam (config_filename, sect, "rowpadding", NULL, buf, sizeof (buf))) {
    sscanf (buf, "%ud", &val);
  }
  defaultRowPadding = val;

  if (GetAppParam (config_filename, sect, "suppressbioseq", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, BoolStrings);
    if (i >= 0 && i < DIM (BoolStrings)) {
      createImplicitBioseq = ! (BoolValues [i]);
    }
  }
  if (GetAppParam (config_filename, sect, "suppressgraphs", NULL, buf, sizeof (buf))) {
    i = StringIndexInStringList (buf, BoolStrings);
    if (i >= 0 && i < DIM (BoolStrings)) {
      createImplicitGraphs = ! (BoolValues [i]);
    }
  }

  for (i = 1; i < APPEARANCEITEM_MAX; i++) {
    sprintf (outputBuffer, "%s%d", "group", (unsigned) i);
    if (GetAppParam (config_filename, sect, outputBuffer, NULL, buf, sizeof (buf))) {
      FIP = ParseFilterItem (buf, defaultRowPadding, defaultGroupPadding, defaultLayout, VCP);
      if (FIP == NULL) continue;
      if (FIP->Type == BioseqFilter) {
        foundBioseqFilter = TRUE;
      }
      if (FIP->Type == GraphFilter) {
        foundGraphFilter = TRUE;
      }
      if (FIP->Type == AlignmentFilter) {
        foundAlignmentFilter = TRUE;
      }
      AddFilterItemToFilter (FIP, FP, VCP);
      filterItemCount++;
    }
  }
  if (filterItemCount == 0) {
    DestroyFilter (FP, VCP);
    return NULL;
  }

  if (createImplicitBioseq && ! foundBioseqFilter) {
    VNP = MemNew (sizeof (ValNode));
    FIP = MemNew (sizeof (FilterItem));
    if (VNP == NULL || FIP == NULL) {
      DestroyFilter (FP, VCP);
      return NULL;
    }
    /* insert a Bioseq filter at the head of the list */
    VNP->next = FP->FilterItemList;
    VNP->data.ptrvalue = FIP;
    FP->FilterItemList = VNP;

    FIP->Type = BioseqFilter;
    FIP->IntraRowPaddingPixels = defaultRowPadding;
  }

  if (createImplicitGraphs && ! foundAlignmentFilter) {
    /* insert an alignment filter at the_end of the list */
    FIP = MemNew (sizeof (FilterItem));
    VNP = ValNodeAddPointer (&FP->FilterItemList, 0, FIP);
    if (FIP == NULL || VNP == NULL ) {
      DestroyFilter (FP, VCP);
      return NULL;
    }
    FIP->Type = AlignmentFilter;
    FIP->LayoutChoice = defaultLayout;
    FIP->GroupPadding = defaultGroupPadding;
    FIP->IntraRowPaddingPixels = defaultRowPadding;
    FIP->LabelLoc = LabelAbove;
    FIP->MatchStrand = StrandValues [0];
  }

  if (createImplicitGraphs && ! foundGraphFilter) {
    /* insert a Graph filter at the_end of the list */
    FIP = MemNew (sizeof (FilterItem));
    VNP = ValNodeAddPointer (&FP->FilterItemList, 0, FIP);
    if (FIP == NULL || VNP == NULL ) {
      DestroyFilter (FP, VCP);
      return NULL;
    }
    FIP->Type = GraphFilter;
    FIP->IntraRowPaddingPixels = 5;
  }

  return FP;
}

/* if this will be used by multiple threads in a multi-threaded application, there should be a lock around writing this */
static ViewerConfigsPtr newGraphicViewer_ConfigFileParse_Global = NULL;

static void InitializeDefaultStyle (
  CharPtr configFileName
);

NLM_EXTERN ViewerConfigsPtr GetGraphicConfigParseResults (
  void
)

{
  Uint1             AppearanceCount;
  Uint1             FilterCount;
  Uint1             i;
  void PNTR PNTR    ptr2;
  ViewerConfigsPtr  VCP;
  ValNodePtr        nameVNP;
  ValNodePtr        VNP;

  if (newGraphicViewer_ConfigFileParse_Global != NULL) {
    return newGraphicViewer_ConfigFileParse_Global;
  }

  InitializeDefaultStyle (config_filename);

  VCP = MemNew (sizeof (ViewerConfigs));
  if (VCP == NULL) return NULL;

  if (ParseConfigFile (VCP) == 0) return NULL;
  /* this should never happen, because of the static default style*/
  if (VCP->AppearanceCount == 0 || VCP->FilterCount == 0) return NULL;

  AppearanceCount = VCP->AppearanceCount;
  FilterCount = VCP->FilterCount;
  i = (AppearanceCount + FilterCount) * 2 + 2; /* total number of pointers needed (the extra 2 are NULL's to terminate the name lists) */
  ptr2 = MemNew (i * sizeof (VoidPtr));
  if (ptr2 == NULL) {
    MemFree (VCP);
    return NULL;
  }
  VCP->AppearanceArray = (AppearancePtr PNTR) ptr2;
  ptr2 += AppearanceCount;
  VCP->AppearanceNameArray = (CharPtr PNTR) ptr2;
  ptr2 += AppearanceCount + 1; /* add a NULL pointer to terminate the list */
  VCP->FilterArray = (FilterPtr PNTR) ptr2;
  ptr2 += FilterCount;
  VCP->FilterNameArray = (CharPtr PNTR) ptr2;
  VNP = VCP->AppearanceList;
  nameVNP = VCP->AppearanceNameList;
  for (i = 0; i < AppearanceCount; i++) {
    VCP->AppearanceArray[i] = VNP->data.ptrvalue;
    VCP->AppearanceNameArray[i] = nameVNP->data.ptrvalue;
    VNP = VNP->next;
    nameVNP = nameVNP->next;
  }

  VNP = VCP->FilterList;
  nameVNP = VCP->FilterNameList;
  for (i = 0; i < FilterCount; i++) {
    VCP->FilterArray[i] = VNP->data.ptrvalue;
    VCP->FilterNameArray[i] = nameVNP->data.ptrvalue;
    VNP = VNP->next;
    nameVNP = nameVNP->next;
  }
  VCP->ArraysPopulated = TRUE;
  newGraphicViewer_ConfigFileParse_Global = VCP;
  return VCP;
}

/* returns count of objects successfully parsed -- so 0 on failure */
NLM_EXTERN Uint2 ParseConfigFile (
  ViewerConfigsPtr VCP
)

{
  Char     tag [32];
  Char     name [128];
  Int2     i;
  Uint2    fCount = 0, aCount = 0;
  VoidPtr  tempPtr;
  unsigned val; /* to match scanf("%ud"...) */

  GetAppParam (config_filename, "filters", "maxlabelscale", NULL, tag, sizeof (tag));
  if (sscanf (tag, "%ud", &val) != 1) {
    val = 200;
  }
  VCP->DefaultMaxScaleWithLabels = val;

  GetAppParam (config_filename, "filters", "grouppadding", NULL, tag, sizeof (tag));
  if (sscanf (tag, "%ud", &val) != 1) {
    val = 3;
  }
  VCP->DefaultGroupPadding = val;

  GetAppParam (config_filename, "filters", "rowpadding", NULL, tag, sizeof (tag));
  if (sscanf (tag, "%ud", &val) != 1) {
    val = 5;
  }
  VCP->DefaultRowPadding = val;

  GetAppParam (config_filename, "styles", "maxarrowscale", NULL, tag, sizeof (tag));
  if (sscanf (tag, "%ud", &val) != 1) {
    val = 5;
  }
  VCP->DefaultMaxScaleForArrow = val;

  GetAppParam (config_filename, "styles", "minarrowpixels", NULL, tag, sizeof (tag));
  if (sscanf (tag, "%ud", &val) != 1) {
    val = 5;
  }
  VCP->DefaultMinPixelsForArrow = val;

  VCP->DefaultShadeSmears = FALSE;
  if (GetAppParam (config_filename, "styles", "shadesmears", NULL, tag, sizeof (tag))) {
    i = StringIndexInStringList (tag, BoolStrings);
    if (i >= 0 && i < DIM (BoolValues)) {
      VCP->DefaultShadeSmears = BoolValues [i];
    }
  }

  for (i = 0; i < 110; i++) {   /* do filters first */
    if (i < 10) {
      sprintf (tag, "filter0%d", (unsigned) i);
    } else {
      sprintf (tag, "filter%d", (unsigned) i - 9);
    }
    if (GetAppParam (config_filename, "filters", tag, NULL, name, sizeof (name))) {
      tempPtr = ParseFilter (name, VCP);
      if (tempPtr == NULL) continue;
      fCount++;
    }
  }
  for (i = 0; i < 110; i++) {
    if (i < 10) {
      sprintf (tag, "style0%d", (unsigned) i);
    } else {
      sprintf (tag, "style%d", (unsigned) i - 9);
    }
    if (GetAppParam (config_filename, "styles", tag, NULL, name, sizeof (name))) {
      tempPtr = ParseAppearance (name, VCP);
      if (tempPtr == NULL) continue;
      aCount++;
    }
  }
  return (aCount + fCount);
}

NLM_EXTERN FilterPtr DestroyFilter (
  FilterPtr FP,
  ViewerConfigsPtr VCP
)

{
  FilterItemPtr  FIP;
  ValNodePtr     VNP;
  Uint1          i;

  if (FP == NULL || VCP == NULL) {
    return NULL;
  }
  for (VNP = FP->FilterItemList; VNP; VNP = VNP->next) { /* free all filterItems, and their labels */
    FIP = (FilterItemPtr) VNP->data.ptrvalue;
    if (FIP == NULL) {
      continue;
    }
    MemFree (FIP->GroupLabel);
    MemFree (FIP);
  }
  for (VNP = VCP->FilterList; VNP != NULL; VNP = VNP->next) {
    if (VNP->data.ptrvalue == FP) {
      i = VNP->choice;
      VNP = ValNodeExtract (&VCP->FilterList, i);
      break;
    }
  }
  if (VNP != NULL) {
    MemFree (VNP);
    VNP = ValNodeExtract (&VCP->FilterNameList, i);
    MemFree (VNP->data.ptrvalue);
    MemFree (VNP);
  }
  --VCP->FilterCount;
  MemFree (FP);
  return NULL;
}

NLM_EXTERN void AddAppearanceItemToAppearance (
  AppearanceItemPtr AIP,
  AppearancePtr AP,
  Uint1 newFeatdef,
  ViewerConfigsPtr VCP
)

{
  Uint1       i;
  ValNodePtr  VNP;

  if (AIP == NULL || AP == NULL || VCP == NULL) return;
  if (newFeatdef == FEATDEF_ANY) {
    for (i = 0; i < APPEARANCEITEM_MAX; i++) {
      AP->FeaturesAppearanceItem [i] = AIP;
    }
  } else if (newFeatdef == FEATDEF_ANY_RNA) {
    for (i = FEATDEF_preRNA; i <= FEATDEF_otherRNA; i++) {
      AP->FeaturesAppearanceItem [i] = AIP;
    }
    AP->FeaturesAppearanceItem [FEATDEF_misc_RNA] = AIP;
    AP->FeaturesAppearanceItem [FEATDEF_precursor_RNA] = AIP;
    AP->FeaturesAppearanceItem [FEATDEF_snoRNA] = AIP;
  } else if (newFeatdef == FEATDEF_ANY_PROT) {
    AP->FeaturesAppearanceItem [FEATDEF_PROT] = AIP;
    for (i = FEATDEF_preprotein; i <= FEATDEF_transit_peptide_aa; i++) {
      AP->FeaturesAppearanceItem [i] = AIP;
    }
  } else if (newFeatdef == FEATDEF_IMP) {
    for (i = FEATDEF_allele; i <= FEATDEF_35_signal; i++) {
      AP->FeaturesAppearanceItem [i] = AIP;
    }
  } else if (newFeatdef < APPEARANCEITEM_MAX) {
    AP->FeaturesAppearanceItem [newFeatdef] = AIP;
  } else return;
  for (VNP = AP->AppearanceItemList; VNP != NULL && VNP->data.ptrvalue != AIP; VNP = VNP->next) continue;
  if (! (VNP != NULL && VNP->data.ptrvalue == AIP)) {    /* AIP was not previously in the AppearanceItemList */
    ValNodeAddPointer (&AP->AppearanceItemList, 0, AIP);
  }
}

NLM_EXTERN AppearancePtr DestroyAppearance (
  AppearancePtr AP,
  ViewerConfigsPtr VCP
)

{
  Uint1       i;
  ValNodePtr  VNP;

  if (AP == NULL || VCP == NULL) return NULL;
  if (AP->AppearanceItemList != NULL) {
    ValNodeFreeData (AP->AppearanceItemList);
  }
  for (VNP = VCP->AppearanceList; VNP != NULL; VNP = VNP->next) {
    if (VNP->data.ptrvalue == AP) {
      i = VNP->choice;
      VNP = ValNodeExtract (&VCP->AppearanceList, i);
      break;
    }
  }
  if (VNP != NULL) {
    MemFree (VNP);
    VNP = ValNodeExtract (&VCP->AppearanceNameList, i);
    MemFree (VNP);
  }
  MemFree (AP);
  return NULL;
}

static void getDim_do_not_render (
  RenderInputPtr RIP,
  Int4Ptr Start,
  Int4Ptr Stop,
  Uint2Ptr height,
  ViewerContextPtr vContext
)

{
  RelevantFeatureItemPtr RFIP;

  RFIP = RIP->RFIP;

  *Start = *Stop = RFIP->Left;
  *height = 1;
}

static void do_not_render (
  RenderInputPtr RIP,
  ViewerContextPtr vContext
)

{
  return;
}

static void getDim_render_with_line (
  RenderInputPtr RIP,
  Int4Ptr Start,
  Int4Ptr Stop,
  Uint2Ptr height,
  ViewerContextPtr vContext
)

{
  RelevantFeatureItemPtr RFIP;

  RFIP = RIP->RFIP;

  if (vContext->allFeatures) {
    *Start = RFIP->Left;
    *Stop = RFIP->Right;
  } else {
    *Start = MAX (RFIP->Left, vContext->from);
    *Stop = MAX (RFIP->Right, vContext->to);
  }
  *height = 1;
}

static void render_wrap_around_markers(
  RenderInputPtr RIP,
  ViewerContextPtr vContext
)
{
  Uint4      StartY;
  RelevantFeatureItemPtr RFIP;
  AppearanceItemPtr       AIP;

  RFIP = RIP->RFIP;
  AIP = RIP->AIP;
  StartY = RIP->yStart - (RIP->featureOffset) - AIP->Height / 2 - 1;

  AddSymbol(RIP->drawSeg, RFIP->Left - 3 * vContext->viewScale,  StartY, LEFT_TRIANGLE_SYMBOL,  FALSE, MIDDLE_LEFT, 0);
  AddSymbol(RIP->drawSeg, RFIP->Right + 3 * vContext->viewScale, StartY, RIGHT_TRIANGLE_SYMBOL, FALSE, MIDDLE_RIGHT, 0);
}

static void render_with_line (
  RenderInputPtr RIP,
  ViewerContextPtr vContext
)

{
  Uint4      StartY;
  PrimitivE  thisPrim;
  RelevantFeatureItemPtr RFIP;
  AppearanceItemPtr       AIP;
  Int4       start, stop;

  RFIP = RIP->RFIP;
  AIP = RIP->AIP;

  StartY = RIP->yStart - (RIP->featureOffset) - AIP->Height / 2;
  if (vContext->allFeatures) {
    start = RFIP->Left;
    stop = RFIP->Right;
  } else {
    start = MAX (RFIP->Left, vContext->from);
    stop = MAX (RFIP->Right, vContext->to);
  }

  if (!RFIP->circularSpanningOrigin || RFIP->numivals < 2) {
    thisPrim = AddLine (RIP->drawSeg, start, StartY, stop, StartY, 0, 0);
  SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
  } else { 
    /* feature spans the origin. draw specially */
    if (RFIP->ivals[0] < stop) {
      thisPrim = AddLine (RIP->drawSeg, RFIP->ivals[0], StartY, stop, StartY, 0, 0); 
      SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
    }
    if (RFIP->ivals[2* RFIP->numivals - 1] > start) {
      thisPrim = AddLine (RIP->drawSeg, start, StartY, RFIP->ivals[2* RFIP->numivals - 1], StartY, 0, 0); 
      SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
    }
    render_wrap_around_markers(RIP, vContext);
  }
}

static void getDim_render_with_capped_line (
  RenderInputPtr RIP,
  Int4Ptr Start,
  Int4Ptr Stop,
  Uint2Ptr height,
  ViewerContextPtr vContext
)

{
  RelevantFeatureItemPtr RFIP;
  AppearanceItemPtr AIP;

  RFIP = RIP->RFIP;
  AIP = RIP->AIP;


  if (vContext->allFeatures) {
    *Start = RFIP->Left;
    *Stop = RFIP->Right;
  } else {
    *Start = MAX (RFIP->Left, vContext->from);
    *Stop = MAX (RFIP->Right, vContext->to);
  }
  *height = AIP->Height;
}

static void render_with_capped_line (
  RenderInputPtr RIP,
  ViewerContextPtr vContext
)

{
  PrimitivE               thisPrim;
  AppearanceItemPtr       AIP;
  RelevantFeatureItemPtr  RFIP;
  Int4                    StartY;

  StartY = RIP->yStart - (RIP->featureOffset);
  render_with_line (RIP, vContext);
  RFIP = RIP->RFIP;
  AIP = RIP->AIP;


  if (!RFIP->circularSpanningOrigin || RFIP->numivals < 2) {
    thisPrim = AddLine (RIP->drawSeg, RFIP->Left, StartY, RFIP->Left, StartY - AIP->Height, 0, 0);
    SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
    thisPrim = AddLine (RIP->drawSeg, RFIP->Right, StartY, RFIP->Right, StartY - AIP->Height, 0, 0);
    SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
  } else {
    /* origin spanning feature */
    thisPrim = AddLine (RIP->drawSeg, RFIP->ivals[0], StartY, RFIP->ivals[0], StartY - AIP->Height, 0, 0);
    SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
    thisPrim = AddLine (RIP->drawSeg, RFIP->ivals[2* RFIP->numivals - 1], StartY, RFIP->ivals[2* RFIP->numivals - 1], StartY - AIP->Height, 0, 0);
    SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);    
  }
}

static void getDim_render_with_box (
  RenderInputPtr RIP,
  Int4Ptr Start,
  Int4Ptr Stop,
  Uint2Ptr height,
  ViewerContextPtr vContext
)
{
  RelevantFeatureItemPtr RFIP;
  AppearanceItemPtr AIP;

  RFIP = RIP->RFIP;
  AIP = RIP->AIP;
  *Start = RFIP->Left;
  *Stop = RFIP->Right;
  *height = AIP->Height;
  if (IsInsertTic(RFIP))
    *height += AIP->Height; 
}

static Boolean IsInsertTic(RelevantFeatureItemPtr RFIP)
{
  int   iival;
  
  /* Insert Tics only on alignments with more than one segment */
  if (RFIP->featdeftype != APPEARANCEITEM_Alignment || RFIP->numivals < 2)
    return FALSE;

  for (iival = 0; iival < RFIP->numivals; ++iival) {
    /* a segment with beginning and end the same is an insert */
    if (RFIP->ivals [2 * iival] == RFIP->ivals [2 * iival + 1] ) {
      return TRUE;
    }
  }
  return FALSE;
}

#if 0 /* TestForSmearOverlap was replaced by PixelsBetweenSeqCoords everwhere it was used */
static Boolean TestForSmearOverlap (
  Int4 PrevEnd,
  Int4 NewStart,
  ViewerContextPtr vContext
)
{
  return PixelsBetweenSeqCoords(PrevEnd, NewStart, vContext->viewScale) < 1;
}
#endif

/* returns TRUE if no visible gap. */
static Boolean NoVisibleGap (
  Int4 x1,
  Int4 x2,
  Uint4 viewScale
)
{
  return abs(PixelsBetweenSeqCoords(x1, x2, viewScale)) < 2;
}

static Boolean TestForSmear (
  RelevantFeatureItemPtr RFIP1,
  RelevantFeatureItemPtr RFIP2,
  Uint4  viewScale
)
{
  Uint4  minSeperation;
  
  minSeperation = 5;  /* do not smear a feature more than 5 pixels wide */

  if (abs(PixelsBetweenSeqCoords(RFIP1->Right, RFIP1->Left, viewScale)) >= minSeperation) return FALSE;
  if (abs(PixelsBetweenSeqCoords(RFIP2->Right, RFIP2->Left, viewScale)) >= minSeperation) return FALSE;

  return (NoVisibleGap (RFIP1->Right, RFIP2->Left, viewScale)
          || NoVisibleGap (RFIP1->Right, RFIP2->Right, viewScale)
          || NoVisibleGap (RFIP1->Left, RFIP2->Right, viewScale)
          || NoVisibleGap (RFIP1->Left, RFIP2->Left, viewScale) );

}

static Int4 PixelsBetweenSeqCoords(Int4 left, Int4 right, Uint4 viewScale)
{
  /* Will be negative if right is really not right of left. */
  /* 0 if they fall on the same pixel. */
  /* Do NOT change this to (right - left)/viewScale. NOT the same. */
  return (right/viewScale - left/viewScale);
}

static void render_with_box_master (
  RenderInputPtr RIP,
  Boolean fillBox,
  ViewerContextPtr vContext
)

{
  Int4                    StartY;
  Uint2                   pieceIValStart;
  PrimitivE               thisPrim;
  Uint2                   i;
  Int4                    mid;
  AppearanceItemPtr       AIP;
  AppearancePtr           AP;
  RelevantFeatureItemPtr  RFIP;
  Boolean                 shade_p;
  Uint1                   arrow;

  RFIP = RIP->RFIP;
  AIP = RIP->AIP;
  AP = vContext->AppPtr;
  StartY = RIP->yStart - (RIP->featureOffset);
  if (RFIP->LeftEnd == EndClipped) {
    thisPrim = AddLine (RIP->drawSeg, vContext->from, StartY - AIP->Height / 2, RFIP->Left, StartY - AIP->Height / 2, 0, 0);
    SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
  }
  if (RFIP->RightEnd == EndClipped) {
    thisPrim = AddLine (RIP->drawSeg, vContext->to, StartY - AIP->Height / 2, RFIP->Right, StartY - AIP->Height / 2, 0, 0);
    SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
  }
  if (RFIP->numivals == 1) {
    shade_p = (RFIP->entityID == 0 && RFIP->itemID == 0) ? AP->ShadeSmears : FALSE;
    if (RFIP->entityID == 0 && RFIP->itemID == 0) { /* is this a multi-feature smear? */
      if (shade_p) {
        /*        AddAttribute (RIP->drawSeg, SHADING_ATT, 0, 0, MEDIUM_SHADING, 0, 0);*/
      }
      thisPrim = AddRectangle (RIP->drawSeg, RFIP->Left, StartY, RFIP->Right, StartY - AIP->Height, NO_ARROW, fillBox, 0);
      SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
      if (shade_p) {
        /*        AddAttribute (RIP->drawSeg, SHADING_ATT, 0, 0, NO_SHADING, 0, 0);*/
      }

    } else { /* nope */
      arrow = NO_ARROW;
      if (RFIP->featstrand == Seq_strand_plus) {
        arrow = RIGHT_ARROW;
      } else if (RFIP->featstrand == Seq_strand_minus) {
        arrow = LEFT_ARROW;
      }
      if (! AIP->ShowArrow) {
        arrow = NO_ARROW;
      }
      if (abs(PixelsBetweenSeqCoords( RFIP->Left, RFIP->Right, vContext->viewScale)) < AP->MinPixelsForArrow) {
        arrow = NO_ARROW;
      }
      if (vContext->viewScale > AP->MaxScaleForArrow) {
        arrow = NO_ARROW;
      }
      thisPrim = AddRectangle (RIP->drawSeg, RFIP->Left, StartY, RFIP->Right, StartY - AIP->Height, arrow, fillBox, 0);
      SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
    }
    return;
  } else {
    i = 0;
    while (i < RFIP->numivals) {
      /* collect a group of interval(s) which do not contain any pixels between them */
      pieceIValStart = i;
      /* this tests is the i-plus-1th feature is part of the smear, which goes from pieceIValStart to i, inclusive */
      /* On alignments only smear away the gaps caused by inserts. */
      if (RFIP->featdeftype == APPEARANCEITEM_Alignment) {
        while (i + 1 < RFIP->numivals &&
               NoVisibleGap (RFIP->ivals [2 * i + 1], RFIP->ivals [2 * i + 2], vContext->viewScale) &&
               (RFIP->ivals [2 * i] == RFIP->ivals [2 * i + 1]  ||  RFIP->ivals [2 * i + 2] == RFIP->ivals [2 * i + 3])) {
          i++;
        }
      } else {
        while (i + 1 < RFIP->numivals &&
               NoVisibleGap (RFIP->ivals [2 * i + 1], RFIP->ivals [2 * i + 2], vContext->viewScale)) {
          i++;
        }
      }

      /* draw the segment and the gap -- drawing the gap first, so that it is overdrawn by the segment */
      if (i + 1 < RFIP->numivals) { /* a gap is present if there are more ivals to consider after i*/
        if (RFIP->circularSpanningOrigin && RFIP->ivals [2 * i + 1] > RFIP->ivals [2 * i + 2]) {
          /* on a circular bioseq, this gap spans the origin and has to be drawn specially */
          /* RFIP->Left will be 0, RFIP->Right will be the length of the Bioseq */
          if (RFIP->ivals [2 * i + 1] < RFIP->Right - 1) {
            /* Draw the part of the gap at the right end. Might not be any. */
            thisPrim = AddLine (RIP->drawSeg, RFIP->ivals[2 * i + 1], StartY - AIP->Height / 2, RFIP->Right, StartY - AIP->Height / 2, 0, 0);
            SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
          }
          if (RFIP->Left <  RFIP->ivals [2 * i + 2]) {
            /* draw the part of the gap at the left end. */
            thisPrim = AddLine (RIP->drawSeg, RFIP->Left, StartY - AIP->Height / 2, RFIP->ivals[2 * i + 2], StartY - AIP->Height / 2, 0, 0);
            SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
          }
          /* No. I didn't put in code to make those lines 'Angle Gap' style. Figured it wouldn't show up very well. You can if you want. */
          
          /* draw markers to show that this wraps around */
          render_wrap_around_markers(RIP, vContext);

        } else {
          /* ordinary gap */
          if (AIP->GapChoice == LineGap) {
            thisPrim = AddLine (RIP->drawSeg, RFIP->ivals [2 * i + 1],                       StartY - AIP->Height / 2, 
                                              RFIP->ivals [2 * i + 2] - vContext->viewScale, StartY - AIP->Height / 2, 0, 0);
            SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
          } else if (AIP->GapChoice == AngleGap) {
            mid = (RFIP->ivals [2 * i + 2] + RFIP->ivals [2 * i + 1]) / 2;
            thisPrim = AddLine (RIP->drawSeg, RFIP->ivals [2 * i + 1], StartY - AIP->Height / 2, 
                                              mid,                     StartY, 0, 0);
            SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
            thisPrim = AddLine (RIP->drawSeg, mid,                                           StartY, 
                                              RFIP->ivals [2 * i + 2] - vContext->viewScale, StartY - AIP->Height / 2, 0, 0);
            SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
          }
        }
      }
      arrow = NO_ARROW;
      if (i == RFIP->numivals - 1  &&  RFIP->featstrand == Seq_strand_plus) {
        arrow = RIGHT_ARROW;
      } else if (RFIP->featstrand == Seq_strand_minus) {
        /* on minus strands, Alignments put their intervals in coordinate order.
          Other features put theirs in biological order (right to  left),
          so we have to draw the arrow differently (or we could sort the intervals so they 
          ended up the same. */
        if ((pieceIValStart == 0 && RFIP->featdeftype == APPEARANCEITEM_Alignment) ||
          (i == RFIP->numivals - 1  &&   RFIP->featdeftype != APPEARANCEITEM_Alignment))
          arrow = LEFT_ARROW;
      }
      if (! AIP->ShowArrow) {
        arrow = NO_ARROW;
      }
      if (ABS (RFIP->Right - RFIP->Left) / vContext->viewScale < AP->MinPixelsForArrow) {
        arrow = NO_ARROW;
      }
      if (vContext->viewScale > AP->MaxScaleForArrow) {
        arrow = NO_ARROW;
      }
      thisPrim = AddRectangle (RIP->drawSeg, RFIP->ivals [2 * pieceIValStart], StartY, RFIP->ivals [2 * i + 1], StartY - AIP->Height, arrow, fillBox, 0);
      SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
      i++;
    }
    if (RFIP->featdeftype == APPEARANCEITEM_Alignment) {
      render_insert_tics(RIP);
    }
  }
}


static void render_insert_tics(RenderInputPtr RIP)
{
  AppearanceItemPtr       AIP;
  RelevantFeatureItemPtr  RFIP;
  PrimitivE               thisPrim;
  Int4                    StartY;
  Int4                    i;

  RFIP = RIP->RFIP;
  AIP = RIP->AIP;
  StartY = RIP->yStart - (RIP->featureOffset);

  /* if we are drawing an aligment, and the interval is zero length, It is an insert. 
     Draw a vertical line the height of the bar under the bar to show this.  */
  for (i = 0; i < RFIP->numivals; ++i) {
    /* a segment with beginning and end the same is an insert */
    if (RFIP->ivals [2 * i] == RFIP->ivals [2 * i + 1] ) {
      thisPrim = AddLine(RIP->drawSeg, RFIP->ivals [2 * i], StartY - AIP->Height, 
                                       RFIP->ivals [2 * i], StartY - AIP->Height * 2, FALSE, 0);
      SetPrimitiveIDs(thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
    }
  }
}


static void render_with_box (
  RenderInputPtr   RIP,
  ViewerContextPtr vContext
)

{
  render_with_box_master (RIP, TRUE, vContext);

}

static void render_with_outline_box (
  RenderInputPtr   RIP,
  ViewerContextPtr vContext
)

{
  render_with_box_master (RIP, FALSE, vContext);
}

static const RenderClass RenderAlgorithmTable [] = {
  {do_not_render, getDim_do_not_render}, /* do_not_render */
  {render_with_line, getDim_render_with_line}, /* Render_Line */
  {render_with_capped_line, getDim_render_with_capped_line}, /* Render_CappedLine */
  {render_with_box, getDim_render_with_box},   /* Render_Box */
  {render_with_outline_box, getDim_render_with_box},   /* Render_OutlineBox */
  /* !!! these do not exist right now - can they be removed? !!! */
  {render_with_line, getDim_render_with_line},
  {render_with_box, getDim_render_with_box},
  {render_with_line, getDim_render_with_line},
  {render_with_line, getDim_render_with_line},
  {render_with_line, getDim_render_with_line},
  {render_with_line, getDim_render_with_line},
  {render_with_line, getDim_render_with_line}
};

static void DrawFeatureAndLabel (
  RenderInputPtr RIP,
  ViewerContextPtr vContext
)

{
  AppearanceItemPtr       AIP;
  RelevantFeatureItemPtr  RFIP;
  FilterItemPtr           FIP;
  FilterPtr               FP;
  CharPtr                 label;
  Char                    tempStringBuffer [256];
  Char                    shortLabel [41];
  Uint1                   stringFlags;
  Uint4                   textWidthBP;
  Int4                    textStartX;
  Int4                    textStartY;
  Uint1                   labelAlign, fitChars;
  PrimitivE               thisPrim;
  Boolean                 addType;
  Boolean                 addDesc;

  FIP = RIP->FIP;
  RFIP = RIP->RFIP;
  AIP = RIP->AIP;
  FP = vContext->FltPtr;
  addType = AIP->AddTypeToLabel;
  addDesc = AIP->AddDescToLabel;
  if (FIP->AddTypeToLabel != TristateUnset) {
    addType = BOOL_FROM_SET_TRISTATE (FIP->AddTypeToLabel);
  }
  if (FIP->AddDescToLabel != TristateUnset) {
    addDesc = BOOL_FROM_SET_TRISTATE (FIP->AddDescToLabel);
  }

  /*  RIP->drawSeg = CreateSegment (RIP->drawSeg, 0, 0);*/
  /* Place each feature in its own segment.  This is not necessary for simple features
     but perhaps the inefficiency is acceptable because it simplifies the algorithm. */
  (*RenderAlgorithmTable [AIP->RenderChoice].RenderFunc) (RIP, vContext);
  if (FIP->LabelLoc == LabelNone) return;
  if (vContext->viewScale > FP->MaxScaleWithLabels) return;
  stringFlags = 0;
  if (addDesc && RFIP->ContentLabel != NULL) {
    stringFlags |= 1;
  }
  if (addType) {
    stringFlags |= 2;
  }
  label = NULL;
  switch (stringFlags) {
    case 0:                    /* no label */
      return;
    case 1:                    /*comment but not type */
      label = RFIP->ContentLabel;
      break;
    case 2:                    /*only type */
      label = FindFeatStrFromFeatDefType (RFIP->featdeftype);
      break;
    case 3:                    /*add both */
      if (StringCmp (FindFeatStrFromFeatDefType (RFIP->featdeftype), RFIP->ContentLabel) != 0) {
        sprintf (tempStringBuffer, "%s: %s", FindFeatStrFromFeatDefType (RFIP->featdeftype), RFIP->ContentLabel);
        label = tempStringBuffer;
      } else {
        label = RFIP->ContentLabel;
      }
      break;
  }
  if (StringHasNoText (label)) return;
  LabelCopy (shortLabel, label, sizeof (shortLabel)-1);
  SelectFont (AIP->LabelFont);
  textWidthBP = StringWidth (shortLabel) * vContext->viewScale;
  switch (FIP->LabelLoc) {
    case LabelAboveClip:
      if (textWidthBP + 2 * vContext->viewScale >= (RFIP->Right - RFIP->Left)) {
        fitChars = Nlm_FitStringWidth (shortLabel, (RFIP->Right - RFIP->Left) / vContext->viewScale);
        if (fitChars <= 2 && StringLen (shortLabel) != fitChars) return;
        shortLabel [fitChars] = '>';
        shortLabel [fitChars + 1] = '\0';
      }
      textStartX = (RFIP->Left + RFIP->Right) / 2;
      /*      textStartY = RIP->yStart - RIP->rowHeight / 2; -- change "labelInside" to mean "above, but not wider than"*/
      textStartY = RIP->yStart;
      labelAlign = LOWER_CENTER;
      break;
    case LabelInside:
      if (textWidthBP + 2 * vContext->viewScale >= (RFIP->Right - RFIP->Left)) {
        fitChars = Nlm_FitStringWidth (shortLabel, (RFIP->Right - RFIP->Left) / vContext->viewScale);
        shortLabel [fitChars + 1] = '\0';
      }
      textStartX = (RFIP->Left + RFIP->Right) / 2;
      textStartY = RIP->yStart - RIP->rowHeight / 2;
      labelAlign = MIDDLE_CENTER;
      break;
    case LabelAboveCull:
      if (textWidthBP + 2 * vContext->viewScale >= (RFIP->Right - RFIP->Left)) return;
      /* else fall through and display the label above */
    case LabelAbove:
      textStartX = (RFIP->Left + RFIP->Right) / 2;
      textStartY = RIP->yStart;
      labelAlign = LOWER_CENTER;
      break;
    case LabelBelow:
      textStartY = RIP->yStart - RIP->Height;
      textStartX = (RFIP->Left + RFIP->Right) / 2;
      labelAlign = LOWER_CENTER;
      break;
    case LabelLeft:
      textStartX = (RFIP->Left);
      textStartY = (RIP->yStart);
      labelAlign = LOWER_LEFT;
      break;
    case LabelRight:
      textStartX = (RFIP->Right);
      textStartY = (RIP->yStart);
      labelAlign = LOWER_RIGHT;
      break;
    default:
      return;
  }
  thisPrim = AddTextLabel (RIP->labelSeg, textStartX, textStartY, shortLabel, AIP->LabelFont, 1, labelAlign, 0);
  SetPrimitiveIDs (thisPrim, RFIP->entityID, RFIP->itemID, RFIP->itemType, 0);
}

static RelevantFeatureItemPtr BuildClippedRFIP (
  RelevantFeatureItemPtr inputRFIP,
  FilterProcessStatePtr FPSP,
  ViewerContextPtr vContext
)

{
  RelevantFeatureItemPtr newRFIP;
  ValNodePtr VNP = NULL;
  Uint2 i, newnumivals;
  Int4  from, to;
  Boolean useThis = TRUE, useLast;
  Boolean clippedLeft, clippedRight;
  Boolean lastClippedLeft, lastClippedRight;

  if ((newRFIP = MemNew (sizeof (RelevantFeatureItem))) == NULL) return NULL;
  if ((VNP = MemNew (sizeof (ValNode))) == NULL) {
    MemFree (newRFIP);
    return NULL;
  }
  VNP->data.ptrvalue = newRFIP;
  VNP->next = FPSP->needFreeList;
  FPSP->needFreeList = VNP;
  MemCopy (newRFIP, inputRFIP, sizeof (RelevantFeatureItem));
  if ((inputRFIP->Left <= vContext->from && inputRFIP->Right <= vContext->from)
      || (inputRFIP->Left >= vContext->to && inputRFIP->Right >= vContext->to)) {
    return NULL; /* entire feature removed by clipping */
  }
  newRFIP->LeftEnd = (inputRFIP->Left >= vContext->from) ? inputRFIP->LeftEnd : EndPartial;
  newRFIP->RightEnd  = (inputRFIP->Right <= vContext->to) ?  inputRFIP->RightEnd  : EndPartial;
  if (inputRFIP->numivals == 1) {
    newRFIP->Left  = MAX (vContext->from, MIN (vContext->to, inputRFIP->Left ));
    newRFIP->Right = MAX (vContext->from, MIN (vContext->to, inputRFIP->Right));
    newRFIP->LeftEnd = (inputRFIP->Left >= vContext->from) ? inputRFIP->LeftEnd : EndPartial;
    newRFIP->RightEnd  = (inputRFIP->Right <= vContext->to) ?  inputRFIP->RightEnd  : EndPartial;
  } else {
    newRFIP->Left = vContext->to;
    newRFIP->Right = vContext->from;
    newnumivals = 0;
    for (i = 0; i < inputRFIP->numivals; i++) {
      from = inputRFIP->ivals [2 * i];
      to = inputRFIP->ivals [2 * i + 1];
      if (from <= vContext->to && from >= vContext->from) {
        newnumivals ++;
      } else if (to <=  vContext->to && to >= vContext->from) {
        newnumivals ++;
      }
    }
    newRFIP->numivals = newnumivals;
    if ((newRFIP->ivals = MemNew (2 * newnumivals * sizeof (Int4))) == NULL) return NULL;
    if ((VNP = MemNew (sizeof (ValNode))) == NULL) {
      MemFree (newRFIP->ivals);
      return NULL;
    }
    VNP->data.ptrvalue = newRFIP->ivals;
    VNP->next = FPSP->needFreeList;
    FPSP->needFreeList = VNP;
    newnumivals = 0;
    for (i = 0; i < inputRFIP->numivals; i++) {
      from = inputRFIP->ivals [2 * i];
      to = inputRFIP->ivals [2 * i + 1];
      if (from <= vContext->to && from >= vContext->from) {
        useThis = TRUE;
        clippedLeft = clippedRight = FALSE;
      } else if (to <=  vContext->to && to >= vContext->from) {
        useThis = TRUE;
        clippedLeft = clippedRight = FALSE;
      } else {
        useThis = FALSE;
        clippedLeft = ((from + to) < (vContext->from + vContext->to));
        clippedRight = !clippedLeft;
      }
      if (i == 0) {
        useLast = useThis;
        lastClippedLeft = clippedLeft;
        lastClippedRight = clippedRight;
      }
      if (lastClippedLeft && useThis) {
        newRFIP->LeftEnd  = EndClipped;
      } else if (lastClippedRight && useThis) {
        newRFIP->RightEnd = EndClipped;
      } else if (useLast && clippedLeft) {
        newRFIP->LeftEnd  = EndClipped;
      } else if (useLast && clippedRight) {
        newRFIP->RightEnd = EndClipped;
      }
      if (useThis) {
        from = MAX (vContext->from, MIN (vContext->to, from));
        to   = MAX (vContext->from, MIN (vContext->to, to  ));
        newRFIP->Left = MIN (newRFIP->Left, from);
        newRFIP->Left = MIN (newRFIP->Left, to);
        newRFIP->Right = MAX (newRFIP->Right, to);
        newRFIP->Right = MAX (newRFIP->Right, from);
        newRFIP->ivals [newnumivals++] = from;
        newRFIP->ivals [newnumivals++] = to;
      }
      useLast = useThis;
    }
  }
  if (newRFIP->Left > newRFIP->Right) return NULL;
  return newRFIP;
}


static void GetFeatureAndDecorationDimensions (
  RenderInputPtr RIP,
  ViewerContextPtr vContext
)

{
  AppearanceItemPtr       AIP;
  RelevantFeatureItemPtr  RFIP;
  FilterItemPtr           FIP;
  FilterPtr               FP;
  Int4                    Start, Stop;
  Uint2                   Height;
  Int2                    lineHeight;
  Int4                    textStartX;
  Uint4                   textWidthBP;
  CharPtr                 label = NULL;
  Char                    tempStringBuffer [256];
  Uint1                   stringFlags;
  Uint2                   featureOffset = 0;
  Boolean                 addType;
  Boolean                 addDesc;

  RFIP = RIP->RFIP;
  AIP = RIP->AIP;
  FIP = RIP->FIP;
  FP = vContext->FltPtr;
  addType = AIP->AddTypeToLabel;
  addDesc = AIP->AddDescToLabel;
  if (FIP->AddTypeToLabel != TristateUnset) {
    addType = BOOL_FROM_SET_TRISTATE (FIP->AddTypeToLabel);
  }
  if (FIP->AddDescToLabel != TristateUnset) {
    addDesc = BOOL_FROM_SET_TRISTATE (FIP->AddDescToLabel);
  }

  (*RenderAlgorithmTable [AIP->RenderChoice].GetDimensions) (RIP, &Start, &Stop, &Height, vContext);
  RIP->Height = Height;
  RIP->decorationHeight = Height;
  RIP->decorationLeft = RFIP->Left;
  RIP->decorationRight = RFIP->Right;
  RIP->featureOffset = 0;

  if (FIP->LabelLoc != LabelNone && vContext->viewScale <= FP->MaxScaleWithLabels) {
    stringFlags = 0;
    if (addDesc && RFIP->ContentLabel != NULL) {
      stringFlags |= 1;
    }
    if (addType) {
      stringFlags |= 2;
    }

    switch (stringFlags) {
      case 0:                  /* no label */
        break;
      case 1:                  /*comment but not type */
        label = RFIP->ContentLabel;
        break;
      case 2:                  /*only type */
        label = FindFeatStrFromFeatDefType (RFIP->featdeftype);
        break;
      case 3:                  /*add both */
        if (StringCmp (FindFeatStrFromFeatDefType (RFIP->featdeftype), RFIP->ContentLabel) != 0) {
          sprintf (tempStringBuffer, "%s: %s", FindFeatStrFromFeatDefType (RFIP->featdeftype), RFIP->ContentLabel);
          label = tempStringBuffer;
        } else {
          label = RFIP->ContentLabel;
        }
        break;
      default:
        return;
    }
  }
  if (! StringHasNoText (label)) {
    SelectFont (AIP->LabelFont);
    textWidthBP = StringWidth (label) * vContext->viewScale;
    lineHeight = LineHeight ();
    switch (FIP->LabelLoc) {
      case LabelInside:
        Height = MAX (Height + lineHeight, Height);
        featureOffset = lineHeight + 1;
        break;
      case LabelAbove:
        textStartX = (Start + Stop) / 2;
        Start = MIN (Start, (signed)(textStartX - textWidthBP / 2));
        Stop = MAX (Stop, textStartX + textWidthBP / 2);
        featureOffset = lineHeight + 1;
        Height += lineHeight + 3;
        break;
      case LabelAboveClip:
        Height += lineHeight + 3;
        featureOffset = lineHeight + 1;
      case LabelAboveCull:
        if (textWidthBP + 2 * vContext->viewScale >= (Stop - Start)) {
          Height += lineHeight + 3;
          featureOffset = lineHeight + 1;
        }
      case LabelBelow:
        textStartX = (Start + Stop) / 2;
        Start = MIN (Start, (signed)(textStartX - textWidthBP / 2));
        Stop = MAX (Stop, textStartX + textWidthBP / 2);
        Height += lineHeight + 3;
        break;
      case LabelLeft:
        Start -= textWidthBP;
        Height = MAX (Height + lineHeight, Height);
        break;
      case LabelRight:
        Stop = RFIP->Right + textWidthBP;
        Height = MAX (Height + lineHeight, Height);
        break;
      default:
        return;
    }
  }
  RIP->decorationLeft = Start;
  RIP->decorationRight = Stop;
  RIP->decorationHeight = Height;
  RIP->featureOffset = featureOffset;
}


static Boolean BuildRenderInputFromRFIP (
  RenderInputPtr target,
  RelevantFeatureItemPtr RFIP,
  FilterProcessStatePtr FPSP
)

{
  AppearancePtr    AppPtr;
  FilterItemPtr    currentFIP;
  ViewerContextPtr vContext;
  RelevantFeatureItemPtr newRFIP;

  vContext = FPSP->vContext;

  if (target == NULL || RFIP == NULL) return FALSE;
  if (!vContext->allFeatures &&
      (
       (RFIP->Left < vContext->from && RFIP->Right < vContext->from)
       || (RFIP->Left > vContext->to && RFIP->Right > vContext->to)
       )) {
    return FALSE; /* this feature is outside the clipping seqloc */
  }
  if (! vContext->allFeatures && (
      (RFIP->Right >= vContext->from || RFIP->Left <= vContext->to)
      || (RFIP->Right < vContext->from && RFIP->Left > vContext->to)
      )) {
    newRFIP = BuildClippedRFIP (RFIP, FPSP, vContext);
    if (newRFIP == NULL) return FALSE;
    RFIP = newRFIP;
  }
  target->RFIP = RFIP;
  target->labelSeg = FPSP->labelSegs [RFIP->featdeftype];
  target->drawSeg = FPSP->drawSegs [RFIP->featdeftype];
  AppPtr = vContext->AppPtr;
  currentFIP = FPSP->currentFIP;
  target->AIP = AppPtr->FeaturesAppearanceItem [RFIP->featdeftype];
  target->FIP = FPSP->currentFIP;
  GetFeatureAndDecorationDimensions (target, vContext);
  target->rowHeight = MAX (target->Height, target->decorationHeight) + currentFIP->IntraRowPaddingPixels;
  return TRUE;
}

/* If this is a named Seq Annotation, return its name. Otherwise, return NULL */
static CharPtr GetSeqAnnotName(SeqAnnotPtr sap)
{
  if (sap != NULL && sap->desc != NULL)
  {
    AnnotDescrPtr  descPtr;
    /* look for a 'title' record */
    for (descPtr = sap->desc; descPtr != NULL; descPtr = descPtr->next)
    {
      if (Annot_descr_title == descPtr->choice) /* title choice */
        return descPtr->data.ptrvalue;
    }
    /* then try for a 'name' record */
    for (descPtr = sap->desc; descPtr != NULL; descPtr = descPtr->next)
    {
      if (Annot_descr_name == descPtr->choice) /* name choice */
        return descPtr->data.ptrvalue;
    }
    /* if an alignment look for a Blast Type or a Hist Seqalign user object */
      if(sap->type ==2) /* not an alignment annotation */
      {
        UserObjectPtr uop;
        ObjectIdPtr oip;
        UserFieldPtr ufp;
 
        for (descPtr = sap->desc; descPtr; descPtr = descPtr->next)
        {
            if (Annot_descr_user == descPtr->choice)
            {
                
                for (uop = descPtr->data.ptrvalue; uop; uop = uop->next)
                {
                    if (uop->type)
                    {
                        oip = uop->type;
                        
                        if (StringCmp(oip->str, "Blast Type") == 0)
                        {
                            ufp = uop->data;
                            if (ufp && ufp->choice == 2)
                            {
                                oip = ufp->label;
                                if (oip && oip->str)
                                {
                                  return oip->str;
                                }
                            }
                        }    
                    }    
                }
            }
        }
        for (descPtr = sap->desc; descPtr; descPtr = descPtr->next)
        {
            if (Annot_descr_user == descPtr->choice)
            {
                
                for (uop = descPtr->data.ptrvalue; uop; uop = uop->next)
                {
                    if (uop->type)
                    {
                        oip = uop->type;
                        
                        if (StringCmp(oip->str, "Hist Seqalign") == 0)
                        {
                            ufp = uop->data;
                            if (ufp && ufp->choice == 4 && ufp->data.boolvalue)
                            {
                                oip = ufp->label;
                                if (oip && oip->str)
                                {
                                    return oip->str;
                                }
                            }
                        }
                    }    
                }
            }
        }
      }
  }
  return NULL;
}

static Boolean GetAndCountFeatures (
  ViewerContextPtr vContext
)

{
  SeqFeatPtr              sfp;
  SeqMgrFeatContext       fContext;
  RelevantFeatureItemPtr  rFeats;
  ValNodePtr              sapList = NULL, VNP, VNPtail;
  SeqAnnotPtr             SAnnP;
  Uint2                   i;
  Int4                    swap;

  if (vContext == NULL) return FALSE;
  vContext->sapCount = 0;
  vContext->featureCount = 0;
  vContext->featVNP = NULL;
  vContext->sapList = NULL;

  /* create list of all named SeqAnnot's in this BioSeq. */
  for (SAnnP = vContext->BSP->annot; SAnnP != NULL; SAnnP = SAnnP->next) 
  {
    if (GetSeqAnnotName(SAnnP)) {
      vContext->sapCount++;
      ValNodeAddPointer (&sapList, 0, SAnnP);
    }
  }
  if (vContext->sapCount > 0) {
    vContext->sapList = MemNew (vContext->sapCount * sizeof (SeqAnnotPtr));
    if (vContext->sapList == NULL) {
      ValNodeFree (sapList);
      return FALSE;
    }
    for (i = 0, VNP = sapList; VNP != NULL && i < vContext->sapCount; VNP = VNP->next, i++) {
      vContext->sapList[i] = VNP->data.ptrvalue;
    }
    ValNodeFree (sapList);
  }
  
  rFeats = MemNew (RELEVANT_FEATS_PER_CHUNK * sizeof (RelevantFeatureItem));
  if (rFeats == NULL) return FALSE;
  ValNodeAddPointer (&vContext->featVNP, 0, rFeats);
  VNPtail = vContext->featVNP;
  i = 0;
  sfp = SeqMgrGetNextFeature (vContext->BSP, NULL, 0, 0, &fContext);
  while (sfp != NULL) {
    vContext->featureCount++;

    rFeats [i].Left = fContext.left;
    rFeats [i].Right = fContext.right;
    rFeats [i].LeftEnd = fContext.partialL ? EndPartial : EndAbsolute;
    rFeats [i].RightEnd  = fContext.partialR ? EndPartial : EndAbsolute;
    rFeats [i].ContentLabel = fContext.label;
    rFeats [i].featdeftype = fContext.featdeftype;
    rFeats [i].entityID = fContext.entityID;
    rFeats [i].itemID = fContext.itemID;
    rFeats [i].itemType = OBJ_SEQFEAT;
    rFeats [i].numivals = fContext.numivals;
    rFeats [i].ivals = fContext.ivals;
    rFeats [i].featstrand = fContext.strand;
    rFeats [i].circularSpanningOrigin = FALSE;
    if (rFeats [i].Left < 0 && fContext.bsp != NULL) {
      /* !!! for features that span origin JK !!! */
      rFeats [i].circularSpanningOrigin = TRUE;
      rFeats [i].Left = 0;
      rFeats [i].Right = fContext.bsp->length;
    }
    if (rFeats [i].Right < rFeats [i].Left) {
      /* protection against (feature indexing vs. trans-spliced features) */
      swap = rFeats [i].Right;
      rFeats [i].Right = rFeats [i].Left;
      rFeats [i].Left = swap;
    }
    /* with trans-spliced genes the left and right values might not span all the intervals. */
    /* we will fix that */
    {
      int ivali;
      Int4  val;
      for (ivali = 0; ivali < rFeats [i].numivals; ++ivali) {
        val = rFeats[i].ivals[2*ivali];
        rFeats[i].Left  = MIN( rFeats[i].Left,  val );
        rFeats[i].Right = MAX( rFeats[i].Right, val );
        val = rFeats[i].ivals[2*ivali+1];
        rFeats[i].Left  = MIN( rFeats[i].Left,  val );
        rFeats[i].Right = MAX( rFeats[i].Right, val );
      }
    }
    if (GetSeqAnnotName(fContext.sap)) { /* save this feature's Annot Ptr if it is a named Seq Annot. */
      rFeats [i].sap = fContext.sap;
    }
    else {
      rFeats [i].sap = NULL;
    }
    i++;
    if (i >= RELEVANT_FEATS_PER_CHUNK) {
      i = 0;
      rFeats = MemNew (RELEVANT_FEATS_PER_CHUNK * sizeof (RelevantFeatureItem));
      VNPtail = ValNodeNew (VNPtail);
      if (rFeats == NULL || VNPtail == NULL) {
        ValNodeFreeData (vContext->featVNP);
        MemFree (rFeats);
        return FALSE;
      }
      VNPtail->data.ptrvalue = rFeats;
    }

    sfp = SeqMgrGetNextFeature (vContext->BSP, sfp, 0, 0, &fContext);
  }
  if (vContext->featureCount == 0) {
    MemFree (rFeats);
    MemFree (vContext->featVNP);
    vContext->featVNP = NULL;
  }
  return TRUE;
}

NLM_EXTERN RelevantFeaturesPtr CollectFeatures (
  BioseqPtr bsp
)

{
  RelevantFeaturesPtr  RFP;
  ViewerContext        VC;

  RFP = MemNew (sizeof (RelevantFeatures));
  if (RFP == NULL) return NULL;
  VC.BSP = bsp;
  if (! GetAndCountFeatures (&VC)) return NULL;
  RFP->featureCount = VC.featureCount;
  RFP->featVNP = VC.featVNP;
  RFP->sapCount = VC.sapCount;
  RFP->sapList = VC.sapList;
  return RFP;
}

static Boolean EnsureFeatureHasSegment (
  FilterProcessStatePtr FPSP,
  Uint1 featdeftype,
  SegmenT parentSegment
)

{
  AppearancePtr     AppPtr;
  AppearanceItemPtr AIP;
  ViewerContextPtr vContext;

  vContext = FPSP->vContext;


  if (parentSegment == NULL) {
    parentSegment = vContext->drawOnMe;
  }

  AppPtr = vContext->AppPtr;
  if (FPSP->drawSegs [featdeftype] == NULL) {
    FPSP->drawSegs [featdeftype] = CreateSegment (parentSegment, 0, 0);
    FPSP->labelSegs [featdeftype] = CreateSegment (parentSegment, 0, 0);
    /* cleaup needed if program is supposed to recover from this !!! */
    if (FPSP->drawSegs [featdeftype] == NULL || FPSP->labelSegs [featdeftype] == NULL) return FALSE;
    AIP = AppPtr->FeaturesAppearanceItem [featdeftype];
    AddAttribute (FPSP->drawSegs [featdeftype],
                  COLOR_ATT | SHADING_ATT | STYLE_ATT | WIDTH_ATT,
                  AIP->Color, AIP->VibLinestyle, AIP->VibShading, 1, 0);
    AddAttribute (FPSP->labelSegs [featdeftype], COLOR_ATT, AIP->LabelColor, 0, 0, 0, 0);
  }
  return TRUE;
}

/*
  return a string describing the sequences in this alignment,
  concatenating strings from all the seqid's of the sequences in this alignment 
  except for the one in 'notthisRow' which ordinarly will be the bioseq.
*/

static Boolean SeqAlignContentLabel(SeqAlignPtr sap, SeqIdPtr notThisSID, CharPtr buf, Int4 buflen, Uint1 format)
{
  Int4      r, rows, slen;
  Char      localbuf[100];
  SeqIdPtr  sid;
  Char      rowDelim[] = ",";
  Int4      rowDelimLen = sizeof(rowDelim) - 1;
  Boolean   firstTime = TRUE;
  
  if (sap == NULL || buf == NULL) return FALSE;
  
  rows = AlnMgr2GetNumRows(sap);
  if (rows < 1)
    rows = sap->dim;
  if (rows < 1)
    return FALSE;
 
  for (r = 1; r <= rows; ++r)
  {
    sid = AlnMgr2GetNthSeqIdPtr(sap, r);
    if (sid == NULL) {
     sid = AlnMgr2GetNthSeqIdPtrStdSeg(sap, r);
    }
    if (sid == NULL) 
      continue;
    if (SeqIdIn(sid, notThisSID))
      continue;

    SeqIdWrite (sid, localbuf, format, sizeof (localbuf) - 1);
    slen = StringLen(localbuf);
    if (slen < buflen - rowDelimLen - 1)
    {
      if (!firstTime) {
        StringNCat(buf, rowDelim, buflen);
        buflen -= sizeof(rowDelim) - 1;
      }
      firstTime = FALSE;
      StringNCat(buf, localbuf, buflen);
      buflen -= slen + 1;
     }
  }
  
  if (StringLen(buf) <= 0)
    return FALSE;
  return TRUE;
}

static void AccumIvals(Int1* accumulator, Int4 accumBegin, Int4 accumLen, RelevantFeatureItemPtr RFIP);
Int4  CountIvals(Int1* accumulator, Int4 accumLen);
void  MakeIvals(Int1* accumulator, Int4 accumBegin, Int4 accumLen, Int4Ptr ivalsOut, Int4 ivalsLen);

static RelevantFeatureItemPtr GetNextRFIPinAlignmentFilter (
  FilterProcessStatePtr FPSP
)

{
    AlignmentFilterStatePtr alignSP;
    SeqAlignSortInfoPtr     alignSorted;
    SeqAlignPtr             SAlnP;
    Int4                    start, stop;
    Uint1                   segType;
    Int4                    nsegs, i;
    SeqIdPtr                SID;
    BioseqPtr               BSP;
    RelevantFeatureItem     RFI;       /* holder for intermediate values we will merge together */
    RelevantFeatureItemPtr  finalRFIP;  /* Our return value. */
    ViewerContextPtr        vContext;
    FilterItemPtr           currentFIP;
    AppearanceItemPtr       AIP;
    Char                    labelbuf[150];
    Uint1                   strand;
    AlignSegIterator        asi;
    ValNodePtr              vnp;
    
    if (FPSP == NULL) return NULL;
    vContext = FPSP->vContext;
    currentFIP = FPSP->currentFIP;
    if (vContext == NULL || currentFIP == NULL) return NULL;

    BSP = vContext->BSP;
    SID = BSP->id;
    AIP = vContext->AppPtr->FeaturesAppearanceItem[APPEARANCEITEM_Alignment];

    
    alignSP = &FPSP->state.align;
    alignSorted = alignSP->alignSorted;

    SAlnP = alignSorted[alignSP->alignIndex].sap;

    /* create new RFIP based on this SeqAlignPtr */
    finalRFIP = MemNew (sizeof (RelevantFeatureItem));
    if (finalRFIP == NULL) {
        MemFree (finalRFIP);
        return NULL;
    }
    vnp = ValNodeAddPointer (&FPSP->lastInFreeList, 0, finalRFIP);
    if (vnp == NULL) {
        MemFree (finalRFIP);
        return NULL;
    }
    if (FPSP->needFreeList == NULL) {
      FPSP->needFreeList = FPSP->lastInFreeList;
    }
    FPSP->lastInFreeList = vnp;

   /* where does this alignment start & stop in bioseq coords? */
    nsegs = AlignSegIteratorCreate(SAlnP, SID, &asi);
    strand = asi.strand;
    if (strand == Seq_strand_unknown)
        strand = Seq_strand_plus;

    if (asi.start < 0 || asi.stop < 0) 
      return NULL;
    finalRFIP->Left = asi.start;
    finalRFIP->Right = asi.stop;
    finalRFIP->featstrand = strand;
    finalRFIP->numivals = 1;
    finalRFIP->ivals = NULL;
    finalRFIP->featdeftype = APPEARANCEITEM_Alignment;
    finalRFIP->circularSpanningOrigin = FALSE;
    finalRFIP->entityID = SAlnP->idx.entityID;
    finalRFIP->itemID = SAlnP->idx.itemID;
    finalRFIP->itemType = SAlnP->idx.itemtype;
    labelbuf[0] = 0;
    if (SeqAlignContentLabel(SAlnP, SID, labelbuf, sizeof(labelbuf) - 1, AIP->format))
    {
        finalRFIP->ContentLabel = StringSave(labelbuf);
    }

    if (nsegs > 1) {
        finalRFIP->ivals = MemNew (2 * nsegs * sizeof (Int4));
        if (finalRFIP->ivals == NULL) 
        {
            MemFree(finalRFIP->ContentLabel);
            return NULL;
        } else {
            finalRFIP->numivals = 0;
            i = 0;
            while (AlignSegIteratorNext(&asi, &start, &stop, NULL, &segType))
            {
                /* ignore gaps on the bioseq */
                /* hence we may have less than nsegs ivals */
                if (segType == AM_GAP) 
                    continue;
                
                if (segType == AM_INSERT) {
                  if (i == 0)
                    start = stop = finalRFIP->Left;
                  else
                    start = stop = finalRFIP->ivals[i - 1];
                }
                finalRFIP->ivals[i++] = start;
                finalRFIP->ivals[i++] = stop;
                finalRFIP->numivals++;
            }
        }
    }
                
    ++alignSP->alignIndex;
    /*
        if we are not done with all the alignments and
        the next alignment(s) has the same accession and strand as this one does
        merge their segments together.
    */
    if (! AlignmentFilterStateDone(alignSP) && 
        alignSorted[alignSP->alignIndex - 1].strand ==  alignSorted[alignSP->alignIndex].strand &&
        StrNCmp(alignSorted[alignSP->alignIndex - 1].label, 
                alignSorted[alignSP->alignIndex].label, MAX_ALIGN_SORT_LABEL) == 0) {
        Int4                    *newIvals;  /* pointer to merged ivals */
        Int4                    newIvalsNum;
        Int1                    *accumulator;
        Int4                    accumBegin, accumEnd, accumLen;
        
        /* keep track of where the segments fall in this array */
        /* 0 - a gap. 1 - a segment. 2 - an insert */
        accumBegin = finalRFIP->Left; 
        accumEnd   = vContext->seqLength;
        accumLen = accumEnd - accumBegin;
        accumulator = MemNew( accumLen * sizeof(Int1) );
        if (accumulator == NULL) {
            return NULL;
        }
        
        AccumIvals(accumulator, accumBegin, accumLen, finalRFIP);
        for ( ;
              ! AlignmentFilterStateDone(alignSP) && 
              alignSorted[alignSP->alignIndex - 1].strand ==  alignSorted[alignSP->alignIndex].strand &&
              StrNCmp(alignSorted[alignSP->alignIndex - 1].label, 
                      alignSorted[alignSP->alignIndex].label, MAX_ALIGN_SORT_LABEL) == 0;
              ++alignSP->alignIndex ) {
        
            SAlnP = alignSorted[alignSP->alignIndex].sap;

          /* where does this alignment start & stop in bioseq coords? */
            nsegs = AlignSegIteratorCreate(SAlnP, SID, &asi);

            if (asi.start < 0 || asi.stop < 0) 
                continue;
            RFI.Left = asi.start;
            finalRFIP->Left = MIN(finalRFIP->Left, RFI.Left);
            RFI.Right = asi.stop;
            finalRFIP->Right = MAX(finalRFIP->Right, RFI.Right);
            RFI.numivals = 1;
            RFI.ivals =  NULL;
            
#ifdef _DEBUG
            if (finalRFIP->Right > vContext->seqLength) { 
                printf("finalRFIP->Right too big: %d\n", finalRFIP->Right); /* put a breakpoint here! */
                return NULL;
            }
#endif            

            if (nsegs > 1) {
                RFI.ivals = MemNew (2 * nsegs * sizeof (Int4));
                if (RFI.ivals == NULL) 
                {
                    MemFree(RFI.ivals);
                } else {
                    RFI.numivals = 0;
                    i = 0;
                    while (AlignSegIteratorNext(&asi, &start, &stop, NULL, &segType))
                    {
                        /* ignore gaps on the bioseq */
                        /* hence we may have less than nsegs ivals */
                        if (segType == AM_GAP) 
                            continue;
                        
                        if (segType == AM_INSERT) {
                          if (i == 0)
                            start = stop = RFI.Left;
                          else
                            start = stop = RFI.ivals[i - 1];
                        }
                        RFI.ivals[i++] = start;
                        RFI.ivals[i++] = stop;
                        RFI.numivals++;
                    }
                }
            }
            AccumIvals(accumulator, accumBegin, accumLen, &RFI);
            if (RFI.ivals != NULL)
                MemFree(RFI.ivals);
        }
        newIvalsNum = CountIvals(accumulator, accumLen);
        newIvals = MemNew( 2 * newIvalsNum * sizeof(Int4) );
        if (newIvals == NULL) {
            MemFree(accumulator);
            return NULL;
        }
        MakeIvals(accumulator, accumBegin, accumLen, newIvals, newIvalsNum);
        MemFree(accumulator);
        
        if (finalRFIP->ivals != NULL)
            MemFree(finalRFIP->ivals);
        finalRFIP->numivals = newIvalsNum;
            
        if (newIvalsNum > 1) {
            finalRFIP->ivals = newIvals;
        } else {
            MemFree(newIvals);
            finalRFIP->ivals = NULL;
        }
    }

    /* remember to delete the final ivals array & label space */
    if (finalRFIP->numivals > 1)
    {
        vnp = ValNodeAddPointer(&FPSP->lastInFreeList, 0, finalRFIP->ivals);
        if (vnp == NULL) {
            MemFree(finalRFIP->ContentLabel);
            MemFree(finalRFIP->ivals);
            return NULL;
        }
        if (FPSP->needFreeList == NULL) {
          FPSP->needFreeList = FPSP->lastInFreeList;
        }
        FPSP->lastInFreeList = vnp;
    }
    vnp = ValNodeAddPointer(&FPSP->lastInFreeList, 0, finalRFIP->ContentLabel);
    if (vnp == NULL)
    {
        MemFree(finalRFIP->ContentLabel);
        return NULL;
    }
    if (FPSP->needFreeList == NULL) {
      FPSP->needFreeList = FPSP->lastInFreeList;
    }
    FPSP->lastInFreeList = vnp;
            
    return finalRFIP;
}


void AccumIvals(Int1* accumulator, Int4 accumBegin, Int4 accumLen, RelevantFeatureItemPtr RFIP)
{
    Int4    i, ai;
    Int4    blockstart, blockend;
    
    /* mark everywhere segments spans. 0 in gaps, 1 in blocks, 2 at inserts */
    if (RFIP->numivals == 1) {
        blockstart = RFIP->Left  - accumBegin;
        blockend   = RFIP->Right - accumBegin;
    
        for (ai = blockstart; ai <= blockend; ++ai)
            if (accumulator[ai] == 0)
                accumulator[ai] = 1;
    }
    else {
        for (i = 0; i < RFIP->numivals; ++i) {
            blockstart = RFIP->ivals[2*i] - accumBegin;
            blockend   = RFIP->ivals[2*i + 1] - accumBegin;
            
#ifdef _DEBUG
            if (blockstart < 0 || accumLen < blockstart || blockend < 0 || accumLen < blockend) {
                printf("AccumIvals problem!"); /* put a breakpoint here! */
                return;
            }
#endif                
            if (blockstart == blockend) {
                accumulator[blockstart] = 2;
            } else {
                for (ai = blockstart; ai <= blockend; ++ai)
                    if (accumulator[ai] == 0)
                        accumulator[ai] = 1;
            }
        }
    }
}

Int4  CountIvals(Int1* accumulator, Int4 accumLen)
{
    Int4    numivalsOut;
    Int4    ai;
    
    /* make new ivals */
    numivalsOut = 0;
    
    for (ai = 0; ai < accumLen; ++ai) {
        if (accumulator[ai] == 0)
            continue;
    /* if it is an insert, add it */
        if (accumulator[ai] == 2) {
            ++numivalsOut;
        } else if (accumulator[ai] == 1) { /* beginning of a block */
            /* find end of block */
            for (; ai < accumLen; ++ai) {
                if (accumulator[ai] != 1)
                    break;
            }
            --ai;
            ++numivalsOut;
        }
    }
    return numivalsOut;
}

void  MakeIvals(Int1* accumulator, Int4 accumBegin, Int4 accumLen, Int4Ptr ivalsOut, Int4 ivalsLen)
{
    Int4    numivalsOut;
    Int4    ai, blocklen;
    
    /* make new ivals */
    numivalsOut = 0;
    
    for (ai = 0; ai < accumLen  &&  numivalsOut < ivalsLen; ++ai) {
    /* ignore spots in gaps. */
        if (accumulator[ai] == 0)
            continue;
    /* if it is an insert, add it */
        if (accumulator[ai] == 2) {
            ivalsOut[numivalsOut * 2]     = accumBegin + ai;
            ivalsOut[numivalsOut * 2 + 1] = accumBegin + ai;
            ++numivalsOut;
        } else if (accumulator[ai] == 1) { /* beginning of a block */
            /* find end of block */
            for (blocklen = 0; ai + blocklen < accumLen; ++blocklen) {
                if (accumulator[ai + blocklen] != 1)
                    break;
            }
            ivalsOut[numivalsOut * 2]     = accumBegin + ai;
            if (accumulator[ai + blocklen] == 2)
                ivalsOut[numivalsOut * 2 + 1] = accumBegin + ai + blocklen;
            else
                ivalsOut[numivalsOut * 2 + 1] = accumBegin + ai + blocklen - 1;
            ++numivalsOut;
            ai += blocklen - 1;
        }
    }
}

/*
  For a given SeqAlign and a given SeqId for a Seq that participates in that SeqAlign,
  keep track of where we are in that alignment so we can iterate through all of that 
  alignment's segments, returning information about each segment.
  Hides the differences between normal/indexable and StdSeg alignments.
*/

/* 
  Create an structure to iterate through all of an alignment's segments.
  return a pointer to that iterator struct that must be deallocated.
   return the number of segments.
*/
static 
Int4 AlignSegIteratorCreate(SeqAlignPtr sap, SeqIdPtr sip,  AlignSegIteratorPtr asip)
{
  Boolean             stdSeg;
  Int4                swap;
  
  if (sap == NULL || sip == NULL  || asip == NULL)
    return 0;
      
  AlnMgr2IndexSingleChildSeqAlign(sap);
  asip->sap = sap;
  asip->sip = sip;
  
  stdSeg = (sap->segtype == SAS_STD);
  if ( ! stdSeg) {
    asip->nsegs = AlnMgr2GetNumSegs(sap);
    asip->alignRow = AlnMgr2GetFirstNForSipList (sap, sip);
    if (asip->alignRow == -1) {
      return 0;
    }
    AlnMgr2GetNthSeqRangeInSA(sap, asip->alignRow, &asip->start, &asip->stop);
    asip->strand = AlnMgr2GetNthStrand(sap, asip->alignRow);
  }
  else {
    asip->nsegs = AlnMgr2GetNumStdSegs(sap);
    asip->alignRow = 0;
    AlnMgr2GetSeqRangeForSipInSAStdSeg(sap, sip, &asip->start, &asip->stop, &asip->strand);
  }

  if (asip->stop < asip->start) {
    swap = asip->stop;
    asip->stop = asip->start;
    asip->start = swap;
  }
  
  asip->currentStdSeg = NULL;
  asip->currentSeg = 0;
  
  return asip->nsegs;
}

/*
  Given an AlignSegIterator return the information about the current segment
  in the pointer arguments, and advance the iterator to the next segment.
  Return false if there are no more segments in which case the output arguments
  will not be changed.
*/
static 
Boolean AlignSegIteratorNext(
  AlignSegIteratorPtr asip, 
  Int4Ptr       startOut, 
  Int4Ptr       stopOut, 
  Uint1Ptr      strandOut,
  Uint1Ptr      segTypeOut
)
{
  Int4    start, stop, swap;
  Uint1   strand, segType;
  Boolean stdSeg;
  Int4    iseg;
  
  
  if (asip == NULL) 
    return FALSE; /* bad argument */

  /* iterate */
  asip->currentSeg++;  
  if (asip->currentSeg > asip->nsegs) /* no more segments */
    return FALSE;
    
  if (asip->strand == Seq_strand_minus)
      iseg = asip->nsegs - asip->currentSeg + 1;
  else
      iseg = asip->currentSeg;
  
  stdSeg = (asip->sap->segtype == SAS_STD);
  if ( ! stdSeg) {
    Int4    alignStart, alignStop;
    Int4    row2, seq2Start;
 
    strand = asip->strand; /* all segments have the same strand */
    /* get segment location in alignment coordinates */
    AlnMgr2GetNthSegmentRange(asip->sap, iseg, &alignStart, &alignStop);
    /* convert to bioseq coordinates */
    start = AlnMgr2MapSeqAlignToBioseq(asip->sap, alignStart, asip->alignRow);
    if (alignStart != alignStop)
        stop  = AlnMgr2MapSeqAlignToBioseq(asip->sap, alignStop , asip->alignRow);
    else
        stop = start;

    /* Is this a insert (a gap on the bioseq)? */
    if (start == -2) {
        segType = AM_INSERT;
    } else {
      /* check the other sequence to see if there is a gap there. */
      if (asip->alignRow == 1)
        row2 = 2;
      else 
        row2 = 1;
      seq2Start = AlnMgr2MapSeqAlignToBioseq(asip->sap, alignStart, row2);

      if (seq2Start == -2 ) 
        segType = AM_GAP;
       else
        segType = AM_SEQ;
    }
  }
  else { /* stdSeg */   
    asip->currentStdSeg = AlnMgr2GetNthStdSeg(asip->sap, iseg);
    if (asip->currentStdSeg == NULL)
        return FALSE;    /* Logic Error. should not happen. */
        
    AlnMgr2GetSeqRangeForSipInStdSeg(asip->currentStdSeg, asip->sip, &start, &stop, &strand, &segType);
  }
  if (stop < start) {
    swap = start;
    start = stop;
    stop = swap;
  }
  
  /* take care of output arguments */
  if (startOut)   *startOut   = start;
  if (stopOut)    *stopOut    = stop;
  if (strandOut)  *strandOut  = strand;
  if (segTypeOut) *segTypeOut = segType;
  
  return TRUE;
}

 
static RelevantFeatureItemPtr GetNextRFIPinFeatureFilter (
  FilterProcessStatePtr FPSP
)

{
  ValNodePtr              currentRFIPblockVNP;
  FeatureFilterStatePtr   featSP;
  RelevantFeatureItemPtr  RFIP = NULL;
  ViewerContextPtr        vContext;
  FilterItemPtr           currentFIP;
  FilterPtr               FP;

  if (FPSP == NULL) return NULL;
  vContext = FPSP->vContext;
  currentFIP = FPSP->currentFIP;
  if (vContext == NULL || currentFIP == NULL) return NULL;
  FP = vContext->FltPtr;
  if (FP == NULL) return NULL;
  
  featSP = &FPSP->state.feat;
  for (; featSP->featureBlockOffset + featSP->indexInBlock < vContext->featureCount; featSP->indexInBlock++) {
    if (featSP->indexInBlock >= RELEVANT_FEATS_PER_CHUNK) {
      featSP->indexInBlock = 0;
      featSP->featureBlockOffset += RELEVANT_FEATS_PER_CHUNK;
      featSP->currentRFIPblockVNP = featSP->currentRFIPblockVNP->next;
      if (featSP->currentRFIPblockVNP == NULL) return NULL;
    }
    currentRFIPblockVNP = featSP->currentRFIPblockVNP;
    RFIP = (RelevantFeatureItemPtr) (currentRFIPblockVNP->data.ptrvalue) + featSP->indexInBlock;
    
    if (FP->GroupByAnnot && RFIP->sap != vContext->currentSAP) continue;
    
    if (! vContext->allFeatures
        && (RFIP->Right < vContext->from || RFIP->Left > vContext->to)) {
      continue;
    }
    if (FPSP->featuresProcessed [featSP->featureBlockOffset + featSP->indexInBlock]
        || (! currentFIP->IncludeFeature [RFIP->featdeftype])) continue;
    if (currentFIP->MatchStrand != BothStrands) {
      if (currentFIP->MatchStrand == MinusStrand && RFIP->featstrand != Seq_strand_minus) continue;
      if (currentFIP->MatchStrand == PlusStrand  && RFIP->featstrand != Seq_strand_plus) continue;
    }
    FPSP->featuresProcessed [featSP->featureBlockOffset + featSP->indexInBlock] = TRUE;
    break;
  }
  if (featSP->featureBlockOffset + featSP->indexInBlock >= vContext->featureCount) return NULL;
  return RFIP;
}



static RelevantFeatureItemPtr GetNextRFIPinFilterItem (
  FilterProcessStatePtr FPSP
)

{
  AlignmentFilterStatePtr alignSP;
  RelevantFeatureItemPtr  RFIP = NULL;
  ViewerContextPtr        vContext;
  FilterItemPtr           currentFIP;

  /* called as an iterator by the rendering functions -- builds & returns the next feature (in an RFIP), or returns NULL if no more left in this Filter */
  if (FPSP == NULL) return NULL;
  vContext = FPSP->vContext;
  currentFIP = FPSP->currentFIP;
  if (vContext == NULL || currentFIP == NULL) return NULL;
  switch (currentFIP->Type) {
  case InvalidFilter:
  case GraphFilter:
  case BioseqFilter:
    return NULL;
  case AlignmentFilter:
    alignSP = &FPSP->state.align;
    while (!AlignmentFilterStateDone(alignSP)) {
      RFIP = GetNextRFIPinAlignmentFilter (FPSP);
      if (RFIP != NULL) 
        return RFIP;
    } 
    /* note: if control reaches here, then RFIP == NULL */
    break;
  case FeatureFilter:
    RFIP = GetNextRFIPinFeatureFilter (FPSP);
    break;
  }
  if (RFIP != NULL) {
    FPSP->featuresProcessedCount++;
  }
  return RFIP;
}

static Boolean AddFeatureToRow (
  InternalRowPtr row,
  RelevantFeatureItemPtr RFIP,
  Boolean SkipSmearTest,
  FilterProcessStatePtr FPSP
)

{
  ValNodePtr             VNP;
  RelevantFeatureItemPtr newRFIP; /* for representing a multi-feature smear */
  RelevantFeatureItemPtr oldRFIP;
  ViewerContextPtr       vContext;

  vContext = FPSP->vContext;

  if (row == NULL || RFIP == NULL) return FALSE;

  if (!SkipSmearTest && row->rowFeatureCount &&
      TestForSmear (RFIP, (RelevantFeatureItemPtr) row->feats->data.ptrvalue, vContext->viewScale)) {
    /* if the last feature was not a smear-in-progress, allocate newRFIP, else re-use the current one */
    oldRFIP = (RelevantFeatureItemPtr) row->feats->data.ptrvalue;
    if (oldRFIP->entityID == 0 && oldRFIP->itemID == 0) {
      /* oldRFIP is already a smear-in-prorgess, just extend it */
      newRFIP = oldRFIP;
    } else {
      /* need to create a new smear */
      newRFIP = MemNew (sizeof (RelevantFeatureItem));
      VNP = MemNew (sizeof (ValNode));
      if (newRFIP == NULL || VNP == NULL) return FALSE;
      VNP->data.ptrvalue = newRFIP;
      VNP->next = FPSP->needFreeList;
      FPSP->needFreeList = VNP;
      row->feats->data.ptrvalue = newRFIP;
      newRFIP->featdeftype = oldRFIP->featdeftype;
      newRFIP->numivals = 1;
    }

    newRFIP->Left = MIN (oldRFIP->Left, RFIP->Left);
    newRFIP->Right = MAX (oldRFIP->Right, RFIP->Right);
  } else {

    VNP = MemNew (sizeof (ValNode));
    if (VNP == NULL) return FALSE;
    VNP->data.ptrvalue = RFIP;
    VNP->next = row->feats;
    row->feats = VNP;
    row->rowFeatureCount++;
  }
  return TRUE;
}

static InternalRowPtr AddARow (
  InternalRowPtr sourceRow
)

{
  InternalRowPtr  IRP;

  if (sourceRow == NULL) return NULL;
  IRP = MemNew (sizeof (InternalRow));
  if (IRP == NULL) return NULL;
  sourceRow->next = IRP;
  return IRP;
}

static Uint2 SimpleDiagonalLayout (
  InternalRowPtr firstRow,
  FilterProcessStatePtr FPSP
)

{
  Uint2                   rows = 0;
  InternalRowPtr          thisRow;
  RelevantFeatureItemPtr  RFIP;

  thisRow = firstRow;
  if (thisRow == NULL) return 0;
  thisRow->rowFeatureCount = 0;
  while ((RFIP = GetNextRFIPinFilterItem (FPSP)) != NULL) {
    AddFeatureToRow (thisRow, RFIP, TRUE, FPSP);
    thisRow = AddARow (thisRow);
    rows++;
  }
  return rows;
}

/* this was copied from seqmgr.c (6.181, 27-feb-2002) */
static Boolean CheckInternalExonBoundaries (Int2 numivalsCDS, Int4Ptr ivalsCDS, Int2 numivalsMRNA, Int4Ptr ivalsMRNA)

{
  Int2  i;
  Int2  j;

  if (numivalsCDS > numivalsMRNA) return FALSE;
  if (ivalsCDS == NULL || ivalsMRNA == NULL) return TRUE;

  /* scan first exon-intron boundary against candidate start positions */

  for (i = 0; i <= numivalsMRNA - numivalsCDS; i++) {
    if (ivalsCDS [1] == ivalsMRNA [2 * i + 1]) break;
  }
  if (i > numivalsMRNA - numivalsCDS) return FALSE;

  /* Addition by Eric: the first interval in the CDS must not be larger than the corresponding interval in the mRNA */
  if (ABS (ivalsCDS [0] - ivalsCDS [1]) > ABS (ivalsMRNA [2 * i] - ivalsMRNA [2 * i + 1])) return FALSE;

  /* scan subsequent exon-intron and intron-exon boundaries */

  for (j = 2; j <= 2 * numivalsCDS - 2; j++) {
    if (ivalsCDS [j] != ivalsMRNA [2 * i + j]) return FALSE;
  }

  /* Addition by Eric: the last interval in the CDS must not be larger than the corresponding interval in the mRNA */
  if (ABS (ivalsCDS [j - 1] - ivalsCDS [j]) > ABS (ivalsMRNA [2 * i + j - 1] - ivalsMRNA [2 * i + j])) return FALSE;

  return TRUE;
}

static Boolean mRNAmatchesCDS (
  RelevantFeatureItemPtr mRNA,
  RelevantFeatureItemPtr CDS
)

{
  /* the mRNA must be the larger feature */
  if (CDS->Left < mRNA->Left || CDS->Right > mRNA->Right) return FALSE;
  /* check strands (anything not equal to strand minus is equal to each other) */
  if (CDS->featstrand != mRNA->featstrand && 
      (CDS->featstrand == Seq_strand_minus || mRNA->featstrand == Seq_strand_minus)) 
    return FALSE;
  /* trivial case */
  if (CDS->numivals == 1 && mRNA->numivals == 1) return TRUE;
  /* . . . and the intervals must line up */
  return CheckInternalExonBoundaries (CDS->numivals, CDS->ivals, mRNA->numivals, mRNA->ivals);
}

typedef struct rFIPentry {
  RelevantFeatureItemPtr RFIP;
  Int4                   decorationLeft;
  Int4                   decorationRight;
  Int4                   Right;
  Int4                   Left;
  Boolean                used;
} RFIPentry, PNTR RFIPentryPtr;

typedef struct rFIPgroup {
  Uint4       memberCount;
  Int4        decorationLeft;
  Int4        decorationRight;
  Int4        Left;
  Int4        Right;
  ValNodePtr  members; /* data.ptrvalue = RFIPentryPtr */
} RFIPgroup, PNTR RFIPgroupPtr;


static Uint2 GeneProductsLayoutInternal (
  InternalRowPtr firstRow,
  FilterProcessStatePtr FPSP,
  Boolean MultiRender
)

{
  Uint2                   rows = 1, i;
  RelevantFeatureItemPtr  RFIP, RFIPcds, RFIPmrna, tRFIP;
  InternalRowPtr          thisRow, thisRow2, lastRow;
  ValNodePtr              fifoHead = NULL, fifoTail = NULL;
  ValNodePtr              bumpedListHead = NULL, bumpedListTail = NULL;
  ValNodePtr              potCDSvnp, potRNAvnp;
  ValNodePtr              GroupsHead = NULL, GroupsTailVNP, MemberTailVNP;
  ValNodePtr              groupVNP, featVNP;
  RFIPentryPtr            tRFIPentry;
  RFIPentryPtr            bumpedListEntry;
  RFIPentryPtr            potCDS, potRNA, GroupsTailMemberTail;
  Uint2                   bumpedCount;
  Boolean                 foundRows, doneCollecting = FALSE;
  Int4                    newLeft, featureStart, rowMaxRight;
  RenderInput             dummyRI;
  RFIPgroupPtr            currentGroup;
  Uint4                   viewScale;
  
  viewScale =  FPSP->vContext->viewScale;

  if (firstRow == NULL) return 0;

  lastRow = firstRow;
  firstRow->layoutData.intvalue = -2000000000; /* the first feature will _always_ fit in the first row */

  while (1) {
    if (doneCollecting) {
      break;
    }
    RFIP = GetNextRFIPinFilterItem (FPSP);
    if (RFIP == NULL) {
      doneCollecting = TRUE;
      bumpedListHead = fifoHead; /* no more incoming features, bump all features in the queue*/
      bumpedListTail = fifoTail;
      fifoHead = NULL;
    } else {
      if (! BuildRenderInputFromRFIP (&dummyRI, RFIP, FPSP)) {
        continue; /* either we're out of memory or this feature doesn't overlap the clipping SeqLoc */
      }

      if ((tRFIPentry = MemNew (sizeof (RFIPentry))) == NULL) goto bail_out;
      if (fifoHead == NULL) {
        fifoTail = ValNodeAddPointer (&fifoHead, 0, tRFIPentry);
      } else {
        fifoTail = ValNodeAddPointer (&fifoTail, 0, tRFIPentry);
      }
      if (fifoTail == NULL) goto bail_out;
      tRFIPentry->RFIP = RFIP;
      tRFIPentry->Left = RFIP->Left;
      tRFIPentry->Right = RFIP->Right;
      tRFIPentry->decorationLeft = dummyRI.decorationLeft;
      tRFIPentry->decorationRight = dummyRI.decorationRight;

    /*
      now find all features which can not overlap the next feature (in the sequence; decoration overlap doesn't matter)
    */
      newLeft = RFIP->Left;

      bumpedCount = 0;
      bumpedListHead = fifoHead;
      for (featVNP = fifoHead;
           featVNP != NULL;
           featVNP = featVNP->next) {
        bumpedListEntry = featVNP->data.ptrvalue;
        RFIP = bumpedListEntry->RFIP;
        if (RFIP->Right > newLeft) break;
        bumpedListTail = featVNP;
        fifoHead = featVNP->next;
        bumpedCount++;
      }
      if (bumpedCount == 0) continue;
    }
    if (bumpedListTail != NULL) {
      bumpedListTail->next = NULL;
    }
    GroupsHead = GroupsTailVNP = NULL;

    for (potCDSvnp = bumpedListHead; potCDSvnp != NULL; potCDSvnp = potCDSvnp->next) {
      /* this pass is only searching for CDS features (and correspondins mRNAs) */
      potCDS = potCDSvnp->data.ptrvalue;
      RFIPcds = potCDS->RFIP;
      if (RFIPcds->featdeftype != FEATDEF_CDS) continue;
      potCDS->used = TRUE;

      if ((currentGroup = MemNew (sizeof (RFIPgroup))) == NULL) goto bail_out;
      if (GroupsHead == NULL) {
        GroupsTailVNP = ValNodeAddPointer (&GroupsHead, 0, currentGroup);
      } else {
        GroupsTailVNP = ValNodeAddPointer (&GroupsTailVNP, 0, currentGroup);
      }
      if (GroupsTailVNP == NULL) goto bail_out;

      /* do not add the CDS to currentGroup->members yet, b/c we want mRNA features to appear first
         (but remember to add it after!) */

      currentGroup->memberCount = 1;
      currentGroup->members = NULL;

      currentGroup->Left = potCDS->Left;
      currentGroup->Right = potCDS->Right;
      currentGroup->decorationLeft = potCDS->decorationLeft;
      currentGroup->decorationRight = potCDS->decorationRight;

      for (potRNAvnp = bumpedListHead; potRNAvnp != NULL; potRNAvnp = potRNAvnp->next) {
        potRNA = potRNAvnp->data.ptrvalue;
        RFIPmrna = potRNA->RFIP;
        if (RFIPmrna->featdeftype != FEATDEF_mRNA) continue;
        if (!MultiRender && potRNA->used) continue;

        if (mRNAmatchesCDS (RFIPmrna, RFIPcds)) {
          potRNA->used = TRUE;

          if ((tRFIPentry = MemNew (sizeof (RFIPentry))) == NULL) goto bail_out;
          if (ValNodeAddPointer (&currentGroup->members, 0, tRFIPentry) == NULL) goto bail_out;

          MemCopy (tRFIPentry, potRNA, sizeof (RFIPentry));

          currentGroup->memberCount++;
          currentGroup->Left = MIN (currentGroup->Left, RFIPmrna->Left);
          currentGroup->Right = MAX (currentGroup->Right, RFIPmrna->Right);
          currentGroup->decorationLeft = MIN (currentGroup->decorationLeft, potRNA->decorationLeft);
          currentGroup->decorationRight = MAX (currentGroup->decorationRight, potRNA->decorationRight);
        }
      }

      if ((GroupsTailMemberTail = MemNew (sizeof (RFIPentry))) == NULL) goto bail_out;
      if (ValNodeAddPointer (&currentGroup->members, 0, GroupsTailMemberTail) == NULL) goto bail_out;
      MemCopy (GroupsTailMemberTail, potCDS, sizeof (RFIPentry));

    }
    /*
      append all non-matched elements to the Groups list
    */
    for (featVNP = bumpedListHead; featVNP != NULL; featVNP = featVNP->next) {
      tRFIPentry = featVNP->data.ptrvalue;
      /* skip feature if it's been matched already */
      if (tRFIPentry->used) {
        continue;
      } else {
        /* add another singleton entry to Groups */
        tRFIP = tRFIPentry->RFIP;

        if ((currentGroup = MemNew (sizeof (RFIPgroup))) == NULL) goto bail_out;
        if (GroupsHead == NULL) {
          GroupsTailVNP = ValNodeAddPointer (&GroupsHead, 0, currentGroup);
        } else {
          GroupsTailVNP = ValNodeAddPointer (&GroupsTailVNP, 0 ,currentGroup);
        }
        if (GroupsTailVNP == NULL) goto bail_out;

        if ((GroupsTailMemberTail = MemNew (sizeof (RFIPentry))) == NULL) goto bail_out;
        if ((MemberTailVNP = ValNodeAddPointer (&currentGroup->members, 0, GroupsTailMemberTail)) == NULL) goto bail_out;

        currentGroup->memberCount = 1;
        MemCopy (GroupsTailMemberTail, tRFIPentry, sizeof (RFIPentry));

        currentGroup->Left = tRFIP->Left;
        currentGroup->Right = tRFIP->Right;
        currentGroup->decorationLeft = tRFIPentry->decorationLeft;
        currentGroup->decorationRight = tRFIPentry->decorationRight;

      }
    }

    /*
      now, assign each element in Groups to a row.  algorithm is the same as in BubbleUpLayout,
      except that instead of looking for the first matching row, need to find (RFIPgroup->members)
      consecutive free rows.
    */
    for (groupVNP = GroupsHead; groupVNP != NULL; groupVNP = groupVNP->next) {
      currentGroup = groupVNP->data.ptrvalue;

      featureStart = currentGroup->decorationLeft;
      for (thisRow = firstRow; thisRow != NULL; thisRow = thisRow->next) {
        foundRows = TRUE;
        for (i = 0, thisRow2 = thisRow, featVNP = currentGroup->members;
             featVNP != NULL && i < currentGroup->memberCount;
             thisRow2 = thisRow2->next, featVNP = featVNP->next, i++) {
          tRFIPentry = featVNP->data.ptrvalue;
/*
  note: if thisRow2 ends up being NULL then it meas thisRow was a good starting point and we just need to add some rows
*/
          if (thisRow2 == NULL) {
            foundRows = TRUE;
            break;
          }
          rowMaxRight = thisRow2->layoutData.intvalue;
          if ( tRFIPentry->decorationLeft <= rowMaxRight  ||   
                NoVisibleGap(tRFIPentry->decorationLeft, rowMaxRight, viewScale) ) {
            foundRows = FALSE;
            if (thisRow2->next == NULL) {
              rows++;
              if ((lastRow = AddARow (lastRow)) == NULL) goto bail_out;
              lastRow->layoutData.intvalue = -2000000000;
            }
            break;
          }
        }
        if (foundRows) {
          for (i = 0,
                 thisRow2 = thisRow,
                 featVNP = currentGroup->members;
               tRFIPentry != NULL
                 && i < currentGroup->memberCount;
               featVNP = featVNP->next,
                 thisRow2 = thisRow2->next,
                 i++) {
            tRFIPentry = featVNP->data.ptrvalue;
            RFIP = tRFIPentry->RFIP;
            if (thisRow2 == NULL) {
              rows++;
              if ((lastRow = AddARow (lastRow)) == NULL) goto bail_out;
              thisRow2 = lastRow;
            }
            AddFeatureToRow (thisRow2, RFIP, FALSE, FPSP);
            rowMaxRight = tRFIPentry->decorationRight;
            thisRow2->layoutData.intvalue = rowMaxRight;
          }
          break;
        }
      }
    }
    bumpedListHead = ValNodeFreeData (bumpedListHead);
    for (groupVNP = GroupsHead; groupVNP != NULL; groupVNP = groupVNP->next) {
      currentGroup = groupVNP->data.ptrvalue;
      ValNodeFreeData (currentGroup->members);
    }
    GroupsHead = ValNodeFreeData (GroupsHead);
  }
bail_out:
  ValNodeFreeData (bumpedListHead);
  ValNodeFreeData (fifoHead);
  for (groupVNP = GroupsHead; groupVNP != NULL; groupVNP = groupVNP->next) {
    currentGroup = groupVNP->data.ptrvalue;
    ValNodeFreeData (currentGroup->members);
  }
  GroupsHead = ValNodeFreeData (GroupsHead);
  return rows;
}

static Uint2 GeneProductsLayout (
  InternalRowPtr firstRow,
  FilterProcessStatePtr FPSP
)

{
  return GeneProductsLayoutInternal (firstRow, FPSP, FALSE);
}

static Uint2 GeneProductsLayoutX (
  InternalRowPtr firstRow,
  FilterProcessStatePtr FPSP
)

{
  return GeneProductsLayoutInternal (firstRow, FPSP, TRUE);
}

static Uint2 BubbleUpLayout (
  InternalRowPtr firstRow,
  FilterProcessStatePtr FPSP
)

{
  Uint2                   rows = 1;
  Int4                    featureStart, rowMaxRight;
  RelevantFeatureItemPtr  RFIP;
  InternalRowPtr          thisRow, lastRow;
  RenderInput             dummyRI;
  Uint4                   viewScale;
  
  viewScale =  FPSP->vContext->viewScale;
  /*
     This uses InternalRow.layoutData as an Int4, which stores the (x) offset of the last used pixel.
     so a feature starting at (internalRow.layoutData + 1) or greater can be placed in the same row
     without a collision.
   */

  /* add the 1st feature to the 1st row */
  do {
    RFIP = GetNextRFIPinFilterItem (FPSP);
    if (RFIP == NULL) return 0;
  } while (! BuildRenderInputFromRFIP (&dummyRI, RFIP, FPSP));

  AddFeatureToRow (firstRow, RFIP, FALSE, FPSP);
  lastRow = firstRow;
  firstRow->layoutData.intvalue = dummyRI.decorationRight;

  while ((RFIP = GetNextRFIPinFilterItem (FPSP)) != NULL) {
    if (! BuildRenderInputFromRFIP (&dummyRI, RFIP, FPSP)) {
      continue;
    }
    featureStart = dummyRI.decorationLeft;
    for (thisRow = firstRow; thisRow != NULL; thisRow = thisRow->next) {
      rowMaxRight = thisRow->layoutData.intvalue;
      if (featureStart >= rowMaxRight  &&  
            ! NoVisibleGap(featureStart, rowMaxRight, viewScale) ) {
        AddFeatureToRow (thisRow, RFIP, FALSE, FPSP);
        rowMaxRight = MAX (rowMaxRight, dummyRI.decorationRight);
        thisRow->layoutData.intvalue = rowMaxRight;
        RFIP = NULL;
        break;
      }
    }
    if (RFIP != NULL) {
      rows++;
      lastRow = AddARow (lastRow);
      AddFeatureToRow (lastRow, RFIP, FALSE, FPSP);
      rowMaxRight = dummyRI.decorationRight;
      lastRow->layoutData.intvalue = rowMaxRight;
    }
  }
  return rows;
}

static Uint2 SingleRowLayout (
  InternalRowPtr firstRow,
  FilterProcessStatePtr FPSP
)

{
  RelevantFeatureItemPtr RFIP, lastRFIP;
  ValNodePtr       freeVNP, vnp;
  Uint4            smearStart, smearStop;
  Uint1            smearFeatdeftype;
  ViewerContextPtr vContext;
  Uint4            viewScale;
  Boolean          adjacentNoGap;
  Boolean          tooNarrow;
  Boolean          smearing = FALSE, justSmeared = FALSE;

  vContext = FPSP->vContext;
  viewScale = vContext->viewScale;
  lastRFIP = GetNextRFIPinFilterItem (FPSP);
  if (lastRFIP == NULL)
    return 0;
  smearFeatdeftype = lastRFIP->featdeftype;

  while ((RFIP = GetNextRFIPinFilterItem (FPSP)) != NULL) {
    adjacentNoGap =  PixelsBetweenSeqCoords(lastRFIP->Right, RFIP->Left, viewScale) < 2; /* was 3 */
    /* TestForSmearOverlap (lastRFIP->Right + 2 * vContext->viewScale, RFIP->Left, vContext); */
    tooNarrow = PixelsBetweenSeqCoords(RFIP->Left,  RFIP->Right, viewScale) < 5;
    /* TestForSmearOverlap (RFIP->Left + 4 * vContext->viewScale, RFIP->Right, vContext); */
    if (adjacentNoGap && tooNarrow) {
      if (smearing == FALSE) {
        tooNarrow = PixelsBetweenSeqCoords(lastRFIP->Left, lastRFIP->Right, viewScale) < 5;
        /* TestForSmearOverlap (lastRFIP->Left + 4 * vContext->viewScale, lastRFIP->Right, vContext); */
        if (tooNarrow) {
          smearStart = lastRFIP->Left;
        } else {
          smearStart = RFIP->Left;
        }
        smearing = TRUE;
      }
      justSmeared = TRUE;
      if (smearFeatdeftype != RFIP->featdeftype) {
        smearFeatdeftype = FEATDEF_ANY;
      } else if (smearFeatdeftype == 0) {
        smearFeatdeftype = RFIP->featdeftype;
      }
      smearStop = RFIP->Right;
      continue;
    }
    /* VNP is non-NULL during a smear; this tests for regular features*/
    if (! justSmeared) {
      AddFeatureToRow (firstRow, lastRFIP, TRUE, FPSP);
      lastRFIP = RFIP;
    } else { /* we just finished a smear group */
      lastRFIP = MemNew (sizeof (RelevantFeatureItem));
      if (lastRFIP == NULL) return 1;
      lastRFIP->Left = smearStart;
      lastRFIP->Right = smearStop;
      lastRFIP->featstrand = Seq_strand_unknown;
      lastRFIP->circularSpanningOrigin = FALSE;
      lastRFIP->LeftEnd = lastRFIP->RightEnd = EndAbsolute;
      lastRFIP->circularSpanningOrigin = FALSE;
      lastRFIP->featdeftype = smearFeatdeftype;
      lastRFIP->numivals = 1;
      vnp = ValNodeAddPointer (&FPSP->lastInFreeList, 0, lastRFIP);
      if (FPSP->needFreeList == NULL) {
        FPSP->needFreeList = FPSP->lastInFreeList;
      }
      FPSP->lastInFreeList = vnp;
      smearing = FALSE;
      AddFeatureToRow (firstRow, lastRFIP, TRUE, FPSP);
      justSmeared = FALSE;
      lastRFIP = RFIP;
    }
  }
  if (! justSmeared) { /* the last feature was not in a smear group */
    AddFeatureToRow (firstRow, lastRFIP, TRUE, FPSP);
  } else {
    RFIP = MemNew (sizeof (RelevantFeatureItem));
    if (RFIP == NULL) return 1;
    RFIP->Left = smearStart;
    RFIP->Right = smearStop;
    RFIP->featstrand = Seq_strand_unknown;
    RFIP->circularSpanningOrigin = FALSE;
    
    RFIP->LeftEnd = RFIP->RightEnd = EndAbsolute;
    RFIP->featdeftype = smearFeatdeftype;
    RFIP->numivals = 1;

    if ((freeVNP = MemNew (sizeof (ValNode))) == NULL) {
      MemFree (RFIP);
      return 1;
    }
    freeVNP->data.ptrvalue = RFIP;
    freeVNP->next = FPSP->needFreeList;
    FPSP->needFreeList = freeVNP;

    AddFeatureToRow (firstRow, RFIP, TRUE, FPSP);
  }
  return 1;
}


/* 
  Call DrawNameAnnotbox() in a sub-function of FilterAndLayout, when you know that something
  will be drawn in as a result of this call to FilterAndLayout in the current sanLevelSeg.
  return FALSE if there is an error. Return true whether we draw anything or not.
*/
static 
Boolean DrawNamedAnnotBox(FilterProcessStatePtr FPSP)
{
  ViewerContextPtr vContext;
  CharPtr          annotName;
  FilterPtr        FP;
  
  if (FPSP == NULL) /* something wrong !? */
    return FALSE;
  vContext = FPSP->vContext;
  if (vContext == NULL)
    return FALSE;
  if (vContext->sanLevelSeg == NULL)
    return FALSE;
  if ((FP = vContext->FltPtr) == NULL)
    return FALSE;

  if (!FP->GroupByAnnot) /* we are not grouping by named annotations */
    return TRUE;
    
  annotName = GetSeqAnnotName(vContext->currentSAP);
  if (annotName == NULL)  /* we are currently not working on a named Seq Annot. */
    return TRUE;
    
  if (FP->DrawAnnotBox && !FPSP->annotBoxDrawn) /* We should draw the box and it hasn't been done yet. */
  {
    AddAttribute (vContext->sanLevelSeg, COLOR_ATT, FP->AnnotBoxColor, 0, 0, 0, 0);
    AddSilentSegRect (vContext->sanLevelSeg, FALSE, 0);
    FPSP->ceiling -= 5;
    FPSP->annotBoxDrawn = TRUE;
  }
  
  /* Have a label that should be drawn at the top of the box? */
  if (!FPSP->annotLabelDrawn && !StringHasNoText (annotName))
  {
    AddAttribute (vContext->sanLevelSeg, COLOR_ATT, FP->AnnotLabelColor, 0, 0, 0, 0);
    switch (FP->AnnotLabelLoc) {
    case LabelOnTop:
      AddTextLabel (vContext->sanLevelSeg, (vContext->from + vContext->to) / 2, FPSP->ceiling,
                    annotName, FP->AnnotLabelFont, 1, LOWER_CENTER, 0);
      SelectFont(FP->AnnotLabelFont);
      FPSP->ceiling -=  LineHeight () + 4;
      break;
    case LabelOnSide:
      AddTextLabel (vContext->sanLevelSeg, 0, FPSP->ceiling, 
                    annotName, FP->AnnotLabelFont, 1, LOWER_RIGHT, 0);
      break;
    default:
      break;
    }
    FPSP->annotLabelDrawn = TRUE;
  }
  return TRUE;
}

/* 
  Call DrawFilterItemBoxLabel() in a sub-function of FilterAndLayout, when you know that something
  will be drawn in as a result of this call to FilterAndLayout in the current filterSeg (vc->drawOnMe).
  return FALSE if there is an error. Return true whether we draw anything or not.
*/
static Boolean DrawFilterItemBoxLabel(
  FilterProcessStatePtr FPSP,
  FilterItemPtr FIP
)
{
  ViewerContextPtr    vContext;
  SegmenT             invisibleSeg;

  if (FPSP == NULL) /* something wrong !? */
    return FALSE;
  vContext = FPSP->vContext;
  if (vContext == NULL)
    return FALSE;
  if (vContext->drawOnMe == NULL)
    return FALSE;
  
  if (FIP->DrawGroupBox && !FPSP->groupBoxDrawn) /* want to draw it, or already drawn. */
  {   
    AddAttribute (vContext->drawOnMe, COLOR_ATT, FIP->GroupBoxColor, 0, 0, 0, 0);
    AddSilentSegRect (vContext->drawOnMe, FALSE, 0);
    FPSP->ceiling -= 5;
    /* add invisible line to force width of SegRect */
    invisibleSeg = CreateSegment (vContext->drawOnMe, 0, 0);
    SetSegmentVisibleFlag (invisibleSeg, FALSE);
    AddLine (invisibleSeg, vContext->from - 1 * vContext->viewScale ,  FPSP->ceiling , 
                           vContext->to + 1 * vContext->viewScale ,  FPSP->ceiling, FALSE, 0);
    FPSP->groupBoxDrawn = TRUE;
  }
    
  /* need to draw a label on top? */
  if (FIP->GroupLabelLoc == LabelOnTop && !FPSP->groupLabelDrawn && !StringHasNoText (FIP->GroupLabel)) {
    AddAttribute (vContext->drawOnMe, COLOR_ATT, FIP->GroupLabelColor, 0, 0, 0, 0);
    AddTextLabel (vContext->drawOnMe, (vContext->from + vContext->to) / 2, FPSP->ceiling,
                  FIP->GroupLabel, FIP->GroupLabelFont, 1, LOWER_CENTER, 0);
    SelectFont (FIP->GroupLabelFont);
    FPSP->ceiling -= LineHeight () + 4;
    FPSP->groupLabelDrawn = TRUE;
  }

  return TRUE;
}



static const LayoutFunction LayoutAlgorithmTable [] = {
  BubbleUpLayout,             /* placeholder for Layout_Inherit */
  SimpleDiagonalLayout,       /* Layout_Diagonal */
  /*  SimpleDiagonalLayout,*/ /* Layout_DiagonalSawtooth (to be implemented) */
  SingleRowLayout,            /* Layout_FeatTypePerLine (same as single-row, but features are grouped by type before processing) */
  BubbleUpLayout,             /* Layout_FeatTypePerLineGroup (same as bubble-up, but features are grouped by type before processing) */
  /*SingleRowLayout,*/        /* Layout_AllInOneLine (which isn't working currently, and may be less useful than expected*/
  BubbleUpLayout,             /* Layout_PackUpward */
  GeneProductsLayout,         /* Layout_GroupCorrespondingFeats (?working?) */
  GeneProductsLayoutX         /* Layout_GroupCorrespondingFeatsRepeat (?working?) */
};

/* non-leaf segments contain SEGMENT_TREE_BASE other segments */
#define SEGMENT_TREE_BASE 16
#define SEGMENT_TREE_BASE2 (SEGMENT_TREE_BASE * SEGMENT_TREE_BASE)
#define SEGMENT_TREE_BASE3 (SEGMENT_TREE_BASE * SEGMENT_TREE_BASE * SEGMENT_TREE_BASE)

static Uint2 ProcessRows (
  LayoutAlgorithm layoutC,
  FilterProcessStatePtr FPSP,
  ViewerContextPtr vContext
)

{
  Uint2                   I, J, K, lastI, lastJ, lastK; /* for keeping track of which segment in the tree we're in*/
  Uint1                   featdeftype;
  Int4                    featMidPoint;
  Uint2                   row, rowCount, rowHeight, totalHeight;
  Uint4                   feat;
  InternalRowPtr          firstRow, thisRow;
  ValNodePtr              VNP;
  RelevantFeatureItemPtr  RFIP;
  RenderInput             RI;           /* dummy used while finding height of each row */
  SegmenT                 SegmentTreeTop;
  SegmenT                 SegmentTreeMid;
  SegmenT                 SegmentTreeBot;
  Boolean                 SegmentChanged = TRUE;
  Boolean                 emptyRow = TRUE;
  Boolean                 allEmpty = TRUE;
  FilterItemPtr           FIP;

  firstRow = MemNew (sizeof (InternalRow));
  if (firstRow == NULL) return 0;
  firstRow->feats = NULL;
  VNP = FPSP->currentFilterVNP;
  if (VNP == NULL) return 0;
  FIP = (FilterItemPtr) VNP->data.ptrvalue;

  rowCount = (*LayoutAlgorithmTable [layoutC]) (firstRow, FPSP);

  thisRow = firstRow;
  totalHeight = 0;

  for (row = 0; row < rowCount; row++) {
    if (thisRow == NULL) continue;
    /*First iterate through features to find the row's height */
    VNP = thisRow->feats;
    rowHeight = 0;
    if (thisRow->rowFeatureCount > 0) {
      allEmpty = FALSE;
    }
    for (feat = 0; feat < thisRow->rowFeatureCount; feat++) {
      RFIP = VNP->data.ptrvalue;
      if (VNP == NULL) break;
      VNP = VNP->next;
      if (RFIP == NULL) return 0;
      if (! BuildRenderInputFromRFIP (&RI, RFIP, FPSP)) {
        continue;
      }
      rowHeight = MAX (rowHeight, RI.decorationHeight);
    }
    if (!allEmpty)
    {
      DrawNamedAnnotBox(FPSP);
      DrawFilterItemBoxLabel(FPSP, FIP);
    }

    /*Repeat, but actually draw them this time */
    VNP = thisRow->feats;
    RI.rowHeight = rowHeight;
    RI.yStart = FPSP->ceiling - totalHeight;
    if (thisRow->rowFeatureCount > 0) {
      emptyRow = FALSE;
    } else {
      emptyRow = TRUE;
    }
    I = J = K = 0;
    SegmentChanged = TRUE;
    for (feat = 0; feat < thisRow->rowFeatureCount; feat++) {
      if (VNP == NULL) break;
      if ((RFIP = VNP->data.ptrvalue) == NULL) return 0;
      VNP = VNP->next;
      featdeftype = RFIP->featdeftype;
      featMidPoint = (RFIP->Left + RFIP->Right) / 2;
      lastI = I;
      lastJ = J;
      lastK = K;
      I = (SEGMENT_TREE_BASE * featMidPoint) / vContext->seqLength;
      J = ((SEGMENT_TREE_BASE2 * featMidPoint) / vContext->seqLength) % SEGMENT_TREE_BASE;
      K = ((SEGMENT_TREE_BASE3 * featMidPoint) / vContext->seqLength) % SEGMENT_TREE_BASE;

      if (I != lastI || SegmentChanged) {
        SegmentTreeTop  = CreateSegment (vContext->drawOnMe, 0, 0);
        SegmentChanged = TRUE;
      }
      if (J != lastJ || SegmentChanged) {
        SegmentTreeMid = CreateSegment (SegmentTreeTop , 0, 0);
        SegmentChanged = TRUE;
      }
      if (K != lastK || SegmentChanged) {
        SegmentTreeBot = CreateSegment (SegmentTreeMid, 0, 0);
        SegmentChanged = TRUE;
      }
      if (SegmentChanged) {
        MemSet (FPSP->drawSegs, 0, sizeof (FPSP->drawSegs));
        MemSet (FPSP->labelSegs, 0, sizeof (FPSP->labelSegs));
        SegmentChanged = FALSE;
      }
      if (! EnsureFeatureHasSegment (FPSP, featdeftype, SegmentTreeBot)) return 0;
      if (! BuildRenderInputFromRFIP (&RI, RFIP, FPSP)) {
        continue;
      }

      DrawFeatureAndLabel (&RI, vContext);
    }
    if (! emptyRow) {
      totalHeight += rowHeight + FPSP->currentFIP->IntraRowPaddingPixels;
    }
    if (thisRow->next == NULL) break;
    thisRow = thisRow->next;
  }
  if (allEmpty) {
    return 0;
  }
  return totalHeight;
}

typedef struct scalesntdata {
  SegmenT                   seg;
  PrimitivE                 snt;
  BoxInfo                   box;
  Int4                      length;
  Int4                      labelOffset;
  BioseqAppearanceItemPtr   bioseqAIP;
  Boolean                   disableLastLabel;
  Boolean                   disableFirstLabel;
  Int4                      offset;
} ScaleSntData, PNTR ScaleSntPtr;

static void ScaleSntDrawProc (
  BigScalar calldata,
  PrimDrawContext pdc
)

{
  Int4                     curScale;
  DrawInfoPtr              dInfoPtr;
  Int4                     i, j;
  RecT                     r;
  PntInfo                  pnt;
  PoinT                    pt;
  ScaleSntPtr              ssp;
  BoxInfo                  tmpBox;
  Uint1                    tickCount;
  Char                     buffer[16];
  BioseqAppearanceItemPtr  bioseqAIP;
  Uint1                    scaleHeight;
  Int4                     from, to;

  ssp = (ScaleSntPtr) calldata;
  if (ssp == NULL) return;

  dInfoPtr = (DrawInfoPtr) pdc;
  tmpBox = ssp->box;
  bioseqAIP = ssp->bioseqAIP;
  scaleHeight = bioseqAIP->scaleHeight;

  from = tmpBox.left;
  to   = tmpBox.right;

  curScale = dInfoPtr->scale.scaleX;
  r.left   = (Int2) ((dInfoPtr->scale.offsetX + tmpBox.left)  / curScale);
  r.right  = (Int2) ((dInfoPtr->scale.offsetX + tmpBox.right)  / curScale);
  SelectFont (bioseqAIP->scaleFont);
  SelectColor (bioseqAIP->scaleColor[0], bioseqAIP->scaleColor[1], bioseqAIP->scaleColor[2]);

  /* if the right-most edge is visible, draw the final tick mark and a right-justified total length label */
  if (dInfoPtr->scale.worldWindow.right >= to - 100 * curScale) {
    pnt.x = to;
    pnt.y = tmpBox.top;
    MapWorldPointToPixel (&pt, &pnt, &dInfoPtr->scale);
    MoveTo (pt.x, pt.y);
    pnt.y = tmpBox.top - scaleHeight;
    MapWorldPointToPixel (&pt, &pnt, &dInfoPtr->scale);
    LineTo (pt.x, pt.y);
    sprintf (buffer, "%ld", (long)to + ssp->labelOffset + 1);
    pt.x += 3 - StringWidth (buffer);
    pt.y += 1 + Ascent ();
    PaintStringEx (buffer, pt.x, pt.y);
  }

  /* if the left-most edge is visible, draw the first label, left-justified */
  if (dInfoPtr->scale.worldWindow.left - 400 * curScale <= from) {
    pnt.x = from;
    pnt.y = tmpBox.top - scaleHeight;
    sprintf (buffer, "%ld", (long)((from == 0) ? 1 : from)  + ssp->labelOffset);
    MapWorldPointToPixel (&pt, &pnt, &dInfoPtr->scale);
    pt.y += 1 + Ascent ();
    PaintStringEx (buffer, pt.x, pt.y);
  }

  if (tmpBox.left > dInfoPtr->scale.worldWindow.right ||
      tmpBox.right < dInfoPtr->scale.worldWindow.left ||
      tmpBox.top < dInfoPtr->scale.worldWindow.bottom ||
      tmpBox.bottom > dInfoPtr->scale.worldWindow.top)
    return;

  if (dInfoPtr->checked == FALSE ) {
    if (tmpBox.left < dInfoPtr->scale.worldWindow16.left)
      tmpBox.left = dInfoPtr->scale.worldWindow16.left;
    if (tmpBox.right > dInfoPtr->scale.worldWindow16.right)
      tmpBox.right = dInfoPtr->scale.worldWindow16.right;
    if (tmpBox.top > dInfoPtr->scale.worldWindow16.top)
      tmpBox.top = dInfoPtr->scale.worldWindow16.top;
    if (tmpBox.bottom < dInfoPtr->scale.worldWindow16.bottom)
      tmpBox.bottom = dInfoPtr->scale.worldWindow16.bottom;
  }

  i = MAX (dInfoPtr->scale.worldWindow.left, tmpBox.left);
  /*  i = i + 10 * curScale - (i % (10 * curScale)) - 1;*/
  while (i % (10 * curScale) != 0) {
    i++; /* !!! do this the right way */
  }
  for (tickCount = (i / (10 * curScale)) % 10;
       i < MIN (dInfoPtr->scale.worldWindow.right, to);
       i += curScale * 10) {
    pnt.x = i;
    pnt.y = tmpBox.top;
    MapWorldPointToPixel (&pt, &pnt, &dInfoPtr->scale);
    MoveTo (pt.x, pt.y);

    if (tickCount == 0 || tickCount == 5) {
      pnt.y = tmpBox.top - scaleHeight; /* draw full-height tick */
      MapWorldPointToPixel (&pt, &pnt, &dInfoPtr->scale);
      LineTo (pt.x, pt.y);
      if (tickCount == 0
          /* if i + 100curScale > the right boundary, this is the last label */
          && (!((i + 100 * curScale >= to) && ssp->disableLastLabel))
          && (!((i - 100 * curScale <= from) && ssp->disableFirstLabel))
          && (i != from)) {
        sprintf (buffer, "%ld", (long)((i == 0) ? 1 : i) + ssp->labelOffset); /* put the origin at 1 instead of 0 */
        pt.x -= StringWidth (buffer) / 2; /* center text around the tick mark*/
        pt.y += 1 + Ascent ();
        PaintStringEx (buffer, pt.x, pt.y);
      }
      /* disable the right-end one in the case of an overlap */
    } else {
      pnt.y = tmpBox.top - scaleHeight / 2;
      MapWorldPointToPixel (&pt, &pnt, &dInfoPtr->scale);
      LineTo (pt.x, pt.y);
    }
    tickCount = (tickCount + 1) % 10;
  }

  /* also, we might need to redraw the labels just to the left or to the right of the update region. */
  i = MAX (dInfoPtr->scale.worldWindow.left, tmpBox.left);
  j = i; /* j = leftmost visible pixel in world coordinates */
  while (i % (100 * curScale) != 0) {
    i--;
  }
  pnt.x = i;
  sprintf (buffer, "%ld", (long)((i == 0) ? 1 : i) + ssp->labelOffset);
  i += curScale * ((StringWidth (buffer) / 2) + 1);
  if (i >= j
      && i > from
      && (!((pnt.x + 100 * curScale >= to) && ssp->disableLastLabel))
      && (!((pnt.x - 100 * curScale <= from) && ssp->disableFirstLabel))
      && pnt.x > from) {
    pnt.y = tmpBox.top - scaleHeight;
    MapWorldPointToPixel (&pt, &pnt, &dInfoPtr->scale);
    pt.x -= StringWidth (buffer) / 2; /* center text around the tick mark*/
    pt.y += 1 + Ascent ();
    PaintStringEx (buffer, pt.x, pt.y);
  }
  /* now check the right side*/

  i = MIN (dInfoPtr->scale.worldWindow.right, to);
  j = i; /* j = rightmost visible pixel in world coordinates */
  while (i % (100 * curScale) != 0) {
    i++;
  }
  pnt.x = i;
  sprintf (buffer, "%ld", (long)i + ssp->labelOffset);
  i -= curScale * ((StringWidth (buffer) / 2) + 1);
  if (i <= j
      && (!((pnt.x + 100 * curScale >= to) && ssp->disableLastLabel))
      && (!((pnt.x - 100 * curScale <= from) && ssp->disableFirstLabel))
      && pnt.x < to) {
    pnt.y = tmpBox.top - scaleHeight;
    MapWorldPointToPixel (&pt, &pnt, &dInfoPtr->scale);
    pt.x -= StringWidth (buffer) / 2; /* center text around the tick mark*/
    pt.y += 1 + Ascent ();
    PaintStringEx (buffer, pt.x, pt.y);
  }
}

static void ScaleSntCleanupProc (
  BigScalar calldata
)

{
  ScaleSntPtr  ssp;

  ssp = (ScaleSntPtr) calldata;
  MemFree (ssp);
}

static Boolean LIBCALLBACK Asn2gphSegmentExploreProc (
  SeqLocPtr slp,
  SeqMgrSegmentContextPtr context
)

{
  /* context->userdata a pointer to vContext */
  RelevantFeatureItemPtr RFIP;
  SeqIdPtr           sip, newid = NULL;
  Int4               gi;
  Char               labelBuf [100];
  Int4               left, right;
  ViewerContextPtr   vContext;
  AppearancePtr      AP;
  BioseqAppearanceItemPtr BioAIP;
  BioseqPtr          bsp;
  ValNodePtr         vnp;

  if ((RFIP = MemNew (sizeof (RelevantFeatureItem))) == NULL) return FALSE;
  vContext = context->userdata;
  bsp = vContext->BSP;
  vnp = ValNodeAddPointer (&vContext->BSPsegmentTail, 0, RFIP);
  if (vContext->BSPsegmentVNP == NULL) {
    vContext->BSPsegmentVNP = vnp;
  }
  vContext->BSPsegmentTail = vnp;
  /* ValNodeAddPointer (&vContext->BSPsegmentVNP, 0, RFIP); */
  sip = SeqLocId (slp);
  if (sip != NULL && sip->choice == SEQID_GI /* && BioseqFindCore (sip) != NULL */) {
    gi = sip->data.intvalue;
    newid = SeqIdStripLocus (GetSeqIdForGI (gi));
    sip = newid;
    if (newid != NULL) {
      ValNodeAddInt (&newid, SEQID_GI, gi);
    }
  }
  
  AP = vContext->AppPtr;
  BioAIP = AP->bioseqAIP;

  left = context->from;
  right = context->to - left + context->cumOffset;
  left = context->cumOffset;
  if (sip != NULL) {
    if (BioAIP->format != PRINTID_FASTA_LONG) { 
      sip = SeqIdFindWorst (sip);
    }
    SeqIdWrite (sip, labelBuf, BioAIP->format, sizeof (labelBuf) - 1);
    RFIP->ContentLabel = StringSave (labelBuf); /* record this in a list of things to be freed so that we dont leak memory!!!!! */
  }
  SeqIdSetFree (newid);
  RFIP->Left = MIN (left, right);
  RFIP->Right = MAX (left, right);
  RFIP->entityID = context->entityID;
  RFIP->itemID = context->itemID;
  if (bsp->repr == Seq_repr_seg) {
    RFIP->itemType = OBJ_BIOSEQ_SEG;
  } else if (bsp->repr == Seq_repr_delta) {
    RFIP->itemType = OBJ_BIOSEQ_DELTA;
  } else {
    RFIP->itemType = OBJ_BIOSEQ_SEG;
  }
  RFIP->numivals = 1;
  RFIP->featdeftype = 0;
  RFIP->featstrand = context->strand;
  RFIP->circularSpanningOrigin = FALSE;
  return TRUE;
}

static Int4 DrawBioseqSegments (
  Int4 initialYOffset,
  FilterItemPtr FIP,
  ViewerContextPtr vContext
)

{
  ValNodePtr   listHead = NULL, vnpSegment = NULL;
  Int4         segmentCount;
  Uint2         rowHeight, row = 0; /* row is either 0 or 1 */
  AppearanceItem segmentAI;
  AppearanceItemPtr oldAIPzero;
  AppearancePtr AP;
  BioseqAppearanceItemPtr BioAIP;
  RelevantFeatureItemPtr RFIP;
  FilterProcessState FPS;
  Uint2         oldMaxScale;

  vContext->BSPsegmentVNP = NULL;
  vContext->BSPsegmentTail = NULL;
  SeqMgrExploreSegments (vContext->BSP, vContext, Asn2gphSegmentExploreProc);
  listHead = vContext->BSPsegmentVNP;
  segmentCount = 0;
  for (vnpSegment = listHead; vnpSegment != NULL; vnpSegment = vnpSegment->next) {
    segmentCount++;
  }

  if (segmentCount <= 1) {
    ValNodeFreeData (listHead);
    return 0;
  }

  oldMaxScale = vContext->FltPtr->MaxScaleWithLabels;
  vContext->FltPtr->MaxScaleWithLabels = 10000;
  AP = vContext->AppPtr;
  BioAIP = AP->bioseqAIP;
  MemCpy (segmentAI.LabelColor, BioAIP->labelColor, sizeof (segmentAI.LabelColor));
  MemCpy (segmentAI.Color, BioAIP->bioseqColor, sizeof (segmentAI.Color));
  segmentAI.RenderChoice = Render_Box;
  segmentAI.Height = BioAIP->height;
  segmentAI.AddDescToLabel = TRUE;
  segmentAI.AddTypeToLabel = FALSE;
  segmentAI.LabelFont = BioAIP->labelFont;
  segmentAI.LabelLoc = FIP->LabelLoc;
  FIP->LabelLoc = LabelAboveClip;

  segmentAI.ShowArrow = FALSE;
  segmentAI.VibLinestyle = SOLID_LINE;
  segmentAI.VibShading = SOLID_SHADING;
  oldAIPzero = vContext->AppPtr->FeaturesAppearanceItem[0];
  vContext->AppPtr->FeaturesAppearanceItem[0] = &segmentAI;

  MemSet (&FPS, 0, sizeof (FPS));
  FPS.currentFIP = FIP;
  FPS.ceiling = initialYOffset;
  FPS.vContext = vContext;

  FPS.renderParm.AIP = &segmentAI;
  FPS.renderParm.FIP = FIP;

  SelectFont (segmentAI.LabelFont);
  rowHeight = LineHeight () + segmentAI.Height + 3 + FIP->IntraRowPaddingPixels;
  row = 0;

  for (vnpSegment = listHead; vnpSegment != NULL; vnpSegment = vnpSegment->next) {

    RFIP = vnpSegment->data.ptrvalue;
    EnsureFeatureHasSegment (&FPS, 0, vContext->drawOnMe);
    if (!BuildRenderInputFromRFIP (&FPS.renderParm, RFIP, &FPS)) {
      continue;
    }
    row = 1 - row; /* alternate between 0 and 1 */
    FPS.renderParm.rowHeight += 2;
    FPS.renderParm.yStart = initialYOffset - (row * rowHeight);
    DrawFeatureAndLabel (&FPS.renderParm, vContext);
  }
  if (FPS.needFreeList != NULL) {
    FPS.needFreeList = ValNodeFreeData (FPS.needFreeList);
    FPS.lastInFreeList = NULL;
  }
  ValNodeFreeData (listHead);
  vContext->BSPsegmentVNP = NULL;
  vContext->BSPsegmentTail = NULL;
  vContext->AppPtr->FeaturesAppearanceItem[0] = oldAIPzero;
  vContext->FltPtr->MaxScaleWithLabels = oldMaxScale;
  return 2 * rowHeight + 7 + FIP->IntraRowPaddingPixels + FIP->GroupPadding;
}

static Int4 DrawBioseq (
  Int4 initialYOffset,
  FilterItemPtr FIP,
  ViewerContextPtr vContext
)

{
  PrimitivE               thisPrim;
  Char                    labelbuf[128];
  BioseqPtr               bsp;
  ScaleSntPtr             ssp;
  Uint2                   labelLineHeight, lastLabelWidth, firstLabelWidth;
  SegmenT                 seg;
  SeqIdPtr                sip;
  BioseqAppearanceItemPtr bioseqAIP;
  Uint1                   scaleHeight;
  Uint1                   height;
  Int4                    yOffset;
  Uint4                   i, j;
  Boolean                 drawScale;
  AppearancePtr           AP;

  AP = vContext->AppPtr;
  bioseqAIP = AP->bioseqAIP;
  yOffset = initialYOffset;
  bsp = vContext->BSP;

  drawScale = bioseqAIP->drawScale;
  if (FIP->DrawScale != TristateUnset) {
    drawScale = BOOL_FROM_SET_TRISTATE(FIP->DrawScale);
  }

  scaleHeight = bioseqAIP->scaleHeight;
  if (bioseqAIP->format != PRINTID_FASTA_LONG) {
    sip = SeqIdFindWorst (bsp->id);
  } else {
    sip = bsp->id;
  }
  SeqIdWrite (sip, labelbuf, bioseqAIP->format, sizeof (labelbuf) - 1);
  seg = CreateSegment (vContext->topLevelSeg, 0, 0);

  if (bioseqAIP->labelLoc == LabelOnTop) {
    AddAttribute (seg, COLOR_ATT, bioseqAIP->labelColor, 0, 0, 1, 0);
    thisPrim = AddTextLabel (seg, vContext->from, yOffset, labelbuf, bioseqAIP->labelFont, 0, LOWER_RIGHT, 0);
    SetPrimitiveIDs (thisPrim, bsp->idx.entityID, bsp->idx.itemID, OBJ_BIOSEQ, 0);
    SelectFont (bioseqAIP->labelFont);
    height = LineHeight() + 1;
    yOffset = initialYOffset - height;
  } else {
    height = 0;
  }

  AddAttribute (seg, COLOR_ATT, bioseqAIP->bioseqColor, 0, 0, 1, 0);
  thisPrim = AddRectangle (seg, vContext->from, yOffset, vContext->to, yOffset - bioseqAIP->height, NO_ARROW, TRUE, 0);
  SetPrimitiveIDs (thisPrim, bsp->idx.entityID, bsp->idx.itemID, OBJ_BIOSEQ, 0);
  AddAttribute (seg, COLOR_ATT, bioseqAIP->labelColor, 0, 0, 1, 0);

  height += bioseqAIP->height + 2;
  yOffset = initialYOffset - height;

  if (bioseqAIP->labelLoc == LabelOnSide) {
    AddAttribute (seg, COLOR_ATT, bioseqAIP->labelColor, 0, 0, 1, 0);
    thisPrim = AddTextLabel (seg, vContext->from, yOffset, labelbuf, bioseqAIP->labelFont, 1, UPPER_LEFT, 0);
    SetPrimitiveIDs (thisPrim, bsp->idx.entityID, bsp->idx.itemID, OBJ_BIOSEQ, 0);
  } else if (bioseqAIP->labelLoc == LabelOnBottom) {
    AddAttribute (seg, COLOR_ATT, bioseqAIP->labelColor, 0, 0, 1, 0);
    thisPrim = AddTextLabel (seg, 0, yOffset, labelbuf, bioseqAIP->labelFont, 1, LOWER_RIGHT, 0);
    SetPrimitiveIDs (thisPrim, bsp->idx.entityID, bsp->idx.itemID, OBJ_BIOSEQ, 0);
    SelectFont (bioseqAIP->labelFont);
    height += LineHeight() + 2;
    yOffset = initialYOffset - height;
  }

  if (drawScale) {

    ssp = (ScaleSntPtr) MemNew (sizeof (ScaleSntData));
    if (ssp == NULL) return height;
    SelectFont (bioseqAIP->scaleFont);
    labelLineHeight = LineHeight();
    ssp->seg = seg;
    ssp->labelOffset = 0;
    ssp->length = vContext->to - vContext->from;
    ssp->box.left = vContext->from;
    ssp->box.right = vContext->to;
    ssp->box.top = yOffset;
    ssp->box.bottom = yOffset - 2 - scaleHeight - labelLineHeight;
    ssp->bioseqAIP = bioseqAIP;
    
    i = vContext->to - vContext->to % (100 * vContext->viewScale); /* the last labelled tick-mark */
    
    sprintf (labelbuf, "%ld", (long)i + ssp->labelOffset);
    j = StringWidth (labelbuf); /* j is the width (pixels) of the last tick mark's label */
    
    sprintf (labelbuf, "%ld", (long)vContext->to + ssp->labelOffset);
    lastLabelWidth = (StringWidth (labelbuf) + 2) * vContext->viewScale;
    
    if (vContext->from > 0) {
      sprintf (labelbuf, "%ld", (long)vContext->from + ssp->labelOffset);
    } else {
      sprintf (labelbuf, "1");
    }
    firstLabelWidth = StringWidth (labelbuf) * vContext->viewScale;
    
    i += vContext->viewScale * j / 2; /* right-most edge of the centered label */
    j = MAX (j, 10); /* always leave at least 10 pixels between the last 2 labels */
    if (i + j * vContext->viewScale >= vContext->to - lastLabelWidth) {
      ssp->disableLastLabel = TRUE;
    } else {
      ssp->disableLastLabel = FALSE;
    }
    
    i = vContext->from + (100 * vContext->viewScale) - vContext->from % (100 * vContext->viewScale); /* the second label (first is at the origin) */
    sprintf (labelbuf, "%ld", (long)vContext->from + ssp->labelOffset);
    if (i - ((StringWidth (labelbuf) / 2 + 5) * vContext->viewScale) <= vContext->from + firstLabelWidth) {
      ssp->disableFirstLabel = TRUE;
    } else {
      ssp->disableFirstLabel = FALSE;
    }
    
    ssp->snt = AddSntRectangle (seg, vContext->from, yOffset,
                                vContext->to + lastLabelWidth, yOffset - scaleHeight - labelLineHeight,
                                ScaleSntDrawProc, (BigScalar) ssp, ScaleSntCleanupProc, 0);
    /*  height += scaleHeight + labelLineHeight + 4;*/
    yOffset = ssp->box.bottom - 1 - 15;
  } else {
    yOffset++;
  }
  yOffset -= DrawBioseqSegments (yOffset, FIP, vContext);
  return initialYOffset - yOffset;
}

/* -=-=-=-==-=-==-=-= GRAPH STUFF =-=-=-=-=-=-=-=-=-*/

typedef struct gphsentdata {
  Boolean        flagIsGUI;
  SegmenT        seg;
  PrimitivE      snt;
  BoxInfo        box;
  Int4           min;
  Int4           max;
  Int4           axis;
  Int4           bottom;
  FloatHi        a;
  FloatHi        b;
  SeqGraphPtr    sgp;
  Uint1          red, green, blue;
} GphSentData, PNTR GphSentPtr;

static void PlotTheWorkingArray (Int4Ptr xp, Int4 len, Int4 scaleX,
                                 Int4 gmin, RecT r, Uint1 uR, Uint1 uG,
                                 Uint1 uB, AttPData PNTR curattrib)
{
  PoinT          pt;
  Int4           i;
  Int4           j;
  Int4           max;
  Int4           min;
  Int4           val;
  Uint1          curR, curG, curB;

  if (curattrib != NULL)
  {
    curR = curattrib->color[0];
    curG = curattrib->color[1];
    curB = curattrib->color[2];
  }
  else
  {
    curR = 0;
    curG = 0;
    curB = 0;
  }

  SelectColor (uR, uG, uB);
  pt.x = r.left;
  i = 0;
  val = (Int4) *xp;
  pt.y = (Int2) (r.bottom - (Int2) (val - gmin));
  if (pt.y < r.top) {
    pt.y = r.top;
  }
  MoveTo (pt.x, pt.y);
  for (; i < len - scaleX; i += scaleX) {
    val = (Int4) *xp;
    min = (Int4) val;
    max = (Int4) val;
    for (j = 1; j < scaleX; j++) {
      xp++;
      val = (Int4) *xp;
      min = MIN (min, (Int4) val);
      max = MAX (max, (Int4) val);
    }
    xp++;
    pt.y = (Int2) (r.bottom - (Int2) (min - gmin));
    if (pt.y < r.top) {
      pt.y = r.top;
    }
    LineTo (pt.x, pt.y);
    pt.y = (Int2) (r.bottom - (Int2) (max - gmin));
    if (pt.y < r.top) {
      pt.y = r.top;
    }
    LineTo (pt.x, pt.y);
    (pt.x)++;
  }
  SelectColor (curR, curG, curB);
  return;
}

static Int4Ptr MakeWorkingSeqGraphInt4Array (Pointer data, Uint1 type,
                                             Int4 pos, Int4 len,
                                             Boolean usescaleflags,
                                             FloatHi a, FloatHi b)
{
  Int4          i;
  Int4Ptr       xpoints, xp;
  FloatHi       fval;
  Int4          ival;
  Byte          bval;
  ByteStorePtr  bs;
  BytePtr       bp;

  xpoints = (Int4Ptr) MemNew ((size_t) (sizeof (Int4) * (len + 10)));

  if (xpoints == NULL)
    return xpoints;

  xp = xpoints;
  switch (type) {
   default:
   case 1:
     for (i = 0; i < len; i++, pos++, xp++) {
      if (usescaleflags) {
        fval = a * (FloatHi) (((FloatHiPtr) data)[pos]) + b;
      } else {
        fval = (FloatHi) (((FloatHiPtr) data)[pos]);
      }
      *xp = (Int4) fval;
    }
    break;
   case 2:
    for (i = 0; i < len; i++, pos++, xp++) {
      if (usescaleflags) {
        ival = (Int4) (a * (FloatHi) (((Int4Ptr) data)[pos]) + b);
      } else {
        ival = (Int4) (((Int4Ptr) data)[pos]);
      }
      *xp = (Int4) ival;
    }
    break;
   case 3:
    bp = MemNew (sizeof (Byte) * (len + 10));
    bs = (ByteStorePtr) data;
    BSSeek (bs, pos, SEEK_SET);
    len = BSRead (bs, (Pointer) bp, len * sizeof (Byte));
    for (i = 0; i < len; i++, pos++, xp++) {
      if (usescaleflags) {
        bval = (Byte) (a * (FloatHi) (bp [i]) + b);
      } else {
        bval = (Byte) (bp [i]);
      }
      *xp = (Int4) bval;
    }
    MemFree (bp);
    break;
  }
  return xpoints;
}

static void GphSentProc (BigScalar calldata, PrimDrawContext pdc)
{
  BioseqPtr    bsp;
  Int4         curScale;
  DrawInfoPtr  dInfoPtr;
  GphSentPtr   gsp;
  Int4         left;
  Int4         len, pos;
  RecT         r;
  Int4         scaleX;
  Int4         scaleY;
  SeqGraphPtr  sgp;
  BoxInfo      tmpBox;
  Int4Ptr      xpoints;
  Int4         tmpscaleX;

  gsp = (GphSentPtr) calldata;
  if (gsp == NULL) return;
  sgp = gsp->sgp;
  if (sgp == NULL || sgp->values == NULL) return;

  dInfoPtr = (DrawInfoPtr) pdc;
  tmpBox = gsp->box;
  if ( (tmpBox.left   > dInfoPtr->scale.worldWindow.right ) ||
       (tmpBox.right  < dInfoPtr->scale.worldWindow.left  ) ||
       (tmpBox.top    < dInfoPtr->scale.worldWindow.bottom) ||
       (tmpBox.bottom > dInfoPtr->scale.worldWindow.top   ) )
    return;

  if ( dInfoPtr->checked == FALSE ) {
    if ( tmpBox.left < dInfoPtr->scale.worldWindow16.left )
      tmpBox.left = dInfoPtr->scale.worldWindow16.left;
    if ( tmpBox.right > dInfoPtr->scale.worldWindow16.right )
      tmpBox.right = dInfoPtr->scale.worldWindow16.right;
    if ( tmpBox.top > dInfoPtr->scale.worldWindow16.top )
      tmpBox.top = dInfoPtr->scale.worldWindow16.top;
    if ( tmpBox.bottom < dInfoPtr->scale.worldWindow16.bottom )
      tmpBox.bottom = dInfoPtr->scale.worldWindow16.bottom;
  }
  scaleX = dInfoPtr->scale.scaleX;
  scaleY = dInfoPtr->scale.scaleY;

  curScale = dInfoPtr->scale.scaleX;
  r.left   = (Int2)((dInfoPtr->scale.offsetX + tmpBox.left )  / curScale);
  r.right  = (Int2)((dInfoPtr->scale.offsetX + tmpBox.right)  / curScale);
  curScale = dInfoPtr->scale.scaleY;
  r.top    = (Int2)((dInfoPtr->scale.offsetY - tmpBox.top   ) / curScale);
  r.bottom = (Int2)((dInfoPtr->scale.offsetY - tmpBox.bottom) / curScale);

  bsp = BioseqFind (SeqLocId (sgp->loc));
  left = GetOffsetInBioseq (sgp->loc, bsp, SEQLOC_LEFT_END);

  if (gsp->flagIsGUI)
  {
    len = tmpBox.right - tmpBox.left;
    pos = tmpBox.left - left;
  }
  else
  {
/* for non-GUI, plot all the sgp values */
    len = sgp->numval;
    pos = 0;
  }

  xpoints = MakeWorkingSeqGraphInt4Array (sgp->values, sgp->flags[2],
                                          pos, len,
                                          (Boolean) (sgp->flags[1] != 0),
                                          gsp->a, gsp->b);
  if (!gsp->flagIsGUI)
  {
    tmpscaleX = sgp->numval / (Int4) (tmpBox.right - tmpBox.left);
    if (tmpscaleX > scaleX)
      scaleX = tmpscaleX;
  }

  PlotTheWorkingArray (xpoints, len, scaleX, gsp->min, r,
                       gsp->red, gsp->green, gsp->blue,
                       &(dInfoPtr->curattrib));

  MemFree (xpoints);
}

static void CleanGSP (BigScalar calldata)
{
  GphSentPtr  gsp;

  gsp = (GphSentPtr) calldata;
  MemFree (gsp);
}

static GphSentPtr AddGphSentinelToPicture (SeqGraphPtr sgp, BioseqPtr bsp,
                                           SegmenT pict, Int4 scaleX,
                                           Int4 top, Int2 start,
                                           Uint1Ptr uRGB, Boolean drawScale)
{
  Int4        axis;
  GphSentPtr  gsp;
  Int4        i;
  Boolean     is_phrap;
  Int4        max;
  Int4        min;
  SegmenT     seg;
  Char        str [32];
  Int4        leftoff, rightoff;

  if (sgp == NULL || bsp == NULL || pict == NULL)
    return NULL;
  gsp = MemNew (sizeof (GphSentData));
  if (gsp == NULL)
    return NULL;
  gsp->flagIsGUI = VibrantIsGUI ();
  if (uRGB != NULL)
  {
    gsp->red   = uRGB[0];
    gsp->green = uRGB[1];
    gsp->blue  = uRGB[2];
  }
  else
  {
    gsp->red   = 0;
    gsp->green = 0;
    gsp->blue  = 0;
  }

  leftoff = GetOffsetInBioseq (sgp->loc, bsp, SEQLOC_LEFT_END);
  rightoff = GetOffsetInBioseq (sgp->loc, bsp, SEQLOC_RIGHT_END);
  if (!gsp->flagIsGUI)
  {
    leftoff /= scaleX;
    rightoff /= scaleX;
  }
  gsp->box.left = leftoff + start;
  gsp->box.right = rightoff - 1 + start;

  gsp->sgp = sgp;
  gsp->a = sgp->a;
  gsp->b = sgp->b;
  is_phrap = (Boolean) (StringICmp (sgp->title, "Phrap Quality") == 0 ||
                        StringICmp (sgp->title, "Phred Quality") == 0);
  switch (sgp->flags [2]) {
    case 1 :
      min = (Int4) sgp->min.realvalue;
      max = (Int4) sgp->max.realvalue;
      axis = (Int4) sgp->axis.realvalue;
      if (sgp->flags [1] != 0) {
        min = (Int4) (sgp->a * ((FloatHi) min) + sgp->b);
        max = (Int4) (sgp->a * ((FloatHi) max) + sgp->b);
      }
      break;
    case 2 :
      min = (Int4) sgp->min.intvalue;
      max = (Int4) sgp->max.intvalue;
      axis = (Int4) sgp->axis.intvalue;
      if (sgp->flags [1] != 0) {
        min = (Int4) (sgp->a * ((FloatHi) min) + sgp->b);
        max = (Int4) (sgp->a * ((FloatHi) max) + sgp->b);
      }
      break;
    case 3 :
      min = (Int4) sgp->min.intvalue;
      max = (Int4) sgp->max.intvalue;
      if (is_phrap) {
        min = MIN (0, min);
        max = MAX (100, max);
      }
      axis = (Int4) sgp->axis.intvalue;
      if (sgp->flags [1] != 0) {
        min = (Int4) (sgp->a * ((FloatHi) min) + sgp->b);
        max = (Int4) (sgp->a * ((FloatHi) max) + sgp->b);
      }
      break;
    default :
      min = (Int4) 0;
      max = (Int4) 100;
      axis = (Int4) 0;
      break;
  }
  gsp->seg = seg = CreateSegment (pict, 0, 0);
  gsp->bottom = top - (max - min) - 20;

  if (drawScale && sgp->title != NULL)  /* StringHasNoText -- vibforms */
  {
    if (StringLen (sgp->title) > 0)
    {
      AddLabel (seg, 
                /* (gsp->box.left + gsp->box.right) / 2, */
                (start + bsp->length) / 2, 
                top,
                sgp->title, SMALL_TEXT, 0, MIDDLE_CENTER, 0);
    }
  }

  top -= 10;
  gsp->box.top = top;
  gsp->box.bottom = gsp->bottom;
  gsp->min = min;
  gsp->max = max;
  gsp->axis = axis;
  gsp->bottom += 10;

  if (drawScale)
  {
      if (is_phrap)
      {
        for (i = 0; i <=100; i += 20) {
          sprintf (str, "%ld", (long) i);
          AddLabel (seg, gsp->box.left, gsp->bottom + i, str,
                    SMALL_TEXT, 5, MIDDLE_LEFT, 0);
        }
      }
      else
      {
        sprintf (str, "%ld", (long) max);
        AddLabel (seg, gsp->box.left, top-10, str,
                  SMALL_TEXT, 5, MIDDLE_LEFT, 0);
        sprintf (str, "%ld", (long) min);
        AddLabel (seg, gsp->box.left, gsp->bottom-10, str,
                  SMALL_TEXT, 5, MIDDLE_LEFT, 0);
        if (min < 0 && max > 0)
        {
          sprintf (str, "%ld", 0L);
          AddLabel (seg, gsp->box.left, gsp->bottom-min-10, str,
                    SMALL_TEXT, 5, MIDDLE_LEFT, 0);
        }
     }
  }

  gsp->snt = AddSntRectangle (seg, gsp->box.left, gsp->box.top,
                              gsp->box.right, gsp->box.bottom,
                              GphSentProc, (BigScalar) gsp, CleanGSP, 0);
  return gsp;
}

static void VisitAndListGraphs (SeqGraphPtr sgp, Pointer userdata)

{
  GphSentPtr        gsp;
  ViewerContextPtr  vContext;
  Boolean           drawScale = FALSE;
  
  vContext = (ViewerContextPtr) userdata;
  if (vContext == NULL) return;

  if (vContext->gphseg == NULL) {
    vContext->gphseg = CreateSegment (vContext->drawOnMe, 0, 0);
    
    /* 
       this first time 'drawScale' stuff here and in AddGphSentinelToPicture
       assumes that all the graphs on this bioseq are the same type
       use the same legend and have the same label. 
    */
    AddSegRect (vContext->gphseg, FALSE, 0); /* draw box around all the graphs, not each one individually */
    drawScale = TRUE;   /* only draw scale on the first graph */
  }

  gsp = AddGphSentinelToPicture (sgp, vContext->BSP, vContext->gphseg,
                                 vContext->viewScale, vContext->gphyOffset,
                                 0, NULL, drawScale);
  if (gsp == NULL) return;
  vContext->gphheight = MAX (vContext->gphheight, gsp->box.top - gsp->box.bottom);
}

static Int4 DrawGraphs (
  Int4 yOffset,
  ViewerContextPtr vContext
)

{
  vContext->gphheight = 0;
  vContext->gphseg = NULL;
  vContext->gphyOffset = yOffset - 16; /* (workaround) drawing the graphs touches some pixels above gphyOffset  */

  VisitGraphsOnBsp (vContext->BSP, (Pointer) vContext, VisitAndListGraphs);

  return vContext->gphheight + 16;
}

static void ResetFilterState (
  FilterProcessStatePtr FPSP
)

{
  FilterItemPtr FIP;
  ViewerContextPtr vContext;


  if (FPSP == NULL) return;
  vContext = FPSP->vContext;
  FIP = FPSP->currentFIP;
  MemSet (&FPSP->state, 0, sizeof (FilterState));
  if (FIP->Type == FeatureFilter) {
    FPSP->state.feat.currentRFIPblockVNP = vContext->featVNP;
  }
}


/*
  Order by accession (label), strand and location
  for sorting.
*/
static int LIBCALLBACK CompareAlignNameLoc(VoidPtr ptr1, VoidPtr ptr2)
{
  SeqAlignSortInfoPtr saip1, saip2;
  Int2                  labelcomp;
  
  if (ptr1 != NULL && ptr2 != NULL) {
    saip1 = (SeqAlignSortInfoPtr) ptr1;
    saip2 = (SeqAlignSortInfoPtr) ptr2;

    labelcomp = StrNCmp(saip1->label, saip2->label, MAX_ALIGN_SORT_LABEL);
    if (labelcomp != 0)
      return labelcomp;
      
    if (saip1->strand < saip2->strand)
      return -1;
    if (saip1->strand > saip2->strand)
      return 1;
      
    if (saip1->start < saip2->start)
      return -1;
    if (saip1->start > saip2->start)
      return 1;
    if (saip1->stop < saip2->stop)
      return -1;
    if (saip1->stop > saip2->stop)
      return 1;
  }
  return 0; 
}

static int LIBCALLBACK ScoreCompare( VoidPtr p1, VoidPtr p2)
{
  if (p1 != NULL  &&  p2 != NULL) {
    Int4 i1 = * (Int4Ptr) p1;
    Int4 i2 = * (Int4Ptr) p2;
    
    return i1 - i2;
  }
  return 0;
}

/*
  Take a number (rawscore) between min and max (inclusive) 
  and linearly scale it into a number from 1 to ACCUMVALUE_MAX/256.
  We divide by 256 since we will be adding these numbers together when smearing.
  Hopefully we won't have more than 256 with large scores at any one point  :)
  Do not call if min >= max.
*/
AccumValue_t NormaliseScore(Int4 rawscore, Int4 min, Int4 max)
{
    AccumValue_t retval;
    FloatHi fscore = rawscore - min;
    fscore *=  ACCUMVALUE_MAX / 256 - 1;
    fscore /= (max - min);
    retval = fscore + 1; 
    return retval;
}


static void FindCutoffScore(SeqAlignPtr sap, Int4 alignCnt, AlignmentFilterStatePtr afsp)
{
  SeqAlignPtr sapIter;
  Int4Ptr     allScores;
  Int4        i;
  /* Int4        cutoffScore; */  /* not normalized */
  
  /* make array to hold all the scores. */
  allScores = MemNew(alignCnt * sizeof(Int4));
  if (allScores == NULL)
      return;

  /* get all the scores */
  i = 0;
  for (sapIter = sap; sapIter != NULL; sapIter = sapIter->next) {
    allScores[i++] = WeightFromAlignScore(sapIter, afsp->scoreType);
  }
    
  /* sort them */
  HeapSort ( allScores, alignCnt, sizeof(Int4), ScoreCompare);
  
  /* find, normalise and return the cutoffPercent score 
     and the min & max scores so we can normalise the rest of the scores later.
  */
  afsp->minScore = allScores[0];
  afsp->maxScore = allScores[alignCnt - 1];
  afsp->cutoffScoreHi = ACCUMVALUE_MAX; /* could add other controls to set this. */
/* Cutoff by actual score, not by percentage.
  if (afsp->cutoffPercent == 100  ||  
      afsp->scoreType == NLM_SCORE_COUNT ||
      afsp->minScore >= afsp->maxScore ) {
    afsp->cutoffScore = 0;
  }
  else {
    cutoffScore = allScores[ (100 - afsp->cutoffPercent) * alignCnt/100 ];
    afsp->cutoffScore = NormaliseScore(cutoffScore, afsp->minScore, afsp->maxScore);
  }
*/  
  MemFree(allScores);
}


/* Gather all the SeqAligns whose normalised score is less than the cutoff score */
static void GatherAlignInfo(
  SeqAlignPtr sap, 
  Int4        alignCnt,
  SeqIdPtr    bioSeqId,
  AlignmentFilterStatePtr afsp
)
{
  SeqAlignSortInfoPtr  infoArray = NULL;
  Int4        infoIndex;
  SeqAlignPtr sapIter;
  Int4        nrows, alignRow;
  Int4        start, stop, swap;
  Uint1       strand;
  Int4        rawScore;
  AccumValue_t  normScore;
  
  infoArray = MemNew(alignCnt * sizeof(SeqAlignSortInfo));
  if (infoArray == NULL)
    return;
  
  infoIndex = 0;
  for (sapIter = sap; sapIter != NULL; sapIter = sapIter->next) 
  {
    /* is this alignment in the top percentile? */
    if (afsp->scoreType != NLM_SCORE_COUNT  &&  afsp->minScore < afsp->maxScore ) {
      rawScore = WeightFromAlignScore(sapIter, afsp->scoreType);
      normScore = NormaliseScore( rawScore, afsp->minScore, afsp->maxScore);
  /*    if (normScore < afsp->cutoffScore ||  afsp->cutoffScoreHi < normScore) */
      if (rawScore < afsp->cutoffScore ||  afsp->cutoffScoreHi < rawScore)
      {
        continue;
      }
    } else {
      normScore = 1;
    }
    
    if (!AlnMgr2IndexSingleChildSeqAlign (sapIter)) continue; /* make sure we are indexed */ 

    /* get dimensions of this alignment (number of sequences aligned) */   
    nrows = AlnMgr2GetNumRows(sapIter);
    if (nrows < 1) {
      nrows = sapIter->dim; 
    }     
    if (nrows != 2) {  /* can't handle 3+ dimension alignments */
      continue;
    }
    
    /* Get the beginning and end points of this alignment in Bioseq coords. */
    if (sapIter->segtype != SAS_STD) {  
      /* not Std Seg alignment, use indexed functions */
      alignRow = AlnMgr2GetFirstNForSipList (sapIter, bioSeqId);
      if (alignRow == -1) {
        continue;
      }
      AlnMgr2GetNthSeqRangeInSA(sapIter, alignRow, &start, &stop);
      strand = AlnMgr2GetNthStrand(sapIter, alignRow);
    } else { 
      /* Std Seg alignment. Use special function */
      AlnMgr2GetSeqRangeForSipInSAStdSeg(sapIter, bioSeqId, &start, &stop, &strand);
    }
    if (start < 0) {
      continue;
    }
    if (stop < start) {
      swap = stop;
      stop = start;
      start = swap;
    }

    /* populate the structure we will use to sort on. */
    infoArray[infoIndex].start = start;
    infoArray[infoIndex].stop  = stop;
    infoArray[infoIndex].strand = strand;
    infoArray[infoIndex].sap   = sapIter;
    infoArray[infoIndex].normScore = normScore;
    if (!SeqAlignContentLabel(sapIter, bioSeqId, infoArray[infoIndex].label, MAX_ALIGN_SORT_LABEL, PRINTID_TEXTID_ACC_VER)) {
      infoArray[infoIndex].label[0] = 0;
    }
    ++infoIndex;
  }
  
  afsp->alignSortedLen = infoIndex;
    
  if (infoIndex == 0) {
    MemFree(infoArray);
    infoArray = NULL;
  }
  afsp->alignSorted = infoArray;
}

static Boolean AlignmentFilterStateInit(
    SeqAlignPtr sap,                /* the head of hte chain of sequence alignments from the bioseq */
    SeqIdPtr sid,                   /* the id of the bioseq so we know how we are viewing the alignments */
    AlignmentFilterStatePtr afsp,   /* What we are initializing. */
    GraphicViewExtrasPtr extras     /* contains the score cuttoff percentage and the kind of scores we use */
)
{  
  SeqAlignPtr   sapIter;
  Int4  alignCnt;
  Uint1 scoreType = NLM_SCORE_COUNT;
  Int2  i = 0;
  
  if (sap == NULL ||  sid == NULL  ||  afsp == NULL)
    return FALSE;
    
  /* what kind of score will we use to weight the alignments? */
  if (extras  &&  extras->alignScoreName) {
    scoreType = StringIndexInStringList (extras->alignScoreName, AlnScoreStrings);
    if (scoreType >= NLM_SCORE_TOOBIG)
        scoreType = NLM_SCORE_COUNT;
  }
  afsp->scoreType = scoreType;
  
  /* what percentile does an alignments score have to be to be displayed? */
  if (extras  && extras->alignScoreCutoff) {
    i = StringIndexInStringList (extras->alignScoreCutoff, AlnScoreCutoffStrings);
    if (i < 0  ||  DIM (AlnScoreCutoffValues) <= i )
        i = 0;
  }
    /*  afsp->cutoffPercent = AlnScoreCutoffValues[i]; */
  if (AlnScoreCutoffValues[i] < 0) {
    afsp->scoreType = NLM_SCORE_COUNT;
  } else {
    afsp->scoreType = NLM_SCORE_BIT;
    afsp->cutoffScore = AlnScoreCutoffValues[i];
  }
  
  /* how many alignments? Count one time now */
  alignCnt = 0;
  for (sapIter = sap; sapIter != NULL; sapIter = sapIter->next) {
    ++alignCnt;
  }

  FindCutoffScore(sap, alignCnt, afsp);
  
  GatherAlignInfo(sap, alignCnt, sid, afsp);
  if (afsp->alignSorted == NULL || afsp->alignSortedLen == 0) {
    /* couldn't allocate memory, or no alignments - nothing to do. */
    return FALSE;
  }
  /* sort the alignments, first by accession, then by location on the bioseq. */
  HeapSort(afsp->alignSorted, afsp->alignSortedLen, sizeof(SeqAlignSortInfo), CompareAlignNameLoc);
  afsp->alignIndex = 0;
  
  return TRUE;
}

static Boolean AlignmentFilterStateDone(AlignmentFilterStatePtr afsp)
{
  if (afsp->alignSorted != NULL &&
      afsp->alignIndex < afsp->alignSortedLen)
    return FALSE;
  return TRUE;
}


static void AlignmentFilterStateFree( AlignmentFilterStatePtr afsp)
{
  if (afsp->alignSorted != NULL)
    MemFree(afsp->alignSorted);
  afsp->alignSorted = NULL;
  afsp->alignSortedLen = 0;
}


  
static Int4 WeightFromAlignScore(SeqAlignPtr sap, Uint1 scoreType)
{
  Int4        weight = 1;
  Int4        score, number;
  Nlm_FloatHi bit_score, evalue;
  
  if (GetScoreAndEvalue(sap, &score, &bit_score, &evalue, &number)) {
    /* evaluate scores and get weight */
    switch (scoreType) {
    case NLM_SCORE_SCORE :
      weight = score;
      break;
    case NLM_SCORE_BIT :
      weight = bit_score;
      break;
    case NLM_SCORE_EVALUE :
      if (evalue > 0) {
        weight = -log(evalue);
      }
      else {  /* 0 is the best value. */
        /*
            We can't use the maxScore here since we do not know it yet
            since this is where we collect the values.
            Our sample data has -log(evalue) ranging from 25 - 429
            so 500 just has to be bigger than anything else we will encounter.
            It will get normalised latter with it as the maxScore.
            
            We could put a special sentinel value (very large or negative) here 
            that gets replaced with the real maxScore later. 
            (But then make sure it gets skipped when calculating the max and min).
        */
        weight = 500;
      }
      break;
    case NLM_SCORE_NUMBER :
      weight = number;
      break;
    case NLM_SCORE_COUNT :
    default:
      weight = 1;
    }
  }
  
  return weight;
}


/*
  Interval Accumulator
  An object which can add or in some way (specified by accumop) intervals on a sequence,
  then from which can be extracted the resulting intervals.
*/

#define ACCUMVALUE_GAP  -1

typedef enum AccumlatorOp {
 NLM_SUM_WEIGHT = 0,
 NLM_MAX_WEIGHT
} AccumulatorOp;


typedef struct AccumNode_s {
  Uint4         coord;
  AccumValue_t  weight;
  struct AccumNode_s * next;  /* makes a single-linked list. */
} AccumNode, *AccumNodePtr;


static AccumNodePtr
InsertNodeAfter(AccumNodePtr node, Uint4 coord, AccumValue_t weight)
{
  AccumNodePtr new_node = (AccumNodePtr) Nlm_MemNew(sizeof(AccumNode));
  if (new_node == NULL) return NULL;
  
  new_node->coord = coord;
  new_node->weight = weight;
  if (node != NULL) {
    new_node->next = node->next;
    node->next = new_node;
  }
  return new_node;
}

static AccumNodePtr
AppendNode(AccumNodePtr head, Uint4 coord, AccumValue_t weight)
{
  while (head->next != NULL)
    head = head->next;
  return InsertNodeAfter(head, coord, weight);
}

static void 
FreeAccumNodes(AccumNodePtr node)
{
  AccumNodePtr del_me;
  while (node) {
    del_me = node;
    node = node->next;
    Nlm_MemFree(del_me);
  }
}

static void
AccumulateWeight(AccumNodePtr node, AccumValue_t w2, AccumulatorOp op)
{
  AccumValue_t w1;
  
  if (w2 == 0)
    return;
  
  w1 = node->weight;
  
  /* gap trumps 0, any weight trumps a gap. */
  if ((w1 == ACCUMVALUE_GAP  &&  w2 <= 0)  ||
      (w2 == ACCUMVALUE_GAP  &&  w1 <= 0)) {
    node->weight = ACCUMVALUE_GAP;
  } else if (w1 == ACCUMVALUE_GAP){
    node->weight = w2; 
  } else if (w2 == ACCUMVALUE_GAP){
    node->weight = w1; 
  } else if (op  == NLM_MAX_WEIGHT) {
    /* max of the weights. */
    if (w2 > w1)
      node->weight = w2;
  } else {
    /* NLM_SUM_WEIGHT */
    if (node->weight < ACCUMVALUE_MAX - w2) /* avoid overflow. */
      node->weight += w2;
    else
      node->weight = ACCUMVALUE_MAX;
  }
}


typedef struct IntervalAccumulator {
  AccumNodePtr        nodes;
  AccumulatorOp       accumOp;
  AccumValue_t        maxWeight;
} IntervalAccumulator, PNTR IntervalAccumulatorPtr;


static IntervalAccumulatorPtr
NewIntervalAccumulator(Uint4 len, AccumulatorOp op)
{
  AccumNodePtr tail_node;
  IntervalAccumulatorPtr IAP;

  IAP = (IntervalAccumulatorPtr) Nlm_MemNew(sizeof(IntervalAccumulator));
  if (IAP == NULL) return NULL;
  IAP->nodes = InsertNodeAfter(NULL, 0, 0); /* header node. coord 0. */
  if (IAP->nodes == NULL) {
    Nlm_MemFree(IAP);
    return NULL;
  }
  tail_node = AppendNode(IAP->nodes, len, 0); /* tail node. max coord. */
  if (tail_node == NULL) {
    FreeAccumNodes(IAP->nodes);
    Nlm_MemFree(IAP);
    return NULL;
  }
  IAP->accumOp = op;
  return IAP;
}

static void
FreeIntervalAccumulator(IntervalAccumulatorPtr *iapp)
{
  IntervalAccumulatorPtr IAP;

  if (iapp == NULL || *iapp == NULL) return;
  IAP = *iapp;
  FreeAccumNodes(IAP->nodes);
  Nlm_MemFree(IAP);
  *iapp = NULL;
}


/* merge in a list of segments. */
static void
AccumSegments(IntervalAccumulatorPtr accum, AccumNodePtr new_nodes)
{

    AccumNodePtr prev_node = accum->nodes;     /* add our node right before this one. */
  AccumValue_t old_weight = 0;    /* the weight of the last old node passed. */
    AccumValue_t in_weight = 0;         /* the weight of the last new node entered. */
    
    AccumNodePtr in_node;
    
    in_node = new_nodes;
  /* skip header node in the input, if we have one. */
    if (in_node->weight == 0  &&  in_node->coord == 0)
      in_node = in_node->next;
        
  for (; in_node != NULL; in_node = in_node->next) {
    
        /* we are adding in_node now. */
        
        /* Find where to insert in_node.  */
        /* while extending the range of the last node added. */
        while (prev_node->next != NULL  && 
               in_node->coord > prev_node->next->coord) {
            prev_node = prev_node->next;
            old_weight = prev_node->weight;
            AccumulateWeight(prev_node, in_weight, accum->accumOp); 
        }
        in_weight = in_node->weight;

        /* insert at node. */
        if (in_node->coord == prev_node->next->coord) {
          prev_node = prev_node->next;
            old_weight = prev_node->weight;
            AccumulateWeight(prev_node, in_weight, accum->accumOp); 
        } else {
          AccumulateWeight(in_node, old_weight, accum->accumOp);
          InsertNodeAfter(prev_node, in_node->coord, in_node->weight);
          prev_node = prev_node->next; /* skip the one we just inserted. */
        } 
    }
    
    ASSERT(in_weight > 0);
  /* extend last range to the end of the accumulator. 
    if (in_weight > 0) {
        while (prev_node->next != NULL) {
            prev_node = prev_node->next;
            AccumulateWeight(prev_node, in_weight, accum->accumOp); 
        }
    }
    */
}




/* Retrieve information. */

static AccumValue_t
GetMaxWeight(const IntervalAccumulatorPtr IAP) 
{
  AccumNodePtr node; 
  AccumValue_t max_weight = 0;

    for (node = IAP->nodes->next; /* skip the header node. */
         node->next != NULL;  /* skip the last (dummy) node. */
         node = node->next) { 
    if (max_weight < node->weight)
      max_weight = node->weight;
    }
    return max_weight;
}


static AccumNodePtr
GetIntervalFromAccumulator(
  IntervalAccumulatorPtr iap, 
  AccumNodePtr nextPos, 
  Uint4Ptr startp, 
  Uint4Ptr stopp, 
  AccumValuePtr_t weightp
)
{
  Uint4             start, stop;
  AccumValue_t      weight = 0;
  
  if (NULL == iap  &&  nextPos == NULL) return NULL;

  if (iap  &&  nextPos == NULL)
    nextPos = iap->nodes->next;  /* skip leading 0,0 node. */
  
  /* are we at the end? */
  if (nextPos == NULL  ||  nextPos->next == NULL)  /* nextPos == NULL would be an error. */
    return NULL;
  
  start = nextPos->coord;
  weight = nextPos->weight;
  
  /* go to the next node. */
  nextPos = nextPos->next;
  /* skip redundant nodes. Those with the same weight as the preceding one. */
  while (nextPos->next  &&  nextPos->weight == weight)
    nextPos = nextPos->next;
  stop = nextPos->coord;
  
  if (startp) *startp = start;
  if (stopp)  *stopp  = stop;
  if (weightp) *weightp = weight;
  
  return nextPos;
}



static Uint2 SmearAlignments (
  FilterProcessStatePtr FPSP,
  ViewerContextPtr vContext  
)

{
  SeqAlignPtr              SAP;
  BioseqPtr                BSP;
  SeqIdPtr                 SID;
  AppearanceItemPtr        AIP;
  FilterItemPtr            FIP;
  
  AlignmentFilterStatePtr  alignSP;
  SeqAlignSortInfoPtr      alignSorted;
  Int4                     alignSortedLen;
  Int4                     alignIndex;
  Int4                     start, stop, maxDensity;
  Uint1                    color[3], col;
  Uint1                    minCol = 224; /* density == min -> light gray */
  Uint1                    maxCol = 0;   /* density == max -> black */
  
  IntervalAccumulatorPtr   plusIAP = NULL, minusIAP = NULL;  /* Smear accumulators */
  AccumNodePtr             thisAlignSegs = NULL;  /* input to the accumulators per alignment */
  AccumNodePtr             accumPos;              /* output iterator on the accumulators. */
  Uint4                    begin, end;
  Int4                     space_pixs;
  AccumValue_t             weight;
  AccumValue_t             density;

  Boolean                  smearedAlignsPlus = FALSE, smearedAlignsMinus = FALSE;
  AccumulatorOp            sumOrMax = NLM_SUM_WEIGHT;
  Boolean                  separateStrands;
  const Uint1              minDensity = 1;  /* minimum density we will display. */
  SegmenT                  seg;
  CharPtr                  annotName;
  Int4                     height = 0;
  Uint2                    space_line_height = 2;
  
  if (FPSP == NULL || vContext == NULL) return 0;
  alignSP = &FPSP->state.align;
  alignSorted  = alignSP->alignSorted;
  alignSortedLen = alignSP->alignSortedLen;
 
   /* get the Appearance item for alignments */
  AIP = vContext->AppPtr->FeaturesAppearanceItem[APPEARANCEITEM_Alignment];

  /* get the bioseq's id for picking out the right part of the alignments */
  BSP = vContext->BSP;
  SID = BSP->id;
   
  /* Get this annotation's name to decide how to display this. */ 
  annotName = GetSeqAnnotName(vContext->currentSAP);
  separateStrands = FALSE;
  if (StringStr(annotName, "BLASTX - swissprot"))
    separateStrands = TRUE;
  else if (StringStr(annotName, "BLASTN - mrna"))
    separateStrands = TRUE;
  else if (StringStr(annotName, "BLASTN - est"))
    separateStrands = FALSE;
  else if (StringStr(annotName, "BLASTN - nr"))
    separateStrands = FALSE;

  plusIAP =  NewIntervalAccumulator(vContext->seqLength, sumOrMax);
  if (plusIAP == NULL)  goto smearAlignmentsDone;
  minusIAP = NewIntervalAccumulator(vContext->seqLength, sumOrMax);
  if (minusIAP == NULL)  goto smearAlignmentsDone;
    
  /* 
    for all the sorted alignments (from a single annotation in this BioSeq)
    treat all alignments with the same accession as one alignment
  */   
  for (alignIndex = 0; 
       alignIndex < alignSortedLen; 
       ++alignIndex) 
  {
    AlignSegIterator asi;
    Int4  nsegs;
    Uint1 segType;
    Uint1 strand;
    
    SAP = alignSorted[alignIndex].sap;
    
    /* sanity checks */
    if (alignSorted[alignIndex].start < 0 || alignSorted[alignIndex].stop < 0)
      continue;
      
    weight = alignSorted[alignIndex].normScore;
    /* if (weight == 0)
      continue;
    */  
    /*
      at the begining of an alignment
      if there was another alignment before this one, 
      with the same accession, strand and that alignment ended before this one begins, 
      treat that space as a gap.
    */
    if (alignIndex > 0 && 
        StrNCmp(alignSorted[alignIndex - 1].label, alignSorted[alignIndex].label, MAX_ALIGN_SORT_LABEL) == 0 &&
        alignSorted[alignIndex - 1].strand == alignSorted[alignIndex].strand &&
        alignSorted[alignIndex - 1].stop < alignSorted[alignIndex].start)
    {
      start = alignSorted[alignIndex - 1].stop;
      AppendNode(thisAlignSegs, start, ACCUMVALUE_GAP );
    } else {
      /* we are starting a new alignment.  */
      /* Smear the last alignment's segments. */
      if (alignIndex > 0) {
        AppendNode(thisAlignSegs, alignSorted[alignIndex - 1].stop, 0);
        if (alignSorted[alignIndex - 1].strand != Seq_strand_minus || !separateStrands )
          AccumSegments(plusIAP, thisAlignSegs);
        else
          AccumSegments(minusIAP, thisAlignSegs);
      }
      
      /* Prepare space for the new alignment's segment info.  */
      FreeAccumNodes(thisAlignSegs);
      thisAlignSegs = InsertNodeAfter(NULL, 0, 0);
    }
        
    /*
      for each segment in an alignment
      if the segment is block or a gap map it appropriately in the density arrays.
    */ 
    nsegs = AlignSegIteratorCreate(SAP, SID, &asi);
    if (nsegs == 0)
      continue;
    while (AlignSegIteratorNext(&asi, &start, &stop, &strand, &segType))
    {
      if (segType == AM_INSERT || start < 0 || stop < 0)
        continue;
        
      if (segType == AM_GAP ) {  /* a gap */
        AppendNode(thisAlignSegs, start, ACCUMVALUE_GAP );
      }
      else if (segType == AM_SEQ) { /* a real alignment. */
        AppendNode(thisAlignSegs, start, weight );
        if (strand != Seq_strand_minus || !separateStrands) {
          smearedAlignsPlus = TRUE;
        } else {
          smearedAlignsMinus = TRUE;
        }
      }
  
    } /* for all segments in an alignment */
  } /* for all alignments in an annotation */
  
    /* Smear the last alignment's segments. */
   if (alignIndex > 0) {
    AppendNode(thisAlignSegs, alignSorted[alignIndex - 1].stop, 0);
    if (alignSorted[alignIndex - 1].strand != Seq_strand_minus || !separateStrands )
      AccumSegments(plusIAP, thisAlignSegs);
    else
      AccumSegments(minusIAP, thisAlignSegs);
  }

  if (!smearedAlignsPlus && !smearedAlignsMinus) 
    goto smearAlignmentsDone; /* there was nothing to show. */
  
  DrawNamedAnnotBox(FPSP);
  FIP = (FilterItemPtr) FPSP->currentFilterVNP->data.ptrvalue;
  DrawFilterItemBoxLabel(FPSP, FIP);
  
  seg = CreateSegment ( vContext->drawOnMe, 0, 0);

  if (smearedAlignsPlus || !separateStrands) {
    height += space_line_height;
    maxDensity = GetMaxWeight(plusIAP);

    accumPos = GetIntervalFromAccumulator(plusIAP, NULL, &begin, &end, &density);
    while (accumPos != NULL) {
    
      if (density > 0  && density != ACCUMVALUE_GAP) {
          /* convert  (1 - maxDensity) to "color" number (224 - 0) */
        if (maxDensity == minDensity) {
          col = minCol;
        } else {
          col = (Uint1) (minCol + (density - minDensity)*(maxCol - minCol)/(maxDensity - minDensity));
        }
        color [2] = color [1] = color [0] = col;  /* set to shade of grey. (minCol = 224) */
        AddAttribute (seg, COLOR_ATT, color, 0, 0, 1, 0);
        AddRectangle (seg, begin, FPSP->ceiling - height, 
                           end,   FPSP->ceiling - height - (AIP->Height), NO_ARROW, TRUE, 0);
      }
      else if (density == ACCUMVALUE_GAP) {
        AddAttribute (seg, COLOR_ATT, NULL, 0, 0, 1, 0);
        AddLine (seg, begin, FPSP->ceiling - height - (AIP->Height)/2, 
                      end,   FPSP->ceiling - height - (AIP->Height)/2, NO_ARROW, 0);
      } else { /* density == 0 */
        /* put a small line above spaces between blocks we draw */
        if (0 < begin  &&  end < vContext->seqLength) { /* ignore gaps at beginning and end of bioseq */
          ASSERT(density == 0);
          space_pixs = (end - begin)/vContext->viewScale;
          /* if (3 <= space_pixs  &&  space_pixs <= 10  &&  end < vContext->seqLength) { */
          if (space_pixs <= 20) { /* don't draw this line if it is more than 20 pixels long. */
            if (space_pixs < 3) { /* make sure bar is always at least 3 pixels long */
              int mid_point = end + begin;
              end = (mid_point + 3 * vContext->viewScale) /2;
              begin = (mid_point - 3 * vContext->viewScale) /2;
            }
            AddAttribute (seg, COLOR_ATT, NULL, 0, 0, 1, 0);
            AddLine (seg, begin,                     FPSP->ceiling + space_line_height, 
                          end - vContext->viewScale, FPSP->ceiling + space_line_height, NO_ARROW, 0);
          }
        }
      }
      accumPos = GetIntervalFromAccumulator(NULL, accumPos, &begin, &end, &density);
    }
    /* put a little arrow to show this is the plus strand */
    if (separateStrands) {
      AddAttribute (seg, COLOR_ATT, NULL, 0, 0, 1, 0);
      AddTextLabel (seg, 0 * vContext->viewScale, FPSP->ceiling - height - (AIP->Height)/2, 
                   ">", FIP->GroupLabelFont, 1, MIDDLE_LEFT, 0);
    }
    height += AIP->Height + FIP->IntraRowPaddingPixels;
  }
  
  if (smearedAlignsMinus) {
    maxDensity = GetMaxWeight(minusIAP);

    accumPos = GetIntervalFromAccumulator(minusIAP, NULL, &begin, &end, &density);
    while (accumPos != NULL) {
    
      if (density > 0  && density != ACCUMVALUE_GAP) {
          /* convert  (1 - maxDensity) to "color" number (224 - 0) */
        if (maxDensity == minDensity) {
          col = minCol;
        } else {
          col = (Uint1) (minCol + (density - minDensity)*(maxCol - minCol)/(maxDensity - minDensity));
        }
        color [2] = color [1] = color [0] = col;  /* set to shade of grey. (minCol = 224) */
        AddAttribute (seg, COLOR_ATT, color, 0, 0, 1, 0);
        AddRectangle (seg, begin, FPSP->ceiling - height, 
                           end,   FPSP->ceiling - height - (AIP->Height), NO_ARROW, TRUE, 0);
      }
      else if (density == ACCUMVALUE_GAP) {
        AddAttribute (seg, COLOR_ATT, NULL, 0, 0, 1, 0);
        AddLine (seg, begin, FPSP->ceiling - height - (AIP->Height)/2, 
                      end,   FPSP->ceiling - height - (AIP->Height)/2, NO_ARROW, 0);
      } else { 
        /* put a small line above spaces between blocks we draw */
        if (0 < begin  &&  end < vContext->seqLength) { /* ignore gaps at beginning and end of bioseq */
          ASSERT(density == 0);
          space_pixs = (end - begin)/vContext->viewScale;
          /* if (3 <= space_pixs  &&  space_pixs <= 10  &&  end < vContext->seqLength) { */
          if (space_pixs <= 20) { /* don't draw this line if it is more than 20 pixels long. */
            if (space_pixs < 3) { /* make sure bar is always at least 3 pixels long */
              int mid_point = end + begin;
              end = (mid_point + 3 * vContext->viewScale) /2;
              begin = (mid_point - 3 * vContext->viewScale) /2;
            }
            AddAttribute (seg, COLOR_ATT, NULL, 0, 0, 1, 0);
            AddLine (seg, begin,                     FPSP->ceiling - height - (AIP->Height) - space_line_height - 1, 
                          end - vContext->viewScale, FPSP->ceiling - height - (AIP->Height) - space_line_height - 1, NO_ARROW, 0);
          }
        }
      }
      accumPos = GetIntervalFromAccumulator(NULL, accumPos, &begin, &end, &density);
    }
    AddAttribute (seg, COLOR_ATT, NULL, 0, 0, 1, 0);
    AddTextLabel (seg, 0, FPSP->ceiling - height - (AIP->Height)/2, 
                 "<", FIP->GroupLabelFont, 1, MIDDLE_LEFT, 0);

    height += space_line_height;
    height += AIP->Height + FIP->IntraRowPaddingPixels;
  }
    
smearAlignmentsDone:

  FreeIntervalAccumulator(&plusIAP);
  FreeIntervalAccumulator(&minusIAP);

  return height;
}


static Boolean FilterAndLayout (
  ViewerContextPtr vContext
)

{
  FilterProcessState  FPS;
  FilterItemPtr       FIP;
  FilterPtr           FP;
  AppearancePtr       AP;
  FilterItem          tempFI;
  Int1                featdeftype;
  LayoutAlgorithm     layoutC;
  Int4                height, totalheight;
  SegmenT             filterSeg, invisibleSeg;
  Uint1               featdefOrder;
  Boolean             emptyFilterGroup;
  Int4                undoCeiling;
  BioseqPtr           BSP;
  SeqAnnotPtr         SAnnP;
  SeqAlignPtr         SAlnP;


  if (vContext == NULL) return FALSE;
  MemSet (&FPS, 0, sizeof (FilterProcessState));
  FPS.vContext = vContext;
  if (vContext->ceiling != NULL) {
    FPS.ceiling = *vContext->ceiling;
  } else {
    FPS.ceiling = 0;
  }
  FPS.featuresProcessed = MemNew (vContext->featureCount * sizeof (Boolean));
  if (FPS.featuresProcessed == NULL && vContext->featureCount != 0) return FALSE;
  AP = vContext->AppPtr;
  vContext->sanLevelSeg = CreateSegment (vContext->topLevelSeg, 0, 0);
  FPS.annotBoxDrawn = FALSE;
  FPS.annotLabelDrawn = FALSE;

  FP = vContext->FltPtr;
  if (! FP->AnnotBoxColorSet) {
    MemCopy (FP->AnnotBoxColor, AP->AnnotBoxColor, sizeof (Uint1 [3]));
  }
  if (! FP->AnnotLabelColorSet) {
    MemCopy (FP->AnnotLabelColor, AP->AnnotLabelColor, sizeof (Uint1 [3]));
  }
  if (! FP->AnnotLabelFontSet) {
    FP->AnnotLabelFont = AP->AnnotLabelFont;
  }

  for (FPS.currentFilterVNP = FP->FilterItemList;
       FPS.currentFilterVNP != NULL;
       FPS.currentFilterVNP = FPS.currentFilterVNP->next) {

    if (FPS.currentFilterVNP->data.ptrvalue == NULL) continue; /* this should not happen if config file parsing worked */

    filterSeg = CreateSegment (vContext->sanLevelSeg, 0, 0);
    MemSet (FPS.labelSegs, 0, sizeof (FPS.labelSegs));
    MemSet (FPS.drawSegs, 0, sizeof (FPS.drawSegs));
    vContext->drawOnMe = filterSeg;
    emptyFilterGroup = TRUE;
    undoCeiling = FPS.ceiling;
    FPS.featuresProcessedCount = 0;
    FPS.groupBoxDrawn = FALSE;
    FPS.groupLabelDrawn = FALSE;

    FIP = (FilterItemPtr) FPS.currentFilterVNP->data.ptrvalue;

    if (! FIP->GroupBoxColorSet) {
      MemCopy (FIP->GroupBoxColor, AP->GroupBoxColor, sizeof (Uint1 [3]));
    }
    if (! FIP->GroupLabelColorSet) {
      MemCopy (FIP->GroupLabelColor, AP->GroupLabelColor, sizeof (Uint1 [3]));
    }
    if (! FIP->GroupLabelFontSet) {
      FIP->GroupLabelFont = AP->GroupLabelFont;
    }

    switch (FIP->Type) {
      case InvalidFilter:
        break;
      case BioseqFilter:
        if (vContext->currentSAP) 
          break;
        height = DrawBioseq (FPS.ceiling, FIP, vContext);
        emptyFilterGroup = FALSE;
        break;
      case GraphFilter:
        if (vContext->currentSAP) 
          break;
        height = DrawGraphs (FPS.ceiling, vContext);
        if (height != 0) {
          emptyFilterGroup = FALSE;
        }
        break;
      case AlignmentFilter:
        BSP = vContext->BSP;
        height = 0;
        totalheight = 0;
        layoutC = (vContext->overrideLayout != Layout_Inherit) ? vContext->overrideLayout : FIP->LayoutChoice;
        FPS.currentFIP = FIP;
        
        /*
         *  Or we could move the current SAnnP into FPS.state.align and put all of this logic
         *  into GetNextRFIPinAlignmentFilter() which SmearAlignments would call, making Alignment
         *  processing more like Feature processing.
         */
        for (SAnnP = BSP->annot; SAnnP != NULL; SAnnP = SAnnP->next) 
        {
          if (SAnnP->type != 2) 
            continue;  /* type 2 annotation is an alignment */
          
          if (FP->GroupByAnnot) /* are we grouping by named annotations? */
          {
            if (GetSeqAnnotName(SAnnP)) /* this is a named annotation */
            {
              if (SAnnP != vContext->currentSAP) /* only do the named annotation we are currently doing. */
                continue;
            }
            else if (vContext->currentSAP) /* don't do any unnamed annotation if we are doing a particular named one. */
              continue;
          }
                   
          emptyFilterGroup = FALSE;
          SAlnP = (SeqAlignPtr) SAnnP->data;
                    
          ResetFilterState (&FPS);
          if ( ! AlignmentFilterStateInit(SAlnP, BSP->id ,&FPS.state.align, vContext->extras))
            continue;

          switch (layoutC) {
            case Layout_FeatTypePerLine:
              height = SmearAlignments (&FPS, vContext);
              break;
            default:
              height = ProcessRows (layoutC, &FPS, vContext);
              break;
          }
          AlignmentFilterStateFree(&FPS.state.align);
          
          totalheight += height;
          if (height > 0)
            FPS.ceiling -= height;
        } /* SAnnp, cycle through all SeqAnnots on this Bioseq */
        height = 0;
        break;
      case FeatureFilter:
        layoutC = (vContext->overrideLayout != Layout_Inherit) ? vContext->overrideLayout : FIP->LayoutChoice;
        /*
          Some layouts act to the user as if they are single FilterGroups, but internally use multiple
          consecutive FilterGroups
          (currently, Layout_FeatTypePerLine, Layout_FeatTypePerLineGroup, Layout_GroupCorrespondingFeats, and Layout_GroupCorrespondingFeatsRepeat).
        */
        /*
          FeatTypePerLineGroup is equiv. to using PackUpwards several times, with single-feature filteritems
          FeatTypePerLine is similar (but using AllInOneLine)
        */
        switch (layoutC) {
          case Layout_FeatTypePerLine:
          case Layout_FeatTypePerLineGroup:
            FPS.currentFIP = &tempFI;
            MemCopy (&tempFI, FIP, sizeof (FilterItem)); /* copy the filter . . . */
            MemSet (&tempFI.IncludeFeature, 0, sizeof (tempFI.IncludeFeature));  /* but don't include any features */
            tempFI.AddTypeToLabel = TristateFalse;
            for (featdefOrder = 1; featdefOrder < APPEARANCEITEM_MAX; featdefOrder++) {
              for (featdeftype = 1; featdeftype < APPEARANCEITEM_MAX; featdeftype++) {
                if (FIP->IncludeFeature [featdeftype] == featdefOrder) {
                  ResetFilterState (&FPS);
                  tempFI.IncludeFeature[featdeftype] = TRUE;
                  height = ProcessRows (layoutC, &FPS, vContext);
                  if (FPS.featuresProcessedCount != 0) {
                    emptyFilterGroup = FALSE;
                  }
                  FPS.ceiling -= height;
                  tempFI.IncludeFeature[featdeftype] = FALSE;
                }
              }
            }
            height = 0; /* prevent FPS.ceiling from being bumped again */
            break;
          case Layout_GroupCorrespondingFeats:
          case Layout_GroupCorrespondingFeatsRepeat:
            /*
              This uses 3 FilterItems:
                - All gene features (compact)
                - CDS & mRNA (grouped by products)
                - anything else included in the filter as specified by the user (compact)
            */
            FPS.currentFIP = &tempFI;
            MemCopy (&tempFI, FIP, sizeof (FilterItem)); /* copy the filter . . .*/
            MemSet (&tempFI.IncludeFeature, 0, sizeof (tempFI.IncludeFeature));  /* but don't include any features*/
            tempFI.GroupPadding = 0;
            tempFI.IncludeFeature [FEATDEF_GENE] = FIP->IncludeFeature [FEATDEF_GENE];
            ResetFilterState (&FPS);
            height = ProcessRows (Layout_PackUpward, &FPS, vContext);
            FPS.ceiling -= height;

            ResetFilterState (&FPS);
            tempFI.IncludeFeature [FEATDEF_CDS] = FIP->IncludeFeature [FEATDEF_CDS];
            tempFI.IncludeFeature [FEATDEF_mRNA] = FIP->IncludeFeature [FEATDEF_mRNA];
            height = ProcessRows (layoutC, &FPS, vContext);
            FPS.ceiling -= height;

            ResetFilterState (&FPS);
            MemCopy (&tempFI.IncludeFeature, &FIP->IncludeFeature, sizeof (tempFI.IncludeFeature));
            tempFI.GroupPadding = FIP->GroupPadding;
            height = ProcessRows (Layout_PackUpward, &FPS, vContext);
            FPS.ceiling -= height;
            height = 0;
            if (FPS.featuresProcessedCount != 0) {
              emptyFilterGroup = FALSE;
            }

            break;
          default:
            FPS.currentFIP = FIP;
            ResetFilterState (&FPS);
            height = ProcessRows (layoutC, &FPS, vContext);
            if (FPS.featuresProcessedCount != 0) {
              emptyFilterGroup = FALSE;
            }
            break;
        } /* switch (layoutC) */
        break;
    } /* switch (FIP->type) */
    if (emptyFilterGroup) {
      FPS.ceiling = undoCeiling;
      continue;
    } else {
      switch (FIP->GroupLabelLoc) {
      default: break;
      case LabelOnTop:
        /* already done in DrawFilterItemBoxLabel() */
        break;
      case LabelOnSide:
        AddAttribute (vContext->drawOnMe, COLOR_ATT, FIP->GroupLabelColor, 0, 0, 0, 0);
        AddTextLabel (filterSeg, 0, FPS.ceiling - height / 2, FIP->GroupLabel,
                      FIP->GroupLabelFont, 1, MIDDLE_RIGHT, 0);
        SelectFont (FIP->GroupLabelFont);
        height = MAX (height, LineHeight () + 3);
        FPS.groupLabelDrawn = TRUE;
        break;
      case LabelOnBottom:
        AddAttribute (vContext->drawOnMe, COLOR_ATT, FIP->GroupLabelColor, 0, 0, 0, 0);
        AddTextLabel (filterSeg, (vContext->from + vContext->to) / 2 , FPS.ceiling - height, FIP->GroupLabel,
                      FIP->GroupLabelFont, 1, LOWER_CENTER, 0);
        SelectFont (FIP->GroupLabelFont);
        height += LineHeight () + 3;
        FPS.groupLabelDrawn = TRUE;
        break;
      }
    }
    if (FPS.groupBoxDrawn) {
      FPS.ceiling -= 10;
    }
    FPS.ceiling -= height + FIP->GroupPadding;
    if (FPS.needFreeList != NULL) {
      FPS.needFreeList = ValNodeFreeData (FPS.needFreeList);
      FPS.lastInFreeList = NULL;
    }
  } /* for ( FP->FilterItemList->next ) */

  if (FP->GroupByAnnot && FP->AnnotLabelLoc == LabelOnBottom) {
    CharPtr             annotName;

    annotName = GetSeqAnnotName(vContext->currentSAP);
    if (annotName != NULL && !StringHasNoText(annotName))
    {
      AddAttribute (vContext->sanLevelSeg, COLOR_ATT, FP->AnnotLabelColor, 0, 0, 0, 0);
      AddTextLabel (vContext->sanLevelSeg, (vContext->from + vContext->to) / 2 , FPS.ceiling, annotName,
                    FP->AnnotLabelFont, 1, LOWER_CENTER, 0);
      SelectFont (FP->AnnotLabelFont);
      FPS.ceiling -= LineHeight () + 3;
      FPS.annotLabelDrawn = TRUE;
    }
  }
  if (FPS.annotBoxDrawn) {
    /* add invisible line to force width of SegRect and space under group boxes. */
    invisibleSeg = CreateSegment (vContext->sanLevelSeg, 0, 0);
    SetSegmentVisibleFlag (invisibleSeg, FALSE);
    AddLine (invisibleSeg, vContext->from - 3 * vContext->viewScale ,  FPS.ceiling + 10, 
                           vContext->to + 3 * vContext->viewScale ,  FPS.ceiling + 10, FALSE, 0);
    FPS.ceiling -= 20;
  }
  if (FPS.needFreeList != NULL) {
    FPS.needFreeList = ValNodeFreeData (FPS.needFreeList);
    FPS.lastInFreeList = NULL;
  }

  if (vContext->ceiling != NULL) {
    *vContext->ceiling = FPS.ceiling;
  }
  return TRUE;
}

NLM_EXTERN RelevantFeaturesPtr FreeCollectedFeatures (
  RelevantFeaturesPtr RFP
)

{
  if (RFP == NULL) return NULL;
  if (RFP->sapList) {
    MemFree (RFP->sapList);
  }
  if (RFP->featVNP != NULL) {
    ValNodeFreeData (RFP->featVNP);
  }
  MemFree (RFP);
  return NULL;
}

NLM_EXTERN SegmenT CreateGraphicViewInternal (
  BioseqPtr bsp,
  Int4 from,
  Int4 to,
  Boolean allFeatures,
  RelevantFeaturesPtr feats,
  Int4 scale,
  Int4Ptr ceiling,
  SegmenT topLevel,
  AppearancePtr AP,
  FilterPtr FP,
  LayoutAlgorithm overrideLayout,
  GraphicViewExtrasPtr extras
)

{
  ViewerContext  VC;
  Int2           sapIndex;
  Int4           theCeiling = 0;

  /*
    Removed checks feats->featureCount == 0 || feats->featVNP == NULL
    to allow display of BSP w/0 features on it.
   */

  if (AP == NULL || FP == NULL) return NULL;
  MemSet ((Pointer) &VC, 0, sizeof (ViewerContext));
  VC.from = MIN (from, to);
  VC.to =   MAX (from, to);
  VC.allFeatures = allFeatures;
  VC.BSP = bsp;
  VC.viewScale = scale;
  VC.sapList = feats->sapList;
  VC.sapCount = feats->sapCount;
  if (topLevel == NULL) {
    VC.drawOnMe = VC.sanLevelSeg = VC.topLevelSeg = CreatePicture ();
  } else {
    VC.drawOnMe = VC.sanLevelSeg = VC.topLevelSeg = topLevel;
  }
  VC.featureCount = feats->featureCount;
  VC.featVNP = feats->featVNP;
  VC.AppPtr = AP;
  VC.FltPtr = FP;
  VC.overrideLayout = overrideLayout;
  VC.seqLength = bsp->length;
  VC.extras = extras;
  
  if (NULL == ceiling)
    VC.ceiling = &theCeiling;
  else
    VC.ceiling = ceiling;
  
  VC.currentSAP = NULL;
  FilterAndLayout (&VC);
  /* do again for named Seq Annot's */
  if (FP->GroupByAnnot)
  {
    for (sapIndex = 0; sapIndex < VC.sapCount; ++sapIndex) {
      VC.currentSAP = VC.sapList[sapIndex];
      FilterAndLayout (&VC);    
    }
  }
  return VC.topLevelSeg;
}

/* returns the 1st segment in a linked list. caller must deallocate it */
NLM_EXTERN SegmenT CreateGraphicViewFromBsp (
  BioseqPtr bsp,
  SeqLocPtr location,
  Int4 scale,
  Int4Ptr ceiling,
  SegmenT topLevel,
  AppearancePtr AP,
  FilterPtr FP,
  LayoutAlgorithm overrideLayout,
  GraphicViewExtrasPtr extras
)

{
  RelevantFeaturesPtr   RFP;
  SegmenT               seg;
  SeqIntPtr             sintp;
  BioseqPtr             parent;
  SeqMgrSegmentContext  context;
  Int4                  from = 0;
  Int4                  to = 0;
  Boolean               allFeatures = TRUE;

  if (location != NULL) {
    bsp = BioseqFindFromSeqLoc (location);
    if (bsp == NULL) return NULL;
    to = bsp->length - 1;

    if (location->choice == SEQLOC_WHOLE) {
      location = NULL; /* no special behavior needed if it's whole */
    } else if (location->choice == SEQLOC_INT) {
      sintp = (SeqIntPtr) location->data.ptrvalue;
      if (sintp != NULL && sintp->from == 0 && sintp->to == bsp->length - 1) {
        location = NULL;
      } else if (sintp != NULL) {
        from = sintp->from;
        to = sintp->to;
        allFeatures = FALSE;
      }
    }
  } else if (bsp != NULL) {
    to = bsp->length - 1;
  }
  if (bsp == NULL) return NULL;
  parent = SeqMgrGetParentOfPart (bsp, &context);
  if (parent != NULL) {
    from = context.cumOffset;
    to = from + context.to - context.from;
    allFeatures = FALSE;
    bsp = parent;
  }
  RFP = CollectFeatures (bsp);
  if (RFP == NULL) return NULL;
  seg = CreateGraphicViewInternal (bsp, from, to, allFeatures, RFP, scale, ceiling, topLevel, AP, FP, overrideLayout, extras);
  FreeCollectedFeatures (RFP);
  return seg;
}

NLM_EXTERN SegmenT CreateGraphicView (
  BioseqPtr bsp,
  SeqLocPtr location,
  Int4 scale,
  CharPtr styleName,
  CharPtr filterName,
  CharPtr overrideLayoutName,
  GraphicViewExtrasPtr extras
)

{
  ViewerConfigsPtr  myVCP;
  FilterPtr         FP;
  AppearancePtr     AP;
  LayoutAlgorithm   overrideLayout;
  Int1              i;

  if (bsp == NULL && location == NULL) return NULL;
  myVCP = GetGraphicConfigParseResults ();

  AP = FindAppearanceByName (styleName, myVCP);
  FP = FindFilterByName (filterName, myVCP);
  i = StringIndexInStringList (overrideLayoutName, LayoutStrings);
  if (i >= 0 && i < DIM (LayoutValues)) {
    overrideLayout = LayoutValues[i];
  } else {
    overrideLayout = Layout_Inherit;
  }
      
  return CreateGraphicViewFromBsp (bsp, location, scale, NULL, NULL, AP, FP, overrideLayout, extras);
}

NLM_EXTERN Uint2 GetAppearanceCount (void)

{
  ViewerConfigsPtr VCP;

  VCP = GetGraphicConfigParseResults ();
  if (VCP == NULL) return 0;
  return VCP->AppearanceCount;
}

NLM_EXTERN Uint2 GetFilterCount (void)

{
  ViewerConfigsPtr VCP;

  VCP = GetGraphicConfigParseResults ();
  if (VCP == NULL) return 0;
  return VCP->FilterCount;
}

NLM_EXTERN Uint2 GetLayoutCount (void)

{
  return DIM (LayoutStrings);
}

NLM_EXTERN Uint2 GetAlnScoreCount (void)
{
  return DIM (AlnScoreStrings);
}

NLM_EXTERN Uint2 GetAlnScoreCutoffCount (void)
{
  return DIM (AlnScoreCutoffStrings);
}

NLM_EXTERN CharPtr PNTR GetStyleNameList (void)

{
  ViewerConfigsPtr VCP;

  VCP = GetGraphicConfigParseResults ();
  if (VCP == NULL) return NULL;
  return VCP->AppearanceNameArray;
}

NLM_EXTERN CharPtr PNTR GetFilterNameList (void)

{
  ViewerConfigsPtr VCP;

  VCP = GetGraphicConfigParseResults ();
  if (VCP == NULL) return NULL;
  return VCP->FilterNameArray;
}

NLM_EXTERN CharPtr PNTR GetAlnScoreNameList(void)
{
    return AlnScoreStrings;
}

NLM_EXTERN CharPtr PNTR GetAlnScoreCutoffList(void)
{
    return AlnScoreCutoffStrings;
}

NLM_EXTERN CharPtr PNTR GetLayoutNameList (void)

{
  return LayoutStrings;
}


/* -=-=-=-=-=-=-=- append default-style.c contents after this point -=-=-=-=-=-=-=-=- */

/* default-style.c : creates a default style for the new graphic viewer
  This is an automatically generated file, which came from an asn2gph configuration file (asn2gph.default)
  It might be better to edit the input file and then re-run the script create-default-style.tcl than to
  edit this file directly.
*/


typedef struct configFileLine {
  CharPtr key, value;
} ConfigFileLine, PNTR ConfigFileLinePtr;

typedef struct staticConfigFile {
  ConfigFileLinePtr lines;
  CharPtr sectionName;
} StaticConfigFile, PNTR StaticConfigFilePtr;


/* [Styles] */
static ConfigFileLine defaultStyleLines1 [] = {
  {"style00", "defaultStyle"},
  {"style100", "summary"},
  {NULL, NULL}
};

/* [defaultStyle.master] */
static ConfigFileLine defaultStyleLines2 [] = {
  {"name", "Default"},
  {"maxarrowscale", "200"},
  {"minarrowpixels", "5"},
  {"shadesmears", "false"},
  {"color", "black"},
  {"labelfont", "program"},
  {"labelcolor", "black"},
  {"label", "above"},
  {"grouplabelfont", "program"},
  {"grouplabelcolor", "dark gray"},
  {"groupboxcolor", "gray"},
  {"displaywith", "box"},
  {"height", "8"},
  {"gap", "line"},
  {"showarrow", "no"},
  {"showtype", "yes"},
  {"showcontent", "yes"},
  {"shadesmears", "false"},
  {"annotboxcolor", "100, 100, 100"},
  {"annotlabelcolor", "black"},
  {"annotlabelfont", "program"},
  {NULL, NULL}
};

/* [defaultStyle.bioseq] */
static ConfigFileLine defaultStyleLines3 [] = {
  {"label", "left"},
  {"format", "accn"},
  {"scale", "true"},
  {"labelfont", "program"},
  {"scalefont", "small"},
  {"height", "10"},
  {"scaleheight", "10"},
  {"color", "0, 0, 0"},
  {"labelcolor", "64, 64, 255"},
  {"scalecolor", "32, 32, 32"},
  {NULL, NULL}
};

/* [defaultStyle.gene] */
static ConfigFileLine defaultStyleLines4 [] = {
  {"label", "above"},
  {"color", "blue"},
  {"labelcolor", "blue"},
  {"showarrow", "true"},
  {NULL, NULL}
};

/* [defaultStyle.mRNA] */
static ConfigFileLine defaultStyleLines5 [] = {
  {"label", "above"},
  {"color", "cyan"},
  {"labelcolor", "cyan"},
  {"showarrow", "true"},
  {"gap", "line"},
  {NULL, NULL}
};

/* [defaultStyle.cds] */
static ConfigFileLine defaultStyleLines6 [] = {
  {"label", "above"},
  {"color", "magenta"},
  {"labelcolor", "magenta"},
  {"showarrow", "true"},
  {"gap", "angle"},
  {NULL, NULL}
};

/* [defaultStyle.tRNA] */
static ConfigFileLine defaultStyleLines7 [] = {
  {"label", "above"},
  {"color", "green"},
  {"labelcolor", "green"},
  {"showarrow", "true"},
  {"gap", "line"},
  {NULL, NULL}
};

/* [defaultStyle.imp] */
static ConfigFileLine defaultStyleLines8 [] = {
  {"showcontent", "no"},
  {"color", "gray"},
  {"labelcolor", "gray"},
  {NULL, NULL}
};

/* [defaultStyle.exon] */
static ConfigFileLine defaultStyleLines9 [] = {
  {"showcontent", "no"},
  {"color", "dark cyan"},
  {"labelcolor", "dark cyan"},
  {NULL, NULL}
};

/* [defaultStyle.intron] */
static ConfigFileLine defaultStyleLines10 [] = {
  {"showcontent", "no"},
  {"color", "light gray"},
  {"labelcolor", "light gray"},
  {NULL, NULL}
};

/* [defaultStyle.bond] */
static ConfigFileLine defaultStyleLines11 [] = {
  {"displaywith", "cappedline"},
  {NULL, NULL}
};

/* [defaultStyle.align] */
static ConfigFileLine defaultStyleLines12 [] = {
  {"label", "above"},
  {"color", "blue"},
  {"labelcolor", "blue"},
  {"showarrow", "true"},
  {"showtype", "no"},
  {"showcontent", "yes"},
  {"format", "accession"},
  {NULL, NULL}
};

/* [summary.master] */
static ConfigFileLine defaultStyleLines13 [] = {
  {"name", "Summary"},
  {"label", "none"},
  {"height", "3"},
  {"labelfont", "small"},
  {"grouplabelfont", "small"},
  {"annotlabelfont", "small"},
  {NULL, NULL}
};

/* [summary.bioseq] */
static ConfigFileLine defaultStyleLines14 [] = {
  {"label", "above"},
  {"format", "accn"},
  {"scale", "true"},
  {"labelfont", "program"},
  {"scalefont", "small"},
  {"height", "5"},
  {"scaleheight", "5"},
  {"color", "0, 0, 0"},
  {"labelcolor", "64, 64, 255"},
  {"scalecolor", "32, 32, 32"},
  {NULL, NULL}
};

/* [summary.gene] */
static ConfigFileLine defaultStyleLines15 [] = {
  {"label", "above"},
  {"color", "blue"},
  {"labelcolor", "blue"},
  {"showarrow", "true"},
  {NULL, NULL}
};

/* [summary.mRNA] */
static ConfigFileLine defaultStyleLines16 [] = {
  {"label", "above"},
  {"color", "cyan"},
  {"labelcolor", "cyan"},
  {"showarrow", "true"},
  {"gap", "line"},
  {NULL, NULL}
};

/* [summary.cds] */
static ConfigFileLine defaultStyleLines17 [] = {
  {"label", "above"},
  {"color", "magenta"},
  {"labelcolor", "magenta"},
  {"showarrow", "true"},
  {"gap", "angle"},
  {NULL, NULL}
};

/* [summary.tRNA] */
static ConfigFileLine defaultStyleLines18 [] = {
  {"label", "above"},
  {"color", "green"},
  {"labelcolor", "green"},
  {"showarrow", "true"},
  {"gap", "line"},
  {NULL, NULL}
};

/* [summary.align] */
static ConfigFileLine defaultStyleLines19 [] = {
  {"label", "above"},
  {"color", "blue"},
  {"labelcolor", "blue"},
  {"showarrow", "true"},
  {"showtype", "no"},
  {"showcontent", "yes"},
  {"format", "accession"},
  {NULL, NULL}
};

/* [summary.imp] */
static ConfigFileLine defaultStyleLines20 [] = {
  {"showcontent", "no"},
  {"color", "gray"},
  {"labelcolor", "gray"},
  {NULL, NULL}
};

/* [summary.exon] */
static ConfigFileLine defaultStyleLines21 [] = {
  {"showcontent", "no"},
  {"color", "dark cyan"},
  {"labelcolor", "dark cyan"},
  {NULL, NULL}
};

/* [summary.intron] */
static ConfigFileLine defaultStyleLines22 [] = {
  {"showcontent", "no"},
  {"color", "light gray"},
  {"labelcolor", "light gray"},
  {NULL, NULL}
};

/* [summary.bond] */
static ConfigFileLine defaultStyleLines23 [] = {
  {"displaywith", "cappedline"},
  {NULL, NULL}
};

/* [Filters] */
static ConfigFileLine defaultStyleLines24 [] = {
  {"filter00", "defaultFilt"},
  {"filter100", "summary"},
  {"maxlabelscale", "200"},
  {"grouppadding", "2"},
  {"rowpadding", "2"},
  {"annotgroup", "yes"},
  {"annotbox", "yes"},
  {"annotlabel", "above"},
  {NULL, NULL}
};

/* [defaultFilt] */
static ConfigFileLine defaultStyleLines25 [] = {
  {"name", "Default"},
  {"layout", "compact"},
  {"group1", "defaultFilt-operons"},
  {"group2", "defaultFilt-gene-cds-prot-mrna"},
  {"group3", "defaultFilt-other-rnas"},
  {"group4", "defaultFilt-exon-intron-label"},
  {"group5", "defaultFilt-variations"},
  {"group6", "defaultFilt-conflicts"},
  {"group7", "defaultFilt-STS"},
  {"group8", "defaultFilt-impfeats"},
  {"group9", "defaultFilt-alignments"},
  {"group10", "defaultFilt-everything-else-label"},
  {NULL, NULL}
};

/* [filters.defaultFilt-gene-cds-prot-mrna] */
static ConfigFileLine defaultStyleLines26 [] = {
  {"feature1", "gene"},
  {"feature2", "cds"},
  {"feature3", "prot"},
  {"feature4", "mrna"},
  {"name", "Gene-mRNA-CDS-Prots"},
  {"grouplabel", "none"},
  {"layout", "geneproducts"},
  {"showtype", "yes"},
  {"showcontent", "yes"},
  {"label", "above"},
  {NULL, NULL}
};

/* [filters.defaultFilt-other-rnas] */
static ConfigFileLine defaultStyleLines27 [] = {
  {"feature1", "rna"},
  {"name", "Structural RNAs"},
  {"grouplabel", "none"},
  {"label", "above"},
  {NULL, NULL}
};

/* [filters.defaultFilt-operons] */
static ConfigFileLine defaultStyleLines28 [] = {
  {"feature1", "operon"},
  {"name", "Operons"},
  {"grouplabel", "none"},
  {"label", "above"},
  {NULL, NULL}
};

/* [filters.defaultFilt-exon-intron-label] */
static ConfigFileLine defaultStyleLines29 [] = {
  {"feature1", "exon"},
  {"feature2", "intron"},
  {"name", "Introns and Exons"},
  {"grouplabel", "none"},
  {"label", "above"},
  {NULL, NULL}
};

/* [filters.defaultFilt-variations] */
static ConfigFileLine defaultStyleLines30 [] = {
  {"feature1", "variation"},
  {"name", "Variations"},
  {"groupbox", "true"},
  {"boxcolor", "red"},
  {"grouplabel", "above"},
  {"layout", "smear"},
  {"showtype", "no"},
  {"showcontent", "no"},
  {NULL, NULL}
};

/* [filters.defaultFilt-conflicts] */
static ConfigFileLine defaultStyleLines31 [] = {
  {"feature1", "conflict"},
  {"name", "Conflicts"},
  {"groupbox", "true"},
  {"boxcolor", "dark red"},
  {"grouplabel", "above"},
  {"layout", "smear"},
  {"showtype", "no"},
  {"showcontent", "no"},
  {NULL, NULL}
};

/* [filters.defaultFilt-STS] */
static ConfigFileLine defaultStyleLines32 [] = {
  {"feature1", "STS"},
  {"name", "STS"},
  {"groupbox", "true"},
  {"boxcolor", "red"},
  {"grouplabel", "above"},
  {"layout", "smear"},
  {"showtype", "no"},
  {"showcontent", "no"},
  {NULL, NULL}
};

/* [filters.defaultFilt-impfeats] */
static ConfigFileLine defaultStyleLines33 [] = {
  {"feature1", "import"},
  {"name", "Import Features"},
  {"grouplabel", "none"},
  {"label", "above"},
  {NULL, NULL}
};

/* [filters.defaultFilt-alignments] */
static ConfigFileLine defaultStyleLines34 [] = {
  {"feature1", "align"},
  {"name", "Alignments"},
  {"grouplabel", "none"},
  {"label", "above"},
  {"layout", "smear"},
  {"showtype", "no"},
  {NULL, NULL}
};

/* [filters.defaultFilt-everything-else-label] */
static ConfigFileLine defaultStyleLines35 [] = {
  {"feature1", "everything"},
  {"grouplabel", "none"},
  {"label", "above"},
  {NULL, NULL}
};

/* [summary] */
static ConfigFileLine defaultStyleLines36 [] = {
  {"group1", "summary-gene-rna-cds-nolabel"},
  {"group2", "summary-allelse"},
  {"group3", "summary-aligns-nolabel"},
  {"name", "Summary"},
  {"defaultlayout", "compact"},
  {"rowpadding", "3"},
  {"grouppadding", "1"},
  {"label", "none"},
  {"annotlabelfont", "small"},
  {NULL, NULL}
};

/* [filters.summary-gene-rna-cds-nolabel] */
static ConfigFileLine defaultStyleLines37 [] = {
  {"feature1", "gene"},
  {"feature2", "rna"},
  {"feature3", "cds"},
  {"layout", "geneproducts"},
  {"label", "none"},
  {NULL, NULL}
};

/* [filters.summary-aligns-nolabel] */
static ConfigFileLine defaultStyleLines38 [] = {
  {"feature1", "align"},
  {"label", "none"},
  {NULL, NULL}
};

 /* [filters.summary-allelse] */
static ConfigFileLine defaultStyleLines39 [] = {
  {"feature1", "everything"},
  {"layout", "smear"},
  {"label", "none"},
  {NULL, NULL}
};


static StaticConfigFile defaultStyle [] = {
  {defaultStyleLines1, "Styles"},
  {defaultStyleLines2, "defaultStyle.master"},
  {defaultStyleLines3, "defaultStyle.bioseq"},
  {defaultStyleLines4, "defaultStyle.gene"},
  {defaultStyleLines5, "defaultStyle.mRNA"},
  {defaultStyleLines6, "defaultStyle.cds"},
  {defaultStyleLines7, "defaultStyle.tRNA"},
  {defaultStyleLines8, "defaultStyle.imp"},
  {defaultStyleLines9, "defaultStyle.exon"},
  {defaultStyleLines10, "defaultStyle.intron"},
  {defaultStyleLines11, "defaultStyle.bond"},
  {defaultStyleLines12, "defaultStyle.align"},
  {defaultStyleLines13, "summary.master"},
  {defaultStyleLines14, "summary.bioseq"},
  {defaultStyleLines15, "summary.gene"},
  {defaultStyleLines16, "summary.mRNA"},
  {defaultStyleLines17, "summary.cds"},
  {defaultStyleLines18, "summary.tRNA"},
  {defaultStyleLines19, "summary.align"},
  {defaultStyleLines20, "summary.imp"},
  {defaultStyleLines21, "summary.exon"},
  {defaultStyleLines22, "summary.intron"},
  {defaultStyleLines23, "summary.bond"},
  {defaultStyleLines24, "Filters"},
  {defaultStyleLines25, "defaultFilt"},
  {defaultStyleLines26, "filters.defaultFilt-gene-cds-prot-mrna"},
  {defaultStyleLines27, "filters.defaultFilt-other-rnas"},
  {defaultStyleLines28, "filters.defaultFilt-operons"},
  {defaultStyleLines29, "filters.defaultFilt-exon-intron-label"},
  {defaultStyleLines30, "filters.defaultFilt-variations"},
  {defaultStyleLines31, "filters.defaultFilt-conflicts"},
  {defaultStyleLines32, "filters.defaultFilt-STS"},
  {defaultStyleLines33, "filters.defaultFilt-impfeats"},
  {defaultStyleLines34, "filters.defaultFilt-alignments"},
  {defaultStyleLines35, "filters.defaultFilt-everything-else-label"},
  {defaultStyleLines36, "summary"},
  {defaultStyleLines37, "filters.summary-gene-rna-cds-nolabel"},
  {defaultStyleLines38, "filters.summary-aligns-nolabel"},
  {defaultStyleLines39, "filters.summary-allelse"},
  {NULL, NULL}
};


static void InitializeDefaultStyle (
  CharPtr configFileName
)

{
  Uint2             sectionNum, lineNum;
  ConfigFileLinePtr lines;
  CharPtr           sectionName;

  for (sectionNum = 0; defaultStyle [sectionNum].lines != NULL; sectionNum++) {
    lines = defaultStyle [sectionNum].lines;
    sectionName = defaultStyle [sectionNum].sectionName;
    for (lineNum = 0; lines [lineNum].key != NULL && lines [lineNum].value != NULL; lineNum++) {
      TransientSetAppParam (configFileName, sectionName, lines [lineNum].key, lines [lineNum].value);
    }
  }
}

/* End of automatically generated file. */