#!/usr/bin/perl
use strict;
use Bio::SeqIO;
use Bio::FeatureIO;

# Names of the input files
my $input_bed_file = $ARGV[0];
my $input_fasta_file = $ARGV[1];

# Read in each feature from the BED file using BioPerl
my $bed_file_object = Bio::FeatureIO->new(-file => $input_bed_file, -format => 'bed');
while( my $feature = $bed_file_object->next_feature()) 
{
  # Read in each sequence from the FASTA file using BioPerl
  my $fasta_file_input_object  = Bio::SeqIO->new(-file => $input_fasta_file, -format => 'fasta');
  # Create a new file for each gene with all the sequences
  my @name_of_gene = $feature->get_tag_values('Name');
  my $fasta_file_output_object = Bio::SeqIO->new(-file => ">".$name_of_gene[0].'.fa', -format => 'fasta');
  
  while(my $sequence = $fasta_file_input_object->next_seq() ) 
  {
    # Get the coordinates of the gene and copy that region out
    my $sequence_of_gene = $sequence->subseq($feature->start, $feature->end);
    # Write out the gene to a file
    my $newseq = Bio::Seq->new( -seq => $sequence_of_gene, -id => $sequence->id );
    $fasta_file_output_object->write_seq($newseq);
  }
}


