Massively cleaned up code and made a number of improvements.