#!/usr/bin/perl

use strict;
use warnings;

my $gesamte_anzahl = 0;

my $pos_hash; # hash for pos
while(<>){   # argument must be given. usage: perl Freq.pl ARGUMENT
    chomp;
#    s/[\r\n]+//g;

    s/^\s+//;
    s/\s+$//; 
    s/ +/ /g;

    next if /^\s*$/;

    my ($freq,$pos) = split /\t+/;
    $pos_hash->{$pos} = $freq;

#    ++$gesamte_anzahl; # counts the total number of freqs
    $gesamte_anzahl += $freq;
}

printf "%*.*s\t%s\t%s\t%s\n\n",-50,50,"POS","Freq","Acc_Freq","Acc_ratio(%)";
# formats the output title

my $akk_freq = 0; # initialize the accumulated frequency
my $akk_pro = 0; # initialize the accumulated percent
foreach my $pos (sort{$pos_hash->{$b} <=> $pos_hash->{$a}} keys %$pos_hash){ 
                                            # sort according to the frequency
    $akk_freq += $pos_hash->{$pos};                # accumulated frequency
    $akk_pro = $akk_freq/$gesamte_anzahl * 100; # accumulated percent

    printf "%*.*s\t%d\t%d\t\t%.2f\n",-50,50,$pos,$pos_hash->{$pos},$akk_freq,$akk_pro;
           # formatted output. %*.*s and -50,50,$psrule mean: 
           # format the string width 50 (-50 means right justifying), precision 50 with the value $psrule
           # number must be adjusted accoding to the text width
}


# <IN> file

# 3	PPER
# 5	VMFIN
# 2	APPR
# 3	ART
# 4	NN	
# 3	VVINF
# 3	NE	
# 4	VVFIN
# 6	PPOSAT	
# 3	PTKVZ	
# 2	KON


# <OUT> file

# POS                                               	Freq	Akk_Freq	Akk_Pro

# PPOSAT                                            	6	6		15.79
# VMFIN                                             	5	11		28.95
# VVFIN                                             	4	15		39.47
# NN                                                	4	19		50.00
# PTKVZ                                             	3	22		57.89
# VVINF                                             	3	25		65.79
# NE                                                	3	28		73.68
# ART                                               	3	31		81.58
# PPER                                              	3	34		89.47
# APPR                                              	2	36		94.74
# KON                                               	2	38		100.00
