This file is indexed.

/usr/bin/bp_genbank2gff3 is in bioperl 1.6.924-3.

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

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
#!/usr/bin/perl 

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
    if 0; # not running under some shell



=pod

=head1 NAME 

bp_genbank2gff3.pl -- Genbank-E<gt>gbrowse-friendly GFF3

=head1 SYNOPSIS

  bp_genbank2gff3.pl [options] filename(s)

  # process a directory containing GenBank flatfiles
  perl bp_genbank2gff3.pl --dir path_to_files --zip

  # process a single file, ignore explicit exons and introns
  perl bp_genbank2gff3.pl --filter exon --filter intron file.gbk.gz

  # process a list of files 
  perl bp_genbank2gff3.pl *gbk.gz

  # process data from URL, with Chado GFF model (-noCDS), and pipe to database loader
  curl ftp://ftp.ncbi.nih.gov/genomes/Saccharomyces_cerevisiae/CHR_X/NC_001142.gbk \
  | perl bp_genbank2gff3.pl -noCDS -in stdin -out stdout \
  | perl gmod_bulk_load_gff3.pl -dbname mychado -organism fromdata

    Options:
        --noinfer  -r  don't infer exon/mRNA subfeatures
        --conf     -i  path to the curation configuration file that contains user preferences
                       for Genbank entries (must be YAML format)
                       (if --manual is passed without --ini, user will be prompted to 
                        create the file if any manual input is saved)
        --sofile  -l  path to to the so.obo file to use for feature type mapping
                       (--sofile live will download the latest online revision)
        --manual   -m  when trying to guess the proper SO term, if more than
                       one option matches the primary tag, the converter will 
                       wait for user input to choose the correct one
                       (only works with --sofile)
        --dir      -d  path to a list of genbank flatfiles
        --outdir   -o  location to write GFF files (can be 'stdout' or '-' for pipe)
        --zip      -z  compress GFF3 output files with gzip
        --summary  -s  print a summary of the features in each contig
        --filter   -x  genbank feature type(s) to ignore
        --split    -y  split output to separate GFF and fasta files for
                       each genbank record
        --nolump   -n  separate file for each reference sequence
                       (default is to lump all records together into one 
                       output file for each input file)
        --ethresh  -e  error threshold for unflattener
                       set this high (>2) to ignore all unflattener errors
        --[no]CDS  -c  Keep CDS-exons, or convert to alternate gene-RNA-protein-exon 
                       model. --CDS is default. Use --CDS to keep default GFF gene model, 
                       use --noCDS to convert to g-r-p-e.
        --format   -f  Input format (SeqIO types): GenBank, Swiss or Uniprot, EMBL work
                       (GenBank is default)
        --GFF_VERSION  3 is default, 2 and 2.5 and other Bio::Tools::GFF versions available
        --quiet        don't talk about what is being processed 
        --typesource   SO sequence type for source (e.g. chromosome; region; contig)
        --help     -h  display this message


=head1 DESCRIPTION

This script uses Bio::SeqFeature::Tools::Unflattener and
Bio::Tools::GFF to convert GenBank flatfiles to GFF3 with gene
containment hierarchies mapped for optimal display in gbrowse.

The input files are assumed to be gzipped GenBank flatfiles for refseq
contigs.  The files may contain multiple GenBank records.  Either a
single file or an entire directory can be processed.  By default, the
DNA sequence is embedded in the GFF but it can be saved into separate
fasta file with the --split(-y) option.

If an input file contains multiple records, the default behaviour is
to dump all GFF and sequence to a file of the same name (with .gff
appended).  Using the 'nolump' option will create a separate file for
each genbank record.  Using the 'split' option will create separate
GFF and Fasta files for each genbank record.


=head2 Notes

=head3 'split' and 'nolump' produce many files

In cases where the input files contain many GenBank records (for
example, the chromosome files for the mouse genome build), a very
large number of output files will be produced if the 'split' or
'nolump' options are selected.  If you do have lists of files E<gt> 6000,
use the --long_list option in bp_bulk_load_gff.pl or
bp_fast_load_gff.pl to load the gff and/ or fasta files.

=head3 Designed for RefSeq

This script is designed for RefSeq genomic sequence entries.  It may
work for third party annotations but this has not been tested.
But see below, Uniprot/Swissprot works, EMBL and possibly EMBL/Ensembl
if you don't mind some gene model unflattener errors (dgg).

=head3 G-R-P-E Gene Model

Don Gilbert worked this over with needs to produce GFF3 suited to
loading to GMOD Chado databases.  Most of the changes I believe are
suited for general use.  One main chado-specific addition is the
  --[no]cds2protein  flag

My favorite GFF is to set the above as ON by default (disable with --nocds2prot)
For general use it probably should be OFF, enabled with --cds2prot.

This writes GFF with an alternate, but useful Gene model,
instead of the consensus model for GFF3 

  [ gene > mRNA> (exon,CDS,UTR) ]

This alternate is

  gene > mRNA > polypeptide > exon 

means the only feature with dna bases is the exon.  The others
specify only location ranges on a genome.  Exon of course is a child
of mRNA and protein/peptide.   

The protein/polypeptide feature is an important one, having all the
annotations of the GenBank CDS feature, protein ID, translation, GO
terms, Dbxrefs to other proteins.

UTRs, introns, CDS-exons are all inferred from the primary exon bases
inside/outside appropriate higher feature ranges.   Other special gene
model features remain the same.

Several other improvements and bugfixes, minor but useful are included

  * IO pipes now work:
    curl ftp://ncbigenomes/... | bp_genbank2gff3 --in stdin --out stdout | gff2chado ...

  * GenBank main record fields are added to source feature, e.g. organism, date,
    and the sourcetype, commonly chromosome for  genomes, is used.

  * Gene Model handling for ncRNA, pseudogenes are added.

  * GFF header is cleaner, more informative.
    --GFF_VERSION flag allows choice of v2 as well as default v3

  * GFF ##FASTA inclusion is improved, and
    CDS translation sequence is moved to FASTA records.

  * FT -> GFF attribute mapping is improved.

  * --format choice of SeqIO input formats (GenBank default). 
    Uniprot/Swissprot and EMBL work and produce useful GFF.

  * SeqFeature::Tools::TypeMapper has a few FT -> SOFA additions
      and more flexible usage.

=head1 TODO

