This file is indexed.

/usr/share/perl5/Bio/SeqIO/embl.pm is in libbio-perl-perl 1.6.923-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
#
# BioPerl module for Bio::SeqIO::EMBL
#
# Please direct questions and support issues to <bioperl-l@bioperl.org> 
#
# Cared for by Ewan Birney <birney@ebi.ac.uk>
#
# Copyright Ewan Birney
#
# You may distribute this module under the same terms as perl itself

# POD documentation - main docs before the code

=head1 NAME

Bio::SeqIO::embl - EMBL sequence input/output stream

=head1 SYNOPSIS

It is probably best not to use this object directly, but
rather go through the SeqIO handler system. Go:

    $stream = Bio::SeqIO->new(-file => $filename, -format => 'EMBL');

    while ( (my $seq = $stream->next_seq()) ) {
        # do something with $seq
    }

=head1 DESCRIPTION

This object can transform Bio::Seq objects to and from EMBL flat
file databases.

There is a lot of flexibility here about how to dump things which
should be documented more fully.

There should be a common object that this and Genbank share (probably
with Swissprot). Too much of the magic is identical.

=head2 Optional functions

=over 3

=item _show_dna()

(output only) shows the dna or not

=item _post_sort()

(output only) provides a sorting func which is applied to the FTHelpers
before printing

=item _id_generation_func()

This is function which is called as

   print "ID   ", $func($annseq), "\n";

To generate the ID line. If it is not there, it generates a sensible ID
line using a number of tools.

If you want to output annotations in EMBL format they need to be
stored in a Bio::Annotation::Collection object which is accessible
through the Bio::SeqI interface method L<annotation()|annotation>.

The following are the names of the keys which are polled from a
L<Bio::Annotation::Collection> object.

 reference  - Should contain Bio::Annotation::Reference objects
 comment    - Should contain Bio::Annotation::Comment objects
 dblink     - Should contain Bio::Annotation::DBLink objects

=back

=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 one
of the Bioperl mailing lists.  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
the bugs and their resolution. Bug reports can be submitted via
the web:

  https://redmine.open-bio.org/projects/bioperl/

=head1 AUTHOR - Ewan Birney

Email birney@ebi.ac.uk

=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::SeqIO::embl;
use vars qw(%FTQUAL_NO_QUOTE);
use strict;
use Bio::SeqIO::FTHelper;
use Bio::SeqFeature::Generic;
use Bio::Species;
use Bio::Seq::SeqFactory;
use Bio::Annotation::Collection;
use Bio::Annotation::Comment;
use Bio::Annotation::Reference;
use Bio::Annotation::DBLink;

use base qw(Bio::SeqIO);

# Note that a qualifier that exceeds one line (i.e. a long label) will
# automatically be quoted regardless:
%FTQUAL_NO_QUOTE=(
                  'anticodon'=>1,
                  'citation'=>1,
                  'codon'=>1,
                  'codon_start'=>1,
                  'cons_splice'=>1,
                  'direction'=>1,
                  'evidence'=>1,
                  'label'=>1,
                  'mod_base'=> 1,
                  'number'=> 1,
                  'rpt_type'=> 1,
                  'rpt_unit'=> 1,
                  'transl_except'=> 1,
                  'transl_table'=> 1,
                  'usedin'=> 1,
                 );

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

    $self->SUPER::_initialize(@args);
    # hash for functions for decoding keys.
    $self->{'_func_ftunit_hash'} = {};
    # sets this to one by default. People can change it
    $self->_show_dna(1);
    if ( ! defined $self->sequence_factory ) {
        $self->sequence_factory(Bio::Seq::SeqFactory->new
                                (-verbose => $self->verbose(),
                                 -type => 'Bio::Seq::RichSeq'));
    }
}

=head2 next_seq

 Title   : next_seq
 Usage   : $seq = $stream->next_seq()
 Function: returns the next sequence in the stream
 Returns : Bio::Seq object
 Args    :

=cut

