import os
import math

def extract_exp_avg_stddev(exp, datapoint, parser, *parser_args):
    def my_parser(f):
        p = os.path.join(os.getcwd(), '../data/', exp, f + '.txt')

        if not os.path.exists(p):
            return None
        with open(p, 'r') as fi:
            return parser(fi.read(), *parser_args)

    acc = []
    acc.append(my_parser(datapoint))
    tmp = None
    i = 0
    while True:
        tmp = my_parser('%s_aux%d' % (datapoint, i + 1))
        if tmp == None:
            break
        acc.append(tmp)
        i += 1

    mean = None
    stddev = None
    if type(acc[0]) is tuple:
        mean = [0 for _ in range(len(acc[0]))]
        stddev = [0 for _ in range(len(acc[0]))]
        for j in range(len(acc[0])):
            for i in range(len(acc)):
                mean[j] += acc[i][j]
            mean[j] /= len(acc)
            for i in range(len(acc)):
                stddev[j] += pow(acc[i][j] - mean[j], 2)
            stddev[j] /= len(acc)
            stddev[j] = math.sqrt(stddev[j])

        mean = tuple(mean)
        stddev = tuple(stddev)
    else:
        mean = 0
        stddev = 0
        for i in range(len(acc)):
            mean += acc[i]
        mean /= len(acc)
        for i in range(len(acc)):
            stddev += pow(acc[i] - mean, 2)
        stddev /= len(acc)
        stddev = math.sqrt(stddev)

    return (mean, stddev)