Reordered code, rewrote mergeVertices, fixed bugs