added collapse function and improved then function