import re


def collapse_linebreaks(string, threshold=1):
    """ Returns a string with consecutive linebreaks collapsed to at most the given threshold.
        Whitespace on empty lines and at the end of each line is removed.
    """
    n = "\n" * threshold
    p = [s.rstrip() for s in string.replace("\r", "").split("\n")]
    string = "\n".join(p)
    string = re.sub(n+r"+", n, string)
    return string