Rewrite mergeFolders to fix some bugs and add tests.