#!/usr/bin/perl

use strict;
use warnings;

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

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


open GENOMESEQ, "mature.fa" || die "$!";
$/=">";<GENOMESEQ>;$/="\n";
while(<GENOMESEQ>) {
   chomp;
   my $seqname = $_;
   my @temp = split(/\s+/,$seqname);
   #$species =~ s/.*MIMAT\d+ //;
   #$species =~ s/ miR-.*$//;
   my $species = $temp[2]." ".$temp[3];
   $/=">";
   my $seq=<GENOMESEQ>;
   chomp($seq);
   $seq=~s/\s+//g;
   $seq=~s/\n+//g;
   $seq=~s/U/T/g; 
   if(exists $txid2org_mir{$species}) {
		open OUT,">>mature/$txid2org_mir{$species}".".fa" || die "$!";
		print OUT ">".$seqname."\n".$seq."\n";
		close OUT;
   }
   $/="\n";
}
close GENOMESEQ;


open GENOMESEQ, "hairpin.fa" || die "$!";
$/=">";<GENOMESEQ>;$/="\n";
while(<GENOMESEQ>) {
   chomp;
   my $seqname = $_;
   my @temp = split(/\s+/,$seqname);
   #$species =~ s/.*MIMAT\d+ //;
   #$species =~ s/ miR-.*$//;
   my $species = $temp[2]." ".$temp[3];
   $/=">";
   my $seq=<GENOMESEQ>;
   chomp($seq);
   $seq=~s/\s+//g;
   $seq=~s/\n+//g;
   $seq=~s/U/T/g; 
   if(exists $txid2org_mir{$species}) {
		open OUT,">>hairpin/$txid2org_mir{$species}".".fa" || die "$!";
		print OUT ">".$seqname."\n".$seq."\n";
		close OUT;
   }
   $/="\n";
}
close GENOMESEQ;

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

