#!/usr/bin/env awk
#
# Computes the mean value of a column c.
# The result can be accessed with get_mean(c) or printed with print_mean([c])
#
# Dependencies:
#   - None
#
# Examples:
#   - tawk '{
#         mean(numPktsSnt)
#     } END {
#         print_mean(numPktsSnt)
#     }' file.txt
#   - tawk '{
#         mean(numPktsSnt)
#     } END {
#         print $0, get_mean(numPktsSnt)
#     }' file.txt
#   - tawk '{
#         mean(numPktsSnt)
#         mean(numPktsRcvd)
#     } END {
#         print_mean()
#     }' file.txt

@include "COLNAME"
@include "hdr"

function mean(c) {
    if (hdr()) next

    if (NUM_SAMPLES[COLNAME[c]] == 0) {
        MEAN[COLNAME[c]] = $c
    } else {
        MEAN[COLNAME[c]] += ($c - MEAN[COLNAME[c]]) / (NUM_SAMPLES[COLNAME[c]]+1)
    }
    NUM_SAMPLES[COLNAME[c]]++
}

function get_mean(c) {
    return MEAN[COLNAME[c]]
}

function print_mean(c,        _i) {
    if (!c) {
        for (_i in MEAN) {
            print _i ": " MEAN[_i]
        }
    } else {
        print get_mean(c)
    }
}
