#!/usr/bin/perl

use strict;
use warnings;

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


open GENOMESEQ, $ARGV[0] || 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 $name2id{$species}) {
     open OUT,">>$name2id{$species}".".fa" || die "$!";
     print OUT ">".$seqname."\n".$seq."\n";
     close OUT;
   }
   $/="\n";
}
close GENOMESEQ;
