def BuildEdgeDict(surface):
    """ Create edge dictionary from a surface.
    The edge dictionary is indexed by a tuple 
    (vertexindex1,vertexindex2) of indices into surface.vertexes. 
    It contains a list of polygon ids that have an edge that shares
    these two vertices. 
    
    This function assumes that identical vertices in the surface 
    have been merged, so the vertexindex uniquely identifies the
    vertex. 

    This function returns the edge dictionary
"""

    edges={}  # lists of polygon numbers, indexed by a tuple of the  vertex indices connected by the edge
    for polynum in range(surface.vertexidx_indices.shape[0]):
        firstidx=surface.vertexidx_indices[polynum]
                
        numvertices=surface.numvertices[polynum]
        for firstvertex in range(numvertices):
            nextvertex=(firstvertex+1) % numvertices
            
            firstvertexidx=surface.vertexidx[firstidx+firstvertex]
            nextvertexidx=surface.vertexidx[firstidx+nextvertex]
            
            if (firstvertexidx,nextvertexidx) in edges:
                edges[(firstvertexidx,nextvertexidx)].append((polynum,firstvertex,nextvertex))
                pass
            elif (nextvertexidx,firstvertexidx) in edges:
                edges[(nextvertexidx,firstvertexidx)].append((polynum,nextvertex,firstvertex))
                pass
            else:
                edges[(firstvertexidx,nextvertexidx)] = [ (polynum,firstvertex,nextvertex) ]
                pass
            pass
        pass
    return edges