Cleaned up the code and made it a lot smaller.