Cleaned up code to make it easier to read and hopefully slightly faster