def trim(msa, threshold=0.0):
    """Trim a MSA to its first and last non-gap containing columns."""

    def gap_pct(msa, index):
        return msa.column(index).count("-") / msa.count()

    length = len(msa)
    start, end = 0, length - 1
    start_found, end_found = False, False

    for i in range(length):
        if start_found and end_found:
            break

        if not start_found and gap_pct(msa, i) > threshold:
            start += 1
        else:
            start_found = True

        # Since we just decrement end, can use it as the index
        if not end_found and gap_pct(msa, end) > threshold:
            end -= 1
        else:
            end_found = True

    return msa[start:end]