It looks like I've changed a lot, but the logic should be the same. I've just moved blocks of code around.