OK I am slightly less brain-dead than when I replied before, here is an explanation of the code I posted above: