Messy code cleaned up