#!/usr/bin/env python

import os, sys

def coverage_all(directory):
    os.chdir(directory)
    r = os.popen('sage -coverage * | grep SCORE').readlines()

    s = []
    scr = 0
    total = 0
    for x in r:
        y = x.lstrip('SCORE ')
        i = y.rfind(' of ')
        j = y.rfind(')')
        n = int(y[i+4:j])

        i = y.rfind(':')
        j = y.rfind('%')
        scr += int(y[i+1:j]) * float(n)

        total += n

        s.append(y)

    print ''.join(s)

    score = (float(scr) / total)
    print "Overall weighted coverage score:  %.1f%%"%score
    print "Total number of functions: ", total

    # Print up to 3 doctest coverage goals. 
    i = 0
    for goal in [68, 70, 75, 80, 85, 90, 95, 99]:
        if score < goal:
            i += 1
            if i > 3: break
            need = int((goal*total - scr)/100.0)
            print "We need %4s more function to get to %s%% coverage."%(need,goal)

if len(sys.argv) == 1:
    coverage_all('%s/devel/sage/sage/'%os.environ["SAGE_ROOT"])
else:
    coverage_all(sys.argv[1])
