This file is indexed.

/usr/share/perl5/Bio/Tools/GFF.pm is in libbio-perl-perl 1.6.924-1.

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

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
#
# BioPerl module for Bio::Tools::GFF
#
# Please direct questions and support issues to <bioperl-l@bioperl.org> 
#
# Cared for by the Bioperl core team
#
# Copyright Matthew Pocock
#
# You may distribute this module under the same terms as perl itself

# POD documentation - main docs before the code

=head1 NAME

Bio::Tools::GFF - A Bio::SeqAnalysisParserI compliant GFF format parser

=head1 SYNOPSIS

    use Bio::Tools::GFF;

    # specify input via -fh or -file
    my $gffio = Bio::Tools::GFF->new(-fh => \*STDIN, -gff_version => 2);
    my $feature;
    # loop over the input stream
    while($feature = $gffio->next_feature()) {
        # do something with feature
    }
    $gffio->close();

    # you can also obtain a GFF parser as a SeqAnalasisParserI in
    # HT analysis pipelines (see Bio::SeqAnalysisParserI and
    # Bio::Factory::SeqAnalysisParserFactory)
    my $factory = Bio::Factory::SeqAnalysisParserFactory->new();
    my $parser = $factory->get_parser(-input => \*STDIN, -method => "gff");
    while($feature = $parser->next_feature()) {
        # do something with feature
    }

=head1 DESCRIPTION

This class provides a simple GFF parser and writer. In the sense of a
SeqAnalysisParser, it parses an input file or stream into SeqFeatureI
objects, but is not in any way specific to a particular analysis
program and the output that program produces.

That is, if you can get your analysis program spit out GFF, here is
your result parser.

=head1 GFF3 AND SEQUENCE DATA

GFF3 supports sequence data; see

http://www.sequenceontology.org/gff3.shtml

There are a number of ways to deal with this -

If you call

  $gffio->ignore_sequence(1)

prior to parsing the sequence data is ignored; this is useful if you
just want the features. It avoids the memory overhead in building and
caching sequences

Alternatively, you can call either

  $gffio->get_seqs()

Or

  $gffio->seq_id_by_h()

At the B<end> of parsing to get either a list or hashref of Bio::Seq
objects (see the documentation for each of these methods)

Note that these objects will not have the features attached - you have
to do this yourself, OR call

  $gffio->features_attached_to_seqs(1)

PRIOR to parsing; this will ensure that the Seqs have the features
attached; ie you will then be able to call

  $seq->get_SeqFeatures();

And use Bio::SeqIO methods

Note that auto-attaching the features to seqs will incur a higher
memory overhead as the features must be cached until the sequence data
is found

=head1 TODO

Make a Bio::SeqIO class specifically for GFF3 with sequence data

=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 the web:

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

=head1 AUTHOR - Matthew Pocock

Email mrp-at-sanger.ac.uk

=head1 CONTRIBUTORS 

Jason Stajich, jason-at-biperl-dot-org
Chris Mungall, cjm-at-fruitfly-dot-org
Steffen Grossmann [SG], grossman at molgen.mpg.de
Malcolm Cook, mec-at-stowers-institute.org

=head1 APPENDIX

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

=cut

# Let the code begin...

package Bio::Tools::GFF;

use vars qw($HAS_HTML_ENTITIES);
use strict;

use Bio::Seq::SeqFactory;
use Bio::LocatableSeq;
use Bio::SeqFeature::Generic;

use base qw(Bio::Root::Root Bio::SeqAnalysisParserI Bio::Root::IO);

my $i = 0;
my %GFF3_ID_Tags = map { $_ => $i++ } qw(ID Parent Target);

# for skipping data that may be represented elsewhere; currently, this is
# only the score
my %SKIPPED_TAGS = map { $_ => 1 } qw(score);


=head2 new

 Title   : new
 Usage   : my $parser = Bio::Tools::GFF->new(-gff_version => 2,
                                             -file        => "filename.gff");
           or
           my $writer = Bio::Tools::GFF->new(-gff_version => 3,
                                             -file        => ">filename.gff3");
 Function: Creates a new instance. Recognized named parameters are -file, -fh,
           and -gff_version.
 Returns : a new object
 Args    : named parameters
           -gff_version => [1,2,3]

=cut

{   # make a class variable such that we can generate unique ID's over
    # a session, no matter how many instances of GFF.pm we make
    # since these have to be unique within the scope of a GFF file.
    
    my $gff3_featureID = 0;
    
    sub _incrementGFF3ID {
        my ($self) = @_;
        return ++ $gff3_featureID;
    }
}


