#!/usr/bin/env perl
#
# orthologer - Pipeline for deducing orthology from fasta files.
# Copyright (C) 2005-2023 E. Zdobnov lab: F. Tegenfeldt
# <fredrik.tegenfeldt@unige.ch> based on code by E. Kriventseva
#
# This file is part of orthologer.
#
# orthologer 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
# (at your option) any later version.
#
# orthologer 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.
#
# You should have received a copy of the GNU General Public License
# along with orthologer.  If not, see <http://www.gnu.org/licenses/>.
#

# arguments: <og file> <todo file>
if (@ARGV < 2) {
    die "usage: dist_count.pl <og file> <todo file>\n";
}
my $orth_file=shift;
my $todo_file=shift;


open(IN,"<$todo_file") or die "unable to read TODO file $todo_file : $!\n";
close IN;

my $sp_list=`cat $todo_file`;

# read in cluster file and extract
# 1 -> cluster id
# 2 -> full gene id
# 3 -> species id (extracted from gene id)
open(IN,"<$orth_file") or die "unable to read OG file $orth_file : $!\n";
while(<IN>){
	if(/^(\d+)\s+((\w+?):\S+)/) {
        push(@{$h{$1}{$3}},$2);
    }
}
close IN;


# open output
open(OUT1,">$orth_file.dist") or die "unable to open dist file for writing ($orth_file.dist) : $!\n";

# print header
my @x= split /[_\s]/, $sp_list; 
print OUT1 "#clid\t",join("\t", @x),"\n"; 

foreach my $i (keys %h){
    # print cluster id
    print OUT1 "$i\t";
    # loop over all species
    foreach my $o (@x){
        my @v=@{$h{$i}{$o}};
        # print count per species
        print OUT1 $#v+1,"\t"
    } 
    print OUT1 "\n"
}

close OUT1;


# read in previous result in a different form
# count each pattern found
# a pattern is the list of counts per species
# "n"   -> counter
# "ids" -> pattern
#
open(IN2,"<$orth_file.dist")               or die "unable to open dist file for reading ($orth_file.dist) : $!\n";
while(<IN2>){
	if (/^(\d+)\s+(.*)/) {
        $pattern{$2}{"n"}++;
        push(@{$pattern{$2}{"ids"}},$1)
    }
}
close IN2;

# output dist count and 111
open(OUT2,">$orth_file.dist_count")      or die "unable to open dist_count file for writing ($orth_file.dist_count) : $!\n";
open(OUT3,">$orth_file.dist_111-og-ids") or die "unable to open dist_111-og-ids file for writing ($orth_file.dist_111-og-ids) : $!\n";

print OUT2 "# count pattern\n";
print OUT3 "# clid's of 1-to-1 groups\n";
foreach my $i (sort {$pattern{$b}{"n"}<=>$pattern{$a}{"n"}} keys %pattern) {
    print OUT2 $pattern{$i}{"n"},"\t$i\n";
	my $f=0;																       
	foreach my $j (split /\s/,$i) {
    	$f++ unless ($j ==1);	
	}
	print OUT3 join(",",@{$pattern{$i}{"ids"}}) if ($f==0);
}
close OUT3;
close OUT2;