My solution for a StackOverflow question