File: getcds.pl

package info (click to toggle)
murasaki 1.68.6-6
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,928 kB
  • ctags: 3,100
  • sloc: cpp: 16,010; perl: 8,365; makefile: 186
file content (665 lines) | stat: -rwxr-xr-x 21,536 bytes parent folder | download | duplicates (5)
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
#!/usr/bin/perl -w

#Copyright (C) 2006-2008 Keio University
#(Kris Popendorf) <comp@bio.keio.ac.jp> (2006)
#
#This file is part of Murasaki.
#
#Murasaki is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#Murasaki is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with Murasaki.  If not, see <http://www.gnu.org/licenses/>.

use File::Basename;
use Getopt::Long;
use Pod::Usage;
#use Data::Dump qw{dump};

use strict;
my ($help,$man,$opt_prefix);

our ($seqhome,$root,$flexible,$strict,$beenwarned);

BEGIN {
  unshift(@INC,(fileparse($0))[1].'perlmodules');
}

use Murasaki;
use Murasaki::SeqFeatures;

our %common_overrides;
our %redirect;

my $opt_force;
my @instantRedirects;
my $verbose;
GetOptions('help|?' => \$help, man => \$man, flexible => \$flexible,
	   force=>\$opt_force,
	   'redirect=s' => sub { push(@instantRedirects,$_[1]) },
	   verbose => \$verbose,
	   'strict!' => \$strict);
pod2usage(1) if $help or $#ARGV<0;
pod2usage(-exitstatus => 0, -verbose => 2) if $man;

my $startdir=$ENV{PWD};
my %dbConnections; #keep connection up in case we use it later

print "Do stuff with @ARGV\n";

