#!/bin/bash
#this script calculates statistical distributions of selected colums / flow from a flowfile, e.g.
#the number of packets, packet size or any other value in a flow file
#it aoutomatically calculates the bin size and accepts manual entries max_value bin_size
#0 counts can be suppressed in the output and the flow direction can be selected A:0. B:1 or B:both

if [ $2 ]; then
     awk -v pos=$2 -v fl=$3 -v max=$4 -v bin=$5 -v sup=$6 'BEGIN { s = 0; m = 0; cm = 0; ss = 0; st = 0;} {
	if (fl == 0 && and(strtonum($2),0x01) == 0x01) next;
	if (fl == 1 && and(strtonum($2),0x01) == 0x00) next;
	i = strtonum($(pos));
	if (!i) next;
	++a[i];
	if (i > m) {m = i};
	s += i;
	ss++;
     }
     END {
	if (!max) {
		max = 10^(int(log(m)/log(10)) + 1);
		bin = max/10;
#	print m, max, bin;
	}
	print "bin\tcount\t%"
	for (i = 0; i < max; i += bin) {
		c = 0;
		for(j = i; j < i+bin; j++) c += a[j];
		if (sup && c) print i"-"i+bin-1"\t"c"\t"100*c/ss;
		if (!sup) print i"-"i+bin-1"\t"c"\t"100*c/ss;
		cm += c * (i+bin +1)/2;
	}
	print "\ntotal col sum, max_col_value, #flows, cent_mass:", m, s, ss, cm/ss;
     }' $1
#> $1"_stat.txt"
else
    echo " flowstat flowfile column flow_direction:0|1|B max_value bin_size supress_0_counts"
fi
