Stackoverflow answer

This is a modification to your code based on my stackoverflow answer.