Cleanup and refactor code