Code from my StackOverflow answers.