summaryrefslogtreecommitdiff
path: root/api/pgppop.c
blob: d16d79d8071c1900c62cd740655f9b9a2e19ff75 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
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
/*  $Id: pgppop.c,v 6.68 2006/07/13 17:06:39 bollin Exp $
* ===========================================================================
*
*                            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:  pgppop.c
*
* Author:  Patrick Durand
*
* Version Creation Date:   05/03/99
*
* $Revision: 6.68 $
*
* File Description: 
*
* Modifications:
* --------------------------------------------------------------------------
*
* $Log: pgppop.c,v $
* Revision 6.68  2006/07/13 17:06:39  bollin
* use Uint4 instead of Uint2 for itemID values
* removed unused variables
* resolved compiler warnings
*
* Revision 6.67  2001/10/03 00:15:47  vakatov
* Replaced some ASSERTs by VERIFYs
*
* Revision 6.66  2001/01/16 17:15:54  hurwitz
* modified DDV_GetBspCoordGivenDispCoord
*
* Revision 6.65  2001/01/10 23:38:39  lewisg
* fix seqid and various memory leaks
*
* Revision 6.64  2000/10/25 01:22:56  bauer
* fixed DDV display of PDB-Id's in CDD-server
*
* Revision 6.63  2000/10/13 19:48:16  hurwitz
* added functions for getting first VALID disp coord in range of bsp coords
*
* Revision 6.62  2000/08/25 18:57:12  shavirin
* Removed printing of BLAST middle line if characters in 1st and 3d
* lines are in lower case - used for unaligned regions.
*
* Revision 6.61  2000/08/11 20:59:07  shavirin
* Added default character for a gap in the function DDV_GetSequenceFromParaG().
*
* Revision 6.60  2000/07/18 19:59:24  bauer
* fixed bug in DDV_Print_Sequence
*
* Revision 6.59  2000/05/19 14:30:52  wheelan
* fixed problem with formatting PDB ids
*
* Revision 6.58  2000/04/19 12:33:32  durand
* for HTML output, replaced double quote char. by a spacein the defline
*
* Revision 6.57  2000/03/31 21:33:21  durand
* added new default color schemas for BLAST
*
* Revision 6.56  2000/03/29 14:21:56  durand
* fixed problem when displaying middle line of BLAST SeqAligns
*
* Revision 6.54  2000/03/28 13:32:28  durand
* update DDV_DisplayDefaultAlign to receive a pre-initialized DDV_Disp_Opt data structure
*
* Revision 6.53  2000/03/27 14:19:13  durand
* fixed bugs in BLAST outputs
*
* Revision 6.52  2000/03/24 12:58:55  durand
* fixed a bug in DDV_DisplayDefaultAlign
*
* Revision 6.51  2000/03/22 14:14:25  durand
* updated DDV_DisplayDefaultAlign to get the SeqAlign size correclty
*
* Revision 6.50  2000/03/21 19:26:48  durand
* pgppop now uses AlignMgr
*
* Revision 6.49  2000/02/24 16:46:51  thiessen
* fixed improper acces to freed memory
*
* Revision 6.48  2000/02/23 19:49:49  durand
* use row number instead of SeqId for coloring
*
* Revision 6.47  2000/02/22 21:20:11  durand
* remove the second $LOG line
*
* Revision 6.46  2000/02/22 20:55:22  thiessen
* add null pointer test to DDV_GetBspCoordGivenDispCoord()
*
* Revision 6.45  2000/02/17 15:54:35  durand
* use ~ for an unaligned gap and - for an aligned gap
*
* Revision 6.44  2000/02/15 15:31:45  lewisg
* move DDVRulerDescr to pgppop
*
* Revision 6.43  2000/02/14 16:39:55  durand
* add new output options for BLAST
*
* Revision 6.42  2000/02/07 14:16:56  durand
* replaced BioseqUnlockById by BioseqUnlock
*
* Revision 6.41  2000/02/03 14:03:57  durand
* replaced call to FeatDefLine() by CreateDefLine()
*
* Revision 6.40  2000/01/26 15:08:22  durand
* update DDV_DeleteParaGList function
*
* Revision 6.39  1999/12/29 22:55:02  lewisg
* get rid of seqalign id
*
* Revision 6.38  1999/12/20 14:37:53  durand
* transfer some PopSet Viewer functions from here to wwwddv.c; update the code to better use Color Manager for BLAST outputs
*
* Revision 6.37  1999/12/08 22:40:54  durand
* add the code to produce colored BLAST outputs
*
* Revision 6.36  1999/12/07 18:46:33  durand
* add DDV_GetBspCoordGivenPgpList function
*
* Revision 6.35  1999/11/26 15:42:25  vakatov
* Fixed for the C++ and/or MSVC DLL compilation
*
* Revision 6.34  1999/10/29 14:14:24  durand
*  add DDV_GetBspCoordGivenDispCoord() and DDV_GetDispCoordGivenBspCoord()
*
* Revision 6.33  1999/10/20 13:13:53  durand
* add new fields in data structure for DDV
*
* Revision 6.32  1999/10/08 17:50:28  durand
* move DDV_DisplayBlastSAP from pgppop.c to ddvcreate.c due to conflict between api and ddv
*
* Revision 6.31  1999/10/07 19:18:46  durand
* Modified function DDV_DisplayBlastSAP to use AlignMgr
*
* Revision 6.30  1999/09/29 17:16:44  shavirin
* Modified function DDV_DisplayBlastSAP(): added new parameter and printing
* of the BLAST scores.
*
* Revision 6.29  1999/09/29 13:42:27  durand
* add middle line for BLAST output
*
* Revision 6.27  1999/09/28 19:49:30  shavirin
* Changed definition of the function DDV_DisplayBlastSAP()
*
* Revision 6.26  1999/09/28 13:06:39  durand
* add a first set of functions to display CDS in PopSet Viewer
*
* Revision 6.24  1999/09/16 18:52:26  durand
* redesign the PopSet viewer toolbar
*
* Revision 6.23  1999/09/07 13:41:55  durand
* update Entrez links for PopSet Viewer
*
* Revision 6.22  1999/09/02 19:08:56  chappey
* fixes in PrintSeqAlignCallback
*
* Revision 6.21  1999/09/01 21:04:20  durand
* call SeqAlignSetFree after PairSeqAlign2MultiSeqAlign
*
* Revision 6.20  1999/08/31 13:51:30  durand
* add PubMed link for PopSet Viewer
*
* Revision 6.18  1999/08/30 21:24:23  durand
* display Unpublished study when a PopSet entry doesn't have a title
*
* Revision 6.17  1999/08/30 20:29:56  durand
* make PrintSeqAlignCallback estern function
*
* Revision 6.16  1999/08/30 18:20:11  durand
* update SeqAlignToBS
*
* Revision 6.15  1999/08/30 17:57:05  sirotkin
* changed mydata in PrintSeqAlignCallback
*
* Revision 6.14  1999/08/30 14:18:08  durand
* use ByteStore to format the SeqAlign output
*
* Revision 6.12  1999/08/27 14:54:04  durand
* fix memory leaks in PopSet Viewer
*
* Revision 6.11  1999/08/16 18:56:59  lewisg
* made DDV_GetSeqAlign extern and added prototype to header
*
* Revision 6.10  1999/08/08 15:54:35  chappey
* made DDV_GetSeqAlign static as there is no prototype
*
* Revision 6.9  1999/08/07 16:57:48  sicotte
* fixed compiler warnings
*
* Revision 6.8  1999/08/07 16:53:13  sicotte
* added includes sqnutils.h and alignval.h for new code
*
* Revision 6.7  1999/08/06 21:43:17  chappey
* SeqAlignToBS new function to save in ByteStore structure the text output of the SeqAlign(s) packaged in a SeqEntry
*
* Revision 6.6  1999/07/22 13:23:13  durand
* made DDV_SearchAli external function
*
* Revision 6.5  1999/07/21 21:52:12  durand
* add some functions to display a summary for a PopSet entry
*
* Revision 6.4  1999/07/19 21:16:01  durand
* add DDV_ResetParaGSeqAlignCoord to reset the seqalign coord in the display data structures of DDV
*
* Revision 6.3  1999/07/15 18:20:51  durand
* add display options to support BLAST outputs
*
* Revision 6.2  1999/07/13 20:46:56  durand
* comment out call to PairSeqAlign2MultiSeqAlign to avoid DDV compiling problems
*
* Revision 6.1  1999/07/09 13:59:58  durand
* move pgppop from desktop to api
*
* Revision 6.2  1999/07/07 19:12:26  durand
* fix a tiny bug in DDV_GetSequenceFromParaG
*
* Revision 6.1  1999/07/06 20:18:07  kans
* initial public checkin
*
* Revision 1.35  1999/07/06 18:54:27  durand
* add new features for the display of PopSet viewer
*
* Revision 1.34  1999/07/02 13:22:17  durand
* fix bugs for the display of minus strand sequences
*
* Revision 1.32  1999/06/29 16:48:10  shavirin
* Changed definition of function DDV_ShowSeqAlign()
*
* Revision 1.31  1999/06/28 22:07:20  durand
* add loader functions and clean the code with Lint and Purify
*
* Revision 1.30  1999/06/24 20:49:41  shavirin
* Added new function DDV_ShowSeqAlign().
*
* Revision 1.29  1999/06/23 18:11:17  durand
* fix a variable initialization problem under NT
*
* Revision 1.28  1999/06/23 17:24:23  durand
* use a binary encoding to manage the display styles
*
* Revision 1.27  1999/06/21 18:37:56  durand
* update DDV_DisplayDefaultAlign to produce full text output
*
* Revision 1.26  1999/06/19 18:36:13  durand
* new display procedure
*
* Revision 1.25  1999/06/16 13:10:48  durand
* update/add functions for Vibrant DDV
*
* Revision 1.24  1999/06/14 23:49:43  durand
* add function for Vibrant DDV
*
* Revision 1.23  1999/06/11 22:33:01  durand
* add new functions for Vibrant DDV
*
* Revision 1.22  1999/06/11 17:59:40  durand
* popset viewer uses more code from UDV
*
* Revision 1.21  1999/06/09 21:35:30  durand
* add constructors/destructors for BspInfo struct as well as read seq function
*
*
*
*
* ==========================================================================
*/
#include <stdio.h>
#include <ncbi.h>
#include <blocks.h>
#include <pgppop.h>
#include <tofasta.h>
#include <udvdef.h>
#include <udvseq.h>
#include <salstruc.h>
#include <sqnutils.h>
#include <alignval.h>
#include <asn2ff6.h>
#include <subutil.h>
#include <ddvcolor.h>
#include <ddvcreate.h>

#define DDV_COLOR_MAX 33 
 static Uint1 DDV_PaletteRGB[DDV_COLOR_MAX][3] =
 {
     /* Red  Grn Blue     Color     ColorID             Old Hex  New Hex */
   255, 255, 255, /* default     0                 0xffffff - */ 
   255,  00, 153, /* hotpink     1                 0xff1493 0xff0099 */
   255,   0, 255, /* magenta     2                 0xff00ff - */
   153,  51, 255, /* purple      3                 0x9b30ff 0x9933ff */
     0,   0, 255, /* blue        4                 0x0000ff - */
    00, 153, 255, /* sky         5                 0x1e90ff 0x0099ff */
     0, 255, 255, /* cyan        6                 0x00ffff - */
     0, 255, 153, /* sea         7                 0x00ff8f 0x00ff99 */
     0, 255,   0, /* green       8                 0x00ff00 - */
   255, 255,   0, /* yellow      9                 0xffff00 - */
   255, 204,   0, /* gold       10                 0xffa500 0xffcc00 */
   255, 102,   0, /* orange     11                 0xff4500 0xff6600 */
   255,   0,   0, /* red        12                 0xff0000 - */
   255, 153, 153, /* pink       13                 0xff7256 0xff9999 */
   255, 204, 204, /* pinktint   14                 0xffaeb9 0xffcccc */
   255, 255, 255, /* white      15                0xffffff  -*/
     0,   0,   0, /* black      16                0x000000 - */
   204, 204, 255, /* bluetint   17                0xb0e2ff - 0xccccff*/
   153, 255, 153, /* greentint  18                0x9aff9a - 0x99ff99 */
   255, 255, 153, /* yellowtint 19                0xffec8b - 0xffff99 */
   102, 102, 102, /* gray       20                0x7d7d7d   0x666666 */
   153, 102,  51, /* brown      21                0x8b5742   01x996633 */
   255,   0,   0, /* perm colors 22: red          0xff0000 - */
     0, 255,   0, /* perm colors 23: green        0x00ff00 - */
   255,   0, 255, /* perm colors 24: magenta      0xff00ff - */
    00, 153, 255, /* perm colors 25: sky          0x1e90ff 0x0099ff */
   153,	 51, 255, /* perm colors 26: purple        0x9b30ff 0x9933ff */
     0, 255,   0, /* SS colors 27: helix, green   0x00ff00 - */
   255, 204,   0, /* SS colors 28: strand, gold   0xffa500 0xffcc00 */
   255, 102,   0, /* SS colors 29: turn, orange   0xff4500 0xff6600 */
     0, 255, 255, /* SS colors 30: coil, cyan     ox00ffff - */
   255, 255,   0, /* highlight colors 31: yellow  0xffff00 - */
     0,   0,   0 /* background colors 32: black  0x000000 - */
 };

static CharPtr DDV_PaletteRGB_NAV[DDV_COLOR_MAX] =
 {
     /* Red  Grn Blue     Color     ColorID             Old Hex  New Hex */
   "ffffff", /* default     0                 0xffffff - */ 
   "ff0099", /* hotpink     1                 0xff1493 0xff0099 */
   "ff00ff", /* magenta     2                 0xff00ff - */
   "9933ff", /* purple      3                 0x9b30ff 0x9933ff */
   "0000ff", /* blue        4                 0x0000ff - */
   "0099ff", /* sky         5                 0x1e90ff 0x0099ff */
   "00ffff", /* cyan        6                 0x00ffff - */
   "00ff99", /* sea         7                 0x00ff8f 0x00ff99 */
   "00ff00", /* green       8                 0x00ff00 - */
   "ffff00", /* yellow      9                 0xffff00 - */
   "ffcc00", /* gold       10                 0xffa500 0xffcc00 */
   "ff6600", /* orange     11                 0xff4500 0xff6600 */
   "ff0000", /* red        12                 0xff0000 - */
   "ff9999", /* pink       13                 0xff7256 0xff9999 */
   "ffcccc", /* pinktint   14                 0xffaeb9 0xffcccc */
   "ffffff", /* white      15                0xffffff  -*/
   "000000", /* black      16                0x000000 - */
   "ccccff", /* bluetint   17                0xb0e2ff - 0xccccff*/
   "99ff99", /* greentint  18                0x9aff9a - 0x99ff99 */
   "ffff99", /* yellowtint 19                0xffec8b - 0xffff99 */
   "666666", /* gray       20                0x7d7d7d   0x666666 */
   "996633", /* brown      21                0x8b5742   01x996633 */
   "ff0000", /* perm colors 22: red          0xff0000 - */
   "00ff00", /* perm colors 23: green        0x00ff00 - */
   "ff00ff", /* perm colors 24: magenta      0xff00ff - */
   "0099ff", /* perm colors 25: sky          0x1e90ff 0x0099ff */
   "9933ff", /* perm colors 26: purple        0x9b30ff 0x9933ff */
   "00ff00", /* SS colors 27: helix, green   0x00ff00 - */
   "ffcc00", /* SS colors 28: strand, gold   0xffa500 0xffcc00 */
   "ff6600", /* SS colors 29: turn, orange   0xff4500 0xff6600 */
   "00ffff", /* SS colors 30: coil, cyan     ox00ffff - */
   "ffff00", /* highlight colors 31: yellow  0xffff00 - */
   "000000" /* background colors 32: black  0x000000 - */
 };

#define DDVCOL_DEFAULT 0
#define DDVCOL_HOTPINK 1
#define DDVCOL_MAGENTA 2
#define DDVCOL_PURPLE 3
#define DDVCOL_BLUE 4
#define DDVCOL_SKY 5
#define DDVCOL_CYAN 6
#define DDVCOL_SEA 7
#define DDVCOL_GREEN 8
#define DDVCOL_YELLOW 9
#define DDVCOL_GOLD 10
#define DDVCOL_ORANGE 11
#define DDVCOL_RED 12
#define DDVCOL_PINK 13
#define DDVCOL_PINKTINT 14
#define DDVCOL_WHITE 15
#define DDVCOL_BLACK 16
#define DDVCOL_BLUETINT 17
#define DDVCOL_GREENTINT 18
#define DDVCOL_YELLOWTINT 19
#define DDVCOL_GRAY 20
#define DDVCOL_BROWN 21

#define DDVCOL_HIGHLIGHT 31
#define DDVCOL_BACKGROUND 32

/*******************************************************************************

  Function : DDV_ConcatStr()
  
  Purpose : merge to CharPtr; realloc if needed
  
  Parameters : 	src; CharPtr source
  				newStr; CharPtr to add to src

  Return value : the merging result of src and newStr

*******************************************************************************/
static CharPtr DDV_ConcatStr(CharPtr src,CharPtr newStr)
{
CharPtr retScr;

	if(src==NULL){
		retScr=StringSave(newStr);
	}
	else{
		retScr=(CharPtr)MemNew((StringLen(src)+StringLen(newStr)+4)*sizeof(Char));
		if (!retScr) return(NULL);
		StringCpy(retScr,src);
		StringCat(retScr,newStr);
		MemFree(src);
	}
	
	return(retScr);
}

/*******************************************************************************

  Function : ConvertToLower()
  
  Purpose : convert an upper case string to a lower case one
  
  Parameters : header of the ValNodeList
  
  Note : this function is a copy of to_lower() (ncbi/tools). Because pgppop.c
         is in ncbi/api, I cannot use the code of salutil.
		 
  Return value : none 

*******************************************************************************/
static CharPtr ConvertToLower (CharPtr str)
{
  CharPtr tmp;
 
  if (str==NULL)
     return NULL;
  tmp = str;
  while (*tmp!='\n' && *tmp!='\0') {
     *tmp = TO_LOWER(*tmp);
     tmp++;
  }
  return str;
}

/*******************************************************************************

  Function : DDV_DeleteTxtList()
  
  Purpose : delete a list of sequence content in a ParaG
  
  Parameters : header of the ValNodeList
  
  Return value : none 

*******************************************************************************/
NLM_EXTERN void DDV_DeleteTxtList(ValNodePtr PNTR vnp)
{
ValNodePtr 	vnp2;
MsaTxtDispPtr mtdp;

	for(vnp2=(*vnp) ; vnp2!=NULL ; vnp2=vnp2->next){
		mtdp=(MsaTxtDispPtr)vnp2->data.ptrvalue;
		if (mtdp) MemFree(mtdp);
	}
	ValNodeFree(*vnp);
	*vnp=NULL;
}

/*******************************************************************************

  Function : DDV_DeleteParaGList()
  
  Purpose : delete a list of ParaG
  
  Parameters : header of the ValNodeList
  
  Return value : none 

*******************************************************************************/
NLM_EXTERN void DDV_DeleteParaGList(ValNodePtr PNTR vnp)
{
ValNodePtr 	vnp2;
ParaGPtr pgp;

	for(vnp2=(*vnp) ; vnp2!=NULL ; vnp2=vnp2->next){
		pgp=(ParaGPtr)vnp2->data.ptrvalue;
		if (pgp){
			if (pgp->ptxtList) DDV_DeleteTxtList(&pgp->ptxtList);
			if (pgp->szEditSeq) MemFree(pgp->szEditSeq);
			if (pgp->pFeatList) ValNodeFree(pgp->pFeatList);
            if (pgp->sip) SeqIdFree(pgp->sip);
			MemFree(pgp);
		}
	}
	ValNodeFree(*vnp);
	*vnp=NULL;
}

