Cleaned up and refactored a bit