Some code to go with my answer to Stackoverflow question 17870680