/*******************************************************************************

  Function : DDV_DeleteDisplayList()
  
  Purpose : delete the complete lists used for the display
  
  Parameters : main data block used for the display
  
  Return value : none 

*******************************************************************************/
NLM_EXTERN void DDV_DeleteDisplayList(MsaParaGPopListPtr mpplp)
{
Int4 i;

	/*ValNode with ParaG*/
	if (mpplp->TableHead){
		for(i=0;i<mpplp->nBsp;i++){
			if (mpplp->TableHead[i]){
				DDV_DeleteParaGList(&(mpplp->TableHead[i]));
			}
		}
		MemFree(mpplp->TableHead);
	}
}

/*******************************************************************************

  Function : DDV_WWW_get_CDS_minus()
  
  Purpose : get the translation of a CDS located on a PLUS strand
  
  Parameters : context; feature data (see explore.h for a def of the structure)
  				start; get the sequence from...
				stop;... to.
				StartLetter; beginning of a ParaG (zero-based value)
				i; order number of the exon (if CDS is exon-encoded)
  				szDNA; DNA sequence
				LineSize; size of a line
				
  Return value : none

*******************************************************************************/
static void DDV_WWW_get_CDS_minus(SeqMgrFeatContextPtr context,Int4 start,
			Int4 stop,Int4 StartLetter,Int2 i,CharPtr szDNA,CharPtr szTrans,
			Int2 LineSize)
{						
CharPtr      	str=NULL;
Int4			il=0,
				pos=0,
				n=0,
				stop_prot=0,
				gap,
				limit;
Int2 			n2,nCompt,
				decal=0,
				numivals2=0;
ByteStorePtr	bs=NULL;
Boolean bGiForProductOk=FALSE;
SeqIdPtr sip=NULL;
Int4 gi=0;
BioseqPtr prot;

	/*retrieve the protein sequence; need to be optimized in future release*/
	if (context->sfp->product){
		prot=BioseqFind(SeqLocId(context->sfp->product));
		sip=(SeqIdPtr)GetProductSeqId(context->sfp->product);
		if (sip){
			gi = GetGINumFromSip(sip);
			if (gi>0) bGiForProductOk=TRUE;
			str=UDV_Read_Sequence (sip,0,prot->length-1, 
				TRUE,prot->length-1);
		}
	}
	else{
		bs = ProteinFromCdRegion (context->sfp, TRUE);
		if (bs){
			str = (CharPtr) BSMerge (bs, NULL);
			BSFree (bs);
		}
	}

	if (!str) return;	

	/*count the lenght of the intron(s)*/
	numivals2=context->numivals*2;
	if (i>0){
		for(nCompt=i;nCompt>0;nCompt-=2){
			il+=(context->ivals[nCompt-2]-
				context->ivals[nCompt+1]-1);
		}
	}

	pos=context->ivals[1]-il-stop;
	/*place the current position within the correct translation frame*/
	if (pos % 3){
		if (!((pos-1) % 3)){
			pos=(pos-1)/3;
			decal=-1;
		}
		else if (!((pos+1) % 3)){
			pos=(pos+1)/3;
			decal=1;
		}						
	}else {
		pos=pos/3;
		decal=0;
	}

	n=pos;
	stop_prot=stop-decal-1; /*-1 == middle of the codon*/
	
	LineSize--;
	gap=0;
	if (szTrans){
		start--;
		while(stop_prot>start){
			limit=stop_prot-StartLetter+gap+1;
			gap=0;
			for(i=0;i<limit;i++){
				if (szDNA[i]=='-') gap++;
			}
			if (szDNA[limit-1]=='-'){
				while(szDNA[i]){
					if (szDNA[i]=='-') gap++;
					else break;
					i++;
				}
			}
			n2=stop_prot-StartLetter+gap+(stop_prot-StartLetter+gap)/LETTER_BLOCK_WIDTH;
			if (str[n])
				szTrans[n2]=str[n];
			else 
				break;
			
			stop_prot-=3;
			n++;
		}
	}

	if (str){
		MemFree (str);
	}
}


/*******************************************************************************

  Function : DDV_WWW_get_CDS_plus()
  
  Purpose : get the translation of a CDS located on a PLUS strand
  
  Parameters : context; feature data (see explore.h for a def of the structure)
  				start; get the sequence from...
				stop;... to.
				StartLetter; beginning of a ParaG (zero-based value)
				i; order number of the exon (if CDS is exon-encoded)
  				szDNA; DNA sequence
				LineSize; size of a line
				
  Return value : none

*******************************************************************************/
static void DDV_WWW_get_CDS_plus(SeqMgrFeatContextPtr context,Int4 start,
			Int4 stop,Int4 StartLetter,Int4 size_pgp,
			Int2 i,CharPtr szDNA,CharPtr szTrans,
			Int2 LineSize,Uint1 strand)
{						
CharPtr      	str=NULL;
Int4			il=0,
				pos=0,
				n=0,
				start_prot,
				limit,
				gap;
Int2 			n2=0,
				decal=0,
				numivals2=0,
				nCompt=0;
ByteStorePtr	bs=NULL;
Boolean bGiForProductOk=FALSE;
SeqIdPtr sip=NULL;
Int4 gi=0;
BioseqPtr prot;

	/*retrieve the protein sequence; need to be optimized in future release*/
	if (context->sfp->product){
		prot=BioseqFind(SeqLocId(context->sfp->product));
		sip=(SeqIdPtr)GetProductSeqId(context->sfp->product);
		if (sip){
			gi = GetGINumFromSip(sip);
			if (gi>0) bGiForProductOk=TRUE;
			str=UDV_Read_Sequence (sip,0,prot->length-1, 
				TRUE,prot->length);
		}
	}
	else{
		bs = ProteinFromCdRegion (context->sfp, TRUE);
		if (bs){
			str = (CharPtr) BSMerge (bs, NULL);
			BSFree (bs);
		}
	}

	if (!str) return;	
	/*count the lenght of the intron(s)*/
	numivals2=context->numivals*2;
	if (i>0 && i<numivals2){
		for(nCompt=2;nCompt<i+2;nCompt+=2){
			il+=(context->ivals[nCompt]-
				context->ivals[nCompt-1]-1);
		}
	}

	pos=start-il-context->ivals[0];
						
	/*place the current position within the correct translation frame*/
	if (pos % 3){
		if (!((pos-1) % 3)){
			pos=(pos-1)/3;
			decal=-1;
		}
		else if (!((pos+1) % 3)){
			pos=(pos+1)/3;
			decal=1;
		}						
	}else {
		pos=pos/3;
		decal=0;
	}

	n=pos;
	LineSize--;
	gap=0;
	
	if (strand==Seq_strand_minus)
		szDNA=reverse_string(szDNA);

	size_pgp--;
	
	if (szTrans){
		start_prot=start+decal+1;
		stop++;
		while(start_prot<stop){
			limit=start_prot-StartLetter+gap+1;

			gap=0;
			for(i=0;i<limit;i++){
				if (szDNA[i]=='-') gap++;
			}
			if (szDNA[(strand==Seq_strand_minus ? limit : limit-1)]=='-'){
				while(szDNA[i]){
					if (szDNA[i]=='-') gap++;
					else break;
					i++;
				}
			}
			if (strand!=Seq_strand_minus){
				n2=start_prot-StartLetter+gap;
				n2+=(n2/LETTER_BLOCK_WIDTH);
			}
			else{
				n2=size_pgp-(start_prot-StartLetter+gap);
				n2+=(n2/LETTER_BLOCK_WIDTH);
			}
			if (n2>LineSize) break;
			if (str[n])
				szTrans[n2]=str[n];
			else 
				break;
			start_prot+=3;
			n++;
		}
	}
	if (str){
		MemFree (str);
	}
}


NLM_EXTERN void DDV_DispFeaturesForPGP(ParaGPtr pgp,BioseqPtr bsp,CharPtr PNTR szFLine,Int4 disp,
	Int2 LineSize, CharPtr szDNA, Uint1 strand)
{
SeqMgrFeatContext    context2;
SeqMgrFeatContextPtr context=NULL;
SeqMgrSegmentContext contextPart;
ValNodePtr           vnp4;
BioseqPtr            parent;
CharPtr              szTrans;
Int4                 from_bsp,to_bsp,start,stop,i,numivals2,i_decal;
Int2                 jj;
Uint4                iID;
Uint2                idx;
Boolean              bDispTrans=FALSE;

	/*the current bsp is just a segment ?*/
	parent=SeqMgrGetParentOfPart(bsp,&contextPart);
	context=NULL;
	szTrans=NULL;
	
	LineSize+=(LineSize/LETTER_BLOCK_WIDTH);
	szTrans=(CharPtr)MemNew(LineSize*sizeof(Char));

	if (szTrans==NULL) return;

	/*for each feature...*/
	for(jj=0,vnp4=pgp->pFeatList;jj<pgp->nFeat;jj++,vnp4=vnp4->next){
		
		if (vnp4 == NULL) break;
		
		/*...get desired feature given iID and idx...*/
		UDV_BigDecodeIdxFeat ((Uint8)vnp4->data.bigintvalue, &iID,&idx,NULL,NULL);
		if (!SeqMgrGetDesiredFeature(0,
			(parent!=NULL ? parent : bsp),iID,idx,NULL,&context2)) continue;
		/*...then copy the original context feature data ...*/
		if (context) {
			MemFree(context->ivals);
			context=MemFree(context);
		}
		if (context) {
			MemFree(context->ivals);
			context=MemFree(context);
		}
		/*...before I modify it*/
		context=UDV_ConvertFeatContext(&context2,contextPart.cumOffset,
			bsp->length);
		if (!context) continue;
		/*temporary situation; will be modified in the future*/
		if (context->strand>Seq_strand_minus ||
			context->strand==Seq_strand_unknown) context->strand=Seq_strand_plus;

		/*if circular DNA with feature overlapping the junction*/
		if(context->left<0 && context->bsp->topology==TOPOLOGY_CIRCULAR){
			/*technically, just for the purpose of a display, a feature
			overlapping the ends of a circular DNA covers all the sequence; that is
			because I ALWAYS display from LEFT to RIGHT.*/
			context->left=0;
			context->right=context->bsp->length-1;
			
			/*strand PLUS*/
			if (context->strand==Seq_strand_plus){
				numivals2=2*context->numivals-2;
				i=numivals2;
				i_decal=-2;
			}

			/*strand MINUS*/
			if (context->strand==Seq_strand_minus){
				numivals2=context->numivals*2;
				i=0;
				i_decal=2;
			}		
		}
		else{
			if (context->left<0){
				context->left=0;
			}
			/*strand PLUS*/
			if (context->strand==Seq_strand_plus){
				numivals2=context->numivals*2;
				i=0;
				i_decal=2;
			}

			/*strand MINUS*/
			if (context->strand==Seq_strand_minus){
				numivals2=2*context->numivals-2;
				i=numivals2;
				i_decal=-2;
			}		
		}
		
		MemSet(szTrans,'.',(LineSize-1)*sizeof(Char));
		
		while (TRUE){
			/*get the bsp coords for the current ParaG*/
			UDV_ComputeBspCoordRangeinPGP(pgp,&from_bsp,&to_bsp);
			/*the ParaG only contains a gap ?*/
			if (from_bsp==INT4_MAX && to_bsp==INT4_MIN) break;
			/*if ivals.stop > end ParaG -> end of drawing*/
			if (context->ivals[i]>to_bsp) break;
			/*if ivals.stop<= start ParaG : not yet in the current ParaG*/
			if (context->ivals[i+1]<from_bsp) {
				if (context->strand==Seq_strand_plus || 
						context->strand==Seq_strand_unknown){
					i=i+i_decal;
					if (i>numivals2-2 || i<0) break;
					else continue;
				}					
				if (context->strand==Seq_strand_minus){
					i=i+i_decal;
					if (i<0) break;
					else continue;
				}
			}
			/*...only display CDS */
			if(context->featdeftype==FEATDEF_CDS){
				/*compute the limits of the feature within ParaG*/
				start=MAX(context->ivals[i],from_bsp);
				stop=MIN(context->ivals[i+1],to_bsp);
				if (start>stop) continue;
				if (context->strand!=Seq_strand_minus)
					DDV_WWW_get_CDS_plus(context,start,
						stop,from_bsp,pgp->StopLetter-pgp->StartLetter,
						i,szDNA,szTrans,LineSize,strand);
				/*else
					DDV_WWW_get_CDS_minus(context,start,
						stop,from_bsp,i,szDNA,szTrans,LineSize);*/
				bDispTrans=TRUE;
			}/*end if(CDS)*/
			if (context->strand==Seq_strand_plus || 
						context->strand==Seq_strand_unknown){
				i=i+i_decal;
				if (i>numivals2-2 || i<0) break;
			}
			if (context->strand==Seq_strand_minus){
				i=i+i_decal;
				if (i<0) break;
			}
		}/*end while()*/
		if (bDispTrans){
			*szFLine=DDV_ConcatStr(*szFLine,"\n");
			DDV_AddBlank2(disp,szFLine);
			*szFLine=DDV_ConcatStr(*szFLine,szTrans);
			bDispTrans=FALSE;
		}
	}/*end for()*/
}	

/*******************************************************************************

  Function : DDV_ResetParaGSeqAlignCoord()
  
  Purpose : this function reset the SeqAlign coords in the display data, ParaG
  
  Parameters : mpplp;main data block used for the display
  				LineSize; max size of each ParaG. Must be the same value as
				the one passed in DDV_PopDisplay().
  
  Return value : none 

*******************************************************************************/
NLM_EXTERN void DDV_ResetParaGSeqAlignCoord(MsaParaGPopListPtr mpplp,Int2 LineSize)
{
Int4 i,decal;
Int2 OldLineSize;
ValNodePtr vnp;
ParaGPtr pgp;

	for(i=0;i<mpplp->nBsp;i++){
		vnp=mpplp->TableHead[i];
		decal=0;
		while(vnp){
			pgp=(ParaGPtr)(vnp->data.ptrvalue);
			if (pgp){
				/*the last ParaG of a list may be smaller than LineSize*/
				/*So, I get the current ParaG size and reuse it two lines below*/
				OldLineSize=pgp->StopLetter-pgp->StartLetter+1;
				pgp->StartLetter=decal;
				pgp->StopLetter=pgp->StartLetter+_min_(LineSize,OldLineSize)-1;
			}
			decal+=(Int4)LineSize;
			vnp=vnp->next;
		}
	}
}

