Refactored with some Python magic, as inspired by Tomasz Jeziersky