This file is indexed.

/usr/share/perl5/Bio/SearchIO/blast.pm is in libbio-perl-perl 1.6.924-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
#
# BioPerl module for Bio::SearchIO::blast
#
# Please direct questions and support issues to <bioperl-l@bioperl.org>
#
# Cared for by Jason Stajich <jason@bioperl.org>
#
# Copyright Jason Stajich
#
# You may distribute this module under the same terms as perl itself

# POD documentation - main docs before the code

# 20030409 - sac
#          PSI-BLAST full parsing support. Rollout of new
#          model which will remove Steve's old psiblast driver
# 20030424 - jason
#          Megablast parsing fix as reported by Neil Saunders
# 20030427 - jason
#          Support bl2seq parsing
# 20031124 - jason
#          Parse more blast statistics, lambda, entropy, etc
#          from WU-BLAST in frame-specific manner
# 20060216 - cjf - fixed blast parsing for BLAST v2.2.13 output
# 20071104 - dmessina - added support for WUBLAST -echofilter
# 20071121 - cjf - fixed several bugs (bugs 2391, 2399, 2409)

=head1 NAME

Bio::SearchIO::blast - Event generator for event based parsing of
blast reports

=head1 SYNOPSIS

   # Do not use this object directly - it is used as part of the
   # Bio::SearchIO system.

    use Bio::SearchIO;
    my $searchio = Bio::SearchIO->new(-format => 'blast',
                                     -file   => 't/data/ecolitst.bls');
    while( my $result = $searchio->next_result ) {
        while( my $hit = $result->next_hit ) {
            while( my $hsp = $hit->next_hsp ) {
                # ...
            }
        }
    }

=head1 DESCRIPTION

This object encapsulated the necessary methods for generating events
suitable for building Bio::Search objects from a BLAST report file.
Read the L<Bio::SearchIO> for more information about how to use this.

This driver can parse:

=over 4

=item *

NCBI produced plain text BLAST reports from blastall, this also
includes PSIBLAST, PSITBLASTN, RPSBLAST, and bl2seq reports.  NCBI XML
BLAST output is parsed with the blastxml SearchIO driver

=item *

WU-BLAST all reports

=item *

Jim Kent's BLAST-like output from his programs (BLASTZ, BLAT)

=item *

BLAST-like output from Paracel BTK output

=back

=head2 bl2seq parsing

Since I cannot differentiate between BLASTX and TBLASTN since bl2seq
doesn't report the algorithm used - I assume it is BLASTX by default -
you can supply the program type with -report_type in the SearchIO
constructor i.e.

  my $parser = Bio::SearchIO->new(-format => 'blast',
                                 -file => 'bl2seq.tblastn.report',
                                 -report_type => 'tblastn');

This only really affects where the frame and strand information are
put - they will always be on the $hsp-E<gt>query instead of on the
$hsp-E<gt>hit part of the feature pair for blastx and tblastn bl2seq
produced reports.  Hope that's clear...

=head1 FEEDBACK

=head2 Mailing Lists

User feedback is an integral part of the evolution of this and other
Bioperl modules. Send your comments and suggestions preferably to
the Bioperl mailing list.  Your participation is much appreciated.

  bioperl-l@bioperl.org                  - General discussion
  http://bioperl.org/wiki/Mailing_lists  - About the mailing lists

=head2 Support

Please direct usage questions or support issues to the mailing list:

I<bioperl-l@bioperl.org>

rather than to the module maintainer directly. Many experienced and
reponsive experts will be able look at the problem and quickly
address it. Please include a thorough description of the problem
with code and data examples if at all possible.

=head2 Reporting Bugs

Report bugs to the Bioperl bug tracking system to help us keep track
of the bugs and their resolution. Bug reports can be submitted via the
web:

  https://github.com/bioperl/bioperl-live/issues

=head1 AUTHOR - Jason Stajich

Email Jason Stajich jason-at-bioperl.org

=head1 CONTRIBUTORS

Steve Chervitz sac-at-bioperl.org

=head1 APPENDIX

The rest of the documentation details each of the object methods.
Internal methods are usually preceded with a _

=cut

# Let the code begin...'

package Bio::SearchIO::blast;

use Bio::SearchIO::IteratedSearchResultEventBuilder;
use strict;
use vars qw(%MAPPING %MODEMAP
  $DEFAULT_BLAST_WRITER_CLASS
  $MAX_HSP_OVERLAP
  $DEFAULT_SIGNIF
  $DEFAULT_SCORE
  $DEFAULTREPORTTYPE
);


use base qw(Bio::SearchIO);
use Data::Dumper;

BEGIN {

    # mapping of NCBI Blast terms to Bioperl hash keys
    %MODEMAP = (
        'BlastOutput' => 'result',
        'Iteration'   => 'iteration',
        'Hit'         => 'hit',
        'Hsp'         => 'hsp'
    );

    # This should really be done more intelligently, like with
    # XSLT

    %MAPPING = (
        'Hsp_bit-score'   => 'HSP-bits',
        'Hsp_score'       => 'HSP-score',
        'Hsp_evalue'      => 'HSP-evalue',
        'Hsp_n',          => 'HSP-n',
        'Hsp_pvalue'      => 'HSP-pvalue',
        'Hsp_query-from'  => 'HSP-query_start',
        'Hsp_query-to'    => 'HSP-query_end',
        'Hsp_hit-from'    => 'HSP-hit_start',
        'Hsp_hit-to'      => 'HSP-hit_end',
        'Hsp_positive'    => 'HSP-conserved',
        'Hsp_identity'    => 'HSP-identical',
        'Hsp_gaps'        => 'HSP-hsp_gaps',
        'Hsp_hitgaps'     => 'HSP-hit_gaps',
        'Hsp_querygaps'   => 'HSP-query_gaps',
        'Hsp_qseq'        => 'HSP-query_seq',
        'Hsp_hseq'        => 'HSP-hit_seq',
        'Hsp_midline'     => 'HSP-homology_seq',
        'Hsp_align-len'   => 'HSP-hsp_length',
        'Hsp_query-frame' => 'HSP-query_frame',
        'Hsp_hit-frame'   => 'HSP-hit_frame',
        'Hsp_links'       => 'HSP-links',
        'Hsp_group'       => 'HSP-hsp_group',
        'Hsp_features'    => 'HSP-hit_features',

        'Hit_id'        => 'HIT-name',
        'Hit_len'       => 'HIT-length',
        'Hit_accession' => 'HIT-accession',
        'Hit_def'       => 'HIT-description',
        'Hit_signif'    => 'HIT-significance',
        # For NCBI blast, the description line contains bits.
        # For WU-blast, the  description line contains score.
        'Hit_score' => 'HIT-score',
        'Hit_bits'  => 'HIT-bits',

        'Iteration_iter-num'  => 'ITERATION-number',
        'Iteration_converged' => 'ITERATION-converged',

        'BlastOutput_program'             => 'RESULT-algorithm_name',
        'BlastOutput_version'             => 'RESULT-algorithm_version',
        'BlastOutput_algorithm-reference' => 'RESULT-algorithm_reference',
        'BlastOutput_rid'                 => 'RESULT-rid',
        'BlastOutput_query-def'           => 'RESULT-query_name',
        'BlastOutput_query-len'           => 'RESULT-query_length',
        'BlastOutput_query-acc'           => 'RESULT-query_accession',
        'BlastOutput_query-gi'            => 'RESULT-query_gi',
        'BlastOutput_querydesc'           => 'RESULT-query_description',
        'BlastOutput_db'                  => 'RESULT-database_name',
        'BlastOutput_db-len'              => 'RESULT-database_entries',
        'BlastOutput_db-let'              => 'RESULT-database_letters',
        'BlastOutput_inclusion-threshold' => 'RESULT-inclusion_threshold',

        'Parameters_matrix'      => { 'RESULT-parameters' => 'matrix' },
        'Parameters_expect'      => { 'RESULT-parameters' => 'expect' },
        'Parameters_include'     => { 'RESULT-parameters' => 'include' },
        'Parameters_sc-match'    => { 'RESULT-parameters' => 'match' },
        'Parameters_sc-mismatch' => { 'RESULT-parameters' => 'mismatch' },
        'Parameters_gap-open'    => { 'RESULT-parameters' => 'gapopen' },
        'Parameters_gap-extend'  => { 'RESULT-parameters' => 'gapext' },
        'Parameters_filter'      => { 'RESULT-parameters' => 'filter' },
        'Parameters_allowgaps'   => { 'RESULT-parameters' => 'allowgaps' },
        'Parameters_full_dbpath' => { 'RESULT-parameters' => 'full_dbpath' },
        'Statistics_db-len'      => { 'RESULT-statistics' => 'dbentries' },
        'Statistics_db-let'      => { 'RESULT-statistics' => 'dbletters' },
        'Statistics_hsp-len'     =>
          { 'RESULT-statistics' => 'effective_hsplength' },
        'Statistics_query-len' => { 'RESULT-statistics' => 'querylength' },
        'Statistics_eff-space' => { 'RESULT-statistics' => 'effectivespace' },
        'Statistics_eff-spaceused' =>
          { 'RESULT-statistics' => 'effectivespaceused' },
        'Statistics_eff-dblen' =>
          { 'RESULT-statistics' => 'effectivedblength' },
        'Statistics_kappa'         => { 'RESULT-statistics' => 'kappa' },
        'Statistics_lambda'        => { 'RESULT-statistics' => 'lambda' },
        'Statistics_entropy'       => { 'RESULT-statistics' => 'entropy' },
        'Statistics_gapped_kappa'  => { 'RESULT-statistics' => 'kappa_gapped' },
        'Statistics_gapped_lambda' =>
          { 'RESULT-statistics' => 'lambda_gapped' },
        'Statistics_gapped_entropy' =>
          { 'RESULT-statistics' => 'entropy_gapped' },

        'Statistics_framewindow' =>
          { 'RESULT-statistics' => 'frameshiftwindow' },
        'Statistics_decay' => { 'RESULT-statistics' => 'decayconst' },

        'Statistics_hit_to_db' => { 'RESULT-statistics' => 'Hits_to_DB' },
        'Statistics_num_suc_extensions' =>
          { 'RESULT-statistics' => 'num_successful_extensions' },
        'Statistics_length_adjustment' => { 'RESULT-statistics' => 'length_adjustment' },
        'Statistics_number_of_hsps_better_than_expect_value_cutoff_without_gapping' =>
          { 'RESULT-statistics' => 'number_of_hsps_better_than_expect_value_cutoff_without_gapping' },
        'Statistics_number_of_hsps_gapped' => { 'RESULT-statistics' => 'number_of_hsps_gapped' },
        'Statistics_number_of_hsps_successfully_gapped' => { 'RESULT-statistics' => 'number_of_hsps_successfully_gapped' },

        # WU-BLAST stats
        'Statistics_DFA_states' => { 'RESULT-statistics' => 'num_dfa_states' },
        'Statistics_DFA_size'   => { 'RESULT-statistics' => 'dfa_size' },
        'Statistics_noprocessors' =>
          { 'RESULT-statistics' => 'no_of_processors' },
        'Statistics_neighbortime' =>
          { 'RESULT-statistics' => 'neighborhood_generate_time' },
        'Statistics_starttime' => { 'RESULT-statistics' => 'start_time' },
        'Statistics_endtime'   => { 'RESULT-statistics' => 'end_time' },
    );

    # add WU-BLAST Frame-Based Statistics
    for my $frame ( 0 .. 3 ) {
        for my $strand ( '+', '-' ) {
            for my $ind (
                qw(length efflength E S W T X X_gapped E2
                E2_gapped S2)
              )
            {
                $MAPPING{"Statistics_frame$strand$frame\_$ind"} =
                  { 'RESULT-statistics' => "Frame$strand$frame\_$ind" };
            }
            for my $val (qw(lambda kappa entropy )) {
                for my $type (qw(used computed gapped)) {
                    my $key = "Statistics_frame$strand$frame\_$val\_$type";
                    my $val =
                      { 'RESULT-statistics' =>
                          "Frame$strand$frame\_$val\_$type" };
                    $MAPPING{$key} = $val;
                }
            }
        }
    }

    # add Statistics
    for my $stats (
        qw(T A X1 X2 X3 S1 S2 X1_bits X2_bits X3_bits
        S1_bits S2_bits  num_extensions
        num_successful_extensions
        seqs_better_than_cutoff
        posted_date
        search_cputime total_cputime
        search_actualtime total_actualtime
        no_of_processors ctxfactor)
      )
    {
        my $key = "Statistics_$stats";
        my $val = { 'RESULT-statistics' => $stats };
        $MAPPING{$key} = $val;
    }

    # add WU-BLAST Parameters
    for my $param (
        qw(span span1 span2 links warnings notes hspsepsmax
        hspsepqmax topcomboN topcomboE postsw cpus wordmask
        filter sort_by_pvalue sort_by_count sort_by_highscore
        sort_by_totalscore sort_by_subjectlength noseqs gi qtype
        qres V B Z Y M N)
      )
    {
        my $key = "Parameters_$param";
        my $val = { 'RESULT-parameters' => $param };
        $MAPPING{$key} = $val;
    }

    $DEFAULT_BLAST_WRITER_CLASS = 'Bio::SearchIO::Writer::HitTableWriter';
    $MAX_HSP_OVERLAP   = 2;           # Used when tiling multiple HSPs.
    $DEFAULTREPORTTYPE = 'BLASTP';    # for bl2seq
}