/*******************************************************************************

  Function : DDV_PopDisplay2()
  
  Purpose : (re)populate ParaGs from the indexed seqalign
  
  Parameters : 	sabp;header of the indexed seqalign
  				mpplp; where ParaGs list are stored
  				nBSP;sabp contains 'nBsp' sequences
				MasterScaleStyle;scale stype for the master sequence
				SlaveScaleStyle;scale stype for the slave sequence
				cbl; number or char/line for a each ParaG
				nBlockToPop; number of blocks to analyse
				ali_from; create ParaG list given a from-to in SEQALIGN COORD
				ali_to;create ParaG list given a from-to in SEQALIGN COORD
				
  Return value : TRUE if success

*******************************************************************************/
NLM_EXTERN Boolean DDV_PopDisplay2(SABlockPtr sabp,MsaParaGPopListPtr mpplp,
			Int4 nBSP,Uint1 MasterScaleStyle,Boolean ShowTick,
			Int2 cbl,Int4 nBlockToPop,Int4 ali_from,Int4 ali_to)
{
SABlockPtr 	sabp2;	/*used to scan "SeqALign" Index blocks*/
SegmentPtr 	segp;	/*used to scan each Bsp segment in a block*/
Int4 		startPgpPos2;/*used to set the from value of each ParaG*/
Int4 		startcopy;/*used to copy the content of a segment in a ParaG*/
Int4 		stopcopy;/*idem*/
Int4 		segsize;/*idem*/
BoolPtr 	bFirst;/*idem*/
Int4 		nCharToCopy;/*idem*/
Int4 		countSegMax=0;/*used to count the number of sequence to display*/
Int4 		countSeg=0;/*idem*/
Int4		countBlock=0;
Int4 		AbsLengthAli=0;/*used to compute the size of the align to display*/
Int4 		i;/*just a little counter*/
ValNodePtr 	vnp,vnp2;/*used to delete additional ParaG nodes, if needed;
				used for REpopulation*/
ParaGPtr pgp1,pgp2;/*used to create new ParaGs*/
MsaTxtDispPtr mtdp;/*used to store the content of a line in a ParaG*/
ValNodePtr PNTR TableDesc=NULL;/*used to populate mpplp->TableHead*/
ValNodePtr PNTR TableText=NULL;/*used to populate ParaG with Text*/
Int4		gFrom,gTo,gDecal_L,gDecal_R;/*used to prepare a display from a range*/

/*
#ifdef DEBUG_DDV
	blk_PrintSABP(sabp);
#endif
*/
	/*some initialisations*/
	if (mpplp->TableHead==NULL){/*First time*/
		mpplp->TableHead=(ValNodePtr PNTR)MemNew(nBSP*sizeof(ValNodePtr));
		if (mpplp->TableHead==NULL) return(FALSE);
		MemSet(mpplp->TableHead,0,nBSP*sizeof(ValNodePtr));
	}
	else{/*reuse the structures*/
		/*same number of BSPs ?*/
		if (nBSP>mpplp->nBsp){/*increase the table*/
			ValNodePtr PNTR tmp;
			tmp=(ValNodePtr PNTR)MemNew(nBSP*sizeof(ValNodePtr));
			if (tmp==NULL) return(FALSE);
			MemSet(tmp,0,nBSP*sizeof(ValNodePtr));
			MemCopy(tmp,mpplp->TableHead,mpplp->nBsp*sizeof(ValNodePtr));
			MemFree(mpplp->TableHead);
			mpplp->TableHead=tmp;
		}
	}
	/*used to populate mpplp->TableHead*/
	TableDesc=(ValNodePtr PNTR)MemNew(nBSP*sizeof(ValNodePtr));
	if (TableDesc==NULL) return(FALSE);
	/*copy the ValNode heads in TableDesc*/
	for(i=0;i<nBSP;i++){
		TableDesc[i]=mpplp->TableHead[i];
	}

	bFirst=(BoolPtr)MemNew(nBSP*sizeof(BoolPtr));
	if (bFirst==NULL) return(FALSE);
	MemSet(bFirst,1,nBSP*sizeof(BoolPtr));

	/*used to populate ParaG with Text*/
	TableText=(ValNodePtr PNTR)MemNew(nBSP*sizeof(ValNodePtr));
	if (TableText==NULL) return(FALSE);
	MemSet(TableText,0,nBSP*sizeof(ValNodePtr));

	/*scan each block of the "SeqALign" Index*/
	for(sabp2=sabp ; sabp2!=NULL ; sabp2=sabp2->next){
		if (!sabp2->visible) continue;/*used only visible block*/
		if(ali_from!=(-1) && ali_to!=(-1)){/*use a range*/
			if (ali_from>sabp2->to) continue;/*not yet in range*/
			gFrom=_max_(ali_from,sabp2->from);
			gTo=_min_(ali_to,sabp2->to);
			gDecal_L=gFrom-sabp2->from;
			gDecal_R=sabp2->to-gTo;
		}
		else{/*display the full alignment*/
			gFrom=sabp2->from;
			gTo=sabp2->to;
			gDecal_L=gDecal_R=0;
		}
		/*used to compute the total align length to display*/
		AbsLengthAli+=(gTo-gFrom+1);
		/*used to compute the total number of bsp to display*/
		countSeg=0;
		countBlock++;
		/*scan each Bsp segment in a block*/
		for(segp=sabp2->segp_head ; segp!=NULL ; segp=segp->next){
			if (!segp->visible){/*hide sequence*/
				/*TableDesc[segp->BspID-1]=NULL;*/
				continue;
			}

			countSeg++;
			/*allocation ?*/
			if (TableDesc[segp->BspID-1]==NULL){
				mpplp->TableHead[segp->BspID-1]=ValNodeNew(NULL);
				TableDesc[segp->BspID-1]=
					mpplp->TableHead[segp->BspID-1];
			}
			/*is this segment a gap ?*/
			if (segp->gap==0) {/*no*/
				if(segp->strand!=Seq_strand_minus){
					startcopy=segp->from+gDecal_L;/*use Bsp coordinates*/
					stopcopy=segp->to+1-gDecal_R;/*use Bsp coordinates*/
				}
				else{
					startcopy=segp->to-gDecal_L;/*use Bsp coordinates*/
					stopcopy=segp->from-1+gDecal_R;/*use Bsp coordinates*/
				}
			}
			else {/*yes*/
				startcopy=gFrom;/*use Align coordinates*/
				stopcopy=gTo+1;/*use Align coordinates*/
			}
			startPgpPos2=gFrom;
			/*retrieve a ParaG*/
			pgp1=(ParaGPtr)TableDesc[segp->BspID-1]->data.ptrvalue;
			/*copy segment data to ParaG*/
			while(((segp->strand!=Seq_strand_minus || segp->gap!=0) ? 
					(startcopy<stopcopy) :
					(startcopy>stopcopy))){
				if (bFirst[segp->BspID-1]){
					bFirst[segp->BspID-1]=FALSE;
					/*is this ParaG already exist*/
					if (pgp1==NULL){/*no: create it*/
						pgp1=(ParaGPtr)MemNew(sizeof(ParaG));
						if (pgp1==NULL) return(FALSE);
						MemSet(pgp1,0,sizeof(ParaG));
						TableDesc[segp->BspID-1]->data.ptrvalue=(Pointer)pgp1;
					}

					/*is the Text fields exist ?*/
					if(pgp1->ptxtList==NULL){
						pgp1->ptxtList=ValNodeNew(NULL);
						if (!pgp1->ptxtList) return(FALSE);
					}
					TableText[segp->BspID-1]=pgp1->ptxtList;

					pgp1->StartLetter=pgp1->StopLetter=startPgpPos2;
					if (segp->BspID-1==0){/*master sequence*/
						pgp1->ScaleStyle=MasterScaleStyle;
						if (MasterScaleStyle&SCALE_POS_LEFT){ 
							pgp1->nLines=1;
						}
						else 
							if (MasterScaleStyle&SCALE_POS_TOP) {
								pgp1->nLines=2;
							}
						else 
							if (MasterScaleStyle&SCALE_POS_BOTH) {
								pgp1->nLines=2;
							}
						else 
							if (MasterScaleStyle&SCALE_POS_NONE) {
								pgp1->nLines=0;
							}
						if (ShowTick) pgp1->nLines++;
					}
					else{
						pgp1->nLines=1;
					}
					pgp1->sip=segp->sip;
				}
				else{
					if (!TableText[segp->BspID-1]->next){
						TableText[segp->BspID-1]->next=
							ValNodeAdd(&(TableText[segp->BspID-1]));
						if (!(TableText[segp->BspID-1]->next)) return(FALSE);
					}
					TableText[segp->BspID-1]=TableText[segp->BspID-1]->next;
				}
				if (segp->strand!=Seq_strand_minus || segp->gap!=0) 
					segsize=stopcopy-startcopy;
				else
					segsize=startcopy-stopcopy;
				
				nCharToCopy=MIN(segsize,cbl-(pgp1->StopLetter-pgp1->StartLetter));
				pgp1->StopLetter+=nCharToCopy;
				/*init a new block of info*/
				mtdp=(MsaTxtDispPtr)TableText[segp->BspID-1]->data.ptrvalue;
				if(!mtdp){
					mtdp=(MsaTxtDispPtr)MemNew(sizeof(MsaTxtDisp));
					if (mtdp==NULL) return(FALSE);
					TableText[segp->BspID-1]->data.ptrvalue=(Pointer)mtdp;
				}
				if (segp->strand!=Seq_strand_minus || segp->gap!=0){
					mtdp->from=startcopy;
					mtdp->to=startcopy+nCharToCopy-1;
				}
				else{
					mtdp->from=startcopy-nCharToCopy+1;
					mtdp->to=startcopy;
				}
				mtdp->SegID=sabp2->SegID;
				mtdp->BspID=segp->BspID;
				mtdp->IsGap=(segp->gap==0 ? FALSE : TRUE);
				mtdp->strand=segp->strand;
				if (mtdp->IsGap) mtdp->TextStyle=MSA_TXT_STYLE_GAP;
				else mtdp->TextStyle=MSA_TXT_STYLE_SEQ;
				
				/*add a next node if needed*/
				/*if (!TableText[segp->BspID-1]->next){
					TableText[segp->BspID-1]->next=
						ValNodeAdd(&(TableText[segp->BspID-1]));
					if (!(TableText[segp->BspID-1]->next)) return(FALSE);
				}
				TableText[segp->BspID-1]=TableText[segp->BspID-1]->next;*/
				pgp2=pgp1;
				vnp=TableDesc[segp->BspID-1];
				/*switch to a next ParaG*/
				if (pgp1->StopLetter-pgp1->StartLetter>=cbl){
					pgp1->StopLetter--;/*swith to zero-based*/
					if (!TableDesc[segp->BspID-1]->next){
						TableDesc[segp->BspID-1]->next=
							ValNodeAdd(&(TableDesc[segp->BspID-1]));
						if (!(TableDesc[segp->BspID-1]->next)) return(FALSE);
					}
					TableDesc[segp->BspID-1]=
						TableDesc[segp->BspID-1]->next;
					vnp2=TableDesc[segp->BspID-1];
					/*retrieve a ParaG*/
					pgp1=(ParaGPtr)TableDesc[segp->BspID-1]->data.ptrvalue;
					bFirst[segp->BspID-1]=TRUE;
					startPgpPos2+=nCharToCopy;
					/*delete additional ParaG->ptxtList if needed*/
					if (TableText[segp->BspID-1]->next){
						DDV_DeleteTxtList(&(TableText[segp->BspID-1]->next));
					}
				}
				else{
					vnp2=TableDesc[segp->BspID-1]->next;
				}
				/*used to compute the total number of bsp to display*/
				if (segp->strand!=Seq_strand_minus || segp->gap!=0)
					startcopy+=nCharToCopy;
				else
					startcopy-=nCharToCopy;
			}/*end while(segment)*/
			/*just in case: switch ParaG-> to zero based*/
			if (countBlock==nBlockToPop){
				if (pgp2 && ((pgp2->StopLetter-pgp2->StartLetter+1)>=AbsLengthAli)) {
					pgp2->StopLetter=pgp2->StartLetter+AbsLengthAli-1;
				}
				/*erase additional ParaG if needed*/
				if (vnp2){
					DDV_DeleteParaGList(&vnp2);
				}
				vnp->next=NULL;
				if (TableText[segp->BspID-1]->next){
					DDV_DeleteTxtList(&TableText[segp->BspID-1]->next);
				}
			}
		}/*end for (segment)*/
		if (countSeg>countSegMax) countSegMax=countSeg;
		if (ali_from!=(-1) && ali_to!=(-1)){/*out of range ?*/
			if (ali_to<=sabp2->to) break;
		}
	}/*end for(block)*/

	/*hack : sometimes a NULL node is added at the end: remove it*/
	for(i=0;i<nBSP;i++){
		vnp=mpplp->TableHead[i];
		while(vnp){
			vnp2=vnp->next;
			if (vnp2 && vnp2->data.ptrvalue==NULL){
				ValNodeFree(vnp2);
				vnp->next=NULL;
			}
			vnp=vnp->next;
		}
	}
	
	/*size of the align to display*/
	mpplp->LengthAli=AbsLengthAli;
	mpplp->nBsp=countSeg;
	MemFree(bFirst);	
	MemFree(TableDesc);
	MemFree(TableText);
	return(TRUE);
}
	/*small version of DDV_PopDisplay2*/
NLM_EXTERN Boolean DDV_PopDisplay(SABlockPtr sabp,MsaParaGPopListPtr mpplp,
			Int4 nBSP,Uint1 MasterScaleStyle,Boolean ShowTick,
			Int2 cbl,Int4 nBlockToPop)
{
	return(DDV_PopDisplay2(sabp, mpplp,nBSP, MasterScaleStyle, ShowTick,
			 cbl, nBlockToPop,-1,-1));
}

/*******************************************************************************

  Function : GetClrFromClrGlobal()
  
  Purpose : get the color of a letter using ColorManager
  				
  Return value : - (see szColor)

*******************************************************************************/
static void GetClrFromClrGlobal(DDV_ColorGlobal * gclr,Int4 bsp_coord,
	SeqIdPtr sip, CharPtr szColor,Int4 row, Uint1Ptr style)
{
DDV_ColorCell * dclrp;
Uint4 i,idx;
Uint1 rgb1[4],rgb2[4];	
Boolean bFound;

	dclrp=DDV_GetColor(gclr,NULL, row, bsp_coord);
	bFound=FALSE;
	(*style)=0;
	
	if (dclrp){
		rgb1[0]=dclrp->rgb[0];
		rgb1[1]=dclrp->rgb[1];
		rgb1[2]=dclrp->rgb[2];
		rgb1[3]=0;
		for(i=0;i<DDV_COLOR_MAX;i++){
			rgb2[0]=DDV_PaletteRGB[i][0];
			rgb2[1]=DDV_PaletteRGB[i][1];
			rgb2[2]=DDV_PaletteRGB[i][2];
			rgb2[3]=0;
			if (*((Uint4Ptr)rgb1 )== *((Uint4Ptr)rgb2)){
				idx=i;
				bFound=TRUE;
				break;
			}
		}
		if (dclrp->UseItalic)
			(*style)|=DDV_TXTSTYLE_ITALIC;
		if (dclrp->UseBold)
			(*style)|=DDV_TXTSTYLE_BOLD;
		if (dclrp->UseUnderline)
			(*style)|=DDV_TXTSTYLE_UNDERLINE;
	}
	
	if (!bFound){
		idx=DDVCOL_BLACK;
	}
	StringCpy(szColor,DDV_PaletteRGB_NAV[idx]);
}

/*******************************************************************************

  Function : GetClrFromLetter()
  
  Purpose : get the colour of a letter (na or aa)
  
  Parameters : 	residue; the letter
  				IsAA; True when prot
				szColor; HTML encoded color
				
  Return value : - (see szColor)

*******************************************************************************/
static void GetClrFromLetter(Char residue,Boolean IsAA,CharPtr szColor)
{

	/*AA colour code system*/
	if(IsAA){/*not yet implemented*/
		StringCpy(szColor,DDV_PaletteRGB_NAV[DDVCOL_BLACK]);
	}
	else{/*NA colour code*/
		switch(residue){
			case '-':
				StringCpy(szColor,DDV_PaletteRGB_NAV[DDVCOL_PINK]);
				break;
			case '.':
				StringCpy(szColor,DDV_PaletteRGB_NAV[DDVCOL_BACKGROUND]);
				break;
			case 'A':case 'a':
				StringCpy(szColor,DDV_PaletteRGB_NAV[DDVCOL_GREEN]);
				break;
			case 'G':case 'g':
				StringCpy(szColor,DDV_PaletteRGB_NAV[DDVCOL_BLACK]);
				break;
			case 'C':case 'c':
				StringCpy(szColor,DDV_PaletteRGB_NAV[DDVCOL_BLUE]);
				break;
			case 'T':case 't':
				StringCpy(szColor,DDV_PaletteRGB_NAV[DDVCOL_RED]);
				break;
			case 'N': case 'n':
				StringCpy(szColor,DDV_PaletteRGB_NAV[DDVCOL_HOTPINK]);
				break;
			default:
				StringCpy(szColor,DDV_PaletteRGB_NAV[DDVCOL_BLACK]);
				break;
		}		
	}
}


#define DDV_DumpStyles(_newStyle,_newColor,_boldOpen,_italicOpen,_underlineOpen,_colorOpen,_szSequence,_szBuf)\
{\
	if (_newStyle&DDV_TXTSTYLE_BOLD){\
		_szSequence=DDV_ConcatStr(_szSequence,"<B>");\
		_boldOpen=TRUE;\
	}\
	if (_newStyle&DDV_TXTSTYLE_ITALIC){\
		_szSequence=DDV_ConcatStr(_szSequence,"<I>");\
		_italicOpen=TRUE;\
	}\
	if (_newStyle&DDV_TXTSTYLE_UNDERLINE){\
		_szSequence=DDV_ConcatStr(_szSequence,"<U>");\
		_underlineOpen=TRUE;\
	}\
	_szSequence=DDV_ConcatStr(_szSequence,"<FONT COLOR=#");\
	_colorOpen=TRUE;\
	_szSequence=DDV_ConcatStr(_szSequence,_newColor);\
	_szSequence=DDV_ConcatStr(_szSequence,">");\
	_szSequence=DDV_ConcatStr(_szSequence,_szBuf);\
	if (_colorOpen){\
		_szSequence=DDV_ConcatStr(_szSequence,"</FONT>");\
		_colorOpen=FALSE;\
	}\
	if (_underlineOpen){\
		_szSequence=DDV_ConcatStr(_szSequence,"</U>");\
		_underlineOpen=FALSE;\
	}\
	if (_italicOpen){\
		_szSequence=DDV_ConcatStr(_szSequence,"</I>");\
		_italicOpen=FALSE;\
	}\
	if (_boldOpen){\
		_szSequence=DDV_ConcatStr(_szSequence,"</B>");\
		_boldOpen=FALSE;\
	}\
}
/*******************************************************************************

  Function : DDV_Print_Sequence()
  
  Purpose : display a sequence
  
  Parameters : 	szSeq; the sequence to display
  				bUseColour; print out a coloured sequence
  				IsAA; True is szSeq is a prot
				fp;file to put in the sequence

  Note: this function can be used to display both Ticks and Numbers for
        the top scale. See the 'what' parameter
				
  Return value : -

*******************************************************************************/
static CharPtr  DDV_Print_Sequence(CharPtr szSeq,Boolean bUseColour,Boolean IsAA,
		ParaGPtr pgp, DDV_ColorGlobal * gclr,Int4 row)
{
CharPtr szBuf,szTmp,szSequence=NULL;
Int4    pos,taille,stop,bsp_coord;
Char    residue;					
Uint2   nCompt=0,nCompt2=0;
Char    curColor[10],newColor[10]={""};
Uint1   curStyle,newStyle;
Boolean boldOpen,italicOpen,underlineOpen,colorOpen;
	
	/*alloc a buffer*/
	taille=StringLen(szSeq)+1;
	szBuf=(CharPtr)MemNew(taille*sizeof(Char));
	if (!szBuf) {
		szSequence=StringSave(szSeq);
		return(szSequence);
	}
	MemSet(szBuf,0,taille*sizeof(Char));
	
	/*prepare the colour display*/
	pos=1;	
	stop=taille+1;
	newStyle=curStyle=0;
	boldOpen=italicOpen=underlineOpen=colorOpen=FALSE;
	/*draw!*/
	if (!bUseColour){/*black-colour display*/
		szTmp=StringChr(szSeq,'\0');
		if (szTmp && *(szTmp-1)==' ') *(szTmp-1)='\0';
		szSequence=StringSave(szSeq);
	}
	else{ /*use colour-coded alphabet fo NA & AA*/
		while(pos<stop){
			residue=szSeq[nCompt];
			/*retrieve "standard" colors if Color Manger is not used*/
			if (gclr==NULL){
				GetClrFromLetter(residue,IsAA,curColor);
			}
			else{/*use Color Manager to get the colors*/
				bsp_coord=DDV_GetBspCoordGivenDispCoord(pgp,pgp->StartLetter+nCompt);
				if (bsp_coord!=(Int4)-1)/*bsp letter*/
					GetClrFromClrGlobal(gclr,bsp_coord,pgp->sip,curColor,row,&curStyle);
				else/*gap*/{
					StringCpy(curColor,DDV_PaletteRGB_NAV[DDVCOL_BLACK]);
					curStyle=0;
				}
					
			}
			/*new colour? or new style?*/
			if (StringCmp(curColor,newColor) || curStyle!=newStyle){
				if (szBuf[0]!='\0'){/*something to draw ?*/
					szBuf[nCompt2]='\0';/*CLOSE THE STRING*/
					DDV_DumpStyles(newStyle,newColor,boldOpen,italicOpen,
						underlineOpen,colorOpen,szSequence,szBuf);
				}
				StringCpy(newColor,curColor);
				newStyle=curStyle;
				nCompt2=0;
				szBuf[nCompt2]='\0';
			}
			szBuf[nCompt2++]=residue;
			
			/*each LETTER_BLOCK_WIDTH, add a empty column*/
			pos++;nCompt++;		
		}
		if (szBuf[0]!='\0'){/*something to draw ?*/
			szBuf[nCompt2-1]='\0';/*CLOSE THE STRING*/
			DDV_DumpStyles(newStyle,newColor,boldOpen,italicOpen,
				underlineOpen,colorOpen,szSequence,szBuf);
		}
	}
	MemFree(szBuf);
	return(szSequence);
}

/*******************************************************************************

  Function : DDV_DisplayTopScale()
  
  Purpose : display a Top scale above the first sequence of the alignment
  
  Parameters : 	from; from 
  				to;  to ... I have no other explanation !
  				offset;used to locate correctly the ruler
				disp_format; display format options
				what;tick or number

  Note: this function can be used to display both Ticks and Numbers for
        the top scale. See the 'what' parameter
				
  Return value : -

*******************************************************************************/
static CharPtr DDV_DisplayTopScale(Int4 from,Int4 to,Int4 offset,Uint4 disp_format,
	Uint1 what)
{
CharPtr	szText,szScale=NULL;
Int4 	pos,i,stop,size,j,k;
Char 	szPos[15]={""};	
Char 	szBlank[TABLE_LEFT_MARGIN+5]={""};	

	size=to-from+1;
	pos=from+1;
	stop=to+2;
	i=0;
	if (disp_format&DISPE_SHOWBLOCK) size+=(size/LETTER_BLOCK_WIDTH);
	szText=(CharPtr)MemNew((size+1)*sizeof(Char));
	if (szText){
		MemSet(szText,' ',size*sizeof(Char));
		while(pos<stop){
			if (!(pos % LETTER_BLOCK_WIDTH)){
				switch(what){
					case SCALE_TICK:
						szText[i]='|';
						break;
					case SCALE_NUM:
						sprintf(szPos,"%i",pos);
						j=StringLen(szPos);
						for(k=0;k<j;k++){
							szText[i-j+k+1]=szPos[k];
						}
						break;
				}
				if (disp_format&DISPE_SHOWBLOCK) i++;
			}
			if (!(pos % LETTER_HALF_BLOCK_WIDTH) && 
				(pos % LETTER_BLOCK_WIDTH) && (what==SCALE_TICK)){
				szText[i]='.';
			}
			pos++;i++;
		}
		if (what==SCALE_NUM) 
			szScale=DDV_ConcatStr(szScale,"\n");
		if(disp_format&DISP_FULL_HTML){
			szScale=DDV_ConcatStr(szScale,"<font color=#700777>");
			DDV_AddBlank2(offset,&szScale);
			szScale=DDV_ConcatStr(szScale,szText);
			szScale=DDV_ConcatStr(szScale,"</font>\n");
		}else if(disp_format&DISP_FULL_TXT){
			DDV_AddBlank2(offset,&szScale);
			szScale=DDV_ConcatStr(szScale,szText);
			szScale=DDV_ConcatStr(szScale,"\n");
		}
		MemFree(szText);
	}
	return(szScale);
}

