def determineIndentationAndTrailingWS(text):
    """Get the indentation used in this document and whether there is
    any trailing whitespace.
    The text is analyzed to find the most used indentations.
    The result is -1 if tab indents are most common.
    A positive result means spaces are used; the amount
    signifies the amount of spaces per indentation.
    0 is returned if the indentation could not be determined.
    The second return value is the number of lines with trailing ws.
    """

    text = text[:32768]  # Limit search for large files

    # create dictionary of indents, -1 means a tab
    indents = {}
    indents[-1] = 0
    trailing = 0

    lines = text.splitlines()
    lines.insert(0, "")  # so the lines start at 1
    for i in range(len(lines)):
        line = lines[i]

        # remove indentation
        lineA = line.lstrip()
        lineB = line.rstrip()
        lineC = lineA.rstrip()
        indent = len(line) - len(lineA)
        if len(lineB) < len(line):
            trailing += 1

        line = lineC
        if line.startswith("#"):
            continue
        else:
            # remove everything after the #
            line = line.split("#", 1)[0].rstrip()
        if not line:
            # continue of no line left
            continue

        # a colon means there will be an indent
        # check the next line (or the one thereafter)
        # and calculate the indentation difference with THIS line.
        if line.endswith(":"):
            if len(lines) > i + 2:
                line2 = lines[i + 1]
                tmp = line2.lstrip()
                if not tmp:
                    line2 = lines[i + 2]
                    tmp = line2.lstrip()
                if tmp:
                    ind2 = len(line2) - len(tmp)
                    ind3 = ind2 - indent
                    if line2.startswith("\t"):
                        indents[-1] += 1
                    elif ind3 > 0:
                        if ind3 not in indents:
                            indents[ind3] = 1
                        indents[ind3] += 1

    # find which was the most common tab width.
    indent, maxvotes = 0, 0
    for nspaces in indents:
        if indents[nspaces] > maxvotes:
            indent, maxvotes = nspaces, indents[nspaces]
    # print "found tabwidth %i" % indent
    return indent, trailing