Fixed up a bit more to ensure it works in every possible case.