/*******************************************************************************

  Function : DDV_GetSequenceFromParaG()
  
  Purpose : retrieve a sequence from a ParaG 
  
  Parameters : pgp ; a ParaG
				szSequence; filled here
				bspLength; size of the sequence
				IsAA; true if the sequence is a protein
  				bsp_strand; strand of the ParaG
				bsp_start; from
				bsp_stop; to of the Parag (bsp coord)

  Note : bsp_strand,bsp_start,bsp_stop ; pointers can be NULL if you don't want
  		to retrieve that information.

  Return value : TRUE if success; see also bsp_strand,bsp_start,bsp_stop

*******************************************************************************/
NLM_EXTERN Boolean DDV_GetSequenceFromParaG(ParaGPtr pgp,
	CharPtr PNTR szSequence,Int4 bspLength,Boolean IsAA,Uint1 PNTR bsp_strand,
	Int4 PNTR bsp_start,Int4 PNTR bsp_stop)
{
Int4          size,from,to,ret,seek;
CharPtr       SeqBuf;
ValNodePtr    vnp2;
MsaTxtDispPtr mtdp;
SeqLocPtr     slp=NULL;
SeqPortPtr    spp=NULL;
Boolean       bOk=FALSE;
SeqIdPtr      sip;
Uint1		  strand=Seq_strand_unknown;

	if (!szSequence || !pgp) 
		return(FALSE);

	/*analyse the sequence description; get the first block
	which describes a Bioseq, not a gap; then retrieves the from*/
	from=INT4_MAX;
	to=INT4_MIN;
	for(vnp2=pgp->ptxtList;vnp2!=NULL;vnp2=vnp2->next){
		mtdp=(MsaTxtDispPtr)(vnp2->data.ptrvalue);
		if (mtdp){
			if (mtdp->IsGap==0) {
				strand=mtdp->strand;
				from=MIN(from,mtdp->from);
				to=MAX(to,mtdp->to);
				if (!bOk) bOk=TRUE;
				/*break;*/
			}
		}
	}

	
	/*if bOk==FALSE, we have only a big gap to display*/
	if (bOk){
		/*open a seqport on the ParaG*/
		sip=SeqIdFindBest(pgp->sip,SEQID_GI);
		if (sip==NULL) sip=pgp->sip;
		slp=SeqLocIntNew(from,to,strand, sip);
		if (!slp) return(FALSE);
		spp = SeqPortNewByLoc (slp, (Uint1)(IsAA==TRUE ? Seq_code_iupacaa 
				: Seq_code_iupacna));
		if (!spp) return(FALSE);
	}

	/*build the text to display for the ParaG: AATAT---ATAT--AAA*/
	for(vnp2=pgp->ptxtList;vnp2!=NULL;vnp2=vnp2->next){
		mtdp=(MsaTxtDispPtr)vnp2->data.ptrvalue;
		if (mtdp){
			Char c;
			size=mtdp->to-mtdp->from+1;
			SeqBuf=(CharPtr)MemNew((size+1)*sizeof(Char));
			if (!SeqBuf) continue;
			if(mtdp->IsGap){
				switch(mtdp->TextStyle){
					case MSA_TXT_STYLE_1:
						c=' ';
						break;
					case MSA_TXT_STYLE_UAGAP:
						c='~';
						break;
					case MSA_TXT_STYLE_GAP:
					case MSA_TXT_STYLE_2:
                                        default:
						c='-';
						break;
				}
				MemSet(SeqBuf,c,size*sizeof(Char));
				SeqBuf[size]='\0';
			}
			else{
				if (strand == Seq_strand_minus)
					seek = to-mtdp->to;
				else
					seek = mtdp->from-from;
				SeqPortSeek(spp, seek, SEEK_SET);
				ret=SeqPortRead (spp,(Uint1Ptr)SeqBuf, (Int2)size);
				if (ret!=size){
					MemSet(SeqBuf,'?',size*sizeof(Char));
					SeqBuf[size]='\0';
				}
			}
			StringCat(*szSequence,SeqBuf);
			MemFree(SeqBuf);
			SeqBuf=NULL;
			
		}
	}

	if (spp) SeqPortFree (spp);
	if (slp) SeqLocFree (slp);

	if (bsp_strand) *bsp_strand=strand;
	if (bsp_start) *bsp_start=from;
	if (bsp_stop) *bsp_stop=to;

	return(TRUE);
}


NLM_EXTERN Int4 DDV_GetBspCoordGivenDispCoord(ParaGPtr pgp, Int4 disp_pos) {
/*****************************************************************************
*  same as DDV_GetBspCoordGivenDispCoord2, except alignment status is ignored
*****************************************************************************/
  Boolean  UnAligned;
  return(DDV_GetBspCoordGivenDispCoord2(pgp, disp_pos, &UnAligned));
}


/*****************************************************************************

Function: DDV_GetBspCoordGivenDispCoord2()

Purpose: compute a BSP coord given a display coord and a ParaG 

Return values: BSP coord
               Alignment status of this coord in pUnAligned

*****************************************************************************/
NLM_EXTERN Int4 DDV_GetBspCoordGivenDispCoord2(ParaGPtr pgp, Int4 disp_pos, Boolean* pUnAligned)
{
MsaTxtDispPtr  mtdp;
ValNodePtr     vnp;
Int4           pgp_start,diff,bsp_coord;

	bsp_coord=(Int4)-1;
    if (!pgp)
      return bsp_coord;
	pgp_start=pgp->StartLetter;
	vnp=pgp->ptxtList;
	while(vnp){
		mtdp=(MsaTxtDispPtr)vnp->data.ptrvalue;
		diff=mtdp->to-mtdp->from;
		if (disp_pos>=pgp_start && disp_pos<=(pgp_start+diff)){
			if (mtdp->TextStyle == MSA_TXT_STYLE_SEQ){
				bsp_coord=mtdp->from+(disp_pos-pgp_start);
				if(mtdp->strand==Seq_strand_minus){
					bsp_coord=mtdp->to-(bsp_coord-mtdp->from);
				}
        *pUnAligned = mtdp->IsUnAligned;
			}
			else{
				bsp_coord=(Int4)-1;
			}
			break;
		}
		pgp_start+=diff+1;
		vnp=vnp->next;
	}

	return(bsp_coord);
}


/*****************************************************************************

Function: DDV_GetBspCoordGivenPgpList()

Purpose: get a bsp_coord given a list of ParaG (for example a row in a SeqAlign)
         and a display coordinates.
		 
Return value: bsp coord

*****************************************************************************/
NLM_EXTERN Int4 DDV_GetBspCoordGivenPgpList(ValNodePtr ParaG_List,Int4 disp_pos)
{
ValNodePtr vnp;
ParaGPtr   pgp,TheParaG;
Boolean    bFound;
Int4       bsp_coord;

	bFound=FALSE;
	vnp=ParaG_List;
	bsp_coord=(Int4)-1;
	while(vnp){
		pgp=(ParaGPtr)vnp->data.ptrvalue;
		if (disp_pos>=pgp->StartLetter && disp_pos<=pgp->StopLetter){
			bFound=TRUE;
			TheParaG=pgp;
			break;
		}
		vnp=vnp->next;
	}
	if (bFound){
		bsp_coord=DDV_GetBspCoordGivenDispCoord(TheParaG,disp_pos);
	}
	return(bsp_coord);
}


/*****************************************************************************

Function: DDV_GetDispCoordGivenBspCoord()

Purpose: compute a display coord given a Bioseq coord and the ParaG list of
    a row (SeqAlign)

Return value: disp coord

*****************************************************************************/
NLM_EXTERN Int4 DDV_GetDispCoordGivenBspCoord(ValNodePtr vnp_head,Int4 bsp_pos)
{
MsaTxtDispPtr  mtdp;
ValNodePtr     vnp,vnp2;
ParaGPtr       pgp;
Int4           pgp_start,diff,disp_coord,bsp_start_pgp,bsp_stop_pgp;

	disp_coord=(Int4)-1;
	vnp2=vnp_head;
	while(vnp2){
		pgp=(ParaGPtr)vnp2->data.ptrvalue;
		UDV_ComputeBspCoordRangeinPGP(pgp,&bsp_start_pgp,&bsp_stop_pgp);
		if(bsp_start_pgp<=bsp_pos && bsp_pos<=bsp_stop_pgp){
			pgp_start=pgp->StartLetter;
			vnp=pgp->ptxtList;
			while(vnp){
				mtdp=(MsaTxtDispPtr)vnp->data.ptrvalue;
				diff=mtdp->to-mtdp->from;
				if (mtdp->TextStyle == MSA_TXT_STYLE_SEQ &&
				    (mtdp->from<=bsp_pos && bsp_pos<=mtdp->to)){
					if(mtdp->strand==Seq_strand_minus){
						disp_coord=pgp_start+(mtdp->to-bsp_pos);
					}
					else{
						disp_coord=pgp_start+(bsp_pos-mtdp->from);
					}
				}
				
				pgp_start+=diff+1;
				vnp=vnp->next;
			}
		}
		vnp2=vnp2->next;
	}
	return(disp_coord);
}


NLM_EXTERN Int4 DDV_GetFirstDispCoordGivenBspCoordRange(ValNodePtr vnp_head,
                                                        Int4 disp_start, Int4 disp_stop) {
/*----------------------------------------------------------------------------
*  get first valid display coord in the bioseq range
*---------------------------------------------------------------------------*/
  Int4  i, start, stop;
  Int4  RetVal;

  if ((disp_start < 0) || (disp_stop < 0)) return(-1);

  start = MIN(disp_start, disp_stop);
  stop = MAX(disp_start, disp_stop);

  for (i=start; i<=stop; i++) {
    RetVal = DDV_GetDispCoordGivenBspCoord(vnp_head, i);
    if (RetVal >= 0) {
      return(RetVal);
    }
  }
  return(-1);
}


NLM_EXTERN Int4 DDV_GetLastDispCoordGivenBspCoordRange(ValNodePtr vnp_head,
                                                       Int4 disp_start, Int4 disp_stop) {
/*----------------------------------------------------------------------------
*  get last valid display coord in the bioseq range
*---------------------------------------------------------------------------*/
  Int4  i, start, stop;
  Int4  RetVal;

  if ((disp_start < 0) || (disp_stop < 0)) return(-1);

  start = MIN(disp_start, disp_stop);
  stop = MAX(disp_start, disp_stop);

  for (i=stop; i>=start; i--) {
    RetVal = DDV_GetDispCoordGivenBspCoord(vnp_head, i);
    if (RetVal >= 0) {
      return(RetVal);
    }
  }
  return(-1);
}


/*******************************************************************************

  Function : DDV_GetFormattedSequence_1()
  
  Purpose : format a sequence given upper/lower case status for each letter
  
  Parameters : 	pgp; the paragraph containing the sequence szSeq.
                szSeq; the sequence
				gclr; contains the letters' layout data
				
  
*******************************************************************************/
static void DDV_GetFormattedSequence_1(ParaGPtr pgp,CharPtr szSeq,
		DDV_ColorGlobal * gclr,Int4 row)
{
DDV_ColorCell * dclrp;
Int4            i,dp;
Boolean         isAlpha;
		
	i=0;

	while(szSeq[i]){
		if (szSeq[i]!=' '){
			if (isalpha(szSeq[i])){
				isAlpha=TRUE;
				dp=DDV_GetBspCoordGivenDispCoord(pgp,pgp->StartLetter+i);
				if (dp==(Int4)-1)
					dclrp=NULL;
				else
					dclrp=DDV_GetColor(gclr,NULL, row, dp);
			}
			else {
				isAlpha=FALSE;
			}

			if (isAlpha && dclrp)
				szSeq[i]=(dclrp->LowerCase ? TO_LOWER(szSeq[i]) : szSeq[i]);
		}
		i++;
	}
}

/*******************************************************************************

  Function : DDV_GetBLASTCompLine_1()
  
  Purpose : get the middle line of a BLAST pairwise seqAlign
  
*******************************************************************************/
NLM_EXTERN CharPtr DDV_GetBLASTCompLine_1(CharPtr szQuery, 
                                          CharPtr szSubject, 
                                          Int4Ptr PNTR matrix, 
                                          Boolean is_aa)
{
    Int4    stop,pos;
    CharPtr szMiddleLine;
    Char    q,s;
    
    stop=StringLen(szSubject);

    if((szMiddleLine=(CharPtr)MemNew((stop+1)*sizeof(Char))) == NULL)
        return NULL;
    
    pos=0;
    while(pos < stop) {

        /* For protein alignments - unaligned regions should not anything
           in the middle line. We show unaligned regions in lower case */

        if(is_aa && IS_LOWER(szQuery[pos]) && IS_LOWER(szSubject[pos])) {
            szMiddleLine[pos]=' ';
            pos++;
            continue;
        }
        q = TO_UPPER(szQuery[pos]);
        s = TO_UPPER(szSubject[pos]);
        if (matrix) {
            if(IS_ALPHA(q) && IS_ALPHA(s)){
                if(q==s) { 
                    szMiddleLine[pos]=szQuery[pos];
                } else {
                    if (matrix[s][q]>0){
                        szMiddleLine[pos]='+';
                    } else {
                        szMiddleLine[pos]=' ';
                    }
                }
            } else {
                szMiddleLine[pos]=' ';
            }
            
        } else {
            if(q == s)
                szMiddleLine[pos]='|';
            else
                szMiddleLine[pos]=' ';
        }
        pos++;
    }
    return(szMiddleLine);
}

/*******************************************************************************

  Function : DDV_GetBLASTCompLine_2()
  
  Purpose : get the middle line of a BLAST pairwise seqAlign
  
*******************************************************************************/
NLM_EXTERN CharPtr DDV_GetBLASTCompLine_2(ParaGPtr pgpQuery, ParaGPtr pgpSubject, 
		Int4Ptr PNTR matrix)
{
CharPtr   szQuery,szSubject,szComp;
BioseqPtr bsp;
Boolean   IsAA;
Int4      bspLength;

	szComp=szQuery=szSubject=NULL;
	/*get the query sequence*/
	szQuery=(CharPtr)MemNew((pgpQuery->StopLetter-pgpQuery->StartLetter+3)*sizeof(Char));
	if (!szQuery) return(NULL);
	bsp=BioseqLockById(pgpQuery->sip);
	if (!bsp) goto error;
	bspLength=BioseqGetLen(bsp);
	IsAA=ISA_aa(bsp->mol);
	BioseqUnlock(bsp);
	if (!DDV_GetSequenceFromParaG(pgpQuery,&szQuery,bspLength,IsAA,NULL,
			NULL,NULL)) goto error;
	/*get the subject sequence*/
	szSubject=(CharPtr)MemNew((pgpSubject->StopLetter-pgpSubject->StartLetter+3)*sizeof(Char));
	if (!szSubject) goto error;
	bsp=BioseqLockById(pgpSubject->sip);
	if (!bsp) goto error;
	bspLength=BioseqGetLen(bsp);
	IsAA=ISA_aa(bsp->mol);
	BioseqUnlock(bsp);
	if (!DDV_GetSequenceFromParaG(pgpSubject,&szSubject,bspLength,IsAA,NULL,
			NULL,NULL)) goto error;

	szComp=DDV_GetBLASTCompLine_1(szQuery,szSubject,matrix, IsAA);
error:
	if (szQuery) MemFree(szQuery);
	if (szSubject) MemFree(szSubject);
	return(szComp);
}

/*******************************************************************************

  Function : DDV_GetBLASTCompLine_3()
  
  Purpose : get the middle line of a BLAST pairwise seqAlign
  
*******************************************************************************/
NLM_EXTERN CharPtr DDV_GetBLASTCompLine_3(CharPtr szQuery, ParaGPtr pgpSubject, 
		Int4Ptr PNTR matrix)
{
CharPtr   szSubject,szComp;
BioseqPtr bsp;
Boolean   IsAA;
Int4      bspLength;

	szComp=szSubject=NULL;
	/*get the subject sequence*/
	szSubject=(CharPtr)MemNew((pgpSubject->StopLetter-pgpSubject->StartLetter+3)*sizeof(Char));
	if (!szSubject) goto error;
	bsp=BioseqLockById(pgpSubject->sip);
	if (!bsp) goto error;
	bspLength=BioseqGetLen(bsp);
	IsAA=ISA_aa(bsp->mol);
	BioseqUnlock(bsp);
	if (!DDV_GetSequenceFromParaG(pgpSubject,&szSubject,bspLength,IsAA,NULL,
			NULL,NULL)) goto error;
			
	szComp=DDV_GetBLASTCompLine_1(szQuery,szSubject,matrix, IsAA);
error:
	if (szSubject) MemFree(szSubject);
	return(szComp);
}

/*******************************************************************************

  Function : DDV_HideMaskedLetters()
  
  Purpose : replace sequence letters with 'X' in masked regions (BLAST)
  
*******************************************************************************/
static void DDV_HideMaskedLetters(CharPtr szSeqMaster,ParaGPtr pgp,ValNodePtr mask)
{
ValNodePtr      vnp;
SeqLocPtr       slp;
Int4            i,bsp_start,bsp_stop,mask_start,mask_stop,scan_from,
                scan_to,max,real_pos;
ValNode         vn;

	if (!szSeqMaster || !pgp || !mask) return;
	
	memset(&vn,0,sizeof(ValNode));
	vn.data.ptrvalue=(Pointer)pgp;

	/*get query sequence range*/
	UDV_ComputeBspCoordRangeinPGP(pgp,&bsp_start,&bsp_stop);
	max=StringLen(szSeqMaster);
	
	/*scan the mask list*/
    vnp=mask;
	while(vnp) {
        slp=(SeqLocPtr)vnp->data.ptrvalue;
        
        if(slp == NULL) 
            return;
        
        if(slp->choice == SEQLOC_PACKED_INT)
            slp = slp->data.ptrvalue;
        else if (slp->choice != SEQLOC_INT)
            return;
        
        while(slp) {

            if(slp->choice != SEQLOC_INT) {
                slp = slp->next;
                continue;
            }
            
            mask_start=SeqLocStart(slp);
            mask_stop=SeqLocStop(slp);
            
			/*check if the masked region is in the bsp range*/
			if (mask_stop>=bsp_start && mask_start<=bsp_stop){
				scan_from=_max_(mask_start,bsp_start);
				scan_to=_min_(mask_stop,bsp_stop)+1;
				for(i=scan_from;i<scan_to;i++){
					real_pos=DDV_GetDispCoordGivenBspCoord(&vn,i)-pgp->StartLetter;
					if (real_pos>=0 && real_pos<max){
						szSeqMaster[real_pos]='X';
					}
				}
			}
			slp = slp->next;
		}
		vnp=vnp->next;
	}
}

