#!/usr/bin/perl

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

if(-d "mature") {
   system("rm -fr mature/");   
}
if(-d "hairpin") {
   system("rm -fr hairpin/");   
}
system("mkdir mature");
system("mkdir hairpin");

my %abbr2org;
my $org;
my $abbr;
open NAME, "table.html.txt" || die "$!";
while(<NAME>) {
   chomp;
   if(/\((.*)\)/) {
	   $org =$1;    
   }
   if(/\/(\w+)-pre.fas/) {
	   $abbr =$1; 
	   $abbr2org{$abbr} = $org;
   } 
}
close NAME;

my %org2txid;
open NAME, "/var/www/html/sRNAtools/db/rfam_14.9/taxonomy.txt" || die "$!";
while(<NAME>) {
   chomp;
   next if(/^#/);
   my @temp = split(/\t/);
   my $name = "";
   if($temp[1] =~ /^(\S+\s\S+)/){
	   $name = $1;   
	   $org2txid{$name} = $temp[0];
   }
   
}
close NAME;

$org2txid{"Chrysemys picta bellii"} = 8478;
$org2txid{"Microcaecilia unicolor"} = 1415580;
$org2txid{"Python bivittatus"} = 176946;
$org2txid{"Xenopus tropicalis"} = 8364;

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


open GENOMESEQ, "ALL.mature.fas" || die "$!";
$/=">";<GENOMESEQ>;$/="\n";
while(<GENOMESEQ>) {
   chomp;
   my $seqname = $_;
   my @temp = split(/-/,$seqname);
   my $spe = $abbr2org{lc($temp[0])};
   $/=">";
   my $seq=<GENOMESEQ>;
   chomp($seq);
   $seq=~s/U/T/g;
   if(exists $org2txid{$spe}) {
	   my $txid = $org2txid{$spe};
	   my $org="";
	   if(exists $txid2org_mir{$txid}) {
			   $org = $txid2org_mir{$txid};
	   } else {
			   if($spe =~ /^(\w)\w+\s+(\w\w)\w+/) {
					my $orgabb = lc($1).$2;
					$org = $orgabb."_".$txid;
			   } else {
				    print $spe."\n";
			   }
	   }
	   
	   if($org ne "") {
			open OUT,">>mature/$org".".fa" || die "$!";
			print OUT ">".$seqname."\n".$seq;
			close OUT;
	   }
   } else {
       print $spe."\n";	   
   }
   $/="\n";
}
close GENOMESEQ;

my %species_info;
open GENOMESEQ, "ALL-pre.fas" || die "$!";
$/=">";<GENOMESEQ>;$/="\n";
while(<GENOMESEQ>) {
   chomp;
   my $seqname = $_;
   my @temp = split(/-/,$seqname);
   my $spe = $abbr2org{lc($temp[0])};
   $/=">";
   my $seq=<GENOMESEQ>;
   chomp($seq);
   $seq=~s/U/T/g;
   if(exists $org2txid{$spe}) {
	   my $txid = $org2txid{$spe};
	   my $org="";
	   if(exists $txid2org_mir{$txid}) {
			   $org = $txid2org_mir{$txid};
	   } else {
			   if($spe =~ /^(\w)\w+\s+(\w\w)\w+/) {
					my $orgabb = lc($1).$2;
					$org = $orgabb."_".$txid;
			   } else {
				    print $spe."\n";
			   }
	   }
	   
	   if($org ne "") {
		    $species_info{$spe} = $org;
			open OUT,">>hairpin/$org".".fa" || die "$!";
			print OUT ">".$seqname."\n".$seq;
			close OUT;
	   }
   } else {
       print $spe."\n";	   
   }
   $/="\n";
}
close GENOMESEQ;

open INFO, ">species.info.txt" || die "$!";
foreach my $key (keys %species_info) {
	print INFO "$key\t$species_info{$key}\n";
}
close INFO;