sub next_seq {
    my ($self,@args) = @_;
    my ($pseq,$c,$line,$name,$desc,$acc,$seqc,$mol,$div,
        $date, $comment, @date_arr);

    my ($annotation, %params, @features) =
        Bio::Annotation::Collection->new();

    $line = $self->_readline;
    # This needs to be before the first eof() test

    if ( !defined $line ) {
        return;                 # no throws - end of file
    }

    if ( $line =~ /^\s+$/ ) {
        while ( defined ($line = $self->_readline) ) {
            $line =~/^\S/ && last;
        }
        # return without error if the whole next sequence was just a single
        # blank line and then eof
        return unless $line;
    }

    # no ID as 1st non-blank line, need short circuit and exit routine
    $self->throw("EMBL stream with no ID. Not embl in my book")
        unless $line =~ /^ID\s+\S+/;

    # At this point we are sure that $line contains an ID header line
    my $alphabet;
    if ( $line =~ tr/;/;/ == 6) { # New style headers contain exactly six semicolons.

        # New style header (EMBL Release >= 87, after June 2006)
        my $topology;
        my $sv;

        # ID   DQ299383; SV 1; linear; mRNA; STD; MAM; 431 BP.
        # This regexp comes from the new2old.pl conversion script, from EBI
        if ($line =~ m/^ID   (\w+);\s+SV (\d+); (\w+); ([^;]+); (\w{3}); (\w{3}); (\d+) BP./) {
            ($name, $sv, $topology, $mol, $div) = ($1, $2, $3, $4, $6);
        }
        if (defined $sv) {
            $params{'-seq_version'} = $sv;
            $params{'-version'} = $sv;
        }

        if (defined $topology && $topology eq 'circular') {
            $params{'-is_circular'} = 1;
        }
    
        if (defined $mol ) {
            if ($mol =~ /DNA/) {
                $alphabet = 'dna';
            } elsif ($mol =~ /RNA/) {
                $alphabet = 'rna';
            } elsif ($mol =~ /AA/) {
                $alphabet = 'protein';
            }
        }
    } else {
    
        # Old style header (EMBL Release < 87, before June 2006)
        if ($line =~ /^ID\s+(\S+)[^;]*;\s+(\S+)[^;]*;\s+(\S+)[^;]*;/) {
        ($name, $mol, $div) = ($1, $2, $3);
        }
    
        if ($mol) {
            if ( $mol =~ /circular/ ) {
            $params{'-is_circular'} = 1;
            $mol =~  s|circular ||;
            }
            if (defined $mol ) {
            if ($mol =~ /DNA/) {
                $alphabet='dna';
            } elsif ($mol =~ /RNA/) {
                $alphabet='rna';
            } elsif ($mol =~ /AA/) {
                $alphabet='protein';
            }
            }
        }
    }

    unless( defined $name && length($name) ) {
    $name = "unknown_id";
    }

    # $self->warn("not parsing upper annotation in EMBL file yet!");
    my $buffer = $line;
    local $_;
    BEFORE_FEATURE_TABLE :
          my $ncbi_taxid;
          until ( !defined $buffer ) {
              $_ = $buffer;
              # Exit at start of Feature table
              if ( /^(F[HT]|SQ)/ ) {
                  $self->_pushback($_) if( $1 eq 'SQ' || $1 eq 'FT');
                  last;
              }
              # Description line(s)
              if (/^DE\s+(\S.*\S)/) {
                  $desc .= $desc ? " $1" : $1;
              }

              #accession number
              if ( /^AC\s+(.*)?/ || /^PA\s+(.*)?/) {
                  my @accs = split(/[; ]+/, $1); # allow space in addition
                  $params{'-accession_number'} = shift @accs
                      unless defined $params{'-accession_number'};
                  push @{$params{'-secondary_accessions'}}, @accs;
              }

              #version number
              if ( /^SV\s+\S+\.(\d+);?/ ) {
                  my $sv = $1;
                  #$sv =~ s/\;//;
                  $params{'-seq_version'} = $sv;
                  $params{'-version'} = $sv;
              }

              #date (NOTE: takes last date line)
              if ( /^DT\s+(.+)$/ ) {
                  my $line = $1;
                  my ($date, $version) = split(' ', $line, 2);
                  $date =~ tr/,//d; # remove comma if new version
                  if ($version) {
                  if ($version =~ /\(Rel\. (\d+), Created\)/xms ) {
                      my $release = Bio::Annotation::SimpleValue->new(
                                                                      -tagname    => 'creation_release',
                                                                      -value      => $1
                                                                     );
                      $annotation->add_Annotation($release);
                  } elsif ($version =~ /\(Rel\. (\d+), Last updated, Version (\d+)\)/xms ) {
                      my $release = Bio::Annotation::SimpleValue->new(
                                                                      -tagname    => 'update_release',
                                                                      -value      => $1
                                                                     );
                      $annotation->add_Annotation($release);

                      my $update = Bio::Annotation::SimpleValue->new(
                                                                     -tagname    => 'update_version',
                                                                     -value      => $2
                                                                    );
                      $annotation->add_Annotation($update);
                  }
                  }
                  push @{$params{'-dates'}}, $date;
              }

              #keywords
              if ( /^KW   (.*)\S*$/ ) {
                  my @kw = split(/\s*\;\s*/,$1);
                  push @{$params{'-keywords'}}, @kw;
              }

              # Organism name and phylogenetic information
              elsif (/^O[SC]/) {
                  # pass the accession number so we can give an informative throw message if necessary
                  my $species = $self->_read_EMBL_Species(\$buffer, $params{'-accession_number'});
                  $params{'-species'}= $species;
              }

              # NCBI TaxID Xref
              elsif (/^OX/) {
                  if (/NCBI_TaxID=(\d+)/) {
                      $ncbi_taxid=$1;
                  }

                  my @links = $self->_read_EMBL_TaxID_DBLink(\$buffer);
                  foreach my $dblink ( @links ) {
                      $annotation->add_Annotation('dblink',$dblink);
                  }
              }

              # References
              elsif (/^R/) {
                  my @refs = $self->_read_EMBL_References(\$buffer);
                  foreach my $ref ( @refs ) {
                      $annotation->add_Annotation('reference',$ref);
                  }
              }

              # DB Xrefs
              elsif (/^DR/) {
                  my @links = $self->_read_EMBL_DBLink(\$buffer);
                  foreach my $dblink ( @links ) {
                      $annotation->add_Annotation('dblink',$dblink);
                  }
              }

              # Comments
              elsif (/^CC\s+(.*)/) {
                  $comment .= $1;
                  $comment .= " ";
                  while (defined ($_ = $self->_readline) ) {
                      if (/^CC\s+(.*)/) {
                          $comment .= $1;
                          $comment .= " ";
                      } else {
                          last;
                      }
                  }
                  my $commobj = Bio::Annotation::Comment->new();
                  $commobj->text($comment);
                  $annotation->add_Annotation('comment',$commobj);
                  $comment = "";
              }

              # Get next line.
              $buffer = $self->_readline;
          }

    while ( defined ($_ = $self->_readline) ) {
        /^FT\s{3}\w/ && last;
        /^SQ / && last;
        /^CO / && last;
    }
    $buffer = $_;

    if (defined($buffer) && $buffer =~ /^FT /) {
        until ( !defined ($buffer) ) {
            my $ftunit = $self->_read_FTHelper_EMBL(\$buffer);

            # process ftunit
            my $feat =
                $ftunit->_generic_seqfeature($self->location_factory(), $name);

            # add taxon_id from source if available
            # Notice, this will override what is found in the OX line.
            # this is by design as this seems to be the official way
            # of specifying a TaxID
            if ($params{'-species'} && ($feat->primary_tag eq 'source')
                && $feat->has_tag('db_xref')
                && (! $params{'-species'}->ncbi_taxid())) {
                foreach my $tagval ($feat->get_tag_values('db_xref')) {
                    if (index($tagval,"taxon:") == 0) {
                        $params{'-species'}->ncbi_taxid(substr($tagval,6));
                        last;
                    }
                }
            }

            # add feature to list of features
            push(@features, $feat);

            if ( $buffer !~ /^FT/ ) {
                last;
            }
        }
    }
    # Set taxid found in OX line
    if ($params{'-species'} && defined $ncbi_taxid
        && (! $params{'-species'}->ncbi_taxid())) {
        $params{'-species'}->ncbi_taxid($ncbi_taxid);
    }

    # skip comments
    while ( defined ($buffer) && $buffer =~ /^XX/ ) {
        $buffer = $self->_readline();
    }
    
    if ( $buffer =~ /^CO/  ) {
	# bug#2982
	# special : create contig as annotation
        while ( defined ($buffer) ) {
	    $annotation->add_Annotation($_) for $self->_read_EMBL_Contig(\$buffer);
            if ( !$buffer || $buffer !~ /^CO/ ) {
                last;
	    }
        }
        $buffer ||= '';
    }
    if ($buffer !~ /^\/\//) { # if no SQ lines following CO (bug#2958)
    if ( $buffer !~ /^SQ/ ) {
        while ( defined ($_ = $self->_readline) ) {
            /^SQ/ && last;
        }
    }
    $seqc = "";
    while ( defined ($_ = $self->_readline) ) {
        m{^//} && last;
        $_ = uc($_);
        s/[^A-Za-z]//g;
        $seqc .= $_;
    }
}
    my $seq = $self->sequence_factory->create
        (-verbose => $self->verbose(),
         -division => $div,
         -seq => $seqc,
         -desc => $desc,
         -display_id => $name,
         -annotation => $annotation,
         -molecule => $mol,
         -alphabet => $alphabet,
         -features => \@features,
         %params);
    return $seq;
}



=head2 _write_ID_line

 Title   : _write_ID_line
 Usage   : $self->_write_ID_line($seq);
 Function: Writes the EMBL Release 87 format ID line to the stream, unless
         : there is a user-supplied ID line generation function in which
         : case that is used instead.
         : ( See Bio::SeqIO::embl::_id_generation_function(). )
 Returns : nothing
 Args    : Bio::Seq object

=cut

sub _write_ID_line {

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

    my $id_line;
    # If there is a user-supplied ID generation function, use it.
    if ( $self->_id_generation_func ) {
        $id_line = "ID   " . &{$self->_id_generation_func}($seq) . "\nXX\n";
    }
    # Otherwise, generate a standard EMBL release 87 (June 2006) ID line.
    else {

        # The sequence name is supposed to be the primary accession number,
        my $name = $seq->accession_number();
        if ( not(defined $name) || $name eq 'unknown') {
            # but if it is not present, use the sequence ID or the empty string
            $name = $seq->id() || '';
        }
 
        $self->warn("No whitespace allowed in EMBL id [". $name. "]") if $name =~ /\s/;

        # Use the sequence version, or default to 1.
        my $version = $seq->version() || 1;

        my $len = $seq->length();

        # Taxonomic division.
        my $div;
        if ( $seq->can('division') && defined($seq->division) &&
             $self->_is_valid_division($seq->division) ) {
            $div = $seq->division();
        } else {
            $div ||= 'UNC';     # 'UNC' is the EMBL division code for 'unclassified'.
        }

        my $mol;
        # If the molecule type is a valid EMBL type, use it.
        if (  $seq->can('molecule')
              && defined($seq->molecule)
              && $self->_is_valid_molecule_type($seq->molecule)
           ) {
            $mol = $seq->molecule();
        }
        # Otherwise, choose unassigned DNA or RNA based on the alphabet.
        elsif ($seq->can('primary_seq') && defined $seq->primary_seq->alphabet) {
            my $alphabet =$seq->primary_seq->alphabet;
            if ($alphabet eq 'dna') {
                $mol ='unassigned DNA';
            } elsif ($alphabet eq 'rna') {
                $mol='unassigned RNA';
            } elsif ($alphabet eq 'protein') {
                $self->warn("Protein sequence found; EMBL is a nucleotide format.");
                $mol='AA';  # AA is not a valid EMBL molecule type.
            }
        }

        my $topology = 'linear';
        if ($seq->is_circular) {
            $topology = 'circular';
        }

        $mol ||= '';            # 'unassigned'; ?
        $id_line = "ID   $name; SV $version; $topology; $mol; STD; $div; $len BP.\nXX\n";
        $self->_print($id_line);
    }
}

=head2 _is_valid_division

 Title   : _is_valid_division
 Usage   : $self->_is_valid_division($div)
 Function: tests division code for validity
 Returns : true if $div is a valid EMBL release 87 taxonomic division.
 Args    : taxonomic division code string

=cut

sub _is_valid_division {
    my ($self, $division) = @_;

    my %EMBL_divisions = (
                          "PHG"    => 1, # Bacteriophage
                          "ENV"    => 1, # Environmental Sample
                          "FUN"    => 1, # Fungal
                          "HUM"    => 1, # Human
                          "INV"    => 1, # Invertebrate
                          "MAM"    => 1, # Other Mammal
                          "VRT"    => 1, # Other Vertebrate
                          "MUS"    => 1, # Mus musculus
                          "PLN"    => 1, # Plant
                          "PRO"    => 1, # Prokaryote
                          "ROD"    => 1, # Other Rodent
                          "SYN"    => 1, # Synthetic
                          "UNC"    => 1, # Unclassified
                          "VRL"    => 1 # Viral
                         );

    return exists($EMBL_divisions{$division});
}

=head2 _is_valid_molecule_type

 Title   : _is_valid_molecule_type
 Usage   : $self->_is_valid_molecule_type($mol)
 Function: tests molecule type for validity
 Returns : true if $mol is a valid EMBL release 87 molecule type.
 Args    : molecule type string

=cut

sub _is_valid_molecule_type {
    my ($self, $moltype) = @_;

    my %EMBL_molecule_types = (
                               "genomic DNA"    => 1,
                               "genomic RNA"    => 1,
                               "mRNA"           => 1,
                               "tRNA"           => 1,
                               "rRNA"           => 1,
                               "snoRNA"         => 1,
                               "snRNA"          => 1,
                               "scRNA"          => 1,
                               "pre-RNA"        => 1,
                               "other RNA"      => 1,
                               "other DNA"      => 1,
                               "unassigned DNA" => 1,
                               "unassigned RNA" => 1
                              );

    return exists($EMBL_molecule_types{$moltype});
}

=head2 write_seq

 Title   : write_seq
 Usage   : $stream->write_seq($seq)
 Function: writes the $seq object (must be seq) to the stream
 Returns : 1 for success and undef for error
 Args    : array of 1 to n Bio::SeqI objects


=cut

sub write_seq {
    my ($self,@seqs) = @_;

    foreach my $seq ( @seqs ) {
        $self->throw("Attempting to write with no seq!") unless defined $seq;
        unless ( ref $seq && $seq->isa('Bio::SeqI' ) ) {
            $self->warn("$seq is not a SeqI compliant sequence object!")
                if $self->verbose >= 0;
            unless ( ref $seq && $seq->isa('Bio::PrimarySeqI' ) ) {
                $self->throw("$seq is not a PrimarySeqI compliant sequence object!");
            }
        }
        my $str = $seq->seq || '';

        # Write the ID line.
        $self->_write_ID_line($seq);


        # Write the accession line if present
        my( $acc );
        {
            if ( my $func = $self->_ac_generation_func ) {
                $acc = &{$func}($seq);
            } elsif ( $seq->isa('Bio::Seq::RichSeqI') &&
                      defined($seq->accession_number) ) {
                $acc = $seq->accession_number;
                $acc = join("; ", $acc, $seq->get_secondary_accessions);
            } elsif ( $seq->can('accession_number') ) {
                $acc = $seq->accession_number;
            }

            if (defined $acc) {
                $self->_print("AC   $acc;\n",
                              "XX\n") || return;
            }
        }

        # Date lines
        my $switch=0;
        if ( $seq->can('get_dates') ) {
            my @dates =  $seq->get_dates();
            my $ct = 1;
            my $date_flag = 0;
            my ($cr) = $seq->annotation->get_Annotations("creation_release");
            my ($ur) = $seq->annotation->get_Annotations("update_release");
            my ($uv) = $seq->annotation->get_Annotations("update_version");

            unless ($cr && $ur && $ur) {
                $date_flag = 1;
            }

            foreach my $dt (@dates) {
                if (!$date_flag) {
                    $self->_write_line_EMBL_regex("DT   ","DT   ",
                                                  $dt." (Rel. $cr, Created)",
                                                  '\s+|$',80) if $ct == 1;
                    $self->_write_line_EMBL_regex("DT   ","DT   ",
                                                  $dt." (Rel. $ur, Last updated, Version $uv)",
                                                  '\s+|$',80) if $ct == 2;
                } else {        # other formats?
                    $self->_write_line_EMBL_regex("DT   ","DT   ",
                                                  $dt,'\s+|$',80);
                }
                $switch =1;
                $ct++;
            }
            if ($switch == 1) {
                $self->_print("XX\n") || return;
            }
        }

        # Description lines
        $self->_write_line_EMBL_regex("DE   ","DE   ",$seq->desc(),'\s+|$',80) || return; #'
        $self->_print( "XX\n") || return;

        # if there, write the kw line
        {
            my( $kw );
            if ( my $func = $self->_kw_generation_func ) {
                $kw = &{$func}($seq);
            } elsif ( $seq->can('keywords') ) {
                $kw = $seq->keywords;
            }
            if (defined $kw) {
                $self->_write_line_EMBL_regex("KW   ", "KW   ", $kw, '\s+|$', 80) || return; #'
                $self->_print( "XX\n") || return;
            }
        }

        # Organism lines

        if ($seq->can('species') && (my $spec = $seq->species)) {
            my @class = $spec->classification();
            shift @class;       # get rid of species name. Some embl files include
                                # the species name in the OC lines, but this seems
                                # more like an error than something we need to
                                # emulate
            my $OS = $spec->scientific_name;
            if ($spec->common_name) {
                $OS .= ' ('.$spec->common_name.')';
            }
            $self->_print("OS   $OS\n") || return;
            my $OC = join('; ', reverse(@class)) .'.';
            $self->_write_line_EMBL_regex("OC   ","OC   ",$OC,'; |$',80) || return;
            if ($spec->organelle) {
                $self->_write_line_EMBL_regex("OG   ","OG   ",$spec->organelle,'; |$',80) || return;
            }
            my $ncbi_taxid = $spec->ncbi_taxid;
            if ($ncbi_taxid) {
                $self->_print("OX   NCBI_TaxID=$ncbi_taxid\n") || return;
            }
            $self->_print("XX\n") || return;
        }
        # Reference lines
        my $t = 1;
        if ( $seq->can('annotation') && defined $seq->annotation ) {
            foreach my $ref ( $seq->annotation->get_Annotations('reference') ) {
                $self->_print( "RN   [$t]\n") || return;

                # Having no RP line is legal, but we need both
                # start and end for a valid location.
                if ($ref->comment) {
                    $self->_write_line_EMBL_regex("RC   ", "RC   ", $ref->comment, '\s+|$', 80) || return; #'
                }
                my $start = $ref->start;
                my $end   = $ref->end;
                if ($start and $end) {
                    $self->_print( "RP   $start-$end\n") || return;
                } elsif ($start or $end) {
                    $self->throw("Both start and end are needed for a valid RP line.".
                                 "  Got: start='$start' end='$end'");
                }

                if (my $med = $ref->medline) {
                    $self->_print( "RX   MEDLINE; $med.\n") || return;
                }
                if (my $pm = $ref->pubmed) {
                    $self->_print( "RX   PUBMED; $pm.\n") || return;
                }
                my $authors = $ref->authors;
                $authors =~ s/([\w\.]) (\w)/$1#$2/g;  # add word wrap protection char '#'

                $self->_write_line_EMBL_regex("RA   ", "RA   ",
                                              $authors . ";",
                                              '\s+|$', 80) || return; #'

                # If there is no title to the reference, it appears
                # as a single semi-colon.  All titles must end in
                # a semi-colon.
                my $ref_title = $ref->title || '';
                $ref_title =~ s/[\s;]*$/;/;
                $self->_write_line_EMBL_regex("RT   ", "RT   ", $ref_title,    '\s+|$', 80) || return; #'
                $self->_write_line_EMBL_regex("RL   ", "RL   ", $ref->location, '\s+|$', 80) || return; #'
                $self->_print("XX\n") || return;
                $t++;
            }

            # DB Xref lines
            if (my @db_xref = $seq->annotation->get_Annotations('dblink') ) {
                for my $dr (@db_xref) {
                    my $db_name = $dr->database;
                    my $prim    = $dr->primary_id;

                    my $opt     = $dr->optional_id || '';
                    my $line = $opt ? "$db_name; $prim; $opt." : "$db_name; $prim.";
                    $self->_write_line_EMBL_regex("DR   ", "DR   ", $line, '\s+|$', 80) || return; #'
                }
                $self->_print("XX\n") || return;
            }
            
            # Comment lines
            foreach my $comment ( $seq->annotation->get_Annotations('comment') ) {
                $self->_write_line_EMBL_regex("CC   ", "CC   ", $comment->text, '\s+|$', 80) || return; #'
                $self->_print("XX\n") || return;
            }
        }
        # "\\s\+\|\$"

        ## FEATURE TABLE

        $self->_print("FH   Key             Location/Qualifiers\n") || return;
        $self->_print("FH\n") || return;

        my @feats = $seq->can('top_SeqFeatures') ? $seq->top_SeqFeatures : ();
        if ($feats[0]) {
            if ( defined $self->_post_sort ) {
                # we need to read things into an array.
                # Process. Sort them. Print 'em

                my $post_sort_func = $self->_post_sort();
                my @fth;

                foreach my $sf ( @feats ) {
                    push(@fth,Bio::SeqIO::FTHelper::from_SeqFeature($sf,$seq));
                }

                @fth = sort { &$post_sort_func($a,$b) } @fth;

                foreach my $fth ( @fth ) {
                    $self->_print_EMBL_FTHelper($fth) || return;
                }
            } else {
                # not post sorted. And so we can print as we get them.
                # lower memory load...

                foreach my $sf ( @feats ) {
                    my @fth = Bio::SeqIO::FTHelper::from_SeqFeature($sf,$seq);
                    foreach my $fth ( @fth ) {
                        if ( $fth->key eq 'CONTIG') {
                            $self->_show_dna(0);
                        }
                        $self->_print_EMBL_FTHelper($fth) || return;
                    }
                }
            }
        }

        if ( $self->_show_dna() == 0 ) {
            $self->_print( "//\n") || return;
            return;
        }
        $self->_print( "XX\n") || return;

        # finished printing features.

	# print contig if present : bug#2982
	if ( $seq->can('annotation') && defined $seq->annotation) {
	    foreach my $ctg ( $seq->annotation->get_Annotations('contig') ) {
		if ($ctg->value) {
		    $self->_write_line_EMBL_regex("CO   ","CO   ", $ctg->value,
						  '[,]|$', 80) || return;
		}
	    }
	}
	# print sequence lines only if sequence is present! bug#2982
	if (length($str)) {
	    $str =~ tr/A-Z/a-z/;

	    # Count each nucleotide
	    my $alen = $str =~ tr/a/a/;
	    my $clen = $str =~ tr/c/c/;
	    my $glen = $str =~ tr/g/g/;
	    my $tlen = $str =~ tr/t/t/;
	    
	    my $len = $seq->length();
	    my $olen = $seq->length() - ($alen + $tlen + $clen + $glen);
	    if ( $olen < 0 ) {
		$self->warn("Weird. More atgc than bases. Problem!");
	    }
	    
	    $self->_print("SQ   Sequence $len BP; $alen A; $clen C; $glen G; $tlen T; $olen other;\n") || return;

	    my $nuc = 60;       # Number of nucleotides per line
	    my $whole_pat = 'a10' x 6; # Pattern for unpacking a whole line
	    my $out_pat   = 'A11' x 6; # Pattern for packing a line
	    my $length = length($str);
	    
	    # Calculate the number of nucleotides which fit on whole lines
	    my $whole = int($length / $nuc) * $nuc;

	    # Print the whole lines
	    my( $i );
	    for ($i = 0; $i < $whole; $i += $nuc) {
		my $blocks = pack $out_pat,
                unpack $whole_pat,
		substr($str, $i, $nuc);
		$self->_print(sprintf("     $blocks%9d\n", $i + $nuc)) || return;
	    }

	    # Print the last line
	    if (my $last = substr($str, $i)) {
		my $last_len = length($last);
		my $last_pat = 'a10' x int($last_len / 10) .'a'. $last_len % 10;
		my $blocks = pack $out_pat,
                unpack($last_pat, $last);
		$self->_print(sprintf("     $blocks%9d\n", $length)) ||
		    return;         # Add the length to the end
	    }
	}
	    
	$self->_print( "//\n") || return;
	
	$self->flush if $self->_flush_on_write && defined $self->_fh;
    }
    return 1;
}

=head2 _print_EMBL_FTHelper

 Title   : _print_EMBL_FTHelper
 Usage   :
 Function: Internal function
 Returns : 1 if writing suceeded, otherwise undef
 Args    :


=cut

sub _print_EMBL_FTHelper {
    my ($self,$fth) = @_;

    if ( ! ref $fth || ! $fth->isa('Bio::SeqIO::FTHelper') ) {
        $fth->warn("$fth is not a FTHelper class. Attempting to print, but there could be tears!");
    }


    #$self->_print( "FH   Key             Location/Qualifiers\n");
    #$self->_print( sprintf("FT   %-15s  %s\n",$fth->key,$fth->loc));
    # let
    if ( $fth->key eq 'CONTIG' ) {
        $self->_print("XX\n") || return;
        $self->_write_line_EMBL_regex("CO   ",
                                      "CO   ",$fth->loc,
                                      '\,|$',80) || return; #'
        return 1;
    }
    $self->_write_line_EMBL_regex(sprintf("FT   %-15s ",$fth->key),
                                  "FT                   ",$fth->loc,
                                  '\,|$',80) || return; #'
    foreach my $tag ( keys %{$fth->field} ) {
        if ( ! defined $fth->field->{$tag} ) {
            next;
        }
        foreach my $value ( @{$fth->field->{$tag}} ) {
            $value =~ s/\"/\"\"/g;
            if ($value eq "_no_value") {
                $self->_write_line_EMBL_regex("FT                   ",
                                              "FT                   ",
                                              "/$tag",'.|$',80) || return; #'
            }
            # there are almost 3x more quoted qualifier values and they
            # are more common too so we take quoted ones first
            #
            # Long qualifiers, that will be line wrapped, are always quoted
            elsif (!$FTQUAL_NO_QUOTE{$tag} or length("/$tag=$value")>=60) {
                my $pat = $value =~ /\s/ ? '\s|\-|$' : '.|\-|$';
                $self->_write_line_EMBL_regex("FT                   ",
                                              "FT                   ",
                                              "/$tag=\"$value\"",$pat,80) || return;
            } else {
                $self->_write_line_EMBL_regex("FT                   ",
                                              "FT                   ",
                                              "/$tag=$value",'.|$',80) || return; #'
                                          }
            }
        }

        return 1;
    }



=head2 _read_EMBL_Contig()

 Title   : _read_EMBL_Contig
 Usage   : 
 Function: convert CO lines into annotations
 Returns : 
 Args    : 

=cut

sub _read_EMBL_Contig {
    my ($self, $buffer) = @_;
    my @ret;
    if ( $$buffer !~ /^CO/ ) {
        warn("Not parsing line '$$buffer' which maybe important");
    }
    $self->_pushback($$buffer);
    while ( defined ($_ = $self->_readline) ) {
	/^C/ || last;
	/^CO\s+(.*)/ && do {
	push @ret, Bio::Annotation::SimpleValue->new( -tagname => 'contig',
						      -value => $1);
	};
    }
    $$buffer = $_;
    return @ret;

}
#'
=head2 _read_EMBL_References

 Title   : _read_EMBL_References
 Usage   :
 Function: Reads references from EMBL format. Internal function really
 Example :
 Returns :
 Args    :


=cut

sub _read_EMBL_References {
    my ($self,$buffer) = @_;
    my (@refs);

    # assume things are starting with RN

    if ( $$buffer !~ /^RN/ ) {
        warn("Not parsing line '$$buffer' which maybe important");
    }
    my $b1;
    my $b2;
    my $title;
    my $loc;
    my $au;
    my $med;
    my $pm;
    my $com;

    while ( defined ($_ = $self->_readline) ) {
        /^R/ || last;
        /^RP   (\d+)-(\d+)/ && do {$b1=$1;$b2=$2;};
        /^RX   MEDLINE;\s+(\d+)/ && do {$med=$1};
        /^RX   PUBMED;\s+(\d+)/ && do {$pm=$1};
        /^RA   (.*)/ && do {
            $au = $self->_concatenate_lines($au,$1); next;
        };
        /^RT   (.*)/ && do {
            $title = $self->_concatenate_lines($title,$1); next;
        };
        /^RL   (.*)/ && do {
            $loc = $self->_concatenate_lines($loc,$1); next;
        };
        /^RC   (.*)/ && do {
            $com = $self->_concatenate_lines($com,$1); next;
        };
    }

    my $ref = Bio::Annotation::Reference->new();
    $au =~ s/;\s*$//g;
    $title =~ s/;\s*$//g;

    $ref->start($b1);
    $ref->end($b2);
    $ref->authors($au);
    $ref->title($title);
    $ref->location($loc);
    $ref->medline($med);
    $ref->comment($com);
    $ref->pubmed($pm);

    push(@refs,$ref);
    $$buffer = $_;

    return @refs;
}

=head2 _read_EMBL_Species

 Title   : _read_EMBL_Species
 Usage   :
 Function: Reads the EMBL Organism species and classification
           lines.
 Example :
 Returns : A Bio::Species object
 Args    : a reference to the current line buffer, accession number

=cut

sub _read_EMBL_Species {
    my( $self, $buffer, $acc ) = @_;
    my $org;

    $_ = $$buffer;
    my( $sub_species, $species, $genus, $common, $sci_name, $class_lines );
    while (defined( $_ ||= $self->_readline )) {
        if (/^OS\s+(.+)/) {
            $sci_name .= ($sci_name) ? ' '.$1 : $1;
        } elsif (s/^OC\s+(.+)$//) {
            $class_lines .= $1;
        } elsif (/^OG\s+(.*)/) {
            $org = $1;
        } else {
            last;
        }

        $_ = undef;             # Empty $_ to trigger read of next line
    }

#    $$buffer = $_;
	$self->_pushback($_);
	
    $sci_name =~ s{\.$}{};
    $sci_name || return;

    # Convert data in classification lines into classification array.
    # only split on ';' or '.' so that classification that is 2 or more words
    # will still get matched, use map() to remove trailing/leading/intervening
    # spaces
    my @class = map { s/^\s+//; s/\s+$//; s/\s{2,}/ /g; $_; } split /(?<!subgen)[;\.]+/, $class_lines;

    # do we have a genus?
    my $possible_genus = $class[-1];
    $possible_genus .= "|$class[-2]" if $class[-2];
    if ($sci_name =~ /^($possible_genus)/) {
        $genus = $1;
        ($species) = $sci_name =~ /^$genus\s+(.+)/;
    } else {
        $species = $sci_name;
    }

    # Don't make a species object if it is "Unknown" or "None"
    if ($genus) {
        return if $genus =~ /^(Unknown|None)$/i;
    }

    # is this organism of rank species or is it lower?
    # (doesn't catch everything, but at least the guess isn't dangerous)
    if ($species =~ /subsp\.|var\./) {
        ($species, $sub_species) = $species =~ /(.+)\s+((?:subsp\.|var\.).+)/;
    }

    # sometimes things have common name in brackets, like
    # Schizosaccharomyces pombe (fission yeast), so get rid of the common
    # name bit. Probably dangerous if real scientific species name ends in
    # bracketed bit.
    unless ($class[-1] eq 'Viruses') {
        ($species, $common) = $species =~ /^(.+)\s+\((.+)\)$/;
        $sci_name =~ s/\s+\(.+\)$// if $common;
    }

    # Bio::Species array needs array in Species -> Kingdom direction
    unless ($class[-1] eq $sci_name) {
        push(@class, $sci_name);
    }
    @class = reverse @class;

    # do minimal sanity checks before we hand off to Bio::Species which won't
    # be able to give informative throw messages if it has to throw because
    # of problems here
    $self->throw("$acc seems to be missing its OS line: invalid.") unless $sci_name;
    my %names;
    foreach my $i (0..$#class) {
        my $name = $class[$i];
        $names{$name}++;
        # this code breaks examples like: Xenopus (Silurana) tropicalis
        # commenting out, see bug 3158
        
        #if ($names{$name} > 1 && ($name ne $class[$i - 1])) {
        #    $self->warn("$acc seems to have an invalid species classification:$name ne $class[$i - 1]");
        #}
    }
    my $make = Bio::Species->new();
    $make->scientific_name($sci_name);
    $make->classification(@class);
    unless ($class[-1] eq 'Viruses') {
        $make->genus($genus) if $genus;
        $make->species($species) if $species;
        $make->sub_species($sub_species) if $sub_species;
        $make->common_name($common) if $common;
    }
    $make->organelle($org) if $org;
    return $make;
}

=head2 _read_EMBL_DBLink

 Title   : _read_EMBL_DBLink
 Usage   :
 Function: Reads the EMBL database cross reference ("DR") lines
 Example :
 Returns : A list of Bio::Annotation::DBLink objects
 Args    :

=cut

sub _read_EMBL_DBLink {
    my( $self,$buffer ) = @_;
    my( @db_link );

    $_ = $$buffer;
    while (defined( $_ ||= $self->_readline )) {
        if ( /^DR   ([^\s;]+);\s*([^\s;]+);?\s*([^\s;]+)?\.$/) {
        my ($databse, $prim_id, $sec_id) = ($1,$2,$3);
        my $link = Bio::Annotation::DBLink->new(-database    => $databse,
                            -primary_id  => $prim_id,
                            -optional_id => $sec_id);

            push(@db_link, $link);
    } else {
            last;
        }
        $_ = undef;             # Empty $_ to trigger read of next line
    }

    $$buffer = $_;
    return @db_link;
}

=head2 _read_EMBL_TaxID_DBLink

 Title   : _read_EMBL_TaxID_DBLink
 Usage   :
 Function: Reads the EMBL database cross reference to NCBI TaxID ("OX") lines
 Example :
 Returns : A list of Bio::Annotation::DBLink objects
 Args    :

=cut

sub _read_EMBL_TaxID_DBLink {
    my( $self,$buffer ) = @_;
    my( @db_link );

    $_ = $$buffer;
    while (defined( $_ ||= $self->_readline )) {
        if ( /^OX   (\S+)=(\d+);$/ ) {
            my ($databse, $prim_id) = ($1,$2);
            my $link = Bio::Annotation::DBLink->new(-database    => $databse,
                                                    -primary_id  => $prim_id,);
            push(@db_link, $link);
        } else {
            last;
        }
        $_ = undef;             # Empty $_ to trigger read of next line
    }

    $$buffer = $_;
    return @db_link;
}

=head2 _filehandle

 Title   : _filehandle
 Usage   : $obj->_filehandle($newval)
 Function:
 Example :
 Returns : value of _filehandle
 Args    : newvalue (optional)


=cut

sub _filehandle{
    my ($obj,$value) = @_;
    if ( defined $value) {
        $obj->{'_filehandle'} = $value;
    }
    return $obj->{'_filehandle'};

}

=head2 _read_FTHelper_EMBL

 Title   : _read_FTHelper_EMBL
 Usage   : _read_FTHelper_EMBL($buffer)
 Function: reads the next FT key line
 Example :
 Returns : Bio::SeqIO::FTHelper object
 Args    : filehandle and reference to a scalar


=cut

sub _read_FTHelper_EMBL {
    my ($self,$buffer) = @_;

    my ($key,                   # The key of the feature
        $loc,                   # The location line from the feature
        @qual,                  # An arrray of lines making up the qualifiers
       );

    if ($$buffer =~ /^FT\s{3}(\S+)\s+(\S+)/ ) {
        $key = $1;
        $loc = $2;
        # Read all the lines up to the next feature
        while ( defined($_ = $self->_readline) ) {
            if (/^FT(\s+)(.+?)\s*$/) {
                # Lines inside features are preceeded by 19 spaces
                # A new feature is preceeded by 3 spaces
                if (length($1) > 4) {
                    # Add to qualifiers if we're in the qualifiers
                    if (@qual) {
                        push(@qual, $2);
                    }
                    # Start the qualifier list if it's the first qualifier
                    elsif (substr($2, 0, 1) eq '/') {
                        @qual = ($2);
                    }
                    # We're still in the location line, so append to location
                    else {
                        $loc .= $2;
                    }
                } else {
                    # We've reached the start of the next feature
                    last;
                }
            } else {
                # We're at the end of the feature table
                last;
            }
        }
    } elsif ( $$buffer =~ /^CO\s+(\S+)/) {
    $key = 'CONTIG';
    $loc = $1;
    # Read all the lines up to the next feature
    while ( defined($_ = $self->_readline) ) {
        if (/^CO\s+(\S+)\s*$/) {
        $loc .= $1;
        } else {
        # We've reached the start of the next feature
        last;
        }
    }
    } else {
        # No feature key
        return;
    }

    # Put the first line of the next feature into the buffer
    $$buffer = $_;

    # Make the new FTHelper object
    my $out = Bio::SeqIO::FTHelper->new();
    $out->verbose($self->verbose());
    $out->key($key);
    $out->loc($loc);

    # Now parse and add any qualifiers.  (@qual is kept
    # intact to provide informative error messages.)
  QUAL: for (my $i = 0; $i < @qual; $i++) {
        $_ = $qual[$i];
        my( $qualifier, $value ) = m{^/([^=]+)(?:=(.+))?}
            or $self->throw("Can't see new qualifier in: $_\nfrom:\n"
                            . join('', map "$_\n", @qual));
        if (defined $value) {
            # Do we have a quoted value?
            if (substr($value, 0, 1) eq '"') {
                # Keep adding to value until we find the trailing quote
                # and the quotes are balanced
              QUOTES:
                while ($value !~ /"$/ or $value =~ tr/"/"/ % 2) { #"
                    $i++;
                    my $next = $qual[$i];
                    if (!defined($next)) {
                        $self->warn("Unbalanced quote in:\n".join("\n", @qual).
                                    "\nAdding quote to close...".
                                    "Check sequence quality!");
                        $value .= '"';
                        last QUOTES;
                    }

                    # Protein sequence translations need to be joined without spaces,
                    # other qualifiers need those.
                    if ($qualifier eq "translation") {
                        $value .= $next;
                    } else {
                        $value .= " $next";
                    }
                }
                # Trim leading and trailing quotes
                $value =~ s/^"|"$//g;
                # Undouble internal quotes
                $value =~ s/""/"/g; #"
            }
        } else {
            $value = '_no_value';
        }

        # Store the qualifier
        $out->field->{$qualifier} ||= [];
        push(@{$out->field->{$qualifier}},$value);
    }

    return $out;
}

=head2 _write_line_EMBL

 Title   : _write_line_EMBL
 Usage   :
 Function: internal function
 Example :
 Returns : 1 if writing suceeded, else undef
 Args    :


=cut

sub _write_line_EMBL {
    my ($self,$pre1,$pre2,$line,$length) = @_;

    $length || $self->throw("Miscalled write_line_EMBL without length. Programming error!");
    my $subl = $length - length $pre2;
    my $linel = length $line;
    my $i;

    my $sub = substr($line,0,$length - length $pre1);

    $self->_print( "$pre1$sub\n") || return;

    for ($i= ($length - length $pre1);$i < $linel;) {
        $sub = substr($line,$i,($subl));
        $self->_print( "$pre2$sub\n") || return;
        $i += $subl;
    }

    return 1;
}

=head2 _write_line_EMBL_regex

 Title   : _write_line_EMBL_regex
 Usage   :
 Function: internal function for writing lines of specified
           length, with different first and the next line
           left hand headers and split at specific points in the
           text
 Example :
 Returns : nothing
 Args    : file handle, first header, second header, text-line, regex for line breaks, total line length


=cut

sub _write_line_EMBL_regex {
    my ($self,$pre1,$pre2,$line,$regex,$length) = @_;

    #print STDOUT "Going to print with $line!\n";

    $length || $self->throw("Programming error - called write_line_EMBL_regex without length.");

    my $subl = $length - (length $pre1) -1 ;
    my( @lines );

  CHUNK: while($line) {
        foreach my $pat ($regex, '[,;\.\/-]\s|'.$regex, '[,;\.\/-]|'.$regex) {
            if ($line =~ m/^(.{0,$subl})($pat)(.*)/ ) {
                my $l = $1.$2;
                $l =~ s/#/ /g  # remove word wrap protection char '#'
                    if $pre1 eq "RA   ";
                my $newl = $3;
                $line = substr($line,length($l));
                # be strict about not padding spaces according to
                # genbank format
                $l =~ s/\s+$//;
                next CHUNK if ($l eq '');
                push(@lines, $l);
                next CHUNK;
            }
        }
        # if we get here none of the patterns matched $subl or less chars
        $self->warn("trouble dissecting \"$line\"\n     into chunks ".
                    "of $subl chars or less - this tag won't print right");
        # insert a space char to prevent infinite loops
        $line = substr($line,0,$subl) . " " . substr($line,$subl);
    }
    my $s = shift @lines;
    ($self->_print("$pre1$s\n") || return) if $s;
    foreach my $s ( @lines ) {
        $self->_print("$pre2$s\n") || return;
    }

    return 1;
}

=head2 _post_sort

 Title   : _post_sort
 Usage   : $obj->_post_sort($newval)
 Function:
 Returns : value of _post_sort
 Args    : newvalue (optional)


=cut

sub _post_sort{
    my $obj = shift;
    if ( @_ ) {
        my $value = shift;
        $obj->{'_post_sort'} = $value;
    }
    return $obj->{'_post_sort'};

}

=head2 _show_dna

 Title   : _show_dna
 Usage   : $obj->_show_dna($newval)
 Function:
 Returns : value of _show_dna
 Args    : newvalue (optional)


=cut

sub _show_dna{
    my $obj = shift;
    if ( @_ ) {
        my $value = shift;
        $obj->{'_show_dna'} = $value;
    }
    return $obj->{'_show_dna'};

}

=head2 _id_generation_func

 Title   : _id_generation_func
 Usage   : $obj->_id_generation_func($newval)
 Function:
 Returns : value of _id_generation_func
 Args    : newvalue (optional)


=cut

sub _id_generation_func{
    my $obj = shift;
    if ( @_ ) {
        my $value = shift;
        $obj->{'_id_generation_func'} = $value;
    }
    return $obj->{'_id_generation_func'};

}

=head2 _ac_generation_func

 Title   : _ac_generation_func
 Usage   : $obj->_ac_generation_func($newval)
 Function:
 Returns : value of _ac_generation_func
 Args    : newvalue (optional)


=cut

sub _ac_generation_func{
    my $obj = shift;
    if ( @_ ) {
        my $value = shift;
        $obj->{'_ac_generation_func'} = $value;
    }
    return $obj->{'_ac_generation_func'};

}

=head2 _sv_generation_func

 Title   : _sv_generation_func
 Usage   : $obj->_sv_generation_func($newval)
 Function:
 Returns : value of _sv_generation_func
 Args    : newvalue (optional)


=cut

sub _sv_generation_func{
    my $obj = shift;
    if ( @_ ) {
        my $value = shift;
        $obj->{'_sv_generation_func'} = $value;
    }
    return $obj->{'_sv_generation_func'};

}

=head2 _kw_generation_func

 Title   : _kw_generation_func
 Usage   : $obj->_kw_generation_func($newval)
 Function:
 Returns : value of _kw_generation_func
 Args    : newvalue (optional)


=cut

sub _kw_generation_func{
    my $obj = shift;
    if ( @_ ) {
        my $value = shift;
        $obj->{'_kw_generation_func'} = $value;
    }
    return $obj->{'_kw_generation_func'};

}

1;