import json


def filter_coverage_file(covfile_handle, cov_functions):
    """Given an input coverage json file and a set of functions that the test
    is targeting, filter the coverage file to only include data generated
    by running the given functions."""
    covdata_out = dict()
    covdata = json.load(covfile_handle)
    # copy basic info
    assert covdata["format_version"] == "1"
    covdata_out["format_version"] = covdata["format_version"]
    covdata_out["current_working_directory"] = covdata["current_working_directory"]
    covdata_out["data_file"] = covdata["data_file"]
    covdata_out["gcc_version"] = covdata["gcc_version"]
    # handle per proj file data
    covdata_out["files"] = list()
    for targetfile in covdata["files"]:
        cur_file = dict()
        cur_file["file"] = targetfile["file"]
        cur_functions = list()
        for function in targetfile["functions"]:
            if function["name"] in cov_functions:
                cur_functions.append(function)
        cur_file["functions"] = cur_functions
        cur_lines = list()
        for line in targetfile["lines"]:
            if line["function_name"] in cov_functions:
                cur_lines.append(line)
        cur_file["lines"] = cur_lines
        covdata_out["files"].append(cur_file)
    return covdata_out