=head2 Are these additions desired?

 * filter input records by taxon (e.g. keep only organism=xxx or taxa level = classYYY
 * handle Entrezgene, other non-sequence SeqIO structures (really should change
    those parsers to produce consistent annotation tags).

=head2 Related bugfixes/tests

These items from Bioperl mail were tested (sample data generating
errors), and found corrected:

 From: Ed Green <green <at> eva.mpg.de>
 Subject: genbank2gff3.pl on new human RefSeq
 Date: 2006-03-13 21:22:26 GMT 
   -- unspecified errors (sample data works now).

 From: Eric Just <e-just <at> northwestern.edu>
 Subject: genbank2gff3.pl
 Date: 2007-01-26 17:08:49 GMT
   -- bug fixed in genbank2gff3 for multi-record handling

This error is for a /trans_splice gene that is hard to handle, and
unflattner/genbank2 doesn't

 From: Chad Matsalla <chad <at> dieselwurks.com> 
 Subject: genbank2gff3.PLS and the unflatenner - Inconsistent order?
 Date: 2005-07-15 19:51:48 GMT 

=head1 AUTHOR 

Sheldon McKay (mckays@cshl.edu)

Copyright (c) 2004 Cold Spring Harbor Laboratory.

=head2 AUTHOR of hacks for GFF2Chado loading

Don Gilbert (gilbertd@indiana.edu)


=cut

use strict;
use warnings;

use lib "$ENV{HOME}/bioperl-live";
# chad put this here to enable situations when this script is tested
# against bioperl compiled into blib along with other programs using blib
BEGIN {
        unshift(@INC,'blib/lib');
};
use Pod::Usage;
use Bio::Root::RootI;
use Bio::SeqIO;
use File::Spec;
use Bio::SeqFeature::Tools::Unflattener;
use Bio::SeqFeature::Tools::TypeMapper;
use Bio::SeqFeature::Tools::IDHandler;
use Bio::Location::SplitLocationI;
use Bio::Location::Simple;
use Bio::Tools::GFF;
use Getopt::Long;
use List::Util qw(first);
use Bio::OntologyIO;
use YAML qw(Dump LoadFile DumpFile);
use File::Basename; 

use vars qw/$split @filter $zip $outdir $help $ethresh
            $ONTOLOGY %FEATURES %DESCENDANTS @RETURN $MANUAL @GFF_LINE_FEAT
            $CONF $YAML $TYPE_MAP $SYN_MAP $noinfer $SO_FILE 
            $file @files $dir $summary $nolump 
            $source_type %proteinfa %exonpar $didheader $verbose $DEBUG $GFF_VERSION 
            $gene_id $rna_id $tnum $ncrna_id $rnum %method %id %seen/;

use constant SO_URL => 
    'http://song.cvs.sourceforge.net/viewvc/*checkout*/song/ontology/so.obo';
use constant ALPHABET => [qw(a b c d e f g h i j k l m n o p q r s t u v w x y z)];
use constant ALPHABET_TO_NUMBER => {
    a => 0, b => 1, c => 2, d => 3, e => 4, f => 5, g => 6, h => 7, i => 8, 
    j => 9, k => 10, l => 11, m => 12, n => 13, o => 14, p => 15, q => 16,
    r => 17, s => 18, t => 19, u => 20, v => 21, w => 22, x => 23, y => 24,
    z => 25,
    };
use constant ALPHABET_DIVISOR => 26;
use constant GM_NEW_TOPLEVEL => 2;
use constant GM_NEW_PART => 1;
use constant GM_DUP_PART => 0;
use constant GM_NOT_PART => -1;

# Options cycle in multiples of 2 because of left side/right side pairing. 
# You can make this number odd, but displayed matches will still round up
use constant OPTION_CYCLE => 6; 

$GFF_VERSION = 3; # allow v2 ...
$verbose = 1; # right default? -nov to turn off

# dgg: change the gene model to  Gene/mRNA/Polypeptide/exons...
my $CDSkeep= 1; # default should be ON (prior behavior), see gene_features()
my $PROTEIN_TYPE = 'polypeptide'; # for noCDSkeep; 
  # protein = flybase chado usage; GMOD Perls use 'polypeptide' with software support

my $FORMAT="GenBank"; # swiss ; embl; genbank ; ** guess from SOURCEID **
my $SOURCEID= $FORMAT; # "UniProt" "GenBank"  "EMBL" should work  
   # other Bio::SeqIO formats may work.  TEST: EntrezGene < problematic tags; InterPro  KEGG 


my %TAG_MAP = (
  db_xref => 'Dbxref',
  name => 'Name',
  note => 'Note', # also pull GO: ids into Ontology_term
  synonym => 'Alias',
  symbol => 'Alias',  # is symbol still used?
  # protein_id => 'Dbxref', also seen Dbxref tags: EC_number 
  # translation: handled in gene_features
);


$| = 1;
my $quiet= !$verbose;
my $ok= GetOptions( 'd|dir|input:s'   => \$dir,
            'z|zip'     => \$zip, 
            'h|help'    => \$help,
            's|summary' => \$summary,
            'r|noinfer' => \$noinfer,
            'i|conf=s' => \$CONF,
            'sofile=s' => \$SO_FILE,
            'm|manual' => \$MANUAL,
            'o|outdir|output:s'=> \$outdir,
            'x|filter:s'=> \@filter,
            'y|split'   => \$split,
            "ethresh|e=s"=>\$ethresh,
            'c|CDS!'    => \$CDSkeep,
            'f|format=s' => \$FORMAT,
            'typesource=s' => \$source_type,
            'GFF_VERSION=s' => \$GFF_VERSION,
            'quiet!'    => \$quiet, # swap quiet to verbose
            'DEBUG!'    => \$DEBUG,
            'n|nolump'  => \$nolump);

my $lump = 1 unless $nolump || $split;
$verbose= !$quiet;

# look for help request
pod2usage(2) if $help || !$ok;

# keep SOURCEID as-is and change FORMAT for SeqIO types; 
# note SeqIO uses file.suffix to guess type; not useful here
$SOURCEID= $FORMAT; 
$FORMAT  = "swiss" if $FORMAT =~/UniProt|trembl/;
$verbose =1 if($DEBUG);

# initialize handlers
my $unflattener = Bio::SeqFeature::Tools::Unflattener->new; # for ensembl genomes (-trust_grouptag=>1);
$unflattener->error_threshold($ethresh) if $ethresh;
$unflattener->verbose(1) if($DEBUG);
# $unflattener->group_tag('gene') if($FORMAT =~ /embl/i) ; #? ensembl only? 
# ensembl parsing is still problematic, forget this

my $tm  = Bio::SeqFeature::Tools::TypeMapper->new;
my $idh = Bio::SeqFeature::Tools::IDHandler->new;

# dgg
$source_type ||= "region"; # should really parse from FT.source contents below

#my $FTSOmap = $tm->FT_SO_map();
my $FTSOmap;
my $FTSOsynonyms;

if (defined($SO_FILE) && $SO_FILE eq 'live') {
    print "\nDownloading the latest SO file from ".SO_URL."\n\n";
    use LWP::UserAgent;
    my $ua = LWP::UserAgent->new(timeout => 30);
    my $request = HTTP::Request->new(GET => SO_URL);
    my $response = $ua->request($request);


    if ($response->status_line =~ /200/) {
        use File::Temp qw/ tempfile /;
        my ($fh, $fn) = tempfile();
        print $fh $response->content;
        $SO_FILE = $fn;
    } else {
        print "Couldn't download SO file online...skipping validation.\n" 
            . "HTTP Status was " . $response->status_line . "\n" 
            and undef $SO_FILE
    }
}

if ($SO_FILE) {


    my (%terms, %syn);

    my $parser = Bio::OntologyIO->new( -format => "obo", -file => $SO_FILE );
    $ONTOLOGY = $parser->next_ontology();

    for ($ONTOLOGY->get_all_terms) { 
        my $feat = $_;

        $terms{$feat->name} = $feat->name;
        #$terms{$feat->name} = $feat;

        my @syn = $_->each_synonym;

        push @{$syn{$_}}, $feat->name for @syn;
        #push @{$syn{$_}}, $feat for @syn;
    }

    $FTSOmap = \%terms;
    $FTSOsynonyms = \%syn;

    my %hardTerms = %{ $tm->FT_SO_map() };
    map { $FTSOmap->{$_} ||= $hardTerms{$_} } keys %hardTerms;

} else { 
    my %terms = %{ $tm->FT_SO_map() };
    while (my ($k,$v) = each %terms) {
        $FTSOmap->{$k} = ref($v) ? shift @$v : $v;
    }
}

$TYPE_MAP = $FTSOmap;
$SYN_MAP = $FTSOsynonyms;


# #convert $FTSOmap undefined to valid SO : moved to TypeMapper->map_types( -undefined => "region")

# stringify filter list if applicable
my $filter = join ' ', @filter  if @filter;

# determine input files
my $stdin=0; # dgg: let dir == stdin == '-' for pipe use
if ($dir && ($dir eq '-' || $dir eq 'stdin')) {
  $stdin=1;  $dir=''; @files=('stdin');
  
} elsif ( $dir ) {
    if ( -d $dir ) {
        opendir DIR, $dir or die "could not open $dir for reading: $!";
        @files = map { "$dir/$_";} grep { /\.gb.*/ } readdir DIR;  
        closedir DIR;
    }
    else {
        die "$dir is not a directory\n";
    }
}
else {
    @files = @ARGV;
    $dir = '';
}

# we should have some files by now
pod2usage(2) unless @files;


my $stdout=0; # dgg: let outdir == stdout == '-' for pipe use
if($outdir && ($outdir eq '-' || $outdir eq 'stdout')) {
  warn("std. output chosen: cannot split\n") if($split);
  warn("std. output chosen: cannot zip\n") if($zip);
  warn("std. output chosen: cannot nolump\n") if($nolump);
  $stdout=1; $lump=1; $split= 0; $zip= 0; # unless we pipe stdout thru gzip
  
} elsif ( $outdir && !-e $outdir ) {
    mkdir($outdir) or die "could not create directory $outdir: $!\n";        
}
elsif ( !$outdir ) {
    $outdir = $dir || '.';
}

for my $file ( @files ) {
    # dgg ; allow 'stdin' / '-' input ?
    chomp $file;
    die "$! $file" unless($stdin || -e $file);
    print "# Input: $file\n" if($verbose);

    my ($lump_fh, $lumpfa_fh, $outfile, $outfa);
    if ($stdout) {
      $lump_fh= *STDOUT; $lump="stdout$$";
      $outfa= "stdout$$.fa";  # this is a temp file ... see below
      open $lumpfa_fh, ">$outfa" or die "Could not create a lump outfile called ($outfa) because ($!)\n";

    } elsif ( $lump ) {
        my ($vol,$dirs,$fileonly) = File::Spec->splitpath($file); 
        $lump = File::Spec->catfile($outdir, $fileonly.'.gff');
        ($outfa = $lump) =~ s/\.gff/\.fa/;
        open $lump_fh, ">$lump" or die "Could not create a lump outfile called ($lump) because ($!)\n";
        open $lumpfa_fh, ">$outfa" or die "Could not create a lump outfile called ($outfa) because ($!)\n";

    }
    
    # open input file, unzip if req'd
    if ($stdin) {
       *FH = *STDIN;
    } elsif ( $file =~ /\.gz/ ) {
        open FH, "gunzip -c $file |";
    }
    else {
        open FH, '<', $file;
    }

    my $in = Bio::SeqIO->new(-fh => \*FH, -format => $FORMAT, -debug=>$DEBUG);
    my $gffio = Bio::Tools::GFF->new( -noparse => 1, -gff_version => $GFF_VERSION );

    while ( my $seq = $in->next_seq() ) {
        my $seq_name = $seq->accession_number;
        my $end = $seq->length;
        my @to_print;

        # arrange disposition of GFF output
        $outfile = $lump || File::Spec->catfile($outdir, $seq_name.'.gff');
        my $out;

        if ( $lump ) {
            $outfile = $lump;
            $out = $lump_fh;
        }
        else {
            $outfile = File::Spec->catfile($outdir, $seq_name.'.gff');
            open $out, ">$outfile";
        }

        # filter out unwanted features
        my $source_feat= undef;
        my @source= filter($seq); $source_feat= $source[0];

        ($source_type,$source_feat)= 
          getSourceInfo( $seq, $source_type, $source_feat ) ;
          # always; here we build main prot $source_feat; # if @source;
          
        # abort if there are no features
        warn "$seq_name has no features, skipping\n" and next
            if !$seq->all_SeqFeatures;


        $FTSOmap->{'source'} = $source_type;
        ## $FTSOmap->{'CDS'}= $PROTEIN_TYPE; # handle this in gene_features

        # construct a GFF header
        # add: get source_type from attributes of source feature? chromosome=X tag
        # also combine 1st ft line here with source ft from $seq ..
        my($header,$info)= gff_header($seq_name, $end, $source_type, $source_feat);
        print $out $header;
        print "# working on $info\n" if($verbose);
        
        # unflatten gene graphs, apply SO types, etc; this also does TypeMapper ..
        unflatten_seq($seq);

        # Note that we use our own get_all_SeqFeatures function 
        # to rescue cloned exons

        @GFF_LINE_FEAT = ();
        for my $feature ( get_all_SeqFeatures($seq) ) {
            
            my $method = $feature->primary_tag;
            next if($SOURCEID =~/UniProt|swiss|trembl/i && $method ne $source_type);
            
            $feature->seq_id($seq->id) unless($feature->seq_id);
            $feature->source_tag($SOURCEID);
            
            # dgg; need to convert some Genbank to GFF tags: note->Note; db_xref->Dbxref;
            ## also, pull any GO:000 ids from /note tag and put into Ontology_term
            maptags2gff($feature);
            
            # current gene name.  The unflattened gene features should be in order so any
            # exons, CDSs, etc that follow will belong to this gene
            my $gene_name;
            if ( $method eq 'gene' || $method eq 'pseudogene' ) {
              @to_print= print_held($out, $gffio, \@to_print);
              $gene_id = $gene_name= gene_name($feature); 
            } else {
              $gene_name= gene_name($feature);
            }
        
            #?? should gene_name from /locus_tag,/gene,/product,/transposon=xxx
            # be converted to or added as  Name=xxx (if not ID= or as well)
            ## problematic: convert_to_name ($feature); # drops /locus_tag,/gene, tags
            convert_to_name($feature); 
            
            ## dgg: extended to protein|polypeptide
            ## this test ($feature->has_tag('gene') ||) is not good: repeat_regions over genes
            ## in yeast have that genbank tag; why?
            ## these include pseudogene ...
            
            ## Note we also have mapped types to SO, so these RNA's are now transcripts:
            # pseudomRNA => "pseudogenic_transcript", 
            # pseudotranscript" => "pseudogenic_transcript", 
            # misc_RNA=>'processed_transcript',

            warn "#at: $method $gene_id/$gene_name\n" if $DEBUG;

            if ( $method =~ /(gene|RNA|CDS|exon|UTR|protein|polypeptide|transcript)/ 
               || ( $gene_id && $gene_name eq $gene_id ) ) {
               
                my $action = gene_features($feature, $gene_id, $gene_name);  # -1, 0, 1, 2 result
                if ($action == GM_DUP_PART) {
                  # ignore, this is dupl. exon with new parent ...
                  
                } elsif ($action == GM_NOT_PART) {
                  add_generic_id( $feature, $gene_name, "nocount");
                  my $gff = $gffio->gff_string($feature);
                  push @GFF_LINE_FEAT, $feature;
                  #print $out "$gff\n" if $gff;

                } elsif ($action > 0) {
                 # hold off print because exon etc. may get 2nd, 3rd parents
                  @to_print= print_held($out, $gffio, \@to_print) if ($action == GM_NEW_TOPLEVEL);
                  push(@to_print, $feature);
                }

            }
            
            # otherwise handle as generic feats with IDHandler labels 
            else {
                add_generic_id( $feature, $gene_name, "");
                my $gff= $gffio->gff_string($feature);
                push @GFF_LINE_FEAT, $feature;
                #print $out "$gff\n" if $gff;
            }
        }

        # don't like doing this after others; do after each new gene id?
        @to_print= print_held($out, $gffio, \@to_print);

        gff_validate(@GFF_LINE_FEAT);

        for my $feature (@GFF_LINE_FEAT) {
            my $gff= $gffio->gff_string($feature);
            print $out "$gff\n" if $gff;
        }

        # deal with the corresponding DNA
        my ($fa_out,$fa_outfile);
        my $dna = $seq->seq;
        if($dna || %proteinfa) {
          $method{'RESIDUES'} += length($dna);
          $dna    =~ s/(\S{60})/$1\n/g;
          $dna   .= "\n";
          
          if ($split) {
              $fa_outfile = $outfile;
              $fa_outfile =~ s/gff$/fa/;
              open $fa_out, ">$fa_outfile" or die $!; 
              print $fa_out ">$seq_name\n$dna" if $dna;
              foreach my $aid (sort keys %proteinfa) { 
                my $aa= delete $proteinfa{$aid}; 
                $method{'RESIDUES(tr)'} += length($aa);
                $aa =~ s/(\S{60})/$1\n/g; 
                print $fa_out ">$aid\n$aa\n"; 
                }
               
          }
          else {
          ## problem here when multiple GB Seqs in one file; all FASTA needs to go at end of $out
          ## see e.g. Mouse: mm_ref_chr19.gbk has NT_082868 and NT_039687 parts in one .gbk
          ## maybe write this to temp .fa then cat to end of lumped gff $out
              print $lumpfa_fh ">$seq_name\n$dna" if $dna;
              foreach my $aid (sort keys %proteinfa) { 
                my $aa= delete $proteinfa{$aid}; 
                $method{'RESIDUES(tr)'} += length($aa);
                $aa =~ s/(\S{60})/$1\n/g; 
                print $lumpfa_fh ">$aid\n$aa\n"; 
                }
          }
          
        %proteinfa=();
        }
     
        if ( $zip && !$lump ) {
            system "gzip -f $outfile";
            system "gzip -f $fa_outfile" if($fa_outfile);
            $outfile .= '.gz';
            $fa_outfile .= '.gz' if $split;
        }

        # print "\n>EOF\n" if($stdout); #?? need this if summary goes to stdout after FASTA
        print "# GFF3 saved to $outfile" unless( !$verbose || $stdout || $lump);
        print ($split ? "; DNA saved to $fa_outfile\n" : "\n") unless($stdout|| $lump);
        
        # dgg: moved to after all inputs; here it prints cumulative sum for each record
        #if ( $summary ) {
        #      print "# Summary:\n# Feature\tCount\n# -------\t-----\n";
        #  
        #      for ( keys %method ) {
        #          print "# $_  $method{$_}\n";
        #      }
        #      print "# \n";
        #  }       
    
    }

    print "# GFF3 saved to $outfile\n" if( $verbose && $lump);
    if ( $summary ) {
        print "# Summary:\n# Feature\tCount\n# -------\t-----\n";
        for ( keys %method ) {
            print "# $_  $method{$_}\n";
        }
        print "# \n";
    }
    
    ## FIXME for piped output w/ split FA files ...
    close($lumpfa_fh) if $lumpfa_fh;
    if (!$split && $outfa && $lump_fh) {     
        print $lump_fh "##FASTA\n"; # GFF3 spec
        open $lumpfa_fh, $outfa or warn "reading FA $outfa: $!";
        while( <$lumpfa_fh>) {
            print $lump_fh $_;
        } # is $lump_fh still open?
        close($lumpfa_fh);
        unlink($outfa);
    }
        

    if ( $zip && $lump ) {
        system "gzip -f $lump";
    }
    
    close FH;
}





sub typeorder {
  return 1 if ($_[0] =~ /gene/);
  return 2 if ($_[0] =~ /RNA|transcript/);
  return 3 if ($_[0] =~ /protein|peptide/);
  return 4 if ($_[0] =~ /exon|CDS/);
  return 3; # default before exon (smallest part)
}

sub sort_by_feattype {
  my($at,$bt)= ($a->primary_tag, $b->primary_tag);
  return (typeorder($at) <=> typeorder($bt))  
    or ($at cmp $bt);
    ## or ($a->name() cmp $b->name());
}

sub print_held {  
  my($out,$gffio,$to_print)= @_;
  return unless(@$to_print);
  @$to_print = sort sort_by_feattype  @$to_print; # put exons after mRNA, otherwise chado loader chokes
  while ( my $feature = shift @$to_print) {
    my $gff= $gffio->gff_string($feature); # $gff =~ s/\'/./g; # dang bug in encode
    push @GFF_LINE_FEAT, $feature;
    #print $out "$gff\n";
    }
  return (); # @to_print
}

sub maptags2gff {
  my $f = shift;
  ## should copy/move locus_tag to Alias, if not ID/Name/Alias already
  # but see below /gene /locus_tag usage
  foreach my $tag (keys %TAG_MAP) {
    if ($f->has_tag($tag)) {
      my $newtag= $TAG_MAP{$tag};
      my @v= $f->get_tag_values($tag);
      $f->remove_tag($tag);
      $f->add_tag_value($newtag,@v);
      
      ## also, pull any GO:000 ids from /note tag and put into Ontology_term
      ## ncbi syntax in CDS /note is now '[goid GO:0005886]' OR '[goid 0005624]'
      if ($tag eq 'note') {  
        map { s/\[goid (\d+)/\[goid GO:$1/g; } @v; 
        my @go= map { m/(GO:\d+)/g } @v; 
        $f->add_tag_value('Ontology_term',@go) if(@go);
        }
      
      }
    }    
}


sub getSourceInfo {
  my ($seq, $source_type, $sf) = @_;  
  
  my $is_swiss= ($SOURCEID =~/UniProt|swiss|trembl/i);
  my $is_gene = ($SOURCEID =~/entrezgene/i);
  my $is_rich = (ref($seq) =~ /RichSeq/);
  my $seq_name= $seq->accession_number();
  
  unless($sf) { # make one
    $source_type=  $is_swiss ? $PROTEIN_TYPE 
        : $is_gene ? "eneg" # "gene"  # "region" # 
        : $is_rich ? $seq->molecule : $source_type;
    $sf = Bio::SeqFeature::Generic->direct_new();
    
    my $len = $seq->length(); $len=1 if($len<1); my $start = 1; ##$start= $len if ($len<1);
    my $loc= $seq->can('location') ? $seq->location() 
            :  new Bio::Location::Simple( -start => $start, -end => $len);
    $sf->location( $loc ); 
    $sf->primary_tag($source_type);
    $sf->source_tag($SOURCEID);
    $sf->seq_id( $seq_name);
    #? $sf->display_name($seq->id()); ## Name or Alias ?
    $sf->add_tag_value( Alias => $seq->id()); # unless id == accession
    $seq->add_SeqFeature($sf);
    ## $source_feat= $sf;
  }
  
  if ($sf->has_tag("chromosome")) {
    $source_type= "chromosome"; 
    my ($chrname) = $sf->get_tag_values("chromosome");
    ## PROBLEM with Name <> ID, RefName for Gbrowse; use Alias instead
    ## e.g. Mouse chr 19 has two IDs in NCBI genbank now
    $sf->add_tag_value( Alias => $chrname );
  }

  # pull GB Comment, Description for source ft ...
  # add reference - can be long, not plain string...             
  warn "# $SOURCEID:$seq_name fields = ", join(",", $seq->annotation->get_all_annotation_keys()),"\n" if $DEBUG;
  # GenBank   fields: keyword,comment,reference,date_changed
  # Entrezgene fields 850293 =ALIAS_SYMBOL,RefSeq status,chromosome,SGD,dblink,Entrez Gene Status,OntologyTerm,LOCUS_SYNONYM

  # is this just for main $seq object or for all seqfeatures ?
  my %AnnotTagMap= ( 
      'gene_name' => 'Alias',   
      'ALIAS_SYMBOL' => 'Alias',  # Entrezgene
      'LOCUS_SYNONYM' => 'Alias', #?
      'symbol' => 'Alias',   
      'synonym' => 'Alias',   
      'dblink' => 'Dbxref',   
      'product' => 'product',
      'Reference' => 'reference',
      'OntologyTerm' => 'Ontology_term',
      'comment'  => 'Note',
      'comment1' => 'Note',
      # various map-type locations
      # gene accession tag is named per source db !??
      # 'Index terms' => keywords ??
      );
  
  
  my ($desc)= $seq->annotation->get_Annotations("desc") || ( $seq->desc() );
  my ($date)= $seq->annotation->get_Annotations("dates") 
      || $seq->annotation->get_Annotations("update-date")
      || $is_rich ? $seq->get_dates() : ();
  my ($comment)= $seq->annotation->get_Annotations("comment");
  my ($species)= $seq->annotation->get_Annotations("species");
  if (!$species 
       && $seq->can('species') 
       && defined $seq->species() 
       && $seq->species()->can('binomial') ) {
    $species= $seq->species()->binomial();
  }

  # update source feature with main GB fields
  $sf->add_tag_value( ID => $seq_name ) unless $sf->has_tag('ID');
  $sf->add_tag_value( Note => $desc ) if($desc && ! $sf->has_tag('Note'));
  $sf->add_tag_value( organism => $species ) if($species && ! $sf->has_tag('organism'));
  $sf->add_tag_value( comment1 => $comment ) if(!$is_swiss && $comment && ! $sf->has_tag('comment1'));
  $sf->add_tag_value( date => $date ) if($date && ! $sf->has_tag('date'));

  $sf->add_tag_value( Dbxref => $SOURCEID.':'.$seq_name ) if $is_swiss || $is_gene;

  foreach my $atag (sort keys %AnnotTagMap) {
      my $gtag= $AnnotTagMap{$atag}; next unless($gtag);
      my @anno = map{ 
          if (ref $_ && $_->can('get_all_values')) { 
              split( /[,;] */, join ";", $_->get_all_values) 
          }
          elsif (ref $_ && $_->can('display_text')) { 
              split( /[,;] */, $_->display_text) 
          }
          elsif (ref $_ && $_->can('value')) { 
              split( /[,;] */, $_->value) 
          } 
          else {
             ();
          }
      } $seq->annotation->get_Annotations($atag);  
      foreach(@anno) { $sf->add_tag_value( $gtag => $_ ); }
  }
    
  #my @genes = map{ split( /[,;] */, "$_"); } $seq->annotation->get_Annotations('gene_name');  
  #$sf->add_tag_value( Alias => $_ ) foreach(@genes);
  # 
  #my @dblink= map { "$_"; } $seq->annotation->get_Annotations("dblink"); # add @all 
  #$sf->add_tag_value( Dbxref => $_ ) foreach(@dblink);
  
  return (wantarray)? ($source_type,$sf) : $source_type; #?
}


sub gene_features {
    my ($f, $gene_id, $genelinkID) = @_;
    local $_ = $f->primary_tag;
    $method{$_}++;
    
    if ( /gene/ ) {
        $f->add_tag_value( ID => $gene_id ) unless($f->has_tag('ID')); # check is same value!? 
        $tnum = $rnum= 0; $ncrna_id= $rna_id  = '';
        return GM_NEW_TOPLEVEL;
        
    } elsif ( /mRNA/ ) {  
        return GM_NOT_PART unless $gene_id;
        return GM_NOT_PART if($genelinkID && $genelinkID ne $gene_id);
        ($rna_id  = $gene_id ) =~ s/gene/mRNA/;
        $rna_id   .= '.t0' . ++$tnum;
        $f->add_tag_value( ID => $rna_id );
        $f->add_tag_value( Parent => $gene_id );
        
    } elsif ( /RNA|transcript/) { 
        ## misc_RNA here; missing exons ... flattener problem?
        #  all of {t,nc,sn}RNA can have gene models now
        ## but problem in Worm chr: mRNA > misc_RNA > CDS with same locus tag
        ## CDS needs to use mRNA, not misc_RNA, rna_id ...
        ## also need to fix cases where tRNA,... lack a 'gene' parent: make this one top-level

        if($gene_id) {
          return GM_NOT_PART if($genelinkID && $genelinkID ne $gene_id);
          ($ncrna_id = $gene_id) =~ s/gene/ncRNA/;
          $ncrna_id .= '.r0' . ++$rnum;
          $f->add_tag_value( Parent => $gene_id );
          $f->add_tag_value( ID => $ncrna_id );
        } else {
          unless ($f->has_tag('ID')) {
            if($genelinkID) {
              $f->add_tag_value( ID => $genelinkID  ) ;
            } else {
              $idh->generate_unique_persistent_id($f);
            }
          }
         ($ncrna_id)= $f->get_tag_values('ID'); 
         return GM_NEW_TOPLEVEL;
          # this feat now acts as gene-top-level; need to print @to_print to flush prior exons?
        }
        
    } elsif ( /exon/ ) { # can belong to any kind of RNA
        return GM_NOT_PART unless ($rna_id||$ncrna_id);
        return GM_NOT_PART if($genelinkID && $genelinkID ne $gene_id);
        ## we are getting duplicate Parents here, which chokes chado loader, with reason...
        ## problem is when mRNA and ncRNA have same exons, both ids are active, called twice
        ## check all Parents
        for my $expar ($rna_id, $ncrna_id) { 
          next unless($expar);
          if ( $exonpar{$expar} and $f->has_tag('Parent') ) {
            my @vals = $f->get_tag_values('Parent');
            next if (grep {$expar eq $_} @vals);
            }
          $exonpar{$expar}++;
          $f->add_tag_value( Parent => $expar); 
          # last; #? could be both
        }
        # now we can skip cloned exons
        # dgg note: multiple parents get added and printed for each unique exon
        return GM_DUP_PART if ++$seen{$f} > 1;
        
    } elsif ( /CDS|protein|polypeptide/ ) {
        return GM_NOT_PART unless $rna_id; ## ignore $ncrna_id ??
        return GM_NOT_PART if($genelinkID && $genelinkID ne $gene_id); #??
        (my $pro_id = $rna_id) =~ s/\.t/\.p/;
        
        if( ! $CDSkeep && /CDS/) {  
          $f->primary_tag($PROTEIN_TYPE); 
        
          ## duplicate problem is Location ..
          if ($f->location->isa("Bio::Location::SplitLocationI")) {
            # my($b,$e)=($f->start, $f->end); # is this all we need?
            my($b,$e)=(-1,0);
            foreach my $l ($f->location->each_Location) {
               $b = $l->start if($b<0 || $b > $l->start);
               $e = $l->end if($e < $l->end);
               }
            $f->location( Bio::Location::Simple->new(
                -start => $b, -end => $e, -strand => $f->strand) );
            }

            $f->add_tag_value( Derives_from => $rna_id ); 
          }
          else {
            $f->add_tag_value( Parent => $rna_id );
          }

        $f->add_tag_value( ID => $pro_id );
        
        move_translation_fasta($f, $pro_id);
        #if( $f->has_tag('translation')) {
        #   my ($aa) = $f->get_tag_values("translation");
        #    $proteinfa{$pro_id}= $aa;
        #    $f->remove_tag("translation");
        #    $f->add_tag_value("translation","length.".length($aa)); # hack for odd chado gbl problem
        #}
    } elsif ( /region/ ) {       
        $f->primary_tag('gene_component_region');
        $f->add_tag_value( Parent => $gene_id ); 
    } else {
        return GM_NOT_PART unless $gene_id;
        $f->add_tag_value( Parent => $gene_id );  
    }
    
    ## return GM_DUP_PART if /exon/ && ++$seen{$f} > 1;
    
    return GM_NEW_PART;
}

## was generic_features >  add_generic_id
sub add_generic_id {
    my ($f, $ft_name, $flags) = @_;
    my $method = $f->primary_tag;
    $method{$method}++ unless($flags =~ /nocount/); ## double counts GM_NOT_PART from above
     
    if ($f->has_tag('ID')) {
    
    }
    elsif ( $f->has_tag($method) ) {
        my ($name) = $f->get_tag_values($method);
        $f->add_tag_value( ID => "$method:$name" );
    }
    elsif($ft_name) { # is this unique ?
        $f->add_tag_value( ID => $ft_name ); 
    }
    else {
        $idh->generate_unique_persistent_id($f);
    }

    move_translation_fasta( $f, ($f->get_tag_values("ID"))[0] )
      if($method =~ /CDS/);

    # return $io->gff_string($f);
}

sub move_translation_fasta {
    my ($f, $ft_id) = @_;
    if( $ft_id && $f->has_tag('translation') ) {
      my ($aa) = $f->get_tag_values("translation");
      if($aa && $aa !~ /^length/) {
        $proteinfa{$ft_id}= $aa;
        $f->remove_tag("translation");
        $f->add_tag_value("translation","length.".length($aa)); # hack for odd chado gbl problem
        }
    }
}

sub gff_header {
    my ($name, $end, $source_type, $source_feat) = @_;
    $source_type ||= "region";

    my $info = "$source_type:$name";
    my $head = "##gff-version $GFF_VERSION\n".
               "##sequence-region $name 1 $end\n".
               "# conversion-by bp_genbank2gff3.pl\n";
    if ($source_feat) {
        ## dgg: these header comment fields are not useful when have multi-records, diff organisms
        for my $key (qw(organism Note date)) {
            my $value;
            if ($source_feat->has_tag($key)) { 
                ($value) = $source_feat->get_tag_values($key);
            }
            if ($value) {
                $head .= "# $key $value\n";
                $info .= ", $value";
            }
        }
        $head = "" if $didheader;
    } else {
        $head .= "$name\t$SOURCEID\t$source_type\t1\t$end\t.\t.\t.\tID=$name\n";
    }
    $didheader++;
    return (wantarray) ? ($head,$info) : $head;
}

sub unflatten_seq {
    my $seq = shift;

    ## print "# working on $source_type:", $seq->accession, "\n"; 
    my $uh_oh = "Possible gene unflattening error with" .  $seq->accession_number .
                ": consult STDERR\n";
    
    eval {
        $unflattener->unflatten_seq( -seq => $seq, 
                                     -noinfer => $noinfer,
                                     -use_magic => 1 );
    };
    
    # deal with unflattening errors
    if ( $@ ) {
        warn $seq->accession_number . " Unflattening error:\n";
        warn "Details: $@\n";
        print "# ".$uh_oh;
    }

    return 0 if !$seq || !$seq->all_SeqFeatures;

    # map feature types to the sequence ontology
    ## $tm->map_types_to_SO( -seq => $seq );
    #$tm->map_types( -seq => $seq, -type_map => $FTSOmap, -undefined => "region" ); #dgg

    map_types( 
        $tm, 
        -seq => $seq, 
        -type_map  => $FTSOmap, 
        -syn_map  => $FTSOsynonyms, 
        -undefined => "region" 
    ); #nml

}

sub filter {
    my $seq = shift;
    ## return unless $filter;
    my @feats;
    my @sources; # dgg; pick source features here; only 1 always?
    if ($filter) {
      for my $f ( $seq->remove_SeqFeatures ) {
        my $m = $f->primary_tag;
        push @sources, $f if ($m eq 'source'); # dgg? but leave in @feats ?
        push @feats, $f unless $filter =~ /$m/i;
      }
      $seq->add_SeqFeature($_) foreach @feats;
    } else {
      for my $f ( $seq->get_SeqFeatures ){
        my $m = $f->primary_tag;
        push @sources, $f if ($m eq 'source'); # dgg? but leave in @feats ?
        }
    }

    return @sources;
}


# The default behaviour of Bio::FeatureHolderI:get_all_SeqFeatures
# changed to filter out cloned features.  We have to implement the old
# method.  These two subroutines were adapted from the v1.4 Bio::FeatureHolderI
sub get_all_SeqFeatures  {
    my $seq = shift;
    my @flatarr;

    foreach my $feat ( $seq->get_SeqFeatures ){
        push(@flatarr,$feat);
        _add_flattened_SeqFeatures(\@flatarr,$feat);
    }
    return @flatarr;
}

sub gene_name {
    my $g = shift;
    my $gene_id = ''; # zero it;

    if ($g->has_tag('locus_tag')) {
        ($gene_id) = $g->get_tag_values('locus_tag');
    }

    elsif ($g->has_tag('gene')) {
        ($gene_id) = $g->get_tag_values('gene'); 
    }
    elsif ($g->has_tag('ID')) { # for non-Genbank > Entrezgene
        ($gene_id) = $g->get_tag_values('ID');
    }

    ## See Unflattener comment:
    # on rare occasions, records will have no /gene or /locus_tag
    # but it WILL have /product tags. These serve the same purpose
    # for grouping. For an example, see AY763288 (also in t/data)
    # eg. product=tRNA-Asp ;  product=similar to crooked neck protein
    elsif ($g->has_tag('product')) {
        my ($name)= $g->get_tag_values('product');
        ($gene_id) = $name unless($name =~ / /); # a description not name
    }

    ## dgg; also handle transposon=xxxx ID/name
    # ID=GenBank:repeat_region:NC_004353:1278337:1281302;transposon=HeT-A{}1685;Dbxref=FLYBASE:FBti0059746
    elsif ($g->has_tag('transposon')) {
        my ($name)= $g->get_tag_values('transposon');
        ($gene_id) = $name unless($name =~ / /); # a description not name
    }
  
    return $gene_id;
}

# same list as gene_name .. change tag to generic Name
sub convert_to_name {
    my $g = shift;
    my $gene_id = ''; # zero it;
    
    if ($g->has_tag('gene')) {
        ($gene_id) = $g->get_tag_values('gene'); 
        $g->remove_tag('gene');
        $g->add_tag_value('Name', $gene_id);
    }
    elsif ($g->has_tag('locus_tag')) {
        ($gene_id) = $g->get_tag_values('locus_tag');
        $g->remove_tag('locus_tag');
        $g->add_tag_value('Name', $gene_id);
    }

    elsif ($g->has_tag('product')) {
        my ($name)= $g->get_tag_values('product');
        ($gene_id) = $name unless($name =~ / /); # a description not name
        ## $g->remove_tag('product');
        $g->add_tag_value('Name', $gene_id);
    }

    elsif ($g->has_tag('transposon')) {
        my ($name)= $g->get_tag_values('transposon');
        ($gene_id) = $name unless($name =~ / /); # a description not name
        ## $g->remove_tag('transposon');
        $g->add_tag_value('Name', $gene_id);
    }
    elsif ($g->has_tag('ID')) { 
        my ($name)= $g->get_tag_values('ID');
        $g->add_tag_value('Name', $name);
    }    
    return $gene_id;
}


sub _add_flattened_SeqFeatures  {
    my ($arrayref,$feat) = @_;
    my @subs = ();

    if ($feat->isa("Bio::FeatureHolderI")) {
        @subs = $feat->get_SeqFeatures;
    } 
    elsif ($feat->isa("Bio::SeqFeatureI")) {
        @subs = $feat->sub_SeqFeature;
    }
    else {
        warn ref($feat)." is neither a FeatureHolderI nor a SeqFeatureI. ".
            "Don't know how to flatten.";
    }

    for my $sub (@subs) {
        push(@$arrayref,$sub);
        _add_flattened_SeqFeatures($arrayref,$sub);
    }

}

sub map_types {

    my ($self, @args) = @_;

    my($sf, $seq, $type_map, $syn_map, $undefmap) =
        $self->_rearrange([qw(FEATURE
                    SEQ
                    TYPE_MAP
                    SYN_MAP
                    UNDEFINED
                    )],
                @args);

    if (!$sf && !$seq) {
        $self->throw("you need to pass in either -feature or -seq");
    }

    my @sfs = ($sf);
    if ($seq) {
        $seq->isa("Bio::SeqI") || $self->throw("$seq NOT A SeqI");
        @sfs = $seq->get_all_SeqFeatures;
    }
    $type_map = $type_map || $self->typemap; # dgg: was type_map;
    foreach my $feat (@sfs) {

        $feat->isa("Bio::SeqFeatureI") || $self->throw("$feat NOT A SeqFeatureI");
        $feat->isa("Bio::FeatureHolderI") || $self->throw("$feat NOT A FeatureHolderI");

        my $primary_tag = $feat->primary_tag;

        #if ($primary_tag =~ /^pseudo(.*)$/) {
        #    $primary_tag = $1;
        #    $feat->primary_tag($primary_tag);
        #}

        my $mtype = $type_map->{$primary_tag};
        if ($mtype) {
            if (ref($mtype)) {
                if (ref($mtype) eq 'ARRAY') {
                    my $soID;
                    ($mtype, $soID) = @$mtype;

                    if ($soID && ref($ONTOLOGY)) {
                        my ($term) = $ONTOLOGY->find_terms(-identifier => $soID);
                        $mtype = $term->name if $term;
                    } 
                    # if SO ID is undefined AND we have an ontology to search, we want to delete 
                    # the feature type hash entry in order to force a fuzzy search
                    elsif (! defined $soID && ref($ONTOLOGY)) {
                        undef $mtype;
                        delete $type_map->{$primary_tag};
                    } 
                    elsif ($undefmap && $mtype eq 'undefined') { # dgg
                        $mtype= $undefmap;
                    }

                    $type_map->{$primary_tag} = $mtype if $mtype;
                }
                elsif (ref($mtype) eq 'CODE') {
                    $mtype = $mtype->($feat);
                }
                else {
                    $self->throw('must be scalar or CODE ref');
                }
            }
            elsif ($undefmap && $mtype eq 'undefined') { # dgg
                $mtype= $undefmap;
            }
            $feat->primary_tag($mtype);
        }

        if ($CONF) {
            conf_read(); 
            my %perfect_matches;
            while (my ($p_tag,$rules) = each %$YAML) {
                RULE:
                for my $rule (@$rules) {
                    for my $tags (@$rule) {
                        while (my ($tag,$values) = each %$tags) {
                            for my $value (@$values) {
                                if ($feat->has_tag($tag)) {
                                    for ($feat->get_tag_values($tag)) {
                                        next RULE unless $_ =~ /\Q$value\E/;
                                    }
                                } elsif ($tag eq 'primary_tag') {
                                    next RULE unless $value eq
                                        $feat->primary_tag; 
                                } elsif ($tag eq 'location') {
                                    next RULE unless $value eq
                                        $feat->start.'..'.$feat->end;
                                } else { next RULE }
                            }
                        }
                    }
                    $perfect_matches{$p_tag}++;
                }
            }
            if (scalar(keys %perfect_matches) == 1) {
                $mtype = $_ for keys %perfect_matches;
            } elsif (scalar(keys %perfect_matches) > 1) {
                warn "There are conflicting rules in the config file for the" .
                     " following types: ";
                warn "\t$_\n" for keys %perfect_matches;
                warn "Until conflict resolution is built into the converter," .
                     " you will have to manually edit the config file to remove the" .
                     " conflict. Sorry :(. Skipping user preference for this entry";
                sleep(2);
            }
        } 

        if ( ! $mtype  && $syn_map) {
            if ($feat->has_tag('note')) {

                my @all_matches;

                my @note = $feat->each_tag_value('note');

                for my $k (keys %$syn_map) {

                    if ($k =~ /"(.+)"/) {

                        my $syn = $1;

                        for my $note (@note) {

                            # look through the notes to see if the description
                            # is an exact match for synonyms
                            if ( $syn eq $note ) { 

                                my @map = @{$syn_map->{$k}};

                                
                                my $best_guess = $map[0];

                                unshift @{$all_matches[-1]}, [$best_guess];

                                $mtype = $MANUAL
                                    ? manual_curation($feat, $best_guess, \@all_matches)
                                    : $best_guess;

                                print '#' x 78 . "\nGuessing the proper SO term for GenBank"
                                    . " entry:\n\n" . GenBank_entry($feat) . "\nis:\t$mtype\n" 
                                    . '#' x 78 . "\n\n";

                            } else {
                                # check both primary tag and and note against
                                # SO synonyms for best matching description

                                SO_fuzzy_match( $k, $primary_tag, $note, $syn, \@all_matches); 
                            }

                        }
                    } 
                }

                #unless ($mtype) {
                for my $note (@note) {
                    for my $name (values %$type_map) {
                    # check primary tag against SO names for best matching
                    # descriptions //NML also need to check against
                    # definition && camel case split terms

                        SO_fuzzy_match($name, $primary_tag, $note, $name, \@all_matches);
                    }
                }
                #}

                if (scalar(@all_matches) && !$mtype) {

                    my $top_matches = first { defined $_ } @{$all_matches[-1]}; 

                    my $best_guess = $top_matches->[0];



                    # if guess has quotes, it is a synonym term. we need to 
                    # look up the corresponding name term
                    # otherwise, guess is a name, so we can use it directly
                    if ($best_guess =~ /"(.+)"/) {

                        $best_guess = $syn_map->{$best_guess}->[0];

                    } 

                    @RETURN = @all_matches;
                    $mtype = $MANUAL
                        ? manual_curation($feat, $best_guess, \@all_matches)
                        : $best_guess;

                    print '#' x 78 . "\nGuessing the proper SO term for GenBank"
                        . " entry:\n\n" . GenBank_entry($feat) . "\nis:\t$mtype\n" 
                        . '#' x 78 . "\n\n";

                }
            }
            $mtype ||= $undefmap;
            $feat->primary_tag($mtype);
        } 
    }


}

sub SO_fuzzy_match {

    my $candidate = shift;
    my $primary_tag = shift;
    my $note = shift;
    my $SO_terms = shift;
    my $best_matches_ref = shift;
    my $modifier = shift; 

    $modifier ||= '';

        my @feat_terms;

    for ( split(" |_", $primary_tag) ) {
        #my @camelCase = /(?:[A-Z]|[a-z])(?:[A-Z]+|[a-z]*)(?=$|[A-Z])/g;
        my @camelCase = /(?:[A-Z]|[a-z])(?:[A-Z]+|[a-z]*)(?=$|[A-Z]|[;:.,])/g;
        push @feat_terms, @camelCase;
    }

    for ( split(" |_", $note) ) {
        #my @camelCase = /(?:[A-Z]|[a-z])(?:[A-Z]+|[a-z]*)(?=$|[A-Z])/g;
        #my @camelCase = /(?:[A-Z]|[a-z])(?:[A-Z]+|[a-z]*)(?=$|[A-Z]|[;:.,])/g;
        (my $word = $_) =~ s/[;:.,]//g;
        push @feat_terms, $word;
    }


    my @SO_terms = split(" |_", $SO_terms);

    # fuzzy match works on a simple point system. When 2 words match,
    # the $plus counter adds one. When they don't, the $minus counter adds
    # one. This is used to sort similar matches together. Better matches
    # are found at the end of the array, near the top.

    # NML: can we improve best match by using synonym tags
    # EXACT,RELATED,NARROW,BROAD?

    my ($plus, $minus) = (0, 0); 
    my %feat_terms;
    my %SO_terms;

    #unique terms
    map {$feat_terms{$_} = 1} @feat_terms;
    map {$SO_terms{$_} = 1} @SO_terms;

    for my $st (keys %SO_terms) {
        for my $ft (keys %feat_terms) {

            ($st =~ m/$modifier\Q$ft\E/) ? $plus++ : $minus++;

        }
    }

    push @{$$best_matches_ref[$plus][$minus]}, $candidate if $plus;

}

sub manual_curation {

    my ($feat, $default_opt,  $all_matches) = @_; 

    my @all_matches = @$all_matches;

    # convert all SO synonyms into names and filter
    # all matches into unique term list because
    # synonyms can map to multiple duplicate names

    my (@unique_SO_terms, %seen);
    for (reverse @all_matches) {
        for (@$_) {
            for (@$_) {
                #my @names;
                if ($_ =~ /"(.+)"/) {
                    for (@{$SYN_MAP->{$_}}) {
                        push @unique_SO_terms, $_ unless $seen{$_};
                        $seen{$_}++;
                    }
                } else { 
                    push @unique_SO_terms, $_ unless $seen{$_};
                    $seen{$_}++;
                }
            }
        }
    }

    my $s = scalar(@unique_SO_terms);

    my $choice = 0;

    my $more = 
        "[a]uto   : automatic input (selects best guess for remaining entries)\r" .
        "[f]ind   : search for other SO terms matching your query (e.g. f gene)\r" . 
        "[i]nput  : add a specific term\r" .
        "[r]eset  : reset to the beginning of matches\r" .
        "[s]kip   : skip this entry (selects best guess for this entry)\r"
    ;

    $more .= 
        "[n]ext   : view the next ".OPTION_CYCLE." terms\r" .
        "[p]rev   : view the previous ".OPTION_CYCLE." terms" if ($s > OPTION_CYCLE);

    my $msg = #"\n\n" . '-' x 156 . "\n"
         "The converter found $s possible matches for the following GenBank entry: ";

    my $directions = 
        "Type a number to select the SO term that best matches"
        . " the genbank entry, or use any of the following options:\r" . '_' x 76 . "\r$more"; 


    # lookup filtered list to pull out definitions
    my @options = map { 
        my $term = $_;
        my %term;
        for (['name', 'name'], ['def', 'definition'], ['synonym',
                'each_synonym']) {
            my ($label, $method) = @$_;
            $term{$label} = \@{[$term->$method]};
        }
        [++$choice, $_->name, ($_->definition || 'none'), \%term, $_->each_synonym ];
    }  map { $ONTOLOGY->find_terms(-name => $_) } @unique_SO_terms;


    my $option = options_cycle(0, OPTION_CYCLE, $msg, $feat, $directions,
            $default_opt, @options);

    if ($option eq 'skip') { return $default_opt 
    } elsif ($option eq 'auto') {
        $MANUAL = 0;
        return $default_opt;
    } else { return $option }

}

sub options_cycle {

    my ($start, $stop, $msg, $feat, $directions, $best_guess, @opt) = @_;

    #NML: really should only call GenBank_entry once. Will need to change
    #method to return array & shift off header
    my $entry = GenBank_entry($feat, "\r");

    my $total = scalar(@opt);

    ($start,$stop) = (0, OPTION_CYCLE) 
        if ( ($start < 0) && ($stop > 0) );

    ($start,$stop) = (0, OPTION_CYCLE) 
        if ( ( ($stop - $start) < OPTION_CYCLE ) && $stop < $total);

    ($start,$stop) = ($total - OPTION_CYCLE, $total) if $start < 0;
    ($start,$stop) = (0, OPTION_CYCLE) if $start >= $total;

    $stop = $total if $stop > $total;

    my $dir_copy = $directions;
    my $msg_copy = $msg;
    my $format = "format STDOUT = \n" .
        '-' x 156 . "\n" . 
        '^' . '<' x 77 .  '| Available Commands:' . "\n" .
        '$msg_copy' . "\n" .
        '-' x 156 . "\n" . 
        ' ' x 78 . "|\n" .
        '^' . '<' x 77 . '| ^' . '<' x 75 . '~' . "\n" .
        '$entry' . ' ' x 74 . '$dir_copy,' . "\n" .
        (' ' x 20 . '^' . '<' x 57 . '| ^' . '<' x 75 . '~' . "\n" .
        ' ' x 20 . '$entry,' . ' ' x 53 . '$dir_copy,' . "\n") x 1000  . ".\n";

    {
        # eval throws redefined warning that breaks formatting. 
        # Turning off warnings just for the eval to fix this.
        no warnings 'redefine';
        eval $format;
    }

    write;

    print '-' x 156 . "\n" .
        'Showing results ' . ( $stop ? ( $start + 1 ) : $start ) . 
        " - $stop of possible SO term matches: (best guess is \"$best_guess\")" .
        "\n" . '-' x 156 . "\n"; 

    for  (my $i = $start; $i < $stop; $i+=2) {

        my ($left, $right) = @opt[$i,$i+1];

        my ($nL, $nmL, $descL, $termL, @synL) = @$left;

        #odd numbered lists can cause fatal undefined errors, so check
        #to make sure we have data
        
        my ($nR, $nmR, $descR, $termR, @synR) = ref($right) ? @$right : (undef, undef, undef);


        my $format = "format STDOUT = \n";

        $format .=
            ' ' x 78 . "|\n" .

            '@>>: name: ^' . '<' x 64 . '~' . ' |' .
                ( ref($right) ? ('@>>: name: ^' . '<' x 64 . '~' ) : '' ) .  "\n" .
            '$nL,' . ' ' x 7 . '$nmL,' .
                ( ref($right) ? (' ' x 63 . '$nR,' .  ' ' x 7 .  "\$nmR,") : '' ) . "\n" .

            ' ' x 11 . '^' . '<' x 61 . '...~' . ' |' . 
                (ref($right) ? ('           ^' . '<' x 61 .  '...~') : '') . "\n" .
            ' ' x 11 . '$nmL,' . 
                (ref($right) ? (' ' x 74 . '$nmR,') : '') . "\n" .
            #' ' x 78 . '|' . "\n" .


            '     def:  ^' . '<' x 65 . ' |' . 
                (ref($right) ? ('     def:  ^' . '<' x 64 . '~') : '') . "\n" .
            ' ' x 11 . '$descL,' . 
                (ref($right) ? (' ' x 72 . '$descR,') : '') . "\n" .


            ('           ^' . '<' x 65 . ' |' . 
                (ref($right) ? ('           ^' . '<' x 64 . '~') : '') . "\n" .
            ' ' x 11 . '$descL,' . 
                (ref($right) ? (' ' x 72 . '$descR,') : '') . "\n") x 5 .


            '           ^' . '<' x 61 . '...~ |' . 
                (ref($right) ? ('           ^' . '<' x 61 . '...~') : '') . "\n" .
            ' ' x 11 . '$descL,' . 
                (ref($right) ? (' ' x 72 . '$descR,') : '') . "\n" .

            ".\n";

        {
            # eval throws redefined warning that breaks formatting. 
            # Turning off warnings just for the eval to fix this.
            no warnings 'redefine';
            eval $format;
        }
        write;

    }   
    print '-' x 156 . "\nenter a command:";

    while (<STDIN>) {

        (my $input = $_) =~ s/\s+$//;

        if ($input =~ /^\d+$/) {
            if ( $input && defined $opt[$input-1] ) {
                return $opt[$input-1]->[1]
            } else {
                print "\nThat number is not an option. Please enter a valid number.\n:";
            }
        } elsif ($input =~ /^n/i | $input =~ /next/i ) {
            return options_cycle($start + OPTION_CYCLE, $stop + OPTION_CYCLE, $msg, 
                    $feat, $directions, $best_guess, @opt)
        } elsif ($input =~ /^p/i | $input =~ /prev/i ) {
            return options_cycle($start - OPTION_CYCLE, $stop - OPTION_CYCLE, $msg,
                    $feat, $directions, $best_guess, @opt)
        } elsif ( $input =~ /^s/i || $input =~ /skip/i ) { return 'skip' 
        } elsif ( $input =~ /^a/i || $input =~ /auto/i ) { return 'auto' 
        } elsif ( $input =~ /^r/i || $input =~ /reset/i ) { 
            return manual_curation($feat, $best_guess, \@RETURN );
        } elsif ( $input =~ /^f/i || $input =~ /find/i ) {

            my ($query, @query_results);

            if ($input =~ /(?:^f|find)\s+?(.*?)$/) { $query = $1;
            } else {

                #do a SO search
                print "Type your search query\n:";
                while (<STDIN>) { chomp($query = $_); last }
            }

            for (keys(%$TYPE_MAP), keys(%$SYN_MAP)) {
                SO_fuzzy_match($_, $query, '', $_, \@query_results, '(?i)');
            }

            return manual_curation($feat, $best_guess, \@query_results);

        } elsif ( $input =~ /^i/i || $input =~ /input/i ) {

            #NML fast input for later
            #my $query;
            #if ($input =~ /(?:^i|input)\s+?(.*?)$/) { $query = $1 };

            #manual input
            print "Type the term you want to use\n:";
            while (<STDIN>) {
                chomp(my $input = $_);

                if (! $TYPE_MAP->{$input}) {

                    print "\"$input\" doesn't appear to be a valid SO term. Are ".
                        "you sure you want to use it? (y or n)\n:";

                    while (<STDIN>) {

                        chomp(my $choice = $_);

                        if ($choice eq 'y') {
                            print 
                                "\nWould you like to save your preference for " .
                                "future use (so you don't have to redo manual " .
                                "curation for this feature everytime you run " . 
                                "the converter)? (y or n)\n";

                            #NML: all these while loops are a mess. Really should condense it.
                            while (<STDIN>) {

                                chomp(my $choice = $_);

                                if ($choice eq 'y') {
                                    curation_save($feat, $input);
                                    return $input;
                                } elsif ($choice eq 'n') {
                                    return $input
                                } else {
                                    print "\nDidn't recognize that command. Please " . 
                                        "type y or n.\n:" 
                                }
                            }

                                
                        } elsif ($choice eq 'n') {
                            return options_cycle($start, $stop, $msg, $feat,
                                    $directions, $best_guess, @opt)
                        } else {
                            print "\nDidn't recognize that command. Please " . 
                                "type y or n.\n:" 
                        }
                    }

                } else { 
                    print 
                        "\nWould you like to save your preference for " .
                        "future use (so you don't have to redo manual " .
                        "curation for this feature everytime you run  " . 
                        "the converter)? (y or n)\n";

                    #NML: all these while loops are a mess. Really should condense it.
                    while (<STDIN>) {

                        chomp(my $choice = $_);

                        if ($choice eq 'y') {
                            curation_save($feat, $input);
                            return $input;
                        } elsif ($choice eq 'n') {
                            return $input
                        } else {
                            print "\nDidn't recognize that command. Please " . 
                                "type y or n.\n:" 
                        }
                    }

                } 

            }
        } else { 
            print "\nDidn't recognize that command. Please re-enter your choice.\n:" 
        }
    }

}

sub GenBank_entry {
    my ($f, $delimiter, $num) = @_;

    $delimiter ||= "\n";


    my $entry  = 

        ($num ? ' [1] ' : ' ' x 5) . $f->primary_tag 
        . ($num 
            ? ' ' x (12 - length $f->primary_tag ) . ' [2] '
            : ' ' x (15 - length $f->primary_tag) 
          )
        . $f->start.'..'.$f->end

        . "$delimiter";

    if ($num) {
        words_tag($f, \$entry);
    } else {
        for my $tag ($f->all_tags) {
            for my $val ( $f->each_tag_value($tag) ) {
                $entry .= ' ' x 20;
                #$entry .= "/$tag=\"$val\"$delimiter";
                $entry .= $val eq '_no_value'
                    ? "/$tag$delimiter"
                    : "/$tag=\"$val\"$delimiter";
            }
        }

    }

    return $entry;
}


sub gff_validate {
    warn "Validating GFF file\n" if $DEBUG;
    my @feat = @_;

    my (%parent2child, %all_ids, %descendants, %reserved);

    for my $f (@feat) {
        for my $aTags (['Parent', \%parent2child], ['ID', \%all_ids]) {
            map { push @{$$aTags[1]->{$_}}, $f } $f->get_tag_values($$aTags[0])
                if $f->has_tag($$aTags[0]); 
        }
    }

    if ($SO_FILE) {
        while (my ($parentID, $aChildren) = each %parent2child) {
            parent_validate($parentID, $aChildren, \%all_ids, \%descendants, \%reserved);
        }
    }

    id_validate(\%all_ids, \%reserved);        
}

sub parent_validate {
    my ($parentID, $aChildren, $hAll, $hDescendants, $hReserved) = @_;

    my $aParents = $hAll->{$parentID};

    map { 
        my $child = $_;
        $child->add_tag_value( validation_error => 
        "feature tried to add Parent tag, but no Parent found with ID $parentID"
        );
        my %parents;
        map { $parents{$_} = 1 } $child->get_tag_values('Parent');
        delete $parents{$parentID};
        my @parents = keys %parents;

        $child->remove_tag('Parent');

        unless ($child->has_tag('ID')) {
            my $id = gene_name($child);
            $child->add_tag_value('ID', $id);
            push @{$hAll->{$id}}, $child
        }

        $child->add_tag_value('Parent', @parents) if @parents;

    } @$aChildren and return unless scalar(@$aParents);

    my $par = join(',', map { $_->primary_tag } @$aParents);
    warn scalar(@$aParents)." POSSIBLE PARENT(S): $par" if $DEBUG;

    #NML manual curation needs to happen here


    my %parentsToRemove;

    CHILD:
    for my $child (@$aChildren) {
        my $childType  = $child->primary_tag;

        warn "WORKING ON $childType at ".$child->start.' to '.$child->end 
            if $DEBUG;

        for (my $i = 0; $i < scalar(@$aParents); $i++) {
            my $parent = $aParents->[$i];
            my $parentType = $parent->primary_tag;

            warn "CHECKING $childType against $parentType" if $DEBUG;

            #cache descendants so we don't have to do repeat searches
            unless ($hDescendants->{$parentType}) {

                for my $term ($ONTOLOGY->find_terms(
                        -name => $parentType
                    ) ) {
                    
                    map {
                        $hDescendants->{$parentType}{$_->name}++
                    } $ONTOLOGY->get_descendant_terms($term);

                }

                # NML: hopefully temporary fix.
                # SO doesn't consider exon/CDS to be a child of mRNA
                # even though common knowledge dictates that they are
                # This cheat fixes the false positives for now
                if ($parentType eq 'mRNA') {
                    $hDescendants->{$parentType}{'exon'} = 1;
                    $hDescendants->{$parentType}{'CDS'} = 1;
                }

            }

            warn "\tCAN $childType at " . $child->start . ' to ' . $child->end .
                " be a child of $parentType?" if $DEBUG;
            if ($hDescendants->{$parentType}{$childType}) {
                warn "\tYES, $childType can be a child of $parentType" if $DEBUG;

                #NML need to deal with multiple children matched to multiple different
                #parents. This model only assumes the first parent id that matches a child will
                #be the reserved feature. 

                $hReserved->{$parentID}{$parent}{'parent'} = $parent;
                push @{$hReserved->{$parentID}{$parent}{'children'}}, $child;

                #mark parent for later removal from all IDs 
                #so we don't accidentally change any parents

                $parentsToRemove{$i}++;

                next CHILD;
            } 
        }


        
        #NML shouldn't have to check this; somehow child can lose Parent
        #it's happening W3110
        #need to track this down
        if ( $child->has_tag('Parent') ) {

            warn "\tNO, @{[$child->primary_tag]} cannot be a child of $parentID"
                if $DEBUG;

            my %parents;

            map { $parents{$_} = 1 } $child->get_tag_values('Parent');

            delete $parents{$parentID};
            my @parents = keys %parents;

            warn 'VALIDATION ERROR '.$child->primary_tag." at ".$child->start .
                ' to ' . $child->end . " cannot be a child of ID $parentID"
                if $DEBUG;

            $child->add_tag_value( validation_error => 
                    "feature cannot be a child of $parentID");

            $child->remove_tag('Parent');

            unless ($child->has_tag('ID')) {
                my $id = gene_name($child);
                $child->add_tag_value('ID', $id);
                push @{$hAll->{$id}}, $child
            }

            $child->add_tag_value('Parent', @parents) if @parents;
        }

    }
    
    #delete $aParents->[$_] for keys %parentsToRemove;
    splice(@$aParents, $_, 1) for keys %parentsToRemove;
}

sub id_validate {
    my ($hAll, $hReserved) = @_;


    for my $id (keys %$hAll) {

        #since 1 feature can have this id, 
        #let's just shift it off and uniquify
        #the rest (unless it's reserved)

        shift @{$hAll->{$id}} unless $hReserved->{$id};
        for my $feat (@{$hAll->{$id}}) {
            id_uniquify(0, $id, $feat, $hAll);
        }
    }

    for my $parentID (keys %$hReserved) {

        my @keys = keys %{$hReserved->{$parentID}};

        shift @keys;

        for my $k (@keys) {
            my $parent = $hReserved->{$parentID}{$k}{'parent'};
            my $aChildren= $hReserved->{$parentID}{$k}{'children'};

            my $value = id_uniquify(0, $parentID, $parent, $hAll);
            for my $child (@$aChildren) {

                my %parents;
                map { $parents{$_}++ } $child->get_tag_values('Parent');
                $child->remove_tag('Parent');
                delete $parents{$parentID};
                $parents{$value}++;
                my @parents = keys %parents;
                $child->add_tag_value('Parent', @parents);
            }

        }
    }
}

sub id_uniquify {
    my ($count, $value, $feat, $hAll) = @_;

    warn "UNIQUIFYING $value" if $DEBUG;

    if (! $count) {
        $feat->add_tag_value(Alias => $value);
        $value .= ('.' . $feat->primary_tag) 
    } elsif ($count == 1) {
        $value .= ".$count" 
    } else { 
        chop $value;
        $value .= $count 
    }
    $count++;

    warn "ENDED UP WITH $value" if $DEBUG;
    if ( $hAll->{$value} ) { 
        warn "$value IS ALREADY TAKEN" if $DEBUG;
        id_uniquify($count, $value, $feat, $hAll);
    } else { 
        #warn "something's breaking ".$feat->primary_tag.' at '.$feat->start.' to '.$feat->end;
        $feat->remove_tag('ID');
        $feat->add_tag_value('ID', $value);
        push @{$hAll->{$value}}, $value;
    }

    $value;
}

sub conf_read {

    print "\nCannot read $CONF. Change file permissions and retry, " .
        "or enter another file\n" and conf_locate() unless -r $CONF;

    print "\nCannot write $CONF. Change file permissions and retry, " .
        "or enter another file\n" and conf_locate() unless -w $CONF;

    $YAML = LoadFile($CONF);

}

sub conf_create {

    my ($path, $input) = @_;

    print "Cannot write to $path. Change directory permissions and retry " .
        "or enter another save path\n" and conf_locate() unless -w $path;

    $CONF = $input;

    open(FH, '>', $CONF);
    close(FH);
    conf_read();


}

sub conf_write { DumpFile($CONF, $YAML) }

sub conf_locate {

    print "\nEnter the location of a previously saved config, or a new " .
        "path and file name to create a new config (this step is " .
        "necessary to save any preferences)";

    print "\n\nenter a command:";

    while (<STDIN>) {
        chomp(my $input = $_);
        my ($fn, $path, $suffix) = fileparse($input, qr/\.[^.]*/);

        if (-e $input && (! -d $input)) {

            print "\nReading $input...\n";
            $CONF = $input;

            conf_read(); 
            last;

        } elsif (! -d $input && $fn.$suffix) {

            print "Creating $input...\n";
            conf_create($path, $input);
            last;

        } elsif (-e $input && -d $input) {
            print "You only entered a directory. " .
                "Please enter BOTH a directory and filename\n";
        } else { 
            print "$input does not appear to be a valid path. Please enter a " .
                "valid directory and filename\n";
        }
        print "\nenter a command:";
    }
}

sub curation_save {

    my ($feat, $input) = @_;

    #my $error = "Enter the location of a previously saved config, or a new " .
    #    "path and file name to create a new config (this step is " .
    #    "necessary to save any preferences)\n";

    if (!$CONF) {
        print "\n\n"; 
        conf_locate();
    } elsif (! -e $CONF) {
        print "\n\nThe config file you have chosen doesn't exist.\n";
        conf_locate();
    } else { conf_read() }

    my $entry = GenBank_entry($feat, "\r", 1);

    my $msg = "Term entered: $input";
    my $directions = "Please select any/all tags that provide evidence for the term you
have entered. You may enter multiple tags by separating them by commas/dashes
(e.g 1,3,5-7). For tags with more than one word value (i.e 'note'), you have
the option of either selecting the entire note as evidence, or specific
keywords. If a tag has multiple keywords, they will be tagged alphabetically
for selection. To select a specific keyword in a tag field, you must enter the
tag number followed by the keyword letter (e.g 3a). Multiple keywords may be
selected by entering each letter separated by commas/dashes (e.g 3b,f,4a-c). The more tags you select, the more specific the GenBank entry will have
to be to match your curation. To match the GenBank entry exactly as it
appears, type every number (start-end), or just type 'all'. Remember, once the converter saves your
preference, you will no longer be prompted to choose a feature type for any
matching entries until you edit the curation.ini file.";
    my $msg_copy = $msg;
    my $dir_copy = $directions;

    my $format = "format STDOUT = \n" .
        '-' x 156 . "\n" . 
        '^' . '<' x 77 .  '| Directions:' . "\n" .
        '$msg_copy' . "\n" .
        '-' x 156 . "\n" . 
        ' ' x 78 . "|\n" .
        '^' . '<' x 77 . '| ^' . '<' x 75 . '~' . "\n" .
        '$entry' . ' ' x 74 . '$dir_copy,' . "\n" .
        (' ' x 15 . '^' . '<' x 62 . '| ^' . '<' x 75 . '~' . "\n" .
        ' ' x 15 . '$entry,' . ' ' x 58 . '$dir_copy,' . "\n") x 20  . ".\n";

    {
        # eval throws redefined warning that breaks formatting. 
        # Turning off warnings just for the eval to fix this.
        no warnings 'redefine';
        eval $format;
    }

    write;
    print '-' x 156 . "\nenter a command:";

    my @tags = words_tag($feat); 

    my $final = {};
    my $choices;
    while (<STDIN>) {

        chomp(my $choice = $_);

        if (scalar(keys %$final) && $choice =~ /^y/i) { last 

        } elsif (scalar(keys %$final) && $choice =~ /^n/i) { curation_save($feat, $input) 

        } elsif (scalar(keys %$final)) { print "\nInvalid selection. Please try again\n";

        } elsif ($choice eq 'all') {

            $choice = '';
            for (my $i=1; $i < scalar(@tags); $i++) {
                $choice .= "$i,";
            }
            chop $choice;
        } 
        #print "CHOICE [$choice]";

        my @selections;
        for (split(/(?<=\w)[^[:alnum:]\-]+(?=\d)/, $choice)) {
            if ($_ =~ /(\d+)(?:\D*)-(\d+)(.*)/) { 

                for ($1..$2) { push @selections, $_ }

                my $dangling_alphas = $3;
                alpha_expand($dangling_alphas, \@selections);

            } else { 
                alpha_expand($_, \@selections);
            }
        }

        foreach my $numbers (@selections) {

            my @c = split(/(?=[\w])/, $numbers);
            s/\W+//g foreach @c;
            my $num;
            
            {
                $^W = 0;
                $num = 0 + shift @c;
            }

            my $tag = $tags[$num];
            if (ref $tag && scalar(@c)) {
                my $no_value;
                foreach (@c) {
                    if (defined $tag->{$_}) {
                        $choices .= "${num}[$_] ";
                        my ($t,$v) = @{$tag->{$_}};
                        push @{${$final->{$input}}[0]{$t}}, $v;

                    } else { $no_value++ }
                    }

                if ($no_value) { 
                    _selection_add($tag,$final,$input,\$choices,$num);
                    #my ($t,$v) = @{$tag->{'all'}};
                    #unless (defined ${$final->{$input}}[0]{$t}) {
                        #$choices .= "$num, ";
                        #push @{${$final->{$input}}[0]{$t}}, $v
                    #}
                }

                $choices = substr($choices, 0, -2);
                $choices .= ', ';

            } elsif (ref $tag) { 
                _selection_add($tag,$final,$input,\$choices,$num);
                #my ($t,$v) = @{$tag->{'all'}};
                #unless (defined ${$final->{$input}}[0]{$t}) {
                    #$choices .= "$num, ";
                    #push @{${$final->{$input}}[0]{$t}}, $v
                #}
            } 
        }
        $choices = substr($choices, 0, -2) if $choices;
        if ($final) {
            print "\nYou have chosen the following tags:\n$choices\n";
            print "This will be written to the config file as:\n";
            print Dump $final;
            print "\nIs this correct? (y or n)\n";
        } else { print "\nInvalid selection. Please try again\n" }
    }
    push @{$YAML->{$input}}, $final->{$input};
    conf_write();
}

#  words_tag() splits each tag value string into multiple words so that the 
#  user can select the parts he/she wants to use for curation
#  it can tag 702 (a - zz) separate words; this should be enough

sub words_tag {

    my ($feat, $entry) = @_;

    my @tags;

    @tags[1,2] = ({'all' => ['primary_tag', $feat->primary_tag]}, {'all' => ['location', $feat->start.'..'.$feat->end]});
    my $i = 3;
    foreach my $tag ($feat->all_tags) {
        foreach my $value ($feat->each_tag_value($tag)) {

            my ($string, $tagged_string);

            my @words = split(/(?=\w+?)/, $value);

            my $pos = 0;


            foreach my $word (@words) {

                (my $sanitized_word = $word) =~ s/\W+?//g;
                $string .= $word;

                my $lead = int($pos/ALPHABET_DIVISOR);
                my $lag = $pos % ALPHABET_DIVISOR;

                my $a =  $lead ? ${(ALPHABET)}[$lead-1] : '';
                $a .= $lag ? ${(ALPHABET)}[$lag] : 'a';

                $tagged_string .= " ($a) $word";

                $tags[$i]{$a} = [$tag, $sanitized_word];
                $pos++;
            }

            $value = $tagged_string if scalar(@words) > 1;

            $$entry .= "[$i] /$tag=\"$value\"\r";

            $tags[$i]{'all'} = [$tag, $string];
        }
        $i++;
    }

    return @tags;
    
}

sub alpha_expand {

    my ($dangling_alphas, $selections) = @_;

    if (defined($dangling_alphas) && $dangling_alphas =~ /(\d)*([[:alpha:]]+)-([[:alpha:]]+)/) {

        my $digit = $1;
        push @$selections, $digit if $digit;

        my $start = $2;
        my $stop = $3;

        my @starts = split('', $start);
        my @stops = split('', $stop);

        my ($final_start, $final_stop);

        for ([\$final_start, \@starts], [\$final_stop, \@stops]) {

            my ($final, $splits) = @$_;

            my $int = ${(ALPHABET_TO_NUMBER)}{$$splits[0]};
            my $rem;


            if ($$splits[1]) {
                $rem = ${(ALPHABET_TO_NUMBER)}{$$splits[1]};
                $int++
            } else {
                $rem = $int;
                $int = 0;
            }


            $$final = $int * ALPHABET_DIVISOR;
            $$final += $rem;

        }

        my $last_number = pop @$selections;
        for my $pos ($final_start..$final_stop) {
            my $lead = int($pos/ALPHABET_DIVISOR);
            my $lag = $pos % ALPHABET_DIVISOR;
            my $alpha =  $lead ? ${(ALPHABET)}[$lead-1] : '';
            $alpha .= $lag ? ${(ALPHABET)}[$lag] : 'a';
            push @$selections, $last_number.$alpha;        
        }

    } elsif (defined($dangling_alphas)) { 
        if ($dangling_alphas =~ /^\d/) {
            push @$selections, $dangling_alphas;
        } elsif ($dangling_alphas =~ /^\D/) {
            #print "$dangling_alphas ".Dumper @$selections;
            my $last_number = pop @$selections;
            $last_number ||= '';
            push @$selections, $last_number.$dangling_alphas;
            #$$selections[-1] .= $dangling_alphas;
        }
    }

}

sub _selection_add {

    my ($tag, $final, $input, $choices, $num) = @_;
    my ($t,$v) = @{$tag->{'all'}};
    unless (defined ${$final->{$input}}[0]{$t}) {
        $$choices .= "$num, ";
        push @{${$final->{$input}}[0]{$t}}, $v
    }

}