#!/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 %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;
$org2txid{"Erythranthe guttata"} = 4155;
$org2txid{"Fragaria ananassa"} = 3747;


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;


my %abbr2org;
open INFO, ">species.info.txt" || die "$!";
open NAME, "species.txt" || die "$!";
while(<NAME>) {
   chomp;
   my $dirname = $_;
   my $spe;
   my $spestr;
   my $abbr;
   if(/(\S+?)_(\S+?)_(\S+)/) {
	   $spe = $1." ".$2;
	   $spestr = $1."_".$2;
       $abbr =$3;   
   }
   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 "") {
		    print INFO "$spe\t$org\n";
			system("cp www.pmiren.com/$dirname/$spestr"."_mature.fa mature/$org.fa");
			system("cp www.pmiren.com/$dirname/$spestr"."_hairpin.fa hairpin/$org.fa");
	   }
   } else {
       print $spe."\n";	   
   }
}
close NAME;
close INFO;