/*******************************************************************************

  Function : DDV_DisplayParaG()
  
  Purpose : display the content of a ParaG
  
  Parameters : 	vnp; the node containing the ParaG
  				i; sequence number (from 1 to nSequence)
  				ShowScale;if true, show the top scale
				disp_format; display format options
				szSeqAcc; Accession number of the sequence
				szSeqName; sequence name
				IsAA; TRUE means protein
				bDispPhilouName;used for PHYLIP format
				szFormattedLine; see 'Return value'
				szSeqMaster; sequence of a master (used to display variations)
				matrix; matrix used for BLAST output
				gclr; enhanced display options (colors, upper/lower case,...)
				
  Return value : the next node in the ParaG ValNode List of a sequence;
                fill szFormattedLine with the info ready to display

*******************************************************************************/
static ValNodePtr DDV_DisplayParaG
(ValNodePtr vnp,Int4 i,Boolean ShowScale, Uint4 disp_format,
 CharPtr szSeqAcc,CharPtr szSeqName,Boolean IsAA, Boolean bDispPhilouName,
 Int4 max_length,Int4 max_scale,Int2 LineSize, CharPtr PNTR szFormattedLine,
 CharPtr PNTR szSeqMaster, Int4Ptr PNTR matrix, DDV_ColorGlobal * gclr,
 ValNodePtr mask
 ) {
    ParaGPtr  pgp;	/*ParaG data*/
    CharPtr   szSequence,szDisp,szFLine=NULL,szTmp,szMiddleLine, idstring;
    BioseqPtr bsp;
    SeqIdPtr  sip;
    Int4      bspLength,size,stop,nCompt2,pos,gi,diff,disp;
    Int4      bsp_start,bsp_stop, n, j;
    Char      szBuf4[WWW_SCRIPT_SIZE]={""};   /*Entrez query*/
    Uint1     bsp_strand;
    Char      tmpstr[99];
	
    if (vnp==NULL) 
        return NULL;
    
    pgp=(ParaGPtr)vnp->data.ptrvalue;
    if (!pgp) 
        return(vnp->next);
    
    szSequence=(CharPtr)MemNew((pgp->StopLetter-pgp->StartLetter+3)*sizeof(Char));
    
    if (!szSequence) 
        return NULL;

    /*get some bsp info*/	
    sip=SeqIdFindBest(pgp->sip,0);
    if (sip==NULL) sip=pgp->sip;

    if((bsp=BioseqLockById(sip)) == NULL)
        goto error;

    bspLength=BioseqGetLen(bsp);
    
    if (!DDV_GetSequenceFromParaG(pgp,&szSequence,bspLength,IsAA,&bsp_strand,
                                  &bsp_start,&bsp_stop)) 
        goto error;
    
    if (gclr) {/*format the output; 
                 only upper/lower case letters are lait out in this function*/
        DDV_GetFormattedSequence_1(pgp,szSequence,gclr,i);
    } else if (disp_format&TEXT_LOWERCASE || ISA_na(bsp->mol)){
	/*switch to lower case if needed; this is for the PopSet viewer: it displays
          DNA sequences using ALWAYS lower case letters. We don't need a complex gclr
          data structure here (this takes time to create...)*/
        szSequence=ConvertToLower(szSequence);
    }
    /*right now, I consider the first sequence of the SeqAlign is the master*/
    if (i==1){
        *szSeqMaster=StringSave(szSequence);
    }
    
    /*if (i==1 && mask){
      DDV_HideMaskedLetters(szSequence,pgp,mask);
      }*/
    
    /*7 : StringLen("unknown"); see below, when I print szSeqAcc*/
    if (max_length<7) max_length=7;
    disp=0;
    
    if(disp_format&DISP_FULL_HTML || disp_format&DISP_FULL_TXT){/*output format: html*/
        /*compute the left part size of the line to display*/
        if (disp_format&DISP_ORDER_NUM) {disp+=7;max_length+=7;}
        if (*szSeqAcc) disp+=StringLen(szSeqAcc);
        else disp+=7;
        diff=max_length-disp;
        diff++;
        disp+=diff;
        if (disp_format&DISP_STRAND) disp+=2;
        if (disp_format&DISP_BSP_COORD)disp+=max_scale+2;
        /*display top scale if needed*/
        if ((disp_format&RULER_TOP) && ShowScale) {
            szTmp=DDV_DisplayTopScale(pgp->StartLetter,
                                      pgp->StopLetter,disp,disp_format,SCALE_NUM);
            if (szTmp){
                szFLine=DDV_ConcatStr(szFLine,szTmp);
                MemFree(szTmp);
            }
        }
        if ((disp_format&RULER_TICK) && ShowScale) {
            szTmp=DDV_DisplayTopScale(pgp->StartLetter,
                                      pgp->StopLetter,disp,disp_format,SCALE_TICK);
            if (szTmp){
                szFLine=DDV_ConcatStr(szFLine,szTmp);
                MemFree(szTmp);
            }
        }
        /*display order num if needed*/
        if (disp_format&DISP_ORDER_NUM){ /*fprintf(fp,"[%4i] ",i);*/
            sprintf(szBuf4,"[%4i] ",i);
            szFLine=DDV_ConcatStr(szFLine,szBuf4);
        }
        /*display sequence name*/
        if (*szSeqAcc) {
            if (disp_format&DISP_FULL_HTML && !(disp_format&DISP_NOLINKONNAME)){
                if (pgp->sip->choice == SEQID_PDB) {
                    n = j = 0;
                    idstring = StringSave(szSeqAcc);
                    while (idstring[n] != '\0') {
                        if (idstring[n] != '_') {
                            tmpstr[j] = idstring[n];
                            j++;
                        }
                        n++;
                    }
                    tmpstr[j] = '\0';
                    sprintf(szBuf4,szEntrezScriptSMART,tmpstr,(IsAA ? "p" : "n"));
                } else {
                    gi=GetGIForSeqId(pgp->sip);
                    if(gi > 0){
                        sprintf(szBuf4,szEntrezScript,gi,(IsAA ? "p" : "n"));
                    } else
                        sprintf(szBuf4,"javascript:void(0)");
                }
                if (szSeqName) {
                    szFLine=DDV_ConcatStr(szFLine,"<a href=\"");
                    szFLine=DDV_ConcatStr(szFLine,szBuf4);
                    szFLine=DDV_ConcatStr(szFLine,"\" onMouseOut=\"window.status=''\" \nonMouseOver=\"window.status='");
                    szFLine=DDV_ConcatStr(szFLine,szSeqName);
                    szFLine=DDV_ConcatStr(szFLine,"';return true\">");
                } else {
                    szFLine=DDV_ConcatStr(szFLine,"<a href=\"");
                    szFLine=DDV_ConcatStr(szFLine,szBuf4);
                    szFLine=DDV_ConcatStr(szFLine,"\" onMouseOut=\"window.status=''\" \nonMouseOver=\"window.status='");
                    szFLine=DDV_ConcatStr(szFLine,"unknown name");
                    szFLine=DDV_ConcatStr(szFLine,"';return true\">");
                }
            }
            szFLine=DDV_ConcatStr(szFLine,szSeqAcc);
            if (disp_format&DISP_FULL_HTML && !(disp_format&DISP_NOLINKONNAME)) 
                szFLine=DDV_ConcatStr(szFLine,"</a>");
        } else {
            szFLine=DDV_ConcatStr(szFLine,"unknown");
        }
        DDV_AddBlank2(diff,&szFLine);
        if (disp_format&DISP_STRAND){
            Char szStuff[]="< >";
            Int1 iStuff=1;
            
            if (bsp_start==INT4_MAX){
                iStuff=1;
            } else {
                if (bsp_strand==Seq_strand_minus)
                    iStuff=0;
                else
                    iStuff=2;
            }
            if (bsp_strand==Seq_strand_minus)
                szFLine=DDV_ConcatStr(szFLine,"<FONT COLOR=#FF0000>");
            sprintf(szBuf4,"%c ", szStuff[iStuff]);
            szFLine=DDV_ConcatStr(szFLine,szBuf4);
            if (bsp_strand==Seq_strand_minus)
                szFLine=DDV_ConcatStr(szFLine,"</FONT>");
        }
        /*display bsp coord if needed*/
        if (disp_format&DISP_BSP_COORD){
            Char szBuf2[15]={""};
            Int4 iVal;
            
            if (bsp_strand==Seq_strand_minus) iVal=bsp_stop;/**/
            else iVal=bsp_start;
            
            if (iVal!=INT4_MAX) {
                sprintf(szBuf2,"%i",++iVal);/*switch to base one*/
                szFLine=DDV_ConcatStr(szFLine,szBuf2);
                DDV_AddBlank2(MAX(2,max_scale-StringLen(szBuf2)+2),&szFLine);
            } 
            else DDV_AddBlank2(max_scale+2,&szFLine);
        }
    } else if (disp_format&DISP_PHYLIP_TXT){
        if (bDispPhilouName){/*Phylip format: seq. names for the first block only*/
            if (szSeqAcc) {/*name only*/
                sprintf(szBuf4,"%-10s ",szSeqAcc);
                szFLine=DDV_ConcatStr(szFLine,szBuf4);
            }
            else {
                szFLine=DDV_ConcatStr(szFLine,"unknown");
            }
        } else {
            sprintf(szBuf4,"%-10s "," ");
            szFLine=DDV_ConcatStr(szFLine,szBuf4);
        }
    }
    /*display sequence*/
    size=StringLen(szSequence);
    if (disp_format&DISPE_SHOWBLOCK){/*AFSDDGTFDG GDFDTEGDFG DFDGETDFGD*/
        stop=size+1;
        size+=(size/LETTER_BLOCK_WIDTH);
        szDisp=(CharPtr)MemNew((size+1)*sizeof(Char));
        if (szDisp){
            MemSet(szDisp,' ',size*sizeof(Char));
            pos=1;
            nCompt2=0;
            while(pos<stop){
                if(disp_format&VIEW_FULLSEQ){
                    szDisp[nCompt2++]=szSequence[pos-1];
                }else if(disp_format&VIEW_VARIA){
                    if(*szSeqMaster && i!=1){
                        if(szSequence[pos-1]=='-'){
                            szSequence[pos-1]='-';
                        }
                        if(szSequence[pos-1]!=(*szSeqMaster)[pos-1]){
                            szDisp[nCompt2++]=szSequence[pos-1];
                        } else {
                            if(szSequence[pos-1]!='-') szDisp[nCompt2++]='.';
                            else szDisp[nCompt2++]=szSequence[pos-1];
                        }
                    } else {
                        szDisp[nCompt2++]=szSequence[pos-1];
                    }
                }
                if (!(pos % LETTER_BLOCK_WIDTH)) {
                    szDisp[nCompt2++]=' ';
                }
                pos++;
            }
            szTmp=DDV_Print_Sequence(szDisp,(Boolean)(disp_format&DISPE_COLOR),IsAA,pgp,gclr,i);
            if (szTmp){
                szFLine=DDV_ConcatStr(szFLine,szTmp);
                MemFree(szTmp);
            }
            MemFree(szDisp);
        } else {
            szTmp=DDV_Print_Sequence(szSequence,(Boolean)(disp_format&DISPE_COLOR),IsAA,pgp,gclr,i);
            if (szTmp){
                szFLine=DDV_ConcatStr(szFLine,szTmp);
                MemFree(szTmp);
            }
        }
    } else {/*AFSDDGTFDGGDFDTEGDFGDFDGETDFGD*/
        if(disp_format&VIEW_FULLSEQ){
            if(disp_format&DISP_FULL_HTML){/*output format*/
                szTmp=DDV_Print_Sequence(szSequence,(Boolean)(disp_format&DISPE_COLOR),IsAA,pgp,gclr,i);
                if (szTmp){
                    szFLine=DDV_ConcatStr(szFLine,szTmp);
                    MemFree(szTmp);
                }
            } else {
                szFLine=DDV_ConcatStr(szFLine,szSequence);
            }
        } else if(disp_format&VIEW_VARIA){
            szDisp=(CharPtr)MemNew((size+1)*sizeof(Char));
            if (szDisp){
                MemSet(szDisp,' ',size*sizeof(Char));
                pos=0;
                stop=size+1;
                while(pos<stop){
                    if(*szSeqMaster && i!=1){
                        if(szSequence[pos]!=(*szSeqMaster)[pos]){
                            szDisp[pos]=szSequence[pos];
                        } else {
                            if(pos==stop-1)
                                szDisp[pos]=szSequence[pos];
                            else
                                szDisp[pos]='.';
                        }
                    } else {
                        szDisp[pos]=szSequence[pos];
                    }
                    pos++;
                }
                if(disp_format&DISP_FULL_HTML){/*output format*/
                    szTmp=DDV_Print_Sequence(szDisp,(Boolean)(disp_format&DISPE_COLOR),IsAA,pgp,gclr,i);
                    if (szTmp){
                        szFLine=DDV_ConcatStr(szFLine,szTmp);
                        MemFree(szTmp);
                    }
                } else {
                    szFLine=DDV_ConcatStr(szFLine,szDisp);
                }
                MemFree(szDisp);
            } else {
                if(disp_format&DISP_FULL_HTML){/*output format*/
                    szTmp=DDV_Print_Sequence(szSequence,(Boolean)(disp_format&DISPE_COLOR),IsAA,pgp,gclr,i);
                    if (szTmp){
                        szFLine=DDV_ConcatStr(szFLine,szTmp);
                        MemFree(szTmp);
                    }
                } else {
                    szFLine=DDV_ConcatStr(szFLine,szSequence);
                }
            }
        }
    }
    /*display bsp coord if needed*/
    if (disp_format&DISP_BSP_COORD){
        Int4 iVal;
        
        if (bsp_strand==Seq_strand_minus) iVal=bsp_start;/**/
        else iVal=bsp_stop;
        
        if (iVal!=INT4_MIN) {
            sprintf(szBuf4,"  %i", iVal+1);
            szFLine=DDV_ConcatStr(szFLine,szBuf4);
        }
        else DDV_AddBlank2(max_scale+2,&szFLine);
    }
    
    /*build the BLAST middle line of the alignment*/
    if(disp_format&DISP_BLAST_MIDLINE && i>1){
        szMiddleLine=DDV_GetBLASTCompLine_1(*szSeqMaster, szSequence, matrix,
                                            IsAA);
        if (szMiddleLine){
            szTmp=(CharPtr)MemNew((disp+1)*sizeof(Char));
            MemSet(szTmp,' ',disp);
            szTmp=DDV_ConcatStr(szTmp,szMiddleLine);
            szTmp=DDV_ConcatStr(szTmp,"\n");
            szTmp=DDV_ConcatStr(szTmp,szFLine);
            MemFree(szFLine);
            szFLine=szTmp;
            MemFree(szMiddleLine);
        }
    }
    
    /*hack: for test purpose (features display on SeqAlign)*/
    /*DDV_DispFeaturesForPGP(pgp, bsp, &szFLine, disp, LineSize, szSequence,
      bsp_strand);*/
    
    
 error:
    if (bsp)BioseqUnlock(bsp);
    MemFree(szSequence);
    szFLine=DDV_ConcatStr(szFLine,"\n");
    *szFormattedLine=szFLine;
    
    return(vnp->next);
}

/*******************************************************************************

  Function : DDV_Nav_Arrows()
  
  Purpose : display the "navigator" links (to jump to next/previous blocks)
  
  Parameters : 	
				gi; gi number used by PopSet viewer to build the HTTP links
				
  				TotalAliLength; SeqAlign size
				numBlockAffich; block number displayed (when display by block is
						required; otherwise numBlockAffich=0).
				disp_format; full HTML, Phylip, ...
				LineSize; size of one text line (number of letter for the sequence)
				
  Return value : -

*******************************************************************************/
static CharPtr DDV_Nav_Arrows(Int4 gi,Int4 TotalAliLength,
		Int4 numBlockAffich,Uint4 disp_format,Int2 LineSize)
{
CharPtr	szWide,szFLine=NULL;
Int4 	k,wide,lGoLeft,lGoRight,fromL,toL,fromR,toR;
Char	szGoLeft[30]={""};
Char	szGoRight[30]={""};
Char 	szWWW[WWW_SCRIPT_SIZE]={""};

	k=TotalAliLength/LineSize;
	if (TotalAliLength%LineSize) k++;
	if (numBlockAffich>1){/*left arrow*/
		fromL=(numBlockAffich-2)*LineSize+1;
		toL=_min_((numBlockAffich-1)*LineSize,TotalAliLength);
		sprintf(szGoLeft,"[%d..%d]",fromL,toL);
		lGoLeft=StringLen(szGoLeft)+2;
	}
	else{
		StringCpy(szGoLeft," ");
		fromL=0;
		toL=0;
		lGoLeft=1;
	}
	if (numBlockAffich<k){/*right arrow*/
		fromR=(numBlockAffich)*LineSize+1;
		toR=_min_((numBlockAffich+1)*LineSize,TotalAliLength);
		sprintf(szGoRight,"[%d..%d]",fromR,toR);
		lGoRight=StringLen(szGoRight)+2;
	}
	else{
		StringCpy(szGoRight," ");
		fromR=0;
		toR=0;
		lGoRight=1;
	}
	wide=LineSize+28;
	if (disp_format&DISPE_SHOWBLOCK) wide+=(LineSize/LETTER_BLOCK_WIDTH);
	szWide=(CharPtr)MemNew(wide*sizeof(Char));
	MemSet(szWide,'.',(wide-lGoLeft-lGoRight)*sizeof(Char));
	szWide[wide-lGoLeft-lGoRight]='\0';
	szFLine=DDV_ConcatStr(szFLine,"<pre>");
	if(fromL!=0 && toL!=0){
		sprintf(szWWW,WWWDDV_script,gi,fromL,toL,disp_format);
		szFLine=DDV_ConcatStr(szFLine,"&lt;&lt<a href=\"");
		szFLine=DDV_ConcatStr(szFLine,szWWW);
		szFLine=DDV_ConcatStr(szFLine,"\" onMouseOut=\"window.status='';return true\" ");
		szFLine=DDV_ConcatStr(szFLine,"onMouseOver=\"window.status='Click to view this region';return true\" >");
		szFLine=DDV_ConcatStr(szFLine,szGoLeft);
		szFLine=DDV_ConcatStr(szFLine,"</a>");
	}
	else{
		szFLine=DDV_ConcatStr(szFLine,szGoLeft);
	}
	szFLine=DDV_ConcatStr(szFLine,"<FONT COLOR=#FFFFFF>");
	szFLine=DDV_ConcatStr(szFLine,szWide);
	szFLine=DDV_ConcatStr(szFLine,"</FONT>");
	
	if(fromR!=0 && toR!=0){
		sprintf(szWWW,WWWDDV_script,gi,fromR,toR,disp_format);
		szFLine=DDV_ConcatStr(szFLine,"<a href=\"");
		szFLine=DDV_ConcatStr(szFLine,szWWW);
		szFLine=DDV_ConcatStr(szFLine,"\" onMouseOut=\"window.status='';return true\" ");
		szFLine=DDV_ConcatStr(szFLine,"onMouseOver=\"window.status='Click to view this region';return true\" >");
		szFLine=DDV_ConcatStr(szFLine,szGoRight);
		szFLine=DDV_ConcatStr(szFLine,"</a>&gt;&gt");
	}
	else{
		szFLine=DDV_ConcatStr(szFLine,szGoRight);
	}
	szFLine=DDV_ConcatStr(szFLine,"</pre>");

	MemFree(szWide);
	return(szFLine);
}

