import re
import logging


def calculateLength(fastacontiglengths, locations):
    """ Calculate total length of contigs overlapping a set of locations """
    if not locations:
        return sum([fastacontiglengths[x] for x in fastacontiglengths.keys()])

    total_length = 0
    for l in re.split("[ ,]", locations):
        contig, _, pos = l.partition(":")
        if contig not in fastacontiglengths:
            logging.warn("Contig %s is not present in input set %s; setting length to 0" %
                            (contig, str(fastacontiglengths)))
            length = 0
            continue

        if pos:
            start, _, end = pos.partition("-")
            start = int(start)
            if end:
                length = int(end) - start + 1
            else:
                length = max(0, fastacontiglengths[contig] - start)
        else:
            length = fastacontiglengths[contig]

        total_length += length

    return total_length