def _construct_end_index(spansStartingFrom):
    """ Creates an index which stores all annotations (from spansStartingFrom) 
       by their end position in text (annotation[END]).
       
       Each start position (in the index) is associated with a list of 
       annotation objects (annotations ending at that position).
       An annotation object is also a list containing the following information:
        *) endTags -- graphic or textual formatting of the end tag,
        *) START position (of the annotation);
        *) layer name;
         
       Multiple annotation objects ending at the same position are sorted by 
       their length: shorter annotations preceding the longer ones;
   """
    endIndex = {}
    for i in spansStartingFrom:
        for span1 in spansStartingFrom[i]:
            endSpan1 = [span1[4], span1[0], span1[2]]
            endLoc1 = span1[1]
            if endLoc1 not in endIndex:
                endIndex[endLoc1] = []
                endIndex[endLoc1].append(endSpan1)
            else:
                inserted = False
                for i in range(len(endIndex[endLoc1])):
                    endSpan2 = endIndex[endLoc1][i]
                    if endSpan2[1] < endSpan1[1]:
                        endIndex[endLoc1].insert(i, endSpan1)
                        inserted = True
                        break
                    elif endSpan2[1] == endSpan1[1] and endSpan2[2] < endSpan1[
                        2]:
                        endIndex[endLoc1].insert(i, endSpan1)
                        inserted = True
                        break
                if not inserted:
                    endIndex[endLoc1].append(endSpan1)
    return endIndex
