#!/usr/bin/perl

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

my $inputfile = $ARGV[0];

if ($inputfile =~ /.gz$/) {
    open(GENOMESEQ, "gzip -dc $inputfile |") || die "cannot open $inputfile\n";
} else {
    open(GENOMESEQ, "<$inputfile") || die "cannot open $inputfile\n";
}

my $samplename = $inputfile;
$samplename =~ s/\.\w+$//;

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


open OUT, ">$samplename.out" || die "$!";
my %seqs;
while(<GENOMESEQ>) {
   chomp;
   my @tem = split(/\t/);
   $tem[3] =~ s/_\d+$//;
   if(exists $idmap{$tem[3]}) {
        $tem[3] = $idmap{$tem[3]};
        print OUT join("\t",@tem)."\n";
   } 
}
close GENOMESEQ;
close OUT; 