sub new {
    my ($class, @args) = @_;
    my $self = $class->SUPER::new(@args);
  
    my ($gff_version, $noparse) = $self->_rearrange([qw(GFF_VERSION NOPARSE)],@args);

    # initialize IO
    $self->_initialize_io(@args);
    $self->_parse_header() unless $noparse;

    $gff_version ||= 2;
    if( ! $self->gff_version($gff_version) )  {
        $self->throw("Can't build a GFF object with the unknown version ".
            $gff_version);
    }
    $self->{'_first'} = 1;
    return $self;
}


=head2 _parse_header

 Title   : _parse_header
 Usage   : $gffio->_parse_header()
 Function: used to turn parse GFF header lines.  currently
           produces Bio::LocatableSeq objects from ##sequence-region
           lines
 Returns : 1 on success
 Args    : none


=cut

sub _parse_header{
    my ($self) = @_;

    my @unhandled;
    local $^W = 0; # hide warnings when we try and parse from a file opened
                   # for writing - there isn't really a better way to do
                   # AFAIK - cannot detech if a FH is read or write.
    while(my $line = $self->_readline()){
        my $handled = 0;
        next if /^\s+$/;
        if($line =~ /^\#\#sequence-region\s+(\S+)\s+(\S+)\s+(\S+)\s*/){
            my($seqid,$start,$end) = ($1,$2,$3);
            push @{ $self->{'segments'} }, Bio::LocatableSeq->new(
                -id    => unescape($seqid),
                -start => $start,
                -end   => $end,
                -length => ($end - $start + 1),  ## make the length explicit
           );
           $handled = 1;
        } elsif($line =~ /^(\#\#feature-ontology)/) {
            #to be implemented
            $self->warn("$1 header tag parsing unimplemented");
        } elsif($line =~ /^(\#\#attribute-ontology)/) {
            #to be implemented
            $self->warn("$1 header tag parsing unimplemented");
        } elsif($line =~ /^(\#\#source-ontology)/) {
            #to be implemented
            $self->warn("$1 header tag parsing unimplemented");
        } elsif($line =~ /^(\#\#\#)/) {
            #to be implemented
            $self->warn("$1 header tag parsing unimplemented");
        } elsif($line =~ /^(\#\#FASTA)/) {
            # initial ##FASTA is optional - artemis does not use it
            $line = $self->_readline();
            if ($line !~ /^\>(\S+)/) {
                $self->throw("##FASTA directive must be followed by fasta header, not: $line");
            }
        }
         
        if ($line =~ /^\>(.*)/) {
            # seq data can be at header or footer
            my $seq = $self->_parse_sequence($line);
            if ($seq) {
                $self->_seq_by_id_h->{$seq->primary_id} = $seq;
            }
        }
             

        if(!$handled){
            push @unhandled, $line;
        }

        #looks like the header is over!
        last unless $line =~ /^\#/;
    }

    foreach my $line (@unhandled){
        $self->_pushback($line);
    }

    return 1;
}

sub _parse_sequence {
    my ($self, $line) = @_;

    if ($line =~ /^\>(.*)/) {
        
        my $seqid = $1;
        $seqid =~ s/\s+$//;
        my $desc = '';
        if ($seqid =~ /(\S+)\s+(.*)/) {
            ($seqid, $desc) = ($1,$2);
        }
        my $res = '';
        while (my $line = $self->_readline) {
            if ($line =~ /^\#/) {
                last;
            }
            if ($line =~ /^\>/) {
                $self->_pushback($line);
                last;
            }
            $line =~ s/\s//g;
            $res .= $line;
        }
        return if $self->ignore_sequence;

        my $seqfactory = Bio::Seq::SeqFactory->new('Bio::Seq');
        my $seq = $seqfactory->create(-seq=>$res, 
                                      -id=>$seqid,
                                      -desc=>$desc);
        $seq->accession_number($seqid);
        if ($self->features_attached_to_seqs) {
            my @feats = 
              @{$self->_feature_idx_by_seq_id->{$seqid}};
            $seq->add_SeqFeature($_) foreach @feats;
            @{$self->_feature_idx_by_seq_id->{$seqid}} = ();
        }
        return $seq;
    }
    else {
        $self->throw("expected fasta header, not: $line");
    }
}


=head2 next_segment

 Title   : next_segment
 Usage   : my $seq = $gffio->next_segment;
 Function: Returns a Bio::LocatableSeq object corresponding to a 
           GFF "##sequence-region" header line.
 Example :
 Returns : A Bio::LocatableSeq object, or undef if
           there are no more sequences.
 Args    : none


=cut

sub next_segment{
    my ($self,@args) = @_;
    return shift @{ $self->{'segments'} } if defined $self->{'segments'};
    return;
}


=head2 next_feature

 Title   : next_feature
 Usage   : $seqfeature = $gffio->next_feature();
 Function: Returns the next feature available in the input file or stream, or
           undef if there are no more features.
 Example :
 Returns : A Bio::SeqFeatureI implementing object, or undef if there are no
           more features.
 Args    : none    

=cut

sub next_feature {
    my ($self) = @_;
    
    my $gff_string;
    
    # be graceful about empty lines or comments, and make sure we return undef
    # if the input's consumed
    while(($gff_string = $self->_readline()) && defined($gff_string)) {
        if ($gff_string =~ /^\#\#\#/) {
            # all forward refs have been seen; TODO
        }
        next if($gff_string =~ /^\#/ || $gff_string =~ /^\s*$/ ||
                $gff_string =~ m{^//});

        while ($gff_string =~ /^\>(.+)/) {
            # fasta can be in header or footer
            my $seq = $self->_parse_sequence($gff_string);
            if ($seq) {
                $self->_seq_by_id_h->{$seq->primary_id} = $seq;
                $gff_string = $self->_readline;
                last unless $gff_string;
            }
        }
        last; 
    }
    return unless $gff_string;

    my $feat = Bio::SeqFeature::Generic->new();
    $self->from_gff_string($feat, $gff_string);

    if ($self->features_attached_to_seqs) {
        push(@{$self->_feature_idx_by_seq_id->{$feat->seq_id}},
             $feat);
    }

    return $feat;
}

sub _feature_idx_by_seq_id {
    my $self = shift;
    $self->{__feature_idx_by_seq_id} = shift if @_;
    $self->{__feature_idx_by_seq_id} = {}
      unless $self->{__feature_idx_by_seq_id};
    return $self->{__feature_idx_by_seq_id};
}


=head2 from_gff_string

 Title   : from_gff_string
 Usage   : $gff->from_gff_string($feature, $gff_string);
 Function: Sets properties of a SeqFeatureI object from a GFF-formatted
           string. Interpretation of the string depends on the version
           that has been specified at initialization.

           This method is used by next_feature(). It actually dispatches to
           one of the version-specific (private) methods.
 Example :
 Returns : void
 Args    : A Bio::SeqFeatureI implementing object to be initialized
           The GFF-formatted string to initialize it from

=cut

sub from_gff_string {
    my ($self, $feat, $gff_string) = @_;

    if($self->gff_version() == 1)  {
        return $self->_from_gff1_string($feat, $gff_string);
    } elsif( $self->gff_version() == 3 ) {
        return $self->_from_gff3_string($feat, $gff_string);
    } else {
        return $self->_from_gff2_string($feat, $gff_string);
    }
}


=head2 _from_gff1_string

 Title   : _from_gff1_string
 Usage   :
 Function:
 Example :
 Returns : void
 Args    : A Bio::SeqFeatureI implementing object to be initialized
           The GFF-formatted string to initialize it from

=cut

sub _from_gff1_string {
    my ($gff, $feat, $string) = @_;
    chomp $string;
    my ($seqname, $source, $primary, $start, $end, $score, 
        $strand, $frame, @group) = split(/\t/, $string);

    if ( !defined $frame ) {
        $feat->throw("[$string] does not look like GFF to me");
    }
    $frame = 0 unless( $frame =~ /^\d+$/);
    $feat->seq_id($seqname);
    $feat->source_tag($source);
    $feat->primary_tag($primary);
    $feat->start($start);
    $feat->end($end);
    $feat->frame($frame);
    if ( $score eq '.' ) {
        #$feat->score(undef);
    } else {
        $feat->score($score);
    }
    if ( $strand eq '-' ) { $feat->strand(-1); }
    if ( $strand eq '+' ) { $feat->strand(1); }
    if ( $strand eq '.' ) { $feat->strand(0); }
    foreach my $g ( @group ) {
        if ( $g =~ /(\S+)=(\S+)/ ) {
            my $tag = $1;
            my $value = $2;
            $feat->add_tag_value($1, $2);
        } else {
            $feat->add_tag_value('group', $g);
        }
    }
}


=head2 _from_gff2_string

 Title   : _from_gff2_string
 Usage   :
 Function:
 Example :
 Returns : void
 Args    : A Bio::SeqFeatureI implementing object to be initialized
           The GFF2-formatted string to initialize it from


=cut

sub _from_gff2_string {
    my ($gff, $feat, $string) = @_;
    chomp($string);

    # according to the Sanger website, GFF2 should be single-tab
    # separated elements, and the free-text at the end should contain
    # text-translated tab symbols but no "real" tabs, so splitting on
    # \t is safe, and $attribs gets the entire attributes field to be
    # parsed later
   
    # sendu: but the tag value pair can (should?) be separated by a tab. The
    # 'no tabs' thing seems to apply only to the free text that is allowed for
    # the value

    my ($seqname, $source, $primary, $start, 
        $end, $score, $strand, $frame, @attribs) = split(/\t+/, $string);
    my $attribs = join ' ', @attribs;
   
    if ( !defined $frame ) {
        $feat->throw("[$string] does not look like GFF2 to me");
    }
    $feat->seq_id($seqname);
    $feat->source_tag($source);
    $feat->primary_tag($primary);
    $feat->start($start);
    $feat->end($end);
    $feat->frame($frame);
    if ( $score eq '.' ) {
        # $feat->score(undef);
    } else {
        $feat->score($score);
    }
    if ( $strand eq '-' ) { $feat->strand(-1); }
    if ( $strand eq '+' ) { $feat->strand(1); }
    if ( $strand eq '.' ) { $feat->strand(0); }


    #  <Begin Inefficient Code from Mark Wilkinson> 
    # this routine is necessay to allow the presence of semicolons in
    # quoted text Semicolons are the delimiting character for new
    # tag/value attributes.  it is more or less a "state" machine, with
    # the "quoted" flag going up and down as we pass thorugh quotes to
    # distinguish free-text semicolon and hash symbols from GFF control
    # characters
     
    my $flag = 0; # this could be changed to a bit and just be twiddled
    my @parsed;

    # run through each character one at a time and check it
    # NOTE: changed to foreach loop which is more efficient in perl
    # --jasons
    for my $a ( split //, $attribs ) { 
        # flag up on entering quoted text, down on leaving it
        if( $a eq '"') { $flag = ( $flag == 0 ) ? 1:0 }
        elsif( $a eq ';' && $flag ) { $a = "INSERT_SEMICOLON_HERE"}
        elsif( $a eq '#' && ! $flag ) { last } 
        push @parsed, $a;
    }
    $attribs = join "", @parsed; # rejoin into a single string

    # <End Inefficient Code>   
    # Please feel free to fix this and make it more "perlish"

    my @key_vals = split /;/, $attribs;   # attributes are semicolon-delimited

    foreach my $pair ( @key_vals ) {
        # replace semicolons that were removed from free-text above.
        $pair =~ s/INSERT_SEMICOLON_HERE/;/g;        

        # separate the key from the value
        my ($blank, $key, $values) = split  /^\s*([\w\d]+)\s/, $pair; 

        if( defined $values ) {
            my @values;
            # free text is quoted, so match each free-text block
            # and remove it from the $values string
            while ($values =~ s/"(.*?)"//){
                # and push it on to the list of values (tags may have
                # more than one value... and the value may be undef) 
                push @values, $1;
            }

            # and what is left over should be space-separated
            # non-free-text values

            my @othervals = split /\s+/, $values;  
            foreach my $othervalue(@othervals){
                # get rid of any empty strings which might 
                # result from the split
                if (CORE::length($othervalue) > 0) {push @values, $othervalue}  
            }

            foreach my $value(@values){
                $feat->add_tag_value($key, $value);
            }
        }
    }
}


sub _from_gff3_string {
    my ($gff, $feat, $string) = @_;
    chomp($string);

    # according to the now nearly final GFF3 spec, columns should 
    # be tab separated, allowing unescaped spaces to occur in
    # column 9

    my ($seqname, $source, $primary, $start, $end, 
        $score, $strand, $frame, $groups) = split(/\t/, $string);
    
    if ( ! defined $frame ) {
        $feat->throw("[$string] does not look like GFF3 to me");
    }
    $feat->seq_id($seqname);
    $feat->source_tag($source);
    $feat->primary_tag($primary);
    $feat->start($start);
    $feat->end($end);
    $feat->frame($frame);
    if ( $score eq '.' ) {
        #$feat->score(undef);
    } else {
        $feat->score($score);
    }
    if ( $strand eq '-' ) { $feat->strand(-1); }
    if ( $strand eq '+' ) { $feat->strand(1); }
    if ( $strand eq '.' ) { $feat->strand(0); }
    my @groups = split(/\s*;\s*/, $groups);

    for my $group (@groups) {
        my ($tag,$value) = split /=/,$group;
        $tag             = unescape($tag);
        my @values       = map {unescape($_)} split /,/,$value;
        for my $v ( @values ) {  $feat->add_tag_value($tag,$v); }
    }
}

# taken from Bio::DB::GFF
sub unescape {
  my $v = shift;
  $v =~ tr/+/ /;
  $v =~ s/%([0-9a-fA-F]{2})/chr hex($1)/ge;
  return $v;
}


=head2 write_feature

 Title   : write_feature
 Usage   : $gffio->write_feature($feature);
 Function: Writes the specified SeqFeatureI object in GFF format to the stream
           associated with this instance.
 Returns : none
 Args    : An array of Bio::SeqFeatureI implementing objects to be serialized

=cut

sub write_feature {
    my ($self, @features) = @_;
    return unless @features;
    if( $self->{'_first'} && $self->gff_version() == 3 ) {
        $self->_print("##gff-version 3\n");
    }
    $self->{'_first'} = 0;
    foreach my $feature ( @features ) {
        $self->_print($self->gff_string($feature)."\n");
    }
}


=head2 gff_string

 Title   : gff_string
 Usage   : $gffstr = $gffio->gff_string($feature);
 Function: Obtain the GFF-formatted representation of a SeqFeatureI object.
           The formatting depends on the version specified at initialization.

           This method is used by write_feature(). It actually dispatches to
           one of the version-specific (private) methods.
 Example :
 Returns : A GFF-formatted string representation of the SeqFeature
 Args    : A Bio::SeqFeatureI implementing object to be GFF-stringified

=cut

sub gff_string{
    my ($self, $feature) = @_;

    if($self->gff_version() == 1) {
        return $self->_gff1_string($feature);
    } elsif( $self->gff_version() == 3 ) {
        return $self->_gff3_string($feature);
    } elsif( $self->gff_version() == 2.5 ) {
        return $self->_gff25_string($feature);
    } else {
        return $self->_gff2_string($feature);
    }
}


=head2 _gff1_string

 Title   : _gff1_string
 Usage   : $gffstr = $gffio->_gff1_string
 Function: 
 Example :
 Returns : A GFF1-formatted string representation of the SeqFeature
 Args    : A Bio::SeqFeatureI implementing object to be GFF-stringified

=cut

sub _gff1_string{
    my ($gff, $feat) = @_;
    my ($str,$score,$frame,$name,$strand);

    if( $feat->can('score') ) {
        $score = $feat->score();
    }
    $score = '.' unless defined $score;

    if( $feat->can('frame') ) {
        $frame = $feat->frame();
    }
    $frame = '.' unless defined $frame;

    $strand = $feat->strand();
    if(! $strand) {
        $strand = ".";
    } elsif( $strand == 1 ) {
        $strand = '+';
    } elsif ( $feat->strand == -1 ) {
        $strand = '-';
    }
   
    if( $feat->can('seqname') ) {
        $name = $feat->seq_id();
        $name ||= 'SEQ';
    } else {
        $name = 'SEQ';
    }

    $str = join("\t",
                $name,
                $feat->source_tag,
                $feat->primary_tag,
                $feat->start,
                $feat->end,
                $score,
                $strand,
                $frame);

    foreach my $tag ( $feat->get_all_tags ) {
        next if exists $SKIPPED_TAGS{$tag};
        foreach my $value ( $feat->get_tag_values($tag) ) {
        $str .= " $tag=$value" if $value;
        }
    }

    return $str;
}


=head2 _gff2_string

 Title   : _gff2_string
 Usage   : $gffstr = $gffio->_gff2_string
 Function: 
 Example :
 Returns : A GFF2-formatted string representation of the SeqFeature
 Args    : A Bio::SeqFeatureI implementing object to be GFF2-stringified

=cut

sub _gff2_string{
    my ($gff, $origfeat) = @_;
    my $feat;
    if ($origfeat->isa('Bio::SeqFeature::FeaturePair')){
        $feat = $origfeat->feature2;
    } else {
        $feat = $origfeat;
    }
    my ($str1, $str2,$score,$frame,$name,$strand);

    if( $feat->can('score') ) {
        $score = $feat->score();
    }
    $score = '.' unless defined $score;

    if( $feat->can('frame') ) {
        $frame = $feat->frame();
    }
    $frame = '.' unless defined $frame;

    $strand = $feat->strand();
    if(! $strand) {
        $strand = ".";
    } elsif( $strand == 1 ) {
        $strand = '+';
    } elsif ( $feat->strand == -1 ) {
        $strand = '-';
    }

    if( $feat->can('seqname') ) {
        $name = $feat->seq_id();
    }
    $name ||= 'SEQ';

    $str1 = join("\t",
                 $name,
                 $feat->source_tag(),
                 $feat->primary_tag(),
                 $feat->start(),
                 $feat->end(),
                 $score,
                 $strand,
                 $frame);
    # the routine below is the only modification I made to the original
    # ->gff_string routine (above) as on November 17th, 2000, the
    # Sanger webpage describing GFF2 format reads: "From version 2
    # onwards, the attribute field must have a tag value structure
    # following the syntax used within objects in a .ace file,
    # flattened onto one line by semicolon separators. Tags must be
    # standard identifiers ([A-Za-z][A-Za-z0-9_]*).  Free text values
    # must be quoted with double quotes".
    # MW
   
    my @group;

    foreach my $tag ( $feat->get_all_tags ) {
        next if exists $SKIPPED_TAGS{$tag};
        my @v;
        foreach my $value ( $feat->get_tag_values($tag) ) {
            unless( defined $value && length($value) ) {
                # quote anything other than valid tag/value characters
                $value = '""';
            } elsif ($value =~ /[^A-Za-z0-9_]/){
                # substitute tab and newline chars by their UNIX equivalent
                $value =~ s/\t/\\t/g;
                $value =~ s/\n/\\n/g;
                $value = '"' . $value . '" ';
            }
            push @v, $value;
            # for this tag (allowed in GFF2 and .ace format)
        }
        push @group, "$tag ".join(" ", @v);
    }

    $str2 .= join(' ; ', @group);
    # Add Target information for Feature Pairs
    if( ! $feat->has_tag('Target') && # This is a bad hack IMHO
        ! $feat->has_tag('Group')  &&
        $origfeat->isa('Bio::SeqFeature::FeaturePair') ) {
        $str2 = sprintf("Target %s %d %d", $origfeat->feature1->seq_id,
                       ( $origfeat->feature1->strand < 0 ? 
                         ( $origfeat->feature1->end,
                           $origfeat->feature1->start) :
                         ( $origfeat->feature1->start,
                           $origfeat->feature1->end) 
                         )) . ($str2?" ; ".$str2:"");  # need to put Target information before other tag/value pairs - mw
    }
    return $str1."\t".$str2;
}


=head2 _gff25_string

 Title   : _gff25_string
 Usage   : $gffstr = $gffio->_gff2_string
 Function: To get a format of GFF that is peculiar to Gbrowse/Bio::DB::GFF
 Example :
 Returns : A GFF2.5-formatted string representation of the SeqFeature
 Args    : A Bio::SeqFeatureI implementing object to be GFF2.5-stringified

=cut

sub _gff25_string {
    my ($gff, $origfeat) = @_;
    my $feat;
    if ($origfeat->isa('Bio::SeqFeature::FeaturePair')){
        $feat = $origfeat->feature2;
    } else {
        $feat = $origfeat;
    }
    my ($str1, $str2,$score,$frame,$name,$strand);

    if( $feat->can('score') ) {
        $score = $feat->score();
    }
    $score = '.' unless defined $score;

    if( $feat->can('frame') ) {
        $frame = $feat->frame();
    }
    $frame = '.' unless defined $frame;

    $strand = $feat->strand();
    if(! $strand) {
        $strand = ".";
    } elsif( $strand == 1 ) {
        $strand = '+';
    } elsif ( $feat->strand == -1 ) {
        $strand = '-';
    }

    if( $feat->can('seqname') ) {
        $name = $feat->seq_id();
        $name ||= 'SEQ';
    } else {
        $name = 'SEQ';
    }
    $str1 = join("\t",
                 $name,
                 $feat->source_tag(),
                 $feat->primary_tag(),
                 $feat->start(),
                 $feat->end(),
                 $score,
                 $strand,
                 $frame);

    my @all_tags = $feat->all_tags;
    my @group; my @firstgroup;
    if (@all_tags) {   # only play this game if it is worth playing...
        foreach my $tag ( @all_tags ) {
            my @v;
            foreach my $value ( $feat->get_tag_values($tag) ) {
            next if exists $SKIPPED_TAGS{$tag};
                unless( defined $value && length($value) ) {
                    $value = '""';
                } elsif ($value =~ /[^A-Za-z0-9_]/){
                    $value =~ s/\t/\\t/g; # substitute tab and newline 
                    # characters
                    $value =~ s/\n/\\n/g; # to their UNIX equivalents
                    $value = '"' . $value . '" ';
                } # if the value contains 
                  # anything other than valid 
                  # tag/value characters, then 
                  # quote it
                push @v, $value;
                # for this tag (allowed in GFF2 and .ace format)
            }
            if (($tag eq 'Group') || ($tag eq 'Target')){ # hopefully we wont get both...
                push @firstgroup, "$tag ".join(" ", @v);
            } else {
                push @group, "$tag ".join(" ", @v);
            }
        }
    }
    $str2 = join(' ; ', (@firstgroup, @group));
    # Add Target information for Feature Pairs
    if( ! $feat->has_tag('Target') && # This is a bad hack IMHO
        ! $feat->has_tag('Group') &&
        $origfeat->isa('Bio::SeqFeature::FeaturePair') ) {
        $str2 = sprintf("Target %s ; tstart %d ; tend %d", $origfeat->feature1->seq_id,
                        ( $origfeat->feature1->strand < 0 ? 
                          ( $origfeat->feature1->end,
                            $origfeat->feature1->start) :
                          ( $origfeat->feature1->start,
                            $origfeat->feature1->end) 
                        )) . ($str2?" ; ".$str2:""); # need to put the target info before other tag/value pairs - mw
    }
    return $str1 . "\t".  $str2;
}


=head2 _gff3_string

  Title   : _gff3_string
  Usage   : $gffstr = $gffio->_gff3_string
  Function: 
  Example :
  Returns : A GFF3-formatted string representation of the SeqFeature
  Args    : A Bio::SeqFeatureI implementing object to be GFF3-stringified

=cut

sub _gff3_string {
    my ($gff, $origfeat) = @_;
    my $feat;
    if ($origfeat->isa('Bio::SeqFeature::FeaturePair')){
        $feat = $origfeat->feature2;
    } else {
        $feat = $origfeat;
    }

    my $ID = $gff->_incrementGFF3ID();

    my ($score,$frame,$name,$strand);

    if( $feat->can('score') ) {
        $score = $feat->score();
    }
    $score = '.' unless defined $score;

    if( $feat->can('frame') ) {
        $frame = $feat->frame();
    }
    $frame = '1' unless defined $frame;

    $strand = $feat->strand();

    if(! $strand) {
        $strand = ".";
    } elsif( $strand == 1 ) {
        $strand = '+';
    } elsif ( $feat->strand == -1 ) {
        $strand = '-';
    }

    if( $feat->can('seqname') ) {
        $name = $feat->seq_id();
        $name ||= 'SEQ';
    } else {
        $name = 'SEQ';
    }

    my @groups;

    # force leading ID and Parent tags
    my @all_tags =  grep { ! exists $GFF3_ID_Tags{$_} } $feat->all_tags;
    for my $t ( sort { $GFF3_ID_Tags{$b} <=> $GFF3_ID_Tags{$a} }
                keys %GFF3_ID_Tags ) {
        unshift @all_tags, $t if $feat->has_tag($t);
    }

    for my $tag ( @all_tags ) {
    next if exists $SKIPPED_TAGS{$tag};
        # next if $tag eq 'Target';
        if ($tag eq 'Target' && ! $origfeat->isa('Bio::SeqFeature::FeaturePair')){  
            # simple Target,start,stop
            my($target_id, $b,$e,$strand) = $feat->get_tag_values($tag); 
            next unless(defined($e) && defined($b) && $target_id);
            ($b,$e)= ($e,$b) if(defined $strand && $strand<0);
            $target_id =~ s/([\t\n\r%&\=;,])/sprintf("%%%X",ord($1))/ge;    
            push @groups, sprintf("Target=%s %d %d", $target_id,$b,$e);
            next;
        }

        my $valuestr;
        # a string which will hold one or more values 
        # for this tag, with quoted free text and 
        # space-separated individual values.
        my @v;
        for my $value ( $feat->get_tag_values($tag) ) {
            if(  defined $value && length($value) ) { 
                                #$value =~ tr/ /+/;  #spaces are allowed now
                if ( ref $value eq 'Bio::Annotation::Comment') {
                    $value = $value->text;
                }

                if ($value =~ /[^a-zA-Z0-9\,\;\=\.:\%\^\*\$\@\!\+\_\?\-]/) {
                    $value =~ s/\t/\\t/g; # substitute tab and newline 
                    # characters
                    $value =~ s/\n/\\n/g; # to their UNIX equivalents

                    # Unescaped quotes are not allowed in GFF3
                    #                    $value = '"' . $value . '"';
                }
                $value =~ s/([\t\n\r%&\=;,])/sprintf("%%%X",ord($1))/ge;
            } else {
                # if it is completely empty, then just make empty double quotes
                $value = '""';
            }
            push @v, $value;
        }
        # can we figure out how to improve this?
        $tag = lcfirst($tag) unless ( $tag =~
            /^(ID|Name|Alias|Parent|Gap|Target|Derives_from|Note|Dbxref|Ontology_term)$/);

        push @groups, "$tag=".join(",",@v);
    }
    # Add Target information for Feature Pairs
    if( $feat->has_tag('Target') && 
        ! $feat->has_tag('Group') &&
        $origfeat->isa('Bio::SeqFeature::FeaturePair') ) {

        my $target_id = $origfeat->feature1->seq_id;
        $target_id =~ s/([\t\n\r%&\=;,])/sprintf("%%%X",ord($1))/ge;    

        push @groups, sprintf("Target=%s %d %d", 
                              $target_id,
                              ( $origfeat->feature1->strand < 0 ? 
                                ( $origfeat->feature1->end,
                                  $origfeat->feature1->start) :
                                ( $origfeat->feature1->start,
                                  $origfeat->feature1->end) 
                                ));
    }

    # unshift @groups, "ID=autogenerated$ID" unless ($feat->has_tag('ID'));
    if ( $feat->can('name') && defined($feat->name) ) {
        # such as might be for Bio::DB::SeqFeature
        unshift @groups, 'Name=' . $feat->name;
    }

    my $gff_string = "";
    if ($feat->location->isa("Bio::Location::SplitLocationI")) {
        my @locs = $feat->location->each_Location;
        foreach my $loc (@locs) {
            $gff_string .= join("\t",
                                $name,
                                $feat->source_tag() || '.',
                                $feat->primary_tag(),
                                $loc->start(),
                                $loc->end(),
                                $score,
                                $strand,
                                $frame,
                                join(';', @groups)) . "\n";
        }
        chop $gff_string;
        return $gff_string;
    } else {
        $gff_string = join("\t",
                           $name,
                           $feat->source_tag() || '.',
                           $feat->primary_tag(),
                           $feat->start(),
                           $feat->end(),
                           $score,
                           $strand,
                           $frame, 
                           join(';', @groups));
    }
    return $gff_string;
}


=head2 gff_version

  Title   : _gff_version
  Usage   : $gffversion = $gffio->gff_version
  Function: 
  Example :
  Returns : The GFF version this parser will accept and emit.
  Args    : none

=cut

sub gff_version {
    my ($self, $value) = @_;
    if(defined $value && grep {$value == $_ } ( 1, 2, 2.5, 3)) {
        $self->{'GFF_VERSION'} = $value;
    }
    return $self->{'GFF_VERSION'};
}


# Make filehandles

=head2 newFh

 Title   : newFh
 Usage   : $fh = Bio::Tools::GFF->newFh(-file=>$filename,-format=>'Format')
 Function: does a new() followed by an fh()
 Example : $fh = Bio::Tools::GFF->newFh(-file=>$filename,-format=>'Format')
           $feature = <$fh>;            # read a feature object
           print $fh $feature;          # write a feature object
 Returns : filehandle tied to the Bio::Tools::GFF class
 Args    :

=cut

sub newFh {
    my $class = shift;
    return unless my $self = $class->new(@_);
    return $self->fh;
}


=head2 fh

 Title   : fh
 Usage   : $obj->fh
 Function:
 Example : $fh = $obj->fh;      # make a tied filehandle
           $feature = <$fh>;    # read a feature object
           print $fh $feature;  # write a feature object
 Returns : filehandle tied to Bio::Tools::GFF class
 Args    : none

=cut


sub fh {
    my $self = shift;
    my $class = ref($self) || $self;
    my $s = Symbol::gensym;
    tie $$s,$class,$self;
    return $s;
}

# This accessor is used for accessing the Bio::Seq objects from a GFF3
# file; if the file you are using has no sequence data you can ignore
# this accessor

# This accessor returns a hash reference containing Bio::Seq objects,
# indexed by Bio::Seq->primary_id

sub _seq_by_id_h {
    my $self = shift;

    return $self->{'_seq_by_id_h'} = shift if @_;
    $self->{'_seq_by_id_h'} = {}
    unless $self->{'_seq_by_id_h'};
    return $self->{'_seq_by_id_h'};
}


=head2 get_seqs

 Title   : get_seqs
 Usage   :
 Function: Returns all Bio::Seq objects populated by GFF3 file
 Example :
 Returns : 
 Args    :

=cut

sub get_seqs {
    my ($self,@args) = @_;
    return values %{$self->_seq_by_id_h};
}


=head2 features_attached_to_seqs

 Title   : features_attached_to_seqs
 Usage   : $obj->features_attached_to_seqs(1);
 Function: For use with GFF3 containg sequence only

    Setting this B<before> parsing ensures that all Bio::Seq object
    created will have the appropriate features added to them

    defaults to false (off)

    Note that this mode will incur higher memory usage because features
    will have to be cached until the relevant feature comes along

 Example : 
 Returns : value of features_attached_to_seqs (a boolean)
 Args    : on set, new value (a boolean, optional)


=cut

sub features_attached_to_seqs{
    my $self = shift;

    return $self->{'_features_attached_to_seqs'} = shift if @_;
    return $self->{'_features_attached_to_seqs'};
}


=head2 ignore_sequence

 Title   : ignore_sequence
 Usage   : $obj->ignore_sequence(1);
 Function: For use with GFF3 containg sequence only

    Setting this B<before> parsing means that all sequence data will be
    ignored

 Example : 
 Returns : value of ignore_sequence (a boolean)
 Args    : on set, new value (a boolean, optional)

=cut

sub ignore_sequence{
    my $self = shift;

    return $self->{'_ignore_sequence'} = shift if @_;
    return $self->{'_ignore_sequence'};
}


sub DESTROY {
    my $self = shift;
    $self->close();
}

sub TIEHANDLE {
    my ($class,$val) = @_;
    return bless {'gffio' => $val}, $class;
}

sub READLINE {
    my $self = shift;
    return $self->{'gffio'}->next_feature() || undef unless wantarray;
    my (@list, $obj);
    push @list, $obj while $obj = $self->{'gffio'}->next_feature();
    return @list;
}

sub PRINT {
    my $self = shift;
    $self->{'gffio'}->write_feature(@_);
}

1;