Reworked function that sometimes failed.