Code ported to Python 3