#!usr/bin/perl -w

use strict;
use warnings;
use Getopt::Long;
use FindBin;
use File::Spec;


# perl /media/xiangyang/fa0b5a1c-cdf8-456c-b415-bd931d086eb0/home/xiangyang/Desktop/tool_dev/AMannot/AManno/NCBI-AMR结构化数据库构建步骤/cp_NCBI-AMR_nt.pl /media/xiangyang/fa0b5a1c-cdf8-456c-b415-bd931d086eb0/home/xiangyang/Desktop/tool_dev/AMannot/AManno/NCBI-AMR结构化数据库构建步骤/refgene20241108/ncbi_dataset/data/nucleotide.fna /media/xiangyang/fa0b5a1c-cdf8-456c-b415-bd931d086eb0/home/xiangyang/Desktop/tool_dev/AMannot/AManno/NCBI-AMR结构化数据库构建步骤/nucleotide20241116.fna /media/xiangyang/fa0b5a1c-cdf8-456c-b415-bd931d086eb0/home/xiangyang/Desktop/tool_dev/AMannot/AManno/NCBI-AMR结构化数据库构建步骤/refgene20241108/refgenes.tsv

my %seq = &parse_fasta($ARGV[0]);
open (LT, $ARGV[2]);
open (OUT, ">$ARGV[1]");
while(<LT>){
    chomp;
    my @a = split /\t/, $_;
    next unless $a[7] =~ /CARBAPENEM|COLISTIN/;
    next unless $a[4] eq "AMR";
    next unless $a[5] eq "AMR";
    next unless $a[0] !~ /^16S_|^23S_|^50S_/;

    my $e = $a[9];
    $e = $a[11] if $a[9] eq "";

    my $add;
    $add = "$a[6]|$a[0]|$a[2]|$a[5]" if $a[0] ne "";
    $add = "$a[6]|$a[1]|$a[2]|$a[5]" if $a[0] eq "";
    if (defined $seq{$e}){
        print OUT ">$e|$add\n$seq{$e}\n";
    }else{
        if (grep($_ =~/^$e/, keys %seq)){
            my @a = grep($_ =~/^$e/, keys %seq);
            print OUT ">$e|$add\n$seq{$a[0]}\n"; 
        }
    }
}
close LT;
close OUT;




sub parse_fasta {

    my ($infile) = @_;
    my $term     = $/; # input record separator;
    my %seq_hash = (); # key:seqid, val:seq
    open my $INFILE, $infile or die "could not open infile '$infile' : $! \n"; 
    $/ = ">"; # input record separator;
    while(<$INFILE>) {

        chomp;

        next if($_ eq '');
        my ($id, @sequencelines) = split /\n/;
        $id =~ s/ .*//g;
        $seq_hash{$id} = join("", @sequencelines);
    }
    $/ = $term;
    return(%seq_hash);

} # end of parse_fasta

