Massively refactored to follow best practices.