/*******************************************************************************

  Function : DDV_AffichageParaG()
  
  Purpose : function to create an HTML/TXT/PHYLIP display of an Indexed SeqAlign
  
  Parameters : 	mpplp; contain the data to create a display (sap, ...)
				gi; gi number used by PopSet viewer to build the HTTP links
				from - to; range of the SeqAlign to display
  				TotalAliLength; SeqAlign size
				numBlockAffich; block number displayed (when display by block is
						required; otherwise numBlockAffich=0).
				disp_format; full HTML, Phylip, ...
				LineSize; size of each line of sequence
				fp; file to put the ouptut
				bspp; filled here withthe formatted text
				matrix; matrix used for BLAST output
				gclr; enhanced display options (colors, upper/lower case,...)
				 
  Return value : - (see bspp)

  Note : if fp==NULL, formatted text will be stored in bspp; Otherwise the
         text is directly sent to fp.
		 
*******************************************************************************/
NLM_EXTERN void DDV_AffichageParaG(MsaParaGPopListPtr mpplp,Int4 gi,Int4 from,Int4 to,
		Int4 TotalAliLength,Int4 numBlockAffich,Uint4 disp_format,Int2 LineSize,
		FILE *fp,ByteStorePtr PNTR bspp,Int4Ptr PNTR matrix,DDV_ColorGlobal * gclr,
		ValNodePtr mask)
{
Int4 			i,j=0,max_length=INT4_MIN,max_scale=INT4_MIN;
ValNodePtr PNTR TableDesc=NULL;
CharPtr 		szColor[]={"#E6EEEE","ccccff","FFFFFF"};
CharPtr 		*szSeqAcc;
CharPtr 		*szSeqName;
CharPtr 		szFline,szTmp;
Char 			szBuf[25],szBuf2[25];
ParaGPtr 		pgp;
BioseqPtr 		bsp;
BoolPtr 		IsAAp;
Boolean			bDispPhilouName=TRUE;
SeqIdPtr        sip;
CharPtr  		szSeqMaster=NULL;

	/*if bspp is not allocated*/
	if (fp==NULL && (*bspp)==NULL){
		(*bspp)=BSNew((Int4)1);
		if ((*bspp)==NULL) return;
	}
	
	/*prepare a list of ParaG heads, names, Acc Number and Mol_type*/
	TableDesc=(ValNodePtr PNTR)MemNew(mpplp->nBsp*sizeof(ValNodePtr));
	szSeqAcc=(CharPtr *)MemNew(mpplp->nBsp*sizeof(CharPtr));
	szSeqName=(CharPtr *)MemNew(mpplp->nBsp*sizeof(CharPtr));
	IsAAp=(BoolPtr)MemNew(mpplp->nBsp*sizeof(Boolean));

	if (!TableDesc || !szSeqAcc || !szSeqName || !IsAAp) goto error;
	MemSet(szSeqAcc,0,mpplp->nBsp*sizeof(CharPtr));	
	MemSet(szSeqName,0,mpplp->nBsp*sizeof(CharPtr));	
	MemSet(IsAAp,0,mpplp->nBsp*sizeof(Boolean));	
	if (!(disp_format&DISPE_TABLE)) j=2;
	else j=0;

	for(i=0;i<mpplp->nBsp;i++){
		TableDesc[i]=mpplp->TableHead[i];/*copy the ValNode heads in TableDesc*/
		/*get the access code*/
		pgp=(ParaGPtr)TableDesc[i]->data.ptrvalue;
		if (pgp){/*create the name table*/
			bsp=BioseqLockById(pgp->sip);
			if (bsp){
				Int2 jj;
				if (disp_format&SEQNAME_BLAST_STD){ 
					if (i==0) 
						StringCpy(szBuf,"Query:");
					else
						StringCpy(szBuf,"Sbjct:");
				}
				else{
					sip = SeqIdFindBest(bsp->id, SEQID_PDB);
					if (!sip)
				   		sip = SeqIdFindBest(bsp->id, 0);
					SeqIdWrite(sip, szBuf,PRINTID_TEXTID_ACCESSION, 14);   
				}
				/*access code*/
				szSeqAcc[i]=StringSave(szBuf);
				max_length=MAX(max_length,(Int4)StringLen(szSeqAcc[i]));
				/*seq title*/
				szSeqName[i]=(CharPtr)MemNew(100*sizeof(Char));
				if (szSeqName[i] && !(disp_format&SEQNAME_BLAST_STD)){
					CreateDefLine(NULL, bsp, szSeqName[i], 99, 0, NULL, NULL);
					jj=0;
					while(szSeqName[i][jj]){
						if (szSeqName[i][jj]=='\'' || szSeqName[i][jj]=='\"') szSeqName[i][jj]=' ';
						jj++;
					}
				}
				
				IsAAp[i]=ISA_aa(bsp->mol);
				/*size for the BSP coord display*/
				sprintf(szBuf2,"%i",BioseqGetLen(bsp));
				max_scale=MAX(max_scale,(Int4)StringLen(szBuf2));
				BioseqUnlock(bsp);
			}
		}
	}

	szFline=NULL;
	if(disp_format&DISP_FULL_HTML){/*output format*/
		if (numBlockAffich>0){/*nav arrow*/
			szTmp=DDV_Nav_Arrows(gi,TotalAliLength,numBlockAffich,disp_format,LineSize);
			szFline=DDV_ConcatStr(szFline,szTmp);
			MemFree(szTmp);
		}
		if (disp_format&DISPE_TABLE){
			szFline=DDV_ConcatStr(szFline,"<table><tr><td bgcolor=");
			szFline=DDV_ConcatStr(szFline,szColor[j]);
			szFline=DDV_ConcatStr(szFline,">");
			szFline=DDV_ConcatStr(szFline,"<pre>");
		}
		else {
			/*if (!(disp_format&DISP_BLAST_STD)) */
				szFline=DDV_ConcatStr(szFline,"<pre>");
		}
	}else if(disp_format&DISP_PHYLIP_TXT){
		sprintf(szBuf,"%7d  %d\n",mpplp->nBsp,mpplp->LengthAli);
		szFline=DDV_ConcatStr(NULL,szBuf);
	}

	if(szFline){
		if (fp)
			fprintf(fp,"%s",szFline);
		else
			BSWrite(*bspp, (VoidPtr)szFline, StringLen(szFline));
		MemFree(szFline);
	}

	i=1;
	while(TRUE){
		szFline=NULL;
		/*display one ParaG (one row; except for BLAST : when the subject line is displayed,
		the comp. line is displayed at the same time*/
		TableDesc[i-1]=DDV_DisplayParaG(TableDesc[i-1],i,(Boolean)(i==1 ? TRUE : FALSE),
			disp_format,szSeqAcc[i-1],szSeqName[i-1],IsAAp[i-1],bDispPhilouName,
			max_length,max_scale,LineSize,&szFline,&szSeqMaster,matrix,gclr,mask);
		/*actually, DDV_DisplayParaG() put a formatted line in szFline; now put that in a file or BS */
		if (szFline){
			if (fp)
				fprintf(fp,"%s",szFline);
			else
				BSWrite(*bspp, (VoidPtr)szFline, StringLen(szFline));
			MemFree(szFline);
		}
		i++;
		/*I use 'i' to count the number of rows displayed. As soon as 'i' > mpplp->nBsp, I need to do
		specials things, especially for the PopSet Viewer. Indeed, PopSet-V puts each "block" of the
		SeqAlign in the cell of a table. So, for each new block, I have to close/open HTML tags.*/
		if (i>mpplp->nBsp){
			i=1;
			if (szSeqMaster) 
				szSeqMaster=MemFree(szSeqMaster);
			if(disp_format&DISP_FULL_HTML){
				if (disp_format&DISPE_TABLE){
					szFline=DDV_ConcatStr(NULL,"</pre>");
					szFline=DDV_ConcatStr(NULL,"</td></tr>");
				}
				else{
					szFline=DDV_ConcatStr(NULL,"\n");
				}
				if(szFline){
					if (fp)
						fprintf(fp,"%s",szFline);
					else
						BSWrite(*bspp, (VoidPtr)szFline, StringLen(szFline));
					MemFree(szFline);
				}
			}else if((disp_format&DISP_PHYLIP_TXT) || (disp_format&DISP_FULL_TXT)){
				szFline=DDV_ConcatStr(NULL,"\n");
				if(szFline){
					if (fp)
						fprintf(fp,"%s",szFline);
					else
						BSWrite(*bspp, (VoidPtr)szFline, StringLen(szFline));
					MemFree(szFline);
				}
			}
			if (numBlockAffich==0){
				if (j==1) j=0; else j=1;
			}
			if(disp_format&DISP_FULL_HTML){
                szFline=NULL;
				if (disp_format&DISPE_TABLE){
					szFline=DDV_ConcatStr(NULL,"<tr><td bgcolor=");
					szFline=DDV_ConcatStr(szFline,szColor[j]);
					szFline=DDV_ConcatStr(szFline,">");
					szFline=DDV_ConcatStr(szFline,"<pre>");
				}
				if(szFline){
					if (fp)
						fprintf(fp,"%s",szFline);
					else
						BSWrite(*bspp, (VoidPtr)szFline, StringLen(szFline));
					MemFree(szFline);
				}
			}else if(disp_format&DISP_PHYLIP_TXT){
				bDispPhilouName=FALSE;
			}
			if (TableDesc[mpplp->nBsp-1]==NULL) break;
		} 
	}
	/*we're close to the end... for the PopSet-Viewer, I need to close the table*/
	if(disp_format&DISP_FULL_HTML){
		if (disp_format&DISPE_TABLE){
			szFline=DDV_ConcatStr(NULL,"</pre>");
			szFline=DDV_ConcatStr(szFline,"</td></tr></table>");
		}
		else{
			/*if (!(disp_format&DISP_BLAST_STD)) */
				szFline=DDV_ConcatStr(NULL,"</pre>");
		}
		if (numBlockAffich>0)/*nav arrow*/{
			szTmp=DDV_Nav_Arrows(gi,TotalAliLength,numBlockAffich,disp_format,LineSize);
			szFline=DDV_ConcatStr(szFline,szTmp);
			MemFree(szTmp);
		}
		if(szFline){
			if (fp)
				fprintf(fp,"%s",szFline);
			else
				BSWrite(*bspp, (VoidPtr)szFline, StringLen(szFline));
			MemFree(szFline);
		}
	}
	/*end of the display*/
error:
	if (TableDesc) MemFree(TableDesc);
	if (szSeqAcc){
		for(i=0;i<mpplp->nBsp;i++){
			if (szSeqAcc[i]){
				MemFree(szSeqAcc[i]);
			}
		}
		MemFree(szSeqAcc);
	}
	if (szSeqName){
		for(i=0;i<mpplp->nBsp;i++){
			if (szSeqName[i]){
				MemFree(szSeqName[i]);
			}
		}
		MemFree(szSeqName);
	}
	if (IsAAp) MemFree(IsAAp);
}

/*******************************************************************************

  Function : DDV_GetGappedSequence()
  
  Purpose : get a gapped sequence from the indexed seq align
  
  Parameters : 	segp; head of the nodes list of one bsp
  				szSequence; ALLOCATED buffer of size SeqAlign, where the sequence
							will be stored.
				IsAA; doesn't need an explanation, I think...
				
  Note : do not forget to allocate 'szSequence' before entering this function
  
  Return value : none (see szSequence)

*******************************************************************************/
static void DDV_GetGappedSequence(SegmentPtr segp,CharPtr szSequence,
		Boolean IsAA)
{
SegmentPtr sp;
CharPtr SeqBuf;/*I use a pointer because I cannot use a fixed array*/

	if (!szSequence || !segp) return;
	/*loop each segment of the bioseq*/
	for(sp=segp ; sp!=NULL ; sp=sp->bsp_next){
		if(sp->gap){/*gap segment*/
			SeqBuf=(CharPtr)MemNew((sp->gap+1)*sizeof(Char));
			if (SeqBuf){
				MemSet(SeqBuf,'-',(sp->gap)*sizeof(Char));
			}
		}
		else{/*sequence segment*/
			SeqBuf=UDV_Read_SequenceEx (sp->sip,sp->from,sp->to, 
				IsAA,(Int2)(sp->to-sp->from+1),(Uint1)
				(sp->strand == Seq_strand_minus ? Seq_strand_minus : Seq_strand_plus));
			if (!SeqBuf){
				SeqBuf=(CharPtr)MemNew((sp->to-sp->from+2)*sizeof(Char));
				if (SeqBuf){
					MemSet(SeqBuf,'?',(sp->to-sp->from+1)*sizeof(Char));
				}
			}
		}
		if (SeqBuf){
			StringCat(szSequence,SeqBuf);
			MemFree(SeqBuf);
			SeqBuf=NULL;
		}
	}
}

/*******************************************************************************

  Function : DDV_PrintFastaGappedSequence()
  
  Purpose : print a character string as a FASTA sequence format
  
  Parameters : 	szSequence; what do you think it is ?
  				fp; may be a real file or 'stdout'
  
  Return value : none

*******************************************************************************/
#define line_fas_size 80
static void DDV_PrintFastaGappedSequence(CharPtr szSequence,FILE *fp)
{
Char szBuf[line_fas_size+1]={""};
Int4 i=0,j=0,len=StringLen(szSequence);

	if (!szSequence || !fp) return;

	while(szSequence[i]){
		szBuf[j++]=szSequence[i++];
		if (i==len || j==line_fas_size){
			szBuf[j]='\0';
			fprintf(fp,"%s\n",szBuf);
			j=0;
		}
	}
}

/*******************************************************************************

  Function : DDV_GetFullFASTAforIdxAli()
  
  Purpose : create the FASTA file for a full Indexed SeqAlign
  
  Parameters :  sap; seqalign (must be indexed before entering this funtion)
				fp; file to put the FASTA
  
  Return value : TRUE if success 

*******************************************************************************/
NLM_EXTERN Boolean DDV_GetFullFASTAforIdxAli(SeqAlignPtr sap,FILE *fp)
{
BioseqPtr	bsp;	
Int4        i,nRow;

	nRow=AlnMgrGetNumRows(sap);
	
	for (i=1 ; i <= nRow ; i++){
		bsp=BioseqLockById(AlnMgrGetNthSeqIdPtr(sap, i));
		if (bsp){
			BioseqToFasta(bsp,fp,(Boolean)ISA_na(bsp->mol));
			BioseqUnlock(bsp);
		}
	}
	return(TRUE);	
}

/*******************************************************************************

  Function : DDV_GetFullGapFASTAforIdxAli()
  
  Purpose : create the gapped FASTA file for a full Indexed SeqAlign
  
  Parameters :  mpplp; indexed seqalign
				fp; file to put the FASTA
  
  Return value : TRUE if success 

*******************************************************************************/
NLM_EXTERN Boolean DDV_GetFullGapFASTAforIdxAli(MsaParaGPopListPtr mpplp,FILE *fp)
{
Int4 i,bspLength;
ParaGPtr 		pgp;
ValNodePtr    vnp;
BioseqPtr bsp;
Boolean   IsAA;
CharPtr szSeq;
Char DefLine[255];

	for (i=0;i<mpplp->nBsp;i++){
		vnp=mpplp->TableHead[i];
		/*get some BSP data*/
		pgp=(ParaGPtr)vnp->data.ptrvalue;
		bsp=BioseqLockById(pgp->sip);
		if (!bsp) continue;
		bspLength=BioseqGetLen(bsp);
		IsAA=ISA_aa(bsp->mol);
		/*print the FASTA header for the bioseq*/
		FastaId(bsp,DefLine,254);
		fprintf(fp,">%s ",DefLine);
		CreateDefLine(NULL, bsp, DefLine, 254, 0,NULL, NULL);
		fprintf(fp,"%s\n",DefLine);
		BioseqUnlock(bsp);
		/*print the gapped sequence*/
		while(vnp){
			pgp=(ParaGPtr)vnp->data.ptrvalue;
			szSeq=(CharPtr)MemNew((pgp->StopLetter-pgp->StartLetter+3)*sizeof(Char));
			if (szSeq){
				if (!DDV_GetSequenceFromParaG(pgp,&szSeq,bspLength,IsAA,NULL,
					NULL,NULL)) continue;
				fprintf(fp,szSeq);
				fprintf(fp,"\n");
				MemFree(szSeq);
			}
			vnp=vnp->next;
		}
	}
	fprintf(fp,"\n");
	return(TRUE);
}

/*******************************************************************************

  Function : DDV_PrintStudyName()
  
  Purpose : print the name/author of the PopSet study
  
*******************************************************************************/
NLM_EXTERN void DDV_PrintStudyName(CharPtr szPopSetName,CharPtr szPopSetAuth,
		CharPtr szJournalTitle,Int4 pmid,FILE *fp)
{
	if (StringLen(szPopSetName)>0 && StringLen(szPopSetAuth)>0) {
		if (StringStr(szPopSetName,"* no title *") || 
			StringStr(szPopSetAuth,"* no title *")){
			fprintf(fp,"<h2>Unpublished study.</h2>");
		}
		else{
			if (pmid!=0){
				fprintf(fp,"<h2>%s (",szPopSetName);
				fprintf(fp,"<a href=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&db=PubMed&list_uids=%d&dopt=Abstract\">",pmid);
				fprintf(fp,"%s <i>et al.</i>",szPopSetAuth);
				if (StringLen(szJournalTitle)>0)
					fprintf(fp,"</a>, <i>%s</i>)<BR></h2>",szJournalTitle);
				else
					fprintf(fp,"</a>)<BR></h2>");
			}
			else{
				fprintf(fp,"<h2>%s (%s <i>et al.</i>", 
					szPopSetName,szPopSetAuth);
				if (StringLen(szJournalTitle)>0)
					fprintf(fp,", <i>%s</i>)<BR></h2>",szJournalTitle);
				else
					fprintf(fp,")<BR></h2>");
			}
		}
	}
	else{
		fprintf(fp,"<h2>Unpublished study.</h2>");
	}
}

/*******************************************************************************

  Function : DDV_GetFirstAuthor()
  
  Purpose : retrieve the first author of the PopSet
  
  Parameters : 	alp; valnode of authors
  				name; filled in this function
  
  Return value : - (see 'name')

*******************************************************************************/
static void DDV_GetFirstAuthor (AuthListPtr alp, CharPtr name)
{
ValNodePtr   names;
AuthorPtr    ap;
PersonIdPtr  pid;

	if (!alp) return;
	names = alp->names;/*this is a ValNodeList, but I only need to deal
	with the first node, i.e the first author*/
	if (alp->choice == 1) {
		ap = (AuthorPtr) names->data.ptrvalue;
		if (ap != NULL) {
			pid = ap->name;
			if (pid != NULL) {
				PersonIdLabel(pid, name, INFO_SIZE, PIDLABEL_GENBANK);
			}
		}
	}
	else if (alp->choice == 2 || alp->choice == 3) {
		StringNCpy(name,(CharPtr)names->data.ptrvalue,INFO_SIZE);
	}
}

