# Giant Virus Finder, a software package to find giant viruses in metagenomes.
# Copyright (C) 2015, Csaba Kerepesi

# This file is part of Giant Virus Finder.

# Giant Virus Finder is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details: <http://www.gnu.org/licenses/>.

# For any other inquiries send an Email to Csaba Kerepesi: kerepesi@caesar.elte.hu
# Giant Virus Finder website: http://pitgroup.org/giant-virus-finder

# $ARGV[0]: target dir
# $ARGV[1]: metagenome dir
# Run: perl GetCandidateReads.pl Giants-in-16Soil 16SoilMetagenome

my $filename="";
my %read=();
my $go=0;

open (IN1, "mgm.list");
while (<IN1>) {
    chop;
    $filename=$_;
    open IN2,"$ARGV[0]/phase1-results/AllGiants-vs-$filename.blast";
        while (<IN2>) {
            if ($_ =~ /^>(.+)/) {
                $read{">$1"}=$filename;
            }
        }
    close IN2;
}
close IN1;

open IN1, "mgm.list";
while (<IN1>) {
    chop;
    $filename=$_;
    open IN2,"$ARGV[1]/$filename";
    open(OUT, '>', "$ARGV[0]/phase1-results/Candidates-in-$filename");
    while (<IN2>) {
        if ($_ =~ /^(>.+)/) {
            $go=0;
            if (exists $read{$1}) {
                print OUT "$1\n";
                $go=1;
            }
        }elsif ($go) {
            print OUT $_;
        }
    }
    close OUT;
    print "$ARGV[0]/phase1-results/Candidates-in-$filename\n";
    close IN2;
}
close IN1;
