#!/usr/bin/perl -w

#This script downloads the most current version of the chromosome
#sequences of the species specified below from the Ensembl database.
#Look for keyword "Customize"

#Author: Armin O. Schmitt, Humboldt-Universitaet zu Berlin, Germany


### General instructions ###
use strict;
use English;
use diagnostics -verbose;
use Bio::EnsEMBL::Registry;
use Bio::Perl;

my $reg = "Bio::EnsEMBL::Registry";
$reg->load_registry_from_db(
			    -host => "ensembldb.ensembl.org",
			    -user => "anonymous",
			    -verbose => '0',
			    -port => 5306);

my $version = Bio::EnsEMBL::Registry->software_version; 
print "Ensembl version:\t" . $version . "\n";

##### Customize species and name of fasta file here ####
my $species = 'bos_taurus';
my $dbOut = "GenomBtau4Ensembl" . $version . ".fasta";
########################################################

my $slice_adaptor = $reg->get_adaptor($species, 'core', 'Slice');
my $slices = $slice_adaptor->fetch_all('toplevel');           

my $seqio = new Bio::SeqIO ( -file => ">>$dbOut" , -format => 'Fasta' );

my $len_total = 0;
my $count = 0;

foreach my $slice (@$slices)
{
    my $len = $slice->length;
    my @fields = split(/:/, $slice->name());
  
    if($fields[0] eq  "chromosome")
    {    	
	$len_total = $len_total + $len;
	$count = $count + 1;
    }
}

print "Total length {bp]:\t" . $len_total . "\n";
print "Number of sequences downloaded:\t" . $count . "\n";