=head2 new

 Title   : new
 Usage   : my $obj = Bio::SearchIO::blast->new(%args);
 Function: Builds a new Bio::SearchIO::blast object
 Returns : Bio::SearchIO::blast
 Args    : Key-value pairs:
           -fh/-file => filehandle/filename to BLAST file
           -format   => 'blast'
           -report_type => 'blastx', 'tblastn', etc -- only for bl2seq
                           reports when you want to distinguish between
                           tblastn and blastx reports (this only controls
                           where the frame information is put - on the query
                           or subject object.
           -inclusion_threshold => e-value threshold for inclusion in the
                                   PSI-BLAST score matrix model (blastpgp)
           -signif      => float or scientific notation number to be used
                           as a P- or Expect value cutoff
           -score       => integer or scientific notation number to be used
                           as a blast score value cutoff
           -bits        => integer or scientific notation number to be used
                           as a bit score value cutoff
           -hit_filter  => reference to a function to be used for
                           filtering hits based on arbitrary criteria.
                           All hits of each BLAST report must satisfy
                           this criteria to be retained.
                           If a hit fails this test, it is ignored.
                           This function should take a
                           Bio::Search::Hit::BlastHit.pm object as its first
                           argument and return true
                           if the hit should be retained.
                           Sample filter function:
                              -hit_filter => sub { $hit = shift;
                                                   $hit->gaps == 0; },
                           (Note: -filt_func is synonymous with -hit_filter)
           -overlap     => integer. The amount of overlap to permit between
                           adjacent HSPs when tiling HSPs. A reasonable value is 2.
                           Default = $Bio::SearchIO::blast::MAX_HSP_OVERLAP.

            The following criteria are not yet supported:
            (these are probably best applied within this module rather than in the
             event handler since they would permit the parser to take some shortcuts.)

           -check_all_hits => boolean. Check all hits for significance against
                              significance criteria.  Default = false.
                              If false, stops processing hits after the first
                              non-significant hit or the first hit that fails
                              the hit_filter call. This speeds parsing,
                              taking advantage of the fact that the hits
                              are processed in the order they appear in the report.
           -min_query_len => integer to be used as a minimum for query sequence length.
                             Reports with query sequences below this length will
                             not be processed. Default = no minimum length.
           -best        => boolean. Only process the best hit of each report;
                           default = false.

=cut

sub _initialize {
    my ( $self, @args ) = @_;
    $self->SUPER::_initialize(@args);

    # Blast reports require a specialized version of the SREB due to the
    # possibility of iterations (PSI-BLAST). Forwarding all arguments to it. An
    # issue here is that we want to set new default object factories if none are
    # supplied.

    my $handler = Bio::SearchIO::IteratedSearchResultEventBuilder->new(@args);
    $self->attach_EventHandler($handler);

    # 2006-04-26 move this to the attach_handler function in this module so we
    # can really reset the handler
    # Optimization: caching
    # the EventHandler since it is used a lot during the parse.

    # $self->{'_handler_cache'} = $handler;

    my ($rpttype ) = $self->_rearrange(
        [
            qw(
              REPORT_TYPE)
        ],
        @args
    );
    defined $rpttype   && ( $self->{'_reporttype'} = $rpttype );
}

sub attach_EventHandler {
    my ($self,$handler) = @_;

    $self->SUPER::attach_EventHandler($handler);

    # Optimization: caching the EventHandler since it is used a lot
    # during the parse.

    $self->{'_handler_cache'} = $handler;
    return;
}

=head2 next_result

 Title   : next_result
 Usage   : my $hit = $searchio->next_result;
 Function: Returns the next Result from a search
 Returns : Bio::Search::Result::ResultI object
 Args    : none

=cut

sub next_result {
    my ($self) = @_;
    my $v      = $self->verbose;
    my $data   = '';
    my $flavor = '';
    $self->{'_seentop'} = 0;     # start next report at top

    my ( $reporttype, $seenquery, $reportline, $reportversion );
    my ( $seeniteration, $found_again );
    my $incl_threshold = $self->inclusion_threshold;
    my $bl2seq_fix;
    $self->start_document();  # let the fun begin...
    my (@hit_signifs);
    my $gapped_stats = 0;    # for switching between gapped/ungapped
                             # lambda, K, H
    local $_ = "\n";   #consistency
    PARSER:
    while ( defined( $_ = $self->_readline ) ) {
        next if (/^\s+$/);       # skip empty lines
        next if (/CPU time:/);
        next if (/^>\s*$/);
        next if (/[*]+\s+No hits found\s+[*]+/);
        if (
               /^((?:\S+?)?BLAST[NPX]?)\s+(.+)$/i  # NCBI BLAST, PSIBLAST
                                                   # RPSBLAST, MEGABLAST
            || /^(P?GENEWISE|HFRAME|SWN|TSWN)\s+(.+)/i    #Paracel BTK
          )
        {
            ($reporttype, $reportversion) = ($1, $2);
            # need to keep track of whether this is WU-BLAST
            if ($reportversion && $reportversion =~ m{WashU$}) {
                $self->{'_wublast'}++;
            }
            $self->debug("blast.pm: Start of new report: $reporttype, $reportversion\n");
            if ( $self->{'_seentop'} ) {
                # This handles multi-result input streams
                $self->_pushback($_);
                last PARSER;
            }
            $self->_start_blastoutput;
            if ($reporttype =~ /RPS-BLAST/) {
                $reporttype .= '(BLASTP)'; # default RPS-BLAST type
            }
            $reportline = $_;   # to fix the fact that RPS-BLAST output is wrong
            $self->element(
                {
                    'Name' => 'BlastOutput_program',
                    'Data' => $reporttype
                }
            );

            $self->element(
                {
                    'Name' => 'BlastOutput_version',
                    'Data' => $reportversion
                }
            );
            $self->element(
                {
                    'Name' => 'BlastOutput_inclusion-threshold',
                    'Data' => $incl_threshold
                }
            );
        }
        # parse the BLAST algorithm reference
        elsif(/^Reference:\s+(.*)$/) {
            # want to preserve newlines for the BLAST algorithm reference
            my $algorithm_reference = "$1\n";
            $_ = $self->_readline;
            # while the current line, does not match an empty line, a RID:, a
            # Database:, or a query definition line (Query=) we are still
            # looking at the algorithm_reference, append it to what we parsed so
            # far
            while($_ !~ /^$/ && $_ !~ /^RID:/ && $_ !~ /^Database:/ && $_ !~ /^Query=/) {
                $algorithm_reference .= "$_";
                $_ = $self->_readline;
            }
            # if we exited the while loop, we saw an empty line, a RID:, or a
            # Database:, so push it back
            $self->_pushback($_);
            $self->element(
                {
                    'Name' => 'BlastOutput_algorithm-reference',
                    'Data' => $algorithm_reference
                }
            );
        }
        # parse BLAST RID (Request ID)
        elsif(/^RID:\s+(.*)$/) {
            my $rid = $1;
            $self->element(
                {
                    'Name' => 'BlastOutput_rid',
                    'Data' => $rid
                }
            );
        }
        # added Windows workaround for bug 1985
        elsif (/^(Searching|Results from round)/) {
            next unless $1 =~ /Results from round/;
            $self->debug("blast.pm: Possible psi blast iterations found...\n");

            $self->in_element('hsp')
              && $self->end_element( { 'Name' => 'Hsp' } );
            $self->in_element('hit')
              && $self->end_element( { 'Name' => 'Hit' } );
            if ( defined $seeniteration ) {
                $self->within_element('iteration')
                  && $self->end_element( { 'Name' => 'Iteration' } );
                $self->start_element( { 'Name' => 'Iteration' } );
            }
            else {
                $self->start_element( { 'Name' => 'Iteration' } );
            }
            $seeniteration = 1;
        }
        elsif (/^Query=\s*(.*)$/) {
            my $q    = $1;
            $self->debug("blast.pm: Query= found...$_\n");
            my $size = 0;
            if ( defined $seenquery ) {
                $self->_pushback($_);
                $self->_pushback($reportline) if $reportline;
                last PARSER;
            }
            if ( !defined $reporttype ) {
                $self->_start_blastoutput;
                if ( defined $seeniteration ) {
                    $self->in_element('iteration')
                      && $self->end_element( { 'Name' => 'Iteration' } );
                    $self->start_element( { 'Name' => 'Iteration' } );
                }
                else {
                    $self->start_element( { 'Name' => 'Iteration' } );
                }
                $seeniteration = 1;
            }
            $seenquery = $q;
            $_ = $self->_readline;
            while ( defined($_) ) {
                if (/^Database:/) {
                    $self->_pushback($_);
                    last;
                }
                # below line fixes length issue with BLAST v2.2.13; still works
                # with BLAST v2.2.12
                if ( /\((\-?[\d,]+)\s+letters.*\)/ || /^Length=(\-?[\d,]+)/ ) {
                    $size = $1;
                    $size =~ s/,//g;
                    last;
                }
                else {
                    # bug 2391
                    $q .= ($q =~ /\w$/ && $_ =~ /^\w/) ? " $_" : $_;
                    $q =~ s/\s+/ /g; # this catches the newline as well
                    $q =~ s/^ | $//g;
                }

                $_ = $self->_readline;
            }
            chomp($q);
            my ( $nm, $desc ) = split( /\s+/, $q, 2 );
            $self->element(
                {
                    'Name' => 'BlastOutput_query-def',
                    'Data' => $nm
                }
            ) if $nm;
            $self->element(
                {
                    'Name' => 'BlastOutput_query-len',
                    'Data' => $size
                }
            );
            defined $desc && $desc =~ s/\s+$//;
            $self->element(
                {
                    'Name' => 'BlastOutput_querydesc',
                    'Data' => $desc
                }
            );
            my ( $gi, $acc, $version ) = $self->_get_seq_identifiers($nm);
            $version = defined($version) && length($version) ? ".$version" : "";
            $self->element(
                {
                    'Name' => 'BlastOutput_query-acc',
                    'Data' => "$acc$version"
                }
            ) if $acc;

            # these elements are dropped with some multiquery reports; add
            # back here
            $self->element(
                {
                    'Name' => 'BlastOutput_db-len',
                    'Data' => $self->{'_blsdb_length'}
                }
            ) if $self->{'_blsdb_length'};
            $self->element(
                {
                    'Name' => 'BlastOutput_db-let',
                    'Data' => $self->{'_blsdb_letters'}
                }
            ) if $self->{'_blsdb_letters'};
            $self->element(
                {
                    'Name' => 'BlastOutput_db',
                    'Data' => $self->{'_blsdb'}
                }
            ) if $self->{'_blsdb_letters'};
        }
        # added check for WU-BLAST -echofilter option (bug 2388)
        elsif (/^>Unfiltered[+-]1$/) {
            # skip all of the lines of unfiltered sequence
            while($_ !~ /^Database:/) {
                $self->debug("Bypassing features line: $_");
                $_ = $self->_readline;
            }
            $self->_pushback($_);
        }
        elsif (/Sequences producing significant alignments:/) {
            $self->debug("blast.pm: Processing NCBI-BLAST descriptions\n");
            $flavor = 'ncbi';

            # PSI-BLAST parsing needs to be fixed to specifically look
            # for old vs new per iteration, as sorting based on duplication
            # leads to bugs, see bug 1986

            # The next line is not necessarily whitespace in psiblast reports.
            # Also note that we must look for the end of this section by testing
            # for a line with a leading >. Blank lines occur with this section
            # for psiblast.
            if ( !$self->in_element('iteration') ) {
                $self->start_element( { 'Name' => 'Iteration' } );
            }

            # changed 8/28/2008 to exit hit table if blank line is found after an
            # appropriate line
            my $h_regex;
            my $seen_block;
          DESCLINE:
            while ( defined( my $descline = $self->_readline() ) ) {
                if ($descline =~ m{^\s*$}) {
                    last DESCLINE if $seen_block;
                    next DESCLINE;
                }
                # any text match is part of block...
                $seen_block++;
                # GCG multiline oddness...
                if ($descline =~ /^(\S+)\s+Begin:\s\d+\s+End:\s+\d+/xms) {
                    my ($id, $nextline) = ($1, $self->_readline);
                    $nextline =~ s{^!}{};
                    $descline = "$id $nextline";
                }
                # NCBI style hit table (no N)
                if ($descline =~ /(?<!cor)          # negative lookahead
                    (\d*\.?(?:[\+\-eE]+)?\d+)       # number (float or scientific notation)
                    \s+                             # space
                    (\d*\.?(?:[\+\-eE]+)?\d+)       # number (float or scientific notation)
                    \s*$/xms) {

                    my ( $score, $evalue ) = ($1, $2);

                    # Some data clean-up so e-value will appear numeric to perl
                    $evalue =~ s/^e/1e/i;

                    # This to handle no-HSP case
                    my @line = split ' ',$descline;

                    # we want to throw away the score, evalue
                    pop @line, pop @line;

                    # and N if it is present (of course they are not
                    # really in that order, but it doesn't matter
                    if ($3) { pop @line }

                    # add the last 2 entries s.t. we can reconstruct
                    # a minimal Hit object at the end of the day
                    push @hit_signifs, [ $evalue, $score, shift @line, join( ' ', @line ) ];
                } elsif ($descline =~ /^CONVERGED/i) {
                    $self->element(
                        {
                            'Name' => 'Iteration_converged',
                            'Data' => 1
                        }
                    );
                } else {
                    $self->_pushback($descline); # Catch leading > (end of section)
                    last DESCLINE;
                }
            }
        }
        elsif (/Sequences producing High-scoring Segment Pairs:/) {

     # This block is for WU-BLAST, so we don't have to check for psi-blast stuff
     # skip the next line
            $self->debug("blast.pm: Processing WU-BLAST descriptions\n");
            $_      = $self->_readline();
            $flavor = 'wu';

            if ( !$self->in_element('iteration') ) {
                $self->start_element( { 'Name' => 'Iteration' } );
            }

            while ( defined( $_ = $self->_readline() )
                && !/^\s+$/ )
            {
                my @line = split;
                pop @line;    # throw away first number which is for 'N'col

                # add the last 2 entries to array s.t. we can reconstruct
                # a minimal Hit object at the end of the day
                push @hit_signifs,
                  [ pop @line, pop @line, shift @line, join( ' ', @line ) ];
            }

        }
        elsif (/^Database:\s*(.+?)\s*$/) {

            $self->debug("blast.pm: Database: $1\n");
            my $db = $1;
            while ( defined( $_ = $self->_readline ) ) {
                if (
                    /^\s+(\-?[\d\,]+|\S+)\s+sequences\;
                   \s+(\-?[\d,]+|\S+)\s+ # Deal with NCBI 2.2.8 OSX problems
                   total\s+letters/ox
                  )
                {
                    my ( $s, $l ) = ( $1, $2 );
                    $s =~ s/,//g;
                    $l =~ s/,//g;
                    $self->element(
                        {
                            'Name' => 'BlastOutput_db-len',
                            'Data' => $s
                        }
                    );
                    $self->element(
                        {
                            'Name' => 'BlastOutput_db-let',
                            'Data' => $l
                        }
                    );
                    # cache for next round in cases with multiple queries
                    $self->{'_blsdb'} = $db;
                    $self->{'_blsdb_length'} = $s;
                    $self->{'_blsdb_letters'} = $l;
                    last;
                }
                else {
                    chomp;
                    $db .= $_;
                }
            }
            $self->element(
                {
                    'Name' => 'BlastOutput_db',
                    'Data' => $db
                }
            );
        }

        # move inside of a hit
        elsif (/^(?:Subject=|>)\s*(\S+)\s*(.*)?/) {
            chomp;

            $self->debug("blast.pm: Hit: $1\n");
            $self->in_element('hsp')
              && $self->end_element( { 'Name' => 'Hsp' } );
            $self->in_element('hit')
              && $self->end_element( { 'Name' => 'Hit' } );

            # special case when bl2seq reports don't have a leading
            # Query=
            if ( !$self->within_element('result') ) {
                $self->_start_blastoutput;
                $self->start_element( { 'Name' => 'Iteration' } );
            }
            elsif ( !$self->within_element('iteration') ) {
                $self->start_element( { 'Name' => 'Iteration' } );
            }
            $self->start_element( { 'Name' => 'Hit' } );
            my $id         = $1;
            my $restofline = $2;

            $self->debug("Starting a hit: $1 $2\n");
            $self->element(
                {
                    'Name' => 'Hit_id',
                    'Data' => $id
                }
            );
            my ($gi, $acc, $version ) = $self->_get_seq_identifiers($id);
            $self->element(
                {
                    'Name' => 'Hit_accession',
                    'Data' => $acc
                }
            );
            # add hit significance (from the hit table)
            # this is where Bug 1986 went awry

            # Changed for Bug2409; hit->significance and hit->score/bits derived
            # from HSPs, not hit table unless necessary

            HITTABLE:
            while (my $v = shift @hit_signifs) {
                my $tableid = $v->[2];
                if ($tableid !~ m{\Q$id\E}) {
                    $self->debug("Hit table ID $tableid doesn't match current hit id $id, checking next hit table entry...\n");
                    next HITTABLE;
                } else {
                    last HITTABLE;
                }
            }
            while ( defined( $_ = $self->_readline() ) ) {
                next if (/^\s+$/);
                chomp;
                if (/Length\s*=\s*([\d,]+)/) {
                    my $l = $1;
                    $l =~ s/\,//g;
                    $self->element(
                        {
                            'Name' => 'Hit_len',
                            'Data' => $l
                        }
                    );
                    last;
                }
                else {
                    if ($restofline !~ /\s$/) { # bug #3235
                        s/^\s(?!\s)/\x01/; #new line to concatenate desc lines with <soh>
                    }
                    $restofline .= ($restofline =~ /\w$/ && $_ =~ /^\w/) ? " $_" : $_;
                    $restofline =~ s/\s+/ /g; # this catches the newline as well
                    $restofline =~ s/^ | $//g;
                }
            }
            $restofline =~ s/\s+/ /g;
            $self->element(
                {
                    'Name' => 'Hit_def',
                    'Data' => $restofline
                }
            );
        }
        elsif (/\s+(Plus|Minus) Strand HSPs:/i) {
            next;
        }
        elsif (
            ( $self->in_element('hit') || $self->in_element('hsp') )
            &&    # paracel genewise BTK
            m/Score\s*=\s*(\S+)\s*bits\s*       # Bit score
              (?:\((\d+)\))?,                   # Raw score
              \s+Log\-Length\sScore\s*=\s*(\d+) # Log-Length score
              /ox
          )
        {
            $self->in_element('hsp')
              && $self->end_element( { 'Name' => 'Hsp' } );
            $self->start_element( { 'Name' => 'Hsp' } );

            $self->debug( "Got paracel genewise HSP score=$1\n");

            # Some data clean-up so e-value will appear numeric to perl
            my ( $bits, $score, $evalue ) = ( $1, $2, $3 );
            $evalue =~ s/^e/1e/i;
            $self->element(
                {
                    'Name' => 'Hsp_score',
                    'Data' => $score
                }
            );
            $self->element(
                {
                    'Name' => 'Hsp_bit-score',
                    'Data' => $bits
                }
            );
            $self->element(
                {
                    'Name' => 'Hsp_evalue',
                    'Data' => $evalue
                }
            );
        }
        elsif (
            ( $self->in_element('hit') || $self->in_element('hsp') )
            &&    # paracel hframe BTK
            m/Score\s*=\s*([^,\s]+),           # Raw score
              \s*Expect\s*=\s*([^,\s]+),       # E-value
              \s*P(?:\(\S+\))?\s*=\s*([^,\s]+) # P-value
              /ox
          )
        {
            $self->in_element('hsp')
              && $self->end_element( { 'Name' => 'Hsp' } );
            $self->start_element( { 'Name' => 'Hsp' } );

            $self->debug( "Got paracel hframe HSP score=$1\n");

            # Some data clean-up so e-value will appear numeric to perl
            my ( $score, $evalue, $pvalue ) = ( $1, $2, $3 );
            $evalue = "1$evalue" if $evalue =~ /^e/;
            $pvalue = "1$pvalue" if $pvalue =~ /^e/;

            $self->element(
                {
                    'Name' => 'Hsp_score',
                    'Data' => $score
                }
            );
            $self->element(
                {
                    'Name' => 'Hsp_evalue',
                    'Data' => $evalue
                }
            );
            $self->element(
                {
                    'Name' => 'Hsp_pvalue',
                    'Data' => $pvalue
                }
            );
        }
        elsif (
            ( $self->in_element('hit') || $self->in_element('hsp') )
            &&    # wublast
            m/Score\s*=\s*(\S+)\s*         # Bit score
                \(([\d\.]+)\s*bits\),         # Raw score
                \s*Expect\s*=\s*([^,\s]+),    # E-value
                \s*(?:Sum)?\s*                # SUM
                P(?:\(\d+\))?\s*=\s*([^,\s]+) # P-value
                (?:\s*,\s+Group\s*\=\s*(\d+))?    # HSP Group
                /ox
          )
        {         # wu-blast HSP parse
            $self->in_element('hsp')
              && $self->end_element( { 'Name' => 'Hsp' } );
            $self->start_element( { 'Name' => 'Hsp' } );

            # Some data clean-up so e-value will appear numeric to perl
            my ( $score, $bits, $evalue, $pvalue, $group ) =
              ( $1, $2, $3, $4, $5 );
            $evalue =~ s/^e/1e/i;
            $pvalue =~ s/^e/1e/i;

            $self->element(
                {
                    'Name' => 'Hsp_score',
                    'Data' => $score
                }
            );
            $self->element(
                {
                    'Name' => 'Hsp_bit-score',
                    'Data' => $bits
                }
            );
            $self->element(
                {
                    'Name' => 'Hsp_evalue',
                    'Data' => $evalue
                }
            );
            $self->element(
                {
                    'Name' => 'Hsp_pvalue',
                    'Data' => $pvalue
                }
            );

            if ( defined $group ) {
                $self->element(
                    {
                        'Name' => 'Hsp_group',
                        'Data' => $group
                    }
                );
            }

        }
        elsif (
            ( $self->in_element('hit') || $self->in_element('hsp') )
            &&    # ncbi blast, works with 2.2.17
            m/^\sFeatures\s\w+\sthis\spart/xmso
            # If the line begins with "Features in/flanking this part of subject sequence:"
            )
        {
            $self->in_element('hsp')
              && $self->end_element( { 'Name' => 'Hsp' } );
            my $featline;
            $_ = $self->_readline;
            while($_ !~ /^\s*$/) {
                chomp;
                $featline .= $_;
                $_ = $self->_readline;
            }
            $self->_pushback($_);
            $featline =~ s{(?:^\s+|\s+^)}{}g;
            $featline =~ s{\n}{;}g;
            $self->start_element( { 'Name' => 'Hsp' } );
            $self->element(
                {
                    'Name' => 'Hsp_features',
                    'Data' => $featline
                }
            );
            $self->{'_seen_hsp_features'} = 1;
        }
        elsif (
            ( $self->in_element('hit') || $self->in_element('hsp') )
            &&    # ncbi blast, works with 2.2.17
            m/Score\s*=\s*(\S+)\s*bits\s* # Bit score
                (?:\((\d+)\))?,            # Missing for BLAT pseudo-BLAST fmt
                \s*Expect(?:\((\d+\+?)\))?\s*=\s*([^,\s]+) # E-value
                /ox
          )
        {         # parse NCBI blast HSP
            if( !$self->{'_seen_hsp_features'} ) {
                $self->in_element('hsp')
                  && $self->end_element( { 'Name' => 'Hsp' } );
                $self->start_element( { 'Name' => 'Hsp' } );
            }

            # Some data clean-up so e-value will appear numeric to perl
            my ( $bits, $score, $n, $evalue ) = ( $1, $2, $3, $4 );
            $evalue =~ s/^e/1e/i;
            $self->element(
                {
                    'Name' => 'Hsp_score',
                    'Data' => $score
                }
            );
            $self->element(
                {
                    'Name' => 'Hsp_bit-score',
                    'Data' => $bits
                }
            );
            $self->element(
                {
                    'Name' => 'Hsp_evalue',
                    'Data' => $evalue
                }
            );
            $self->element(
                {
                    'Name' => 'Hsp_n',
                    'Data' => $n
                }
            ) if defined $n;
            $score = '' unless defined $score;    # deal with BLAT which
                                                  # has no score only bits
            $self->debug("Got NCBI HSP score=$score, evalue $evalue\n");
        }
        elsif (
            $self->in_element('hsp')
            && m/Identities\s*=\s*(\d+)\s*\/\s*(\d+)\s*[\d\%\(\)]+\s*
                (?:,\s*Positives\s*=\s*(\d+)\/(\d+)\s*[\d\%\(\)]+\s*)? # pos only valid for Protein alignments
                (?:\,\s*Gaps\s*=\s*(\d+)\/(\d+))? # Gaps
                /oxi
          )
        {
            $self->element(
                {
                    'Name' => 'Hsp_identity',
                    'Data' => $1
                }
            );
            $self->element(
                {
                    'Name' => 'Hsp_align-len',
                    'Data' => $2
                }
            );
            if ( defined $3 ) {
                $self->element(
                    {
                        'Name' => 'Hsp_positive',
                        'Data' => $3
                    }
                );
            }
            else {
                $self->element(
                    {
                        'Name' => 'Hsp_positive',
                        'Data' => $1
                    }
                );
            }
            if ( defined $6 ) {
                $self->element(
                    {
                        'Name' => 'Hsp_gaps',
                        'Data' => $5
                    }
                );
            }

            $self->{'_Query'} = { 'begin' => 0, 'end' => 0 };
            $self->{'_Sbjct'} = { 'begin' => 0, 'end' => 0 };

            if (/(Frame\s*=\s*.+)$/) {

                # handle wu-blast Frame listing on same line
                $self->_pushback($1);
            }
        }
        elsif ( $self->in_element('hsp')
            && /Strand\s*=\s*(Plus|Minus)\s*\/\s*(Plus|Minus)/i )
        {

            # consume this event ( we infer strand from start/end)
            if (!defined($reporttype)) {
                $self->{'_reporttype'} = $reporttype = 'BLASTN';
                $bl2seq_fix = 1;    # special case to resubmit the algorithm
                                    # reporttype
            }
            next;
        }
        elsif ( $self->in_element('hsp')
            && /Links\s*=\s*(\S+)/ox )
        {
            $self->element(
                {
                    'Name' => 'Hsp_links',
                    'Data' => $1
                }
            );
        }
        elsif ( $self->in_element('hsp')
            && /Frame\s*=\s*([\+\-][1-3])\s*(\/\s*([\+\-][1-3]))?/ )
        {
            my $frame1 = $1 || 0;
            my $frame2 = $2 || 0;
            # this is for bl2seq only
            if ( not defined $reporttype ) {
                $bl2seq_fix = 1;
                if ( $frame1 && $frame2 ) {
                    $reporttype = 'TBLASTX'
                }
                else {
                    # We can distinguish between BLASTX and TBLASTN from the report
                    # (and assign $frame1 properly) by using the start/end from query.
                    # If the report is BLASTX, the coordinates distance from query
                    # will be 3 times the length of the alignment shown (coordinates in nt,
                    # alignment in aa); if not then subject is the nucleotide sequence (TBLASTN).
                    # Will have to fast-forward to query alignment line and then go back.
                    my $fh = $self->_fh;
                    my $file_pos = tell $fh;

                    my $a_position = '';
                    my $ali_length = '';
                    my $b_position = '';
                    while (my $line = <$fh>) {
                        if ($line =~ m/^(?:Query|Sbjct):?\s+(\-?\d+)?\s*(\S+)\s+(\-?\d+)?/) {
                            $a_position   = $1;
                            my $alignment = $2;
                            $b_position   = $3;

                            use Bio::LocatableSeq;
                            my $gap_symbols = $Bio::LocatableSeq::GAP_SYMBOLS;
                            $alignment =~ s/[$gap_symbols]//g;
                            $ali_length = length($alignment);
                            last;
                        }
                    }
                    my $coord_length = ($a_position < $b_position) ? ($b_position - $a_position + 1)
                                     : ($a_position - $b_position + 1);
                    ($coord_length == ($ali_length * 3)) ? ($reporttype = 'BLASTX') : ($reporttype = 'TBLASTN');

                    # Rewind filehandle to its original position to continue parsing
                    seek $fh, $file_pos, 0;
                }
                $self->{'_reporttype'} = $reporttype;
            }

            my ( $queryframe, $hitframe );
            if ( $reporttype eq 'TBLASTX' ) {
                ( $queryframe, $hitframe ) = ( $frame1, $frame2 );
                $hitframe =~ s/\/\s*//g;
            }
            elsif ( $reporttype eq 'TBLASTN' || $reporttype eq 'PSITBLASTN') {
                ( $hitframe, $queryframe ) = ( $frame1, 0 );
            }
            elsif ( $reporttype eq 'BLASTX' || $reporttype eq 'RPS-BLAST(BLASTP)') {
                ( $queryframe, $hitframe ) = ( $frame1, 0 );
                # though NCBI doesn't report it, this is a special BLASTX-like
                # RPS-BLAST; should be handled differently
                if ($reporttype eq 'RPS-BLAST(BLASTP)') {
                    $self->element(
                        {
                            'Name' => 'BlastOutput_program',
                            'Data' => 'RPS-BLAST(BLASTX)'
                        }
                    );
                }
            }
            $self->element(
                {
                    'Name' => 'Hsp_query-frame',
                    'Data' => $queryframe
                }
            );

            $self->element(
                {
                    'Name' => 'Hsp_hit-frame',
                    'Data' => $hitframe
                }
            );
        }
        elsif (/^Parameters:/
            || /^\s+Database:\s+?/
            || /^\s+Subset/
            || /^\s*Lambda/
            || /^\s*Histogram/
            || ( $self->in_element('hsp') && /WARNING|NOTE/ ) )
        {

            # Note: Lambda check was necessary to parse
            # t/data/ecoli_domains.rpsblast AND to parse bl2seq
            $self->debug("blast.pm: found parameters section \n");

            $self->in_element('hsp')
              && $self->end_element( { 'Name' => 'Hsp' } );
            $self->in_element('hit')
              && $self->end_element( { 'Name' => 'Hit' } );

            # This is for the case when we specify -b 0 (or B=0 for WU-BLAST)
            # and still want to construct minimal Hit objects
            $self->_cleanup_hits(\@hit_signifs) if scalar(@hit_signifs);
            $self->within_element('iteration')
              && $self->end_element( { 'Name' => 'Iteration' } );

            next if /^\s+Subset/;
            my $blast = (/^(\s+Database\:)|(\s*Lambda)/) ? 'ncbi' : 'wublast';
            if (/^\s*Histogram/) {
                $blast = 'btk';
            }

            my $last = '';

            # default is that gaps are allowed
            $self->element(
                {
                    'Name' => 'Parameters_allowgaps',
                    'Data' => 'yes'
                }
            );
            while ( defined( $_ = $self->_readline ) ) {
                # If Lambda/Kappa/Entropy numbers appear first at this point,
                # pushback and add the header line to process it correctly
                if (/^\s+[\d+\.]+\s+[\d+\.]+\s+[\d+\.]/ and $last eq '') {
                    $self->_pushback($_);
                    $self->_pushback("Lambda     K      H\n");
                    next;
                }
                elsif (
                    /^((?:\S+)?BLAST[NPX]?)\s+(.+)$/i  # NCBI BLAST, PSIBLAST
                                                      # RPSBLAST, MEGABLAST
                    || /^(P?GENEWISE|HFRAME|SWN|TSWN)\s+(.+)/i    #Paracel BTK
                  )
                {
                    $self->_pushback($_);

                    # let's handle this in the loop
                    last;
                }
                elsif (/^Query=/) {
                    $self->_pushback($_);
                    $self->_pushback($reportline) if $reportline;
                    last PARSER;
                }

                # here is where difference between wublast and ncbiblast
                # is better handled by different logic
                if (   /Number of Sequences:\s+([\d\,]+)/i
                    || /of sequences in database:\s+(\-?[\d,]+)/i )
                {
                    my $c = $1;
                    $c =~ s/\,//g;
                    $self->element(
                        {
                            'Name' => 'Statistics_db-len',
                            'Data' => $c
                        }
                    );
                }
                elsif (/letters in database:\s+(\-?[\d,]+)/i) {
                    my $s = $1;
                    $s =~ s/,//g;
                    $self->element(
                        {
                            'Name' => 'Statistics_db-let',
                            'Data' => $s
                        }
                    );
                }
                elsif ( $blast eq 'btk' ) {
                    next;
                }
                elsif ( $blast eq 'wublast' ) {

                    # warn($_);
                    if (/E=(\S+)/) {
                        $self->element(
                            {
                                'Name' => 'Parameters_expect',
                                'Data' => $1
                            }
                        );
                    }
                    elsif (/nogaps/) {
                        $self->element(
                            {
                                'Name' => 'Parameters_allowgaps',
                                'Data' => 'no'
                            }
                        );
                    }
                    elsif (/ctxfactor=(\S+)/) {
                        $self->element(
                            {
                                'Name' => 'Statistics_ctxfactor',
                                'Data' => $1
                            }
                        );
                    }
                    elsif (
/(postsw|links|span[12]?|warnings|notes|gi|noseqs|qres|qype)/
                      )
                    {
                        $self->element(
                            {
                                'Name' => "Parameters_$1",
                                'Data' => 'yes'
                            }
                        );
                    }
                    elsif (/(\S+)=(\S+)/) {
                        $self->element(
                            {
                                'Name' => "Parameters_$1",
                                'Data' => $2
                            }
                        );
                    }
                    elsif ( $last =~ /(Frame|Strand)\s+MatID\s+Matrix name/i ) {
                        my $firstgapinfo = 1;
                        my $frame        = undef;
                        while ( defined($_) && !/^\s+$/ ) {
                            s/^\s+//;
                            s/\s+$//;
                            if ( $firstgapinfo
                                && s/Q=(\d+),R=(\d+)\s+//x )
                            {
                                $firstgapinfo = 0;

                                $self->element(
                                    {
                                        'Name' => 'Parameters_gap-open',
                                        'Data' => $1
                                    }
                                );
                                $self->element(
                                    {
                                        'Name' => 'Parameters_gap-extend',
                                        'Data' => $2
                                    }
                                );
                                my @fields = split;

                                for my $type (
                                    qw(lambda_gapped
                                    kappa_gapped
                                    entropy_gapped)
                                  )
                                {
                                    next if $type eq 'n/a';
                                    if ( !@fields ) {
                                        warn "fields is empty for $type\n";
                                        next;
                                    }
                                    $self->element(
                                        {
                                            'Name' =>
                                              "Statistics_frame$frame\_$type",
                                            'Data' => shift @fields
                                        }
                                    );
                                }
                            }
                            else {
                                my ( $frameo, $matid, $matrix, @fields ) =
                                  split;
                                if ( !defined $frame ) {

                                    # keep some sort of default feature I guess
                                    # even though this is sort of wrong
                                    $self->element(
                                        {
                                            'Name' => 'Parameters_matrix',
                                            'Data' => $matrix
                                        }
                                    );
                                    $self->element(
                                        {
                                            'Name' => 'Statistics_lambda',
                                            'Data' => $fields[0]
                                        }
                                    );
                                    $self->element(
                                        {
                                            'Name' => 'Statistics_kappa',
                                            'Data' => $fields[1]
                                        }
                                    );
                                    $self->element(
                                        {
                                            'Name' => 'Statistics_entropy',
                                            'Data' => $fields[2]
                                        }
                                    );
                                }
                                $frame = $frameo;
                                my $ii = 0;
                                for my $type (
                                    qw(lambda_used
                                    kappa_used
                                    entropy_used
                                    lambda_computed
                                    kappa_computed
                                    entropy_computed)
                                  )
                                {
                                    my $f = $fields[$ii];
                                    next unless defined $f;    # deal with n/a
                                    if ( $f eq 'same' ) {
                                        $f = $fields[ $ii - 3 ];
                                    }
                                    $ii++;
                                    $self->element(
                                        {
                                            'Name' =>
                                              "Statistics_frame$frame\_$type",
                                            'Data' => $f
                                        }
                                    );

                                }
                            }

                            # get the next line
                            $_ = $self->_readline;
                        }
                        $last = $_;
                    }
                    elsif ( $last =~ /(Frame|Strand)\s+MatID\s+Length/i ) {
                        my $frame = undef;
                        while ( defined($_) && !/^\s+/ ) {
                            s/^\s+//;
                            s/\s+$//;
                            my @fields = split;
                            if ( @fields <= 3 ) {
                                for my $type (qw(X_gapped E2_gapped S2)) {
                                    last unless @fields;
                                    $self->element(
                                        {
                                            'Name' =>
                                              "Statistics_frame$frame\_$type",
                                            'Data' => shift @fields
                                        }
                                    );
                                }
                            }
                            else {

                                for my $type (
                                    qw(length
                                    efflength
                                    E S W T X E2 S2)
                                  )
                                {
                                    $self->element(
                                        {
                                            'Name' =>
                                              "Statistics_frame$frame\_$type",
                                            'Data' => shift @fields
                                        }
                                    );
                                }
                            }
                            $_ = $self->_readline;
                        }
                        $last = $_;
                    }
                    elsif (/(\S+\s+\S+)\s+DFA:\s+(\S+)\s+\((.+)\)/) {
                        if ( $1 eq 'states in' ) {
                            $self->element(
                                {
                                    'Name' => 'Statistics_DFA_states',
                                    'Data' => "$2 $3"
                                }
                            );
                        }
                        elsif ( $1 eq 'size of' ) {
                            $self->element(
                                {
                                    'Name' => 'Statistics_DFA_size',
                                    'Data' => "$2 $3"
                                }
                            );
                        }
                    }
                    elsif (
                        m/^\s+Time to generate neighborhood:\s+
                          (\S+\s+\S+\s+\S+)/x
                      )
                    {
                        $self->element(
                            {
                                'Name' => 'Statistics_neighbortime',
                                'Data' => $1
                            }
                        );
                    }
                    elsif (/processors\s+used:\s+(\d+)/) {
                        $self->element(
                            {
                                'Name' => 'Statistics_noprocessors',
                                'Data' => $1
                            }
                        );
                    }
                    elsif (
                        m/^\s+(\S+)\s+cpu\s+time:\s+ # cputype
                          (\S+\s+\S+\s+\S+)          # cputime
                          \s+Elapsed:\s+(\S+)/x
                      )
                    {
                        my $cputype = lc($1);
                        $self->element(
                            {
                                'Name' => "Statistics_$cputype\_cputime",
                                'Data' => $2
                            }
                        );
                        $self->element(
                            {
                                'Name' => "Statistics_$cputype\_actualtime",
                                'Data' => $3
                            }
                        );
                    }
                    elsif (/^\s+Start:/) {
                        my ( $junk, $start, $stime, $end, $etime ) =
                          split( /\s+(Start|End)\:\s+/, $_ );
                        chomp($stime);
                        $self->element(
                            {
                                'Name' => 'Statistics_starttime',
                                'Data' => $stime
                            }
                        );
                        chomp($etime);
                        $self->element(
                            {
                                'Name' => 'Statistics_endtime',
                                'Data' => $etime
                            }
                        );
                    }
                    elsif (/^\s+Database:\s+(.+)$/) {
                        $self->element(
                            {
                                'Name' => 'Parameters_full_dbpath',
                                'Data' => $1
                            }
                        );

                    }
                    elsif (/^\s+Posted:\s+(.+)/) {
                        my $d = $1;
                        chomp($d);
                        $self->element(
                            {
                                'Name' => 'Statistics_posted_date',
                                'Data' => $d
                            }
                        );
                    }
                }
                elsif ( $blast eq 'ncbi' ) {

                    if (m/^Matrix:\s+(.+)\s*$/oxi) {
                        $self->element(
                            {
                                'Name' => 'Parameters_matrix',
                                'Data' => $1
                            }
                        );
                    }
                    elsif (/^Gapped/) {
                        $gapped_stats = 1;
                    }
                    elsif (/^Lambda/) {
                        $_ = $self->_readline;
                        s/^\s+//;
                        my ( $lambda, $kappa, $entropy ) = split;
                        if ($gapped_stats) {
                            $self->element(
                                {
                                    'Name' => "Statistics_gapped_lambda",
                                    'Data' => $lambda
                                }
                            );
                            $self->element(
                                {
                                    'Name' => "Statistics_gapped_kappa",
                                    'Data' => $kappa
                                }
                            );
                            $self->element(
                                {
                                    'Name' => "Statistics_gapped_entropy",
                                    'Data' => $entropy
                                }
                            );
                        }
                        else {
                            $self->element(
                                {
                                    'Name' => "Statistics_lambda",
                                    'Data' => $lambda
                                }
                            );
                            $self->element(
                                {
                                    'Name' => "Statistics_kappa",
                                    'Data' => $kappa
                                }
                            );
                            $self->element(
                                {
                                    'Name' => "Statistics_entropy",
                                    'Data' => $entropy
                                }
                            );
                        }
                    }
                    elsif (m/effective\s+search\s+space\s+used:\s+(\d+)/oxi) {
                        $self->element(
                            {
                                'Name' => 'Statistics_eff-spaceused',
                                'Data' => $1
                            }
                        );
                    }
                    elsif (m/effective\s+search\s+space:\s+(\d+)/oxi) {
                        $self->element(
                            {
                                'Name' => 'Statistics_eff-space',
                                'Data' => $1
                            }
                        );
                    }
                    elsif (
                        m/Gap\s+Penalties:\s+Existence:\s+(\d+)\,
                          \s+Extension:\s+(\d+)/ox
                      )
                    {
                        $self->element(
                            {
                                'Name' => 'Parameters_gap-open',
                                'Data' => $1
                            }
                        );
                        $self->element(
                            {
                                'Name' => 'Parameters_gap-extend',
                                'Data' => $2
                            }
                        );
                    }
                    elsif (/effective\s+HSP\s+length:\s+(\d+)/) {
                        $self->element(
                            {
                                'Name' => 'Statistics_hsp-len',
                                'Data' => $1
                            }
                        );
                    }
                    elsif (/Number\s+of\s+HSP's\s+better\s+than\s+(\S+)\s+without\s+gapping:\s+(\d+)/) {
                        $self->element(
                            {
                                'Name' => 'Statistics_number_of_hsps_better_than_expect_value_cutoff_without_gapping',
                                'Data' => $2
                            }
                        );
                    }
                    elsif (/Number\s+of\s+HSP's\s+gapped:\s+(\d+)/) {
                        $self->element(
                            {
                                'Name' => 'Statistics_number_of_hsps_gapped',
                                'Data' => $1
                            }
                        );
                    }
                    elsif (/Number\s+of\s+HSP's\s+successfully\s+gapped:\s+(\d+)/) {
                        $self->element(
                            {
                                'Name' => 'Statistics_number_of_hsps_successfully_gapped',
                                'Data' => $1
                            }
                        );
                    }
                    elsif (/Length\s+adjustment:\s+(\d+)/) {
                        $self->element(
                            {
                                'Name' => 'Statistics_length_adjustment',
                                'Data' => $1
                            }
                        );
                    }
                    elsif (/effective\s+length\s+of\s+query:\s+([\d\,]+)/i) {
                        my $c = $1;
                        $c =~ s/\,//g;
                        $self->element(
                            {
                                'Name' => 'Statistics_query-len',
                                'Data' => $c
                            }
                        );
                    }
                    elsif (/effective\s+length\s+of\s+database:\s+([\d\,]+)/i) {
                        my $c = $1;
                        $c =~ s/\,//g;
                        $self->element(
                            {
                                'Name' => 'Statistics_eff-dblen',
                                'Data' => $c
                            }
                        );
                    }
                    elsif (
/^(T|A|X1|X2|X3|S1|S2):\s+(\d+(\.\d+)?)\s+(?:\(\s*(\d+\.\d+) bits\))?/
                      )
                    {
                        my $v = $2;
                        chomp($v);
                        $self->element(
                            {
                                'Name' => "Statistics_$1",
                                'Data' => $v
                            }
                        );
                        if ( defined $4 ) {
                            $self->element(
                                {
                                    'Name' => "Statistics_$1_bits",
                                    'Data' => $4
                                }
                            );
                        }
                    }
                    elsif (
                        m/frameshift\s+window\,
                          \s+decay\s+const:\s+(\d+)\,\s+([\.\d]+)/x
                      )
                    {
                        $self->element(
                            {
                                'Name' => 'Statistics_framewindow',
                                'Data' => $1
                            }
                        );
                        $self->element(
                            {
                                'Name' => 'Statistics_decay',
                                'Data' => $2
                            }
                        );
                    }
                    elsif (m/^Number\s+of\s+Hits\s+to\s+DB:\s+(\S+)/ox) {
                        $self->element(
                            {
                                'Name' => 'Statistics_hit_to_db',
                                'Data' => $1
                            }
                        );
                    }
                    elsif (m/^Number\s+of\s+extensions:\s+(\S+)/ox) {
                        $self->element(
                            {
                                'Name' => 'Statistics_num_extensions',
                                'Data' => $1
                            }
                        );
                    }
                    elsif (
                        m/^Number\s+of\s+successful\s+extensions:\s+
                          (\S+)/ox
                      )
                    {
                        $self->element(
                            {
                                'Name' => 'Statistics_num_suc_extensions',
                                'Data' => $1
                            }
                        );
                    }
                    elsif (
                        m/^Number\s+of\s+sequences\s+better\s+than\s+
                          (\S+):\s+(\d+)/ox
                      )
                    {
                        $self->element(
                            {
                                'Name' => 'Parameters_expect',
                                'Data' => $1
                            }
                        );
                        $self->element(
                            {
                                'Name' => 'Statistics_seqs_better_than_cutoff',
                                'Data' => $2
                            }
                        );
                    }
                    elsif (/^\s+Posted\s+date:\s+(.+)/) {
                        my $d = $1;
                        chomp($d);
                        $self->element(
                            {
                                'Name' => 'Statistics_posted_date',
                                'Data' => $d
                            }
                        );
                    }
                    elsif ( !/^\s+$/ ) {
                        #$self->debug( "unmatched stat $_");
                    }
                }
                $last = $_;
            }
        } elsif ( $self->in_element('hsp') ) {
            $self->debug("blast.pm: Processing HSP\n");
            # let's read 3 lines at a time;
            # bl2seq hackiness... Not sure I like
            $self->{'_reporttype'} ||= $DEFAULTREPORTTYPE;
            my %data = (
                'Query' => '',
                'Mid'   => '',
                'Hit'   => ''
            );
            my $len;
            for ( my $i = 0 ; defined($_) && $i < 3 ; $i++ ) {
                # $self->debug("$i: $_") if $v;
                if ( ( $i == 0 && /^\s+$/) ||
                     /^\s*(?:Lambda|Minus|Plus|Score)/i
                    ) {
                    $self->_pushback($_) if defined $_;
                    $self->end_element( { 'Name' => 'Hsp' } );
                    last;
                }
                chomp;
                if (/^((Query|Sbjct):?\s+(\-?\d+)?\s*)(\S+)\s+(\-?\d+)?/) {
                    my ( $full, $type, $start, $str, $end ) =
                      ( $1, $2, $3, $4, $5 );

                    if ( $str eq '-' ) {
                        $i = 3 if $type eq 'Sbjct';
                    }
                    else {
                        $data{$type} = $str;
                    }
                    $len = length($full);
                    $self->{"\_$type"}->{'begin'} = $start
                      unless $self->{"_$type"}->{'begin'};
                    $self->{"\_$type"}->{'end'} = $end;
                } elsif (/^((Query|Sbjct):?\s+(\-?0+)\s*)/) {
                   # Bug from NCBI's BLAST: unaligned output
                   $_ = $self->_readline() for 0..1;
                   last;
                } else {
                    $self->throw("no data for midline $_")
                      unless ( defined $_ && defined $len );
                    $data{'Mid'} = substr( $_, $len );
                }
                $_ = $self->_readline();
            }
            $self->characters(
                {
                    'Name' => 'Hsp_qseq',
                    'Data' => $data{'Query'}
                }
            );
            $self->characters(
                {
                    'Name' => 'Hsp_hseq',
                    'Data' => $data{'Sbjct'}
                }
            );
            $self->characters(
                {
                    'Name' => 'Hsp_midline',
                    'Data' => $data{'Mid'}
                }
            );
        }
        else {
            #$self->debug("blast.pm: unrecognized line $_");
        }
    }

    $self->debug("blast.pm: End of BlastOutput\n");
    if ( $self->{'_seentop'} ) {
        $self->within_element('hsp')
          && $self->end_element( { 'Name' => 'Hsp' } );
        $self->within_element('hit')
          && $self->end_element( { 'Name' => 'Hit' } );
        # cleanup extra hits
        $self->_cleanup_hits(\@hit_signifs) if scalar(@hit_signifs);
        $self->within_element('iteration')
          && $self->end_element( { 'Name' => 'Iteration' } );
        if ($bl2seq_fix) {
            $self->element(
                {
                    'Name' => 'BlastOutput_program',
                    'Data' => $reporttype
                }
            );
        }
        $self->end_element( { 'Name' => 'BlastOutput' } );
    }
    return $self->end_document();
}

# Private method for internal use only.
sub _start_blastoutput {
    my $self = shift;
    $self->start_element( { 'Name' => 'BlastOutput' } );
    $self->{'_seentop'} = 1;
    $self->{'_result_count'}++;
    $self->{'_handler_rc'} = undef;
}

=head2 _will_handle

 Title   : _will_handle
 Usage   : Private method. For internal use only.
              if( $self->_will_handle($type) ) { ... }
 Function: Provides an optimized way to check whether or not an element of a
           given type is to be handled.
 Returns : Reference to EventHandler object if the element type is to be handled.
           undef if the element type is not to be handled.
 Args    : string containing type of element.

Optimizations:

=over 2

=item 1

Using the cached pointer to the EventHandler to minimize repeated
lookups.

=item 2

Caching the will_handle status for each type that is encountered so
that it only need be checked by calling
handler-E<gt>will_handle($type) once.

=back

This does not lead to a major savings by itself (only 5-10%).  In
combination with other optimizations, or for large parse jobs, the
savings good be significant.

To test against the unoptimized version, remove the parentheses from
around the third term in the ternary " ? : " operator and add two
calls to $self-E<gt>_eventHandler().

=cut

sub _will_handle {
    my ( $self, $type ) = @_;
    my $handler     = $self->{'_handler_cache'};
    my $will_handle =
      defined( $self->{'_will_handle_cache'}->{$type} )
      ? $self->{'_will_handle_cache'}->{$type}
      : ( $self->{'_will_handle_cache'}->{$type} =
          $handler->will_handle($type) );

    return $will_handle ? $handler : undef;
}

=head2 start_element

 Title   : start_element
 Usage   : $eventgenerator->start_element
 Function: Handles a start element event
 Returns : none
 Args    : hashref with at least 2 keys 'Data' and 'Name'

=cut

sub start_element {
    my ( $self, $data ) = @_;

    # we currently don't care about attributes
    my $nm   = $data->{'Name'};
    my $type = $MODEMAP{$nm};
    if ($type) {
        my $handler = $self->_will_handle($type);
        if ($handler) {
            my $func = sprintf( "start_%s", lc $type );
            $self->{'_handler_rc'} = $handler->$func( $data->{'Attributes'} );
        }
        #else {
            #$self->debug( # changed 4/29/2006 to play nice with other event handlers
            #    "Bio::SearchIO::InternalParserError ".
            #    "\nCan't handle elements of type \'$type.\'"
            #);
        #}
        unshift @{ $self->{'_elements'} }, $type;
        if ( $type eq 'result' ) {
            $self->{'_values'} = {};
            $self->{'_result'} = undef;
        } else {
            # cleanup some things
            if ( defined $self->{'_values'} ) {
                foreach my $k (
                    grep { /^\U$type\-/ }
                    keys %{ $self->{'_values'} }
                  )
                {
                    delete $self->{'_values'}->{$k};
                }
            }
        }
    }
}

=head2 end_element

 Title   : end_element
 Usage   : $eventgenerator->end_element
 Function: Handles an end element event
 Returns : hashref with an element's worth of data
 Args    : hashref with at least 2 keys 'Data' and 'Name'


=cut

sub end_element {
    my ( $self, $data ) = @_;

    my $nm   = $data->{'Name'};
    my $type;
    my $rc;
    # cache these (TODO: we should probably cache all cross-report data)
    if ( $nm eq 'BlastOutput_program' ) {
        if ( $self->{'_last_data'} =~ /(t?blast[npx])/i ) {
            $self->{'_reporttype'} = uc $1;
        }
        $self->{'_reporttype'} ||= $DEFAULTREPORTTYPE;
    }

    if ( $nm eq 'BlastOutput_version' ) {
        $self->{'_reportversion'} = $self->{'_last_data'};
    }

    # Hsps are sort of weird, in that they end when another
    # object begins so have to detect this in end_element for now
    if ( $nm eq 'Hsp' ) {
        foreach (qw(Hsp_qseq Hsp_midline Hsp_hseq Hsp_features)) {
            $self->element(
                {
                    'Name' => $_,
                    'Data' => $self->{'_last_hspdata'}->{$_}
                }
            ) if defined $self->{'_last_hspdata'}->{$_};
        }
        $self->{'_last_hspdata'} = {};
        $self->element(
            {
                'Name' => 'Hsp_query-from',
                'Data' => $self->{'_Query'}->{'begin'}
            }
        );
        $self->element(
            {
                'Name' => 'Hsp_query-to',
                'Data' => $self->{'_Query'}->{'end'}
            }
        );

        $self->element(
            {
                'Name' => 'Hsp_hit-from',
                'Data' => $self->{'_Sbjct'}->{'begin'}
            }
        );
        $self->element(
            {
                'Name' => 'Hsp_hit-to',
                'Data' => $self->{'_Sbjct'}->{'end'}
            }
        );

        #    } elsif( $nm eq 'Iteration' ) {
        # Nothing special needs to be done here.
    }
    if ( $type = $MODEMAP{$nm} ) {
        my $handler = $self->_will_handle($type);
        if ($handler) {
            my $func = sprintf( "end_%s", lc $type );
            $rc = $handler->$func( $self->{'_reporttype'}, $self->{'_values'} );
        }
        shift @{ $self->{'_elements'} };

    }
    elsif ( $MAPPING{$nm} ) {
        if ( ref( $MAPPING{$nm} ) =~ /hash/i ) {

            # this is where we shove in the data from the
            # hashref info about params or statistics
            my $key = ( keys %{ $MAPPING{$nm} } )[0];
            $self->{'_values'}->{$key}->{ $MAPPING{$nm}->{$key} } =
              $self->{'_last_data'};
        }
        else {
            $self->{'_values'}->{ $MAPPING{$nm} } = $self->{'_last_data'};
        }
    }
    else {
        #$self->debug("blast.pm: unknown nm $nm, ignoring\n");
    }
    $self->{'_last_data'} = '';    # remove read data if we are at
                                   # end of an element
    $self->{'_result'} = $rc if ( defined $type && $type eq 'result' );
    $self->{'_seen_hsp_features'} = 0;
    return $rc;
}

=head2 element

 Title   : element
 Usage   : $eventhandler->element({'Name' => $name, 'Data' => $str});
 Function: Convenience method that calls start_element, characters, end_element
 Returns : none
 Args    : Hash ref with the keys 'Name' and 'Data'


=cut

sub element {
    my ( $self, $data ) = @_;
    # Note that start element isn't needed for character data
    # Not too SAX-y, though
    #$self->start_element($data);
    $self->characters($data);
    $self->end_element($data);
}

=head2 characters

 Title   : characters
 Usage   : $eventgenerator->characters($str)
 Function: Send a character events
 Returns : none
 Args    : string


=cut

sub characters {
    my ( $self, $data ) = @_;
    if (   $self->in_element('hsp')
        && $data->{'Name'} =~ /^Hsp\_(qseq|hseq|midline)$/ )
    {
        $self->{'_last_hspdata'}->{ $data->{'Name'} } .= $data->{'Data'}
          if defined $data->{'Data'};
    }
    return unless ( defined $data->{'Data'} && $data->{'Data'} !~ /^\s+$/ );
    $self->{'_last_data'} = $data->{'Data'};
}

=head2 within_element

 Title   : within_element
 Usage   : if( $eventgenerator->within_element($element) ) {}
 Function: Test if we are within a particular element
           This is different than 'in' because within can be tested
           for a whole block.
 Returns : boolean
 Args    : string element name

See Also: L<in_element>

=cut

sub within_element {
    my ( $self, $name ) = @_;
    return 0
      if ( !defined $name && !defined $self->{'_elements'}
        || scalar @{ $self->{'_elements'} } == 0 );
    foreach ( @{ $self->{'_elements'} } ) {
        if ( $_ eq $name ) {
            return 1;
        }
    }
    return 0;
}

=head2 in_element

 Title   : in_element
 Usage   : if( $eventgenerator->in_element($element) ) {}
 Function: Test if we are in a particular element
           This is different than 'within_element' because within
           can be tested for a whole block.
 Returns : boolean
 Args    : string element name

See Also: L<within_element>

=cut

sub in_element {
    my ( $self, $name ) = @_;
    return 0 if !defined $self->{'_elements'}->[0];
    return ( $self->{'_elements'}->[0] eq $name );
}

=head2 start_document

 Title   : start_document
 Usage   : $eventgenerator->start_document
 Function: Handle a start document event
 Returns : none
 Args    : none


=cut

sub start_document {
    my ($self) = @_;
    $self->{'_lasttype'} = '';
    $self->{'_values'}   = {};
    $self->{'_result'}   = undef;
    $self->{'_elements'} = [];
}

=head2 end_document

 Title   : end_document
 Usage   : $eventgenerator->end_document
 Function: Handles an end document event
 Returns : Bio::Search::Result::ResultI object
 Args    : none


=cut

sub end_document {
    my ( $self, @args ) = @_;

    #$self->debug("blast.pm: end_document\n");
    return $self->{'_result'};
}

sub write_result {
    my ( $self, $blast, @args ) = @_;

    if ( not defined( $self->writer ) ) {
        $self->warn("Writer not defined. Using a $DEFAULT_BLAST_WRITER_CLASS");
        $self->writer( $DEFAULT_BLAST_WRITER_CLASS->new() );
    }
    $self->SUPER::write_result( $blast, @args );
}

sub result_count {
    my $self = shift;
    return $self->{'_result_count'};
}

sub report_count { shift->result_count }

=head2 inclusion_threshold

 Title   : inclusion_threshold
 Usage   : my $incl_thresh = $isreb->inclusion_threshold;
         : $isreb->inclusion_threshold(1e-5);
 Function: Get/Set the e-value threshold for inclusion in the PSI-BLAST
           score matrix model (blastpgp) that was used for generating the reports
           being parsed.
 Returns : number (real)
           Default value: $Bio::SearchIO::IteratedSearchResultEventBuilder::DEFAULT_INCLUSION_THRESHOLD
 Args    : number (real)  (e.g., 0.0001 or 1e-4 )

=cut

=head2 max_significance

 Usage     : $obj->max_significance();
 Purpose   : Set/Get the P or Expect value used as significance screening cutoff.
             This is the value of the -signif parameter supplied to new().
             Hits with P or E-value above this are skipped.
 Returns   : Scientific notation number with this format: 1.0e-05.
 Argument  : Scientific notation number or float (when setting)
 Comments  : Screening of significant hits uses the data provided on the
           : description line. For NCBI BLAST1 and WU-BLAST, this data
           : is P-value. for NCBI BLAST2 it is an Expect value.

=cut

=head2 signif

Synonym for L<max_significance()|max_significance>

=cut

=head2 min_score

 Usage     : $obj->min_score();
 Purpose   : Set/Get the Blast score used as screening cutoff.
             This is the value of the -score parameter supplied to new().
             Hits with scores below this are skipped.
 Returns   : Integer or scientific notation number.
 Argument  : Integer or scientific notation number (when setting)
 Comments  : Screening of significant hits uses the data provided on the
           : description line.

=cut

=head2 min_query_length

 Usage     : $obj->min_query_length();
 Purpose   : Gets the query sequence length used as screening criteria.
             This is the value of the -min_query_len parameter supplied to new().
             Hits with sequence length below this are skipped.
 Returns   : Integer
 Argument  : n/a

=cut

=head2 best_hit_only

 Title     : best_hit_only
 Usage     : print "only getting best hit.\n" if $obj->best_hit_only;
 Purpose   : Set/Get the indicator for whether or not to process only
           : the best BlastHit.
 Returns   : Boolean (1 | 0)
 Argument  : Boolean (1 | 0) (when setting)

=cut

=head2 check_all_hits

 Title     : check_all_hits
 Usage     : print "checking all hits.\n" if $obj->check_all_hits;
 Purpose   : Set/Get the indicator for whether or not to process all hits.
           : If false, the parser will stop processing hits after the
           : the first non-significance hit or the first hit that fails
           : any hit filter.
 Returns   : Boolean (1 | 0)
 Argument  : Boolean (1 | 0) (when setting)

=cut

# general private method used to make minimal hits from leftover
# data in the hit table

sub _cleanup_hits {
    my ($self, $hits) = @_;
    while ( my $v = shift @{ $hits }) {
        next unless defined $v;
        $self->start_element( { 'Name' => 'Hit' } );
        my $id   = $v->[2];
        my $desc = $v->[3];
        $self->element(
            {
                'Name' => 'Hit_id',
                'Data' => $id
            }
        );
        my ($gi, $acc, $version ) = $self->_get_seq_identifiers($id);
        $self->element(
            {
                'Name' => 'Hit_accession',
                'Data' => $acc
            }
        );
        if ( defined $v ) {
            $self->element(
                {
                    'Name' => 'Hit_signif',
                    'Data' => $v->[0]
                }
            );
            if (exists $self->{'_wublast'}) {
                $self->element(
                    {
                        'Name' => 'Hit_score',
                        'Data' => $v->[1]
                    }
                );
            } else {
                $self->element(
                    {
                        'Name' => 'Hit_bits',
                        'Data' => $v->[1]
                    }
                );
            }

        }
        $self->element(
            {
                'Name' => 'Hit_def',
                'Data' => $desc
            }
        );
        $self->end_element( { 'Name' => 'Hit' } );
    }
}


1;

__END__

Developer Notes
---------------

The following information is added in hopes of increasing the
maintainability of this code. It runs the risk of becoming obsolete as
the code gets updated. As always, double check against the actual
source. If you find any discrepencies, please correct them.
[ This documentation added on 3 Jun 2003. ]

The logic is the brainchild of Jason Stajich, documented by Steve
Chervitz. Jason: please check it over and modify as you see fit.

Question:
Elmo wants to know: How does this module unmarshall data from the input stream?
(i.e., how does information from a raw input file get added to
the correct Bioperl object?)

Answer:

This answer is specific to SearchIO::blast, but may apply to other
SearchIO.pm subclasses as well. The following description gives the
basic idea. The actual processing is a little more complex for
certain types of data (HSP, Report Parameters).

You can think of blast::next_result() as faking a SAX XML parser,
making a non-XML document behave like its XML. The overhead to do this
is quite substantial (~650 lines of code instead of ~80 in
blastxml.pm).

0. First, add a key => value pair for the datum of interest to %MAPPING
    Example:
           'Foo_bar'   => 'Foo-bar',

1. next_result() collects the datum of interest from the input stream,
   and calls element().
    Example:
            $self->element({ 'Name' => 'Foo_bar',
                             'Data' => $foobar});

2. The element() method is a convenience method that calls start_element(),
   characters(), and end_element().

3. start_element() checks to see if the event handler can handle a start_xxx(),
   where xxx = the 'Name' parameter passed into element(), and calls start_xxx()
   if so. Otherwise, start_element() does not do anything.

   Data that will have such an event handler are defined in %MODEMAP.
   Typically, there are only handler methods for the main parts of
   the search result (e.g., Result, Iteration, Hit, HSP),
   which have corresponding Bioperl modules. So in this example,
   there was an earlier call such as $self->element({'Name'=>'Foo'})
   and the Foo_bar datum is meant to ultimately go into a Foo object.

   The start_foo() method in the handler will typically do any
   data initialization necessary to prepare for creating a new Foo object.
   Example: SearchResultEventBuilder::start_result()

4. characters() takes the value of the 'Data' key from the hashref argument in
   the elements() call and saves it in a local data member:
   Example:
   $self->{'_last_data'} = $data->{'Data'};

5. end_element() is like start_element() in that it does the check for whether
   the event handler can handle end_xxx() and if so, calls it, passing in
   the data collected from all of the characters() calls that occurred
   since the start_xxx() call.

   If there isn't any special handler for the data type specified by 'Name',
   end_element() will place the data saved by characters() into another
   local data member that saves it in a hash with a key defined by %MAPPING.
   Example:
           $nm = $data->{'Name'};
           $self->{'_values'}->{$MAPPING{$nm}} = $self->{'_last_data'};

   In this case, $MAPPING{$nm} is 'Foo-bar'.

   end_element() finishes by resetting the local data member used by
   characters(). (i.e., $self->{'_last_data'} = '';)

6. When the next_result() method encounters the end of the Foo element in the
   input stream. It will invoke $self->end_element({'Name'=>'Foo'}).
   end_element() then sends all of the data in the $self->{'_values'} hash.
   Note that $self->{'_values'} is cleaned out during start_element(),
   keeping it at a resonable size.

   In the event handler, the end_foo() method takes the hash from end_element()
   and creates a new hash containing the same data, but having keys lacking
   the 'Foo' prefix (e.g., 'Foo-bar' becomes '-bar'). The handler's end_foo()
   method then creates the Foo object, passing in this new hash as an argument.
   Example: SearchResultEventBuilder::end_result()

7. Objects created from the data in the search result are managed by
   the event handler which adds them to a ResultI object (using API methods
   for that object). The ResultI object gets passed back to
   SearchIO::end_element() when it calls end_result().

   The ResultI object is then saved in an internal data member of the
   SearchIO object, which returns it at the end of next_result()
   by calling end_document().

   (Technical Note: All objects created by end_xxx() methods in the event
    handler are returned to SearchIO::end_element(), but the SearchIO object
    only cares about the ResultI objects.)

(Sesame Street aficionados note: This answer was NOT given by Mr. Noodle ;-P)