ported to python3 (and should still work with py2)