/*******************************************************************************

  Function : DDV_GetPubValues()
  
  Purpose : analyse a Imprint pointer and get "82 (21), 7289-7293 (1985)"
  
  Parameters : 	imp; should contains 82 (21), 7289-7293 (1985)
  				szBuf; where to put "82 (21), 7289-7293 (1985)"
  
  Return value : TRUE if imp!=NULL (see also 'szBuf')

*******************************************************************************/
static Boolean DDV_GetPubValues(ImprintPtr imp,CharPtr szImp)
{
Int2         year=(Int2)-1;
Char         szBuf[6]={""};

	if (szImp==NULL) return(FALSE);
	
	StringCpy(szImp," ");
	DateRead (imp->date,&year, NULL, NULL, NULL);
	if (imp->volume){
		StringCat(szImp,imp->volume);
	}
	if (imp->issue){
		StringCat(szImp," (");
		StringCat(szImp,imp->volume);
		StringCat(szImp,")");
	}
	if (imp->pages){
		StringCat(szImp,", ");
		StringCat(szImp,imp->pages);
	}
	if (year!=(Int2)-1){
		StringCat(szImp," (");
		sprintf(szBuf,"%d",year);
		StringCat(szImp,szBuf);
		StringCat(szImp,")");
	}
	
	return(TRUE);
}

static void	DDV_AnalysePubDesc(PubdescPtr pdp, CharPtr szPopSetName,
		CharPtr szPopSetAuth,CharPtr szJournalTitle,Int4Ptr pmid)
{
ValNodePtr   vnp,vnp2;
CitArtPtr    cap;
CitGenPtr    cgp;
CitSubPtr    csp;
CitPatPtr    cpp;
CitBookPtr   cbp;
ImprintPtr   imp;
MedlineEntryPtr mep;
Char         szBuf[80+1]={""};

	for (vnp = pdp->pub; vnp != NULL; vnp = vnp->next) {
		switch(vnp->choice){
			case PUB_Article:/*article*/
				cap = (CitArtPtr) vnp->data.ptrvalue;
				if (!cap) break;
				for (vnp2 = cap->title; vnp2 != NULL; vnp2 = vnp2->next) {
					if(vnp2->choice==Cit_title_name){
						StringNCpy(szPopSetName,(CharPtr)vnp2->data.ptrvalue,INFO_SIZE);
					}
				}
				if (cap->from==1/*journal type*/){
					CitJourPtr cjp=(CitJourPtr)cap->fromptr;
					if (cjp && cjp->title && cjp->title->data.ptrvalue){
						StringNCpy(szBuf,(CharPtr)(cjp->title->data.ptrvalue),80);
						StringCpy(szJournalTitle,szBuf);
						imp=cjp->imp;
						if (imp){
							if (DDV_GetPubValues(imp,szBuf))
								StringCat(szJournalTitle,szBuf);
						}
					}
				}
				DDV_GetFirstAuthor (cap->authors, szPopSetAuth);
				break;
			case PUB_Gen:/*gen*/
				cgp = (CitGenPtr) vnp->data.ptrvalue;
				if (!cgp) break;
				if (cgp->title && *(cgp->title))
					StringNCpy(szPopSetName,cgp->title,INFO_SIZE);
				if (cgp->journal && cgp->journal->data.ptrvalue){
					StringNCpy(szJournalTitle,(CharPtr)(cgp->journal->data.ptrvalue),INFO_SIZE);
				}
				DDV_GetFirstAuthor (cgp->authors, szPopSetAuth);
				break;
			case PUB_Sub:/*Sub*/
				csp = (CitSubPtr) vnp->data.ptrvalue;
				if (!csp) break;
				if (csp->descr && *(csp->descr))
					StringNCpy(szPopSetName,csp->descr,INFO_SIZE);
				StringCpy(szJournalTitle,"direct submission");
				DDV_GetFirstAuthor (csp->authors, szPopSetAuth);
				break;
			case PUB_Patent:/*Pat*/
				cpp = (CitPatPtr) vnp->data.ptrvalue;
				if (!cpp) break;
				if (cpp->title && *(cpp->title))
					StringNCpy(szPopSetName,cpp->title,INFO_SIZE);
				DDV_GetFirstAuthor (cpp->authors, szPopSetAuth);
				break;
			case PUB_Book:/*Book*/
				cbp = (CitBookPtr) vnp->data.ptrvalue;
				if (!cbp) break;
				for (vnp2 = cbp->title; vnp2 != NULL; vnp2 = vnp2->next) {
					if(vnp2->choice==Cit_title_name){
						StringNCpy(szPopSetName,(CharPtr)vnp2->data.ptrvalue,INFO_SIZE);
					}
				}
				if (cbp->title && cbp->title->data.ptrvalue){
					StringNCpy(szBuf,(CharPtr)(cbp->title->data.ptrvalue),80);
					StringCpy(szJournalTitle,szBuf);
					imp=cbp->imp;
					if (imp){
						if (DDV_GetPubValues(imp,szBuf))
							StringCat(szJournalTitle,szBuf);
					}
				}
				DDV_GetFirstAuthor (cbp->authors, szPopSetAuth);
				break;
			case PUB_Medline:/*Medline*/
				mep = (MedlineEntryPtr) vnp->data.ptrvalue;
				if (!mep) break;
				cap = mep->cit;
				for (vnp2 = cap->title; vnp2 != NULL; vnp2 = vnp2->next) {
					if(vnp2->choice==Cit_title_name){
						StringNCpy(szPopSetName,(CharPtr)vnp2->data.ptrvalue,INFO_SIZE);
					}
				}
				if (cap->from==1/*journal type*/){
					CitJourPtr cjp=(CitJourPtr)cap->fromptr;
					if (cjp && cjp->title && cjp->title->data.ptrvalue){
						StringNCpy(szBuf,(CharPtr)(cjp->title->data.ptrvalue),80);
						StringCpy(szJournalTitle,szBuf);
						imp=cjp->imp;
						if (imp){
							if (DDV_GetPubValues(imp,szBuf))
								StringCat(szJournalTitle,szBuf);
						}
					}
				}
				DDV_GetFirstAuthor (cap->authors, szPopSetAuth);
				break;
			case PUB_PMid:/*PubMed Id*/
				*pmid=vnp->data.intvalue;
				break;
		}
	}
}

/*******************************************************************************

  Function : DDV_GetArticleInfo()
  
  Purpose : retrieve the article's title of the PopSet
  
  Parameters : 	sep; seqentry
  				szPopSetName; filled in this function
  				szPopSetAuth; filled in this function

  Note:
	A BioseqSetPtr contains the field 'descr'. This is a ValNodeList.
	Among the nodes, one is of type Seq_descr_pub, the PubMed data information.
	In this case, descr->data.ptrvalue if of type PubdescPtr. Let say
	pdp=(PubdescPtr)descr->data.ptrvalue. Now, pdp is a ValNode List of 
	PubMed fields where pdp->choice can be PUB_Article. In that case
	pdp->data.ptrvalue if of type CitArtPtr. This data block contains
	the article info: title and authors.

	This function is designed to retrieve the first title and the first
	author correponding to that title.

	I've enhanced this function to manage Gen, Sub, Pat, Book, Medline.
  
  Return value : - (see 'szPopSetName' & 'szPopSetAuth')

*******************************************************************************/
NLM_EXTERN void	DDV_GetArticleInfo(SeqEntryPtr sep,CharPtr szPopSetName,
	CharPtr szPopSetAuth,CharPtr szJournalTitle,Int4Ptr pmid)
{
BioseqSetPtr bssp;
PubdescPtr   pdp;
ValNodePtr   vnp3;

	if (!sep || !szPopSetName || !szPopSetAuth) return;
	
	*szPopSetName='\0';
	*szPopSetAuth='\0';
	*szJournalTitle='\0';
	*pmid=0;
	
	if (IS_Bioseq_set (sep)) {/*a Pop-set is a BSSP*/
		bssp = (BioseqSetPtr) sep->data.ptrvalue;		
		if (bssp){
			if(bssp->descr != NULL) {
				for (vnp3=bssp->descr ; vnp3 != NULL ; vnp3 = vnp3->next){
					if(vnp3->choice==Seq_descr_pub){
    					pdp = (PubdescPtr) vnp3->data.ptrvalue;
						if (pdp){
							DDV_AnalysePubDesc(pdp,szPopSetName,
								szPopSetAuth,szJournalTitle,pmid);
						}
					}
				}
			}
		}
	}
	if (*(szPopSetName)=='\0') StringCpy(szPopSetName,"* no title *");
	if (*(szPopSetAuth)=='\0') StringCpy(szPopSetAuth,"* no authors *");
}

/*******************************************************************************

  Function : DDV_AnalyseBiosource()
  
  Purpose : analyse a BioSource pointer and get TaxName and common name
  
  Parameters : 	biop; BioSource pointer
  				szTaxName; fills here with a TaxName
				szCommonName;fills here with the first common name
  
  Return value : - (see 'name')

*******************************************************************************/
static void	DDV_AnalyseBiosource(BioSourcePtr biop, CharPtr PNTR szTaxName,
		CharPtr PNTR szCommonName)
{

	if (!biop) return;

	if (biop->org && biop->org->taxname){
		*szTaxName=biop->org->taxname;
	}
	if (biop->org && biop->org->common){
		*szCommonName=biop->org->common;
	}
	
}

/*******************************************************************************

  Function : DDV_GetEntryBioSource()
  
  Purpose : retrieve the BioSource, given a sep
  
  Note : this function can be called several times to fill the valnode vnpp
  with all the Biosources of all SeqSet of an Entry. This is used, for example,
  by the PopSet Viewer to build the organim names list.
  
  Parameters : 	sep; seqentry
  				vnpp; list to fill. data.ptrvalue if of type PopSourcePtr (see pgppop.h)

*******************************************************************************/

NLM_EXTERN void	DDV_GetEntryBioSource(SeqEntryPtr sep,ValNodePtr PNTR vnpp)
{
BioseqSetPtr bssp;
BioSourcePtr biop;
ValNodePtr   vnp;
PopSourcePtr psp;

	if (!sep || !vnpp) return;
	
	if (IS_Bioseq_set (sep)) {/*a Pop-set is a BSSP*/
		bssp = (BioseqSetPtr) sep->data.ptrvalue;		
		if (bssp){
			if(bssp->descr != NULL) {/*scan the 'desc' field of the bssp*/
				for (vnp=bssp->descr ; vnp != NULL ; vnp = vnp->next){
					if(vnp->choice==Seq_descr_source){/*BioSource ?*/
    					biop = (BioSourcePtr) vnp->data.ptrvalue;
						if (biop){
							psp=(PopSourcePtr)MemNew(sizeof(PopSource));
							if (psp){
								DDV_AnalyseBiosource(biop,&(psp->szTaxName),
									&(psp->szCommonName));
								if (!(*vnpp)) *vnpp=ValNodeAddPointer(NULL,0,(Pointer)psp);
								else ValNodeAddPointer(vnpp,0,(Pointer)psp);
							}
						}
					}
				}
			}
		}
	}
}

/*******************************************************************************

  Function : SearchBioSource()
  
  Purpose : caalback for SeqEntryExplore to get all the biosources of all set
  in a popset entry, fo example
  
  Parameters : see Toolbox doc !
  
  Return value : none 

*******************************************************************************/
static void SearchBioSource(SeqEntryPtr sep, Pointer mydata, Int4 index, Int2 indent)
{
ValNodePtr PNTR	vnpp;

	vnpp=(ValNodePtr PNTR)mydata;

	if (IS_Bioseq_set (sep)) {
		DDV_GetEntryBioSource(sep, vnpp);
	}
}

/*******************************************************************************

  Function : DDV_DisplayDefaultAlign()
  
  Purpose : build a default SeqAlign display.
  
  Parameters : 	sap; SeqAlign
				gi;gi number - used by PopSet viewer to build the HTTP links
				from - to; range of the Sap to display
				disp_format; display formats (see pgppop.h)
				disp_data; for future implementation
				fp; to send the output
  Return value : FALSE if failed 

*******************************************************************************/
NLM_EXTERN Boolean DDV_DisplayDefaultAlign(SeqAlignPtr sap,Int4 gi,Int4 from,Int4 to,
		Uint4 disp_format,Pointer disp_data,FILE *fp)
{
SABlockPtr		sabp=NULL;/*indexed SeqAlign*/
Int4			sapLength;/*indexed SeqAlign size*/
MsaParaGPopList mppl;/*contains the data for the display*/
Int4			numBlockAffich=0,restdiv;
Int2            LineSize;
DDVOptionsBlockPtr dobp;
Int4Ptr PNTR    matrix;
ByteStorePtr   PNTR byteSpp;
DDV_Disp_Opt   ddo;

	MemSet(&mppl,0,sizeof(MsaParaGPopList));
	MemSet(&ddo,0,sizeof(DDV_Disp_Opt));

	if (disp_data){
		dobp=(DDVOptionsBlockPtr)disp_data;
		LineSize=dobp->LineSize;
		byteSpp=dobp->byteSpp;
		matrix=dobp->matrix;
		if (dobp->ddop) MemCpy(&ddo,dobp->ddop,sizeof(DDV_Disp_Opt));
	}
	else{
		LineSize=ParaG_Size;
		byteSpp=NULL;
		matrix=NULL;
		DDV_InitDefSAPdispStyles(&ddo);
	}

	if (disp_format&DISP_FASTA_NOGAP){/*don't need a ParaG structure*/
		DDV_GetFullFASTAforIdxAli(sap,fp);
	}
	else{/*HTML, gapped FASTA and PHYLIP: need a ParaG structure*/
		/*build the ParaG list for the display*/
		if (from==(Int4)-1 || to==(Int4)-1){
			if (!DDV_CreateDisplayFromIndex_EX(sap,&mppl,LineSize,&ddo,
					(Int4)-1,(Int4)-1)){
				goto error;
			}
			/*see the 'Important note' 20 lines below*/
			if (AlnMgrIsSAPDiscAli(sap))
				sapLength = mppl.LengthAli;
			else
				sapLength=AlnMgrGetAlnLength(mppl.sap, FALSE);
			from=0;
			to=sapLength-1;
		}
		else{
			/*for a nice view, always start as a multiple of LETTER_BLOCK_WIDTH*/
			restdiv=from%LETTER_BLOCK_WIDTH;
			from=from-restdiv;
			/*right now, this function is able to build a display for master-
			slave as well as disc. align. But note that 'from,to' don't work
			for a disc seqalign. To allow that, it's necassary to update the
			function UABuildDescriptor() in ddvcreate.c*/
			if (!DDV_CreateDisplayFromIndex_EX(sap,&mppl,LineSize,&ddo,
					from,to)){
				goto error;
			}
			/*Important note : sapLength MUST be the full length of the SeqAlign.
			Example : you have a master-slave SeqAlign, 1000 letters long.
			from=25 and to=250. mppl->LengthAli will be 250-25+1 but 
			sapLength will be 1000.
			Because right now it's not possible to only display a small region
			of a disc. seqalign, mppl->LengthAli==sapLength. As soon as it'll
			be possible to use from,to for a disc align, the following if-then
			will have to be updated*/
			if (AlnMgrIsSAPDiscAli(sap))
				sapLength = mppl.LengthAli;
			else
				sapLength=AlnMgrGetAlnLength(mppl.sap, FALSE);
		}
		/*show by block ?*/
		if ((to-from+1)<sapLength) {
			numBlockAffich=from/LineSize+1;
		}		

		/*Create the display */
		if (disp_format&DISP_FASTA_GAP){/*gapped FASTA output*/
			DDV_GetFullGapFASTAforIdxAli(&mppl,fp);
		}
		else{/*HTML of Phylip output*/
			DDV_AffichageParaG(&mppl,gi,from,to,sapLength,numBlockAffich,disp_format,
				LineSize,fp,byteSpp,matrix,NULL,NULL);
		}

		/*done... delete data*/
		DDV_DeleteDisplayList(&mppl);
	}
error:
	/*if (sabp) CleanupBlocks(sabp);*/
	
	return(TRUE);
}

/*******************************************************************************

  Function : DDV_ReadSeqGivenSpp()
  
  Purpose : read a sequence buffer.
  
  Parameters : 	spp; open seqport
  				from-to; range to read
				strand; one of the Seq_strand_... (see objloc.h)
				IsAA; TRUE if the sequence is a protein
				bError; set to TRUE only if an error occurs when reading the seq.
				
  Return value : a buffer with the sequence 

*******************************************************************************/
NLM_EXTERN CharPtr DDV_ReadSeqGivenSpp(SeqPortPtr spp,Int4 from,Int4 to,Uint1 strand,
	Boolean IsAA,BoolPtr bError)
{
Int4 len,seek,i;
CharPtr szSeq=NULL;

Byte residue;

	if (!spp) return (NULL);
	if (from>to) return (NULL);

	len=to-from+1;
	szSeq=(CharPtr)MemNew((len+1)*sizeof(Char));		
	if (!szSeq) return (NULL);
	if(IsAA) {
		seek=from;
	} 
	else {
		if(strand == Seq_strand_minus)
			seek = to;
		else
			seek = from;
	}
	SeqPortSeek(spp, seek, SEEK_SET);
	for(i=0;i<len;i++){
		residue = SeqPortGetResidue(spp);
		if (residue!=SEQPORT_EOF && IS_residue(residue)) {
			szSeq[i] = (Char)residue;
		}
	}

	return(szSeq);
}


/*******************************************************************************

  Function : DDV_OpenBspFullSeqPort()
  
  Purpose : open a seqport of a full sequence.
  
  Parameters : 	bsp; bioseq (be sure it's locked)
				strand; one of the Seq_strand_... (see objloc.h)

  Return value : an open seqport 

*******************************************************************************/
NLM_EXTERN SeqPortPtr DDV_OpenBspFullSeqPort(BioseqPtr bsp,Uint1 strand)
{
SeqPortPtr spp;

	if (!bsp) return (NULL);
		
	if(bsp->mol!=Seq_mol_aa) {
    	spp= SeqPortNew(bsp, (Int4)0,(Int4) bsp->length-1, 
			strand, Seq_code_iupacna);
	}
	else {
    	spp= SeqPortNew(bsp, (Int4)0,(Int4) bsp->length-1, 
			0, Seq_code_ncbistdaa);
	}
	return(spp);
}

/*******************************************************************************

  Function : DDV_BspInfoNew()
  
  Purpose : BspInfo constructor.
  
  Parameters : 	InitInfo; TRUE means init the 'ascii' fields of BspInfo
  				InitSeqPort; TRUE means open a seqport
				sip; sequence identifier
				strand; one of the Seq_strand_... (see objloc.h)

  Return value : a pointer to an initialized BspInfo structure 

*******************************************************************************/
NLM_EXTERN BspInfoPtr DDV_BspInfoNew(Boolean InitInfo,Boolean InitSeqPort,SeqIdPtr sip,
		Uint1 strand)
{
BspInfoPtr bip;


	if (!sip) return(NULL);

	/*alloc*/
	bip=(BspInfoPtr)MemNew(sizeof(BspInfo));
	if (!bip) return(NULL);
	
	/*lock the bsp in memory*/
	bip->bsp=BioseqLockById(sip);
	if (!bip->bsp) return(NULL);
	bip->sip=sip;
	/*init Bsp info fields*/
	if (InitInfo){
		UDV_ReadBspDataForViewer(bip);
	}
	
	/*open the seqport on the full sequence*/
	if (InitSeqPort){
		bip->spp=DDV_OpenBspFullSeqPort(bip->bsp,strand);
	}
	
	return(bip);
}


