#!/usr/bin/perl -w
#
## author: axel wintsche
## mail: wint(spider monkey)bioinf(dot)uni-leipzig(dot)de
use strict;

$#ARGV == 0 or die "HowMuch.pl <list of ncbi ids of known organism>\n";

my %count;
my $nodes_file = "/scr/k10/taxonomy/nodes.dmp";
my $names_file = "/scr/k10/taxonomy/names.dmp";

open(KNOWN, "<$ARGV[0]");

foreach(<KNOWN>) {
	chomp $_;
	addID($_);
}
close(KNOWN);

foreach(keys(%count)) {
	my $grep = `grep -m 1 -P '^$_\\s.+scientific name' '$names_file'`;
	my $name = (split /\s*\|\s*/, $grep)[1];
	
	print $name."\t".$_."\t".$count{$_}."\n";
}



## ------------------ subs --------------------------

sub addID {

	my $id = shift;
	my $true = 1;
	while($true > 0) {
		if(exists $count{$id}) { $count{$id}++; }
		else { $count{$id} = 1; }
		
		# if $id is the root then leave this loop
		if($id == 1){ $true = 0; }
		# get parent id
		my $grep = `grep -m 1 -P '^$id\\s' '$nodes_file'`;
		$id = (split /\s*\|\s*/, $grep)[1];
	}
}
