#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;


my %objspe;
foreach my $obj ("hsa","mmu","rno","dre","ptr","ggo","gga","ssc","mml","dme","cel","ath","osa","zma","gma","sbi","bdi","mtr","sly","ptc","vvi") {
 $objspe{$obj} = 1;
}


my %name2taxon;
open NAME, "/var/www/html/sRNAtools/db/mirbase/hairpins/organisms.txt" || die "$!";
while(<NAME>) {
   chomp;
   next if(/^#/);
   my @temp = split(/\t/);
   next if not exists $objspe{$temp[0]};
   $name2taxon{$temp[4]} = $temp[0];
}
close NAME;


my %id2type;
open NAME, "rfam.tsv" || die "$!";
while(<NAME>) {
   chomp;
   next if(/^#/);
   my @temp = split(/\t/);
   $id2type{$temp[0]} = $temp[4];
}
close NAME;


  my $infile = "rfam.fasta";
  open GENOMESEQ, "$infile" || die "$!";
  $/=">";<GENOMESEQ>;$/="\n";
  while(<GENOMESEQ>) {
   chomp;
   my $seqname = $_;
   $seqname =~ s/\s.*$//;
   my @temp = split(/_/,$seqname);
   my $id = $temp[0];
   my $gid = $temp[1];
   $/=">";
   my $seq=<GENOMESEQ>;
   chomp($seq);
   $seq=~s/\s+//g;
   $seq=~s/\n+//g;
   $seq=~s/U/T/g;
   if($id2type{$id} and $id2type{$id} ne "tRNA" and $id2type{$id} ne "lncRNA" and $id2type{$id} ne "other" and $id2type{$id} ne "precursor_RNA") {
    if(exists $name2taxon{$gid}) {
     open OUT,">>seqs/$name2taxon{$gid}".".fa" || die "$!";
     print OUT ">".$seqname."|".$id2type{$id}."\n".$seq."\n";
     close OUT;
    }
   }
   $/="\n";
  }
  close GENOMESEQ;

