Merging pcercuei's code fixes. He's better at python than I am.