Originally found on the Internet. Updated by Grigori Fursin and Anton Lokhmotov (changes are under CK copyright/license).