#!/usr/bin/perl
use strict;
use warnings;
use Encode qw/decode/;
use Encode qw/encode/;
use utf8;

my @cut_result = ();
my %series_count = ();
open CUT, "$ARGV[0]" or die;
while (<CUT>) {
	chomp;
	push @cut_result, $_;
	++$series_count{$_};
}
close CUT;

open DATA, "$ARGV[1]" or die;
my $data_flag = 0;
my %count = ();
my @words = ();
while (<DATA>) {
	chomp;
	my $line = $_;
	unless ($data_flag) {
		@words = split /\t/, $_;
		shift @words;
		$data_flag = 1;
		next;
	}
	my $subtree = shift @cut_result;
	my @each_count = split /\t/, $_;
	shift @each_count;
	foreach my $word (@words) {
		${$count{$word}}{$subtree} += shift @each_count;
	}
}
close DATA;

my %total_count = ();
foreach my $word (keys %count) {
	foreach my $subtree (keys %{$count{$word}}) {
		$total_count{$word} += ${$count{$word}}{$subtree};
	}
}

foreach my $word (sort { $total_count{$b} <=> $total_count{$a} } keys %total_count) {
	print "$word";
	foreach my $subtree (sort { $a <=> $b } keys %{$count{$word}}) {
		my $ratio = ${$count{$word}}{$subtree} / $series_count{$subtree};
		print "\t${$count{$word}}{$subtree}\t$ratio";
	}
	print "\n";
}

