Added set merging and fixed some memory allocation bugs