Clean up and refactor code