while(@ARGV){
  my ($filename,$outfile);
  $filename=shift(@ARGV);
  $outfile=shift(@ARGV) if @ARGV;
  if($outfile and -f $outfile){ #if it's another input file, throw it back on!
    unshift(@ARGV,$outfile);
    $outfile="$filename.cds";
  }

#  print "Make cds for $filename\n";

  $outfile="$filename.cds" unless $outfile;
  my @cds_features;
  our $src_primary='CDS';
  open(my $infh,$filename) or die "Couldn't open source file $filename";
  procOverrides("$filename.overrides") if -f "$filename.overrides";
  $src_primary=$common_overrides{CDS} if $common_overrides{CDS};

  my $redirect="$filename.redirect";
  my $globalRedirect=getPath($redirect)."/.redirect";
  push(@cds_features,useRedirect($filename,\@instantRedirects,$outfile)) if scalar(@instantRedirects);
  push(@cds_features,useRedirect($filename,$globalRedirect,$outfile)) if -f $globalRedirect;
  push(@cds_features,useRedirect($filename,$redirect,$outfile)) if -f $redirect;

  $_=<$infh>;
  if($_ and m/(\S+)\t(\d+)\t(\d+)\t(\d+)/){ #stitch format
    print "$filename is a stitch file. Compiling constituent parts:\n";
    do{
      my ($src,$len,$start,$stop)=m/(\S+)\t(\d+)\t(\d+)\t(\d+)/;
      #recursively generate baby!
      my $localpath=getPath($filename);
      if(!-f $src and $localpath ne './'){
	print "Don't see $src from this directory.\n".
	  "Trying from $localpath\n";
	chdir($localpath);
      }
      die "Can't find component file: $src\n" unless -f $src;
      my $runopts="";
      $runopts.=" --flexible" if $flexible;
      $runopts.=" --force" if $opt_force;
      $runopts.=" --verbose" if $verbose;
      $runopts.=join(" ",map {"--redirect=$_"} @instantRedirects);
      system("$root/getcds.pl $runopts $src") unless -f "$src.cds";
      die "Couldn't load annotation data for $src" unless -f "$src.cds";
      my $offset=$start-1;
      print "Adding $src.cds with offset $offset -> ";
      my @cds=readCds("$src.cds",$offset);
      print scalar(@cds)." CDS's\n";
      push(@cds_features,@cds);
    }while(<$infh>);
    close($infh);
  }else{ #simple file
    close($infh);
    if($filename=~m/\.fa(?:\.gz)?$/){ #bioperl won't get crap out of fasta files
      #in case we already got some data manually from a .redirect, don't duplicate
      unless($redirect{ensembl_build} || $redirect{ucsc_build} || $redirect{gtf}){
	#hope we can guess a database based on the filename
	my ($db,$build,$chrom)=guessDbSource($filename);
	if($db){
	  die "No chromosome?" unless $chrom;
	  die "Couldn't find $db build for chromosome $chrom\n" unless $build;
	  print "Appears to be $db data (build $build).\n";
	  push(@cds_features,ensemblFetch($build,$chrom)) if($db=~m/^ensembl$/i);
	  push(@cds_features,ucscFetch($build,$chrom)) if($db=~m/^ucsc$/i);
	}else{
	  die "Couldn't find a db source for $filename";
	}
      }
    }else{
      unless($redirect{nobioperl}){
	print "Loading $filename\n";
	my $seq=Bio::SeqIO->new(-file => $filename)->next_seq;
	die "Error loading $filename"  unless $seq;
	@cds_features = grep { $_->primary_tag eq $src_primary } $seq->get_SeqFeatures;
	print "$filename loaded. Contains ".($#cds_features+1)." CDSs\n";
	if($#cds_features<0 and !$opt_force){
	  print "Cowardly refusing to write an empty .cds file (use --force to force this).\n";
	  exit(2);
	}
      }
    }
  }
  writeCds("$outfile",@cds_features);
}

sub useRedirect {
  my ($filename,$redirect,$outfile)=@_;
  our $src_primary;
  if(ref $redirect){ #oneshot wonders
    foreach (@$redirect){
      s!^(.*?)(#|//|;|%).*$!$1!; #chop off various comments
      my ($key,$val)=m/^(.*?)=(.*)$/;
      next unless $key; #nothing? skip...
      $val=~s/\s+$//; #cleanup any spaces at end
      print "Redirect: $key = $val\n";
      $redirect{$key}=$val;
    }
  }else{
    print "Loading redirect $redirect...\n";
    open(my $infh,$redirect) or return;
    while(<$infh>){
      chomp;
      s!^(.*?)(#|//|;|%).*$!$1!; #chop off various comments
      my ($key,$val)=m/^(.*?)=(.*)$/;
      next unless $key; #nothing? skip...
      $val=~s/\s+$//; #cleanup any spaces at end
      print "Redirect: $key : $val\n";
      $redirect{$key}=$val;
    }
  }
  my ($chromosome,$offset)=(0,0);
  my $raw_chromosome; #before getting mangled hacchy-style
  my $out_primary=$src_primary;
  my ($ucsc_chromosome)=($filename=~m/(chr[^.]+)/);
  $out_primary=$redirect{primary} if exists $redirect{primary};
  $offset=$redirect{offset} if exists $redirect{offset};
  $redirect{nobioperl}=1 unless exists $redirect{'+bioperl'};
  if(exists($redirect{chromosome})){
    $chromosome=$redirect{chromosome};
    $raw_chromosome=$chromosome;
  }else{
    $chromosome=(parseEnsemblName($filename))->{chrom} if parseEnsemblName($filename);
    $chromosome=$1 if $filename=~m/chr(?:omosome\.?)?([^.]*)\..*$/ and !$chromosome;
    $chromosome=$1 if $filename=~m/(\d+|.)\..*$/ and !$chromosome;
    $raw_chromosome=$chromosome;
    my %conv=(X=>-1,Y=>-2,M=>-3,Un=>-2);
    $chromosome=$conv{$chromosome} if(exists($conv{$chromosome}));
  }
  return gtfFetch($redirect{gtf},$raw_chromosome,$filename) if $redirect{gtf};
  return ensemblFetch($redirect{ensembl_build},$raw_chromosome) if $redirect{ensembl_build};
  return ucscFetch($redirect{ucsc_build},$ucsc_chromosome) if $redirect{ucsc_build};
  if($redirect{murasaki_synth}){
    my $inf=$redirect{murasaki_synth};
    $inf.=getName($inf) if -d $inf;
    return murasakiSynth($inf,exists $redirect{murasaki_synth_id} ? $redirect{murasaki_synth_id}:getSeqId(repSuffix($inf,".seqs"),$filename));
  }

  #extract from one of hacchy's cooked files
  print "Identified as hacchy-zome $chromosome\n";
  die "Unknown chromosome" unless ($chromosome=~m/-?\d+/ and $chromosome!=0);
  die "No annotation source file?" unless $redirect{src};
  open(my $src,$redirect{src}) or die "Couldn't open indicated src file: $redirect{src}";
  my @features;
  while(<$src>){
    chomp;
    my @a=split(/\t/);
    next unless($a[1]==$chromosome or $chromosome eq 'any');
    push(@features,new Bio::SeqFeature::Generic
	 (-primary => $out_primary,
	  -tag => {($a[0] ? (gene => $a[0]):()), ($a[0] ? (locus_tag=>$a[0]):())},
	  -start => $offset+$a[2],
	  -end => $offset+$a[3],
	  -strand => $a[4])
	);
  }
  print "Derived ".scalar(@features)." features from $redirect.\n";
  return @features;
}

sub ensemblFetch {
  my ($build,$chromosome)=@_;
  my $out_primary=our $src_primary;
  $out_primary=$redirect{primary} if exists $redirect{primary};
  my $offset=exists $redirect{offset} ? $redirect{offset}:0;

  use DBI;
  my $dbh=getDb('ensembl',$build);
  my $sth = $dbh->prepare("SELECT i.stable_id,s.name,g.seq_region_start,g.seq_region_end,g.seq_region_strand FROM gene g, gene_stable_id i, seq_region s, coord_system c WHERE c.coord_system_id=s.coord_system_id AND c.name='chromosome' AND g.gene_id=i.gene_id and s.seq_region_id=g.seq_region_id AND s.name='$chromosome'"); #weee for ugly long SQL!
  print "Connected. Running query for chromosome $chromosome...\n";
  my $rv=$sth->execute;
  print "Query returned: $rv rows\n";
  my @a;
  my @features;
  while(@a=$sth->fetchrow_array){
    push(@features,new Bio::SeqFeature::Generic
	 (-primary => $out_primary,
	  -tag => {gene => $a[0], locus_tag=>$a[0]},
	  -start => $offset+$a[2],
	  -end => $offset+$a[3],
	  -strand => $a[4])
	);
  }
#  $dbh->disconnect or warn $dbh->errstr;
  return @features;
}

sub gtfFetch {
  my ($gtf,$chromosome,$filename)=@_;
  my @features;
  my $mergeExons=!$redirect{keepExons};
  my $offset=exists $redirect{offset} ? $redirect{offset}:0;

  print "Extracting features for $chromosome from ".(fileparse($gtf))[0]."\n";

  my %regions;
  my $multiseg=$chromosome=~m/seqlevel|nonchromosomal/;
  if($multiseg and $filename){
    #gets much more complicated
    %regions=loadSegments($filename);
  }

  my $length=`$root/geneparse -l -c $filename`;

  my $out_primary=our $src_primary;
  $out_primary=$redirect{primary} if exists $redirect{primary};

  open(my $gtfh,($gtf=~m/\.gz$/ ? "zcat $gtf|":$gtf)) or die "Couldn't open $gtf";
  my (@noteOrder,%notes);
  my $anonId=1;
  while(<$gtfh>){
    my $rawline=$_;
    my $segoffset=0;
    chomp;
    my ($chrom,$family,$feature,$start,$stop,$score,$strand,$frame,$infoString)=split(/\t/);
    next unless $feature eq $src_primary;
    if($multiseg){
#      warn "Source contig not found for $chrom?" unless exists $regions{$chrom};
      next unless exists $regions{$chrom};
      $segoffset=$regions{$chrom}->{offset};
    }else{
      next unless $chrom eq $chromosome;
    }

    $infoString=~s/;\s*$//;
    my @bits=split(/;\s*/,$infoString);
    my %info;
    foreach my $bit (@bits){
      $bit=~m/^\s*(\S+)\s"(.*)"$/ or die "Malformed info bit: '$bit'";
      $info{$1}=$2;
    }

    my $id=$info{gene_id};
    $id="ANON".($anonId) unless $id;
    
    if($multiseg){
      if($stop-$start>=$regions{$chrom}->{length}){
#	print dump($regions{$chrom})."\n";
	possiblyFatal("CDS outside of region: ($stop-$start=".($stop-$start).")>=".($regions{$chrom}->{length})." (from $rawline -> $chrom)\n");
      }
      
      if($offset+$stop+$segoffset){
	possiblyFatal("CDS outside of genome: $offset + $stop + $segoffset > $length (from $chrom)\n");
      }
    }

    my $note={-primary => $out_primary,
	      -tag => {gene=>$id,locus_tag=>$id},
	      -start => $offset+$start+$segoffset,
	      -end => $offset+$stop+$segoffset,
	      -strand => $strand};

    unless($mergeExons){
      push(@features,new Bio::SeqFeature::Generic
	   (%$note));
    }else{
      if($notes{$id}){
	mergeFeature($notes{$id},$note);
      }else{
	push(@noteOrder,$id);
	$notes{$id}=$note;
      }
    }
  }

  if($mergeExons){
    foreach my $id (@noteOrder){
      push(@features,new Bio::SeqFeature::Generic
	   (%{$notes{$id}}));
    }
  }
  
  print "Got ".(scalar @features)." features.\n";

  return @features;
}

sub mergeFeature {
  my ($target,$add)=@_;
  die "Merging two non-matching tags ($target->{-tag}->{gene} and $add->{-tag}->{gene})"
    unless $target->{-tag}->{gene} eq $add->{-tag}->{gene};
  #sadly, this seems to happen. wtf are these genes?
  warn "Merging two tags on different strands! ($target->{-strand} and $add->{-strand})"
    unless $target->{-strand} eq $add->{-strand};
  $target->{-start}=$add->{-start} if $target->{-start}>$add->{-start};
  $target->{-end}=$add->{-end} if $target->{-end}<$add->{-end};
}

sub ucscFetch {
  my ($build,$chromosome)=@_;
  my $out_primary=our $src_primary;
  $out_primary=$redirect{primary} if exists $redirect{primary};
  my $offset=exists $redirect{offset} ? $redirect{offset}:0;

  use DBI;
  my $dbh=getDb('ucsc',$build);
  my $sth = $dbh->prepare("SELECT name,chrom,cdsStart,cdsEnd,strand FROM ensGene WHERE chrom='$chromosome'"); #weee for short boring SQL!
  print "Connected. Running query for chromosome $chromosome...\n";
  my $rv=$sth->execute;
  print "Query returned: $rv rows\n";
  my @a;
  my @features;
  while(@a=$sth->fetchrow_array){
    push(@features,new Bio::SeqFeature::Generic
	 (-primary => $out_primary,
	  -tag => {gene => $a[0], locus_tag=>$a[0]},
	  -start => $offset+$a[2],
	  -end => $offset+$a[3],
	  -strand => $a[4])
	);
  }
#  $dbh->disconnect or warn $dbh->errstr;
  return @features;
}

sub murasakiSynth {
  my ($alignment,$seqid)=@_;
  my $out_primary=our $src_primary;
  $out_primary=$redirect{primary} if exists $redirect{primary};
  open(my $fh,$alignment) or die "Couldn't open $alignment.";
  my $alignname=getName($alignment);
  my $line=0;
  my @features;
  while(<$fh>){
    chomp;
    my @dats=split(/\t/);
    my ($start,$stop,$strand)=@dats[map {$seqid*3+$_} (0..2)];
    ($start,$stop)=(0-$stop,0-$start) if $start<0;
    $strand=($strand eq '+' ? 1:-1);
    my $id="$alignname:$seqid:$line";
    push(@features,new Bio::SeqFeature::Generic
	 (-primary => $out_primary,
	  -tag =>{gene=>$id,locus_tag=>$id},
	  -start=>$start,
	  -end=>$stop,
	  -strand=>$strand));
  }continue{$line++}
  return @features;
}

sub procOverrides {
  my $src=pop;
  open(my $infh,$src) or return;
  while(<$infh>){
    chomp;
    my ($key,$val)=m/^(.*?)=(.*)$/;
    print "Overriding $key as $val\n";
    $common_overrides{$key}=$val;
  }
}

sub getSeqId {
  my ($seqf,$target)=@_;
  open(my $fh,$seqf) or die "No sequence file $seqf";
  my $id=0;
  local $_;
  while(<$fh>){
    chomp;
    return $id if m/$target/;
  }continue{$id++}
  die "Couldn't find $target in $seqf";
  return 0;
}

sub getPath {
  my @ret=map {
    my ($name,$path,$suffix) = fileparse($_, qr{\.[^.]*});
    $path
  } @_;
  return @ret if $#_;
  return $ret[0];
}

sub getName {
  my @ret=map {
    my ($name,$path,$suffix) = fileparse($_, qr{\.[^.]*});
    $name
  } @_;
  return @ret if $#_;
  return $ret[0];
}

sub slurp {
 local $/;
  open(my $fh,"@_") or return;
  return <$fh>;
}

sub getDb {
  my ($db,$build)=@_;
  return $dbConnections{$db} if $dbConnections{$db};

  use DBI;

  my $dbh;
  if($db=~m/^ucsc$/i){
    my $dsn = "DBI:mysql:$build:genome-mysql.cse.ucsc.edu";
    my $db_user_name='genome';
    print "Connecting to UCSC MySQL DB...\n";
    $dbh = DBI->connect($dsn, $db_user_name) or die "Couldn't connect to $dsn!";
  }elsif($db=~m/^ensembl$/i){
    my ($release,$version)=$build=~m/_(\d+)(_[^_]+)$/;
    my $port=$release>47 ? 5306:3306;
    my $dsn = "DBI:mysql:$build:ensembldb.ensembl.org:$port";
    my $db_user_name='anonymous';
    print "Connecting to Ensembl MySQL DB...\n";
    $dbh = DBI->connect($dsn, $db_user_name) or die "Couldn't connect!";
  }else{
    die "Unknown database: $db";
  }
  $dbConnections{$db}=$dbh;
  return $dbh;
}

sub parseEnsemblDbName {
  my @bits=split(/_/,$_[0]);
  return {species=>"$bits[0] $bits[1]",
	  data=>$bits[2],
	  release=>$bits[3],
	  assembly=>$bits[4]}
}

sub parseEnsemblName {
  my ($file)=@_;
  my ($filename,$dir)=fileparse($file);
  my ($species,$assembly,$release,$type,$chrom,$gz)=($filename=~m/([^.]+)\.(.+)\.(\d+)\.(dna(?:_rm)?)\.((?:chromosome\.[^.]+)|nonchromosomal|seqlevel)\.fa(\.gz)?/) or return undef;
  $chrom=$1 if $chrom=~m/chromosome\.(.*)/;
  return {file=>$filename,
	  species=>$species,
	  assembly=>$assembly,
	  release=>$release,
	  type=>$type,
	  chrom=>$chrom,
	  compressed=>$gz};
}


sub guessDbSource {
  my ($file)=@_;
  my ($filename,$dir)=fileparse($file);
  my ($db,$build,$chrom);
  my $dat;
  if($dat=parseEnsemblName($filename)){
    my ($species,$assembly,$release,$dna,$file_chrom,$gz)=@{$dat}{qw{species assembly release type chrom compressed}};
    print "Looks like an Ensembl sequence ($species assembly: $assembly release: $release chromosome: $file_chrom).\n";
    $db='ensembl';
    my @dbs=getAllDbs($db,$release);
#    print "Databases available: ".join("\n",@dbs)."\n";
    my @similar;
    do {
      my $base=lc($species)."_core";
      my $tail=$assembly;
      $tail=~s/\D//g;
      @similar=grep(/^${base}_\d+_${tail}/,@dbs);
      unless(@similar){ #try just using release number
	print "No results for ${base}_\\d+_${tail}\n";
	#get by release (should only have one choice available)
	my $base=lc($species)."_core_$release";
	print "Trying $base\n";
	@similar=grep(/^$base/,@dbs);
      }
      unless(@similar){ #last resort
	#bos taurus acts a little strange. 3.1 is in the database as 3,3a,3b,3c,3d
	print "Still no results!\n";
	($tail)=($assembly=~m/^\D*(\d+)/); #just use the first numeric part
	if($tail){
	  print "Trying ${base}_\\d+_${tail}\n";
	  @similar=grep(/^${base}_\d+_${tail}/,@dbs);
	}
      }
    };
    my @best=grep {parseEnsemblDbName($_)->{release}==$release} @similar; #if possible, get same release
    if(!@best){ #otherwise take the highest release number
      @best=sort {parseEnsemblDbName($a)->{release}<=>parseEnsemblDbName($b)->{release}} @similar if $#similar>0;
    }
    #now take latest version/assembly
    @best=sort {parseEnsemblDbName($a)->{assembly}<=>parseEnsemblDbName($b)->{assembly}} @best;
    $build=$best[$#best];
    $chrom=$file_chrom;
  }
  return ($db,$build,$chrom);
}

sub getAllDbs {
  my ($db,$release)=@_;
  our %dbsAvailable;
  return @{$dbsAvailable{$db}} if ref $dbsAvailable{$db};

  my @dbs;
  my $dbid=$db;
  $dbid.=$release>47 ? "_v2":"_v1" if($db eq 'ensembl');
  my $cachefile="$ENV{HOME}/.murasaki.dbcache.$dbid";
  if(-f $cachefile and -M $cachefile < 1){
    print "Loading $db databases from cache ($cachefile)\n";
    @dbs=split(/\n/,slurp($cachefile));
  }else{
    use DBI;
    print "Loading available data sources for $dbid\n";
    my %sources=('ensembl_v1'=>
		 {host=>'ensembldb.ensembl.org',user=>'anonymous',port=>3306},
		 'ucsc'=>
		 {host=>'genome-mysql.cse.ucsc.edu',user=>'genome'}
		);
    $sources{'ensembl_v2'}={%{$sources{'ensembl_v1'}},port=>5306};
    die "Unknown db: $dbid" unless ref $sources{$dbid};
    @dbs=DBI->data_sources("mysql",$sources{$dbid});


    @dbs=map {(split(/:/,$_))[2]} @dbs; #only need the names
    blit(join("\n",@dbs),$cachefile);
    my $count=@dbs;
    print "Data sources availabe in $dbid: $count\n";
  }
  $dbsAvailable{$db}=[@dbs];
  return @dbs;
}

sub blit {
  my ($dat,$file)=@_;
  open(my $fh,">$file");
  print $fh $dat;
}

sub loadSegments {
  my ($filename)=(@_);
  unless(-f "$filename.len"){
    print "Extracting subsequence meta-data from $filename\n";
    system("$root/getsegments $filename") and die "Error creating segment data for $filename"
  }
  open(my $segfh,"$filename.len") or die "Couldn't open $filename.len";
  my $length=<$segfh>; #first line is length only
  local $_;
  my ($at,%regions)=(0,());
  while(<$segfh>){
    chomp;
    my ($length,$name)=split(/\t/,$_);
    my ($id,$meta)=$name=~m/^(.*?)\s+(.*)$/;
    if($meta=~m/dna(?:_rm)?:.*:.*:/){ #this is ensembl style
      $id=(split(/:/,$name))[3];
    }else{
      $id=$name unless $id;
    }
    $regions{$id}={offset=>$at,
		   length=>$length};
    $at+=$length+10;
  }
  print "Loaded meta-data for ".scalar(keys %regions)." subsequences\n";
  return %regions;
}

sub possiblyFatal {
  our ($strict,$beenwarned);
  my ($msg)=@_;
  die $msg if $strict;
  warn $msg unless $beenwarned;
  unless($beenwarned or $verbose){
    warn "Further warning suppressed (set verbose to see them).";
    $beenwarned=1;
  }
}

__END__

=head1 NAME

getcds.pl - CDS extraction from various annotation formats

=head1 SYNOPSIS

getcds.pl [options] input file [output file] [input file [outputfile] ...]

=head1 OPTIONS

 Options include:
   redirect => Enable a redirect at runtime. explained below.
   force => allows writing empty .cds files

If [output file] is unspecificied, "[input file].cds" is used.

There's lots of dark magic that can be performed with .redirect files.
Redirects are used to modify the ordinary behaviour and can be applied on
a global basis (a .redirect file in the same directory as [input file]), and/or
on a per-input basis ([input file].redirect). Redirects are read in that order
such that per-input effects are applied ontop of global effects.

If you've left the filename as-is from an Ensembl downoad, the appropriate
Ensembl DB source will be guessed automatically.

Possible redirects:

=item CDS - changes what tag type is searched for when running on bioperl
files (default is CDS)

=item offset - add some value to all coordinates

=item +bioperl - on top of any other redirect-based data, also extract annotation via
bioperl (using a direct disables bioperl's parser by default)

=item ensembl_build - grab data from the ensembl (in the specified schema)

=item ucsc_build - grab data from (in the specified schema)

=item murasaki_synth - synthesize annotation data for each anchor from an alignment (if this is a directory, then each input file (eg input.lav) is checked for a corresponding .anchors file (eg. input.anchors).

=item primary - what to type of tags to create from data gathered from outside data
(eg: ensembl, ucsc, or murasaki). default is the same as the cds redirect.

=item chromosome - forces a specific chromosome rather than deriving from filename

=item gtf - extract annotation from a .gtf file