I've refactored this, take a look when you have a sec.