Removed a lot of cruft, and made code more dry