/*******************************************************************************

  Function : DDV_BspInfoDelete()
  
  Purpose : BspInfo destructor.
  
  Parameters : 	bip; a pointer to an initialized BspInfo structure

  Return value : NULL, always 

*******************************************************************************/
NLM_EXTERN BspInfoPtr DDV_BspInfoDelete(BspInfoPtr bip)
{ 
	if(bip) {
		if (bip->spp) SeqPortFree(bip->spp);
		if (bip->bsp) BioseqUnlock(bip->bsp);
		if (bip->bspGeneticCode) MemFree(bip->bspGeneticCode);
		if (bip->SeqBuf) MemFree(bip->SeqBuf);
		MemFree(bip);
	}
	return(NULL);
}

/*******************************************************************************

  Function : DDV_BspInfoDeleteList()
  
  Purpose : BspInfo list destructor.
  
  Parameters : 	bip; a pointer to an initialized BspInfo structure

  Return value : NULL, always 

*******************************************************************************/
NLM_EXTERN BspInfoPtr DDV_BspInfoDeleteList(BspInfoPtr bip)
{
BspInfoPtr next;

	while (bip != NULL){
		next = bip->next;
		DDV_BspInfoDelete(bip);
		bip = next;
	}
	return(NULL);
}

/*******************************************************************************

  Function : DDV_LocateParaG()
  
  Purpose : compute StartLine valies for PGP in a Full Horz display style 
  
  Parameters : -
  
  Return value : -

*******************************************************************************/
NLM_EXTERN void DDV_LocateParaG(ValNodePtr PNTR TableHead,Int4 nBsp)
{
ParaGPtr pgp;
Int4 StartLine=0,StartLine2=0,i;
ValNodePtr vnp;
Boolean bFirst;
	
	if (TableHead==NULL || nBsp==0) return;
	
	for(i=0;i<nBsp;i++){
		StartLine=StartLine2;
		bFirst=TRUE;
		for(vnp=TableHead[i];vnp!=NULL;vnp=vnp->next){
			pgp=(ParaGPtr)(vnp->data.ptrvalue);
			if (pgp){
				pgp->StartLine=StartLine;
				if (bFirst) {
					StartLine2+=pgp->nLines;
					bFirst=FALSE;
				}
			}
		}
	}	
}

/*******************************************************************************

  Function : DDV_CreateDisplay()
  
  Purpose : create a display for DDV panel.
  
  Parameters : 	sap; seqalign
				mpplp; allocated structure filled here

  Return value : TRUE if success

*******************************************************************************/
NLM_EXTERN Boolean DDV_CreateDisplay(SeqAlignPtr sap,MsaParaGPopListPtr mpplp)
{
Int4 numBlocks;
Boolean nRet;

	if (!sap) return(FALSE);

	/*build the indexed SeqAlign*/
	mpplp->sabp=Blockify(sap);
	if (!mpplp->sabp) return(FALSE);

	/*retrieve the size of the alignment*/
	GetBlockInfo(mpplp->sabp, &mpplp->LengthAli, &mpplp->nBsp,&numBlocks,NULL);
	
	/*build the ParaG list for the display*/
	nRet=DDV_PopDisplay2(mpplp->sabp,mpplp,mpplp->nBsp,SCALE_POS_NONE,
			TRUE,ParaG_Size,numBlocks,0,mpplp->LengthAli-1);

	DDV_LocateParaG(mpplp->TableHead,mpplp->nBsp);
	
	return(nRet);
}

NLM_EXTERN Boolean DDV_ShowSeqAlign(SeqAlignPtr seqalign, Int4 gi, Int4 from, Int4 to,
                         Uint4 disp_format)
{
    
    SABlockPtr sabp;       /* indexed SeqAlign */
    Int4  sapLength, sapNumBioseqs, numBlocks;/* indexed SeqAlign size */
    Int4  restdiv;         /* used to modify the udp->from value */
    MsaParaGPopList mppl;  /* contains the data for the display */
    Char szPopSetName[INFO_SIZE+1]={""};/*article title of the Pop-Set*/
    /*article first author name of the Pop-Set*/    
    Char szPopSetAuth[INFO_SIZE+1]={""};
    Int4 numBlockAffich=0;
    
    /*seqalign = PairSeqAlign2MultiSeqAlign(seqalign);*/
    
    /*build the indexed SeqAlign*/
    if((sabp = Blockify(seqalign)) == NULL) {
        printf("Error No. 54. Could not show align");
        return FALSE;
    }
    
    /*retrieve the size of the alignment*/
    GetBlockInfo(sabp, &sapLength, &sapNumBioseqs,&numBlocks,NULL);
    
    if (disp_format & DISP_FASTA_NOGAP){ /*don't need a ParaG structure*/
        DDV_GetFullFASTAforIdxAli(seqalign, stdout);
    } 
	else {   /* HTML, gapped FASTA and Phylip : 
		need to create the ParaG structure */
        /* for a nice view, always start as a multiple of LETTER_BLOCK_WIDTH */
        restdiv = from % LETTER_BLOCK_WIDTH;
        from = from-restdiv;
        
        /*user didn't give from-to; from=0 and to=sapLength-1*/
        if (to < 1) to = sapLength-1;
        
        /*some security*/
        
        if (from >= to) 
            return FALSE;
        
        if (from < 0 || to < 0) 
            return FALSE;
        
        /* build the ParaG list for the display */
        DDV_PopDisplay2(sabp, &mppl, sapNumBioseqs, SCALE_POS_TOP,
                        TRUE, ParaG_Size, numBlocks, from, to);
        
        /*show by block ?*/
        if ((to - from + 1) < sapLength) {
            numBlockAffich = from/ParaG_Size+1;
        }	
                
		if (disp_format&DISP_FASTA_GAP){/*gapped FASTA output*/
			DDV_GetFullGapFASTAforIdxAli(&mppl,stdout);
		}
        /*Create the HTML display for the Population division*/
		else{/*HTML of Phylip output*/
	        DDV_AffichageParaG(&mppl, gi, from, to, sapLength,
            numBlockAffich, disp_format, ParaG_Size,stdout,NULL,NULL,NULL,NULL);
		}
        /*done... delete data*/
        DDV_DeleteDisplayList(&mppl);
    }
    
    if (sabp) CleanupBlocks(sabp);
    
    return TRUE;
}

/*******************************************************************************

  Function : DDV_SearchAli()
  
  Purpose : callback of SeqEntryExplore from  DDV_GetSeqAlign()
  
  Parameters : see toolkit code...
  
  Return value : none 

*******************************************************************************/
NLM_EXTERN void DDV_SearchAli(SeqEntryPtr sep, Pointer mydata, Int4 index, Int2 indent)
{
ValNodePtr PNTR	vnpp;
BioseqPtr     bsp;
BioseqSetPtr  bssp;
SeqAnnotPtr   sap,sap2;
SeqAlignPtr   salp;

	vnpp=(ValNodePtr PNTR)mydata;
	
	/*Bioseq or BioseqSet ?... the SeqAlign (if any) is in the seqannot part*/
	if (IS_Bioseq (sep)) {
		bsp = (BioseqPtr) sep->data.ptrvalue;
		sap = bsp->annot;
	} else if (IS_Bioseq_set (sep)) {
		bssp = (BioseqSetPtr) sep->data.ptrvalue;
		sap = bssp->annot;
	} else return;
	sap2=sap;
	while (sap2 != NULL) {
		if (sap2->type == 2) {/*seqalign*/
			salp=(SeqAlignPtr)sap2->data;
			while(salp){
				if (!(*vnpp)) *vnpp=ValNodeAddPointer(NULL,OBJ_SEQALIGN,(Pointer)salp);
				else ValNodeAddPointer(vnpp,OBJ_SEQALIGN,(Pointer)salp);
				salp=salp->next;
			}
		}
		sap2=sap2->next;
	}
}

/*******************************************************************************

  Function : DDV_GetSeqAlign()
  
  Purpose : given dataptr and datatype, look for any SeqAligns
  
  Parameters : dataptr; the data to analyse
  				datatype; OBJ_BIOSEQ,OBJ_SEQENTRY, etc.
				vnp; filled here. data.ptrvalue == SeqALignPtr
  
  Return value : none 

*******************************************************************************/
NLM_EXTERN void DDV_GetSeqAlign(Pointer dataptr,Uint2 datatype,
		ValNodePtr PNTR vnp)
{
BioseqPtr     bsp;
BioseqSetPtr  bssp;
SeqEntryPtr   sep;
SeqAnnotPtr   sap;

	if(datatype==OBJ_SEQENTRY){
		SeqEntryExplore((SeqEntryPtr)dataptr,(Pointer) vnp,DDV_SearchAli);
	} 
	else if(datatype==OBJ_BIOSEQ || datatype==OBJ_BIOSEQSET){
		/*create a seqentry; then explore it*/
		sep = SeqEntryNew ();
		if (sep != NULL) {
			if (datatype == OBJ_BIOSEQ) {
				bsp = (BioseqPtr) dataptr;
				sep->choice = 1;
				sep->data.ptrvalue = bsp;
			} else if (datatype == OBJ_BIOSEQSET) {
				bssp = (BioseqSetPtr) dataptr;
				sep->choice = 2;
				sep->data.ptrvalue = bssp;
			}
			SeqEntryExplore(sep,(Pointer) vnp,DDV_SearchAli);
			SeqEntryFree (sep);
		}
	}
	else if(datatype==OBJ_SEQALIGN){
		ValNodeAddPointer(vnp,OBJ_SEQALIGN,(SeqAlignPtr)dataptr);
	}
	else if(datatype==OBJ_SEQANNOT){
		sap=(SeqAnnotPtr)dataptr;
		while (sap != NULL) {
			if (sap->type == 2) {/*seqalign*/
				ValNodeAddPointer(vnp,OBJ_SEQALIGN,sap->data);
			}
			sap=sap->next;
		}
	}
}

/*******************************************************************************

  Function : DDV_PrintPopSetSummary()
  
  Purpose : display a summary for a PopSet entry
  
*******************************************************************************/
NLM_EXTERN void DDV_PrintPopSetSummary(SeqEntryPtr sep, Int4 gi, FILE *FileOut)
{
ValNodePtr  vnp_sap,vnp_biosrc,vnp_biosrc2,vnp,vnp2;
SeqAlignPtr sap;
Int4		sapLength, sapNumBioseqs;
Uint2	    i;	
Boolean bPairwise=TRUE,bPrintTax,bPrintCom;
Uint4 disp_format;
PopSourcePtr psp,psp2;

	disp_format=RULER_TOP;
	disp_format|=RULER_TICK;
	disp_format|=DISPE_SHOWBLOCK;
	disp_format|=VIEW_FULLSEQ;
	disp_format|=DISP_FULL_HTML;
	disp_format|=DISP_ORDER_NUM; 
	disp_format|=DISP_STRAND;
	disp_format|=DISP_BSP_COORD;

	/*scan the SeqEntry and get all the SeqALigns*/
	vnp_sap=NULL;
	DDV_GetSeqAlign((Pointer) sep, OBJ_SEQENTRY, &vnp_sap);

	/*scan the SeqEntry and get all the biosources*/
	vnp_biosrc=NULL;
	SeqEntryExplore(sep,(Pointer) &vnp_biosrc,SearchBioSource);

	fprintf(FileOut,"<UL>\n");

	/*summary of biosource; if a name occurs several times, display only once*/
	if (vnp_biosrc){
		vnp_biosrc2=NULL;
		vnp=vnp_biosrc;
		fprintf(FileOut,"<B>Source of the sequences : </B><BR><UL>");
		while(vnp){
			psp=(PopSourcePtr)vnp->data.ptrvalue;
			if (psp->szTaxName) bPrintTax=TRUE;
			else bPrintTax=FALSE;
			if (psp->szCommonName) bPrintCom=TRUE;
			else bPrintCom=FALSE;
			if (bPrintTax || bPrintCom){
				if (vnp_biosrc2){
					vnp2=vnp_biosrc2;
					while(vnp2){
						psp2=(PopSourcePtr)vnp2->data.ptrvalue;
						if (psp->szTaxName && psp2->szTaxName){
							if (!StringCmp(psp->szTaxName,psp2->szTaxName)) bPrintTax=FALSE;
						}
						if (psp->szCommonName && psp2->szCommonName){
							if (!StringCmp(psp->szCommonName,psp2->szCommonName)) bPrintCom=FALSE;
						}
						vnp2=vnp2->next;
					}
					if (bPrintTax || bPrintCom){
						fprintf(FileOut,", \n");
						ValNodeAddPointer(&vnp_biosrc2,0,(Pointer)psp);
					}
				}
				else{
					vnp_biosrc2=ValNodeAddPointer(NULL,0,(Pointer)psp);
				}
				if (bPrintTax && bPrintCom){
					fprintf(FileOut,"%s (%s)",psp->szTaxName,psp->szCommonName);
				}
				else if (bPrintTax && !bPrintCom){
					fprintf(FileOut,"%s",psp->szTaxName);
				}
				else if (!bPrintTax && bPrintCom){
					fprintf(FileOut,"%s",psp->szCommonName);
				}
			}
			vnp=vnp->next;
		}
		fprintf(FileOut,".<BR></UL>\n");
		ValNodeFreeData(vnp_biosrc);
		if (vnp_biosrc2) ValNodeFreeData(vnp_biosrc2);
	}
	
	fprintf(FileOut,"<B>Content :</B><BR><BR><UL>\n");
	/*scan vnp_sap and display the summary for SeqAlign*/
	if(vnp_sap){
		i=0;
		vnp=vnp_sap;
		fprintf(FileOut,"<B>List of sequence alignment(s) : </B><BR><UL>");
		while(vnp){
			/*get a SeqAlign*/
			sap = (SeqAlignPtr) vnp->data.ptrvalue;			
			/*build the indexed SeqAlign*/
			AlnMgrIndexSeqAlign(sap);
			/*retrieve the size of the alignment*/
			sapLength=AlnMgrGetAlnLength(sap, FALSE);
			sapNumBioseqs=AlnMgrGetNumRows(sap);
			if (sapNumBioseqs>2) 
				bPairwise=FALSE;
			fprintf(FileOut,"Sequence Alignment no. %i : %i sequences, %i letters ",
					i+1,sapNumBioseqs,sapLength);
			if (gi!=0) {
				fprintf(FileOut," (<a href=\"wwwddv.cgi?gi=%i\">Text view</a>).",gi);
			}
			fprintf(FileOut,"<BR>\n");
			vnp=vnp->next;i++;
		}

		fprintf(FileOut,"<BR></UL>\n");
		ValNodeFree(vnp_sap);
	}
	else{/*summary if no SeqAlign*/
		
		fprintf(FileOut,"This entry contains no sequence alignment.<BR>");
		if (gi!=0) {
			fprintf(FileOut,"Yan can either :<BR><BR>");
			fprintf(FileOut,"<a href=\"wwwddv.cgi?gi=%i\"",gi);
			fprintf(FileOut," onMouseOut=\"window.status='';return true\" \
onMouseOver=\"window.status='Click to see the list of sequences'; return true\" >");
			fprintf(FileOut,"- view the list of sequences</a>, or <BR>\n");
		}
	}
	fprintf(FileOut,"</UL></UL>\n");
}

/**************************************************************
***************************************************************
COLOMBE FOR KARL 
***************************************************************
***************************************************************/

NLM_EXTERN void PrintSeqAlignCallback (SeqEntryPtr sep, Pointer mydata,
                                   Int4 index, Int2 indent)
{
  BioseqPtr          bsp;
  BioseqSetPtr       bssp;
  SeqAnnotPtr        sap;
  SeqAlignPtr        salp,salp2;
  Uint4              option = 0;
  DDVOptionsBlockPtr dobp = (DDVOptionsBlockPtr) mydata;
  
  if (sep != NULL && sep->data.ptrvalue)
  {
     option = RULER_TOP;
     option|=DISPE_SHOWBLOCK;
     option|=VIEW_VARIA;
     option|=DISP_FULL_TXT;
     option|=DISP_STRAND;
     option|=DISP_BSP_COORD;

     if (IS_Bioseq(sep))
     {
        bsp = (BioseqPtr) sep->data.ptrvalue;
        if (bsp!=NULL) {
           for (sap=bsp->annot;sap!=NULL;sap=sap->next)
           {
              if (sap->type == 2) {
                 salp = (SeqAlignPtr)sap->data;
                 salp2 = PairSeqAlign2MultiSeqAlign (salp);
                 if (salp2==NULL) {
                    salp2 = (SeqAlignPtr) AsnIoMemCopy (salp, (AsnReadFunc) SeqAlignAsnRead, (AsnWriteFunc) SeqAlignAsnWrite);   
                 }
                 DDV_DisplayDefaultAlign (salp2, 0, -1,-1, option, dobp, NULL);
                 SeqAlignSetFree(salp2);
                 BSWrite(*(dobp ->byteSpp),"\n//\n",4);
              }
           }
        }
     }
     else if(IS_Bioseq_set(sep)) {
        bssp = (BioseqSetPtr)sep->data.ptrvalue;
        if (bssp!=NULL) {
           for (sap=bssp->annot;sap!=NULL;sap=sap->next)
           {
              if (sap->type == 2) {
                 salp = (SeqAlignPtr)sap->data;
                 salp2 = PairSeqAlign2MultiSeqAlign (salp);
                 if (salp2==NULL) {
                    salp2 = (SeqAlignPtr) AsnIoMemCopy (salp, (AsnReadFunc) SeqAlignAsnRead, (AsnWriteFunc) SeqAlignAsnWrite);   
                 }
                 DDV_DisplayDefaultAlign (salp2, 0, -1,-1, option, dobp, NULL);
                 SeqAlignSetFree(salp2);
                 BSWrite(*(dobp ->byteSpp),"\n//\n",4);
              }
           }
        }
     }
  }
}

NLM_EXTERN ByteStorePtr SeqAlignToBS (Uint2 entityID)
{{
  SeqEntryPtr sep;
  ByteStorePtr bsp = NULL;
  DDVOptionsBlockPtr dobp=MemNew(sizeof (DDVOptionsBlock));

  dobp->LineSize=50; 
  dobp->byteSpp = & bsp;
  sep = GetTopSeqEntryForEntityID (entityID);
  if (sep) {
     SeqEntryExplore (sep, (Pointer)dobp, PrintSeqAlignCallback);
  }
  dobp->byteSpp=NULL;
  MemFree(dobp);
  return bsp;
}}


NLM_EXTERN DDVRulerDescrPtr DDV_RulerDescrNew(DDVRulerDescrPtr pRulerDescr) {
/*******************************************************************************
*
*  make a copy of RulerDescr.
*  return pointer to new RulerDescr.
*
*******************************************************************************/
  DDVRulerDescrPtr  pCopy;

  pCopy = MemNew(sizeof(DDVRulerDescr));
  ASSERT(pCopy != NULL);
  MemCopy(pCopy, pRulerDescr, sizeof(DDVRulerDescr));
  return(pCopy);
}


NLM_EXTERN DDVRulerDescrPtr DDV_RulerDescrFree(DDVRulerDescrPtr pRulerDescr) {
/*******************************************************************************
*
*  free memory used for RulerDescr.
*  returns NULL for successful completion.
*
*******************************************************************************/
  VERIFY(MemFree(pRulerDescr) == NULL);
  return(NULL);
}

/****/